@whotracksme/reporting 7.1.0 β†’ 7.2.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,16 @@
1
+ # v7.2.0 (Mon May 19 2025)
2
+
3
+ #### πŸš€ Enhancement
4
+
5
+ - 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))
6
+
7
+ #### Authors: 2
8
+
9
+ - Krzysztof Modras ([@chrmod](https://github.com/chrmod))
10
+ - Philipp Claßen ([@philipp-classen](https://github.com/philipp-classen))
11
+
12
+ ---
13
+
1
14
  # v7.1.0 (Mon May 19 2025)
2
15
 
3
16
  #### πŸš€ Enhancement
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "7.1.0",
3
+ "version": "7.2.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,17 @@ 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;
27
30
 
28
31
  function getExtensionDomain() {
29
32
  getExtensionDomain.cached =
@@ -31,6 +34,66 @@ function getExtensionDomain() {
31
34
  return getExtensionDomain.cached;
32
35
  }
33
36
 
37
+ function identicalExceptForSearchParams(url1, url2) {
38
+ if (url1 === url2) {
39
+ return true;
40
+ }
41
+ const x = new URL(url1);
42
+ const y = new URL(url2);
43
+ x.search = '';
44
+ y.search = '';
45
+ return x.toString() === y.toString();
46
+ }
47
+
48
+ // A list of safe URL parameter modifier operations.
49
+ // Rule of thumb:
50
+ // * builtins to remove or randomize should be safe.
51
+ // * replacing by arbitrary values could lead to unintended effects
52
+ // (e.g. for sites that can be redirected via URL parameters)
53
+ const BUILTIN_PARAM_MODIFIERS = {
54
+ /**
55
+ * Replaced the old value with a random one (10-20 alpha-numeric characters).
56
+ */
57
+ random1: (oldValue) => {
58
+ requireString(oldValue);
59
+
60
+ const length = Math.round(randomBetween(6, 14));
61
+ const array = new Uint8Array(length);
62
+ crypto.getRandomValues(array);
63
+
64
+ let result = '';
65
+ const characters =
66
+ 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.- ';
67
+ for (let i = 0; i < length; i++) {
68
+ result += characters[array[i] % characters.length];
69
+ }
70
+ return result.trim();
71
+ },
72
+ };
73
+
74
+ function createLocalUrl(url, params) {
75
+ const paramEntries = Object.entries(params);
76
+ if (paramEntries.length === 0) {
77
+ return url;
78
+ }
79
+
80
+ const modifiedUrl = new URL(url);
81
+ for (const [operation, queryKeyNames] of paramEntries) {
82
+ const func = BUILTIN_PARAM_MODIFIERS[operation];
83
+ if (!func) {
84
+ throw new Error(`Unsupported operation: <<${operation}>>`);
85
+ }
86
+ const { searchParams } = modifiedUrl;
87
+ for (const key of queryKeyNames) {
88
+ const val = searchParams.get(key);
89
+ if (val !== null) {
90
+ searchParams.set(key, func(val));
91
+ }
92
+ }
93
+ }
94
+ return modifiedUrl.toString();
95
+ }
96
+
34
97
  /**
35
98
  * Note: 429 (too many requests) is intentionally not included in the list.
36
99
  * Even though it is by definition a temporary error, it depends on the context
@@ -121,7 +184,7 @@ async function headerOverrideViaDNR(url, headers) {
121
184
  value,
122
185
  }));
123
186
  const rule = {
124
- id: RESERVED_DNR_RULE_ID,
187
+ id: RESERVED_DNR_RULE_ID_HEADER_OVERRIDE,
125
188
  priority: 1,
126
189
  action: {
127
190
  type: 'modifyHeaders',
@@ -149,6 +212,83 @@ async function headerOverrideViaDNR(url, headers) {
149
212
  };
150
213
  }
151
214
 
215
+ async function tryCloseOffscreenDocument() {
216
+ try {
217
+ await chrome.offscreen.closeDocument();
218
+ } catch (e) {
219
+ if (e.message === 'No current offscreen document.') {
220
+ logger.debug('offscreen document already closed.');
221
+ } else {
222
+ throw e;
223
+ }
224
+ }
225
+ }
226
+
227
+ const OFFSCREEN_DOCUMENT_PATH = 'offscreen/doublefetch/index.html';
228
+
229
+ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
230
+ const cleanups = [];
231
+ try {
232
+ const domain = new URL(url).hostname;
233
+ const rule = {
234
+ id: RESERVED_DNR_RULE_ID_OFFSCREEN,
235
+ condition: {
236
+ initiatorDomains: [chrome.runtime.id],
237
+ requestDomains: [domain],
238
+ resourceTypes: ['sub_frame'],
239
+ },
240
+ action: {
241
+ type: 'modifyHeaders',
242
+ responseHeaders: [
243
+ { header: 'X-Frame-Options', operation: 'remove' },
244
+ { header: 'Frame-Options', operation: 'remove' },
245
+ ],
246
+ },
247
+ };
248
+
249
+ await chrome.declarativeNetRequest.updateSessionRules({
250
+ removeRuleIds: [rule.id],
251
+ addRules: [rule],
252
+ });
253
+ cleanups.push(() =>
254
+ chrome.declarativeNetRequest.updateSessionRules({
255
+ removeRuleIds: [rule.id],
256
+ }),
257
+ );
258
+
259
+ const offscreenUrl = chrome.runtime.getURL(OFFSCREEN_DOCUMENT_PATH);
260
+ const existingContexts = await chrome.runtime.getContexts({
261
+ contextTypes: ['OFFSCREEN_DOCUMENT'],
262
+ documentUrls: [offscreenUrl],
263
+ });
264
+ if (existingContexts.length > 0) {
265
+ // TODO: what do do here? Normally, it should not happen in our setup.
266
+ // Maybe close the document and continue?
267
+ logger.warn('Existing context found:', existingContexts);
268
+ throw new Error('Unexpected: existing context found');
269
+ }
270
+
271
+ await chrome.offscreen.createDocument({
272
+ url: OFFSCREEN_DOCUMENT_PATH,
273
+ reasons: ['IFRAME_SCRIPTING'],
274
+ justification: 'credentialless iframe',
275
+ });
276
+ cleanups.push(() => tryCloseOffscreenDocument());
277
+
278
+ return await asyncCallback();
279
+ } finally {
280
+ await Promise.all(
281
+ cleanups.map(async (x) => {
282
+ try {
283
+ await x();
284
+ } catch (e) {
285
+ logger.warn('Unexpected error while cleaning up resources:', e);
286
+ }
287
+ }),
288
+ );
289
+ }
290
+ }
291
+
152
292
  // Note: the parameters are almost identical to "anonymousHttpGet"
153
293
  // with the exception that "step" is not defined. The implementation
154
294
  // here is only a single request, not a chain of requests.
@@ -335,71 +475,228 @@ const LOCK = new SeqExecutor();
335
475
  * "SOCS=CAESEwgDEgk0ODE3Nzk3MjQaAmVuIAEaBgiA_LyaBg"
336
476
  * (Maybe there is a way to generalize?)
337
477
  */
338
- export async function anonymousHttpGet(url, params = {}) {
478
+ export async function anonymousHttpGet(originalUrl, params = {}) {
339
479
  return LOCK.run(async () => {
340
480
  const { steps = [], ...sharedParams } = params;
341
481
  if (steps.length === 0) {
342
- return singleHttpGetStep(url, sharedParams);
482
+ return singleHttpGetStep(originalUrl, sharedParams);
343
483
  }
344
484
  if (!chrome?.webRequest?.onHeadersReceived) {
345
485
  throw new MultiStepDoublefetchNotSupportedError();
346
486
  }
487
+ const hasDynamicSteps = steps.some((x) => x.dynamic);
488
+ if (hasDynamicSteps && !chrome?.offscreen?.createDocument) {
489
+ throw new DynamicDoublefetchNotSupportedError();
490
+ }
347
491
 
348
492
  // 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(),
493
+ // "foo={{cookie:bar}}"). The context is built from the requests from
494
+ // earlier steps. For instance, a use case is to bypass consent dialogs
495
+ // by modifying cookies.
496
+ const observer = {
497
+ // to be overwritten later to mark dependencies for the next step:
498
+ // e.g. "ctx.cookie.set('foo', '42')" will trigger onChange('cookie', 'foo', '42')
499
+ onChange: null,
355
500
  };
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);
501
+ const ctx = withContextObserver(
502
+ {
503
+ cookie: new Map(), // default ('set-cookies' in response)
504
+ cookie0: new Map(), // fallback ('cookies' in request)
505
+ param: new Map(), // URL params
506
+ },
507
+ observer,
508
+ );
509
+
510
+ let content;
511
+ for (
512
+ let unsafeStepIdx = 0;
513
+ unsafeStepIdx < steps.length;
514
+ unsafeStepIdx += 1
515
+ ) {
516
+ const stepIdx = unsafeStepIdx; // eliminate pitfalls due to mutability
517
+ const currentStep = steps[stepIdx];
518
+ const nextStep = steps[stepIdx + 1];
519
+ const localParams = {
520
+ ...sharedParams,
521
+ ...currentStep,
522
+ };
523
+
524
+ const readyForNextStep = new Promise((resolve, reject) => {
525
+ observer.onChange = null;
526
+ if (!currentStep.dynamic) {
527
+ resolve();
528
+ return;
529
+ }
530
+
531
+ try {
532
+ const graph = buildDependencyGraph(nextStep);
533
+ if (graph.allReady) {
534
+ resolve();
535
+ return;
536
+ }
537
+ observer.onChange = graph.onChange;
538
+ graph.onReady = resolve;
539
+ } catch (e) {
540
+ reject(e);
541
+ }
542
+ });
543
+
544
+ if (localParams.headers) {
545
+ localParams.headers = replacePlaceholders(localParams.headers, ctx);
546
+ }
547
+
548
+ const localUrl = createLocalUrl(originalUrl, localParams.params || {});
549
+ if (!identicalExceptForSearchParams(originalUrl, localUrl)) {
550
+ // By design, this should be impossible to reach. But by enforcing it, we
551
+ // eliminate the risk of ending up with unintended requests to different hosts.
552
+ throw new PermanentlyUnableToFetchUrlError(
553
+ `Rejected: local URL should only change params, but got: ${originalUrl} -> ${localUrl}`,
554
+ );
555
+ }
556
+
557
+ const { origin } = new URL(localUrl);
558
+ const matchedUrls = [`${origin}/*`];
559
+
560
+ const onBeforeSendHeaders = (details) => {
561
+ if (
562
+ details.tabId !== -1 ||
563
+ (details.type !== 'xmlhttprequest' && details.type !== 'sub_frame')
564
+ ) {
565
+ logger.debug('onBeforeSendHeaders[ignored]:', details);
566
+ return;
567
+ }
568
+
569
+ logger.debug('onBeforeSendHeaders[match]', details);
570
+ for (const header of details.requestHeaders) {
571
+ if (header.name.toLowerCase() === 'cookie') {
572
+ for (const line of header.value.split('\n')) {
573
+ const start = line.indexOf('=');
574
+ if (start > 0) {
575
+ const key = line.slice(0, start);
576
+ const value = split0(line.slice(start + 1), ';');
577
+ ctx.cookie0.set(key, value);
578
+ }
579
+ }
580
+ }
581
+ }
582
+ const { searchParams } = new URL(details.url);
583
+ for (const [key, value] of [...searchParams]) {
584
+ ctx.param.set(key, value);
585
+ }
586
+ };
587
+ try {
588
+ chrome.webRequest.onBeforeSendHeaders.addListener(
589
+ onBeforeSendHeaders,
590
+ { urls: matchedUrls },
591
+ [
592
+ 'requestHeaders',
593
+ 'extraHeaders', // Note: needed for Chromium, but will be rejected by Firefox
594
+ ],
595
+ );
596
+ } catch (e) {
597
+ chrome.webRequest.onBeforeSendHeaders.addListener(
598
+ onBeforeSendHeaders,
599
+ { urls: matchedUrls },
600
+ ['requestHeaders'],
601
+ );
602
+ }
603
+
604
+ const onHeadersReceived = (details) => {
605
+ if (
606
+ details.tabId !== -1 ||
607
+ (details.type !== 'xmlhttprequest' && details.type !== 'sub_frame')
608
+ ) {
609
+ logger.debug('onHeaderReceived[ignored]:', details);
610
+ return { responseHeaders: details.responseHeaders };
611
+ }
612
+
613
+ logger.debug('onHeaderReceived[match]:', details);
614
+ for (const header of details.responseHeaders) {
615
+ if (header.name.toLowerCase() === 'set-cookie') {
616
+ for (const line of header.value.split('\n')) {
617
+ const start = line.indexOf('=');
618
+ if (start > 0) {
619
+ const key = line.slice(0, start);
620
+ const value = split0(line.slice(start + 1), ';');
621
+ ctx.cookie.set(key, value);
622
+ }
365
623
  }
366
624
  }
367
625
  }
626
+ return { responseHeaders: details.responseHeaders };
627
+ };
628
+ try {
629
+ chrome.webRequest.onHeadersReceived.addListener(
630
+ onHeadersReceived,
631
+ { urls: matchedUrls },
632
+ [
633
+ 'responseHeaders',
634
+ 'extraHeaders', // Note: needed for Chromium, but will be rejected by Firefox
635
+ ],
636
+ );
637
+ } catch (e) {
638
+ chrome.webRequest.onHeadersReceived.addListener(
639
+ onHeadersReceived,
640
+ { urls: matchedUrls },
641
+ ['responseHeaders'],
642
+ );
368
643
  }
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);
644
+ try {
645
+ if (currentStep.dynamic) {
646
+ // TODO: getting content of the last step is currently not implemented.
647
+ // If needed, one idea is to use content scripts in the offscreen document.
648
+ content = '';
649
+
650
+ await withOffscreenDocumentReady(localUrl, localParams, async () => {
651
+ const { ok, error } = await chrome.runtime.sendMessage({
652
+ target: 'offscreen:urlReporting',
653
+ type: 'request',
654
+ data: { url: localUrl },
655
+ });
656
+ if (!ok) {
657
+ throw new Error(
658
+ `Unexpected error (details: ${error || '<unavailable>'})`,
659
+ );
660
+ }
661
+
662
+ let timeout = null;
663
+ const timedOut = new Promise((resolve, reject) => {
664
+ const maxTime = params.timeout || 15 * SECOND;
665
+ timeout = setTimeout(() => {
666
+ timeout = null;
667
+ logger.warn(
668
+ 'Dynamic fetch of URL',
669
+ localUrl,
670
+ 'exceeded the timeout of',
671
+ maxTime,
672
+ 'ms. Details:',
673
+ {
674
+ localUrl,
675
+ currentStep,
676
+ nextStep,
677
+ ctx,
678
+ },
679
+ );
680
+ reject(`Timeout when dynamically fetching ${localUrl}`);
681
+ }, maxTime);
682
+ });
683
+ try {
684
+ await Promise.race([readyForNextStep, timedOut]);
685
+ } finally {
686
+ clearTimeout(timeout);
687
+ }
688
+ });
689
+ } else {
690
+ content = await singleHttpGetStep(localUrl, localParams);
396
691
  }
397
- content = await singleHttpGetStep(url, localParams);
692
+ } finally {
693
+ chrome.webRequest.onBeforeSendHeaders.removeListener(
694
+ onBeforeSendHeaders,
695
+ );
696
+ chrome.webRequest.onHeadersReceived.removeListener(onHeadersReceived);
398
697
  }
399
- return content;
400
- } finally {
401
- chrome.webRequest.onHeadersReceived.removeListener(handler);
402
698
  }
699
+ return content;
403
700
  });
404
701
  }
405
702
 
@@ -424,13 +721,29 @@ export function replacePlaceholders(headers, ctx) {
424
721
  if (end < 0) {
425
722
  throw new Error(`Corrupted placeholder expression: ${value}`);
426
723
  }
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');
724
+
725
+ const fullExpression = value.slice(pos, end);
726
+ let resolved;
727
+ for (const expr of fullExpression.split('||')) {
728
+ if (expr.startsWith('cookie:')) {
729
+ const key = expr.slice('cookie:'.length);
730
+ resolved = ctx.cookie.get(key);
731
+ } else if (expr.startsWith('cookie0:')) {
732
+ const key = expr.slice('cookie0:'.length);
733
+ resolved = ctx.cookie0.get(key);
734
+ } else if (expr.startsWith('param:')) {
735
+ const key = expr.slice('param:'.length);
736
+ resolved = ctx.param.get(key);
737
+ } else {
738
+ throw new Error(
739
+ `Unsupported expression: stopped at <<${expr}>> (full expression: ${fullExpression})`,
740
+ );
741
+ }
742
+ if (resolved) {
743
+ break;
744
+ }
433
745
  }
746
+ parts.push(resolved || '');
434
747
  pos = end + 2;
435
748
  }
436
749
  const newValue = parts.join('');
@@ -438,3 +751,127 @@ export function replacePlaceholders(headers, ctx) {
438
751
  }),
439
752
  );
440
753
  }
754
+
755
+ // Note: exported for tests only
756
+ export function findPlaceholders(text) {
757
+ const found = [];
758
+ let pos = 0;
759
+ for (;;) {
760
+ const startPos = text.indexOf('{{', pos);
761
+ if (startPos === -1) break;
762
+ const endPos = text.indexOf('}}', startPos + 2);
763
+ if (endPos === -1) break;
764
+
765
+ found.push(text.slice(startPos + 2, endPos));
766
+ pos = endPos + 2;
767
+ }
768
+ return found;
769
+ }
770
+
771
+ // Note: exported for tests only
772
+ export function buildDependencyGraph(nextStep) {
773
+ const graph = {
774
+ allReady: true,
775
+ onChange: null,
776
+ onReady: () => {}, // can be overwritten by the caller
777
+ };
778
+
779
+ // 1) find all dependencies
780
+ // (if there are none, we can exit early without entering "observe-mode")
781
+ if (nextStep?.headers) {
782
+ const allTemplates = Object.values(nextStep.headers);
783
+ if (allTemplates.length > 0) {
784
+ // Keep track of which placeholders expression exist and by what
785
+ // (atomic) placeholders they get resolved. For instance, in the
786
+ // text "X={{cookie:A||cookie:B}}", there is one placeholder
787
+ // expression ("cookie:A||cookie:B"); it resolves once either
788
+ // "cookie:A" or "cookie:B" becomes available.
789
+ //
790
+ // The pending set would thus be { "cookie:A||cookie:B" }
791
+ // and the resolvedBy mapping would be: {
792
+ // "cookie:A" => ["cookie:A||cookie:B"],
793
+ // "cookie:B" => ["cookie:A||cookie:B"]
794
+ // }
795
+ const pendingExpressions = new Set();
796
+ const expressionResolvedByPlaceholder = new Map();
797
+
798
+ for (const template of allTemplates) {
799
+ for (const expression of findPlaceholders(template)) {
800
+ pendingExpressions.add(expression);
801
+
802
+ for (const placeholder of expression.split('||')) {
803
+ const unlocks =
804
+ expressionResolvedByPlaceholder.get(placeholder) || [];
805
+ if (!unlocks.includes(expression)) {
806
+ unlocks.push(expression);
807
+ }
808
+ expressionResolvedByPlaceholder.set(placeholder, unlocks);
809
+ }
810
+ }
811
+ }
812
+
813
+ // 2) if there are unresolved dependencies, switch to "observe-mode"
814
+ // The caller is expected to setup the "onReady" and "onChange" hooks.
815
+ // "onChange" should connect to the context observer.
816
+ if (pendingExpressions.size > 0) {
817
+ logger.debug('[observe-mode] waiting for:', pendingExpressions);
818
+ graph.allReady = false;
819
+ graph.onChange = (type, key, value) => {
820
+ if (!graph.allReady && value) {
821
+ const placeholder = `${type}:${key}`;
822
+ const resolvedExpressions =
823
+ expressionResolvedByPlaceholder.get(placeholder) || [];
824
+ for (const resolved of resolvedExpressions) {
825
+ if (pendingExpressions.delete(resolved)) {
826
+ logger.debug(
827
+ '[observe-mode]',
828
+ placeholder,
829
+ '->',
830
+ value,
831
+ 'resolved expression',
832
+ resolved,
833
+ );
834
+ if (pendingExpressions.size === 0) {
835
+ logger.debug('[observe-mode] all dependencies resolved');
836
+ graph.allReady = true;
837
+ graph.onReady();
838
+ return;
839
+ }
840
+ }
841
+ }
842
+ }
843
+ };
844
+ }
845
+ }
846
+ }
847
+ return graph;
848
+ }
849
+
850
+ function withContextObserver(ctx, observer) {
851
+ const mapTypes = Object.keys(ctx);
852
+ mapTypes.forEach((type) => {
853
+ ctx[type] = new Proxy(ctx[type], {
854
+ get(target, property, receiver) {
855
+ if (property === 'set') {
856
+ return function (key, value) {
857
+ // the only interesting part (the rest of the function
858
+ // is boilerplate to delegate to the underlying map)
859
+ if (observer.onChange) {
860
+ observer.onChange(type, key, value);
861
+ }
862
+ return target.set(key, value);
863
+ };
864
+ }
865
+ if (property === 'size') {
866
+ return target.size;
867
+ }
868
+ const value = Reflect.get(target, property, receiver);
869
+ if (typeof value === 'function') {
870
+ return value.bind(target);
871
+ }
872
+ return value;
873
+ },
874
+ });
875
+ });
876
+ return ctx;
877
+ }
@@ -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
@@ -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
  });