@freedomofpress/webcat 0.0.0-stage → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/Readme.md +45 -0
  2. package/data/block.json +101 -0
  3. package/data/list.json +80 -0
  4. package/dist/hooks/content.js +1 -0
  5. package/dist/lib/browser/chrome.d.ts +86 -0
  6. package/dist/lib/browser/chrome.js +138 -0
  7. package/dist/lib/browser/kvstore.d.ts +70 -0
  8. package/dist/lib/browser/kvstore.js +241 -0
  9. package/dist/lib/browser/permissions.d.ts +113 -0
  10. package/dist/lib/browser/permissions.js +182 -0
  11. package/dist/lib/browser/requests.d.ts +145 -0
  12. package/dist/lib/browser/requests.js +292 -0
  13. package/dist/lib/browser/scripting.d.ts +19 -0
  14. package/dist/lib/browser/scripting.js +92 -0
  15. package/dist/lib/browser/sync.d.ts +68 -0
  16. package/dist/lib/browser/sync.js +114 -0
  17. package/dist/lib/browser/utils.d.ts +5 -0
  18. package/dist/lib/browser/utils.js +11 -0
  19. package/dist/lib/config.d.ts +45 -0
  20. package/dist/lib/config.js +45 -0
  21. package/dist/lib/validator_set.d.ts +4 -0
  22. package/dist/lib/validator_set.js +20 -0
  23. package/dist/lib/webcat/cache.d.ts +200 -0
  24. package/dist/lib/webcat/cache.js +308 -0
  25. package/dist/lib/webcat/canonicalize.d.ts +1 -0
  26. package/dist/lib/webcat/canonicalize.js +58 -0
  27. package/dist/lib/webcat/db.d.ts +30 -0
  28. package/dist/lib/webcat/db.js +131 -0
  29. package/dist/lib/webcat/encoding.d.ts +8 -0
  30. package/dist/lib/webcat/encoding.js +57 -0
  31. package/dist/lib/webcat/handler.d.ts +26 -0
  32. package/dist/lib/webcat/handler.js +419 -0
  33. package/dist/lib/webcat/hookbuilder.d.ts +47 -0
  34. package/dist/lib/webcat/hookbuilder.js +170 -0
  35. package/dist/lib/webcat/interfaces/bundle.d.ts +46 -0
  36. package/dist/lib/webcat/interfaces/bundle.js +8 -0
  37. package/dist/lib/webcat/interfaces/database.d.ts +68 -0
  38. package/dist/lib/webcat/interfaces/database.js +1 -0
  39. package/dist/lib/webcat/interfaces/errors.d.ts +451 -0
  40. package/dist/lib/webcat/interfaces/errors.js +109 -0
  41. package/dist/lib/webcat/interfaces/log.d.ts +14 -0
  42. package/dist/lib/webcat/interfaces/log.js +10 -0
  43. package/dist/lib/webcat/interfaces/originstate.d.ts +40 -0
  44. package/dist/lib/webcat/interfaces/originstate.js +1 -0
  45. package/dist/lib/webcat/interfaces/requeststate.d.ts +10 -0
  46. package/dist/lib/webcat/interfaces/requeststate.js +1 -0
  47. package/dist/lib/webcat/logger.d.ts +64 -0
  48. package/dist/lib/webcat/logger.js +112 -0
  49. package/dist/lib/webcat/originstate.d.ts +45 -0
  50. package/dist/lib/webcat/originstate.js +302 -0
  51. package/dist/lib/webcat/parsers.d.ts +21 -0
  52. package/dist/lib/webcat/parsers.js +36 -0
  53. package/dist/lib/webcat/request.d.ts +11 -0
  54. package/dist/lib/webcat/request.js +78 -0
  55. package/dist/lib/webcat/resources.d.ts +3 -0
  56. package/dist/lib/webcat/resources.js +41 -0
  57. package/dist/lib/webcat/response.d.ts +39 -0
  58. package/dist/lib/webcat/response.js +394 -0
  59. package/dist/lib/webcat/ui.d.ts +70 -0
  60. package/dist/lib/webcat/ui.js +282 -0
  61. package/dist/lib/webcat/updater.d.ts +115 -0
  62. package/dist/lib/webcat/updater.js +296 -0
  63. package/dist/lib/webcat/utils.d.ts +8 -0
  64. package/dist/lib/webcat/utils.js +74 -0
  65. package/dist/lib/webcat/validators.d.ts +16 -0
  66. package/dist/lib/webcat/validators.js +457 -0
  67. package/dist/lib/webcat.d.ts +11 -0
  68. package/dist/lib/webcat.js +130 -0
  69. package/icons/dark/webcat-error.SVG +1 -0
  70. package/icons/dark/webcat-ok.SVG +1 -0
  71. package/icons/dark/webcat.SVG +1 -0
  72. package/icons/light/webcat-error.SVG +1 -0
  73. package/icons/light/webcat-ok.SVG +1 -0
  74. package/icons/light/webcat.SVG +1 -0
  75. package/package.json +72 -4
  76. package/pages/error.css +9 -0
  77. package/pages/error.html +70 -0
  78. package/pages/error.js +51 -0
  79. package/pages/popup.css +16 -0
  80. package/pages/popup.html +14 -0
  81. package/pages/popup.js +48 -0
  82. package/README.md +0 -3
