Repository navigation
Expand file tree
/
Copy pathScript.js
More file actions
1302 lines (1125 loc) · 41.2 KB
/
Copy pathScript.js
File metadata and controls
1302 lines (1125 loc) · 41.2 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
/**
* mihomo配置覆写脚本(精简版)
* 作者:AIsouler
* 源仓库:https://github.com/AIsouler/MyClash
* 脚本链接:https://raw.githubusercontent.com/AIsouler/MyClash/main/Script/Script.js
* 友情推荐,非常好用、省电且内存占用低的代理软件:https://github.com/appshubcc/Bettbox
*/
// --- 静态配置区域 ---
// 适配 Bettbox 自定义配置参数
const Compatible_With_Bettbox = { ruleOptionsEnable: true };
/**
* 自定义配置选项
* true = 启用
* false = 禁用
*/
const ruleOptionsEnable = {
// 基础策略组
手动选择: true, // 是否启用手动选择策略组
自动选择: true, // 是否启用自动选择策略组
// 以下为分流策略配置
Google: true, // Google服务
AI: true, // 国外AI服务
Telegram: true, // Telegram通讯软件
Steam: true, // Steam游戏平台
AdBlock: true, // 广告拦截
// 以下为非分流策略配置
极简模式: false, // 是否启用极简模式
生成地区自动选择组: true, // 是否生成地区自动选择策略组
隐藏地区手动选择组: false, // 是否隐藏地区手动选择策略组
生成倍率组: true, // 是否生成低倍率/高倍率策略组
分流组添加所有节点: false, // 是否为分流策略组添加所有节点
过滤低倍率节点: false, // 是否过滤低倍率节点
过滤高倍率节点: false, // 是否过滤高倍率节点
过滤非地区节点: true, // 是否过滤非地区节点
屏蔽国外QUIC: true, // 是否屏蔽国外QUIC流量
代理IPV4优先: false, // 是否将订阅节点统一为 IPv4 优先(与“代理IPV6优先”同时开启时不生效)
代理IPV6优先: false, // 是否将订阅节点统一为 IPv6 优先(与“代理IPV4优先”同时开启时不生效)
链式代理: false, // 是否启用链式代理(自定义节点作为落地节点,经“链式中转”策略组中转)
};
// 定义前置规则
const prefixRules = [
// 私有网络直连
'RULE-SET,private,直连',
// 国内直连
'RULE-SET,geolocation-cn,直连',
'RULE-SET,games_cn,直连', // 已包含 steam 下载域名
'RULE-SET,epicgames,直连',
'RULE-SET,apple_cn,直连',
'RULE-SET,microsoft_cn,直连',
'DOMAIN,fsend.cn,直连',
'DOMAIN,international-gfe.download.nvidia.com,直连',
];
// 此处添加自定义节点,填入下方[]内(可选,留空则不生成“自建节点”策略组)
// 自定义节点不参与节点过滤与 hosts 改写;与订阅节点(标准化后)重名时自动添加“自建-”前缀
// 示例:
// const customizeProxies = [
// {
// name: '自建-日本-01',
// type: 'vmess',
// server: '5.6.7.8',
// port: 443,
// uuid: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx',
// alterId: 0,
// cipher: 'auto',
// tls: true,
// servername: 'example.com',
// network: 'ws',
// 'ws-opts': {
// path: '/path',
// headers: { Host: 'example.com' },
// },
// },
// ];
const customizeProxies = [];
// 链式代理启用时,自定义节点的 dialer-proxy 引用目标
const dialerProxyName = '链式中转';
// 定义全局排除节点的正则表达式,用于排除非地区节点
const excludeFilter =
/群|返利|循环|官网|客服|网站|网址|获取|订阅|流量|到期|机场|下次|版本|官址|备用|过期|已用|联系|邮箱|工单|贩卖|通知|倒卖|防止|国内|地址|频道|电报|无法|说明|使用|提示|访问|支持|教程|关注|更新|作者|加入|超时|收藏|优惠|福利|邀请|好友|失联|选择|剩余|公益|发布|DIZTNA|通路|登录|禁止|定时|渠道|牢记|永久|余额|阁下|本站|刷新|导航|建议|重置|以下|过滤|⚠️|@|t\.me\/\+|\bexpire\b|\bhttps?:\/\/|\.com|\btraffic\b/iu;
// 屏蔽国外QUIC
const blockForeignQuic = [
'AND,((NETWORK,UDP),(DST-PORT,443),(NOT,((OR,((RULE-SET,cn_additional),(RULE-SET,cn_ip,no-resolve)))))),REJECT',
];
// 直连节点
const directProxies = [
{
name: '🇨🇳 直连 | 双栈',
type: 'direct',
},
{
name: '🇨🇳 直连 | IPv4优先',
type: 'direct',
'ip-version': 'ipv4-prefer',
},
{
name: '🇨🇳 直连 | IPv6优先',
type: 'direct',
'ip-version': 'ipv6-prefer',
},
{
name: '🇨🇳 直连 | 仅IPv4',
type: 'direct',
'ip-version': 'ipv4',
},
{
name: '🇨🇳 直连 | 仅IPv6',
type: 'direct',
'ip-version': 'ipv6',
},
];
// 定义地区策略组
const regionDefinitions = [
{
name: '香港',
flag: '🇭🇰',
regex: /🇭🇰|香港|(?<![A-Za-z])HKG?(?![A-Za-z])|hong\s*kong/i,
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/HongKong.svg',
},
{
name: '日本',
flag: '🇯🇵',
regex: /🇯🇵|日本|东京|大阪|京都|(?<![A-Za-z])JPN?(?![A-Za-z])|japan/i,
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Japan.svg',
},
{
name: '美国',
flag: '🇺🇸',
regex:
/🇺🇸|美国|纽约|洛杉矶|旧金山|芝加哥|休斯顿|迈阿密|西雅图|波士顿|华盛顿|圣何塞|圣地亚哥|(?<![A-Za-z])USA?(?![A-Za-z])|america|united\s*states/i,
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/America.svg',
},
{
name: '新加坡',
flag: '🇸🇬',
regex: /🇸🇬|新加坡|狮城|(?<![A-Za-z])SGP?(?![A-Za-z])|singapore/i,
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Singapore.svg',
},
];
// 定义倍率策略组
const lowRateRegionName = '低倍率节点';
const highRateRegionName = '高倍率节点';
const rateRegionDefinitions = [
{
name: lowRateRegionName,
regex:
/^(?!.*(?:剩|期)).*(?:(?<!\d)0\.[0-5]|(?<=[ \[\(||丨∣┃\-‐–—−-﹣])0[*×✕✖⨯⨉x倍])|(?:(?<=[ \[\(||丨∣┃\-‐–—−-﹣])[*×✕✖⨯⨉x]0(?=[ \)\]]|倍|$))|^(?!.*(?:客户端|软件)).*下载|低倍|免费|(?<![A-Za-z])free(?![A-Za-z])/i,
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Available.svg',
},
{
name: highRateRegionName,
regex:
/(?<=[ \[\(||丨∣┃\-‐–—−-﹣])((?:[*×✕✖⨯⨉x]\s*(?:[2-9]\d*|[1-9]\d+)(?:\.\d+)?)|(?:(?<![\d.])(?:[2-9]\d*|[1-9]\d+)(?:\.\d+)?\s*(?:倍|[*×✕✖⨯⨉x])))/i,
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Airport.svg',
},
];
// 全部策略组定义(地区 + 倍率),统一用于节点匹配与归类
const allRegionDefinitions = [...regionDefinitions, ...rateRegionDefinitions];
// Rule Providers 通用配置
const ruleProviderCommonDomain = {
type: 'http',
format: 'mrs',
interval: 86400,
behavior: 'domain',
};
const ruleProviderCommonIpcidr = {
type: 'http',
format: 'mrs',
interval: 86400,
behavior: 'ipcidr',
};
// 定义基础 Rule Providers
const baseRuleProviders = {
// --- 直连规则集 ---
private: {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geosite/private.mrs',
path: './ruleset/private.mrs',
'path-in-bundle': 'geo/geosite/private.mrs',
},
private_ip: {
...ruleProviderCommonIpcidr,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geoip/private.mrs',
path: './ruleset/private_ip.mrs',
'path-in-bundle': 'geo/geoip/private.mrs',
},
games_cn: {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geosite/category-games@cn.mrs',
path: './ruleset/category-games@cn.mrs',
'path-in-bundle': 'geo/geosite/category-games@cn.mrs',
},
epicgames: {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geosite/epicgames.mrs',
path: './ruleset/epicgames.mrs',
'path-in-bundle': 'geo/geosite/epicgames.mrs',
},
apple_cn: {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geosite/apple@cn.mrs',
path: './ruleset/apple@cn.mrs',
'path-in-bundle': 'geo/geosite/apple@cn.mrs',
},
microsoft_cn: {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geosite/microsoft@cn.mrs',
path: './ruleset/microsoft@cn.mrs',
'path-in-bundle': 'geo/geosite/microsoft@cn.mrs',
},
'geolocation-cn': {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geosite/geolocation-cn.mrs',
path: './ruleset/geolocation-cn.mrs',
'path-in-bundle': 'geo/geosite/geolocation-cn.mrs',
},
cn_ip: {
...ruleProviderCommonIpcidr,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geoip/cn.mrs',
path: './ruleset/cn_ip.mrs',
'path-in-bundle': 'geo/geoip/cn.mrs',
},
// --- 代理规则集 ---
'geolocation-!cn': {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geosite/geolocation-!cn.mrs',
path: './ruleset/geolocation-!cn.mrs',
'path-in-bundle': 'geo/geosite/geolocation-!cn.mrs',
},
// --- 其他规则集 ---
fakeip_filter: {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geosite/fakeip-filter.mrs',
path: './ruleset/fakeip-filter.mrs',
'path-in-bundle': 'geo/geosite/fakeip-filter.mrs',
},
cn_additional: {
...ruleProviderCommonDomain,
url: 'https://static-file-global.353355.xyz/rules/cn-additional-list.mrs',
path: './ruleset/cn-additional-list.mrs',
'path-in-bundle': 'geo/geosite/cn.mrs',
},
cn: {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geosite/cn.mrs',
path: './ruleset/cn.mrs',
'path-in-bundle': 'geo/geosite/cn.mrs',
},
};
// 策略组公共配置
const groupBaseOption = {
interval: 600,
timeout: 3000,
url: 'https://www.apple.com/library/test/success.html',
lazy: true,
'max-failed-times': 3,
'empty-fallback': 'REJECT',
};
// select策略组通用配置
const selectBaseOption = {
...groupBaseOption,
type: 'select',
};
// url-test策略组通用配置
const urlTestBaseOption = {
...groupBaseOption,
type: 'url-test',
tolerance: 50,
'exclude-type': 'DIRECT',
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Auto.svg',
hidden: true,
};
// 定义基础策略组
const baseGroups = [
{
name: '手动选择',
baseOption: selectBaseOption,
includeAll: true,
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Static.svg',
},
{
name: '自动选择',
baseOption: urlTestBaseOption,
includeAll: true,
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Auto.svg',
},
];
// 定义分流策略组配置
const serviceConfigs = [
...baseGroups,
{
name: 'Google',
baseOption: selectBaseOption,
providers: {
google: {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geosite/google.mrs',
path: './ruleset/google.mrs',
'path-in-bundle': 'geo/geosite/google.mrs',
},
google_ip: {
...ruleProviderCommonIpcidr,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geoip/google.mrs',
path: './ruleset/google_ip.mrs',
'path-in-bundle': 'geo/geoip/google.mrs',
},
},
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Google.svg',
rules: ['RULE-SET,google,Google', 'RULE-SET,google_ip,Google,no-resolve'],
},
{
name: 'AI',
baseOption: selectBaseOption,
defaultSelected: '美国',
providers: {
ai: {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geosite/category-ai-!cn.mrs',
path: './ruleset/ai.mrs',
'path-in-bundle': 'geo/geosite/category-ai-!cn.mrs',
},
},
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/ChatGPT.svg',
rules: ['RULE-SET,ai,AI'],
},
{
name: 'Telegram',
baseOption: selectBaseOption,
providers: {
telegram: {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geosite/telegram.mrs',
path: './ruleset/telegram.mrs',
'path-in-bundle': 'geo/geosite/telegram.mrs',
},
telegram_ip: {
...ruleProviderCommonIpcidr,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geoip/telegram.mrs',
path: './ruleset/telegram_ip.mrs',
'path-in-bundle': 'geo/geoip/telegram.mrs',
},
},
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Telegram.svg',
rules: ['RULE-SET,telegram,Telegram', 'RULE-SET,telegram_ip,Telegram,no-resolve'],
},
{
name: 'Steam',
baseOption: selectBaseOption,
direct: true,
providers: {
steam: {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geosite/steam.mrs',
path: './ruleset/steam.mrs',
'path-in-bundle': 'geo/geosite/steam.mrs',
},
steam_ip: {
...ruleProviderCommonIpcidr,
url: 'https://fastly.jsdelivr.net/gh/appshubcc/bett-rules@meta/geo/geoip/steam.mrs',
path: './ruleset/steam_ip.mrs',
'path-in-bundle': 'geo/geoip/steam.mrs',
},
},
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Steam.svg',
rules: ['RULE-SET,steam,Steam', 'RULE-SET,steam_ip,Steam,no-resolve'],
},
{
name: 'AdBlock',
baseOption: selectBaseOption,
reject: true,
providers: {
adblockmihomolite: {
...ruleProviderCommonDomain,
url: 'https://fastly.jsdelivr.net/gh/217heidai/adblockfilters@main/rules/adblockmihomolite.mrs',
path: './ruleset/adblockmihomolite.mrs',
'path-in-bundle': 'geo/geosite/category-ads-all.mrs',
},
},
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/AdBlock.svg',
rules: ['RULE-SET,adblockmihomolite,AdBlock'],
},
];
// ---节点过滤、重命名及验证---
/**
* 节点匹配缓存,避免重复执行正则
*/
const regionMatchCache = new Map();
function getMatchedRegions(proxyName) {
if (regionMatchCache.has(proxyName)) {
return regionMatchCache.get(proxyName);
}
const regions = allRegionDefinitions.filter((region) => region.regex.test(proxyName));
regionMatchCache.set(proxyName, regions);
return regions;
}
/**
* 标准化节点名称:补全地区国旗、折叠多余空格,并预缓存匹配结果
*/
const flagRegex = /[\u{1F1E6}-\u{1F1FF}]{2}/u;
function normalizeProxyName(proxy) {
const originalName = proxy.name;
const flag = originalName.match(flagRegex)?.[0];
const nameWithoutFlag = (flag ? originalName.replace(flag, '') : originalName).replace(/\s+/g, ' ').trim();
const matchedRegions = getMatchedRegions(originalName);
const regionFlag = flag || matchedRegions.find((region) => region.flag)?.flag;
const normalizedName = regionFlag ? `${regionFlag} ${nameWithoutFlag}` : nameWithoutFlag;
if (normalizedName !== originalName) {
regionMatchCache.set(normalizedName, matchedRegions);
}
return normalizedName === originalName ? proxy : { ...proxy, name: normalizedName };
}
/**
* 修复 dialer-proxy 引用:目标被重命名则更新,被移除或不存在则删除引用
*/
function fixDialerProxy(proxy, renameMap, normalizedProxyNames) {
const target = proxy['dialer-proxy'];
if (!target) return proxy;
if (renameMap.has(target)) {
return { ...proxy, 'dialer-proxy': renameMap.get(target) };
}
if (normalizedProxyNames.has(target)) {
return proxy;
}
const copy = { ...proxy };
delete copy['dialer-proxy'];
return copy;
}
/**
* 读取代理 IP 版本偏好:仅其中一个开关开启时返回对应偏好,
* 同时开启或同时关闭时返回 null(不应用任何偏好,节点保持原样)
*/
function getIpVersionPreference() {
const ipv4PreferEnabled = ruleOptionsEnable.代理IPV4优先;
const ipv6PreferEnabled = ruleOptionsEnable.代理IPV6优先;
if (ipv4PreferEnabled && !ipv6PreferEnabled) return 'ipv4-prefer';
if (ipv6PreferEnabled && !ipv4PreferEnabled) return 'ipv6-prefer';
return null;
}
/**
* 过滤并标准化节点:剔除内置/信息节点、按配置过滤、去重、修复 dialer-proxy 引用,空列表时抛错
*/
function filterAndNormalizeProxies(config) {
regionMatchCache.clear();
const filterLowRateProxiesEnabled = ruleOptionsEnable.过滤低倍率节点;
const filterHighRateProxiesEnabled = ruleOptionsEnable.过滤高倍率节点;
const filterNonRegionProxiesEnabled = ruleOptionsEnable.过滤非地区节点;
const lowRateRegex = filterLowRateProxiesEnabled
? rateRegionDefinitions.find((r) => r.name === lowRateRegionName)?.regex
: null;
const highRateRegex = filterHighRateProxiesEnabled
? rateRegionDefinitions.find((r) => r.name === highRateRegionName)?.regex
: null;
const originalProxies = config.proxies || [];
const filteredRawProxies = originalProxies.filter((proxy) => {
const type = String(proxy.type ?? '').toLowerCase();
if (type === 'direct' || type === 'reject' || type === 'rematch') return false;
if (lowRateRegex?.test(proxy.name) || highRateRegex?.test(proxy.name)) return false;
if (!filterNonRegionProxiesEnabled) return true;
const isRegionProxy = getMatchedRegions(proxy.name).some((region) => regionDefinitions.includes(region));
return isRegionProxy || !excludeFilter.test(proxy.name);
});
const renameMap = new Map();
const normalizedProxies = [];
const uniqueNames = new Set();
for (const rawProxy of filteredRawProxies) {
const normalized = normalizeProxyName(rawProxy);
if (normalized.name !== rawProxy.name) {
renameMap.set(rawProxy.name, normalized.name);
}
if (!uniqueNames.has(normalized.name)) {
uniqueNames.add(normalized.name);
normalizedProxies.push(normalized);
}
}
const normalizedProxyNames = new Set(normalizedProxies.map((p) => p.name));
const filteredProxies = normalizedProxies.map((proxy) => fixDialerProxy(proxy, renameMap, normalizedProxyNames));
if (!filteredProxies.length) {
throw new Error('配置文件中未找到任何代理节点,请使用机场提供的配置文件进行覆写');
}
const ipVersionPreference = getIpVersionPreference();
if (ipVersionPreference) {
return filteredProxies.map((proxy) =>
proxy['ip-version'] === ipVersionPreference ? proxy : { ...proxy, 'ip-version': ipVersionPreference },
);
}
return filteredProxies;
}
// ---构建地区组和倍率组---
/**
* 构建地区策略组,可附带自动选择组
*/
function createRegionGroup(name, icon, proxies) {
const generateRegionAutoSelectEnabled = ruleOptionsEnable.生成地区自动选择组;
const hideManualSelectGroupEnabled = ruleOptionsEnable.隐藏地区手动选择组;
if (generateRegionAutoSelectEnabled) {
const urlTestName = `${name}-自动选择`;
return [
{
...urlTestBaseOption,
name: urlTestName,
proxies,
},
{
...selectBaseOption,
name,
icon,
proxies: [...proxies, urlTestName],
hidden: hideManualSelectGroupEnabled,
},
];
}
return [
{
...selectBaseOption,
name,
icon,
proxies,
hidden: hideManualSelectGroupEnabled,
},
];
}
/**
* 将节点按地区/倍率归类,构建地区策略组、倍率策略组与“其他节点”组
*/
function buildRegionGroups(filteredProxies, customProxies) {
const generateRateGroupEnabled = ruleOptionsEnable.生成倍率组;
const regionGroups = Object.fromEntries(allRegionDefinitions.map(({ name }) => [name, []]));
const otherProxies = [];
for (const proxy of [...filteredProxies, ...customProxies]) {
const matchedRegions = getMatchedRegions(proxy.name);
const isRegionProxy = matchedRegions.some((region) => regionDefinitions.includes(region));
for (const region of matchedRegions) {
regionGroups[region.name].push(proxy.name);
}
if (!isRegionProxy) {
otherProxies.push(proxy.name);
}
}
const generatedRegionGroups = allRegionDefinitions
.filter((r) => regionGroups[r.name].length > 0 && (generateRateGroupEnabled || !rateRegionDefinitions.includes(r)))
.flatMap((r) => createRegionGroup(r.name, r.icon, regionGroups[r.name]));
if (otherProxies.length > 0) {
generatedRegionGroups.push(
...createRegionGroup(
'其他节点',
'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/WorldMap.svg',
otherProxies,
),
);
}
return generatedRegionGroups;
}
// ---构建自定义节点组---
/**
* 处理自定义节点:标准化名称、与订阅节点重名时添加“自建-”前缀、内部去重,
* 并构建“自建节点”策略组。
* 自定义节点不参与订阅节点过滤,也不参与 hosts 改写及 DNS 域名处理。
*/
function buildCustomizeGroups(filteredProxies, customizeList = customizeProxies) {
const chainEnabled = ruleOptionsEnable.链式代理;
if (!customizeList.length) {
if (chainEnabled) {
throw new Error('启用失败,请在脚本中添加自定义节点后尝试');
}
return { customProxies: [], customProxyNames: [], customGroup: null };
}
const usedNames = new Set(filteredProxies.map((p) => p.name));
const customPrefix = '自建-';
const customProxies = [];
for (const proxy of customizeList) {
const normalized = normalizeProxyName(proxy);
let name = normalized.name;
while (usedNames.has(name)) {
name = normalizeProxyName({ name: `${customPrefix}${name}` }).name.replace(`${customPrefix} `, customPrefix);
}
usedNames.add(name);
let customProxy = name === normalized.name ? normalized : { ...normalized, name };
if (chainEnabled && customProxy['dialer-proxy'] !== dialerProxyName) {
customProxy = { ...customProxy, 'dialer-proxy': dialerProxyName };
}
customProxies.push(customProxy);
}
const customProxyNames = customProxies.map((p) => p.name);
const customGroup = {
...selectBaseOption,
name: chainEnabled ? '链式落地' : '自建节点',
proxies: customProxyNames,
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Server.svg',
};
return {
customProxies,
customProxyNames,
customGroup,
};
}
// ---构建基础策略组和分流策略组---
/**
* 构建基础/分流策略组/部分节点组、GLOBAL 组与规则集,并汇总分流规则
*/
function buildFunctionalGroups(filteredProxies, generatedRegionGroups, customizeInfo) {
const minimalModeEnabled = ruleOptionsEnable.极简模式;
const blockForeignQuicEnabled = ruleOptionsEnable.屏蔽国外QUIC;
const addAllNodesToServiceGroupsEnabled = ruleOptionsEnable.分流组添加所有节点;
const chainEnabled = ruleOptionsEnable.链式代理;
const hideManualSelectGroupEnabled = ruleOptionsEnable.隐藏地区手动选择组;
const functionalGroups = [];
const functionalRules = [];
const finalRuleProviders = { ...baseRuleProviders };
if (!blockForeignQuicEnabled) {
delete finalRuleProviders.cn_additional;
}
const { customProxyNames = [], customGroup = null } = customizeInfo || {};
const filteredProxyNames = filteredProxies.map((p) => p.name);
const allProxiesNames = [...customProxyNames, ...filteredProxyNames];
const groupNamesOfSelect = generatedRegionGroups.filter((g) => g.type === 'select').map((g) => g.name);
const baseGroupNames = baseGroups.filter((g) => ruleOptionsEnable[g.name]).map((g) => g.name);
const customGroupNames = customGroup ? [customGroup.name] : [];
const chainGroup =
chainEnabled && customGroup
? {
...selectBaseOption,
name: dialerProxyName,
proxies: filteredProxyNames,
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Bypass.svg',
}
: null;
if (minimalModeEnabled) {
const defaultGroup = {
...selectBaseOption,
name: '默认代理',
proxies: allProxiesNames,
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Proxy.svg',
};
const finalRuleProviders = { ...baseRuleProviders };
if (!blockForeignQuicEnabled) delete finalRuleProviders.cn_additional;
const directGroup = {
...selectBaseOption,
name: '直连',
proxies: [...directProxies.map((p) => p.name)],
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/China.svg',
hidden: true,
};
const globalGroup = {
...selectBaseOption,
name: 'GLOBAL',
proxies: ['默认代理', ...customGroupNames, ...(chainGroup ? [chainGroup.name] : []), '直连'],
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Global.svg',
};
return {
globalGroup,
functionalGroups: [defaultGroup],
functionalRules: [],
finalRuleProviders,
chainGroup,
directGroup,
};
}
functionalGroups.push({
...selectBaseOption,
name: '默认代理',
proxies: [...groupNamesOfSelect, ...baseGroupNames, ...customGroupNames],
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Proxy.svg',
});
const orderedServiceConfigs = [
...serviceConfigs.filter((svc) => svc.name === 'AdBlock'),
...serviceConfigs.filter((svc) => svc.name !== 'AdBlock'),
];
for (const svc of orderedServiceConfigs) {
if (!ruleOptionsEnable[svc.name]) continue;
functionalRules.push(...(svc.rules || []));
Object.assign(finalRuleProviders, svc.providers || {});
}
for (const svc of serviceConfigs) {
if (!ruleOptionsEnable[svc.name]) continue;
let groupProxies = [];
if (svc.includeAll) {
groupProxies = [...allProxiesNames];
} else if (svc.reject) {
groupProxies = ['REJECT', 'REJECT-DROP', 'PASS'];
} else {
groupProxies = !addAllNodesToServiceGroupsEnabled
? ['默认代理', ...customGroupNames, ...baseGroupNames, ...groupNamesOfSelect, ...(svc.direct ? ['直连'] : [])]
: [
'默认代理',
...customGroupNames,
...baseGroupNames,
...groupNamesOfSelect,
...allProxiesNames,
...(svc.direct ? ['直连'] : []),
];
}
functionalGroups.push({
...svc.baseOption,
name: svc.name,
icon: svc.icon,
proxies: groupProxies,
...(svc.defaultSelected !== undefined && {
'default-selected': svc.defaultSelected,
}),
});
}
functionalGroups.push({
...selectBaseOption,
name: '漏网之鱼',
proxies: ['默认代理', '直连', ...groupNamesOfSelect],
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Stack.svg',
});
const directGroup = {
...selectBaseOption,
name: '直连',
proxies: [...directProxies.map((p) => p.name)],
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/China.svg',
hidden: hideManualSelectGroupEnabled,
};
const globalGroup = {
...selectBaseOption,
name: 'GLOBAL',
proxies: [
...functionalGroups.map((g) => g.name),
...customGroupNames,
...(chainGroup ? [chainGroup.name] : []),
directGroup.name,
...generatedRegionGroups.map((g) => g.name),
],
icon: 'https://fastly.jsdelivr.net/gh/AIsouler/MyClash@main/Icons/svg/Global.svg',
};
return { globalGroup, functionalGroups, functionalRules, finalRuleProviders, chainGroup, directGroup };
}
// ---dns和hosts相关处理---
// 常见的公共 DNS,用于过滤订阅中的公共 DNS
const commonDnsList = [
// IPv4(国内)
'223.5.5.5',
'223.6.6.6',
'119.29.29.29',
'1.12.12.12',
'120.53.53.53',
'114.114.114.114',
'180.76.76.76',
'1.2.4.8',
'116.116.116.116',
'101.226.4.6',
'123.125.81.6',
'180.184.1.1',
'180.184.2.2',
// IPv6(国内)
'2400:3200::1',
'2400:3200:baba::1',
'2402:4e00::',
'2400:da00::6666',
// IPv4(国外)
'1.1.1.1',
'1.0.0.1',
'8.8.8.8',
'8.8.4.4',
'9.9.9.9',
'149.112.112.112',
'208.67.222.222',
'208.67.220.220',
'94.140.14.14',
'94.140.15.15',
'76.76.2.0',
'76.76.10.0',
'185.228.168.9',
'185.228.169.9',
'77.88.8.8',
'77.88.8.1',
'156.154.70.1',
'156.154.71.1',
// IPv6(国外)
'2606:4700:4700::1111',
'2606:4700:4700::1001',
'2001:4860:4860::8888',
'2001:4860:4860::8844',
'2620:fe::fe',
'2620:fe::9',
'2620:119:35::35',
'2620:119:53::53',
'2a10:50c0::bad1:ff',
'2a10:50c0::bad2:ff',
'2a10:50c0::ad1:ff',
'2a10:50c0::ad2:ff',
'2a0d:2a00:1::2',
'2a0d:2a00:2::2',
'2a02:6b8::feed:0ff',
'2a02:6b8:0:1::feed:0ff',
'2610:a1:1018::1',
'2610:a1:1019::1',
// 关键词(国内)
'alidns',
'doh.pub',
'dot.pub',
'dns.pub',
'dnspod',
'dns.baidu',
// 关键词(国外)
'dns.google',
'dns.cloudflare',
'dns.apple',
'cloudflare-dns',
'quad9',
'opendns',
'nextdns',
'adguard',
'one.one.one.one',
];
// 预编译公共 DNS 正则
const commonDnsRegex = new RegExp(
commonDnsList.map((dns) => dns.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')).join('|'),
'i',
);
// 国内外 DNS 定义
const chinaDNS = ['223.5.5.5#DIRECT', '119.29.29.29#DIRECT'];
const foreignDNS = ['https://cloudflare-dns.com/dns-query#默认代理', 'https://dns.google/dns-query#默认代理'];
const defaultDNS = ['114.114.114.114#DIRECT', 'tls://223.5.5.5#DIRECT', 'https://1.12.12.12/dns-query#DIRECT'];
const proxyServerDNS = ['114.114.114.114#DIRECT', 'tls://223.5.5.5#DIRECT', 'https://doh.pub/dns-query#DIRECT'];
/**
* hosts 匹配优先级:精确 > +. > . > *(同级按出现顺序)
*/
function hostSpecificity(pattern) {
if (pattern.startsWith('+.')) return 2;
if (pattern.startsWith('.')) return 1;
if (pattern.includes('*')) return 0;
return 3;
}
/**
* 判断域名规则(精确/通配)是否匹配节点域名集合,忽略大小写
*/
function matchDomainPattern(pattern, domains) {
pattern = pattern.toLowerCase();
// 精确匹配
if (!pattern.includes('*') && !pattern.startsWith('+.') && !pattern.startsWith('.')) {
return typeof domains === 'string'
? domains.toLowerCase() === pattern
: [...domains].some((d) => d.toLowerCase() === pattern);
}
const domainList = typeof domains === 'string' ? [domains.toLowerCase()] : [...domains].map((d) => d.toLowerCase());
// +.example.com
if (pattern.startsWith('+.')) {
const suffix = pattern.slice(2);
return domainList.some((domain) => domain === suffix || domain.endsWith(`.${suffix}`));
}
// .example.com
if (pattern.startsWith('.')) {
const suffix = pattern.slice(1);
return domainList.some((domain) => domain !== suffix && domain.endsWith(`.${suffix}`));
}
// *.example.com、example.*.com 等
const patternParts = pattern.split('.');
return domainList.some((domain) => {
const domainParts = domain.split('.');
return (
patternParts.length === domainParts.length &&
patternParts.every((part, index) => part === '*' || part === domainParts[index])
);
});
}
/**
* 根据订阅 hosts 映射改写节点 server,改写后无需再复制 hosts 进新配置。
* 支持链式映射(如 a: b、b: c 时节点 a 改写为 c);
* 回环映射(a: b、b: a)由内核校验拒绝,此处仅以已访问集合防御性终止
*/
function applyHostsToProxies(proxies, hosts) {
if (!hosts || typeof hosts !== 'object') return proxies;
const hostEntries = Object.entries(hosts)
.filter(
([, value]) => (typeof value === 'string' && value.length > 0) || (Array.isArray(value) && value.length > 0),
)
.sort((a, b) => hostSpecificity(b[0]) - hostSpecificity(a[0]));
if (hostEntries.length === 0) return proxies;
const targetOf = (value) => {
if (Array.isArray(value)) value = value.find((v) => typeof v === 'string' && v.length > 0);
return typeof value === 'string' && value.length > 0 ? value : null;
};
const resolveCache = new Map();
const resolve = (server) => {
const cached = resolveCache.get(server);
if (cached !== undefined) return cached;
const seen = new Set();
let current = server.toLowerCase();