@whotracksme/reporting 5.1.24 β†’ 5.1.25

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.
@@ -7,13 +7,13 @@ on:
7
7
  jobs:
8
8
  release:
9
9
  name: Trigger release
10
- runs-on: ubuntu-20.04
10
+ runs-on: ubuntu-24.04
11
11
  if: "!contains(github.event.head_commit.message, 'ci skip') && !contains(github.event.head_commit.message, 'skip ci')"
12
12
  steps:
13
13
  - uses: actions/checkout@v2
14
14
  - uses: actions/setup-node@v2
15
15
  with:
16
- node-version: '18'
16
+ node-version: '22'
17
17
  cache: 'npm'
18
18
 
19
19
  - name: Prepare repository
@@ -12,9 +12,6 @@ jobs:
12
12
 
13
13
  steps:
14
14
  - uses: actions/checkout@v2
15
- - uses: actions/setup-node@v2
16
- with:
17
- node-version: '18'
18
- cache: 'npm'
15
+ - uses: jdx/mise-action@v2
19
16
  - run: npm ci
20
17
  - run: npm test
package/.tool-versions CHANGED
@@ -1 +1 @@
1
- nodejs 19.8.1
1
+ nodejs 22.8.0
package/CHANGELOG.md CHANGED
@@ -1,3 +1,19 @@
1
+ # v5.1.25 (Mon Sep 23 2024)
2
+
3
+ #### πŸ› Bug Fix
4
+
5
+ - The new tests assume Node 22. Also, upgrade to Ubuntu 24.04. [#100](https://github.com/whotracksme/webextension-packages/pull/100) ([@philipp-classen](https://github.com/philipp-classen))
6
+ - Fix page store persistance [#99](https://github.com/whotracksme/webextension-packages/pull/99) ([@chrmod](https://github.com/chrmod))
7
+ - Fix storage values [#99](https://github.com/whotracksme/webextension-packages/pull/99) ([@chrmod](https://github.com/chrmod))
8
+ - Basic unit test setup [#94](https://github.com/whotracksme/webextension-packages/pull/94) ([@chrmod](https://github.com/chrmod))
9
+
10
+ #### Authors: 2
11
+
12
+ - Krzysztof Modras ([@chrmod](https://github.com/chrmod))
13
+ - Philipp Claßen ([@philipp-classen](https://github.com/philipp-classen))
14
+
15
+ ---
16
+
1
17
  # v5.1.24 (Fri Sep 13 2024)
2
18
 
3
19
  #### πŸ› Bug Fix
package/package.json CHANGED
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "@whotracksme/reporting",
3
- "version": "5.1.24",
3
+ "version": "5.1.25",
4
4
  "type": "module",
5
5
  "description": "",
6
6
  "scripts": {
7
7
  "lint": "eslint reporting/ communication/",
8
8
  "lint.fix": "eslint --fix reporting/ communication/",
9
- "test": "npm run lint && npm run test --workspaces --if-present",
9
+ "test": "npm run lint && npm run test --workspaces --if-present && npm run test.unit --workspaces --if-present",
10
10
  "release": "auto shipit"
11
11
  },
12
12
  "publishConfig": {
@@ -7,6 +7,8 @@
7
7
  "start.firefox": "cp example/manifests/firefox.json example/manifest.json && web-ext run -s ./example -t firefox-desktop",
8
8
  "build": "rollup -c",
9
9
  "watch": "rollup -c -w",
10
+ "test.unit": "mocha --file ./test/setup.unit.js ./test/**/*.test.js",
11
+ "test.unit.watch": "npm run test.unit -- --node-option=watch",
10
12
  "test": "karma start --single-run --browsers ChromeHeadless karma.conf.cjs"
11
13
  },
12
14
  "author": "Ghostery GmbH",
@@ -25,7 +27,7 @@
25
27
  "karma-mocha-reporter": "^2.2.5",
26
28
  "karma-rollup-preprocessor": "^7.0.8",
27
29
  "karma-sinon": "^1.0.5",
28
- "mocha": "^9.2.2",
30
+ "mocha": "^10.7.3",
29
31
  "rollup": "^2.79.1",
30
32
  "rollup-plugin-polyfill-node": "^0.8.0",
31
33
  "rollup-plugin-sourcemaps": "^0.6.3",
@@ -524,7 +524,8 @@ export default class RequestMonitor {
524
524
  // check for tracking status headers for first party
525
525
  const trackingStatus = getTrackingStatus(state);
526
526
  if (trackingStatus) {
527
- state.page.setTrackingStatus(trackingStatus);
527
+ state.page.tsv = trackingStatus.value;
528
+ state.page.tsvId = trackingStatus.statusId;
528
529
  }
529
530
  return false;
530
531
  }
@@ -11,6 +11,7 @@
11
11
 
12
12
  /* eslint no-param-reassign: 'off' */
13
13
  import { truncateDomain } from '../utils';
14
+ import { getStatsForDomain } from '../../webrequest-pipeline/page.js';
14
15
 
15
16
  // maps string (web-ext) to int (FF cpt). Anti-tracking still uses these legacy types.
16
17
  const TYPE_LOOKUP = {
@@ -44,7 +45,8 @@ export default class PageLogger {
44
45
  }
45
46
 
46
47
  _attachCounters(state) {
47
- const stats = state.page.getStatsForDomain(
48
+ const stats = getStatsForDomain(
49
+ state.page,
48
50
  truncateDomain(state.urlParts.domainInfo, 2),
49
51
  );
50
52
  state.reqLog = stats;
@@ -88,6 +88,12 @@ export default class ChromeStorageMap {
88
88
  });
89
89
  }
90
90
 
91
+ countNonExpiredKeys() {
92
+ this._warnIfOutOfSync();
93
+ this._expireOldEntries();
94
+ return this._inMemoryMap.size;
95
+ }
96
+
91
97
  get(_key) {
92
98
  this._warnIfOutOfSync();
93
99
  const key = this.normalizeKey(_key);
@@ -106,7 +112,7 @@ export default class ChromeStorageMap {
106
112
  values() {
107
113
  this._warnIfOutOfSync();
108
114
  this._expireOldEntries();
109
- return Object.values(this._inMemoryMap);
115
+ return this._inMemoryMap.values();
110
116
  }
111
117
 
112
118
  has(_key) {
@@ -9,8 +9,8 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
- import logger from './logger';
13
- import ChromeStorageMap from '../request/utils/chrome-storage-map';
12
+ import logger from './logger.js';
13
+ import ChromeStorageMap from '../request/utils/chrome-storage-map.js';
14
14
 
15
15
  function checkUserAgent(pattern) {
16
16
  return navigator.userAgent.indexOf(pattern) !== -1;
@@ -11,15 +11,14 @@
11
11
 
12
12
  import {
13
13
  VALID_RESPONSE_PROPERTIES,
14
- addListener,
15
- removeListener,
16
- } from './utils/webrequest';
14
+ default as WebRequestListenersManager,
15
+ } from './utils/webrequest.js';
17
16
 
18
- import Pipeline from './pipeline';
19
- import WebRequestContext from './webrequest-context';
20
- import PageStore from './page-store';
21
- import logger from './logger';
22
- import CnameUncloaker, { isCnameUncloakSupported } from './cname-uncloak';
17
+ import Pipeline from './pipeline.js';
18
+ import WebRequestContext from './webrequest-context.js';
19
+ import PageStore from './page-store.js';
20
+ import logger from './logger.js';
21
+ import CnameUncloaker, { isCnameUncloakSupported } from './cname-uncloak.js';
23
22
 
24
23
  function modifyHeaderByType(headers, name, value) {
25
24
  const lowerCaseName = name.toLowerCase();
@@ -94,6 +93,7 @@ export default class WebRequestPipeline {
94
93
  constructor() {
95
94
  this.initialized = false;
96
95
  this.onPageStagedListeners = new Set();
96
+ this.listenerManager = new WebRequestListenersManager();
97
97
  }
98
98
 
99
99
  enabled() {
@@ -158,7 +158,7 @@ export default class WebRequestPipeline {
158
158
  if (this.pipelines.has(event)) {
159
159
  const pipeline = this.pipelines.get(event);
160
160
  this[event] = undefined;
161
- removeListener(event, pipeline.listener);
161
+ this.listenerManager.removeListener(event, pipeline.listener);
162
162
  pipeline.pipeline.unload();
163
163
  this.pipelines.delete(event);
164
164
  }
@@ -168,7 +168,6 @@ export default class WebRequestPipeline {
168
168
  if (this.pipelines.has(event)) {
169
169
  return this.pipelines.get(event).pipeline;
170
170
  }
171
-
172
171
  // Create pipeline step
173
172
  const pipeline = new Pipeline(`webRequestPipeline.${event}`, [], false);
174
173
 
@@ -246,7 +245,7 @@ export default class WebRequestPipeline {
246
245
  // can call it: `webRequestPipeline.background.onBeforeRequest(details)`.
247
246
  this[event] = listener;
248
247
 
249
- addListener(event, listener);
248
+ this.listenerManager.addListener(event, listener);
250
249
 
251
250
  return pipeline;
252
251
  }
@@ -9,6 +9,6 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
- import { Logger } from '../logger';
12
+ import { Logger } from '../logger.js';
13
13
 
14
14
  export default Logger.get('webrequest-pipeline', { level: 'error' });
@@ -9,13 +9,13 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
- import logger from './logger';
13
- import Page, { PAGE_LOADING_STATE } from './page';
14
- import ChromeStorageMap from '../request/utils/chrome-storage-map';
15
-
16
- function makeTabContext(tab) {
17
- return new Page(tab);
18
- }
12
+ import logger from './logger.js';
13
+ import {
14
+ setActive,
15
+ create as makeTabContext,
16
+ PAGE_LOADING_STATE,
17
+ } from './page.js';
18
+ import ChromeStorageMap from '../request/utils/chrome-storage-map.js';
19
19
 
20
20
  const PAGE_TTL = 1000 * 60 * 60; // 1 hour
21
21
 
@@ -69,7 +69,10 @@ export default class PageStore {
69
69
  if (this.staged.push(page) > 5) {
70
70
  this.staged.shift();
71
71
  }
72
- page.stage();
72
+ setActive(page, false);
73
+ page.destroyed = Date.now();
74
+ // unset previous (to prevent history chain memory leak)
75
+ page.previous = undefined;
73
76
  this.notifyPageStageListeners(page);
74
77
  }
75
78
 
@@ -85,14 +88,14 @@ export default class PageStore {
85
88
  */
86
89
  onTabUpdated = (tabId, info, tab) => {
87
90
  let tabContext = this.tabs.get(tabId);
88
- if (tabContext === undefined) {
91
+ if (!tabContext) {
89
92
  tabContext = makeTabContext(tab);
90
93
  this.tabs.set(tabId, tabContext);
91
94
  }
92
95
 
93
96
  // Update `isPrivate` and `url` if available
94
97
  tabContext.isPrivate = tab.incognito;
95
- tabContext.setActive(tab.active);
98
+ setActive(tabContext, tab.active);
96
99
  if (info.url !== undefined) {
97
100
  tabContext.url = info.url;
98
101
  }
@@ -114,13 +117,13 @@ export default class PageStore {
114
117
  // otherwise, we only have to mark the previous tab as inactive
115
118
  if (!previousTabId) {
116
119
  for (const tab of this.tabs.values()) {
117
- tab.setActive(false);
120
+ setActive(tab, false);
118
121
  }
119
122
  } else if (this.tabs.has(previousTabId)) {
120
- this.tabs.get(previousTabId).setActive(false);
123
+ setActive(this.tabs.get(previousTabId), false);
121
124
  }
122
125
  if (this.tabs.has(tabId)) {
123
- this.tabs.get(tabId).setActive(true);
126
+ setActive(this.tabs.get(tabId), true);
124
127
  }
125
128
  };
126
129
 
@@ -132,9 +135,9 @@ export default class PageStore {
132
135
  return;
133
136
  }
134
137
  if (windowId === focusedWindow) {
135
- tabContext.setActive(true);
138
+ setActive(tabContext, true);
136
139
  } else {
137
- tabContext.setActive(false);
140
+ setActive(tabContext, false);
138
141
  }
139
142
  });
140
143
  });
@@ -169,7 +172,7 @@ export default class PageStore {
169
172
  });
170
173
  nextContext.previous = tabContext;
171
174
  this.tabs.set(tabId, nextContext);
172
- nextContext.updateState(PAGE_LOADING_STATE.NAVIGATING);
175
+ nextContext.state = PAGE_LOADING_STATE.NAVIGATING;
173
176
  }
174
177
  };
175
178
 
@@ -177,7 +180,7 @@ export default class PageStore {
177
180
  const { frameId, tabId } = details;
178
181
  const tabContext = this.tabs.get(tabId);
179
182
  if (frameId === 0 && tabContext) {
180
- tabContext.updateState(PAGE_LOADING_STATE.COMMITTED);
183
+ tabContext.state = PAGE_LOADING_STATE.COMMITTED;
181
184
  } else if (tabContext && !tabContext.frames[frameId]) {
182
185
  // frame created without request
183
186
  this.onSubFrame(details);
@@ -187,7 +190,7 @@ export default class PageStore {
187
190
  onNavigationComplete = ({ frameId, tabId }) => {
188
191
  const tabContext = this.tabs.get(tabId);
189
192
  if (frameId === 0 && tabContext) {
190
- tabContext.updateState(PAGE_LOADING_STATE.COMPLETE);
193
+ tabContext.state = PAGE_LOADING_STATE.COMPLETE;
191
194
  }
192
195
  };
193
196
 
@@ -198,7 +201,7 @@ export default class PageStore {
198
201
  }
199
202
  // Update last request id from the tab
200
203
  let tabContext = this.tabs.get(tabId);
201
- if (tabContext === undefined) {
204
+ if (!tabContext) {
202
205
  tabContext = makeTabContext({ url, incognito: false });
203
206
  this.tabs.set(tabId, tabContext);
204
207
  }
@@ -229,7 +232,7 @@ export default class PageStore {
229
232
  onSubFrame = (details) => {
230
233
  const { tabId, frameId, parentFrameId, url } = details;
231
234
  const tab = this.tabs.get(tabId);
232
- if (tab === undefined) {
235
+ if (!tab) {
233
236
  logger.log('Could not find tab for sub_frame request', details);
234
237
  return;
235
238
  }
@@ -16,125 +16,102 @@ export const PAGE_LOADING_STATE = {
16
16
  COMPLETE: 'complete',
17
17
  };
18
18
 
19
- export default class Page {
20
- constructor({ id, active, url, incognito, created }) {
21
- this.id = id || 0;
22
- this.url = url;
23
- this.isRedirect = false;
24
- this.isPrivate = incognito;
25
- this.isPrivateServer = false;
26
- this.created = created || Date.now();
27
- this.destroyed = null;
28
- this.lastRequestId = null;
29
- this.frames = {
30
- 0: {
31
- parentFrameId: -1,
32
- url,
33
- },
34
- };
35
- this.state = PAGE_LOADING_STATE.CREATED;
36
-
37
- this.activeTime = 0;
38
- this.activeFrom = active ? Date.now() : 0;
39
-
40
- this.requestStats = {};
41
- this.annotations = {};
42
- this.counter = 0;
43
-
44
- this.tsv = '';
45
- this.tsvId = undefined;
46
- }
47
-
48
- setActive(active) {
49
- if (active && this.activeFrom === 0) {
50
- this.activeFrom = Date.now();
51
- } else if (!active && this.activeFrom > 0) {
52
- this.activeTime += Date.now() - this.activeFrom;
53
- this.activeFrom = 0;
54
- }
55
- }
19
+ export function create({ id, active, url, incognito, created }) {
20
+ const page = {};
21
+ page.id = id || 0;
22
+ page.url = url;
23
+ page.isRedirect = false;
24
+ page.isPrivate = incognito;
25
+ page.isPrivateServer = false;
26
+ page.created = created || Date.now();
27
+ page.destroyed = null;
28
+ page.lastRequestId = null;
29
+ page.frames = {
30
+ 0: {
31
+ parentFrameId: -1,
32
+ url,
33
+ },
34
+ };
35
+ page.state = PAGE_LOADING_STATE.CREATED;
36
+
37
+ page.activeTime = 0;
38
+ page.activeFrom = active ? Date.now() : 0;
39
+
40
+ page.requestStats = {};
41
+ page.annotations = {};
42
+ page.counter = 0;
43
+
44
+ page.tsv = '';
45
+ page.tsvId = undefined;
46
+ return page;
47
+ }
56
48
 
57
- updateState(newState) {
58
- this.state = newState;
49
+ export function setActive(page, active) {
50
+ if (active && page.activeFrom === 0) {
51
+ page.activeFrom = Date.now();
52
+ } else if (!active && page.activeFrom > 0) {
53
+ page.activeTime += Date.now() - page.activeFrom;
54
+ page.activeFrom = 0;
59
55
  }
56
+ }
60
57
 
61
- stage() {
62
- this.setActive(false);
63
- this.destroyed = Date.now();
64
- // unset previous (to prevent history chain memory leak)
65
- this.previous = undefined;
58
+ export function getStatsForDomain(page, domain) {
59
+ let stats = page.requestStats[domain];
60
+ if (!stats) {
61
+ stats = {};
62
+ page.requestStats[domain] = stats;
66
63
  }
64
+ return stats;
65
+ }
67
66
 
68
- getStatsForDomain(domain) {
69
- let stats = this.requestStats[domain];
70
- if (!stats) {
71
- stats = {};
72
- this.requestStats[domain] = stats;
73
- }
74
- return stats;
75
- }
67
+ export function getFrameAncestors(page, { parentFrameId }) {
68
+ const ancestors = [];
76
69
 
77
- setTrackingStatus(status) {
78
- this.tsv = status.value;
79
- this.tsvId = status.statusId;
80
- }
70
+ // Reconstruct frame ancestors
71
+ let currentFrameId = parentFrameId;
72
+ while (currentFrameId !== -1) {
73
+ const frame = page.frames[currentFrameId];
81
74
 
82
- getFrameAncestors({ parentFrameId }) {
83
- const ancestors = [];
84
-
85
- // Reconstruct frame ancestors
86
- let currentFrameId = parentFrameId;
87
- while (currentFrameId !== -1) {
88
- const frame = this.frames[currentFrameId];
89
-
90
- // If `frame` if undefined, this means we do not have any information
91
- // about the frame associated with `currentFrameId`. This can happen if
92
- // the event for `main_frame` or `sub_frame` was not emitted from the
93
- // webRequest API for this frame; this can happen when Service Workers
94
- // are used. In this case, we consider that the parent frame is the main
95
- // frame (which is very likely the case).
96
- if (frame === undefined) {
97
- ancestors.push({
98
- frameId: 0,
99
- url: this.url,
100
- });
101
- break;
102
- }
103
-
104
- // Continue going up the ancestors chain
75
+ // If `frame` if undefined, this means we do not have any information
76
+ // about the frame associated with `currentFrameId`. This can happen if
77
+ // the event for `main_frame` or `sub_frame` was not emitted from the
78
+ // webRequest API for this frame; this can happen when Service Workers
79
+ // are used. In this case, we consider that the parent frame is the main
80
+ // frame (which is very likely the case).
81
+ if (frame === undefined) {
105
82
  ancestors.push({
106
- frameId: currentFrameId,
107
- url: frame.url,
83
+ frameId: 0,
84
+ url: page.url,
108
85
  });
109
- currentFrameId = frame.parentFrameId;
86
+ break;
110
87
  }
111
88
 
112
- return ancestors;
113
- }
114
-
115
- /**
116
- * Return the URL of top-level document (i.e.: tab URL).
117
- */
118
- getTabUrl() {
119
- return this.url;
89
+ // Continue going up the ancestors chain
90
+ ancestors.push({
91
+ frameId: currentFrameId,
92
+ url: frame.url,
93
+ });
94
+ currentFrameId = frame.parentFrameId;
120
95
  }
121
96
 
122
- /**
123
- * Return the URL of the frame.
124
- */
125
- getFrameUrl(context) {
126
- const { frameId } = context;
97
+ return ancestors;
98
+ }
127
99
 
128
- const frame = this.frames[frameId];
100
+ /**
101
+ * Return the URL of the frame.
102
+ */
103
+ export function getFrameUrl(page, context) {
104
+ const { frameId } = context;
129
105
 
130
- // In some cases, frame creation does not trigger a webRequest event (e.g.:
131
- // if the iframe is specified in the HTML of the page directly). In this
132
- // case we try to fall-back to something else: documentUrl, originUrl,
133
- // initiator.
134
- if (frame === undefined) {
135
- return context.documentUrl || context.originUrl || context.initiator;
136
- }
106
+ const frame = page.frames[frameId];
137
107
 
138
- return frame.url;
108
+ // In some cases, frame creation does not trigger a webRequest event (e.g.:
109
+ // if the iframe is specified in the HTML of the page directly). In this
110
+ // case we try to fall-back to something else: documentUrl, originUrl,
111
+ // initiator.
112
+ if (frame === undefined) {
113
+ return context.documentUrl || context.originUrl || context.initiator;
139
114
  }
115
+
116
+ return frame.url;
140
117
  }
@@ -9,7 +9,7 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
- import logger from './logger';
12
+ import logger from './logger.js';
13
13
 
14
14
  /**
15
15
  * Handles a set of function pipelines. These pipelines start with an initial state
@@ -9,7 +9,7 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
- import logger from '../logger';
12
+ import logger from '../logger.js';
13
13
 
14
14
  export const VALID_RESPONSE_PROPERTIES = {
15
15
  onBeforeRequest: ['cancel', 'redirectUrl'],
@@ -21,10 +21,6 @@ export const VALID_RESPONSE_PROPERTIES = {
21
21
  onErrorOccurred: [],
22
22
  };
23
23
 
24
- const HAS_WEB_REQUEST_BLOCKING = chrome?.runtime
25
- ?.getManifest()
26
- ?.permissions.includes('webRequestBlocking');
27
-
28
24
  function getOptionArray(options) {
29
25
  if (!options) {
30
26
  return [];
@@ -41,73 +37,83 @@ function getOptionArray(options) {
41
37
  // options.REQUEST_BODY,
42
38
  ];
43
39
 
44
- if (HAS_WEB_REQUEST_BLOCKING) {
40
+ if (
41
+ chrome?.runtime?.getManifest()?.permissions.includes('webRequestBlocking')
42
+ ) {
45
43
  optionsSubset.push(options.BLOCKING);
46
44
  }
47
45
 
48
46
  return optionsSubset.filter((o) => !!o);
49
47
  }
50
48
 
51
- // build allowed extraInfo options from <Step>Options objects.
52
- export const EXTRA_INFO_SPEC = {
53
- onBeforeRequest: getOptionArray(chrome.webRequest.OnBeforeRequestOptions),
54
- onBeforeSendHeaders: getOptionArray(
55
- chrome.webRequest.OnBeforeSendHeadersOptions,
56
- ),
57
- onHeadersReceived: getOptionArray(chrome.webRequest.OnHeadersReceivedOptions),
58
- onAuthRequired: getOptionArray(chrome.webRequest.OnAuthRequiredOptions),
59
- onBeforeRedirect: getOptionArray(chrome.webRequest.OnBeforeRedirectOptions),
60
- onCompleted: getOptionArray(chrome.webRequest.OnCompletedOptions),
61
- onErrorOccurred: undefined,
62
- };
63
-
64
- const HANDLERS = {};
65
49
  const urls = ['http://*/*', 'https://*/*'];
66
50
 
67
- for (const event of Object.keys(EXTRA_INFO_SPEC)) {
68
- // It might be that the platform does not support all listeners:
69
- if (chrome.webRequest[event] === undefined) {
70
- logger.warn(`chrome.webRequest.${event} is not supported`);
71
- continue;
72
- }
51
+ export default class WebRequestListenersManager {
52
+ constructor() {
53
+ this.HANDLERS = {};
54
+ // build allowed extraInfo options from <Step>Options objects.
55
+ const EXTRA_INFO_SPEC = {
56
+ onBeforeRequest: getOptionArray(chrome.webRequest.OnBeforeRequestOptions),
57
+ onBeforeSendHeaders: getOptionArray(
58
+ chrome.webRequest.OnBeforeSendHeadersOptions,
59
+ ),
60
+ onHeadersReceived: getOptionArray(
61
+ chrome.webRequest.OnHeadersReceivedOptions,
62
+ ),
63
+ onAuthRequired: getOptionArray(chrome.webRequest.OnAuthRequiredOptions),
64
+ onBeforeRedirect: getOptionArray(
65
+ chrome.webRequest.OnBeforeRedirectOptions,
66
+ ),
67
+ onCompleted: getOptionArray(chrome.webRequest.OnCompletedOptions),
68
+ onErrorOccurred: undefined,
69
+ };
70
+
71
+ for (const event of Object.keys(EXTRA_INFO_SPEC)) {
72
+ // It might be that the platform does not support all listeners:
73
+ if (chrome.webRequest[event] === undefined) {
74
+ logger.warn(`chrome.webRequest.${event} is not supported`);
75
+ continue;
76
+ }
73
77
 
74
- // Get allowed options for this event (e.g.: 'blocking', 'requestHeaders',
75
- // etc.)
76
- const extraInfoSpec = EXTRA_INFO_SPEC[event];
78
+ // Get allowed options for this event (e.g.: 'blocking', 'requestHeaders',
79
+ // etc.)
80
+ const extraInfoSpec = EXTRA_INFO_SPEC[event];
77
81
 
78
- let firstCall = true;
79
- const callback = (...args) => {
80
- if (!HANDLERS[event]) {
81
- if (firstCall) {
82
- firstCall = false;
83
- logger.info(
84
- `webRequest.${event} called without listener being assigned`,
85
- );
82
+ let firstCall = true;
83
+ const callback = (...args) => {
84
+ if (!this.HANDLERS[event]) {
85
+ if (firstCall) {
86
+ firstCall = false;
87
+ logger.info(
88
+ `webRequest.${event} called without listener being assigned`,
89
+ );
90
+ }
91
+ return;
92
+ }
93
+ return this.HANDLERS[event](...args);
94
+ };
95
+
96
+ if (extraInfoSpec === undefined) {
97
+ chrome.webRequest[event].addListener(callback, { urls });
98
+ } else {
99
+ chrome.webRequest[event].addListener(callback, { urls }, extraInfoSpec);
86
100
  }
87
- return;
88
101
  }
89
- return HANDLERS[event](...args);
90
- };
91
-
92
- if (extraInfoSpec === undefined) {
93
- chrome.webRequest[event].addListener(callback, { urls });
94
- } else {
95
- chrome.webRequest[event].addListener(callback, { urls }, extraInfoSpec);
96
102
  }
97
- }
98
103
 
99
- export function addListener(event, listener) {
100
- if (HANDLERS[event]) {
101
- throw new Error(
102
- `webRequest.${event} expects only one listener as this all WebRequestPipeline should need`,
103
- );
104
+ addListener(event, listener) {
105
+ if (this.HANDLERS[event]) {
106
+ throw new Error(
107
+ `webRequest.${event} expects only one listener as this all WebRequestPipeline should need`,
108
+ );
109
+ }
110
+ this.HANDLERS[event] = listener;
104
111
  }
105
- HANDLERS[event] = listener;
106
- }
107
112
 
108
- export function removeListener(event, listener) {
109
- if (HANDLERS[event] !== listener) {
110
- throw new Error(`webRequest.${event} trying to remove wrong listener`);
113
+ removeListener(event, listener) {
114
+ if (this.HANDLERS[event] !== listener) {
115
+ throw new Error(`webRequest.${event} trying to remove wrong listener`);
116
+ }
117
+ this.HANDLERS[event] = null;
111
118
  }
112
- HANDLERS[event] = null;
113
119
  }
@@ -9,8 +9,9 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
- import { parse } from '../utils/url';
13
- import logger from './logger';
12
+ import { parse } from '../utils/url.js';
13
+ import logger from './logger.js';
14
+ import { getFrameUrl, getFrameAncestors } from './page.js';
14
15
 
15
16
  /**
16
17
  * Transform an array of headers (i.e.: `{ name, value }`) into a `Map`.
@@ -61,13 +62,13 @@ export default class WebRequestContext {
61
62
  // **Chromium addition**
62
63
  // frameAncestors
63
64
  if (context.frameAncestors === undefined) {
64
- context.frameAncestors = page ? page.getFrameAncestors(context) : [];
65
+ context.frameAncestors = page ? getFrameAncestors(page, context) : [];
65
66
  }
66
67
 
67
68
  // Cliqz-specific extensions to webRequest details
68
69
  context.page = page;
69
- context.tabUrl = context.tabUrl || (page && page.getTabUrl());
70
- context.frameUrl = context.frameUrl || (page && page.getFrameUrl(context));
70
+ context.tabUrl = context.tabUrl || (page && page.url);
71
+ context.frameUrl = context.frameUrl || (page && getFrameUrl(page, context));
71
72
  context.isPrivate = page ? page.isPrivate : null;
72
73
  context.isMainFrame = context.type === 'main_frame';
73
74
  context.isRedirect = page && context.isMainFrame && page.isRedirect;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * WhoTracks.Me
3
+ * https://ghostery.com/whotracksme
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 * as chai from 'chai';
13
+ import sinonChai from 'sinon-chai';
14
+ import chaiAsPromised from 'chai-as-promised';
15
+
16
+ chai.use(chaiAsPromised);
17
+ chai.use(sinonChai);
@@ -0,0 +1,62 @@
1
+ /**
2
+ * WhoTracks.Me
3
+ * https://ghostery.com/whotracksme
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 chrome from 'sinon-chrome';
13
+ import { expect } from 'chai';
14
+
15
+ import WebRequestPipeline from '../../src/webrequest-pipeline/index.js';
16
+
17
+ describe('WebRequestPipeline', function () {
18
+ before(function () {
19
+ chrome.storage.session = chrome.storage.local;
20
+ globalThis.chrome = chrome;
21
+ });
22
+
23
+ beforeEach(function () {
24
+ chrome.flush();
25
+ chrome.storage.session.get.yields({});
26
+ });
27
+
28
+ after(function () {
29
+ chrome.flush();
30
+ delete globalThis.chrome;
31
+ });
32
+
33
+ context('PageStore', function () {
34
+ it('starts empty', function () {
35
+ const pipeline = new WebRequestPipeline();
36
+ pipeline.init();
37
+ expect(pipeline.pageStore.tabs.countNonExpiredKeys()).to.be.equal(0);
38
+ });
39
+
40
+ context('on webRequest.onBeforeRequest', function () {
41
+ it('creates a page', function () {
42
+ const pipeline = new WebRequestPipeline();
43
+ pipeline.init();
44
+ pipeline.addPipelineStep('onBeforeRequest', {
45
+ name: 'test',
46
+ spec: 'annotate',
47
+ fn: () => {},
48
+ });
49
+ const details = {
50
+ tabId: 1,
51
+ url: 'https://example.com',
52
+ type: 'main_frame',
53
+ };
54
+ chrome.webRequest.onBeforeRequest.dispatch(details);
55
+ expect(pipeline.pageStore.tabs.has(details.tabId)).to.be.true;
56
+ expect(pipeline.pageStore.tabs.get(details.tabId)).to.deep.include({
57
+ url: details.url,
58
+ });
59
+ });
60
+ });
61
+ });
62
+ });
@@ -0,0 +1,135 @@
1
+ /**
2
+ * WhoTracks.Me
3
+ * https://ghostery.com/whotracksme
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 chrome from 'sinon-chrome';
13
+ import { mock } from 'sinon';
14
+ import { expect } from 'chai';
15
+
16
+ import PageStore from '../../src/webrequest-pipeline/page-store.js';
17
+ import { PAGE_LOADING_STATE } from '../../src/webrequest-pipeline/page.js';
18
+
19
+ describe('PageStore', function () {
20
+ before(function () {
21
+ chrome.storage.session = chrome.storage.local;
22
+ globalThis.chrome = chrome;
23
+ });
24
+
25
+ beforeEach(function () {
26
+ chrome.flush();
27
+ chrome.storage.session.get.yields({});
28
+ });
29
+
30
+ after(function () {
31
+ chrome.flush();
32
+ delete globalThis.chrome;
33
+ });
34
+
35
+ it('starts with empty tabs', async function () {
36
+ const store = new PageStore({});
37
+ await store.init();
38
+ expect(store.tabs.countNonExpiredKeys()).to.be.equal(0);
39
+ });
40
+
41
+ context('on chrome.tabs.onCreated', function () {
42
+ it('creates a page', async function () {
43
+ const store = new PageStore({});
44
+ await store.init();
45
+ const tab = { id: 1 };
46
+ chrome.tabs.onCreated.dispatch(tab);
47
+ expect(store.tabs.has(tab.id)).to.be.true;
48
+ expect(store.tabs.get(tab.id)).to.deep.include({
49
+ id: tab.id,
50
+ });
51
+ });
52
+ });
53
+
54
+ context('on chrome.tabs.onUpdated', function () {
55
+ it('creates a page', async function () {
56
+ const store = new PageStore({});
57
+ await store.init();
58
+ const tab = { id: 1 };
59
+ chrome.tabs.onUpdated.dispatch(tab.id, {}, tab);
60
+ expect(store.tabs.has(tab.id)).to.be.true;
61
+ expect(store.tabs.get(tab.id)).to.deep.include({
62
+ id: tab.id,
63
+ });
64
+ });
65
+
66
+ it('updates a page', async function () {
67
+ const store = new PageStore({});
68
+ await store.init();
69
+ const tab = { id: 1 };
70
+ chrome.tabs.onCreated.dispatch(tab);
71
+ expect(store.tabs.has(tab.id)).to.be.true;
72
+ expect(store.tabs.get(tab.id)).to.deep.include({
73
+ id: tab.id,
74
+ });
75
+ expect(store.tabs.get(tab.id)).to.have.property('url', undefined);
76
+ chrome.tabs.onUpdated.dispatch(tab.id, { url: 'about:blank' }, tab);
77
+ expect(store.tabs.get(tab.id)).to.have.property('url', 'about:blank');
78
+ });
79
+ });
80
+
81
+ context('on chrome.webNavigation.onBeforeNavigate', function () {
82
+ it('creates a page', async function () {
83
+ const store = new PageStore({});
84
+ await store.init();
85
+ const details = { tabId: 1, frameId: 0, url: 'about:blank' };
86
+ chrome.webNavigation.onBeforeNavigate.dispatch(details);
87
+ expect(store.tabs.has(details.tabId)).to.be.true;
88
+ expect(store.tabs.get(details.tabId)).to.deep.include({
89
+ id: details.tabId,
90
+ url: details.url,
91
+ });
92
+ });
93
+
94
+ it('stages the page', async function () {
95
+ const listener = mock();
96
+ const store = new PageStore({ notifyPageStageListeners: listener });
97
+ await store.init();
98
+ const details = {
99
+ tabId: 1,
100
+ frameId: 0,
101
+ url: 'about:blank',
102
+ timeStamp: Date.now(),
103
+ };
104
+ chrome.webNavigation.onBeforeNavigate.dispatch(details);
105
+ expect(listener).to.not.have.been.called;
106
+ const page = store.tabs.get(details.tabId);
107
+ page.state = PAGE_LOADING_STATE.COMPLETE;
108
+ chrome.webNavigation.onBeforeNavigate.dispatch({
109
+ ...details,
110
+ timeStamp: details.timeStamp + 300,
111
+ });
112
+ expect(listener).to.have.been.calledWith(page);
113
+ });
114
+
115
+ it('ignore duplicates', async function () {
116
+ const listener = mock();
117
+ const store = new PageStore({ notifyPageStageListeners: listener });
118
+ await store.init();
119
+ const details = {
120
+ tabId: 1,
121
+ frameId: 0,
122
+ url: 'about:blank',
123
+ timeStamp: Date.now(),
124
+ };
125
+ chrome.webNavigation.onBeforeNavigate.dispatch(details);
126
+ expect(listener).to.not.have.been.called;
127
+ store.tabs.get(details.tabId).state = PAGE_LOADING_STATE.COMPLETE;
128
+ chrome.webNavigation.onBeforeNavigate.dispatch({
129
+ ...details,
130
+ timeStamp: details.timeStamp + 1,
131
+ });
132
+ expect(listener).to.not.have.been.called;
133
+ });
134
+ });
135
+ });