@whotracksme/reporting 11.1.1 → 12.1.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 (40) hide show
  1. package/CHANGELOG.md +39 -0
  2. package/package.json +1 -1
  3. package/reporting/README.md +13 -0
  4. package/reporting/example/README.md +4 -0
  5. package/reporting/example/e2e/README.md +265 -0
  6. package/reporting/example/e2e/console-capture.js +67 -0
  7. package/reporting/example/e2e/control.js +449 -0
  8. package/reporting/example/e2e/hub.mjs +380 -0
  9. package/reporting/example/e2e/launch.mjs +92 -0
  10. package/reporting/example/e2e/mock-extension.mjs +106 -0
  11. package/reporting/example/e2e/pages/private-fixture.html +16 -0
  12. package/reporting/example/e2e/run.mjs +226 -0
  13. package/reporting/example/e2e/scenarios/privacy-guards.json +26 -0
  14. package/reporting/example/e2e/scenarios/smoke.json +15 -0
  15. package/reporting/example/e2e/verify.mjs +159 -0
  16. package/reporting/example/index.js +55 -46
  17. package/reporting/example/manifests/chromium.json +1 -0
  18. package/reporting/example/storage.js +65 -0
  19. package/reporting/package.json +5 -1
  20. package/reporting/rollup.config.cjs +1 -1
  21. package/reporting/snapshots/0001/snapshot.json +13 -13
  22. package/reporting/snapshots/0003/snapshot.json +5 -5
  23. package/reporting/snapshots/0005/snapshot.json +13 -13
  24. package/reporting/src/doublefetch-page-handler.js +30 -20
  25. package/reporting/src/doublefetch-unbreak.js +186 -0
  26. package/reporting/src/http.js +197 -19
  27. package/reporting/src/index.js +1 -0
  28. package/reporting/src/offscreen/doublefetch/capture.js +90 -0
  29. package/reporting/src/patterns.js +142 -2
  30. package/reporting/src/request/index.js +6 -0
  31. package/reporting/src/request/page-store.js +1 -0
  32. package/reporting/src/request/support.js +29 -0
  33. package/reporting/src/search-extractor.js +8 -2
  34. package/reporting/src/utils.js +19 -0
  35. package/reporting/test/doublefetch-unbreak.spec.js +133 -0
  36. package/reporting/test/http.spec.js +113 -0
  37. package/reporting/test/index.js +1 -0
  38. package/reporting/test/patterns.spec.js +239 -0
  39. package/reporting/test/search-extractor.spec.js +19 -1
  40. package/reporting/test/setup.unit.js +9 -0
