@whotracksme/reporting 8.0.2 → 9.0.1

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.
@@ -39,9 +39,11 @@ import {
39
39
  checkValidContext,
40
40
  } from './steps/check-context.js';
41
41
  import PageStore from './page-store.js';
42
+ import ChromeStorageMap from './utils/chrome-storage-map.js';
42
43
 
43
44
  const DAY_CHANGE_INTERVAL = 20 * 1000;
44
45
  const RECENTLY_MODIFIED_TTL = 30 * 1000;
46
+ const REPORTED_DOCUMENTS_TTL = 5 * 60 * 1000;
45
47
 
46
48
  function hasBlockingWebRequest() {
47
49
  return chrome.runtime
@@ -87,6 +89,13 @@ export default class RequestReporter {
87
89
  this.pageStore = new PageStore({
88
90
  notifyPageStageListeners: this.onPageStaged.bind(this),
89
91
  });
92
+ // Dedupe tp_events by root documentId so a SW restart that
93
+ // re-flushes a not-yet-persisted #pages.delete can't emit the
94
+ // same page twice.
95
+ this.reportedDocuments = new ChromeStorageMap({
96
+ storageKey: 'wtm-request-reporting:reported-documents',
97
+ ttlInMs: REPORTED_DOCUMENTS_TTL,
98
+ });
90
99
 
91
100
  this.ready = false;
92
101
 
@@ -251,6 +260,7 @@ export default class RequestReporter {
251
260
  DAY_CHANGE_INTERVAL,
252
261
  );
253
262
 
263
+ await this.reportedDocuments.isReady;
254
264
  await this.pageStore.init();
255
265
 
256
266
  this.pageLogger = new PageLogger(this.config.placeHolder);
@@ -719,6 +729,9 @@ export default class RequestReporter {
719
729
 
720
730
  onPageStaged(page) {
721
731
  if (page.state === 'complete' && !page.isPrivate && !page.isPrivateServer) {
732
+ if (this.reportedDocuments.has(page.documentId)) {
733
+ return;
734
+ }
722
735
  const payload = buildPageLoadObject(page);
723
736
  if (
724
737
  payload.scheme.startsWith('http') &&
@@ -728,6 +741,7 @@ export default class RequestReporter {
728
741
  action: 'wtm.attrack.tp_events',
729
742
  payload: [payload],
730
743
  });
744
+ this.reportedDocuments.set(page.documentId, 1);
731
745
  }
732
746
  }
733
747
  }
@@ -9,13 +9,18 @@
9
9
  * file, You can obtain one at http://mozilla.org/MPL/2.0
10
10
  */
11
11
 
12
+ import logger from '../logger.js';
12
13
  import ChromeStorageMap from './utils/chrome-storage-map.js';
13
14
 
14
15
  const PAGE_TTL = 1000 * 60 * 60; // 1 hour
15
16
 
17
+ const BFCACHE_TTL_MS = 10 * 60 * 1000;
18
+ // Min gap between sweeps driven by webNavigation.onCompleted, so a
19
+ // burst of navigations doesn't trigger N tabs.query/getAllFrames
20
+ // roundtrips back-to-back.
21
+ const FLUSH_THROTTLE_MS = 30 * 1000;
22
+
16
23
  const PAGE_LOADING_STATE = {
17
- CREATED: 'created',
18
- NAVIGATING: 'navigating',
19
24
  COMMITTED: 'committed',
20
25
  COMPLETE: 'complete',
21
26
  };
@@ -29,76 +34,80 @@ function makePageActive(page, active) {
29
34
  }
30
35
  }
31
36
 
32
- function createPageFromTab(tab) {
33
- const { id, active, url, incognito, created } = tab;
34
- const page = {};
35
- page.id = id;
36
- page.url = url;
37
- page.isPrivate = incognito || false;
38
- page.isPrivateServer = false;
39
- page.created = created || Date.now();
40
- page.destroyed = null;
41
- page.frames = {
42
- 0: {
43
- parentFrameId: -1,
44
- url,
45
- },
37
+ function createPage({ tabId, documentId, url, isPrivate, active }) {
38
+ return {
39
+ id: tabId,
40
+ documentId,
41
+ documentIds: [documentId],
42
+ url,
43
+ isPrivate: !!isPrivate,
44
+ isPrivateServer: false,
45
+ created: Date.now(),
46
+ destroyed: null,
47
+ // Wall-clock instant at which the next sweep should stage this
48
+ // page. null while the page is live; set to `now + BFCACHE_TTL_MS`
49
+ // when a sweep first finds no live doc; 0 when the tab is
50
+ // closed/discarded; cleared on bfcache restore.
51
+ stageAfter: null,
52
+ state: PAGE_LOADING_STATE.COMMITTED,
53
+ activeTime: 0,
54
+ activeFrom: active ? Date.now() : 0,
55
+ requestStats: {},
56
+ annotations: {},
57
+ counter: 0,
46
58
  };
47
- page.state = PAGE_LOADING_STATE.CREATED;
48
-
49
- page.activeTime = 0;
50
- page.activeFrom = active ? Date.now() : 0;
51
-
52
- page.requestStats = {};
53
- page.annotations = {};
54
- page.counter = 0;
55
- page.previous = null;
56
- return page;
57
59
  }
58
60
 
59
61
  export default class PageStore {
60
62
  #notifyPageStageListeners;
63
+ // rootDocumentId -> page; persisted across SW restarts.
61
64
  #pages;
65
+ // Any documentId (root or sub-frame) -> owning page. Rebuilt on init.
66
+ #documentIndex;
67
+ // tabId -> { isPrivate, active }; used at commit time so a new page
68
+ // inherits the current tab's flags.
69
+ #tabContext;
70
+ #lastFlush = 0;
62
71
 
63
72
  constructor({ notifyPageStageListeners }) {
64
73
  this.#pages = new ChromeStorageMap({
65
- storageKey: 'wtm-url-reporting:page-store:tabs',
74
+ storageKey: 'wtm-request-reporting:page-store:pages',
66
75
  ttlInMs: PAGE_TTL,
67
76
  });
77
+ this.#documentIndex = new Map();
78
+ this.#tabContext = new Map();
68
79
  this.#notifyPageStageListeners = notifyPageStageListeners;
69
80
  }
70
81
 
71
82
  async init() {
72
83
  await this.#pages.isReady;
84
+ for (const page of this.#pages.values()) {
85
+ for (const docId of page.documentIds) {
86
+ this.#documentIndex.set(docId, page);
87
+ }
88
+ }
89
+ // Seed tabContext before subscribing so a concurrent onCommitted
90
+ // can't create a page with default isPrivate/active flags.
91
+ for (const tab of await chrome.tabs.query({})) {
92
+ this.#onTabCreated(tab);
93
+ }
73
94
  chrome.tabs.onCreated.addListener(this.#onTabCreated);
74
95
  chrome.tabs.onUpdated.addListener(this.#onTabUpdated);
75
96
  chrome.tabs.onRemoved.addListener(this.#onTabRemoved);
76
97
  chrome.tabs.onActivated.addListener(this.#onTabActivated);
77
- chrome.webNavigation.onBeforeNavigate.addListener(this.#onBeforeNavigate);
78
98
  chrome.webNavigation.onCommitted.addListener(this.#onNavigationCommitted);
79
99
  chrome.webNavigation.onCompleted.addListener(this.#onNavigationCompleted);
80
-
81
- // Note: not available on Firefox Android
100
+ // Not available on Firefox Android.
82
101
  chrome.windows?.onFocusChanged?.addListener(this.#onWindowFocusChanged);
83
-
84
- // popupate initially open tabs
85
- (await chrome.tabs.query({})).forEach((tab) => this.#onTabCreated(tab));
86
102
  }
87
103
 
88
104
  unload() {
89
- this.#pages.forEach((serializedPage) => {
90
- const page = createPageFromTab(serializedPage);
91
- this.#stagePage(page);
92
- });
93
- this.#pages.clear();
94
-
105
+ this.#documentIndex.clear();
106
+ this.#tabContext.clear();
95
107
  chrome.tabs.onCreated.removeListener(this.#onTabCreated);
96
108
  chrome.tabs.onUpdated.removeListener(this.#onTabUpdated);
97
109
  chrome.tabs.onRemoved.removeListener(this.#onTabRemoved);
98
110
  chrome.tabs.onActivated.removeListener(this.#onTabActivated);
99
- chrome.webNavigation.onBeforeNavigate.removeListener(
100
- this.#onBeforeNavigate,
101
- );
102
111
  chrome.webNavigation.onCommitted.removeListener(
103
112
  this.#onNavigationCommitted,
104
113
  );
@@ -109,214 +118,213 @@ export default class PageStore {
109
118
  }
110
119
 
111
120
  checkIfEmpty() {
112
- // this operations can potentially be expensive
121
+ // this operation can potentially be expensive
113
122
  return this.#pages.countNonExpiredKeys() === 0;
114
123
  }
115
124
 
116
- #stagePage(page) {
117
- makePageActive(page, false);
118
- page.destroyed = Date.now();
119
- // unset previous (to prevent history chain memory leak)
120
- page.previous = undefined;
121
- this.#pages.set(page.id, page);
122
- this.#notifyPageStageListeners(page);
125
+ // Test helper: returns the first stored page for `tabId`.
126
+ findPageForTab(tabId) {
127
+ for (const page of this.#pages.values()) {
128
+ if (page.id === tabId) return page;
129
+ }
130
+ return undefined;
123
131
  }
124
132
 
125
- /**
126
- * Create a new `tabContext` for the new tab
127
- */
128
- #onTabCreated = (tab) => {
129
- this.#pages.set(tab.id, createPageFromTab(tab));
130
- };
131
-
132
- /**
133
- * Update an existing tab or create it if we do not have a context yet.
134
- */
135
- #onTabUpdated = (tabId, info, tab) => {
136
- let page = this.#pages.get(tabId);
137
- if (!page) {
138
- page = createPageFromTab(tab);
133
+ // Stage pages whose tab is gone or whose docs have been absent
134
+ // from the live set for BFCACHE_TTL_MS.
135
+ async flush() {
136
+ const live = await this.#collectLiveDocumentIds();
137
+ const now = Date.now();
138
+ this.#lastFlush = now;
139
+ for (const page of this.#pages.values()) {
140
+ if (page.documentIds.some((d) => live.has(d))) {
141
+ if (page.stageAfter !== null) {
142
+ page.stageAfter = null;
143
+ this.#pages.set(page.documentId, page);
144
+ }
145
+ } else if (page.stageAfter === null) {
146
+ page.stageAfter = now + BFCACHE_TTL_MS;
147
+ this.#pages.set(page.documentId, page);
148
+ } else if (now >= page.stageAfter) {
149
+ this.#stagePage(page);
150
+ }
139
151
  }
152
+ }
140
153
 
141
- // Update `isPrivate` and `url` if available
142
- page.isPrivate = tab.incognito;
143
- makePageActive(page, tab.active);
144
- if (info.url !== undefined) {
145
- page.url = info.url;
154
+ async #collectLiveDocumentIds() {
155
+ const live = new Set();
156
+ for (const tab of await chrome.tabs.query({})) {
157
+ try {
158
+ const frames = await chrome.webNavigation.getAllFrames({
159
+ tabId: tab.id,
160
+ });
161
+ for (const frame of frames) {
162
+ if (frame.documentId) live.add(frame.documentId);
163
+ }
164
+ } catch (e) {
165
+ // Tab can disappear between tabs.query and getAllFrames.
166
+ // Skip it — its docs will look gone, which is fine.
167
+ logger.debug('PageStore: getAllFrames failed for tab', tab.id, e);
168
+ }
146
169
  }
170
+ return live;
171
+ }
147
172
 
148
- this.#pages.set(tabId, page);
149
- };
150
-
151
- /**
152
- * Remove tab context for `tabId`.
153
- */
154
- #onTabRemoved = (tabId) => {
155
- const page = this.#pages.get(tabId);
156
- if (!page) {
157
- return;
173
+ #stagePage(page) {
174
+ for (const docId of page.documentIds) {
175
+ this.#documentIndex.delete(docId);
158
176
  }
159
- if (page.state === PAGE_LOADING_STATE.COMPLETE) {
160
- this.#stagePage(page);
177
+ this.#pages.delete(page.documentId);
178
+ const snapshot = structuredClone(page);
179
+ makePageActive(snapshot, false);
180
+ snapshot.destroyed = Date.now();
181
+ this.#notifyPageStageListeners(snapshot);
182
+ }
183
+
184
+ #indexDocument(page, documentId) {
185
+ if (!page.documentIds.includes(documentId)) {
186
+ page.documentIds.push(documentId);
161
187
  }
162
- this.#pages.delete(tabId);
163
- };
188
+ this.#documentIndex.set(documentId, page);
189
+ }
164
190
 
165
- #onTabActivated = (details) => {
166
- const { previousTabId, tabId } = details;
167
- // if previousTabId is not set (e.g. on chrome), set all tabs to inactive
168
- // otherwise, we only have to mark the previous tab as inactive
169
- if (!previousTabId) {
170
- for (const page of this.#pages.values()) {
171
- makePageActive(page, false);
172
- this.#pages.set(page.id, page);
191
+ #setTabActive(tabId, active) {
192
+ const ctx = this.#tabContext.get(tabId);
193
+ if (ctx) ctx.active = active;
194
+ for (const page of this.#pages.values()) {
195
+ if (page.id === tabId) {
196
+ makePageActive(page, active);
197
+ this.#pages.set(page.documentId, page);
173
198
  }
174
- } else if (this.#pages.has(previousTabId)) {
175
- const previousPage = this.#pages.get(previousTabId);
176
- makePageActive(previousPage, false);
177
- this.#pages.set(previousPage.id, previousPage);
178
199
  }
200
+ }
179
201
 
180
- if (this.#pages.has(tabId)) {
181
- const page = this.#pages.get(tabId);
182
- makePageActive(page, true);
183
- this.#pages.set(page.id, page);
184
- }
202
+ #onTabCreated = (tab) => {
203
+ this.#tabContext.set(tab.id, {
204
+ isPrivate: !!tab.incognito,
205
+ active: !!tab.active,
206
+ });
185
207
  };
186
208
 
187
- // Note: not available on Firefox Android
188
- #onWindowFocusChanged = async (focusedWindowId) => {
189
- const activeTabs = await chrome.tabs.query({ active: true });
190
- for (const { id, windowId } of activeTabs) {
191
- const page = this.#pages.get(id);
192
- if (!page) {
193
- continue;
209
+ #onTabUpdated = (tabId, info, tab) => {
210
+ if (info.discarded) {
211
+ // Memory-discarded tab: docs are gone but onRemoved won't fire
212
+ // until the user closes the tab.
213
+ this.#markTabGone(tabId);
214
+ return;
215
+ }
216
+ const ctx = {
217
+ isPrivate: !!tab.incognito,
218
+ active: !!tab.active,
219
+ };
220
+ this.#tabContext.set(tabId, ctx);
221
+ for (const page of this.#pages.values()) {
222
+ if (page.id === tabId) {
223
+ page.isPrivate = ctx.isPrivate;
224
+ makePageActive(page, ctx.active);
225
+ this.#pages.set(page.documentId, page);
194
226
  }
195
- makePageActive(page, windowId === focusedWindowId);
196
- this.#pages.set(id, page);
197
227
  }
198
228
  };
199
229
 
200
- #onBeforeNavigate = (details) => {
201
- const { frameId, tabId, url, timeStamp } = details;
230
+ #onTabRemoved = (tabId) => {
231
+ this.#tabContext.delete(tabId);
232
+ this.#markTabGone(tabId);
233
+ };
202
234
 
203
- if (frameId !== 0) {
204
- return;
235
+ #markTabGone(tabId) {
236
+ for (const page of this.#pages.values()) {
237
+ if (page.id === tabId) {
238
+ page.stageAfter = 0;
239
+ this.#pages.set(page.documentId, page);
240
+ }
205
241
  }
242
+ // Tab close is a definitive end-of-life signal; flush eagerly
243
+ // (no throttle) so the page emits before the SW can suspend.
244
+ this.flush().catch((e) =>
245
+ logger.debug('PageStore: flush after tab gone failed', e),
246
+ );
247
+ }
206
248
 
207
- const page = this.#pages.get(tabId);
208
-
209
- if (page) {
210
- // ignore duplicated #onBeforeNavigate https://bugzilla.mozilla.org/show_bug.cgi?id=1732564
211
- if (
212
- page.id === tabId &&
213
- page.url === url &&
214
- page.created + 200 > timeStamp
215
- ) {
216
- return;
217
- }
218
- // We are starting a navigation to a new page - if the previous page is complete (i.e. fully
219
- // loaded), stage it before we create the new page info.
220
- if (page.state === PAGE_LOADING_STATE.COMPLETE) {
221
- this.#stagePage(page);
249
+ #onTabActivated = ({ previousTabId, tabId }) => {
250
+ if (previousTabId) {
251
+ this.#setTabActive(previousTabId, false);
252
+ } else {
253
+ for (const otherTabId of this.#tabContext.keys()) {
254
+ if (otherTabId !== tabId) this.#setTabActive(otherTabId, false);
222
255
  }
223
256
  }
224
-
225
- // create a new page for the navigation
226
- this.#pages.delete(tabId);
227
-
228
- const nextPage = createPageFromTab({
229
- id: tabId,
230
- active: false,
231
- url,
232
- incognito: page ? page.isPrivate : false,
233
- created: timeStamp,
234
- });
235
- nextPage.previous = page;
236
- nextPage.state = PAGE_LOADING_STATE.NAVIGATING;
237
- this.#pages.set(tabId, nextPage);
257
+ this.#setTabActive(tabId, true);
238
258
  };
239
259
 
240
- #onNavigationCommitted = (details) => {
241
- const { frameId, tabId } = details;
242
- const page = this.#pages.get(tabId);
243
-
244
- if (!page) {
245
- return;
246
- }
247
-
248
- if (frameId === 0) {
249
- page.state = PAGE_LOADING_STATE.COMMITTED;
250
- this.#pages.set(tabId, page);
251
- } else if (!page.frames[frameId]) {
252
- // frame created without request
253
- this.onSubFrame(details);
260
+ #onWindowFocusChanged = async (focusedWindowId) => {
261
+ for (const { id, windowId } of await chrome.tabs.query({ active: true })) {
262
+ this.#setTabActive(id, windowId === focusedWindowId);
254
263
  }
255
264
  };
256
265
 
257
- #onNavigationCompleted = (details) => {
258
- const { frameId, tabId } = details;
259
- const page = this.#pages.get(tabId);
260
- if (!page) {
266
+ #onNavigationCommitted = ({
267
+ frameId,
268
+ tabId,
269
+ documentId,
270
+ parentDocumentId,
271
+ url,
272
+ }) => {
273
+ if (frameId !== 0) {
274
+ if (this.#documentIndex.has(documentId)) return;
275
+ const owner =
276
+ parentDocumentId && this.#documentIndex.get(parentDocumentId);
277
+ if (!owner) return;
278
+ this.#indexDocument(owner, documentId);
279
+ this.#pages.set(owner.documentId, owner);
261
280
  return;
262
281
  }
263
- if (frameId === 0) {
264
- page.state = PAGE_LOADING_STATE.COMPLETE;
282
+ // Main-frame. Reuse an existing record for a bfcache re-commit
283
+ // so accumulated stats survive forward/back navigation; preserve
284
+ // its state, since onCompleted is not guaranteed to re-fire on
285
+ // restore and we'd otherwise downgrade a complete page back to
286
+ // committed and silently drop it at staging.
287
+ let page = this.#pages.get(documentId);
288
+ if (!page) {
289
+ const ctx = this.#tabContext.get(tabId) || {};
290
+ page = createPage({ tabId, documentId, url, ...ctx });
265
291
  }
266
- this.#pages.set(tabId, page);
292
+ page.url = url;
293
+ page.stageAfter = null;
294
+ this.#indexDocument(page, documentId);
295
+ this.#pages.set(documentId, page);
267
296
  };
268
297
 
269
- onSubFrame = (details) => {
270
- const { tabId, frameId, parentFrameId, url } = details;
271
- const page = this.#pages.get(tabId);
272
- if (!page) {
273
- return;
298
+ #onNavigationCompleted = ({ frameId, documentId }) => {
299
+ if (frameId !== 0) return;
300
+ const page = this.#pages.get(documentId);
301
+ if (page) {
302
+ page.state = PAGE_LOADING_STATE.COMPLETE;
303
+ this.#pages.set(documentId, page);
274
304
  }
275
- // Keep track of frameUrl as well as parent frame
276
- page.frames[frameId] = {
277
- parentFrameId,
278
- url,
279
- };
280
- this.#pages.set(tabId, page);
305
+ if (Date.now() - this.#lastFlush < FLUSH_THROTTLE_MS) return;
306
+ this.flush().catch((e) => logger.debug('PageStore: flush failed', e));
281
307
  };
282
308
 
283
- getPageForRequest(context) {
284
- const { tabId, frameId, originUrl, type, initiator } = context;
285
- const page = this.#pages.get(tabId);
286
- if (!page) {
287
- return null;
309
+ getPageForRequest({ documentId, parentDocumentId, documentLifecycle }) {
310
+ // Prerender docs were never seen by the user.
311
+ if (documentLifecycle === 'prerender') return null;
312
+ if (documentId) {
313
+ const direct = this.#documentIndex.get(documentId);
314
+ if (direct) return direct;
288
315
  }
289
-
290
- // check if the current page has the given frame id, otherwise check if it belongs to the
291
- // previous page
292
- if (!page.frames[frameId]) {
293
- if (page.previous && page.previous.frames[frameId]) {
294
- return page.previous;
316
+ // Sub-frame request can fire before its own onCommitted, or
317
+ // without a documentId (iframe HTML fetch). Fall back to parent.
318
+ if (parentDocumentId) {
319
+ const owner = this.#documentIndex.get(parentDocumentId);
320
+ if (owner) {
321
+ if (documentId) {
322
+ this.#indexDocument(owner, documentId);
323
+ this.#pages.set(owner.documentId, owner);
324
+ }
325
+ return owner;
295
326
  }
296
- return null;
297
- }
298
-
299
- const couldBePreviousPage =
300
- frameId === 0 && type !== 'main_frame' && page.previous;
301
-
302
- // for main frame requests: check if the origin url is from the previous page (Firefox)
303
- if (
304
- couldBePreviousPage &&
305
- page.url !== originUrl &&
306
- page.previous.url === originUrl
307
- ) {
308
- return page.previous;
309
- }
310
- // on Chrome we have `initiator` which only contains the origin. In this case, check for a
311
- // different origin
312
- if (
313
- couldBePreviousPage &&
314
- initiator &&
315
- !page.url.startsWith(initiator) &&
316
- page.previous.url.startsWith(initiator)
317
- ) {
318
- return page.previous;
319
327
  }
320
- return page;
328
+ return null;
321
329
  }
322
330
  }
@@ -125,11 +125,6 @@ export class WebRequestContext {
125
125
  return null;
126
126
  }
127
127
 
128
- // Sub frames book keeping
129
- if (context.type === 'sub_frame') {
130
- pageStore.onSubFrame(context);
131
- }
132
-
133
128
  // Get context on this page
134
129
  const page = pageStore.getPageForRequest(context);
135
130
 
@@ -140,6 +140,17 @@ function playEvents(chrome, events, options = {}) {
140
140
  }
141
141
  }
142
142
  }
143
+ // Replaying with a documentIdPrefix lets the test simulate a
144
+ // fresh browsing session: identical events, but documentIds
145
+ // the reporter has never seen, so documentId-keyed dedupe
146
+ // doesn't suppress the replay.
147
+ if (options.documentIdPrefix) {
148
+ for (const prop of ['documentId', 'parentDocumentId']) {
149
+ if (event[prop]) {
150
+ event[prop] = options.documentIdPrefix + event[prop];
151
+ }
152
+ }
153
+ }
143
154
  return event;
144
155
  });
145
156
  if (events.api === 'tabs' && event.event === 'onCreated') {