From 014f2a2f4e2071c35314d67285711f0f4615266b Mon Sep 17 00:00:00 2001 From: Wojtek Kosior Date: Wed, 18 Aug 2021 17:53:57 +0200 Subject: implement smuggling via cookies instead of URL --- common/misc.js | 84 ++++++++++++---------------------------------------------- 1 file changed, 17 insertions(+), 67 deletions(-) (limited to 'common') diff --git a/common/misc.js b/common/misc.js index 3c7dc46..39c696f 100644 --- a/common/misc.js +++ b/common/misc.js @@ -45,11 +45,6 @@ function gen_nonce(length) // Default 16 return Uint8toHex(randomData); } -function gen_unique(url) -{ - return sha256(get_secure_salt() + url); -} - function get_secure_salt() { if (is_chrome) @@ -58,72 +53,29 @@ function get_secure_salt() return browser.runtime.getURL("dummy"); } -/* - * stripping url from query and target (everything after `#' or `?' - * gets removed) - */ -function url_item(url) -{ - let url_re = /^([^?#]*).*$/; - let match = url_re.exec(url); - return match[1]; -} - -/* - * Assume a url like: - * https://example.com/green?illuminati=confirmed##winky - * This function will make it into an object like: - * { - * "base_url": "https://example.com/green?illuminati=confirmed", - * "target": "#", - * "target2": "#winky", - * "policy": , - * "current": - * } - * In case url doesn't have 2 #'s, target2 and target can be set to undefined. - */ -function url_extract_target(url) +function extract_signed(signature, data, times) { - const url_re = /^([^#]*)((#[^#]*)(#.*)?)?$/; - const match = url_re.exec(url); - const targets = { - base_url: match[1], - target: match[3] || "", - target2: match[4] || "" - }; - if (!targets.target) - return targets; - - /* %7B -> { */ - const index = targets.target.indexOf('%7B'); - if (index === -1) - return targets; - const now = new Date(); - const sig = targets.target.substring(1, index); - const policy = targets.target.substring(index); - if (sig !== sign_policy(policy, now) && - sig !== sign_policy(policy, now, -1)) - return targets; + times ||= [[now], [now, -1]]; + + const reductor = + (ok, time) => ok || signature === sign_data(data, ...time); + if (!times.reduce(reductor, false)) + return undefined; try { - targets.policy = JSON.parse(decodeURIComponent(policy)); - targets.current = targets.policy.base_url === targets.base_url; + return JSON.parse(decodeURIComponent(data)); } catch (e) { /* This should not be reached - it's our self-produced valid JSON. */ console.log("Unexpected internal error - invalid JSON smuggled!", e); } - - return targets; } /* csp rule that blocks all scripts except for those injected by us */ function csp_rule(nonce) { - let rule = `script-src 'nonce-${nonce}';`; - if (is_chrome) - rule += `script-src-elem 'nonce-${nonce}';`; - return rule; + const rule = `'nonce-${nonce}'`; + return `script-src ${rule}; script-src-elem ${rule}; script-src-attr 'none'; prefetch-src 'none';`; } /* @@ -149,10 +101,10 @@ function is_privileged_url(url) return !!/^(chrome(-extension)?|moz-extension):\/\/|^about:/i.exec(url); } -/* Sign a given policy for a given time */ -function sign_policy(policy, now, hours_offset) { +/* Sign a given string for a given time */ +function sign_data(data, now, hours_offset) { let time = Math.floor(now / 3600000) + (hours_offset || 0); - return gen_unique(time + policy); + return sha256(get_secure_salt() + time + data); } /* Parse a CSP header */ @@ -175,11 +127,11 @@ function parse_csp(csp) { } /* Make CSP headers do our bidding, not interfere */ -function sanitize_csp_header(header, rule, block) +function sanitize_csp_header(header, rule, allow) { const csp = parse_csp(header.value); - if (block) { + if (!allow) { /* No snitching */ delete csp['report-to']; delete csp['report-uri']; @@ -223,10 +175,8 @@ const matchers = { /* * EXPORTS_START * EXPORT gen_nonce - * EXPORT gen_unique - * EXPORT url_item - * EXPORT url_extract_target - * EXPORT sign_policy + * EXPORT extract_signed + * EXPORT sign_data * EXPORT csp_rule * EXPORT nice_name * EXPORT open_in_settings -- cgit v1.2.3 From 3d0efa153c95f3bf4912379f910bc59d0fd563c9 Mon Sep 17 00:00:00 2001 From: Wojtek Kosior Date: Wed, 18 Aug 2021 20:54:07 +0200 Subject: remove unneeded policy-related cosole messages; restore IceCat 60 compatibility --- background/policy_injector.js | 3 +-- build.sh | 19 +++++++++++++++++-- common/misc.js | 2 +- content/main.js | 5 +---- 4 files changed, 20 insertions(+), 9 deletions(-) (limited to 'common') diff --git a/background/policy_injector.js b/background/policy_injector.js index 947812e..702f879 100644 --- a/background/policy_injector.js +++ b/background/policy_injector.js @@ -33,7 +33,6 @@ const report_only = "content-security-policy-report-only"; function headers_inject(details) { - console.log("ijnector details", details); const url = details.url; if (is_privileged_url(url)) return; @@ -70,7 +69,7 @@ function headers_inject(details) headers.push(hachette_header); } - orig_csp_headers ||= + orig_csp_headers = orig_csp_headers || headers.filter(h => csp_header_names.has(h.name.toLowerCase())); headers = headers.filter(h => !csp_header_names.has(h.name.toLowerCase())); diff --git a/build.sh b/build.sh index 941ce1e..31f3dec 100755 --- a/build.sh +++ b/build.sh @@ -267,9 +267,24 @@ $(map_get EXPORTCODES $FILEKEY) done if [ "$BROWSER" = "chromium" ]; then - echo "window.killtheweb={is_chrome: true, browser: window.chrome};" > $BUILDDIR/exports_init.js + cat > $BUILDDIR/exports_init.js < $BUILDDIR/exports_init.js + cat > $BUILDDIR/exports_init.js < ok || signature === sign_data(data, ...time); diff --git a/content/main.js b/content/main.js index 8adcd48..164ebe3 100644 --- a/content/main.js +++ b/content/main.js @@ -84,8 +84,6 @@ function block_script(node) function inject_csp(head) { - console.log('injecting CSP'); - let meta = document.createElement("meta"); meta.setAttribute("http-equiv", "Content-Security-Policy"); meta.setAttribute("content", csp_rule(nonce)); @@ -102,9 +100,8 @@ if (!is_privileged_url(document.URL)) { const matches = [...document.cookie.matchAll(/hachette-(\w*)=([^;]*)/g)]; let [policy, signature] = matches.reduce(reductor, []); - console.log("extracted policy", [signature, policy]); if (!policy || policy.url !== document.URL) { - console.log("using default policy"); + console.log("WARNING! Using default policy!!!"); policy = {allow: false, nonce: gen_nonce()}; } -- cgit v1.2.3 From d09b7ee10541b5a81430d2e11abb3a9a09643ade Mon Sep 17 00:00:00 2001 From: Wojtek Kosior Date: Fri, 20 Aug 2021 12:57:48 +0200 Subject: sanitize `' tags containing CSP rules under Chromium This commit adds a mechanism of hijacking document when it loads and injecting sanitized nodes to the DOM from the level of content script. --- background/policy_injector.js | 23 ++--- common/misc.js | 27 +++++- content/main.js | 99 ++++---------------- content/sanitize_document.js | 209 ++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 256 insertions(+), 102 deletions(-) create mode 100644 content/sanitize_document.js (limited to 'common') diff --git a/background/policy_injector.js b/background/policy_injector.js index 702f879..3398b53 100644 --- a/background/policy_injector.js +++ b/background/policy_injector.js @@ -18,19 +18,12 @@ * IMPORT query_best * IMPORT sanitize_csp_header * IMPORT csp_rule + * IMPORT is_csp_header_name * IMPORTS_END */ var storage; -const csp_header_names = new Set([ - "content-security-policy", - "x-webkit-csp", - "x-content-security-policy" -]); - -const report_only = "content-security-policy-report-only"; - function headers_inject(details) { const url = details.url; @@ -40,7 +33,6 @@ function headers_inject(details) const [pattern, settings] = query_best(storage, url); const allow = !!(settings && settings.allow); const nonce = gen_nonce(); - const rule = `'nonce-${nonce}'`; let orig_csp_headers; let old_signature; @@ -70,20 +62,19 @@ function headers_inject(details) } orig_csp_headers = orig_csp_headers || - headers.filter(h => csp_header_names.has(h.name.toLowerCase())); - headers = headers.filter(h => !csp_header_names.has(h.name.toLowerCase())); + headers.filter(h => is_csp_header_name(h.name)); - /* Remove headers that only snitch on us */ - if (!allow) - headers = headers.filter(h => h.name.toLowerCase() !== report_only); + /* When blocking remove report-only CSP headers that snitch on us. */ + headers = headers.filter(h => !is_csp_header_name(h.name, !allow)); if (old_signature) headers = headers.filter(h => h.name.search(old_signature) === -1); - const sanitizer = h => sanitize_csp_header(h, rule, allow); + const policy_object = {allow, nonce, url}; + const sanitizer = h => sanitize_csp_header(h, policy_object); headers.push(...orig_csp_headers.map(sanitizer)); - const policy = encodeURIComponent(JSON.stringify({allow, nonce, url})); + const policy = encodeURIComponent(JSON.stringify(policy_object)); const policy_signature = sign_data(policy, new Date()); const later_30sec = new Date(new Date().getTime() + 30000).toGMTString(); headers.push({ diff --git a/common/misc.js b/common/misc.js index 6e825d6..8894d60 100644 --- a/common/misc.js +++ b/common/misc.js @@ -78,6 +78,23 @@ function csp_rule(nonce) return `script-src ${rule}; script-src-elem ${rule}; script-src-attr 'none'; prefetch-src 'none';`; } +/* Check if some HTTP header might define CSP rules. */ +const csp_header_names = new Set([ + "content-security-policy", + "x-webkit-csp", + "x-content-security-policy" +]); + +const report_only_header_name = "content-security-policy-report-only"; + +function is_csp_header_name(string, include_report_only) +{ + string = string && string.toLowerCase() || ""; + + return (include_report_only && string === report_only_header_name) || + csp_header_names.has(string); +} + /* * Print item together with type, e.g. * nice_name("s", "hello") → "hello (script)" @@ -127,11 +144,12 @@ function parse_csp(csp) { } /* Make CSP headers do our bidding, not interfere */ -function sanitize_csp_header(header, rule, allow) +function sanitize_csp_header(header, policy) { + const rule = `'nonce-${policy.nonce}'`; const csp = parse_csp(header.value); - if (!allow) { + if (!policy.allow) { /* No snitching */ delete csp['report-to']; delete csp['report-uri']; @@ -153,11 +171,11 @@ function sanitize_csp_header(header, rule, allow) else csp['script-src-elem'] = [rule]; - const new_policy = Object.entries(csp).map( + const new_csp = Object.entries(csp).map( i => `${i[0]} ${i[1].join(' ')};` ); - return {name: header.name, value: new_policy.join('')}; + return {name: header.name, value: new_csp.join('')}; } /* Regexes and objest to use as/in schemas for parse_json_with_schema(). */ @@ -178,6 +196,7 @@ const matchers = { * EXPORT extract_signed * EXPORT sign_data * EXPORT csp_rule + * EXPORT is_csp_header_name * EXPORT nice_name * EXPORT open_in_settings * EXPORT is_privileged_url diff --git a/content/main.js b/content/main.js index 164ebe3..441636c 100644 --- a/content/main.js +++ b/content/main.js @@ -11,87 +11,24 @@ * IMPORT handle_page_actions * IMPORT extract_signed * IMPORT gen_nonce - * IMPORT csp_rule * IMPORT is_privileged_url - * IMPORT sanitize_attributes * IMPORT mozilla_suppress_scripts * IMPORT is_chrome * IMPORT is_mozilla * IMPORT start_activity_info_server + * IMPORT modify_on_the_fly * IMPORTS_END */ -/* - * Due to some technical limitations the chosen method of whitelisting sites - * is to smuggle whitelist indicator in page's url as a "magical" string - * after '#'. Right now this is only supplemental in HTTP(s) pages where - * blocking of native scripts also happens through CSP header injection but is - * necessary for protocols like ftp:// and file://. - * - * The code that actually injects the magical string into ftp:// and file:// - * urls has not yet been added to the extension. - */ - -var nonce = undefined; - -function handle_mutation(mutations, observer) -{ - if (document.readyState === 'complete') { - console.log("mutation handling complete"); - observer.disconnect(); - return; - } - for (const mutation of mutations) { - for (const node of mutation.addedNodes) - block_node(node); - } -} - -function block_nodes_recursively(node) -{ - block_node(node); - for (const child of node.children) - block_nodes_recursively(child); -} - -function block_node(node) +function accept_node(node, parent) { + const clone = document.importNode(node, false); + node.hachette_corresponding = clone; /* - * Modifying `; + ``; const doctype_decl = /^(\s*"']*>)?/i.exec(decoded)[0]; decoded = doctype_decl + dummy_script + decoded.substring(doctype_decl.length); diff --git a/common/ajax.js b/common/ajax.js index 8082bbe..7269a8a 100644 --- a/common/ajax.js +++ b/common/ajax.js @@ -1,6 +1,7 @@ /** - * part of Hachette - * Wrapping XMLHttpRequest into a Promise. + * This file is part of Haketilo. + * + * Function: Wrapping XMLHttpRequest into a Promise. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/common/connection_types.js b/common/connection_types.js index 88c6964..3e9df56 100644 --- a/common/connection_types.js +++ b/common/connection_types.js @@ -1,5 +1,7 @@ /** - * Hachette background scripts message connection types "enum" + * This file is part of Haketilo. + * + * Function: Define an "enum" of message connection types. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/common/lock.js b/common/lock.js index 822ad1b..6cf0835 100644 --- a/common/lock.js +++ b/common/lock.js @@ -1,5 +1,7 @@ /** - * Hachette lock (aka binary semaphore aka mutex) + * This file is part of Haketilo. + * + * Function: Implement a lock (aka binary semaphore aka mutex). * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/common/message_server.js b/common/message_server.js index ea40487..c8c6696 100644 --- a/common/message_server.js +++ b/common/message_server.js @@ -1,5 +1,7 @@ /** - * Hachette message server + * This file is part of Haketilo. + * + * Function: Message server. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/common/misc.js b/common/misc.js index 6cded84..9ffb7ff 100644 --- a/common/misc.js +++ b/common/misc.js @@ -1,5 +1,7 @@ /** - * Hachette miscellaneous operations refactored to a separate file + * This file is part of Haketilo. + * + * Function: Miscellaneous operations refactored to a separate file. * * Copyright (C) 2021 Wojtek Kosior * Copyright (C) 2021 jahoti diff --git a/common/observable.js b/common/observable.js index 02f1c1b..ab3b444 100644 --- a/common/observable.js +++ b/common/observable.js @@ -1,6 +1,7 @@ /** - * part of Hachette - * Facilitate listening to events + * This file is part of Haketilo. + * + * Function: Facilitate listening to (internal, self-generated) events. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/common/once.js b/common/once.js index 098b43f..93e842f 100644 --- a/common/once.js +++ b/common/once.js @@ -1,5 +1,8 @@ /** - * Hachette feature initialization promise + * This file is part of Haketilo. + * + * Function: Wrap APIs that depend on some asynchronous initialization into + * promises. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/common/patterns.js b/common/patterns.js index ae29fcd..625be05 100644 --- a/common/patterns.js +++ b/common/patterns.js @@ -1,5 +1,7 @@ /** - * Hachette operations on page url patterns + * This file is part of Haketilo. + * + * Function: Operations on page URL patterns. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/common/sanitize_JSON.js b/common/sanitize_JSON.js index 8b86d2d..4cf1ef4 100644 --- a/common/sanitize_JSON.js +++ b/common/sanitize_JSON.js @@ -1,6 +1,7 @@ /** - * part of Hachette - * Powerful, full-blown format enforcer for externally-obtained JSON + * This file is part of Haketilo. + * + * Function: Powerful, full-blown format enforcer for externally-obtained JSON. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/common/settings_query.js b/common/settings_query.js index b54e580..7e1315e 100644 --- a/common/settings_query.js +++ b/common/settings_query.js @@ -1,5 +1,7 @@ /** - * Hachette querying page settings with regard to wildcard records + * This file is part of Haketilo. + * + * Function: Querying page settings. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/common/signing.js b/common/signing.js index 1904bcd..11cd442 100644 --- a/common/signing.js +++ b/common/signing.js @@ -1,6 +1,7 @@ /** - * part of Hachette - * Functions related to "signing" of data, refactored to a separate file. + * This file is part of Haketilo. + * + * Functions: Operations related to "signing" of data. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. @@ -16,7 +17,7 @@ /* * In order to make certain data synchronously accessible in certain contexts, - * hachette smuggles it in string form in places like cookies, URLs and headers. + * Haketilo smuggles it in string form in places like cookies, URLs and headers. * When using the smuggled data, we first need to make sure it isn't spoofed. * For that, we use this pseudo-signing mechanism. * diff --git a/common/storage_client.js b/common/storage_client.js index 2b2f495..ef4a0b8 100644 --- a/common/storage_client.js +++ b/common/storage_client.js @@ -1,5 +1,7 @@ /** - * Hachette storage through connection (client side) + * This file is part of Haketilo. + * + * Function: Storage through messages (client side). * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/common/storage_light.js b/common/storage_light.js index 067bf0c..32e3b1f 100644 --- a/common/storage_light.js +++ b/common/storage_light.js @@ -1,6 +1,7 @@ /** - * part of Hachette - * Storage manager, lighter than the previous one. + * This file is part of Haketilo. + * + * Function: Storage manager, lighter than the previous one. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/common/storage_raw.js b/common/storage_raw.js index 4c02ee4..e354b6b 100644 --- a/common/storage_raw.js +++ b/common/storage_raw.js @@ -1,6 +1,7 @@ /** - * part of Hachette - * Basic wrappers for storage API functions. + * This file is part of Haketilo. + * + * Function: Basic wrappers for storage API functions. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/common/stored_types.js b/common/stored_types.js index bfceba6..a693b1c 100644 --- a/common/stored_types.js +++ b/common/stored_types.js @@ -1,5 +1,7 @@ /** - * Hachette stored item types "enum" + * This file is part of Haketilo. + * + * Function: Define an "enum" of stored item types. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/content/activity_info_server.js b/content/activity_info_server.js index 1b69703..d1dfe36 100644 --- a/content/activity_info_server.js +++ b/content/activity_info_server.js @@ -1,7 +1,8 @@ /** - * part of Hachette - * Informing about activities performed by content script (script injection, - * script blocking). + * This file is part of Haketilo. + * + * Function: Informing the popup about what happens in the content script + * (script injection, script blocking, etc.). * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/content/main.js b/content/main.js index 6478ea0..cec9943 100644 --- a/content/main.js +++ b/content/main.js @@ -1,5 +1,7 @@ /** - * Hachette main content script run in all frames + * This file is part of Haketilo. + * + * Function: Main content script that runs in all frames. * * Copyright (C) 2021 Wojtek Kosior * Copyright (C) 2021 jahoti @@ -33,7 +35,7 @@ function extract_cookie_policy(cookie, min_time) let policy = null; const extracted_signatures = []; - for (const match of cookie.matchAll(/hachette-(\w*)=([^;]*)/g)) { + for (const match of cookie.matchAll(/haketilo-(\w*)=([^;]*)/g)) { const new_result = extract_signed(...match.slice(1, 3)); if (new_result.fail) continue; @@ -60,7 +62,7 @@ function extract_url_policy(url, min_time) const [base_url, payload, anchor] = /^([^#]*)#?([^#]*)(#?.*)$/.exec(url).splice(1, 4); - const match = /^hachette_([^_]+)_(.*)$/.exec(payload); + const match = /^haketilo_([^_]+)_(.*)$/.exec(payload); if (!match) return [null, url]; @@ -83,7 +85,7 @@ function employ_nonhttp_policy(policy) policy.nonce = gen_nonce(); const [base_url, target] = /^([^#]*)(#?.*)$/.exec(policy.url).slice(1, 3); const encoded_policy = encodeURIComponent(JSON.stringify(policy)); - const payload = "hachette_" + + const payload = "haketilo_" + sign_data(encoded_policy, new Date().getTime()).join("_"); const resulting_url = `${base_url}#${payload}${target}`; location.href = resulting_url; @@ -187,7 +189,7 @@ function sanitize_meta(meta) function sanitize_script(script) { - script.hachette_blocked_type = script.getAttribute("type"); + script.haketilo_blocked_type = script.getAttribute("type"); script.type = "text/plain"; } @@ -197,12 +199,12 @@ function sanitize_script(script) */ function desanitize_script(script) { - script.setAttribute("type", script.hachette_blocked_type); + script.setAttribute("type", script.haketilo_blocked_type); - if ([null, undefined].includes(script.hachette_blocked_type)) + if ([null, undefined].includes(script.haketilo_blocked_type)) script.removeAttribute("type"); - delete script.hachette_blocked_type; + delete script.haketilo_blocked_type; } const bad_url_reg = /^data:([^,;]*ml|unknown-content-type)/i; @@ -235,7 +237,7 @@ function start_data_urls_sanitizing(doc) */ function prevent_script_execution(event) { - if (!event.target._hachette_payload) + if (!event.target.haketilo_payload) event.preventDefault(); } @@ -336,7 +338,7 @@ if (!is_privileged_url(document.URL)) { let signatures; [policy, signatures] = extract_cookie_policy(document.cookie, min_time); for (const signature of signatures) - document.cookie = `hachette-${signature}=; Max-Age=-1;`; + document.cookie = `haketilo-${signature}=; Max-Age=-1;`; } else { const scheme = /^([^:]*)/.exec(document.URL)[1]; const known_scheme = ["file", "ftp"].includes(scheme); diff --git a/content/page_actions.js b/content/page_actions.js index 040b4ab..db7c352 100644 --- a/content/page_actions.js +++ b/content/page_actions.js @@ -1,5 +1,7 @@ /** - * Hachette handling of page actions in content scripts + * This file is part of Haketilo. + * + * Function: Handle page actions in a content script. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. @@ -60,7 +62,7 @@ function add_script(script_text) let script = document.createElement("script"); script.textContent = script_text; script.setAttribute("nonce", nonce); - script._hachette_payload = true; + script.haketilo_payload = true; document.body.appendChild(script); report_script(script_text); diff --git a/content/repo_query.js b/content/repo_query.js index 3708108..637282c 100644 --- a/content/repo_query.js +++ b/content/repo_query.js @@ -1,6 +1,7 @@ /** - * part of Hachette - * Getting available content for site from remote repositories. + * This file is part of Haketilo. + * + * Function: Getting available content for site from remote repositories. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/copyright b/copyright index 4c37eb3..fe2aed7 100644 --- a/copyright +++ b/copyright @@ -1,5 +1,5 @@ Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ -Upstream-Name: Hachette +Upstream-Name: Haketilo Source: https://git.koszko.org/browser-extension/ Files: * diff --git a/html/DOM_helpers.js b/html/DOM_helpers.js index 01e2be9..4fe118d 100644 --- a/html/DOM_helpers.js +++ b/html/DOM_helpers.js @@ -1,5 +1,7 @@ /** - * Hachette operations on DOM elements + * This file is part of Haketilo. + * + * Function: Operations on DOM elements. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/html/MOZILLA_scrollbar_fix.css b/html/MOZILLA_scrollbar_fix.css index 5feb7c3..cdbd5c6 100644 --- a/html/MOZILLA_scrollbar_fix.css +++ b/html/MOZILLA_scrollbar_fix.css @@ -1,6 +1,8 @@ /** - * Hachette - * Hacky fix for vertical scrollbar width being included in child's width. + * This file is part of Haketilo. + * + * Function: Hacky fix for vertical scrollbar width being included in child's + * width. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/html/back_button.css b/html/back_button.css index 1ddc5da..b83e834 100644 --- a/html/back_button.css +++ b/html/back_button.css @@ -1,6 +1,7 @@ /** - * part of Hachette - * Style for a "back" button with a CSS arrow image. + * This file is part of Haketilo. + * + * Function: Style for a "back" button with a CSS arrow image. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/html/base.css b/html/base.css index df52f7c..517a5c1 100644 --- a/html/base.css +++ b/html/base.css @@ -1,5 +1,7 @@ /** - * Hachette base styles + * This file is part of Haketilo. + * + * Function: Base styles. * * Copyright (C) 2021 Wojtek Kosior * Copyright (C) 2021 Nicholas Johnson diff --git a/html/default_blocking_policy.js b/html/default_blocking_policy.js index 2f49bac..b6458f3 100644 --- a/html/default_blocking_policy.js +++ b/html/default_blocking_policy.js @@ -1,6 +1,7 @@ /** - * part of Hachette - * Default policy dialog logic. + * This file is part of Haketilo. + * + * Function: Logic for the dialog of default policy selection. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/html/display-panel.html b/html/display-panel.html index 3ed1b7a..ee9e767 100644 --- a/html/display-panel.html +++ b/html/display-panel.html @@ -1,12 +1,16 @@ - Hachette - page settings + Haketilo - page settings @@ -331,7 +335,7 @@ diff --git a/html/display-panel.js b/html/display-panel.js index 84c922f..c078850 100644 --- a/html/display-panel.js +++ b/html/display-panel.js @@ -1,5 +1,7 @@ /** - * Hachette display panel logic + * This file is part of Haketilo. + * + * Function: Popup logic. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/html/import_frame.js b/html/import_frame.js index c0eb2f0..ae6fab4 100644 --- a/html/import_frame.js +++ b/html/import_frame.js @@ -1,5 +1,7 @@ /** - * Hachette HTML import frame script + * This file is part of Haketilo. + * + * Function: Logic for the settings import frame. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/html/options.html b/html/options.html index 54ab9e8..2e8317c 100644 --- a/html/options.html +++ b/html/options.html @@ -1,12 +1,16 @@ - Hachette options + Haketilo options diff --git a/html/options_main.js b/html/options_main.js index 27ab0ec..f8faf9b 100644 --- a/html/options_main.js +++ b/html/options_main.js @@ -1,5 +1,7 @@ /** - * Hachette HTML options page main script + * This file is part of Haketilo. + * + * Function: Settings page logic. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. diff --git a/icons/hachette.svg b/icons/hachette.svg deleted file mode 100644 index 6e8948d..0000000 --- a/icons/hachette.svg +++ /dev/null @@ -1,127 +0,0 @@ - - - Hatchet - - - - - - - - - - - - image/svg+xml - - Hatchet - - - David Lyons - - - - - dlyons - - - - 2017-05 - - - hatchet - ax - wood - - - Hatchet - - - - - - - - - - - - - - - - - - - - - - diff --git a/icons/hachette128.png b/icons/hachette128.png deleted file mode 100644 index 18816e9..0000000 Binary files a/icons/hachette128.png and /dev/null differ diff --git a/icons/hachette16.png b/icons/hachette16.png deleted file mode 100644 index 182ede5..0000000 Binary files a/icons/hachette16.png and /dev/null differ diff --git a/icons/hachette32.png b/icons/hachette32.png deleted file mode 100644 index ffaa84b..0000000 Binary files a/icons/hachette32.png and /dev/null differ diff --git a/icons/hachette48.png b/icons/hachette48.png deleted file mode 100644 index 1ffcd38..0000000 Binary files a/icons/hachette48.png and /dev/null differ diff --git a/icons/hachette64.png b/icons/hachette64.png deleted file mode 100644 index a02abb0..0000000 Binary files a/icons/hachette64.png and /dev/null differ diff --git a/icons/haketilo.svg b/icons/haketilo.svg new file mode 100644 index 0000000..6e8948d --- /dev/null +++ b/icons/haketilo.svg @@ -0,0 +1,127 @@ + + + Hatchet + + + + + + + + + + + + image/svg+xml + + Hatchet + + + David Lyons + + + + + dlyons + + + + 2017-05 + + + hatchet + ax + wood + + + Hatchet + + + + + + + + + + + + + + + + + + + + + + diff --git a/icons/haketilo128.png b/icons/haketilo128.png new file mode 100644 index 0000000..18816e9 Binary files /dev/null and b/icons/haketilo128.png differ diff --git a/icons/haketilo16.png b/icons/haketilo16.png new file mode 100644 index 0000000..182ede5 Binary files /dev/null and b/icons/haketilo16.png differ diff --git a/icons/haketilo32.png b/icons/haketilo32.png new file mode 100644 index 0000000..ffaa84b Binary files /dev/null and b/icons/haketilo32.png differ diff --git a/icons/haketilo48.png b/icons/haketilo48.png new file mode 100644 index 0000000..1ffcd38 Binary files /dev/null and b/icons/haketilo48.png differ diff --git a/icons/haketilo64.png b/icons/haketilo64.png new file mode 100644 index 0000000..a02abb0 Binary files /dev/null and b/icons/haketilo64.png differ diff --git a/manifest.json b/manifest.json index ce2577e..9d34732 100644 --- a/manifest.json +++ b/manifest.json @@ -1,18 +1,20 @@ +// This is the manifest file of Haketilo. +// // Copyright (C) 2021 Wojtek Kosior // Redistribution terms are gathered in the `copyright' file. { "manifest_version": 2, - "name": "Hachette", - "short_name": "Hachette", + "name": "Haketilo", + "short_name": "Haketilo", "version": "0.0.1", "author": "various", "description": "Control your \"Web\" browsing.",_GECKO_APPLICATIONS_ "icons":{ - "128": "icons/hachette128.png", - "64": "icons/hachette64.png", - "48": "icons/hachette48.png", - "32": "icons/hachette32.png", - "16": "icons/hachette16.png" + "128": "icons/haketilo128.png", + "64": "icons/haketilo64.png", + "48": "icons/haketilo48.png", + "32": "icons/haketilo32.png", + "16": "icons/haketilo16.png" }, "permissions": [ "contextMenus", @@ -29,13 +31,13 @@ "browser_action": { "browser_style": true, "default_icon": { - "128": "icons/hachette128.png", - "64": "icons/hachette64.png", - "48": "icons/hachette48.png", - "32": "icons/hachette32.png", - "16": "icons/hachette16.png" + "128": "icons/haketilo128.png", + "64": "icons/haketilo64.png", + "48": "icons/haketilo48.png", + "32": "icons/haketilo32.png", + "16": "icons/haketilo16.png" }, - "default_title": "Hachette", + "default_title": "Haketilo", "default_popup": "html/display-panel.html" }, "options_ui": { diff --git a/re-generate_icons.sh b/re-generate_icons.sh index ba0c28a..e557ad0 100755 --- a/re-generate_icons.sh +++ b/re-generate_icons.sh @@ -4,5 +4,5 @@ # Redistribution terms are gathered in the `copyright' file. for SIZE in 128 64 48 32 16; do - inkscape -z -e icons/hachette$SIZE.png -w $SIZE -h $SIZE icons/hachette.svg + inkscape -z -e icons/haketilo$SIZE.png -w $SIZE -h $SIZE icons/haketilo.svg done -- cgit v1.2.3 From 96068ada37bfa1d7e6485551138ba36600664caf Mon Sep 17 00:00:00 2001 From: Wojtek Kosior Date: Sat, 20 Nov 2021 18:29:59 +0100 Subject: replace cookies with synchronous XmlHttpRequest as policy smuggling method. Note: this breaks Mozilla port of Haketilo. Synchronous XmlHttpRequest doesn't work as well there. This will be fixed with dynamically-registered content scripts later. --- background/cookie_filter.js | 46 ------------- background/main.js | 120 +++++++++++++++++++++++++++------ background/page_actions_server.js | 32 ++------- background/policy_injector.js | 67 +++--------------- background/stream_filter.js | 6 +- build.sh | 16 +---- common/misc.js | 2 +- common/signing.js | 74 -------------------- content/activity_info_server.js | 4 +- content/main.js | 138 +++++++++++--------------------------- content/page_actions.js | 27 ++++---- dummy | 0 html/display-panel.js | 13 ++-- manifest.json | 3 +- 14 files changed, 180 insertions(+), 368 deletions(-) delete mode 100644 background/cookie_filter.js delete mode 100644 common/signing.js create mode 100644 dummy (limited to 'common') diff --git a/background/cookie_filter.js b/background/cookie_filter.js deleted file mode 100644 index 64d18b2..0000000 --- a/background/cookie_filter.js +++ /dev/null @@ -1,46 +0,0 @@ -/** - * This file is part of Haketilo. - * - * Function: Filtering request headers to remove haketilo cookies that might - * have slipped through. - * - * Copyright (C) 2021 Wojtek Kosior - * Redistribution terms are gathered in the `copyright' file. - */ - -/* - * IMPORTS_START - * IMPORT extract_signed - * IMPORTS_END - */ - -function is_valid_haketilo_cookie(cookie) -{ - const match = /^haketilo-(\w*)=(.*)$/.exec(cookie); - if (!match) - return false; - - return !extract_signed(match.slice(1, 3)).fail; -} - -function remove_haketilo_cookies(header) -{ - if (header.name !== "Cookie") - return header; - - const cookies = header.value.split("; "); - const value = cookies.filter(c => !is_valid_haketilo_cookie(c)).join("; "); - - return value ? {name: "Cookie", value} : null; -} - -function filter_cookie_headers(headers) -{ - return headers.map(remove_haketilo_cookies).filter(h => h); -} - -/* - * EXPORTS_START - * EXPORT filter_cookie_headers - * EXPORTS_END - */ diff --git a/background/main.js b/background/main.js index 40b3a9e..9cdfb97 100644 --- a/background/main.js +++ b/background/main.js @@ -17,11 +17,10 @@ * IMPORT browser * IMPORT is_privileged_url * IMPORT query_best - * IMPORT gen_nonce * IMPORT inject_csp_headers * IMPORT apply_stream_filter - * IMPORT filter_cookie_headers * IMPORT is_chrome + * IMPORT is_mozilla * IMPORTS_END */ @@ -51,34 +50,53 @@ async function init_ext(install_details) browser.runtime.onInstalled.addListener(init_ext); +/* + * The function below implements a more practical interface for what it does by + * wrapping the old query_best() function. + */ +function decide_policy_for_url(storage, policy_observable, url) +{ + if (storage === undefined) + return {allow: false}; + + const settings = + {allow: policy_observable !== undefined && policy_observable.value}; + + const [pattern, queried_settings] = query_best(storage, url); + + if (queried_settings) { + settings.payload = queried_settings.components; + settings.allow = !!queried_settings.allow && !settings.payload; + settings.pattern = pattern; + } + + return settings; +} let storage; let policy_observable = {}; -function on_headers_received(details) +function sanitize_web_page(details) { const url = details.url; if (is_privileged_url(details.url)) return; - const [pattern, settings] = query_best(storage, details.url); - const has_payload = !!(settings && settings.components); - const allow = !has_payload && - !!(settings ? settings.allow : policy_observable.value); - const nonce = gen_nonce(); - const policy = {allow, url, nonce, has_payload}; + const policy = + decide_policy_for_url(storage, policy_observable, details.url); let headers = details.responseHeaders; + + headers = inject_csp_headers(headers, policy); + let skip = false; for (const header of headers) { if ((header.name.toLowerCase().trim() === "content-disposition" && /^\s*attachment\s*(;.*)$/i.test(header.value))) skip = true; } - - headers = inject_csp_headers(headers, policy); - skip = skip || (details.statusCode >= 300 && details.statusCode < 400); + if (!skip) { /* Check for API availability. */ if (browser.webRequest.filterResponseData) @@ -88,11 +106,49 @@ function on_headers_received(details) return {responseHeaders: headers}; } -function on_before_send_headers(details) +const request_url_regex = /^[^?]*\?url=(.*)$/; +const redirect_url_template = browser.runtime.getURL("dummy") + "?settings="; + +function synchronously_smuggle_policy(details) { - let headers = details.requestHeaders; - headers = filter_cookie_headers(headers); - return {requestHeaders: headers}; + /* + * Content script will make a synchronous XmlHttpRequest to extension's + * `dummy` file to query settings for given URL. We smuggle that + * information in query parameter of the URL we redirect to. + * A risk of fingerprinting arises if a page with script execution allowed + * guesses the dummy file URL and makes an AJAX call to it. It is currently + * a problem in ManifestV2 Chromium-family port of Haketilo because Chromium + * uses predictable URLs for web-accessible resources. We plan to fix it in + * the future ManifestV3 port. + */ + if (details.type !== "xmlhttprequest") + return {cancel: true}; + + console.debug(`Settings queried using XHR for '${details.url}'.`); + + let policy = {allow: false}; + + try { + /* + * request_url should be of the following format: + * ?url= + */ + const match = request_url_regex.exec(details.url); + const queried_url = decodeURIComponent(match[1]); + + if (details.initiator && !queried_url.startsWith(details.initiator)) { + console.warn(`Blocked suspicious query of '${url}' by '${details.initiator}'. This might be the result of page fingerprinting the browser.`); + return {cancel: true}; + } + + policy = decide_policy_for_url(storage, policy_observable, queried_url); + } catch (e) { + console.warn(`Bad request! Expected ${browser.runtime.getURL("dummy")}?url=. Got ${request_url}. This might be the result of page fingerprinting the browser.`); + } + + const encoded_policy = encodeURIComponent(JSON.stringify(policy)); + + return {redirectUrl: redirect_url_template + encoded_policy}; } const all_types = [ @@ -110,18 +166,40 @@ async function start_webRequest_operations() extra_opts.push("extraHeaders"); browser.webRequest.onHeadersReceived.addListener( - on_headers_received, + sanitize_web_page, {urls: [""], types: ["main_frame", "sub_frame"]}, extra_opts.concat("responseHeaders") ); - browser.webRequest.onBeforeSendHeaders.addListener( - on_before_send_headers, - {urls: [""], types: all_types}, - extra_opts.concat("requestHeaders") + const dummy_url_pattern = browser.runtime.getURL("dummy") + "?url=*"; + browser.webRequest.onBeforeRequest.addListener( + synchronously_smuggle_policy, + {urls: [dummy_url_pattern], types: ["xmlhttprequest"]}, + extra_opts ); policy_observable = await light_storage.observe_var("default_allow"); } start_webRequest_operations(); + +const code = `\ +console.warn("Hi, I'm Mr Dynamic!"); + +console.debug("let's see how window.killtheweb looks like now"); + +console.log("killtheweb", window.killtheweb); +` + +async function test_dynamic_content_scripts() +{ + browser.contentScripts.register({ + "js": [{code}], + "matches": [""], + "allFrames": true, + "runAt": "document_start" +}); +} + +if (is_mozilla) + test_dynamic_content_scripts(); diff --git a/background/page_actions_server.js b/background/page_actions_server.js index 156a79f..74783c9 100644 --- a/background/page_actions_server.js +++ b/background/page_actions_server.js @@ -16,34 +16,12 @@ * IMPORT browser * IMPORT listen_for_connection * IMPORT sha256 - * IMPORT query_best * IMPORT make_ajax_request * IMPORTS_END */ var storage; var handler; -let policy_observable; - -function send_actions(url, port) -{ - const [pattern, queried_settings] = query_best(storage, url); - - const settings = {allow: policy_observable && policy_observable.value}; - Object.assign(settings, queried_settings); - if (settings.components) - settings.allow = false; - - const repos = storage.get_all(TYPE_PREFIX.REPO); - - port.postMessage(["settings", [pattern, settings, repos]]); - - const components = settings.components; - const processed_bags = new Set(); - - if (components !== undefined) - send_scripts([components], port, processed_bags); -} // TODO: parallelize script fetching async function send_scripts(components, port, processed_bags) @@ -116,9 +94,11 @@ async function fetch_remote_script(script_data) function handle_message(port, message, handler) { port.onMessage.removeListener(handler[0]); - let url = message.url; - console.log({url}); - send_actions(url, port); + console.debug(`Loading payload '${message.payload}'.`); + + const processed_bags = new Set(); + + send_scripts([message.payload], port, processed_bags); } function new_connection(port) @@ -134,8 +114,6 @@ async function start_page_actions_server() storage = await get_storage(); listen_for_connection(CONNECTION_TYPE.PAGE_ACTIONS, new_connection); - - policy_observable = await light_storage.observe_var("default_allow"); } /* diff --git a/background/policy_injector.js b/background/policy_injector.js index 881595b..b49ec47 100644 --- a/background/policy_injector.js +++ b/background/policy_injector.js @@ -10,77 +10,28 @@ /* * IMPORTS_START - * IMPORT sign_data - * IMPORT extract_signed * IMPORT make_csp_rule * IMPORT csp_header_regex + * Re-enable the import below once nonce stuff here is ready + * !mport gen_nonce * IMPORTS_END */ function inject_csp_headers(headers, policy) { let csp_headers; - let old_signature; - let haketilo_header; - for (const header of headers.filter(h => h.name === "x-haketilo")) { - /* x-haketilo header has format: _0_ */ - const match = /^([^_]+)_(0_.*)$/.exec(header.value); - if (!match) - continue; + if (policy.payload) { + headers = headers.filter(h => !csp_header_regex.test(h.name)); - const result = extract_signed(...match.slice(1, 3)); - if (result.fail) - continue; + // TODO: make CSP rules with nonces and facilitate passing them to + // content scripts via dynamic content script registration or + // synchronous XHRs - /* This should succeed - it's our self-produced valid JSON. */ - const old_data = JSON.parse(decodeURIComponent(result.data)); - - /* Confirmed- it's the originals, smuggled in! */ - csp_headers = old_data.csp_headers; - old_signature = old_data.policy_sig; - - haketilo_header = header; - break; + // policy.nonce = gen_nonce(); } - if (policy.has_payload) { - csp_headers = []; - const non_csp_headers = []; - const header_list = - h => csp_header_regex.test(h) ? csp_headers : non_csp_headers; - headers.forEach(h => header_list(h.name).push(h)); - headers = non_csp_headers; - } else { - headers.push(...csp_headers || []); - } - - if (!haketilo_header) { - haketilo_header = {name: "x-haketilo"}; - headers.push(haketilo_header); - } - - if (old_signature) - headers = headers.filter(h => h.value.search(old_signature) === -1); - - const policy_str = encodeURIComponent(JSON.stringify(policy)); - const signed_policy = sign_data(policy_str, new Date().getTime()); - const later_30sec = new Date(new Date().getTime() + 30000).toGMTString(); - headers.push({ - name: "Set-Cookie", - value: `haketilo-${signed_policy.join("=")}; Expires=${later_30sec};` - }); - - /* - * Smuggle in the signature and the original CSP headers for future use. - * These are signed with a time of 0, as it's not clear there is a limit on - * how long Firefox might retain headers in the cache. - */ - let haketilo_data = {csp_headers, policy_sig: signed_policy[0]}; - haketilo_data = encodeURIComponent(JSON.stringify(haketilo_data)); - haketilo_header.value = sign_data(haketilo_data, 0).join("_"); - - if (!policy.allow) { + if (!policy.allow && (policy.nonce || !policy.payload)) { headers.push({ name: "content-security-policy", value: make_csp_rule(policy) diff --git a/background/stream_filter.js b/background/stream_filter.js index e5e0827..e5d124c 100644 --- a/background/stream_filter.js +++ b/background/stream_filter.js @@ -174,8 +174,7 @@ function filter_data(properties, event) * as harmless anyway). */ - const dummy_script = - ``; + const dummy_script = ``; const doctype_decl = /^(\s*"']*>)?/i.exec(decoded)[0]; decoded = doctype_decl + dummy_script + decoded.substring(doctype_decl.length); @@ -189,11 +188,10 @@ function filter_data(properties, event) function apply_stream_filter(details, headers, policy) { - if (!policy.has_payload) + if (!policy.payload) return headers; const properties = properties_from_headers(headers); - properties.policy = policy; properties.filter = browser.webRequest.filterResponseData(details.requestId); diff --git a/build.sh b/build.sh index 936ab06..ed6a141 100755 --- a/build.sh +++ b/build.sh @@ -180,7 +180,6 @@ build_main() { mkdir -p "$BUILDDIR"/$DIR done - CHROMIUM_KEY='' CHROMIUM_UPDATE_URL='' GECKO_APPLICATIONS='' @@ -189,20 +188,7 @@ build_main() { fi if [ "$BROWSER" = "chromium" ]; then - CHROMIUM_KEY="$(dd if=/dev/urandom bs=32 count=1 2>/dev/null | base64)" - CHROMIUM_KEY=$(echo chromium-key-dummy-file-$CHROMIUM_KEY | tr / -) - touch "$BUILDDIR"/$CHROMIUM_KEY - CHROMIUM_UPDATE_URL="$UPDATE_URL" - - CHROMIUM_KEY="\n\ - // WARNING!!!\n\ - // EACH USER SHOULD REPLACE DUMMY FILE's VALUE WITH A UNIQUE ONE!!!\n\ - // OTHERWISE, SECURITY CAN BE TRIVIALLY COMPROMISED!\n\ - // Only relevant to users of chrome-based browsers.\n\ - // Users of Firefox forks are safe.\n\ - \"$CHROMIUM_KEY\"\ -" else GECKO_APPLICATIONS="\n\ \"applications\": {\n\ @@ -215,7 +201,6 @@ build_main() { sed "\ s^_GECKO_APPLICATIONS_^$GECKO_APPLICATIONS^ -s^_CHROMIUM_KEY_^$CHROMIUM_KEY^ s^_CHROMIUM_UPDATE_URL_^$CHROMIUM_UPDATE_URL^ s^_BGSCRIPTS_^$BGSCRIPTS^ s^_CONTENTSCRIPTS_^$CONTENTSCRIPTS^" \ @@ -279,6 +264,7 @@ EOF fi cp -r copyright licenses/ "$BUILDDIR" + cp dummy "$BUILDDIR" cp html/*.css "$BUILDDIR"/html mkdir "$BUILDDIR"/icons cp icons/*.png "$BUILDDIR"/icons diff --git a/common/misc.js b/common/misc.js index 9ffb7ff..5b0addb 100644 --- a/common/misc.js +++ b/common/misc.js @@ -49,7 +49,7 @@ function gen_nonce(length=16) function make_csp_rule(policy) { let rule = "prefetch-src 'none'; script-src-attr 'none';"; - const script_src = policy.has_payload ? + const script_src = policy.nonce !== undefined ? `'nonce-${policy.nonce}'` : "'none'"; rule += ` script-src ${script_src}; script-src-elem ${script_src};`; return rule; diff --git a/common/signing.js b/common/signing.js deleted file mode 100644 index 11cd442..0000000 --- a/common/signing.js +++ /dev/null @@ -1,74 +0,0 @@ -/** - * This file is part of Haketilo. - * - * Functions: Operations related to "signing" of data. - * - * Copyright (C) 2021 Wojtek Kosior - * Redistribution terms are gathered in the `copyright' file. - */ - -/* - * IMPORTS_START - * IMPORT sha256 - * IMPORT browser - * IMPORT is_mozilla - * IMPORTS_END - */ - -/* - * In order to make certain data synchronously accessible in certain contexts, - * Haketilo smuggles it in string form in places like cookies, URLs and headers. - * When using the smuggled data, we first need to make sure it isn't spoofed. - * For that, we use this pseudo-signing mechanism. - * - * Despite what name suggests, no assymetric cryptography is involved, as it - * would bring no additional benefits and would incur bigger performance - * overhead. Instead, we hash the string data together with some secret value - * that is supposed to be known only by this browser instance. Resulting hash - * sum plays the role of the signature. In the hash we also include current - * time. This way, even if signed data leaks (which shouldn't happen in the - * first place), an attacker won't be able to re-use it indefinitely. - * - * The secret shared between execution contexts has to be available - * synchronously. Under Mozilla, this is the extension's per-session id. Under - * Chromium, this is a dummy web-accessible-resource name that resides in the - * manifest and is supposed to be constructed by each user using a unique value - * (this is done automatically by `build.sh'). - */ - -function get_secret() -{ - if (is_mozilla) - return browser.runtime.getURL("dummy"); - - return chrome.runtime.getManifest().web_accessible_resources - .map(r => /^chromium-key-dummy-file-(.*)/.exec(r)).filter(r => r)[0][1]; -} - -function extract_signed(signature, signed_data) -{ - const match = /^([1-9][0-9]{12}|0)_(.*)$/.exec(signed_data); - if (!match) - return {fail: "bad format"}; - - const result = {time: parseInt(match[1]), data: match[2]}; - if (sign_data(result.data, result.time)[0] !== signature) - result.fail = "bad signature"; - - return result; -} - -/* - * Sign a given string for a given time. Time should be either 0 or in the range - * 10^12 <= time < 10^13. - */ -function sign_data(data, time) { - return [sha256(get_secret() + time + data), `${time}_${data}`]; -} - -/* - * EXPORTS_START - * EXPORT extract_signed - * EXPORT sign_data - * EXPORTS_END - */ diff --git a/content/activity_info_server.js b/content/activity_info_server.js index d1dfe36..aa92b75 100644 --- a/content/activity_info_server.js +++ b/content/activity_info_server.js @@ -42,7 +42,9 @@ function report_script(script_data) function report_settings(settings) { - report_activity("settings", settings); + const settings_clone = {}; + Object.assign(settings_clone, settings) + report_activity("settings", settings_clone); } function report_document_type(is_html) diff --git a/content/main.js b/content/main.js index cec9943..ce1ff7a 100644 --- a/content/main.js +++ b/content/main.js @@ -11,15 +11,15 @@ /* * IMPORTS_START * IMPORT handle_page_actions - * IMPORT extract_signed - * IMPORT sign_data * IMPORT gen_nonce * IMPORT is_privileged_url + * IMPORT browser * IMPORT is_chrome * IMPORT is_mozilla * IMPORT start_activity_info_server * IMPORT make_csp_rule * IMPORT csp_header_regex + * IMPORT report_settings * IMPORTS_END */ @@ -29,69 +29,6 @@ const wait_loaded = e => e.content_loaded ? Promise.resolve() : wait_loaded(document).then(() => document.content_loaded = true); -function extract_cookie_policy(cookie, min_time) -{ - let best_result = {time: -1}; - let policy = null; - const extracted_signatures = []; - - for (const match of cookie.matchAll(/haketilo-(\w*)=([^;]*)/g)) { - const new_result = extract_signed(...match.slice(1, 3)); - if (new_result.fail) - continue; - - extracted_signatures.push(match[1]); - - if (new_result.time < Math.max(min_time, best_result.time)) - continue; - - /* This should succeed - it's our self-produced valid JSON. */ - const new_policy = JSON.parse(decodeURIComponent(new_result.data)); - if (new_policy.url !== document.URL) - continue; - - best_result = new_result; - policy = new_policy; - } - - return [policy, extracted_signatures]; -} - -function extract_url_policy(url, min_time) -{ - const [base_url, payload, anchor] = - /^([^#]*)#?([^#]*)(#?.*)$/.exec(url).splice(1, 4); - - const match = /^haketilo_([^_]+)_(.*)$/.exec(payload); - if (!match) - return [null, url]; - - const result = extract_signed(...match.slice(1, 3)); - if (result.fail) - return [null, url]; - - const original_url = base_url + anchor; - const policy = result.time < min_time ? null : - JSON.parse(decodeURIComponent(result.data)); - - return [policy.url === original_url ? policy : null, original_url]; -} - -function employ_nonhttp_policy(policy) -{ - if (!policy.allow) - return; - - policy.nonce = gen_nonce(); - const [base_url, target] = /^([^#]*)(#?.*)$/.exec(policy.url).slice(1, 3); - const encoded_policy = encodeURIComponent(JSON.stringify(policy)); - const payload = "haketilo_" + - sign_data(encoded_policy, new Date().getTime()).join("_"); - const resulting_url = `${base_url}#${payload}${target}`; - location.href = resulting_url; - location.reload(); -} - /* * In the case of HTML documents: * 1. When injecting some payload we need to sanitize CSP tags before @@ -306,7 +243,7 @@ http-equiv="Content-Security-Policy" content="${make_csp_rule(policy)}"\ start_data_urls_sanitizing(doc); } -async function disable_service_workers() +async function _disable_service_workers() { if (!navigator.serviceWorker) return; @@ -315,7 +252,7 @@ async function disable_service_workers() if (registrations.length === 0) return; - console.warn("Service Workers detected on this page! Unregistering and reloading"); + console.warn("Service Workers detected on this page! Unregistering and reloading."); try { await Promise.all(registrations.map(r => r.unregister())); @@ -327,50 +264,57 @@ async function disable_service_workers() return new Promise(() => 0); } -if (!is_privileged_url(document.URL)) { - let policy_received_callback = () => undefined; - let policy; - - /* Signature valid for half an hour. */ - const min_time = new Date().getTime() - 1800 * 1000; - - if (/^https?:/.test(document.URL)) { - let signatures; - [policy, signatures] = extract_cookie_policy(document.cookie, min_time); - for (const signature of signatures) - document.cookie = `haketilo-${signature}=; Max-Age=-1;`; - } else { - const scheme = /^([^:]*)/.exec(document.URL)[1]; - const known_scheme = ["file", "ftp"].includes(scheme); - - if (!known_scheme) - console.warn(`Unknown url scheme: \`${scheme}'!`); - - let original_url; - [policy, original_url] = extract_url_policy(document.URL, min_time); - history.replaceState(null, "", original_url); - - if (known_scheme && !policy) - policy_received_callback = employ_nonhttp_policy; +/* + * Trying to use servce workers APIs might result in exceptions, for example + * when in a non-HTML document. Because of this, we wrap the function that does + * the actual work in a try {} block. + */ +async function disable_service_workers() +{ + try { + await _disable_service_workers() + } catch (e) { + console.debug("Exception thrown during an attempt to detect and disable service workers.", e); } +} - if (!policy) { - console.debug("Using fallback policy!"); - policy = {allow: false, nonce: gen_nonce()}; +function synchronously_get_policy(url) +{ + const encoded_url = encodeURIComponent(url); + const request_url = `${browser.runtime.getURL("dummy")}?url=${encoded_url}`; + + try { + var xhttp = new XMLHttpRequest(); + xhttp.open("GET", request_url, false); + xhttp.send(); + } catch(e) { + console.error("Failure to synchronously fetch policy for url.", e); + return {allow: false}; } + const policy = /^[^?]*\?settings=(.*)$/.exec(xhttp.responseURL)[1]; + return JSON.parse(decodeURIComponent(policy)); +} + +if (!is_privileged_url(document.URL)) { + const policy = synchronously_get_policy(document.URL); + if (!(document instanceof HTMLDocument)) - policy.has_payload = false; + delete policy.payload; console.debug("current policy", policy); + report_settings(policy); + + policy.nonce = gen_nonce(); + const doc_ready = Promise.all([ policy.allow ? Promise.resolve() : sanitize_document(document, policy), policy.allow ? Promise.resolve() : disable_service_workers(), wait_loaded(document) ]); - handle_page_actions(policy.nonce, policy_received_callback, doc_ready); + handle_page_actions(policy, doc_ready); start_activity_info_server(); } diff --git a/content/page_actions.js b/content/page_actions.js index db7c352..845e452 100644 --- a/content/page_actions.js +++ b/content/page_actions.js @@ -12,19 +12,17 @@ * IMPORT CONNECTION_TYPE * IMPORT browser * IMPORT report_script - * IMPORT report_settings * IMPORT report_document_type * IMPORTS_END */ -let policy_received_callback; +let policy; /* Snapshot url and content type early; these can be changed by other code. */ let url; let is_html; let port; let loaded = false; let scripts_awaiting = []; -let nonce; function handle_message(message) { @@ -38,9 +36,8 @@ function handle_message(message) scripts_awaiting.push(script_text); } } - if (action === "settings") { - report_settings(data); - policy_received_callback({url, allow: data[1].allow}); + else { + console.error(`Bad page action '${action}'.`); } } @@ -61,27 +58,27 @@ function add_script(script_text) let script = document.createElement("script"); script.textContent = script_text; - script.setAttribute("nonce", nonce); + script.setAttribute("nonce", policy.nonce); script.haketilo_payload = true; document.body.appendChild(script); report_script(script_text); } -function handle_page_actions(script_nonce, policy_received_cb, - doc_ready_promise) { - policy_received_callback = policy_received_cb; +function handle_page_actions(_policy, doc_ready_promise) { + policy = _policy; + url = document.URL; is_html = document instanceof HTMLDocument; report_document_type(is_html); doc_ready_promise.then(document_ready); - port = browser.runtime.connect({name : CONNECTION_TYPE.PAGE_ACTIONS}); - port.onMessage.addListener(handle_message); - port.postMessage({url}); - - nonce = script_nonce; + if (policy.payload) { + port = browser.runtime.connect({name : CONNECTION_TYPE.PAGE_ACTIONS}); + port.onMessage.addListener(handle_message); + port.postMessage({payload: policy.payload}); + } } /* diff --git a/dummy b/dummy new file mode 100644 index 0000000..e69de29 diff --git a/html/display-panel.js b/html/display-panel.js index c078850..4fe0173 100644 --- a/html/display-panel.js +++ b/html/display-panel.js @@ -229,14 +229,14 @@ function handle_activity_report(message) const [type, data] = message; if (type === "settings") { - let [pattern, settings] = data; + const settings = data; blocked_span.textContent = settings.allow ? "no" : "yes"; - if (pattern) { + if (settings.pattern) { pattern_span.textContent = pattern; const settings_opener = - () => open_in_settings(TYPE_PREFIX.PAGE, pattern); + () => open_in_settings(TYPE_PREFIX.PAGE, settings.pattern); view_pattern_but.classList.remove("hide"); view_pattern_but.addEventListener("click", settings_opener); } else { @@ -244,11 +244,10 @@ function handle_activity_report(message) blocked_span.textContent = blocked_span.textContent + " (default)"; } - const components = settings.components; - if (components) { - payload_span.textContent = nice_name(...components); + if (settings.payload) { + payload_span.textContent = nice_name(...settings.payload); payload_buttons_div.classList.remove("hide"); - const settings_opener = () => open_in_settings(...components); + const settings_opener = () => open_in_settings(...settings.payload); view_payload_but.addEventListener("click", settings_opener); } else { payload_span.textContent = "none"; diff --git a/manifest.json b/manifest.json index b18ea3e..7b4cb26 100644 --- a/manifest.json +++ b/manifest.json @@ -44,8 +44,7 @@ "page": "html/options.html", "open_in_tab": true }_CHROMIUM_UPDATE_URL_, - "web_accessible_resources": [_CHROMIUM_KEY_ - ], + "web_accessible_resources": ["dummy"], "background": { "persistent": true, "scripts": [_BGSCRIPTS_] -- cgit v1.2.3 From 6106c789ee818fd18240fd3f99eead598406852f Mon Sep 17 00:00:00 2001 From: Wojtek Kosior Date: Tue, 30 Nov 2021 19:31:49 +0100 Subject: rewrite parts of build script in awk --- CHROMIUM_exports_init.js | 3 + MOZILLA_exports_init.js | 57 +++++++++++ build.sh | 257 +++++++++++------------------------------------ common/storage_light.js | 1 + compute_scripts.awk | 196 ++++++++++++++++++++++++++++++++++++ copyright | 3 +- process_html_file.sh | 2 +- shell_utils.sh | 25 ++--- upload_amo.sh | 25 +++-- write_makefile.sh | 4 +- 10 files changed, 343 insertions(+), 230 deletions(-) create mode 100644 CHROMIUM_exports_init.js create mode 100644 MOZILLA_exports_init.js create mode 100644 compute_scripts.awk (limited to 'common') diff --git a/CHROMIUM_exports_init.js b/CHROMIUM_exports_init.js new file mode 100644 index 0000000..d2ca065 --- /dev/null +++ b/CHROMIUM_exports_init.js @@ -0,0 +1,3 @@ +// SPDX-License-Identifier: CC0-1.0 + +window.killtheweb={is_chrome: true, browser: window.chrome}; diff --git a/MOZILLA_exports_init.js b/MOZILLA_exports_init.js new file mode 100644 index 0000000..0015f0c --- /dev/null +++ b/MOZILLA_exports_init.js @@ -0,0 +1,57 @@ +// SPDX-License-Identifier: GPL-3.0-or-later + +/** + * This file is part of Haketilo. + * + * Function: Data structure to query items by URL patterns. + * + * Copyright (C) 2021 Wojtek Kosior + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * As additional permission under GNU GPL version 3 section 7, you + * may distribute forms of that code without the copy of the GNU + * GPL normally required by section 4, provided you include this + * license notice and, in case of non-source distribution, a URL + * through which recipients can access the Corresponding Source. + * If you modify file(s) with this exception, you may extend this + * exception to your version of the file(s), but you are not + * obligated to do so. If you do not wish to do so, delete this + * exception statement from your version. + * + * As a special exception to the GPL, any HTML file which merely + * makes function calls to this code, and for that purpose + * includes it by reference shall be deemed a separate work for + * copyright law purposes. If you modify this code, you may extend + * this exception to your version of the code, but you are not + * obligated to do so. If you do not wish to do so, delete this + * exception statement from your version. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + * + * I, Wojtek Kosior, thereby promise not to sue for violation of this file's + * license. Although I request that you do not make use this code in a + * proprietary program, I am not going to enforce this in court. + */ + +/* Polyfill for IceCat 60. */ +String.prototype.matchAll = String.prototype.matchAll || function(regex) { + if (regex.flags.search("g") === -1) + throw new TypeError("String.prototype.matchAll called with a non-global RegExp argument"); + + for (const matches = [];;) { + if (matches[matches.push(regex.exec(this)) - 1] === null) + return matches.splice(0, matches.length - 1); + } +} + +window.killtheweb={is_mozilla: true, browser: this.browser}; diff --git a/build.sh b/build.sh index ed6a141..3d3d4be 100755 --- a/build.sh +++ b/build.sh @@ -3,180 +3,70 @@ # Copyright (C) 2021 Wojtek Kosior # Redistribution terms are gathered in the `copyright' file. -handle_export_line() { - if [ "x$1" = "xEXPORTS_START" ]; then - if [ "$STATE" = "before_block" ]; then - STATE="in_block" - fi - elif [ "x$1" = "xEXPORT" ]; then - if [ "$STATE" != "in_block" ]; then - return - fi - - EXPORTCODE="${EXPORTCODE}window.killtheweb.$2 = $2;$ENDL" - - PREVIOUS_FILE="$(map_get EXPORTS $2)" - if [ "x$PREVIOUS_FILE" != "x" ]; then - errcho "export $2 present in both $PREVIOUS_FILE and $FILE" - return 1 - fi - - map_set_instr EXPORTS $2 "$FILE" - - elif [ "x$1" = "xEXPORTS_END" ]; then - if [ "$STATE" = "in_block" ]; then - STATE="after_block" - fi - fi -} - -translate_exports() { - STATE="before_block" - EXPORTCODE='' - - while read EXPORT_LINE; do - handle_export_line $EXPORT_LINE || return 1 - done - - map_set_instr EXPORTCODES $FILEKEY "$EXPORTCODE" -} - -add_exports() { - FILE="$1" - FILEKEY="$(sanitize "$FILE")" - - eval "$(grep -o 'EXPORT.\+' "$1" | translate_exports || exit 1)" -} - -handle_import_line() { - if [ "x$1" = "xIMPORTS_START" ]; then - if [ "$STATE" = "before_block" ]; then - STATE="in_block" - fi - elif [ "x$1" = "xIMPORT" ]; then - if [ "$STATE" != "in_block" ]; then - return - fi - - IMPORTCODE="${IMPORTCODE}const $2 = window.killtheweb.$2;$ENDL" - - IMPORTS="$IMPORTS $2" - - elif [ "x$1" = "xIMPORTS_END" ]; then - if [ "$STATE" = "in_block" ]; then - STATE="after_block" - fi - fi -} - -translate_imports() { - STATE="before_block" - IMPORTCODE='' - IMPORTS='' - - while read IMPORT_LINE; do - handle_import_line $IMPORT_LINE || return 1 - done - - map_set_instr IMPORTCODES $FILEKEY "$IMPORTCODE" - map_set_instr IMPORTS $FILEKEY "$IMPORTS" -} - -add_imports() { - FILE="$1" - FILEKEY="$(sanitize "$FILE")" - - eval "$(grep -o 'IMPORT.\+' "$1" | translate_imports || exit 1)" -} +set -e -compute_scripts_list_rec() { - local FILE="$1" - local FILEKEY=$(sanitize "$1") - - local FILESTATE="$(map_get FILESTATES $FILEKEY)" - if [ "xprocessed" = "x$FILESTATE" ]; then - return - fi - if [ "xprocessing" = "x$FILESTATE" ]; then - errcho "import loop on $FILE" - return 1 - fi - - USED="$USED $FILEKEY" - - map_set FILESTATES $FILEKEY "processing" - - local IMPORT - for IMPORT in $(map_get IMPORTS $FILEKEY); do - NEXT_FILE="$(map_get EXPORTS $IMPORT)" - if [ "x" = "x$NEXT_FILE" ]; then - errcho "nothing exports $IMPORT, required by $FILE" - return 1 - fi - if ! compute_scripts_list_rec "$NEXT_FILE"; then - errcho "when satisfying $IMPORT for $FILE" - return 1 - fi - done - - [ "x$FILE" = "xexports_init.js" ] || echo $FILE # exports_init.js is hardcoded to load first; the entire export system depends on it - map_set FILESTATES $FILEKEY "processed" -} - -compute_scripts_list() { - USED='' - echo COMPUTED_SCRIPTS=\"exports_init.js - compute_scripts_list_rec "$1" - echo \" - - for FILEKEY in $USED; do - map_set_instr USED $FILEKEY yes - done -} +. ./shell_utils.sh as_json_list() { while true; do if [ "x" = "x$2" ]; then - echo -n '\\n'"\t\t\"$1\""'\\n\t' + printf '\\n\t\t"%s"\\n\t' "$1" return fi - echo -n '\\n'"\t\t\"$1\"," + printf '\\n\t\t"%s",' "$1" shift done } as_html_list() { while [ "x" != "x$1" ]; do - echo -n '\\n'" " + printf '\\n ' "$1" shift done } -build_main() { - # placate importers of these, as they are exported by the yet-to-be-created exports_init.js - EXPORTS__browser=exports_init.js - EXPORTS__is_chrome=exports_init.js - EXPORTS__is_mozilla=exports_init.js +compute_scripts() { + local DIRS="$1" + local ROOT_SCRIPT="$2" + + local AVAILABLE="$(find $DIRS -name '[^.#]*.js')" + + awk -f compute_scripts.awk script_dependencies "$ROOT_SCRIPT" $AVAILABLE +} - SCRIPTDIRS='background html common content' +build_main() { + local ALL_SCRIPTDIRS='background html common content' - SCRIPTS=$(find $SCRIPTDIRS -name '[^.#]*.js') + local ALL_SCRIPTS_AVAILABLE="$(find $ALL_SCRIPTDIRS -name '[^.#]*.js')" - for SCRIPT in $SCRIPTS; do - add_exports $SCRIPT - add_imports $SCRIPT + local SCRIPT + for SCRIPT in $ALL_SCRIPTS_AVAILABLE; do + map_set SCRIPTS_UNUSED $(sanitize $SCRIPT) yes done - eval "$(compute_scripts_list background/main.js || exit 1)" - BGSCRIPTS="$(as_json_list $COMPUTED_SCRIPTS)" - eval "$(compute_scripts_list content/main.js || exit 1)" - CONTENTSCRIPTS="$(as_json_list $COMPUTED_SCRIPTS)" - eval "$(compute_scripts_list html/display-panel.js || exit 1)" - POPUPSCRIPTS="$(as_html_list $COMPUTED_SCRIPTS)" - eval "$(compute_scripts_list html/options_main.js || exit 1)" - OPTIONSSCRIPTS="$(as_html_list $COMPUTED_SCRIPTS)" + local ROOT=background/main.js + local SCRIPTS_BG="$( compute_scripts 'common/ background/' $ROOT)" + + local ROOT=content/main.js + local SCRIPTS_CONTENT="$( compute_scripts 'common/ content/' $ROOT)" + + local ROOT=html/display-panel.js + local SCRIPTS_POPUP="$( compute_scripts 'common/ html/' $ROOT)" + + local ROOT=html/options_main.js + local SCRIPTS_OPTIONS="$( compute_scripts 'common/ html/' $ROOT)" - for DIR in $(find $SCRIPTDIRS -type d); do + local BGSCRIPTS="$( as_json_list $SCRIPTS_BG )" + local CONTENTSCRIPTS="$( as_json_list $SCRIPTS_CONTENT )" + local POPUPSCRIPTS="$( as_html_list $SCRIPTS_POPUP )" + local OPTIONSSCRIPTS="$( as_html_list $SCRIPTS_OPTIONS )" + + for SCRIPT in $SCRIPTS_BG $SCRIPTS_CONTENT $SCRIPTS_POPUP $SCRIPTS_OPTIONS + do + map_del SCRIPTS_UNUSED $(sanitize $SCRIPT) + done + + for DIR in $(find $ALL_SCRIPTDIRS -type d); do mkdir -p "$BUILDDIR"/$DIR done @@ -214,53 +104,24 @@ s^_CONTENTSCRIPTS_^$CONTENTSCRIPTS^" \ sed "s^_OPTIONSSCRIPTS_^$OPTIONSSCRIPTS^" \ > "$BUILDDIR"/html/options.html - for FILE in $SCRIPTS; do + for FILE in $ALL_SCRIPTS_AVAILABLE; do FILEKEY=$(sanitize "$FILE") - if [ "xyes" != "x$(map_get USED $FILEKEY)" ]; then - errcho "WARNING! $FILE not used" + if [ "x$(map_get SCRIPTS_UNUSED $FILEKEY)" = "xyes" ]; then + printf 'WARNING! %s not used\n' "$FILE" >&2 else - (echo "\ -\"use strict\"; - -({fun: (function() { -$(map_get IMPORTCODES $FILEKEY) - -"; - -# A hack to insert the contents of default_settings.json at the appropriate location in background/main.js -if [ "$FILE" = "background/main.js" ]; then - # Uses an internal sed expression to escape and indent the JSON file for use in the external sed expression - sed 's/^ `DEFAULT SETTINGS`$/'"$(sed -E 's/([\\\&\/])/\\\1/g; s/^/ /; s/$/\\/' < default_settings.json) "/g < "$FILE" -else - cat $FILE -fi - -echo " - -$(map_get EXPORTCODES $FILEKEY) -})}).fun();") > "$BUILDDIR"/$FILE + awk -f compute_scripts.awk wrapped_code "$FILE" > "$BUILDDIR"/$FILE fi done + # A hack to insert the contents of default_settings.json at the appropriate + # location in background/main.js. Uses an internal sed expression to escape + # and indent the JSON file for use in the external sed expression. + sed -i 's/^ `DEFAULT SETTINGS`$/'"$(sed -E 's/([\\\&\/])/\\\1/g; s/^/ /; s/$/\\/' < default_settings.json) "/g "$BUILDDIR"/background/main.js + if [ "$BROWSER" = "chromium" ]; then - cat > "$BUILDDIR"/exports_init.js < "$BUILDDIR"/exports_init.js < "$MOZILLA_FILE" + printf '\n' > "$MOZILLA_FILE" done fi if [ "$BROWSER" = "mozilla" ]; then for CHROMIUM_FILE in $(find "$BUILDDIR" -name "CHROMIUM_*"); do - echo > "$CHROMIUM_FILE" + printf '\n' > "$CHROMIUM_FILE" done fi } +print_usage() { + printf 'usage: %s mozilla|chromium [source directory] [update url]\n' \ + "$0" >&2 +} + main() { if [ "x$1" = "xmozilla" -o "x$1" = "xchromium" ]; then BROWSER=$1 else - errcho "usage: $0 mozilla|chromium [source directory] [update url]" + print_usage exit 1 fi @@ -296,13 +162,12 @@ main() { mkdir "$BUILDDIR" cd "$SRCDIR" else - errcho "usage: $0 mozilla|chromium [source directory] [update url]" + print_usage exit 2 fi UPDATE_URL="$3" - . ./shell_utils.sh build_main } diff --git a/common/storage_light.js b/common/storage_light.js index 32e3b1f..246e5eb 100644 --- a/common/storage_light.js +++ b/common/storage_light.js @@ -13,6 +13,7 @@ * IMPORT raw_storage * IMPORT is_mozilla * IMPORT observables + * IMPORTS_END */ const reg_spec = new Set(["\\", "[", "]", "(", ")", "{", "}", ".", "*", "+"]); diff --git a/compute_scripts.awk b/compute_scripts.awk new file mode 100644 index 0000000..123106c --- /dev/null +++ b/compute_scripts.awk @@ -0,0 +1,196 @@ +# SPDX-License-Identifier: CC0-1.0 +# +# Process javascript files and resolve dependencies between them +# +# This file is part of Haketilo +# +# Copyright (C) 2021, Wojtek Kosior +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the CC0 1.0 Universal License as published by +# the Creative Commons Corporation. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# CC0 1.0 Universal License for more details. + +function read_file(filename, + imports_state, exports_state, line, record, result) { + imports_state = "not_started" + exports_state = "not_started" + + do { + result = (getline line < filename) + if (result < 0) { + printf "error reading %s", filename + exit 1 + } + + if (imports_state == "started" && + line ~ /^([[:space:]]*\*[[:space:]]+)?IMPORT[[:space:]]+[_a-zA-Z][_a-zA-Z0-9]*[[:space:]]*$/) { + record = line + + sub(/^([[:space:]]*\*[[:space:]]+)?IMPORT[[:space:]]+/, "", record) + sub(/([[:space:]]+$)/, "", record) + + imports[filename,++import_counts[filename]] = record + } + if (imports_state == "started" && + line ~ /^([[:space:]]*\*[[:space:]]+)?IMPORTS_END[[:space:]]*$/) + imports_state = "finished" + if (imports_state == "not_started" && + line ~ /^([[:space:]]*\*[[:space:]]+)?IMPORTS_START[[:space:]]*$/) + imports_state = "started" + + if (exports_state == "started" && + line ~ /^([[:space:]]*\*[[:space:]]+)?EXPORT[[:space:]]+[_a-zA-Z][_a-zA-Z0-9]*[[:space:]]*$/) { + record = line + + sub(/^([[:space:]]*\*[[:space:]]+)?EXPORT[[:space:]]+/, "", record) + sub(/([[:space:]]+$)/, "", record) + + if (record in exports) { + printf "ERROR: '%s' exported by both %s and %s\n", + exports[record], filename > "/dev/stderr" + } + + provides[record] = filename + exports[filename,++export_counts[filename]] = record + } + if (exports_state == "started" && + line ~ /^([[:space:]]*\*[[:space:]]+)?EXPORTS_END[[:space:]]*$/) + exports_state = "finished" + if (exports_state == "not_started" && + line ~ /^([[:space:]]*\*[[:space:]]+)?EXPORTS_START[[:space:]]*$/) + exports_state = "started" + } while (result > 0) + + if (imports_state == "started") { + printf "ERROR: Unclosed IMPORTS list in '%s'\n", filename \ + > "/dev/stderr" + exit 1 + } + + if (exports_state == "started") { + printf "ERROR: Unclosed EXPORTS list in '%s'\n", filename \ + > "/dev/stderr" + exit 1 + } + + close(filename) +} + +function print_file(filename, line) { + while ((getline line < filename) > 0) + print(line) + + close(filename) +} + +function print_imports_code(filename, i, count, import_name) { + count = import_counts[filename] + for (i = 1; i <= count; i++) { + import_name = imports[filename,i] + printf "const %s = window.killtheweb.%s;\n", import_name, import_name + } +} + +function print_exports_code(filename, i, count, export_name) { + count = export_counts[filename] + for (i = 1; i <= count; i++) { + export_name = exports[filename,i] + printf "window.killtheweb.%s = %s;\n", export_name, export_name + } +} + +function wrap_file(filename) { + print "\"use strict\";\n\n({fun: (function() {\n" + print_imports_code(filename) + printf "\n\n" + + print_file(filename) + + printf "\n\n" + print_exports_code(filename) + print "\n})}).fun();" +} + +function compute_dependencies(filename, i, count, import_name, next_file) { + if (processed[filename] == "used") + return 0 + + if (processed[filename] == "on_stack") { + printf "import loop on %s\n", filename > "/dev/stderr" + return 1 + } + + processed[filename] = "on_stack" + + count = import_counts[filename] + for (i = 1; i <= count; i++) { + import_name = imports[filename,i] + if (!(import_name in provides)) { + printf "nothing exports %s, required by %s\n", + import_name, filename > "/dev/stderr" + return 1 + } + + if (compute_dependencies(provides[import_name]) > 0) { + printf "when satisfying %s for %s\n", + import_name, filename > "/dev/stderr" + return 1 + } + } + + processed[filename] = "used" + print filename + + return 0 +} + +function print_usage() { + printf "usage: %2 compute_scripts.awk script_dependencies|wrapped_code FILENAME[...]\n", + ARGV[0] > "/dev/stderr" + exit 1 +} + +function mock_exports_init() { + provides["browser"] = "exports_init.js" + provides["is_chrome"] = "exports_init.js" + provides["is_mozilla"] = "exports_init.js" + + processed["exports_init.js"] = "used" +} + +BEGIN { + operation = ARGV[1] + + if (ARGC < 3) + print_usage() + + root_filename = ARGV[2] + + for (i = 2; i < ARGC; i++) + filenames[ARGV[i]] + + mock_exports_init() + + for (filename in filenames) { + # A filename is allowed to appear multiple times in the list. + # Let's only process it once. + if (!(filename in processed)) + read_file(filename) + processed[filename] = "not_used" + } + + if (operation == "script_dependencies") { + print("exports_init.js") + if (compute_dependencies(root_filename) > 0) + exit 1 + } else if (operation == "wrapped_code") { + wrap_file(root_filename) + } else { + print_usage() + } +} diff --git a/copyright b/copyright index 81f9966..a238d33 100644 --- a/copyright +++ b/copyright @@ -6,7 +6,8 @@ Files: * Copyright: 2021 Wojtek Kosior License: GPL-3+-javascript or Alicense-1.0 -Files: *.sh default_settings.json Makefile.in +Files: *.sh default_settings.json Makefile.in compute_scripts.awk + CHROMIUM_exports_init.js Copyright: 2021 Wojtek Kosior 2021 jahoti License: CC0 diff --git a/process_html_file.sh b/process_html_file.sh index 1ed0295..2f58cbf 100755 --- a/process_html_file.sh +++ b/process_html_file.sh @@ -12,7 +12,7 @@ FILE="$1" FILEKEY=$(sanitize "$FILE") if [ "x$(map_get HTML_FILENAMES $FILEKEY)" = "xyes" ]; then - errcho "import loop on $FILE" + printf 'import loop on %s\n' "$FILE" >&2 exit 1 fi diff --git a/shell_utils.sh b/shell_utils.sh index 5fd24ff..6d4cc76 100644 --- a/shell_utils.sh +++ b/shell_utils.sh @@ -3,21 +3,8 @@ # This file is meant to be sourced in sh. -ENDL=" -" - -# A "raw" echo, interprets neither backclash escapes nor command-line options. -# Does not emit trailing newline. -ech() { - printf %s "$*" -} - -errcho() { - echo "$@" >&2 -} - map_set_instr() { - echo "$1__$2='$3'" + printf "%s__%s='%s'" "$1" "$2" "$3" } map_set() { @@ -29,11 +16,11 @@ map_set_export() { } map_get() { - eval "echo \"\$$1__$2\"" + eval "printf %s \"\$$1__$2\"" } map_del_instr() { - echo "unset $1__$2" + printf 'unset %s__%s' "$1" "$2" } map_del() { @@ -41,18 +28,18 @@ map_del() { } sanitize() { - echo "$1" | tr /.- _ + printf %s "$1" | tr /.- _ } escape_regex_special() { - ech "$1" | sed 's/\([]\.*?{},()[-]\)/\\\1/g' + printf %s "$1" | sed 's/\([]\.*?{},()[-]\)/\\\1/g' } # Note: We don't actually parse JSON. We extract needed keys with sed regexes # which does not work in the general case but is sufficient for now. get_json_key() { local KEY_REG="$(escape_regex_special "$1")" - ech "$2" | + printf %s "$2" | sed 's/\(.*"'"$KEY_REG"'"[[:space:]]*:[[:space:]]*"\([^"]*\)"\)\?.*/\2/' | grep . | head -1 } diff --git a/upload_amo.sh b/upload_amo.sh index 115f39a..71e12ca 100755 --- a/upload_amo.sh +++ b/upload_amo.sh @@ -24,11 +24,11 @@ SECRET="$3" XPI_PATH="$4" base64url() { - ech "$1" | base64 -w 0 | tr '/+' '_-' | tr -d '=' + printf %s "$1" | base64 -w 0 | tr '/+' '_-' | tr -d '=' } sha256hmac() { - base64url "$(ech "$2" | openssl dgst -sha256 -hmac "$1" -binary -)" + base64url "$(printf %s "$2" | openssl dgst -sha256 -hmac "$1" -binary -)" } get_manifest_key() { @@ -52,8 +52,8 @@ EOF local JWT_MESSAGE=$(base64url "$JWT_HEAD").$(base64url "$JWT_PAYLOAD") local JWT_SIGNATURE=$(sha256hmac "$SECRET" "$JWT_MESSAGE") local JWT=$JWT_MESSAGE.$JWT_SIGNATURE - errcho "Using JWT: $JWT" - ech $JWT + printf "Using JWT: $JWT\n" >&2 + printf $JWT } get_extension_url() { @@ -61,19 +61,22 @@ get_extension_url() { EXTENSION_VER="$(get_manifest_key version "$XPI_PATH")" if [ -z "$EXTENSION_ID" -o -z "$EXTENSION_VER" ]; then - errcho "Couldn't extract extension id and version. Please check if $XPI_PATH contains proper manifest.json file." + printf "Couldn't extract extension id and version. Please check if %s contains proper manifest.json file.\n" \ + "$XPI_PATH" >&2 exit 1 fi - ech "https://addons.mozilla.org/api/v4/addons/$EXTENSION_ID/versions/$EXTENSION_VER/" + printf 'https://addons.mozilla.org/api/v4/addons/%s/versions/%s/' \ + "$EXTENSION_ID" "$EXTENSION_VER" } -usage() { - errcho "Usage: $_PROG_NAME upload|check|test API_KEY SECRET XPI_PATH" +print_usage() { + printf 'Usage: %s upload|check|test API_KEY SECRET XPI_PATH\n' \ + "$_PROG_NAME" >&2 } if [ $# != 4 ]; then - usage + print_usage exit 1 fi @@ -83,7 +86,7 @@ case "$OPERATION" in test) curl "https://addons.mozilla.org/api/v4/accounts/profile/" \ -g -H "Authorization: JWT $(generate_jwt)" - echo + printf '\n' ;; check) RETURNED_DATA="$(curl $(get_extension_url) \ @@ -95,7 +98,7 @@ case "$OPERATION" in -H "Authorization: JWT $(generate_jwt)")" ;; *) - usage + print_usage exit 1 ;; esac diff --git a/write_makefile.sh b/write_makefile.sh index d5c0fa9..4011fe8 100755 --- a/write_makefile.sh +++ b/write_makefile.sh @@ -14,10 +14,10 @@ # CC0 1.0 Universal License for more details. if [ ! -e record.conf ]; then - echo "Record of configuration 'record.conf' does not exist." >&2 + printf "Record of configuration 'record.conf' does not exist.\n" >&2 exit 1 elif [ "$(head -n 1 record.conf | cut -c -9)x" != "srcdir = x" ]; then - echo "Record of configuration 'record.conf' is invalid." >&2 + printf "Record of configuration 'record.conf' is invalid.\n" >&2 exit 2 fi -- cgit v1.2.3 From 93dd73600e91eb19e11f5ca57f9429a85cf0150f Mon Sep 17 00:00:00 2001 From: Wojtek Kosior Date: Wed, 24 Nov 2021 15:53:00 +0100 Subject: improve unit testing approach Unit tests were moved to their own subdirectory. Fixtures common to many unit tests were moved to test/unit/conftest.py. A facility to execute scripts in page's global scope was added. A workaround was employed to present information about errors in injected scripts. Sample unit tests for regexes in common/patterns.js were added. --- common/patterns.js | 48 ++++++++++++-------- compute_scripts.awk | 14 ++++-- copyright | 5 ++- test/__init__.py | 1 + test/profiles.py | 5 +++ test/script_loader.py | 21 +++++---- test/test_unit.py | 57 ------------------------ test/unit/__init__.py | 2 + test/unit/conftest.py | 109 +++++++++++++++++++++++++++++++++++++++++++++ test/unit/test_basic.py | 41 +++++++++++++++++ test/unit/test_patterns.py | 91 +++++++++++++++++++++++++++++++++++++ 11 files changed, 305 insertions(+), 89 deletions(-) delete mode 100644 test/test_unit.py create mode 100644 test/unit/__init__.py create mode 100644 test/unit/conftest.py create mode 100644 test/unit/test_basic.py create mode 100644 test/unit/test_patterns.py (limited to 'common') diff --git a/common/patterns.js b/common/patterns.js index 625be05..635b128 100644 --- a/common/patterns.js +++ b/common/patterns.js @@ -7,15 +7,17 @@ * Redistribution terms are gathered in the `copyright' file. */ -const MAX_URL_PATH_LEN = 12; -const MAX_URL_PATH_CHARS = 255; -const MAX_DOMAIN_LEN = 7; -const MAX_DOMAIN_CHARS = 100; +const MAX = { + URL_PATH_LEN: 12, + URL_PATH_CHARS: 255, + DOMAIN_LEN: 7, + DOMAIN_CHARS: 100 +}; const proto_regex = /^(\w+):\/\/(.*)$/; const user_re = "[^/?#@]+@" -const domain_re = "[^/?#]+"; +const domain_re = "[.a-zA-Z0-9-]+"; const path_re = "[^?#]*"; const query_re = "\\??[^#]*"; @@ -25,11 +27,17 @@ const file_regex = new RegExp(`^(${path_re}).*`); const ftp_regex = new RegExp(`^(${user_re})?(${domain_re})(${path_re}).*`); -function deconstruct_url(url) +function deconstruct_url(url, use_limits=true) { + const max = MAX; + if (!use_limits) { + for (key in MAX) + max[key] = Infinity; + } + const proto_match = proto_regex.exec(url); if (proto_match === null) - return undefined; + throw `bad url '${url}'`; const deco = {proto: proto_match[1]}; @@ -37,20 +45,22 @@ function deconstruct_url(url) deco.path = file_regex.exec(proto_match[2])[1]; } else if (deco.proto === "ftp") { [deco.domain, deco.path] = ftp_regex.exec(proto_match[2]).slice(2, 4); - } else { + } else if (deco.proto === "http" || deco.proto === "https") { const http_match = http_regex.exec(proto_match[2]); if (!http_match) return undefined; [deco.domain, deco.path, deco.query] = http_match.slice(1, 4); + deco.domain = deco.domain.toLowerCase(); + } else { + throw `unsupported protocol in url '${url}'`; } - const leading_dash = deco.path[0] === "/"; deco.trailing_dash = deco.path[deco.path.length - 1] === "/"; if (deco.domain) { - if (deco.domain.length > MAX_DOMAIN_CHARS) { + if (deco.domain.length > max.DOMAIN_CHARS) { const idx = deco.domain.indexOf(".", deco.domain.length - - MAX_DOMAIN_CHARS); + max.DOMAIN_CHARS); if (idx === -1) deco.domain = []; else @@ -59,7 +69,7 @@ function deconstruct_url(url) deco.domain_truncated = true; } - if (deco.path.length > MAX_URL_PATH_CHARS) { + if (deco.path.length > max.URL_PATH_CHARS) { deco.path = deco.path.substring(0, deco.path.lastIndexOf("/")); deco.path_truncated = true; } @@ -67,16 +77,14 @@ function deconstruct_url(url) if (typeof deco.domain === "string") { deco.domain = deco.domain.split("."); - if (deco.domain.splice(0, deco.domain.length - MAX_DOMAIN_LEN).length + if (deco.domain.splice(0, deco.domain.length - max.DOMAIN_LEN).length > 0) deco.domain_truncated = true; } deco.path = deco.path.split("/").filter(s => s !== ""); - if (deco.domain && deco.path.splice(MAX_URL_PATH_LEN).length > 0) + if (deco.domain && deco.path.splice(max.URL_PATH_LEN).length > 0) deco.path_truncated = true; - if (leading_dash || deco.path.length === 0) - deco.path.unshift(""); return deco; } @@ -98,13 +106,14 @@ function* each_domain_pattern(deco) function* each_path_pattern(deco) { - for (let slice = deco.path.length; slice > 0; slice--) { - const path_part = deco.path.slice(0, slice).join("/"); + for (let slice = deco.path.length; slice >= 0; slice--) { + const path_part = ["", ...deco.path.slice(0, slice)].join("/"); const path_wildcards = []; if (slice === deco.path.length && !deco.path_truncated) { if (deco.trailing_dash) yield path_part + "/"; - yield path_part; + if (slice > 0 || deco.proto !== "file") + yield path_part; } if (slice === deco.path.length - 1 && !deco.path_truncated && deco.path[slice] !== "*") @@ -137,5 +146,6 @@ function* each_url_pattern(url) /* * EXPORTS_START * EXPORT each_url_pattern + * EXPORT deconstruct_url * EXPORTS_END */ diff --git a/compute_scripts.awk b/compute_scripts.awk index 2bad3c5..1f3b11e 100644 --- a/compute_scripts.awk +++ b/compute_scripts.awk @@ -105,8 +105,7 @@ function print_exports_code(filename, i, count, export_name) { } } -function wrap_file(filename) { - print "\"use strict\";\n\n({fun: (function() {\n" +function partially_wrap_file(filename) { print_imports_code(filename) printf "\n\n" @@ -114,6 +113,13 @@ function wrap_file(filename) { printf "\n\n" print_exports_code(filename) +} + +function wrap_file(filename) { + print "\"use strict\";\n\n({fun: (function() {\n" + + partially_wrap_file(filename) + print "\n})}).fun();" } @@ -151,7 +157,7 @@ function compute_dependencies(filename, i, count, import_name, next_file) { } function print_usage() { - printf "usage: %2 compute_scripts.awk script_dependencies|wrapped_code FILENAME[...]\n", + printf "usage: %2 compute_scripts.awk script_dependencies|wrapped_code|partially_wrapped_code FILENAME[...]\n", ARGV[0] > "/dev/stderr" exit 1 } @@ -189,6 +195,8 @@ BEGIN { print("exports_init.js") if (compute_dependencies(root_filename) > 0) exit 1 + } else if (operation == "partially_wrapped_code") { + partially_wrap_file(root_filename) } else if (operation == "wrapped_code") { wrap_file(root_filename) } else { diff --git a/copyright b/copyright index c7934b7..243b4a1 100644 --- a/copyright +++ b/copyright @@ -75,11 +75,12 @@ License: AGPL-3+ Comment: Wojtek Kosior promises not to sue even in case of violations of the license. -Files: test/__init__.py test/test_unit.py test/default_profiles/icecat_empty/extensions.json +Files: test/__init__.py test/unit/* + test/default_profiles/icecat_empty/extensions.json Copyright: 2021 Wojtek Kosior License: CC0 -Files: test/profiles.py test/script_loader.py +Files: test/profiles.py test/script_loader.py test/unit/conftest.py Copyright: 2021 Wojtek Kosior License: GPL-3+ Comment: Wojtek Kosior promises not to sue even in case of violations diff --git a/test/__init__.py b/test/__init__.py index 19b869e..2b351bb 100644 --- a/test/__init__.py +++ b/test/__init__.py @@ -1 +1,2 @@ # SPDX-License-Identifier: CC0-1.0 +# Copyright (C) 2021 Wojtek Kosior diff --git a/test/profiles.py b/test/profiles.py index a833097..d6a4efc 100755 --- a/test/profiles.py +++ b/test/profiles.py @@ -43,11 +43,15 @@ def set_profile_proxy(profile, proxy_host, proxy_port): profile.set_preference(f'network.proxy.backup.{proto}', '') profile.set_preference(f'network.proxy.backup.{proto}_port', 0) +def set_profile_console_logging(profile): + profile.set_preference('devtools.console.stdout.content', True) + def firefox_safe_mode(firefox_binary=default_firefox_binary, proxy_host=default_proxy_host, proxy_port=default_proxy_port): profile = webdriver.FirefoxProfile() set_profile_proxy(profile, proxy_host, proxy_port) + set_profile_console_logging(profile) options = Options() options.add_argument('--safe-mode') @@ -61,6 +65,7 @@ def firefox_with_profile(firefox_binary=default_firefox_binary, proxy_port=default_proxy_port): profile = webdriver.FirefoxProfile(profile_dir) set_profile_proxy(profile, proxy_host, proxy_port) + set_profile_console_logging(profile) return webdriver.Firefox(firefox_profile=profile, firefox_binary=firefox_binary) diff --git a/test/script_loader.py b/test/script_loader.py index 22196c3..15269c7 100644 --- a/test/script_loader.py +++ b/test/script_loader.py @@ -49,14 +49,15 @@ def available_scripts(directory): if script_name_regex.match(script.name): yield script -def get_wrapped_script(script_path): +def wrapped_script(script_path, wrap_partially=True): if script_path == 'exports_init.js': with open(script_root / 'MOZILLA_exports_init.js') as script: return script.read() - awk = subprocess.run(['awk', '-f', str(awk_script), 'wrapped_code', - str(script_path)], - stdout=subprocess.PIPE, cwd=script_root, check=True) + command = 'partially_wrapped_code' if wrap_partially else 'wrapped_code' + awk_command = ['awk', '-f', str(awk_script), command, str(script_path)] + awk = subprocess.run(awk_command, stdout=subprocess.PIPE, cwd=script_root, + check=True) return awk.stdout.decode() @@ -67,8 +68,10 @@ def load_script(path, import_dirs): project directory. Return a string containing script from `path` together with all other - scripts it depends on, wrapped in the same way Haketilo's build system wraps - them, with imports properly satisfied. + scripts it depends. Dependencies are wrapped in the same way Haketilo's + build system wraps them, with imports properly satisfied. The main script + being loaded is wrapped partially - it also has its imports satisfied, but + its code is not placed inside an anonymous function, so the """ path = make_relative_path(path) @@ -79,6 +82,8 @@ def load_script(path, import_dirs): str(path), *[str(s) for s in available]], stdout=subprocess.PIPE, cwd=script_root, check=True) - output = awk.stdout.decode() + to_load = awk.stdout.decode().split() + texts = [wrapped_script(path, wrap_partially=(i == len(to_load) - 1)) + for i, path in enumerate(to_load)] - return '\n'.join([get_wrapped_script(path) for path in output.split()]) + return '\n'.join(texts) diff --git a/test/test_unit.py b/test/test_unit.py deleted file mode 100644 index ce46f88..0000000 --- a/test/test_unit.py +++ /dev/null @@ -1,57 +0,0 @@ -# SPDX-License-Identifier: CC0-1.0 - -""" -Haketilo unit tests -""" - -# This file is part of Haketilo -# -# Copyright (C) 2021, jahoti -# Copyright (C) 2021, Wojtek Kosior -# -# This program is free software: you can redistribute it and/or modify -# it under the terms of the CC0 1.0 Universal License as published by -# the Creative Commons Corporation. -# -# This program is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# CC0 1.0 Universal License for more details. - -import pytest -from .profiles import firefox_safe_mode -from .server import do_an_internet -from .script_loader import load_script - -@pytest.fixture(scope="module") -def proxy(): - httpd = do_an_internet() - yield httpd - httpd.shutdown() - -@pytest.fixture(scope="module") -def driver(proxy): - with firefox_safe_mode() as driver: - yield driver - driver.quit() - -def test_proxy(driver): - """ - A trivial test case that verifies mocked web pages served by proxy can be - accessed by the browser driven. - """ - for proto in ['http://', 'https://']: - driver.get(proto + 'gotmyowndoma.in') - element = driver.find_element_by_tag_name('title') - title = driver.execute_script('return arguments[0].innerText;', element) - assert "Schrodinger's Document" in title - -def test_script_loader(driver): - """ - A trivial test case that verifies Haketilo's .js files can be properly - loaded into a test page together with their dependencies. - """ - driver.get('http://gotmyowndoma.in') - driver.execute_script(load_script('common/stored_types.js', ['common'])) - get_var_prefix = 'return window.haketilo_exports.TYPE_PREFIX.VAR;' - assert driver.execute_script(get_var_prefix) == '_' diff --git a/test/unit/__init__.py b/test/unit/__init__.py new file mode 100644 index 0000000..2b351bb --- /dev/null +++ b/test/unit/__init__.py @@ -0,0 +1,2 @@ +# SPDX-License-Identifier: CC0-1.0 +# Copyright (C) 2021 Wojtek Kosior diff --git a/test/unit/conftest.py b/test/unit/conftest.py new file mode 100644 index 0000000..6877b7a --- /dev/null +++ b/test/unit/conftest.py @@ -0,0 +1,109 @@ +# SPDX-License-Identifier: GPL-3.0-or-later + +""" +Common fixtures for Haketilo unit tests +""" + +# This file is part of Haketilo. +# +# Copyright (C) 2021 Wojtek Kosior +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program. If not, see . +# +# I, Wojtek Kosior, thereby promise not to sue for violation of this file's +# license. Although I request that you do not make use this code in a +# proprietary program, I am not going to enforce this in court. + +import pytest + +from ..profiles import firefox_safe_mode +from ..server import do_an_internet +from ..script_loader import load_script + +@pytest.fixture(scope="package") +def proxy(): + httpd = do_an_internet() + yield httpd + httpd.shutdown() + +@pytest.fixture(scope="package") +def driver(proxy): + with firefox_safe_mode() as driver: + yield driver + driver.quit() + +script_injecting_script = '''\ +/* + * Selenium by default executes scripts in some weird one-time context. We want + * separately-loaded scripts to be able to access global variables defined + * before, including those declared with `const` or `let`. To achieve that, we + * run our scripts by injecting them into the page inside a