aboutsummaryrefslogtreecommitdiff
path: root/background/policy_injector.js
blob: 318190b215451977554c91572374c909ef725a85 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
/**
 * Hachette injecting policy to page using webRequest
 *
 * Copyright (C) 2021 Wojtek Kosior
 * Copyright (C) 2021 jahoti
 * Redistribution terms are gathered in the `copyright' file.
 */

/*
 * IMPORTS_START
 * IMPORT sign_data
 * IMPORT extract_signed
 * IMPORT sanitize_csp_header
 * IMPORT make_csp_rule
 * IMPORT is_csp_header_name
 * IMPORTS_END
 */

function inject_csp_headers(headers, policy)
{
    if (!policy.allow || policy.has_payload) {
	/* Remove report-only CSP headers that snitch on us. */
	headers = headers.filter(h => !is_csp_header_name(h.name, true));

	/* Add our own CSP header */
	headers.push({
	    name: "content-security-policy",
	    value: make_csp_rule(policy)
	});
    }
    
    const policy_str = encodeURIComponent(JSON.stringify(policy));
    const signed_policy = sign_data(policy_str, new Date().getTime());
    const later_30sec = new Date(new Date().getTime() + 30000).toGMTString();
    headers.push({
	name: "Set-Cookie",
	value: `hachette-${signed_policy.join("=")}; Expires=${later_30sec};`
    });

    return headers;
}

/*
 * EXPORTS_START
 * EXPORT inject_csp_headers
 * EXPORTS_END
 */