forked from Troywww/Subhub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clash.js
508 lines (452 loc) · 16.5 KB
/
clash.js
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
import Parser from './parser.js';
// 定义节点协议列表
const NODE_PROTOCOLS = ['vless:', 'vmess:', 'trojan:', 'ss:', 'ssr:', 'hysteria:', 'tuic:', 'hy2:', 'hysteria2:'];
// 基础配置
const BASE_CONFIG = `port: 7890
socks-port: 7891
allow-lan: true
mode: rule
log-level: info
external-controller: :9090
dns:
enable: true
enhanced-mode: fake-ip
fake-ip-range: 198.18.0.1/16
nameserver:
- 223.5.5.5
- 119.29.29.29
fallback:
- 8.8.8.8
- 8.8.4.4
default-nameserver:
- 223.5.5.5
- 119.29.29.29
fake-ip-filter:
- '*.lan'
- localhost.ptlogin2.qq.com
- '+.srv.nintendo.net'
- '+.stun.playstation.net'
- '+.msftconnecttest.com'
- '+.msftncsi.com'
- '+.xboxlive.com'
- 'msftconnecttest.com'
- 'xbox.*.microsoft.com'
- '*.battlenet.com.cn'
- '*.battlenet.com'
- '*.blzstatic.cn'
- '*.battle.net'
`;
// 设置默认模板URL和环境变量处理
const getTemplateUrl = (env) => {
return env?.DEFAULT_TEMPLATE_URL || 'https://raw.githubusercontent.com/Troywww/singbox_conf/refs/heads/main/singbox_clash_conf.txt';
};
export async function handleClashRequest(request, env) {
try {
const url = new URL(request.url);
const directUrl = url.searchParams.get('url');
const templateUrl = url.searchParams.get('template') || getTemplateUrl(env);
console.log('Fetching template from:', templateUrl);
// 检查必需的URL参数
let nodes = [];
if (directUrl) {
nodes = await Parser.parse(directUrl, env);
} else {
return new Response('Missing required parameters', { status: 400 });
}
if (!nodes || nodes.length === 0) {
return new Response('No valid nodes found', { status: 400 });
}
// 获取模板配置
const templateResponse = await fetch(templateUrl);
console.log('Template response:', {
status: templateResponse.status,
contentType: templateResponse.headers.get('content-type'),
url: templateUrl
});
// 检查是否是内部模板URL
let templateContent;
if (templateUrl.startsWith('https://inner.template.secret/id-')) {
const templateId = templateUrl.replace('https://inner.template.secret/id-', '');
const templateData = await env.TEMPLATE_CONFIG.get(templateId);
if (!templateData) {
return new Response('Template not found', { status: 404 });
}
const templateInfo = JSON.parse(templateData);
templateContent = templateInfo.content;
} else {
if (!templateResponse.ok) {
return new Response('Failed to fetch template', { status: 500 });
}
templateContent = await templateResponse.text();
}
// 生成完整的 Clash 配置
const config = await generateClashConfig(templateContent, nodes);
return new Response(config, {
headers: {
'Content-Type': 'text/yaml',
'Content-Disposition': 'attachment; filename=config.yaml'
}
});
} catch (error) {
console.error('Clash convert error:', error);
return new Response('Internal Server Error: ' + error.message, { status: 500 });
}
}
async function generateClashConfig(templateContent, nodes) {
let config = BASE_CONFIG + '\n';
// 添加代理节点
config += 'proxies:\n';
const proxies = nodes.map(node => {
const converted = convertNodeToClash(node);
return converted;
}).filter(Boolean);
proxies.forEach(proxy => {
config += ' -';
function writeValue(obj, indent = 4) {
Object.entries(obj).forEach(([key, value]) => {
if (value === undefined || value === null) {
return;
}
const spaces = ' '.repeat(indent);
if (typeof value === 'object') {
config += `\n${spaces}${key}:`;
writeValue(value, indent + 2);
} else {
const formattedValue = typeof value === 'boolean' || typeof value === 'number'
? value
: `"${value}"`;
config += `\n${spaces}${key}: ${formattedValue}`;
}
});
}
writeValue(proxy);
config += '\n';
});
// 处理分组
config += '\nproxy-groups:\n';
const groupLines = templateContent.split('\n')
.filter(line => line.startsWith('custom_proxy_group='));
groupLines.forEach(line => {
const [groupName, ...rest] = line.slice('custom_proxy_group='.length).split('`');
const groupType = rest[0];
const options = rest.slice(1);
config += ` - name: "${groupName}"\n`;
config += ` type: ${groupType === 'url-test' ? 'url-test' : 'select'}\n`;
// 处理 url-test 类型的特殊配置
if (groupType === 'url-test') {
const testUrl = options.find(opt => opt.startsWith('http')) || 'http://www.gstatic.com/generate_204';
const interval = 300;
const tolerance = groupName.includes('欧美') ? 150 : 50;
config += ` url: ${testUrl}\n`;
config += ` interval: ${interval}\n`;
config += ` tolerance: ${tolerance}\n`;
}
config += ' proxies:\n';
let hasProxies = false;
// 处理分组选项
options.forEach(option => {
if (option.startsWith('[]')) {
hasProxies = true;
const groupRef = option.slice(2);
config += ` - ${groupRef}\n`;
} else if (option === 'DIRECT' || option === 'REJECT') {
hasProxies = true;
config += ` - ${option}\n`;
} else if (!option.startsWith('http')) {
try {
let matchedCount = 0;
// 处理正则表达式过滤
let pattern = option;
// 处理否定查找
if (pattern.includes('(?!')) {
const [excludePattern, includePattern] = pattern.split(')).*$');
const exclude = excludePattern.substring(excludePattern.indexOf('.*(') + 3).split('|');
const include = includePattern ? includePattern.slice(1).split('|') : [];
// 添加调试日志
console.log('Pattern processing:', {
original: pattern,
exclude,
include,
includePattern
});
const matchedProxies = proxies.filter(proxy => {
const isExcluded = exclude.some(keyword =>
proxy.name.includes(keyword)
);
if (isExcluded) return false;
// 如果没有包含模式,则返回所有未被排除的节点
if (!includePattern || include.length === 0) {
return true;
}
// 如果有包含模式,则需要匹配包含模式
return include.some(keyword =>
proxy.name.includes(keyword)
);
});
matchedProxies.forEach(proxy => {
hasProxies = true;
matchedCount++;
config += ` - ${proxy.name}\n`;
});
} else {
const filter = new RegExp(pattern);
const matchedProxies = proxies.filter(proxy =>
filter.test(proxy.name)
);
matchedProxies.forEach(proxy => {
hasProxies = true;
matchedCount++;
config += ` - ${proxy.name}\n`;
});
}
} catch (error) {
console.error('Error processing proxy group option:', error);
}
}
});
// 如果分组没有任何节点,添加 DIRECT
if (!hasProxies) {
config += ' - "DIRECT"\n';
}
});
// 处理规则
config += '\nrules:\n';
const ruleLines = templateContent.split('\n')
.filter(line => line.startsWith('ruleset='))
.map(line => line.trim());
// 获取并解析所有规则列表
for (const line of ruleLines) {
const groupEndIndex = line.indexOf(',');
const group = line.substring('ruleset='.length, groupEndIndex);
const url = line.substring(groupEndIndex + 1);
if (url.startsWith('[]')) {
// 处理内置规则
const ruleContent = url.slice(2);
if (ruleContent === 'MATCH' || ruleContent === 'FINAL') {
config += ` - MATCH,${group}\n`;
} else if (ruleContent.startsWith('GEOIP,')) {
config += ` - ${ruleContent},${group}\n`;
} else {
config += ` - ${ruleContent},${group}\n`;
}
} else {
try {
// 获取规则列表内容
const response = await fetch(url);
if (!response.ok) {
console.error(`Failed to fetch rules from ${url}: ${response.status}`);
continue;
}
const ruleContent = await response.text();
const rules = ruleContent.split('\n')
.map(rule => rule.trim())
.filter(rule => rule && !rule.startsWith('#'));
// 添加解析后的规则
rules.forEach(rule => {
if (rule.includes(',')) {
const parts = rule.split(',');
const ruleType = parts[0];
const ruleValue = parts[1];
// 跳过 USER-AGENT 和 URL-REGEX 规则
if (ruleType === 'USER-AGENT' || ruleType === 'URL-REGEX') {
return;
}
// 处理规则
if (ruleType === 'IP-CIDR' || ruleType === 'IP-CIDR6') {
config += ` - ${ruleType},${ruleValue},${group},no-resolve\n`;
} else if (ruleType === 'FINAL') {
config += ` - MATCH,${group}\n`;
} else {
config += ` - ${ruleType},${ruleValue},${group}\n`;
}
}
});
} catch (error) {
console.error(`Error processing rule list ${url}:`, error);
}
}
}
return config;
}
function convertNodeToClash(node) {
switch (node.type) {
case 'vmess':
return convertVmess(node);
case 'vless':
return convertVless(node);
case 'trojan':
return convertTrojan(node);
case 'ss':
return convertShadowsocks(node);
case 'ssr':
return convertShadowsocksR(node);
case 'hysteria':
return convertHysteria(node);
case 'hysteria2':
return convertHysteria2(node);
case 'tuic':
return convertTuic(node);
default:
return null;
}
}
function convertVmess(node) {
// 基础配置
const config = {
name: node.name,
type: 'vmess',
server: node.server,
port: node.port,
uuid: node.settings.id,
alterId: node.settings.aid || 0,
cipher: 'auto',
udp: true
};
// 网络设置
if (node.settings.net) {
config.network = node.settings.net;
// ws 配置
if (node.settings.net === 'ws') {
config['ws-opts'] = {
path: node.settings.path || '/',
headers: {
Host: node.settings.host || ''
}
};
}
}
// TLS 设置
if (node.settings.tls === 'tls') {
config.tls = true;
if (node.settings.sni) {
config.servername = node.settings.sni;
}
}
return config;
}
function convertVless(node) {
const config = {
name: node.name,
type: 'vless',
server: node.server,
port: node.port,
uuid: node.settings.id,
network: node.settings.type || node.settings.net || 'tcp',
'skip-cert-verify': false,
tls: true
};
// 基本配置
if (node.settings.flow) {
config.flow = node.settings.flow;
}
if (node.settings.sni || node.settings.host) {
config.servername = node.settings.sni || node.settings.host;
}
// Reality 配置
if (node.settings.security === 'reality') {
config.flow = 'xtls-rprx-vision';
config['reality-opts'] = {
'public-key': node.settings.pbk
};
config['client-fingerprint'] = node.settings.fp || 'chrome';
}
// WebSocket 配置
if (node.settings.type === 'ws' || node.settings.net === 'ws') {
config['ws-opts'] = {
path: node.settings.path || '/',
headers: {
Host: node.settings.host || node.settings.sni || node.server
}
};
}
return config;
}
function convertTrojan(node) {
return {
name: node.name,
type: 'trojan',
server: node.server,
port: node.port,
password: node.settings.password,
udp: true,
'skip-cert-verify': true,
network: node.settings.type || 'tcp',
'ws-opts': node.settings.type === 'ws' ? {
path: node.settings.path,
headers: { Host: node.settings.host }
} : undefined,
sni: node.settings.sni || undefined,
alpn: node.settings.alpn ? [node.settings.alpn] : undefined
};
}
function convertShadowsocks(node) {
return {
name: node.name,
type: 'ss',
server: node.server,
port: node.port,
cipher: node.settings.method,
password: node.settings.password,
udp: true
};
}
function convertShadowsocksR(node) {
return {
name: node.name,
type: 'ssr',
server: node.server,
port: node.port,
cipher: node.settings.method,
password: node.settings.password,
protocol: node.settings.protocol,
'protocol-param': node.settings.protocolParam,
obfs: node.settings.obfs,
'obfs-param': node.settings.obfsParam,
udp: true
};
}
function convertHysteria(node) {
return {
name: node.name,
type: 'hysteria',
server: node.server,
port: node.port,
auth_str: node.settings.auth,
up: node.settings.up,
down: node.settings.down,
'skip-cert-verify': true,
sni: node.settings.sni,
alpn: node.settings.alpn ? [node.settings.alpn] : undefined,
obfs: node.settings.obfs
};
}
function convertHysteria2(node) {
return {
name: node.name,
type: 'hysteria2',
server: node.server,
port: node.port,
password: node.settings.auth,
'skip-cert-verify': true,
sni: node.settings.sni,
obfs: node.settings.obfs,
'obfs-password': node.settings.obfsParam
};
}
// 添加新的转换函数
function convertTuic(node) {
return {
name: node.name,
type: 'tuic',
server: node.server,
port: node.port,
uuid: node.settings.uuid,
password: node.settings.password,
'congestion-controller': node.settings.congestion_control || 'bbr',
'udp-relay-mode': node.settings.udp_relay_mode || 'native',
'reduce-rtt': node.settings.reduce_rtt || false,
'skip-cert-verify': true,
sni: node.settings.sni || undefined,
alpn: node.settings.alpn ? [node.settings.alpn] : undefined
};
}