@whotracksme/reporting 11.1.1 → 12.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,423 @@
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
+ const DEFAULT_HUB_URL = 'ws://127.0.0.1:7878/ws';
13
+ const MAX_BUFFERED_RECORDS = 2000;
14
+
15
+ function sleep(ms) {
16
+ return new Promise((resolve) => setTimeout(resolve, ms));
17
+ }
18
+
19
+ export default class E2EBridge {
20
+ constructor({ hubUrl = DEFAULT_HUB_URL } = {}) {
21
+ this.hubUrl = hubUrl;
22
+ this.socket = null;
23
+ this.buffer = [];
24
+ this.reconnectDelay = 1000;
25
+ this.commands = {};
26
+ this.connected = false;
27
+ }
28
+
29
+ registerCommands(commands) {
30
+ Object.assign(this.commands, commands);
31
+ }
32
+
33
+ connect() {
34
+ if (this.socket) {
35
+ return;
36
+ }
37
+ let socket;
38
+ try {
39
+ socket = new WebSocket(this.hubUrl);
40
+ } catch {
41
+ this._scheduleReconnect();
42
+ return;
43
+ }
44
+ this.socket = socket;
45
+
46
+ socket.addEventListener('open', () => {
47
+ this.connected = true;
48
+ this.reconnectDelay = 1000;
49
+ this._raw({
50
+ kind: 'hello',
51
+ info: {
52
+ extensionId: chrome.runtime.id,
53
+ userAgent: navigator.userAgent,
54
+ manifestVersion: chrome.runtime.getManifest().manifest_version,
55
+ startedAt: Date.now(),
56
+ },
57
+ });
58
+ const pending = this.buffer.splice(0, this.buffer.length);
59
+ pending.forEach((record) => this._raw(record));
60
+ });
61
+
62
+ socket.addEventListener('message', (event) => {
63
+ let msg;
64
+ try {
65
+ msg = JSON.parse(event.data);
66
+ } catch {
67
+ return;
68
+ }
69
+ if (msg.kind === 'command') {
70
+ this._runCommand(msg);
71
+ }
72
+ });
73
+
74
+ socket.addEventListener('close', () => {
75
+ this.connected = false;
76
+ this.socket = null;
77
+ this._scheduleReconnect();
78
+ });
79
+
80
+ socket.addEventListener('error', () => {
81
+ try {
82
+ socket.close();
83
+ } catch {
84
+ // the close handler takes care of reconnecting
85
+ }
86
+ });
87
+ }
88
+
89
+ _scheduleReconnect() {
90
+ setTimeout(() => this.connect(), this.reconnectDelay);
91
+ this.reconnectDelay = Math.min(this.reconnectDelay * 2, 30000);
92
+ }
93
+
94
+ _raw(record) {
95
+ if (this.socket && this.socket.readyState === WebSocket.OPEN) {
96
+ this.socket.send(JSON.stringify(record));
97
+ return true;
98
+ }
99
+ return false;
100
+ }
101
+
102
+ _send(record) {
103
+ if (!this._raw(record)) {
104
+ this.buffer.push(record);
105
+ if (this.buffer.length > MAX_BUFFERED_RECORDS) {
106
+ this.buffer.shift();
107
+ }
108
+ }
109
+ }
110
+
111
+ async _runCommand({ id, name, args }) {
112
+ const handler = this.commands[name];
113
+ if (!handler) {
114
+ this._raw({
115
+ kind: 'result',
116
+ id,
117
+ error: `unknown command: ${name}. Known: ${Object.keys(this.commands)
118
+ .sort()
119
+ .join(', ')}`,
120
+ });
121
+ return;
122
+ }
123
+ try {
124
+ const result = await handler(args || {});
125
+ this._raw({ kind: 'result', id, result: result ?? null });
126
+ } catch (e) {
127
+ this._raw({ kind: 'result', id, error: `${e?.stack || e}` });
128
+ }
129
+ }
130
+
131
+ captureMessage(source, body, context) {
132
+ this._send({ kind: 'message', source, body, context, sentAt: Date.now() });
133
+ }
134
+
135
+ captureEvent(event, details) {
136
+ this._send({ kind: 'event', event, details, at: Date.now() });
137
+ }
138
+
139
+ captureConsole(level, text) {
140
+ this._send({ kind: 'console', level, text });
141
+ }
142
+ }
143
+
144
+ // No public queue snapshot exists on the scheduler.
145
+ function summarizeJobs(jobScheduler) {
146
+ const description = jobScheduler._describeJobs();
147
+ const byState = {};
148
+ for (const [state, jobs] of Object.entries(description.queues.byState)) {
149
+ byState[state] = jobs.length;
150
+ }
151
+ const byType = {};
152
+ for (const [type, queue] of Object.entries(description.queues.byType)) {
153
+ byType[type] = queue.all.length;
154
+ }
155
+ return {
156
+ total: description.queues.all.length,
157
+ byState,
158
+ byType,
159
+ stats: { ...jobScheduler.stats },
160
+ };
161
+ }
162
+
163
+ async function waitForTabLoad(tabId, timeoutInMs) {
164
+ return new Promise((resolve) => {
165
+ let settled = false;
166
+ const finish = (reason) => {
167
+ if (settled) {
168
+ return;
169
+ }
170
+ settled = true;
171
+ chrome.webNavigation.onCompleted.removeListener(onCompleted);
172
+ clearTimeout(timer);
173
+ clearInterval(poller);
174
+ resolve(reason);
175
+ };
176
+
177
+ function onCompleted(details) {
178
+ if (details.tabId === tabId && details.frameId === 0) {
179
+ finish('onCompleted');
180
+ }
181
+ }
182
+
183
+ chrome.webNavigation.onCompleted.addListener(onCompleted);
184
+ const timer = setTimeout(() => finish('timeout'), timeoutInMs);
185
+
186
+ // onCompleted can be missed, so the poll is the safety net.
187
+ const poller = setInterval(async () => {
188
+ try {
189
+ const tab = await chrome.tabs.get(tabId);
190
+ if (tab.status === 'complete' && tab.url && tab.url !== 'about:blank') {
191
+ finish('polled');
192
+ }
193
+ } catch {
194
+ finish('tab-gone');
195
+ }
196
+ }, 250);
197
+ });
198
+ }
199
+
200
+ // Never inject synthetic input events: isTrusted=false is a bot signal.
201
+ export function createCommands({
202
+ urlReporter,
203
+ requestReporter,
204
+ quorumControl,
205
+ bridge,
206
+ }) {
207
+ const { jobScheduler, pageAggregator, patterns } = urlReporter;
208
+
209
+ async function resolveTabId({ tabId, newTab }) {
210
+ if (tabId) {
211
+ return tabId;
212
+ }
213
+ if (newTab) {
214
+ const created = await chrome.tabs.create({
215
+ url: 'about:blank',
216
+ active: true,
217
+ });
218
+ return created.id;
219
+ }
220
+ const [active] = await chrome.tabs.query({
221
+ active: true,
222
+ lastFocusedWindow: true,
223
+ });
224
+ if (active?.url && /^https?:/.test(active.url)) {
225
+ return active.id;
226
+ }
227
+ const created = await chrome.tabs.create({
228
+ url: 'about:blank',
229
+ active: true,
230
+ });
231
+ return created.id;
232
+ }
233
+
234
+ async function navigate({
235
+ url,
236
+ tabId,
237
+ newTab = false,
238
+ waitForLoad = true,
239
+ timeoutInMs = 45000,
240
+ settleInMs = 1500,
241
+ }) {
242
+ if (!url) {
243
+ throw new Error('navigate requires a "url"');
244
+ }
245
+ if (!/^https?:\/\//.test(url)) {
246
+ throw new Error('navigate only accepts http(s) URLs');
247
+ }
248
+ const targetTabId = await resolveTabId({ tabId, newTab });
249
+ await chrome.tabs.update(targetTabId, { url, active: true });
250
+ let reason = 'not-awaited';
251
+ if (waitForLoad) {
252
+ reason = await waitForTabLoad(targetTabId, timeoutInMs);
253
+ }
254
+ if (settleInMs > 0) {
255
+ await sleep(settleInMs);
256
+ }
257
+ const tab = await chrome.tabs.get(targetTabId).catch(() => null);
258
+ return {
259
+ tabId: targetTabId,
260
+ requestedUrl: url,
261
+ url: tab?.url,
262
+ title: tab?.title,
263
+ status: tab?.status,
264
+ loadedBecause: reason,
265
+ };
266
+ }
267
+
268
+ async function pendingJobsSettled({ settleInMs }) {
269
+ await sleep(settleInMs);
270
+ return summarizeJobs(jobScheduler);
271
+ }
272
+
273
+ async function flush({
274
+ maxRounds = 12,
275
+ settleInMs = 3500,
276
+ forceExpiration = true,
277
+ } = {}) {
278
+ const rounds = [];
279
+ for (let round = 1; round <= maxRounds; round += 1) {
280
+ pageAggregator.fullSync();
281
+ if (forceExpiration) {
282
+ await pageAggregator.checkExpiredPages({
283
+ forceExpiration: true,
284
+ maxEntriesToCheck: 1000,
285
+ });
286
+ }
287
+ await urlReporter.processPendingJobs();
288
+ const pending = summarizeJobs(jobScheduler);
289
+ rounds.push({ round, pending: pending.total, byState: pending.byState });
290
+ if (pending.total === 0) {
291
+ return { drained: true, rounds };
292
+ }
293
+ await pendingJobsSettled({ settleInMs });
294
+ }
295
+ return { drained: false, rounds, pending: summarizeJobs(jobScheduler) };
296
+ }
297
+
298
+ return {
299
+ async ping() {
300
+ return { pong: true, now: Date.now() };
301
+ },
302
+
303
+ async state() {
304
+ const tabs = await chrome.tabs.query({});
305
+ return {
306
+ extensionId: chrome.runtime.id,
307
+ isActive: urlReporter.isActive,
308
+ requestReporterReady: requestReporter?.ready ?? null,
309
+ patternCategories: Object.keys(patterns.getRulesSnapshot() || {}),
310
+ countryCode: urlReporter.countryProvider.getSafeCountryCode(),
311
+ jobs: summarizeJobs(jobScheduler),
312
+ quorum: quorumControl.describe(),
313
+ tabs: tabs.map(({ id, url, title, status, active }) => ({
314
+ id,
315
+ url,
316
+ title,
317
+ status,
318
+ active,
319
+ })),
320
+ };
321
+ },
322
+
323
+ navigate,
324
+
325
+ async closeTabs({ urlContains } = {}) {
326
+ const tabs = await chrome.tabs.query({});
327
+ const victims = tabs.filter(
328
+ (tab) =>
329
+ tab.url &&
330
+ /^https?:/.test(tab.url) &&
331
+ (!urlContains || tab.url.includes(urlContains)),
332
+ );
333
+ if (victims.length > 0) {
334
+ await chrome.tabs.remove(victims.map((tab) => tab.id));
335
+ }
336
+ return { closed: victims.map((tab) => tab.url) };
337
+ },
338
+
339
+ flush,
340
+
341
+ async processPendingJobs() {
342
+ await urlReporter.processPendingJobs();
343
+ return summarizeJobs(jobScheduler);
344
+ },
345
+
346
+ async expirePages({ forceExpiration = true, maxEntriesToCheck = 1000 }) {
347
+ pageAggregator.fullSync();
348
+ const result = await pageAggregator.checkExpiredPages({
349
+ forceExpiration,
350
+ maxEntriesToCheck,
351
+ });
352
+ return { ...result, jobs: summarizeJobs(jobScheduler) };
353
+ },
354
+
355
+ async dumpJobs({ includeArgs = false } = {}) {
356
+ const description = jobScheduler._describeJobs();
357
+ const describe = (jobEntry) => ({
358
+ type: jobEntry.job?.type,
359
+ readyAt: jobEntry._meta?.readyAt,
360
+ expireAt: jobEntry._meta?.expireAt,
361
+ createdAt: jobEntry._meta?.createdAt,
362
+ args: includeArgs ? jobEntry.job?.args : undefined,
363
+ });
364
+ return {
365
+ summary: summarizeJobs(jobScheduler),
366
+ byState: Object.fromEntries(
367
+ Object.entries(description.queues.byState).map(([state, jobs]) => [
368
+ state,
369
+ jobs.map(describe),
370
+ ]),
371
+ ),
372
+ };
373
+ },
374
+
375
+ async selfChecks() {
376
+ const check = await urlReporter.selfChecks();
377
+ return check.report();
378
+ },
379
+
380
+ async setQuorum({ mode }) {
381
+ quorumControl.setMode(mode);
382
+ return quorumControl.describe();
383
+ },
384
+
385
+ // Restarts rather than unload()+init(): Pages#init is one-shot.
386
+ async reset() {
387
+ await chrome.storage.local.clear();
388
+ bridge.captureEvent('reset', { strategy: 'worker-restart' });
389
+ setTimeout(() => chrome.runtime.reload(), 50);
390
+ return { ok: true, restarting: true };
391
+ },
392
+
393
+ async reload() {
394
+ bridge.captureEvent('reload', {});
395
+ setTimeout(() => chrome.runtime.reload(), 50);
396
+ return { ok: true, restarting: true };
397
+ },
398
+ };
399
+ }
400
+
401
+ export function pipeJobEventsToHub(jobScheduler, bridge) {
402
+ const events = [
403
+ 'jobRegistered',
404
+ 'jobStarted',
405
+ 'jobSucceeded',
406
+ 'jobFailed',
407
+ 'jobExpired',
408
+ 'jobRejected',
409
+ ];
410
+ for (const event of events) {
411
+ jobScheduler.addObserver(
412
+ event,
413
+ (jobEntry) => {
414
+ bridge.captureEvent(event, {
415
+ type: jobEntry?.job?.type,
416
+ args: jobEntry?.job?.args,
417
+ meta: jobEntry?._meta,
418
+ });
419
+ },
420
+ { ignoreAfterInitWarning: true },
421
+ );
422
+ }
423
+ }