@whotracksme/reporting 5.1.17

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.
Files changed (179) hide show
  1. package/.editorconfig +12 -0
  2. package/.eslintignore +3 -0
  3. package/.eslintrc +16 -0
  4. package/.github/workflows/release.yml +34 -0
  5. package/.github/workflows/tests.yml +20 -0
  6. package/.prettierrc +9 -0
  7. package/.tool-versions +1 -0
  8. package/CHANGELOG.md +795 -0
  9. package/LICENSE +373 -0
  10. package/README.md +1 -0
  11. package/communication/README.md +11 -0
  12. package/communication/example/index.js +43 -0
  13. package/communication/example/manifest.json +16 -0
  14. package/communication/karma.conf.cjs +19 -0
  15. package/communication/package.json +52 -0
  16. package/communication/rollup.common-config.cjs +17 -0
  17. package/communication/rollup.config.cjs +10 -0
  18. package/communication/src/encoding.js +54 -0
  19. package/communication/src/errors.js +84 -0
  20. package/communication/src/index.js +76 -0
  21. package/communication/src/logger.js +41 -0
  22. package/communication/src/padding.js +60 -0
  23. package/communication/src/proxied-http.js +231 -0
  24. package/communication/src/server-public-key-accessor.js +123 -0
  25. package/communication/src/timestamps.js +37 -0
  26. package/communication/src/trusted-clock.js +58 -0
  27. package/communication/src/utils.js +28 -0
  28. package/communication/src/zlib.js +17 -0
  29. package/communication/test/helpers/in-memory-database.js +43 -0
  30. package/communication/test/server-public-key-accessor.spec.js +135 -0
  31. package/communication/test/utils.spec.js +43 -0
  32. package/package.json +50 -0
  33. package/reporting/TODO.md +2 -0
  34. package/reporting/assets/request/bloom_filter.dat +0 -0
  35. package/reporting/assets/request/update.json +1 -0
  36. package/reporting/example/content.js +11 -0
  37. package/reporting/example/index.js +132 -0
  38. package/reporting/example/inspector/index.html +17 -0
  39. package/reporting/example/inspector/index.js +27 -0
  40. package/reporting/example/manifests/chromium.json +37 -0
  41. package/reporting/example/manifests/firefox.json +35 -0
  42. package/reporting/example/rules.json +62 -0
  43. package/reporting/example/setup.js +1 -0
  44. package/reporting/example/tests/test1.html +10 -0
  45. package/reporting/karma.conf.cjs +22 -0
  46. package/reporting/package.json +63 -0
  47. package/reporting/rollup.common-config.cjs +19 -0
  48. package/reporting/rollup.config.cjs +20 -0
  49. package/reporting/src/LRU.js +149 -0
  50. package/reporting/src/activity-estimator.js +298 -0
  51. package/reporting/src/alive-check.js +139 -0
  52. package/reporting/src/alive-message-generator.js +142 -0
  53. package/reporting/src/bloom-filters.js +345 -0
  54. package/reporting/src/country-provider.js +295 -0
  55. package/reporting/src/cyrb53.js +32 -0
  56. package/reporting/src/digest.js +33 -0
  57. package/reporting/src/doublefetch-page-handler.js +548 -0
  58. package/reporting/src/duplicate-detector.js +233 -0
  59. package/reporting/src/errors.js +84 -0
  60. package/reporting/src/event-listener-queue.js +121 -0
  61. package/reporting/src/fixed-size-cache.js +63 -0
  62. package/reporting/src/hash-detector.js +1526 -0
  63. package/reporting/src/html-parser.js +17 -0
  64. package/reporting/src/http.js +265 -0
  65. package/reporting/src/index.js +14 -0
  66. package/reporting/src/job-scheduler.js +912 -0
  67. package/reporting/src/logger.js +121 -0
  68. package/reporting/src/md5.js +334 -0
  69. package/reporting/src/message-sender.js +51 -0
  70. package/reporting/src/network.js +140 -0
  71. package/reporting/src/new-page-approver.js +119 -0
  72. package/reporting/src/page-aggregator.js +185 -0
  73. package/reporting/src/page-quorum-check-handler.js +200 -0
  74. package/reporting/src/page-structure.js +136 -0
  75. package/reporting/src/pagedb.js +671 -0
  76. package/reporting/src/pages.js +1798 -0
  77. package/reporting/src/patterns-updater.js +310 -0
  78. package/reporting/src/patterns.js +416 -0
  79. package/reporting/src/persisted-bitarray.js +265 -0
  80. package/reporting/src/persisted-hashes.js +189 -0
  81. package/reporting/src/quorum-checker.js +327 -0
  82. package/reporting/src/random.js +39 -0
  83. package/reporting/src/reporting.js +290 -0
  84. package/reporting/src/request/config.js +116 -0
  85. package/reporting/src/request/content-script.js +77 -0
  86. package/reporting/src/request/database.js +147 -0
  87. package/reporting/src/request/dnt.js +24 -0
  88. package/reporting/src/request/hash.js +101 -0
  89. package/reporting/src/request/index.js +874 -0
  90. package/reporting/src/request/page-telemetry.js +42 -0
  91. package/reporting/src/request/qs-whitelist2.js +247 -0
  92. package/reporting/src/request/resources/prob.js +601 -0
  93. package/reporting/src/request/steps/block-rules.js +40 -0
  94. package/reporting/src/request/steps/check-context.js +37 -0
  95. package/reporting/src/request/steps/cookie-context.js +209 -0
  96. package/reporting/src/request/steps/oauth-detector.js +101 -0
  97. package/reporting/src/request/steps/page-logger.js +177 -0
  98. package/reporting/src/request/steps/redirect-tagger.js +75 -0
  99. package/reporting/src/request/steps/subdomain-check.js +34 -0
  100. package/reporting/src/request/steps/token-checker/index.js +189 -0
  101. package/reporting/src/request/steps/token-checker/token-domain.js +129 -0
  102. package/reporting/src/request/steps/token-examiner.js +182 -0
  103. package/reporting/src/request/steps/token-telemetry/cached-entry-pipeline.js +210 -0
  104. package/reporting/src/request/steps/token-telemetry/index.js +234 -0
  105. package/reporting/src/request/steps/token-telemetry/key-pipeline.js +109 -0
  106. package/reporting/src/request/steps/token-telemetry/token-pipeline.js +105 -0
  107. package/reporting/src/request/time.js +73 -0
  108. package/reporting/src/request/utils/bloom-filter-packed.js +107 -0
  109. package/reporting/src/request/utils/chrome-storage-map.js +282 -0
  110. package/reporting/src/request/utils/subject.js +37 -0
  111. package/reporting/src/request/utils/temp-set.js +56 -0
  112. package/reporting/src/request/utils/tlds.js +55 -0
  113. package/reporting/src/request/utils.js +41 -0
  114. package/reporting/src/request-reporter.js +111 -0
  115. package/reporting/src/sanitizer.js +519 -0
  116. package/reporting/src/search-extractor.js +338 -0
  117. package/reporting/src/self-check.js +105 -0
  118. package/reporting/src/seq-executor.js +43 -0
  119. package/reporting/src/session-storage.js +399 -0
  120. package/reporting/src/url-analyzer.js +161 -0
  121. package/reporting/src/url-cleaner.js +60 -0
  122. package/reporting/src/utils/pacemaker.js +279 -0
  123. package/reporting/src/utils/url.js +114 -0
  124. package/reporting/src/utils.js +345 -0
  125. package/reporting/src/webrequest-pipeline/cname-uncloak.js +110 -0
  126. package/reporting/src/webrequest-pipeline/index.js +287 -0
  127. package/reporting/src/webrequest-pipeline/logger.js +14 -0
  128. package/reporting/src/webrequest-pipeline/page-store.js +282 -0
  129. package/reporting/src/webrequest-pipeline/page.js +140 -0
  130. package/reporting/src/webrequest-pipeline/pipeline.js +249 -0
  131. package/reporting/src/webrequest-pipeline/utils/webrequest.js +113 -0
  132. package/reporting/src/webrequest-pipeline/webrequest-context.js +153 -0
  133. package/reporting/test/README.md +2 -0
  134. package/reporting/test/activity-estimator.spec.js +356 -0
  135. package/reporting/test/alive-check.spec.js +156 -0
  136. package/reporting/test/alive-message-generator.spec.js +186 -0
  137. package/reporting/test/country-provider.spec.js +263 -0
  138. package/reporting/test/doublefetch-page-handler.spec.js +818 -0
  139. package/reporting/test/duplicate-detector.spec.js +689 -0
  140. package/reporting/test/helpers/dom-parsers.js +41 -0
  141. package/reporting/test/helpers/fake-session-storage.js +69 -0
  142. package/reporting/test/helpers/fast-check-utils.js +28 -0
  143. package/reporting/test/helpers/fetch-mock.js +57 -0
  144. package/reporting/test/helpers/in-memory-database.js +14 -0
  145. package/reporting/test/helpers/memory-map.js +72 -0
  146. package/reporting/test/helpers/pagedb-mocks.js +41 -0
  147. package/reporting/test/index.js +47 -0
  148. package/reporting/test/job-scheduler.spec.js +691 -0
  149. package/reporting/test/network.spec.js +72 -0
  150. package/reporting/test/page-aggregator.spec.js +104 -0
  151. package/reporting/test/page-quorum-check-handler.spec.js +86 -0
  152. package/reporting/test/pagedb.spec.js +250 -0
  153. package/reporting/test/pages.spec.js +693 -0
  154. package/reporting/test/patterns-updater.spec.js +446 -0
  155. package/reporting/test/patterns.spec.js +751 -0
  156. package/reporting/test/persisted-hashes.spec.js +169 -0
  157. package/reporting/test/reporting.spec.js +205 -0
  158. package/reporting/test/request/database.spec.js +59 -0
  159. package/reporting/test/request/hash.spec.js +108 -0
  160. package/reporting/test/request/index.spec.js +378 -0
  161. package/reporting/test/request/qs-whitelist2.spec.js +189 -0
  162. package/reporting/test/request/steps/check-context.spec.js +51 -0
  163. package/reporting/test/request/steps/oauth-detector.spec.js +339 -0
  164. package/reporting/test/request/test-pages.js +1246 -0
  165. package/reporting/test/request/utils/bloom-filter-packed.spec.js +37 -0
  166. package/reporting/test/request/utils/chrome-storage-map.spec.js +28 -0
  167. package/reporting/test/request/utils/tldts.spec.js +62 -0
  168. package/reporting/test/request/utils.spec.js +168 -0
  169. package/reporting/test/sanitizer.spec.js +1087 -0
  170. package/reporting/test/search-extractor.spec.js +590 -0
  171. package/reporting/test/seq-executor.spec.js +158 -0
  172. package/reporting/test/session-storage.spec.js +400 -0
  173. package/reporting/test/setup.js +24 -0
  174. package/reporting/test/url-analyzer.spec.js +451 -0
  175. package/reporting/test/url-cleaner.spec.js +102 -0
  176. package/reporting/test/utils/pacemaker.spec.js +222 -0
  177. package/reporting/test/utils/url.spec.js +660 -0
  178. package/reporting/test/utils.spec.js +299 -0
  179. package/reporting/test/webrequest-pipeline/pipeline.spec.js +251 -0
