@whotracksme/reporting 7.7.2 β†’ 7.8.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,22 @@
1
+ # v7.8.0 (Wed Sep 24 2025)
2
+
3
+ #### πŸš€ Enhancement
4
+
5
+ - Better error recovery in doublefetch [#170](https://github.com/whotracksme/webextension-packages/pull/170) ([@philipp-classen](https://github.com/philipp-classen))
6
+ - Clear jobScheduler queues faster [#173](https://github.com/whotracksme/webextension-packages/pull/173) ([@philipp-classen](https://github.com/philipp-classen))
7
+ - Tweak: if chrome.scripting.registerContentScripts is unable, [#171](https://github.com/whotracksme/webextension-packages/pull/171) ([@philipp-classen](https://github.com/philipp-classen))
8
+ - 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))
9
+
10
+ #### 🏠 Internal
11
+
12
+ - 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))
13
+
14
+ #### Authors: 1
15
+
16
+ - Philipp Claßen ([@philipp-classen](https://github.com/philipp-classen))
17
+
18
+ ---
19
+
1
20
  # v7.7.2 (Thu Sep 18 2025)
2
21
 
3
22
  #### πŸ› 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.8.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',
@@ -309,8 +309,40 @@ async function tryCloseOffscreenDocument() {
309
309
  }
310
310
  }
311
311
  }
312
+
312
313
  const OFFSCREEN_DOCUMENT_PREFIX = 'offscreen/doublefetch';
313
- const OFFSCREEN_DOCUMENT_PATH = `${OFFSCREEN_DOCUMENT_PREFIX}/index.html`;
314
+ const OFFSCREEN_DOCUMENT_INDEX_HTML = `${OFFSCREEN_DOCUMENT_PREFIX}/index.html`;
315
+ const OFFSCREEN_DOCUMENT_FIXES_JS = `${OFFSCREEN_DOCUMENT_PREFIX}/offscreen-fix.js`;
316
+
317
+ async function tryRegisterOffscreenFixes(domain) {
318
+ if (!chrome?.scripting?.registerContentScripts) {
319
+ logger.warn('Skipping offscreen-fixes (chrome.scripting API unavailable)');
320
+ return () => {};
321
+ }
322
+
323
+ logger.debug('Installing offscreen fixes for domain:', domain);
324
+ const id = 'offscreen-fix';
325
+ await chrome.scripting.registerContentScripts([
326
+ {
327
+ id,
328
+ matches: [`https://*.${domain}/*`, `https://${domain}/*`],
329
+ js: [OFFSCREEN_DOCUMENT_FIXES_JS],
330
+ runAt: 'document_start',
331
+ allFrames: true,
332
+ world: 'MAIN',
333
+ },
334
+ ]);
335
+
336
+ return () => {
337
+ logger.debug('Removing offscreen fixes for domain:', domain);
338
+ chrome.scripting.unregisterContentScripts({ ids: [id] }).catch((e) => {
339
+ logger.error(
340
+ 'cleanup failed: unable to remove offscreen fixes content script:',
341
+ e,
342
+ );
343
+ });
344
+ };
345
+ }
314
346
 
315
347
  async function withOffscreenDocumentReady(url, headers, asyncCallback) {
316
348
  const cleanups = [];
@@ -335,28 +367,8 @@ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
335
367
  const undoDNRChange = await addDNRSessionRule(rule);
336
368
  cleanups.push(undoDNRChange);
337
369
 
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
- });
370
+ const undoOffscreenFixes = await tryRegisterOffscreenFixes(domain);
371
+ cleanups.push(undoOffscreenFixes);
360
372
 
361
373
  const undoHeaderOverride = await headerOverride({
362
374
  headers,
@@ -365,7 +377,7 @@ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
365
377
  });
366
378
  cleanups.push(undoHeaderOverride);
367
379
 
368
- const offscreenUrl = chrome.runtime.getURL(OFFSCREEN_DOCUMENT_PATH);
380
+ const offscreenUrl = chrome.runtime.getURL(OFFSCREEN_DOCUMENT_INDEX_HTML);
369
381
  const existingContexts = await chrome.runtime.getContexts({
370
382
  contextTypes: ['OFFSCREEN_DOCUMENT'],
371
383
  documentUrls: [offscreenUrl],
@@ -378,7 +390,7 @@ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
378
390
  }
379
391
 
380
392
  await chrome.offscreen.createDocument({
381
- url: OFFSCREEN_DOCUMENT_PATH,
393
+ url: OFFSCREEN_DOCUMENT_INDEX_HTML,
382
394
  reasons: ['IFRAME_SCRIPTING'],
383
395
  justification: 'credentialless iframe',
384
396
  });
@@ -398,9 +410,26 @@ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
398
410
  }
