@whotracksme/reporting 8.0.0 β†’ 8.0.2

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.
package/.eslintignore CHANGED
@@ -1,3 +1,4 @@
1
1
  **/*.bundle.js
2
2
  **/trackers-preview-generated.js
3
3
  **/scripts/**/*.js
4
+ reporting/example/offscreen/**
package/CHANGELOG.md CHANGED
@@ -1,3 +1,36 @@
1
+ # v8.0.2 (Mon Apr 27 2026)
2
+
3
+ #### πŸ› Bug Fix
4
+
5
+ - Guarantee deterministic key orders in messages with nested payloads [#200](https://github.com/whotracksme/webextension-packages/pull/200) ([@philipp-classen](https://github.com/philipp-classen))
6
+
7
+ #### 🏠 Internal
8
+
9
+ - Refresh request-pipeline fixtures to 2026-04-23 Chromium recordings [#198](https://github.com/whotracksme/webextension-packages/pull/198) ([@chrmod](https://github.com/chrmod))
10
+
11
+ #### πŸ“ Documentation
12
+
13
+ - Fixed comment (session storage, not local storage) [#199](https://github.com/whotracksme/webextension-packages/pull/199) ([@philipp-classen](https://github.com/philipp-classen))
14
+
15
+ #### Authors: 2
16
+
17
+ - Krzysztof Modras ([@chrmod](https://github.com/chrmod))
18
+ - Philipp Claßen ([@philipp-classen](https://github.com/philipp-classen))
19
+
20
+ ---
21
+
22
+ # v8.0.1 (Tue Apr 21 2026)
23
+
24
+ #### πŸ› Bug Fix
25
+
26
+ - Developer tooling for the request pipeline [#195](https://github.com/whotracksme/webextension-packages/pull/195) ([@chrmod](https://github.com/chrmod))
27
+
28
+ #### Authors: 1
29
+
30
+ - Krzysztof Modras ([@chrmod](https://github.com/chrmod))
31
+
32
+ ---
33
+
1
34
  # v8.0.0 (Thu Apr 16 2026)
2
35
 
3
36
  #### πŸ’₯ Breaking Change
@@ -13,20 +13,21 @@
13
13
  * Use case: when running object through JSON.stringify, it
14
14
  * should not be distinguishable in which order the object keys
15
15
  * where added.
16
- *
17
- * Note: The current implement only operates on the first level.
18
- * In our context, that should be suffient, since
19
- * anonymous-communication will not add nested structures.
20
- * The only nested structure is the payload, which means the
21
- * message creator will be responsible for the ordering.
22
- *
23
- * Should that become a burden, we could extend this function
24
- * to recursively sort the object keys.
25
16
  */
26
17
  export function sortObjectKeys(obj) {
18
+ if (Array.isArray(obj)) {
19
+ return obj.map(sortObjectKeys);
20
+ }
21
+ if (obj === null || typeof obj !== 'object') {
22
+ return obj;
23
+ }
27
24
  const sortByKeys = (x, y) => {
28
25
  if (x[0] === y[0]) return 0;
29
26
  return x[0] < y[0] ? -1 : 1;
30
27
  };
31
- return Object.fromEntries(Object.entries(obj).sort(sortByKeys));
28
+ return Object.fromEntries(
29
+ Object.entries(obj)
30
+ .sort(sortByKeys)
31
+ .map(([k, v]) => [k, sortObjectKeys(v)]),
32
+ );
32
33
  }
@@ -41,6 +41,80 @@ describe('#sortObjectKeys', function () {
41
41
  );
42
42
  });
43
43
 
