@whotracksme/reporting 6.3.2 → 7.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.
package/CHANGELOG.md CHANGED
@@ -1,3 +1,15 @@
1
+ # v7.0.0 (Mon May 19 2025)
2
+
3
+ #### 💥 Breaking Change
4
+
5
+ - Navigational tracking detection [#148](https://github.com/whotracksme/webextension-packages/pull/148) ([@philipp-classen](https://github.com/philipp-classen))
6
+
7
+ #### Authors: 1
8
+
9
+ - Philipp Claßen ([@philipp-classen](https://github.com/philipp-classen))
10
+
11
+ ---
12
+
1
13
  # v6.3.2 (Tue May 06 2025)
2
14
 
3
15
  #### 🐛 Bug Fix
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "6.3.2",
3
+ "version": "7.0.0",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
@@ -10,7 +10,6 @@
10
10
  */
11
11
  import './setup.js';
12
12
  import { UrlReporter, RequestReporter, setLogLevel } from '../src/index.js';
13
- import rules from './rules.json';
14
13
 
15
14
  (chrome.action || chrome.browserAction).onClicked.addListener(() => {
16
15
  chrome.tabs.create({
@@ -53,7 +52,7 @@ const communication = {
53
52
  msg,
54
53
  );
55
54
  },
56
- // TODO: use actuall anonymous-communication to access quorum
55
+ // TODO: use actual anonymous-communication to access quorum
57
56
  sendInstant(msg) {
58
57
  console.warn('[Communication instant]', msg);
59
58
  return Promise.resolve({
@@ -74,7 +73,7 @@ const communication = {
74
73
  const config = {
75
74
  url: {
76
75
  ALLOWED_COUNTRY_CODES: ['de'],
77
- PATTERNS_URL: '',
76
+ PATTERNS_URL: 'https://cdn2.ghostery.com/wtm-chrome-desktop/patterns.json',
78
77
  CONFIG_URL: 'https://api.ghostery.net/api/v1/config',
79
78
  },
80
79
  request: {
@@ -132,13 +131,8 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
132
131
  }
133
132
  });
134
133
 
135
- (async function () {
136
- await urlReporter.init();
137
- await urlReporter.patterns.updatePatterns(rules);
138
- await urlReporter.analyzeUrl('https://www.google.com/search?q=shoes');
139
- await urlReporter.processPendingJobs();
140
- await requestReporter.init();
141
- })();
134
+ urlReporter.init().catch(console.error);
135
+ requestReporter.init().catch(console.error);
142
136
 
143
137
  globalThis.urlReporter = urlReporter;
144
138
  globalThis.requestReporter = requestReporter;
@@ -0,0 +1,38 @@
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 random from './random';
13
+
14
+ const HOUR = 60 * 60 * 1000;
15
+
16
+ /**
17
+ * Minimum delay before repeating an action that should not
18
+ * be repeat untiled the next day (e.g. for doublefetch attempts
19
+ * for queries). Waiting for next start of day (in UTC time) is
20
+ * recommended, as trying to send messages earlier is a waste of
21
+ * resources. Not that only successful attempts should be counted,
22
+ * and failed ones should be rolled back.
23
+ *
24
+ * In addition, enforce a minimum cooldown, intended for people
25
+ * living in timezones like US west coast where UTC midnight
26
+ * happens during the day. Without a minimum cooldown, there is
27
+ * the risk of introducing bias in the collected data, as we
28
+ * would include repeated searches with higher likelihood than
29
+ * in other parts of the world (e.g. Europe).
30
+ */
31
+ export function timezoneAgnosticDailyExpireAt() {
32
+ const minCooldown = 8 * HOUR;
33
+ const tillNextUtcDay = new Date().setUTCHours(23, 59, 59, 999) + 1;
34
+ const tillCooldown = Date.now() + minCooldown;
35
+ const randomNoise = Math.ceil(random() * 2 * HOUR);
36
+
37
+ return Math.max(tillCooldown, tillNextUtcDay) + randomNoise;
38
+ }
@@ -444,7 +444,7 @@ export default class JobScheduler {
444
444
  } else {
445
445
  logger.error('Job failed (unexpected error):', jobEntry.job, e);
446
446
  }
447
- this.notifyObservers('jobFailed', jobEntry);
447
+ this.notifyObservers('jobFailed', jobEntry, e);
448
448
  } finally {
449
449
  now = Date.now();
450
450
  this._removeFromRunningQueue(jobEntry, now);
@@ -783,6 +783,16 @@ export default class JobScheduler {
783
783
  return count;
784
784
  }
785
785
 
786
+ getTotalJobsInDlq() {
787
+ let count = 0;
788
+ for (const queue of Object.values(this.jobQueues)) {
789
+ if (queue.dlq) {
790
+ count += queue.dlq.length;
791
+ }
792
+ }
793
+ return count;
794
+ }
795
+
786
796
  _precomputed() {
787
797
  if (!this._cachedPrecomputed) {
788
798
  // Group the different types into set with the same priority and sort
@@ -0,0 +1,261 @@
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 logger from './logger';
13
+ import { requireParam, requireString, requireObject, fastHash } from './utils';
14
+ import random from './random';
15
+ import { timezoneAgnosticDailyExpireAt } from './cooldowns';
16
+
17
+ const SECOND = 1000;
18
+
19
+ function tryParseHostname(url) {
20
+ try {
21
+ return new URL(url).host;
22
+ } catch (e) {
23
+ return null;
24
+ }
25
+ }
26
+
27
+ function hasQueryParams(url, params) {
28
+ try {
29
+ const { searchParams } = new URL(url);
30
+ return params.every((key) => searchParams.has(key));
31
+ } catch (e) {
32
+ return false;
33
+ }
34
+ }
35
+
36
+ const searchAdRedirectByCategory = {
37
+ go: (url) =>
38
+ url.startsWith('https://www.googleadservices.com/') ||
39
+ url.startsWith('https://www.google.com/aclk?'),
40
+ bi: (url) => url.startsWith('https://www.bing.com/aclk?'),
41
+ dd: (url) =>
42
+ url.startsWith('https://www.bing.com/aclick?') ||
43
+ (url.startsWith('https://duckduckgo.com/y.js?') &&
44
+ hasQueryParams(url, ['ad_domain', 'ad_provider', 'ad_type'])),
45
+ gh: (url) => url.startsWith('https://tatrck.com/h/'),
46
+ br: (url) =>
47
+ url.startsWith('https://search.brave.com/a/redirect?') &&
48
+ hasQueryParams(url, ['click_url', 'placement_id']),
49
+ ec: (url) =>
50
+ url.startsWith('https://syndicatedsearch.goog/aclk?') ||
51
+ url.startsWith('https://ad.doubleclick.net/searchads/link/click?'),
52
+ };
53
+
54
+ // exported only for tests
55
+ export function isAdUrlByCategory(url, category) {
56
+ requireString(url);
57
+ requireString(category);
58
+
59
+ const check = searchAdRedirectByCategory[category];
60
+ return !!(check && check(url));
61
+ }
62
+
63
+ function isTracking(url) {
64
+ requireString(url);
65
+
66
+ // Note: For bootstrapping, start with the tracking ads. We could integrate
67
+ // with the adblocker engine or TrackerDB eventually here to improve coverage.
68
+ return Object.values(searchAdRedirectByCategory).some((check) => check(url));
69
+ }
70
+
71
+ function isSearchAdRedirect(category, redirects) {
72
+ const trackingUrls = redirects.map((x) => x.from).filter(isTracking);
73
+ const isAd =
74
+ (redirects.length > 0 && isAdUrlByCategory(redirects[0].from, category)) ||
75
+ (trackingUrls.length > 0 && isAdUrlByCategory(trackingUrls[0], category));
76
+ return { isAd, trackingUrls };
77
+ }
78
+
79
+ function toSendMessageJob(action, payload, deduplicateBy) {
80
+ const body = {
81
+ action,
82
+ payload,
83
+ ver: 3, // Note: no need to keep this number in sync among messages
84
+ 'anti-duplicates': Math.floor(random() * 10000000),
85
+ };
86
+ return { type: 'send-message', args: { body, deduplicateBy } };
87
+ }
88
+
89
+ /**
90
+ * Responsible for detecting navigational tracking
91
+ * (https://privacycg.github.io/nav-tracking-mitigations/#navigational-tracking).
92
+ *
93
+ * It observes events emitted by the "Page", so some events will
94
+ * have been filtered already (e.g. "incognito" tabs are filtered out).
95
+ */
96
+ export default class NavTrackingDetector {
97
+ constructor({ sanitizer, persistedHashes, quorumChecker, jobScheduler }) {
98
+ this.active = false;
99
+ this.sanitizer = requireParam(sanitizer);
100
+ this.persistedHashes = requireParam(persistedHashes);
101
+ this.quorumChecker = requireParam(quorumChecker);
102
+ this.jobScheduler = requireParam(jobScheduler);
103
+
104
+ this.jobScheduler.registerHandler(
105
+ 'nav-track-detect:quorum-isAdCheck',
106
+ async (job) => {
107
+ const { action, payload, deduplicateBy, quorumCheck } = job.args;
108
+ requireString(action);
109
+ requireObject(payload);
110
+ requireString(quorumCheck);
111
+
112
+ // Rate limit the quorum check to once per day.
113
+ //
114
+ // Note: there is another, independent check based on "deduplicateBy"
115
+ // before sending the message. This check here only protects
116
+ // rate-limits the quorum check.)
117
+ const expireAt = timezoneAgnosticDailyExpireAt();
118
+ const dedupHash = fastHash(`nav-track:quorum:${quorumCheck}`, {
119
+ truncate: true,
120
+ });
121
+ const wasAdded = await this.persistedHashes.add(dedupHash, expireAt);
122
+ if (!wasAdded) {
123
+ logger.debug(
124
+ 'Dropping before quorum check (already seen):',
125
+ action,
126
+ payload,
127
+ );
128
+ return [];
129
+ }
130
+ try {
131
+ if (await this._passesQuorum(quorumCheck)) {
132
+ return [toSendMessageJob(action, payload, deduplicateBy)];
133
+ } else {
134
+ logger.debug(
135
+ 'Dropping message (failed to reach quorum):',
136
+ action,
137
+ payload,
138
+ );
139
+ return [];
140
+ }
141
+ } catch (e) {
142
+ // unblock the hash to allow retries later
143
+ // (at this point, the error could be caused by a network error,
144
+ // so it is still possible that a retry later could work.)
145
+ await this.persistedHashes.delete(dedupHash).catch(() => {});
146
+ throw e;
147
+ }
148
+ },
149
+ {
150
+ priority: -1000,
151
+ cooldownInMs: 3 * SECOND,
152
+ maxJobsTotal: 200,
153
+ },
154
+ );
155
+ }
156
+
157
+ async init() {
158
+ this.active = true;
159
+ }
160
+
161
+ unload() {
162
+ this.active = false;
163
+ }
164
+
165
+ onPageEvent(event) {
166
+ if (!this.active) {
167
+ return;
168
+ }
169
+
170
+ if (event.type === 'safe-page-navigation') {
171
+ this._analyzeNavigation(event);
172
+ } else if (event.type === 'safe-search-landing') {
173
+ this._analyzeLanding(event.details);
174
+ }
175
+ }
176
+
177
+ // general case: page navigation
178
+ _analyzeNavigation(event) {
179
+ // TODO:
180
+ // A difference is that publically indexed 'search -> host' navigations
181
+ // less sensitive than arbitrary 'host -> host' navigations. Thus,
182
+ // it is likely that additional checks will be needed to support them.
183
+ // For now, start start without it.
184
+ console.debug('[STUB]: general navigation are not yet covered', event);
185
+ }
186
+
187
+ // special case: public search engine landings
188
+ _analyzeLanding({ from, to, redirects }) {
189
+ // Open questions:
190
+ // * Is it sufficient to look only at the first hop? For instance, what
191
+ // about permanent a redirect that is still controlled by the original
192
+ // site owner, before it hands control over to the tracker?
193
+ // * Currently, we look only at the first hop, even though there are chains
194
+ // of tracker redirects? Potentially, these could be useful. The message
195
+ // thus puts the results in an array; but for now, it will only have a
196
+ // single entry.
197
+ // * Should we use the statusCode? For instance, treat permanent redirects
198
+ // differently? - Currently, we do not.
199
+ const { category, query: unsafeQuery } = from;
200
+ const { isAd, trackingUrls } = isSearchAdRedirect(category, redirects);
201
+ if (!isAd) {
202
+ return;
203
+ }
204
+
205
+ // Since the context is a search engine landing, it is likely
206
+ // that it is a public hostname. Also, hostname are normally safe
207
+ // to share (e.g. they will be sent as cleartext even in https).
208
+ const hostname = tryParseHostname(to.targetUrl);
209
+ if (!hostname) {
210
+ return;
211
+ }
212
+ const trackingHosts = trackingUrls.map(tryParseHostname);
213
+
214
+ // null out the query if there is the risk of leaking information
215
+ const { accept } = this.sanitizer.checkSuspiciousQuery(unsafeQuery);
216
+ const query = accept ? unsafeQuery : null;
217
+
218
+ const action = 'wtm.nav-track-detect.search-ad';
219
+ this._registerJob({
220
+ type: 'nav-track-detect:quorum-isAdCheck',
221
+ args: {
222
+ action,
223
+ payload: {
224
+ from: {
225
+ search: {
226
+ category,
227
+ query,
228
+ },
229
+ },
230
+ to: {
231
+ hostname,
232
+ },
233
+ via: {
234
+ redirects: trackingHosts,
235
+ },
236
+ },
237
+ quorumCheck: JSON.stringify([
238
+ action,
239
+ category,
240
+ hostname,
241
+ trackingHosts,
242
+ ]),
243
+ },
244
+ });
245
+ }
246
+
247
+ async _passesQuorum(quorumCheck) {
248
+ requireString(quorumCheck);
249
+
250
+ // TODO: maybe break this also in two independent jobs
251
+ // (not strictly required, but could improve error recovery).
252
+ await this.quorumChecker.sendQuorumIncrement({ text: quorumCheck });
253
+ return this.quorumChecker.checkQuorumConsent({ text: quorumCheck });
254
+ }
255
+
256
+ _registerJob(job) {
257
+ this.jobScheduler.registerJob(job).catch((e) => {
258
+ logger.error('Failed to register job', job, e);
259
+ });
260
+ }
261
+ }
@@ -72,7 +72,7 @@ export function isLocalIP(ip) {
72
72
  export class DnsResolver {
73
73
  constructor() {
74
74
  this.dns = new Map();
75
- this._ttlInMs = DAY; // TODO: reconsider (if possible, make it small)
75
+ this._ttlInMs = DAY;
76
76
  }
77
77
 
78
78
  isPrivateURL(url) {
@@ -47,15 +47,14 @@ export default class PageAggregator {
47
47
  if (event.type === 'full-sync') {
48
48
  this.fullSync();
49
49
  } else if (event.type === 'lazy-init' || event.type === 'page-updated') {
50
- // TODO: is there a down-side in increasing the cooldown?
51
- // (especially, if there are many tabs open, it may become a problem)
52
50
  if (Date.now() > this._lastFullSync + COOLDOWN_FOR_FORCING_A_FULL_SYNC) {
53
51
  logger.debug('Forcing full sync');
54
52
  this.fullSync();
55
53
  } else {
56
- const { tabId } = event;
57
- this.syncTab(tabId);
54
+ this.syncTab(event.tabId);
58
55
  }
56
+ } else if (event.type === 'search-landing') {
57
+ this.syncTab(event.tabId);
59
58
  } else if (event.type === 'activity-updated') {
60
59
  const { urls, activityEstimator } = event;
61
60
  this._dbExecutor
@@ -63,8 +62,6 @@ export default class PageAggregator {
63
62
  await this.pagedb.updateActivity(urls, activityEstimator);
64
63
  })
65
64
  .catch(console.error);
66
- } else {
67
- logger.warn('Unexpected signal:', event);
68
65
  }
69
66
  }
70
67