399
411
  }
400
412
 
413
+ // This is the recovery page returned if the "emptyHtml" flag is set.
414
+ //
415
+ // Changes to this HTML should be treated like API changes.
416
+ // If you need to change it, prefer to do it in a backward compatible
417
+ // way by adding extra meta tags.
418
+ const EMPTY_RESCUE_HTML = `
419
+ <!DOCTYPE html>
420
+ <html>
421
+ <head>
422
+ <meta charset="UTF-8">
423
+ <meta name="rescue" content="error">
424
+ <title>Empty</title>
425
+ </head>
426
+ <body></body>
427
+ </html>
428
+ `;
429
+
401
430
  // 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.
431
+ // with the exception that "step" and "emptyHTML" is not defined.
432
+ // The implementation here is only a single request, not a chain of requests.
404
433
  async function singleHttpGetStep(url, params = {}) {
405
434
  const {
406
435
  headers = null,
@@ -569,17 +598,28 @@ const LOCK = new SeqExecutor();
569
598
  * can be used in later requests. Still, the chain of requests always
570
599
  * starts from a clean state. In other words, the temporary context is
571
600
  * 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?)
601
+ * - onError (optional):
602
+ * A fallback configuration for error recovery.
603
+ * - emptyHtml (default: false):
604
+ * Bypasses the fetch and returns an empty HTML document
605
+ * (see EMPTY_RESCUE_HTML).
606
+ * This can sometimes be useful, especially for error recovery,
607
+ * to gracefully handle with failed requests.
577
608
  */
578
609
  export async function anonymousHttpGet(originalUrl, params = {}) {
579
- return LOCK.run(async () => {
580
- const { steps = [], ...sharedParams } = params;
610
+ return LOCK.run(() => anonymousHttpGet_(originalUrl, params));
611
+ }
612
+
613
+ async function anonymousHttpGet_(originalUrl, params = {}) {
614
+ const { steps = [], emptyHtml = false, onError, ...sharedParams } = params;
615
+ if (emptyHtml) {
616
+ logger.debug('Returning empty HTML for URL:', originalUrl);
617
+ return EMPTY_RESCUE_HTML;
618
+ }
619
+
620
+ try {
581
621
  if (steps.length === 0) {
582
- return singleHttpGetStep(originalUrl, sharedParams);
622
+ return await singleHttpGetStep(originalUrl, sharedParams);
583
623
  }
584
624
  if (!chrome?.webRequest?.onHeadersReceived) {
585
625
  throw new MultiStepDoublefetchNotSupportedError();
@@ -616,10 +656,7 @@ export async function anonymousHttpGet(originalUrl, params = {}) {
616
656
  const stepIdx = unsafeStepIdx; // eliminate pitfalls due to mutability
617
657
  const currentStep = steps[stepIdx];
618
658
  const nextStep = steps[stepIdx + 1];
619
- const localParams = {
620
- ...sharedParams,
621
- ...currentStep,
622
- };
659
+ const localParams = { ...sharedParams, ...currentStep };
623
660
 
624
661
  const readyForNextStep = new Promise((resolve, reject) => {
625
662
  observer.onChange = null;
@@ -801,7 +838,22 @@ export async function anonymousHttpGet(originalUrl, params = {}) {
801
838
  }
802
839
  }
803
840
  return content;
804
- });
841
+ } catch (e) {
842
+ if (onError) {
843
+ const rescueParams = {
844
+ ...sharedParams,
845
+ ...onError,
846
+ };
847
+ logger.info(
848
+ 'Entering rescue path for URL:',
849
+ originalUrl,
850
+ 'Config:',
851
+ rescueParams,
852
+ );
853
+ return anonymousHttpGet_(originalUrl, rescueParams);
854
+ }
855
+ throw e;
856
+ }
805
857
  }
806
858
 
807
859
  // 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;