forked from Troywww/Subhub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
singbox.js
696 lines (623 loc) · 22.6 KB
/
singbox.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
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
import Parser from './parser.js';
// 在文件顶部添加规则类型定义
const RULE_TYPES = {
CLASH_MODE: 'clash_mode',
GEOIP: 'geoip',
FINAL: 'final',
PROTOCOL: 'protocol'
};
// 在文件顶部添加常量配置
const URL_TEST_CONFIG = {
TEST_URL: 'http://www.gstatic.com/generate_204',
BACKUP_TEST_URL: 'https://cp.cloudflare.com/generate_204',
INTERVAL: '300s',
TOLERANCE: 50,
};
// 基础配置
const BASE_CONFIG = {
dns: {
servers: [
{
tag: "dns_proxy",
address: "https://1.1.1.1/dns-query",
detour: "proxy"
},
{
tag: "dns_direct",
address: "https://223.5.5.5/dns-query",
detour: "direct"
},
{
tag: "dns_block",
address: "rcode://success"
},
{
tag: "dns_fakeip",
address: "fakeip"
}
],
rules: [
{
geosite: ["category-ads-all"],
server: "dns_block",
disable_cache: true
},
{
geosite: ["geolocation-!cn"],
query_type: ["A", "AAAA"],
server: "dns_fakeip"
},
{
geosite: ["geolocation-!cn"],
server: "dns_proxy"
}
],
final: "dns_direct",
independent_cache: true,
fakeip: {
enabled: true,
inet4_range: "198.18.0.0/15"
}
},
ntp: {
enabled: true,
server: "time.apple.com",
server_port: 123,
interval: "30m",
detour: "direct"
},
inbounds: [
{
type: "mixed",
tag: "mixed-in",
listen: "0.0.0.0",
listen_port: 2080
},
{
type: "tun",
tag: "tun-in",
inet4_address: "172.19.0.1/30",
auto_route: true,
strict_route: true,
stack: "system",
sniff: true
}
]
};
// 设置默认模板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 handleSingboxRequest(request, env) {
try {
const url = new URL(request.url);
const directUrl = url.searchParams.get('url');
const templateUrl = url.searchParams.get('template') || getTemplateUrl(env);
// 检测用户平台
const userAgent = request.headers.get('User-Agent') || '';
const isApplePlatform = userAgent.includes('iPhone') ||
userAgent.includes('iPad') ||
userAgent.includes('Macintosh') ||
userAgent.includes('SFI/');
// 检查必需的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);
// 检查是否是内部模板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();
}
// 生成完整的 Singbox 配置
const config = await generateSingboxConfig(templateContent, nodes, isApplePlatform);
return new Response(JSON.stringify(config, null, 2), {
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
console.error('Singbox convert error:', error);
return new Response('Internal Server Error: ' + error.message, { status: 500 });
}
}
// 修改 generateSingboxConfig 函数以支持苹果平台参数
async function generateSingboxConfig(templateContent, proxies, isApplePlatform) {
// 首先将节点转换为 Singbox 格式
const singboxNodes = proxies.map(node => ({
...convertNodeToSingbox(node),
tag: node.name // 确保保留原始名称作为tag
}));
// 解析分组规则
const groups = parseGroups(templateContent);
// 创建分组映射
const groupOutbounds = {};
// 使用基础配置模板
const config = {
...BASE_CONFIG, // 展开基础配置
outbounds: [
...singboxNodes, // 直接使用转换好的节点
...Object.entries(groups).map(([name, group]) => {
const outboundsList = [];
// 处理分组选项
group.patterns.forEach(option => {
if (option.startsWith('[]')) {
const groupRef = option.slice(2);
if (groupRef !== name) {
outboundsList.push(groupRef);
}
} else if (option === 'DIRECT') {
outboundsList.push('direct');
} else if (option === 'REJECT') {
outboundsList.push('block');
} else if (!option.includes('http')) {
const matchedNodes = matchProxies(singboxNodes, option);
outboundsList.push(...matchedNodes.map(p => p.tag));
}
});
return generateGroupOutbound(name, group, outboundsList);
}),
{
type: 'direct',
tag: 'direct'
},
{
type: 'block',
tag: 'block'
},
{
type: 'dns',
tag: 'dns-out'
}
],
route: {},
experimental: {},
};
const { rules, finalOutbound } = await generateRules(templateContent, groupOutbounds, isApplePlatform);
config.route = {
rules: rules,
auto_detect_interface: true,
final: finalOutbound
};
config.experimental = {};
return config;
}
// 解析分组规则
function parseGroups(template) {
const groups = {};
const lines = template.split('\n');
for (const line of lines) {
if (line.startsWith('custom_proxy_group=')) {
const [name, ...parts] = line.slice('custom_proxy_group='.length).split('`');
const type = parts[0];
const patterns = parts.slice(1).filter(p => p && !p.includes('http'));
groups[name] = {
type,
patterns,
filter: patterns.map(pattern => {
if (pattern === 'DIRECT') return null;
if (pattern.startsWith('^') && pattern.endsWith('$')) {
return new RegExp(pattern);
}
if (pattern.startsWith('(') && pattern.endsWith(')')) {
return new RegExp(pattern.slice(1, -1));
}
return pattern;
}).filter(Boolean)
};
}
}
return groups;
}
// 对代理进行分组
function groupProxies(proxies, groups) {
if (!proxies || !Array.isArray(proxies)) {
return {};
}
if (!groups || typeof groups !== 'object') {
return {};
}
const result = {};
for (const [name, group] of Object.entries(groups)) {
if (!group || !Array.isArray(group.filter)) {
result[name] = [];
continue;
}
result[name] = proxies.filter(proxy => {
if (!proxy || typeof proxy.tag !== 'string') {
return false;
}
return group.filter.some(pattern => {
if (!pattern) {
return false;
}
if (pattern instanceof RegExp) {
return pattern.test(proxy.tag);
}
if (typeof pattern === 'string') {
return proxy.tag.includes(pattern);
}
return false;
});
});
}
return result;
}
// 匹配代理节点
function matchProxies(proxies, pattern) {
// 安全检查
if (!proxies || !pattern || pattern === 'DIRECT' || pattern.startsWith('[]')) {
return [];
}
// 确保 proxies 是数组
if (!Array.isArray(proxies)) {
return [];
}
// 过滤掉无效的代理节点
const validProxies = proxies.filter(proxy => proxy && proxy.tag);
// 处理否定查找模式 (?!...)
if (pattern.includes('(?!')) {
const [excludePattern, includePattern] = pattern.split(')).*$');
const exclude = excludePattern.substring(excludePattern.indexOf('.*(') + 3).split('|');
const include = includePattern ? includePattern.slice(1).split('|') : [];
const result = validProxies.filter(proxy => {
const isExcluded = exclude.some(keyword => {
if (!keyword) return false;
return proxy.tag.indexOf(keyword) !== -1;
});
if (isExcluded) return false;
return include.length === 0 || include.some(keyword => {
if (!keyword) return false;
return proxy.tag.indexOf(keyword) !== -1;
});
});
return result;
}
// 处理普通正则表达式模式
else if (pattern.startsWith('(') && pattern.endsWith(')')) {
const keywords = pattern.slice(1, -1).split('|');
const result = validProxies.filter(proxy =>
keywords.some(keyword => proxy.tag.indexOf(keyword) !== -1)
);
return result;
}
// 处理完整正则表达式
else if (pattern.startsWith('^') || pattern.endsWith('$')) {
try {
const regex = new RegExp(pattern, 'i');
const result = validProxies.filter(proxy => regex.test(proxy.tag));
return result;
} catch (e) {
console.log('Regex error:', e.message);
return [];
}
}
// 普通字符串匹配
else {
const result = validProxies.filter(proxy => proxy.tag.indexOf(pattern) !== -1);
return result;
}
}
// 修改 generateGroupOutbound
function generateGroupOutbound(name, group, outbounds) {
// 如果 outbounds 为空,添加 direct
if (outbounds.length === 0) {
outbounds.push('direct');
}
// 转换所有出站引用为小写
const normalizedOutbounds = outbounds.map(out => {
if (out === 'DIRECT') return 'direct';
if (out === 'REJECT') return 'block';
return out;
});
const groupConfig = {
type: group.type === 'url-test' ? 'urltest' : 'selector',
tag: name,
outbounds: normalizedOutbounds
};
// 如果是 url-test 类型,添优化的测试配置
if (group.type === 'url-test') {
Object.assign(groupConfig, {
url: URL_TEST_CONFIG.TEST_URL,
interval: URL_TEST_CONFIG.INTERVAL,
tolerance: URL_TEST_CONFIG.TOLERANCE,
idle_timeout: URL_TEST_CONFIG.IDLE_TIMEOUT,
interrupt_exist_connections: true
});
}
return groupConfig;
}
// 修改节点转换函数
function convertNodeToSingbox(node) {
const tag = node.name || `${node.type}-${node.server}:${node.port}`;
switch (node.type) {
case 'vmess':
return {
type: 'vmess',
tag,
server: node.server,
server_port: node.port,
uuid: node.settings.id,
security: 'auto',
alter_id: node.settings.aid || 0,
global_padding: false,
authenticated_length: true,
multiplex: {
enabled: false,
protocol: 'smux',
max_streams: 32
},
tls: {
enabled: !!node.settings.tls,
server_name: node.settings.sni || node.settings.host || node.server,
insecure: true,
alpn: node.settings.alpn ? node.settings.alpn.split(',') : undefined
},
transport: node.settings.net ? {
type: node.settings.net,
path: node.settings.path || '/',
headers: node.settings.host ? { Host: node.settings.host } : undefined
} : undefined
};
case 'vless':
const tlsEnabled = node.settings.security === 'tls' || node.settings.tls === 'tls';
return {
type: 'vless',
tag,
server: node.server,
server_port: node.port,
uuid: node.settings.id,
flow: node.settings.flow || '',
tls: node.settings.security === 'reality' ? {
enabled: true,
server_name: node.settings.sni,
reality: {
enabled: true,
public_key: node.settings.pbk,
short_id: node.settings.sid || '',
},
utls: {
enabled: true,
fingerprint: node.settings.fp || 'chrome'
}
} : tlsEnabled ? {
enabled: true,
server_name: node.settings.sni || node.settings.host || node.server,
insecure: false,
utls: {
enabled: true,
fingerprint: node.settings.fp || 'random'
}
} : undefined,
transport: node.settings.type !== 'tcp' ? {
type: node.settings.type || node.settings.net,
path: node.settings.path || '/',
headers: node.settings.host ? { Host: node.settings.host } : undefined
} : undefined
};
case 'trojan':
return {
tag: node.name,
type: 'trojan',
server: node.server,
server_port: node.port,
password: node.settings.password,
transport: {
type: node.settings.type || 'tcp',
path: node.settings.path,
headers: node.settings.host ? { Host: node.settings.host } : undefined
},
tls: {
enabled: true,
server_name: node.settings.sni,
insecure: true
}
};
case 'ss':
return {
tag: node.name,
type: 'shadowsocks',
server: node.server,
server_port: node.port,
method: node.settings.method,
password: node.settings.password
};
case 'ssr':
return {
tag: node.name,
type: 'shadowsocksr',
server: node.server,
server_port: node.port,
method: 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
};
case 'hysteria':
return {
tag: node.name,
type: 'hysteria',
server: node.server,
server_port: node.port,
auth_str: node.settings.auth,
up_mbps: parseInt(node.settings.up),
down_mbps: parseInt(node.settings.down),
tls: {
enabled: true,
server_name: node.settings.sni,
insecure: true,
alpn: node.settings.alpn ? [node.settings.alpn] : undefined
},
obfs: node.settings.obfs
};
case 'hysteria2':
return {
tag: node.name,
type: 'hysteria2',
server: node.server,
server_port: node.port,
password: node.settings.auth,
tls: {
enabled: true,
server_name: node.settings.sni,
insecure: true
},
obfs: {
type: node.settings.obfs,
password: node.settings.obfsParam
}
};
case 'tuic':
return {
type: 'tuic',
tag,
server: node.server,
server_port: node.port,
uuid: node.settings.uuid,
password: node.settings.password,
congestion_control: node.settings.congestion_control || 'bbr',
udp_relay_mode: node.settings.udp_relay_mode || 'native',
zero_rtt_handshake: node.settings.reduce_rtt || false,
tls: {
enabled: true,
server_name: node.settings.sni || node.server,
alpn: node.settings.alpn || ['h3'],
disable_sni: node.settings.disable_sni || false
}
};
default:
return null;
}
}
// 修改 generateRules 函数
async function generateRules(template, groupOutbounds, isApplePlatform) {
// 首先检查参数
if (!template) {
return { rules: [], finalOutbound: 'direct' };
}
const rules = [
{
[RULE_TYPES.CLASH_MODE]: "Global",
outbound: "🚀 节点选择"
},
{
[RULE_TYPES.CLASH_MODE]: "Direct",
outbound: "direct"
},
{
[RULE_TYPES.PROTOCOL]: "dns",
outbound: "dns-out"
}
];
let finalOutbound = 'direct';
// 确保模板内容是字符串并且包含规则
const ruleLines = template.split('\n')
.filter(line => line && typeof line === 'string' && line.startsWith('ruleset='))
.map(line => line.trim());
for (const line of ruleLines) {
// 确保规则行格式正确
if (!line.includes(',')) {
continue;
}
const [group, ...urlParts] = line.slice('ruleset='.length).split(',');
const url = urlParts.join(',');
// 确保 group 存在
if (!group) {
continue;
}
const outbound = group === 'DIRECT' ? 'direct' :
group === 'REJECT' ? 'block' :
group;
if (url.startsWith('[]')) {
const ruleContent = url.slice(2);
if (!ruleContent) {
continue;
}
if (ruleContent.startsWith('GEOIP,')) {
const [, geoipValue] = ruleContent.split(',');
if (geoipValue) {
rules.push({
geoip: [geoipValue.toLowerCase()],
outbound: outbound
});
}
} else if (ruleContent === 'MATCH' || ruleContent === 'FINAL') {
finalOutbound = outbound;
}
} else {
try {
const rulesByType = {
domain: new Set(),
domain_suffix: new Set(),
domain_keyword: new Set(),
ip_cidr: new Set(),
...(isApplePlatform ? {} : { process_name: new Set() })
};
const response = await fetch(url);
if (!response.ok) {
continue;
}
const ruleContent = await response.text();
ruleContent.split('\n')
.map(rule => rule && rule.trim())
.filter(rule => rule && !rule.startsWith('#'))
.forEach(rule => {
const [type, ...valueParts] = rule.split(',');
const value = valueParts.join(',');
if (!type || !value) {
return;
}
switch (type) {
case 'DOMAIN-SUFFIX':
rulesByType.domain_suffix.add(value);
break;
case 'DOMAIN':
rulesByType.domain.add(value);
break;
case 'DOMAIN-KEYWORD':
rulesByType.domain_keyword.add(value);
break;
case 'IP-CIDR':
case 'IP-CIDR6':
rulesByType.ip_cidr.add(value.split(',')[0]);
break;
case 'PROCESS-NAME':
if (!isApplePlatform && rulesByType.process_name) {
rulesByType.process_name.add(value);
}
break;
}
});
for (const [type, values] of Object.entries(rulesByType)) {
if (values.size > 0) {
rules.push({
[type]: Array.from(values),
outbound
});
}
}
} catch (error) {
console.error(`Error processing rule list ${url}:`, error);
}
}
}
return { rules, finalOutbound };
}