@whotracksme/reporting 11.1.1 → 12.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.
@@ -0,0 +1,187 @@
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
+ },
24
+ });
25
+
26
+ const e2eDir = path.dirname(fileURLToPath(import.meta.url));
27
+
28
+ function resolveScenario(nameOrPath) {
29
+ const candidates = [
30
+ nameOrPath,
31
+ path.join(e2eDir, 'scenarios', nameOrPath),
32
+ path.join(e2eDir, 'scenarios', `${nameOrPath}.json`),
33
+ ];
34
+ const found = candidates.find((c) => fs.existsSync(c));
35
+ if (!found) {
36
+ const available = fs
37
+ .readdirSync(path.join(e2eDir, 'scenarios'))
38
+ .filter((f) => f.endsWith('.json'))
39
+ .map((f) => f.replace(/\.json$/, ''));
40
+ console.error(
41
+ `unknown scenario "${nameOrPath}". Available: ${available.join(', ')}`,
42
+ );
43
+ process.exit(2);
44
+ }
45
+ return found;
46
+ }
47
+
48
+ async function hub(method, route, body) {
49
+ const response = await fetch(`${values.hub}${route}`, {
50
+ method,
51
+ headers:
52
+ method === 'POST' ? { 'Content-Type': 'application/json' } : undefined,
53
+ body: body ? JSON.stringify(body) : undefined,
54
+ });
55
+ const text = await response.text();
56
+ let parsed;
57
+ try {
58
+ parsed = JSON.parse(text);
59
+ } catch {
60
+ parsed = { raw: text };
61
+ }
62
+ return { status: response.status, body: parsed };
63
+ }
64
+
65
+ async function command(name, args = {}, timeout) {
66
+ const { status, body } = await hub('POST', '/cmd', { name, args, timeout });
67
+ if (status !== 200) {
68
+ throw new Error(`${name} failed: ${body.error || status}`);
69
+ }
70
+ return body.result;
71
+ }
72
+
73
+ const health = await hub('GET', '/health').catch(() => null);
74
+ if (!health || health.status !== 200) {
75
+ console.error(
76
+ `hub is not reachable at ${values.hub} — start it with:\n npm --workspace=reporting run e2e.hub`,
77
+ );
78
+ process.exit(2);
79
+ }
80
+ if (!health.body.extensionConnected) {
81
+ console.error(
82
+ 'hub is up but the extension has not connected.\n' +
83
+ 'Check that the example extension is loaded and enabled, then reload it.',
84
+ );
85
+ process.exit(2);
86
+ }
87
+
88
+ const scenarioFile = resolveScenario(positionals[0] || 'smoke');
89
+ const scenario = JSON.parse(fs.readFileSync(scenarioFile, 'utf8'));
90
+
91
+ console.error(`scenario: ${scenario.name} (${path.basename(scenarioFile)})`);
92
+
93
+ if (!values['keep-messages']) {
94
+ await hub('POST', '/messages/clear');
95
+ }
96
+ const startSeq = (await hub('GET', '/health')).body.seq;
97
+
98
+ const STEP_OPTIONS = ['timeout', 'continueOnError'];
99
+
100
+ const trace = [];
101
+ for (const [index, step] of (scenario.steps || []).entries()) {
102
+ const entry = Object.entries(step).find(
103
+ ([key]) => !STEP_OPTIONS.includes(key),
104
+ );
105
+ if (!entry) {
106
+ console.error(`\nstep ${index + 1} has no command key`);
107
+ process.exitCode = 1;
108
+ break;
109
+ }
110
+ const [name, args] = entry;
111
+ const label = `${index + 1}/${scenario.steps.length} ${name}`;
112
+ process.stderr.write(` ${label} ... `);
113
+ const startedAt = Date.now();
114
+ try {
115
+ const result = await command(name, args ?? {}, step.timeout);
116
+ const took = Date.now() - startedAt;
117
+ process.stderr.write(`ok (${took}ms)\n`);
118
+ trace.push({ step: name, args, result, tookInMs: took });
119
+ } catch (e) {
120
+ process.stderr.write(`FAILED\n`);
121
+ console.error(`\n ${e.message}\n`);
122
+ trace.push({ step: name, args, error: e.message });
123
+ if (step.continueOnError !== true) {
124
+ process.exitCode = 1;
125
+ break;
126
+ }
127
+ }
128
+ }
129
+
130
+ const captured = (await hub('GET', `/messages?since=${startSeq}`)).body
131
+ .messages;
132
+ const events = (await hub('GET', `/events?since=${startSeq}`)).body.events;
133
+ const result = verify(captured, scenario.expect || {});
134
+
135
+ if (values.json) {
136
+ console.log(
137
+ JSON.stringify(
138
+ { scenario: scenario.name, result, captured, trace },
139
+ null,
140
+ 2,
141
+ ),
142
+ );
143
+ } else {
144
+ console.log(`\ncaptured ${captured.length} message(s):`);
145
+ const byAction = {};
146
+ for (const message of captured) {
147
+ const action = message.body?.action || message.body?.type || '<unknown>';
148
+ byAction[action] = (byAction[action] || 0) + 1;
149
+ }
150
+ for (const [action, count] of Object.entries(byAction)) {
151
+ console.log(` ${count}x ${action}`);
152
+ }
153
+
154
+ if (result.ok) {
155
+ console.log('\nPASSED');
156
+ } else {
157
+ console.log(`\nFAILED — ${result.failures.length} problem(s):`);
158
+ for (const failure of result.failures) {
159
+ console.log(` [${failure.kind}] ${failure.detail}`);
160
+ if (failure.sawInstead?.length) {
161
+ console.log(
162
+ ` saw instead: ${JSON.stringify(failure.sawInstead).slice(
163
+ 0,
164
+ 300,
165
+ )}`,
166
+ );
167
+ }
168
+ }
169
+ const interesting = events.filter((e) =>
170
+ ['jobRejected', 'jobFailed', 'jobExpired'].includes(e.event),
171
+ );
172
+ if (interesting.length > 0) {
173
+ console.log('\n job events worth a look:');
174
+ for (const event of interesting.slice(0, 20)) {
175
+ console.log(
176
+ ` ${event.event} ${event.details?.type} ${JSON.stringify(
177
+ event.details?.args || {},
178
+ ).slice(0, 160)}`,
179
+ );
180
+ }
181
+ }
182
+ }
183
+ }
184
+
185
+ if (!result.ok) {
186
+ process.exitCode = 1;
187
+ }
@@ -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
  ]
