@whotracksme/reporting 7.2.0 β†’ 7.3.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.3.0 (Wed May 21 2025)
2
+
3
+ #### πŸš€ Enhancement
4
+
5
+ - Added missing header overwrite in doublefetch [#160](https://github.com/whotracksme/webextension-packages/pull/160) ([@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
  # v7.2.0 (Mon May 19 2025)
2
14
 
3
15
  #### πŸš€ Enhancement
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "7.2.0",
3
+ "version": "7.3.0",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
@@ -28,6 +28,39 @@ const SECOND = 1000;
28
28
  const RESERVED_DNR_RULE_ID_HEADER_OVERRIDE = 1333;
29
29
  const RESERVED_DNR_RULE_ID_OFFSCREEN = 1334;
30
30
 
31
+ /**
32
+ * Depending on the context, there are different ways how requests are being
33
+ * triggered. For instance, the normal one is to use the fetch API; but
34
+ * with dynamic rendering using offscreen, it will be technically triggered
35
+ * from an iframe. That impacts how APIs should be later interpreted.
36
+ */
37
+ const REQUEST_TYPE = {
38
+ FETCH_API: Symbol('FETCH_API'),
39
+ IFRAME: Symbol('IFRAME'),
40
+ };
41
+
42
+ // maps our REQUEST_TYPE to the type used in the webRequestAPI
43
+ function matchesWebRequestApiType(requestType, webRequestApiType) {
44
+ if (requestType === REQUEST_TYPE.FETCH_API) {
45
+ return webRequestApiType === 'xmlhttprequest';
46
+ }
47
+ if (requestType === REQUEST_TYPE.IFRAME) {
48
+ return webRequestApiType === 'sub_frame';
49
+ }
50
+ throw new Error(`Unexpected requestType: ${requestType}`);
51
+ }
52
+
53
+ // maps our REQUEST_TYPE to the resource Type array used by the DNR API
54
+ function requestTypeToDNRResourceTypes(requestType) {
55
+ if (requestType === REQUEST_TYPE.FETCH_API) {
56
+ return ['xmlhttprequest'];
57
+ }
58
+ if (requestType === REQUEST_TYPE.IFRAME) {
59
+ return ['sub_frame'];
60
+ }
61
+ throw new Error(`Unexpected requestType: ${requestType}`);
62
+ }
63
+
31
64
  function getExtensionDomain() {
32
65
  getExtensionDomain.cached =
33
66
  getExtensionDomain.cached || new URL(chrome.runtime.getURL('')).host;
@@ -110,6 +143,29 @@ const httpStatusCodesThatShouldBeRetried = [
110
143
  599, // Network Connect Timeout Error
111
144
  ];
112
145
 
146
+ // Overwrites the headers of the request to the given URL.
147
+ // It automatically selects the mechanism (e.g. webRequestAPI, DNR)
148
+ // based on the available APIs.
149
+ //
150
+ // Returns a cleanup callback to undo the changes.
151
+ async function headerOverride(params) {
152
+ const { headers } = params;
153
+ if (!headers || Object.keys(headers).length === 0) {
154
+ return () => {};
155
+ }
156
+
157
+ if (
158
+ chrome?.webRequest?.onBeforeSendHeaders &&
159
+ chrome.runtime.getManifest().permissions.includes('webRequestBlocking')
160
+ ) {
161
+ return headerOverrideViaWebRequestAPI(params);
162
+ } else if (chrome?.declarativeNetRequest?.updateSessionRules) {
163
+ return await headerOverrideViaDNR(params);
164
+ } else {
165
+ throw new UnableToOverrideHeadersError();
166
+ }
167
+ }
168
+
113
169
  // The following code overwrite the headers of the request.
114
170
  // Note that "fetch" allows to overwrite headers in a simple declarative way,
115
171
  // but unfortunately it is limited. For example, it is not possible to
@@ -122,13 +178,13 @@ const httpStatusCodesThatShouldBeRetried = [
122
178
  // side-effects. To mitigate the risk, uninstall the handler at the first
123
179
  // opportunity: either if it is called or if the request finished
124
180
  // (and we know the handle will never be called).
125
- function headerOverrideViaWebRequestAPI(url, headers) {
181
+ function headerOverrideViaWebRequestAPI({ url, headers, requestType }) {
126
182
  let uninstallHandler;
127
183
  let webRequestHandler = (details) => {
128
184
  if (
129
185
  details.url !== url ||
130
- details.type !== 'xmlhttprequest' ||
131
- details.method !== 'GET'
186
+ details.method !== 'GET' ||
187
+ !matchesWebRequestApiType(requestType, details.type)
132
188
  ) {
133
189
  // does that match the request that we intended to trigger
134
190
  return {};
@@ -177,7 +233,7 @@ function headerOverrideViaWebRequestAPI(url, headers) {
177
233
  }
178
234
 
179
235
  // Like headerOverrideViaWebRequestAPI, but using the DNR API.
180
- async function headerOverrideViaDNR(url, headers) {
236
+ async function headerOverrideViaDNR({ url, headers, requestType }) {
181
237
  const requestHeaders = Object.entries(headers).map(([header, value]) => ({
182
238
  header,
183
239
  operation: 'set',
@@ -192,22 +248,52 @@ async function headerOverrideViaDNR(url, headers) {
192
248
  },
193
249
  condition: {
194
250
  urlFilter: url,
195
- resourceTypes: ['xmlhttprequest'],
251
+ resourceTypes: requestTypeToDNRResourceTypes(requestType),
196
252
  initiatorDomains: [getExtensionDomain()],
197
253
  },
198
254
  };
255
+
199
256
  logger.debug('Installing temporary DNR rule for URL:', url);
200
- await chrome.declarativeNetRequest.updateSessionRules({
201
- addRules: [rule],
202
- });
257
+ const cleanup = await addDNRSessionRule(rule);
258
+
203
259
  return () => {
204
260
  logger.debug('Removing temporary DNR rule for URL:', url);
205
- chrome.declarativeNetRequest
261
+ return cleanup();
262
+ };
263
+ }
264
+
265
+ async function addDNRSessionRule(rule) {
266
+ try {
267
+ await chrome.declarativeNetRequest.updateSessionRules({ addRules: [rule] });
268
+ } catch (e) {
269
+ try {
270
+ logger.warn(
271
+ 'Unable to install DNR rule. Trying to delete rule first:',
272
+ rule,
273
+ e,
274
+ );
275
+ await chrome.declarativeNetRequest.updateSessionRules({
276
+ removeRuleIds: [rule.id],
277
+ });
278
+ } catch (e2) {
279
+ logger.warn('Retry not possible (unable to remove DNR rule):', rule, e2);
280
+ throw e;
281
+ }
282
+
283
+ logger.debug('Second attempt to install DNR rule:', rule);
284
+ await chrome.declarativeNetRequest.updateSessionRules({
285
+ addRules: [rule],
286
+ });
287
+ logger.debug('Succeed in install DNR rule on the second attempt:', rule);
288
+ }
289
+
290
+ return () => {
291
+ return chrome.declarativeNetRequest
206
292
  .updateSessionRules({
207
293
  removeRuleIds: [rule.id],
208
294
  })
209
295
  .catch((e) => {
210
- logger.warn('Failed to remove DNR rule', e);
296
+ logger.error('cleanup failed: unable to remove DNR rule:', rule, e);
211
297
  });
212
298
  };
213
299
  }
@@ -246,15 +332,15 @@ async function withOffscreenDocumentReady(url, headers, asyncCallback) {
246
332
  },
247
333
  };
248
334
 
249
- await chrome.declarativeNetRequest.updateSessionRules({
250
- removeRuleIds: [rule.id],
251
- addRules: [rule],
335
+ const undoDNRChange = await addDNRSessionRule(rule);
336
+ cleanups.push(undoDNRChange);
337
+
338
+ const undoHeaderOverride = await headerOverride({
339
+ headers,
340
+ url,
341
+ requestType: REQUEST_TYPE.IFRAME,
252
342
  });
253
- cleanups.push(() =>
254
- chrome.declarativeNetRequest.updateSessionRules({
255
- removeRuleIds: [rule.id],
256
- }),
257
- );
343
+ cleanups.push(undoHeaderOverride);
258
344
 
259
345
  const offscreenUrl = chrome.runtime.getURL(OFFSCREEN_DOCUMENT_PATH);
260
346
  const existingContexts = await chrome.runtime.getContexts({
@@ -330,22 +416,12 @@ async function singleHttpGetStep(url, params = {}) {
330
416
  }
331
417
 
332
418
  try {
333
- // optional cleanup operation that will be run after the request is completed
334
- let cleanup = () => {};
335
- if (headers && Object.keys(headers).length > 0) {
336
- if (
337
- chrome?.webRequest?.onBeforeSendHeaders &&
338
- chrome.runtime.getManifest().permissions.includes('webRequestBlocking')
339
- ) {
340
- cleanup = headerOverrideViaWebRequestAPI(url, headers);
341
- } else if (chrome?.declarativeNetRequest?.updateSessionRules) {
342
- cleanup = await headerOverrideViaDNR(url, headers);
343
- } else {
344
- throw new UnableToOverrideHeadersError();
345
- }
346
- }
347
-
348
419
  let response;
420
+ const undoHeaderOverride = await headerOverride({
421
+ headers,
422
+ url,
423
+ requestType: REQUEST_TYPE.FETCH_API,
424
+ });
349
425
  try {
350
426
  response = await fetch(url, options);
351
427
  } catch (e) {
@@ -353,8 +429,9 @@ async function singleHttpGetStep(url, params = {}) {
353
429
  cause: e,
354
430
  });
355
431
  } finally {
356
- cleanup();
432
+ await undoHeaderOverride();
357
433
  }
434
+
358
435
  if (
359
436
  response.status === 0 &&
360
437
  (response.type == 'opaqueredirect' || response.type == 'opaque')
@@ -647,45 +724,49 @@ export async function anonymousHttpGet(originalUrl, params = {}) {
647
724
  // If needed, one idea is to use content scripts in the offscreen document.
648
725
  content = '';
649
726
 
650
- await withOffscreenDocumentReady(localUrl, localParams, async () => {
651
- const { ok, error } = await chrome.runtime.sendMessage({
652
- target: 'offscreen:urlReporting',
653
- type: 'request',
654
- data: { url: localUrl },
655
- });
656
- if (!ok) {
657
- throw new Error(
658
- `Unexpected error (details: ${error || '<unavailable>'})`,
659
- );
660
- }
727
+ await withOffscreenDocumentReady(
728
+ localUrl,
729
+ localParams.headers,
730
+ async () => {
731
+ const { ok, error } = await chrome.runtime.sendMessage({
732
+ target: 'offscreen:urlReporting',
733
+ type: 'request',
734
+ data: { url: localUrl },
735
+ });
736
+ if (!ok) {
737
+ throw new Error(
738
+ `Unexpected error (details: ${error || '<unavailable>'})`,
739
+ );
740
+ }
661
741
 
662
- let timeout = null;
663
- const timedOut = new Promise((resolve, reject) => {
664
- const maxTime = params.timeout || 15 * SECOND;
665
- timeout = setTimeout(() => {
666
- timeout = null;
667
- logger.warn(
668
- 'Dynamic fetch of URL',
669
- localUrl,
670
- 'exceeded the timeout of',
671
- maxTime,
672
- 'ms. Details:',
673
- {
742
+ let timeout = null;
743
+ const timedOut = new Promise((resolve, reject) => {
744
+ const maxTime = params.timeout || 15 * SECOND;
745
+ timeout = setTimeout(() => {
746
+ timeout = null;
747
+ logger.warn(
748
+ 'Dynamic fetch of URL',
674
749
  localUrl,
675
- currentStep,
676
- nextStep,
677
- ctx,
678
- },
679
- );
680
- reject(`Timeout when dynamically fetching ${localUrl}`);
681
- }, maxTime);
682
- });
683
- try {
684
- await Promise.race([readyForNextStep, timedOut]);
685
- } finally {
686
- clearTimeout(timeout);
687
- }
688
- });
750
+ 'exceeded the timeout of',
751
+ maxTime,
752
+ 'ms. Details:',
753
+ {
754
+ localUrl,
755
+ currentStep,
756
+ nextStep,
757
+ ctx,
758
+ },
759
+ );
760
+ reject(`Timeout when dynamically fetching ${localUrl}`);
761
+ }, maxTime);
762
+ });
763
+ try {
764
+ await Promise.race([readyForNextStep, timedOut]);
765
+ } finally {
766
+ clearTimeout(timeout);
767
+ }
768
+ },
769
+ );
689
770
  } else {
690
771
  content = await singleHttpGetStep(localUrl, localParams);
691
772
  }
@@ -313,7 +313,7 @@ export default class SearchExtractor {
313
313
  const body = {
314
314
  action,
315
315
  payload,
316
- ver: 3, // Note: no need to keep this number in sync among messages
316
+ ver: 4, // Note: no need to keep this number in sync among messages
317
317
  'anti-duplicates': Math.floor(random() * 10000000),
318
318
  };
319
319
  messages.push({ body, deduplicateBy });