-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
1671 lines (1392 loc) · 51.7 KB
/
background.js
File metadata and controls
1671 lines (1392 loc) · 51.7 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
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Background Script - Orchestrates all protection features
// Libraries are loaded via manifest.json scripts array
// Global state
let currentConfig = null;
let currentDomainFilter = null;
let lastNotificationTime = {};
let configLoaded = false;
let initializationPromise = null;
let turnstileTimestamps = {}; // Track domains with Turnstile: { hostname: timestamp }
let proxyDisabledForWhitelist = false; // Track if proxy is temporarily disabled for whitelisted tab
let triggeredFeaturesPerTab = {}; // Track triggered features per tab: { tabId: { hostname: string, features: Set } }
let lastAppliedWebRTCPolicy = null;
let pendingWebRTCPolicy = null;
// Timing / behavior constants
const TURNSTILE_BYPASS_TTL_MS = 3 * 60 * 1000;
const TURNSTILE_RELOAD_DELAY_MS = 1000;
const ACTIVATION_RECHECK_DELAY_MS = 377;
const NOTIFICATION_THROTTLE_MS = 3770;
const TURNSTILE_SESSION_KEY = "__STEALTH_GUARD_TURNSTILE_TS__";
const SESSION_STORAGE_KEY = "stealth-guard-sessions";
const ACTIVE_SESSIONS_STORAGE_KEY = "stealth-guard-active-sessions";
const MAX_SAVED_SESSIONS_PER_DOMAIN = 20;
// Debug logging helpers
const debugLog = function(...args) {
if (currentConfig && currentConfig.notifications && currentConfig.notifications.enabled) {
console.log(...args);
}
};
const debugWarn = function(...args) {
if (currentConfig && currentConfig.notifications && currentConfig.notifications.enabled) {
console.warn(...args);
}
};
const debugError = function(...args) {
// Always log errors regardless of debug setting
console.error(...args);
};
// Utility helpers
function getHostnameFromUrl(url) {
try {
return new URL(url).hostname;
} catch (e) {
return null;
}
}
function resolveTabHostname(sender, fallbackHostname = null) {
if (sender && sender.tab && sender.tab.url) {
const tabHostname = getHostnameFromUrl(sender.tab.url);
if (tabHostname) {
return tabHostname;
}
}
return fallbackHostname;
}
function setCurrentConfig(config) {
currentConfig = config;
currentDomainFilter = config ? new DomainFilter(config) : null;
}
function getDomainFilter(config = currentConfig) {
if (!config) {
return null;
}
if (!currentDomainFilter || currentDomainFilter.config !== config) {
currentDomainFilter = new DomainFilter(config);
}
return currentDomainFilter;
}
function isHostnameOnGlobalAllowlist(hostname, config = currentConfig) {
if (!hostname || !config) {
return false;
}
const filter = getDomainFilter(config);
return filter ? filter.isWhitelisted(hostname, config.globalWhitelist || "") : false;
}
function isHostnameOnFeatureAllowlist(hostname, whitelist, config = currentConfig) {
if (!hostname || !whitelist || !config) {
return false;
}
const filter = getDomainFilter(config);
return filter ? filter.isWhitelisted(hostname, whitelist) : false;
}
function pruneExpiredTurnstileEntries(now = Date.now()) {
for (const domain in turnstileTimestamps) {
if (now - turnstileTimestamps[domain] >= TURNSTILE_BYPASS_TTL_MS) {
delete turnstileTimestamps[domain];
}
}
}
function getExactTurnstileBypass(hostname) {
if (!hostname) {
return { active: false, remainingMs: 0 };
}
const now = Date.now();
const timestamp = turnstileTimestamps[hostname];
if (!timestamp) {
return { active: false, remainingMs: 0 };
}
const age = now - timestamp;
if (age >= TURNSTILE_BYPASS_TTL_MS) {
delete turnstileTimestamps[hostname];
return { active: false, remainingMs: 0 };
}
return {
active: true,
remainingMs: TURNSTILE_BYPASS_TTL_MS - age
};
}
function getTurnstileBypassIncludingParents(hostname) {
if (!hostname) {
return { active: false, matchedDomain: null, remainingMs: 0 };
}
pruneExpiredTurnstileEntries();
const labels = hostname.split(".");
for (let i = 0; i < labels.length; i++) {
const domain = labels.slice(i).join(".");
const bypass = getExactTurnstileBypass(domain);
if (bypass.active) {
return {
active: true,
matchedDomain: domain,
remainingMs: bypass.remainingMs
};
}
}
return { active: false, matchedDomain: null, remainingMs: 0 };
}
function isCloudflareChallengeHostname(hostname) {
return hostname === "challenges.cloudflare.com" || hostname.endsWith(".challenges.cloudflare.com");
}
async function ensureBackgroundInitialized() {
if (!configLoaded) {
debugLog("[Background] Config not loaded yet, waiting for initialization...");
await initializationPromise;
debugLog("[Background] Initialization complete");
}
}
function markTriggeredFeatureForTab(tabId, hostname, feature) {
if (!tabId) {
return;
}
if (!triggeredFeaturesPerTab[tabId] || triggeredFeaturesPerTab[tabId].hostname !== hostname) {
triggeredFeaturesPerTab[tabId] = { hostname: hostname, features: new Set() };
}
triggeredFeaturesPerTab[tabId].features.add(feature);
}
function queryTabs(queryInfo) {
return new Promise((resolve) => {
chrome.tabs.query(queryInfo, (tabs) => {
if (chrome.runtime.lastError) {
debugWarn("[Background] Failed to query tabs for broadcast:", chrome.runtime.lastError.message);
resolve([]);
return;
}
resolve(tabs || []);
});
});
}
function sendMessageToTabIgnoringErrors(tabId, message) {
return new Promise((resolve) => {
chrome.tabs.sendMessage(tabId, message, () => {
// Read runtime.lastError to suppress "Unchecked runtime.lastError" noise.
// These two failures are expected during tab broadcasts:
// 1) Tab has no content script, 2) Receiver doesn't send a response.
const error = chrome.runtime.lastError;
if (error) {
const msg = error.message || "";
const expected =
msg.includes("Could not establish connection. Receiving end does not exist.") ||
msg.includes("The message port closed before a response was received.");
if (!expected) {
debugWarn("[Background] tabs.sendMessage warning for tab", tabId + ":", msg);
}
}
resolve();
});
});
}
async function broadcastConfigUpdated(config) {
const tabs = await queryTabs({ url: ["http://*/*", "https://*/*"] });
await Promise.all(
tabs
.filter(tab => typeof tab.id === "number")
.map(tab => sendMessageToTabIgnoringErrors(tab.id, { type: "config-updated", config }))
);
}
function addFeatureIfActive(injectionConfig, filter, config, url, featureName, label) {
const isActive = filter.shouldActivateFeature(url, featureName);
debugLog(`[Background] ${label} active:`, isActive);
if (isActive) {
injectionConfig[featureName] = config[featureName];
}
return isActive;
}
function setTurnstileSessionFlagAndReload(tabId, timestamp) {
if (typeof tabId !== "number") {
return;
}
const code = `
try {
// Set Turnstile timestamp for injector to read synchronously
sessionStorage.setItem('${TURNSTILE_SESSION_KEY}', '${timestamp}');
} catch (e) {
// Ignore errors
}
`;
chrome.tabs.executeScript(tabId, {
code: code,
runAt: "document_start"
}, () => {
debugLog("[Background] SessionStorage flag set, scheduling reload in 1s for tab:", tabId);
setTimeout(() => {
debugLog("[Background] Reloading tab now:", tabId);
chrome.tabs.reload(tabId, { bypassCache: true });
}, TURNSTILE_RELOAD_DELAY_MS);
});
}
// ========== SESSION SWITCHER ==========
function normalizeSessionHostname(hostname) {
if (!hostname || typeof hostname !== "string") {
return "";
}
return hostname.trim().toLowerCase().replace(/^www\./, "");
}
function resolveSessionHostname(request, sender) {
const explicitHostname = normalizeSessionHostname(request && (request.hostname || request.domain));
if (explicitHostname) {
return explicitHostname;
}
return normalizeSessionHostname(resolveTabHostname(sender));
}
function sanitizeSessionName(name) {
const trimmed = typeof name === "string" ? name.trim() : "";
if (trimmed) {
return trimmed.slice(0, 64);
}
const now = new Date();
return "Session " + now.toLocaleString();
}
function createSessionId() {
return "session-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2, 8);
}
async function readSessionState() {
const stored = await storage.read([SESSION_STORAGE_KEY, ACTIVE_SESSIONS_STORAGE_KEY]);
const sessions = Array.isArray(stored[SESSION_STORAGE_KEY]) ? stored[SESSION_STORAGE_KEY] : [];
const activeSessions = stored[ACTIVE_SESSIONS_STORAGE_KEY] && typeof stored[ACTIVE_SESSIONS_STORAGE_KEY] === "object"
? stored[ACTIVE_SESSIONS_STORAGE_KEY]
: {};
return { sessions, activeSessions };
}
async function writeSessionState(sessions, activeSessions) {
await storage.write({
[SESSION_STORAGE_KEY]: sessions,
[ACTIVE_SESSIONS_STORAGE_KEY]: activeSessions
});
}
function cookiesGetAllCookieStores() {
return new Promise((resolve, reject) => {
chrome.cookies.getAllCookieStores((stores) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve(stores || []);
});
});
}
function cookiesGetAll(details) {
return new Promise((resolve, reject) => {
chrome.cookies.getAll(details, (cookies) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve(cookies || []);
});
});
}
function cookiesRemove(details) {
return new Promise((resolve, reject) => {
chrome.cookies.remove(details, (removed) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve(removed);
});
});
}
function cookiesSet(details) {
return new Promise((resolve, reject) => {
chrome.cookies.set(details, (cookie) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve(cookie);
});
});
}
function buildCookieUrl(cookie, fallbackHostname) {
const protocol = cookie.secure ? "https" : "http";
let host = cookie.domain || fallbackHostname;
if (typeof host !== "string") {
throw new Error("Invalid cookie host");
}
host = host.replace(/^\./, "").trim();
if (!host) {
throw new Error("Invalid cookie host");
}
const path = cookie.path || "/";
return protocol + "://" + host + path;
}
function maybeCopyCookiePartitionKey(targetDetails, cookie) {
if (!cookie || !cookie.partitionKey) {
return;
}
// Preserve partitioned cookie identity when the browser exposes it.
// Without this, restored auth cookies may become non-partitioned and invalid.
targetDetails.partitionKey = cookie.partitionKey;
}
function cookieMatchesHostname(cookie, hostname) {
if (!cookie || !cookie.domain || !hostname) {
return false;
}
const normalizedHostname = hostname.split(":")[0].toLowerCase();
const cookieDomain = cookie.domain.replace(/^\./, "").toLowerCase();
return (
cookieDomain === normalizedHostname ||
cookieDomain === "www." + normalizedHostname ||
normalizedHostname.endsWith("." + cookieDomain) ||
cookieDomain.endsWith("." + normalizedHostname)
);
}
async function getCookiesForHostname(hostname) {
if (!chrome.cookies || !chrome.cookies.getAllCookieStores) {
return [];
}
const stores = await cookiesGetAllCookieStores();
const allCookies = [];
for (const store of stores) {
const storeCookies = await cookiesGetAll({ storeId: store.id });
const matchingCookies = storeCookies.filter((cookie) => cookieMatchesHostname(cookie, hostname));
allCookies.push(...matchingCookies);
}
return allCookies;
}
async function clearCookiesForHostname(hostname) {
const cookies = await getCookiesForHostname(hostname);
const removeOperations = cookies.map(async (cookie) => {
try {
const removeDetails = {
url: buildCookieUrl(cookie, hostname),
name: cookie.name,
storeId: cookie.storeId
};
maybeCopyCookiePartitionKey(removeDetails, cookie);
await cookiesRemove(removeDetails);
} catch (error) {
debugWarn("[Session] Failed to remove cookie:", cookie.name, error);
}
});
await Promise.all(removeOperations);
}
async function restoreCookies(cookies, fallbackHostname) {
if (!Array.isArray(cookies) || cookies.length === 0) {
return;
}
const restoreOperations = cookies.map(async (cookie) => {
try {
const details = {
url: buildCookieUrl(cookie, fallbackHostname),
name: cookie.name,
value: cookie.value,
path: cookie.path,
secure: cookie.secure,
httpOnly: cookie.httpOnly,
storeId: cookie.storeId
};
if (cookie.domain && cookie.domain.startsWith(".")) {
details.domain = cookie.domain;
}
if (!cookie.session && typeof cookie.expirationDate === "number") {
details.expirationDate = cookie.expirationDate;
}
if (cookie.sameSite && cookie.sameSite !== "unspecified") {
details.sameSite = cookie.sameSite;
}
if (typeof cookie.sameParty === "boolean") {
details.sameParty = cookie.sameParty;
}
maybeCopyCookiePartitionKey(details, cookie);
await cookiesSet(details);
} catch (error) {
debugWarn("[Session] Failed to restore cookie:", cookie && cookie.name, error);
}
});
await Promise.all(restoreOperations);
}
function executeScriptInTab(tabId, code, runAt = "document_idle") {
return new Promise((resolve, reject) => {
chrome.tabs.executeScript(tabId, { code, runAt }, (results) => {
if (chrome.runtime.lastError) {
reject(new Error(chrome.runtime.lastError.message));
return;
}
resolve(results);
});
});
}
async function readTabStorageSnapshot(tabId) {
const script = `
(() => {
const snapshot = { localStorage: {}, sessionStorage: {} };
try {
for (let i = 0; i < localStorage.length; i++) {
const key = localStorage.key(i);
if (key !== null) {
snapshot.localStorage[key] = localStorage.getItem(key);
}
}
} catch (error) {}
try {
for (let i = 0; i < sessionStorage.length; i++) {
const key = sessionStorage.key(i);
if (key !== null) {
snapshot.sessionStorage[key] = sessionStorage.getItem(key);
}
}
} catch (error) {}
return snapshot;
})();
`;
try {
const results = await executeScriptInTab(tabId, script);
return (results && results[0]) || { localStorage: {}, sessionStorage: {} };
} catch (error) {
debugWarn("[Session] Failed to read storage snapshot:", error);
return { localStorage: {}, sessionStorage: {} };
}
}
async function clearTabStorage(tabId) {
const script = `
(() => {
try { localStorage.clear(); } catch (error) {}
try { sessionStorage.clear(); } catch (error) {}
return true;
})();
`;
await executeScriptInTab(tabId, script);
}
async function restoreTabStorage(tabId, storageSnapshot) {
const payload = JSON.stringify({
localStorage: storageSnapshot && storageSnapshot.localStorage ? storageSnapshot.localStorage : {},
sessionStorage: storageSnapshot && storageSnapshot.sessionStorage ? storageSnapshot.sessionStorage : {}
});
const script = `
((snapshot) => {
try {
localStorage.clear();
Object.keys(snapshot.localStorage || {}).forEach((key) => {
const value = snapshot.localStorage[key];
localStorage.setItem(key, value === null || value === undefined ? "" : String(value));
});
} catch (error) {}
try {
sessionStorage.clear();
Object.keys(snapshot.sessionStorage || {}).forEach((key) => {
const value = snapshot.sessionStorage[key];
sessionStorage.setItem(key, value === null || value === undefined ? "" : String(value));
});
} catch (error) {}
return true;
})(${payload});
`;
await executeScriptInTab(tabId, script);
}
function reloadTab(tabId) {
return new Promise((resolve) => {
chrome.tabs.reload(tabId, { bypassCache: true }, () => {
resolve();
});
});
}
function sortSessionsForHostname(sessions, hostname) {
return sessions
.filter((session) => session.domain === hostname)
.sort((a, b) => (b.lastUsed || b.createdAt || 0) - (a.lastUsed || a.createdAt || 0));
}
function cleanupSessionLimits(sessions, activeSessions, hostname) {
const domainSessions = sortSessionsForHostname(sessions, hostname);
if (domainSessions.length <= MAX_SAVED_SESSIONS_PER_DOMAIN) {
return sessions;
}
const keepIds = new Set(domainSessions.slice(0, MAX_SAVED_SESSIONS_PER_DOMAIN).map((session) => session.id));
const nextSessions = sessions.filter((session) => session.domain !== hostname || keepIds.has(session.id));
if (activeSessions[hostname] && !keepIds.has(activeSessions[hostname])) {
delete activeSessions[hostname];
}
return nextSessions;
}
// ========== INITIALIZATION ==========
// Initialize config immediately when background script loads
initializationPromise = (async function initializeBackground() {
try {
// Initial logs before config is loaded - use console.log since debugLog isn't ready yet
setCurrentConfig(await loadConfig());
configLoaded = true;
await applyUserAgentSpoofing();
await applyWebRTCPolicy();
await applyProxySettings();
setupContextMenus();
debugLog("Stealth Guard initialized successfully");
} catch (e) {
debugError("Failed to initialize:", e);
debugError("Stack:", e.stack);
}
})();
// Initialize on install
chrome.runtime.onInstalled.addListener(async (details) => {
debugLog("Stealth Guard installed/updated");
// Ensure config is loaded
if (!configLoaded) {
setCurrentConfig(await loadConfig());
configLoaded = true;
}
// Apply User-Agent spoofing
await applyUserAgentSpoofing();
// Apply WebRTC policy
await applyWebRTCPolicy();
// Apply proxy settings
await applyProxySettings();
// Setup context menus
setupContextMenus();
// Open welcome page on first install
if (details.reason === "install") {
chrome.tabs.create({ url: "options/options.html" });
}
});
// Initialize on startup
chrome.runtime.onStartup.addListener(async () => {
debugLog("Stealth Guard starting");
setCurrentConfig(await loadConfig());
configLoaded = true;
await applyUserAgentSpoofing();
await applyWebRTCPolicy();
await applyProxySettings();
});
// ========== DYNAMIC CONFIG INJECTION ==========
// Config injection is handled by injector.js content script.
// The injector currently reads from session/storage cache directly.
// "get-injection-config" is retained as a legacy compatibility endpoint.
// ========== USER-AGENT SPOOFING ==========
// HTTP User-Agent header modification using declarativeNetRequest API
// Inspired by UA Switcher Pro - this approach works reliably in all Chrome installs
const USER_AGENT_PRESETS = {
macos: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.6 Safari/605.1.15",
macos_chrome: "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36",
windows: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36 Edg/125.0.0.0",
iphone: "Mozilla/5.0 (iPhone; CPU iPhone OS 17_4_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4.1 Mobile/15E148 Safari/604.1",
android: "Mozilla/5.0 (Linux; Android 14; Pixel 8 Pro) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Mobile Safari/537.36"
};
const UA_RULE_ID = 1; // Rule ID for User-Agent modification (Legacy DNR)
// Helper to remove legacy DNR rules
async function clearDNRRules() {
try {
await chrome.declarativeNetRequest.updateSessionRules({
removeRuleIds: [UA_RULE_ID],
addRules: []
});
} catch (e) {}
}
// Global reference to the listener function so we can remove it
let uaListener = null;
// Apply User-Agent spoofing using webRequest (Synchronous & Reliable)
async function applyUserAgentSpoofing() {
try {
const config = await getConfig();
// Always clear legacy DNR rules first
await clearDNRRules();
// Remove existing listener if any
if (uaListener) {
chrome.webRequest.onBeforeSendHeaders.removeListener(uaListener);
uaListener = null;
}
// Check if User-Agent spoofing is enabled
if (!config.useragent || !config.useragent.enabled) {
debugLog("User-Agent spoofing disabled");
return;
}
// Get the User-Agent string
const preset = config.useragent.preset || "macos";
const userAgent = USER_AGENT_PRESETS[preset];
if (!userAgent) {
debugWarn("Invalid User-Agent preset:", preset);
return;
}
// Create the listener function
uaListener = function(details) {
// Check if this domain is in the Turnstile bypass list
let hostname = null;
try {
hostname = new URL(details.url).hostname;
} catch (e) {
return { requestHeaders: details.requestHeaders };
}
// Check specific Cloudflare challenge domain first
if (isCloudflareChallengeHostname(hostname)) {
debugLog("[UA Listener] BYPASS: Cloudflare challenge domain:", hostname);
return { requestHeaders: details.requestHeaders };
}
// Check Turnstile bypass window
const bypassInfo = getTurnstileBypassIncludingParents(hostname);
if (bypassInfo.active) {
// Bypass active: Don't modify headers (send real UA)
debugLog(
"[UA Listener] BYPASS: Turnstile domain",
bypassInfo.matchedDomain,
"age:",
Math.round((TURNSTILE_BYPASS_TTL_MS - bypassInfo.remainingMs) / 1000) + "s",
"for URL:",
details.url.substring(0, 100)
);
return { requestHeaders: details.requestHeaders };
}
// Modify the User-Agent header
let uaHeaderFound = false;
for (let i = 0; i < details.requestHeaders.length; ++i) {
if (details.requestHeaders[i].name.toLowerCase() === 'user-agent') {
details.requestHeaders[i].value = userAgent;
uaHeaderFound = true;
break;
}
}
// If no User-Agent header found (rare), add it
if (!uaHeaderFound) {
details.requestHeaders.push({
name: 'User-Agent',
value: userAgent
});
}
return { requestHeaders: details.requestHeaders };
};
// Register the listener
chrome.webRequest.onBeforeSendHeaders.addListener(
uaListener,
{ urls: ["<all_urls>"] },
["blocking", "requestHeaders", "extraHeaders"]
);
debugLog("User-Agent spoofing enabled (webRequest):", preset, "->", userAgent);
} catch (e) {
debugError("Failed to apply User-Agent spoofing:", e);
}
}
// ========== WEBRTC POLICY ==========
async function applyWebRTCPolicyValue(policy) {
if (lastAppliedWebRTCPolicy === policy || pendingWebRTCPolicy === policy) {
return;
}
pendingWebRTCPolicy = policy;
try {
await chrome.privacy.network.webRTCIPHandlingPolicy.set({ value: policy });
lastAppliedWebRTCPolicy = policy;
} finally {
if (pendingWebRTCPolicy === policy) {
pendingWebRTCPolicy = null;
}
}
}
async function applyWebRTCPolicy() {
try {
const config = await getConfig();
const policy = config.webrtc.enabled ? config.webrtc.policy : "default";
await applyWebRTCPolicyValue(policy);
debugLog("[WebRTC] Base policy applied:", policy);
} catch (e) {
console.error("Failed to apply WebRTC policy:", e);
}
}
// Simple WebRTC policy setter (similar to WebRTC Leak Killer)
function setWebRTCPolicy(url) {
getConfig().then(config => {
if (!config.webrtc.enabled) {
// Protection disabled - allow WebRTC everywhere
applyWebRTCPolicyValue("default")
.then(() => {
debugLog("[WebRTC] Protection disabled, allowing WebRTC");
})
.catch((error) => {
debugError("[WebRTC] Failed to set default policy:", error);
});
return;
}
// Check if URL is on whitelist/allowlist
const hostname = getHostnameFromUrl(url);
const isOnAllowlist = isHostnameOnFeatureAllowlist(hostname, config.webrtc.whitelist, config);
// Set policy: allow if on allowlist, block otherwise
const policy = isOnAllowlist ? "default" : config.webrtc.policy;
applyWebRTCPolicyValue(policy)
.then(() => {
debugLog("[WebRTC] Policy set to:", policy, "for:", url);
})
.catch((error) => {
debugError("[WebRTC] Failed to set policy:", error);
});
}).catch(e => {
debugError("[WebRTC] Failed to set policy:", e);
});
}
// Main listener: navigation events (like WebRTC Leak Killer)
chrome.webNavigation.onBeforeNavigate.addListener((details) => {
if (details.frameId !== 0) return; // Only main frame
setWebRTCPolicy(details.url);
});
// Secondary listener: fires after navigation commits (more reliable timing)
chrome.webNavigation.onCommitted.addListener((details) => {
if (details.frameId !== 0) return; // Only main frame
setWebRTCPolicy(details.url);
});
// Tab update listener: catches URL changes and loading state changes
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
// Clear triggered features only when navigating to a different domain
if (changeInfo.url) {
try {
const newHostname = new URL(changeInfo.url).hostname;
const tabData = triggeredFeaturesPerTab[tabId];
if (tabData && tabData.hostname !== newHostname) {
delete triggeredFeaturesPerTab[tabId];
}
} catch (e) {
// Invalid URL, clear the data
delete triggeredFeaturesPerTab[tabId];
}
}
if (changeInfo.url && tab.active) {
setWebRTCPolicy(changeInfo.url);
updateProxyForActiveTab(changeInfo.url);
}
});
// Tab removed listener: clean up triggered features
chrome.tabs.onRemoved.addListener((tabId) => {
delete triggeredFeaturesPerTab[tabId];
});
// Tab activation listener: for switching between existing tabs
chrome.tabs.onActivated.addListener((activeInfo) => {
chrome.tabs.get(activeInfo.tabId, (tab) => {
if (chrome.runtime.lastError) {
// Tab might be closed or not accessible, ignore
return;
}
if (tab && tab.url) {
setWebRTCPolicy(tab.url);
updateProxyForActiveTab(tab.url);
// Delayed check to ensure policy is applied after activation
setTimeout(() => {
chrome.tabs.get(activeInfo.tabId, (currentTab) => {
if (chrome.runtime.lastError) {
// Tab might be closed, ignore
return;
}
if (currentTab && currentTab.active && currentTab.url) {
setWebRTCPolicy(currentTab.url);
}
});
}, ACTIVATION_RECHECK_DELAY_MS);
}
});
});
// ========== ACTIVE TAB PROXY BYPASS FOR WHITELISTED PAGES ==========
// Track pending proxy disable for re-navigation
let pendingProxyDisableTabId = null;
// Update proxy based on whether active tab is on a whitelisted domain
async function updateProxyForActiveTab(url) {
if (!currentConfig || !currentConfig.proxy || !currentConfig.proxy.enabled) {
return; // Proxy not enabled, nothing to do
}
try {
const urlObj = new URL(url);
const hostname = urlObj.hostname;
// Check if this domain is on the global whitelist
const isWhitelisted = isHostnameOnGlobalAllowlist(hostname, currentConfig);
if (isWhitelisted && !proxyDisabledForWhitelist) {
// Disable proxy completely for whitelisted tab
debugLog("[Proxy] Active tab is whitelisted, disabling proxy for:", hostname);
proxyDisabledForWhitelist = true;
await chrome.proxy.settings.set({
value: { mode: 'system' },
scope: 'regular'
});
} else if (!isWhitelisted && proxyDisabledForWhitelist) {
// Re-enable proxy for non-whitelisted tab
debugLog("[Proxy] Active tab is not whitelisted, re-enabling proxy");
proxyDisabledForWhitelist = false;
await applyProxySettings();
}
} catch (e) {
// Ignore invalid URLs (like chrome:// pages)
}
}
// Intercept main frame requests to whitelisted domains
// This ensures proxy is disabled BEFORE any resources load
chrome.webRequest.onBeforeRequest.addListener(
(details) => {
// Only handle main frame requests
if (details.type !== 'main_frame') {
return {};
}
// Skip if this is a re-navigation after proxy disable
if (pendingProxyDisableTabId === details.tabId) {
pendingProxyDisableTabId = null;
debugLog("[Proxy] Allowing re-navigation after proxy disable");
return {};
}
// Skip non-http URLs
if (!details.url.startsWith('http://') && !details.url.startsWith('https://')) {
return {};
}
try {
const url = new URL(details.url);
const hostname = url.hostname;
// Check if proxy is enabled and not already disabled for whitelist
if (!currentConfig || !currentConfig.proxy || !currentConfig.proxy.enabled) {
return {};
}
if (proxyDisabledForWhitelist) {
return {};
}
// Check if this domain is whitelisted
const isWhitelisted = isHostnameOnGlobalAllowlist(hostname, currentConfig);
if (isWhitelisted) {
// Cancel this request, disable proxy, then re-navigate
debugLog("[Proxy] Intercepted whitelisted navigation, disabling proxy first:", hostname);
proxyDisabledForWhitelist = true;
pendingProxyDisableTabId = details.tabId;
chrome.proxy.settings.set({
value: { mode: 'system' },
scope: 'regular'
}, () => {
// Re-navigate after proxy is disabled
debugLog("[Proxy] Proxy disabled, re-navigating to:", details.url);
chrome.tabs.update(details.tabId, { url: details.url });
});