Project

General

Profile

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

haketilo / content / main.js @ 2875397f

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

    
9
/*
10
 * IMPORTS_START
11
 * IMPORT handle_page_actions
12
 * IMPORT extract_signed
13
 * IMPORT gen_nonce
14
 * IMPORT is_privileged_url
15
 * IMPORT mozilla_suppress_scripts
16
 * IMPORT is_chrome
17
 * IMPORT is_mozilla
18
 * IMPORT start_activity_info_server
19
 * IMPORT modify_on_the_fly
20
 * IMPORTS_END
21
 */
22

    
23
function accept_node(node, parent)
24
{
25
    const clone = document.importNode(node, false);
26
    node.hachette_corresponding = clone;
27
    /*
28
     * TODO: Stop page's own issues like "Error parsing a meta element's
29
     * content:" from appearing as extension's errors.
30
     */
31
    parent.hachette_corresponding.appendChild(clone);
32
}
33

    
34
if (!is_privileged_url(document.URL)) {
35
    /* Signature valid for half an hour. */
36
    const min_time = new Date().getTime() - 1800 * 1000;
37
    let best_result = {time: -1};
38
    let policy = null;
39
    const extracted_signatures = [];
40
    for (const match of document.cookie.matchAll(/hachette-(\w*)=([^;]*)/g)) {
41
	const new_result = extract_signed(...match.slice(1, 3));
42
	if (new_result.fail)
43
	    continue;
44

    
45
	extracted_signatures.push(match[1]);
46

    
47
	if (new_result.time < Math.max(min_time, best_result.time))
48
	    continue;
49

    
50
	/* This should succeed - it's our self-produced valid JSON. */
51
	const new_policy = JSON.parse(decodeURIComponent(new_result.data));
52
	if (new_policy.url !== document.URL)
53
	    continue;
54

    
55
	best_result = new_result;
56
	policy = new_policy;
57
    }
58

    
59
    if (!policy) {
60
	console.warn("WARNING! Using default policy!!!");
61
	policy = {allow: false, nonce: gen_nonce()};
62
    }
63

    
64
    for (const signature of extracted_signatures)
65
	document.cookie = `hachette-${signature}=; Max-Age=-1;`;
66

    
67
    handle_page_actions(policy.nonce);
68

    
69
    if (!policy.allow) {
70
	const old_html = document.documentElement;
71
	const new_html = document.createElement("html");
72
	old_html.replaceWith(new_html);
73
	old_html.hachette_corresponding = new_html;
74

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

    
80
    start_activity_info_server();
81
}
(3-3/6)