@whotracksme/reporting 7.12.3 → 8.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.
Files changed (31) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/communication/test/helpers/in-memory-database.js +45 -0
  3. package/package.json +1 -1
  4. package/reporting/src/hash-detector-v2/index.js +164 -0
  5. package/reporting/src/hash-detector-v2/prob.js +599 -0
  6. package/reporting/src/hash-detector-v2.js +18 -0
  7. package/reporting/src/observable.js +43 -0
  8. package/reporting/src/pages.js +11 -12
  9. package/reporting/src/paused-domains-reporter.js +50 -0
  10. package/reporting/src/persisted-counters.js +158 -0
  11. package/reporting/src/popularity-estimator.js +625 -0
  12. package/reporting/src/popularity-vote-handler.js +219 -0
  13. package/reporting/src/popularity-vote-sanitizer.js +384 -0
  14. package/reporting/src/random.js +90 -1
  15. package/reporting/src/reporting.js +98 -13
  16. package/reporting/src/utils.js +41 -1
  17. package/reporting/test/activity-estimator.spec.js +3 -2
  18. package/reporting/test/alive-check.spec.js +2 -2
  19. package/reporting/test/country-provider.spec.js +2 -2
  20. package/reporting/test/index.js +6 -0
  21. package/reporting/test/job-scheduler.spec.js +2 -2
  22. package/reporting/test/observable.spec.js +72 -0
  23. package/reporting/test/page-aggregator.spec.js +3 -0
  24. package/reporting/test/patterns-updater.spec.js +2 -2
  25. package/reporting/test/persisted-counters.spec.js +132 -0
  26. package/reporting/test/popularity-estimator.spec.js +710 -0
  27. package/reporting/test/popularity-vote-handler.spec.js +420 -0
  28. package/reporting/test/popularity-vote-sanitizer.spec.js +635 -0
  29. package/reporting/test/random.spec.js +157 -0
  30. package/reporting/test/reporting.spec.js +202 -180
  31. package/reporting/test/utils.spec.js +42 -0
