Project

General

Profile

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

haketilo / common / misc.js @ 57e4ed2b

1
/**
2
 * Hachette miscellaneous operations refactored to a separate file
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 sha256
12
 * IMPORT browser
13
 * IMPORT is_chrome
14
 * IMPORT TYPE_NAME
15
 * IMPORTS_END
16
 */
17

    
18
/* Generate a random base64-encoded 128-bit sequence */
19
function gen_nonce()
20
{
21
    let randomData = new Uint8Array(16);
22
    crypto.getRandomValues(randomData);
23
    return btoa(String.fromCharCode.apply(null, randomData));
24
}
25

    
26
/*
27
 * generating unique, per-site value that can be computed synchronously
28
 * and is impossible to guess for a malicious website
29
 */
30

    
31
/* Uint8toHex is a separate function not exported as (a) it's useful and (b) it will be used in crypto.subtle-based digests */
32
function Uint8toHex(data)
33
{
34
    let returnValue = '';
35
    for (let byte of data)
36
	returnValue += ('00' + byte.toString(16)).slice(-2);
37
    return returnValue;
38
}
39

    
40
function gen_nonce(length) // Default 16
41
{
42
    let randomData = new Uint8Array(length || 16);
43
    crypto.getRandomValues(randomData);
44
    return Uint8toHex(randomData);
45
}
46

    
47
function gen_unique(url)
48
{
49
    return sha256(get_secure_salt() + url);
50
}
51

    
52
function get_secure_salt()
53
{
54
    if (is_chrome)
55
	return browser.runtime.getManifest().key.substring(0, 50);
56
    else
57
	return browser.runtime.getURL("dummy");
58
}
59

    
60
/*
61
 * stripping url from query and target (everything after `#' or `?'
62
 * gets removed)
63
 */
64
function url_item(url)
65
{
66
    let url_re = /^([^?#]*).*$/;
67
    let match = url_re.exec(url);
68
    return match[1];
69
}
70

    
71
/*
72
 * Assume a url like:
73
 *     https://example.com/green?illuminati=confirmed#<injected-policy>#winky
74
 * This function will make it into an object like:
75
 * {
76
 *     "base_url": "https://example.com/green?illuminati=confirmed",
77
 *     "target":   "#<injected-policy>",
78
 *     "target2":  "#winky",
79
 *     "policy":   <injected-policy-as-js-object>,
80
 *     "current":  <boolean-indicating-whether-policy-url-matches>
81
 * }
82
 * In case url doesn't have 2 #'s, target2 and target can be set to undefined.
83
 */
84
function url_extract_target(url)
85
{
86
    const url_re = /^([^#]*)((#[^#]*)(#.*)?)?$/;
87
    const match = url_re.exec(url);
88
    const targets  = {
89
	base_url: match[1],
90
	target:   match[3] || "",
91
	target2:  match[4] || ""
92
    };
93
    if (!targets.target)
94
	return targets;
95

    
96
    /* %7B -> { */
97
    const index = targets.target.indexOf('%7B');
98
    if (index === -1)
99
	return targets;
100

    
101
    const now = new Date();
102
    const sig = targets.target.substring(1, index);
103
    const policy = targets.target.substring(index);
104
    if (sig !== sign_policy(policy, now) &&
105
	sig !== sign_policy(policy, now, -1))
106
	return targets;
107

    
108
    try {
109
	targets.policy = JSON.parse(decodeURIComponent(policy));
110
	targets.current = targets.policy.base_url === targets.base_url;
111
    } catch (e) {
112
	/* This should not be reached - it's our self-produced valid JSON. */
113
	console.log("Unexpected internal error - invalid JSON smuggled!", e);
114
    }
115

    
116
    return targets;
117
}
118

    
119
/* csp rule that blocks all scripts except for those injected by us */
120
function csp_rule(nonce)
121
{
122
    let rule = `script-src 'nonce-${nonce}';`;
123
    if (is_chrome)
124
	rule += `script-src-elem 'nonce-${nonce}';`;
125
    return rule;
126
}
127

    
128
/*
129
 * Print item together with type, e.g.
130
 * nice_name("s", "hello") → "hello (script)"
131
 */
132
function nice_name(prefix, name)
133
{
134
    return `${name} (${TYPE_NAME[prefix]})`;
135
}
136

    
137
/* Open settings tab with given item's editing already on. */
138
function open_in_settings(prefix, name)
139
{
140
    name = encodeURIComponent(name);
141
    const url = browser.runtime.getURL("html/options.html#" + prefix + name);
142
    window.open(url, "_blank");
143
}
144

    
145
/* Check if url corresponds to a browser's special page */
146
function is_privileged_url(url)
147
{
148
    return !!/^(chrome(-extension)?|moz-extension):\/\/|^about:/i.exec(url);
149
}
150

    
151
/* Sign a given policy for a given time */
152
function sign_policy(policy, now, hours_offset) {
153
    let time = Math.floor(now / 3600000) + (hours_offset || 0);
154
    return gen_unique(time + policy);
155
}
156

    
157
/* Parse a CSP header */
158
function parse_csp(csp) {
159
    let directive, directive_array;
160
    let directives = {};
161
    for (directive of csp.split(';')) {
162
	directive = directive.trim;
163
	if (directive === '')
164
	    continue;
165

    
166
	directive_array = directive.split(/\s+/);
167
	directive = directive_array.shift();
168
	/* The "true" case should never occur; nevertheless... */
169
	directives[directive] = directive in directives ?
170
	    directives[directive].concat(directive_array) :
171
	    directive_array;
172
    }
173
    return directives;
174
}
175

    
176
/*
177
 * EXPORTS_START
178
 * EXPORT gen_nonce
179
 * EXPORT gen_unique
180
 * EXPORT url_item
181
 * EXPORT url_extract_target
182
 * EXPORT sign_policy
183
 * EXPORT csp_rule
184
 * EXPORT nice_name
185
 * EXPORT open_in_settings
186
 * EXPORT is_privileged_url
187
 * EXPORT parse_csp
188
 * EXPORTS_END
189
 */
(4-4/9)