-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
379 lines (338 loc) · 12.7 KB
/
background.js
File metadata and controls
379 lines (338 loc) · 12.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
// 在 chrome.runtime.onInstalled 事件处理函数中初始化白名单
chrome.runtime.onInstalled.addListener(() => {
// 从 config.yaml 加载白名单
fetch('config.yaml')
.then(response => response.text())
.then(yamlText => {
// 简单解析 YAML 文件中的白名单
const whitelist = parseWhitelistFromYaml(yamlText);
chrome.storage.sync.set({
proxies: [
{ type: 'http', host: '127.0.0.1', port: 8080 },
{ type: 'socks5', host: '127.0.0.1', port: 10808 }
],
isProxyEnabled: false,
currentProxy: 0,
whitelist: whitelist // 使用从 config.yaml 加载的白名单
}, function() {
console.log('默认设置已完成。白名单已从 config.yaml 加载,共 ' + whitelist.length + ' 个域名');
// 初始化时设置为直连模式
chrome.proxy.settings.set({
value: { mode: 'direct' },
scope: 'regular'
}, function() {
console.log('初始代理设置为直连模式');
});
});
})
.catch(error => {
console.error('加载 config.yaml 失败:', error);
// 如果加载失败,使用空白名单
chrome.storage.sync.set({
proxies: [
{ type: 'http', host: '127.0.0.1', port: 8080 },
{ type: 'socks5', host: '127.0.0.1', port: 9050 }
],
isProxyEnabled: false,
currentProxy: 0,
whitelist: [] // 初始化白名单为空数组
});
});
});
// 简单解析 YAML 文件中的白名单
function parseWhitelistFromYaml(yamlText) {
const whitelist = [];
const lines = yamlText.split('\n');
let inWhitelistSection = false;
for (const line of lines) {
if (line.trim().startsWith('whitelist:')) {
inWhitelistSection = true;
continue;
}
if (inWhitelistSection && line.trim().startsWith('-')) {
const domain = line.trim().substring(1).trim();
if (domain && !domain.startsWith('#')) {
whitelist.push(domain);
}
}
}
return whitelist;
}
// 监听来自popup.js的消息
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.action === 'toggleProxy') {
updateProxySettings(request.enable, request.proxyConfig);
sendResponse({success: true});
} else if (request.action === 'getProxyState') {
chrome.proxy.settings.get({}, function(config) {
sendResponse({
isEnabled: config.value.mode !== 'direct',
currentConfig: config.value
});
});
return true; // 保持消息通道开放以进行异步响应
} else if (request.action === 'addToWhitelist') {
// 修正:使用 request 而不是 message
addToWhitelist(request.domain, sendResponse);
return true;
} else if (request.action === 'removeFromWhitelist') {
// 修正:使用 request 而不是 message
removeFromWhitelist(request.domain, sendResponse);
return true;
} else if (request.action === 'getWhitelist') {
// 获取白名单列表
getWhitelist(sendResponse);
return true;
}
// 批量添加到白名单
if (request.action === 'batchAddToWhitelist') {
chrome.storage.sync.get(['whitelist'], function(data) {
const whitelist = data.whitelist || [];
const newWhitelist = [...whitelist, ...request.domains];
chrome.storage.sync.set({whitelist: newWhitelist}, function() {
sendResponse({success: true});
});
});
return true; // 异步响应
}
// 清空白名单
if (request.action === 'clearWhitelist') {
chrome.storage.sync.set({whitelist: []}, function() {
sendResponse({success: true});
});
return true; // 异步响应
}
});
// 添加域名到白名单
function addToWhitelist(domain, callback) {
if (!domain) {
callback({success: false, message: '域名不能为空'});
return;
}
// 格式化域名,移除协议前缀和路径
domain = formatDomain(domain);
chrome.storage.sync.get(['whitelist'], function(data) {
let whitelist = data.whitelist || [];
// 检查域名是否已存在于白名单中
if (whitelist.includes(domain)) {
callback({success: false, message: '该域名已在白名单中'});
return;
}
// 添加到白名单
whitelist.push(domain);
chrome.storage.sync.set({whitelist: whitelist}, function() {
// 更新 config.yaml 文件
updateConfigYaml(whitelist);
// 如果代理已启用,更新代理设置以应用新的白名单
chrome.storage.sync.get(['isProxyEnabled', 'proxies', 'currentProxy'], function(data) {
if (data.isProxyEnabled && data.proxies && data.proxies[data.currentProxy]) {
updateProxySettings(true, data.proxies[data.currentProxy]);
}
callback({success: true, whitelist: whitelist});
});
});
});
}
// 从白名单移除域名
function removeFromWhitelist(domain, callback) {
if (!domain) {
callback({success: false, message: '域名不能为空'});
return;
}
// 格式化域名,确保与存储的格式一致
domain = formatDomain(domain);
chrome.storage.sync.get(['whitelist'], function(data) {
let whitelist = data.whitelist || [];
// 检查域名是否存在于白名单中
const index = whitelist.indexOf(domain);
if (index === -1) {
callback({success: false, message: '该域名不在白名单中'});
return;
}
// 使用 splice 移除指定域名
whitelist.splice(index, 1);
chrome.storage.sync.set({whitelist: whitelist}, function() {
if (chrome.runtime.lastError) {
callback({success: false, message: '保存白名单时出错:' + chrome.runtime.lastError.message});
return;
}
// 如果代理已启用,更新代理设置以应用新的白名单
chrome.storage.sync.get(['isProxyEnabled', 'proxies', 'currentProxy'], function(data) {
if (data.isProxyEnabled && data.proxies && data.proxies[data.currentProxy]) {
updateProxySettings(true, data.proxies[data.currentProxy]);
}
callback({success: true, whitelist: whitelist, message: '域名已成功从白名单中移除'});
});
});
});
}
// 获取白名单列表
function getWhitelist(callback) {
chrome.storage.sync.get(['whitelist'], function(data) {
callback({whitelist: data.whitelist || []});
});
}
// 格式化域名,移除协议前缀和路径
function formatDomain(domain) {
// 移除协议前缀 (http://, https://, etc.)
domain = domain.replace(/^(https?:\/\/)?(www\.)?/i, '');
// 移除路径和查询参数
domain = domain.split('/')[0];
return domain.trim().toLowerCase();
}
// 修改 updateProxySettings 函数以支持白名单
function updateProxySettings(enable, proxyConfig) {
let config = {};
if (enable && proxyConfig) {
// 确保代理类型正确
const scheme = proxyConfig.type.toLowerCase();
// 获取白名单
chrome.storage.sync.get(['whitelist'], function(data) {
const whitelist = data.whitelist || [];
// 修改白名单格式,确保正确的匹配模式
const formattedWhitelist = whitelist.map(domain => {
// 确保域名前有通配符和点,这样可以匹配子域名
return domain.startsWith('*.') ? domain : `*.${domain}`;
});
// 添加不带通配符的版本,以匹配主域名
whitelist.forEach(domain => {
formattedWhitelist.push(domain);
});
const bypassList = ['<local>', 'localhost', '127.0.0.1'].concat(formattedWhitelist);
if (scheme === 'socks5' && proxyConfig.username && proxyConfig.password) {
// 对于带认证的SOCKS5代理,使用PAC脚本
let bypassRules = '';
if (whitelist.length > 0) {
bypassRules = `
// 检查是否在白名单中
// 使用更精确的匹配方式
if (${whitelist.map(domain => {
// 转义点,避免正则表达式中的特殊含义
const escapedDomain = domain.replace(/\./g, '\\.');
// 使用更精确的匹配模式
return `(host === "${domain}" || host.endsWith(".${domain}"))`;
}).join(' || ')}) {
return "DIRECT";
}
`;
}
const pacScript = `
function FindProxyForURL(url, host) {
// 本地地址直连
if (shExpMatch(host, "localhost") || shExpMatch(host, "127.0.0.1")) {
return "DIRECT";
}
${bypassRules}
return "SOCKS5 ${proxyConfig.username}:${proxyConfig.password}@${proxyConfig.host}:${proxyConfig.port}";
}
`;
config = {
mode: 'pac_script',
pacScript: {
data: pacScript
}
};
console.log('设置带认证的SOCKS5代理 (PAC脚本模式),白名单域名数量:', whitelist.length);
} else {
// 对于其他代理类型或不需要认证的SOCKS5,使用普通模式
config = {
mode: 'fixed_servers',
rules: {
singleProxy: {
scheme: scheme,
host: proxyConfig.host,
port: parseInt(proxyConfig.port)
},
bypassList: bypassList
}
};
console.log('设置代理:', scheme, proxyConfig.host, proxyConfig.port, '白名单域名数量:', whitelist.length);
}
if (proxyConfig.username && proxyConfig.password && scheme !== 'socks5') {
console.log('代理需要认证 (非SOCKS5)');
}
chrome.proxy.settings.set({
value: config,
scope: 'regular'
}, function() {
if (chrome.runtime.lastError) {
console.error('代理设置错误:', chrome.runtime.lastError);
} else {
console.log('代理设置已更新:', enable ? '启用' : '禁用');
chrome.storage.sync.set({ isProxyEnabled: enable });
}
});
});
} else {
config = { mode: 'direct' };
console.log('设置为直连模式');
chrome.proxy.settings.set({
value: config,
scope: 'regular'
}, function() {
if (chrome.runtime.lastError) {
console.error('代理设置错误:', chrome.runtime.lastError);
} else {
console.log('代理设置已更新:', enable ? '启用' : '禁用');
chrome.storage.sync.set({ isProxyEnabled: enable });
}
});
}
}
// 处理代理认证
chrome.webRequest.onAuthRequired.addListener(
function(details, callbackFn) {
// 检查是否是代理认证请求
if (details.isProxy) {
chrome.storage.sync.get(['proxies', 'currentProxy'], function(data) {
if (data.proxies && data.proxies[data.currentProxy]) {
const currentProxy = data.proxies[data.currentProxy];
if (currentProxy.username && currentProxy.password) {
console.log('提供代理认证信息');
callbackFn({
authCredentials: {
username: currentProxy.username,
password: currentProxy.password
}
});
return;
}
}
// 如果没有认证信息,尝试继续请求而不是直接取消
console.log('没有代理认证信息,尝试继续请求');
callbackFn({});
});
} else {
// 非代理认证请求,继续
callbackFn({});
}
},
{urls: ["<all_urls>"]},
["asyncBlocking"]
);
// 更新 config.yaml 文件
function updateConfigYaml(whitelist) {
// 由于浏览器扩展无法直接写入文件系统,我们需要通过下载文件的方式让用户更新 config.yaml
// 创建一个包含更新后白名单的 YAML 文本
let yamlContent = "# Proxy 24 配置文件\nwhitelist:\n # 白名单域名列表,每行一个域名\n";
whitelist.forEach(domain => {
yamlContent += ` - ${domain}\n`;
});
// 创建一个下载链接
const blob = new Blob([yamlContent], {type: 'text/yaml'});
const url = URL.createObjectURL(blob);
// 创建并触发下载
chrome.downloads.download({
url: url,
filename: 'config.yaml',
saveAs: true
}, function(downloadId) {
if (chrome.runtime.lastError) {
console.error('下载 config.yaml 失败:', chrome.runtime.lastError);
} else {
console.log('config.yaml 已准备下载,ID:', downloadId);
}
// 释放 URL 对象
URL.revokeObjectURL(url);
});
}