@whotracksme/reporting 6.3.2 → 7.1.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.
@@ -299,6 +299,8 @@ class ActiveTab {
299
299
  /**
300
300
  * Responsible for aggregating information about open pages.
301
301
  *
302
+ * 1) Aggregation
303
+ *
302
304
  * It works by aggregating information from available extension APIs.
303
305
  * The implementation needs to be fault-tolerant to recover from inconsistent
304
306
  * states, loss of the state (if the service worker gets killed), lack of APIs
@@ -306,9 +308,23 @@ class ActiveTab {
306
308
  *
307
309
  * For error recovery, it may sacrifice precision by deleting information
308
310
  * that is most likely outdated or even wrong. The overall goal of this class
309
- * is to provide information that are reliable and match or exceed what the
311
+ * is to provide information that is reliable and matches or exceeds what the
310
312
  * chrome.tabs.query IP would get.
311
- * not called and events have been skipped.
313
+ *
314
+ * 2) Observerable "page" events
315
+ *
316
+ * In addition to providing access to the current state, the class will emit
317
+ * events that are domain-specific and higher-level than the browser APIs.
318
+ * "addObserver" can used by other classed to register a (synchronous)
319
+ * event handler.
320
+ *
321
+ * Note: These events are not intended to provide complete coverage (e.g.
322
+ * actions in incognito tabs will be omitted). If you need complete information,
323
+ * it is recommended to consume the browser APIs directly.
324
+ *
325
+ * ----------------------------------------------------------------------
326
+ *
327
+ * Cross-browser support:
312
328
  *
313
329
  * List of Safari quirks:
314
330
  * https://developer.apple.com/documentation/safariservices/safari_web_extensions/assessing_your_safari_web_extension_s_browser_compatibility
@@ -365,6 +381,9 @@ export default class Pages {
365
381
  this.isPageLoadMethodReliable =
366
382
  this.chrome.webNavigation?.onHistoryStateUpdated?.addListener &&
367
383
  this.chrome.webNavigation?.onHistoryStateUpdated?.removeListener;
384
+
385
+ // should be generally safe to keep always enabled (even on other platforms)
386
+ this.enableFirefoxAndroidQuirks = true;
368
387
  }
369
388
 
370
389
  addObserver(onPageEventCallback) {
@@ -845,6 +864,7 @@ export default class Pages {
845
864
  // listeners for chrome.webRequest API:
846
865
  if (this.chrome.webRequest) {
847
866
  for (const type of [
867
+ 'onBeforeRequest', // note: unavailable on Safari
848
868
  'onBeforeRedirect', // note: unavailable on Safari
849
869
  'onResponseStarted', // note: unavailable on Safari
850
870
  'onCompleted', // note: unavailable on Safari
@@ -922,29 +942,63 @@ export default class Pages {
922
942
  };
923
943
  }
924
944
 
945
+ // Firefox quirks:
946
+ // * "pendingUrl" is not supported (https://bugzilla.mozilla.org/show_bug.cgi?id=1620774)
947
+ // * "openerTabId" is not available on Firefox for Android
925
948
  chrome_tabs_onCreated(tab) {
926
949
  if (tab.incognito) {
927
950
  this.openTabs.delete(tab.id);
928
951
  return;
929
952
  }
930
953
 
931
- if (
932
- tab.openerTabId === undefined ||
933
- (tab.pendingUrl && !isRealPage(tab.pendingUrl))
934
- ) {
954
+ if (tab.openerTabId !== undefined) {
955
+ if (tab.pendingUrl && !isRealPage(tab.pendingUrl)) {
956
+ // skip if it is clear that the destination is an internal page
957
+ return;
958
+ }
959
+
960
+ const openedFrom = this.openTabs.get(tab.openerTabId);
961
+ if (openedFrom) {
962
+ const oldEntry = this.openTabs.get(tab.id);
963
+ const entry = {
964
+ status: 'created',
965
+ ...oldEntry,
966
+ windowId: tab.windowId,
967
+ lastUpdatedAt: Date.now(),
968
+ pageId: ++this._pageIdGenerator,
969
+ openedFrom: { ...openedFrom },
970
+ };
971
+ this.openTabs.set(tab.id, entry);
972
+ }
935
973
  return;
936
974
  }
937
975
 
938
- const openerTab = this.openTabs.get(tab.openerTabId);
939
- if (openerTab) {
940
- const oldEntry = this.openTabs.get(tab.id);
976
+ // On Firefox Android, it is more difficult, because the "openerTabId"
977
+ // is not implemented. But we can speculate and verify later (e.g. with
978
+ // webRequest.onBeforeRequest).
979
+ if (
980
+ this.enableFirefoxAndroidQuirks &&
981
+ tab.active === false &&
982
+ this.activeTab.tabId !== TAB_ID_NONE &&
983
+ tab.url === 'about:blank' &&
984
+ !this.openTabs.has(tab.id)
985
+ ) {
986
+ const activeTab = this.openTabs.get(this.activeTab.tabId);
987
+ if (!activeTab || !isRealPage(activeTab.url)) {
988
+ return;
989
+ }
990
+
991
+ const now = Date.now();
941
992
  const entry = {
942
993
  status: 'created',
943
- ...oldEntry,
944
994
  windowId: tab.windowId,
945
- lastUpdatedAt: Date.now(),
995
+ lastUpdatedAt: now,
946
996
  pageId: ++this._pageIdGenerator,
947
- openerTab: { ...openerTab },
997
+ _unverifiedOpener__FirefoxAndroid__: {
998
+ openedFrom: { ...activeTab },
999
+ lastUpdatedAt: now,
1000
+ expectedOriginUrl: activeTab.url,
1001
+ },
948
1002
  };
949
1003
  this.openTabs.set(tab.id, entry);
950
1004
  }
@@ -981,6 +1035,24 @@ export default class Pages {
981
1035
 
982
1036
  this._initAllOptionalFields(tabId, entry, now);
983
1037
  this.openTabs.set(tabId, entry);
1038
+
1039
+ if (entry.search?.depth === 1) {
1040
+ const { url, search, redirects = [] } = entry;
1041
+ this.notifyObservers({
1042
+ type: 'safe-search-landing',
1043
+ tabId,
1044
+ details: {
1045
+ from: {
1046
+ category: search.category,
1047
+ query: search.query,
1048
+ },
1049
+ to: {
1050
+ targetUrl: url,
1051
+ },
1052
+ redirects,
1053
+ },
1054
+ });
1055
+ }
984
1056
  return;
985
1057
  }
986
1058
 
@@ -1024,8 +1096,8 @@ export default class Pages {
1024
1096
  if (oldTabEntry) {
1025
1097
  if (oldTabEntry.status !== 'created') {
1026
1098
  entry.openedFrom = { ...oldTabEntry };
1027
- } else if (oldTabEntry.openerTab) {
1028
- entry.openedFrom = { ...oldTabEntry.openerTab };
1099
+ } else if (oldTabEntry.openedFrom) {
1100
+ entry.openedFrom = { ...oldTabEntry.openedFrom };
1029
1101
  }
1030
1102
 
1031
1103
  const redirects = entry.openedFrom?.pendingRedirects || [];
@@ -1044,12 +1116,9 @@ export default class Pages {
1044
1116
  // If a link opened in a new tab, we need to merge the opener.
1045
1117
  if (
1046
1118
  entry.openedFrom?.status === 'redirecting' &&
1047
- entry.openedFrom.openerTab
1119
+ entry.openedFrom.openedFrom
1048
1120
  ) {
1049
- entry.openedFrom = {
1050
- ...entry.openedFrom.openerTab,
1051
- ...entry.openedFrom,
1052
- };
1121
+ entry.openedFrom = { ...entry.openedFrom.openedFrom };
1053
1122
  }
1054
1123
 
1055
1124
  const previousUrl = entry.openedFrom?.url;
@@ -1076,7 +1145,6 @@ export default class Pages {
1076
1145
  };
1077
1146
  }
1078
1147
  }
1079
-
1080
1148
  this.openTabs.set(tabId, entry);
1081
1149
  return;
1082
1150
  }
@@ -1090,7 +1158,7 @@ export default class Pages {
1090
1158
  let updated = false;
1091
1159
  if (tab.title && tab.title !== entry.title) {
1092
1160
  entry.title = tab.title;
1093
- entry.pageId = ++this._pageIdGenerator; // TODO: is this too conservative?
1161
+ entry.pageId = ++this._pageIdGenerator;
1094
1162
  updated = true;
1095
1163
  }
1096
1164
  if (tab.url && tab.url !== entry.url) {
@@ -1135,6 +1203,36 @@ export default class Pages {
1135
1203
  }
1136
1204
  }
1137
1205
 
1206
+ // Safari quirks:
1207
+ // * This API is not available on iOS
1208
+ chrome_webRequest_onBeforeRequest(details) {
1209
+ const { incognito, type, tabId, originUrl } = details;
1210
+ if (incognito || tabId === -1 || type !== 'main_frame') {
1211
+ return;
1212
+ }
1213
+
1214
+ if (this.enableFirefoxAndroidQuirks) {
1215
+ const oldEntry = this.openTabs.get(tabId);
1216
+ if (oldEntry?._unverifiedOpener__FirefoxAndroid__) {
1217
+ let { _unverifiedOpener__FirefoxAndroid__: candidate, ...entry } =
1218
+ oldEntry;
1219
+ entry.lastUpdatedAt = Date.now();
1220
+ if (
1221
+ !entry.openedFrom &&
1222
+ entry.status === 'created' &&
1223
+ this.activeTab.tabId !== tabId &&
1224
+ originUrl === candidate.expectedOriginUrl
1225
+ ) {
1226
+ entry.openedFrom = { ...candidate.openedFrom };
1227
+ logger.debug('confirmed openedFrom:', oldEntry, '->', entry);
1228
+ } else {
1229
+ logger.debug('rejected openedFrom:', oldEntry, '->', entry);
1230
+ }
1231
+ this.openTabs.set(tabId, entry);
1232
+ }
1233
+ }
1234
+ }
1235
+
1138
1236
  // Safari quirks:
1139
1237
  // * This API is not available
1140
1238
  chrome_webRequest_onBeforeRedirect(details) {
@@ -1153,11 +1251,17 @@ export default class Pages {
1153
1251
  const { tabId, statusCode, url: from, redirectUrl: to } = details;
1154
1252
  logger.debug('Detected redirect:', from, '->', to, 'with tabId', tabId);
1155
1253
 
1254
+ const oldEntry = this.openTabs.get(tabId);
1156
1255
  const entry = {
1157
- ...this.openTabs.get(tabId),
1256
+ ...oldEntry,
1158
1257
  status: 'redirecting',
1159
1258
  lastUpdatedAt: Date.now(),
1160
1259
  };
1260
+
1261
+ if (oldEntry && oldEntry.status === 'created' && oldEntry.openedFrom) {
1262
+ entry.openedFrom = { ...oldEntry.openedFrom };
1263
+ }
1264
+
1161
1265
  const thisRedirect = {
1162
1266
  from,
1163
1267
  to,
@@ -1241,8 +1345,8 @@ export default class Pages {
1241
1345
  return;
1242
1346
  }
1243
1347
  const { tabId, sourceTabId, windowId } = details;
1244
- const openerTab = this.openTabs.get(sourceTabId);
1245
- if (!openerTab) {
1348
+ const openedFrom = this.openTabs.get(sourceTabId);
1349
+ if (!openedFrom) {
1246
1350
  return;
1247
1351
  }
1248
1352
 
@@ -1253,7 +1357,7 @@ export default class Pages {
1253
1357
  pageId: ++this._pageIdGenerator,
1254
1358
  windowId,
1255
1359
  lastUpdatedAt: Date.now(),
1256
- openerTab: { ...openerTab },
1360
+ openedFrom: { ...openedFrom },
1257
1361
  };
1258
1362
  this.openTabs.set(tabId, entry);
1259
1363
  }
@@ -1282,8 +1386,28 @@ export default class Pages {
1282
1386
  // Safari quirks:
1283
1387
  // * The API exists, but "transitionType" is not supported
1284
1388
  chrome_webNavigation_onCommitted(details) {
1285
- if (details.frameId !== 0) return; // not top-level frame (of the active page)
1389
+ const { tabId, frameId, url } = details;
1390
+ if (frameId !== 0) return; // not top-level frame (of the active page)
1391
+
1392
+ let entry = this.openTabs.get(tabId);
1393
+ if (!entry) {
1394
+ logger.debug('Skipping navigation to', url, 'in private tab with', tabId);
1395
+ return;
1396
+ }
1286
1397
 
1398
+ const now = Date.now();
1399
+ entry = {
1400
+ ...entry,
1401
+ lastUpdated: now,
1402
+
1403
+ // Some pages trigger a history navigation with the identical URL
1404
+ // immediately after loading. Remember the context here to be
1405
+ // able to skip it later.
1406
+ _previous_webNavigation_onCommitted: {
1407
+ url,
1408
+ lastUpdated: now,
1409
+ },
1410
+ };
1287
1411
  const isBackOrForward =
1288
1412
  details.transitionQualifiers?.includes('forward_back');
1289
1413
 
@@ -1298,16 +1422,15 @@ export default class Pages {
1298
1422
  // See also https://stackoverflow.com/q/25542015/783510
1299
1423
  forgetOpenedFrom = true;
1300
1424
  }
1301
- if (forgetOpenedFrom) {
1302
- const { tabId } = details;
1303
- const oldEntry = this.openTabs.get(tabId);
1304
- if (oldEntry?.previousUrl || oldEntry?.openedFrom) {
1305
- // this creates a copy, but omits the fields related to "opened from"
1306
- // eslint-disable-next-line no-unused-vars
1307
- const { previousUrl, openedFrom, search, ...entry } = { ...oldEntry };
1308
- this.openTabs.set(tabId, entry);
1309
- }
1425
+ if (forgetOpenedFrom && (entry.previousUrl || entry.openedFrom)) {
1426
+ // this creates a copy, but omits the fields related to "opened from"
1427
+ // eslint-disable-next-line no-unused-vars
1428
+ const { previousUrl, openedFrom, search, ...newEntry } = { ...entry };
1429
+ entry = newEntry;
1310
1430
  }
1431
+
1432
+ this.openTabs.set(tabId, entry);
1433
+ this._onWebNavigation(tabId, url, entry, { isHistoryNavigation: false });
1311
1434
  }
1312
1435
 
1313
1436
  // Safari quirks:
@@ -1317,15 +1440,21 @@ export default class Pages {
1317
1440
  // * 'server_redirect' is limited to top-level frames
1318
1441
  // * 'client_redirect' is not supplied when redirections are created by JavaScript.
1319
1442
  chrome_webNavigation_onHistoryStateUpdated(details) {
1320
- const { tabId, frameId, parentFrameId } = details;
1443
+ const { tabId, frameId, parentFrameId, url } = details;
1321
1444
  if (frameId !== 0) return; // not top-level frame (of the active page)
1322
1445
  if (parentFrameId !== -1) return; // not main frame
1323
1446
 
1324
- const entry = this.openTabs.get(tabId);
1325
- if (!entry) {
1326
- logger.warn('Navigation event in a non-existing tab detected!');
1447
+ const oldEntry = this.openTabs.get(tabId);
1448
+ if (!oldEntry) {
1449
+ logger.debug(
1450
+ 'Skipping history navigation to',
1451
+ url,
1452
+ 'in private tab with',
1453
+ tabId,
1454
+ );
1327
1455
  return;
1328
1456
  }
1457
+ const { _previous_webNavigation_onCommitted, ...entry } = oldEntry;
1329
1458
  this.openTabs.set(tabId, {
1330
1459
  ...entry,
1331
1460
  pageLoadMethod: 'history-navigation',
@@ -1333,6 +1462,65 @@ export default class Pages {
1333
1462
  lastUpdatedAt: Date.now(),
1334
1463
  pageId: ++this._pageIdGenerator,
1335
1464
  });
1465
+
1466
+ if (_previous_webNavigation_onCommitted?.url === url) {
1467
+ logger.debug(
1468
+ 'Skipping page event for redundant history navigation to',
1469
+ url,
1470
+ 'in tab',
1471
+ tabId,
1472
+ );
1473
+ } else {
1474
+ this._onWebNavigation(tabId, url, entry, { isHistoryNavigation: true });
1475
+ }
1476
+ }
1477
+
1478
+ _onWebNavigation(tabId, url, entry, { isHistoryNavigation }) {
1479
+ // Note: on Firefox, this will also skip navigations to "about:blank"
1480
+ if (!isRealPage(url)) {
1481
+ return;
1482
+ }
1483
+
1484
+ // check for inconsistencies (this would indicate a bug caused by
1485
+ // wrong assumptions about the ordering of browser API events)
1486
+ if (url !== entry.url) {
1487
+ logger.warn(
1488
+ 'webNavigation reports a navigation in tab',
1489
+ tabId,
1490
+ 'to',
1491
+ url,
1492
+ 'This is inconsistent with the openTabs URL:',
1493
+ entry.url,
1494
+ );
1495
+ return;
1496
+ }
1497
+
1498
+ // immediately skip navigations to URLs that should never be shared
1499
+ if (this.dnsResolver.isPrivateURL(url)) {
1500
+ logger.debug('Skipping navigation to private URL:', url);
1501
+ return;
1502
+ }
1503
+
1504
+ logger.debug('Detected safe page navigation to URL:', url, 'in tab', tabId);
1505
+ const pageEvent = {
1506
+ type: 'safe-page-navigation',
1507
+ url,
1508
+ isHistoryNavigation,
1509
+ tabId,
1510
+ };
1511
+ if (entry.redirects) {
1512
+ pageEvent.redirects = entry.redirects.map(({ from, to, statusCode }) => ({
1513
+ from: this.dnsResolver.isPrivateURL(from) ? null : from,
1514
+ to: this.dnsResolver.isPrivateURL(to) ? null : to,
1515
+ statusCode,
1516
+ }));
1517
+ }
1518
+ if (entry.previousUrl) {
1519
+ pageEvent.previousUrl = this.dnsResolver.isPrivateURL(entry.previousUrl)
1520
+ ? null
1521
+ : entry.previousUrl;
1522
+ }
1523
+ this.notifyObservers(pageEvent);
1336
1524
  }
1337
1525
 
1338
1526
  chrome_windows_onRemoved(windowId) {
@@ -1865,6 +2053,7 @@ export default class Pages {
1865
2053
  }
1866
2054
  }
1867
2055
 
2056
+ // exported for tests
1868
2057
  export const eventListenerQueue = new EventListenerQueue({
1869
2058
  connectTimeoutInMs: 1000,
1870
2059
  maxBufferLength: 1024,
@@ -18,6 +18,7 @@ import Pages from './pages';
18
18
  import PageAggregator from './page-aggregator';
19
19
  import PageDB from './pagedb';
20
20
  import NewPageApprover from './new-page-approver';
21
+ import NavTrackingDetector from './nav-tracking-detector';
21
22
  import MessageSender from './message-sender';
22
23
  import DuplicateDetector from './duplicate-detector';
23
24
  import DoublefetchPageHandler from './doublefetch-page-handler';
@@ -106,6 +107,7 @@ export default class Reporting {
106
107
  this.pages.addObserver(
107
108
  this.pageAggregator.onPageEvent.bind(this.pageAggregator),
108
109
  );
110
+ this.pages.addObserver(this._onPageEvent.bind(this));
109
111
 
110
112
  this.doublefetchPageHandler = new DoublefetchPageHandler({
111
113
  jobScheduler: this.jobScheduler,
@@ -125,6 +127,16 @@ export default class Reporting {
125
127
  countryProvider: this.countryProvider,
126
128
  });
127
129
 
130
+ this.navTrackingDetector = new NavTrackingDetector({
131
+ sanitizer: this.sanitizer,
132
+ persistedHashes: this.persistedHashes,
133
+ quorumChecker: this.quorumChecker,
134
+ jobScheduler: this.jobScheduler,
135
+ });
136
+ this.pages.addObserver(
137
+ this.navTrackingDetector.onPageEvent.bind(this.navTrackingDetector),
138
+ );
139
+
128
140
  this.duplicateDetector = new DuplicateDetector(this.persistedHashes);
129
141
  this.messageSender = new MessageSender({
130
142
  duplicateDetector: this.duplicateDetector,
@@ -195,6 +207,7 @@ export default class Reporting {
195
207
  await Promise.all([
196
208
  this.pages.init(),
197
209
  this.pageAggregator.init(),
210
+ this.navTrackingDetector.init(),
198
211
  this.duplicateDetector.init(),
199
212
  this.patternsUpdater.init(),
200
213
  this.countryProvider.init(),
@@ -211,6 +224,7 @@ export default class Reporting {
211
224
  try {
212
225
  this.duplicateDetector.unload();
213
226
  this.pages.unload();
227
+ this.navTrackingDetector.unload();
214
228
  this.pageAggregator.unload();
215
229
  this.jobScheduler.unload();
216
230
 
@@ -224,40 +238,41 @@ export default class Reporting {
224
238
  }
225
239
  }
226
240
 
227
- /**
228
- * Should be called when the user navigates to a new page.
229
- *
230
- * Calling this function alone should not have a noticable
231
- * performance impact (both in terms of CPU or network).
232
- *
233
- * @return true iff new jobs were registered
234
- */
235
- async analyzeUrl(url) {
241
+ _onPageEvent(event) {
236
242
  if (!this.isActive) {
237
- return false;
243
+ return;
238
244
  }
239
- this.aliveCheck.ping();
240
- await this._ensurePatternsAreUpToDate();
241
245
 
246
+ if (event.type === 'safe-page-navigation') {
247
+ logger.debug('Navigation in non-private tab detected:', event.url);
248
+ this.aliveCheck.ping();
249
+ this._onSafePageNavigation(event.url).catch((e) => {
250
+ logger.error('Failed to handle event', event, e);
251
+ });
252
+ }
253
+ }
254
+
255
+ async _onSafePageNavigation(url) {
256
+ await this._ensurePatternsAreUpToDate();
257
+ if (!this.isActive) {
258
+ return;
259
+ }
242
260
  const { isSupported, category, query, doublefetchRequest } =
243
261
  this.urlAnalyzer.parseSearchLinks(url);
244
- if (!isSupported) {
245
- return false;
262
+ if (isSupported) {
263
+ logger.debug('Potential report found on URL:', url);
264
+ await this.jobScheduler.registerJob({
265
+ type: 'doublefetch-query',
266
+ args: {
267
+ query,
268
+ category,
269
+ doublefetchRequest,
270
+ },
271
+ config: {
272
+ readyIn: { min: 2 * SECOND, max: 8 * SECOND },
273
+ },
274
+ });
246
275
  }
247
-
248
- logger.debug('Potential report found on URL:', url);
249
- await this.jobScheduler.registerJob({
250
- type: 'doublefetch-query',
251
- args: {
252
- query,
253
- category,
254
- doublefetchRequest,
255
- },
256
- config: {
257
- readyIn: { min: 2 * SECOND, max: 8 * SECOND },
258
- },
259
- });
260
- return true;
261
276
  }
262
277
 
263
278
  async processPendingJobs() {
@@ -15,6 +15,7 @@ import logger from './logger';
15
15
  import parseHtml from './html-parser';
16
16
  import { fastHash } from './utils';
17
17
  import random from './random';
18
+ import { timezoneAgnosticDailyExpireAt } from './cooldowns';
18
19
  import { anonymousHttpGet } from './http';
19
20
  import { lookupBuiltinTransform } from './patterns';
20
21
  import { BadPatternError } from './errors';
@@ -25,30 +26,6 @@ function doublefetchQueryHash(query, category) {
25
26
  return fastHash(`dfq:${category}:${query.trim()}`, { truncate: true });
26
27
  }
27
28
 
28
- const HOUR = 60 * 60 * 1000;
29
-
30
- /**
31
- * Minimum delay before repeating doublefetch attempts
32
- * for queries (only counting successful attempts).
33
- * Waiting for next start of day (in UTC time) is recommended,
34
- * as trying to send messages earlier is a waste of resources.
35
- *
36
- * In addition, enforce a minimum cooldown, intended for people
37
- * living in timezones like US west coast where UTC midnight
38
- * happens during the day. Without a minimum cooldown, there is
39
- * the risk of introducing bias in the collected data, as we
40
- * would include repeated searches with higher likelihood than
41
- * in other parts of the world (e.g. Europe).
42
- */
43
- function chooseExpiration() {
44
- const minCooldown = 8 * HOUR;
45
- const tillNextUtcDay = new Date().setUTCHours(23, 59, 59, 999) + 1;
46
- const tillCooldown = Date.now() + minCooldown;
47
- const randomNoise = Math.ceil(random() * 2 * HOUR);
48
-
49
- return Math.max(tillCooldown, tillNextUtcDay) + randomNoise;
50
- }
51
-
52
29
  function runSelector(item, selector, attr, baseURI) {
53
30
  const elem = selector ? item.querySelector(selector) : item;
54
31
  if (elem) {
@@ -149,7 +126,8 @@ export default class SearchExtractor {
149
126
  }
150
127
 
151
128
  const queryHash = doublefetchQueryHash(query, category);
152
- const expireAt = chooseExpiration();
129
+ const expireAt = timezoneAgnosticDailyExpireAt();
130
+
153
131
  const wasAdded = await this.persistedHashes.add(queryHash, expireAt);
154
132
  if (!wasAdded) {
155
133
  return discard('Query has been recently seen.');
@@ -341,6 +319,18 @@ export default class SearchExtractor {
341
319
  messages.push({ body, deduplicateBy });
342
320
  }
343
321
  logger.debug('Found the following messages:', messages);
344
- return messages;
322
+
323
+ const filteredMessages = messages.filter((msg) => {
324
+ const { omitIfExistsAny = [] } = output[msg.body.action];
325
+ const isRedundant = omitIfExistsAny.some((action) =>
326
+ messages.some((x) => x.body.action === action),
327
+ );
328
+ return !isRedundant;
329
+ });
330
+ if (messages.length !== filteredMessages.length) {
331
+ logger.debug('Remaining messages after filtering:', filteredMessages);
332
+ }
333
+
334
+ return filteredMessages;
345
335
  }
346
336
  }
@@ -77,7 +77,7 @@ export function requireArrayOfStrings(value, name) {
77
77
  throw new Error(
78
78
  name
79
79
  ? `${name} should be an array of strings, but got: ${value}`
80
- : `Paramter should be an array of strings, but got: ${value}`,
80
+ : `Parameter should be an array of strings, but got: ${value}`,
81
81
  );
82
82
  }
83
83
  value.forEach((x, idx) => {
@@ -0,0 +1,80 @@
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 JobScheduler from '../../src/job-scheduler.js';
15
+
16
+ export function createInMemoryJobScheduler() {
17
+ const storageKey = 'some-key';
18
+ const storage = {
19
+ async get(key) {
20
+ expect(key).to.equal(storageKey);
21
+ return this._content;
22
+ },
23
+ async set(key, obj) {
24
+ expect(key).to.equal(storageKey);
25
+ this._content = obj;
26
+ },
27
+ };
28
+ return new JobScheduler({ storage, storageKey });
29
+ }
30
+
31
+ export async function runClockUntilJobQueueIsEmpty(
32
+ jobScheduler,
33
+ clock,
34
+ { maxIterations = 1000, fallbackHandler = async () => {} } = {},
35
+ ) {
36
+ async function advanceTo(ts) {
37
+ const diff = ts - Date.now();
38
+ if (diff > 0) {
39
+ await clock.tickAsync(diff);
40
+ }
41
+ }
42
+
43
+ function expireCooldowns() {
44
+ return advanceTo(Math.max(0, ...Object.values(jobScheduler.cooldowns)));
45
+ }
46
+
47
+ async function waitForNextJob() {
48
+ const { queues, handlers } = jobScheduler._describeJobs();
49
+
50
+ // to ensure progress, we need to install handlers for each message type
51
+ for (const type of Object.keys(queues.byType)) {
52
+ if (!handlers.includes(type)) {
53
+ jobScheduler.registerHandler(type, fallbackHandler);
54
+ }
55
+ }
56
+
57
+ const { ready, running, waiting } = queues.byState;
58
+ if (ready.length === 0 && running.length === 0 && waiting.length > 0) {
59
+ const nextEventAt = Math.min(
60
+ ...waiting.flatMap(({ _meta: { expireAt, readyAt } }) => [
61
+ expireAt,
62
+ readyAt,
63
+ ]),
64
+ );
65
+ await advanceTo(nextEventAt);
66
+ }
67
+ }
68
+
69
+ let iter = 0;
70
+ while (jobScheduler.getTotalJobs() > jobScheduler.getTotalJobsInDlq()) {
71
+ iter += 1;
72
+ if (iter > maxIterations) {
73
+ throw new Error(`Exceeded maximum steps (steps=${maxIterations})`);
74
+ }
75
+ await expireCooldowns();
76
+ await waitForNextJob();
77
+ await jobScheduler.processPendingJobs();
78
+ await clock.runAllAsync();
79
+ }
80
+ }