@whotracksme/reporting 5.1.17

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.
Files changed (179) hide show
  1. package/.editorconfig +12 -0
  2. package/.eslintignore +3 -0
  3. package/.eslintrc +16 -0
  4. package/.github/workflows/release.yml +34 -0
  5. package/.github/workflows/tests.yml +20 -0
  6. package/.prettierrc +9 -0
  7. package/.tool-versions +1 -0
  8. package/CHANGELOG.md +795 -0
  9. package/LICENSE +373 -0
  10. package/README.md +1 -0
  11. package/communication/README.md +11 -0
  12. package/communication/example/index.js +43 -0
  13. package/communication/example/manifest.json +16 -0
  14. package/communication/karma.conf.cjs +19 -0
  15. package/communication/package.json +52 -0
  16. package/communication/rollup.common-config.cjs +17 -0
  17. package/communication/rollup.config.cjs +10 -0
  18. package/communication/src/encoding.js +54 -0
  19. package/communication/src/errors.js +84 -0
  20. package/communication/src/index.js +76 -0
  21. package/communication/src/logger.js +41 -0
  22. package/communication/src/padding.js +60 -0
  23. package/communication/src/proxied-http.js +231 -0
  24. package/communication/src/server-public-key-accessor.js +123 -0
  25. package/communication/src/timestamps.js +37 -0
  26. package/communication/src/trusted-clock.js +58 -0
  27. package/communication/src/utils.js +28 -0
  28. package/communication/src/zlib.js +17 -0
  29. package/communication/test/helpers/in-memory-database.js +43 -0
  30. package/communication/test/server-public-key-accessor.spec.js +135 -0
  31. package/communication/test/utils.spec.js +43 -0
  32. package/package.json +50 -0
  33. package/reporting/TODO.md +2 -0
  34. package/reporting/assets/request/bloom_filter.dat +0 -0
  35. package/reporting/assets/request/update.json +1 -0
  36. package/reporting/example/content.js +11 -0
  37. package/reporting/example/index.js +132 -0
  38. package/reporting/example/inspector/index.html +17 -0
  39. package/reporting/example/inspector/index.js +27 -0
  40. package/reporting/example/manifests/chromium.json +37 -0
  41. package/reporting/example/manifests/firefox.json +35 -0
  42. package/reporting/example/rules.json +62 -0
  43. package/reporting/example/setup.js +1 -0
  44. package/reporting/example/tests/test1.html +10 -0
  45. package/reporting/karma.conf.cjs +22 -0
  46. package/reporting/package.json +63 -0
  47. package/reporting/rollup.common-config.cjs +19 -0
  48. package/reporting/rollup.config.cjs +20 -0
  49. package/reporting/src/LRU.js +149 -0
  50. package/reporting/src/activity-estimator.js +298 -0
  51. package/reporting/src/alive-check.js +139 -0
  52. package/reporting/src/alive-message-generator.js +142 -0
  53. package/reporting/src/bloom-filters.js +345 -0
  54. package/reporting/src/country-provider.js +295 -0
  55. package/reporting/src/cyrb53.js +32 -0
  56. package/reporting/src/digest.js +33 -0
  57. package/reporting/src/doublefetch-page-handler.js +548 -0
  58. package/reporting/src/duplicate-detector.js +233 -0
  59. package/reporting/src/errors.js +84 -0
  60. package/reporting/src/event-listener-queue.js +121 -0
  61. package/reporting/src/fixed-size-cache.js +63 -0
  62. package/reporting/src/hash-detector.js +1526 -0
  63. package/reporting/src/html-parser.js +17 -0
  64. package/reporting/src/http.js +265 -0
  65. package/reporting/src/index.js +14 -0
  66. package/reporting/src/job-scheduler.js +912 -0
  67. package/reporting/src/logger.js +121 -0
  68. package/reporting/src/md5.js +334 -0
  69. package/reporting/src/message-sender.js +51 -0
  70. package/reporting/src/network.js +140 -0
  71. package/reporting/src/new-page-approver.js +119 -0
  72. package/reporting/src/page-aggregator.js +185 -0
  73. package/reporting/src/page-quorum-check-handler.js +200 -0
  74. package/reporting/src/page-structure.js +136 -0
  75. package/reporting/src/pagedb.js +671 -0
  76. package/reporting/src/pages.js +1798 -0
  77. package/reporting/src/patterns-updater.js +310 -0
  78. package/reporting/src/patterns.js +416 -0
  79. package/reporting/src/persisted-bitarray.js +265 -0
  80. package/reporting/src/persisted-hashes.js +189 -0
  81. package/reporting/src/quorum-checker.js +327 -0
  82. package/reporting/src/random.js +39 -0
  83. package/reporting/src/reporting.js +290 -0
  84. package/reporting/src/request/config.js +116 -0
  85. package/reporting/src/request/content-script.js +77 -0
  86. package/reporting/src/request/database.js +147 -0
  87. package/reporting/src/request/dnt.js +24 -0
  88. package/reporting/src/request/hash.js +101 -0
  89. package/reporting/src/request/index.js +874 -0
  90. package/reporting/src/request/page-telemetry.js +42 -0
  91. package/reporting/src/request/qs-whitelist2.js +247 -0
  92. package/reporting/src/request/resources/prob.js +601 -0
  93. package/reporting/src/request/steps/block-rules.js +40 -0
  94. package/reporting/src/request/steps/check-context.js +37 -0
  95. package/reporting/src/request/steps/cookie-context.js +209 -0
  96. package/reporting/src/request/steps/oauth-detector.js +101 -0
  97. package/reporting/src/request/steps/page-logger.js +177 -0
  98. package/reporting/src/request/steps/redirect-tagger.js +75 -0
  99. package/reporting/src/request/steps/subdomain-check.js +34 -0
  100. package/reporting/src/request/steps/token-checker/index.js +189 -0
  101. package/reporting/src/request/steps/token-checker/token-domain.js +129 -0
  102. package/reporting/src/request/steps/token-examiner.js +182 -0
  103. package/reporting/src/request/steps/token-telemetry/cached-entry-pipeline.js +210 -0
  104. package/reporting/src/request/steps/token-telemetry/index.js +234 -0
  105. package/reporting/src/request/steps/token-telemetry/key-pipeline.js +109 -0
  106. package/reporting/src/request/steps/token-telemetry/token-pipeline.js +105 -0
  107. package/reporting/src/request/time.js +73 -0
  108. package/reporting/src/request/utils/bloom-filter-packed.js +107 -0
  109. package/reporting/src/request/utils/chrome-storage-map.js +282 -0
  110. package/reporting/src/request/utils/subject.js +37 -0
  111. package/reporting/src/request/utils/temp-set.js +56 -0
  112. package/reporting/src/request/utils/tlds.js +55 -0
  113. package/reporting/src/request/utils.js +41 -0
  114. package/reporting/src/request-reporter.js +111 -0
  115. package/reporting/src/sanitizer.js +519 -0
  116. package/reporting/src/search-extractor.js +338 -0
  117. package/reporting/src/self-check.js +105 -0
  118. package/reporting/src/seq-executor.js +43 -0
  119. package/reporting/src/session-storage.js +399 -0
  120. package/reporting/src/url-analyzer.js +161 -0
  121. package/reporting/src/url-cleaner.js +60 -0
  122. package/reporting/src/utils/pacemaker.js +279 -0
  123. package/reporting/src/utils/url.js +114 -0
  124. package/reporting/src/utils.js +345 -0
  125. package/reporting/src/webrequest-pipeline/cname-uncloak.js +110 -0
  126. package/reporting/src/webrequest-pipeline/index.js +287 -0
  127. package/reporting/src/webrequest-pipeline/logger.js +14 -0
  128. package/reporting/src/webrequest-pipeline/page-store.js +282 -0
  129. package/reporting/src/webrequest-pipeline/page.js +140 -0
  130. package/reporting/src/webrequest-pipeline/pipeline.js +249 -0
  131. package/reporting/src/webrequest-pipeline/utils/webrequest.js +113 -0
  132. package/reporting/src/webrequest-pipeline/webrequest-context.js +153 -0
  133. package/reporting/test/README.md +2 -0
  134. package/reporting/test/activity-estimator.spec.js +356 -0
  135. package/reporting/test/alive-check.spec.js +156 -0
  136. package/reporting/test/alive-message-generator.spec.js +186 -0
  137. package/reporting/test/country-provider.spec.js +263 -0
  138. package/reporting/test/doublefetch-page-handler.spec.js +818 -0
  139. package/reporting/test/duplicate-detector.spec.js +689 -0
  140. package/reporting/test/helpers/dom-parsers.js +41 -0
  141. package/reporting/test/helpers/fake-session-storage.js +69 -0
  142. package/reporting/test/helpers/fast-check-utils.js +28 -0
  143. package/reporting/test/helpers/fetch-mock.js +57 -0
  144. package/reporting/test/helpers/in-memory-database.js +14 -0
  145. package/reporting/test/helpers/memory-map.js +72 -0
  146. package/reporting/test/helpers/pagedb-mocks.js +41 -0
  147. package/reporting/test/index.js +47 -0
  148. package/reporting/test/job-scheduler.spec.js +691 -0
  149. package/reporting/test/network.spec.js +72 -0
  150. package/reporting/test/page-aggregator.spec.js +104 -0
  151. package/reporting/test/page-quorum-check-handler.spec.js +86 -0
  152. package/reporting/test/pagedb.spec.js +250 -0
  153. package/reporting/test/pages.spec.js +693 -0
  154. package/reporting/test/patterns-updater.spec.js +446 -0
  155. package/reporting/test/patterns.spec.js +751 -0
  156. package/reporting/test/persisted-hashes.spec.js +169 -0
  157. package/reporting/test/reporting.spec.js +205 -0
  158. package/reporting/test/request/database.spec.js +59 -0
  159. package/reporting/test/request/hash.spec.js +108 -0
  160. package/reporting/test/request/index.spec.js +378 -0
  161. package/reporting/test/request/qs-whitelist2.spec.js +189 -0
  162. package/reporting/test/request/steps/check-context.spec.js +51 -0
  163. package/reporting/test/request/steps/oauth-detector.spec.js +339 -0
  164. package/reporting/test/request/test-pages.js +1246 -0
  165. package/reporting/test/request/utils/bloom-filter-packed.spec.js +37 -0
  166. package/reporting/test/request/utils/chrome-storage-map.spec.js +28 -0
  167. package/reporting/test/request/utils/tldts.spec.js +62 -0
  168. package/reporting/test/request/utils.spec.js +168 -0
  169. package/reporting/test/sanitizer.spec.js +1087 -0
  170. package/reporting/test/search-extractor.spec.js +590 -0
  171. package/reporting/test/seq-executor.spec.js +158 -0
  172. package/reporting/test/session-storage.spec.js +400 -0
  173. package/reporting/test/setup.js +24 -0
  174. package/reporting/test/url-analyzer.spec.js +451 -0
  175. package/reporting/test/url-cleaner.spec.js +102 -0
  176. package/reporting/test/utils/pacemaker.spec.js +222 -0
  177. package/reporting/test/utils/url.spec.js +660 -0
  178. package/reporting/test/utils.spec.js +299 -0
  179. package/reporting/test/webrequest-pipeline/pipeline.spec.js +251 -0