@@ -0,0 +1,131 @@
1
+ import { NamespacedKVStore } from "../browser/kvstore.js";
2
+ import permissions from "../browser/permissions.js";
3
+ import { PersistentLRUCache, LRUSet, CacheKey } from "./cache.js";
4
+ import { OriginState } from "./originstate.js";
5
+ import { extractHostname, extractRawHash } from "./parsers.js";
6
+ import "../browser/sync.js";
7
+ import "./canonicalize.js";
8
+ import "./encoding.js";
9
+ import "./interfaces/bundle.js";
10
+ import "./interfaces/errors.js";
11
+ import "./utils.js";
12
+ import "./validators.js";
13
+ import "@freedomofpress/sigstore-browser";
14
+ import "@freedomofpress/sigsum";
15
+ import "@freedomofpress/sigsum/dist/compiledPolicy";
16
+ import "@freedomofpress/sigsum/dist/crypto";
17
+ import "@freedomofpress/sigsum/dist/proof";
18
+ import "@freedomofpress/sigsum/dist/types";
19
+ var __create = Object.create;
20
+ var __defProp = Object.defineProperty;
21
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
22
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
23
+ var __typeError = (msg) => {
24
+ throw TypeError(msg);
25
+ };
26
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
27
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
28
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol("metadata")] ?? null)];
29
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
30
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError("Function expected") : fn;
31
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError("Already initialized") : fns.push(__expectFn(fn || null)) });
32
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol("metadata"), array[3]);
33
+ var __runInitializers = (array, flags, self, value) => {
34
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) fns[i].call(self);
35
+ return value;
36
+ };
37
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
38
+ var it, done, ctx, k = flags & 7, p = false;
39
+ var j = 0;
40
+ var extraInitializers = array[j] || (array[j] = []);
41
+ var desc = k && (target = target.prototype, k < 5 && (k > 3 || !p) && __getOwnPropDesc(target, name));
42
+ __name(target, name);
43
+ for (var i = decorators.length - 1; i >= 0; i--) {
44
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
45
+ it = (0, decorators[i])(target, ctx), done._ = 1;
46
+ __expectFn(it) && (target = it);
47
+ }
48
+ return __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
49
+ };
50
+ var _WebcatDatabase_decorators, _init, _a;
51
+ const META_KEY = "block_meta";
52
+ _WebcatDatabase_decorators = [permissions.require("unlimitedStorage")];
53
+ class WebcatDatabase extends (_a = NamespacedKVStore) {
54
+ constructor(config) {
55
+ super(config.namespace);
56
+ this.origins = void 0;
57
+ this.nonOrigins = void 0;
58
+ this.enrollments = this.namespace("enrollments");
59
+ this.origins = new PersistentLRUCache(
60
+ config.originCacheSize,
61
+ this.namespace("origins"),
62
+ "session",
63
+ OriginState
64
+ );
65
+ this.nonOrigins = new LRUSet(config.nonOriginCacheSize);
66
+ }
67
+ async updateList(leaves, meta) {
68
+ const batch = {};
69
+ for (const [reverseKey, hexHash] of leaves) {
70
+ const hostname = extractHostname(reverseKey);
71
+ const rawHash = extractRawHash(hexHash);
72
+ batch[hostname] = Array.from(rawHash);
73
+ }
74
+ const old = await this.enrollments.getKeys();
75
+ const disenrolled = old.filter((enrollment) => !(enrollment in batch));
76
+ for (const host of disenrolled) {
77
+ await this.enrollments.remove(host);
78
+ }
79
+ await this.enrollments.set(batch);
80
+ await this.set({ [META_KEY]: meta });
81
+ await this.origins.clear();
82
+ await this.nonOrigins.clear();
83
+ console.log(`[webcat] Replaced list with ${leaves.length} entries`);
84
+ }
85
+ async getBlockMeta() {
86
+ return await this.get(META_KEY) ?? null;
87
+ }
88
+ async listAllFQDNs() {
89
+ return await this.enrollments.getKeys();
90
+ }
91
+ async getFQDNEnrollment(fqdn, cachePartition) {
92
+ const originState = await this.origins.get(CacheKey(fqdn, cachePartition));
93
+ if (originState) {
94
+ const cached = originState.enrollment_hash;
95
+ if (!cached) {
96
+ throw new Error(
97
+ "FATAL: cached origin exists without an enrollment_hash"
98
+ );
99
+ }
100
+ return cached;
101
+ }
102
+ if (await this.nonOrigins.has(CacheKey(fqdn, cachePartition))) {
103
+ return new Uint8Array();
104
+ }
105
+ const stored = await this.enrollments.get(fqdn);
106
+ if (stored) {
107
+ return new Uint8Array(stored);
108
+ } else {
109
+ await this.nonOrigins.add(CacheKey(fqdn, cachePartition));
110
+ return new Uint8Array();
111
+ }
112
+ }
113
+ async setLastChecked() {
114
+ await this.set({ lastChecked: Date.now() }, "session");
115
+ }
116
+ async getLastChecked() {
117
+ return await this.get("lastChecked", "session") ?? null;
118
+ }
119
+ async setLastUpdated() {
120
+ await this.set({ lastUpdated: Date.now() }, "session");
121
+ }
122
+ async getLastUpdated() {
123
+ return await this.get("lastUpdated", "session") ?? null;
124
+ }
125
+ }
126
+ _init = __decoratorStart(_a);
127
+ WebcatDatabase = __decorateElement(_init, 0, "WebcatDatabase", _WebcatDatabase_decorators, WebcatDatabase);
128
+ __runInitializers(_init, 1, WebcatDatabase);
129
+ export {
130
+ WebcatDatabase
131
+ };
@@ -0,0 +1,8 @@
1
+ export declare function base64ToUint8Array(base64: string): Uint8Array;
2
+ export declare function Uint8ArrayToBase64(uint8Array: Uint8Array): string;
3
+ export declare function stringToUint8Array(str: string): Uint8Array<ArrayBuffer>;
4
+ export declare function Uint8ArrayToString(uint8Array: Uint8Array): string;
5
+ export declare function base64UrlToUint8Array(base64url: string): Uint8Array;
6
+ export declare function Uint8ArrayToBase64Url(uint8Array: Uint8Array): string;
7
+ export declare function hexToUint8Array(hex: string): Uint8Array;
8
+ export declare function Uint8ArrayToHex(uint8Array: Uint8Array): string;
@@ -0,0 +1,57 @@
1
+ function base64ToUint8Array(base64) {
2
+ const binaryString = atob(base64);
3
+ const length = binaryString.length;
4
+ const bytes = new Uint8Array(length);
5
+ for (let i = 0; i < length; i++) {
6
+ bytes[i] = binaryString.charCodeAt(i);
7
+ }
8
+ return bytes;
9
+ }
10
+ function Uint8ArrayToBase64(uint8Array) {
11
+ let binaryString = "";
12
+ for (let i = 0; i < uint8Array.length; i++) {
13
+ binaryString += String.fromCharCode(uint8Array[i]);
14
+ }
15
+ return btoa(binaryString);
16
+ }
17
+ function stringToUint8Array(str) {
18
+ const encoder = new TextEncoder();
19
+ return encoder.encode(str);
20
+ }
21
+ function Uint8ArrayToString(uint8Array) {
22
+ const decoder = new TextDecoder("ascii");
23
+ return decoder.decode(uint8Array);
24
+ }
25
+ function base64UrlToUint8Array(base64url) {
26
+ const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/").padEnd(base64url.length + (4 - base64url.length % 4) % 4, "=");
27
+ return base64ToUint8Array(base64);
28
+ }
29
+ function Uint8ArrayToBase64Url(uint8Array) {
30
+ return Uint8ArrayToBase64(uint8Array).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
31
+ }
32
+ function hexToUint8Array(hex) {
33
+ if (!/^[0-9a-fA-F]*$/.test(hex)) {
34
+ throw new Error("Hex string contains invalid characters");
35
+ }
36
+ if (hex.length % 2 !== 0) {
37
+ throw new Error("Hex string must have an even length");
38
+ }
39
+ const uint8Array = new Uint8Array(hex.length / 2);
40
+ for (let i = 0; i < uint8Array.length; i++) {
41
+ uint8Array[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
42
+ }
43
+ return uint8Array;
44
+ }
45
+ function Uint8ArrayToHex(uint8Array) {
46
+ return Array.from(uint8Array).map((b) => b.toString(16).padStart(2, "0")).join("");
47
+ }
48
+ export {
49
+ Uint8ArrayToBase64,
50
+ Uint8ArrayToBase64Url,
51
+ Uint8ArrayToHex,
52
+ Uint8ArrayToString,
53
+ base64ToUint8Array,
54
+ base64UrlToUint8Array,
55
+ hexToUint8Array,
56
+ stringToUint8Array
57
+ };
@@ -0,0 +1,26 @@
1
+ import { NamespacedKVStore } from "../browser/kvstore";
2
+ import { BeforeRequestDetails, RequestEvent, RequestHandler } from "../browser/requests";
3
+ import { HookBuilderConfig } from "./hookbuilder";
4
+ import { Database } from "./interfaces/database";
5
+ import { BundleFetcherConfig } from "./originstate";
6
+ import { WebcatUI } from "./ui";
7
+ export interface WebcatRequestHandler extends RequestHandler {
8
+ addEventListener: RequestHandler["addEventListener"] & ((type: "beforeframeload", callback: (event: RequestEvent<BeforeRequestDetails>) => void) => void);
9
+ }
10
+ export declare class WebcatRequestHandler extends RequestHandler {
11
+ #private;
12
+ constructor(db: Database & NamespacedKVStore, ui: WebcatUI, config: BundleFetcherConfig & HookBuilderConfig);
13
+ bind(fqdns: string[]): Promise<void>;
14
+ /**
15
+ * Binds the handler to `<all_urls>`. Unlike {@link bind}, does not bind
16
+ * content scripts. The bindAll method can be called synchronously before
17
+ * FQDNs are available, but it should be always followed by a call to
18
+ * {@link bind} to both restrict the scope of the binding and bind content
19
+ * scripts.
20
+ */
21
+ bindAll(): void;
22
+ protected getListenerOptions(fqdns: string[], type: "beforerequest"): [browser.webRequest.RequestFilter, browser.webRequest.OnBeforeRequestOptions[]];
23
+ protected getListenerOptions(fqdns: string[], type: "beforeheaders"): [browser.webRequest.RequestFilter, browser.webRequest.OnBeforeSendHeadersOptions[]];
24
+ protected getListenerOptions(fqdns: string[], type: "headersreceived"): [browser.webRequest.RequestFilter, browser.webRequest.OnHeadersReceivedOptions[]];
25
+ protected getListenerOptions(fqdns: string[], type: "erroroccurred" | "completed"): [browser.webRequest.RequestFilter];
26
+ }
@@ -0,0 +1,419 @@
1
+ var __knownSymbol = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
2
+ var __typeError = (msg) => {
3
+ throw TypeError(msg);
4
+ };
5
+ var __accessCheck = (obj, member, msg) => member.has(obj) || __typeError("Cannot " + msg);
6
+ var __privateGet = (obj, member, getter) => (__accessCheck(obj, member, "read from private field"), getter ? getter.call(obj) : member.get(obj));
7
+ var __privateAdd = (obj, member, value) => member.has(obj) ? __typeError("Cannot add the same private member more than once") : member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
8
+ var __privateSet = (obj, member, value, setter) => (__accessCheck(obj, member, "write to private field"), setter ? setter.call(obj, value) : member.set(obj, value), value);
9
+ var __privateMethod = (obj, member, method) => (__accessCheck(obj, member, "access private method"), method);
10
+ var __using = (stack, value, async) => {
11
+ if (value != null) {
12
+ if (typeof value !== "object" && typeof value !== "function") __typeError("Object expected");
13
+ var dispose, inner;
14
+ if (async) dispose = value[__knownSymbol("asyncDispose")];
15
+ if (dispose === void 0) {
16
+ dispose = value[__knownSymbol("dispose")];
17
+ if (async) inner = dispose;
18
+ }
19
+ if (typeof dispose !== "function") __typeError("Object not disposable");
20
+ if (inner) dispose = function() {
21
+ try {
22
+ inner.call(this);
23
+ } catch (e) {
24
+ return Promise.reject(e);
25
+ }
26
+ };
27
+ stack.push([async, dispose, value]);
28
+ } else if (async) {
29
+ stack.push([async]);
30
+ }
31
+ return value;
32
+ };
33
+ var __callDispose = (stack, error, hasError) => {
34
+ var E = typeof SuppressedError === "function" ? SuppressedError : function(e, s, m, _) {
35
+ return _ = Error(m), _.name = "SuppressedError", _.error = e, _.suppressed = s, _;
36
+ };
37
+ var fail = (e) => error = hasError ? new E(e, error, "An error was suppressed during disposal") : (hasError = true, e);
38
+ var next = (it) => {
39
+ while (it = stack.pop()) {
40
+ try {
41
+ var result = it[1] && it[1].call(it[2]);
42
+ if (it[0]) return Promise.resolve(result).then(next, (e) => (fail(e), next()));
43
+ } catch (e) {
44
+ fail(e);
45
+ }
46
+ }
47
+ if (hasError) throw error;
48
+ };
49
+ return next();
50
+ };
51
+ var _db, _ui, _config, _hooks, _contentScript, _responseValidator, _mutex, _requestLock, _bindLock, _WebcatRequestHandler_instances, initializeState_fn, onRequest_fn, onHeaders_fn, commitVerifiedOrigin_fn, getFirstParty_fn, onWindowClosed_fn;
52
+ import permissions from "../browser/permissions.js";
53
+ import { RequestHandler, RequestEvent } from "../browser/requests.js";
54
+ import { ContentScript } from "../browser/scripting.js";
55
+ import { Mutex } from "../browser/sync.js";
56
+ import { CacheKey, isInPartition } from "./cache.js";
57
+ import { HookBuilder } from "./hookbuilder.js";
58
+ import { WebcatError } from "./interfaces/errors.js";
59
+ import { logger } from "./logger.js";
60
+ import { validateOrigin } from "./request.js";
61
+ import { FRAME_TYPES } from "./resources.js";
62
+ import { ResponseValidator } from "./response.js";
63
+ import { clearBrowserCaches, getFQDN, isExtensionRequest, isSameOriginURL, isNewerSemver } from "./utils.js";
64
+ import "../browser/utils.js";
65
+ import "./originstate.js";
66
+ import "./canonicalize.js";
67
+ import "./encoding.js";
68
+ import "./interfaces/bundle.js";
69
+ import "./validators.js";
70
+ import "@freedomofpress/sigstore-browser";
71
+ import "@freedomofpress/sigsum";
72
+ import "@freedomofpress/sigsum/dist/compiledPolicy";
73
+ import "@freedomofpress/sigsum/dist/crypto";
74
+ import "@freedomofpress/sigsum/dist/proof";
75
+ import "@freedomofpress/sigsum/dist/types";
76
+ import "./parsers.js";
77
+ var __create = Object.create;
78
+ var __defProp = Object.defineProperty;
79
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
80
+ var __knownSymbol2 = (name, symbol) => (symbol = Symbol[name]) ? symbol : Symbol.for("Symbol." + name);
81
+ var __typeError2 = (msg) => {
82
+ throw TypeError(msg);
83
+ };
84
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
85
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
86
+ var __decoratorStart = (base) => [, , , __create(base?.[__knownSymbol2("metadata")] ?? null)];
87
+ var __decoratorStrings = ["class", "method", "getter", "setter", "accessor", "field", "value", "get", "set"];
88
+ var __expectFn = (fn) => fn !== void 0 && typeof fn !== "function" ? __typeError2("Function expected") : fn;
89
+ var __decoratorContext = (kind, name, done, metadata, fns) => ({ kind: __decoratorStrings[kind], name, metadata, addInitializer: (fn) => done._ ? __typeError2("Already initialized") : fns.push(__expectFn(fn || null)) });
90
+ var __decoratorMetadata = (array, target) => __defNormalProp(target, __knownSymbol2("metadata"), array[3]);
91
+ var __runInitializers = (array, flags, self, value) => {
92
+ for (var i = 0, fns = array[flags >> 1], n = fns && fns.length; i < n; i++) fns[i].call(self);
93
+ return value;
94
+ };
95
+ var __decorateElement = (array, flags, name, decorators, target, extra) => {
96
+ var it, done, ctx, k = flags & 7, p = false;
97
+ var j = 0;
98
+ var extraInitializers = array[j] || (array[j] = []);
99
+ var desc = k && (target = target.prototype, k < 5 && (k > 3 || !p) && __getOwnPropDesc(target, name));
100
+ __name(target, name);
101
+ for (var i = decorators.length - 1; i >= 0; i--) {
102
+ ctx = __decoratorContext(k, name, done = {}, array[3], extraInitializers);
103
+ it = (0, decorators[i])(target, ctx), done._ = 1;
104
+ __expectFn(it) && (target = it);
105
+ }
106
+ return __decoratorMetadata(array, target), desc && __defProp(target, name, desc), p ? k ^ 4 ? extra : desc : target;
107
+ };
108
+ var _WebcatRequestHandler_decorators, _init, _a;
109
+ _WebcatRequestHandler_decorators = [permissions.require("scripting"), permissions.require("webNavigation"), permissions.require("<all_urls>")];
110
+ class WebcatRequestHandler extends (_a = RequestHandler) {
111
+ constructor(db, ui, config) {
112
+ super();
113
+ __privateAdd(this, _WebcatRequestHandler_instances);
114
+ __privateAdd(this, _db);
115
+ __privateAdd(this, _ui);
116
+ __privateAdd(this, _config);
117
+ __privateAdd(this, _hooks);
118
+ __privateAdd(this, _contentScript);
119
+ __privateAdd(this, _responseValidator);
120
+ __privateAdd(this, _mutex, new Mutex());
121
+ __privateAdd(this, _requestLock, __privateGet(this, _mutex).createLock());
122
+ __privateAdd(this, _bindLock, __privateGet(this, _mutex).createLock());
123
+ __privateSet(this, _db, db);
124
+ __privateSet(this, _ui, ui);
125
+ __privateSet(this, _config, config);
126
+ __privateSet(this, _hooks, new HookBuilder(db.namespace("hooks"), config));
127
+ __privateSet(this, _contentScript, new ContentScript(__privateGet(this, _hooks).getStaticHookPath()));
128
+ __privateSet(this, _responseValidator, new ResponseValidator(
129
+ __privateGet(this, _db),
130
+ __privateGet(this, _ui),
131
+ __privateGet(this, _hooks)
132
+ ));
133
+ this.addEventListener("beforerequest", __privateMethod(this, _WebcatRequestHandler_instances, onRequest_fn));
134
+ this.addEventListener("headersreceived", __privateMethod(this, _WebcatRequestHandler_instances, onHeaders_fn));
135
+ browser.windows.onRemoved.addListener(__privateMethod(this, _WebcatRequestHandler_instances, onWindowClosed_fn).bind(this));
136
+ __privateGet(this, _mutex).acquire(__privateGet(this, _bindLock));
137
+ }
138
+ async bind(fqdns) {
139
+ var _stack = [];
140
+ try {
141
+ const lock = __privateGet(this, _bindLock);
142
+ __privateSet(this, _bindLock, void 0);
143
+ const _ = __using(_stack, await __privateGet(this, _mutex).acquire(lock));
144
+ super.bind(fqdns);
145
+ const newFqdns = await __privateGet(this, _contentScript).bind(fqdns);
146
+ await clearBrowserCaches(newFqdns);
147
+ } catch (_2) {
148
+ var _error = _2, _hasError = true;
149
+ } finally {
150
+ __callDispose(_stack, _error, _hasError);
151
+ }
152
+ }
153
+ /**
154
+ * Binds the handler to `<all_urls>`. Unlike {@link bind}, does not bind
155
+ * content scripts. The bindAll method can be called synchronously before
156
+ * FQDNs are available, but it should be always followed by a call to
157
+ * {@link bind} to both restrict the scope of the binding and bind content
158
+ * scripts.
159
+ */
160
+ bindAll() {
161
+ super.bind(["<all_urls>"]);
162
+ }
163
+ // prettier-ignore
164
+ getListenerOptions(fqdns, type) {
165
+ let all = false;
166
+ for (let i; (i = fqdns.indexOf("<all_urls>")) !== -1; ) {
167
+ fqdns = [...fqdns.slice(0, i), ...fqdns.slice(i + 1)];
168
+ all = true;
169
+ }
170
+ let result;
171
+ if (type === "beforeheaders") {
172
+ const [filter, options] = super.getListenerOptions(fqdns, type);
173
+ filter.types = ["script"];
174
+ result = [filter, options];
175
+ } else {
176
+ result = super.getListenerOptions(fqdns, type);
177
+ }
178
+ if (all) {
179
+ result[0].urls.push("<all_urls>");
180
+ }
181
+ return result;
182
+ }
183
+ }
184
+ _db = new WeakMap();
185
+ _ui = new WeakMap();
186
+ _config = new WeakMap();
187
+ _hooks = new WeakMap();
188
+ _contentScript = new WeakMap();
189
+ _responseValidator = new WeakMap();
190
+ _mutex = new WeakMap();
191
+ _requestLock = new WeakMap();
192
+ _bindLock = new WeakMap();
193
+ _WebcatRequestHandler_instances = new WeakSet();
194
+ initializeState_fn = async function(details) {
195
+ return Object.assign(details, {
196
+ state: {
197
+ fqdn: getFQDN(details.url),
198
+ cachePartition: {
199
+ firstParty: await __privateMethod(this, _WebcatRequestHandler_instances, getFirstParty_fn).call(this, details),
200
+ incognito: !!details.incognito
201
+ },
202
+ isFrame: FRAME_TYPES.includes(details.type)
203
+ }
204
+ });
205
+ };
206
+ onRequest_fn = async function(event) {
207
+ var _stack = [];
208
+ try {
209
+ const blockingResponse = __using(_stack, event.createBlockingResponse());
210
+ if (isExtensionRequest(event.details)) {
211
+ blockingResponse.cancel = false;
212
+ return;
213
+ }
214
+ const details = await __privateMethod(this, _WebcatRequestHandler_instances, initializeState_fn).call(this, event.details);
215
+ const _ = __using(_stack, await __privateGet(this, _mutex).acquire(__privateGet(this, _requestLock)));
216
+ if (details.state.isFrame) {
217
+ logger.info(`Loading ${details.type} ${details.url}`, details);
218
+ const beforeframeload = new RequestEvent(
219
+ "beforeframeload",
220
+ event.details
221
+ );
222
+ this.dispatchEvent(beforeframeload);
223
+ const frameResult = await beforeframeload.ready();
224
+ if (frameResult.cancel) {
225
+ return blockingResponse.set(frameResult);
226
+ }
227
+ }
228
+ if (!details.state.isFrame) {
229
+ const cached = await __privateGet(this, _db).origins.get(
230
+ CacheKey(details.state.fqdn, details.state.cachePartition)
231
+ );
232
+ const now = Math.floor(Date.now() / 1e3);
233
+ if (cached?.validUntil && cached.validUntil > now) {
234
+ details.state.pendingOrigin = cached;
235
+ }
236
+ }
237
+ if (!details.state.pendingOrigin) {
238
+ const result = await validateOrigin(
239
+ __privateGet(this, _db),
240
+ __privateGet(this, _ui),
241
+ details,
242
+ __privateGet(this, _config)
243
+ );
244
+ if (result instanceof WebcatError) {
245
+ if (details.state.isFrame) {
246
+ __privateGet(this, _ui).showErrorPage(details, result);
247
+ }
248
+ return blockingResponse.set({ cancel: true });
249
+ }
250
+ if (result) {
251
+ if (details.state.isFrame) {
252
+ logger.info(`Redirecting to https`, details);
253
+ }
254
+ return blockingResponse.set({ ...result, cancel: false });
255
+ }
256
+ }
257
+ if (!details.state.pendingOrigin) {
258
+ blockingResponse.cancel = false;
259
+ return;
260
+ }
261
+ await __privateGet(this, _responseValidator).validateContent(details);
262
+ blockingResponse.cancel = false;
263
+ } catch (_2) {
264
+ var _error = _2, _hasError = true;
265
+ } finally {
266
+ __callDispose(_stack, _error, _hasError);
267
+ }
268
+ };
269
+ onHeaders_fn = async function(event) {
270
+ var _stack = [];
271
+ try {
272
+ const blockingResponse = __using(_stack, event.createBlockingResponse());
273
+ const details = event.details;
274
+ if (isExtensionRequest(details)) {
275
+ const location = details.responseHeaders?.find(
276
+ (header) => header.name.toLowerCase() === "location"
277
+ )?.value;
278
+ if (location && !isSameOriginURL(location, details.url)) {
279
+ return;
280
+ }
281
+ blockingResponse.cancel = false;
282
+ return;
283
+ }
284
+ if (!details.state) {
285
+ blockingResponse.cancel = false;
286
+ return;
287
+ }
288
+ if (!details.state.pendingOrigin) {
289
+ throw new Error("missing pendingOrigin in request state");
290
+ }
291
+ const result = await __privateGet(this, _responseValidator).validateHeaders(details);
292
+ if (result instanceof WebcatError) {
293
+ logger.error(
294
+ `Error when parsing response headers: ${result}: ${result.details?.join(", ")}`,
295
+ details
296
+ );
297
+ __privateGet(this, _ui).showErrorPage(details, result);
298
+ return blockingResponse.set({ cancel: true });
299
+ }
300
+ await __privateMethod(this, _WebcatRequestHandler_instances, commitVerifiedOrigin_fn).call(this, details.state.fqdn, details.state.pendingOrigin, details.state.cachePartition);
301
+ if (details.state.isFrame) {
302
+ blockingResponse.setHeader("Origin-Agent-Cluster", "?1");
303
+ }
304
+ __privateGet(this, _responseValidator).markContent(event.details);
305
+ if (FRAME_TYPES.includes(details.type) && details.state.pendingOrigin.manifest) {
306
+ const wasm = details.state.pendingOrigin.manifest.wasm;
307
+ const listener = async (navDetails) => {
308
+ if (navDetails.tabId !== details.tabId) return;
309
+ if (navDetails.frameId !== details.frameId) return;
310
+ browser.webNavigation.onDOMContentLoaded.removeListener(listener);
311
+ const [func, args] = await __privateGet(this, _hooks).getContentScriptHooks(
312
+ wasm,
313
+ details.state.cachePartition.firstParty,
314
+ details.state.cachePartition.firstParty === new URL(details.url).origin
315
+ );
316
+ await browser.scripting.executeScript({
317
+ target: {
318
+ tabId: details.tabId,
319
+ frameIds: [details.frameId]
320
+ },
321
+ func,
322
+ args,
323
+ injectImmediately: true,
324
+ world: "ISOLATED"
325
+ });
326
+ };
327
+ browser.webNavigation.onDOMContentLoaded.addListener(listener);
328
+ }
329
+ blockingResponse.cancel = false;
330
+ } catch (_) {
331
+ var _error = _, _hasError = true;
332
+ } finally {
333
+ __callDispose(_stack, _error, _hasError);
334
+ }
335
+ };
336
+ commitVerifiedOrigin_fn = async function(fqdn, newState, cachePartition) {
337
+ if (newState.stale) {
338
+ return;
339
+ }
340
+ if (!newState.isManifestVerified()) {
341
+ return;
342
+ }
343
+ const incoming = newState.manifest.version;
344
+ const currentState = await __privateGet(this, _db).origins.get(
345
+ CacheKey(fqdn, cachePartition)
346
+ );
347
+ if (currentState && currentState.isManifestVerified()) {
348
+ const current = currentState.manifest.version;
349
+ if (!isNewerSemver(incoming, current) && currentState.validUntil >= newState.validUntil) {
350
+ return;
351
+ }
352
+ }
353
+ await __privateGet(this, _db).origins.set(CacheKey(fqdn, cachePartition), newState);
354
+ };
355
+ getFirstParty_fn = async function(details) {
356
+ if (details.tabId === -1 || details.frameId === -1 || details.frameId === 0) {
357
+ for (const url of [details.url, details.documentUrl, details.originUrl]) {
358
+ if (url === void 0) continue;
359
+ try {
360
+ return await __privateGet(this, _hooks).decryptFragment(url);
361
+ } catch {
362
+ }
363
+ }
364
+ }
365
+ if (details.frameAncestors?.length) {
366
+ return new URL(
367
+ details.frameAncestors[details.frameAncestors.length - 1].url
368
+ ).origin;
369
+ }
370
+ if (details.frameId !== 0 && details.frameId !== -1) {
371
+ const frames = await browser.webNavigation.getAllFrames({
372
+ tabId: details.tabId
373
+ });
374
+ if (frames.find((frame) => frame.frameId === details.frameId)) {
375
+ return new URL(frames.find((frame) => frame.frameId === 0)?.url || "").origin;
376
+ }
377
+ logger.addLog(
378
+ "warn",
379
+ `Cannot determine first-party origin for '${details.url}'; using unique cache partition`,
380
+ details.tabId,
381
+ getFQDN(details.url)
382
+ );
383
+ return details.requestId;
384
+ }
385
+ if (details.documentUrl) {
386
+ return new URL(details.documentUrl).origin;
387
+ }
388
+ if (details.type === "main_frame") {
389
+ return new URL(details.url).origin;
390
+ }
391
+ logger.addLog(
392
+ "error",
393
+ `No first-party origin found for '${details.url}'`,
394
+ details.tabId,
395
+ getFQDN(details.url)
396
+ );
397
+ return details.requestId;
398
+ };
399
+ onWindowClosed_fn = async function() {
400
+ const windows = await browser.windows.getAll();
401
+ if (windows.filter((win) => win.incognito).length === 0) {
402
+ for (const key of await __privateGet(this, _db).origins.keys()) {
403
+ if (isInPartition(key, { incognito: true })) {
404
+ __privateGet(this, _db).origins.delete(key);
405
+ }
406
+ }
407
+ for (const value of await __privateGet(this, _db).nonOrigins.values()) {
408
+ if (isInPartition(value, { incognito: true })) {
409
+ __privateGet(this, _db).nonOrigins.delete(value);
410
+ }
411
+ }
412
+ }
413
+ };
414
+ _init = __decoratorStart(_a);
415
+ WebcatRequestHandler = __decorateElement(_init, 0, "WebcatRequestHandler", _WebcatRequestHandler_decorators, WebcatRequestHandler);
416
+ __runInitializers(_init, 1, WebcatRequestHandler);
417
+ export {
418
+ WebcatRequestHandler
419
+ };