@whotracksme/reporting 6.1.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,15 @@
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
+
1
13
  # v6.1.0 (Thu Jan 16 2025)
2
14
 
3
15
  #### πŸš€ Enhancement
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "6.1.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,6 +15,7 @@ import {
15
15
  PermanentlyUnableToFetchUrlError,
16
16
  RateLimitedByServerError,
17
17
  UnableToOverrideHeadersError,
18
+ MultiStepDoublefetchNotSupportedError,
18
19
  } from './errors';
19
20
  import { split0 } from './utils';
20
21
  import SeqExecutor from './seq-executor';
@@ -148,6 +149,150 @@ async function headerOverrideViaDNR(url, headers) {
148
149
  };
149
150
  }
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 = {}) {
156
+ const {
157
+ headers = null,
158
+ redirect = 'manual',
159
+ shouldFollowRedirect = () => true,
160
+ timeout = 15 * SECOND,
161
+ treat429AsPermanentError = false,
162
+ downloadLimit = 10 * 1024 * 1024, // 10 MB
163
+ allowedContentTypes = null,
164
+ } = params;
165
+
166
+ if (redirect !== 'follow' && params.shouldFollowRedirect) {
167
+ logger.warn(
168
+ 'shouldFollowRedirect ignored because redirects will be automatically resolved',
169
+ );
170
+ }
171
+
172
+ const controller = new AbortController();
173
+ const options = {
174
+ credentials: 'omit',
175
+ mode: 'no-cors',
176
+ redirect,
177
+ signal: controller.signal,
178
+ };
179
+
180
+ let timeoutTimer;
181
+ let timeoutTriggered = false;
182
+ if (timeout && timeout > 0) {
183
+ timeoutTimer = setTimeout(() => {
184
+ const msg = `Request to ${url} timed out (limit: ${timeout} ms)`;
185
+ controller.abort(new TemporarilyUnableToFetchUrlError(msg));
186
+ logger.warn(msg);
187
+ timeoutTimer = null;
188
+ timeoutTriggered = true;
189
+ }, timeout);
190
+ }
191
+
192
+ try {
193
+ // optional cleanup operation that will be run after the request is completed
194
+ let cleanup = () => {};
195
+ if (headers && Object.keys(headers).length > 0) {
196
+ if (
197
+ chrome?.webRequest?.onBeforeSendHeaders &&
198
+ chrome.runtime.getManifest().permissions.includes('webRequestBlocking')
199
+ ) {
200
+ cleanup = headerOverrideViaWebRequestAPI(url, headers);
201
+ } else if (chrome?.declarativeNetRequest?.updateSessionRules) {
202
+ cleanup = await headerOverrideViaDNR(url, headers);
203
+ } else {
204
+ throw new UnableToOverrideHeadersError();
205
+ }
206
+ }
207
+
208
+ let response;
209
+ try {
210
+ response = await fetch(url, options);
211
+ } catch (e) {
212
+ throw new TemporarilyUnableToFetchUrlError(`Failed to fetch url ${url}`, {
213
+ cause: e,
214
+ });
215
+ } finally {
216
+ cleanup();
217
+ }
218
+ if (
219
+ response.status === 0 &&
220
+ (response.type == 'opaqueredirect' || response.type == 'opaque')
221
+ ) {
222
+ throw new PermanentlyUnableToFetchUrlError(
223
+ `Failed to fetch url ${url}: not allowed to follow redirects (response.type=${response.type})`,
224
+ );
225
+ }
226
+ if (response.url !== url && !shouldFollowRedirect(response.url)) {
227
+ throw new PermanentlyUnableToFetchUrlError(
228
+ `Failed to fetch url ${url}: detected forbidden redirect to ${response.url}`,
229
+ );
230
+ }
231
+
232
+ if (!response.ok) {
233
+ const msg = `Failed to fetch url ${url}: ${response.statusText}`;
234
+ if (response.status === 429) {
235
+ if (treat429AsPermanentError) {
236
+ throw new PermanentlyUnableToFetchUrlError(msg);
237
+ }
238
+ throw new RateLimitedByServerError(msg);
239
+ }
240
+ if (httpStatusCodesThatShouldBeRetried.includes(response.status)) {
241
+ throw new TemporarilyUnableToFetchUrlError(msg);
242
+ }
243
+ throw new PermanentlyUnableToFetchUrlError(msg);
244
+ }
245
+
246
+ if (downloadLimit && downloadLimit > 0) {
247
+ const contentLength = response.headers.get('content-length');
248
+ if (contentLength && contentLength > downloadLimit) {
249
+ const err = new PermanentlyUnableToFetchUrlError(
250
+ `Exceeded size limit when fetching url ${url} (${contentLength} > ${downloadLimit})`,
251
+ );
252
+ controller.abort(err);
253
+ throw err;
254
+ }
255
+ }
256
+
257
+ if (allowedContentTypes) {
258
+ const value = response.headers.get('content-type');
259
+ if (value) {
260
+ const contentType = split0(value, ';').trim().toLowerCase();
261
+ if (!allowedContentTypes.includes(contentType)) {
262
+ const err = new PermanentlyUnableToFetchUrlError(
263
+ `Unexpected "Content-Type" <${contentType}> (<${value}> not in {${allowedContentTypes}})`,
264
+ );
265
+ controller.abort(err);
266
+ throw err;
267
+ }
268
+ } else {
269
+ logger.warn(
270
+ 'The URL',
271
+ url,
272
+ 'did not return a "Content-Type" HTTP header.',
273
+ 'Continue and assume the types are matching...',
274
+ );
275
+ }
276
+ }
277
+
278
+ try {
279
+ return await response.text();
280
+ } catch (e) {
281
+ if (timeoutTriggered) {
282
+ throw new TemporarilyUnableToFetchUrlError(
283
+ `Failed to fetch url ${url} because the request timed out.`,
284
+ );
285
+ }
286
+ throw new TemporarilyUnableToFetchUrlError(
287
+ `Failed to fetch url ${url} (${e.message})`,
288
+ { cause: e },
289
+ );
290
+ }
291
+ } finally {
292
+ clearTimeout(timeoutTimer);
293
+ }
294
+ }
295
+
151
296
  // Enforces only one active double-fetch request at a time.
