-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
479 lines (408 loc) · 12.4 KB
/
Copy pathbackground.js
File metadata and controls
479 lines (408 loc) · 12.4 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
// Background service worker for proxy management
let proxyConfig = {
enabled: true,
host: "127.0.0.1",
port: "1080",
type: "socks5",
};
let whitelist = [];
let vpnDetected = false;
let lastIpAddress = null;
let autoAddMode = true;
let tabDomains = {};
let tabMainDomain = {};
let autoAddedDomains = new Set();
chrome.runtime.onInstalled.addListener(async () => {
const data = await chrome.storage.local.get(["proxyConfig", "whitelist"]);
if (data.proxyConfig) {
proxyConfig = data.proxyConfig;
} else {
await chrome.storage.local.set({ proxyConfig });
}
if (data.whitelist && Array.isArray(data.whitelist)) {
whitelist = data.whitelist;
} else {
whitelist = [];
await chrome.storage.local.set({ whitelist: [] });
}
const autoAddData = await chrome.storage.local.get(["autoAddMode"]);
if (autoAddData.autoAddMode !== undefined) {
autoAddMode = autoAddData.autoAddMode;
} else {
await chrome.storage.local.set({ autoAddMode: true });
}
updateProxySettings();
startVpnDetection();
});
chrome.runtime.onStartup.addListener(async () => {
const data = await chrome.storage.local.get(["proxyConfig", "whitelist"]);
if (data.proxyConfig) {
proxyConfig = data.proxyConfig;
}
if (data.whitelist && Array.isArray(data.whitelist)) {
whitelist = data.whitelist;
}
const autoAddData = await chrome.storage.local.get(["autoAddMode"]);
if (autoAddData.autoAddMode !== undefined) {
autoAddMode = autoAddData.autoAddMode;
}
updateProxySettings();
startVpnDetection();
});
// Listen for messages from popup
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "getConfig") {
sendResponse({
proxyConfig,
whitelist,
vpnDetected,
autoAddMode,
});
} else if (request.action === "toggleAutoAdd") {
autoAddMode = request.enabled;
chrome.storage.local.set({ autoAddMode });
sendResponse({ success: true, autoAddMode });
} else if (request.action === "updateConfig") {
proxyConfig = request.proxyConfig;
chrome.storage.local.set({ proxyConfig });
updateProxySettings();
sendResponse({ success: true });
} else if (request.action === "getTabDomains") {
// Get all domains used by the current tab
const domains = tabDomains[request.tabId] || new Set();
sendResponse({ domains: Array.from(domains) });
} else if (request.action === "addToWhitelist") {
const domainsToAdd = request.domains || [request.domain];
let added = [];
domainsToAdd.forEach((domain) => {
if (domain && !whitelist.includes(domain)) {
whitelist.push(domain);
added.push(domain);
// Add related domains for common services
const relatedDomains = getRelatedDomains(domain);
relatedDomains.forEach((related) => {
if (!whitelist.includes(related)) {
whitelist.push(related);
added.push(related);
console.log(`Auto-added related domain: ${related} for ${domain}`);
}
});
}
});
if (added.length > 0) {
chrome.storage.local.set({ whitelist }, () => {
updateProxySettings();
});
}
sendResponse({ success: true, whitelist, added });
} else if (request.action === "removeFromWhitelist") {
whitelist = whitelist.filter((d) => d !== request.domain);
chrome.storage.local.set({ whitelist }, () => {
updateProxySettings();
});
sendResponse({ success: true, whitelist });
} else if (request.action === "toggleProxy") {
proxyConfig.enabled = request.enabled;
chrome.storage.local.set({ proxyConfig }, () => {
updateProxySettings();
});
sendResponse({ success: true });
}
return true;
});
// Update proxy settings based on configuration
async function updateProxySettings() {
// If VPN is detected or proxy is disabled, use direct connection
if (vpnDetected || !proxyConfig.enabled) {
await chrome.proxy.settings.set({
value: {
mode: "direct",
},
scope: "regular",
});
return;
}
// Configure PAC script for whitelist-based routing
const pacScript = generatePacScript();
await chrome.proxy.settings.set({
value: {
mode: "pac_script",
pacScript: {
data: pacScript,
},
},
scope: "regular",
});
}
// Get related domains for common services
function getRelatedDomains(domain) {
const relatedMap = {
// YouTube domains
"youtube.com": [
"ytimg.com",
"googlevideo.com",
"yt3.ggpht.com",
"yt3.googleusercontent.com",
"googleapis.com",
],
"www.youtube.com": [
"ytimg.com",
"googlevideo.com",
"yt3.ggpht.com",
"yt3.googleusercontent.com",
],
// Twitter domains
"twitter.com": ["twimg.com", "t.co"],
"x.com": ["twimg.com", "t.co"],
// Facebook domains
"facebook.com": ["fbcdn.net", "facebook.net"],
// Instagram domains
"instagram.com": ["cdninstagram.com", "fbcdn.net"],
// Google services
"google.com": ["gstatic.com", "googleapis.com", "googleusercontent.com"],
// Add more as needed
};
// Check if domain or its parent has related domains
const exactMatch = relatedMap[domain];
if (exactMatch) return exactMatch;
// Check without www
const withoutWww = domain.replace(/^www\./, "");
if (relatedMap[withoutWww]) return relatedMap[withoutWww];
return [];
}
// Generate PAC script for selective proxy routing
function generatePacScript() {
const proxyString = `${proxyConfig.type.toUpperCase()} ${proxyConfig.host}:${
proxyConfig.port
}`;
// Create whitelist pattern matching
const whitelistConditions = whitelist
.map((domain) => {
// Match exact domain, all subdomains, and all paths/APIs
return `(host == "${domain}" || dnsDomainIs(host, ".${domain}"))`;
})
.join(" || ");
const pacScript = `
function FindProxyForURL(url, host) {
// Whitelist check - these domains and ALL their subdomains/APIs use proxy
if (${whitelistConditions || "false"}) {
return "${proxyString}";
}
// Everything else goes direct
return "DIRECT";
}
`;
return pacScript;
}
// VPN Detection - check for routing changes
async function detectVpn() {
try {
// Check if external IP has changed significantly
// This is a heuristic - if we can't reach a test server or routing changed
const response = await fetch("https://api.ipify.org?format=json", {
method: "GET",
cache: "no-cache",
});
const data = await response.json();
const currentIp = data.ip;
if (lastIpAddress === null) {
lastIpAddress = currentIp;
return false;
}
// If IP changed, might indicate VPN activation
// Additional check: test latency or routing
if (lastIpAddress !== currentIp) {
// IP changed - could be VPN, check if it's a known VPN range
// For now, we'll use a simple check
const wasVpn = vpnDetected;
// Check if routing through a tunnel (heuristic: check for private IP from public service)
// This is a simplified check
const startTime = Date.now();
await fetch("https://www.google.com/generate_204", { cache: "no-cache" });
const latency = Date.now() - startTime;
// High latency might indicate VPN tunnel
vpnDetected = latency > 500; // Threshold can be adjusted
if (vpnDetected !== wasVpn) {
console.log("VPN status changed:", vpnDetected);
updateProxySettings();
}
lastIpAddress = currentIp;
}
return vpnDetected;
} catch (error) {
console.error("VPN detection error:", error);
return false;
}
}
// Start VPN detection polling
function startVpnDetection() {
// Check every 30 seconds
setInterval(detectVpn, 30000);
// Initial check
detectVpn();
}
// Track web requests to detect all domains used by a page
chrome.webRequest.onBeforeRequest.addListener(
(details) => {
if (details.tabId > 0) {
try {
const url = new URL(details.url);
const domain = url.hostname;
// Initialize set for this tab if it doesn't exist
if (!tabDomains[details.tabId]) {
tabDomains[details.tabId] = new Set();
}
// Add domain to the tab's domain list
tabDomains[details.tabId].add(domain);
const parts = domain.split(".");
if (parts.length > 2) {
const parentDomain = parts.slice(-2).join(".");
tabDomains[details.tabId].add(parentDomain);
}
} catch (e) {}
}
},
{ urls: ["<all_urls>"] }
);
// Also track completed requests to catch more domains
chrome.webRequest.onCompleted.addListener(
(details) => {
if (details.tabId > 0) {
try {
const url = new URL(details.url);
const domain = url.hostname;
if (!tabDomains[details.tabId]) {
tabDomains[details.tabId] = new Set();
}
tabDomains[details.tabId].add(domain);
const parts = domain.split(".");
if (parts.length > 2) {
const parentDomain = parts.slice(-2).join(".");
tabDomains[details.tabId].add(parentDomain);
}
if (autoAddMode && tabMainDomain[details.tabId]) {
autoAddDomainsForTab(details.tabId);
}
} catch (e) {}
}
},
{ urls: ["<all_urls>"] }
);
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === "complete" && tab.url) {
try {
const url = new URL(tab.url);
if (!url.protocol.startsWith("chrome")) {
tabMainDomain[tabId] = url.hostname;
if (autoAddMode) {
setTimeout(() => {
autoAddDomainsForTab(tabId);
}, 3000);
}
}
} catch (e) {}
}
});
function autoAddDomainsForTab(tabId) {
if (!autoAddMode || !tabDomains[tabId] || tabDomains[tabId].size === 0) {
return;
}
const mainDomain = tabMainDomain[tabId];
if (!mainDomain) return;
const mainDomainInWhitelist = whitelist.some(
(w) =>
mainDomain === w ||
mainDomain.endsWith("." + w) ||
w.endsWith("." + mainDomain) ||
(mainDomain.startsWith("www.") && mainDomain.substring(4) === w) ||
"www." + mainDomain === w
);
if (!mainDomainInWhitelist) {
return;
}
if (autoAddedDomains.has(mainDomain)) {
return;
}
const domains = Array.from(tabDomains[tabId]);
let addedCount = 0;
let addedDomainsList = [];
domains.forEach((domain) => {
if (!whitelist.includes(domain)) {
whitelist.push(domain);
addedCount++;
addedDomainsList.push(domain);
// Add related domains
const relatedDomains = getRelatedDomains(domain);
relatedDomains.forEach((related) => {
if (!whitelist.includes(related)) {
whitelist.push(related);
addedCount++;
addedDomainsList.push(related);
}
});
// Add www/non-www versions
if (domain.startsWith("www.")) {
const nonWww = domain.substring(4);
if (!whitelist.includes(nonWww)) {
whitelist.push(nonWww);
addedCount++;
addedDomainsList.push(nonWww);
}
} else {
const withWww = "www." + domain;
if (!whitelist.includes(withWww)) {
whitelist.push(withWww);
addedCount++;
addedDomainsList.push(withWww);
}
}
}
});
if (addedCount > 0) {
autoAddedDomains.add(mainDomain);
chrome.storage.local.set({ whitelist }, () => {
updateProxySettings();
});
}
}
// Clean up when tab is closed
chrome.tabs.onRemoved.addListener((tabId) => {
delete tabDomains[tabId];
delete tabMainDomain[tabId];
});
setInterval(() => {
const tabIds = Object.keys(tabDomains);
if (tabIds.length > 100) {
tabIds.slice(0, tabIds.length - 100).forEach((id) => {
delete tabDomains[id];
});
}
}, 60000);
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create({
id: "addToWhitelist",
title: "Add to Proxy Whitelist (with all domains)",
contexts: ["page"],
});
});
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === "addToWhitelist") {
const url = new URL(tab.url);
const mainDomain = url.hostname;
const allDomains = tabDomains[tab.id]
? Array.from(tabDomains[tab.id])
: [mainDomain];
let added = [];
allDomains.forEach((domain) => {
if (!whitelist.includes(domain)) {
whitelist.push(domain);
added.push(domain);
}
});
if (added.length > 0) {
chrome.storage.local.set({ whitelist }, () => {
updateProxySettings();
});
}
}
});