@whotracksme/reporting 5.1.28 → 5.1.30

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 (59) hide show
  1. package/CHANGELOG.md +37 -0
  2. package/package.json +1 -1
  3. package/reporting/example/index.js +2 -12
  4. package/reporting/example/manifests/chromium.json +1 -0
  5. package/reporting/snapshots/0001/events.log.br +0 -0
  6. package/reporting/snapshots/0001/snapshot.json +4173 -0
  7. package/reporting/snapshots/0002/events.log.br +0 -0
  8. package/reporting/snapshots/0002/snapshot.json +2539 -0
  9. package/reporting/snapshots/0003/events.log.br +0 -0
  10. package/reporting/snapshots/0003/snapshot.json +855 -0
  11. package/reporting/snapshots/0004/events.log.br +0 -0
  12. package/reporting/snapshots/0004/snapshot.json +802 -0
  13. package/reporting/src/hash-detector.js +1 -1
  14. package/reporting/src/index.js +1 -2
  15. package/reporting/src/request/config.js +9 -4
  16. package/reporting/src/request/{hash.js → hash/index.js} +3 -3
  17. package/reporting/src/request/index.js +447 -496
  18. package/reporting/src/{webrequest-pipeline → request}/page-store.js +65 -75
  19. package/reporting/src/request/qs-whitelist2.js +0 -2
  20. package/reporting/src/request/steps/cookie-context.js +6 -5
  21. package/reporting/src/request/steps/oauth-detector.js +3 -24
  22. package/reporting/src/request/steps/page-logger.js +3 -4
  23. package/reporting/src/request/steps/token-checker/token-domain.js +1 -1
  24. package/reporting/src/request/steps/token-examiner.js +3 -4
  25. package/reporting/src/request/steps/token-telemetry/cached-entry-pipeline.js +55 -75
  26. package/reporting/src/request/steps/token-telemetry/index.js +86 -115
  27. package/reporting/src/request/steps/token-telemetry/key-pipeline.js +3 -2
  28. package/reporting/src/request/steps/token-telemetry/token-pipeline.js +3 -2
  29. package/reporting/src/request/utils/temp-set.js +2 -4
  30. package/reporting/src/request/{time.js → utils/time.js} +0 -5
  31. package/reporting/src/request/utils/tlds.js +1 -11
  32. package/reporting/src/request/{utils.js → utils/utils.js} +9 -0
  33. package/reporting/src/{webrequest-pipeline/webrequest-context.js → request/utils/webrequest.js} +84 -4
  34. package/reporting/src/utils/url.js +0 -25
  35. package/reporting/test/helpers/scenarios.js +76 -17
  36. package/reporting/test/index.js +3 -8
  37. package/reporting/test/request/database.test.js +96 -0
  38. package/reporting/test/request/{hash.spec.js → hash/index.spec.js} +2 -2
  39. package/reporting/test/request/index.spec.js +24 -46
  40. package/reporting/test/{request-reporter.test.js → request/index.test.js} +102 -46
  41. package/reporting/test/{webrequest-pipeline → request}/page-store.test.js +1 -1
  42. package/reporting/test/request/steps/oauth-detector.spec.js +15 -25
  43. package/reporting/test/request/{utils.spec.js → utils/utils.spec.js} +2 -2
  44. package/reporting/test/setup.unit.js +1 -0
  45. package/reporting/test/utils/url.spec.js +1 -26
  46. package/reporting/src/request/page-telemetry.js +0 -42
  47. package/reporting/src/request/steps/subdomain-check.js +0 -34
  48. package/reporting/src/request/utils/subject.js +0 -37
  49. package/reporting/src/request-reporter.js +0 -111
  50. package/reporting/src/utils/pacemaker.js +0 -279
  51. package/reporting/src/webrequest-pipeline/cname-uncloak.js +0 -110
  52. package/reporting/src/webrequest-pipeline/index.js +0 -286
  53. package/reporting/src/webrequest-pipeline/logger.js +0 -14
  54. package/reporting/src/webrequest-pipeline/pipeline.js +0 -249
  55. package/reporting/src/webrequest-pipeline/utils/webrequest.js +0 -119
  56. package/reporting/test/utils/pacemaker.spec.js +0 -222
  57. package/reporting/test/webrequest-pipeline/index.test.js +0 -160
  58. package/reporting/test/webrequest-pipeline/pipeline.spec.js +0 -251
  59. /package/reporting/src/request/{resources → hash}/prob.js +0 -0