152
297
  const LOCK = new SeqExecutor();
153
298
 
@@ -178,6 +323,12 @@ const LOCK = new SeqExecutor();
178
323
  * An optional list of supported Content-Types (e.g. "text/html").
179
324
  * If given and the HTTP "Content-Type" header does not match, the
180
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.
181
332
  *
182
333
  * TODO: For pages like YouTube, double-fetch fails because of consent
183
334
  * pages. In the YouTube example, the following cookie could be set:
@@ -186,148 +337,104 @@ const LOCK = new SeqExecutor();
186
337
  */
187
338
  export async function anonymousHttpGet(url, params = {}) {
188
339
  return LOCK.run(async () => {
189
- const {
190
- headers = null,
191
- redirect = 'manual',
192
- shouldFollowRedirect = () => true,
193
- timeout = 15 * SECOND,
194
- treat429AsPermanentError = false,
195
- downloadLimit = 10 * 1024 * 1024, // 10 MB
196
- allowedContentTypes = null,
197
- } = params;
198
-
199
- if (redirect !== 'follow' && params.shouldFollowRedirect) {
200
- logger.warn(
201
- 'shouldFollowRedirect ignored because redirects will be automatically resolved',
202
- );
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();
203
346
  }
204
347
 
205
- const controller = new AbortController();
206
- const options = {
207
- credentials: 'omit',
208
- mode: 'no-cors',
209
- redirect,
210
- signal: controller.signal,
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(),
211
355
  };
212
-
213
- let timeoutTimer;
214
- let timeoutTriggered = false;
215
- if (timeout && timeout > 0) {
216
- timeoutTimer = setTimeout(() => {
217
- const msg = `Request to ${url} timed out (limit: ${timeout} ms)`;
218
- controller.abort(new TemporarilyUnableToFetchUrlError(msg));
219
- logger.warn(msg);
220
- timeoutTimer = null;
221
- timeoutTriggered = true;
222
- }, timeout);
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
+ );
223
386
  }
224
-
225
387
  try {
226
- // optional cleanup operation that will be run after the request is completed
227
- let cleanup = () => {};
228
- if (headers && Object.keys(headers).length > 0) {
229
- if (
230
- chrome?.webRequest?.onBeforeSendHeaders &&
231
- chrome.runtime
232
- .getManifest()
233
- .permissions.includes('webRequestBlocking')
234
- ) {
235
- cleanup = headerOverrideViaWebRequestAPI(url, headers);
236
- } else if (chrome?.declarativeNetRequest?.updateSessionRules) {
237
- cleanup = await headerOverrideViaDNR(url, headers);
238
- } else {
239
- throw new UnableToOverrideHeadersError();
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);
240
396
  }
397
+ content = await singleHttpGetStep(url, localParams);
241
398
  }
399
+ return content;
400
+ } finally {
401
+ chrome.webRequest.onHeadersReceived.removeListener(handler);
402
+ }
403
+ });
404
+ }
242
405
 
