Project

General

Profile

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

haketilo / background / main.js @ 2875397f

1
/**
2
 * Hachette main background script
3
 *
4
 * Copyright (C) 2021 Wojtek Kosior
5
 * Redistribution terms are gathered in the `copyright' file.
6
 */
7

    
8
/*
9
 * IMPORTS_START
10
 * IMPORT TYPE_PREFIX
11
 * IMPORT get_storage
12
 * IMPORT start_storage_server
13
 * IMPORT start_page_actions_server
14
 * IMPORT browser
15
 * IMPORT is_privileged_url
16
 * IMPORT query_best
17
 * IMPORT gen_nonce
18
 * IMPORT inject_csp_headers
19
 * IMPORT apply_stream_filter
20
 * IMPORT is_chrome
21
 * IMPORTS_END
22
 */
23

    
24
start_storage_server();
25
start_page_actions_server();
26

    
27
async function init_ext(install_details)
28
{
29
    if (install_details.reason != "install")
30
	return;
31

    
32
    let storage = await get_storage();
33

    
34
    await storage.clear();
35

    
36
    /*
37
     * Below we add sample settings to the extension.
38
     */
39

    
40
    for (let setting of // The next line is replaced with the contents of /default_settings.json by the build script
41
        `DEFAULT SETTINGS`
42
    ) {
43
	let [key, value] = Object.entries(setting)[0];
44
	storage.set(key[0], key.substring(1), value);
45
    }
46
}
47

    
48
browser.runtime.onInstalled.addListener(init_ext);
49

    
50

    
51
let storage;
52

    
53
function on_headers_received(details)
54
{
55
    const url = details.url;
56
    if (is_privileged_url(details.url))
57
	return;
58

    
59
    const [pattern, settings] = query_best(storage, details.url);
60
    const allow = !!(settings && settings.allow);
61
    const nonce = gen_nonce();
62
    const policy = {allow, url, nonce};
63

    
64
    let headers = details.responseHeaders;
65
    let skip = false;
66
    for (const header of headers) {
67
	if ((header.name.toLowerCase().trim() === "content-disposition" &&
68
	     /^\s*attachment\s*(;.*)$/i.test(header.value)))
69
	    skip = true;
70
    }
71

    
72
    headers = inject_csp_headers(headers, policy);
73

    
74
    skip = skip || (details.statusCode >= 300 && details.statusCode < 400);
75
    if (!skip) {
76
	/* Check for API availability. */
77
	if (browser.webRequest.filterResponseData)
78
	    headers = apply_stream_filter(details, headers, policy);
79
    }
80

    
81
    return {responseHeaders: headers};
82
}
83

    
84
async function start_webRequest_operations()
85
{
86
    storage = await get_storage();
87

    
88
    const extra_opts = ["blocking", "responseHeaders"];
89
    if (is_chrome)
90
	extra_opts.push("extraHeaders");
91

    
92
    browser.webRequest.onHeadersReceived.addListener(
93
	on_headers_received,
94
	{urls: ["<all_urls>"], types: ["main_frame", "sub_frame"]},
95
	extra_opts
96
    );
97
}
98

    
99
start_webRequest_operations();
(1-1/6)