@@ -10,7 +10,6 @@
10
10
  */
11
11
 
12
12
  import md5, { truncatedHash } from '../../../md5.js';
13
- import Subject from '../../utils/subject.js';
14
13
  import KeyPipeline, { getSiteTokensMap } from './key-pipeline.js';
15
14
  import TokenPipeline from './token-pipeline.js';
16
15
 
@@ -72,113 +71,94 @@ export default class TokenTelemetry {
72
71
  this.config = config;
73
72
  this.trustedClock = trustedClock;
74
73
  this.shouldCheckToken = shouldCheckToken;
75
- this.subjectTokens = new Subject();
76
- this.tokenSendQueue = new Subject();
77
- this.keySendQueue = new Subject();
78
-
74
+ this.batch = [];
79
75
  this.tokens = new TokenPipeline({
80
76
  name: 'tokens',
81
77
  db: database.tokens,
82
78
  trustedClock,
83
79
  options: opts,
80
+ sendMessage: (payload) =>
81
+ this.telemetry({ action: 'wtm.attrack.tokensv2', payload }),
82
+ batchInterval: this.TOKEN_BATCH_INTERVAL,
83
+ batchLimit: this.TOKEN_BATCH_SIZE,
84
84
  });
85
85
  this.keys = new KeyPipeline({
86
86
  name: 'keys',
87
87
  db: database.keys,
88
88
  trustedClock,
89
89
  options: opts,
90
+ sendMessage: (payload) =>
91
+ this.telemetry({ action: 'wtm.attrack.keysv2', payload }),
92
+ batchInterval: this.KEY_BATCH_INTERVAL,
93
+ batchLimit: this.KEY_BATCH_SIZE,
90
94
  });
91
95
  }
92
96
 
93
97
  async init() {
94
98
  await this.tokens.isReady;
95
99
  await this.keys.isReady;
96
- let filteredTokensBatch = [];
97
- const filteredTokens = new Subject();
100
+ await this.tokens.init();
101
+ await this.keys.init();
102
+
98
103
  setInterval(() => {
99
- filteredTokens.pub(filteredTokensBatch);
100
- filteredTokensBatch = [];
104
+ this.#processBatch([...this.batch]);
105
+ this.batch = [];
101
106
  }, this.TOKEN_BUFFER_TIME);
102
107
 
103
- this.subjectTokens.subscribe((token) => {
104
- filteredTokensBatch.push(token);
105
- });
108
+ // run every x minutes while there is activity
109
+ setInterval(async () => {
110
+ await this.tokens.clean();
111
+ await this.keys.clean();
112
+ }, this.CLEAN_INTERVAL);
113
+ }
106
114
 
107
- // token subscription pipeline takes batches of tokens (grouped by value)
108
- // caches their state, and pushes values for sending once they reach a sending
109
- // threshold.
115
+ // token subscription pipeline takes batches of tokens (grouped by value)
116
+ // caches their state, and pushes values for sending once they reach a sending
117
+ // threshold.
118
+ #processBatch(batch) {
119
+ if (batch.length === 0) {
120
+ return;
121
+ }
110
122
  const today = this.trustedClock.getTimeAsYYYYMMDD();
