@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,1798 @@
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 {
14
+ equalityCanBeProven,
15
+ flattenObject,
16
+ isNil,
17
+ requireInt,
18
+ requireParam,
19
+ split0,
20
+ } from './utils';
21
+ import { DnsResolver } from './network';
22
+ import ActivityEstimator from './activity-estimator';
23
+ import { analyzePageStructure } from './page-structure';
24
+ import EventListenerQueue from './event-listener-queue';
25
+ import SelfCheck from './self-check';
26
+
27
+ /**
28
+ * Marker for lazy variables where the initialization was aborted.
29
+ *
30
+ * (exported for tests only)
31
+ */
32
+ export const CANCEL_LAZY_VAR = { _tag: 'CANCEL_LAZY_VAR' };
33
+
34
+ /**
35
+ * An ID that represents the absence of a browser tab.
36
+ */
37
+ export const TAB_ID_NONE = -1;
38
+
39
+ /**
40
+ * The windowId value that represents the absence of a browser window.
41
+ */
42
+ export const WINDOW_ID_NONE = -1;
43
+
44
+ /**
45
+ * The windowId value that represents the current window.
46
+ */
47
+ export const WINDOW_ID_CURRENT = -2;
48
+
49
+ /**
50
+ * Recursively traverses the given object and performs two operations:
51
+ * - pending or cancelled lazy vars will removed
52
+ * - resolved lazy vars will be inlined
53
+ *
54
+ * For more details on lazy variables, see Pages#_setLazyVar.
55
+ *
56
+ * Note: the implementation assumes that objects are free of cycles
57
+ *
58
+ * (exported for tests only)
59
+ */
60
+ export function stripLazyVars(obj) {
61
+ if (isNil(obj)) {
62
+ return obj;
63
+ }
64
+ if (Array.isArray(obj)) {
65
+ return obj.map(stripLazyVars);
66
+ }
67
+ if (obj === CANCEL_LAZY_VAR) {
68
+ return undefined;
69
+ }
70
+ if (Object(obj) !== obj || obj.constructor === Date) {
71
+ return obj;
72
+ }
73
+ const result = {};
74
+ for (const [key, val] of Object.entries(obj)) {
75
+ if (val?._pending) {
76
+ if (val.result && val.result !== CANCEL_LAZY_VAR) {
77
+ result[key] = stripLazyVars(val.result);
78
+ }
79
+ } else {
80
+ result[key] = stripLazyVars(val);
81
+ }
82
+ }
83
+ return result;
84
+ }
85
+
86
+ function isRealPage(url) {
87
+ return url && (url.startsWith('http://') || url.startsWith('https://'));
88
+ }
89
+
90
+ function sameHostname(url1, url2) {
91
+ try {
92
+ return new URL(url1).hostname === new URL(url2).hostname;
93
+ } catch (e) {
94
+ return false;
95
+ }
96
+ }
97
+
98
+ /**
99
+ * The API should match an ES6 map.
100
+ */
101
+ class OpenTabs {
102
+ constructor(pages) {
103
+ this._map = new Map();
104
+ this._pages = pages;
105
+ }
106
+
107
+ has(tabId) {
108
+ return this._map.has(tabId);
109
+ }
110
+
111
+ get(tabId) {
112
+ return this._map.get(tabId);
113
+ }
114
+
115
+ keys() {
116
+ return this._map.keys();
117
+ }
118
+
119
+ values() {
120
+ return this._map.values();
121
+ }
122
+
123
+ entries() {
124
+ return this._map.entries();
125
+ }
126
+
127
+ set(tabId, value) {
128
+ const result = this._map.set(tabId, value);
129
+ this._pages._onTabChanged(tabId);
130
+ return result;
131
+ }
132
+
133
+ delete(tabId) {
134
+ const wasDeleted = this._map.delete(tabId);
135
+ if (wasDeleted) {
136
+ this._pages._onTabChanged(tabId);
137
+ }
138
+ return wasDeleted;
139
+ }
140
+
141
+ // spread operator: [...openTabs]
142
+ *[Symbol.iterator]() {
143
+ for (const entry of this._map) {
144
+ yield entry;
145
+ }
146
+ }
147
+
148
+ /**
149
+ * This will not trigger tab change events.
150
+ */
151
+ restoreTabsFromMap(openTabs) {
152
+ this._map = openTabs;
153
+ }
154
+ }
155
+
156
+ /**
157
+ * An abstraction of the active tab. Note that we assume that there is a single
158
+ * active tab, which already different from what the browser sees: the browser
159
+ * sees multiple windows, and generally one active tab per window.
160
+ *
161
+ * The definition of the active tab used in this class is closer to what you
162
+ * would get by executing:
163
+ * ```
164
+ * chrome.tabs.query({ active: true, currentWindow: true })
165
+ * ```
166
+ */
167
+ class ActiveTab {
168
+ constructor(pages) {
169
+ this._pages = pages;
170
+ this._state = {
171
+ tabId: TAB_ID_NONE,
172
+ windowId: WINDOW_ID_NONE,
173
+ activeTabInWindow: new Map(),
174
+ lastUpdated: 0, // Unix epoch
175
+ };
176
+ this._pendingFlush = null;
177
+ }
178
+
179
+ get tabId() {
180
+ return this._state.tabId;
181
+ }
182
+
183
+ get activeWindowId() {
184
+ return this._state.windowId;
185
+ }
186
+
187
+ updateActiveTab({ tabId, windowId, now = Date.now() }) {
188
+ const previousTabId = this._state.tabId;
189
+ this._state.tabId = tabId;
190
+ this._state.windowId = windowId;
191
+ this._state.lastUpdated = now;
192
+ this.saveActiveTabInWindow({ tabId, windowId, now });
193
+ this._markDirty();
194
+
195
+ if (tabId !== previousTabId) {
196
+ this._pages._activeTab_onActiveTabChanged({ tabId, previousTabId, now });
197
+ }
198
+ }
199
+
200
+ saveActiveTabInWindow({ tabId, windowId, now = Date.now() }) {
201
+ if (windowId !== WINDOW_ID_NONE) {
202
+ this._state.activeTabInWindow.set(windowId, tabId);
203
+ this._state.lastUpdated = now;
204
+ this._markDirty();
205
+ }
206
+ }
207
+
208
+ focusWindow(windowId, now = Date.now()) {
209
+ const tabId = this._state.activeTabInWindow.get(windowId) ?? TAB_ID_NONE;
210
+ this.updateActiveTab({ tabId, windowId, now });
211
+ }
212
+
213
+ removeWindow(windowId, now = Date.now()) {
214
+ if (this._state.windowId === windowId) {
215
+ this._state.tabId = TAB_ID_NONE;
216
+ this._state.windowId = WINDOW_ID_NONE;
217
+ }
218
+ this._state.activeTabInWindow.delete(windowId);
219
+ this._state.lastUpdated = now;
220
+ this._markDirty();
221
+ }
222
+
223
+ _markDirty() {
224
+ if (this._pendingFlush === null) {
225
+ this._pendingFlush = setTimeout(() => {
226
+ this.flush();
227
+ }, 0);
228
+ }
229
+ }
230
+
231
+ flush() {
232
+ if (this._pendingFlush !== null) {
233
+ this._pendingFlush = null;
234
+ this._pages._activeTab_onInternalStateChanged();
235
+ }
236
+ }
237
+
238
+ serialize() {
239
+ return {
240
+ tabId: this._state.tabId,
241
+ windowId: this._state.windowId,
242
+ activeTabInWindow__serialized__: [...this._state.activeTabInWindow],
243
+ lastUpdated: this._state.lastUpdated,
244
+ };
245
+ }
246
+
247
+ restore(state) {
248
+ this._state = ActiveTab.ensureValidState({
249
+ tabId: state.tabId,
250
+ windowId: state.windowId,
251
+ activeTabInWindow: new Map(state.activeTabInWindow__serialized__),
252
+ lastUpdated: state.lastUpdated || 0,
253
+ });
254
+ }
255
+
256
+ static ensureValidState(state) {
257
+ const { tabId, windowId, activeTabInWindow, lastUpdated } = state || {};
258
+ requireInt(tabId, 'tabId');
259
+ requireInt(windowId, 'windowId');
260
+ requireInt(lastUpdated, 'lastUpdated');
261
+
262
+ for (const [key, value] of [...activeTabInWindow]) {
263
+ requireInt(key, 'activeTabInWindow[key]');
264
+ requireInt(value, 'activeTabInWindow[value]');
265
+ }
266
+ return state;
267
+ }
268
+
269
+ selfChecks(check = new SelfCheck()) {
270
+ try {
271
+ ActiveTab.ensureValidState(this._state);
272
+ } catch (e) {
273
+ check.fail('Invalid state', {
274
+ state: this._state,
275
+ reason: e.message,
276
+ });
277
+ return check;
278
+ }
279
+
280
+ const { tabId, windowId, activeTabInWindow } = this._state;
281
+ if (tabId !== TAB_ID_NONE && activeTabInWindow.get(windowId) !== tabId) {
282
+ check.warn('tabId and activeTabInWindow out of sync');
283
+ }
284
+ return check;
285
+ }
286
+ }
287
+
288
+ /**
289
+ * Responsible for aggregating information about open pages.
290
+ *
291
+ * It works by aggregating information from available extension APIs.
292
+ * The implementation needs to be fault-tolerant to recover from inconsistent
293
+ * states, loss of the state (if the service worker gets killed), lack of APIs
294
+ * (e.g. on Safari), and fail gracefully in situations where the listener is
295
+ *
296
+ * For error recovery, it may sacrifice precision by deleting information
297
+ * that is most likely outdated or even wrong. The overall goal of this class
298
+ * is to provide information that are reliable and match or exceed what the
299
+ * chrome.tabs.query IP would get.
300
+ * not called and events have been skipped.
301
+ *
302
+ * List of Safari quirks:
303
+ * https://developer.apple.com/documentation/safariservices/safari_web_extensions/assessing_your_safari_web_extension_s_browser_compatibility
304
+ *
305
+ * TODO: how to deal with speculative requests? Is it a problem?
306
+ * https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/webRequest#speculative_requests
307
+ */
308
+ export default class Pages {
309
+ constructor({
310
+ config,
311
+ urlAnalyzer,
312
+ newPageApprover,
313
+ pageSessionStore,
314
+ dnsResolver = new DnsResolver(),
315
+ }) {
316
+ this.isActive = false;
317
+ this.urlAnalyzer = requireParam(urlAnalyzer);
318
+ this.newPageApprover = requireParam(newPageApprover);
319
+ this.observers = [];
320
+
321
+ this.openTabs = new OpenTabs(this);
322
+ this.activeTab = new ActiveTab(this);
323
+ this.activityEstimator = new ActivityEstimator({
324
+ onActivityUpdated: this._activityEstimator_onActivityUpdated.bind(this),
325
+ onInternalStateChanged:
326
+ this._activityEstimator_onInternalStateChanged.bind(this),
327
+ });
328
+
329
+ this.dnsResolver = requireParam(dnsResolver);
330
+ this.sessionStore = requireParam(pageSessionStore);
331
+
332
+ // Browsers have the concept of tab id that must be unique per browser
333
+ // session. To detect navigations in the same tab, the additional "page id"
334
+ // is introduced. It will be updated on navigation events.
335
+ this._pageIdGenerator = 1 + Math.floor(Math.random() * 0x100000000);
336
+
337
+ // Inject chrome APIs (e.g. chrome.tabs, chrome.webNavigation). Since the
338
+ // availability of APIs differs among plattforms, the implementation should
339
+ // not to make any assumptions.
340
+ this.chrome = config.pages?.chrome || globalThis.chrome || {};
341
+ if (!this.chrome?.tabs?.query) {
342
+ logger.warn('chrome.tabs.query API missing');
343
+ }
344
+
345
+ // Protection against misconfigured servers that create long redirect chains.
346
+ // If the end is reached, the magic value "..." will be added.
347
+ this.maxRedirects = 8;
348
+
349
+ // counts the original languages seen (intended for debugging only)
350
+ this.langStats = {};
351
+ this.verboseLogging = config.pages?.verbose ?? false;
352
+
353
+ // quirks: some fields are not available on all platforms (e.g. Safari)
354
+ this.isPageLoadMethodReliable =
355
+ this.chrome.webNavigation?.onHistoryStateUpdated?.addListener &&
356
+ this.chrome.webNavigation?.onHistoryStateUpdated?.removeListener;
357
+ }
358
+
359
+ addObserver(onPageEventCallback) {
360
+ this.observers.push(onPageEventCallback);
361
+ }
362
+
363
+ async init() {
364
+ this.isActive = true;
365
+
366
+ // The rest can be done asynchronously, so that the module doesn't get
367
+ // slowed down. Loading data from session storage and getting the open tabs
368
+ // can be triggered in parallel. Only the initial restore will first initialize
369
+ // with the information from session storage before it can sync with the
370
+ // currently open tabs. That ordering is enforced to preserve information
371
+ // that is missing in the "chrome.tabs.query" result.
372
+ if (!this._ready) {
373
+ this._ready = new Promise((done) => {
374
+ (async () => {
375
+ try {
376
+ const pendingInit = this.sessionStore.init();
377
+ const pendingTabSyncParams =
378
+ this._prepareSyncWithOpenTabsFromTabsAPI();
379
+ try {
380
+ await pendingInit;
381
+ this._restoreSession(this.sessionStore.getEntries());
382
+ } catch (e) {
383
+ logger.warn(
384
+ 'Failed to restore previous state from in-memory session (if there was any)',
385
+ e,
386
+ );
387
+ this.sessionStore.clear();
388
+ }
389
+
390
+ try {
391
+ this._syncWithOpenTabsFromTabsAPI(await pendingTabSyncParams);
392
+ } catch (e) {
393
+ logger.warn('Failed to sync with open tabs', e);
394
+ }
395
+
396
+ if (this.isActive) {
397
+ eventListenerQueue.replayEvents();
398
+ this._setupListener();
399
+ }
400
+ this._updateSession();
401
+
402
+ logger.debug(
403
+ 'Successfully initialized. Forcing full page aggregator sync...',
404
+ );
405
+ this.notifyObservers({
406
+ type: 'full-sync',
407
+ });
408
+ } finally {
409
+ eventListenerQueue.close();
410
+ done();
411
+ }
412
+ })();
413
+ });
414
+ }
415
+ }
416
+
417
+ async blockUntilFullInit() {
418
+ if (!this.isActive) {
419
+ throw new Error('Not active (try to call "init" first)');
420
+ }
421
+ await this._ready;
422
+ }
423
+
424
+ async syncWithBrowser() {
425
+ await this.blockUntilFullInit();
426
+ this._syncWithOpenTabsFromTabsAPI(
427
+ await this._prepareSyncWithOpenTabsFromTabsAPI(),
428
+ );
429
+ }
430
+
431
+ _restoreSession(session) {
432
+ if (!session || Object.keys(session).length === 0) {
433
+ logger.debug('Found no previous state about pages to restore');
434
+ return;
435
+ }
436
+
437
+ const { dnsResolver, activeTab, activityEstimator, ...openTabs } = session;
438
+ this.activeTab.restore(activeTab);
439
+ this.dnsResolver.restore(dnsResolver);
440
+ this.activityEstimator.restore(activityEstimator);
441
+ this._restoreTabs(openTabs);
442
+ }
443
+
444
+ _serializeFullSession() {
445
+ return {
446
+ dnsResolver: this.dnsResolver.serialize(),
447
+ activeTab: this.activeTab.serialize(),
448
+ activityEstimator: this.activityEstimator.serialize(),
449
+ ...this._serializeTabs(),
450
+ };
451
+ }
452
+
453
+ _updateSession() {
454
+ if (this.sessionStore.isReady()) {
455
+ this.sessionStore.replaceItems(this._serializeFullSession());
456
+ }
457
+ }
458
+
459
+ _onTabChanged(tabId) {
460
+ if (this.verboseLogging) {
461
+ console.trace('tabChanged:', tabId, ':', this.openTabs.get(tabId));
462
+ }
463
+
464
+ const content = this.openTabs.get(tabId);
465
+ if (tabId === this.activeTab.tabId) {
466
+ this.activityEstimator.updateActiveUrl(content?.url || null);
467
+ }
468
+
469
+ if (this.sessionStore.isReady()) {
470
+ if (content) {
471
+ this.sessionStore.set(tabId, this._serializeTabContent(content));
472
+ } else {
473
+ this.sessionStore.remove(tabId);
474
+ }
475
+ }
476
+ }
477
+
478
+ _activeTab_onActiveTabChanged({ tabId, previousTabId, now = Date.now() }) {
479
+ if (this.verboseLogging) {
480
+ const url = this.openTabs.get(tabId)?.url;
481
+ console.trace('activeTabChanged:', {
482
+ url,
483
+ from: {
484
+ tabId: previousTabId,
485
+ url: this.openTabs.get(previousTabId)?.url,
486
+ },
487
+ to: {
488
+ tabId,
489
+ url,
490
+ },
491
+ });
492
+ }
493
+
494
+ const url = this.openTabs.get(tabId)?.url;
495
+ this.activityEstimator.updateActiveUrl(url || null, now);
496
+ }
497
+
498
+ _activeTab_onInternalStateChanged() {
499
+ if (this.sessionStore.isReady()) {
500
+ this.sessionStore.set('activeTab', this.activeTab.serialize());
501
+ }
502
+ }
503
+
504
+ _activityEstimator_onActivityUpdated(urls) {
505
+ if (this.isActive && urls.length > 0) {
506
+ this.notifyObservers({
507
+ type: 'activity-updated',
508
+ urls,
509
+ activityEstimator: this.activityEstimator,
510
+ });
511
+ }
512
+ }
513
+
514
+ _activityEstimator_onInternalStateChanged() {
515
+ if (this.sessionStore.isReady()) {
516
+ this.sessionStore.set(
517
+ 'activityEstimator',
518
+ this.activityEstimator.serialize(),
519
+ );
520
+ }
521
+ }
522
+
523
+ _serializeTabContent(tabContent) {
524
+ return stripLazyVars(tabContent);
525
+ }
526
+
527
+ _deserializeTabContent(tabContent) {
528
+ const result = {};
529
+ Object.entries(tabContent).forEach(([key, val]) => {
530
+ if (val._pending) {
531
+ logger.warn(
532
+ 'Lazy variable should not have been serialized (since they are promises):',
533
+ key,
534
+ '->',
535
+ val,
536
+ '(drop and continue...)',
537
+ );
538
+ } else {
539
+ result[key] = val;
540
+ }
541
+ });
542
+ return result;
543
+ }
544
+
545
+ _serializeTabs() {
546
+ const result = {};
547
+ for (const [tabId, tabContent] of this.openTabs) {
548
+ result[tabId] = this._serializeTabContent(tabContent);
549
+ }
550
+ return result;
551
+ }
552
+
553
+ _restoreTabs(openTabs) {
554
+ if (openTabs) {
555
+ // TODO: maybe merge together?
556
+ const deserializedTabs = Object.entries(openTabs).map(
557
+ ([tabId, tabContent]) => [
558
+ tabId,
559
+ this._deserializeTabContent(tabContent),
560
+ ],
561
+ );
562
+ this.openTabs.restoreTabsFromMap(new Map(deserializedTabs));
563
+ }
564
+ }
565
+
566
+ async _tryChromeTabsQuery(...args) {
567
+ if (this.chrome?.tabs?.query) {
568
+ return this.chrome.tabs.query(...args);
569
+ }
570
+
571
+ if (!this._warnedAboutChromeTabsQueryApi) {
572
+ this._warnedAboutChromeTabsQueryApi = true;
573
+ logger.warn('chrome.tabs.query not available on this platform');
574
+ }
575
+ return undefined;
576
+ }
577
+
578
+ // Note: Unavailable on Firefox for Android
579
+ async _tryChromeWindowsGetLastFocused(...args) {
580
+ if (this.chrome?.windows?.getLastFocused) {
581
+ return this.chrome.windows.getLastFocused(...args);
582
+ }
583
+
584
+ if (!this._warnedAboutChromeWindowsGetLastFocusedApi) {
585
+ this._warnedAboutChromeWindowsGetLastFocusedApi = true;
586
+ logger.warn(
587
+ 'chrome.windows.getLastFocused not available on this platform',
588
+ );
589
+ }
590
+ return undefined;
591
+ }
592
+
593
+ async _prepareSyncWithOpenTabsFromTabsAPI() {
594
+ const [tabs, lastFocusedWindow] = await Promise.all([
595
+ this._tryChromeTabsQuery({}),
596
+ this._tryChromeWindowsGetLastFocused(),
597
+ ]);
598
+ return {
599
+ tabs: tabs || [],
600
+ lastActiveWindowId: lastFocusedWindow?.id || null,
601
+ };
602
+ }
603
+
604
+ _syncWithOpenTabsFromTabsAPI({
605
+ tabs, // Note: may be [] if the API is not available
606
+ lastActiveWindowId, // Note: may be null if the API is not available
607
+ now = Date.now(),
608
+ }) {
609
+ const activeTabCandidates = [];
610
+ const unmatchedTabIds = new Set(this.openTabs.keys());
611
+ for (const tab of tabs) {
612
+ if (tab.incognito || !isRealPage(tab.url)) {
613
+ continue;
614
+ }
615
+
616
+ let oldEntry = null;
617
+ if (unmatchedTabIds.delete(tab.id)) {
618
+ oldEntry = this.openTabs.get(tab.id);
619
+ if (oldEntry.url !== tab.url) {
620
+ // TODO: Can this happen? If so, when?
621
+ logger.warn('Ignoring tab after a URL mismatch:', {
622
+ oldEntry,
623
+ newEntry: tab,
624
+ });
625
+ oldEntry = null;
626
+ }
627
+ }
628
+
629
+ const { id: tabId, windowId, status, title, url } = tab;
630
+ const entry = {
631
+ ...oldEntry,
632
+ status,
633
+ title,
634
+ url,
635
+ windowId,
636
+ lastUpdatedAt: now,
637
+ pageId: ++this._pageIdGenerator,
638
+ };
639
+ this._initVisibility(tabId, entry, now);
640
+
641
+ if (tab.active && isRealPage(tab.url)) {
642
+ this.activeTab.saveActiveTabInWindow({
643
+ tabId,
644
+ windowId,
645
+ now,
646
+ });
647
+ if (windowId === lastActiveWindowId || isNil(lastActiveWindowId)) {
648
+ activeTabCandidates.push({ tabId, windowId });
649
+ if (tab.status === 'complete') {
650
+ this._initAllOptionalFields(tabId, entry, now);
651
+ }
652
+ }
653
+ }
654
+ this.openTabs.set(tabId, entry);
655
+ }
656
+
657
+ if (
658
+ activeTabCandidates.length > 1 &&
659
+ this.chrome?.windows?.getLastFocused
660
+ ) {
661
+ logger.warn(
662
+ 'Multiple tabs are being detected as active',
663
+ '(since the chrome.windows API is available, this is unexpected)',
664
+ activeTabCandidates,
665
+ );
666
+ }
667
+
668
+ if (activeTabCandidates.length === 1) {
669
+ const { tabId, windowId } = activeTabCandidates[0];
670
+ this.activeTab.updateActiveTab({ tabId, windowId, now });
671
+ } else {
672
+ this.activeTab.updateActiveTab({
673
+ tabId: TAB_ID_NONE,
674
+ windowId: WINDOW_ID_NONE,
675
+ now,
676
+ });
677
+ }
678
+
679
+ if (unmatchedTabIds.size > 0) {
680
+ unmatchedTabIds.forEach((tabId) => this.openTabs.delete(tabId));
681
+ }
682
+ }
683
+
684
+ unload() {
685
+ this.isActive = false;
686
+ if (this._removeListeners) {
687
+ this._removeListeners();
688
+ this._removeListeners = null;
689
+ }
690
+ this.activeTab.flush();
691
+ this.activityEstimator.flush();
692
+ eventListenerQueue.close();
693
+ }
694
+
695
+ notifyObservers(event) {
696
+ this.observers.forEach((observer) => {
697
+ try {
698
+ observer(event);
699
+ } catch (e) {
700
+ logger.error('Unexpected error in observer', e);
701
+ }
702
+ });
703
+ }
704
+
705
+ describe(now = Date.now()) {
706
+ const openTabs = {};
707
+ for (const [tabId, pageInfo] of this.openTabs) {
708
+ if (isRealPage(pageInfo.url)) {
709
+ const isActive = tabId === this.activeTab.tabId;
710
+ openTabs[tabId] = this._describePage(pageInfo, isActive, now);
711
+ }
712
+ }
713
+
714
+ let activeTab;
715
+ if (
716
+ this.activeTab.tabId !== TAB_ID_NONE &&
717
+ openTabs[this.activeTab.tabId]
718
+ ) {
719
+ activeTab = {
720
+ tabId: this.activeTab.tabId,
721
+ tab: openTabs[this.activeTab.tabId],
722
+ };
723
+ }
724
+
725
+ return {
726
+ activeTab,
727
+ openTabs,
728
+ };
729
+ }
730
+
731
+ describeTab(tabId, now = Date.now()) {
732
+ const pageInfo = this.openTabs.get(tabId);
733
+ if (!pageInfo || !isRealPage(pageInfo.url)) {
734
+ return null;
735
+ }
736
+ const isActive = tabId === this.activeTab.tabId;
737
+ return this._describePage(pageInfo, isActive, now);
738
+ }
739
+
740
+ /**
741
+ * Either the (non-negative) id of the tab that is assumed to be active,
742
+ * or TAB_ID_NONE, which is guaranteed to be -1.
743
+ */
744
+ getActiveTabId() {
745
+ return this.activeTab.tabId;
746
+ }
747
+
748
+ _describePage(pageInfo, isActive, now = Date.now()) {
749
+ const result = {
750
+ status: pageInfo.status,
751
+ title: pageInfo.title,
752
+ url: pageInfo.url,
753
+ visibility: pageInfo.visibility,
754
+ windowId: pageInfo.windowId,
755
+ lastUpdatedAt: pageInfo.lastUpdatedAt,
756
+ isActive,
757
+ };
758
+
759
+ if (pageInfo.previousUrl) {
760
+ result.ref = pageInfo.previousUrl;
761
+ }
762
+ if (this.isPageLoadMethodReliable && pageInfo.pageLoadMethod) {
763
+ result.pageLoadMethod = pageInfo.pageLoadMethod;
764
+ }
765
+
766
+ this._tryUnwrapLazyVar(pageInfo.language, (value) => {
767
+ result.lang = value;
768
+ });
769
+ this._tryUnwrapLazyVar(pageInfo.pageStructure, (value) => {
770
+ result.preDoublefetch = value;
771
+ if (value.noindex) {
772
+ result.visibility = 'private';
773
+ }
774
+ });
775
+
776
+ if (pageInfo.redirects) {
777
+ result.redirects = pageInfo.redirects;
778
+ }
779
+ if (pageInfo.search) {
780
+ result.search = {
781
+ category: pageInfo.search.category,
782
+ query: pageInfo.search.query,
783
+ depth: pageInfo.search.depth,
784
+ };
785
+ }
786
+
787
+ if (isActive && pageInfo.url) {
788
+ result.activity = this.activityEstimator.estimate(pageInfo.url, now);
789
+ }
790
+
791
+ return result;
792
+ }
793
+
794
+ _setupListener() {
795
+ if (this._removeListeners) {
796
+ // listeners have been already installed
797
+ return;
798
+ }
799
+ const cleanup = [];
800
+
801
+ const wrapHandler = (handler) => {
802
+ handler = handler.bind(this);
803
+ return (...args) => {
804
+ if (this.isActive) {
805
+ handler(...args);
806
+ }
807
+ };
808
+ };
809
+
810
+ // listeners for chrome.tabs API:
811
+ if (this.chrome.tabs) {
812
+ for (const type of [
813
+ 'onCreated',
814
+ 'onUpdated',
815
+ 'onRemoved',
816
+ 'onActivated',
817
+ ]) {
818
+ const handler = wrapHandler(this[`chrome_tabs_${type}`]);
819
+ if (
820
+ this.chrome.tabs[type]?.addListener &&
821
+ this.chrome.tabs[type]?.removeListener
822
+ ) {
823
+ this.chrome.tabs[type].addListener(handler);
824
+ cleanup.push(() => this.chrome.tabs[type].removeListener(handler));
825
+ }
826
+ }
827
+ }
828
+
829
+ // listeners for chrome.webRequest API:
830
+ if (this.chrome.webRequest) {
831
+ for (const type of [
832
+ 'onBeforeRedirect', // note: unavailable on Safari
833
+ 'onResponseStarted', // note: unavailable on Safari
834
+ 'onCompleted', // note: unavailable on Safari
835
+ 'onAuthRequired', // note: unavailable on Safari
836
+ ]) {
837
+ const handler = wrapHandler(this[`chrome_webRequest_${type}`]);
838
+ if (
839
+ this.chrome.webRequest[type]?.addListener &&
840
+ this.chrome.webRequest[type]?.removeListener
841
+ ) {
842
+ try {
843
+ this.chrome.webRequest[type].addListener(
844
+ handler,
845
+ { urls: ['<all_urls>'] },
846
+ ['responseHeaders'],
847
+ );
848
+ } catch (e) {
849
+ this.chrome.webRequest[type].addListener(handler, {
850
+ urls: ['<all_urls>'],
851
+ });
852
+ }
853
+ cleanup.push(() =>
854
+ this.chrome.webRequest[type].removeListener(handler),
855
+ );
856
+ } else {
857
+ logger.info(`chrome.webRequest.${type} API is unavailable`);
858
+ }
859
+ }
860
+ }
861
+
862
+ // listeners for chrome.webNavigation API:
863
+ if (this.chrome.webNavigation) {
864
+ for (const type of [
865
+ 'onCreatedNavigationTarget', // note: unavailable on Safari
866
+ 'onBeforeNavigate',
867
+ 'onCommitted',
868
+ 'onHistoryStateUpdated', // note: unavailable on Safari
869
+ ]) {
870
+ const handler = wrapHandler(this[`chrome_webNavigation_${type}`]);
871
+ if (
872
+ this.chrome.webNavigation[type]?.addListener &&
873
+ this.chrome.webNavigation[type]?.removeListener
874
+ ) {
875
+ this.chrome.webNavigation[type].addListener(handler);
876
+ cleanup.push(() =>
877
+ this.chrome.webNavigation[type].removeListener(handler),
878
+ );
879
+ } else {
880
+ logger.info(`chrome.webNavigation.${type} API is unavailable`);
881
+ }
882
+ }
883
+ }
884
+
885
+ // listeners for chrome.windows API:
886
+ if (this.chrome.windows) {
887
+ for (const type of [
888
+ 'onRemoved', // note: unavailable on Firefox Android and Safari iOS
889
+ 'onFocusChanged', // note: unavailable on Firefox Android
890
+ ]) {
891
+ const handler = wrapHandler(this[`chrome_windows_${type}`]);
892
+ if (
893
+ this.chrome.windows[type]?.addListener &&
894
+ this.chrome.windows[type]?.removeListener
895
+ ) {
896
+ this.chrome.windows[type].addListener(handler);
897
+ cleanup.push(() => this.chrome.windows[type].removeListener(handler));
898
+ } else {
899
+ logger.info(`chrome.windows.${type} API is unavailable`);
900
+ }
901
+ }
902
+ }
903
+
904
+ this._removeListeners = () => {
905
+ cleanup.forEach((f) => f());
906
+ };
907
+ }
908
+
909
+ chrome_tabs_onCreated(tab) {
910
+ if (tab.incognito) {
911
+ this.openTabs.delete(tab.id);
912
+ return;
913
+ }
914
+
915
+ if (
916
+ tab.openerTabId === undefined ||
917
+ (tab.pendingUrl && !isRealPage(tab.pendingUrl))
918
+ ) {
919
+ return;
920
+ }
921
+
922
+ const openerTab = this.openTabs.get(tab.openerTabId);
923
+ if (openerTab) {
924
+ const oldEntry = this.openTabs.get(tab.id);
925
+ const entry = {
926
+ status: 'created',
927
+ ...oldEntry,
928
+ windowId: tab.windowId,
929
+ lastUpdatedAt: Date.now(),
930
+ pageId: ++this._pageIdGenerator,
931
+ openerTab: { ...openerTab },
932
+ };
933
+ this.openTabs.set(tab.id, entry);
934
+ }
935
+ }
936
+
937
+ chrome_tabs_onUpdated(tabId, changeInfo, tab) {
938
+ if (tab.incognito) {
939
+ return;
940
+ }
941
+
942
+ const now = Date.now();
943
+ const { windowId } = tab;
944
+ if (tab.active) {
945
+ if (this.activeTab.activeWindowId === windowId) {
946
+ this.activeTab.updateActiveTab({ tabId, windowId, now });
947
+ } else {
948
+ this.activeTab.saveActiveTabInWindow({ tabId, windowId, now });
949
+ }
950
+ }
951
+
952
+ let oldTabEntry = this.openTabs.get(tabId);
953
+ if (changeInfo.status === 'complete') {
954
+ const entry = {
955
+ ...oldTabEntry,
956
+ status: 'complete',
957
+ title: tab.title,
958
+ url: tab.url,
959
+ windowId,
960
+ lastUpdatedAt: now,
961
+ };
962
+ this._initAllOptionalFields(tabId, entry, now);
963
+ this.openTabs.set(tabId, entry);
964
+ return;
965
+ }
966
+
967
+ if (tab.status === 'loading') {
968
+ let entry;
969
+ if (
970
+ oldTabEntry &&
971
+ (oldTabEntry.url === tab.url ||
972
+ (oldTabEntry.url === 'about:blank' &&
973
+ oldTabEntry.status === 'loading'))
974
+ ) {
975
+ // still loading the same page
976
+ entry = {
977
+ ...oldTabEntry,
978
+ title: tab.title,
979
+ url: tab.url,
980
+ windowId,
981
+ lastUpdatedAt: now,
982
+ };
983
+
984
+ const red = entry._unverifiedRedirects;
985
+ if (red && tab.url !== 'about:blank') {
986
+ if (red[red.length - 1].to === tab.url) {
987
+ entry.redirects = [...red];
988
+ logger.debug('confirmed redirect:', red, '->', tab.url);
989
+ } else {
990
+ logger.warn('rejected redirects:', { ...entry });
991
+ }
992
+ delete entry._unverifiedRedirects;
993
+ }
994
+ } else {
995
+ entry = {
996
+ status: 'loading',
997
+ pageLoadMethod: 'full-page-load',
998
+ title: tab.title,
999
+ url: tab.url,
1000
+ windowId,
1001
+ lastUpdatedAt: now,
1002
+ pageId: ++this._pageIdGenerator,
1003
+ };
1004
+ if (oldTabEntry) {
1005
+ if (oldTabEntry.status !== 'created') {
1006
+ entry.openedFrom = { ...oldTabEntry };
1007
+ } else if (oldTabEntry.openerTab) {
1008
+ entry.openedFrom = { ...oldTabEntry.openerTab };
1009
+ }
1010
+
1011
+ const redirects = entry.openedFrom?.pendingRedirects || [];
1012
+ if (redirects.length > 0) {
1013
+ const target = redirects[redirects.length - 1].to;
1014
+ if (target === tab.url) {
1015
+ entry.redirects = [...redirects];
1016
+ } else if (tab.url === 'about:blank') {
1017
+ logger.debug('delaying redirect matching:', redirects);
1018
+ entry._unverifiedRedirects = [...redirects];
1019
+ }
1020
+ }
1021
+
1022
+ const previousUrl = entry.openedFrom?.url;
1023
+ if (isRealPage(previousUrl)) {
1024
+ entry.previousUrl = previousUrl;
1025
+ }
1026
+ }
1027
+ }
1028
+
1029
+ if (!entry.search && entry.openedFrom?.search && entry.previousUrl) {
1030
+ // depth 0: the SERP
1031
+ // depth 1: the landing page
1032
+ // depth 2: one click within the landing page (but on within the same hostname)
1033
+ // depth >=3: drop (because the query could become a session ID)
1034
+ if (
1035
+ entry.openedFrom.search.depth === 0 ||
1036
+ (entry.openedFrom.search.depth === 1 &&
1037
+ sameHostname(entry.url, entry.previousUrl))
1038
+ ) {
1039
+ entry.search = {
1040
+ ...entry.openedFrom.search,
1041
+ depth: entry.openedFrom.search.depth + 1,
1042
+ lastUpdatedAt: now,
1043
+ };
1044
+ }
1045
+ }
1046
+
1047
+ this.openTabs.set(tabId, entry);
1048
+ return;
1049
+ }
1050
+
1051
+ if (oldTabEntry) {
1052
+ const entry = {
1053
+ ...oldTabEntry,
1054
+ lastUpdatedAt: now,
1055
+ };
1056
+
1057
+ let updated = false;
1058
+ if (tab.title && tab.title !== entry.title) {
1059
+ entry.title = tab.title;
1060
+ entry.pageId = ++this._pageIdGenerator; // TODO: is this too conservative?
1061
+ updated = true;
1062
+ }
1063
+ if (tab.url && tab.url !== entry.url) {
1064
+ entry.url = tab.url;
1065
+ entry.pageId = ++this._pageIdGenerator;
1066
+ updated = true;
1067
+ }
1068
+
1069
+ this.openTabs.set(tabId, entry);
1070
+ if (updated) {
1071
+ this.notifyObservers({
1072
+ type: 'page-updated',
1073
+ tabId,
1074
+ });
1075
+ }
1076
+ return;
1077
+ }
1078
+
1079
+ logger.warn('Unexpected status:', changeInfo.status);
1080
+ }
1081
+
1082
+ chrome_tabs_onRemoved(tabId) {
1083
+ if (!this.openTabs.delete(tabId)) {
1084
+ logger.debug('Trying to remove unknown tab:', tabId);
1085
+ }
1086
+ if (this.activeTab.tabId === tabId) {
1087
+ this.activeTab.updateActiveTab({
1088
+ tabId: TAB_ID_NONE,
1089
+ windowId: WINDOW_ID_NONE,
1090
+ });
1091
+ }
1092
+ }
1093
+
1094
+ chrome_tabs_onActivated(activeInfo) {
1095
+ const now = Date.now();
1096
+ const { tabId, windowId } = activeInfo;
1097
+ this.activeTab.updateActiveTab({ tabId, windowId, now });
1098
+
1099
+ const entry = this.openTabs.get(tabId);
1100
+ if (entry?.status === 'complete') {
1101
+ this._initAllOptionalFields(tabId, entry, now);
1102
+ }
1103
+ }
1104
+
1105
+ // Safari quirks:
1106
+ // * This API is not available
1107
+ chrome_webRequest_onBeforeRedirect(details) {
1108
+ if (details.initiator && details.initiator !== 'null' && details.ip) {
1109
+ this._cacheDnsResolution(details.initiator, details.ip);
1110
+ }
1111
+ if (details.type !== 'main_frame') {
1112
+ return;
1113
+ }
1114
+ if (details.statusCode === 0) {
1115
+ // Ignore mysterious even from Firefox with statusCode=0 and url=redirectUrl.
1116
+ // Perhaps it has to do with single-page applications, but the documentation
1117
+ // does not give any insights about this behavior.
1118
+ return;
1119
+ }
1120
+ const { tabId, statusCode, url: from, redirectUrl: to } = details;
1121
+ logger.debug('Detected redirect:', from, '->', to, 'with tabId', tabId);
1122
+
1123
+ const entry = {
1124
+ ...this.openTabs.get(tabId),
1125
+ status: 'redirecting',
1126
+ lastUpdatedAt: Date.now(),
1127
+ };
1128
+ const thisRedirect = {
1129
+ from,
1130
+ to,
1131
+ statusCode,
1132
+ };
1133
+ if (!entry.pendingRedirects) {
1134
+ entry.pendingRedirects = [thisRedirect];
1135
+ } else if (entry.pendingRedirects.length < this.maxRedirects) {
1136
+ entry.pendingRedirects = [...entry.pendingRedirects, thisRedirect];
1137
+ } else if (
1138
+ entry.pendingRedirects[entry.pendingRedirects.length - 1].to !== '...'
1139
+ ) {
1140
+ logger.warn(
1141
+ 'Break exceptionally long redirect chain (redirect loop?):',
1142
+ entry.pendingRedirects,
1143
+ '-->',
1144
+ thisRedirect,
1145
+ '(destination will be replaced by "...")',
1146
+ );
1147
+ thisRedirect.to = '...';
1148
+ entry.pendingRedirects = [...entry.pendingRedirects, thisRedirect];
1149
+ } else {
1150
+ entry.pendingRedirects = [...entry.pendingRedirects];
1151
+ }
1152
+ this.openTabs.set(tabId, entry);
1153
+ }
1154
+
1155
+ // Safari quirks:
1156
+ // * This API is not available
1157
+ chrome_webRequest_onResponseStarted(details) {
1158
+ if (details.initiator && details.initiator !== 'null' && details.ip) {
1159
+ this._cacheDnsResolution(details.initiator, details.ip);
1160
+ }
1161
+ }
1162
+
1163
+ // Safari quirks:
1164
+ // * This API is not available
1165
+ chrome_webRequest_onCompleted(details) {
1166
+ if (this.activeTab.tabId === details.tabId) {
1167
+ const entry = this.openTabs.get(details.tabId);
1168
+ if (entry && isRealPage(entry.url)) {
1169
+ let contentLength = 0;
1170
+ for (const { name, value } of details.responseHeaders) {
1171
+ if (name.toLowerCase() === 'content-length') {
1172
+ contentLength = Number(value) || 0;
1173
+ break;
1174
+ }
1175
+ }
1176
+ if (contentLength > 1024) {
1177
+ this.activityEstimator.dynamicLoadDetected(entry.url);
1178
+ }
1179
+ }
1180
+ }
1181
+ }
1182
+
1183
+ // Test page: https://jigsaw.w3.org/HTTP/Basic/
1184
+ //
1185
+ // Safari quirks:
1186
+ // * This API is not available
1187
+ chrome_webRequest_onAuthRequired(details) {
1188
+ const { tabId, url } = details;
1189
+ const entry = this.openTabs.get(tabId);
1190
+ if (entry?.url === url) {
1191
+ this.openTabs.set(tabId, {
1192
+ entry,
1193
+ visibility: 'private',
1194
+ pageId: ++this._pageIdGenerator,
1195
+ lastUpdatedAt: Date.now(),
1196
+ });
1197
+ }
1198
+
1199
+ this.newPageApprover.markAsPrivate(url).catch((e) => {
1200
+ logger.warn('Failed to mark page as private:', url, e);
1201
+ });
1202
+ }
1203
+
1204
+ // Safari quirks:
1205
+ // * This API is not available
1206
+ chrome_webNavigation_onCreatedNavigationTarget(details) {
1207
+ if (details.sourceFrameId !== 0) {
1208
+ return;
1209
+ }
1210
+ const { tabId, sourceTabId, windowId } = details;
1211
+ const openerTab = this.openTabs.get(sourceTabId);
1212
+ if (!openerTab) {
1213
+ return;
1214
+ }
1215
+
1216
+ const oldEntry = this.openTabs.get(tabId);
1217
+ const entry = {
1218
+ status: 'created',
1219
+ ...oldEntry,
1220
+ windowId,
1221
+ lastUpdatedAt: Date.now(),
1222
+ openerTab: { ...openerTab },
1223
+ };
1224
+ this.openTabs.set(tabId, entry);
1225
+ }
1226
+
1227
+ chrome_webNavigation_onBeforeNavigate(details) {
1228
+ if (details.frameId !== 0) {
1229
+ return;
1230
+ }
1231
+ const { tabId, url } = details;
1232
+ const oldEntry = this.openTabs.get(tabId);
1233
+ if (oldEntry && oldEntry.url !== url) {
1234
+ // Invalidate the page id since there will be a navigation in the near future.
1235
+ // The tab API should handle the update, but all pending operations that
1236
+ // inspect the content of the page should be aborted.
1237
+ this.openTabs.set(tabId, {
1238
+ ...oldEntry,
1239
+ pageId: ++this._pageIdGenerator,
1240
+ lastUpdatedAt: Date.now(),
1241
+ });
1242
+ }
1243
+ }
1244
+
1245
+ // has two interesting fields in details:
1246
+ // - transitionQualifiers: ['forward_back']
1247
+ // - transitionType: "link"
1248
+ //
1249
+ // Safari quirks:
1250
+ // * The API exists, but "transitionType" is not supported
1251
+ chrome_webNavigation_onCommitted(details) {
1252
+ if (details.frameId !== 0) {
1253
+ return;
1254
+ }
1255
+ const isBackOrForward =
1256
+ details.transitionQualifiers?.includes('forward_back');
1257
+
1258
+ // TODO for Safari: according to their docs, transitionType is not supported
1259
+ let forgetOpenedFrom = details.transitionType !== 'link';
1260
+ if (isBackOrForward) {
1261
+ // Maybe we could be smarter here; unfortunately the API gives no clues
1262
+ // whether it was a back or a forward navigation. As a workaround, forget
1263
+ // all information that may be wrong. In some situation it may be possible
1264
+ // to prove that it was a forward navigation (in that case, we should
1265
+ // not clear the information).
1266
+ // See also https://stackoverflow.com/q/25542015/783510
1267
+ forgetOpenedFrom = true;
1268
+ }
1269
+ if (forgetOpenedFrom) {
1270
+ const { tabId } = details;
1271
+ const oldEntry = this.openTabs.get(tabId);
1272
+ if (oldEntry?.previousUrl || oldEntry?.openedFrom) {
1273
+ // this creates a copy, but omits the fields related to "opened from"
1274
+ // eslint-disable-next-line no-unused-vars
1275
+ const { previousUrl, openedFrom, search, ...entry } = { ...oldEntry };
1276
+ this.openTabs.set(tabId, entry);
1277
+ }
1278
+ }
1279
+ }
1280
+
1281
+ // TODO: this needs to be thought through (the timing between chrome.tab and webNavigation might be subtle)
1282
+ //
1283
+ // Safari quirks:
1284
+ // * This API is not available
1285
+ chrome_webNavigation_onHistoryStateUpdated(details) {
1286
+ const { tabId } = details;
1287
+ const entry = this.openTabs.get(tabId);
1288
+ if (!entry) {
1289
+ logger.warn('Navigation event in a non-existing tab detected!');
1290
+ return;
1291
+ }
1292
+ this.openTabs.set(tabId, {
1293
+ ...entry,
1294
+ pageLoadMethod: 'history-navigation',
1295
+ status: 'after-history-state-update',
1296
+ lastUpdatedAt: Date.now(),
1297
+ pageId: ++this._pageIdGenerator,
1298
+ });
1299
+ }
1300
+
1301
+ chrome_windows_onRemoved(windowId) {
1302
+ if (windowId !== WINDOW_ID_NONE) {
1303
+ this.activeTab.removeWindow(windowId);
1304
+ }
1305
+ }
1306
+
1307
+ /**
1308
+ * This API makes more sense on Desktop than on Mobile:
1309
+ * - Unavailabe on Firefox for Android.
1310
+ * - Safari on iOS (https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/API/windows/onFocusChanged):
1311
+ * > Fires when toggling in or out of private browsing mode, leaving Safari
1312
+ * > to the home screen, and returning to Safari from the home screen.
1313
+ */
1314
+ chrome_windows_onFocusChanged(windowId) {
1315
+ if (windowId !== WINDOW_ID_NONE) {
1316
+ this.activeTab.focusWindow(windowId);
1317
+ }
1318
+ }
1319
+
1320
+ /**
1321
+ * Tabs can be closed at any point. This function detects such cases
1322
+ * and warns as a side-effect. Thus, it should be used only in situations
1323
+ * where it is possible, but unexpected that the tab is gone.
1324
+ */
1325
+ _tabVanished(tabId, pageId, ...details) {
1326
+ const entry = this.openTabs.get(tabId);
1327
+ if (!entry) {
1328
+ logger.debug('Tab', tabId, 'closed:', ...details);
1329
+ return true;
1330
+ }
1331
+ if (entry.pageId !== pageId) {
1332
+ logger.debug('Tab', tabId, 'changed pageId:', ...details);
1333
+ return true;
1334
+ }
1335
+ return false;
1336
+ }
1337
+
1338
+ _cacheDnsResolution(url, ip) {
1339
+ if (
1340
+ this.dnsResolver.cacheDnsResolution({ url, ip }) &&
1341
+ this.sessionStore.isReady()
1342
+ ) {
1343
+ this.sessionStore.set('dnsResolver', this.dnsResolver.serialize());
1344
+ }
1345
+ }
1346
+
1347
+ _initVisibility(tabId, entry) {
1348
+ if (!entry.visibility) {
1349
+ const { visibility, search } = this._checkPageVisibility(entry.url);
1350
+ entry.visibility = visibility;
1351
+ if (visibility !== 'private') {
1352
+ if (search) {
1353
+ entry.search = {
1354
+ category: search.category,
1355
+ query: search.query,
1356
+ depth: 0,
1357
+ lastUpdatedAt: Date.now(),
1358
+ };
1359
+ }
1360
+ }
1361
+ }
1362
+ }
1363
+
1364
+ _initAllOptionalFields(tabId, entry) {
1365
+ const now = Date.now();
1366
+ const { pageId } = entry;
1367
+ this._initVisibility(tabId, entry, now);
1368
+ this._tryAnalyzePageStructure(tabId, entry, now);
1369
+
1370
+ // Note: this benefits from running after the page structure.
1371
+ // Unless there is a reason, do not move it up.
1372
+ this._tryLanguageDetection(tabId, pageId, entry);
1373
+ }
1374
+
1375
+ _tryLanguageDetection(tabId, pageId, entry) {
1376
+ this._setLazyVar('language', entry, tabId, {
1377
+ precond: () => entry.visibility !== 'private' && isRealPage(entry.url),
1378
+ init: () => this._detectLanguage(tabId, pageId, entry),
1379
+ });
1380
+ }
1381
+
1382
+ /**
1383
+ * There are three types of results:
1384
+ *
1385
+ * 1) If it was successful in detecting a language, it returns something
1386
+ * 'en', 'de', 'fr'.
1387
+ * 2) If the language could not be detected by the API or belonged to a
1388
+ * group that is considered too small to be safe, '--' will be returned.
1389
+ * 3) If the language detection was skipped, it returns an empty string ('')
1390
+ */
1391
+ async _detectLanguage(tabId, pageId, entry) {
1392
+ if (!this.chrome?.tabs?.detectLanguage) {
1393
+ return ''; // the API is not available on all platforms (e.g. Firefox for Android)
1394
+ }
1395
+
1396
+ // If the website does not want to be indexed, there is
1397
+ // no point in running a costly language detection.
1398
+ if (entry.pageStructure) {
1399
+ try {
1400
+ const structure = await this._awaitLazyVar(entry.pageStructure);
1401
+ if (structure?.noindex) {
1402
+ logger.debug(
1403
+ 'No need to detect the language, since the page is private',
1404
+ );
1405
+ return '';
1406
+ }
1407
+ } catch (e) {
1408
+ logger.warn(
1409
+ 'Unexpected error while waiting for the page structure:',
1410
+ e,
1411
+ );
1412
+ return '';
1413
+ }
1414
+ }
1415
+
1416
+ if (this._tabVanished(tabId, pageId, 'before detectLanguage')) {
1417
+ return CANCEL_LAZY_VAR;
1418
+ }
1419
+ try {
1420
+ const lang = await this.chrome.tabs.detectLanguage(tabId);
1421
+ const normalizedLang = this._normalizeDetectedLanguage(lang);
1422
+ logger.debug(
1423
+ 'detected language for tabID',
1424
+ tabId,
1425
+ ':',
1426
+ lang,
1427
+ '->',
1428
+ normalizedLang,
1429
+ );
1430
+ return normalizedLang;
1431
+ } catch (e) {
1432
+ if (this._tabVanished(tabId, pageId, 'during detectLanguage')) {
1433
+ return CANCEL_LAZY_VAR;
1434
+ }
1435
+ if (e.message === 'Cannot determine language') {
1436
+ logger.debug('API to detect language is not available', e);
1437
+ return '';
1438
+ }
1439
+
1440
+ logger.warn('Unexpected error', e);
1441
+ return '';
1442
+ }
1443
+ }
1444
+
1445
+ /**
1446
+ * Takes the output of chrome.tabs.detectLanguage and maps it to well-known values.
1447
+ * If possible, avoid browser-specific differences (e.g. "de" on Firefox/Chrome vs
1448
+ * "de-DE" on Safari). Also, hide languages that we did not expect, or that are
1449
+ * expected to be relatively rare.
1450
+ */
1451
+ _normalizeDetectedLanguage(lang) {
1452
+ this.langStats[lang] = (this.langStats[lang] || 0) + 1;
1453
+
1454
+ const cleanedLang = split0(lang, '-');
1455
+ switch (cleanedLang) {
1456
+ // Note: the following list was taken from Chrome and checked on Wikipedia
1457
+ // homepages. Smaller languages that were not consistently detected by Firefox
1458
+ // where removed.
1459
+ case 'af': // Africaans
1460
+ case 'ar': // Arabic
1461
+ case 'ca': // Catalan
1462
+ case 'cs': // Czech
1463
+ case 'da': // Danish
1464
+ case 'de': // German
1465
+ case 'el': // Greek
1466
+ case 'en': // English
1467
+ case 'es': // Spanish
1468
+ case 'fa': // Persian
1469
+ case 'fi': // Finish
1470
+ case 'fr': // French
1471
+ case 'hi': // Hindi
1472
+ case 'hr': // Croatian
1473
+ case 'hu': // Hungarian
1474
+ case 'id': // Indonesian
1475
+ case 'it': // Italian
1476
+ case 'ja': // Japanese
1477
+ case 'ko': // Korean
1478
+ case 'nl': // Dutch
1479
+ case 'no': // Norwegian
1480
+ case 'pl': // Polish
1481
+ case 'pt': // Portuguese
1482
+ case 'ro': // Romanian
1483
+ case 'ru': // Russian
1484
+ case 'sk': // Slovak
1485
+ case 'sl': // Slovenian
1486
+ case 'sq': // Albanian
1487
+ case 'sr': // Serbian
1488
+ case 'sv': // Swedish
1489
+ case 'th': // Thai
1490
+ case 'tr': // Turkish
1491
+ case 'uk': // Ukrainian
1492
+ case 'vi': // Vietnamese
1493
+ case 'zh': // Chinese
1494
+ return cleanedLang;
1495
+
1496
+ case 'und':
1497
+ // Firefox and Chrome return 'und' for unknown languages
1498
+ return '--';
1499
+
1500
+ // An incomplete list of languages where the number of speakers is low.
1501
+ // You can put them here if you want to suppress a warning.
1502
+ case 'la': // Latin
1503
+ case 'fy': // Frisian
1504
+ case 'yi': // Yiddish
1505
+ case 'iw': // Hebrew (Chrome)
1506
+ case 'he': // Hebrew (Firefox)
1507
+ return '--';
1508
+ }
1509
+
1510
+ if (this.langStats[lang] === 1) {
1511
+ logger.info('Unexpected language:', lang);
1512
+ }
1513
+ return '--';
1514
+ }
1515
+
1516
+ _tryAnalyzePageStructure(tabId, entry) {
1517
+ const { pageId } = entry;
1518
+ this._setLazyVar('pageStructure', entry, tabId, {
1519
+ precond: () =>
1520
+ entry.status === 'complete' &&
1521
+ entry.visibility !== 'private' &&
1522
+ isRealPage(entry.url),
1523
+ init: () => this._analyzePageStructure(tabId, pageId),
1524
+ });
1525
+ }
1526
+
1527
+ async _analyzePageStructure(tabId, pageId) {
1528
+ if (this._tabVanished(tabId, pageId, 'before analyzePageStructure')) {
1529
+ return CANCEL_LAZY_VAR;
1530
+ }
1531
+ try {
1532
+ const wrappedResult = await chrome.scripting.executeScript({
1533
+ target: {
1534
+ tabId,
1535
+ },
1536
+ func: analyzePageStructure,
1537
+ });
1538
+ const { result } = wrappedResult[0];
1539
+ if (this._tabVanished(tabId, pageId, 'after analyzePageStructure')) {
1540
+ logger.warn(
1541
+ 'analyzePageStructure completed but the page has changed. Ignoring results:',
1542
+ result,
1543
+ );
1544
+ return CANCEL_LAZY_VAR;
1545
+ }
1546
+ logger.debug('Page structure:', result);
1547
+ return {
1548
+ ...result,
1549
+ lastUpdatedAt: Date.now(),
1550
+ };
1551
+ } catch (e) {
1552
+ // On Chrome, it is expected to fail on the extension store
1553
+ // (e.g. https://chrome.google.com/webstore/category/recommended_extensions?hl=en)
1554
+ const msg = e.message;
1555
+ if (msg === 'The extensions gallery cannot be scripted.') {
1556
+ return {
1557
+ noindex: true,
1558
+ details: msg,
1559
+ };
1560
+ }
1561
+ if (this._tabVanished(tabId, pageId, 'during analyzePageStructure')) {
1562
+ return CANCEL_LAZY_VAR;
1563
+ }
1564
+
1565
+ // On Chrome: if the page did not load
1566
+ if (
1567
+ msg.startsWith('Frame with ID') &&
1568
+ msg.endsWith('is showing error page')
1569
+ ) {
1570
+ return {
1571
+ noindex: true,
1572
+ details: 'Page failed to load',
1573
+ };
1574
+ }
1575
+
1576
+ logger.error('Unable to extract structural information', e);
1577
+ return {
1578
+ error: true,
1579
+ details: `Unable to run analyzePageStructure script (reason: ${e})`,
1580
+ noindex: true,
1581
+ };
1582
+ }
1583
+ }
1584
+
1585
+ // TODO:
1586
+ // Maybe extract this functionality.
1587
+ // Caching old values could also help. Not primarily for performance
1588
+ // (though it could make help for that as well), but to put "unknown"
1589
+ // into the right visibility category if possible.
1590
+ _checkPageVisibility(url) {
1591
+ if (!isRealPage(url)) {
1592
+ return {
1593
+ visibility: 'private',
1594
+ reason: 'not an HTTP page',
1595
+ };
1596
+ }
1597
+
1598
+ const { category, query } = this.urlAnalyzer.parseSearchLinks(url);
1599
+ if (category && query) {
1600
+ const normalizedCategory = category.startsWith('search-')
1601
+ ? category.slice('search-'.length)
1602
+ : category;
1603
+ return {
1604
+ visibility: 'public',
1605
+ reason: 'indexed by search engine',
1606
+ search: {
1607
+ category: normalizedCategory,
1608
+ query,
1609
+ },
1610
+ };
1611
+ }
1612
+
1613
+ if (this.dnsResolver.isPrivateURL(url)) {
1614
+ return {
1615
+ visibility: 'private',
1616
+ reason: 'private network',
1617
+ };
1618
+ }
1619
+
1620
+ return {
1621
+ visibility: 'unknown',
1622
+ reason: 'further checks are needed',
1623
+ };
1624
+ }
1625
+
1626
+ // This provides a low-level mechanism to safely deal with values
1627
+ // that need asynchronous initialization.
1628
+ // Other classes should not be aware of it, since they should only
1629
+ // operate on snapshots (which don't export myChecks operations).
1630
+ // Neither should it be needed to understand it while accessing values
1631
+ // during debugging; once the operations are finished, they only
1632
+ // the actual results will be preserved.
1633
+ //
1634
+ // Notes:
1635
+ // - "asyncInit" is not expected not throw. If it may fail, define an
1636
+ // explicit error state (e.g. CANCEL_LAZY_VAR) and resolve with that.
1637
+ // - To safely read the value, you can use the "_tryUnwrapLazyVar" helper.
1638
+ // Note that "CANCEL_LAZY_VAR" will be interpreted as error cases
1639
+ // and results in missing values (i.e. the callback does not trigger).
1640
+ // - There is limited support for lazy vars to depend on each other
1641
+ // (see _awaitLazyVar), but be careful when using it since you get
1642
+ // only weak guarantees (e.g. the lazy var might not be present yet).
1643
+ // If you have important dependencies, consider merging them together
1644
+ // in one big lazy var (within the async init, dependencies are
1645
+ // easier to manage).
1646
+ _setLazyVar(field, entry, tabId, { init: asyncInit, precond = () => true }) {
1647
+ if (!entry[field] && precond()) {
1648
+ entry[field] = {
1649
+ _pending: asyncInit(),
1650
+ };
1651
+ entry[field]._pending
1652
+ .then((result) => {
1653
+ const now = Date.now();
1654
+ entry[field].result = result;
1655
+ entry[field].resolvedAt = now;
1656
+ entry.lastUpdatedAt = now;
1657
+
1658
+ if (this.openTabs.get(tabId)?.[field] === entry[field]) {
1659
+ const entry_ = this.openTabs.get(tabId);
1660
+ entry_[field] = result;
1661
+ entry_.lastUpdatedAt = now;
1662
+ }
1663
+ entry[field] = result;
1664
+
1665
+ this._onTabChanged(tabId);
1666
+ this.notifyObservers({
1667
+ type: 'lazy-init',
1668
+ field,
1669
+ tabId,
1670
+ });
1671
+ })
1672
+ .catch((e) => {
1673
+ logger.error(
1674
+ `Internal error while initializing field: "${field}" (it is a bug in the code)`,
1675
+ e,
1676
+ );
1677
+ });
1678
+ }
1679
+ }
1680
+
1681
+ _tryUnwrapLazyVar(value, callbackIfPresent) {
1682
+ if (!isNil(value) && value !== CANCEL_LAZY_VAR) {
1683
+ if (!value._pending) {
1684
+ callbackIfPresent(value);
1685
+ } else if (!isNil(value.result) && value.result !== CANCEL_LAZY_VAR) {
1686
+ callbackIfPresent(value.result);
1687
+ }
1688
+ }
1689
+ }
1690
+
1691
+ async _awaitLazyVar(value) {
1692
+ if (!value) {
1693
+ throw new Error(
1694
+ 'Lazy var not found (cannot await a lazy var before it has been initialized)',
1695
+ );
1696
+ }
1697
+ await value._pending;
1698
+ return value._pending ? value.result : value;
1699
+ }
1700
+
1701
+ /**
1702
+ * Listeners defined in this class follow a naming convention, for instance:
1703
+ * - "chrome_tabs_onCreated" (listener for chrome.tabs.onCreated)
1704
+ * - "chrome_webNavigation_onCommitted" (chrome.webNavigation.onCommitted)
1705
+ *
1706
+ * Example output:
1707
+ * [
1708
+ * { method: 'chrome_tabs_onCreated', api: 'tabs', type: 'onCreated' },
1709
+ * { method: 'chrome_webNavigation_onCommitted', api: 'webNavigation', type: 'onCommitted' },
1710
+ * ]
1711
+ */
1712
+ static describeListeners() {
1713
+ const listeners = Object.getOwnPropertyNames(Pages);
1714
+ return ['webRequest', 'webNavigation', 'tabs', 'windows'].flatMap((api) => {
1715
+ const prefix = `chrome_${api}_`;
1716
+ return listeners
1717
+ .filter((method) => method.startsWith(prefix))
1718
+ .map((method) => ({
1719
+ method,
1720
+ api,
1721
+ type: method.slice(prefix.length),
1722
+ }));
1723
+ });
1724
+ }
1725
+
1726
+ async selfChecks(check = new SelfCheck()) {
1727
+ const myChecks = (async () => {
1728
+ if (this.isActive) {
1729
+ if (this.sessionStore.isReady()) {
1730
+ const expectedSession = this._serializeFullSession();
1731
+ const detectedPromises = flattenObject(expectedSession).filter(
1732
+ ({ path }) =>
1733
+ path.includes('_pending') || path.includes(CANCEL_LAZY_VAR._tag),
1734
+ );
1735
+ if (detectedPromises.length > 0) {
1736
+ check.fail('Promises must not be serialized', { detectedPromises });
1737
+ } else {
1738
+ const realSession = this.sessionStore.getEntries();
1739
+ if (equalityCanBeProven(expectedSession, realSession)) {
1740
+ check.pass('Session in sync', {
1741
+ expectedSession,
1742
+ realSession,
1743
+ });
1744
+ } else {
1745
+ check.warn('Session may be out to sync', {
1746
+ expectedSession,
1747
+ realSession,
1748
+ });
1749
+ }
1750
+ }
1751
+ } else {
1752
+ check.warn('initialization of sessionStore not finished');
1753
+ }
1754
+ }
1755
+
1756
+ // check page ids:
1757
+ // - all entry *must* have page ids
1758
+ // - page ids *should* be unique
1759
+ const tabsWithMissingPageIds = [];
1760
+ const pageIds = new Set();
1761
+ const pageIdClashes = [];
1762
+ for (const [tabId, entry] of this.openTabs.entries()) {
1763
+ if (!entry.pageId) {
1764
+ tabsWithMissingPageIds.push([tabId, entry]);
1765
+ }
1766
+ if (pageIds.has(tabId)) {
1767
+ // not an error, but by construction, it should be extremely
1768
+ // unlikely that this happens
1769
+ pageIdClashes.push([tabId, entry]);
1770
+ } else {
1771
+ pageIds.add(tabId);
1772
+ }
1773
+ }
1774
+ if (tabsWithMissingPageIds.length > 0) {
1775
+ check.fail(
1776
+ 'Found entry without page ids',
1777
+ Object.fromEntries(tabsWithMissingPageIds),
1778
+ );
1779
+ }
1780
+ if (pageIdClashes.length > 0) {
1781
+ check.warn('Found a pageId clash', Object.fromEntries(pageIdClashes));
1782
+ }
1783
+ })();
1784
+ await Promise.all([
1785
+ myChecks,
1786
+ eventListenerQueue.selfChecks(check.for('eventListenerQueue')),
1787
+ this.activeTab.selfChecks(check.for('activeTab')),
1788
+ this.activityEstimator.selfChecks(check.for('activityEstimator')),
1789
+ ]);
1790
+ return check;
1791
+ }
1792
+ }
1793
+
1794
+ export const eventListenerQueue = new EventListenerQueue({
1795
+ connectTimeoutInMs: 1000,
1796
+ maxBufferLength: 1024,
1797
+ listeners: Pages.describeListeners(),
1798
+ });