@@ -0,0 +1,287 @@
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 {
13
+ VALID_RESPONSE_PROPERTIES,
14
+ addListener,
15
+ removeListener,
16
+ } from './utils/webrequest';
17
+
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';
23
+
24
+ function modifyHeaderByType(headers, name, value) {
25
+ const lowerCaseName = name.toLowerCase();
26
+ const filteredHeaders = headers.filter(
27
+ (h) => h.name.toLowerCase() !== lowerCaseName,
28
+ );
29
+ if (value) {
30
+ filteredHeaders.push({ name, value });
31
+ }
32
+ return filteredHeaders;
33
+ }
34
+
35
+ /**
36
+ * Small abstraction on top of blocking responses expected by WebRequest API. It
37
+ * provides a few helpers to block, redirect or modify headers. It is also able
38
+ * to create a valid blocking response taking into account platform-specific
39
+ * allowed capabilities.
40
+ */
41
+ class BlockingResponse {
42
+ constructor(details) {
43
+ this.details = details;
44
+
45
+ // Blocking response
46
+ this.redirectUrl = undefined;
47
+ this.cancel = undefined;
48
+ this.responseHeaders = undefined;
49
+ this.requestHeaders = undefined;
50
+ this.shouldIncrementCounter = undefined;
51
+ }
52
+
53
+ redirectTo(url) {
54
+ this.redirectUrl = url;
55
+ }
56
+
57
+ block() {
58
+ this.cancel = true;
59
+ }
60
+
61
+ modifyHeader(name, value) {
62
+ this.requestHeaders = modifyHeaderByType(
63
+ this.requestHeaders || this.details.requestHeaders || [],
64
+ name,
65
+ value,
66
+ );
67
+ }
68
+
69
+ modifyResponseHeader(name, value) {
70
+ this.responseHeaders = modifyHeaderByType(
71
+ this.responseHeaders || this.details.responseHeaders || [],
72
+ name,
73
+ value,
74
+ );
75
+ }
76
+
77
+ toWebRequestResponse(event) {
78
+ const allowedProperties = VALID_RESPONSE_PROPERTIES[event];
79
+ const response = {};
80
+
81
+ for (let i = 0; i < allowedProperties.length; i += 1) {
82
+ const prop = allowedProperties[i];
83
+ const value = this[prop];
84
+ if (value !== undefined) {
85
+ response[prop] = value;
86
+ }
87
+ }
88
+
89
+ return response;
90
+ }
91
+ }
92
+
93
+ export default class WebRequestPipeline {
94
+ constructor() {
95
+ this.initialized = false;
96
+ this.onPageStagedListeners = new Set();
97
+ }
98
+
99
+ enabled() {
100
+ return true;
101
+ }
102
+
103
+ init(_settings, browser) {
104
+ // Optionally enable CNAME-uncloaking.
105
+ this.cnameUncloaker = isCnameUncloakSupported(browser)
106
+ ? new CnameUncloaker(browser.dns.resolve)
107
+ : null;
108
+
109
+ if (this.initialized) {
110
+ return;
111
+ }
112
+
113
+ this.pipelines = new Map();
114
+ this.pageStore = new PageStore({
115
+ notifyPageStageListeners: this.notifyPageStageListeners.bind(this),
116
+ });
117
+ this.pageStore.init();
118
+
119
+ this.initialized = true;
120
+ }
121
+
122
+ unload() {
123
+ if (!this.initialized) {
124
+ return;
125
+ }
126
+
127
+ this.onPageStagedListeners.clear();
128
+
129
+ if (this.cnameUncloaker !== null) {
130
+ this.cnameUncloaker.unload();
131
+ this.cnameUncloaker = null;
132
+ }
133
+
134
+ // Remove webrequest listeners
135
+ this.pipelines.forEach((pipeline, event) => {
136
+ this.unloadPipeline(event);
137
+ });
138
+
139
+ this.pageStore.unload();
140
+ this.initialized = false;
141
+ }
142
+
143
+ addOnPageStageListener(listener) {
144
+ this.onPageStagedListeners.add(listener);
145
+ }
146
+
147
+ notifyPageStageListeners(page) {
148
+ this.onPageStagedListeners.forEach((listener) => {
149
+ try {
150
+ listener(page);
151
+ } catch (e) {
152
+ logger.error('Page stage listener failed', e);
153
+ }
154
+ });
155
+ }
156
+
157
+ unloadPipeline(event) {
158
+ if (this.pipelines.has(event)) {
159
+ const pipeline = this.pipelines.get(event);
160
+ this[event] = undefined;
161
+ removeListener(event, pipeline.listener);
162
+ pipeline.pipeline.unload();
163
+ this.pipelines.delete(event);
164
+ }
165
+ }
166
+
167
+ getPipeline(event) {
168
+ if (this.pipelines.has(event)) {
169
+ return this.pipelines.get(event).pipeline;
170
+ }
171
+
172
+ // Create pipeline step
173
+ const pipeline = new Pipeline(`webRequestPipeline.${event}`, [], false);
174
+
175
+ // Register listener for this event
176
+ const listener = (details) => {
177
+ const webRequestContext = WebRequestContext.fromDetails(
178
+ details,
179
+ this.pageStore,
180
+ event,
181
+ );
182
+
183
+ // Request is not supported, so do not alter
184
+ if (webRequestContext === null) {
185
+ logger.debug('Ignore unsupported request', details);
186
+ return {};
187
+ }
188
+
189
+ const response = new BlockingResponse(details);
190
+
191
+ // Optionally uncloack first-party CNAME to uncover 1st-party tracking.
192
+ // This feature can only be enabled in the following cases:
193
+ //
194
+ // 1. `browser.dns` API is available (feature-detection)
195
+ // 2. webRequest supports async response (Firefox)
196
+ if (
197
+ // Will be set if uncloaking is supported on this platform (check
198
+ // background `init(...)` for more details).
199
+ this.cnameUncloaker !== null &&
200
+ // We ignore 'main_frame' to make sure we do not introduce any latency
201
+ // on the main request (because of DNS resolve) and also because we do
202
+ // not expect any privacy leak from this first request.
203
+ webRequestContext.type !== 'main_frame' &&
204
+ // Check that request is 1st-party
205
+ webRequestContext.urlParts !== null &&
206
+ webRequestContext.tabUrlParts !== null &&
207
+ webRequestContext.tabUrlParts.generalDomain ===
208
+ webRequestContext.urlParts.generalDomain &&
209
+ // Check that hostname is not the same as general domain (we need a subdomain)
210
+ webRequestContext.urlParts.hostname !==
211
+ webRequestContext.urlParts.generalDomain
212
+ ) {
213
+ const cnameResult = this.cnameUncloaker.resolveCNAME(
214
+ webRequestContext.urlParts.hostname,
215
+ );
216
+
217
+ // Synchronous response means that the CNAME was cached.
218
+ if (typeof cnameResult === 'string') {
219
+ if (cnameResult !== '') {
220
+ webRequestContext.setCNAME(cnameResult);
221
+ }
222
+ pipeline.safeExecute(webRequestContext, response, true);
223
+ return response.toWebRequestResponse(event);
224
+ }
225
+
226
+ // Otherwise it's a promise and we wait for CNAME before processing.
227
+ return cnameResult.then((cname) => {
228
+ if (cnameResult !== '') {
229
+ webRequestContext.setCNAME(cname);
230
+ }
231
+ pipeline.safeExecute(webRequestContext, response, true);
232
+ return response.toWebRequestResponse(event);
233
+ });
234
+ }
235
+
236
+ pipeline.safeExecute(webRequestContext, response, true);
237
+ return response.toWebRequestResponse(event);
238
+ };
239
+
240
+ this.pipelines.set(event, {
241
+ pipeline,
242
+ listener,
243
+ });
244
+
245
+ // Register the event listener as an attribute of background so that we
246
+ // can call it: `webRequestPipeline.background.onBeforeRequest(details)`.
247
+ this[event] = listener;
248
+
249
+ addListener(event, listener);
250
+
251
+ return pipeline;
252
+ }
253
+
254
+ addPipelineStep(stage, opts) {
255
+ if (this.initialized) {
256
+ const pipeline = this.getPipeline(stage);
257
+ if (pipeline === null) {
258
+ logger.error('WebRequest pipeline (add) does not have stage', stage);
259
+ } else {
260
+ pipeline.addPipelineStep(opts);
261
+ }
262
+ }
263
+ }
264
+
265
+ removePipelineStep(stage, name) {
266
+ if (this.initialized) {
267
+ const pipeline = this.getPipeline(stage);
268
+
269
+ if (pipeline === null) {
270
+ logger.error('WebRequest pipeline (remove) does not have stage', stage);
271
+ } else {
272
+ pipeline.removePipelineStep(name);
273
+ if (pipeline.length === 0) {
274
+ this.unloadPipeline(stage);
275
+ }
276
+ }
277
+ }
278
+ }
279
+
280
+ getPageStore() {
281
+ return this.pageStore;
282
+ }
283
+
284
+ getPageForTab(tabId) {
285
+ return this.pageStore.tabs.get(tabId);
286
+ }
287
+ }
@@ -0,0 +1,14 @@
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
+
14
+ export default Logger.get('webrequest-pipeline', { level: 'error' });
@@ -0,0 +1,282 @@
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 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
+ }
19
+
20
+ const PAGE_TTL = 1000 * 60 * 60; // 1 hour
21
+
22
+ export default class PageStore {
23
+ constructor({ notifyPageStageListeners }) {
24
+ this.tabs = new ChromeStorageMap({
25
+ storageKey: 'wtm-url-reporting:page-store:tabs',
26
+ ttlInMs: PAGE_TTL,
27
+ });
28
+ this.staged = [];
29
+ this.notifyPageStageListeners = notifyPageStageListeners;
30
+ }
31
+
32
+ async init() {
33
+ await this.tabs.isReady;
34
+ chrome.tabs.onCreated.addListener(this.onTabCreated);
35
+ chrome.tabs.onUpdated.addListener(this.onTabUpdated);
36
+ chrome.tabs.onRemoved.addListener(this.onTabRemoved);
37
+ chrome.tabs.onActivated.addListener(this.onTabActivated);
38
+ chrome.webNavigation.onBeforeNavigate.addListener(this.onBeforeNavigate);
39
+ chrome.webNavigation.onCommitted.addListener(this.onNavigationCommitted);
40
+ chrome.webNavigation.onCompleted.addListener(this.onNavigationComplete);
41
+ if (chrome.windows && chrome.windows.onFocusChanged) {
42
+ chrome.windows.onFocusChanged.addListener(this.onWindowFocusChanged);
43
+ }
44
+ // popupate initially open tabs
45
+ chrome.tabs.query({}, (openTabs) => {
46
+ openTabs.forEach((tab) => {
47
+ this.onTabCreated(tab);
48
+ });
49
+ });
50
+ }
51
+
52
+ unload() {
53
+ this.tabs.forEach((page) => this.stagePage(page));
54
+ this.tabs.clear();
55
+
56
+ chrome.tabs.onCreated.removeListener(this.onTabCreated);
57
+ chrome.tabs.onUpdated.removeListener(this.onTabUpdated);
58
+ chrome.tabs.onRemoved.removeListener(this.onTabRemoved);
59
+ chrome.tabs.onActivated.removeListener(this.onTabActivated);
60
+ chrome.webNavigation.onBeforeNavigate.removeListener(this.onBeforeNavigate);
61
+ chrome.webNavigation.onCommitted.removeListener(this.onNavigationCommitted);
62
+ chrome.webNavigation.onCompleted.removeListener(this.onNavigationComplete);
63
+ if (chrome.windows && chrome.windows.onFocusChanged) {
64
+ chrome.windows.onFocusChanged.removeListener(this.onWindowFocusChanged);
65
+ }
66
+ }
67
+
68
+ stagePage(page) {
69
+ if (this.staged.push(page) > 5) {
70
+ this.staged.shift();
71
+ }
72
+ page.stage();
73
+ this.notifyPageStageListeners(page);
74
+ }
75
+
76
+ /**
77
+ * Create a new `tabContext` for the new tab
78
+ */
79
+ onTabCreated = (tab) => {
80
+ this.tabs.set(tab.id, makeTabContext(tab));
81
+ };
82
+
83
+ /**
84
+ * Update an existing tab or create it if we do not have a context yet.
85
+ */
86
+ onTabUpdated = (tabId, info, tab) => {
87
+ let tabContext = this.tabs.get(tabId);
88
+ if (tabContext === undefined) {
89
+ tabContext = makeTabContext(tab);
90
+ this.tabs.set(tabId, tabContext);
91
+ }
92
+
93
+ // Update `isPrivate` and `url` if available
94
+ tabContext.isPrivate = tab.incognito;
95
+ tabContext.setActive(tab.active);
96
+ if (info.url !== undefined) {
97
+ tabContext.url = info.url;
98
+ }
99
+ };
100
+
101
+ /**
102
+ * Remove tab context for `tabId`.
103
+ */
104
+ onTabRemoved = (tabId) => {
105
+ const tabContext = this.tabs.get(tabId);
106
+ if (tabContext && tabContext.state === PAGE_LOADING_STATE.COMPLETE) {
107
+ this.stagePage(tabContext);
108
+ }
109
+ this.tabs.delete(tabId);
110
+ };
111
+
112
+ onTabActivated = ({ previousTabId, tabId }) => {
113
+ // if previousTabId is not set (e.g. on chrome), set all tabs to inactive
114
+ // otherwise, we only have to mark the previous tab as inactive
115
+ if (!previousTabId) {
116
+ for (const tab of this.tabs.values()) {
117
+ tab.setActive(false);
118
+ }
119
+ } else if (this.tabs.has(previousTabId)) {
120
+ this.tabs.get(previousTabId).setActive(false);
121
+ }
122
+ if (this.tabs.has(tabId)) {
123
+ this.tabs.get(tabId).setActive(true);
124
+ }
125
+ };
126
+
127
+ onWindowFocusChanged = (focusedWindow) => {
128
+ chrome.tabs.query({ active: true }, (activeTabs) => {
129
+ activeTabs.forEach(({ id, windowId }) => {
130
+ const tabContext = this.tabs.get(id);
131
+ if (!tabContext) {
132
+ return;
133
+ }
134
+ if (windowId === focusedWindow) {
135
+ tabContext.setActive(true);
136
+ } else {
137
+ tabContext.setActive(false);
138
+ }
139
+ });
140
+ });
141
+ };
142
+
143
+ onBeforeNavigate = (details) => {
144
+ const { frameId, tabId, url, timeStamp } = details;
145
+ const tabContext = this.tabs.get(tabId);
146
+ if (frameId === 0) {
147
+ // ignore duplicated onBeforeNavigate https://bugzilla.mozilla.org/show_bug.cgi?id=1732564
148
+ if (
149
+ tabContext &&
150
+ tabContext.id === tabId &&
151
+ tabContext.url === url &&
152
+ tabContext.created + 200 > timeStamp
153
+ ) {
154
+ return;
155
+ }
156
+ // We are starting a navigation to a new page - if the previous page is complete (i.e. fully
157
+ // loaded), stage it before we create the new page info.
158
+ if (tabContext && tabContext.state === PAGE_LOADING_STATE.COMPLETE) {
159
+ this.stagePage(tabContext);
160
+ }
161
+ // create a new page for the navigation
162
+ this.tabs.delete(tabId);
163
+ const nextContext = makeTabContext({
164
+ id: tabId,
165
+ active: false,
166
+ url,
167
+ incognito: tabContext ? tabContext.isPrivate : false,
168
+ created: timeStamp,
169
+ });
170
+ nextContext.previous = tabContext;
171
+ this.tabs.set(tabId, nextContext);
172
+ nextContext.updateState(PAGE_LOADING_STATE.NAVIGATING);
173
+ }
174
+ };
175
+
176
+ onNavigationCommitted = (details) => {
177
+ const { frameId, tabId } = details;
178
+ const tabContext = this.tabs.get(tabId);
179
+ if (frameId === 0 && tabContext) {
180
+ tabContext.updateState(PAGE_LOADING_STATE.COMMITTED);
181
+ } else if (tabContext && !tabContext.frames[frameId]) {
182
+ // frame created without request
183
+ this.onSubFrame(details);
184
+ }
185
+ };
186
+
187
+ onNavigationComplete = ({ frameId, tabId }) => {
188
+ const tabContext = this.tabs.get(tabId);
189
+ if (frameId === 0 && tabContext) {
190
+ tabContext.updateState(PAGE_LOADING_STATE.COMPLETE);
191
+ }
192
+ };
193
+
194
+ onMainFrame = ({ tabId, url, requestId }, event) => {
195
+ // main frame from tabId -1 is from service worker and should not be saved
196
+ if (tabId === -1) {
197
+ return;
198
+ }
199
+ // Update last request id from the tab
200
+ let tabContext = this.tabs.get(tabId);
201
+ if (tabContext === undefined) {
202
+ tabContext = makeTabContext({ url, incognito: false });
203
+ this.tabs.set(tabId, tabContext);
204
+ }
205
+
206
+ if (event === 'onBeforeRequest') {
207
+ tabContext.frames = {};
208
+ // Detect redirect: if the last request on this tab had the same id and
209
+ // this was from the same `onBeforeRequest` hook, we can assume this is a
210
+ // redirection.
211
+ if (tabContext.lastRequestId === requestId) {
212
+ tabContext.isRedirect = true;
213
+ }
214
+
215
+ // Only keep track of `lastRequestId` with `onBeforeRequest` listener
216
+ // since we need this information for redirect detection only and this can
217
+ // be detected with this hook.
218
+ tabContext.lastRequestId = requestId;
219
+ }
220
+
221
+ // Update context of tab with `url` and main frame information
222
+ tabContext.url = url;
223
+ tabContext.frames[0] = {
224
+ parentFrameId: -1,
225
+ url,
226
+ };
227
+ };
228
+
229
+ onSubFrame = (details) => {
230
+ const { tabId, frameId, parentFrameId, url } = details;
231
+ const tab = this.tabs.get(tabId);
232
+ if (tab === undefined) {
233
+ logger.log('Could not find tab for sub_frame request', details);
234
+ return;
235
+ }
236
+
237
+ // Keep track of frameUrl as well as parent frame
238
+ tab.frames[frameId] = {
239
+ parentFrameId,
240
+ url,
241
+ };
242
+ };
243
+
244
+ getPageForRequest(context) {
245
+ const { tabId, frameId, originUrl, type, initiator } = context;
246
+ const tab = this.tabs.get(tabId);
247
+ if (!tab) {
248
+ return null;
249
+ }
250
+ // check if the current page has the given frame id, otherwise check if it belongs to the
251
+ // previous page
252
+ if (!tab.frames[frameId]) {
253
+ if (tab.previous && tab.previous.frames[frameId]) {
254
+ return tab.previous;
255
+ }
256
+ return null;
257
+ }
258
+
259
+ const couldBePreviousPage =
260
+ frameId === 0 && type !== 'main_frame' && tab.previous;
261
+
262
+ // for main frame requests: check if the origin url is from the previous page (Firefox)
263
+ if (
264
+ couldBePreviousPage &&
265
+ tab.url !== originUrl &&
266
+ tab.previous.url === originUrl
267
+ ) {
268
+ return tab.previous;
269
+ }
270
+ // on Chrome we have `initiator` which only contains the origin. In this case, check for a
271
+ // different origin
272
+ if (
273
+ couldBePreviousPage &&
274
+ initiator &&
275
+ !tab.url.startsWith(initiator) &&
276
+ tab.previous.url.startsWith(initiator)
277
+ ) {
278
+ return tab.previous;
279
+ }
280
+ return tab;
281
+ }
282
+ }