44
+ describe('should handle primitive values', function () {
45
+ for (const x of [
46
+ true,
47
+ false,
48
+ undefined,
49
+ null,
50
+ 0,
51
+ 1,
52
+ 1.23,
53
+ '',
54
+ 'foo',
55
+ // not primitive, but include:
56
+ [],
57
+ {},
58
+ ]) {
59
+ it(`- <<${x}>>`, function () {
60
+ const { x: xAfter } = sortObjectKeys({ x });
61
+ expect(xAfter).to.eql(x);
62
+ });
63
+
64
+ it(`- [${x}]`, function () {
65
+ const { x: xAfter } = sortObjectKeys({ x: [x] });
66
+ expect(xAfter).to.eql([x]);
67
+ });
68
+ }
69
+ });
70
+
71
+ it('should sort keys in nested structures', function () {
72
+ const obj1 = {
73
+ payload: {
74
+ paused: false,
75
+ mode: 'default',
76
+ },
77
+ };
78
+ const obj2 = {
79
+ payload: {
80
+ mode: 'default',
81
+ paused: false,
82
+ },
83
+ };
84
+
85
+ const obj1Json = JSON.stringify(sortObjectKeys(obj1));
86
+ const obj2Json = JSON.stringify(sortObjectKeys(obj2));
87
+ expect(obj1Json).to.eql(obj2Json);
88
+ });
89
+
90
+ it('should sort numeric-string keys in numeric order', function () {
91
+ const obj = {
92
+ payload: {
93
+ r: {
94
+ '11': { foo: 42, bar: null },
95
+ '10': { foo: 42, bar: null },
96
+ '2': { foo: 42, bar: null },
97
+ '1': { foo: 42, bar: null },
98
+ '0': { foo: 42, bar: null },
99
+ },
100
+ },
101
+ };
102
+ const objJson = JSON.stringify(sortObjectKeys(obj));
103
+
104
+ const expectedJson = JSON.stringify({
105
+ payload: {
106
+ r: {
107
+ '0': { bar: null, foo: 42 },
108
+ '1': { bar: null, foo: 42 },
109
+ '2': { bar: null, foo: 42 },
110
+ '10': { bar: null, foo: 42 },
111
+ '11': { bar: null, foo: 42 },
112
+ },
113
+ },
114
+ });
115
+ expect(objJson).to.eql(expectedJson);
116
+ });
117
+
44
118
  it('should support object with "toString" property', function () {
45
119
  // Note: used to throw (found by QuickCheck)
46
120
  const obj1 = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "8.0.0",
3
+ "version": "8.0.2",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
@@ -0,0 +1,26 @@
1
+ # Reporting
2
+
3
+ ## Development setup
4
+
5
+ Run `npm ci` in the project root.
6
+
7
+ - Build: `npm --workspace=reporting run build`
8
+ - Watch: `npm --workspace=reporting run watch`
9
+
10
+ ## Running the example extension
11
+
12
+ Interactive (DevTools + web-ext live reload):
13
+
14
+ ```
15
+ npm --workspace=reporting start # Chromium
16
+ npm --workspace=reporting run start.firefox
17
+ ```
18
+
19
+ For a scripted runner with log capture and an HTTP control surface,
20
+ see `example/README.md`.
21
+
22
+ ## Tests
23
+
24
+ See `test/README.md` for the two test suites (node-mocha + karma),
25
+ subset scripts, and the snapshot record workflow. Scenario/snapshot
26
+ fixtures are documented in `scenarios/README.md`.
@@ -0,0 +1,65 @@
1
+ # reporting/example
2
+
3
+ Scripted extension runner with log capture. For the interactive
4
+ `web-ext run` loop, see the package-level `../README.md`.
5
+
6
+ ## Usage
7
+
8
+ ```
9
+ node reporting/example/run.mjs --url https://example.com --wait 10
10
+ ```
11
+
12
+ Requires built bundles β€” run `npm --workspace=reporting run build` first.
13
+
14
+ What it does:
15
+
16
+ - Launches Chrome Canary via wdio with `--enable-unsafe-extension-debugging`
17
+ - Installs the unpacked extension via WebDriver BiDi `webExtension.install`
18
+ - Subscribes to BiDi `log.entryAdded` for page + content-script console
19
+ - Attaches puppeteer-core to chromedriver's debug port for service-worker
20
+ console (BiDi doesn't currently forward SW console events)
21
+ - Writes all entries to `logs/run.log`
22
+ - Navigates to each `--url`, waits `--wait` seconds, uninstalls, exits
23
+
24
+ Flags:
25
+
26
+ - `--url <URL>` β€” can be repeated; visited in order
27
+ - `--wait <seconds>` β€” total time to keep the browser open (default `10`)
28
+ - `--headless` β€” run headless (extension registration may differ)
29
+ - `--log-file <path>` β€” override log output path
30
+ - `--keep-open` β€” don't auto-close; exposes the control server (below)
31
+ - `--port <n>` β€” control server port when `--keep-open` (default `7878`)
32
+ - `--browser-version <channel>` β€” `canary` (default), `dev`, `beta`,
33
+ `stable`, or an explicit version
34
+
35
+ ## Control server (`--keep-open`)
36
+
37
+ Drive a long-lived runner without restarting the browser between steps:
38
+
39
+ ```
40
+ POST /navigate {"url": "https://..."} β†’ {url, title}
41
+ POST /eval {"code": "return ...", "target": "page"} β†’ {result}
42
+ POST /eval {"code": "chrome.runtime.id", "target": "sw"} β†’ {result}
43
+ POST /shutdown β†’ {ok: true}, exits
44
+ GET /state β†’ {extensionId, tabs, sw}
45
+ GET /logs/tail?lines=N β†’ {lines: [...]}
46
+ ```
47
+
48
+ - `/eval` page target: `code` is a function body; write `return <expr>`.
49
+ - `/eval` sw target: `code` is an expression evaluated in the SW realm
50
+ (e.g. `"chrome.runtime.id"`, `"await chrome.storage.local.get(null)"`).
51
+ Returns `409` if no SW is currently attached β€” MV3 service workers may
52
+ have idled out; poke it first with a navigation.
53
+
54
+ ## Why Chrome Canary
55
+
56
+ Two reasons stable Chrome doesn't work today:
57
+
58
+ 1. Stable Chrome refuses `--load-extension` as a security hardening (the
59
+ old web-ext path). BiDi `webExtension.install` sidesteps this.
60
+ 2. Chromedriver's BiDi mapper in stable doesn't yet implement
61
+ `webExtension.install` β€” it returns "Method not available". Canary
62
+ (paired with the matching chromedriver wdio auto-fetches) does.
63
+
64
+ When `browserVersion` is `canary` and wdio doesn't find a local Canary
65
+ install, it downloads Chrome for Testing via `@puppeteer/browsers`.
@@ -0,0 +1,2 @@
1
+ *
2
+ !.gitignore
@@ -0,0 +1,288 @@
1
+ import { remote } from 'webdriverio';
2
+ import puppeteer from 'puppeteer-core';
3
+ import http from 'node:http';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { parseArgs } from 'node:util';
6
+ import path from 'node:path';
7
+ import fs from 'node:fs';
8
+
9
+ const { values } = parseArgs({
10
+ options: {
11
+ url: { type: 'string', multiple: true, default: [] },
12
+ wait: { type: 'string', default: '10' },
13
+ headless: { type: 'boolean', default: false },
14
+ 'keep-open': { type: 'boolean', default: false },
15
+ 'log-file': { type: 'string' },
16
+ 'browser-version': { type: 'string', default: 'canary' },
17
+ port: { type: 'string', default: '7878' },
18
+ },
19
+ });
20
+
21
+ const exampleDir = path.dirname(fileURLToPath(import.meta.url));
22
+
23
+ for (const bundle of ['index.bundle.js', 'content.bundle.js']) {
24
+ if (!fs.existsSync(path.join(exampleDir, bundle))) {
25
+ console.error(
26
+ `missing example/${bundle} β€” run \`npm --workspace=reporting run build\` first`,
27
+ );
28
+ process.exit(1);
29
+ }
30
+ }
31
+
32
+ if (!fs.existsSync(path.join(exampleDir, 'manifest.json'))) {
33
+ fs.copyFileSync(
34
+ path.join(exampleDir, 'manifests', 'chromium.json'),
35
+ path.join(exampleDir, 'manifest.json'),
36
+ );
37
+ }
38
+
39
+ const logDir = path.join(exampleDir, 'logs');
40
+ fs.mkdirSync(logDir, { recursive: true });
41
+ const logFile = values['log-file'] || path.join(logDir, 'run.log');
42
+ fs.writeFileSync(logFile, '');
43
+
44
+ function log(source, level, text) {
45
+ const line = `${new Date().toISOString()} [${source}] [${level}] ${text}\n`;
46
+ fs.appendFileSync(logFile, line);
47
+ process.stdout.write(line);
48
+ }
49
+
50
+ function stringifyArg(v) {
51
+ if (v == null) return String(v);
52
+ if (v.type === 'string') return v.value ?? '';
53
+ if (v.type === 'number' || v.type === 'boolean') return String(v.value);
54
+ if (v.type === 'object' || v.type === 'array') return JSON.stringify(v);
55
+ return v.value !== undefined ? String(v.value) : JSON.stringify(v);
56
+ }
57
+
58
+ const chromeArgs = [
59
+ '--no-first-run',
60
+ '--no-default-browser-check',
61
+ '--enable-unsafe-extension-debugging',
62
+ ];
63
+ if (values.headless) chromeArgs.push('--headless=new');
64
+
65
+ log(
66
+ 'runner',
67
+ 'info',
68
+ `launching chrome (browserVersion=${values['browser-version']})`,
69
+ );
70
+
71
+ const browser = await remote({
72
+ logLevel: 'warn',
73
+ capabilities: {
74
+ browserName: 'chrome',
75
+ browserVersion: values['browser-version'],
76
+ 'goog:chromeOptions': { args: chromeArgs },
77
+ webSocketUrl: true,
78
+ },
79
+ });
80
+
81
+ await browser.sessionSubscribe({ events: ['log.entryAdded'] });
82
+ browser.on('log.entryAdded', (entry) => {
83
+ const text = entry.args
84
+ ? entry.args.map(stringifyArg).join(' ')
85
+ : entry.text || '';
86
+ const ctx = entry.source?.context;
87
+ const realm = entry.source?.realm;
88
+ const src = ctx
89
+ ? `page:${ctx.slice(0, 8)}`
90
+ : realm
91
+ ? `realm:${realm.slice(0, 8)}`
92
+ : 'page';
93
+ log(src, entry.level || 'info', text);
94
+ });
95
+
96
+ let extensionId;
97
+ try {
98
+ const result = await browser.webExtensionInstall({
99
+ extensionData: { type: 'path', path: exampleDir },
100
+ });
101
+ extensionId = result.extension;
102
+ log('runner', 'info', `extension installed: ${extensionId}`);
103
+ } catch (err) {
104
+ log('runner', 'error', `webExtension.install failed: ${err.message}`);
105
+ await browser.deleteSession();
106
+ process.exit(1);
107
+ }
108
+
109
+ let swWorker = null;
110
+ const debuggerAddress =
111
+ browser.capabilities['goog:chromeOptions']?.debuggerAddress;
112
+ if (debuggerAddress) {
113
+ try {
114
+ const cdpBrowser = await puppeteer.connect({
115
+ browserURL: `http://${debuggerAddress}`,
116
+ defaultViewport: null,
117
+ });
118
+ const attached = new WeakSet();
119
+ const attachSW = async (target) => {
120
+ if (attached.has(target) || target.type() !== 'service_worker') return;
121
+ attached.add(target);
122
+ try {
123
+ const worker = await target.worker();
124
+ if (!worker) return;
125
+ swWorker = worker;
126
+ worker.on('console', (msg) => log('sw', msg.type(), msg.text()));
127
+ worker.on('error', (err) => log('sw', 'error', err.message));
128
+ log('runner', 'info', `attached SW: ${target.url()}`);
129
+ } catch (err) {
130
+ log('runner', 'warn', `SW attach failed: ${err.message}`);
131
+ }
132
+ };
133
+ for (const t of cdpBrowser.targets()) await attachSW(t);
134
+ cdpBrowser.on('targetcreated', attachSW);
135
+ } catch (err) {
136
+ log('runner', 'warn', `CDP side-channel failed: ${err.message}`);
137
+ }
138
+ } else {
139
+ log('runner', 'warn', 'no debuggerAddress β€” SW logs will not be captured');
140
+ }
141
+
142
+ for (const url of values.url) {
143
+ log('runner', 'info', `navigating: ${url}`);
144
+ try {
145
+ await browser.url(url);
146
+ } catch (err) {
147
+ log('runner', 'error', `navigate ${url} failed: ${err.message}`);
148
+ }
149
+ }
150
+
151
+ const waitMs = Math.max(0, Number(values.wait) * 1000);
152
+
153
+ async function shutdown() {
154
+ if (extensionId) {
155
+ await browser
156
+ .webExtensionUninstall({ extension: extensionId })
157
+ .catch(() => {});
158
+ }
159
+ await browser.deleteSession().catch(() => {});
160
+ }
161
+
162
+ function readJsonBody(req) {
163
+ return new Promise((resolve) => {
164
+ const chunks = [];
165
+ req.on('data', (c) => chunks.push(c));
166
+ req.on('end', () => {
167
+ const raw = Buffer.concat(chunks).toString('utf8');
168
+ if (!raw) return resolve({});
169
+ try {
170
+ resolve(JSON.parse(raw));
171
+ } catch {
172
+ resolve({ _parseError: true });
173
+ }
174
+ });
175
+ });
176
+ }
177
+
178
+ async function handleControl(method, url, body) {
179
+ const p = url.pathname;
180
+
181
+ if (method === 'POST' && p === '/navigate') {
182
+ if (!body.url) return [400, { error: 'missing url' }];
183
+ await browser.url(body.url);
184
+ return [
185
+ 200,
186
+ { url: await browser.getUrl(), title: await browser.getTitle() },
187
+ ];
188
+ }
189
+
190
+ if (method === 'POST' && p === '/eval') {
191
+ if (!body.code) return [400, { error: 'missing code' }];
192
+ if (body.target === 'sw') {
193
+ if (!swWorker) return [409, { error: 'no SW attached' }];
194
+ try {
195
+ const result = await swWorker.evaluate(body.code);
196
+ return [200, { result }];
197
+ } catch (err) {
198
+ return [500, { error: err.message }];
199
+ }
200
+ }
201
+ try {
202
+ const result = await browser.execute(body.code);
203
+ return [200, { result }];
204
+ } catch (err) {
205
+ return [500, { error: err.message }];
206
+ }
207
+ }
208
+
209
+ if (method === 'GET' && p === '/state') {
210
+ const handles = await browser.getWindowHandles();
211
+ const cur = await browser.getWindowHandle();
212
+ const tabs = [];
213
+ for (const h of handles) {
214
+ await browser.switchToWindow(h);
215
+ tabs.push({
216
+ handle: h,
217
+ url: await browser.getUrl(),
218
+ title: await browser.getTitle(),
219
+ });
220
+ }
221
+ await browser.switchToWindow(cur);
222
+ return [
223
+ 200,
224
+ {
225
+ extensionId,
226
+ tabs,
227
+ sw: swWorker ? { url: swWorker.url() } : null,
228
+ },
229
+ ];
230
+ }
231
+
232
+ if (method === 'GET' && p === '/logs/tail') {
233
+ const n = Number(url.searchParams.get('lines')) || 50;
234
+ const content = fs.readFileSync(logFile, 'utf8');
235
+ const lines = content.split('\n').filter(Boolean).slice(-n);
236
+ return [200, { lines }];
237
+ }
238
+
239
+ return [404, { error: 'unknown route' }];
240
+ }
241
+
242
+ let controlServer;
243
+ function startControlServer(port) {
244
+ controlServer = http.createServer(async (req, res) => {
245
+ try {
246
+ const url = new URL(req.url, 'http://localhost');
247
+ const body = req.method === 'POST' ? await readJsonBody(req) : {};
248
+ if (req.method === 'POST' && url.pathname === '/shutdown') {
249
+ res.writeHead(200, { 'Content-Type': 'application/json' });
250
+ res.end(JSON.stringify({ ok: true }));
251
+ setTimeout(async () => {
252
+ await shutdown();
253
+ process.exit(0);
254
+ }, 10);
255
+ return;
256
+ }
257
+ const [status, reply] = await handleControl(req.method, url, body);
258
+ res.writeHead(status, { 'Content-Type': 'application/json' });
259
+ res.end(JSON.stringify(reply));
260
+ } catch (err) {
261
+ res.writeHead(500, { 'Content-Type': 'application/json' });
262
+ res.end(JSON.stringify({ error: err.message }));
263
+ }
264
+ });
265
+ controlServer.listen(port, '127.0.0.1', () => {
266
+ log('runner', 'info', `control on http://127.0.0.1:${port}`);
267
+ log(
268
+ 'runner',
269
+ 'info',
270
+ 'routes: POST /navigate {url}, POST /eval {code,target?}, POST /shutdown, GET /state, GET /logs/tail?lines=N',
271
+ );
272
+ });
273
+ }
274
+
275
+ if (values['keep-open']) {
276
+ startControlServer(Number(values.port));
277
+ log('runner', 'info', 'keeping browser open (ctrl-c to exit)');
278
+ process.on('SIGINT', async () => {
279
+ controlServer?.close();
280
+ await shutdown();
281
+ process.exit(0);
282
+ });
283
+ } else {
284
+ log('runner', 'info', `waiting ${values.wait}s`);
285
+ await new Promise((r) => setTimeout(r, waitMs));
286
+ await shutdown();
287
+ log('runner', 'info', `done, logs at ${logFile}`);
288
+ }
@@ -1,11 +1,12 @@
1
1
  const rollupPreprocessor = require('./rollup.common-config.cjs');
2
2
 
3
3
  module.exports = function (config) {
4
+ const entry = process.env.KARMA_TEST_ENTRY || 'test/index.js';
4
5
  config.set({
5
6
  frameworks: ['mocha', 'chai', 'sinon'],
6
- files: [{ pattern: 'test/index.js', watched: false }],
7
+ files: [{ pattern: entry, watched: false }],
7
8
  preprocessors: {
8
- 'test/index.js': ['rollup'],
9
+ [entry]: ['rollup'],
9
10
  },
10
11
  reporters: ['mocha'],
11
12
  port: 9876,
@@ -5,11 +5,15 @@
5
5
  "scripts": {
6
6
  "start": "cp example/manifests/chromium.json example/manifest.json && web-ext run -s ./example -t chromium",
7
7
  "start.firefox": "cp example/manifests/firefox.json example/manifest.json && web-ext run -s ./example -t firefox-desktop",
8
+ "start.auto": "cp example/manifests/chromium.json example/manifest.json && node example/run.mjs",
8
9
  "build": "rollup -c",
9
10
  "watch": "rollup -c -w",
10
11
  "test.unit": "mocha --file ./test/setup.unit.js './test/**/*.test.js'",
12
+ "test.unit.request": "mocha --file ./test/setup.unit.js './test/request/**/*.test.js'",
13
+ "test.unit.request.record": "RECORD_SNAPSHOT=1 mocha --file ./test/setup.unit.js './test/request/**/*.test.js'",
11
14
  "test.unit.watch": "npm run test.unit -- --node-option=watch",
12
- "test": "karma start --single-run --browsers ChromeHeadless karma.conf.cjs"
15
+ "test": "karma start --single-run --browsers ChromeHeadless karma.conf.cjs",
16
+ "test.karma.request": "KARMA_TEST_ENTRY=test/request.js karma start --single-run --browsers ChromeHeadless karma.conf.cjs"
13
17
  },
14
18
  "author": "Ghostery GmbH",
15
19
  "license": "MPL-2.0",
@@ -29,6 +33,7 @@
29
33
  "karma-rollup-preprocessor": "^7.0.8",
30
34
  "karma-sinon": "^1.0.5",
31
35
  "mocha": "^11.7.1",
36
+ "puppeteer-core": "^24.42.0",
32
37
  "rollup": "^2.79.1",
33
38
  "rollup-plugin-copy": "^3.5.0",
34
39
  "rollup-plugin-polyfill-node": "^0.8.0",
@@ -36,7 +41,8 @@
36
41
  "sinon": "^21.0.0",
37
42
  "sinon-chai": "^4.0.1",
38
43
  "sinon-chrome": "^3.0.1",
39
- "web-ext": "^8.2.0"
44
+ "web-ext": "^8.2.0",
45
+ "webdriverio": "^9.27.0"
40
46
  },
41
47
  "dependencies": {
42
48
  "@ghostery/url-parser": "^1.3.0",
@@ -5,7 +5,13 @@ const commonjs = require('@rollup/plugin-commonjs');
5
5
  const json = require('@rollup/plugin-json');
6
6
 
7
7
  module.exports = {
8
- plugins: [nodePolyfills(), nodeResolve(), sourcemaps(), commonjs(), json()],
8
+ plugins: [
9
+ nodePolyfills(),
10
+ nodeResolve(),
11
+ sourcemaps(),
12
+ commonjs({ strictRequires: ['**/cssom/**'] }),
13
+ json(),
14
+ ],
9
15
  external: ['chai', 'sinon'],
10
16
  output: {
11
17
  globals: {
@@ -0,0 +1,79 @@
1
+ # Scenarios
2
+
3
+ Pre-recorded `chrome.webRequest.*`, `chrome.webNavigation.*`, and
4
+ `chrome.tabs.*` event streams that drive `RequestReporter` in node-mocha
5
+ integration tests without a real browser.
6
+
7
+ ## Layout
8
+
9
+ ```
10
+ scenarios/<release>/events_<scenario>_<browser>.log ← JSONL, one event per line
11
+ ```
12
+
13
+ A `release` identifies the recording date and the schema version of the
14
+ events format. When a scenario needs to be re-recorded (browser API drift,
15
+ schema change), bump the release rather than editing an existing file β€”
16
+ earlier releases may still be referenced by tests pinned to them.
17
+
18
+ `events_*.log` files are also downloaded on demand from
19
+ `github.com/ghostery/webextension-event-recorder/releases` if they aren't
20
+ present locally β€” the repository tracks them once pulled. See
21
+ `test/helpers/scenarios.js` for the download logic.
22
+
23
+ ## Current index
24
+
25
+ Scenarios actively used by `reporting/test/request/index.test.js`:
26
+
27
+ | Release | Scenario | What it covers |
28
+ | ---------------- | ----------------- | ------------------------------------------------------------------ |
29
+ | `2026-04-23` | `0001-empty-page` | Plain page load with no third-party resources β€” `requestStats` must stay empty. |
30
+ | `2026-04-23` | `0002-3rd-party` | Page with a single third-party script; verifies detection + the `wtm.attrack.tp_events` report shape. |
31
+ | `2026-04-23` | `0004-ping` | Navigator `sendBeacon`/ping endpoints (non-XHR background request). |
32
+ | `2026-04-23` | `0005-preload` | `<link rel=preload>` triggers the tracker path through a different webRequest ordering. |
33
+ | `2026-04-23` | `0008-navigation` | Two successive navigations on the same tab; each page's trackers must be reported to the right page hostname. |
34
+
35
+ The `2026-04-23` release also ships Chromium recordings for scenarios
36
+ not yet wired into the test suite: `0003-prefetch`, `0006-preconnect`,
37
+ `0007-prerender`, `0009-beacon` β€” useful targets for exercising the
38
+ document-centric attribution paths.
39
+
40
+ Earlier releases (`2024-08-02`, `2024-08-02-1`, `2024-08-02-2`,
41
+ `2024-09-27`, `2024-09-30`) remain available via the on-demand
42
+ download path and are referenced by tests pinned to them.
43
+
44
+ ## Related: `../snapshots/`
45
+
46
+ A separate fixture set used only by the `snapshots` `describe` block in
47
+ `reporting/test/request/index.test.js`. Each `snapshots/<N>/` contains:
48
+
49
+ - `events.log.br` β€” brotli-compressed event stream (replayed by `playSnapshotScenario`)
50
+ - `snapshot.json` β€” expected telemetry messages after replay
51
+
52
+ Approximate content (by inspection of `tps` keys):
53
+
54
+ | Snapshot | Site | Notes |
55
+ | -------- | ------------- | -------------------------------------------------------------- |
56
+ | `0001` | onet.pl | Polish news portal, ~160 third-party domains. |
57
+ | `0002` | onet.pl | Shorter session, ~94 third parties. |
58
+ | `0003` | soundcloud.com| Stream playback, CDN + Statsig + OneTrust. |
59
+ | `0004` | soundcloud.com| Smaller session. |
60
+ | `0005` | nike.com | E-commerce, bluecore + doubleclick + bing. |
61
+ | `0006` | nike.com | Variant session. |
62
+
63
+ The snapshot test replays each events stream twice β€” the second time with
64
+ URL rewrites (`onet.pl→wp.pl`, `soundcloud.com→google.com`,
65
+ `nike.com→adidas.com`) so the token-telemetry code sees the same trackers
66
+ on a different domain, which is needed to trigger quorum-based reporting.
67
+
68
+ ## Re-recording snapshots
69
+
70
+ When a change in `src/request/` legitimately shifts the telemetry output,
71
+ re-record the expected snapshots:
72
+
73
+ ```
74
+ npm --workspace=reporting run test.unit.request.record
75
+ ```
76
+
77
+ Then `git diff reporting/snapshots/` and commit the expected changes
78
+ alongside the source change. The record step is idempotent β€” running it
79
+ twice produces byte-identical files.
@@ -11,7 +11,7 @@
11
11
  */
12
12
 
13
13
  // This global provides an API like an ES Map but will sync
14
- // with local storage from time to time. That is done to prevent
14
+ // with session storage from time to time. That is done to prevent
15
15
  // the loss of all stats when the browser terminates the execution
16
16
  // context (background script or service worker).
17
17
  export default class ChromeStorageMap {
@@ -34,7 +34,7 @@ export default class ChromeStorageMap {
34
34
  this.maxEntries = maxEntries;
35
35
 
36
36
  // Make sure old entries that were not cleaned up are eventually
37
- // removed. Otherwise, we could exceed the local storage quota.
37
+ // removed. Otherwise, we could exceed the session storage quota.
38
38
  // Plus, when the maps get big, serializing and deserializing
39
39
  // may become expensive. If the actively triggered clean up works,
40
40
  // there should be no need to make this expiration too aggressive.
@@ -1,2 +1,42 @@
1
- Please add you spec to `index.js`.
2
- We do that (instead of listing files in karma config) to generate a single bundle.
1
+ # reporting/test
2
+
3
+ Two test suites live here, distinguished by filename suffix.
4
+
5
+ ## Node (mocha, sinon-chrome) β€” fast
6
+
7
+ - Pattern: `*.test.js`
8
+ - Setup: `setup.unit.js`
9
+ - All: `npm --workspace=reporting run test.unit`
10
+ - Request subset: `npm --workspace=reporting run test.unit.request`
11
+ - Watch: `npm --workspace=reporting run test.unit.watch`
12
+
13
+ Prefer this suite for request-pipeline work β€” seconds vs. minutes.
14
+
15
+ ## Browser (karma, headless Chrome) β€” covers DOM/CSSOM paths
16
+
17
+ - Pattern: `*.spec.js`
18
+ - Setup: `setup.js`
19
+ - Entry bundles: `test/index.js` (full) or `test/request.js` (subset)
20
+ - All: `npm --workspace=reporting run test`
21
+ - Request subset: `npm --workspace=reporting run test.karma.request`
22
+
23
+ New karma specs must be added to `index.js` (or `request.js` for the
24
+ request subset) β€” karma bundles a single entry with rollup, so a spec
25
+ that isn't imported there will not run.
26
+
27
+ ## Re-recording request snapshots
28
+
29
+ `request/index.test.js` has a `snapshots` block that replays recorded
30
+ event streams (under `../snapshots/`) and asserts the emitted telemetry
31
+ matches `snapshot.json`. When a source change legitimately shifts the
32
+ output:
33
+
34
+ ```
35
+ npm --workspace=reporting run test.unit.request.record
36
+ ```
37
+
38
+ Sets `RECORD_SNAPSHOT=1`; inspect `git diff reporting/snapshots/` and
39
+ commit the expected changes alongside the source change. The record
40
+ step is idempotent β€” re-running produces byte-identical files.
41
+
42
+ See `../scenarios/README.md` for the scenario + snapshot index.
@@ -72,7 +72,10 @@ export function recordSnapshot(name, messages) {
72
72
  }
73
73
  }
74
74
  const sortedMessages = sortObjectKeys(messages);
75
- fs.writeFileSync(snapshotPath, JSON.stringify(sortedMessages, null, 2));
75
+ fs.writeFileSync(
76
+ snapshotPath,
77
+ JSON.stringify(sortedMessages, null, 2) + '\n',
78
+ );
76
79
  }
77
80
 
78
81
  export function readSnapshot(name) {
@@ -171,7 +171,7 @@ describe('RequestReporter', function () {
171
171
  it('detects no 3rd parties', async function () {
172
172
  const { seenTabIds } = await playScenario(chrome, {
173
173
  scenarioName: this.test.parent.title,
174
- scenarioRelease: '2024-08-02',
174
+ scenarioRelease: '2026-04-23',
175
175
  });
176
176
  await clock.runToLast();
177
177
  expect(
@@ -191,7 +191,7 @@ describe('RequestReporter', function () {
191
191
  it('detects 3rd parties', async function () {
192
192
  const { seenTabIds } = await playScenario(chrome, {
193
193
  scenarioName: this.test.parent.title,
194
- scenarioRelease: '2024-08-02',
194
+ scenarioRelease: '2026-04-23',
195
195
  });
196
196
  await clock.runToLast();
197
197
  expect(
@@ -209,7 +209,7 @@ describe('RequestReporter', function () {
209
209
  it('reports 3rd parties', async function () {
210
210
  const { seenTabIds } = await playScenario(chrome, {
211
211
  scenarioName: this.test.parent.title,
212
- scenarioRelease: '2024-08-02',
212
+ scenarioRelease: '2026-04-23',
213
213
  });
214
214
  await clock.runToLast();
215
215
  const eventPromise = new Promise((resolve) =>
@@ -226,17 +226,40 @@ describe('RequestReporter', function () {
226
226
  });
227
227
  });
228
228
 
229
- context('0004-ping', function () {
230
- it('reports pings', async function () {
229
+ context('0003-prefetch', function () {
230
+ it('reports prefetched 3rd parties', async function () {
231
+ const { seenTabIds } = await playScenario(chrome, {
232
+ scenarioName: this.test.parent.title,
233
+ scenarioRelease: '2026-04-23',
234
+ });
235
+ await clock.runToLast();
231
236
  const eventPromise = new Promise((resolve) =>
232
237
  communicationEmitter.once('send', resolve),
233
238
  );
234
- await playScenario(chrome, {
239
+ // force stage all pages
240
+ seenTabIds.forEach((tabId) => chrome.tabs.onRemoved.dispatch(tabId));
241
+ await clock.runToLast();
242
+ const event = await eventPromise;
243
+ expect(event).to.deep.include({
244
+ action: 'wtm.attrack.tp_events',
245
+ });
246
+ expect(event.payload.data[0].tps).to.have.keys(['subdomain.localhost']);
247
+ });
248
+ });
249
+
250
+ context('0004-ping', function () {
251
+ it('reports pings', async function () {
252
+ const { seenTabIds } = await playScenario(chrome, {
235
253
  scenarioName: this.test.parent.title,
236
- scenarioRelease: '2024-08-02-1',
254
+ scenarioRelease: '2026-04-23',
237
255
  });
238
256
  await clock.runToLast();
239
- // first tp_event from the page that sent ping
257
+ const eventPromise = new Promise((resolve) =>
258
+ communicationEmitter.once('send', resolve),
259
+ );
260
+ // force stage all pages
261
+ seenTabIds.forEach((tabId) => chrome.tabs.onRemoved.dispatch(tabId));
262
+ await clock.runToLast();
240
263
  const event = await eventPromise;
241
264
  expect(event).to.deep.include({
242
265
  action: 'wtm.attrack.tp_events',
@@ -249,7 +272,7 @@ describe('RequestReporter', function () {
249
272
  it('reports 3rd parties', async function () {
250
273
  const { seenTabIds } = await playScenario(chrome, {
251
274
  scenarioName: this.test.parent.title,
252
- scenarioRelease: '2024-08-02',
275
+ scenarioRelease: '2026-04-23',
253
276
  });
254
277
  await clock.runToLast();
255
278
  const eventPromise = new Promise((resolve) =>
@@ -266,6 +289,43 @@ describe('RequestReporter', function () {
266
289
  });
267
290
  });
268
291
 
292
+ context('0006-preconnect', function () {
293
+ it('does not attribute preconnect hints as 3rd parties', async function () {
294
+ const { seenTabIds } = await playScenario(chrome, {
295
+ scenarioName: this.test.parent.title,
296
+ scenarioRelease: '2026-04-23',
297
+ });
298
+ await clock.runToLast();
299
+ expect(reporter.pageStore.checkIfEmpty()).to.be.false;
300
+ expect(seenTabIds).to.have.property('size', 1);
301
+ const tabId = seenTabIds.values().next().value;
302
+ const tab = reporter.pageStore.getPageForRequest({ tabId, frameId: 0 });
303
+ // preconnect opens a socket but fires no webRequest, so no
304
+ // third-party counters should accumulate.
305
+ expect(tab.requestStats).to.be.empty;
306
+ });
307
+ });
308
+
309
+ context('0007-prerender', function () {
310
+ it('keeps prerender stats off the visible page', async function () {
311
+ const { seenTabIds } = await playScenario(chrome, {
312
+ scenarioName: this.test.parent.title,
313
+ scenarioRelease: '2026-04-23',
314
+ });
315
+ await clock.runToLast();
316
+ expect(reporter.pageStore.checkIfEmpty()).to.be.false;
317
+ // The visible localhost:8080 page has no third parties; the
318
+ // prerendered document lives on a separate tab and is not
319
+ // counted against the one the user is looking at.
320
+ const visibleTabId = seenTabIds.values().next().value;
321
+ const tab = reporter.pageStore.getPageForRequest({
322
+ tabId: visibleTabId,
323
+ frameId: 0,
324
+ });
325
+ expect(tab.requestStats).to.be.empty;
326
+ });
327
+ });
328
+
269
329
  context('0008-navigation', function () {
270
330
  it('reports 3rd parties', async function () {
271
331
  const eventPromise1 = new Promise((resolve) =>
@@ -273,7 +333,7 @@ describe('RequestReporter', function () {
273
333
  );
274
334
  const { seenTabIds } = await playScenario(chrome, {
275
335
  scenarioName: this.test.parent.title,
276
- scenarioRelease: '2024-08-02-2',
336
+ scenarioRelease: '2026-04-23',
277
337
  });
278
338
  await clock.runToLast();
279
339
  const event1 = await eventPromise1;
@@ -299,6 +359,39 @@ describe('RequestReporter', function () {
299
359
  });
300
360
  });
301
361
 
362
+ context('0009-beacon', function () {
363
+ // SKIP: passes only on the documentId-centric attribution
364
+ // branch. User searches on search.localhost, clicks through to
365
+ // landing.localhost, and the search document fires two beacons
366
+ // to beacon.localhost (click handler + pagehide). Each beacon
367
+ // webRequest carries the search document's documentId, so
368
+ // correct attribution keeps beacon.localhost on search's
369
+ // tp_events. Main's tabId+previous-chain logic misattributes
370
+ // the beacons to a staged-and-dead page, silently dropping
371
+ // them.
372
+ it.skip('attributes late beacon to the source document', async function () {
373
+ const events = [];
374
+ communicationEmitter.on('send', (msg) => {
375
+ if (msg.action === 'wtm.attrack.tp_events') {
376
+ events.push(msg);
377
+ }
378
+ });
379
+ const { seenTabIds } = await playScenario(chrome, {
380
+ scenarioName: this.test.parent.title,
381
+ scenarioRelease: '2026-04-23',
382
+ });
383
+ await clock.runToLast();
384
+ // Force-stage remaining pages so any held documents flush.
385
+ seenTabIds.forEach((tabId) => chrome.tabs.onRemoved.dispatch(tabId));
386
+ await clock.runToLast();
387
+ const emittedBeacon = events.some((e) =>
388
+ Object.keys(e.payload.data[0].tps).includes('beacon.localhost'),
389
+ );
390
+ expect(emittedBeacon, 'beacon.localhost must land in some tp_events')
391
+ .to.be.true;
392
+ });
393
+ });
394
+
302
395
  context('snapshots', function () {
303
396
  this.timeout(10000);
304
397
 
@@ -335,10 +428,14 @@ describe('RequestReporter', function () {
335
428
  .NEW_ENTRY_MIN_AGE,
336
429
  );
337
430
 
338
- // eslint-disable-next-line no-undef
339
- if (process.argv.includes('--record-snapshot')) {
431
+ /* eslint-disable no-undef */
432
+ if (
433
+ process.argv.includes('--record-snapshot') ||
434
+ process.env.RECORD_SNAPSHOT
435
+ ) {
340
436
  recordSnapshot(snapshotName, messages);
341
437
  }
438
+ /* eslint-enable no-undef */
342
439
 
343
440
  const snapshot = await readSnapshot(snapshotName);
344
441
  expect(messages).to.have.lengthOf(snapshot.length);
@@ -0,0 +1,14 @@
1
+ import './setup.js';
2
+
3
+ import './request/qs-whitelist2.spec.js';
4
+ import './request/hash/index.spec.js';
5
+ import './request/database.spec.js';
6
+ import './request/index.spec.js';
7
+
8
+ import './request/utils/tldts.spec.js';
9
+ import './request/utils/bloom-filter-packed.spec.js';
10
+ import './request/utils/chrome-storage-map.spec.js';
11
+ import './request/utils/utils.spec.js';
12
+
13
+ import './request/steps/check-context.spec.js';
14
+ import './request/steps/oauth-detector.spec.js';