@whotracksme/reporting 7.12.2 → 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 +24 -0
  2. package/communication/test/helpers/in-memory-database.js +45 -0
  3. package/package.json +2 -2
  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
@@ -30,15 +30,46 @@ import PersistedHashes from './persisted-hashes';
30
30
  import AliveCheck from './alive-check';
31
31
  import AliveMessageGenerator from './alive-message-generator';
32
32
  import SessionStorageWrapper from './session-storage';
33
+ import PopularityEstimator from './popularity-estimator';
34
+ import PopularityVoteHandler from './popularity-vote-handler';
35
+ import PausedDomainsReporter from './paused-domains-reporter';
33
36
  import AttrackMessageHandler from './communication-proxy/attrack-message-handler';
37
+ import Observable from './observable';
38
+ import { requireString, requireBoolean } from './utils';
34
39
  import logger from './logger';
35
40
  import SelfCheck from './self-check';
36
41
  import { BloomFilter } from './bloom-filters';
37
42
 
38
43
  const SECOND = 1000;
39
44
 
45
+ function disabledService() {
46
+ return {
47
+ isActive: false,
48
+ init: () => Promise.resolve(),
49
+ unload: () => {},
50
+ selfChecks: async (check = new SelfCheck()) => check,
51
+ };
52
+ }
53
+
40
54
  export default class Reporting {
41
- constructor({ config, storage, communication, connectDatabase }) {
55
+ constructor({
56
+ config,
57
+ storage,
58
+ communication,
59
+ connectDatabase,
60
+
61
+ // Optional integration of pause functionality.
62
+ // If running in an environment that has no concept
63
+ // of pausing, it can be safely omitted.
64
+ //
65
+ // Stub implementation:
66
+ // {
67
+ // getFilteringMode: () => 'default',
68
+ // isHostnamePaused: (_hostname) => false,
69
+ // connectHostnamePausingEvents: (_notify) => {},
70
+ // }
71
+ pauseState,
72
+ }) {
42
73
  // Defines whether Reporting is fully initialized and has permission
43
74
  // to collect data.
44
75
  this.isActive = false;
@@ -145,6 +176,23 @@ export default class Reporting {
145
176
  jobScheduler: this.jobScheduler,
146
177
  });
147
178
 
179
+ this.popularityEstimator = new PopularityEstimator({
180
+ storage,
181
+ storageKey: 'popularity_estimator',
182
+ connectDatabase,
183
+ jobScheduler: this.jobScheduler,
184
+ });
185
+ this.pages.addObserver(
186
+ this.popularityEstimator.onPageEvent.bind(this.popularityEstimator),
187
+ );
188
+ this.popularityVoteHandler = new PopularityVoteHandler({
189
+ jobScheduler: this.jobScheduler,
190
+ communication,
191
+ quorumChecker: this.quorumChecker,
192
+ countryProvider: this.countryProvider,
193
+ pauseState,
194
+ });
195
+
148
196
  const aliveMessageGenerator = new AliveMessageGenerator({
149
197
  quorumChecker: this.quorumChecker,
150
198
  storage,
@@ -163,6 +211,34 @@ export default class Reporting {
163
211
  communication,
164
212
  jobScheduler: this.jobScheduler,
165
213
  });
214
+
215
+ const hostnamePauseEvents = new Observable();
216
+ if (pauseState) {
217
+ pauseState.connectHostnamePausingEvents((msg) => {
218
+ if (this.isActive) {
219
+ // validate external message
220
+ const { hostname, paused } = msg;
221
+ requireString(hostname);
222
+ requireBoolean(paused);
223
+
224
+ hostnamePauseEvents.notifyObservers({ hostname, paused });
225
+ }
226
+ });
227
+ const filterModeProvider = pauseState.getFilteringMode.bind(pauseState);
228
+ this.pausedDomainsReporter = new PausedDomainsReporter({
229
+ filterModeProvider,
230
+ });
231
+ hostnamePauseEvents.addObserver(
232
+ this.pausedDomainsReporter.onPauseEvent.bind(
233
+ this.pausedDomainsReporter,
234
+ ),
235
+ );
236
+ } else {
237
+ logger.debug(
238
+ 'Disabling pausedDomainsReporter (requires access to the pause state)',
239
+ );
240
+ this.pausedDomainsReporter = disabledService();
241
+ }
166
242
  }
167
243
 
168
244
  async init() {
@@ -205,6 +281,8 @@ export default class Reporting {
205
281
  this.patternsUpdater.init(),
206
282
  this.countryProvider.init(),
207
283
  this.jobScheduler.init(),
284
+ this.popularityEstimator.init(),
285
+ this.pausedDomainsReporter.init(),
208
286
  ]);
209
287
 
210
288
  logger.debug('Fully initialized and ready');
@@ -220,6 +298,8 @@ export default class Reporting {
220
298
  this.navTrackingDetector.unload();
221
299
  this.pageAggregator.unload();
222
300
  this.jobScheduler.unload();
301
+ this.popularityEstimator.unload();
302
+ this.pausedDomainsReporter.unload();
223
303
 
224
304
  // Attempt to finish all pending changes, though it would not
225
305
  // be critical if we lose them. Important operations should
@@ -275,7 +355,7 @@ export default class Reporting {
275
355
 
276
356
  async _ensurePatternsAreUpToDate() {
277
357
  // Currently, the PatternsUpdater needs to be externally triggered.
278
- // This implementation detail could be avoided, if the PatternsUpdater
358
+ // This implementation detail could be avoided if the PatternsUpdater
279
359
  // could use a browser API like timers in persistent background pages
280
360
  // or the Alert API (Manifest V3).
281
361
  // The "update" function is a quick operation unless for the rare
@@ -295,17 +375,22 @@ export default class Reporting {
295
375
  if (!this.isActive) {
296
376
  check.warn('reporting is not enabled');
297
377
  }
298
- await Promise.all([
299
- this.pages.selfChecks(check.for('pages')),
300
- this.pagedb.selfChecks(check.for('pagedb')),
301
- this.patterns.selfChecks(check.for('patterns')),
302
- this.patternsUpdater.selfChecks(check.for('patternsUpdater')),
303
- this.bloomFilter.selfChecks(check.for('bloomFilter')),
304
- this.jobScheduler.selfChecks(check.for('jobScheduler')),
305
- this.quorumChecker.selfChecks(check.for('quorumChecker')),
306
- this.newPageApprover.selfChecks(check.for('newPageApprover')),
307
- this.pageSessionStore.selfChecks(check.for('pageSessionStore')),
308
- ]);
378
+
379
+ await Promise.all(
380
+ [
381
+ 'pages',
382
+ 'pagedb',
383
+ 'patterns',
384
+ 'patternsUpdater',
385
+ 'bloomFilter',
386
+ 'jobScheduler',
387
+ 'quorumChecker',
388
+ 'newPageApprover',
389
+ 'pageSessionStore',
390
+ 'popularityEstimator',
391
+ ].map((x) => this[x].selfChecks(check.for(x))),
392
+ );
393
+
309
394
  return check;
310
395
  }
311
396
  }
@@ -50,6 +50,20 @@ export function requireIntOrNull(value, name) {
50
50
  return value;
51
51
  }
52
52
 
53
+ // Expects a UTC timestamp represented as Unix period:
54
+ // - PASS: requireUTC(Date.now())
55
+ // - FAIL: requireUTC(new Date())
56
+ export function requireUTC(value, name) {
57
+ if (!Number.isSafeInteger(value) || value < 0) {
58
+ throw new Error(
59
+ name
60
+ ? `${name} should be a UTC timestamp, but got: <${value}>`
61
+ : `Parameter should be a UTC timestamp, but got: <${value}>`,
62
+ );
63
+ }
64
+ return value;
65
+ }
66
+
53
67
  export function requireString(value, name) {
54
68
  if (typeof value !== 'string') {
55
69
  throw new Error(
@@ -244,7 +258,7 @@ function sortedObjectEntries(x) {
244
258
  * If it returns true, you may assume that both inputs represent
245
259
  * the same data.
246
260
 
247
- * WARN: This implemenation will not detect identity in all situations;
261
+ * WARN: This implementation will not detect identity in all situations;
248
262
  * you may still get false for identical objects.
249
263
  * If you need stronger guarantees, use a real deepEqual implementation.
250
264
  *
@@ -305,6 +319,32 @@ export function split0(str, on) {
305
319
  return pos < 0 ? str : str.slice(0, pos);
306
320
  }
307
321
 
322
+ /**
323
+ * Checks if a string contains a specified character at least once,
324
+ * excluding any leading or trailing occurrences of that character.
325
+ *
326
+ * Example:
327
+ * 1) includesMiddleChar('a+b', '+') ==> true
328
+ * 2) includesMiddleChar('+ab', '+') ==> false
329
+ * 3) includesMiddleChar('ab+', '+') ==> false
330
+ */
331
+ export function includesMiddleChar(str, char) {
332
+ let start = 0;
333
+ let end = str.length - 1;
334
+ while (start < end && str[start] === char) {
335
+ start += 1;
336
+ }
337
+ while (end > start && str[end] === char) {
338
+ end -= 1;
339
+ }
340
+ for (let i = start; i < end; i += 1) {
341
+ if (str[i] === char) {
342
+ return true;
343
+ }
344
+ }
345
+ return false;
346
+ }
347
+
308
348
  /**
309
349
  * Drop-in replacement for JSON.parse if you need to handle untrusted data.
310
350
  *
@@ -72,8 +72,9 @@ describe('#ActivityEstimator', function () {
72
72
  clock?.restore();
73
73
  clock = sinon.useFakeTimers(new Date('2020-01-01'));
74
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
75
+ // Unless a timer was set at least once, clock.jump will fail
76
+ // TODO: we can remove this workaround if this fix is shipped with @sinon:
77
+ // https://github.com/sinonjs/fake-timers/pull/541
77
78
  setTimeout(() => {}, 0);
78
79
 
79
80
  listeners = new Listeners();
@@ -38,8 +38,8 @@ describe('#AliveCheck', function () {
38
38
  });
39
39
  }
40
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.
41
+ // Helper that simulates an event like a restart of the service worker/background script:
42
+ // it keeps the storage, but purges everything that was in memory.
43
43
  async function simulateRestart() {
44
44
  uut = newAliveCheck();
45
45
  }
@@ -71,8 +71,8 @@ describe('#CountryProvider', function () {
71
71
  });
72
72
  }
73
73
 
74
- // Helper that simulate an event like a restart of the service worker/background script:
75
- // it keeps the storage but purges everything that was in memory.
74
+ // Helper that simulates an event like a restart of the service worker/background script:
75
+ // it keeps the storage, but purges everything that was in memory.
76
76
  async function simulateRestart() {
77
77
  uut = newCountryProvider();
78
78
  }
@@ -15,9 +15,15 @@ import './alive-check.spec.js';
15
15
  import './alive-message-generator.spec.js';
16
16
  import './nav-tracking-detector.spec.js';
17
17
  import './network.spec.js';
18
+ import './observable.spec.js';
18
19
  import './pagedb.spec.js';
19
20
  import './pages.spec.js';
20
21
  import './page-aggregator.spec.js';
22
+ import './persisted-counters.spec.js';
23
+ import './popularity-estimator.spec.js';
24
+ import './popularity-vote-handler.spec.js';
25
+ import './popularity-vote-sanitizer.spec.js';
26
+ import './random.spec.js';
21
27
  import './sanitizer.spec.js';
22
28
  import './search-extractor.spec.js';
23
29
  import './session-storage.spec.js';
@@ -69,8 +69,8 @@ describe('#JobScheduler', function () {
69
69
  storageKey,
70
70
  });
71
71
  }
72
- // Helper that simulate an event like a restart of the service worker/background script:
73
- // it keeps the storage but purges everything that was in memory.
72
+ // Helper that simulates an event like a restart of the service worker/background script:
73
+ // it keeps the storage, but purges everything that was in memory.
74
74
  async function simulateRestart() {
75
75
  uut.unload();
76
76
  uut = newJobScheduler();
@@ -0,0 +1,72 @@
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
+
15
+ import Observable from '../src/observable.js';
16
+
17
+ describe('#Observable', function () {
18
+ let uut;
19
+
20
+ beforeEach(() => {
21
+ uut = new Observable();
22
+ });
23
+
24
+ it('should handle empty observer list', () => {
25
+ expect(() => uut.notifyObservers()).to.not.throw();
26
+ });
27
+
28
+ it('should call all subscribed observers', () => {
29
+ const observer1 = sinon.stub();
30
+ const observer2 = sinon.stub();
31
+ const observer3 = sinon.stub();
32
+ uut.addObserver(observer1);
33
+ uut.addObserver(observer2);
34
+ uut.addObserver(observer3);
35
+
36
+ uut.notifyObservers('foo', 'bar');
37
+
38
+ expect(observer1.calledOnceWithExactly('foo', 'bar')).to.be.true;
39
+ expect(observer2.calledOnceWithExactly('foo', 'bar')).to.be.true;
40
+ expect(observer3.calledOnceWithExactly('foo', 'bar')).to.be.true;
41
+ });
42
+
43
+ it('should continue if a single observers fails', () => {
44
+ const observer1 = sinon.stub().throws(new Error('Test error'));
45
+ const observer2 = sinon.stub();
46
+ const observer3 = sinon.stub();
47
+
48
+ uut.addObserver(observer1);
49
+ uut.addObserver(observer2);
50
+ uut.addObserver(observer3);
51
+
52
+ expect(() => uut.notifyObservers('arg1', 'arg2')).to.not.throw();
53
+
54
+ expect(observer1.calledOnce).to.be.true;
55
+ expect(observer2.calledOnce).to.be.true;
56
+ expect(observer3.calledOnce).to.be.true;
57
+ });
58
+
59
+ it('should not call observers that have unsubscribed', () => {
60
+ const observer1 = sinon.stub();
61
+ const observer2 = sinon.stub();
62
+ uut.addObserver(observer1);
63
+
64
+ uut.addObserver(observer2);
65
+ uut.removeObserver(observer2);
66
+
67
+ uut.notifyObservers('foo', 'bar');
68
+
69
+ expect(observer1.calledOnceWithExactly('foo', 'bar')).to.be.true;
70
+ expect(observer2.calledOnceWithExactly('foo', 'bar')).to.be.false;
71
+ });
72
+ });
@@ -72,8 +72,11 @@ describe('#PageAggregator', function () {
72
72
 
73
73
  describe('#init', function () {
74
74
  it('load + unload should not fail', async function () {
75
+ expect(uut.active).to.be.false;
75
76
  await uut.init();
77
+ expect(uut.active).to.be.true;
76
78
  uut.unload();
79
+ expect(uut.active).to.be.false;
77
80
  });
78
81
 
79
82
  it('should support multiple init and unload calls', async function () {
@@ -176,8 +176,8 @@ describe('#PatternsUpdater', function () {
176
176
  });
177
177
  }
178
178
 
179
- // Helper that simulate an event like a restart of the service worker/background script:
180
- // it keeps the storage but purges everything that was in memory.
179
+ // Helper that simulates an event like a restart of the service worker/background script:
180
+ // it keeps the storage, but purges everything that was in memory.
181
181
  async function simulateRestart() {
182
182
  uut = newPatternsUpdater();
183
183
  }
@@ -0,0 +1,132 @@
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 PersistedCounters from '../src/persisted-counters.js';
16
+
17
+ import InMemoryDatabase from './helpers/in-memory-database.js';
18
+
19
+ describe('#PersistedCounters', function () {
20
+ let db;
21
+ let uut;
22
+
23
+ function initMocks() {
24
+ db = new InMemoryDatabase();
25
+ uut = new PersistedCounters({ name: 'test', db });
26
+ }
27
+
28
+ function tearDown() {
29
+ db = null;
30
+ uut = null;
31
+ }
32
+
33
+ beforeEach(initMocks);
34
+ afterEach(tearDown);
35
+
36
+ describe('#sample', function () {
37
+ it('should return an empty array if nothing has been counted yet', async function () {
38
+ expect(await uut.sample()).to.eql([]);
39
+ });
40
+
41
+ it('should pick only element', async function () {
42
+ uut.count('foo');
43
+ expect(await uut.sample()).to.eql(['foo']);
44
+ });
45
+
46
+ it('should pick elements based on their counts', async function () {
47
+ uut.count('foo');
48
+ uut.count('bar');
49
+ uut.count('bar');
50
+
51
+ let foo = 0;
52
+ let bar = 0;
53
+ const samples = await uut.sample(1000);
54
+ for (const sample of samples) {
55
+ if (sample === 'foo') {
56
+ foo += 1;
57
+ } else if (sample === 'bar') {
58
+ bar += 1;
59
+ } else {
60
+ assert.fail(`Expected "foo" or "sample", but got: ${sample}`);
61
+ }
62
+ }
63
+ expect(foo + bar).to.eql(1000);
64
+ expect(foo).to.be.greaterThan(0);
65
+ expect(bar).to.be.greaterThan(0);
66
+ expect(bar).to.be.greaterThan(1.5 * foo);
67
+ expect(bar).to.be.lessThan(3 * foo);
68
+ });
69
+ });
70
+
71
+ describe('[property based testing]', function () {
72
+ describe('with default options', function () {
73
+ it('should return the expected number of samples, all with valid keys', async function () {
74
+ await fc.assert(
75
+ fc
76
+ .asyncProperty(
77
+ fc.array(fc.string()),
78
+ fc.nat(100),
79
+ async (keys, numSamples) => {
80
+ keys.forEach((key) => uut.count(key));
81
+ const result = await uut.sample(numSamples);
82
+ if (keys.length === 0) {
83
+ expect(result).to.eql([]);
84
+ } else {
85
+ expect(result).to.have.lengthOf(numSamples);
86
+ for (const key of result) {
87
+ expect(keys).to.include(key);
88
+ }
89
+ }
90
+ },
91
+ )
92
+ .beforeEach(initMocks)
93
+ .afterEach(tearDown),
94
+ );
95
+ });
96
+ });
97
+
98
+ describe('with grouping (option: { group: true })', function () {
99
+ it('should return groups summing to the expected number of samples, all with valid keys', async function () {
100
+ await fc.assert(
101
+ fc
102
+ .asyncProperty(
103
+ fc.array(fc.string()),
104
+ fc.nat(100),
105
+ async (keys, numSamples) => {
106
+ keys.forEach((key) => uut.count(key));
107
+ const result = await uut.sample(numSamples, { group: true });
108
+ if (keys.length === 0) {
109
+ expect(result).to.eql([]);
110
+ } else {
111
+ let sum = 0;
112
+ const keysSeen = new Set();
113
+ for (const [key, count] of result) {
114
+ expect(keys).to.include(key);
115
+ expect(count).to.be.a('number').greaterThan(0);
116
+ sum += count;
117
+
118
+ // there should be also no duplicates
119
+ expect(keysSeen).to.not.include(key);
120
+ keysSeen.add(key);
121
+ }
122
+ expect(sum).to.eql(numSamples);
123
+ }
124
+ },
125
+ )
126
+ .beforeEach(initMocks)
127
+ .afterEach(tearDown),
128
+ );
129
+ });
130
+ });
131
+ });
132
+ });