@@ -0,0 +1,226 @@
1
+ /**
2
+ * WhoTracks.Me
3
+ * https://whotracks.me/
4
+ *
5
+ * Copyright 2017-present Ghostery GmbH. All rights reserved.
6
+ *
7
+ * This Source Code Form is subject to the terms of the Mozilla Public
8
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
9
+ * file, You can obtain one at http://mozilla.org/MPL/2.0
10
+ */
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { fileURLToPath } from 'node:url';
14
+ import { parseArgs } from 'node:util';
15
+ import { verify } from './verify.mjs';
16
+
17
+ const { values, positionals } = parseArgs({
18
+ allowPositionals: true,
19
+ options: {
20
+ hub: { type: 'string', default: 'http://127.0.0.1:7878' },
21
+ json: { type: 'boolean', default: false },
22
+ 'keep-messages': { type: 'boolean', default: false },
23
+ patterns: { type: 'string' },
24
+ },
25
+ });
26
+
27
+ const e2eDir = path.dirname(fileURLToPath(import.meta.url));
28
+
29
+ function resolveScenario(nameOrPath) {
30
+ const candidates = [
31
+ nameOrPath,
32
+ path.join(e2eDir, 'scenarios', nameOrPath),
33
+ path.join(e2eDir, 'scenarios', `${nameOrPath}.json`),
34
+ ];
35
+ const found = candidates.find((c) => fs.existsSync(c));
36
+ if (!found) {
37
+ const available = fs
38
+ .readdirSync(path.join(e2eDir, 'scenarios'))
39
+ .filter((f) => f.endsWith('.json'))
40
+ .map((f) => f.replace(/\.json$/, ''));
41
+ console.error(
42
+ `unknown scenario "${nameOrPath}". Available: ${available.join(', ')}`,
43
+ );
44
+ process.exit(2);
45
+ }
46
+ return found;
47
+ }
48
+
49
+ async function hub(method, route, body) {
50
+ const response = await fetch(`${values.hub}${route}`, {
51
+ method,
52
+ headers:
53
+ method === 'POST' ? { 'Content-Type': 'application/json' } : undefined,
54
+ body: body ? JSON.stringify(body) : undefined,
55
+ });
56
+ const text = await response.text();
57
+ let parsed;
58
+ try {
59
+ parsed = JSON.parse(text);
60
+ } catch {
61
+ parsed = { raw: text };
62
+ }
63
+ return { status: response.status, body: parsed };
64
+ }
65
+
66
+ async function command(name, args = {}, timeout) {
67
+ const { status, body } = await hub('POST', '/cmd', { name, args, timeout });
68
+ if (status !== 200) {
69
+ throw new Error(`${name} failed: ${body.error || status}`);
70
+ }
71
+ return body.result;
72
+ }
73
+
74
+ const health = await hub('GET', '/health').catch(() => null);
75
+ if (!health || health.status !== 200) {
76
+ console.error(
77
+ `hub is not reachable at ${values.hub} — start it with:\n npm --workspace=reporting run e2e.hub`,
78
+ );
79
+ process.exit(2);
80
+ }
81
+ if (!health.body.extensionConnected) {
82
+ console.error(
83
+ 'hub is up but the extension has not connected.\n' +
84
+ 'Check that the example extension is loaded and enabled, then reload it.',
85
+ );
86
+ process.exit(2);
87
+ }
88
+
89
+ const scenarioFile = resolveScenario(positionals[0] || 'smoke');
90
+ const scenario = JSON.parse(fs.readFileSync(scenarioFile, 'utf8'));
91
+
92
+ console.error(`scenario: ${scenario.name} (${path.basename(scenarioFile)})`);
93
+
94
+ if (!values['keep-messages']) {
95
+ await hub('POST', '/messages/clear');
96
+ }
97
+ const startSeq = (await hub('GET', '/health')).body.seq;
98
+
99
+ const STEP_OPTIONS = ['timeout', 'continueOnError'];
100
+
101
+ // A local patterns file replaces the served one for the run. A reset restarts
102
+ // the worker with empty storage, so it has to be applied again afterwards.
103
+ const patternsOverride = values.patterns
104
+ ? JSON.parse(fs.readFileSync(values.patterns, 'utf8'))
105
+ : null;
106
+
107
+ async function applyPatternsOverride() {
108
+ if (!patternsOverride) {
109
+ return;
110
+ }
111
+ const { categories } = await command('setPatterns', {
112
+ rules: patternsOverride,
113
+ });
114
+ console.error(` patterns: ${values.patterns} (${categories.join(', ')})`);
115
+ }
116
+
117
+ // The worker reconnects before init() has finished; a navigation that lands
118
+ // in that window is dropped, so a restart is only done once it is active.
119
+ async function waitUntilActive(timeoutInMs = 30000) {
120
+ const startedAt = Date.now();
121
+ for (;;) {
122
+ const state = await command('state');
123
+ if (state.isActive) {
124
+ return;
125
+ }
126
+ if (Date.now() - startedAt > timeoutInMs) {
127
+ throw new Error('reporter did not become active after the restart');
128
+ }
129
+ await new Promise((resolve) => setTimeout(resolve, 250));
130
+ }
131
+ }
132
+
133
+ await applyPatternsOverride();
134
+
135
+ const trace = [];
136
+ for (const [index, step] of (scenario.steps || []).entries()) {
137
+ const entry = Object.entries(step).find(
138
+ ([key]) => !STEP_OPTIONS.includes(key),
139
+ );
140
+ if (!entry) {
141
+ console.error(`\nstep ${index + 1} has no command key`);
142
+ process.exitCode = 1;
143
+ break;
144
+ }
145
+ const [name, args] = entry;
146
+ const label = `${index + 1}/${scenario.steps.length} ${name}`;
147
+ process.stderr.write(` ${label} ... `);
148
+ const startedAt = Date.now();
149
+ try {
150
+ const result = await command(name, args ?? {}, step.timeout);
151
+ const took = Date.now() - startedAt;
152
+ process.stderr.write(`ok (${took}ms)\n`);
153
+ trace.push({ step: name, args, result, tookInMs: took });
154
+ if (name === 'reset' || name === 'reload') {
155
+ await waitUntilActive();
156
+ await applyPatternsOverride();
157
+ }
158
+ } catch (e) {
159
+ process.stderr.write(`FAILED\n`);
160
+ console.error(`\n ${e.message}\n`);
161
+ trace.push({ step: name, args, error: e.message });
162
+ if (step.continueOnError !== true) {
163
+ process.exitCode = 1;
164
+ break;
165
+ }
166
+ }
167
+ }
168
+
169
+ const captured = (await hub('GET', `/messages?since=${startSeq}`)).body
170
+ .messages;
171
+ const events = (await hub('GET', `/events?since=${startSeq}`)).body.events;
172
+ const result = verify(captured, scenario.expect || {});
173
+
174
+ if (values.json) {
175
+ console.log(
176
+ JSON.stringify(
177
+ { scenario: scenario.name, result, captured, trace },
178
+ null,
179
+ 2,
180
+ ),
181
+ );
182
+ } else {
183
+ console.log(`\ncaptured ${captured.length} message(s):`);
184
+ const byAction = {};
185
+ for (const message of captured) {
186
+ const action = message.body?.action || message.body?.type || '<unknown>';
187
+ byAction[action] = (byAction[action] || 0) + 1;
188
+ }
189
+ for (const [action, count] of Object.entries(byAction)) {
190
+ console.log(` ${count}x ${action}`);
191
+ }
192
+
193
+ if (result.ok) {
194
+ console.log('\nPASSED');
195
+ } else {
196
+ console.log(`\nFAILED — ${result.failures.length} problem(s):`);
197
+ for (const failure of result.failures) {
198
+ console.log(` [${failure.kind}] ${failure.detail}`);
199
+ if (failure.sawInstead?.length) {
200
+ console.log(
201
+ ` saw instead: ${JSON.stringify(failure.sawInstead).slice(
202
+ 0,
203
+ 300,
204
+ )}`,
205
+ );
206
+ }
207
+ }
208
+ const interesting = events.filter((e) =>
209
+ ['jobRejected', 'jobFailed', 'jobExpired'].includes(e.event),
210
+ );
211
+ if (interesting.length > 0) {
212
+ console.log('\n job events worth a look:');
213
+ for (const event of interesting.slice(0, 20)) {
214
+ console.log(
215
+ ` ${event.event} ${event.details?.type} ${JSON.stringify(
216
+ event.details?.args || {},
217
+ ).slice(0, 160)}`,
218
+ );
219
+ }
220
+ }
221
+ }
222
+ }
223
+
224
+ if (!result.ok) {
225
+ process.exitCode = 1;
226
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "name": "privacy-guards",
3
+ "description": "Negative scenario. A page on a private host with a non-standard port must be dropped by sanitizeUrl, and denying quorum must suppress page messages entirely.",
4
+ "steps": [
5
+ { "reset": {} },
6
+ { "closeTabs": {} },
7
+ {
8
+ "navigate": {
9
+ "url": "http://127.0.0.1:7878/pages/private-fixture.html?token=wtm-e2e-secret-token"
10
+ }
11
+ },
12
+ { "flush": { "maxRounds": 8 } },
13
+ { "setQuorum": { "mode": "never" } },
14
+ { "navigate": { "url": "https://en.wikipedia.org/wiki/Hamburg" } },
15
+ { "flush": { "maxRounds": 8 } }
16
+ ],
17
+ "expect": {
18
+ "mustNotAppear": [
19
+ "wtm-e2e-private-marker",
20
+ "wtm-e2e-secret-token",
21
+ "127.0.0.1",
22
+ "private-fixture"
23
+ ],
24
+ "forbiddenActions": ["wtm.page"]
25
+ }
26
+ }
@@ -0,0 +1,15 @@
1
+ {
2
+ "name": "smoke",
3
+ "description": "Hub/extension connectivity plus one public page all the way to a wtm.page message.",
4
+ "steps": [
5
+ { "reset": {} },
6
+ { "closeTabs": {} },
7
+ { "navigate": { "url": "https://en.wikipedia.org/wiki/Berlin" } },
8
+ { "flush": { "maxRounds": 12 } }
9
+ ],
10
+ "expect": {
11
+ "messages": {
12
+ "wtm.page": [{ "url": "~wikipedia.org/wiki/Berlin" }]
13
+ }
14
+ }
15
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * WhoTracks.Me
3
+ * https://whotracks.me/
4
+ *
5
+ * Copyright 2017-present Ghostery GmbH. All rights reserved.
6
+ *
7
+ * This Source Code Form is subject to the terms of the Mozilla Public
8
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
9
+ * file, You can obtain one at http://mozilla.org/MPL/2.0
10
+ */
11
+
12
+ const REQUIRED_FIELDS = {
13
+ 'wtm.page': ['url', 't', 'ref', 'redirects', 'lang', 'ctry', 'activity'],
14
+ 'wtm.attrack.tp_events': null,
15
+ 'wtm.attrack.tokensv2': null,
16
+ 'wtm.attrack.keysv2': null,
17
+ };
18
+
19
+ // Actions come from the patterns file, not this repo, so they cannot be listed.
20
+ const SEARCH_CONTEXT_FIELDS = ['q', 'qurl', 'ctry'];
21
+
22
+ function looksLikeSearchMessage(message) {
23
+ return typeof message.body?.payload?.qurl === 'string';
24
+ }
25
+
26
+ function collectStrings(value, found = []) {
27
+ if (typeof value === 'string') {
28
+ found.push(value);
29
+ } else if (Array.isArray(value)) {
30
+ value.forEach((item) => collectStrings(item, found));
31
+ } else if (value && typeof value === 'object') {
32
+ Object.entries(value).forEach(([key, item]) => {
33
+ found.push(key);
34
+ collectStrings(item, found);
35
+ });
36
+ }
37
+ return found;
38
+ }
39
+
40
+ function actionOf(message) {
41
+ return message.body?.action || message.body?.type || '<unknown>';
42
+ }
43
+
44
+ function requiredFieldsFor(message) {
45
+ const action = actionOf(message);
46
+ if (action in REQUIRED_FIELDS) {
47
+ return REQUIRED_FIELDS[action];
48
+ }
49
+ return looksLikeSearchMessage(message) ? SEARCH_CONTEXT_FIELDS : null;
50
+ }
51
+
52
+ export function checkShapes(messages) {
53
+ const failures = [];
54
+ for (const message of messages) {
55
+ const action = actionOf(message);
56
+ const required = requiredFieldsFor(message);
57
+ if (!required) {
58
+ continue;
59
+ }
60
+ const payload = message.body?.payload || {};
61
+ const missing = required.filter((field) => !(field in payload));
62
+ if (missing.length > 0) {
63
+ failures.push({
64
+ kind: 'shape',
65
+ seq: message.seq,
66
+ action,
67
+ detail: `payload is missing: ${missing.join(', ')}`,
68
+ });
69
+ }
70
+ }
71
+ return failures;
72
+ }
73
+
74
+ // Scans every string and every object key: a leak hiding in a key is still a leak.
75
+ export function checkNoLeaks(messages, mustNotAppear = []) {
76
+ const failures = [];
77
+ if (mustNotAppear.length === 0) {
78
+ return failures;
79
+ }
80
+ for (const message of messages) {
81
+ const haystack = collectStrings(message.body).join('\0').toLowerCase();
82
+ for (const needle of mustNotAppear) {
83
+ if (haystack.includes(needle.toLowerCase())) {
84
+ failures.push({
85
+ kind: 'leak',
86
+ seq: message.seq,
87
+ action: actionOf(message),
88
+ detail: `forbidden string "${needle}" appears in an outgoing message`,
89
+ message: message.body,
90
+ });
91
+ }
92
+ }
93
+ }
94
+ return failures;
95
+ }
96
+
97
+ function matches(message, expectation) {
98
+ const payload = message.body?.payload || {};
99
+ return Object.entries(expectation).every(([pathExpr, expected]) => {
100
+ const actual = pathExpr
101
+ .split('.')
102
+ .reduce((acc, key) => (acc == null ? acc : acc[key]), payload);
103
+ if (expected instanceof RegExp) {
104
+ return typeof actual === 'string' && expected.test(actual);
105
+ }
106
+ if (typeof expected === 'string' && expected.startsWith('~')) {
107
+ return typeof actual === 'string' && actual.includes(expected.slice(1));
108
+ }
109
+ return actual === expected;
110
+ });
111
+ }
112
+
113
+ export function checkExpected(messages, expected = {}) {
114
+ const failures = [];
115
+ for (const [key, expectations] of Object.entries(expected)) {
116
+ const exact = key.startsWith('=');
117
+ const action = exact ? key.slice(1) : key;
118
+ const candidates = messages.filter((m) =>
119
+ exact ? actionOf(m) === action : actionOf(m).startsWith(action),
120
+ );
121
+ for (const expectation of expectations) {
122
+ const hit = candidates.find((message) => matches(message, expectation));
123
+ if (!hit) {
124
+ failures.push({
125
+ kind: 'missing',
126
+ action,
127
+ detail: `no ${action} message matched ${JSON.stringify(expectation)}`,
128
+ sawInstead: candidates.map((m) => m.body?.payload?.url ?? m.body),
129
+ });
130
+ }
131
+ }
132
+ }
133
+ return failures;
134
+ }
135
+
136
+ export function checkForbiddenActions(messages, forbiddenActions = []) {
137
+ return messages
138
+ .filter((message) =>
139
+ forbiddenActions.some((action) => actionOf(message).startsWith(action)),
140
+ )
141
+ .map((message) => ({
142
+ kind: 'forbidden-action',
143
+ seq: message.seq,
144
+ action: actionOf(message),
145
+ detail: `message action "${actionOf(
146
+ message,
147
+ )}" must not be sent in this scenario`,
148
+ }));
149
+ }
150
+
151
+ export function verify(messages, expect = {}) {
152
+ const failures = [
153
+ ...checkShapes(messages),
154
+ ...checkNoLeaks(messages, expect.mustNotAppear || []),
155
+ ...checkForbiddenActions(messages, expect.forbiddenActions || []),
156
+ ...checkExpected(messages, expect.messages || {}),
157
+ ];
158
+ return { ok: failures.length === 0, failures };
159
+ }
@@ -9,7 +9,14 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
  import './setup.js';
12
+ // Must stay above the src/ import: Logger binds console.* in its constructor.
13
+ import { attachConsoleSink } from './e2e/console-capture.js';
12
14
  import { UrlReporter, RequestReporter, setLogLevel } from '../src/index.js';
15
+ import { createStorage, createTrustedClock } from './storage.js';
16
+ import E2EBridge, {
17
+ createCommands,
18
+ pipeJobEventsToHub,
19
+ } from './e2e/control.js';
13
20
 
14
21
  (chrome.action || chrome.browserAction).onClicked.addListener(() => {
15
22
  chrome.tabs.create({
@@ -20,54 +27,43 @@ import { UrlReporter, RequestReporter, setLogLevel } from '../src/index.js';
20
27
 
21
28
  setLogLevel('debug');
22
29
 
23
- function createStorage() {
24
- const storage = {
25
- storage: {},
26
- async get(key) {
27
- return this.storage[key];
28
- },
29
- async set(key, value) {
30
- this.storage[key] = value;
31
- },
32
- async remove(key) {
33
- delete this.storage[key];
34
- },
35
- async clear() {
36
- this.storage = {};
37
- },
38
- async keys() {
39
- return Object.keys(this.storage);
40
- },
41
- open() {},
42
- close() {},
43
- };
44
- return storage;
45
- }
30
+ const bridge = new E2EBridge({ hubUrl: 'ws://127.0.0.1:7878/ws' });
31
+ attachConsoleSink((level, text) => bridge.captureConsole(level, text));
32
+
33
+ const trustedClock = createTrustedClock();
34
+
35
+ // Stubbed: an end-to-end run exercises message construction, not quorum itself.
36
+ const quorumControl = {
37
+ mode: 'always',
38
+ setMode(mode) {
39
+ if (!['always', 'never'].includes(mode)) {
40
+ throw new Error(`unsupported quorum mode: ${mode}`);
41
+ }
42
+ this.mode = mode;
43
+ },
44
+ describe() {
45
+ return { mode: this.mode, real: false };
46
+ },
47
+ verdict() {
48
+ return this.mode === 'always';
49
+ },
50
+ };
46
51
 
47
52
  const communication = {
48
53
  send(msg) {
49
- console.log(
50
- '%c[DRY-RUN] send message:',
51
- 'color: blue; font-size: 30px;',
52
- msg,
53
- );
54
+ bridge.captureMessage('url-reporter', msg);
55
+ console.log('[DRY-RUN] send message:', msg);
54
56
  },
55
- // TODO: use actual anonymous-communication to access quorum
56
57
  sendInstant(msg) {
58
+ const result = quorumControl.verdict();
59
+ bridge.captureMessage('quorum', msg, { stubbedResult: result });
57
60
  console.warn('[Communication instant]', msg);
58
61
  return Promise.resolve({
59
62
  ok: true,
60
- json: () => Promise.resolve({ result: true }),
63
+ json: () => Promise.resolve({ result }),
61
64
  });
62
65
  },
63
- trustedClock: {
64
- getTimeAsYYYYMMDD() {
65
- return '';
66
- },
67
- getTimeAsYYYYMMDDHH() {
68
- return '';
69
- },
70
- },
66
+ trustedClock,
71
67
  };
72
68
 
73
69
  const config = {
@@ -84,27 +80,39 @@ const config = {
84
80
  },
85
81
  };
86
82
 
83
+ function connectDatabase(namespace) {
84
+ return createStorage(namespace);
85
+ }
86
+
87
87
  const urlReporter = new UrlReporter({
88
88
  config: config.url,
89
- storage: createStorage(),
90
- connectDatabase: createStorage,
89
+ storage: connectDatabase('urlreporter'),
90
+ connectDatabase,
91
91
  communication,
92
92
  });
93
93
 
94
94
  const requestReporter = new RequestReporter(config.request, {
95
95
  dryRunMode: true,
96
96
  onMessageReady: (msg) => {
97
- console.log(
98
- '%c[DRY-RUN] request-reporter message ready:',
99
- 'color: green; font-size: 30px;',
100
- msg,
101
- );
97
+ bridge.captureMessage('request-reporter', msg);
98
+ console.log('[DRY-RUN] request-reporter message ready:', msg);
102
99
  },
103
100
  countryProvider: urlReporter.countryProvider,
104
- trustedClock: communication.trustedClock,
101
+ trustedClock,
105
102
  getBrowserInfo: () => ({ name: 'xx' }),
106
103
  });
107
104
 
105
+ pipeJobEventsToHub(urlReporter.jobScheduler, bridge);
106
+ bridge.registerCommands(
107
+ createCommands({
108
+ urlReporter,
109
+ requestReporter,
110
+ quorumControl,
111
+ bridge,
112
+ }),
113
+ );
114
+ bridge.connect();
115
+
108
116
  chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
109
117
  if (request.action === 'mousedown') {
110
118
  requestReporter.recordClick(
@@ -138,3 +146,4 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
138
146
 
139
147
  globalThis.urlReporter = urlReporter;
140
148
  globalThis.requestReporter = requestReporter;
149
+ globalThis.e2eBridge = bridge;
@@ -33,6 +33,7 @@
33
33
  "host_permissions": [
34
34
  "https://collector-hpn.ghostery.net/*",
35
35
  "http://localhost:3001/*",
36
+ "http://127.0.0.1:7878/*",
36
37
  "http://*/*",
37
38
  "https://*/*"
38
39
  ]
@@ -0,0 +1,65 @@
1
+ /**
2
+ * WhoTracks.Me
3
+ * https://whotracks.me/
4
+ *
5
+ * Copyright 2017-present Ghostery GmbH. All rights reserved.
6
+ *
7
+ * This Source Code Form is subject to the terms of the Mozilla Public
8
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
9
+ * file, You can obtain one at http://mozilla.org/MPL/2.0
10
+ */
11
+
12
+ // In-memory storage would disable every persistence path in the library.
13
+ export function createStorage(namespace) {
14
+ const prefix = `${namespace}::`;
15
+ const scopedKey = (key) => `${prefix}${key}`;
16
+
17
+ return {
18
+ async get(key) {
19
+ const result = await chrome.storage.local.get(scopedKey(key));
20
+ return result[scopedKey(key)];
21
+ },
22
+ async set(key, value) {
23
+ await chrome.storage.local.set({ [scopedKey(key)]: value });
24
+ },
25
+ async remove(key) {
26
+ await chrome.storage.local.remove(scopedKey(key));
27
+ },
28
+ async clear() {
29
+ const all = await chrome.storage.local.get(null);
30
+ const owned = Object.keys(all).filter((key) => key.startsWith(prefix));
31
+ if (owned.length > 0) {
32
+ await chrome.storage.local.remove(owned);
33
+ }
34
+ },
35
+ async keys() {
36
+ const all = await chrome.storage.local.get(null);
37
+ return Object.keys(all)
38
+ .filter((key) => key.startsWith(prefix))
39
+ .map((key) => key.slice(prefix.length));
40
+ },
41
+ open() {},
42
+ close() {},
43
+ };
44
+ }
45
+
46
+ export function createTrustedClock() {
47
+ const pad = (value, length = 2) => String(value).padStart(length, '0');
48
+ const parts = (date) => ({
49
+ year: pad(date.getUTCFullYear(), 4),
50
+ month: pad(date.getUTCMonth() + 1),
51
+ day: pad(date.getUTCDate()),
52
+ hour: pad(date.getUTCHours()),
53
+ });
54
+
55
+ return {
56
+ getTimeAsYYYYMMDD() {
57
+ const { year, month, day } = parts(new Date());
58
+ return `${year}${month}${day}`;
59
+ },
60
+ getTimeAsYYYYMMDDHH() {
61
+ const { year, month, day, hour } = parts(new Date());
62
+ return `${year}${month}${day}${hour}`;
63
+ },
64
+ };
65
+ }
@@ -12,6 +12,9 @@
12
12
  "test.unit.request": "mocha --file ./test/setup.unit.js './test/request/**/*.test.js'",
13
13
  "test.unit.request.record": "RECORD_SNAPSHOT=1 mocha --file ./test/setup.unit.js './test/request/**/*.test.js'",
14
14
  "test.unit.watch": "npm run test.unit -- --node-option=watch",
15
+ "e2e.hub": "node example/e2e/hub.mjs",
16
+ "e2e.launch": "node example/e2e/launch.mjs",
17
+ "e2e": "node example/e2e/run.mjs",
15
18
  "test": "karma start --single-run --browsers ChromeHeadless karma.conf.cjs",
16
19
  "test.karma.request": "KARMA_TEST_ENTRY=test/request.js karma start --single-run --browsers ChromeHeadless karma.conf.cjs"
17
20
  },
@@ -42,7 +45,8 @@
42
45
  "sinon-chai": "^4.0.1",
43
46
  "sinon-chrome": "^3.0.1",
44
47
  "web-ext": "^8.2.0",
45
- "webdriverio": "^9.27.0"
48
+ "webdriverio": "^9.27.0",
49
+ "ws": "^8.17.1"
46
50
  },
47
51
  "dependencies": {
48
52
  "@ghostery/url-parser": "^1.3.0",
@@ -29,7 +29,7 @@ module.exports = [
29
29
  copy({
30
30
  targets: [
31
31
  { src: 'src/offscreen/doublefetch/index.html', dest: 'example/offscreen/doublefetch/' },
32
- { src: 'src/offscreen/doublefetch/offscreen-fix.js', dest: 'example/offscreen/doublefetch/' },
32
+ { src: 'src/offscreen/doublefetch/capture.js', dest: 'example/offscreen/doublefetch/' },
33
33
  ]
34
34
  })
35
35
  ]