@@ -0,0 +1,420 @@
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
+ import sinon from 'sinon';
14
+ import * as fc from 'fast-check';
15
+
16
+ import * as tldts from 'tldts-experimental';
17
+
18
+ import PopularityVoteHandler from '../src/popularity-vote-handler.js';
19
+ import { sanitizeHostname } from '../src/popularity-vote-sanitizer.js';
20
+ import { requireString, requireUTC } from '../src/utils.js';
21
+
22
+ import {
23
+ createInMemoryJobScheduler,
24
+ runClockUntilJobQueueIsEmpty,
25
+ } from './helpers/in-memory-job-scheduler.js';
26
+
27
+ const SECOND = 1000;
28
+
29
+ function computeUrlProjections(url) {
30
+ const { hostname, pathname } = new URL(url);
31
+ const { domain } = tldts.parse(hostname, {
32
+ extractHostname: false,
33
+ mixedInputs: false,
34
+ validateHostname: false,
35
+ });
36
+ return { domain, hostname, hostnamePath: hostname + pathname };
37
+ }
38
+
39
+ class CommunicationStub {
40
+ _messagesSent = [];
41
+
42
+ async send(message) {
43
+ this._messagesSent.push({
44
+ message,
45
+ sentAt: Date.now(),
46
+ });
47
+ }
48
+ }
49
+
50
+ class QuorumCheckerStub {
51
+ _overwrites = new Map();
52
+ _default = false;
53
+ _quorumIncCalls = 0;
54
+ _quorumCheckCalls = 0;
55
+
56
+ _everythingReachesQuorum() {
57
+ this._default = true;
58
+ this._overwrites.clear();
59
+ }
60
+
61
+ _everythingFailsQuorum() {
62
+ this._default = false;
63
+ this._overwrites.clear();
64
+ }
65
+
66
+ _everythingFailsQuorumExcept(vote) {
67
+ requireString(vote);
68
+ this._everythingFailsQuorum();
69
+ this._overwrites.set(vote, true);
70
+ }
71
+
72
+ async sendQuorumIncrement({ text, now = Date.now() } = {}) {
73
+ requireString(text);
74
+ requireUTC(now);
75
+ this._quorumIncCalls += 1;
76
+ }
77
+
78
+ async checkQuorumConsent({ text }) {
79
+ this._quorumCheckCalls += 1;
80
+ return this._overwrites.get(text) ?? this._default;
81
+ }
82
+ }
83
+
84
+ class CountryProviderStub {
85
+ _ctry = '--';
86
+
87
+ getSafeCountryCode() {
88
+ return this._ctry;
89
+ }
90
+ }
91
+
92
+ describe('#PopularityVoteHandler', function () {
93
+ // The PopularityVoteHandler constructor registers job handlers
94
+ // as a side-effect. The linter does not understand that.
95
+ // eslint-disable-next-line no-unused-vars
96
+ let uut;
97
+ let clock;
98
+
99
+ let jobScheduler;
100
+ let communication;
101
+ let quorumChecker;
102
+ let countryProvider;
103
+ let pauseState;
104
+
105
+ function initMocks() {
106
+ clock?.restore();
107
+ clock = sinon.useFakeTimers(new Date('2026-01-01'));
108
+
109
+ // Unless a timer was set at least once, clock.jump will fail
110
+ // TODO: we can remove this workaround if this fix is shipped with @sinon:
111
+ // https://github.com/sinonjs/fake-timers/pull/541
112
+ setTimeout(() => {}, 0);
113
+
114
+ jobScheduler = createInMemoryJobScheduler();
115
+ communication = new CommunicationStub();
116
+ quorumChecker = new QuorumCheckerStub();
117
+ countryProvider = new CountryProviderStub();
118
+ pauseState = {
119
+ isHostnamePaused(hostname) {
120
+ requireString(hostname);
121
+ return false;
122
+ },
123
+ getFilteringMode() {
124
+ return 'default';
125
+ },
126
+ };
127
+ uut = newPopularityVoteHandler();
128
+ }
129
+
130
+ function newPopularityVoteHandler() {
131
+ return new PopularityVoteHandler({
132
+ jobScheduler,
133
+ communication,
134
+ quorumChecker,
135
+ countryProvider,
136
+ pauseState,
137
+ });
138
+ }
139
+
140
+ function tearDown() {
141
+ clock?.restore();
142
+ clock = null;
143
+ uut = null;
144
+ jobScheduler = null;
145
+ communication = null;
146
+ quorumChecker = null;
147
+ countryProvider = null;
148
+ pauseState = null;
149
+ }
150
+
151
+ beforeEach(initMocks);
152
+ afterEach(tearDown);
153
+
154
+ async function expectExactlyTheseSignals(
155
+ prepareVotingJob,
156
+ expectedPayloads,
157
+ { ignoreMasking = false, ignoreFailedJobs = false } = {},
158
+ ) {
159
+ let unexpectedFailedJobs = [];
160
+ jobScheduler.addObserver('jobFailed', (jobEntry, { exception }) => {
161
+ unexpectedFailedJobs.push({ jobEntry, exception });
162
+ });
163
+
164
+ await jobScheduler.init();
165
+ try {
166
+ // eliminate any chance of races between the tests
167
+ const messagesSent = communication._messagesSent;
168
+ expect(messagesSent).to.be.empty;
169
+
170
+ await jobScheduler.registerJob(prepareVotingJob);
171
+ await runClockUntilJobQueueIsEmpty(jobScheduler, clock);
172
+
173
+ if (unexpectedFailedJobs.length > 0 && !ignoreFailedJobs) {
174
+ console.error('Detected failed jobs:', unexpectedFailedJobs);
175
+ throw (
176
+ unexpectedFailedJobs[0].exception || Error('Failed jobs detected')
177
+ );
178
+ }
179
+
180
+ let actualPayloads = messagesSent.map(({ message }) => {
181
+ const { action, payload, ver } = message;
182
+ expect(action).to.eql('wtm.popularity');
183
+ expect(ver).to.eql(3);
184
+ return payload;
185
+ });
186
+ if (ignoreMasking) {
187
+ actualPayloads = actualPayloads.map((payload) => ({
188
+ ...payload,
189
+ vote: '<ignore>',
190
+ }));
191
+ expectedPayloads = expectedPayloads.map((payload) => ({
192
+ ...payload,
193
+ vote: '<ignore>',
194
+ }));
195
+ }
196
+ try {
197
+ expect(actualPayloads).to.have.deep.members(expectedPayloads);
198
+ } catch (e) {
199
+ console.error(
200
+ 'Mismatch detected: expected messages\n',
201
+ JSON.stringify(expectedPayloads, null, 2),
202
+ '\n---\nBut got:\n',
203
+ JSON.stringify(actualPayloads, null, 2),
204
+ );
205
+ throw e;
206
+ }
207
+ } finally {
208
+ jobScheduler.unload();
209
+ }
210
+ }
211
+
212
+ describe('#PopularityVoteHandler', function () {
213
+ describe('simple domain vote that reaches quorum', function () {
214
+ for (const count of [1, 2, 3]) {
215
+ describe(`with count=${count}`, function () {
216
+ it('should send messages with the original domain', async function () {
217
+ const urlProjection = 'domain';
218
+ const countType = 'visits';
219
+ const intervalType = '1d';
220
+
221
+ const prepareVotingJob = {
222
+ type: 'popularity-estimator:prepare-voting:v1',
223
+ args: {
224
+ urlProjection,
225
+ countType,
226
+ intervalType,
227
+ sample: {
228
+ value: 'example.com',
229
+ count,
230
+ },
231
+ },
232
+ };
233
+ quorumChecker._everythingReachesQuorum();
234
+ countryProvider._ctry = 'de';
235
+
236
+ const payload = {
237
+ type: {
238
+ urlProjection,
239
+ countType,
240
+ intervalType,
241
+ },
242
+ vote: 'example.com',
243
+ ctry: 'de',
244
+ adblocker: {
245
+ paused: false,
246
+ mode: 'default',
247
+ },
248
+ };
249
+
250
+ const expected = Array(count).fill(payload);
251
+ await expectExactlyTheseSignals(prepareVotingJob, expected);
252
+ });
253
+ });
254
+ }
255
+ });
256
+
257
+ describe('simple domain vote that fails quorum', function () {
258
+ for (const count of [1, 2, 3]) {
259
+ describe(`with count=${count}`, function () {
260
+ it('should send messages but mask the domain', async function () {
261
+ const urlProjection = 'domain';
262
+ const countType = 'visits';
263
+ const intervalType = '1d';
264
+
265
+ const prepareVotingJob = {
266
+ type: 'popularity-estimator:prepare-voting:v1',
267
+ args: {
268
+ urlProjection,
269
+ countType,
270
+ intervalType,
271
+ sample: {
272
+ value: 'example.com',
273
+ count,
274
+ },
275
+ },
276
+ };
277
+ quorumChecker._everythingFailsQuorum();
278
+ countryProvider._ctry = 'fr';
279
+
280
+ const payload = {
281
+ type: {
282
+ urlProjection,
283
+ countType,
284
+ intervalType,
285
+ },
286
+ vote: '--',
287
+ ctry: 'fr',
288
+ adblocker: {
289
+ paused: false,
290
+ mode: 'default',
291
+ },
292
+ };
293
+
294
+ const expected = Array(count).fill(payload);
295
+ await expectExactlyTheseSignals(prepareVotingJob, expected);
296
+ });
297
+ });
298
+ }
299
+ });
300
+
301
+ describe('[property based testing]', function () {
302
+ it('should not crash for arbitrary URLs', async function () {
303
+ this.timeout(60 * SECOND);
304
+ await fc.assert(
305
+ fc
306
+ .asyncProperty(
307
+ fc.webUrl(),
308
+ fc.constantFrom('domain', 'hostname', 'hostnamePath'),
309
+ fc.constantFrom('1d', '1w', '4w'),
310
+ fc.integer({ min: 1, max: 3 }),
311
+ async (url, urlProjection, intervalType, count) => {
312
+ const vote = computeUrlProjections(url)[urlProjection];
313
+ const countType = 'visits';
314
+
315
+ const prepareVotingJob = {
316
+ type: 'popularity-estimator:prepare-voting:v1',
317
+ args: {
318
+ urlProjection,
319
+ countType,
320
+ intervalType,
321
+ sample: {
322
+ value: vote,
323
+ count,
324
+ },
325
+ },
326
+ };
327
+
328
+ quorumChecker._everythingReachesQuorum();
329
+ countryProvider._ctry = 'de';
330
+
331
+ const payload = {
332
+ type: {
333
+ urlProjection,
334
+ countType,
335
+ intervalType,
336
+ },
337
+ vote,
338
+ ctry: 'de',
339
+ adblocker: {
340
+ paused: false,
341
+ mode: 'default',
342
+ },
343
+ };
344
+ const expected = Array(count).fill(payload);
345
+ await expectExactlyTheseSignals(prepareVotingJob, expected, {
346
+ ignoreMasking: true,
347
+ });
348
+ return true;
349
+ },
350
+ )
351
+ .beforeEach(initMocks)
352
+ .afterEach(tearDown),
353
+ { numRuns: 10 },
354
+ );
355
+ });
356
+
357
+ it('network requests (quorum and final message) must be sanitized, but pauseState must use the original value', async function () {
358
+ this.timeout(60 * SECOND);
359
+ await fc.assert(
360
+ fc
361
+ .asyncProperty(
362
+ fc.webUrl(),
363
+ fc.constantFrom('domain', 'hostname'),
364
+ fc.constantFrom('1d', '1w', '4w'),
365
+ async (url, urlProjection, intervalType) => {
366
+ const projections = computeUrlProjections(url);
367
+ const unmaskedVote = projections[urlProjection];
368
+ const countType = 'visits';
369
+
370
+ const { hostname } = new URL(url);
371
+ if (urlProjection === 'domain') {
372
+ expect(hostname.endsWith(unmaskedVote)).to.be.true;
373
+ } else {
374
+ expect(unmaskedVote).to.eql(hostname);
375
+ }
376
+
377
+ pauseState.isHostnamePaused = (actual) => {
378
+ expect(actual).to.eql(unmaskedVote); // <- original value
379
+ return true;
380
+ };
381
+
382
+ const vote = sanitizeHostname(unmaskedVote);
383
+ quorumChecker._everythingFailsQuorumExcept(vote); // <- masked value
384
+ countryProvider._ctry = 'de';
385
+
386
+ const prepareVotingJob = {
387
+ type: 'popularity-estimator:prepare-voting:v1',
388
+ args: {
389
+ urlProjection,
390
+ countType,
391
+ intervalType,
392
+ sample: {
393
+ value: unmaskedVote,
394
+ count: 1,
395
+ },
396
+ },
397
+ };
398
+
399
+ await expectExactlyTheseSignals(prepareVotingJob, [
400
+ {
401
+ type: { urlProjection, countType, intervalType },
402
+ vote, // <- masked value
403
+ ctry: 'de',
404
+ adblocker: {
405
+ paused: true,
406
+ mode: 'default',
407
+ },
408
+ },
409
+ ]);
410
+ return true;
411
+ },
412
+ )
413
+ .beforeEach(initMocks)
414
+ .afterEach(tearDown),
415
+ { numRuns: 10 },
416
+ );
417
+ });
418
+ });
419
+ });
420
+ });