@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,356 @@
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 sinon from 'sinon';
14
+ import fc from 'fast-check';
15
+
16
+ import ActivityEstimator from '../src/activity-estimator.js';
17
+
18
+ const SECOND = 1000;
19
+ const MINUTE = 60 * SECOND;
20
+ const HOUR = 60 * MINUTE;
21
+ const DAY = 24 * HOUR;
22
+ const WEEK = 7 * DAY;
23
+
24
+ class Listeners {
25
+ constructor() {
26
+ this.reset();
27
+ }
28
+
29
+ reset() {
30
+ this.events = [];
31
+ this.counts = {
32
+ onActivityUpdated: 0,
33
+ onInternalStateChanged: 0,
34
+ };
35
+ }
36
+
37
+ onActivityUpdated(...args) {
38
+ expect(args).to.have.lengthOf(1);
39
+ const urls = args[0];
40
+ for (const url of urls) {
41
+ if (!URL.canParse(url)) {
42
+ assert.fail(`Failed to parse URL: ${url}`);
43
+ }
44
+ }
45
+
46
+ const type = 'onActivityUpdated';
47
+ this.events.push({ type, ts: Date.now(), urls });
48
+ this.counts[type] += 1;
49
+ }
50
+
51
+ onInternalStateChanged(...args) {
52
+ expect(args).to.be.empty;
53
+ const type = 'onInternalStateChanged';
54
+ this.events.push({ type, ts: Date.now() });
55
+ this.counts[type] += 1;
56
+ }
57
+
58
+ wasCalled(type) {
59
+ if (this.counts[type] === undefined) {
60
+ throw new Error(`Unknown type: ${type}`);
61
+ }
62
+ expect(this.counts[type]).to.be.greaterThan(0);
63
+ }
64
+ }
65
+
66
+ describe('#ActivityEstimator', function () {
67
+ let uut;
68
+ let clock;
69
+ let listeners;
70
+
71
+ function initMocks() {
72
+ clock?.restore();
73
+ clock = sinon.useFakeTimers(new Date('2020-01-01'));
74
+
75
+ // workaround for a weird Sinon bug: unless a timer was set at least once, clock.jump will fail
76
+ // TODO: report upstream: https://github.com/sinonjs/sinon
77
+ setTimeout(() => {}, 0);
78
+
79
+ listeners = new Listeners();
80
+ uut = new ActivityEstimator({
81
+ onActivityUpdated: (...args) => {
82
+ listeners.onActivityUpdated(...args);
83
+ },
84
+ onInternalStateChanged: (...args) => {
85
+ listeners.onInternalStateChanged(...args);
86
+ },
87
+ });
88
+ }
89
+
90
+ function tearDown() {
91
+ clock?.restore();
92
+ clock = null;
93
+ listeners = null;
94
+ }
95
+
96
+ beforeEach(initMocks);
97
+ afterEach(tearDown);
98
+
99
+ async function passesSelfChecks() {
100
+ const checks = await uut.selfChecks();
101
+ if (!checks.allPassed()) {
102
+ const fullReport = JSON.stringify(checks.report(), null, 2);
103
+ const shortReport = JSON.stringify(checks.report().log.failures, null, 2);
104
+ assert.fail(
105
+ `self checks failed:\n${fullReport}:\n\nThis is the error:\n${shortReport}`,
106
+ );
107
+ }
108
+ }
109
+
110
+ const SOME_URL = 'https://example.test/';
111
+ const ANOTHER_URL = 'https://example2.test/';
112
+
113
+ function expectLowestScore(url) {
114
+ const score = uut.estimate(url);
115
+ expect(score).to.eql(0.0);
116
+ }
117
+
118
+ function expectNonZeroScore(url) {
119
+ const score = uut.estimate(url);
120
+ expect(score).to.be.greaterThan(0.0);
121
+ }
122
+
123
+ it('should treat unknown URLs as inactive', function () {
124
+ expectLowestScore(SOME_URL);
125
+ });
126
+
127
+ describe('should recognize that the current active URL is somewhat active', function () {
128
+ it('after the URL has been activated', function () {
129
+ uut.updateActiveUrl(SOME_URL);
130
+ expectNonZeroScore(SOME_URL);
131
+ });
132
+
133
+ it('after a dynamic load has been detected', function () {
134
+ uut.dynamicLoadDetected(SOME_URL);
135
+ expectNonZeroScore(SOME_URL);
136
+ });
137
+ });
138
+
139
+ describe('should not instanty reduce activity scores if a URL becomes as inactive', function () {
140
+ for (const delay of [
141
+ 1,
142
+ 5,
143
+ 100,
144
+ 1 * SECOND,
145
+ 5 * SECOND,
146
+ 30 * SECOND,
147
+ 4 * MINUTE,
148
+ 20 * MINUTE,
149
+ 29 * MINUTE,
150
+ 2 * HOUR,
151
+ 3 * DAY,
152
+ 2 * WEEK,
153
+ ]) {
154
+ it(`after the URL has been active for ${delay} ms`, async function () {
155
+ const url = SOME_URL;
156
+ uut.updateActiveUrl(url);
157
+ expectNonZeroScore(url);
158
+ clock.tick(delay);
159
+
160
+ const now = Date.now();
161
+ const scoreBeforeDisabling = uut.estimate(url, now);
162
+ uut.updateActiveUrl(null);
163
+ const scoreAfterDisabling = uut.estimate(url, now);
164
+ expect(scoreBeforeDisabling).to.eql(scoreAfterDisabling);
165
+ return { defaultHandler: false };
166
+ });
167
+ }
168
+ });
169
+
170
+ it('should no long increase the score of inactive tabs', function () {
171
+ const scores = [];
172
+ const pushScores = () => {
173
+ const now = Date.now();
174
+ scores.push({
175
+ [SOME_URL]: uut.estimate(SOME_URL, now),
176
+ [ANOTHER_URL]: uut.estimate(ANOTHER_URL, now),
177
+ });
178
+ };
179
+ pushScores();
180
+
181
+ const scoreIncreased = (url) => {
182
+ const curr = scores[scores.length - 1];
183
+ const prev = scores[scores.length - 2];
184
+ return curr[url] > prev[url];
185
+ };
186
+
187
+ const scoreDidNotIncrease = (url) => {
188
+ const curr = scores[scores.length - 1];
189
+ const prev = scores[scores.length - 2];
190
+ return curr[url] <= prev[url];
191
+ };
192
+
193
+ pushScores();
194
+ scoreDidNotIncrease(SOME_URL);
195
+ scoreDidNotIncrease(ANOTHER_URL);
196
+
197
+ uut.updateActiveUrl(SOME_URL);
198
+ pushScores();
199
+ scoreIncreased(SOME_URL);
200
+ scoreDidNotIncrease(ANOTHER_URL);
201
+
202
+ clock.tick(SECOND);
203
+ pushScores();
204
+ scoreIncreased(SOME_URL);
205
+ scoreDidNotIncrease(ANOTHER_URL);
206
+
207
+ uut.updateActiveUrl(null);
208
+ clock.tick(SECOND);
209
+ pushScores();
210
+ scoreDidNotIncrease(SOME_URL);
211
+ scoreDidNotIncrease(ANOTHER_URL);
212
+
213
+ clock.tick(SECOND);
214
+ pushScores();
215
+ scoreDidNotIncrease(SOME_URL);
216
+ scoreDidNotIncrease(ANOTHER_URL);
217
+
218
+ clock.tick(HOUR);
219
+ pushScores();
220
+ scoreDidNotIncrease(SOME_URL);
221
+ scoreDidNotIncrease(ANOTHER_URL);
222
+
223
+ uut.dynamicLoadDetected(ANOTHER_URL);
224
+ pushScores();
225
+ scoreDidNotIncrease(SOME_URL);
226
+ scoreIncreased(ANOTHER_URL);
227
+ });
228
+
229
+ it('should handle situations without active tabs', async function () {
230
+ uut.updateActiveUrl(null);
231
+ await passesSelfChecks();
232
+
233
+ await clock.tickAsync(1 * SECOND);
234
+ uut.updateActiveUrl(null);
235
+ await passesSelfChecks();
236
+ });
237
+
238
+ describe('events', function () {
239
+ it('activating an URL should trigger events', async function () {
240
+ uut.updateActiveUrl(SOME_URL);
241
+ await clock.runAllAsync();
242
+ listeners.wasCalled('onActivityUpdated');
243
+ listeners.wasCalled('onInternalStateChanged');
244
+ });
245
+ });
246
+
247
+ describe('[property based testing]', function () {
248
+ function arbitraryScenario({
249
+ urls = [
250
+ 'https://example1.test/',
251
+ 'https://example2.test/',
252
+ 'https://example3.test/',
253
+ null,
254
+ ],
255
+ } = {}) {
256
+ return fc.array(
257
+ fc.record({
258
+ url: fc.option(...urls.map((url) => fc.constant(url))),
259
+ isDynamicLoad: fc.boolean(),
260
+ delay: fc.nat(1 * WEEK),
261
+ jump: fc.nat(1 * WEEK),
262
+ }),
263
+ );
264
+ }
265
+
266
+ async function runScenario(steps, { customHook } = {}) {
267
+ for (let i = 0; i < steps.length; i += 1) {
268
+ const step = steps[i];
269
+ try {
270
+ const { url, delay = 0, jump = 0, isDynamicLoad = false } = step;
271
+ const handleDelays = async () => {
272
+ if (delay > 0) {
273
+ clock.tick(delay);
274
+ await passesSelfChecks();
275
+ }
276
+ if (jump > 0) {
277
+ clock.jump(jump);
278
+ await passesSelfChecks();
279
+ }
280
+ };
281
+ const defaultHandler = async () => {
282
+ await clock.runAllAsync();
283
+ await passesSelfChecks();
284
+ await handleDelays();
285
+ if (url !== undefined) {
286
+ if (url && isDynamicLoad) {
287
+ uut.dynamicLoadDetected(url);
288
+ } else {
289
+ uut.updateActiveUrl(url);
290
+ }
291
+ if (url) {
292
+ expectNonZeroScore(url);
293
+ }
294
+ }
295
+ };
296
+
297
+ if (customHook) {
298
+ await customHook({
299
+ ...step,
300
+ runDefaultHandler: defaultHandler,
301
+ handleDelays,
302
+ });
303
+ } else {
304
+ await defaultHandler();
305
+ }
306
+ await passesSelfChecks();
307
+ await clock.runAllAsync();
308
+ } catch (e) {
309
+ const allSteps = JSON.stringify(steps, null, 2);
310
+ const lastStep = JSON.stringify(step);
311
+ console.error(
312
+ `Scenario:\n\n---\n${allSteps}\nScenario failed at step ${i} (${lastStep}):\nError:`,
313
+ e,
314
+ );
315
+ throw e;
316
+ }
317
+ }
318
+ }
319
+
320
+ describe('should not reach an inconsistent state', function () {
321
+ it('when switching between URLs and doing dynamic loads', async function () {
322
+ this.timeout(20 * SECOND);
323
+ await fc.assert(
324
+ fc
325
+ .asyncProperty(arbitraryScenario(), runScenario)
326
+ .beforeEach(initMocks)
327
+ .afterEach(tearDown),
328
+ );
329
+ });
330
+ });
331
+
332
+ it('should not change the current activity score when a page becomes inactive', async function () {
333
+ this.timeout(20 * SECOND);
334
+ await fc.assert(
335
+ fc
336
+ .asyncProperty(arbitraryScenario(), async (steps) => {
337
+ await runScenario(steps, {
338
+ customHook: async ({ url, runDefaultHandler, handleDelays }) => {
339
+ if (url) {
340
+ await handleDelays();
341
+ const scoreBeforeDisabling = uut.estimate(url);
342
+ uut.updateActiveUrl(null);
343
+ const scoreAfterDisabling = uut.estimate(url);
344
+ expect(scoreBeforeDisabling).to.eql(scoreAfterDisabling);
345
+ } else {
346
+ await runDefaultHandler();
347
+ }
348
+ },
349
+ });
350
+ })
351
+ .beforeEach(initMocks)
352
+ .afterEach(tearDown),
353
+ );
354
+ });
355
+ });
356
+ });
@@ -0,0 +1,156 @@
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 } from 'chai';
13
+
14
+ import AliveCheck from '../src/alive-check.js';
15
+
16
+ const SECOND = 1000;
17
+ const MINUTE = 60 * SECOND;
18
+ const HOUR = 60 * MINUTE;
19
+ const DAY = 24 * HOUR;
20
+
21
+ describe('#AliveCheck', function () {
22
+ const storageKey = 'some-storage-key';
23
+ let communication;
24
+ let countryProvider;
25
+ let trustedClock;
26
+ let aliveMessageGenerator;
27
+ let storage;
28
+ let uut;
29
+
30
+ function newAliveCheck() {
31
+ return new AliveCheck({
32
+ communication,
33
+ countryProvider,
34
+ trustedClock,
35
+ aliveMessageGenerator,
36
+ storage,
37
+ storageKey,
38
+ });
39
+ }
40
+
41
+ // Helper that simulate an event like a restart of the service worker/background script:
42
+ // it keeps the storage but purges everything that was in memory.
43
+ async function simulateRestart() {
44
+ uut = newAliveCheck();
45
+ }
46
+
47
+ function expectNoMessageSent() {
48
+ expect(communication._message).to.be.an('array').that.is.empty;
49
+ communication._message.length = 0;
50
+ }
51
+
52
+ function expectOneMessageSent() {
53
+ expect(communication._message).to.be.an('array').that.has.lengthOf(1);
54
+ communication._message.length = 0;
55
+ }
56
+
57
+ function numMessagesSent() {
58
+ const count = communication._message.length;
59
+ communication._message.length = 0;
60
+ return count;
61
+ }
62
+
63
+ beforeEach(() => {
64
+ communication = {
65
+ _message: [],
66
+ async send(msg) {
67
+ this._message.push(msg);
68
+ },
69
+ };
70
+ countryProvider = {
71
+ getSafeCountryCode: () => 'de',
72
+ };
73
+ trustedClock = {
74
+ getTimeAsYYYYMMDDHH: () => '<some timestamp>',
75
+ };
76
+ aliveMessageGenerator = {
77
+ async generateMessage(ctry, hour) {
78
+ return {
79
+ browser: '',
80
+ version: '',
81
+ os: '',
82
+ language: '',
83
+ ctry: '--',
84
+ t: hour,
85
+ };
86
+ },
87
+ };
88
+ storage = {
89
+ async get(key) {
90
+ expect(key).to.equal(storageKey);
91
+ return this._content;
92
+ },
93
+ async set(key, obj) {
94
+ expect(key).to.equal(storageKey);
95
+ this._content = obj;
96
+ },
97
+ };
98
+ uut = newAliveCheck();
99
+ });
100
+
101
+ describe('on a fresh extension installation', function () {
102
+ it('should not immediately send a message', async () => {
103
+ await uut._check();
104
+ expectNoMessageSent();
105
+ });
106
+
107
+ it('should eventually send a message (after more then one hour of activity)', async () => {
108
+ let now = Date.now();
109
+ for (let i = 0; i < 90; i += 1) {
110
+ await uut._check(now);
111
+ now += 1 * MINUTE;
112
+ }
113
+ expectOneMessageSent();
114
+ });
115
+
116
+ it('should not send more then one message per hour', async () => {
117
+ let now = Date.now();
118
+ for (let i = 0; i < DAY; i += MINUTE) {
119
+ if (i % 7 === 0) {
120
+ await simulateRestart();
121
+ }
122
+ await uut._check(now);
123
+ now += 1 * MINUTE;
124
+ }
125
+ // underspecify what should happen on the first day
126
+ expect(numMessagesSent()).to.be.within(22, 24);
127
+
128
+ // if we repeat (now the effect of the initial installation is gone),
129
+ // the semantic is clear: one message per hour over one day -> 24 messages
130
+ for (let i = 0; i < DAY; i += MINUTE) {
131
+ if (i % 7 === 0) {
132
+ await simulateRestart();
133
+ }
134
+ await uut._check(now);
135
+ now += 1 * MINUTE;
136
+ }
137
+ expect(numMessagesSent()).to.eql(24);
138
+ });
139
+ });
140
+
141
+ describe('when multiple check happens at the same time', function () {
142
+ it('should not result in multiple messages', async () => {
143
+ let now = Date.now();
144
+ for (let i = 0; i < DAY; i += MINUTE) {
145
+ await Promise.all([
146
+ uut._check(now),
147
+ uut._check(now),
148
+ uut._check(now),
149
+ uut._check(now),
150
+ ]);
151
+ expect(numMessagesSent()).to.be.at.most(1);
152
+ now += MINUTE;
153
+ }
154
+ });
155
+ });
156
+ });
@@ -0,0 +1,186 @@
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 } from 'chai';
13
+
14
+ import AliveMessageGenerator from '../src/alive-message-generator.js';
15
+
16
+ describe('#AliveMessageGenerator', function () {
17
+ const someHour = '2024030803';
18
+ const anotherHour = '2024030804';
19
+
20
+ const storageKey = 'some-storage-key';
21
+ let browserInfoProvider;
22
+ let quorumChecker;
23
+ let storage;
24
+ let uut;
25
+
26
+ let _browserInfo;
27
+ let _shouldPassQuorum;
28
+
29
+ function newAliveMessageGenerator() {
30
+ return new AliveMessageGenerator({
31
+ browserInfoProvider,
32
+ quorumChecker,
33
+ storage,
34
+ storageKey,
35
+ });
36
+ }
37
+
38
+ // Helper that simulate an event like a restart of the service worker/background script:
39
+ // it keeps the storage but purges everything that was in memory.
40
+ async function simulateRestart() {
41
+ uut = newAliveMessageGenerator();
42
+ }
43
+
44
+ function assumeQuorumReached(value = true) {
45
+ _shouldPassQuorum = value;
46
+ }
47
+
48
+ function assumeQuorumNotReached() {
49
+ assumeQuorumReached(false);
50
+ }
51
+
52
+ beforeEach(() => {
53
+ _browserInfo = {
54
+ browser: 'Firefox',
55
+ version: '122',
56
+ os: 'Linux',
57
+ language: 'en-US',
58
+ };
59
+ browserInfoProvider = async () => _browserInfo;
60
+
61
+ quorumChecker = {
62
+ _incCalls: 0,
63
+ _getCalls: 0,
64
+
65
+ async sendQuorumIncrement({ text }) {
66
+ this._incCalls += 1;
67
+ expect(text).to.be.a('string');
68
+ },
69
+ async checkQuorumConsent({ text }) {
70
+ this._getCalls += 1;
71
+ expect(text).to.be.a('string');
72
+ return _shouldPassQuorum;
73
+ },
74
+ };
75
+ assumeQuorumReached();
76
+
77
+ storage = {
78
+ async get(key) {
79
+ expect(key).to.equal(storageKey);
80
+ return this._content;
81
+ },
82
+ async set(key, obj) {
83
+ expect(key).to.equal(storageKey);
84
+ this._content = obj;
85
+ },
86
+ };
87
+ uut = newAliveMessageGenerator();
88
+ });
89
+
90
+ function runGenericTests() {
91
+ it('should only check once for quorum if the config is the same', async function () {
92
+ expect(quorumChecker._incCalls).to.eql(0);
93
+ expect(quorumChecker._getCalls).to.eql(0);
94
+ await uut.generateMessage('de', someHour);
95
+ expect(quorumChecker._incCalls).to.eql(1);
96
+ expect(quorumChecker._getCalls).to.eql(1);
97
+ await uut.generateMessage('de', someHour);
98
+ expect(quorumChecker._incCalls).to.eql(1);
99
+ expect(quorumChecker._getCalls).to.eql(1);
100
+ });
101
+
102
+ it('should only check again for quorum if the config changed', async function () {
103
+ expect(quorumChecker._incCalls).to.eql(0);
104
+ expect(quorumChecker._getCalls).to.eql(0);
105
+ await uut.generateMessage('de', someHour);
106
+ expect(quorumChecker._incCalls).to.eql(1);
107
+ expect(quorumChecker._getCalls).to.eql(1);
108
+ await uut.generateMessage('us', someHour);
109
+ expect(quorumChecker._incCalls).to.eql(2);
110
+ expect(quorumChecker._getCalls).to.eql(2);
111
+ await uut.generateMessage('fr', someHour);
112
+ expect(quorumChecker._incCalls).to.eql(3);
113
+ expect(quorumChecker._getCalls).to.eql(3);
114
+ });
115
+
116
+ it('should only check again for quorum if the config changed', async function () {
117
+ expect(quorumChecker._incCalls).to.eql(0);
118
+ expect(quorumChecker._getCalls).to.eql(0);
119
+ await uut.generateMessage('de', someHour);
120
+ expect(quorumChecker._incCalls).to.eql(1);
121
+ expect(quorumChecker._getCalls).to.eql(1);
122
+ await uut.generateMessage('de', anotherHour);
123
+ expect(quorumChecker._incCalls).to.eql(1);
124
+ expect(quorumChecker._getCalls).to.eql(1);
125
+ });
126
+
127
+ it('should not check quorum again after an extension restart', async function () {
128
+ expect(quorumChecker._incCalls).to.eql(0);
129
+ expect(quorumChecker._getCalls).to.eql(0);
130
+ await uut.generateMessage('de', someHour);
131
+ expect(quorumChecker._incCalls).to.eql(1);
132
+ expect(quorumChecker._getCalls).to.eql(1);
133
+
134
+ simulateRestart();
135
+ await uut.generateMessage('de', someHour);
136
+ expect(quorumChecker._incCalls).to.eql(1);
137
+ expect(quorumChecker._getCalls).to.eql(1);
138
+
139
+ // unless the config changes
140
+ simulateRestart();
141
+ await uut.generateMessage('us', someHour);
142
+ expect(quorumChecker._incCalls).to.eql(2);
143
+ expect(quorumChecker._getCalls).to.eql(2);
144
+ });
145
+ }
146
+
147
+ describe('if quorum is reached', function () {
148
+ beforeEach(assumeQuorumReached);
149
+ runGenericTests();
150
+
151
+ it('should share the config', async function () {
152
+ _browserInfo = {
153
+ browser: 'Firefox',
154
+ version: '122.1',
155
+ os: 'Linux',
156
+ language: 'en-US',
157
+ };
158
+ const message = await uut.generateMessage('de', '2024010203');
159
+ expect(message).to.deep.eql({
160
+ browser: 'Firefox',
161
+ version: '122', // only major version
162
+ os: 'Linux',
163
+ language: 'en-US',
164
+ ctry: 'de',
165
+ t: '2024010203',
166
+ });
167
+ });
168
+ });
169
+
170
+ describe('if quorum is not reached', function () {
171
+ beforeEach(assumeQuorumNotReached);
172
+ runGenericTests();
173
+
174
+ it('should not share the config', async function () {
175
+ const message = await uut.generateMessage('de', '2024010203');
176
+ expect(message).to.deep.eql({
177
+ browser: '',
178
+ version: '',
179
+ os: '',
180
+ language: '',
181
+ ctry: '--',
182
+ t: '2024010203',
183
+ });
184
+ });
185
+ });
186
+ });