@@ -14,6 +14,7 @@ import { requireParam, requireInt, lazyInitAsync } from './utils';
14
14
  import { randomBetween } from './random';
15
15
  import { BadJobError } from './errors';
16
16
  import { anonymousHttpGet } from './http';
17
+ import { findSafeCookies } from './doublefetch-unbreak';
17
18
  import parseHtml from './html-parser';
18
19
  import { analyzePageStructure } from './page-structure';
19
20
  import { sanitizeUrl } from './sanitizer';
@@ -311,6 +312,19 @@ export function sanitizeActivity(activity) {
311
312
  return noisyActivity.toFixed(4);
312
313
  }
313
314
 
315
+ // Compatibility layer to deal with known website breakage.
316
+ //
317
+ // TODO: This should come from patterns. For now, start with a hard-coded list.
318
+ function unbreakConfig(url) {
319
+ const { hostname } = new URL(url);
320
+ if (hostname === 'imdb.com' || hostname.endsWith('.imdb.com')) {
321
+ return {
322
+ headers: { Cookie: 'aws-waf-token={{safecookie:aws-waf-token}}' },
323
+ };
324
+ }
325
+ return null;
326
+ }
327
+
314
328
  class CachedPageFetcher {
315
329
  constructor() {
316
330
  this.urlToAsyncPageStructure = new Map();
@@ -332,6 +346,15 @@ class CachedPageFetcher {
332
346
  return from.origin === to.origin && from.pathname === to.pathname;
333
347
  };
334
348
 
349
+ let unbreak = unbreakConfig(url);
350
+ if (unbreak) {
351
+ logger.debug('[double-fetch] fixes found:', url, '->', unbreak);
352
+ unbreak = {
353
+ ...unbreak,
354
+ safecookie: await findSafeCookies(url, unbreak),
355
+ };
356
+ }
357
+
335
358
  let html;
336
359
  try {
337
360
  html = await anonymousHttpGet(url, {
@@ -340,6 +363,7 @@ class CachedPageFetcher {
340
363
  treat429AsPermanentError: true,
341
364
  downloadLimit: this.downloadLimit,
342
365
  allowedContentTypes: ALLOW_HTML_AND_TEXT,
366
+ ...unbreak,
343
367
  });
344
368
  } catch (e) {
345
369
  if (e.isPermanentError) {