@whotracksme/reporting 9.0.1 โ†’ 10.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,33 @@
1
+ # v10.0.0 (Wed Jun 03 2026)
2
+
3
+ #### ๐Ÿ’ฅ Breaking Change
4
+
5
+ - page: improved double-fetch and add limited support for JSON-LD. [#209](https://github.com/whotracksme/webextension-packages/pull/209) ([@philipp-classen](https://github.com/philipp-classen))
6
+ - (refactor) extract shared error handling code [#209](https://github.com/whotracksme/webextension-packages/pull/209) ([@philipp-classen](https://github.com/philipp-classen))
7
+
8
+ #### ๐Ÿ› Bug Fix
9
+
10
+ - Workaround for Linkedom to detect the title in the <title> element [#211](https://github.com/whotracksme/webextension-packages/pull/211) ([@philipp-classen](https://github.com/philipp-classen))
11
+
12
+ #### Authors: 1
13
+
14
+ - Philipp ClaรŸen ([@philipp-classen](https://github.com/philipp-classen))
15
+
16
+ ---
17
+
18
+ # v9.0.2 (Wed Jun 03 2026)
19
+
20
+ #### ๐Ÿ› Bug Fix
21
+
22
+ - The old implemtention was overly aggressive in detecting page modifications. [#210](https://github.com/whotracksme/webextension-packages/pull/210) ([@philipp-classen](https://github.com/philipp-classen))
23
+ - Revert "Follow-up: experiment with sequentializing writes to work around a potential (#187)" [#208](https://github.com/whotracksme/webextension-packages/pull/208) ([@philipp-classen](https://github.com/philipp-classen))
24
+
25
+ #### Authors: 1
26
+
27
+ - Philipp ClaรŸen ([@philipp-classen](https://github.com/philipp-classen))
28
+
29
+ ---
30
+
1
31
  # v9.0.1 (Wed Apr 29 2026)
2
32
 
3
33
  #### ๐Ÿ› Bug Fix
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "9.0.1",
3
+ "version": "10.0.0",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
@@ -10,7 +10,7 @@
10
10
  */
11
11
 
12
12
  import logger from './logger';
13
- import { requireParam, lazyInitAsync } from './utils';
13
+ import { requireParam, requireInt, lazyInitAsync } from './utils';
14
14
  import { randomBetween } from './random';
15
15
  import { BadJobError } from './errors';
16
16
  import { anonymousHttpGet } from './http';
@@ -46,6 +46,50 @@ function isSubSequence({ sequence, subsequence }) {
46
46
  return i === subsequence.length;
47
47
  }
48
48
 
49
+ export function toTrustedUrl(url, { baseUrl, log, logWarn }) {
50
+ if (!url) {
51
+ return null;
52
+ }
53
+
54
+ if (!baseUrl.startsWith('https://')) {
55
+ logWarn('baseUrl must be an absolute URL (and https only):', baseUrl);
56
+ return null;
57
+ }
58
+ if (!url.startsWith('https://') && !url.startsWith('/')) {
59
+ // note: relative URL without a leading '/' are technically possible,
60
+ // but uncommon enough that we can ignore. If we handle them, it is
61
+ // opening more possibilities of false-positives.
62
+ log('URL must either absolute or relative with a leading /', url);
63
+ return null;
64
+ }
65
+
66
+ let from;
67
+ try {
68
+ from = new URL(baseUrl);
69
+ } catch (e) {
70
+ logWarn('Invalid baseUrl (possible but unexpected):', baseUrl);
71
+ return null;
72
+ }
73
+
74
+ let to;
75
+ try {
76
+ to = new URL(url, baseUrl);
77
+ } catch (e) {
78
+ log('Ignore invalid url:', url);
79
+ return null;
80
+ }
81
+
82
+ if (from.origin !== to.origin) {
83
+ log('origin mismatch found:', baseUrl, '->', url);
84
+ return null;
85
+ }
86
+
87
+ // Normalization (https://example.test/foo#123 => https://example.test/foo).
88
+ // We are looking for the most simple version of the URL
89
+ to.hash = '';
90
+ return to.toString();
91
+ }
92
+
49
93
  /**
50
94
  * This checks if the extracted title of a website is safe to share.
51
95
  * To decide, it compares it with the title on the doublefetch HTML.
@@ -134,6 +178,107 @@ export function titlesMatchAfterDoublefetch({
134
178
  return false;
135
179
  }
136
180
 
181
+ // Conservative list of "@type" fields that related only to the current website.
182
+ // In other words, types that are purely navigational should not be listed.
183
+ // Same with types that related to other entities like the organization or
184
+ // information about the author.
185
+ //
186
+ // Note: Schema.org is not forced, but it is the most common vocabulary by far.
187
+ // Thus a good starting point to extend coverage, is its documentation:
188
+ // https://schema.org/docs/full.html
189
+ const URL_RELATED_JSONLD_TYPES = new Set([
190
+ // Schema.org
191
+ 'article', // covers a relatively common typo (should be "Article")
192
+ 'Article',
193
+ 'BackgroundNewsArticle',
194
+ 'NewsArticle',
195
+ 'BlogPosting',
196
+ 'PodcastEpisode',
197
+ 'ReportageNewsArticle',
198
+ 'ScholarlyArticle',
199
+ 'TechArticle',
200
+ 'VideoObject',
201
+ 'WebPage',
202
+ ]);
203
+
204
+ export function findAlternativeUrlInJsonLD(jsonld) {
205
+ const { '@type': type, '@id': url } = jsonld;
206
+ if (!url || !type || !url.startsWith('https://')) return null;
207
+ return URL_RELATED_JSONLD_TYPES.has(type) ? url : null;
208
+ }
209
+
210
+ export function aggregateMetaDataInJsonLD(jsonldArray) {
211
+ const matches = [];
212
+
213
+ for (const jsonld of jsonldArray) {
214
+ const { '@type': type, '@context': context } = jsonld;
215
+ if (context !== 'http://schema.org' && context !== 'https://schema.org') {
216
+ continue;
217
+ }
218
+ if (!URL_RELATED_JSONLD_TYPES.has(type)) {
219
+ continue;
220
+ }
221
+
222
+ const content = {};
223
+ for (const key of [
224
+ 'dateCreated',
225
+ 'dateModified',
226
+ 'datePublished',
227
+ 'uploadDate',
228
+ 'duration',
229
+ ]) {
230
+ if (jsonld[key]) {
231
+ content[key] = jsonld[key];
232
+ }
233
+ }
234
+ if (Object.keys(content).length > 0) {
235
+ content.type = type;
236
+ }
237
+ matches.push(content);
238
+ }
239
+ if (matches.length === 0) {
240
+ return {};
241
+ }
242
+
243
+ // The first always wins, but we can try to merge information
244
+ // from other entries as long as they are not conflicting.
245
+ // It is rare, a use case are entries that are duplicated, but
246
+ // the second entry has extra fields.
247
+ let result = matches.shift();
248
+ for (const other of matches) {
249
+ if (
250
+ Object.entries(result).every(
251
+ ([key, value]) => (other[key] || value) === value,
252
+ )
253
+ ) {
254
+ for (const [key, value] of Object.entries(other)) {
255
+ result[key] ||= value;
256
+ }
257
+ }
258
+ }
259
+ return result;
260
+ }
261
+
262
+ /**
263
+ * Heuristic to reject text that is clearly not a timestamp.
264
+ * It does not have to be extremely precise.
265
+ */
266
+ export function looksLikeSafeTimestamp(str) {
267
+ if (typeof str !== 'string') return false;
268
+ if (str.length < 4 || str.length > 40) return false;
269
+ return !isNaN(new Date(str));
270
+ }
271
+
272
+ export function looksLikeSafeDuration(str) {
273
+ if (typeof str !== 'string') return false;
274
+ if (str.length > 20) return false;
275
+
276
+ // ISO 8601 durations (https://en.wikipedia.org/wiki/ISO_8601#Durations)
277
+ return /^P(?!$)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?$/.test(
278
+ str,
279
+ );
280
+ }
281
+
137
282
  /**
138
283
  * The activity should be number between 0 and 1. To avoid suprises like
139
284
  * leaking details such as clock resolution or floating point rounding,
@@ -264,15 +409,42 @@ export default class DoublefetchPageHandler {
264
409
  if (!preDoublefetch) {
265
410
  throw new BadJobError('preDoublefetch missing');
266
411
  }
267
- const canonicalUrl = preDoublefetch?.meta?.canonicalUrl;
268
- const canonicalUrlDiffers = canonicalUrl && canonicalUrl !== url;
269
412
 
270
413
  const pageFetcher = this.pageFetcherProvider();
271
414
  const log = logger.debug.bind(logger.debug, `[doublefetch=${url}]`);
272
415
  const logWarn = logger.warn.bind(logger.warn, `[doublefetch=${url}]`);
416
+ const withBaseUrl = (baseUrl) => ({ baseUrl, log, logWarn });
417
+ const canonicalUrl = toTrustedUrl(
418
+ preDoublefetch?.meta?.canonicalUrl,
419
+ withBaseUrl(url),
420
+ );
421
+ const canonicalUrlDiffers = canonicalUrl && canonicalUrl !== url;
273
422
 
274
423
  try {
275
- const checkUrl = async (urlToTest, { isCanonicalUrl }) => {
424
+ // shared error handling when testing alternative URLs (e.g. canonical URLs)
425
+ const markAsPrivateOrRethrowToRetry = async (failedUrl, e) => {
426
+ if (e.isPermanentError) {
427
+ logWarn(
428
+ 'Alternative URL failed permanently, so mark it as private:',
429
+ failedUrl,
430
+ e,
431
+ );
432
+ await this._tryMarkAsPrivate(failedUrl);
433
+ } else {
434
+ throw e;
435
+ }
436
+ };
437
+
438
+ const checkUrl = async (urlToTest, { isCanonicalUrl, level = 0 }) => {
439
+ if (requireInt(level) >= 3) {
440
+ // By design, there should be at most two recursion steps:
441
+ // - level: 0 (initial call) [may recurse]
442
+ // - level: 1 (test discovered candidates) [only new JSON-LD candidates may recurse]
443
+ // - level: 2 (reachable by deep JSON-LD candidate) [may NOT recurse]
444
+ // - level: 3 (unreachable and indicates a bug)
445
+ throw new Error('exceeded maximum recursion level');
446
+ }
447
+
276
448
  if (await this.newPageApprover.mightBeMarkedAsPrivate(urlToTest)) {
277
449
  return { ok: false, details: 'marked as private in bloom filter' };
278
450
  }
@@ -283,41 +455,49 @@ export default class DoublefetchPageHandler {
283
455
  return { ok: false, details: rejectReason };
284
456
  }
285
457
 
286
- const canonicalUrl2 = pageStructure?.meta?.canonicalUrl;
287
- if (canonicalUrl2) {
288
- if (!isCanonicalUrl && urlToTest === canonicalUrl2) {
458
+ // Also consider alternative URLs that we just discovered.
459
+ // If we found a canonical URL, we want to try it immediately,
460
+ // even before the actual URL that we want to test (urlToTest).
461
+ //
462
+ // Note: There are more canidates (e.g. JSON-LD), but these
463
+ // will be delayed and only tested with the actual URL fails.
464
+ const canonicalUrlCandidate = toTrustedUrl(
465
+ pageStructure.meta?.canonicalUrl,
466
+ withBaseUrl(urlToTest),
467
+ );
468
+ if (canonicalUrlCandidate) {
469
+ if (!isCanonicalUrl && urlToTest === canonicalUrlCandidate) {
289
470
  log(
290
471
  'Found a matching canonical URL in doublefetch result for URL:',
291
472
  urlToTest,
292
473
  );
293
474
  isCanonicalUrl = true;
294
- } else if (urlToTest === url && canonicalUrl2 !== canonicalUrl) {
475
+ } else if (
476
+ urlToTest === url &&
477
+ canonicalUrlCandidate !== canonicalUrl
478
+ ) {
479
+ // We detected a potential canonical URL, but since it does not
480
+ // match our original URL, we cannot confirm yet. If it does not
481
+ // work, ignore it and continue.
295
482
  log(
296
483
  'Updated canonical URL from',
297
484
  canonicalUrl,
298
- 'to',
299
- canonicalUrl2,
485
+ 'to the candidate',
486
+ canonicalUrlCandidate,
300
487
  );
301
488
  try {
302
- const result = await checkUrl(canonicalUrl2, {
489
+ const result = await checkUrl(canonicalUrlCandidate, {
303
490
  isCanonicalUrl: true,
491
+ level: level + 1,
304
492
  });
305
493
  if (result.ok) {
494
+ log('Confirmed candidate:', canonicalUrlCandidate);
306
495
  return result;
307
496
  }
308
497
  } catch (e) {
309
- if (e.isPermanentError) {
310
- logWarn(
311
- 'Failed to process (corrected) canonical URL',
312
- canonicalUrl2,
313
- '(falling back to original URL now)',
314
- e,
315
- );
316
- await this._tryMarkAsPrivate(canonicalUrl2);
317
- } else {
318
- throw e;
319
- }
498
+ await markAsPrivateOrRethrowToRetry(canonicalUrlCandidate, e);
320
499
  }
500
+ log('Candidate did not work:', canonicalUrlCandidate);
321
501
  }
322
502
  }
323
503
 
@@ -328,6 +508,44 @@ export default class DoublefetchPageHandler {
328
508
  log,
329
509
  });
330
510
  if (!accept) {
511
+ // Now that the actual URL failed, try other alternative URLs.
512
+ // JSON-LD may include candidates, but they are less trustworthy.
513
+ const mayUseJsonLD = !isCanonicalUrl || level <= 1;
514
+ if (mayUseJsonLD && pageStructure?.meta?.jsonld?.length > 0) {
515
+ for (const jsonld of pageStructure.meta.jsonld) {
516
+ const bestMatch = findAlternativeUrlInJsonLD(jsonld);
517
+ const jsonldCandidateUrl = toTrustedUrl(
518
+ bestMatch,
519
+ withBaseUrl(urlToTest),
520
+ );
521
+ if (
522
+ jsonldCandidateUrl &&
523
+ jsonldCandidateUrl !== canonicalUrl &&
524
+ jsonldCandidateUrl !== urlToTest
525
+ ) {
526
+ log(
527
+ 'Structure did not match, but try a candidate from JSON-LD instead:',
528
+ jsonldCandidateUrl,
529
+ );
530
+ try {
531
+ const result = await checkUrl(jsonldCandidateUrl, {
532
+ isCanonicalUrl: true,
533
+ level: level + 1,
534
+ });
535
+ if (result.ok) {
536
+ log('Confirmed candidate:', jsonldCandidateUrl);
537
+ return result;
538
+ }
539
+ } catch (e) {
540
+ await markAsPrivateOrRethrowToRetry(jsonldCandidateUrl, e);
541
+ }
542
+ log('JSON-LD candidate did not work:', jsonldCandidateUrl);
543
+ break; // stop after checking one candidate
544
+ }
545
+ }
546
+ }
547
+
548
+ // No luck with the alternative URLs either. Give up.
331
549
  return { ok: false, details };
332
550
  }
333
551
 
@@ -335,6 +553,7 @@ export default class DoublefetchPageHandler {
335
553
  page,
336
554
  doublefetchUrl: urlToTest,
337
555
  isCanonicalUrl,
556
+ doublefetchPageStructure: pageStructure,
338
557
  log,
339
558
  logWarn,
340
559
  });
@@ -344,29 +563,25 @@ export default class DoublefetchPageHandler {
344
563
  return { ok: true, safePage };
345
564
  };
346
565
 
566
+ // Test URLs in this order:
567
+ // 1. Canonical URL (if it exists and differs from the original URL)
568
+ // 2. Original URL
569
+ // 3. Discovered alternative URLs (will trigger recursive calls)
347
570
  let safePage;
348
571
  if (canonicalUrlDiffers) {
349
572
  try {
573
+ // step 1: canonical URL
350
574
  const result = await checkUrl(canonicalUrl, { isCanonicalUrl: true });
351
575
  if (result.ok) {
352
576
  safePage = result.safePage;
353
577
  }
354
578
  } catch (e) {
355
- if (e.isPermanentError) {
356
- logWarn(
357
- 'Failed to process canonical URL',
358
- canonicalUrl,
359
- '(falling back to original URL now)',
360
- e,
361
- );
362
- await this._tryMarkAsPrivate(canonicalUrl);
363
- } else {
364
- throw e;
365
- }
579
+ await markAsPrivateOrRethrowToRetry(canonicalUrl, e);
366
580
  }
367
581
  }
368
582
 
369
583
  if (!safePage) {
584
+ // step 2: original URL
370
585
  const isCanonicalUrl = url === canonicalUrl;
371
586
  const result = await checkUrl(url, { isCanonicalUrl });
372
587
  if (result.ok) {
@@ -403,9 +618,9 @@ export default class DoublefetchPageHandler {
403
618
  const accept = () => ({ accept: true });
404
619
  const discard = (reason) => ({ accept: false, details: reason });
405
620
 
406
- if (before.noindex !== false) {
621
+ if (before.noindex !== false && page.pageLoadMethod === 'full-page-load') {
407
622
  logger.warn(
408
- 'noindex pages should have been filtered out already:',
623
+ 'noindex pages should have been filtered out already (it was a full-page-load):',
409
624
  before,
410
625
  );
411
626
  return discard('noindex must be false (before)');
@@ -448,32 +663,61 @@ export default class DoublefetchPageHandler {
448
663
  }
449
664
  }
450
665
 
451
- if (
452
- !titlesMatchAfterDoublefetch({
453
- before: page.title,
454
- after: after.title,
455
- })
456
- ) {
666
+ // Now, confirm the title, or more precise the "page title".
667
+ // There are three types of titles:
668
+ // 1) "page title": the title from the tab API (should be what the user saw)
669
+ // 2) "DOM title": the title in the "page-structure" (before doublefetch)
670
+ // 3) "doublefetch title(s)": again, extract by "page-structure", but not from
671
+ // the real document, but from the parsed HTML *after* a doublefetch request.
672
+ //
673
+ // Candidates for the "doublefetch title":
674
+ // There is always the main title (typically <title>...</title>), but
675
+ // we can safely try fallback like "og:title" (Open Graph Meta Tags).
676
+ const doublefetchTitles = [after.title];
677
+ if (after?.meta?.og?.title && after.meta.og.title !== after.title) {
678
+ doublefetchTitles.push(after.meta.og.title);
679
+ }
680
+
681
+ const confirmTitle = (before) =>
682
+ doublefetchTitles.some((after) =>
683
+ titlesMatchAfterDoublefetch({ before, after }),
684
+ );
685
+
686
+ // Always confirm the "page title" (it will be part of the message)
687
+ if (!confirmTitle(page.title)) {
457
688
  return discard(
458
- `titles do not match the page title: <<${page.title}>> ==> <<${after.title}>>`,
689
+ `no match for the 'page title' (tab API): <<${
690
+ page.title
691
+ }>> ==> ${JSON.stringify(doublefetchTitles)}`,
459
692
  );
460
693
  }
694
+
695
+ // When a page gets loaded, the "page title" and "DOM title" should generally match.
696
+ // But for single-page applications, it is possible that the "DOM title" gets outdated,
697
+ // because the content may not be fully updated during the history navigations.
698
+ // This is why this step needs to be optional (to avoid false-negatives).
461
699
  if (
462
700
  page.pageLoadMethod !== 'history-navigation' &&
463
- !titlesMatchAfterDoublefetch({
464
- before: before.title,
465
- after: after.title,
466
- })
701
+ !confirmTitle(before.title)
467
702
  ) {
468
703
  return discard(
469
- `titles do not match the meta title: <<${before.title}>> ==> <<${after.title}>>`,
704
+ `no match for the 'DOM title' (extracted via 'page-structure'): <<${
705
+ before.title
706
+ }>> ==> ${JSON.stringify(doublefetchTitles)}`,
470
707
  );
471
708
  }
472
709
 
473
710
  return accept();
474
711
  }
475
712
 
476
- _sanitizePage({ page, doublefetchUrl, isCanonicalUrl, log, logWarn }) {
713
+ _sanitizePage({
714
+ page,
715
+ doublefetchUrl,
716
+ isCanonicalUrl,
717
+ doublefetchPageStructure,
718
+ log,
719
+ logWarn,
720
+ }) {
477
721
  const safePage = {
478
722
  url: doublefetchUrl,
479
723
  title: page.title,
@@ -567,6 +811,34 @@ export default class DoublefetchPageHandler {
567
811
  if (page.ref) {
568
812
  safePage.ref = maskUrl(page.ref);
569
813
  }
814
+
815
+ if (doublefetchPageStructure.meta?.jsonld?.length > 0) {
816
+ const { type, ...safeFields } = aggregateMetaDataInJsonLD(
817
+ doublefetchPageStructure.meta.jsonld,
818
+ );
819
+ if (type) {
820
+ safePage.jsonld = { type };
821
+
822
+ // timestamps
823
+ for (const key of [
824
+ 'dateCreated',
825
+ 'dateModified',
826
+ 'datePublished',
827
+ 'uploadDate',
828
+ ]) {
829
+ const timestamp = safeFields[key];
830
+ if (looksLikeSafeTimestamp(timestamp)) {
831
+ safePage.jsonld[key] = timestamp;
832
+ }
833
+ }
834
+
835
+ // durations (currently only the field "duration")
836
+ if (looksLikeSafeDuration(safeFields.duration)) {
837
+ safePage.jsonld.duration = safeFields.duration;
838
+ }
839
+ }
840
+ }
841
+
570
842
  return safePage;
571
843
  }
572
844
 
@@ -847,18 +847,10 @@ export default class JobScheduler {
847
847
 
848
848
  async _writeJobsToDisk() {
849
849
  this._clearAutoFlushTimer();
850
-
851
- // [Experiment] Potential workaround for a Safari bug:
852
- // * we see indicators that Safari corrupts the data when there
853
- // are concurrent write operation to chrome.storage.local
854
- // * as a mitigation, serialize the writes now
855
- this._writeToDiskExecutor ||= new SeqExecutor();
856
- return this._writeToDiskExecutor.run(async () =>
857
- this.storage.set(this.storageKey, {
858
- dbVersion: DB_VERSION,
859
- jobQueues: this.jobQueues,
860
- }),
861
- );
850
+ return this.storage.set(this.storageKey, {
851
+ dbVersion: DB_VERSION,
852
+ jobQueues: this.jobQueues,
853
+ });
862
854
  }
863
855
 
864
856
  /**
@@ -11,10 +11,18 @@
11
11
 
12
12
  import logger from './logger';
13
13
  import { BadJobError } from './errors';
14
- import random from './random';
14
+ import { random32Bit } from './random';
15
15
 
16
16
  function createPageMessage(safePage, ctry) {
17
- const { url, title, ref = null, redirects = null, search, lang } = safePage;
17
+ const {
18
+ url,
19
+ title,
20
+ ref = null,
21
+ redirects = null,
22
+ jsonld,
23
+ search,
24
+ lang,
25
+ } = safePage;
18
26
  const { activity } = safePage.aggregator;
19
27
 
20
28
  const payload = {
@@ -35,14 +43,23 @@ function createPageMessage(safePage, ctry) {
35
43
  };
36
44
  }
37
45
 
46
+ // For now, only attach when present. The alternative would be to "null"
47
+ // it like "ref" and "redirects". But the semantic might be misleading,
48
+ // since a lack of "jsonld" does not imply that the page did not have
49
+ // JSON-LD meta data. Since we are conservative in detecting it, it is
50
+ // expected to see only limited coverage at this point.
51
+ if (jsonld) {
52
+ payload.jsonld = jsonld;
53
+ }
54
+
38
55
  // consider page messages as duplicates if "payload.url" is identical
39
56
  const deduplicateBy = 'url';
40
57
 
41
58
  const body = {
42
59
  action: 'wtm.page',
43
60
  payload,
44
- ver: 3, // Note: no need to keep this number in sync among messages
45
- 'anti-duplicates': Math.floor(random() * 10000000),
61
+ ver: 4, // Note: no need to keep this number in sync among messages
62
+ 'anti-duplicates': random32Bit(),
46
63
  };
47
64
  return { body, deduplicateBy };
48
65
  }
@@ -17,6 +17,37 @@ export async function analyzePageStructure(doc) {
17
17
  if (doc.title) {
18
18
  return doc.title;
19
19
  }
20
+
21
+ // Workaround for parsers like Linkedom, which require <title> tags
22
+ // to be within <html><head> (though they are optional in HTML5):
23
+ // ```
24
+ // <!doctype html>
25
+ // <html>
26
+ // <head>
27
+ // <title>...</title>
28
+ // </head>
29
+ // <body>...</body>
30
+ // </html>
31
+ // ```
32
+ //
33
+ // But these parsers fail on valid examples like that:
34
+ // ```
35
+ // <!doctype html>
36
+ // <title>...</title>
37
+ // ```
38
+ //
39
+ // The workaround introduces the risk of false-positive matches
40
+ // (e.g. within <body>). Since the parsers are expected to create
41
+ // the implicit <html> and <head>, the following guard will not
42
+ // result in "null" on browsers like Firefox or Chrome, only
43
+ // in parsers like Linkedom.
44
+ if (doc.querySelector('html > head > title') === null) {
45
+ const title = doc.querySelector('title')?.textContent?.trim();
46
+ if (title) {
47
+ return title;
48
+ }
49
+ }
50
+
20
51
  const elem = doc.querySelector('html > head > meta[name="title"]');
21
52
  if (elem) {
22
53
  return elem.getAttribute('content') || '';
@@ -54,7 +85,6 @@ export async function analyzePageStructure(doc) {
54
85
  requestedIndex ||
55
86
  tags.includes('all') ||
56
87
  tags.includes('index') ||
57
- tags.includes('index') ||
58
88
  tags.includes('max-image-preview:large') ||
59
89
  tags.includes('max-image-preview:standard') ||
60
90
  tags.includes('max-video-preview:-1');
@@ -93,16 +123,82 @@ export async function analyzePageStructure(doc) {
93
123
  return og;
94
124
  }
95
125
 
126
+ function sanitizeJsonLdField(text) {
127
+ if (typeof text === 'string') {
128
+ const text_ = text.trim();
129
+ if (text_.length <= 2048) {
130
+ return text_;
131
+ }
132
+ }
133
+ return null;
134
+ }
135
+
136
+ // parse JSON-LD (https://json-ld.org/)
137
+ function parseJsonLd(doc) {
138
+ const jsonld = [];
139
+ for (const elem of doc.querySelectorAll(
140
+ 'script[type="application/ld+json"]',
141
+ )) {
142
+ let parsedJson;
143
+ try {
144
+ parsedJson = JSON.parse(elem.textContent);
145
+
146
+ // 1) some websites put the content in a '@graph' array, for instance:
147
+ // {
148
+ // "@context": "https://schema.org",
149
+ // "@graph": [
150
+ // {<0>},
151
+ // {<1>},
152
+ // ]
153
+ // }
154
+ // ==> lift "@graph" to the top-level
155
+ if (
156
+ typeof parsedJson['@context'] === 'string' &&
157
+ Array.isArray(parsedJson['@graph']) &&
158
+ Object.keys(parsedJson).length === 2
159
+ ) {
160
+ for (const elem of parsedJson['@graph']) {
161
+ elem['@context'] ||= parsedJson['@context'];
162
+ }
163
+ parsedJson = parsedJson['@graph'];
164
+ }
165
+
166
+ // 2) some websites use arrays, some split it across multiple scripts
167
+ // ==> everything becomes an array
168
+ parsedJson = Array.isArray(parsedJson) ? parsedJson : [parsedJson];
169
+ } catch (e) {
170
+ continue; // ignore broken JSON
171
+ }
172
+ for (const json of parsedJson) {
173
+ const entry = {};
174
+ for (const key of [
175
+ '@context',
176
+ '@type',
177
+ '@id',
178
+ 'url',
179
+ 'name',
180
+ 'headline',
181
+ 'duration',
182
+ 'dateCreated',
183
+ 'dateModified',
184
+ 'datePublished',
185
+ 'uploadDate',
186
+ ]) {
187
+ const value = sanitizeJsonLdField(json[key]);
188
+ if (value) {
189
+ entry[key] = value;
190
+ }
191
+ }
192
+ jsonld.push(entry);
193
+ }
194
+ }
195
+ return jsonld;
196
+ }
197
+
96
198
  doc = doc || document;
97
199
 
98
200
  try {
99
201
  const { noindex, requestedIndex } = parseMetaRobotTags(doc);
100
- if (noindex) {
101
- return {
102
- noindex: true,
103
- };
104
- }
105
-
106
202
  const title = getTitle(doc);
107
203
  const url = doc.URL;
108
204
 
@@ -113,6 +209,7 @@ export async function analyzePageStructure(doc) {
113
209
  const contentType = doc.contentType || null;
114
210
  const language = parseHtmlLangAttribute(doc);
115
211
  const og = parseOpenGraphMetaTags(doc);
212
+ const jsonld = parseJsonLd(doc);
116
213
 
117
214
  return {
118
215
  title,
@@ -122,8 +219,9 @@ export async function analyzePageStructure(doc) {
122
219
  language,
123
220
  contentType,
124
221
  og,
222
+ jsonld,
125
223
  },
126
- noindex: false,
224
+ noindex,
127
225
  requestedIndex,
128
226
  };
129
227
  } catch (e) {
@@ -441,10 +441,15 @@ export default class PageDB {
441
441
  return reject('incomplete information: page not fully loaded');
442
442
  }
443
443
 
444
- // check static heuristics
445
- if (page.preDoublefetch.noindex) {
444
+ // "noindex" pages can be immediately dropped unless we detected history
445
+ // navigations, because the meta information might be stale.
446
+ if (
447
+ page.preDoublefetch.noindex &&
448
+ page.pageLoadMethod !== 'history-navigation'
449
+ ) {
446
450
  return rejectForever('marked as noindex');
447
451
  }
452
+
448
453
  if (page.search && page.search.depth === 0) {
449
454
  return rejectForever('ignore search engine result pages');
450
455
  }
@@ -1454,24 +1454,30 @@ export default class Pages {
1454
1454
  return;
1455
1455
  }
1456
1456
  const { _previous_webNavigation_onCommitted, ...entry } = oldEntry;
1457
- this.openTabs.set(tabId, {
1457
+ const newEntry = {
1458
1458
  ...entry,
1459
1459
  pageLoadMethod: 'history-navigation',
1460
1460
  status: 'after-history-state-update',
1461
1461
  lastUpdatedAt: Date.now(),
1462
- pageId: ++this._pageIdGenerator,
1463
- });
1462
+ };
1464
1463
 
1465
- if (_previous_webNavigation_onCommitted?.url === url) {
1464
+ const isRedundant = _previous_webNavigation_onCommitted?.url === url;
1465
+ if (isRedundant) {
1466
1466
  logger.debug(
1467
1467
  'Skipping page event for redundant history navigation to',
1468
1468
  url,
1469
1469
  'in tab',
1470
1470
  tabId,
1471
1471
  );
1472
- } else {
1473
- this._onWebNavigation(tabId, url, entry, { isHistoryNavigation: true });
1472
+ this.openTabs.set(tabId, newEntry);
1473
+ return;
1474
1474
  }
1475
+
1476
+ // looks like a genuine navigation, so be conservative and
1477
+ // assume that the content of the page changed
1478
+ newEntry.pageId = ++this._pageIdGenerator;
1479
+ this.openTabs.set(tabId, newEntry);
1480
+ this._onWebNavigation(tabId, url, entry, { isHistoryNavigation: true });
1475
1481
  }
1476
1482
 
1477
1483
  _onWebNavigation(tabId, url, entry, { isHistoryNavigation }) {
@@ -20,6 +20,11 @@ import {
20
20
  import DoublefetchPageHandler, {
21
21
  titlesMatchAfterDoublefetch,
22
22
  sanitizeActivity,
23
+ toTrustedUrl,
24
+ findAlternativeUrlInJsonLD,
25
+ aggregateMetaDataInJsonLD,
26
+ looksLikeSafeTimestamp,
27
+ looksLikeSafeDuration,
23
28
  } from '../src/doublefetch-page-handler.js';
24
29
 
25
30
  class JobSchedulerMock {
@@ -205,6 +210,107 @@ describe('DoublefetchPageHandler', function () {
205
210
  canonicalUrl: null,
206
211
  });
207
212
  });
213
+
214
+ it('should check not only the title in <title>, but also og:title (Open Graph Protocol title)', async function () {
215
+ const page = {
216
+ aggregator: {
217
+ firstSeenAt: 1778263491203,
218
+ lastSeenAt: 1778263491206,
219
+ lastWrittenAt: 1778263562547,
220
+ activity: 0.0645025,
221
+ },
222
+ url: 'https://www.twitch.tv/sieglinde',
223
+ status: 'complete',
224
+ pageLoadMethod: 'history-navigation',
225
+ title: 'Sieglinde - Twitch',
226
+ preDoublefetch: {
227
+ meta: {
228
+ canonicalUrl: 'https://www.twitch.tv/sieglinde',
229
+ contentType: 'text/html',
230
+ jsonld: [
231
+ {
232
+ '@context': 'http://schema.org',
233
+ '@type': 'VideoObject',
234
+ name: 'Sieglinde - Twitch',
235
+ uploadDate: '2026-06-02T06:06:04Z',
236
+ },
237
+ ],
238
+ language: 'en-US',
239
+ og: {
240
+ image:
241
+ 'https://static-cdn.jtvnw.net/jtv_user_pictures/ab1ba65f-22a9-45a4-9455-50807c03e8d1-profile_image-300x300.png',
242
+ title: 'Sieglinde - Twitch',
243
+ url: 'https://www.twitch.tv/sieglinde',
244
+ video:
245
+ 'https://player.twitch.tv/?channel=sieglinde&player=facebook&autoplay=true&parent=meta.tag',
246
+ },
247
+ },
248
+ noindex: false,
249
+ requestedIndex: true,
250
+ title: 'sieglinde - Twitch',
251
+ url: 'https://www.twitch.tv/sieglinde',
252
+ lastUpdatedAt: 1778263491202,
253
+ },
254
+ lastUpdatedAt: 1778263491204,
255
+ lang: 'en',
256
+ };
257
+
258
+ // The original page title (tab API) was "Sieglinde - Twitch".
259
+ //
260
+ // Note that the DOM <title> changed after doublefetch from "sieglinde - Twitch"
261
+ // to "Twitch". "Twitch" alone would be not enough, but the Open Graph title (og:title)
262
+ // is "Sieglinde - Twitch", which still allows us to confirm the page title.
263
+ pageFetcherMock.reconfig({
264
+ 'https://www.twitch.tv/sieglinde': {
265
+ title: 'Twitch',
266
+ meta: {
267
+ canonicalUrl: 'https://www.twitch.tv/sieglinde',
268
+ language: null,
269
+ contentType: null,
270
+ og: {
271
+ title: 'Sieglinde - Twitch',
272
+ url: 'https://www.twitch.tv/sieglinde',
273
+ image:
274
+ 'https://static-cdn.jtvnw.net/jtv_user_pictures/ab1ba65f-22a9-45a4-9455-50807c03e8d1-profile_image-300x300.png',
275
+ video:
276
+ 'https://player.twitch.tv/?channel=sieglinde&player=facebook&autoplay=true&parent=meta.tag',
277
+ },
278
+ jsonld: [
279
+ {
280
+ '@context': 'http://schema.org',
281
+ '@type': 'VideoObject',
282
+ name: 'Sieglinde - Twitch',
283
+ uploadDate: '2026-05-07T06:06:04Z',
284
+ },
285
+ ],
286
+ },
287
+ noindex: false,
288
+ requestedIndex: true,
289
+ },
290
+ });
291
+
292
+ const { ok, safePage } = await uut.runJob(page);
293
+
294
+ expect(ok).to.be.true;
295
+ pageFetcherMock.expectAllFetchedOnce();
296
+ relaxedSafePageEqual(safePage, {
297
+ url: 'https://www.twitch.tv/sieglinde',
298
+ title: 'Sieglinde - Twitch',
299
+ requestedIndex: true,
300
+ lang: {
301
+ html: 'en-US',
302
+ detect: 'en',
303
+ },
304
+ aggregator: {
305
+ activity: '0.0645',
306
+ },
307
+ canonicalUrl: 'https://www.twitch.tv/sieglinde',
308
+ jsonld: {
309
+ type: 'VideoObject',
310
+ uploadDate: '2026-05-07T06:06:04Z',
311
+ },
312
+ });
313
+ });
208
314
  });
209
315
 
210
316
  describe('when given a website with canonical URL', function () {
@@ -295,7 +401,7 @@ describe('DoublefetchPageHandler', function () {
295
401
  });
296
402
  });
297
403
 
298
- describe('when a page indexed by search engine, has a canonical URL, and signals it wants to be shared', function () {
404
+ describe('when a page indexed by a search engine, has a canonical URL, and signals it wants to be shared', function () {
299
405
  it('should allow a safe Wikipedia page like https://de.wikipedia.org/wiki/J%C3%BCrgen_Klopp', async function () {
300
406
  const page = {
301
407
  aggregator: {
@@ -858,3 +964,190 @@ describe('#sanitizeActivity', function () {
858
964
  });
859
965
  });
860
966
  });
967
+
968
+ describe('#toTrustedUrl', function () {
969
+ function withBaseUrl(baseUrl) {
970
+ const noop = () => {};
971
+ return { baseUrl, log: noop, logWarn: noop };
972
+ }
973
+
974
+ for (const { url, baseUrl, expected } of [
975
+ {
976
+ url: 'https://abc.test/foo',
977
+ baseUrl: 'https://abc.test/foo',
978
+ expected: 'https://abc.test/foo',
979
+ },
980
+ {
981
+ url: 'https://abc.test/keepme',
982
+ baseUrl: 'https://abc.test/ignore',
983
+ expected: 'https://abc.test/keepme',
984
+ },
985
+ {
986
+ url: 'https://abc.test/foo',
987
+ baseUrl: 'https://example.other/',
988
+ expected: null,
989
+ },
990
+ {
991
+ url: '/foo', // relative
992
+ baseUrl: 'https://abc.test/',
993
+ expected: 'https://abc.test/foo',
994
+ },
995
+ {
996
+ url: 'foo', // relative (non-leading '/')
997
+ baseUrl: 'https://abc.test/',
998
+ expected: null,
999
+ },
1000
+ {
1001
+ url: '{{ .og_url }}', // invalid
1002
+ baseUrl: 'https://abc.test/',
1003
+ expected: null,
1004
+ },
1005
+ ]) {
1006
+ it(`url=${url} + baseUrl=${baseUrl} ==> ${expected}`, function () {
1007
+ expect(toTrustedUrl(url, withBaseUrl(baseUrl))).to.eql(expected);
1008
+ });
1009
+ }
1010
+ });
1011
+
1012
+ describe('#findAlternativeUrlInJsonLD', function () {
1013
+ it('should detect use the "@id" for "VideoObject" types', function () {
1014
+ expect(
1015
+ findAlternativeUrlInJsonLD({
1016
+ '@context': 'https://schema.org',
1017
+ '@type': 'VideoObject',
1018
+ '@id': 'https://www.youtube.com/watch?v=dNoTvg0t52c',
1019
+ name: 'EPICA - Storm The Sorrow (Official video - HD remastered)',
1020
+ uploadDate: '2012-04-24T04:55:09-07:00',
1021
+ }),
1022
+ ).to.eql('https://www.youtube.com/watch?v=dNoTvg0t52c');
1023
+ });
1024
+ });
1025
+
1026
+ describe('#aggregateMetaDataInJsonLD', function () {
1027
+ it('should merge a duplicate entry that has extra fields', function () {
1028
+ const entry1 = {
1029
+ '@context': 'https://schema.org',
1030
+ '@type': 'VideoObject',
1031
+ '@id': 'https://www.youtube.com/watch?v=W-fFHeTX70Q',
1032
+ name: 'The Best of Beethoven',
1033
+ uploadDate: '2012-11-13T03:05:47-08:00',
1034
+ };
1035
+ const entry2 = {
1036
+ ...entry1,
1037
+ duration: 'PT5858S',
1038
+ };
1039
+
1040
+ const expected = {
1041
+ type: 'VideoObject',
1042
+ uploadDate: '2012-11-13T03:05:47-08:00',
1043
+ duration: 'PT5858S',
1044
+ };
1045
+
1046
+ // the order does not matter
1047
+ expect(aggregateMetaDataInJsonLD([entry1, entry2])).to.eql(expected);
1048
+ expect(aggregateMetaDataInJsonLD([entry2, entry1])).to.eql(expected);
1049
+
1050
+ // ... we can also repeat it multiple times
1051
+ expect(aggregateMetaDataInJsonLD([entry1, entry1, entry2])).to.eql(
1052
+ expected,
1053
+ );
1054
+ expect(aggregateMetaDataInJsonLD([entry1, entry2, entry1])).to.eql(
1055
+ expected,
1056
+ );
1057
+ });
1058
+ });
1059
+
1060
+ describe('#looksLikeSafeTimestamp', function () {
1061
+ function shouldAccept(str) {
1062
+ if (!looksLikeSafeTimestamp(str)) {
1063
+ expect.fail(`Expected to be accepted, but was rejected: <<${str}>>`);
1064
+ }
1065
+ }
1066
+
1067
+ function shouldReject(str) {
1068
+ if (looksLikeSafeTimestamp(str)) {
1069
+ expect.fail(`Expected to be rejected, but was accepted: <<${str}>>`);
1070
+ }
1071
+ }
1072
+
1073
+ it('should accept typical timestamps', function () {
1074
+ shouldAccept('2024-01-15T12:34:56Z');
1075
+ shouldAccept('2012-04-24T04:55:09-07:00');
1076
+ shouldAccept('2026-02-01T08:55:42+00:00');
1077
+ shouldAccept('2024-01-15');
1078
+ shouldAccept('2021-10-07 05:14:11');
1079
+ });
1080
+
1081
+ it('should reject uncommon formats', function () {
1082
+ shouldReject('2026-03-31 15:37:45America/Sao_Paulo');
1083
+ });
1084
+
1085
+ it('should reject non-strings', function () {
1086
+ shouldReject(null);
1087
+ shouldReject(undefined);
1088
+ shouldReject(123);
1089
+ shouldReject({});
1090
+ });
1091
+
1092
+ it('should reject strings that are too short or too long', function () {
1093
+ shouldReject('');
1094
+ shouldReject('0');
1095
+ shouldReject('1/1');
1096
+ shouldReject('x'.repeat(128));
1097
+ });
1098
+
1099
+ it('should reject strings that are clearly not timestamps', function () {
1100
+ shouldReject('hello world');
1101
+ shouldReject('not a date at all');
1102
+ });
1103
+ });
1104
+
1105
+ describe('#looksLikeSafeDuration', function () {
1106
+ function shouldAccept(str) {
1107
+ if (!looksLikeSafeDuration(str)) {
1108
+ expect.fail(`Expected to be accepted, but was rejected: <<${str}>>`);
1109
+ }
1110
+ }
1111
+
1112
+ function shouldReject(str) {
1113
+ if (looksLikeSafeDuration(str)) {
1114
+ expect.fail(`Expected to be rejected, but was accepted: <<${str}>>`);
1115
+ }
1116
+ }
1117
+
1118
+ it('should accept typical ISO 8601 durations', function () {
1119
+ shouldAccept('PT1H');
1120
+ shouldAccept('PT15M');
1121
+ shouldAccept('PT1H30M');
1122
+ shouldAccept('PT1H30M45S');
1123
+ shouldAccept('P1D');
1124
+ shouldAccept('P1Y2M3DT4H5M6S');
1125
+ });
1126
+
1127
+ it('should reject malformed durations', function () {
1128
+ shouldReject('P');
1129
+ shouldReject('PT');
1130
+ shouldReject('1H');
1131
+ shouldReject('P1H');
1132
+ shouldReject('P1YT');
1133
+ shouldReject('PT1X');
1134
+ });
1135
+
1136
+ it('should reject values that are no durations', function () {
1137
+ shouldReject('');
1138
+ shouldReject('Duration');
1139
+ shouldReject('Dauer');
1140
+ shouldReject('Kesto');
1141
+ });
1142
+
1143
+ it('should reject non-strings', function () {
1144
+ shouldReject(null);
1145
+ shouldReject(undefined);
1146
+ shouldReject(123);
1147
+ shouldReject({});
1148
+ });
1149
+
1150
+ it('should reject strings that are too long', function () {
1151
+ shouldReject('P' + '1Y'.repeat(20));
1152
+ });
1153
+ });