-
Notifications
You must be signed in to change notification settings - Fork 6.1k
Expand file tree
/
Copy path明文源吗
More file actions
6415 lines (5741 loc) · 334 KB
/
明文源吗
File metadata and controls
6415 lines (5741 loc) · 334 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
// CFnew - 终端 v2.9.6
// 版本: v2.9.6
import { connect } from 'cloudflare:sockets';
let at = '351c9981-04b6-4103-aa4b-864aa9c91469';
let fallbackAddress = '';
let socks5Config = '';
let customPreferredIPs = [];
let customPreferredDomains = [];
let enableSocksDowngrade = false;
let disableNonTLS = false;
let disablePreferred = false;
let enableRegionMatching = true;
let currentWorkerRegion = '';
let manualWorkerRegion = '';
let piu = '';
let cp = '';
let ev = true;
let et = false;
let ex = false;
let tp = '';
// 启用ECH功能(true启用,false禁用)
let enableECH = false;
// 自定义DNS服务器(默认:https://223.5.5.5/dns-query)
let customDNS = 'https://223.5.5.5/dns-query';
// 自定义ECH域名(默认:cloudflare-ech.com)
let customECHDomain = 'cloudflare-ech.com';
let scu = 'https://url.v1.mk/sub';
// 远程配置URL(硬编码)
const remoteConfigUrl = 'https://raw.githubusercontent.com/byJoey/test/refs/heads/main/tist.ini';
let epd = false; // 优选域名默认关闭
let epi = true;
let egi = false;
let ena = false; // 原生地址默认关闭
let kvStore = null;
let kvConfig = {};
let kvConfigLastLoad = 0;
const KV_CACHE_TTL = 5 * 60 * 60 * 1000; // 5小时缓存
const regionMapping = {
'HK': ['🇭🇰 香港', 'HK', 'Hong Kong'],
'US': ['🇺🇸 美国', 'US', 'United States'],
'SG': ['🇸🇬 新加坡', 'SG', 'Singapore'],
'JP': ['🇯🇵 日本', 'JP', 'Japan'],
'KR': ['🇰🇷 韩国', 'KR', 'South Korea'],
'DE': ['🇩🇪 德国', 'DE', 'Germany'],
'SE': ['🇸🇪 瑞典', 'SE', 'Sweden'],
'NL': ['🇳🇱 荷兰', 'NL', 'Netherlands'],
'FI': ['🇫🇮 芬兰', 'FI', 'Finland'],
'GB': ['🇬🇧 英国', 'GB', 'United Kingdom'],
'Oracle': ['甲骨文', 'Oracle'],
'DigitalOcean': ['数码海', 'DigitalOcean'],
'Vultr': ['Vultr', 'Vultr'],
'Multacom': ['Multacom', 'Multacom']
};
let backupIPs = [
{ domain: 'ProxyIP.HK.CMLiussss.net', region: 'HK', regionCode: 'HK', port: 443 },
{ domain: 'ProxyIP.US.CMLiussss.net', region: 'US', regionCode: 'US', port: 443 },
{ domain: 'ProxyIP.SG.CMLiussss.net', region: 'SG', regionCode: 'SG', port: 443 },
{ domain: 'ProxyIP.JP.CMLiussss.net', region: 'JP', regionCode: 'JP', port: 443 },
{ domain: 'ProxyIP.KR.CMLiussss.net', region: 'KR', regionCode: 'KR', port: 443 },
{ domain: 'ProxyIP.DE.CMLiussss.net', region: 'DE', regionCode: 'DE', port: 443 },
{ domain: 'ProxyIP.SE.CMLiussss.net', region: 'SE', regionCode: 'SE', port: 443 },
{ domain: 'ProxyIP.NL.CMLiussss.net', region: 'NL', regionCode: 'NL', port: 443 },
{ domain: 'ProxyIP.FI.CMLiussss.net', region: 'FI', regionCode: 'FI', port: 443 },
{ domain: 'ProxyIP.GB.CMLiussss.net', region: 'GB', regionCode: 'GB', port: 443 },
{ domain: 'ProxyIP.Oracle.cmliussss.net', region: 'Oracle', regionCode: 'Oracle', port: 443 },
{ domain: 'ProxyIP.DigitalOcean.CMLiussss.net', region: 'DigitalOcean', regionCode: 'DigitalOcean', port: 443 },
{ domain: 'ProxyIP.Vultr.CMLiussss.net', region: 'Vultr', regionCode: 'Vultr', port: 443 },
{ domain: 'ProxyIP.Multacom.CMLiussss.net', region: 'Multacom', regionCode: 'Multacom', port: 443 }
];
const directDomains = [
{ name: "cloudflare.182682.xyz", domain: "cloudflare.182682.xyz" }, { name: "speed.marisalnc.com", domain: "speed.marisalnc.com" },
{ domain: "freeyx.cloudflare88.eu.org" }, { domain: "bestcf.top" }, { domain: "cdn.2020111.xyz" }, { domain: "cfip.cfcdn.vip" },
{ domain: "cf.0sm.com" }, { domain: "cf.090227.xyz" }, { domain: "cf.zhetengsha.eu.org" }, { domain: "cloudflare.9jy.cc" },
{ domain: "cf.zerone-cdn.pp.ua" }, { domain: "cfip.1323123.xyz" }, { domain: "cnamefuckxxs.yuchen.icu" }, { domain: "cloudflare-ip.mofashi.ltd" },
{ domain: "115155.xyz" }, { domain: "cname.xirancdn.us" }, { domain: "f3058171cad.002404.xyz" }, { domain: "8.889288.xyz" },
{ domain: "cdn.tzpro.xyz" }, { domain: "cf.877771.xyz" }, { domain: "xn--b6gac.eu.org" }
];
const E_INVALID_DATA = atob('aW52YWxpZCBkYXRh');
const E_INVALID_USER = atob('aW52YWxpZCB1c2Vy');
const E_UNSUPPORTED_CMD = atob('Y29tbWFuZCBpcyBub3Qgc3VwcG9ydGVk');
const E_UDP_DNS_ONLY = atob('VURQIHByb3h5IG9ubHkgZW5hYmxlIGZvciBETlMgd2hpY2ggaXMgcG9ydCA1Mw==');
const E_INVALID_ADDR_TYPE = atob('aW52YWxpZCBhZGRyZXNzVHlwZQ==');
const E_EMPTY_ADDR = atob('YWRkcmVzc1ZhbHVlIGlzIGVtcHR5');
const E_WS_NOT_OPEN = atob('d2ViU29ja2V0LmVhZHlTdGF0ZSBpcyBub3Qgb3Blbg==');
const E_INVALID_ID_STR = atob('U3RyaW5naWZpZWQgaWRlbnRpZmllciBpcyBpbnZhbGlk');
const E_INVALID_SOCKS_ADDR = atob('SW52YWxpZCBTT0NLUyBhZGRyZXNzIGZvcm1hdA==');
const E_SOCKS_NO_METHOD = atob('bm8gYWNjZXB0YWJsZSBtZXRob2Rz');
const E_SOCKS_AUTH_NEEDED = atob('c29ja3Mgc2VydmVyIG5lZWRzIGF1dGg=');
const E_SOCKS_AUTH_FAIL = atob('ZmFpbCB0byBhdXRoIHNvY2tzIHNlcnZlcg==');
const E_SOCKS_CONN_FAIL = atob('ZmFpbCB0byBvcGVuIHNvY2tzIGNvbm5lY3Rpb24=');
let parsedSocks5Config = {};
let isSocksEnabled = false;
const ADDRESS_TYPE_IPV4 = 1;
const ADDRESS_TYPE_URL = 2;
const ADDRESS_TYPE_IPV6 = 3;
function isValidFormat(str) {
const userRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
return userRegex.test(str);
}
function isValidIP(ip) {
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
if (ipv4Regex.test(ip)) return true;
const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
if (ipv6Regex.test(ip)) return true;
const ipv6ShortRegex = /^::1$|^::$|^(?:[0-9a-fA-F]{1,4}:)*::(?:[0-9a-fA-F]{1,4}:)*[0-9a-fA-F]{1,4}$/;
if (ipv6ShortRegex.test(ip)) return true;
return false;
}
function createNodeNamer(skip = false) {
// 如果配置了 yxURL,则跳过编号
const forceSkip = (typeof piu !== 'undefined' && piu && piu.trim());
let skipNumbering = forceSkip || skip;
const counters = {};
function setSkipNumbering(flag) {
if (!forceSkip) {
skipNumbering = flag;
}
}
function namer(baseName, nodeName = null) {
if (skipNumbering || (baseName && baseName.includes('.'))) {
return nodeName || baseName;
}
if (!counters[baseName]) counters[baseName] = 0;
counters[baseName]++;
const index = String(counters[baseName]).padStart(2, '0');
return `${nodeName || baseName}-${index}`;
}
return { namer, setSkipNumbering };
}
async function initKVStore(env) {
if (env.C) {
try {
kvStore = env.C;
await loadKVConfig();
} catch (error) {
kvStore = null;
}
} else {
}
}
async function loadKVConfig(force = false) {
if (!kvStore) {
return;
}
if (!force && kvConfigLastLoad > 0 && (Date.now() - kvConfigLastLoad) < KV_CACHE_TTL) {
return;
}
try {
const configData = await kvStore.get('c');
if (configData) {
kvConfig = JSON.parse(configData);
} else {
}
kvConfigLastLoad = Date.now();
} catch (error) {
kvConfig = {};
}
}
async function saveKVConfig() {
if (!kvStore) {
return;
}
try {
const configString = JSON.stringify(kvConfig);
await kvStore.put('c', configString);
kvConfigLastLoad = Date.now();
} catch (error) {
throw error;
}
}
function getConfigValue(key, defaultValue = '') {
if (kvConfig[key] !== undefined) {
return kvConfig[key];
}
return defaultValue;
}
async function setConfigValue(key, value) {
kvConfig[key] = value;
await saveKVConfig();
}
async function detectWorkerRegion(request) {
try {
const cfCountry = request.cf?.country;
if (cfCountry) {
const countryToRegion = {
'US': 'US', 'SG': 'SG', 'JP': 'JP', 'KR': 'KR',
'DE': 'DE', 'SE': 'SE', 'NL': 'NL', 'FI': 'FI', 'GB': 'GB',
'CN': 'SG', 'TW': 'JP', 'AU': 'SG', 'CA': 'US',
'FR': 'DE', 'IT': 'DE', 'ES': 'DE', 'CH': 'DE',
'AT': 'DE', 'BE': 'NL', 'DK': 'SE', 'NO': 'SE', 'IE': 'GB'
};
if (countryToRegion[cfCountry]) {
return countryToRegion[cfCountry];
}
}
return 'SG';
} catch (error) {
return 'SG';
}
}
async function checkIPAvailability(domain, port = 443, timeout = 2000) {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeout);
const response = await fetch(`https://${domain}`, {
method: 'HEAD',
signal: controller.signal,
headers: {
'User-Agent': 'Mozilla/5.0 (compatible; CF-IP-Checker/1.0)'
}
});
clearTimeout(timeoutId);
return response.status < 500;
} catch (error) {
return true;
}
}
async function getBestBackupIP(workerRegion = '', useRegionMatching = enableRegionMatching) {
if (backupIPs.length === 0) {
return null;
}
const availableIPs = backupIPs.map(ip => ({ ...ip, available: true }));
if (useRegionMatching && workerRegion) {
const sortedIPs = getSmartRegionSelection(workerRegion, availableIPs, useRegionMatching);
if (sortedIPs.length > 0) {
const selectedIP = sortedIPs[0];
return selectedIP;
}
}
const selectedIP = availableIPs[0];
return selectedIP;
}
function getNearbyRegions(region) {
const nearbyMap = {
'US': ['SG', 'JP', 'KR'],
'SG': ['JP', 'KR', 'US'],
'JP': ['SG', 'KR', 'US'],
'KR': ['JP', 'SG', 'US'],
'DE': ['NL', 'GB', 'SE', 'FI'],
'SE': ['DE', 'NL', 'FI', 'GB'],
'NL': ['DE', 'GB', 'SE', 'FI'],
'FI': ['SE', 'DE', 'NL', 'GB'],
'GB': ['DE', 'NL', 'SE', 'FI']
};
return nearbyMap[region] || [];
}
function getAllRegionsByPriority(region) {
const nearbyRegions = getNearbyRegions(region);
const allRegions = ['US', 'SG', 'JP', 'KR', 'DE', 'SE', 'NL', 'FI', 'GB'];
return [region, ...nearbyRegions, ...allRegions.filter(r => r !== region && !nearbyRegions.includes(r))];
}
function getSmartRegionSelection(workerRegion, availableIPs, useRegionMatching = enableRegionMatching) {
if (!useRegionMatching || !workerRegion) {
return availableIPs;
}
const priorityRegions = getAllRegionsByPriority(workerRegion);
const sortedIPs = [];
for (const region of priorityRegions) {
const regionIPs = availableIPs.filter(ip => ip.regionCode === region);
sortedIPs.push(...regionIPs);
}
return sortedIPs;
}
function parseAddressAndPort(input) {
if (input.includes('[') && input.includes(']')) {
const match = input.match(/^\[([^\]]+)\](?::(\d+))?$/);
if (match) {
return {
address: match[1],
port: match[2] ? parseInt(match[2], 10) : null
};
}
}
const lastColonIndex = input.lastIndexOf(':');
if (lastColonIndex > 0) {
const address = input.substring(0, lastColonIndex);
const portStr = input.substring(lastColonIndex + 1);
const port = parseInt(portStr, 10);
// address 含 ':' 说明是裸 IPv6(如 2001:db8::1),整体当地址,无端口
if (!address.includes(':') && !isNaN(port) && port > 0 && port <= 65535) {
return { address, port };
}
}
return { address: input, port: null };
}
export default {
async fetch(request, env, ctx) {
try {
const isWebSocket = request.headers.get('Upgrade') === atob('d2Vic29ja2V0');
const isPost = request.method === 'POST';
const reqUrl = new URL(request.url);
const pathSegments = reqUrl.pathname.split('/').filter(p => p);
if (!isWebSocket && !isPost && reqUrl.pathname !== '/') {
const tmpAt = (env.u || env.U || '').toLowerCase();
const tmpCp = (env.d || env.D || '').toLowerCase();
const firstSeg = pathSegments[0] || '';
const cleanCp = tmpCp.startsWith('/') ? tmpCp.substring(1) : tmpCp;
if (firstSeg !== tmpAt && (cleanCp ? firstSeg !== cleanCp : false)) {
return new Response('Not Found', { status: 404 });
}
}
await initKVStore(env);
at = (env.u || env.U || at).toLowerCase();
const subPath = (env.d || env.D || at).toLowerCase();
const ci = getConfigValue('p', env.p || env.P);
let useCustomIP = false;
const manualRegion = getConfigValue('wk', env.wk || env.WK);
if (manualRegion && manualRegion.trim()) {
manualWorkerRegion = manualRegion.trim().toUpperCase();
currentWorkerRegion = manualWorkerRegion;
} else if (ci && ci.trim()) {
useCustomIP = true;
currentWorkerRegion = 'CUSTOM';
} else {
currentWorkerRegion = await detectWorkerRegion(request);
}
const regionMatchingControl = env.rm || env.RM;
if (regionMatchingControl && regionMatchingControl.toLowerCase() === 'no') {
enableRegionMatching = false;
}
const envFallback = getConfigValue('p', env.p || env.P);
if (envFallback) {
fallbackAddress = envFallback.trim();
}
socks5Config = getConfigValue('s', env.s || env.S) || socks5Config;
if (socks5Config) {
try {
parsedSocks5Config = parseSocksConfig(socks5Config);
isSocksEnabled = true;
} catch (err) {
isSocksEnabled = false;
}
}
const customPreferred = getConfigValue('yx', env.yx || env.YX);
if (customPreferred) {
try {
const preferredList = customPreferred.split(',').map(item => item.trim()).filter(item => item);
customPreferredIPs = [];
customPreferredDomains = [];
preferredList.forEach(item => {
let nodeName = '';
let addressPart = item;
if (item.includes('#')) {
const parts = item.split('#');
addressPart = parts[0].trim();
nodeName = parts[1].trim();
}
const { address, port } = parseAddressAndPort(addressPart);
if (!nodeName) {
nodeName = '自定义优选-' + address + (port ? ':' + port : '');
}
if (isValidIP(address)) {
customPreferredIPs.push({
ip: address,
port: port,
isp: nodeName
});
} else {
customPreferredDomains.push({
domain: address,
port: port,
name: nodeName
});
}
});
} catch (err) {
customPreferredIPs = [];
customPreferredDomains = [];
}
}
const downgradeControl = getConfigValue('qj', env.qj || env.QJ);
if (downgradeControl && downgradeControl.toLowerCase() === 'no') {
enableSocksDowngrade = true;
}
const dkbyControl = getConfigValue('dkby', env.dkby || env.DKBY);
if (dkbyControl && dkbyControl.toLowerCase() === 'yes') {
disableNonTLS = true;
}
const yxbyControl = env.yxby || env.YXBY;
if (yxbyControl && yxbyControl.toLowerCase() === 'yes') {
disablePreferred = true;
}
const vlessControl = getConfigValue('ev', env.ev);
if (vlessControl !== undefined && vlessControl !== '') {
ev = vlessControl === 'yes' || vlessControl === true || vlessControl === 'true';
}
const tjControl = getConfigValue('et', env.et);
if (tjControl !== undefined && tjControl !== '') {
et = tjControl === 'yes' || tjControl === true || tjControl === 'true';
}
tp = getConfigValue('tp', env.tp) || '';
const xhttpControl = getConfigValue('ex', env.ex);
if (xhttpControl !== undefined && xhttpControl !== '') {
ex = xhttpControl === 'yes' || xhttpControl === true || xhttpControl === 'true';
}
scu = getConfigValue('scu', env.scu) || 'https://url.v1.mk/sub';
const preferredDomainsControl = getConfigValue('epd', env.epd || 'no');
if (preferredDomainsControl !== undefined && preferredDomainsControl !== '') {
epd = preferredDomainsControl !== 'no' && preferredDomainsControl !== false && preferredDomainsControl !== 'false';
}
const preferredIPsControl = getConfigValue('epi', env.epi);
if (preferredIPsControl !== undefined && preferredIPsControl !== '') {
epi = preferredIPsControl !== 'no' && preferredIPsControl !== false && preferredIPsControl !== 'false';
}
const githubIPsControl = getConfigValue('egi', env.egi);
if (githubIPsControl !== undefined && githubIPsControl !== '') {
egi = githubIPsControl !== 'no' && githubIPsControl !== false && githubIPsControl !== 'false';
}
const nativeAddressControl = getConfigValue('ena', env.ena);
if (nativeAddressControl !== undefined && nativeAddressControl !== '') {
ena = nativeAddressControl !== 'no' && nativeAddressControl !== false && nativeAddressControl !== 'false';
}
const echControl = getConfigValue('ech', env.ech);
if (echControl !== undefined && echControl !== '') {
enableECH = echControl === 'yes' || echControl === true || echControl === 'true';
}
// 加载自定义DNS和ECH域名配置
const customDNSValue = getConfigValue('customDNS', '');
if (customDNSValue && customDNSValue.trim()) {
customDNS = customDNSValue.trim();
}
const customECHDomainValue = getConfigValue('customECHDomain', '');
if (customECHDomainValue && customECHDomainValue.trim()) {
customECHDomain = customECHDomainValue.trim();
}
// 如果启用了ECH,自动启用仅TLS模式(避免80端口干扰)
// ECH需要TLS才能工作,所以必须禁用非TLS节点
if (enableECH) {
disableNonTLS = true;
// 检查 KV 中是否有 dkby: yes,没有就直接写入
const currentDkby = getConfigValue('dkby', '');
if (currentDkby !== 'yes') {
await setConfigValue('dkby', 'yes');
}
}
if (!ev && !et && !ex) {
ev = true;
}
piu = getConfigValue('yxURL', env.yxURL || env.YXURL) || '';
cp = getConfigValue('d', env.d || env.D) || '';
const url = new URL(request.url);
if (url.pathname.includes('/api/config')) {
const pathParts = url.pathname.split('/').filter(p => p);
const apiIndex = pathParts.indexOf('api');
if (apiIndex > 0) {
const pathSegments = pathParts.slice(0, apiIndex);
const pathIdentifier = pathSegments.join('/');
let isValid = false;
if (cp && cp.trim()) {
const cleanCustomPath = cp.trim().startsWith('/') ? cp.trim().substring(1) : cp.trim();
isValid = (pathIdentifier === cleanCustomPath);
} else {
isValid = (isValidFormat(pathIdentifier) && pathIdentifier === at);
}
if (isValid) {
return await handleConfigAPI(request);
} else {
return new Response(JSON.stringify({ error: '路径验证失败' }), {
status: 403,
headers: { 'Content-Type': 'application/json' }
});
}
}
return new Response(JSON.stringify({ error: '无效的API路径' }), {
status: 404,
headers: { 'Content-Type': 'application/json' }
});
}
if (url.pathname.includes('/api/preferred-ips')) {
const pathParts = url.pathname.split('/').filter(p => p);
const apiIndex = pathParts.indexOf('api');
if (apiIndex > 0) {
const pathSegments = pathParts.slice(0, apiIndex);
const pathIdentifier = pathSegments.join('/');
let isValid = false;
if (cp && cp.trim()) {
const cleanCustomPath = cp.trim().startsWith('/') ? cp.trim().substring(1) : cp.trim();
isValid = (pathIdentifier === cleanCustomPath);
} else {
isValid = (isValidFormat(pathIdentifier) && pathIdentifier === at);
}
if (isValid) {
return await handlePreferredIPsAPI(request);
} else {
return new Response(JSON.stringify({ error: '路径验证失败' }), {
status: 403,
headers: { 'Content-Type': 'application/json' }
});
}
}
return new Response(JSON.stringify({ error: '无效的API路径' }), {
status: 404,
headers: { 'Content-Type': 'application/json' }
});
}
if (request.method === 'POST' && ex) {
const r = await handleXhttpPost(request);
if (r) {
ctx.waitUntil(r.closed);
return new Response(r.readable, {
headers: {
'X-Accel-Buffering': 'no',
'Cache-Control': 'no-store',
Connection: 'keep-alive',
'User-Agent': 'Go-http-client/2.0',
'Content-Type': 'application/grpc',
},
});
}
return new Response('Internal Server Error', { status: 500 });
}
if (request.headers.get('Upgrade') === atob('d2Vic29ja2V0')) {
return await handleWsRequest(request);
}
if (request.method === 'GET') {
// 处理 /{UUID}/region 或 /{自定义路径}/region
if (url.pathname.endsWith('/region')) {
const pathParts = url.pathname.split('/').filter(p => p);
if (pathParts.length === 2 && pathParts[1] === 'region') {
const pathIdentifier = pathParts[0];
let isValid = false;
if (cp && cp.trim()) {
// 使用自定义路径
const cleanCustomPath = cp.trim().startsWith('/') ? cp.trim().substring(1) : cp.trim();
isValid = (pathIdentifier === cleanCustomPath);
} else {
// 使用UUID路径
isValid = (isValidFormat(pathIdentifier) && pathIdentifier === at);
}
if (isValid) {
const ci = getConfigValue('p', env.p || env.P);
const manualRegion = getConfigValue('wk', env.wk || env.WK);
if (manualRegion && manualRegion.trim()) {
return new Response(JSON.stringify({
region: manualRegion.trim().toUpperCase(),
detectionMethod: '手动指定地区',
manualRegion: manualRegion.trim().toUpperCase(),
timestamp: new Date().toISOString()
}), {
headers: { 'Content-Type': 'application/json' }
});
} else if (ci && ci.trim()) {
return new Response(JSON.stringify({
region: 'CUSTOM',
detectionMethod: '自定义ProxyIP模式', ci: ci,
timestamp: new Date().toISOString()
}), {
headers: { 'Content-Type': 'application/json' }
});
} else {
const detectedRegion = await detectWorkerRegion(request);
return new Response(JSON.stringify({
region: detectedRegion,
detectionMethod: 'API检测',
timestamp: new Date().toISOString()
}), {
headers: { 'Content-Type': 'application/json' }
});
}
} else {
return new Response(JSON.stringify({
error: '访问被拒绝',
message: '路径验证失败'
}), {
status: 403,
headers: { 'Content-Type': 'application/json' }
});
}
}
}
// 处理 /{UUID}/test-api 或 /{自定义路径}/test-api
if (url.pathname.endsWith('/test-api')) {
const pathParts = url.pathname.split('/').filter(p => p);
if (pathParts.length === 2 && pathParts[1] === 'test-api') {
const pathIdentifier = pathParts[0];
let isValid = false;
if (cp && cp.trim()) {
// 使用自定义路径
const cleanCustomPath = cp.trim().startsWith('/') ? cp.trim().substring(1) : cp.trim();
isValid = (pathIdentifier === cleanCustomPath);
} else {
// 使用UUID路径
isValid = (isValidFormat(pathIdentifier) && pathIdentifier === at);
}
if (isValid) {
try {
const testRegion = await detectWorkerRegion(request);
return new Response(JSON.stringify({
detectedRegion: testRegion,
message: 'API测试完成',
timestamp: new Date().toISOString()
}), {
headers: { 'Content-Type': 'application/json' }
});
} catch (error) {
return new Response(JSON.stringify({
error: error.message,
message: 'API测试失败'
}), {
status: 500,
headers: { 'Content-Type': 'application/json' }
});
}
} else {
return new Response(JSON.stringify({
error: '访问被拒绝',
message: '路径验证失败'
}), {
status: 403,
headers: { 'Content-Type': 'application/json' }
});
}
}
}
if (url.pathname === '/') {
// 检查是否有自定义首页URL配置
const customHomepage = getConfigValue('homepage', env.homepage || env.HOMEPAGE);
if (customHomepage && customHomepage.trim()) {
try {
// 从自定义URL获取内容
const homepageResponse = await fetch(customHomepage.trim(), {
method: 'GET',
headers: {
'User-Agent': request.headers.get('User-Agent') || 'Mozilla/5.0',
'Accept': request.headers.get('Accept') || '*/*',
'Accept-Language': request.headers.get('Accept-Language') || 'en-US,en;q=0.9',
},
redirect: 'follow'
});
if (homepageResponse.ok) {
// 获取响应内容
const contentType = homepageResponse.headers.get('Content-Type') || 'text/html; charset=utf-8';
const content = await homepageResponse.text();
// 返回自定义首页内容
return new Response(content, {
status: homepageResponse.status,
headers: {
'Content-Type': contentType,
'Cache-Control': 'no-cache, no-store, must-revalidate',
}
});
}
} catch (error) {
// 如果获取失败,继续使用默认终端页面
console.error('获取自定义首页失败:', error);
}
}
// 优先检查Cookie中的语言设置
const cookieHeader = request.headers.get('Cookie') || '';
let langFromCookie = null;
if (cookieHeader) {
const cookies = cookieHeader.split(';').map(c => c.trim());
for (const cookie of cookies) {
if (cookie.startsWith('preferredLanguage=')) {
langFromCookie = cookie.split('=')[1];
break;
}
}
}
let isFarsi = false;
if (langFromCookie === 'fa' || langFromCookie === 'fa-IR') {
isFarsi = true;
} else if (langFromCookie === 'zh' || langFromCookie === 'zh-CN') {
isFarsi = false;
} else {
// 如果没有Cookie,使用浏览器语言检测
const acceptLanguage = request.headers.get('Accept-Language') || '';
const browserLang = acceptLanguage.split(',')[0].split('-')[0].toLowerCase();
isFarsi = browserLang === 'fa' || acceptLanguage.includes('fa-IR') || acceptLanguage.includes('fa');
}
const lang = isFarsi ? 'fa' : 'zh-CN';
const langAttr = isFarsi ? 'fa-IR' : 'zh-CN';
const translations = {
zh: {
title: '终端',
terminal: '终端',
congratulations: '恭喜你来到这',
enterU: '请输入你U变量的值',
enterD: '请输入你D变量的值',
command: '命令: connect [',
uuid: 'UUID',
path: 'PATH',
inputU: '输入U变量的内容并且回车...',
inputD: '输入D变量的内容并且回车...',
connecting: '正在连接...',
invading: '正在入侵...',
success: '连接成功!返回结果...',
error: '错误: 无效的UUID格式',
reenter: '请重新输入有效的UUID'
},
fa: {
title: 'ترمینال',
terminal: 'ترمینال',
congratulations: 'تبریک میگوییم به شما',
enterU: 'لطفا مقدار متغیر U خود را وارد کنید',
enterD: 'لطفا مقدار متغیر D خود را وارد کنید',
command: 'دستور: connect [',
uuid: 'UUID',
path: 'PATH',
inputU: 'محتویات متغیر U را وارد کرده و Enter را بزنید...',
inputD: 'محتویات متغیر D را وارد کرده و Enter را بزنید...',
connecting: 'در حال اتصال...',
invading: 'در حال نفوذ...',
success: 'اتصال موفق! در حال بازگشت نتیجه...',
error: 'خطا: فرمت UUID نامعتبر',
reenter: 'لطفا UUID معتبر را دوباره وارد کنید'
}
};
const t = translations[isFarsi ? 'fa' : 'zh'];
const terminalHtml = `<!DOCTYPE html>
<html lang="${langAttr}" dir="${isFarsi ? 'rtl' : 'ltr'}">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>${t.title}</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body {
font-family: "Courier New", monospace;
background: #000; color: #00ff00; min-height: 100vh;
overflow-x: hidden; position: relative;
display: flex; justify-content: center; align-items: center;
}
.matrix-bg {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: #000;
z-index: -1;
}
@keyframes bg-pulse {
0%, 100% { background: linear-gradient(45deg, #000 0%, #001100 50%, #000 100%); }
50% { background: linear-gradient(45deg, #000 0%, #002200 50%, #000 100%); }
}
.matrix-rain {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: transparent;
z-index: -1;
display: none;
}
@keyframes matrix-fall {
0% { transform: translateY(-100%); }
100% { transform: translateY(100vh); }
}
.matrix-code-rain {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
pointer-events: none; z-index: -1;
overflow: hidden;
display: none;
}
.matrix-column {
position: absolute; top: -100%; left: 0;
color: #00ff00; font-family: "Courier New", monospace;
font-size: 14px; line-height: 1.2;
text-shadow: 0 0 5px #00ff00;
}
@keyframes matrix-drop {
0% { top: -100%; opacity: 1; }
10% { opacity: 1; }
90% { opacity: 0.3; }
100% { top: 100vh; opacity: 0; }
}
.matrix-column:nth-child(odd) {
animation-duration: 12s;
animation-delay: -2s;
}
.matrix-column:nth-child(even) {
animation-duration: 18s;
animation-delay: -5s;
}
.matrix-column:nth-child(3n) {
animation-duration: 20s;
animation-delay: -8s;
}
.terminal {
width: 90%; max-width: 800px; height: 500px;
background: rgba(0, 0, 0, 0.9);
border: 2px solid #00ff00;
border-radius: 8px;
box-shadow: 0 0 30px rgba(0, 255, 0, 0.5), inset 0 0 20px rgba(0, 255, 0, 0.1);
backdrop-filter: blur(10px);
position: relative; z-index: 1;
overflow: hidden;
}
.terminal-header {
background: rgba(0, 20, 0, 0.8);
padding: 10px 15px;
border-bottom: 1px solid #00ff00;
display: flex; align-items: center;
}
.terminal-buttons {
display: flex; gap: 8px;
}
.terminal-button {
width: 12px; height: 12px; border-radius: 50%;
background: #ff5f57; border: none;
}
.terminal-button:nth-child(2) { background: #ffbd2e; }
.terminal-button:nth-child(3) { background: #28ca42; }
.terminal-title {
margin-left: 15px; color: #00ff00;
font-size: 14px; font-weight: bold;
}
.terminal-body {
padding: 20px; height: calc(100% - 50px);
overflow-y: auto; font-size: 14px;
line-height: 1.4;
}
.terminal-line {
margin-bottom: 8px; display: flex; align-items: center;
}
.terminal-prompt {
color: #00ff00; margin-right: 10px;
font-weight: bold;
}
.terminal-input {
background: transparent; border: none; outline: none;
color: #00ff00; font-family: "Courier New", monospace;
font-size: 14px; flex: 1;
caret-color: #00ff00;
}
.terminal-input::placeholder {
color: #00aa00; opacity: 0.7;
}
.terminal-cursor {
display: inline-block; width: 8px; height: 16px;
background: #00ff00;
margin-left: 2px;
}
@keyframes blink {
0%, 50% { opacity: 1; }
51%, 100% { opacity: 0; }
}
.terminal-output {
color: #00aa00; margin: 5px 0;
}
.terminal-error {
color: #ff4444; margin: 5px 0;
}
.terminal-success {
color: #44ff44; margin: 5px 0;
}
.matrix-text {
position: fixed; top: 20px; right: 20px;
color: #00ff00; font-family: "Courier New", monospace;
font-size: 0.8rem; opacity: 0.6;
}
@keyframes matrix-flicker {
0%, 100% { opacity: 0.6; }
50% { opacity: 1; }
}
</style>
</head>
<body>
<div class="matrix-bg"></div>
<div class="matrix-rain"></div>
<div class="matrix-code-rain" id="matrixCodeRain"></div>
<div class="matrix-text">${t.terminal}</div>
<div style="position: fixed; top: 20px; left: 20px; z-index: 1000;">
<select id="languageSelector" style="background: rgba(0, 20, 0, 0.9); border: 2px solid #00ff00; color: #00ff00; padding: 8px 12px; font-family: 'Courier New', monospace; font-size: 14px; cursor: pointer; text-shadow: 0 0 5px #00ff00; box-shadow: 0 0 15px rgba(0, 255, 0, 0.4);" onchange="changeLanguage(this.value)">
<option value="zh" ${!isFarsi ? 'selected' : ''}>🇨🇳 中文</option>
<option value="fa" ${isFarsi ? 'selected' : ''}>🇮🇷 فارسی</option>
</select>
</div>
<div class="terminal">
<div class="terminal-header">
<div class="terminal-buttons">
<div class="terminal-button"></div>
<div class="terminal-button"></div>
<div class="terminal-button"></div>
</div>
<div class="terminal-title">${t.terminal}</div>
</div>
<div class="terminal-body" id="terminalBody">
<div class="terminal-line">
<span class="terminal-prompt">root:~$</span>
<span class="terminal-output">${t.congratulations}</span>
</div>
<div class="terminal-line">
<span class="terminal-prompt">root:~$</span>
<span class="terminal-output">${cp && cp.trim() ? t.enterD : t.enterU}</span>
</div>
<div class="terminal-line">
<span class="terminal-prompt">root:~$</span>
<span class="terminal-output">${t.command}${cp && cp.trim() ? t.path : t.uuid}]</span>
</div>
<div class="terminal-line">