@whotracksme/reporting 6.0.0 → 6.2.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,27 @@
1
+ # v6.2.0 (Sun Jan 19 2025)
2
+
3
+ #### 🚀 Enhancement
4
+
5
+ - Added support for multi-step doublefetch. [#152](https://github.com/whotracksme/webextension-packages/pull/152) ([@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
+
13
+ # v6.1.0 (Thu Jan 16 2025)
14
+
15
+ #### 🚀 Enhancement
16
+
17
+ - MV3 support for anonymousHttpGet [#151](https://github.com/whotracksme/webextension-packages/pull/151) ([@philipp-classen](https://github.com/philipp-classen))
18
+
19
+ #### Authors: 1
20
+
21
+ - Philipp Claßen ([@philipp-classen](https://github.com/philipp-classen))
22
+
23
+ ---
24
+
1
25
  # v6.0.0 (Wed Jan 15 2025)
2
26
 
3
27
  #### 💥 Breaking Change
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "6.0.0",
3
+ "version": "6.2.0",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
@@ -52,6 +52,11 @@ export class BadJobError extends PermanentError {}
52
52
  */
53
53
  export class UnableToOverrideHeadersError extends PermanentError {}
54
54
 
55
+ /**
56
+ * If the platform lacks the required APIs to support multi-step doublefetch.
57
+ */
58
+ export class MultiStepDoublefetchNotSupportedError extends PermanentError {}
59
+
55
60
  /**
56
61
  * Thrown when requests failed, but where the client can try to
57
62
  * repeat the request without modification (e.g. timeouts will
@@ -15,11 +15,22 @@ import {
15
15
  PermanentlyUnableToFetchUrlError,
16
16
  RateLimitedByServerError,
17
17
  UnableToOverrideHeadersError,
18
+ MultiStepDoublefetchNotSupportedError,
18
19
  } from './errors';
19
20
  import { split0 } from './utils';
21
+ import SeqExecutor from './seq-executor';
20
22
 
21
23
  const SECOND = 1000;
22
24
 
25
+ // This ID must not be used by other parts of the extension.
26
+ const RESERVED_DNR_RULE_ID = 1333;
27
+
28
+ function getExtensionDomain() {
29
+ getExtensionDomain.cached =
30
+ getExtensionDomain.cached || new URL(chrome.runtime.getURL('')).host;
31
+ return getExtensionDomain.cached;
32
+ }
33
+
23
34
  /**
24
35
  * Note: 429 (too many requests) is intentionally not included in the list.
25
36
  * Even though it is by definition a temporary error, it depends on the context
@@ -36,40 +47,112 @@ const httpStatusCodesThatShouldBeRetried = [
36
47
  599, // Network Connect Timeout Error
37
48
  ];
38
49
 
39
- /**
40
- * Performs a HTTP Get. Given the constraints, it tries to include
41
- * as few information as possible (e.g. credentials from cookies will
42
- * be omitted).
43
- *
44
- * Optional:
45
- * - headers: allows to overwrite headers
46
- * - redirect: 'follow' (or by default, it will fail with a permanent error)
47
- * - shouldFollowRedirect:
48
- * If redirect is set 'follow', this callback decides whether the final
49
- * redirect location should be followed. By default, all redirects are
50
- * accepted. Expects a function of type (finalUrl) => true|false
51
- * - treat429AsPermanentError:
52
- * By default, HTTP 429 (too many requests) will result in a
53
- * recoverable error (RateLimitedByServerError). For many use cases,
54
- * that is reasonable; but for double-fetch requests, repeating may
55
- * degrade user experience. Setting this flag will instead raise a
56
- * PermanentlyUnableToFetchUrlError instead.
57
- * - downloadLimit:
58
- * A best-effort attempt to define an upper bound for the number of
59
- * bytes downloaded. Note that there are no guarantees that it will
60
- * be able to stop bigger downloads. Also, it is based on the data
61
- * that comes over the wire; in other words, *after* compression.
62
- * - allowedContentTypes (optional):
63
- * An optional list of supported Content-Types (e.g. "text/html").
64
- * If given and the HTTP "Content-Type" header does not match, the
65
- * function will fail with a permanent error.
66
- *
67
- * TODO: For pages like YouTube, double-fetch fails because of consent
68
- * pages. In the YouTube example, the following cookie could be set:
69
- * "SOCS=CAESEwgDEgk0ODE3Nzk3MjQaAmVuIAEaBgiA_LyaBg"
70
- * (Maybe there is a way to generalize?)
71
- */
72
- export async function anonymousHttpGet(url, params = {}) {
50
+ // The following code overwrite the headers of the request.
51
+ // Note that "fetch" allows to overwrite headers in a simple declarative way,
52
+ // but unfortunately it is limited. For example, it is not possible to
53
+ // overwrite the cookie headers. The following code will work for all
54
+ // type of headers.
55
+ //
56
+ // The matching logic is not perfect, but should be fairly accurate.
57
+ // Ideally, we would want to run the handler only for the request that we
58
+ // are about to trigger, but not for any other requests to avoid unintended
59
+ // side-effects. To mitigate the risk, uninstall the handler at the first
60
+ // opportunity: either if it is called or if the request finished
61
+ // (and we know the handle will never be called).
62
+ function headerOverrideViaWebRequestAPI(url, headers) {
63
+ let uninstallHandler;
64
+ let webRequestHandler = (details) => {
65
+ if (
66
+ details.url !== url ||
67
+ details.type !== 'xmlhttprequest' ||
68
+ details.method !== 'GET'
69
+ ) {
70
+ // does that match the request that we intended to trigger
71
+ return {};
72
+ }
73
+
74
+ // match: now we can already deregister the listener
75
+ // (it should not be executed multiple times)
76
+ uninstallHandler();
77
+ const headerNames = Object.keys(headers);
78
+ const normalizedHeaders = headerNames.map((x) => x.toLowerCase());
79
+
80
+ /* eslint-disable no-param-reassign */
81
+ details.requestHeaders = details.requestHeaders.filter(
82
+ (header) => !normalizedHeaders.includes(header.name.toLowerCase()),
83
+ );
84
+
85
+ headerNames.forEach((name) => {
86
+ details.requestHeaders.push({
87
+ name,
88
+ value: headers[name],
89
+ });
90
+ });
91
+
92
+ return {
93
+ requestHeaders: details.requestHeaders,
94
+ };
95
+ };
96
+
97
+ logger.debug('Installing temporary webrequest handler for URL:', url);
98
+ chrome.webRequest.onBeforeSendHeaders.addListener(
99
+ webRequestHandler,
100
+ {
101
+ urls: [url],
102
+ },
103
+ ['blocking', 'requestHeaders'],
104
+ );
105
+
106
+ uninstallHandler = () => {
107
+ if (webRequestHandler) {
108
+ logger.debug('Removing temporary webrequest handler for URL:', url);
109
+ chrome.webRequest.onBeforeSendHeaders.removeListener(webRequestHandler);
110
+ webRequestHandler = null;
111
+ }
112
+ };
113
+ return uninstallHandler;
114
+ }
115
+
116
+ // Like headerOverrideViaWebRequestAPI, but using the DNR API.
117
+ async function headerOverrideViaDNR(url, headers) {
118
+ const requestHeaders = Object.entries(headers).map(([header, value]) => ({
119
+ header,
120
+ operation: 'set',
121
+ value,
122
+ }));
123
+ const rule = {
124
+ id: RESERVED_DNR_RULE_ID,
125
+ priority: 1,
126
+ action: {
127
+ type: 'modifyHeaders',
128
+ requestHeaders,
129
+ },
130
+ condition: {
131
+ urlFilter: url,
132
+ resourceTypes: ['xmlhttprequest'],
133
+ initiatorDomains: [getExtensionDomain()],
134
+ },
135
+ };
136
+ logger.debug('Installing temporary DNR rule for URL:', url);
137
+ await chrome.declarativeNetRequest.updateSessionRules({
138
+ addRules: [rule],
139
+ });
140
+ return () => {
141
+ logger.debug('Removing temporary DNR rule for URL:', url);
142
+ chrome.declarativeNetRequest
143
+ .updateSessionRules({
144
+ removeRuleIds: [rule.id],
145
+ })
146
+ .catch((e) => {
147
+ logger.warn('Failed to remove DNR rule', e);
148
+ });
149
+ };
150
+ }
151
+
152
+ // Note: the parameters are almost identical to "anonymousHttpGet"
153
+ // with the exception that "step" is not defined. The implementation
154
+ // here is only a single request, not a chain of requests.
155
+ async function singleHttpGetStep(url, params = {}) {
73
156
  const {
74
157
  headers = null,
75
158
  redirect = 'manual',
@@ -107,73 +190,19 @@ export async function anonymousHttpGet(url, params = {}) {
107
190
  }
108
191
 
109
192
  try {
110
- // The following code overwrite the headers of the request.
111
- // Note that "fetch" allows to overwrite headers in a simple declarative way,
112
- // but unfortunately it is limited. For example, it is not possible to
113
- // overwrite the cookie headers. The following code will work for all
114
- // type of headers.
115
- //
116
- // The matching logic is not perfect but should be fairly accurate.
117
- // Ideally, we would want to run the handler only for the request that we
118
- // are about to trigger, but not for any other requests to avoid unintended
119
- // side-effects. To mitigate the risk, uninstall the handler at the first
120
- // opportunity: either if it is called or if the request finished
121
- // (and we know the handle will never be called).
122
- let webRequestHandler;
123
- const uninstallHandler = () => {
124
- if (webRequestHandler) {
125
- chrome.webRequest.onBeforeSendHeaders.removeListener(webRequestHandler);
126
- webRequestHandler = null;
127
- }
128
- };
129
- const headerNames = Object.keys(headers || {});
130
- if (headerNames.length > 0) {
193
+ // optional cleanup operation that will be run after the request is completed
194
+ let cleanup = () => {};
195
+ if (headers && Object.keys(headers).length > 0) {
131
196
  if (
132
- !chrome.webRequest ||
133
- !chrome.webRequest.onBeforeSendHeaders ||
134
- !chrome.runtime.getManifest().permissions.includes('webRequestBlocking')
197
+ chrome?.webRequest?.onBeforeSendHeaders &&
198
+ chrome.runtime.getManifest().permissions.includes('webRequestBlocking')
135
199
  ) {
200
+ cleanup = headerOverrideViaWebRequestAPI(url, headers);
201
+ } else if (chrome?.declarativeNetRequest?.updateSessionRules) {
202
+ cleanup = await headerOverrideViaDNR(url, headers);
203
+ } else {
136
204
  throw new UnableToOverrideHeadersError();
137
205
  }
138
- webRequestHandler = (details) => {
139
- if (
140
- details.url !== url ||
141
- details.type !== 'xmlhttprequest' ||
142
- details.method !== 'GET'
143
- ) {
144
- // does that match the request that we intended to trigger
145
- return {};
146
- }
147
-
148
- // match: now we can already deregister the listener
149
- // (it should not be executed multiple times)
150
- uninstallHandler();
151
- const normalizedHeaders = headerNames.map((x) => x.toLowerCase());
152
-
153
- /* eslint-disable no-param-reassign */
154
- details.requestHeaders = details.requestHeaders.filter(
155
- (header) => !normalizedHeaders.includes(header.name.toLowerCase()),
156
- );
157
-
158
- headerNames.forEach((name) => {
159
- details.requestHeaders.push({
160
- name,
161
- value: headers[name],
162
- });
163
- });
164
-
165
- return {
166
- requestHeaders: details.requestHeaders,
167
- };
168
- };
169
-
170
- chrome.webRequest.onBeforeSendHeaders.addListener(
171
- webRequestHandler,
172
- {
173
- urls: [url],
174
- },
175
- ['blocking', 'requestHeaders'],
176
- );
177
206
  }
178
207
 
179
208
  let response;
@@ -184,7 +213,7 @@ export async function anonymousHttpGet(url, params = {}) {
184
213
  cause: e,
185
214
  });
186
215
  } finally {
187
- uninstallHandler();
216
+ cleanup();
188
217
  }
189
218
  if (
190
219
  response.status === 0 &&
@@ -263,3 +292,149 @@ export async function anonymousHttpGet(url, params = {}) {
263
292
  clearTimeout(timeoutTimer);
264
293
  }
265
294
  }
295
+
296
+ // Enforces only one active double-fetch request at a time.
297
+ const LOCK = new SeqExecutor();
298
+
299
+ /**
300
+ * Performs a HTTP Get. Given the constraints, it tries to include
301
+ * as few information as possible (e.g. credentials from cookies will
302
+ * be omitted).
303
+ *
304
+ * Optional:
305
+ * - headers: allows to overwrite headers
306
+ * - redirect: 'follow' (or by default, it will fail with a permanent error)
307
+ * - shouldFollowRedirect:
308
+ * If redirect is set 'follow', this callback decides whether the final
309
+ * redirect location should be followed. By default, all redirects are
310
+ * accepted. Expects a function of type (finalUrl) => true|false
311
+ * - treat429AsPermanentError:
312
+ * By default, HTTP 429 (too many requests) will result in a
313
+ * recoverable error (RateLimitedByServerError). For many use cases,
314
+ * that is reasonable; but for double-fetch requests, repeating may
315
+ * degrade user experience. Setting this flag will instead raise a
316
+ * PermanentlyUnableToFetchUrlError instead.
317
+ * - downloadLimit:
318
+ * A best-effort attempt to define an upper bound for the number of
319
+ * bytes downloaded. Note that there are no guarantees that it will
320
+ * be able to stop bigger downloads. Also, it is based on the data
321
+ * that comes over the wire; in other words, *after* compression.
322
+ * - allowedContentTypes (optional):
323
+ * An optional list of supported Content-Types (e.g. "text/html").
324
+ * If given and the HTTP "Content-Type" header does not match, the
325
+ * function will fail with a permanent error.
326
+ * - steps (optional):
327
+ * To configure multi-step double-fetch. That means, multiple requests
328
+ * to the same URL can be performed; values seen in earlier request
329
+ * can be used in later requests. Still, the chain of requests always
330
+ * starts from a clean state. In other words, the temporary context is
331
+ * fully isolated and will be discarded once all steps have completed.
332
+ *
333
+ * TODO: For pages like YouTube, double-fetch fails because of consent
334
+ * pages. In the YouTube example, the following cookie could be set:
335
+ * "SOCS=CAESEwgDEgk0ODE3Nzk3MjQaAmVuIAEaBgiA_LyaBg"
336
+ * (Maybe there is a way to generalize?)
337
+ */
338
+ export async function anonymousHttpGet(url, params = {}) {
339
+ return LOCK.run(async () => {
340
+ const { steps = [], ...sharedParams } = params;
341
+ if (steps.length === 0) {
342
+ return singleHttpGetStep(url, sharedParams);
343
+ }
344
+ if (!chrome?.webRequest?.onHeadersReceived) {
345
+ throw new MultiStepDoublefetchNotSupportedError();
346
+ }
347
+
348
+ // The context that can be queried with the placeholder syntax (e.g.
349
+ // "foo={{cookies:bar}"). The context is built from the requests from
350
+ // earlier steps. Currently, only cookies are provided, because this
351
+ // is a common use case to bypass consent dialogs; if needed we can
352
+ // extend it to other values (e.g. HTTP headers).
353
+ const ctx = {
354
+ cookie: new Map(),
355
+ };
356
+ const handler = (details) => {
357
+ for (let header of details.responseHeaders) {
358
+ if (header.name.toLowerCase() === 'set-cookie') {
359
+ for (const line of header.value.split('\n')) {
360
+ const start = line.indexOf('=');
361
+ if (start > 0) {
362
+ const key = line.slice(0, start);
363
+ const value = split0(line.slice(start + 1), ';');
364
+ ctx.cookie.set(key, value);
365
+ }
366
+ }
367
+ }
368
+ }
369
+ return { responseHeaders: details.responseHeaders };
370
+ };
371
+ try {
372
+ chrome.webRequest.onHeadersReceived.addListener(
373
+ handler,
374
+ { urls: [url] },
375
+ [
376
+ 'responseHeaders',
377
+ 'extraHeaders', // Note: needed for Chromium, but will be rejected by Firefox
378
+ ],
379
+ );
380
+ } catch (e) {
381
+ chrome.webRequest.onHeadersReceived.addListener(
382
+ handler,
383
+ { urls: [url] },
384
+ ['responseHeaders'],
385
+ );
386
+ }
387
+ try {
388
+ let content;
389
+ for (const step of steps) {
390
+ const localParams = {
391
+ ...sharedParams,
392
+ ...step,
393
+ };
394
+ if (localParams.headers) {
395
+ localParams.headers = replacePlaceholders(localParams.headers, ctx);
396
+ }
397
+ content = await singleHttpGetStep(url, localParams);
398
+ }
399
+ return content;
400
+ } finally {
401
+ chrome.webRequest.onHeadersReceived.removeListener(handler);
402
+ }
403
+ });
404
+ }
405
+
406
+ // Resolves placeholder expressions ("{{ }}"} with values provided by the
407
+ // the context. See unit test for examples.
408
+ //
409
+ // Note: exported for tests only
410
+ export function replacePlaceholders(headers, ctx) {
411
+ return Object.fromEntries(
412
+ Object.entries(headers).map(([key, value]) => {
413
+ const parts = [];
414
+ let pos = 0;
415
+ while (pos < value.length) {
416
+ const start = value.indexOf('{{', pos);
417
+ if (start < 0) {
418
+ parts.push(value.slice(pos));
419
+ break;
420
+ }
421
+ parts.push(value.slice(pos, start));
422
+ pos = start + 2;
423
+ const end = value.indexOf('}}', pos);
424
+ if (end < 0) {
425
+ throw new Error(`Corrupted placeholder expression: ${value}`);
426
+ }
427
+ const expression = value.slice(pos, end);
428
+ if (expression.startsWith('cookie:')) {
429
+ const cookieKey = expression.slice('cookie:'.length);
430
+ parts.push(ctx.cookie.get(cookieKey) || '');
431
+ } else {
432
+ throw new Error('currently only cookies are support');
433
+ }
434
+ pos = end + 2;
435
+ }
436
+ const newValue = parts.join('');
437
+ return [key, newValue];
438
+ }),
439
+ );
440
+ }
@@ -336,7 +336,7 @@ export function lookupBuiltinTransform(name) {
336
336
  * to disable clients that do not meet the minimum requirements of the
337
337
  * current patterns.
338
338
  */
339
- const PATTERN_DSL_VERSION = 3;
339
+ const PATTERN_DSL_VERSION = 4;
340
340
 
341
341
  /**
342
342
  * "Magic" empty rule set, which exists only if patterns were loaded, but
@@ -415,13 +415,17 @@ export default class Patterns {
415
415
  }
416
416
  const doublefetchRequest = { url };
417
417
  if (this._rules[msgType].doublefetch) {
418
- const { headers, followRedirects } = this._rules[msgType].doublefetch;
418
+ const { headers, followRedirects, steps } =
419
+ this._rules[msgType].doublefetch;
419
420
  if (followRedirects) {
420
421
  doublefetchRequest.redirect = 'follow';
421
422
  }
422
423
  if (headers) {
423
424
  doublefetchRequest.headers = headers;
424
425
  }
426
+ if (steps) {
427
+ doublefetchRequest.steps = steps;
428
+ }
425
429
  }
426
430
  return doublefetchRequest;
427
431
  }
@@ -160,6 +160,7 @@ export default class SearchExtractor {
160
160
  const html = await anonymousHttpGet(doublefetchRequest.url, {
161
161
  headers: doublefetchRequest.headers,
162
162
  redirect: doublefetchRequest.redirect,
163
+ steps: doublefetchRequest.steps,
163
164
  treat429AsPermanentError: true,
164
165
  });
165
166
  doc = await parseHtml(html);
@@ -0,0 +1,61 @@
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 { replacePlaceholders } from '../src/http.js';
15
+
16
+ describe('#replacePlaceholders', function () {
17
+ const emptyContext = {
18
+ cookie: new Map(),
19
+ };
20
+
21
+ const cookie_x_to_y = {
22
+ cookie: new Map([['x', 'y']]),
23
+ };
24
+
25
+ it('should work with empty strings', function () {
26
+ expect(replacePlaceholders({ key: '' }, emptyContext)).to.eql({ key: '' });
27
+ });
28
+
29
+ it('should work with expressions without placeholders', function () {
30
+ expect(replacePlaceholders({ key: 'foo' }, emptyContext)).to.eql({
31
+ key: 'foo',
32
+ });
33
+ });
34
+
35
+ it('should replace one placeholder in the start', function () {
36
+ expect(
37
+ replacePlaceholders({ key: '{{cookie:x}};bar' }, cookie_x_to_y),
38
+ ).to.eql({ key: 'y;bar' });
39
+ });
40
+
41
+ it('should replace one placeholder in the middle', function () {
42
+ expect(
43
+ replacePlaceholders({ key: 'foo={{cookie:x}};bar' }, cookie_x_to_y),
44
+ ).to.eql({ key: 'foo=y;bar' });
45
+ });
46
+
47
+ it('should replace one placeholder at the end', function () {
48
+ expect(
49
+ replacePlaceholders({ key: 'foo={{cookie:x}}' }, cookie_x_to_y),
50
+ ).to.eql({ key: 'foo=y' });
51
+ });
52
+
53
+ it('should support multiple placeholders', function () {
54
+ expect(
55
+ replacePlaceholders(
56
+ { key: 'foo={{cookie:x}};bar={{cookie:x}}' },
57
+ cookie_x_to_y,
58
+ ),
59
+ ).to.eql({ key: 'foo=y;bar=y' });
60
+ });
61
+ });
@@ -4,6 +4,7 @@ import './reporting.spec.js';
4
4
  import './activity-estimator.spec.js';
5
5
  import './duplicate-detector.spec.js';
6
6
  import './doublefetch-page-handler.spec.js';
7
+ import './http.spec.js';
7
8
  import './patterns.spec.js';
8
9
  import './patterns-updater.spec.js';
9
10
  import './job-scheduler.spec.js';