111
- filteredTokens.subscribe((batch) => {
112
- if (batch.length === 0) {
113
- return;
123
+ // process a batch of entries for a specific token
124
+ const token = batch[0].token;
125
+
126
+ const tokenStats = this.tokens.get(token);
127
+ const entryCutoff = Date.now() - this.NEW_ENTRY_MIN_AGE;
128
+ tokenStats.dirty = true;
129
+
130
+ batch.forEach((entry) => {
131
+ if (!tokenStats.sites.includes(entry.fp)) {
132
+ tokenStats.sites.push(entry.fp);
114
133
  }
115
- // process a batch of entries for a specific token
116
- const token = batch[0].token;
134
+ if (!tokenStats.trackers.includes(entry.tp)) {
135
+ tokenStats.trackers.push(entry.tp);
136
+ }
137
+ tokenStats.safe = tokenStats.safe && entry.safe;
117
138
 
118
- const tokenStats = this.tokens.get(token);
119
- const entryCutoff = Date.now() - this.NEW_ENTRY_MIN_AGE;
120
- tokenStats.dirty = true;
139
+ const keyKey = `${entry.tp}:${entry.key}`;
140
+ const keyStats = this.keys.get(keyKey);
141
+ keyStats.key = entry.key;
142
+ keyStats.tracker = entry.tp;
143
+ keyStats.dirty = true;
144
+ const siteTokens = getSiteTokensMap(keyStats.sitesTokens, entry.fp);
145
+ siteTokens[entry.token] = entry.safe;
121
146
 
122
- batch.forEach((entry) => {
123
- if (!tokenStats.sites.includes(entry.fp)) {
124
- tokenStats.sites.push(entry.fp);
125
- }
126
- if (!tokenStats.trackers.includes(entry.tp)) {
127
- tokenStats.trackers.push(entry.tp);
128
- }
129
- tokenStats.safe = tokenStats.safe && entry.safe;
130
-
131
- const keyKey = `${entry.tp}:${entry.key}`;
132
- const keyStats = this.keys.get(keyKey);
133
- keyStats.key = entry.key;
134
- keyStats.tracker = entry.tp;
135
- keyStats.dirty = true;
136
- const siteTokens = getSiteTokensMap(keyStats.sitesTokens, entry.fp);
137
- siteTokens[entry.token] = entry.safe;
138
-
139
- if (
140
- keyStats.lastSent !== today &&
141
- (Object.keys(keyStats.sitesTokens).length > 1 ||
142
- (keyStats.count > this.MIN_COUNT && keyStats.created < entryCutoff))
143
- ) {
144
- this.keySendQueue.pub(keyKey);
145
- }
146
- });
147
147
  if (
148
- tokenStats.lastSent !== today &&
149
- (tokenStats.sites.length > 1 ||
150
- (tokenStats.count > this.MIN_COUNT &&
151
- tokenStats.created < entryCutoff))
148
+ keyStats.lastSent !== today &&
149
+ (Object.keys(keyStats.sitesTokens).length > 1 ||
150
+ (keyStats.count > this.MIN_COUNT && keyStats.created < entryCutoff))
152
151
  ) {
153
- this.tokenSendQueue.pub(token);
152
+ this.keys.processEntry(keyKey);
154
153
  }
155
154
  });
156
-
157
- this.tokens.init(
158
- this.tokenSendQueue,
159
- (payload) => this.telemetry({ action: 'wtm.attrack.tokensv2', payload }),
160
- this.TOKEN_BATCH_INTERVAL,
161
- this.TOKEN_BATCH_SIZE,
162
- this.subjectTokens,
163
- );
164
- this.keys.init(
165
- this.keySendQueue,
166
- (payload) => this.telemetry({ action: 'wtm.attrack.keysv2', payload }),
167
- this.KEY_BATCH_INTERVAL,
168
- this.KEY_BATCH_SIZE,
169
- this.subjectTokens,
170
- );
171
-
172
- // run every x minutes while there is activity
173
- setInterval(async () => {
174
- await this.tokens.clean();
175
- await this.keys.clean();
176
- }, this.CLEAN_INTERVAL);
177
- }
178
-
179
- unload() {
180
- this.tokens.unload();
181
- this.keys.unload();
155
+ if (
156
+ tokenStats.lastSent !== today &&
157
+ (tokenStats.sites.length > 1 ||
158
+ (tokenStats.count > this.MIN_COUNT && tokenStats.created < entryCutoff))
159
+ ) {
160
+ this.tokens.processEntry(token);
161
+ }
182
162
  }
183
163
 
184
164
  extractKeyTokens(state) {
@@ -191,44 +171,35 @@ export default class TokenTelemetry {
191
171
  // const domain = md5(truncatedDomain).substr(0, 16);
192
172
  const firstParty = truncatedHash(state.tabUrlParts.generalDomain);
193
173
  const generalDomain = truncatedHash(state.urlParts.generalDomain);
194
- this._saveKeyTokens({
195
- // thirdParty: truncatedDomain,
196
- kv: keyTokens,
197
- firstParty,
198
- thirdPartyGeneralDomain: generalDomain,
199
- });
200
- }
201
- return true;
202
- }
203
174
 
204
- _saveKeyTokens({ kv, firstParty, thirdPartyGeneralDomain }) {
205
- // anything here should already be hash
206
- const isTracker = this.qsWhitelist.isTrackerDomain(thirdPartyGeneralDomain);
175
+ // anything here should already be hash
176
+ const isTracker = this.qsWhitelist.isTrackerDomain(generalDomain);
207
177
 
208
- /* eslint camelcase: 'off' */
209
- kv.forEach(([k, v]) => {
210
- if (!this.shouldCheckToken(v)) {
211
- return;
212
- }
213
- const token = md5(v);
214
- const key = md5(k);
215
-
216
- // put token in safe bucket if: value is short, domain is not a tracker,
217
- // or key or value is whitelisted
218
- const safe =
219
- !isTracker ||
220
- this.qsWhitelist.isSafeKey(thirdPartyGeneralDomain, key) ||
221
- this.qsWhitelist.isSafeToken(thirdPartyGeneralDomain, token);
222
-
223
- this.subjectTokens.pub({
224
- day: this.trustedClock.getTimeAsYYYYMMDD(),
225
- key,
226
- token,
227
- tp: thirdPartyGeneralDomain,
228
- fp: firstParty,
229
- safe,
230
- isTracker,
178
+ keyTokens.forEach(([k, v]) => {
179
+ if (!this.shouldCheckToken(v)) {
180
+ return;
181
+ }
182
+ const token = md5(v);
183
+ const key = md5(k);
184
+
185
+ // put token in safe bucket if: value is short, domain is not a tracker,
186
+ // or key or value is whitelisted
187
+ const safe =
188
+ !isTracker ||
189
+ this.qsWhitelist.isSafeKey(generalDomain, key) ||
190
+ this.qsWhitelist.isSafeToken(generalDomain, token);
191
+
192
+ this.batch.push({
193
+ day: this.trustedClock.getTimeAsYYYYMMDD(),
194
+ key,
195
+ token,
196
+ tp: generalDomain,
197
+ fp: firstParty,
198
+ safe,
199
+ isTracker,
200
+ });
231
201
  });
232
- });
202
+ }
203
+ return true;
233
204
  }
234
205
  }
@@ -21,8 +21,9 @@ export function getSiteTokensMap(siteTokens, key) {
21
21
  }
22
22
 
23
23
  export default class KeyPipeline extends CachedEntryPipeline {
24
- constructor({ db, trustedClock, name, options }) {
25
- super({ db, trustedClock, name, options, primaryKey: 'hash' });
24
+ constructor(options) {
25
+ super(options);
26
+ this.primaryKey = 'hash';
26
27
  }
27
28
 
28
29
  newEntry() {
@@ -12,8 +12,9 @@
12
12
  import CachedEntryPipeline from './cached-entry-pipeline.js';
13
13
 
14
14
  export default class TokenPipeline extends CachedEntryPipeline {
15
- constructor({ db, trustedClock, options, name }) {
16
- super({ db, trustedClock, name, options, primaryKey: 'token' });
15
+ constructor(options) {
16
+ super(options);
17
+ this.primaryKey = 'token';
17
18
  }
18
19
 
19
20
  newEntry() {
@@ -12,8 +12,6 @@
12
12
  /* eslint func-names: 'off' */
13
13
  /* eslint prefer-arrow-callback: 'off' */
14
14
 
15
- import pacemaker from '../../utils/pacemaker.js';
16
-
17
15
  /** Set like class whose members are removed after a specific amount of time
18
16
  */
19
17
  export default class TempSet {
@@ -32,7 +30,7 @@ export default class TempSet {
32
30
 
33
31
  add(item, ttl) {
34
32
  this._items.add(item);
35
- const timeout = pacemaker.setTimeout(
33
+ const timeout = setTimeout(
36
34
  function () {
37
35
  this.delete(item);
38
36
  this._timeouts.delete(timeout);
@@ -48,7 +46,7 @@ export default class TempSet {
48
46
 
49
47
  clear() {
50
48
  for (const t of this._timeouts) {
51
- pacemaker.clearTimeout(t);
49
+ clearTimeout(t);
52
50
  }
53
51
  this._timeouts.clear();
54
52
  this._items.clear();
@@ -56,11 +56,6 @@ export function dateString(date) {
56
56
  return yyyy + (mm[1] ? mm : `0${mm[0]}`) + (dd[1] ? dd : `0${dd[0]}`); // padding
57
57
  }
58
58
 
59
- export function hourString(date) {
60
- const hour = date.getUTCHours().toString();
61
- return dateString(date) + (hour[1] ? hour : `0${hour[0]}`);
62
- }
63
-
64
59
  export function getCurrentDay() {
65
60
  if (!getCurrentDay._currentDay || Date.now() > getCurrentDay._nextDayCheck) {
66
61
  const day = getTime().substr(0, 8);
@@ -30,9 +30,6 @@ function parse(url) {
30
30
  }
31
31
 
32
32
  const getGeneralDomain = (url) => parse(url).domain;
33
- const getPublicSuffix = tldts.getPublicSuffix;
34
- const getDomainWithoutSuffix = tldts.getDomainWithoutSuffix;
35
- const extractHostname = tldts.getHostname;
36
33
 
37
34
  function sameGeneralDomain(uri1, uri2) {
38
35
  if (uri1 === uri2) {
@@ -45,11 +42,4 @@ function sameGeneralDomain(uri1, uri2) {
45
42
  return domain1 !== null && domain2 !== null && domain1 === domain2;
46
43
  }
47
44
 
48
- export {
49
- extractHostname,
50
- getDomainWithoutSuffix,
51
- getGeneralDomain,
52
- getPublicSuffix,
53
- parse,
54
- sameGeneralDomain,
55
- };
45
+ export { getGeneralDomain, sameGeneralDomain };
@@ -39,3 +39,12 @@ export function shuffle(s) {
39
39
  }
40
40
  return a.join('');
41
41
  }
42
+
43
+ const ipv4Part = '0*([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])'; // numbers 0 - 255
44
+ const ipv4Regex = new RegExp(
45
+ `^${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}([:]([0-9])+)?$`,
46
+ ); // port number
47
+
48
+ export function isIpv4Address(host) {
49
+ return ipv4Regex.test(host);
50
+ }
@@ -9,8 +9,89 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
- import { parse } from '../utils/url.js';
13
- import logger from './logger.js';
12
+ import { parse } from '../../utils/url.js';
13
+
14
+ const VALID_RESPONSE_PROPERTIES = {
15
+ onBeforeRequest: ['cancel', 'redirectUrl'],
16
+ onBeforeSendHeaders: ['cancel', 'requestHeaders'],
17
+ onSendHeaders: [],
18
+ onHeadersReceived: ['cancel', 'redirectUrl', 'responseHeaders'],
19
+ onAuthRequired: ['cancel'],
20
+ onResponseStarted: [],
21
+ onBeforeRedirect: [],
22
+ onCompleted: [],
23
+ onErrorOccurred: [],
24
+ };
25
+
26
+ function modifyHeaderByType(headers, name, value) {
27
+ const lowerCaseName = name.toLowerCase();
28
+ const filteredHeaders = headers.filter(
29
+ (h) => h.name.toLowerCase() !== lowerCaseName,
30
+ );
31
+ if (value) {
32
+ filteredHeaders.push({ name, value });
33
+ }
34
+ return filteredHeaders;
35
+ }
36
+
37
+ /**
38
+ * Small abstraction on top of blocking responses expected by WebRequest API. It
39
+ * provides a few helpers to block, redirect or modify headers. It is also able
40
+ * to create a valid blocking response taking into account platform-specific
41
+ * allowed capabilities.
42
+ */
43
+ export class BlockingResponse {
44
+ constructor(details, event) {
45
+ this.details = details;
46
+
47
+ // Blocking response
48
+ this.redirectUrl = undefined;
49
+ this.cancel = undefined;
50
+ this.responseHeaders = undefined;
51
+ this.requestHeaders = undefined;
52
+ this.shouldIncrementCounter = undefined;
53
+ this.event = event;
54
+ }
55
+
56
+ redirectTo(url) {
57
+ this.redirectUrl = url;
58
+ }
59
+
60
+ block() {
61
+ this.cancel = true;
62
+ }
63
+
64
+ modifyHeader(name, value) {
65
+ this.requestHeaders = modifyHeaderByType(
66
+ this.requestHeaders || this.details.requestHeaders || [],
67
+ name,
68
+ value,
69
+ );
70
+ }
71
+
72
+ modifyResponseHeader(name, value) {
73
+ this.responseHeaders = modifyHeaderByType(
74
+ this.responseHeaders || this.details.responseHeaders || [],
75
+ name,
76
+ value,
77
+ );
78
+ }
79
+
80
+ toWebRequestResponse() {
81
+ const allowedProperties = VALID_RESPONSE_PROPERTIES[this.event];
82
+ const response = {};
83
+
84
+ for (let i = 0; i < allowedProperties.length; i += 1) {
85
+ const prop = allowedProperties[i];
86
+ const value = this[prop];
87
+ if (value !== undefined) {
88
+ response[prop] = value;
89
+ }
90
+ }
91
+
92
+ return response;
93
+ }
94
+ }
14
95
 
15
96
  /**
16
97
  * Transform an array of headers (i.e.: `{ name, value }`) into a `Map`.
@@ -29,7 +110,7 @@ function createHeadersGetter(headers) {
29
110
  /**
30
111
  * Wrap webRequest's details to provide convenient helpers.
31
112
  */
32
- export default class WebRequestContext {
113
+ export class WebRequestContext {
33
114
  /**
34
115
  * "Smart" constructor for `WebRequestContext`. It will make sure that the same
35
116
  * information is provided for different browsers (e.g.: Chrome and Firefox) as
@@ -41,7 +122,6 @@ export default class WebRequestContext {
41
122
 
42
123
  // Check if we have a URL
43
124
  if (!context.url) {
44
- logger.log('Ignoring request with empty url', context);
45
125
  return null;
46
126
  }
47
127
 
@@ -11,15 +11,6 @@
11
11
 
12
12
  import { ImmutableURL } from '@cliqz/url-parser';
13
13
 
14
- const ipv4Part = '0*([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])'; // numbers 0 - 255
15
- const ipv4Regex = new RegExp(
16
- `^${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}\\.${ipv4Part}([:]([0-9])+)?$`,
17
- ); // port number
18
-
19
- export function isIpv4Address(host) {
20
- return ipv4Regex.test(host);
21
- }
22
-
23
14
  /**
24
15
  * This is an abstraction over URL with caching and basic error handling built in. The main
25
16
  * difference is that this catches exceptions from the URL constructor (when the url is invalid)
@@ -67,19 +58,3 @@ function tryDecode(fn) {
67
58
  }
68
59
 
69
60
  export const tryDecodeURIComponent = tryDecode(decodeURIComponent);
70
-
71
- export function getName(url) {
72
- if (url === null) {
73
- return null;
74
- }
75
-
76
- if (url.hostIsIp) {
77
- return 'IP';
78
- }
79
-
80
- if (!url.hostname) {
81
- return url.pathname;
82
- }
83
-
84
- return url.domainInfo.domainWithoutSuffix || url.generalDomain;
85
- }
@@ -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
+ 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
+ }
@@ -21,27 +21,22 @@ import './search-extractor.spec.js';
21
21
  import './session-storage.spec.js';
22
22
  import './seq-executor.spec.js';
23
23
  import './url-cleaner.spec.js';
24
- import './utils.spec.js';
25
24
 
26
25
  // Request utils
27
26
  import './request/utils/tldts.spec.js';
28
27
  import './request/utils/bloom-filter-packed.spec.js';
29
28
  import './request/utils/chrome-storage-map.spec.js';
29
+ import './request/utils/utils.spec.js';
30
30
 
31
31
  // Request steps
32
32
  import './request/steps/check-context.spec.js';
33
33
  import './request/steps/oauth-detector.spec.js';
34
34
 
35
35
  // Request
36
- import './request/utils.spec.js';
37
36
  import './request/qs-whitelist2.spec.js';
38
- import './request/hash.spec.js';
37
+ import './request/hash/index.spec.js';
39
38
  import './request/database.spec.js';
40
39
  import './request/index.spec.js';
41
40
 
42
- // // Utils
43
- import './utils/pacemaker.spec.js';
41
+ // Utils
44
42
  import './utils/url.spec.js';
45
-
46
- // // Webrequest-pipeline
47
- import './webrequest-pipeline/pipeline.spec.js';