-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbackground.js
More file actions
608 lines (521 loc) · 15.1 KB
/
Copy pathbackground.js
File metadata and controls
608 lines (521 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
importScripts("shared/config.js");
const {
BLOCK_RULE_ID,
CLEAN_URL_RULE_ID,
TRACKING_PARAMS,
TRACKER_DOMAINS,
TRACKER_CATEGORIES
} = globalThis.GetBlockedConfig;
const TAB_STATS_KEY = "getblockedTabStats";
const PENDING_NAVIGATION_KEY = "getblockedPendingNavigation";
const OBSOLETE_TOTALS_KEY = "getblockedTotals";
const DECOY_MODE_KEY = "getblockedDecoyMode";
const DECOY_SESSION_PROFILE_KEY = "getblockedDecoySessionProfile";
let updateQueue = Promise.resolve();
function queueUpdate(task) {
const operation = updateQueue.then(task);
updateQueue = operation.catch((error) => {
console.warn("GetBlocked update failed:", error);
});
return operation;
}
function storageGet(keys) {
return new Promise((resolve, reject) => {
chrome.storage.local.get(keys, (result) => {
const error = chrome.runtime.lastError;
if (error) {
reject(error);
return;
}
resolve(result);
});
});
}
function storageSet(items) {
return new Promise((resolve, reject) => {
chrome.storage.local.set(items, () => {
const error = chrome.runtime.lastError;
if (error) {
reject(error);
return;
}
resolve();
});
});
}
function storageRemove(keys) {
return new Promise((resolve, reject) => {
chrome.storage.local.remove(keys, () => {
const error = chrome.runtime.lastError;
if (error) {
reject(error);
return;
}
resolve();
});
});
}
function sessionStorageGet(keys) {
return new Promise((resolve, reject) => {
chrome.storage.session.get(keys, (result) => {
const error = chrome.runtime.lastError;
if (error) {
reject(error);
return;
}
resolve(result);
});
});
}
function sessionStorageSet(items) {
return new Promise((resolve, reject) => {
chrome.storage.session.set(items, () => {
const error = chrome.runtime.lastError;
if (error) {
reject(error);
return;
}
resolve();
});
});
}
function updateStaticRules(options) {
return chrome.declarativeNetRequest.updateStaticRules(options);
}
function setBadgeText(tabId, text) {
return new Promise((resolve) => {
if (!Number.isInteger(tabId) || tabId < 0) {
resolve();
return;
}
chrome.action.setBadgeText({ tabId, text }, () => {
void chrome.runtime.lastError;
resolve();
});
});
}
function configureActionBadge() {
chrome.action.setBadgeBackgroundColor({ color: "#0f766e" });
chrome.declarativeNetRequest.setExtensionActionOptions(
{ displayActionCountAsBadgeText: false },
() => {
void chrome.runtime.lastError;
}
);
}
function createEmptyTabStats() {
return {
blockedOnPage: 0,
decoyedRequests: 0,
trackingLinksCleaned: 0,
trackingParamsRemoved: 0,
visibleAttempts: 0,
trackingLinksDetected: 0,
trackerElementsDetected: 0,
estimatedTrackerRequests: 0,
detectedCategories: [],
updatedAt: Date.now()
};
}
function isKnownTrackerHost(hostname) {
const normalizedHost = String(hostname || "").toLowerCase();
return TRACKER_DOMAINS.some((domain) => {
return normalizedHost === domain || normalizedHost.endsWith(`.${domain}`);
});
}
function getTrackerCategories(hostname) {
return Object.entries(TRACKER_CATEGORIES)
.filter(([, domains]) => {
return domains.some((domain) => {
return hostname === domain || hostname.endsWith(`.${domain}`);
});
})
.map(([category]) => category);
}
function createFakeSessionProfile() {
const firstNames = ["Alex", "Casey", "Jordan", "Morgan", "Riley", "Taylor"];
const lastNames = ["Avery", "Hayes", "Parker", "Reed", "Rowan", "Sage"];
const randomValues = crypto.getRandomValues(new Uint32Array(4));
const token = Array.from(randomValues, (value) => {
return value.toString(16).padStart(8, "0");
}).join("");
const firstName = firstNames[randomValues[0] % firstNames.length];
const lastName = lastNames[randomValues[1] % lastNames.length];
const username = `${firstName}.${lastName}.${token.slice(0, 6)}`.toLowerCase();
const phoneSuffix = String(randomValues[2] % 100).padStart(2, "0");
return Object.freeze({
anonymousId: `anon_${token}`,
clientId: `${randomValues[0]}.${randomValues[1]}`,
userId: `user_${token.slice(0, 20)}`,
deviceId: `device_${token.slice(8, 28)}`,
sessionId: `session_${token.slice(16)}`,
email: `${username}@example.invalid`,
firstName,
lastName,
fullName: `${firstName} ${lastName}`,
username,
phone: `+120255501${phoneSuffix}`
});
}
async function getDecoyMode() {
const result = await storageGet(DECOY_MODE_KEY);
return result[DECOY_MODE_KEY] === true;
}
async function ensureDecoySessionProfile() {
const result = await sessionStorageGet(DECOY_SESSION_PROFILE_KEY);
const existing = result[DECOY_SESSION_PROFILE_KEY];
if (existing && typeof existing === "object") {
return existing;
}
const profile = createFakeSessionProfile();
await sessionStorageSet({ [DECOY_SESSION_PROFILE_KEY]: profile });
return profile;
}
async function applyDecoyRuleState(enabled) {
await updateStaticRules({
rulesetId: "getblocked_static_rules",
disableRuleIds: enabled ? [BLOCK_RULE_ID] : [],
enableRuleIds: enabled
? [CLEAN_URL_RULE_ID]
: [BLOCK_RULE_ID, CLEAN_URL_RULE_ID]
});
}
async function syncDecoyRuleStateFromStorage() {
await applyDecoyRuleState(await getDecoyMode());
}
async function setDecoyMode(enabled) {
await applyDecoyRuleState(enabled);
await storageSet({ [DECOY_MODE_KEY]: enabled });
if (enabled) {
await clearBlockedCounts();
} else {
const tabStats = await getAllTabStats();
await syncAllTabBadges(tabStats, false);
}
return {
enabled,
profile: enabled ? await ensureDecoySessionProfile() : null
};
}
async function getDecoyConfiguration() {
const enabled = await getDecoyMode();
return {
enabled,
profile: enabled ? await ensureDecoySessionProfile() : null
};
}
function normalizeTabStats(stats) {
return {
...createEmptyTabStats(),
...(stats || {})
};
}
function countTrackingParams(rawUrl) {
try {
const url = new URL(rawUrl);
let count = 0;
for (const paramName of TRACKING_PARAMS) {
count += url.searchParams.getAll(paramName).length;
}
return count;
} catch (error) {
return 0;
}
}
async function getAllTabStats() {
const result = await storageGet(TAB_STATS_KEY);
return result[TAB_STATS_KEY] || {};
}
async function setAllTabStats(tabStats) {
await storageSet({
[TAB_STATS_KEY]: tabStats
});
}
function getActiveBadgeCount(stats, decoyMode) {
const count = decoyMode ? stats.decoyedRequests : stats.blockedOnPage;
return Math.max(0, Number(count) || 0);
}
async function syncBadgeForTab(tabId, stats, decoyMode = null) {
if (!Number.isInteger(tabId) || tabId < 0) {
return;
}
const mode = decoyMode === null ? await getDecoyMode() : decoyMode;
const count = getActiveBadgeCount(normalizeTabStats(stats), mode);
await setBadgeText(tabId, count > 0 ? String(count) : "");
}
async function syncAllTabBadges(tabStats, decoyMode = null) {
await Promise.all(
Object.entries(tabStats).map(([tabId, stats]) => {
return syncBadgeForTab(Number(tabId), stats, decoyMode);
})
);
}
async function clearBlockedCounts() {
const tabStats = await getAllTabStats();
const updatedAt = Date.now();
const nextStats = Object.fromEntries(
Object.entries(tabStats).map(([tabId, stats]) => {
return [
tabId,
normalizeTabStats({
...stats,
blockedOnPage: 0,
updatedAt
})
];
})
);
await setAllTabStats(nextStats);
await syncAllTabBadges(nextStats, true);
}
async function getTabStats(tabId) {
const tabStats = await getAllTabStats();
return normalizeTabStats(tabStats[String(tabId)]);
}
async function updateTabStats(tabId, updater) {
if (!Number.isInteger(tabId) || tabId < 0) {
return createEmptyTabStats();
}
const tabStats = await getAllTabStats();
const current = normalizeTabStats(tabStats[String(tabId)]);
const next = normalizeTabStats({
...current,
...updater(current),
updatedAt: Date.now()
});
await setAllTabStats({
...tabStats,
[String(tabId)]: next
});
await syncBadgeForTab(tabId, next);
return next;
}
async function resetTabStats(tabId, initialStats = {}) {
if (!Number.isInteger(tabId) || tabId < 0) {
return;
}
const tabStats = await getAllTabStats();
const next = normalizeTabStats({
...createEmptyTabStats(),
...initialStats,
updatedAt: Date.now()
});
await setAllTabStats({
...tabStats,
[String(tabId)]: next
});
await syncBadgeForTab(tabId, next);
}
async function setPendingNavigation(tabId, trackingParamCount) {
if (!Number.isInteger(tabId) || tabId < 0) {
return;
}
const result = await storageGet(PENDING_NAVIGATION_KEY);
const pending = result[PENDING_NAVIGATION_KEY] || {};
const key = String(tabId);
if (trackingParamCount <= 0) {
delete pending[key];
} else {
pending[key] = {
trackingParamCount,
updatedAt: Date.now()
};
}
await storageSet({
[PENDING_NAVIGATION_KEY]: pending
});
}
async function popPendingNavigation(tabId) {
const result = await storageGet(PENDING_NAVIGATION_KEY);
const pending = result[PENDING_NAVIGATION_KEY] || {};
const key = String(tabId);
const current = pending[key] || { trackingParamCount: 0 };
if (Object.prototype.hasOwnProperty.call(pending, key)) {
delete pending[key];
await storageSet({
[PENDING_NAVIGATION_KEY]: pending
});
}
return current;
}
async function removeTabLocalData(tabId) {
const [statsResult, pendingResult] = await Promise.all([
storageGet(TAB_STATS_KEY),
storageGet(PENDING_NAVIGATION_KEY)
]);
const tabStats = statsResult[TAB_STATS_KEY] || {};
const pending = pendingResult[PENDING_NAVIGATION_KEY] || {};
const key = String(tabId);
delete tabStats[key];
delete pending[key];
await Promise.all([
storageSet({ [TAB_STATS_KEY]: tabStats }),
storageSet({ [PENDING_NAVIGATION_KEY]: pending })
]);
}
async function clearTransientLocalData() {
await storageRemove([TAB_STATS_KEY, PENDING_NAVIGATION_KEY, OBSOLETE_TOTALS_KEY]);
}
async function syncBlockedEstimateForTab(tabId, estimate) {
const safeEstimate = Math.max(0, Number(estimate) || 0);
const current = await getTabStats(tabId);
if (safeEstimate <= current.blockedOnPage) {
return current;
}
return updateTabStats(tabId, () => ({
blockedOnPage: safeEstimate
}));
}
async function updatePageSignals(tabId, signals) {
const detectedCategories = Array.isArray(signals.detectedCategories)
? signals.detectedCategories.filter((category) => {
return typeof category === "string" && category.length > 0;
})
: [];
const safeSignals = {
visibleAttempts: Math.max(0, Number(signals.visibleAttempts) || 0),
trackingLinksDetected: Math.max(
0,
Number(signals.trackingLinksDetected) || 0
),
trackerElementsDetected: Math.max(
0,
Number(signals.trackerElementsDetected) || 0
),
estimatedTrackerRequests: Math.max(
0,
Number(signals.estimatedTrackerRequests) || 0
),
detectedCategories
};
await updateTabStats(tabId, (current) => ({
...safeSignals,
detectedCategories: Array.from(
new Set([...current.detectedCategories, ...safeSignals.detectedCategories])
)
}));
if (!(await getDecoyMode())) {
await syncBlockedEstimateForTab(tabId, safeSignals.estimatedTrackerRequests);
}
}
async function recordDecoyedRequest(tabId, hostname) {
const normalizedHost = String(hostname || "").toLowerCase();
if (!(await getDecoyMode()) || !isKnownTrackerHost(normalizedHost)) {
return;
}
await updateTabStats(tabId, (current) => ({
decoyedRequests: current.decoyedRequests + 1,
detectedCategories: Array.from(
new Set([
...current.detectedCategories,
...getTrackerCategories(normalizedHost)
])
)
}));
}
async function getReport(tabId) {
await updateQueue;
const decoyMode = await getDecoyMode();
const pageStats = await getTabStats(tabId);
await syncBadgeForTab(tabId, pageStats, decoyMode);
return {
page: pageStats,
decoyMode,
localOnly: true,
counterMode: "local_estimate"
};
}
function handleMessage(message, sender, sendResponse) {
if (message?.type === "GETBLOCKED_PAGE_SIGNALS") {
const tabId = sender.tab?.id;
const signals = message.payload || {};
queueUpdate(() => updatePageSignals(tabId, signals));
sendResponse({ ok: true });
return false;
}
if (message?.type === "GETBLOCKED_DECOYED_REQUEST") {
queueUpdate(() => {
return recordDecoyedRequest(sender.tab?.id, message.hostname);
});
sendResponse({ ok: true });
return false;
}
if (message?.type === "GETBLOCKED_DECOY_CONFIG") {
getDecoyConfiguration()
.then((configuration) => sendResponse({ ok: true, configuration }))
.catch((error) => {
sendResponse({
ok: false,
error: error.message || "Unable to load Decoy Mode"
});
});
return true;
}
if (message?.type === "SET_GETBLOCKED_DECOY_MODE") {
const enabled = message.enabled === true;
queueUpdate(() => setDecoyMode(enabled))
.then((configuration) => sendResponse({ ok: true, configuration }))
.catch((error) => {
sendResponse({
ok: false,
error: error.message || "Unable to update Decoy Mode"
});
});
return true;
}
if (message?.type === "GETBLOCKED_REPORT") {
getReport(message.tabId)
.then((report) => sendResponse({ ok: true, report }))
.catch((error) => {
sendResponse({
ok: false,
error: error.message || "Unable to load report"
});
});
return true;
}
return false;
}
chrome.runtime.onInstalled.addListener(() => {
queueUpdate(async () => {
await clearTransientLocalData();
await syncDecoyRuleStateFromStorage();
});
configureActionBadge();
});
chrome.runtime.onStartup.addListener(() => {
queueUpdate(async () => {
await clearTransientLocalData();
await syncDecoyRuleStateFromStorage();
});
configureActionBadge();
});
chrome.webNavigation.onBeforeNavigate.addListener((details) => {
if (details.frameId !== 0) {
return;
}
const trackingParamCount = countTrackingParams(details.url);
queueUpdate(() => setPendingNavigation(details.tabId, trackingParamCount));
});
chrome.webNavigation.onCommitted.addListener((details) => {
if (details.frameId !== 0) {
return;
}
queueUpdate(async () => {
const pending = await popPendingNavigation(details.tabId);
const remainingTrackingParams = countTrackingParams(details.url);
const trackingParamsRemoved = Math.max(
0,
(pending.trackingParamCount || 0) - remainingTrackingParams
);
await resetTabStats(details.tabId, {
trackingLinksCleaned: trackingParamsRemoved > 0 ? 1 : 0,
trackingParamsRemoved
});
});
});
chrome.tabs.onRemoved.addListener((tabId) => {
queueUpdate(() => removeTabLocalData(tabId));
});
chrome.runtime.onMessage.addListener(handleMessage);
configureActionBadge();