aboutsummaryrefslogtreecommitdiff
path: root/content/main.js
blob: 4ae77384d933a377f223b42a37fd09bc55df8b71 (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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/**
 * Hachette main content script run in all frames
 *
 * Copyright (C) 2021 Wojtek Kosior
 * Copyright (C) 2021 jahoti
 * Redistribution terms are gathered in the `copyright' file.
 */

/*
 * IMPORTS_START
 * IMPORT handle_page_actions
 * IMPORT extract_signed
 * IMPORT gen_nonce
 * IMPORT is_privileged_url
 * IMPORT mozilla_suppress_scripts
 * IMPORT is_chrome
 * IMPORT is_mozilla
 * IMPORT start_activity_info_server
 * IMPORT modify_on_the_fly
 * IMPORTS_END
 */

function accept_node(node, parent)
{
    const clone = document.importNode(node, false);
    node.hachette_corresponding = clone;
    /*
     * TODO: Stop page's own issues like "Error parsing a meta element's
     * content:" from appearing as extension's errors.
     */
    parent.hachette_corresponding.appendChild(clone);
}

if (!is_privileged_url(document.URL)) {
    const reductor =
	  (ac, [_, sig, pol]) => ac[0] && ac || [extract_signed(sig, pol), sig];
    const matches = [...document.cookie.matchAll(/hachette-(\w*)=([^;]*)/g)];
    let [policy, signature] = matches.reduce(reductor, []);

    if (!policy || policy.url !== document.URL) {
	console.log("WARNING! Using default policy!!!");
	policy = {allow: false, nonce: gen_nonce()};
    }

    if (signature)
	document.cookie = `hachette-${signature}=; Max-Age=-1;`;

    handle_page_actions(policy.nonce);

    if (!policy.allow) {
	const old_html = document.documentElement;
	const new_html = document.createElement("html");
	old_html.replaceWith(new_html);
	old_html.hachette_corresponding = new_html;

	const modify_end =
	      modify_on_the_fly(old_html, policy, {node_eater: accept_node});
	document.addEventListener("DOMContentLoaded", modify_end);
    }

    start_activity_info_server();
}