@@ -0,0 +1,818 @@
1
+ /**
2
+ * WhoTracks.Me
3
+ * https://whotracks.me/
4
+ *
5
+ * Copyright 2017-present Ghostery GmbH. All rights reserved.
6
+ *
7
+ * This Source Code Form is subject to the terms of the Mozilla Public
8
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
9
+ * file, You can obtain one at http://mozilla.org/MPL/2.0
10
+ */
11
+
12
+ import { expect, assert } from 'chai';
13
+ import * as fc from 'fast-check';
14
+
15
+ import Sanitizer from '../src/sanitizer';
16
+ import {
17
+ TemporarilyUnableToFetchUrlError,
18
+ PermanentlyUnableToFetchUrlError,
19
+ } from '../src/errors';
20
+ import DoublefetchPageHandler, {
21
+ titlesMatchAfterDoublefetch,
22
+ sanitizeActivity,
23
+ } from '../src/doublefetch-page-handler.js';
24
+
25
+ class JobSchedulerMock {
26
+ registerHandler(type, handler, config) {
27
+ expect(type).to.eql('doublefetch-page');
28
+ expect(handler).to.be.a('function');
29
+ if (config) {
30
+ expect(config).to.be.an('object');
31
+ }
32
+ }
33
+ }
34
+
35
+ class CountryProviderMock {
36
+ getSafeCountryCode() {
37
+ return '--';
38
+ }
39
+ }
40
+
41
+ class NewPageApproverMock {
42
+ constructor() {
43
+ this.privatePages = new Set();
44
+ }
45
+
46
+ async mightBeMarkedAsPrivate(url) {
47
+ expect(url).to.be.a('string');
48
+ return this.privatePages.has(url);
49
+ }
50
+
51
+ async markAsPrivate(url) {
52
+ expect(url).to.be.a('string');
53
+ this.privatePages.add(url);
54
+ }
55
+ }
56
+
57
+ class PageFetcherMock {
58
+ constructor(pageMocks = {}) {
59
+ this._pageMocks = pageMocks; // url to (PageStructure or Error)
60
+ this._requestedUrls = [];
61
+ }
62
+
63
+ reconfig(urlsToResults) {
64
+ this._pageMocks = urlsToResults;
65
+ this._requestedUrls = [];
66
+ }
67
+
68
+ expectAllFetchedOnce() {
69
+ const expected = Object.keys(this._pageMocks).toSorted();
70
+ const actual = [...new Set(this._requestedUrls)].toSorted();
71
+ expect(actual).to.eql(expected);
72
+ }
73
+
74
+ async doublefetchUrl(url) {
75
+ this._requestedUrls.push(url);
76
+ const result = this._pageMocks[url];
77
+ if (!result) {
78
+ throw new Error(`Unexpected URL: ${url}`);
79
+ }
80
+ if (result.isPermanentError) {
81
+ return { rejectReason: `unable to fetch page (details: ${result})` };
82
+ }
83
+ if (result instanceof Error) {
84
+ throw result;
85
+ }
86
+ return { pageStructure: result };
87
+ }
88
+ }
89
+
90
+ function relaxedSafePageEqual(safePage_, expectedSafePage_) {
91
+ const { aggregator: aggregator_, ...safePage } = safePage_;
92
+ const { aggregator: expectedAggregator_, ...expectedSafePage } =
93
+ expectedSafePage_;
94
+ expect(safePage).to.eql(expectedSafePage);
95
+
96
+ // When comparing the aggregated activity, values like the activity will
97
+ // also be approximations of their input, because random noisy is applied.
98
+ if (expectedAggregator_) {
99
+ const { activity, aggregator } = aggregator_;
100
+ const { activity: expectedActivity, expectedAggregator } =
101
+ expectedAggregator_;
102
+ if (activity !== expectedActivity) {
103
+ expect(+activity).to.be.closeTo(+expectedActivity, 0.1);
104
+ }
105
+ expect(aggregator).to.eql(expectedAggregator);
106
+ }
107
+ }
108
+
109
+ describe('DoublefetchPageHandler', function () {
110
+ let uut;
111
+ let countryProvider;
112
+ let jobScheduler;
113
+ let sanitizer;
114
+ let newPageApprover;
115
+ let pageFetcherMock;
116
+
117
+ beforeEach(function () {
118
+ jobScheduler = new JobSchedulerMock();
119
+ countryProvider = new CountryProviderMock();
120
+ sanitizer = new Sanitizer(countryProvider);
121
+ newPageApprover = new NewPageApproverMock();
122
+ pageFetcherMock = new PageFetcherMock();
123
+ uut = new DoublefetchPageHandler({
124
+ jobScheduler,
125
+ sanitizer,
126
+ newPageApprover,
127
+ pageFetcherProvider: () => pageFetcherMock,
128
+ });
129
+ });
130
+
131
+ afterEach(function () {
132
+ uut = null;
133
+ });
134
+
135
+ describe('when given a website without canonical URL', function () {
136
+ it('should allow a safe page like https://software.codidact.com/posts/291498', async function () {
137
+ const page = {
138
+ aggregator: {
139
+ firstSeenAt: 1717420575480,
140
+ lastSeenAt: 1717420575483,
141
+ lastWrittenAt: 1717420575583,
142
+ activity: 0.005740833333333333,
143
+ },
144
+ url: 'https://software.codidact.com/posts/291498',
145
+ status: 'complete',
146
+ pageLoadMethod: 'full-page-load',
147
+ title: 'Software Development - Check if a file exists in Node.js',
148
+ preDoublefetch: {
149
+ meta: {
150
+ canonicalUrl: null,
151
+ contentType: 'text/html',
152
+ language: 'en',
153
+ og: {
154
+ image:
155
+ 'https://software.codidact.comhttps://codidact.com/community-assets/software/logo-large.png',
156
+ title: 'Check if a file exists in Node.js',
157
+ url: 'https://software.codidact.com/posts/291498',
158
+ },
159
+ },
160
+ noindex: false,
161
+ requestedIndex: false,
162
+ title: 'Software Development - Check if a file exists in Node.js',
163
+ url: 'https://software.codidact.com/posts/291498',
164
+ lastUpdatedAt: 1717420575479,
165
+ },
166
+ lastUpdatedAt: 1717420575480,
167
+ lang: 'en',
168
+ };
169
+
170
+ pageFetcherMock.reconfig({
171
+ 'https://software.codidact.com/posts/291498': {
172
+ title:
173
+ '\n Software Development - Check if a file exists in Node.js\n',
174
+ meta: {
175
+ canonicalUrl: null,
176
+ language: 'en',
177
+ contentType: null,
178
+ og: {
179
+ title: 'Check if a file exists in Node.js',
180
+ url: 'https://software.codidact.com/posts/291498',
181
+ image:
182
+ 'https://software.codidact.comhttps://codidact.com/community-assets/software/logo-large.png',
183
+ },
184
+ },
185
+ noindex: false,
186
+ requestedIndex: false,
187
+ },
188
+ });
189
+
190
+ const { ok, safePage } = await uut.runJob(page);
191
+
192
+ expect(ok).to.be.true;
193
+ pageFetcherMock.expectAllFetchedOnce();
194
+ relaxedSafePageEqual(safePage, {
195
+ url: 'https://software.codidact.com/posts/291498',
196
+ title: 'Software Development - Check if a file exists in Node.js',
197
+ requestedIndex: false,
198
+ lang: {
199
+ html: 'en',
200
+ detect: 'en',
201
+ },
202
+ aggregator: {
203
+ activity: '0.0062',
204
+ },
205
+ canonicalUrl: null,
206
+ });
207
+ });
208
+ });
209
+
210
+ describe('when given a website with canonical URL', function () {
211
+ it('should allow a safe page like https://www.ghostery.com/ (coming from https://www.ghostery.com/)', async function () {
212
+ const page = {
213
+ aggregator: {
214
+ firstSeenAt: 1717021430155,
215
+ lastSeenAt: 1717021430158,
216
+ lastWrittenAt: 1717021430395,
217
+ activity: 0.005635,
218
+ },
219
+ url: 'https://www.ghostery.com/',
220
+ status: 'complete',
221
+ pageLoadMethod: 'full-page-load',
222
+ title: 'Best Ad Blocker & Privacy Browser | Ghostery',
223
+ redirects: [
224
+ {
225
+ from: 'https://ghostery.com/',
226
+ to: 'https://www.ghostery.com/',
227
+ statusCode: 301,
228
+ },
229
+ ],
230
+ preDoublefetch: {
231
+ meta: {
232
+ canonicalUrl: 'https://www.ghostery.com/',
233
+ contentType: 'text/html',
234
+ language: 'en',
235
+ og: {
236
+ image:
237
+ 'https://www.ghostery.com/assets/ghostery-mobile-5b87b0a50ae994a6526277563ed73ab9ee96bb34506cf30b11b19bfc0d365f0f.png',
238
+ title: 'Best Ad Blocker & Privacy Browser',
239
+ url: 'https://www.ghostery.com/',
240
+ },
241
+ },
242
+ noindex: false,
243
+ requestedIndex: false,
244
+ title: 'Best Ad Blocker & Privacy Browser | Ghostery',
245
+ url: 'https://www.ghostery.com/',
246
+ lastUpdatedAt: 1717021430154,
247
+ },
248
+ lastUpdatedAt: 1717021430156,
249
+ lang: 'en',
250
+ };
251
+
252
+ pageFetcherMock.reconfig({
253
+ 'https://www.ghostery.com/': {
254
+ title: 'Best Ad Blocker & Privacy Browser | Ghostery',
255
+ meta: {
256
+ canonicalUrl: 'https://www.ghostery.com/',
257
+ language: 'en',
258
+ contentType: null,
259
+ og: {
260
+ title: 'Best Ad Blocker & Privacy Browser',
261
+ url: 'https://www.ghostery.com/',
262
+ image:
263
+ 'https://www.ghostery.com/assets/ghostery-mobile-5b87b0a50ae994a6526277563ed73ab9ee96bb34506cf30b11b19bfc0d365f0f.png',
264
+ },
265
+ },
266
+ noindex: false,
267
+ requestedIndex: false,
268
+ },
269
+ });
270
+
271
+ const { ok, safePage } = await uut.runJob(page);
272
+
273
+ expect(ok).to.be.true;
274
+ pageFetcherMock.expectAllFetchedOnce();
275
+ relaxedSafePageEqual(safePage, {
276
+ url: 'https://www.ghostery.com/',
277
+ title: 'Best Ad Blocker & Privacy Browser | Ghostery',
278
+ requestedIndex: false,
279
+ lang: {
280
+ html: 'en',
281
+ detect: 'en',
282
+ },
283
+ aggregator: {
284
+ activity: '0.0056',
285
+ },
286
+ canonicalUrl: 'https://www.ghostery.com/',
287
+ redirects: [
288
+ {
289
+ from: 'https://ghostery.com/',
290
+ to: 'https://www.ghostery.com/',
291
+ statusCode: 301,
292
+ },
293
+ ],
294
+ });
295
+ });
296
+ });
297
+
298
+ describe('when a page indexed by search engine, has a canonical URL, and signals it wants to be shared', function () {
299
+ it('should allow a safe Wikipedia page like https://de.wikipedia.org/wiki/J%C3%BCrgen_Klopp', async function () {
300
+ const page = {
301
+ aggregator: {
302
+ firstSeenAt: 1717193683762,
303
+ lastSeenAt: 1717193683763,
304
+ lastWrittenAt: 1717193739746,
305
+ activity: 0.05103,
306
+ },
307
+ url: 'https://de.wikipedia.org/wiki/J%C3%BCrgen_Klopp',
308
+ status: 'complete',
309
+ pageLoadMethod: 'full-page-load',
310
+ title: 'Jürgen Klopp – Wikipedia',
311
+ search: {
312
+ category: 'go',
313
+ query: 'jürgen klopp',
314
+ depth: 1,
315
+ },
316
+ ref: 'https://www.google.com/search?gs_ssp=eJzj4tLP1TcwMTOOLzA1YPTizTq8pyg9NU8hOye_oAAAcLEJFA&q=j%C3%BCrgen+klopp&oq=&gs_lcrp=EgZjaHJvbWUqDwgHEC4YAxiPARi0AhjqAjIJCAAQRRg7GMIDMhEIARAAGAMYQhiPARi0AhjqAjIRCAIQABgDGEIYjwEYtAIY6gIyEQgDEAAYAxhCGI8BGLQCGOoCMg8IBBAuGAMYjwEYtAIY6gIyEQgFEAAYAxhCGI8BGLQCGOoCMg8IBhAuGAMYjwEYtAIY6gIyDwgHEC4YAxiPARi0AhjqAtIBDDc4NTEwODA2ajBqN6gCCLACAQ&sourceid=chrome&ie=UTF-8',
317
+ preDoublefetch: {
318
+ meta: {
319
+ canonicalUrl: 'https://de.wikipedia.org/wiki/J%C3%BCrgen_Klopp',
320
+ contentType: 'text/html',
321
+ language: 'de',
322
+ og: {
323
+ image:
324
+ 'https://upload.wikimedia.org/wikipedia/commons/8/81/J%C3%BCrgen_Klopp%2C_Liverpool_vs._Chelsea%2C_UEFA_Super_Cup_2019-08-14_04.jpg',
325
+ title: 'Jürgen Klopp – Wikipedia',
326
+ },
327
+ },
328
+ noindex: false,
329
+ requestedIndex: true,
330
+ title: 'Jürgen Klopp – Wikipedia',
331
+ url: 'https://de.wikipedia.org/wiki/J%C3%BCrgen_Klopp',
332
+ lastUpdatedAt: 1717193683762,
333
+ },
334
+ lastUpdatedAt: 1717193683763,
335
+ lang: 'de',
336
+ };
337
+
338
+ pageFetcherMock.reconfig({
339
+ 'https://de.wikipedia.org/wiki/J%C3%BCrgen_Klopp': {
340
+ title: 'Jürgen Klopp – Wikipedia',
341
+ meta: {
342
+ canonicalUrl: 'https://de.wikipedia.org/wiki/J%C3%BCrgen_Klopp',
343
+ language: 'de',
344
+ contentType: null,
345
+ og: {
346
+ title: 'Jürgen Klopp – Wikipedia',
347
+ image:
348
+ 'https://upload.wikimedia.org/wikipedia/commons/8/81/J%C3%BCrgen_Klopp%2C_Liverpool_vs._Chelsea%2C_UEFA_Super_Cup_2019-08-14_04.jpg',
349
+ },
350
+ },
351
+ noindex: false,
352
+ requestedIndex: true,
353
+ },
354
+ });
355
+
356
+ const { ok, safePage } = await uut.runJob(page);
357
+
358
+ expect(ok).to.be.true;
359
+ pageFetcherMock.expectAllFetchedOnce();
360
+ relaxedSafePageEqual(safePage, {
361
+ url: 'https://de.wikipedia.org/wiki/J%C3%BCrgen_Klopp',
362
+ title: 'Jürgen Klopp – Wikipedia',
363
+ requestedIndex: true,
364
+ lang: {
365
+ html: 'de',
366
+ detect: 'de',
367
+ },
368
+ aggregator: {
369
+ activity: '0.0510',
370
+ },
371
+ canonicalUrl: 'https://de.wikipedia.org/wiki/J%C3%BCrgen_Klopp',
372
+ ref: 'https://www.google.com/ (PROTECTED)',
373
+ search: {
374
+ query: 'jürgen klopp',
375
+ category: 'go',
376
+ depth: 1,
377
+ },
378
+ });
379
+ });
380
+ });
381
+
382
+ // YouTube is an example where this happens. Some single-page navigations update the
383
+ // canonical URL in the DOM after navigations, but every page. The canonical URL
384
+ // can only be trusted in after full page load. Either by a normal navigation, or
385
+ // in a double-fetch request.
386
+ describe('when canonical URLs do not get updated on history navigations', function () {
387
+ it('should prefer the canonical URL in the doublefetch request', async function () {
388
+ const page = {
389
+ aggregator: {
390
+ firstSeenAt: 1716993609947,
391
+ lastSeenAt: 1716993610906,
392
+ lastWrittenAt: 1716993616542,
393
+ activity: 0.00962,
394
+ },
395
+ url: 'https://www.youtube.com/watch?v=y5uAf4ccrtE',
396
+ status: 'complete',
397
+ pageLoadMethod: 'history-navigation',
398
+ title:
399
+ 'Eine kurze Geschichte über… das Mittelalter | Terra X | MrWissen2go - YouTube',
400
+ ref: 'https://www.youtube.com/watch?v=Yzk-28bBKGs',
401
+ preDoublefetch: {
402
+ meta: {
403
+ canonicalUrl: 'https://www.youtube.com/watch?v=hLT-W55y-LI',
404
+ contentType: 'text/html',
405
+ language: 'en',
406
+ og: {
407
+ image: 'https://i.ytimg.com/vi/hLT-W55y-LI/maxresdefault.jpg',
408
+ title:
409
+ 'Vom Bürokratiewahnsinn im Wohnungsbau. Viele Normen - Teure Wohnungen? | SWR Doku',
410
+ url: 'https://www.youtube.com/watch?v=hLT-W55y-LI',
411
+ },
412
+ },
413
+ noindex: false,
414
+ requestedIndex: false,
415
+ title:
416
+ 'Feste Heimat: Wie lebte es sich auf einer Burg? | Ganze Folge Terra X - YouTube',
417
+ url: 'https://www.youtube.com/watch?v=y5uAf4ccrtE',
418
+ lastUpdatedAt: 1716993609947,
419
+ },
420
+ lastUpdatedAt: 1716993610906,
421
+ lang: 'en',
422
+ };
423
+
424
+ pageFetcherMock.reconfig({
425
+ 'https://www.youtube.com/watch?v=hLT-W55y-LI': {
426
+ title:
427
+ 'Vom Bürokratiewahnsinn im Wohnungsbau. Viele Normen - Teure Wohnungen? | SWR Doku - YouTube',
428
+ meta: {
429
+ canonicalUrl: 'https://www.youtube.com/watch?v=hLT-W55y-LI',
430
+ language: 'en',
431
+ contentType: null,
432
+ og: {
433
+ title:
434
+ 'Vom Bürokratiewahnsinn im Wohnungsbau. Viele Normen - Teure Wohnungen? | SWR Doku',
435
+ url: 'https://www.youtube.com/watch?v=hLT-W55y-LI',
436
+ image: 'https://i.ytimg.com/vi/hLT-W55y-LI/maxresdefault.jpg',
437
+ },
438
+ },
439
+ noindex: false,
440
+ requestedIndex: false,
441
+ },
442
+ 'https://www.youtube.com/watch?v=y5uAf4ccrtE': {
443
+ title:
444
+ 'Eine kurze Geschichte über… das Mittelalter | Terra X | MrWissen2go - YouTube',
445
+ meta: {
446
+ canonicalUrl: 'https://www.youtube.com/watch?v=y5uAf4ccrtE',
447
+ language: 'en',
448
+ contentType: null,
449
+ og: {
450
+ title:
451
+ 'Eine kurze Geschichte über… das Mittelalter | Terra X | MrWissen2go',
452
+ url: 'https://www.youtube.com/watch?v=y5uAf4ccrtE',
453
+ image: 'https://i.ytimg.com/vi/y5uAf4ccrtE/maxresdefault.jpg',
454
+ },
455
+ },
456
+ noindex: false,
457
+ requestedIndex: false,
458
+ },
459
+ });
460
+
461
+ const { ok, safePage } = await uut.runJob(page);
462
+
463
+ expect(ok).to.be.true;
464
+ pageFetcherMock.expectAllFetchedOnce();
465
+ relaxedSafePageEqual(safePage, {
466
+ url: 'https://www.youtube.com/watch?v=y5uAf4ccrtE',
467
+ title:
468
+ 'Eine kurze Geschichte über… das Mittelalter | Terra X | MrWissen2go - YouTube',
469
+ requestedIndex: false,
470
+ lang: {
471
+ html: 'en',
472
+ detect: 'en',
473
+ },
474
+ aggregator: {
475
+ activity: '0.0096',
476
+ },
477
+ ref: 'https://www.youtube.com/ (PROTECTED)',
478
+ canonicalUrl: 'https://www.youtube.com/watch?v=y5uAf4ccrtE',
479
+ });
480
+ });
481
+ });
482
+
483
+ describe('[error handling]', function () {
484
+ function somePageWithoutCanonicalUrl() {
485
+ return {
486
+ aggregator: {
487
+ firstSeenAt: 1717422627782,
488
+ lastSeenAt: 1717422627784,
489
+ lastWrittenAt: 1717422627883,
490
+ activity: 0.004188333333333333,
491
+ },
492
+ url: 'https://www.example.com/',
493
+ status: 'complete',
494
+ pageLoadMethod: 'full-page-load',
495
+ title: 'Example Domain',
496
+ preDoublefetch: {
497
+ meta: {
498
+ canonicalUrl: null,
499
+ contentType: 'text/html',
500
+ language: null,
501
+ og: {},
502
+ },
503
+ noindex: false,
504
+ requestedIndex: false,
505
+ title: 'Example Domain',
506
+ url: 'https://www.example.com/',
507
+ lastUpdatedAt: 1717422627782,
508
+ },
509
+ lastUpdatedAt: 1717422627784,
510
+ lang: '--',
511
+ };
512
+ }
513
+
514
+ it('should fail with a non-permanent error when a page is temporarily not reachable', async function () {
515
+ const page = somePageWithoutCanonicalUrl();
516
+ pageFetcherMock.reconfig({
517
+ [page.url]: new TemporarilyUnableToFetchUrlError(),
518
+ });
519
+
520
+ try {
521
+ await uut.runJob(page);
522
+ } catch (err) {
523
+ expect(err.isPermanentError).to.be.false;
524
+ return;
525
+ }
526
+ assert.fail('Expected to throw');
527
+ });
528
+
529
+ it('should drop the page if it is permanently not reachable', async function () {
530
+ const page = somePageWithoutCanonicalUrl();
531
+ pageFetcherMock.reconfig({
532
+ [page.url]: new PermanentlyUnableToFetchUrlError(),
533
+ });
534
+
535
+ const { ok, details } = await uut.runJob(page);
536
+
537
+ expect(ok).to.be.false;
538
+ expect(details).to.be.a('string').that.is.not.empty;
539
+ });
540
+ });
541
+ });
542
+
543
+ describe('#titlesMatchAfterDoublefetch', function () {
544
+ function shouldMatch(before, after) {
545
+ if (!titlesMatchAfterDoublefetch({ before, after })) {
546
+ expect.fail(
547
+ `Expected titles to match, but they did not:\n` +
548
+ `before: <<${before}>>\n` +
549
+ `after: <<${after}>>`,
550
+ );
551
+ }
552
+ }
553
+
554
+ function shouldNotMatch(before, after) {
555
+ if (titlesMatchAfterDoublefetch({ before, after })) {
556
+ expect.fail(
557
+ `Did not expect titles to match, but they did:\n` +
558
+ `before: <<${before}>>\n` +
559
+ `after: <<${after}>>`,
560
+ );
561
+ }
562
+ }
563
+
564
+ it('should always reject pages without titles', function () {
565
+ shouldNotMatch({ before: '', after: '' });
566
+ shouldNotMatch({ before: '', after: 'foo' });
567
+ shouldNotMatch({ before: undefined, after: '' });
568
+ shouldNotMatch({ before: null, after: '' });
569
+ });
570
+
571
+ it('should accept perfect matches', function () {
572
+ shouldNotMatch({ before: 'Some title', after: 'Some title' });
573
+ });
574
+
575
+ it('should reject completely different titles', function () {
576
+ shouldNotMatch({
577
+ before: 'Some title (XYZ)',
578
+ after: 'This is some unrelated title',
579
+ });
580
+ });
581
+
582
+ it('should reject completely different titles', function () {
583
+ shouldNotMatch({
584
+ before: 'Some title (XYZ)',
585
+ after: 'This is some unrelated title',
586
+ });
587
+ });
588
+
589
+ describe('should not do precise matching for uppercase and lowercase letters', function () {
590
+ for (const { before, after } of [
591
+ { before: 'Example Search - YouTube', after: 'example search - YouTube' },
592
+ ]) {
593
+ it(`- ${before} --> ${after}`, function () {
594
+ shouldMatch(before, after);
595
+ });
596
+ }
597
+ });
598
+
599
+ describe('should accept titles that are subsets of doublefetch, but not vice versa', function () {
600
+ for (const { before, after } of [
601
+ {
602
+ // Note: might not be the best example, since this is still likely to
603
+ // be dropped since it could trigger the email detector. But Mastodon
604
+ // is an example where the title can be more detailed if you are not
605
+ // logged in.
606
+ before: 'muenchen.social - Die erste Mastodon Instanz für München',
607
+ after:
608
+ 'Max Mustermann (@maxmustermann@muenchen.social) - muenchen.social - Die erste Mastodon Instanz für München',
609
+ },
610
+ ]) {
611
+ it(`- ${before} --> ${after}`, function () {
612
+ shouldMatch(before, after);
613
+ });
614
+ it(`- ${before} --> ${after} (swapping orders!)`, function () {
615
+ shouldNotMatch(after, before);
616
+ });
617
+ }
618
+ });
619
+
620
+ describe('when the encoding is broken after doublefetch', function () {
621
+ describe('should have some tolerance for broken characters', function () {
622
+ for (const { before, after } of [
623
+ {
624
+ before: 'Imputada la de Sánchez (presuntamente) | España',
625
+ after: 'Imputada la de S�nchez (presuntamente) | Espa�a',
626
+ },
627
+ {
628
+ before: 'Opinión. Editoriales y columnas | EL MUNDO',
629
+ after: '\nOpini�n. Editoriales y columnas | EL MUNDO ',
630
+ },
631
+ {
632
+ before:
633
+ 'Zaragoza reclama el impago de 28 millones de euros en fondos europeos al Gobierno y amenaza con denunciarlo en Bruselas | Aragón',
634
+ after:
635
+ 'Zaragoza reclama el impago de 28 millones de euros en fondos europeos al Gobierno y amenaza con denunciarlo en Bruselas | Arag�n',
636
+ },
637
+ {
638
+ before: 'Cataluña - Noticias de Cataluña | EL MUNDO',
639
+ after: '\nCatalu�a - Noticias de Catalu�a | EL MUNDO ',
640
+ },
641
+ {
642
+ before: 'Cataluña - Noticias de Cataluña | EL MUNDO',
643
+ after: '\nCatalu�a - Noticias de Cataluña | EL MUNDO ',
644
+ },
645
+ {
646
+ before: 'AKŞAM - Haberler - Son Dakika Haberleri',
647
+ after: 'AK�AM - Haberler - Son Dakika Haberleri',
648
+ },
649
+ ]) {
650
+ it(`- ${before} --> ${after}`, function () {
651
+ shouldMatch(before, after);
652
+ });
653
+ }
654
+ });
655
+
656
+ describe('should have some tolerance even if it is not consistently broken', function () {
657
+ for (const { before, after } of [
658
+ {
659
+ before: 'Cataluña - Noticias de Cataluña | EL MUNDO',
660
+ after: '\nCataluña - Noticias de Cataluña | EL MUNDO ',
661
+ },
662
+ {
663
+ before: 'Cataluña - Noticias de Cataluña | EL MUNDO',
664
+ after: '\nCatalu�a - Noticias de Cataluña | EL MUNDO ',
665
+ },
666
+ {
667
+ before: 'Cataluña - Noticias de Cataluña | EL MUNDO',
668
+ after: '\nCataluña - Noticias de Catalu�a | EL MUNDO ',
669
+ },
670
+ {
671
+ before: 'Cataluña - Noticias de Cataluña | EL MUNDO',
672
+ after: '\nCatalu�a - Noticias de Catalu�a | EL MUNDO ',
673
+ },
674
+ {
675
+ before: 'öäÖÄ߀ Cataluña - Noticias de Cataluña | EL MUNDO',
676
+ after: '\nöäÖÄ߀ Catalu�a - Noticias de Catalu�a | EL MUNDO ',
677
+ },
678
+ {
679
+ before: 'öäÖÄ߀ Cataluña - Noticias de Cataluña | EL MUNDO',
680
+ after: '\nöäÖÄ�€ Catalu�a - Noticias de Catalu�a | EL MUNDO ',
681
+ },
682
+ ]) {
683
+ it(`- ${before} --> ${after}`, function () {
684
+ shouldMatch(before, after);
685
+ });
686
+ }
687
+ });
688
+
689
+ describe('should only tolerate encoding errors for non-ascii characters', function () {
690
+ for (const { before, after } of [
691
+ {
692
+ before: 'This is a pure ascii text',
693
+ after: 'This is a p�re ascii text',
694
+ },
695
+ {
696
+ before: 'Imputada la de Sánchez (presuntamente) | España',
697
+ after: '�mputada la de S�nchez (presuntamente) | Espa�a',
698
+ },
699
+ ]) {
700
+ it(`- ${before} --> ${after}`, function () {
701
+ shouldNotMatch(before, after);
702
+ });
703
+ }
704
+ });
705
+
706
+ describe('should still reject if doublefetch encoding errors destroy too much', function () {
707
+ for (const { before, after } of [
708
+ { before: 'á', after: '�' },
709
+ {
710
+ before: 'Imputada la de Sánchez (presuntamente) | España',
711
+ after: '�������� �� �� ������� (presuntamente) | Espa�a',
712
+ },
713
+ ]) {
714
+ it(`- ${before} --> ${after}`, function () {
715
+ shouldNotMatch(before, after);
716
+ });
717
+ }
718
+ });
719
+ });
720
+ });
721
+
722
+ describe('#sanitizeActivity', function () {
723
+ function ensureInRange(x) {
724
+ expect(x).to.be.a('string');
725
+ expect(Number(x)).to.be.within(0, 1);
726
+ }
727
+
728
+ it('should map bad inputs to "0"', function () {
729
+ expect(sanitizeActivity(null)).to.eql('0');
730
+ expect(sanitizeActivity(undefined)).to.eql('0');
731
+ expect(sanitizeActivity({})).to.eql('0');
732
+ expect(sanitizeActivity('x')).to.eql('0');
733
+ expect(sanitizeActivity('1')).to.eql('0');
734
+ });
735
+
736
+ it('should reasonably normalize values like 0.33333...', function () {
737
+ const result = sanitizeActivity(1 / 3);
738
+ ensureInRange(result);
739
+ expect(Number(result)).to.be.greaterThan(0.2);
740
+ expect(Number(result)).to.be.lessThan(0.45);
741
+ expect(result.length).to.be.lessThanOrEqual('0.1234'.length);
742
+ });
743
+
744
+ describe('[property based testing]', function () {
745
+ it('should keep values between 0 and 1', function () {
746
+ fc.assert(
747
+ fc.property(fc.double(), (x) => {
748
+ ensureInRange(sanitizeActivity(x));
749
+ }),
750
+ );
751
+ });
752
+
753
+ it('should not change numbers too drastically', function () {
754
+ fc.assert(
755
+ fc.property(fc.double({ min: 0, max: 1, noNaN: true }), (x) => {
756
+ const result = sanitizeActivity(x);
757
+ ensureInRange(result);
758
+ expect(Number(result)).to.be.within(x - 0.1, x + 0.1);
759
+ }),
760
+ );
761
+ });
762
+
763
+ it('should not drastically change the ordering', function () {
764
+ fc.assert(
765
+ fc.property(fc.double({ min: 0, max: 0.4, noNaN: true }), (low) => {
766
+ const high = 1.0 - low;
767
+ const low_ = sanitizeActivity(low);
768
+ const high_ = sanitizeActivity(high);
769
+ ensureInRange(low_);
770
+ ensureInRange(high_);
771
+ expect(Number(low_)).to.be.lessThan(Number(high_));
772
+ }),
773
+ );
774
+ });
775
+
776
+ it('should not round up small numbers to 1', function () {
777
+ fc.assert(
778
+ fc.property(fc.double({ min: 0, max: 0.85, noNaN: true }), (x) => {
779
+ const result = sanitizeActivity(x);
780
+ expect(Number(result)).to.be.lessThan(1.0);
781
+ }),
782
+ );
783
+ });
784
+
785
+ it('should not round up big numbers to 0', function () {
786
+ fc.assert(
787
+ fc.property(fc.double({ min: 0.15, max: 1, noNaN: true }), (x) => {
788
+ const result = sanitizeActivity(x);
789
+ expect(Number(result)).to.be.greaterThan(0.0);
790
+ }),
791
+ );
792
+ });
793
+
794
+ it('should map bad inputs to "0"', function () {
795
+ fc.assert(
796
+ fc.property(fc.anything(), (x) => {
797
+ if (!Number.isFinite(x)) {
798
+ expect(sanitizeActivity(x)).to.eql('0');
799
+ }
800
+ }),
801
+ );
802
+ });
803
+
804
+ it('should not change the mean too much', function () {
805
+ fc.assert(
806
+ fc.property(fc.double({ min: 0, max: 1, noNaN: true }), (x) => {
807
+ const numRuns = 1000;
808
+ let sum = 0;
809
+ for (let i = 0; i < numRuns; i += 1) {
810
+ sum += Number(sanitizeActivity(x));
811
+ }
812
+ const mean = sum / numRuns;
813
+ expect(mean).to.be.within(x - 0.03, x + 0.03);
814
+ }),
815
+ );
816
+ });
817
+ });
818
+ });