243
- let response;
244
- try {
245
- response = await fetch(url, options);
246
- } catch (e) {
247
- throw new TemporarilyUnableToFetchUrlError(
248
- `Failed to fetch url ${url}`,
249
- {
250
- cause: e,
251
- },
252
- );
253
- } finally {
254
- cleanup();
255
- }
256
- if (
257
- response.status === 0 &&
258
- (response.type == 'opaqueredirect' || response.type == 'opaque')
259
- ) {
260
- throw new PermanentlyUnableToFetchUrlError(
261
- `Failed to fetch url ${url}: not allowed to follow redirects (response.type=${response.type})`,
262
- );
263
- }
264
- if (response.url !== url && !shouldFollowRedirect(response.url)) {
265
- throw new PermanentlyUnableToFetchUrlError(
266
- `Failed to fetch url ${url}: detected forbidden redirect to ${response.url}`,
267
- );
268
- }
269
-
270
- if (!response.ok) {
271
- const msg = `Failed to fetch url ${url}: ${response.statusText}`;
272
- if (response.status === 429) {
273
- if (treat429AsPermanentError) {
274
- throw new PermanentlyUnableToFetchUrlError(msg);
275
- }
276
- throw new RateLimitedByServerError(msg);
277
- }
278
- if (httpStatusCodesThatShouldBeRetried.includes(response.status)) {
279
- throw new TemporarilyUnableToFetchUrlError(msg);
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;
280
420
  }
281
- throw new PermanentlyUnableToFetchUrlError(msg);
282
- }
283
-
284
- if (downloadLimit && downloadLimit > 0) {
285
- const contentLength = response.headers.get('content-length');
286
- if (contentLength && contentLength > downloadLimit) {
287
- const err = new PermanentlyUnableToFetchUrlError(
288
- `Exceeded size limit when fetching url ${url} (${contentLength} > ${downloadLimit})`,
289
- );
290
- controller.abort(err);
291
- throw err;
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}`);
292
426
  }
293
- }
294
-
295
- if (allowedContentTypes) {
296
- const value = response.headers.get('content-type');
297
- if (value) {
298
- const contentType = split0(value, ';').trim().toLowerCase();
299
- if (!allowedContentTypes.includes(contentType)) {
300
- const err = new PermanentlyUnableToFetchUrlError(
301
- `Unexpected "Content-Type" <${contentType}> (<${value}> not in {${allowedContentTypes}})`,
302
- );
303
- controller.abort(err);
304
- throw err;
305
- }
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) || '');
306
431
  } else {
307
- logger.warn(
308
- 'The URL',
309
- url,
310
- 'did not return a "Content-Type" HTTP header.',
311
- 'Continue and assume the types are matching...',
312
- );
313
- }
314
- }
315
-
316
- try {
317
- return await response.text();
318
- } catch (e) {
319
- if (timeoutTriggered) {
320
- throw new TemporarilyUnableToFetchUrlError(
321
- `Failed to fetch url ${url} because the request timed out.`,
322
- );
432
+ throw new Error('currently only cookies are support');
323
433
  }
324
- throw new TemporarilyUnableToFetchUrlError(
325
- `Failed to fetch url ${url} (${e.message})`,
326
- { cause: e },
327
- );
434
+ pos = end + 2;
328
435
  }
329
- } finally {
330
- clearTimeout(timeoutTimer);
331
- }
332
- });
436
+ const newValue = parts.join('');
437
+ return [key, newValue];
438
+ }),
439
+ );
333
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';