@whotracksme/reporting 5.1.28 → 5.1.29

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.
@@ -138,14 +138,14 @@ export default class RequestMonitor {
138
138
  return this.config.forceBlockEnabled;
139
139
  }
140
140
 
141
- async telemetry(message) {
141
+ telemetry(message) {
142
142
  if (!this.communication) {
143
143
  logger.error('No provider provider loaded');
144
144
  return;
145
145
  }
146
146
 
147
147
  message.type = 'wtm.request';
148
- message.userAgent = (await this.getBrowserInfo()).name;
148
+ message.userAgent = this.userAgent;
149
149
  message.ts = this.trustedClock.getTimeAsYYYYMMDD();
150
150
  message['anti-duplicates'] = Math.floor(random() * 10000000);
151
151
 
@@ -188,7 +188,7 @@ export default class RequestMonitor {
188
188
  this.webRequestPipeline.addOnPageStageListener((page) => {
189
189
  this.onPageStaged(page);
190
190
  });
191
-
191
+ this.userAgent = (await this.getBrowserInfo()).name;
192
192
  await this.initPipeline();
193
193
  }
194
194
 
@@ -66,13 +66,13 @@ export default class CachedEntryPipeline {
66
66
  * by #serialiseEntry
67
67
  * @param keys
68
68
  */
69
- saveBatchToDb(keys) {
69
+ async saveBatchToDb(keys) {
70
70
  const rows = keys.map((key) => {
71
71
  const entry = this.getFromCache(key);
72
72
  entry.dirty = false;
73
73
  return this.serialiseEntry(key, entry);
74
74
  });
75
- return this.db.bulkPut(rows);
75
+ await this.db.bulkPut(rows);
76
76
  }
77
77
 
78
78
  /**
@@ -83,25 +83,21 @@ export default class CachedEntryPipeline {
83
83
  * @param batchInterval how often to run batches
84
84
  * @param batchLimit maximum messages per batch
85
85
  */
86
- async init(
87
- inputObservable,
88
- sendMessage,
89
- batchInterval,
90
- batchLimit,
91
- overflowSubject,
92
- ) {
86
+ async init(inputObservable, sendMessage, batchInterval, batchLimit) {
93
87
  await this.cache.isReady;
94
88
  const pipeline = new Subject();
95
89
  this.input = inputObservable;
96
90
 
97
- let batch = [];
91
+ let inputBatch = [];
98
92
  setInterval(() => {
99
- pipeline.pub(batch);
100
- batch = [];
93
+ if (inputBatch.length > 0) {
94
+ pipeline.pub(inputBatch);
95
+ inputBatch = [];
96
+ }
101
97
  }, batchInterval);
102
98
 
103
99
  inputObservable.subscribe((token) => {
104
- batch.push(token);
100
+ inputBatch.push(token);
105
101
  });
106
102
 
107
103
  pipeline.subscribe(async (batch) => {
@@ -136,7 +132,7 @@ export default class CachedEntryPipeline {
136
132
  sendMessage(msg);
137
133
  });
138
134
  // push overflowed entries back into the queue
139
- overflowKeys.forEach((k) => overflowSubject.pub(k));
135
+ overflowKeys.forEach((k) => this.input.pub(k));
140
136
  } catch (e) {
141
137
  logger.error('Failed to initialize stream', e);
142
138
  }
@@ -159,14 +159,12 @@ export default class TokenTelemetry {
159
159
  (payload) => this.telemetry({ action: 'wtm.attrack.tokensv2', payload }),
160
160
  this.TOKEN_BATCH_INTERVAL,
161
161
  this.TOKEN_BATCH_SIZE,
162
- this.subjectTokens,
163
162
  );
164
163
  this.keys.init(
165
164
  this.keySendQueue,
166
165
  (payload) => this.telemetry({ action: 'wtm.attrack.keysv2', payload }),
167
166
  this.KEY_BATCH_INTERVAL,
168
167
  this.KEY_BATCH_SIZE,
169
- this.subjectTokens,
170
168
  );
171
169
 
172
170
  // run every x minutes while there is activity
@@ -48,12 +48,43 @@ async function download(release, scenario, browser) {
48
48
  return scenarioPath;
49
49
  }
50
50
 
51
+ function getSnapshotScenarioPath(name) {
52
+ return path.join(import.meta.dirname, '..', '..', 'snapshots', name);
53
+ }
54
+
55
+ export function recordSnapshot(name, messages) {
56
+ const snapshotPath = path.join(
57
+ getSnapshotScenarioPath(name),
58
+ 'snapshot.json',
59
+ );
60
+ fs.writeFileSync(snapshotPath, JSON.stringify(messages, null, 2));
61
+ }
62
+
63
+ export function readSnapshot(name) {
64
+ const snapshotPath = path.join(
65
+ getSnapshotScenarioPath(name),
66
+ 'snapshot.json',
67
+ );
68
+ return JSON.parse(fs.readFileSync(snapshotPath, { encoding: 'utf-8' }));
69
+ }
70
+
71
+ export function playSnapshotScenario(chrome, name, options = {}) {
72
+ const scenarioPath = path.join(
73
+ getSnapshotScenarioPath(name),
74
+ 'events.log.br',
75
+ );
76
+ const events = loadScenario(scenarioPath);
77
+ return playEvents(chrome, events, options);
78
+ }
79
+
51
80
  function loadScenario(scenarioPath) {
52
- return fs
53
- .readFileSync(scenarioPath, { encoding: 'utf-8' })
54
- .split('\n')
55
- .filter(Boolean)
56
- .map(JSON.parse);
81
+ let body;
82
+ if (scenarioPath.endsWith('.br')) {
83
+ body = brotliDecompressSync(fs.readFileSync(scenarioPath)).toString('utf8');
84
+ } else {
85
+ body = fs.readFileSync(scenarioPath, { encoding: 'utf-8' });
86
+ }
87
+ return body.split('\n').filter(Boolean).map(JSON.parse);
57
88
  }
58
89
 
59
90
  function rewriteIp(event) {
@@ -64,21 +95,35 @@ function rewriteIp(event) {
64
95
  return event;
65
96
  }
66
97
 
67
- export async function playScenario(
68
- chrome,
69
- { scenarioRelease, scenarioName, browser = 'chrome' },
70
- ) {
71
- if (!scenarioRelease) {
72
- throw new Error('specify scenario release');
73
- }
74
-
98
+ export function playEvents(chrome, events, options = {}) {
75
99
  const seenTabIds = new Set();
76
- const scenarioPath = await download(scenarioRelease, scenarioName, browser);
77
- const events = loadScenario(scenarioPath);
78
100
  for (const event of events) {
79
101
  try {
80
- const args = event.args.map(rewriteIp);
81
-
102
+ const args = event.args.map(rewriteIp).map((a) => {
103
+ if (typeof a !== 'object') {
104
+ return a;
105
+ }
106
+ const event = { ...a };
107
+ if (options.rewriteUrls) {
108
+ for (const key of Object.keys(options.rewriteUrls)) {
109
+ for (const prop of [
110
+ 'url',
111
+ 'originUrl',
112
+ 'initiator',
113
+ 'redirectUrl',
114
+ 'favIconUrl',
115
+ ]) {
116
+ if (event[prop]) {
117
+ event[prop] = event[prop].replace(
118
+ key,
119
+ options.rewriteUrls[key],
120
+ );
121
+ }
122
+ }
123
+ }
124
+ }
125
+ return event;
126
+ });
82
127
  if (events.api === 'tabs' && event.event === 'onCreated') {
83
128
  seenTabIds.add(args[0].id);
84
129
  } else {
@@ -102,3 +147,17 @@ export async function playScenario(
102
147
 
103
148
  return { seenTabIds };
104
149
  }
150
+
151
+ export async function playScenario(
152
+ chrome,
153
+ { scenarioRelease, scenarioName, browser = 'chrome' },
154
+ ) {
155
+ if (!scenarioRelease) {
156
+ throw new Error('specify scenario release');
157
+ }
158
+
159
+ const scenarioPath = await download(scenarioRelease, scenarioName, browser);
160
+ const events = loadScenario(scenarioPath);
161
+
162
+ return playEvents(chrome, events);
163
+ }
@@ -0,0 +1,96 @@
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 { IDBFactory } from 'fake-indexeddb';
13
+ import { expect } from 'chai';
14
+ import { deleteDB } from 'idb';
15
+
16
+ import Database from '../../src/request/database.js';
17
+
18
+ describe('request/database', function () {
19
+ let database;
20
+
21
+ beforeEach(async function () {
22
+ globalThis.indexedDB = new IDBFactory();
23
+
24
+ if (database) {
25
+ await database.unload();
26
+ await deleteDB(database.tableName);
27
+ }
28
+ database = new Database();
29
+ await database.init();
30
+ });
31
+
32
+ afterEach(function () {
33
+ delete globalThis.indexedDB;
34
+ });
35
+
36
+ describe('#tokens', function () {
37
+ it('#bulkPut', async function () {
38
+ const token = {
39
+ token: '8b72dcfadc69a786b66584b8b69d0512',
40
+ created: 10060,
41
+ safe: false,
42
+ lastSent: '',
43
+ sites: ['a10104ad75306d26', '6287472925cbc9b4'],
44
+ trackers: [
45
+ 'e10f949fcaacdb19',
46
+ 'e317a68e65ec3e72',
47
+ '14dd5266c70789bd',
48
+ '685c1532a4c8585c',
49
+ 'b1d934463190cb39',
50
+ '9521166916c82eac',
51
+ '513d8f48d45a9708',
52
+ 'aaaa9055e37b2c41',
53
+ '04e2599b3faf050b',
54
+ '2388a0be94d354c3',
55
+ '0fc2925edc331870',
56
+ 'b8ea0ff0ff328509',
57
+ 'a1da39e35b260336',
58
+ 'dd9091206cde9290',
59
+ 'dbb493430c36961e',
60
+ '7936b9e9fc6b1595',
61
+ '6dd56db607da346c',
62
+ '4b1f42f90487b5be',
63
+ 'fe61a5b83c837c9f',
64
+ '1a3c9a8ebcc58dac',
65
+ '1d5920f4b44b27a8',
66
+ '78f46604122e0a47',
67
+ '2952759073d266f1',
68
+ '8ea58e416a21d5bb',
69
+ '2343ec78a04c6ea9',
70
+ '1df7e81cf5e2db18',
71
+ 'f989f85475637850',
72
+ 'dbbc49f14541867e',
73
+ 'e244a3dd0980a641',
74
+ '421d522c51846d95',
75
+ '6660d08b6d1c5653',
76
+ '25ac106d69e67d6b',
77
+ '135b955866e31ce0',
78
+ 'aef0ae912fccaca6',
79
+ '3a59fb0cba397714',
80
+ 'b7961d2144027cc7',
81
+ '39e67d76e378a4d8',
82
+ '824a9c5b7b39d556',
83
+ '05d986b30d7eb849',
84
+ ],
85
+ count: 1,
86
+ };
87
+ expect(await database.tokens.count()).to.equal(0);
88
+ await database.tokens.bulkPut([
89
+ token,
90
+ // add the same token with a different id
91
+ { ...token, token: 1 },
92
+ ]);
93
+ expect(await database.tokens.count()).to.equal(2);
94
+ });
95
+ });
96
+ });
@@ -123,6 +123,7 @@ describe('request/index', function () {
123
123
  countryProvider: {},
124
124
  trustedClock,
125
125
  communication: {},
126
+ getBrowserInfo: () => ({ name: 'xx' }),
126
127
  },
127
128
  );
128
129
  await attrack.init(config);
@@ -10,14 +10,18 @@
10
10
  * file, You can obtain one at http://mozilla.org/MPL/2.0
11
11
  */
12
12
 
13
- import 'fake-indexeddb/auto';
14
- import { IDBFactory } from 'fake-indexeddb';
15
13
  import chrome from 'sinon-chrome';
16
14
  import sinon from 'sinon';
17
15
  import { expect } from 'chai';
18
16
  import EventEmitter from 'node:events';
17
+ import { IDBFactory } from 'fake-indexeddb';
19
18
 
20
- import { playScenario } from './helpers/scenarios.js';
19
+ import {
20
+ playScenario,
21
+ playSnapshotScenario,
22
+ recordSnapshot,
23
+ readSnapshot,
24
+ } from './helpers/scenarios.js';
21
25
  import { base64ToArrayBuffer } from './helpers/fetch-mock.js';
22
26
 
23
27
  import { setLogLevel } from '../src/logger.js';
@@ -59,7 +63,7 @@ describe('RequestReporter', function () {
59
63
  async arrayBuffer() {
60
64
  // empty bloom filter
61
65
  return base64ToArrayBuffer('AAAAAgrdwUcnN1113w==');
62
- }
66
+ },
63
67
  });
64
68
  }
65
69
 
@@ -98,10 +102,10 @@ describe('RequestReporter', function () {
98
102
  communicationEmiter.removeAllListeners();
99
103
  const communication = {
100
104
  send(msg) {
101
- communicationEmiter.emit('send', msg)
105
+ communicationEmiter.emit('send', msg);
102
106
  },
103
107
  sendInstant(msg) {
104
- communicationEmiter.emit('sendInstant', msg)
108
+ communicationEmiter.emit('sendInstant', msg);
105
109
  },
106
110
  trustedClock,
107
111
  };
@@ -138,7 +142,10 @@ describe('RequestReporter', function () {
138
142
  ).to.be.false;
139
143
  expect(seenTabIds).to.have.property('size', 1);
140
144
  const tabId = seenTabIds.values().next().value;
141
- const tab = reporter.webRequestPipeline.pageStore.getPageForRequest({ tabId, frameId: 0 });
145
+ const tab = reporter.webRequestPipeline.pageStore.getPageForRequest({
146
+ tabId,
147
+ frameId: 0,
148
+ });
142
149
  expect(tab.requestStats).to.be.empty;
143
150
  });
144
151
  });
@@ -155,10 +162,11 @@ describe('RequestReporter', function () {
155
162
  ).to.be.false;
156
163
  expect(seenTabIds).to.have.property('size', 1);
157
164
  const tabId = seenTabIds.values().next().value;
158
- const tab = reporter.webRequestPipeline.pageStore.getPageForRequest({ tabId, frameId: 0 });
159
- expect(tab.requestStats).to.have.keys([
160
- 'script.localhost',
161
- ]);
165
+ const tab = reporter.webRequestPipeline.pageStore.getPageForRequest({
166
+ tabId,
167
+ frameId: 0,
168
+ });
169
+ expect(tab.requestStats).to.have.keys(['script.localhost']);
162
170
  });
163
171
 
164
172
  it('reports 3rd parties', async function () {
@@ -167,23 +175,25 @@ describe('RequestReporter', function () {
167
175
  scenarioRelease: '2024-08-02',
168
176
  });
169
177
  await clock.runToLast();
170
- const eventPromise = new Promise((resolve) => communicationEmiter.once('send', resolve));
178
+ const eventPromise = new Promise((resolve) =>
179
+ communicationEmiter.once('send', resolve),
180
+ );
171
181
  // force stage all pages
172
- seenTabIds.forEach(tabId => chrome.tabs.onRemoved.dispatch(tabId));
182
+ seenTabIds.forEach((tabId) => chrome.tabs.onRemoved.dispatch(tabId));
173
183
  await clock.runToLast();
174
184
  const event = await eventPromise;
175
185
  expect(event).to.deep.include({
176
186
  action: 'wtm.attrack.tp_events',
177
187
  });
178
- expect(event.payload.data[0].tps).to.have.keys([
179
- 'script.localhost',
180
- ])
188
+ expect(event.payload.data[0].tps).to.have.keys(['script.localhost']);
181
189
  });
182
190
  });
183
191
 
184
192
  context('0004-ping', function () {
185
193
  it('reports pings', async function () {
186
- const eventPromise = new Promise((resolve) => communicationEmiter.once('send', resolve));
194
+ const eventPromise = new Promise((resolve) =>
195
+ communicationEmiter.once('send', resolve),
196
+ );
187
197
  await playScenario(chrome, {
188
198
  scenarioName: this.test.parent.title,
189
199
  scenarioRelease: '2024-08-02-1',
@@ -194,9 +204,7 @@ describe('RequestReporter', function () {
194
204
  expect(event).to.deep.include({
195
205
  action: 'wtm.attrack.tp_events',
196
206
  });
197
- expect(event.payload.data[0].tps).to.have.keys([
198
- 'ping.localhost',
199
- ])
207
+ expect(event.payload.data[0].tps).to.have.keys(['ping.localhost']);
200
208
  });
201
209
  });
202
210
 
@@ -207,23 +215,25 @@ describe('RequestReporter', function () {
207
215
  scenarioRelease: '2024-08-02',
208
216
  });
209
217
  await clock.runToLast();
210
- const eventPromise = new Promise((resolve) => communicationEmiter.once('send', resolve));
218
+ const eventPromise = new Promise((resolve) =>
219
+ communicationEmiter.once('send', resolve),
220
+ );
211
221
  // force stage all pages
212
- seenTabIds.forEach(tabId => chrome.tabs.onRemoved.dispatch(tabId));
222
+ seenTabIds.forEach((tabId) => chrome.tabs.onRemoved.dispatch(tabId));
213
223
  await clock.runToLast();
214
224
  const event = await eventPromise;
215
225
  expect(event).to.deep.include({
216
226
  action: 'wtm.attrack.tp_events',
217
227
  });
218
- expect(event.payload.data[0].tps).to.have.keys([
219
- 'preload.localhost',
220
- ]);
228
+ expect(event.payload.data[0].tps).to.have.keys(['preload.localhost']);
221
229
  });
222
230
  });
223
231
 
224
232
  context('0008-navigation', function () {
225
233
  it('reports 3rd parties', async function () {
226
- const eventPromise1 = new Promise((resolve) => communicationEmiter.once('send', resolve));
234
+ const eventPromise1 = new Promise((resolve) =>
235
+ communicationEmiter.once('send', resolve),
236
+ );
227
237
  const { seenTabIds } = await playScenario(chrome, {
228
238
  scenarioName: this.test.parent.title,
229
239
  scenarioRelease: '2024-08-02-2',
@@ -233,23 +243,73 @@ describe('RequestReporter', function () {
233
243
  expect(event1).to.deep.include({
234
244
  action: 'wtm.attrack.tp_events',
235
245
  });
236
- expect(event1.payload.data[0].tps).to.have.keys([
237
- 'script1.localhost',
238
- ]);
239
- const eventPromise2 = new Promise((resolve) => communicationEmiter.once('send', resolve));
246
+ expect(event1.payload.data[0].tps).to.have.keys(['script1.localhost']);
247
+ const eventPromise2 = new Promise((resolve) =>
248
+ communicationEmiter.once('send', resolve),
249
+ );
240
250
  // force stage all pages
241
- seenTabIds.forEach(tabId => chrome.tabs.onRemoved.dispatch(tabId));
251
+ seenTabIds.forEach((tabId) => chrome.tabs.onRemoved.dispatch(tabId));
242
252
  await clock.runToLast();
243
253
  const event2 = await eventPromise2;
244
254
  expect(event2).to.deep.include({
245
255
  action: 'wtm.attrack.tp_events',
246
256
  });
247
- expect(event2.payload.data[0].tps).to.have.keys([
248
- 'script2.localhost',
249
- ]);
257
+ expect(event2.payload.data[0].tps).to.have.keys(['script2.localhost']);
250
258
  // reports should belong to different pages
251
- expect(event1.payload.data[0].hostname).to.not.be.equal(event2.payload.data[0].hostname);
259
+ expect(event1.payload.data[0].hostname).to.not.be.equal(
260
+ event2.payload.data[0].hostname,
261
+ );
252
262
  });
253
263
  });
264
+
265
+ context('snapshots', function () {
266
+ this.timeout(10000);
267
+
268
+ function cleanupMessage(message) {
269
+ delete message['anti-duplicates'];
270
+ return message;
271
+ }
272
+
273
+ async function processRunloopUntil(timeout) {
274
+ const start = Date.now();
275
+ // eslint-disable-next-line no-constant-condition
276
+ while (true) {
277
+ const now = await clock.runToLast();
278
+ if (now - start > timeout) {
279
+ break;
280
+ }
281
+ }
282
+ }
283
+
284
+ for (const snapshotName of ['0001', '0002']) {
285
+ it(snapshotName, async function () {
286
+ const messages = [];
287
+ communicationEmiter.addListener('send', (message) =>
288
+ messages.push(cleanupMessage(message)),
289
+ );
290
+ playSnapshotScenario(chrome, snapshotName);
291
+
292
+ // run twice to allow token telemetry to trigger
293
+ playSnapshotScenario(chrome, snapshotName, {
294
+ rewriteUrls: { 'onet.pl': 'wp.pl' },
295
+ });
296
+ await processRunloopUntil(
297
+ reporter.requestMonitor.pipelineSteps.tokenTelemetry
298
+ .NEW_ENTRY_MIN_AGE,
299
+ );
300
+
301
+ // eslint-disable-next-line no-undef
302
+ if (process.argv.includes('--record-snapshot')) {
303
+ recordSnapshot(snapshotName, messages);
304
+ }
305
+
306
+ const snapshot = await readSnapshot(snapshotName);
307
+ expect(messages).to.have.lengthOf(snapshot.length);
308
+ messages.forEach((message, index) => {
309
+ expect(message).to.deep.equal(snapshot[index]);
310
+ });
311
+ });
312
+ }
313
+ });
254
314
  });
255
315
  });
@@ -9,6 +9,7 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
+ import 'fake-indexeddb/auto';
12
13
  import * as chai from 'chai';
13
14
  import sinonChai from 'sinon-chai';
14
15
  import chaiAsPromised from 'chai-as-promised';