Project

General

Profile

Download (1.71 KB) Statistics
| Branch: | Tag: | Revision:

haketilo / background / policy_injector.js @ b93f26bf

1
/**
2
 * Myext injecting policy to page using webRequest
3
 *
4
 * Copyright (C) 2021 Wojtek Kosior
5
 * Redistribution terms are gathered in the `copyright' file.
6
 */
7

    
8
"use strict";
9

    
10
(() => {
11
    const TYPE_PREFIX = window.TYPE_PREFIX;
12
    const get_storage = window.get_storage;
13
    const browser = window.browser;
14
    const is_chrome = window.is_chrome;
15
    const gen_unique = window.gen_unique;
16
    const url_item = window.url_item;
17
    const get_query_best = window.get_query_best;
18

    
19
    var storage;
20
    var query_best;
21

    
22
    let csp_header_names = {
23
	"content-security-policy" : true,
24
	"x-webkit-csp" : true,
25
	"x-content-security-policy" : true
26
    };
27

    
28
    function is_noncsp_header(header)
29
    {
30
	return !csp_header_names[header.name.toLowerCase()];
31
    }
32

    
33
    function inject(details)
34
    {
35
	let url = url_item(details.url);
36

    
37
	let [pattern, settings] = query_best(url);
38

    
39
	if (settings !== undefined && settings.allow) {
40
	    console.log("allowing", url);
41
	    return {cancel : false};
42
	}
43

    
44
	let nonce = gen_unique(url).substring(1);
45
	let headers = details.responseHeaders.filter(is_noncsp_header);
46
	headers.push({
47
	    name : "content-security-policy",
48
	    value : `script-src 'nonce-${nonce}'; script-src-elem 'nonce-${nonce}';`
49
	});
50

    
51
	console.log("modified headers", url, headers);
52

    
53
	return {responseHeaders: headers};
54
    }
55

    
56
    async function start() {
57
	storage = await get_storage();
58
	query_best = await get_query_best();
59

    
60
	let extra_opts = ["blocking", "responseHeaders"];
61
	if (is_chrome)
62
	    extra_opts.push("extraHeaders");
63

    
64
	browser.webRequest.onHeadersReceived.addListener(
65
	    inject,
66
	    {
67
		urls: ["<all_urls>"],
68
		types: ["main_frame", "sub_frame"]
69
	    },
70
	    extra_opts
71
	);
72
    }
73

    
74
    window.start_policy_injector = start;
75
})();
(4-4/7)