@whotracksme/reporting 7.7.2 โ†’ 7.9.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,34 @@
1
+ # v7.9.0 (Mon Nov 10 2025)
2
+
3
+ #### ๐Ÿš€ Enhancement
4
+
5
+ - Avoid conflicts between adblocker and temporary DNR overwrites [#177](https://github.com/whotracksme/webextension-packages/pull/177) ([@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.8.0 (Wed Sep 24 2025)
14
+
15
+ #### ๐Ÿš€ Enhancement
16
+
17
+ - Better error recovery in doublefetch [#170](https://github.com/whotracksme/webextension-packages/pull/170) ([@philipp-classen](https://github.com/philipp-classen))
18
+ - Clear jobScheduler queues faster [#173](https://github.com/whotracksme/webextension-packages/pull/173) ([@philipp-classen](https://github.com/philipp-classen))
19
+ - Tweak: if chrome.scripting.registerContentScripts is unable, [#171](https://github.com/whotracksme/webextension-packages/pull/171) ([@philipp-classen](https://github.com/philipp-classen))
20
+ - Only for consistency: use the local chrome object instead of the global [#171](https://github.com/whotracksme/webextension-packages/pull/171) ([@philipp-classen](https://github.com/philipp-classen))
21
+
22
+ #### ๐Ÿ  Internal
23
+
24
+ - debugging release errors: Enable more verbose logs for "auto shipit" [#175](https://github.com/whotracksme/webextension-packages/pull/175) ([@philipp-classen](https://github.com/philipp-classen))
25
+
26
+ #### Authors: 1
27
+
28
+ - Philipp ClaรŸen ([@philipp-classen](https://github.com/philipp-classen))
29
+
30
+ ---
31
+
1
32
  # v7.7.2 (Thu Sep 18 2025)
2
33
 
3
34
  #### ๐Ÿ› Bug Fix
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "7.7.2",
3
+ "version": "7.9.0",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
@@ -8,7 +8,7 @@
8
8
  "lint.fix": "eslint --fix reporting/ communication/",
9
9
  "test": "npm run test --workspaces --if-present ",
10
10
  "test.unit": "npm run test.unit --workspaces --if-present",
11
- "release": "auto shipit"
11
+ "release": "auto shipit -v"
12
12
  },
13
13
  "publishConfig": {
14
14
  "access": "public"
@@ -26,13 +26,13 @@ export default class AttrackMessageHandler {
26
26
 
27
27
  this._configOverride = {
28
28
  'wtm.attrack.tokensv2': {
29
- readyIn: { min: 13 * MINUTE, max: 4 * HOUR },
29
+ readyIn: { min: 7 * MINUTE, max: 1 * HOUR },
30
30
  },
31
31
  'wtm.attrack.keysv2': {
32
- readyIn: { min: 19 * MINUTE, max: 4 * HOUR },
32
+ readyIn: { min: 5 * MINUTE, max: 1 * HOUR },
33
33
  },
34
34
  'wtm.attrack.tp_events': {
35
- readyIn: { min: 23 * MINUTE, max: 2 * HOUR },
35
+ readyIn: { min: 3 * MINUTE, max: 30 * MINUTE },
36
36
  },
37
37
  };
38
38
 
@@ -47,9 +47,10 @@ export default class AttrackMessageHandler {
47
47
  },
48
48
  {
49
49
  priority: -1000,
50
+ maxJobsTotal: 200,
50
51
  cooldownInMs: 2 * SECOND,
51
- maxJobsTotal: 500,
52
- ttlInMs: 14 * DAY,
52
+ maxAutoRetriesAfterError: 2,
53
+ ttlInMs: 5 * DAY,
53
54
  },
54
55
  );
55
56
  }
@@ -234,8 +234,9 @@ export default class DoublefetchPageHandler {
234
234
 
235
235
  const config = {
236
236
  priority: -1000,
237
- cooldownInMs: 3 * SECOND,
238
237
  maxJobsTotal: 200,
238
+ cooldownInMs: 3 * SECOND,
239
+ maxAutoRetriesAfterError: 1,
239
240
  };
240
241
  jobScheduler.registerHandler(
241
242
  'doublefetch-page',
@@ -28,6 +28,10 @@ const SECOND = 1000;
28
28
  const RESERVED_DNR_RULE_ID_HEADER_OVERRIDE = 1333;
29
29
  const RESERVED_DNR_RULE_ID_OFFSCREEN = 1334;
30
30
 
31
+ // This should be above all rules of the adblocker engine.
32
+ // Otherwise, exclusion rules will effectively disable them.
33
+ const DNR_HEADER_OVERWRITE_PRIORITY = (1 << 30) - 1;
34
+
31
35
  /**
32
36
  * Depending on the context, there are different ways how requests are being
33
37
  * triggered. For instance, the normal one is to use the fetch API; but
@@ -241,7 +245,7 @@ async function headerOverrideViaDNR({ url, headers, requestType }) {
241
245
  }));
242
246
  const rule = {
243
247
  id: RESERVED_DNR_RULE_ID_HEADER_OVERRIDE,
244
- priority: 1,
248
+ priority: DNR_HEADER_OVERWRITE_PRIORITY,
245
249
  action: {
246
250
  type: 'modifyHeaders',
247
251
  requestHeaders,
@@ -309,8 +313,40 @@ async function tryCloseOffscreenDocument() {
309
313
  }
310
314
  }
311
315
  }
316
+
312
317
  const OFFSCREEN_DOCUMENT_PREFIX = 'offscreen/doublefetch';
313
- const OFFSCREEN_DOCUMENT_PATH = `${OFFSCREEN_DOCUMENT_PREFIX}/index.html`;
318
+ const OFFSCREEN_DOCUMENT_INDEX_HTML = `${OFFSCREEN_DOCUMENT_PREFIX}/index.html`;
319
+ const OFFSCREEN_DOCUMENT_FIXES_JS = `${OFFSCREEN_DOCUMENT_PREFIX}/offscreen-fix.js`;
320
+
321
+ async function tryRegisterOffscreenFixes(domain) {
322
+ if (!chrome?.scripting?.registerContentScripts) {
323
+ logger.warn('Skipping offscreen-fixes (chrome.scripting API unavailable)');
324
+ return () => {};
325
+ }
326
+
327
+ logger.debug('Installing offscreen fixes for domain:', domain);
328
+ const id = 'offscreen-fix';
329
+ await chrome.scripting.registerContentScripts([
330
+ {
331
+ id,
332
+ matches: [`https://*.${domain}/*`, `https://${domain}/*`],
333
+ js: [OFFSCREEN_DOCUMENT_FIXES_JS],
334
+ runAt: 'document_start',
335
+ allFrames: true,
336
+ world: 'MAIN',
337
+ },
338
+ ]);
339
+
340
+ return () => {
341
+ logger.debug('Removing offscreen fixes for domain:', domain);
342
+ chrome.scripting.unregisterContentScripts({ ids: [id] }).catch((e) => {
343
+ logger.error(
344
+ 'cleanup failed: unable to remove offscreen fixes content script:',
345
+ e,
346
+ );
347
+ });
348
+ };
349
+ }
314
350
 
315
351
  async function withOffscreenDocumentReady(url, headers, asyncCallback) {
316
352
  const cleanups = [];
@@ -335,28 +371,8 @@ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
335
371
  const undoDNRChange = await addDNRSessionRule(rule);
336
372
  cleanups.push(undoDNRChange);
337
373
 
338
- await chrome.scripting.registerContentScripts([
339
- {
340
- id: 'offscreen-fix',
341
- matches: [`https://*.${domain}/*`, `https://${domain}/*`],
342
- js: [`${OFFSCREEN_DOCUMENT_PREFIX}/offscreen-fix.js`],
343
- runAt: 'document_start',
344
- allFrames: true,
345
- world: 'MAIN',
346
- },
347
- ]);
348
- cleanups.push(() => {
349
- chrome.scripting
350
- .unregisterContentScripts({
351
- ids: ['offscreen-fix'],
352
- })
353
- .catch((e) => {
354
- logger.error(
355
- 'cleanup failed: unable to remove offscreen content script:',
356
- e,
357
- );
358
- });
359
- });
374
+ const undoOffscreenFixes = await tryRegisterOffscreenFixes(domain);
375
+ cleanups.push(undoOffscreenFixes);
360
376
 
361
377
  const undoHeaderOverride = await headerOverride({
362
378
  headers,
@@ -365,7 +381,7 @@ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
365
381
  });
366
382
  cleanups.push(undoHeaderOverride);
367
383
 
368
- const offscreenUrl = chrome.runtime.getURL(OFFSCREEN_DOCUMENT_PATH);
384
+ const offscreenUrl = chrome.runtime.getURL(OFFSCREEN_DOCUMENT_INDEX_HTML);
369
385
  const existingContexts = await chrome.runtime.getContexts({
370
386
  contextTypes: ['OFFSCREEN_DOCUMENT'],
371
387
  documentUrls: [offscreenUrl],
@@ -378,7 +394,7 @@ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
378
394
  }
379
395
 
380
396
  await chrome.offscreen.createDocument({
381
- url: OFFSCREEN_DOCUMENT_PATH,
397
+ url: OFFSCREEN_DOCUMENT_INDEX_HTML,
382
398
  reasons: ['IFRAME_SCRIPTING'],
383
399
  justification: 'credentialless iframe',
384
400
  });
@@ -398,9 +414,26 @@ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
398
414
  }
399
415
  }
400
416
 
417
+ // This is the recovery page returned if the "emptyHtml" flag is set.
418
+ //
419
+ // Changes to this HTML should be treated like API changes.
420
+ // If you need to change it, prefer to do it in a backward compatible
421
+ // way by adding extra meta tags.
422
+ const EMPTY_RESCUE_HTML = `
423
+ <!DOCTYPE html>
424
+ <html>
425
+ <head>
426
+ <meta charset="UTF-8">
427
+ <meta name="rescue" content="error">
428
+ <title>Empty</title>
429
+ </head>
430
+ <body></body>
431
+ </html>
432
+ `;
433
+
401
434
  // Note: the parameters are almost identical to "anonymousHttpGet"
402
- // with the exception that "step" is not defined. The implementation
403
- // here is only a single request, not a chain of requests.
435
+ // with the exception that "step" and "emptyHTML" is not defined.
436
+ // The implementation here is only a single request, not a chain of requests.
404
437
  async function singleHttpGetStep(url, params = {}) {
405
438
  const {
406
439
  headers = null,
@@ -569,17 +602,28 @@ const LOCK = new SeqExecutor();
569
602
  * can be used in later requests. Still, the chain of requests always
570
603
  * starts from a clean state. In other words, the temporary context is
571
604
  * fully isolated and will be discarded once all steps have completed.
572
- *
573
- * TODO: For pages like YouTube, double-fetch fails because of consent
574
- * pages. In the YouTube example, the following cookie could be set:
575
- * "SOCS=CAESEwgDEgk0ODE3Nzk3MjQaAmVuIAEaBgiA_LyaBg"
576
- * (Maybe there is a way to generalize?)
605
+ * - onError (optional):
606
+ * A fallback configuration for error recovery.
607
+ * - emptyHtml (default: false):
608
+ * Bypasses the fetch and returns an empty HTML document
609
+ * (see EMPTY_RESCUE_HTML).
610
+ * This can sometimes be useful, especially for error recovery,
611
+ * to gracefully handle with failed requests.
577
612
  */
578
613
  export async function anonymousHttpGet(originalUrl, params = {}) {
579
- return LOCK.run(async () => {
580
- const { steps = [], ...sharedParams } = params;
614
+ return LOCK.run(() => anonymousHttpGet_(originalUrl, params));
615
+ }
616
+
617
+ async function anonymousHttpGet_(originalUrl, params = {}) {
618
+ const { steps = [], emptyHtml = false, onError, ...sharedParams } = params;
619
+ if (emptyHtml) {
620
+ logger.debug('Returning empty HTML for URL:', originalUrl);
621
+ return EMPTY_RESCUE_HTML;
622
+ }
623
+
624
+ try {
581
625
  if (steps.length === 0) {
582
- return singleHttpGetStep(originalUrl, sharedParams);
626
+ return await singleHttpGetStep(originalUrl, sharedParams);
583
627
  }
584
628
  if (!chrome?.webRequest?.onHeadersReceived) {
585
629
  throw new MultiStepDoublefetchNotSupportedError();
@@ -616,10 +660,7 @@ export async function anonymousHttpGet(originalUrl, params = {}) {
616
660
  const stepIdx = unsafeStepIdx; // eliminate pitfalls due to mutability
617
661
  const currentStep = steps[stepIdx];
618
662
  const nextStep = steps[stepIdx + 1];
619
- const localParams = {
620
- ...sharedParams,
621
- ...currentStep,
622
- };
663
+ const localParams = { ...sharedParams, ...currentStep };
623
664
 
624
665
  const readyForNextStep = new Promise((resolve, reject) => {
625
666
  observer.onChange = null;
@@ -801,7 +842,22 @@ export async function anonymousHttpGet(originalUrl, params = {}) {
801
842
  }
802
843
  }
803
844
  return content;
804
- });
845
+ } catch (e) {
846
+ if (onError) {
847
+ const rescueParams = {
848
+ ...sharedParams,
849
+ ...onError,
850
+ };
851
+ logger.info(
852
+ 'Entering rescue path for URL:',
853
+ originalUrl,
854
+ 'Config:',
855
+ rescueParams,
856
+ );
857
+ return anonymousHttpGet_(originalUrl, rescueParams);
858
+ }
859
+ throw e;
860
+ }
805
861
  }
806
862
 
807
863
  // Resolves placeholder expressions ("{{ }}"} with values provided by the
@@ -1751,7 +1751,7 @@ export default class Pages {
1751
1751
  return CANCEL_LAZY_VAR;
1752
1752
  }
1753
1753
  try {
1754
- const wrappedResult = await chrome.scripting.executeScript({
1754
+ const wrappedResult = await this.chrome.scripting.executeScript({
1755
1755
  target: {
1756
1756
  tabId,
1757
1757
  },
@@ -10,7 +10,7 @@
10
10
  */
11
11
 
12
12
  import logger from './logger';
13
- import { randBetween, clamp } from './utils';
13
+ import { randBetween, clamp, parseUntrustedJSON } from './utils';
14
14
  import SelfChecks from './self-check';
15
15
 
16
16
  const SECOND = 1000;
@@ -202,7 +202,9 @@ export default class PatternsUpdater {
202
202
  );
203
203
  }
204
204
  const newPatterns = await response.text();
205
- const rules = JSON.parse(newPatterns);
205
+ const rules = parseUntrustedJSON(newPatterns, {
206
+ maxSize: 1024 * 1024, // 1 MB
207
+ });
206
208
 
207
209
  // Bookkeeping to detect if the server just released an update.
208
210
  // It is useful for debugging, but it also means we should
@@ -20,6 +20,7 @@ import {
20
20
  requireBoolean,
21
21
  requireObject,
22
22
  requireArrayOfStrings,
23
+ parseUntrustedJSON,
23
24
  } from './utils';
24
25
 
25
26
  /**
@@ -286,7 +287,10 @@ const TRANSFORMS = new Map(
286
287
  requireString(path);
287
288
  requireBoolean(extractObjects);
288
289
  try {
289
- let obj = JSON.parse(text);
290
+ let obj = parseUntrustedJSON(text, {
291
+ maxSize: 1024 * 1024, // 1 MB
292
+ sanitizeSilently: true,
293
+ });
290
294
  for (const field of path.split('.')) {
291
295
  if (!Object.hasOwn(obj, field)) {
292
296
  return '';
@@ -336,7 +340,7 @@ export function lookupBuiltinTransform(name) {
336
340
  * to disable clients that do not meet the minimum requirements of the
337
341
  * current patterns.
338
342
  */
339
- const PATTERN_DSL_VERSION = 6;
343
+ const PATTERN_DSL_VERSION = 7;
340
344
 
341
345
  /**
342
346
  * "Magic" empty rule set, which exists only if patterns were loaded, but
@@ -413,21 +417,31 @@ export default class Patterns {
413
417
  if (!this._rules[msgType]) {
414
418
  return null;
415
419
  }
416
- const doublefetchRequest = { url };
417
- if (this._rules[msgType].doublefetch) {
418
- const { headers, followRedirects, steps } =
419
- this._rules[msgType].doublefetch;
420
+ const convert = (
421
+ { followRedirects, headers, steps, emptyHtml, onError },
422
+ target = {},
423
+ ) => {
420
424
  if (followRedirects) {
421
- doublefetchRequest.redirect = 'follow';
425
+ target.redirect = 'follow';
422
426
  }
423
427
  if (headers) {
424
- doublefetchRequest.headers = headers;
428
+ target.headers = headers;
425
429
  }
426
430
  if (steps) {
427
- doublefetchRequest.steps = steps;
431
+ target.steps = steps;
428
432
  }
429
- }
430
- return doublefetchRequest;
433
+ if (typeof emptyHtml === 'boolean') {
434
+ target.emptyHtml = emptyHtml;
435
+ }
436
+ if (onError) {
437
+ target.onError = convert(onError);
438
+ }
439
+ return target;
440
+ };
441
+
442
+ // Start with the mandatory "url" field and fill the remaining,
443
+ // optional fields from the configuration from patterns.
444
+ return convert(this._rules[msgType].doublefetch || {}, { url });
431
445
  }
432
446
 
433
447
  _sanitizeRules(rules) {
@@ -135,10 +135,9 @@ export default class SearchExtractor {
135
135
 
136
136
  let doc;
137
137
  try {
138
- const html = await anonymousHttpGet(doublefetchRequest.url, {
139
- headers: doublefetchRequest.headers,
140
- redirect: doublefetchRequest.redirect,
141
- steps: doublefetchRequest.steps,
138
+ const { url, ...params } = doublefetchRequest;
139
+ const html = await anonymousHttpGet(url, {
140
+ ...params,
142
141
  treat429AsPermanentError: true,
143
142
  });
144
143
  doc = await parseHtml(html);
@@ -305,6 +305,43 @@ export function split0(str, on) {
305
305
  return pos < 0 ? str : str.slice(0, pos);
306
306
  }
307
307
 
308
+ /**
309
+ * Drop-in replacement for JSON.parse if you need to handle untrusted data.
310
+ *
311
+ * Warning: this implementation will not be able to magically solve all
312
+ * possible attacks. Depending on the specific use case, additional
313
+ * verifications may be needed (e.g. allowing only specific known fields).
314
+ */
315
+ export function parseUntrustedJSON(
316
+ untrustedJson,
317
+ { sanitizeSilently = false, maxSize } = {},
318
+ ) {
319
+ if (typeof untrustedJson !== 'string') {
320
+ throw new Error(
321
+ 'Untrusted JSON detected: unexpected input to be of type "string"',
322
+ );
323
+ }
324
+ if (!isNil(maxSize) && untrustedJson.length > maxSize) {
325
+ throw new Error(
326
+ `Untrusted JSON detected: input exceeded maximum size of ${maxSize}`,
327
+ );
328
+ }
329
+
330
+ if (sanitizeSilently) {
331
+ const filterBadKeys = (key, value) =>
332
+ key === '__proto__' ? undefined : value;
333
+ return JSON.parse(untrustedJson, filterBadKeys);
334
+ }
335
+
336
+ const failOnBadKeys = (key, value) => {
337
+ if (key === '__proto__') {
338
+ throw new Error('Untrusted JSON detected: unexpected __proto__');
339
+ }
340
+ return value;
341
+ };
342
+ return JSON.parse(untrustedJson, failOnBadKeys);
343
+ }
344
+
308
345
  /**
309
346
  * Lazy initialized variables:
310
347
  * - evaluated once at the first request
@@ -23,6 +23,7 @@ import './search-extractor.spec.js';
23
23
  import './session-storage.spec.js';
24
24
  import './seq-executor.spec.js';
25
25
  import './url-cleaner.spec.js';
26
+ import './utils.spec.js';
26
27
 
27
28
  // Request utils
28
29
  import './request/utils/tldts.spec.js';
@@ -12,7 +12,7 @@
12
12
  import { expect } from 'chai';
13
13
  import fc from 'fast-check';
14
14
 
15
- import { lookupBuiltinTransform } from '../src/patterns.js';
15
+ import Patterns, { lookupBuiltinTransform } from '../src/patterns.js';
16
16
 
17
17
  describe('Test builtin primitives', function () {
18
18
  describe('#queryParam', function () {
@@ -916,3 +916,160 @@ describe('Test builtin primitives', function () {
916
916
  });
917
917
  });
918
918
  });
919
+
920
+ describe('Patterns', function () {
921
+ describe('#createDoublefetchRequest', function () {
922
+ it('should default to an empty request', function () {
923
+ const uut = new Patterns();
924
+ const msgType = 'some-message-type';
925
+ const url = 'https://example.test/foo';
926
+
927
+ // message type is known, but has no explicit config
928
+ uut.updatePatterns({
929
+ [msgType]: {
930
+ input: {},
931
+ output: {},
932
+ },
933
+ });
934
+ expect(uut.createDoublefetchRequest(msgType, url)).to.eql({ url });
935
+ });
936
+
937
+ it('should return null if the message type is unknown', function () {
938
+ const uut = new Patterns();
939
+ const msgType = 'some-message-type';
940
+ const url = 'https://example.test/foo';
941
+
942
+ uut.updatePatterns({});
943
+ expect(uut.createDoublefetchRequest(msgType, url)).to.eql(null);
944
+ });
945
+
946
+ // General helper to verify that the doublefetch section from the
947
+ // pattern rules is correctly converted to a doublefetch request.
948
+ function check({ config: doublefetch, result: outputForUrl }) {
949
+ expect(doublefetch).to.be.an('object');
950
+ expect(outputForUrl).to.be.a('function');
951
+
952
+ const uut = new Patterns();
953
+ const msgType = 'some-message-type';
954
+ const url = 'https://example.test/foo';
955
+
956
+ uut.updatePatterns({
957
+ [msgType]: {
958
+ doublefetch,
959
+ input: {},
960
+ output: {},
961
+ },
962
+ });
963
+
964
+ const actual = uut.createDoublefetchRequest(msgType, url);
965
+ const expected = outputForUrl(url);
966
+ expect(actual).to.eql(expected);
967
+ }
968
+
969
+ describe('should translate followRedirects=true to redirect=follow', function () {
970
+ it('in a flat example', function () {
971
+ check({
972
+ config: {
973
+ followRedirects: true,
974
+ },
975
+ result: (url) => ({
976
+ url,
977
+ redirect: 'follow',
978
+ }),
979
+ });
980
+ });
981
+
982
+ it('in a nested example', function () {
983
+ check({
984
+ config: {
985
+ onError: {
986
+ followRedirects: true,
987
+ },
988
+ },
989
+ result: (url) => ({
990
+ url,
991
+ onError: {
992
+ redirect: 'follow',
993
+ },
994
+ }),
995
+ });
996
+ });
997
+ });
998
+
999
+ describe('should forward', function () {
1000
+ // Specialized function for the common use case that the doublefetch
1001
+ // config in the patterns will be identical to the doublefetch request.
1002
+ function shouldForward(config) {
1003
+ check({
1004
+ config,
1005
+ result: (url) => ({
1006
+ url,
1007
+ ...config,
1008
+ }),
1009
+ });
1010
+ }
1011
+
1012
+ it('empty configs', function () {
1013
+ shouldForward({});
1014
+ });
1015
+
1016
+ it('header overwrites', function () {
1017
+ shouldForward({
1018
+ headers: {
1019
+ foo: 'foo',
1020
+ bar: 'bar',
1021
+ },
1022
+ });
1023
+ });
1024
+
1025
+ it('simple steps', function () {
1026
+ shouldForward({
1027
+ steps: [{ dynamic: true }, {}],
1028
+ });
1029
+ });
1030
+
1031
+ it('emptyHtml', function () {
1032
+ shouldForward({ emptyHtml: true });
1033
+ shouldForward({ emptyHtml: false });
1034
+ });
1035
+
1036
+ it('onError', function () {
1037
+ shouldForward({ onError: {} });
1038
+ shouldForward({ onError: { emptyHtml: true } });
1039
+ shouldForward({ onError: { headers: { foo: 'foo' } } });
1040
+ });
1041
+ });
1042
+
1043
+ describe('should drop unexpected fields', function () {
1044
+ function shouldDrop(config) {
1045
+ check({
1046
+ config,
1047
+ result: (url) => ({ url }),
1048
+ });
1049
+ }
1050
+
1051
+ function shouldOnlyKeep(config, keep) {
1052
+ check({
1053
+ config,
1054
+ result: (url) => ({ url, ...keep }),
1055
+ });
1056
+ }
1057
+
1058
+ it('in a flat example', function () {
1059
+ shouldDrop({ foo: 'unexpected field' });
1060
+ shouldDrop({ __proto__: { admin: true } });
1061
+ });
1062
+
1063
+ it('in a nested example', function () {
1064
+ shouldOnlyKeep(
1065
+ { onError: { foo: 'unexpected field' } },
1066
+ { onError: {} },
1067
+ );
1068
+ shouldOnlyKeep(
1069
+ { onError: { __proto__: { admin: true } } },
1070
+ { onError: {} },
1071
+ );
1072
+ });
1073
+ });
1074
+ });
1075
+ });
@@ -16,6 +16,7 @@ import {
16
16
  chunk,
17
17
  flattenObject,
18
18
  equalityCanBeProven,
19
+ parseUntrustedJSON,
19
20
  lazyInitAsync,
20
21
  } from '../src/utils.js';
21
22
 
@@ -153,6 +154,65 @@ describe('#equalityCanBeProven', function () {
153
154
  });
154
155
  });
155
156
 
157
+ describe('#parseUntrustedJSON', function () {
158
+ describe('should be a drop-in replacement for JSON.parse for safe data', function () {
159
+ for (const json of [
160
+ '{"foo": "bar"}',
161
+ '[{"foo": 42, "bar": []}]',
162
+ '{"a": [1, 2, {"b": 3}], "c": {"d": {"e": 4}}}',
163
+ ]) {
164
+ it(`- well-formed input: <<${json}>>`, function () {
165
+ expect(parseUntrustedJSON(json)).to.eql(JSON.parse(json));
166
+ });
167
+ }
168
+
169
+ for (const badJson of [
170
+ '',
171
+ 'some broken JSON',
172
+ '{{{',
173
+ 123,
174
+ null,
175
+ undefined,
176
+ { foo: 'bar' },
177
+ [],
178
+ ]) {
179
+ it(`- corrupted input: <<${badJson}>>`, function () {
180
+ expect(() => parseUntrustedJSON(badJson)).to.throw;
181
+ });
182
+ }
183
+ });
184
+
185
+ describe('should detect __proto__ fields', function () {
186
+ it('at the top level', function () {
187
+ // by default, we should reject this input
188
+ const json = '{"foo":42, "__proto__":{"admin": true} }';
189
+ expect(() => parseUntrustedJSON(json)).to.throw;
190
+
191
+ // unless we want to process such data (but without the __proto__ field)
192
+ const sanitized = parseUntrustedJSON(json, { sanitizeSilently: true });
193
+ expect(sanitized.__proto__.admin).to.be.undefined;
194
+
195
+ // Note: this would normally happen
196
+ expect(JSON.parse(json).__proto__.admin).to.be.true;
197
+ });
198
+
199
+ it('nested within the JSON', function () {
200
+ const json =
201
+ '{"foo":42, "bar": {"baz": 123, "__proto__": {"admin": true}}}';
202
+ expect(() => parseUntrustedJSON(json)).to.throw;
203
+
204
+ const sanitized = parseUntrustedJSON(json, { sanitizeSilently: true });
205
+ expect(sanitized.bar.__proto__.admin).to.be.undefined;
206
+ });
207
+ });
208
+
209
+ it('should reject input that exceeds the maximum length', function () {
210
+ const json = '{"foo": "bar"}';
211
+ expect(() => parseUntrustedJSON(json, { maxSize: 3 })).to.throw;
212
+ expect(parseUntrustedJSON(json, { maxSize: 1024 }).foo).to.eql('bar');
213
+ });
214
+ });
215
+
156
216
  describe('#lazyInitAsync', function () {
157
217
  async function expectToThrow(func, message) {
158
218
  let error = null;