@whotracksme/reporting 7.1.0 → 7.3.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,28 @@
1
+ # v7.3.0 (Wed May 21 2025)
2
+
3
+ #### 🚀 Enhancement
4
+
5
+ - Added missing header overwrite in doublefetch [#160](https://github.com/whotracksme/webextension-packages/pull/160) ([@philipp-classen](https://github.com/philipp-classen))
6
+
7
+ #### Authors: 1
8
+
9
+ - Philipp Claßen ([@philipp-classen](https://github.com/philipp-classen))
10
+
11
+ ---
12
+
13
+ # v7.2.0 (Mon May 19 2025)
14
+
15
+ #### 🚀 Enhancement
16
+
17
+ - Initial support for dynamic double-fetch [#158](https://github.com/whotracksme/webextension-packages/pull/158) ([@philipp-classen](https://github.com/philipp-classen) [@chrmod](https://github.com/chrmod))
18
+
19
+ #### Authors: 2
20
+
21
+ - Krzysztof Modras ([@chrmod](https://github.com/chrmod))
22
+ - Philipp Claßen ([@philipp-classen](https://github.com/philipp-classen))
23
+
24
+ ---
25
+
1
26
  # v7.1.0 (Mon May 19 2025)
2
27
 
3
28
  #### 🚀 Enhancement
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "7.1.0",
3
+ "version": "7.3.0",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
@@ -131,8 +131,10 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
131
131
  }
132
132
  });
133
133
 
134
- urlReporter.init().catch(console.error);
135
- requestReporter.init().catch(console.error);
134
+ (async () => {
135
+ await urlReporter.init();
136
+ await requestReporter.init();
137
+ })();
136
138
 
137
139
  globalThis.urlReporter = urlReporter;
138
140
  globalThis.requestReporter = requestReporter;
@@ -7,6 +7,9 @@
7
7
  "version_name": "1.0.0",
8
8
  "description": "",
9
9
  "permissions": [
10
+ "declarativeNetRequest",
11
+ "declarativeNetRequestWithHostAccess",
12
+ "offscreen",
10
13
  "webNavigation",
11
14
  "webRequest",
12
15
  "tabs",
File without changes
@@ -30,6 +30,7 @@
30
30
  "karma-sinon": "^1.0.5",
31
31
  "mocha": "^10.7.3",
32
32
  "rollup": "^2.79.1",
33
+ "rollup-plugin-copy": "^3.5.0",
33
34
  "rollup-plugin-polyfill-node": "^0.8.0",
34
35
  "rollup-plugin-sourcemaps": "^0.6.3",
35
36
  "sinon": "^15.2.0",
@@ -1,4 +1,5 @@
1
1
  const commonConfig = require('./rollup.common-config.cjs');
2
+ const copy = require('rollup-plugin-copy');
2
3
 
3
4
  module.exports = [
4
5
  {
@@ -17,4 +18,19 @@ module.exports = [
17
18
  file: 'example/content.bundle.js',
18
19
  },
19
20
  },
21
+ {
22
+ ...commonConfig,
23
+ input: 'src/offscreen/doublefetch/index.js',
24
+ output: {
25
+ ...commonConfig.output,
26
+ file: 'example/offscreen/doublefetch/index.js',
27
+ },
28
+ plugins: [
29
+ copy({
30
+ targets: [
31
+ { src: 'src/offscreen/doublefetch/index.html', dest: 'example/offscreen/doublefetch/' },
32
+ ]
33
+ })
34
+ ]
35
+ },
20
36
  ];
@@ -57,6 +57,11 @@ export class UnableToOverrideHeadersError extends PermanentError {}
57
57
  */
58
58
  export class MultiStepDoublefetchNotSupportedError extends PermanentError {}
59
59
 
60
+ /**
61
+ * If the platform lacks the required APIs to support dynamic request doublefetch.
62
+ */
63
+ export class DynamicDoublefetchNotSupportedError extends PermanentError {}
64
+
60
65
  /**
61
66
  * Thrown when requests failed, but where the client can try to
62
67
  * repeat the request without modification (e.g. timeouts will
@@ -16,14 +16,50 @@ import {
16
16
  RateLimitedByServerError,
17
17
  UnableToOverrideHeadersError,
18
18
  MultiStepDoublefetchNotSupportedError,
19
+ DynamicDoublefetchNotSupportedError,
19
20
  } from './errors';
20
- import { split0 } from './utils';
21
+ import { requireString, split0 } from './utils';
21
22
  import SeqExecutor from './seq-executor';
23
+ import { randomBetween } from './random';
22
24
 
23
25
  const SECOND = 1000;
24
26
 
25
27
  // This ID must not be used by other parts of the extension.
26
- const RESERVED_DNR_RULE_ID = 1333;
28
+ const RESERVED_DNR_RULE_ID_HEADER_OVERRIDE = 1333;
29
+ const RESERVED_DNR_RULE_ID_OFFSCREEN = 1334;
30
+
31
+ /**
32
+ * Depending on the context, there are different ways how requests are being
33
+ * triggered. For instance, the normal one is to use the fetch API; but
34
+ * with dynamic rendering using offscreen, it will be technically triggered
35
+ * from an iframe. That impacts how APIs should be later interpreted.
36
+ */
37
+ const REQUEST_TYPE = {
38
+ FETCH_API: Symbol('FETCH_API'),
39
+ IFRAME: Symbol('IFRAME'),
40
+ };
41
+
42
+ // maps our REQUEST_TYPE to the type used in the webRequestAPI
43
+ function matchesWebRequestApiType(requestType, webRequestApiType) {
44
+ if (requestType === REQUEST_TYPE.FETCH_API) {
45
+ return webRequestApiType === 'xmlhttprequest';
46
+ }
47
+ if (requestType === REQUEST_TYPE.IFRAME) {
48
+ return webRequestApiType === 'sub_frame';
49
+ }
50
+ throw new Error(`Unexpected requestType: ${requestType}`);
51
+ }
52
+
53
+ // maps our REQUEST_TYPE to the resource Type array used by the DNR API
54
+ function requestTypeToDNRResourceTypes(requestType) {
55
+ if (requestType === REQUEST_TYPE.FETCH_API) {
56
+ return ['xmlhttprequest'];
57
+ }
58
+ if (requestType === REQUEST_TYPE.IFRAME) {
59
+ return ['sub_frame'];
60
+ }
61
+ throw new Error(`Unexpected requestType: ${requestType}`);
62
+ }
27
63
 
28
64
  function getExtensionDomain() {
29
65
  getExtensionDomain.cached =
@@ -31,6 +67,66 @@ function getExtensionDomain() {
31
67
  return getExtensionDomain.cached;
32
68
  }
33
69
 
70
+ function identicalExceptForSearchParams(url1, url2) {
71
+ if (url1 === url2) {
72
+ return true;
73
+ }
74
+ const x = new URL(url1);
75
+ const y = new URL(url2);
76
+ x.search = '';
77
+ y.search = '';
78
+ return x.toString() === y.toString();
79
+ }
80
+
81
+ // A list of safe URL parameter modifier operations.
82
+ // Rule of thumb:
83
+ // * builtins to remove or randomize should be safe.
84
+ // * replacing by arbitrary values could lead to unintended effects
85
+ // (e.g. for sites that can be redirected via URL parameters)
86
+ const BUILTIN_PARAM_MODIFIERS = {
87
+ /**
88
+ * Replaced the old value with a random one (10-20 alpha-numeric characters).
89
+ */
90
+ random1: (oldValue) => {
91
+ requireString(oldValue);
92
+
93
+ const length = Math.round(randomBetween(6, 14));
94
+ const array = new Uint8Array(length);
95
+ crypto.getRandomValues(array);
96
+
97
+ let result = '';
98
+ const characters =
99
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.- ';
100
+ for (let i = 0; i < length; i++) {
101
+ result += characters[array[i] % characters.length];
102
+ }
103
+ return result.trim();
104
+ },
105
+ };
106
+
107
+ function createLocalUrl(url, params) {
108
+ const paramEntries = Object.entries(params);
109
+ if (paramEntries.length === 0) {
110
+ return url;
111
+ }
112
+
113
+ const modifiedUrl = new URL(url);
114
+ for (const [operation, queryKeyNames] of paramEntries) {
115
+ const func = BUILTIN_PARAM_MODIFIERS[operation];
116
+ if (!func) {
117
+ throw new Error(`Unsupported operation: <<${operation}>>`);
118
+ }
119
+ const { searchParams } = modifiedUrl;
120
+ for (const key of queryKeyNames) {
121
+ const val = searchParams.get(key);
122
+ if (val !== null) {
123
+ searchParams.set(key, func(val));
124
+ }
125
+ }
126
+ }
127
+ return modifiedUrl.toString();
128
+ }
129
+
34
130
  /**
35
131
  * Note: 429 (too many requests) is intentionally not included in the list.
36
132
  * Even though it is by definition a temporary error, it depends on the context
@@ -47,6 +143,29 @@ const httpStatusCodesThatShouldBeRetried = [
47
143
  599, // Network Connect Timeout Error
48
144
  ];
49
145
 
146
+ // Overwrites the headers of the request to the given URL.
147
+ // It automatically selects the mechanism (e.g. webRequestAPI, DNR)
148
+ // based on the available APIs.
149
+ //
150
+ // Returns a cleanup callback to undo the changes.
151
+ async function headerOverride(params) {
152
+ const { headers } = params;
153
+ if (!headers || Object.keys(headers).length === 0) {
154
+ return () => {};
155
+ }
156
+
157
+ if (
158
+ chrome?.webRequest?.onBeforeSendHeaders &&
159
+ chrome.runtime.getManifest().permissions.includes('webRequestBlocking')
160
+ ) {
161
+ return headerOverrideViaWebRequestAPI(params);
162
+ } else if (chrome?.declarativeNetRequest?.updateSessionRules) {
163
+ return await headerOverrideViaDNR(params);
164
+ } else {
165
+ throw new UnableToOverrideHeadersError();
166
+ }
167
+ }
168
+
50
169
  // The following code overwrite the headers of the request.
51
170
  // Note that "fetch" allows to overwrite headers in a simple declarative way,
52
171
  // but unfortunately it is limited. For example, it is not possible to
@@ -59,13 +178,13 @@ const httpStatusCodesThatShouldBeRetried = [
59
178
  // side-effects. To mitigate the risk, uninstall the handler at the first
60
179
  // opportunity: either if it is called or if the request finished
61
180
  // (and we know the handle will never be called).
62
- function headerOverrideViaWebRequestAPI(url, headers) {
181
+ function headerOverrideViaWebRequestAPI({ url, headers, requestType }) {
63
182
  let uninstallHandler;
64
183
  let webRequestHandler = (details) => {
65
184
  if (
66
185
  details.url !== url ||
67
- details.type !== 'xmlhttprequest' ||
68
- details.method !== 'GET'
186
+ details.method !== 'GET' ||
187
+ !matchesWebRequestApiType(requestType, details.type)
69
188
  ) {
70
189
  // does that match the request that we intended to trigger
71
190
  return {};
@@ -114,14 +233,14 @@ function headerOverrideViaWebRequestAPI(url, headers) {
114
233
  }
115
234
 
116
235
  // Like headerOverrideViaWebRequestAPI, but using the DNR API.
117
- async function headerOverrideViaDNR(url, headers) {
236
+ async function headerOverrideViaDNR({ url, headers, requestType }) {
118
237
  const requestHeaders = Object.entries(headers).map(([header, value]) => ({
119
238
  header,
120
239
  operation: 'set',
121
240
  value,
122
241
  }));
123
242
  const rule = {
124
- id: RESERVED_DNR_RULE_ID,
243
+ id: RESERVED_DNR_RULE_ID_HEADER_OVERRIDE,
125
244
  priority: 1,
126
245
  action: {
127
246
  type: 'modifyHeaders',
@@ -129,26 +248,133 @@ async function headerOverrideViaDNR(url, headers) {
129
248
  },
130
249
  condition: {
131
250
  urlFilter: url,
132
- resourceTypes: ['xmlhttprequest'],
251
+ resourceTypes: requestTypeToDNRResourceTypes(requestType),
133
252
  initiatorDomains: [getExtensionDomain()],
134
253
  },
135
254
  };
255
+
136
256
  logger.debug('Installing temporary DNR rule for URL:', url);
137
- await chrome.declarativeNetRequest.updateSessionRules({
138
- addRules: [rule],
139
- });
257
+ const cleanup = await addDNRSessionRule(rule);
258
+
140
259
  return () => {
141
260
  logger.debug('Removing temporary DNR rule for URL:', url);
142
- chrome.declarativeNetRequest
261
+ return cleanup();
262
+ };
263
+ }
264
+
265
+ async function addDNRSessionRule(rule) {
266
+ try {
267
+ await chrome.declarativeNetRequest.updateSessionRules({ addRules: [rule] });
268
+ } catch (e) {
269
+ try {
270
+ logger.warn(
271
+ 'Unable to install DNR rule. Trying to delete rule first:',
272
+ rule,
273
+ e,
274
+ );
275
+ await chrome.declarativeNetRequest.updateSessionRules({
276
+ removeRuleIds: [rule.id],
277
+ });
278
+ } catch (e2) {
279
+ logger.warn('Retry not possible (unable to remove DNR rule):', rule, e2);
280
+ throw e;
281
+ }
282
+
283
+ logger.debug('Second attempt to install DNR rule:', rule);
284
+ await chrome.declarativeNetRequest.updateSessionRules({
285
+ addRules: [rule],
286
+ });
287
+ logger.debug('Succeed in install DNR rule on the second attempt:', rule);
288
+ }
289
+
290
+ return () => {
291
+ return chrome.declarativeNetRequest
143
292
  .updateSessionRules({
144
293
  removeRuleIds: [rule.id],
145
294
  })
146
295
  .catch((e) => {
147
- logger.warn('Failed to remove DNR rule', e);
296
+ logger.error('cleanup failed: unable to remove DNR rule:', rule, e);
148
297
  });
149
298
  };
150
299
  }
151
300
 
301
+ async function tryCloseOffscreenDocument() {
302
+ try {
303
+ await chrome.offscreen.closeDocument();
304
+ } catch (e) {
305
+ if (e.message === 'No current offscreen document.') {
306
+ logger.debug('offscreen document already closed.');
307
+ } else {
308
+ throw e;
309
+ }
310
+ }
311
+ }
312
+
313
+ const OFFSCREEN_DOCUMENT_PATH = 'offscreen/doublefetch/index.html';
314
+
315
+ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
316
+ const cleanups = [];
317
+ try {
318
+ const domain = new URL(url).hostname;
319
+ const rule = {
320
+ id: RESERVED_DNR_RULE_ID_OFFSCREEN,
321
+ condition: {
322
+ initiatorDomains: [chrome.runtime.id],
323
+ requestDomains: [domain],
324
+ resourceTypes: ['sub_frame'],
325
+ },
326
+ action: {
327
+ type: 'modifyHeaders',
328
+ responseHeaders: [
329
+ { header: 'X-Frame-Options', operation: 'remove' },
330
+ { header: 'Frame-Options', operation: 'remove' },
331
+ ],
332
+ },
333
+ };
334
+
335
+ const undoDNRChange = await addDNRSessionRule(rule);
336
+ cleanups.push(undoDNRChange);
337
+
338
+ const undoHeaderOverride = await headerOverride({
339
+ headers,
340
+ url,
341
+ requestType: REQUEST_TYPE.IFRAME,
342
+ });
343
+ cleanups.push(undoHeaderOverride);
344
+
345
+ const offscreenUrl = chrome.runtime.getURL(OFFSCREEN_DOCUMENT_PATH);
346
+ const existingContexts = await chrome.runtime.getContexts({
347
+ contextTypes: ['OFFSCREEN_DOCUMENT'],
348
+ documentUrls: [offscreenUrl],
349
+ });
350
+ if (existingContexts.length > 0) {
351
+ // TODO: what do do here? Normally, it should not happen in our setup.
352
+ // Maybe close the document and continue?
353
+ logger.warn('Existing context found:', existingContexts);
354
+ throw new Error('Unexpected: existing context found');
355
+ }
356
+
357
+ await chrome.offscreen.createDocument({
358
+ url: OFFSCREEN_DOCUMENT_PATH,
359
+ reasons: ['IFRAME_SCRIPTING'],
360
+ justification: 'credentialless iframe',
361
+ });
362
+ cleanups.push(() => tryCloseOffscreenDocument());
363
+
364
+ return await asyncCallback();
365
+ } finally {
366
+ await Promise.all(
367
+ cleanups.map(async (x) => {
368
+ try {
369
+ await x();
370
+ } catch (e) {
371
+ logger.warn('Unexpected error while cleaning up resources:', e);
372
+ }
373
+ }),
374
+ );
375
+ }
376
+ }
377
+
152
378
  // Note: the parameters are almost identical to "anonymousHttpGet"
153
379
  // with the exception that "step" is not defined. The implementation
154
380
  // here is only a single request, not a chain of requests.
@@ -190,22 +416,12 @@ async function singleHttpGetStep(url, params = {}) {
190
416
  }
191
417
 
192
418
  try {
193
- // optional cleanup operation that will be run after the request is completed
194
- let cleanup = () => {};
195
- if (headers && Object.keys(headers).length > 0) {
196
- if (
197
- chrome?.webRequest?.onBeforeSendHeaders &&
198
- chrome.runtime.getManifest().permissions.includes('webRequestBlocking')
199
- ) {
200
- cleanup = headerOverrideViaWebRequestAPI(url, headers);
201
- } else if (chrome?.declarativeNetRequest?.updateSessionRules) {
202
- cleanup = await headerOverrideViaDNR(url, headers);
203
- } else {
204
- throw new UnableToOverrideHeadersError();
205
- }
206
- }
207
-
208
419
  let response;
420
+ const undoHeaderOverride = await headerOverride({
421
+ headers,
422
+ url,
423
+ requestType: REQUEST_TYPE.FETCH_API,
424
+ });
209
425
  try {
210
426
  response = await fetch(url, options);
211
427
  } catch (e) {
@@ -213,8 +429,9 @@ async function singleHttpGetStep(url, params = {}) {
213
429
  cause: e,
214
430
  });
215
431
  } finally {
216
- cleanup();
432
+ await undoHeaderOverride();
217
433
  }
434
+
218
435
  if (
219
436
  response.status === 0 &&
220
437
  (response.type == 'opaqueredirect' || response.type == 'opaque')
@@ -335,71 +552,232 @@ const LOCK = new SeqExecutor();
335
552
  * "SOCS=CAESEwgDEgk0ODE3Nzk3MjQaAmVuIAEaBgiA_LyaBg"
336
553
  * (Maybe there is a way to generalize?)
337
554
  */
338
- export async function anonymousHttpGet(url, params = {}) {
555
+ export async function anonymousHttpGet(originalUrl, params = {}) {
339
556
  return LOCK.run(async () => {
340
557
  const { steps = [], ...sharedParams } = params;
341
558
  if (steps.length === 0) {
342
- return singleHttpGetStep(url, sharedParams);
559
+ return singleHttpGetStep(originalUrl, sharedParams);
343
560
  }
344
561
  if (!chrome?.webRequest?.onHeadersReceived) {
345
562
  throw new MultiStepDoublefetchNotSupportedError();
346
563
  }
564
+ const hasDynamicSteps = steps.some((x) => x.dynamic);
565
+ if (hasDynamicSteps && !chrome?.offscreen?.createDocument) {
566
+ throw new DynamicDoublefetchNotSupportedError();
567
+ }
347
568
 
348
569
  // The context that can be queried with the placeholder syntax (e.g.
349
- // "foo={{cookies:bar}"). The context is built from the requests from
350
- // earlier steps. Currently, only cookies are provided, because this
351
- // is a common use case to bypass consent dialogs; if needed we can
352
- // extend it to other values (e.g. HTTP headers).
353
- const ctx = {
354
- cookie: new Map(),
570
+ // "foo={{cookie:bar}}"). The context is built from the requests from
571
+ // earlier steps. For instance, a use case is to bypass consent dialogs
572
+ // by modifying cookies.
573
+ const observer = {
574
+ // to be overwritten later to mark dependencies for the next step:
575
+ // e.g. "ctx.cookie.set('foo', '42')" will trigger onChange('cookie', 'foo', '42')
576
+ onChange: null,
355
577
  };
356
- const handler = (details) => {
357
- for (let header of details.responseHeaders) {
358
- if (header.name.toLowerCase() === 'set-cookie') {
359
- for (const line of header.value.split('\n')) {
360
- const start = line.indexOf('=');
361
- if (start > 0) {
362
- const key = line.slice(0, start);
363
- const value = split0(line.slice(start + 1), ';');
364
- ctx.cookie.set(key, value);
578
+ const ctx = withContextObserver(
579
+ {
580
+ cookie: new Map(), // default ('set-cookies' in response)
581
+ cookie0: new Map(), // fallback ('cookies' in request)
582
+ param: new Map(), // URL params
583
+ },
584
+ observer,
585
+ );
586
+
587
+ let content;
588
+ for (
589
+ let unsafeStepIdx = 0;
590
+ unsafeStepIdx < steps.length;
591
+ unsafeStepIdx += 1
592
+ ) {
593
+ const stepIdx = unsafeStepIdx; // eliminate pitfalls due to mutability
594
+ const currentStep = steps[stepIdx];
595
+ const nextStep = steps[stepIdx + 1];
596
+ const localParams = {
597
+ ...sharedParams,
598
+ ...currentStep,
599
+ };
600
+
601
+ const readyForNextStep = new Promise((resolve, reject) => {
602
+ observer.onChange = null;
603
+ if (!currentStep.dynamic) {
604
+ resolve();
605
+ return;
606
+ }
607
+
608
+ try {
609
+ const graph = buildDependencyGraph(nextStep);
610
+ if (graph.allReady) {
611
+ resolve();
612
+ return;
613
+ }
614
+ observer.onChange = graph.onChange;
615
+ graph.onReady = resolve;
616
+ } catch (e) {
617
+ reject(e);
618
+ }
619
+ });
620
+
621
+ if (localParams.headers) {
622
+ localParams.headers = replacePlaceholders(localParams.headers, ctx);
623
+ }
624
+
625
+ const localUrl = createLocalUrl(originalUrl, localParams.params || {});
626
+ if (!identicalExceptForSearchParams(originalUrl, localUrl)) {
627
+ // By design, this should be impossible to reach. But by enforcing it, we
628
+ // eliminate the risk of ending up with unintended requests to different hosts.
629
+ throw new PermanentlyUnableToFetchUrlError(
630
+ `Rejected: local URL should only change params, but got: ${originalUrl} -> ${localUrl}`,
631
+ );
632
+ }
633
+
634
+ const { origin } = new URL(localUrl);
635
+ const matchedUrls = [`${origin}/*`];
636
+
637
+ const onBeforeSendHeaders = (details) => {
638
+ if (
639
+ details.tabId !== -1 ||
640
+ (details.type !== 'xmlhttprequest' && details.type !== 'sub_frame')
641
+ ) {
642
+ logger.debug('onBeforeSendHeaders[ignored]:', details);
643
+ return;
644
+ }
645
+
646
+ logger.debug('onBeforeSendHeaders[match]', details);
647
+ for (const header of details.requestHeaders) {
648
+ if (header.name.toLowerCase() === 'cookie') {
649
+ for (const line of header.value.split('\n')) {
650
+ const start = line.indexOf('=');
651
+ if (start > 0) {
652
+ const key = line.slice(0, start);
653
+ const value = split0(line.slice(start + 1), ';');
654
+ ctx.cookie0.set(key, value);
655
+ }
365
656
  }
366
657
  }
367
658
  }
659
+ const { searchParams } = new URL(details.url);
660
+ for (const [key, value] of [...searchParams]) {
661
+ ctx.param.set(key, value);
662
+ }
663
+ };
664
+ try {
665
+ chrome.webRequest.onBeforeSendHeaders.addListener(
666
+ onBeforeSendHeaders,
667
+ { urls: matchedUrls },
668
+ [
669
+ 'requestHeaders',
670
+ 'extraHeaders', // Note: needed for Chromium, but will be rejected by Firefox
671
+ ],
672
+ );
673
+ } catch (e) {
674
+ chrome.webRequest.onBeforeSendHeaders.addListener(
675
+ onBeforeSendHeaders,
676
+ { urls: matchedUrls },
677
+ ['requestHeaders'],
678
+ );
368
679
  }
369
- return { responseHeaders: details.responseHeaders };
370
- };
371
- try {
372
- chrome.webRequest.onHeadersReceived.addListener(
373
- handler,
374
- { urls: [url] },
375
- [
376
- 'responseHeaders',
377
- 'extraHeaders', // Note: needed for Chromium, but will be rejected by Firefox
378
- ],
379
- );
380
- } catch (e) {
381
- chrome.webRequest.onHeadersReceived.addListener(
382
- handler,
383
- { urls: [url] },
384
- ['responseHeaders'],
385
- );
386
- }
387
- try {
388
- let content;
389
- for (const step of steps) {
390
- const localParams = {
391
- ...sharedParams,
392
- ...step,
393
- };
394
- if (localParams.headers) {
395
- localParams.headers = replacePlaceholders(localParams.headers, ctx);
680
+
681
+ const onHeadersReceived = (details) => {
682
+ if (
683
+ details.tabId !== -1 ||
684
+ (details.type !== 'xmlhttprequest' && details.type !== 'sub_frame')
685
+ ) {
686
+ logger.debug('onHeaderReceived[ignored]:', details);
687
+ return { responseHeaders: details.responseHeaders };
688
+ }
689
+
690
+ logger.debug('onHeaderReceived[match]:', details);
691
+ for (const header of details.responseHeaders) {
692
+ if (header.name.toLowerCase() === 'set-cookie') {
693
+ for (const line of header.value.split('\n')) {
694
+ const start = line.indexOf('=');
695
+ if (start > 0) {
696
+ const key = line.slice(0, start);
697
+ const value = split0(line.slice(start + 1), ';');
698
+ ctx.cookie.set(key, value);
699
+ }
700
+ }
701
+ }
396
702
  }
397
- content = await singleHttpGetStep(url, localParams);
703
+ return { responseHeaders: details.responseHeaders };
704
+ };
705
+ try {
706
+ chrome.webRequest.onHeadersReceived.addListener(
707
+ onHeadersReceived,
708
+ { urls: matchedUrls },
709
+ [
710
+ 'responseHeaders',
711
+ 'extraHeaders', // Note: needed for Chromium, but will be rejected by Firefox
712
+ ],
713
+ );
714
+ } catch (e) {
715
+ chrome.webRequest.onHeadersReceived.addListener(
716
+ onHeadersReceived,
717
+ { urls: matchedUrls },
718
+ ['responseHeaders'],
719
+ );
720
+ }
721
+ try {
722
+ if (currentStep.dynamic) {
723
+ // TODO: getting content of the last step is currently not implemented.
724
+ // If needed, one idea is to use content scripts in the offscreen document.
725
+ content = '';
726
+
727
+ await withOffscreenDocumentReady(
728
+ localUrl,
729
+ localParams.headers,
730
+ async () => {
731
+ const { ok, error } = await chrome.runtime.sendMessage({
732
+ target: 'offscreen:urlReporting',
733
+ type: 'request',
734
+ data: { url: localUrl },
735
+ });
736
+ if (!ok) {
737
+ throw new Error(
738
+ `Unexpected error (details: ${error || '<unavailable>'})`,
739
+ );
740
+ }
741
+
742
+ let timeout = null;
743
+ const timedOut = new Promise((resolve, reject) => {
744
+ const maxTime = params.timeout || 15 * SECOND;
745
+ timeout = setTimeout(() => {
746
+ timeout = null;
747
+ logger.warn(
748
+ 'Dynamic fetch of URL',
749
+ localUrl,
750
+ 'exceeded the timeout of',
751
+ maxTime,
752
+ 'ms. Details:',
753
+ {
754
+ localUrl,
755
+ currentStep,
756
+ nextStep,
757
+ ctx,
758
+ },
759
+ );
760
+ reject(`Timeout when dynamically fetching ${localUrl}`);
761
+ }, maxTime);
762
+ });
763
+ try {
764
+ await Promise.race([readyForNextStep, timedOut]);
765
+ } finally {
766
+ clearTimeout(timeout);
767
+ }
768
+ },
769
+ );
770
+ } else {
771
+ content = await singleHttpGetStep(localUrl, localParams);
772
+ }
773
+ } finally {
774
+ chrome.webRequest.onBeforeSendHeaders.removeListener(
775
+ onBeforeSendHeaders,
776
+ );
777
+ chrome.webRequest.onHeadersReceived.removeListener(onHeadersReceived);
398
778
  }
399
- return content;
400
- } finally {
401
- chrome.webRequest.onHeadersReceived.removeListener(handler);
402
779
  }
780
+ return content;
403
781
  });
404
782
  }
405
783
 
@@ -424,13 +802,29 @@ export function replacePlaceholders(headers, ctx) {
424
802
  if (end < 0) {
425
803
  throw new Error(`Corrupted placeholder expression: ${value}`);
426
804
  }
427
- const expression = value.slice(pos, end);
428
- if (expression.startsWith('cookie:')) {
429
- const cookieKey = expression.slice('cookie:'.length);
430
- parts.push(ctx.cookie.get(cookieKey) || '');
431
- } else {
432
- throw new Error('currently only cookies are support');
805
+
806
+ const fullExpression = value.slice(pos, end);
807
+ let resolved;
808
+ for (const expr of fullExpression.split('||')) {
809
+ if (expr.startsWith('cookie:')) {
810
+ const key = expr.slice('cookie:'.length);
811
+ resolved = ctx.cookie.get(key);
812
+ } else if (expr.startsWith('cookie0:')) {
813
+ const key = expr.slice('cookie0:'.length);
814
+ resolved = ctx.cookie0.get(key);
815
+ } else if (expr.startsWith('param:')) {
816
+ const key = expr.slice('param:'.length);
817
+ resolved = ctx.param.get(key);
818
+ } else {
819
+ throw new Error(
820
+ `Unsupported expression: stopped at <<${expr}>> (full expression: ${fullExpression})`,
821
+ );
822
+ }
823
+ if (resolved) {
824
+ break;
825
+ }
433
826
  }
827
+ parts.push(resolved || '');
434
828
  pos = end + 2;
435
829
  }
436
830
  const newValue = parts.join('');
@@ -438,3 +832,127 @@ export function replacePlaceholders(headers, ctx) {
438
832
  }),
439
833
  );
440
834
  }
835
+
836
+ // Note: exported for tests only
837
+ export function findPlaceholders(text) {
838
+ const found = [];
839
+ let pos = 0;
840
+ for (;;) {
841
+ const startPos = text.indexOf('{{', pos);
842
+ if (startPos === -1) break;
843
+ const endPos = text.indexOf('}}', startPos + 2);
844
+ if (endPos === -1) break;
845
+
846
+ found.push(text.slice(startPos + 2, endPos));
847
+ pos = endPos + 2;
848
+ }
849
+ return found;
850
+ }
851
+
852
+ // Note: exported for tests only
853
+ export function buildDependencyGraph(nextStep) {
854
+ const graph = {
855
+ allReady: true,
856
+ onChange: null,
857
+ onReady: () => {}, // can be overwritten by the caller
858
+ };
859
+
860
+ // 1) find all dependencies
861
+ // (if there are none, we can exit early without entering "observe-mode")
862
+ if (nextStep?.headers) {
863
+ const allTemplates = Object.values(nextStep.headers);
864
+ if (allTemplates.length > 0) {
865
+ // Keep track of which placeholders expression exist and by what
866
+ // (atomic) placeholders they get resolved. For instance, in the
867
+ // text "X={{cookie:A||cookie:B}}", there is one placeholder
868
+ // expression ("cookie:A||cookie:B"); it resolves once either
869
+ // "cookie:A" or "cookie:B" becomes available.
870
+ //
871
+ // The pending set would thus be { "cookie:A||cookie:B" }
872
+ // and the resolvedBy mapping would be: {
873
+ // "cookie:A" => ["cookie:A||cookie:B"],
874
+ // "cookie:B" => ["cookie:A||cookie:B"]
875
+ // }
876
+ const pendingExpressions = new Set();
877
+ const expressionResolvedByPlaceholder = new Map();
878
+
879
+ for (const template of allTemplates) {
880
+ for (const expression of findPlaceholders(template)) {
881
+ pendingExpressions.add(expression);
882
+
883
+ for (const placeholder of expression.split('||')) {
884
+ const unlocks =
885
+ expressionResolvedByPlaceholder.get(placeholder) || [];
886
+ if (!unlocks.includes(expression)) {
887
+ unlocks.push(expression);
888
+ }
889
+ expressionResolvedByPlaceholder.set(placeholder, unlocks);
890
+ }
891
+ }
892
+ }
893
+
894
+ // 2) if there are unresolved dependencies, switch to "observe-mode"
895
+ // The caller is expected to setup the "onReady" and "onChange" hooks.
896
+ // "onChange" should connect to the context observer.
897
+ if (pendingExpressions.size > 0) {
898
+ logger.debug('[observe-mode] waiting for:', pendingExpressions);
899
+ graph.allReady = false;
900
+ graph.onChange = (type, key, value) => {
901
+ if (!graph.allReady && value) {
902
+ const placeholder = `${type}:${key}`;
903
+ const resolvedExpressions =
904
+ expressionResolvedByPlaceholder.get(placeholder) || [];
905
+ for (const resolved of resolvedExpressions) {
906
+ if (pendingExpressions.delete(resolved)) {
907
+ logger.debug(
908
+ '[observe-mode]',
909
+ placeholder,
910
+ '->',
911
+ value,
912
+ 'resolved expression',
913
+ resolved,
914
+ );
915
+ if (pendingExpressions.size === 0) {
916
+ logger.debug('[observe-mode] all dependencies resolved');
917
+ graph.allReady = true;
918
+ graph.onReady();
919
+ return;
920
+ }
921
+ }
922
+ }
923
+ }
924
+ };
925
+ }
926
+ }
927
+ }
928
+ return graph;
929
+ }
930
+
931
+ function withContextObserver(ctx, observer) {
932
+ const mapTypes = Object.keys(ctx);
933
+ mapTypes.forEach((type) => {
934
+ ctx[type] = new Proxy(ctx[type], {
935
+ get(target, property, receiver) {
936
+ if (property === 'set') {
937
+ return function (key, value) {
938
+ // the only interesting part (the rest of the function
939
+ // is boilerplate to delegate to the underlying map)
940
+ if (observer.onChange) {
941
+ observer.onChange(type, key, value);
942
+ }
943
+ return target.set(key, value);
944
+ };
945
+ }
946
+ if (property === 'size') {
947
+ return target.size;
948
+ }
949
+ const value = Reflect.get(target, property, receiver);
950
+ if (typeof value === 'function') {
951
+ return value.bind(target);
952
+ }
953
+ return value;
954
+ },
955
+ });
956
+ });
957
+ return ctx;
958
+ }
@@ -0,0 +1,8 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ </head>
5
+ <body>
6
+ <script src="./index.js" type="module"></script>
7
+ </body>
8
+ </html>
@@ -0,0 +1,23 @@
1
+ chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
2
+ if (message.target !== 'offscreen:urlReporting') {
3
+ return;
4
+ }
5
+
6
+ if (message.type === 'request') {
7
+ const url = message.data?.url;
8
+ if (!url) {
9
+ sendResponse({ ok: false, error: 'missing URL' });
10
+ return;
11
+ }
12
+
13
+ const iframe = document.createElement('iframe');
14
+ iframe.credentialless = true;
15
+ iframe.src = url;
16
+ document.body.appendChild(iframe);
17
+
18
+ sendResponse({ ok: true });
19
+ return;
20
+ }
21
+
22
+ sendResponse({ ok: false, error: 'unexpected message type' });
23
+ });
@@ -336,7 +336,7 @@ export function lookupBuiltinTransform(name) {
336
336
  * to disable clients that do not meet the minimum requirements of the
337
337
  * current patterns.
338
338
  */
339
- const PATTERN_DSL_VERSION = 5;
339
+ const PATTERN_DSL_VERSION = 6;
340
340
 
341
341
  /**
342
342
  * "Magic" empty rule set, which exists only if patterns were loaded, but
@@ -313,7 +313,7 @@ export default class SearchExtractor {
313
313
  const body = {
314
314
  action,
315
315
  payload,
316
- ver: 3, // Note: no need to keep this number in sync among messages
316
+ ver: 4, // Note: no need to keep this number in sync among messages
317
317
  'anti-duplicates': Math.floor(random() * 10000000),
318
318
  };
319
319
  messages.push({ body, deduplicateBy });
@@ -11,7 +11,11 @@
11
11
 
12
12
  import { expect } from 'chai';
13
13
 
14
- import { replacePlaceholders } from '../src/http.js';
14
+ import {
15
+ replacePlaceholders,
16
+ findPlaceholders,
17
+ buildDependencyGraph,
18
+ } from '../src/http.js';
15
19
 
16
20
  describe('#replacePlaceholders', function () {
17
21
  const emptyContext = {
@@ -58,4 +62,184 @@ describe('#replacePlaceholders', function () {
58
62
  ),
59
63
  ).to.eql({ key: 'foo=y;bar=y' });
60
64
  });
65
+
66
+ describe('should support short-circut placeholders with "||"', function () {
67
+ it('with left-side argument present', function () {
68
+ expect(
69
+ replacePlaceholders(
70
+ { key: 'foo={{cookie:x||cookie:MISSING}}' },
71
+ cookie_x_to_y,
72
+ ),
73
+ ).to.eql({ key: 'foo=y' });
74
+ });
75
+
76
+ it('with right-side argument present', function () {
77
+ expect(
78
+ replacePlaceholders(
79
+ { key: 'foo={{cookie:MISSING||cookie:x}}' },
80
+ cookie_x_to_y,
81
+ ),
82
+ ).to.eql({ key: 'foo=y' });
83
+ });
84
+
85
+ it('falling back to empty if none arguments are present', function () {
86
+ expect(
87
+ replacePlaceholders(
88
+ { key: 'foo={{cookie:MISSING||cookie:ALSO_MISSING}}' },
89
+ cookie_x_to_y,
90
+ ),
91
+ ).to.eql({ key: 'foo=' });
92
+ });
93
+
94
+ it('left-argument should win', function () {
95
+ const ctx = {
96
+ cookie: new Map([
97
+ ['left', 'left-won'],
98
+ ['right', 'right-won'],
99
+ ]),
100
+ };
101
+ expect(
102
+ replacePlaceholders({ key: 'foo={{cookie:left||cookie:right}}' }, ctx),
103
+ ).to.eql({ key: 'foo=left-won' });
104
+ });
105
+
106
+ it('blank values do not win, even if present', function () {
107
+ const ctx = {
108
+ cookie: new Map([
109
+ ['left', ''],
110
+ ['right', 'right'],
111
+ ]),
112
+ };
113
+ expect(
114
+ replacePlaceholders({ key: 'foo={{cookie:left||cookie:right}}' }, ctx),
115
+ ).to.eql({ key: 'foo=right' });
116
+ });
117
+ });
118
+ });
119
+
120
+ describe('#findPlaceholders', function () {
121
+ it('should work with empty strings', function () {
122
+ expect(findPlaceholders('')).to.eql([]);
123
+ });
124
+
125
+ it('should work when there are no placeholders', function () {
126
+ expect(findPlaceholders('foo')).to.eql([]);
127
+ });
128
+
129
+ it('should find one placeholder', function () {
130
+ expect(findPlaceholders('x={{cookie:foo}}')).to.eql(['cookie:foo']);
131
+ });
132
+
133
+ it('should find multiple placeholders', function () {
134
+ expect(findPlaceholders('x={{foo}};y={{bar}}')).to.eql(['foo', 'bar']);
135
+ });
136
+
137
+ it('should support the reuse of placeholders', function () {
138
+ expect(findPlaceholders('x={{foo}};y={{foo}}')).to.eql(['foo', 'foo']);
139
+ });
140
+
141
+ it('should support (ill-formed) empty placeholders', function () {
142
+ expect(findPlaceholders('x={{}}')).to.eql(['']);
143
+ });
144
+
145
+ it('should support broken texts gracefully', function () {
146
+ expect(findPlaceholders('x={{} }')).to.eql([]);
147
+ expect(findPlaceholders('x={{ {{}}')).to.eql([' {{']);
148
+ expect(findPlaceholders('x={{')).to.eql([]);
149
+ expect(findPlaceholders('x={{foo')).to.eql([]);
150
+ expect(findPlaceholders('}}{{')).to.eql([]);
151
+ });
152
+
153
+ describe('should support short-circuit evaluation with "||"', function () {
154
+ expect(findPlaceholders('abc={{foo||bar}}')).to.eql(['foo||bar']);
155
+ });
156
+ });
157
+
158
+ describe('#buildDependencyGraph', function () {
159
+ it('should be immediately ready if there is no next step', function () {
160
+ expect(buildDependencyGraph(undefined).allReady).to.eql(true);
161
+ });
162
+
163
+ it('should be immediately ready if there are no dependencies', function () {
164
+ expect(buildDependencyGraph({}).allReady).to.eql(true);
165
+ expect(
166
+ buildDependencyGraph({
167
+ headers: {},
168
+ }).allReady,
169
+ ).to.eql(true);
170
+ expect(
171
+ buildDependencyGraph({
172
+ headers: {
173
+ SomeHeader: 'some text, but no placeholder',
174
+ },
175
+ }).allReady,
176
+ ).to.eql(true);
177
+ });
178
+
179
+ it('should not resolve immediately, but when its single dependency is resolved', function () {
180
+ const graph = buildDependencyGraph({
181
+ headers: {
182
+ Cookie: 'some text, with {{cookie:FOO}} placeholder',
183
+ },
184
+ });
185
+ expect(graph.allReady).to.eql(false);
186
+
187
+ let onReadyCalled = 0;
188
+ graph.onReady = () => {
189
+ onReadyCalled += 1;
190
+ };
191
+
192
+ graph.onChange('cookie', 'FOO', 'dummy value');
193
+ expect(onReadyCalled).to.eql(1);
194
+ expect(graph.allReady).to.eql(true);
195
+ });
196
+
197
+ it('should not resolve when both dependencies are ready', function () {
198
+ const graph = buildDependencyGraph({
199
+ headers: {
200
+ Cookie: 'first={{cookie:X}};second={{cookie:Y}}',
201
+ },
202
+ });
203
+ expect(graph.allReady).to.eql(false);
204
+
205
+ let onReadyCalled = 0;
206
+ graph.onReady = () => {
207
+ onReadyCalled += 1;
208
+ };
209
+
210
+ // not yet resolved, one missing
211
+ graph.onChange('cookie', 'X', 'dummy value');
212
+ expect(onReadyCalled).to.eql(0);
213
+ expect(graph.allReady).to.eql(false);
214
+
215
+ // ... but now both are ready
216
+ graph.onChange('cookie', 'Y', 'dummy value');
217
+ expect(onReadyCalled).to.eql(1);
218
+ expect(graph.allReady).to.eql(true);
219
+ });
220
+
221
+ it('should support short-circuit "||" expressions', function () {
222
+ const graph = buildDependencyGraph({
223
+ headers: {
224
+ Cookie:
225
+ 'first={{cookie:X1||cookie:X2}};second={{cookie:Y1||cookie:Y2}}',
226
+ },
227
+ });
228
+ expect(graph.allReady).to.eql(false);
229
+
230
+ let onReadyCalled = 0;
231
+ graph.onReady = () => {
232
+ onReadyCalled += 1;
233
+ };
234
+
235
+ // this resolves the first placeholder
236
+ graph.onChange('cookie', 'X1', 'dummy value');
237
+ expect(onReadyCalled).to.eql(0);
238
+ expect(graph.allReady).to.eql(false);
239
+
240
+ // this resolves the second placeholder
241
+ graph.onChange('cookie', 'Y2', 'dummy value');
242
+ expect(onReadyCalled).to.eql(1);
243
+ expect(graph.allReady).to.eql(true);
244
+ });
61
245
  });