前言

一个月前马斯克开源了自家的大语言模型 grok-1 并顺带着嘲讽了一下 OpenAI,想看看 OpenAI 关于 “Open” 的部分。

这波我肯定是站马斯克了,记得第一次听说 OpenAI 名字的时候,还以为这是一个研究 AI 的开源社区,因为它遵循了 OpenCV, OpenGL 这样的命名模式。

后来 GPT-4 需要一个月 20 刀的时候,也算是认清 OpenAI 的真面目了。

自从大语言模型诞生以来,中国民众想使用 AI 服务是真的难。可谓是双向卡脖子,一方面阿美丽卡的公司不对中国开放服务。另一方面国民无法访问自由的互联网。

最近,ChatGPT-3.5 可以免注册使用了(它总算是 Open 了一小部分😂),也就是说对于我们来说又少了一道使用 ChatCPT 的门槛。

这篇博客介绍了一种访问 chat.openai.com 的方法。

基于 Cloudflare 搭建 Vless 节点

既然 chat.openai.com 已经可以免注册使用了,那么原则上我们就只剩下 GFW 这一个障碍了。但并不是任何一个梯子都可以访问 chat.openai.com 的,比如我的甲骨文云的梯子就不行。

原因在于 OpenAI 屏蔽了许多知名云服务提供商的 IP,也就是专门针对我们这些使用代理的用户设置的障碍。

把代理节点搭建在 Cloudflare 家里,使用 Cloudflare 的 IP 就可以正常访问 chat.openai.com 了。

免费的东西,建议人手一个。

节点搭建

  1. 登录 Cloudflare

    https://www.cloudflare.com/

  2. 按下图操作依次执行

  1. 进入到编辑代码界面后,删除默认内容,然后复制下面的代码并粘贴到 worker.js 代码框中

2024-07-21 更新:

这种白嫖的教程总是很容易失效,往往是白嫖客和官方之间的循环对抗。

在我写这篇文章的时候,下面两个代码都是可用的,但是未来可能会失效。

点击查看代码 1:

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
// <!--GAMFC-->version base on commit 43fad05dcdae3b723c53c226f8181fc5bd47223e, time is 2023-06-22 15:20:05 UTC<!--GAMFC-END-->.
// @ts-ignore
import { connect } from 'cloudflare:sockets';

// How to generate your own UUID:
// [Windows] Press "Win + R", input cmd and run: Powershell -NoExit -Command "[guid]::NewGuid()"
let userID = '❗❗❗填写这里❗❗❗';

let proxyIP = '';

let sub = '';// 留空则使用内置订阅
let subconverter = 'subapi-loadbalancing.pages.dev';// clash订阅转换后端,目前使用CM的订阅转换功能。自带虚假uuid和host订阅。
let subconfig = "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online.ini"; //订阅配置文件

// The user name and password do not contain special characters
// Setting the address will ignore proxyIP
// Example: user:pass@host:port or host:port
let socks5Address = 'wgxls:wgxlsslxgw@uk2.1881997.xyz:44753';

if (!isValidUUID(userID)) {
throw new Error('uuid is not valid');
}

let parsedSocks5Address = {};
let enableSocks = true;

// 虚假uuid和hostname,用于发送给配置生成服务
let fakeUserID ;
let fakeHostName ;
let noTLS = 'false';
const expire = 4102329600;//2099-12-31
let proxyIPs;
let addresses = [];
let addressesapi = [];
let addressesnotls = [];
let addressesnotlsapi = [];
let addressescsv = [];
let DLS = 8;
let FileName = 'edgetunnel';
let BotToken ='';
let ChatID ='';
let proxyhosts = [];//本地代理域名池
let proxyhostsURL = 'https://raw.githubusercontent.com/cmliu/CFcdnVmess2sub/main/proxyhosts';//在线代理域名池URL
let RproxyIP = 'false';
export default {
/**
* @param {import("@cloudflare/workers-types").Request} request
* @param {{UUID: string, PROXYIP: string}} env
* @param {import("@cloudflare/workers-types").ExecutionContext} ctx
* @returns {Promise<Response>}
*/
async fetch(request, env, ctx) {
try {
const UA = request.headers.get('User-Agent') || 'null';
const userAgent = UA.toLowerCase();
userID = (env.UUID || userID).toLowerCase();

const currentDate = new Date();
currentDate.setHours(0, 0, 0, 0);
const timestamp = Math.ceil(currentDate.getTime() / 1000);
const fakeUserIDMD5 = await MD5MD5(`${userID}${timestamp}`);
fakeUserID = fakeUserIDMD5.slice(0, 8) + "-" + fakeUserIDMD5.slice(8, 12) + "-" + fakeUserIDMD5.slice(12, 16) + "-" + fakeUserIDMD5.slice(16, 20) + "-" + fakeUserIDMD5.slice(20);
fakeHostName = fakeUserIDMD5.slice(6, 9) + "." + fakeUserIDMD5.slice(13, 19);
//console.log(`${fakeUserID}\n${fakeHostName}`); // 打印fakeID

proxyIP = env.PROXYIP || proxyIP;
proxyIPs = await ADD(proxyIP);
proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)];
//console.log(proxyIP);
socks5Address = env.SOCKS5 || socks5Address;
sub = env.SUB || sub;
subconverter = env.SUBAPI || subconverter;
subconfig = env.SUBCONFIG || subconfig;
if (socks5Address) {
try {
parsedSocks5Address = socks5AddressParser(socks5Address);
RproxyIP = env.RPROXYIP || 'false';
enableSocks = true;
} catch (err) {
/** @type {Error} */
let e = err;
console.log(e.toString());
RproxyIP = env.RPROXYIP || !proxyIP ? 'true' : 'false';
enableSocks = false;
}
} else {
RproxyIP = env.RPROXYIP || !proxyIP ? 'true' : 'false';
}
if (env.ADD) addresses = await ADD(env.ADD);
if (env.ADDAPI) addressesapi = await ADD(env.ADDAPI);
if (env.ADDNOTLS) addressesnotls = await ADD(env.ADDNOTLS);
if (env.ADDNOTLSAPI) addressesnotlsapi = await ADD(env.ADDNOTLSAPI);
if (env.ADDCSV) addressescsv = await ADD(env.ADDCSV);
DLS = env.DLS || DLS;
BotToken = env.TGTOKEN || BotToken;
ChatID = env.TGID || ChatID;
const upgradeHeader = request.headers.get('Upgrade');
const url = new URL(request.url);
if (url.searchParams.has('sub') && url.searchParams.get('sub') !== '') sub = url.searchParams.get('sub');
if (url.searchParams.has('notls')) noTLS = 'true';
if (!upgradeHeader || upgradeHeader !== 'websocket') {
// const url = new URL(request.url);
switch (url.pathname.toLowerCase()) {
case '/':
const envKey = env.URL302 ? 'URL302' : (env.URL ? 'URL' : null);
if (envKey) {
const URLs = await ADD(env[envKey]);
const URL = URLs[Math.floor(Math.random() * URLs.length)];
return envKey === 'URL302' ? Response.redirect(URL, 302) : fetch(new Request(URL, request));
}
return new Response(JSON.stringify(request.cf, null, 4), { status: 200 });
case `/${fakeUserID}`:
const fakeConfig = await getVLESSConfig(userID, request.headers.get('Host'), sub, 'CF-Workers-SUB', RproxyIP, url);
return new Response(`${fakeConfig}`, { status: 200 });
case '/config': {
await sendMessage(`#获取订阅 ${FileName}`, request.headers.get('CF-Connecting-IP'), `UA: ${UA}</tg-spoiler>\n域名: ${url.hostname}\n<tg-spoiler>入口: ${url.pathname + url.search}</tg-spoiler>`);
if ((!sub || sub == '') && (addresses.length + addressesapi.length + addressesnotls.length + addressesnotlsapi.length + addressescsv.length) == 0){
if (request.headers.get('Host').includes(".workers.dev")) {
sub = 'workervless2sub-f1q.pages.dev';
subconfig = 'https://raw.githubusercontent.com/cmliu/ACL4SSR/main/Clash/config/ACL4SSR_Online.ini';
} else {
sub = 'vless-4ca.pages.dev';
subconfig = "https://raw.githubusercontent.com/cmliu/ACL4SSR/main/Clash/config/ACL4SSR_Online_Full_MultiMode.ini";
}
}
const vlessConfig = await getVLESSConfig(userID, request.headers.get('Host'), sub, UA, RproxyIP, url);
const now = Date.now();
//const timestamp = Math.floor(now / 1000);
const today = new Date(now);
today.setHours(0, 0, 0, 0);
const UD = Math.floor(((now - today.getTime())/86400000) * 24 * 1099511627776 / 2);
let pagesSum = UD;
let workersSum = UD;
let total = 24 * 1099511627776 ;
if (env.CFEMAIL && env.CFKEY){
const email = env.CFEMAIL;
const key = env.CFKEY;
const accountIndex = env.CFID || 0;
const accountId = await getAccountId(email, key);
if (accountId){
const now = new Date()
now.setUTCHours(0, 0, 0, 0)
const startDate = now.toISOString()
const endDate = new Date().toISOString();
const Sum = await getSum(accountId, accountIndex, email, key, startDate, endDate);
pagesSum = Sum[0];
workersSum = Sum[1];
total = 102400 ;
}
}
//console.log(`pagesSum: ${pagesSum}\nworkersSum: ${workersSum}\ntotal: ${total}`);
if (userAgent && userAgent.includes('mozilla')){
return new Response(`${vlessConfig}`, {
status: 200,
headers: {
"Content-Type": "text/plain;charset=utf-8",
"Profile-Update-Interval": "6",
"Subscription-Userinfo": `upload=${pagesSum}; download=${workersSum}; total=${total}; expire=${expire}`,
}
});
} else {
return new Response(`${vlessConfig}`, {
status: 200,
headers: {
"Content-Disposition": `attachment; filename=${FileName}; filename*=utf-8''${encodeURIComponent(FileName)}`,
"Content-Type": "text/plain;charset=utf-8",
"Profile-Update-Interval": "6",
"Subscription-Userinfo": `upload=${pagesSum}; download=${workersSum}; total=${total}; expire=${expire}`,
}
});
}
}
default:
return new Response('Not found', { status: 404 });
}
} else {
proxyIP = url.searchParams.get('proxyip') || proxyIP;
if (new RegExp('/proxyip=', 'i').test(url.pathname)) proxyIP = url.pathname.toLowerCase().split('/proxyip=')[1];
else if (new RegExp('/proxyip.', 'i').test(url.pathname)) proxyIP = `proxyip.${url.pathname.toLowerCase().split("/proxyip.")[1]}`;

socks5Address = url.searchParams.get('socks5') || socks5Address;
if (new RegExp('/socks5=', 'i').test(url.pathname)) socks5Address = url.pathname.split('5=')[1];
else if (new RegExp('/socks://', 'i').test(url.pathname) || new RegExp('/socks5://', 'i').test(url.pathname)) {
socks5Address = url.pathname.split('://')[1].split('#')[0];
if (socks5Address.includes('@')){
let userPassword = socks5Address.split('@')[0];
const base64Regex = /^(?:[A-Z0-9+/]{4})*(?:[A-Z0-9+/]{2}==|[A-Z0-9+/]{3}=)?$/i;
if (base64Regex.test(userPassword) && !userPassword.includes(':')) userPassword = atob(userPassword);
socks5Address = `${userPassword}@${socks5Address.split('@')[1]}`;
}
}
if (socks5Address) {
try {
parsedSocks5Address = socks5AddressParser(socks5Address);
enableSocks = true;
} catch (err) {
/** @type {Error} */
let e = err;
console.log(e.toString());
enableSocks = false;
}
} else {
enableSocks = false;
}
return await vlessOverWSHandler(request);
}
} catch (err) {
/** @type {Error} */ let e = err;
return new Response(e.toString());
}
},
};

/**
* 处理 VLESS over WebSocket 的请求
* @param {import("@cloudflare/workers-types").Request} request
*/
async function vlessOverWSHandler(request) {

/** @type {import("@cloudflare/workers-types").WebSocket[]} */
// @ts-ignore
const webSocketPair = new WebSocketPair();
const [client, webSocket] = Object.values(webSocketPair);

// 接受 WebSocket 连接
webSocket.accept();

let address = '';
let portWithRandomLog = '';
// 日志函数,用于记录连接信息
const log = (/** @type {string} */ info, /** @type {string | undefined} */ event) => {
console.log(`[${address}:${portWithRandomLog}] ${info}`, event || '');
};
// 获取早期数据头部,可能包含了一些初始化数据
const earlyDataHeader = request.headers.get('sec-websocket-protocol') || '';

// 创建一个可读的 WebSocket 流,用于接收客户端数据
const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log);

/** @type {{ value: import("@cloudflare/workers-types").Socket | null}}*/
// 用于存储远程 Socket 的包装器
let remoteSocketWapper = {
value: null,
};
// 标记是否为 DNS 查询
let isDns = false;

// WebSocket 数据流向远程服务器的管道
readableWebSocketStream.pipeTo(new WritableStream({
async write(chunk, controller) {
if (isDns) {
// 如果是 DNS 查询,调用 DNS 处理函数
return await handleDNSQuery(chunk, webSocket, null, log);
}
if (remoteSocketWapper.value) {
// 如果已有远程 Socket,直接写入数据
const writer = remoteSocketWapper.value.writable.getWriter()
await writer.write(chunk);
writer.releaseLock();
return;
}

// 处理 VLESS 协议头部
const {
hasError,
message,
addressType,
portRemote = 443,
addressRemote = '',
rawDataIndex,
vlessVersion = new Uint8Array([0, 0]),
isUDP,
} = processVlessHeader(chunk, userID);
// 设置地址和端口信息,用于日志
address = addressRemote;
portWithRandomLog = `${portRemote}--${Math.random()} ${isUDP ? 'udp ' : 'tcp '} `;
if (hasError) {
// 如果有错误,抛出异常
throw new Error(message);
return;
}
// 如果是 UDP 且端口不是 DNS 端口(53),则关闭连接
if (isUDP) {
if (portRemote === 53) {
isDns = true;
} else {
throw new Error('UDP 代理仅对 DNS(53 端口)启用');
return;
}
}
// 构建 VLESS 响应头部
const vlessResponseHeader = new Uint8Array([vlessVersion[0], 0]);
// 获取实际的客户端数据
const rawClientData = chunk.slice(rawDataIndex);

if (isDns) {
// 如果是 DNS 查询,调用 DNS 处理函数
return handleDNSQuery(rawClientData, webSocket, vlessResponseHeader, log);
}
// 处理 TCP 出站连接
log(`处理 TCP 出站连接 ${addressRemote}:${portRemote}`);
handleTCPOutBound(remoteSocketWapper, addressType, addressRemote, portRemote, rawClientData, webSocket, vlessResponseHeader, log);
},
close() {
log(`readableWebSocketStream 已关闭`);
},
abort(reason) {
log(`readableWebSocketStream 已中止`, JSON.stringify(reason));
},
})).catch((err) => {
log('readableWebSocketStream 管道错误', err);
});

// 返回一个 WebSocket 升级的响应
return new Response(null, {
status: 101,
// @ts-ignore
webSocket: client,
});
}

/**
* 处理出站 TCP 连接。
*
* @param {any} remoteSocket 远程 Socket 的包装器,用于存储实际的 Socket 对象
* @param {number} addressType 要连接的远程地址类型(如 IP 类型:IPv4 或 IPv6)
* @param {string} addressRemote 要连接的远程地址
* @param {number} portRemote 要连接的远程端口
* @param {Uint8Array} rawClientData 要写入的原始客户端数据
* @param {import("@cloudflare/workers-types").WebSocket} webSocket 用于传递远程 Socket 的 WebSocket
* @param {Uint8Array} vlessResponseHeader VLESS 响应头部
* @param {function} log 日志记录函数
* @returns {Promise<void>} 异步操作的 Promise
*/
async function handleTCPOutBound(remoteSocket, addressType, addressRemote, portRemote, rawClientData, webSocket, vlessResponseHeader, log,) {
/**
* 连接远程服务器并写入数据
* @param {string} address 要连接的地址
* @param {number} port 要连接的端口
* @param {boolean} socks 是否使用 SOCKS5 代理连接
* @returns {Promise<import("@cloudflare/workers-types").Socket>} 连接后的 TCP Socket
*/
async function connectAndWrite(address, port, socks = false) {
/** @type {import("@cloudflare/workers-types").Socket} */
log(`connected to ${address}:${port}`);
//if (/^(?:(?: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]?)$/.test(address)) address = `${atob('d3d3Lg==')}${address}${atob('LmlwLjA5MDIyNy54eXo=')}`;
// 如果指定使用 SOCKS5 代理,则通过 SOCKS5 协议连接;否则直接连接
const tcpSocket = socks ? await socks5Connect(addressType, address, port, log)
: connect({
hostname: address,
port: port,
});
remoteSocket.value = tcpSocket;
//log(`connected to ${address}:${port}`);
const writer = tcpSocket.writable.getWriter();
// 首次写入,通常是 TLS 客户端 Hello 消息
await writer.write(rawClientData);
writer.releaseLock();
return tcpSocket;
}

/**
* 重试函数:当 Cloudflare 的 TCP Socket 没有传入数据时,我们尝试重定向 IP
* 这可能是因为某些网络问题导致的连接失败
*/
async function retry() {
if (enableSocks) {
// 如果启用了 SOCKS5,通过 SOCKS5 代理重试连接
tcpSocket = await connectAndWrite(addressRemote, portRemote, true);
} else {
// 否则,尝试使用预设的代理 IP(如果有)或原始地址重试连接
if (!proxyIP || proxyIP == '') proxyIP = atob('cHJveHlpcC5meHhrLmRlZHluLmlv');
tcpSocket = await connectAndWrite(proxyIP || addressRemote, portRemote);
}
// 无论重试是否成功,都要关闭 WebSocket(可能是为了重新建立连接)
tcpSocket.closed.catch(error => {
console.log('retry tcpSocket closed error', error);
}).finally(() => {
safeCloseWebSocket(webSocket);
})
// 建立从远程 Socket 到 WebSocket 的数据流
remoteSocketToWS(tcpSocket, webSocket, vlessResponseHeader, null, log);
}

// 首次尝试连接远程服务器
let tcpSocket = await connectAndWrite(addressRemote, portRemote);

// 当远程 Socket 就绪时,将其传递给 WebSocket
// 建立从远程服务器到 WebSocket 的数据流,用于将远程服务器的响应发送回客户端
// 如果连接失败或无数据,retry 函数将被调用进行重试
remoteSocketToWS(tcpSocket, webSocket, vlessResponseHeader, retry, log);
}

/**
* 将 WebSocket 转换为可读流(ReadableStream)
* @param {import("@cloudflare/workers-types").WebSocket} webSocketServer 服务器端的 WebSocket 对象
* @param {string} earlyDataHeader WebSocket 0-RTT(零往返时间)的早期数据头部
* @param {(info: string)=> void} log 日志记录函数,用于记录 WebSocket 0-RTT 相关信息
* @returns {ReadableStream} 由 WebSocket 消息组成的可读流
*/
function makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) {
// 标记可读流是否已被取消
let readableStreamCancel = false;

// 创建一个新的可读流
const stream = new ReadableStream({
// 当流开始时的初始化函数
start(controller) {
// 监听 WebSocket 的消息事件
webSocketServer.addEventListener('message', (event) => {
// 如果流已被取消,不再处理新消息
if (readableStreamCancel) {
return;
}
const message = event.data;
// 将消息加入流的队列中
controller.enqueue(message);
});

// 监听 WebSocket 的关闭事件
// 注意:这个事件意味着客户端关闭了客户端 -> 服务器的流
// 但是,服务器 -> 客户端的流仍然打开,直到在服务器端调用 close()
// WebSocket 协议要求在每个方向上都要发送单独的关闭消息,以完全关闭 Socket
webSocketServer.addEventListener('close', () => {
// 客户端发送了关闭信号,需要关闭服务器端
safeCloseWebSocket(webSocketServer);
// 如果流未被取消,则关闭控制器
if (readableStreamCancel) {
return;
}
controller.close();
});

// 监听 WebSocket 的错误事件
webSocketServer.addEventListener('error', (err) => {
log('WebSocket 服务器发生错误');
// 将错误传递给控制器
controller.error(err);
});

// 处理 WebSocket 0-RTT(零往返时间)的早期数据
// 0-RTT 允许在完全建立连接之前发送数据,提高了效率
const { earlyData, error } = base64ToArrayBuffer(earlyDataHeader);
if (error) {
// 如果解码早期数据时出错,将错误传递给控制器
controller.error(error);
} else if (earlyData) {
// 如果有早期数据,将其加入流的队列中
controller.enqueue(earlyData);
}
},

// 当使用者从流中拉取数据时调用
pull(controller) {
// 这里可以实现反压机制
// 如果 WebSocket 可以在流满时停止读取,我们就可以实现反压
// 参考:https://streams.spec.whatwg.org/#example-rs-push-backpressure
},

// 当流被取消时调用
cancel(reason) {
// 流被取消的几种情况:
// 1. 当管道的 WritableStream 有错误时,这个取消函数会被调用,所以在这里处理 WebSocket 服务器的关闭
// 2. 如果 ReadableStream 被取消,所有 controller.close/enqueue 都需要跳过
// 3. 但是经过测试,即使 ReadableStream 被取消,controller.error 仍然有效
if (readableStreamCancel) {
return;
}
log(`可读流被取消,原因是 ${reason}`);
readableStreamCancel = true;
// 安全地关闭 WebSocket
safeCloseWebSocket(webSocketServer);
}
});

return stream;
}

// https://xtls.github.io/development/protocols/vless.html
// https://github.com/zizifn/excalidraw-backup/blob/main/v2ray-protocol.excalidraw

/**
* 解析 VLESS 协议的头部数据
* @param { ArrayBuffer} vlessBuffer VLESS 协议的原始头部数据
* @param {string} userID 用于验证的用户 ID
* @returns {Object} 解析结果,包括是否有错误、错误信息、远程地址信息等
*/
function processVlessHeader(vlessBuffer, userID) {
// 检查数据长度是否足够(至少需要 24 字节)
if (vlessBuffer.byteLength < 24) {
return {
hasError: true,
message: 'invalid data',
};
}

// 解析 VLESS 协议版本(第一个字节)
const version = new Uint8Array(vlessBuffer.slice(0, 1));

let isValidUser = false;
let isUDP = false;

// 验证用户 ID(接下来的 16 个字节)
if (stringify(new Uint8Array(vlessBuffer.slice(1, 17))) === userID) {
isValidUser = true;
}
// 如果用户 ID 无效,返回错误
if (!isValidUser) {
return {
hasError: true,
message: `invalid user ${(new Uint8Array(vlessBuffer.slice(1, 17)))}`,
};
}

// 获取附加选项的长度(第 17 个字节)
const optLength = new Uint8Array(vlessBuffer.slice(17, 18))[0];
// 暂时跳过附加选项

// 解析命令(紧跟在选项之后的 1 个字节)
// 0x01: TCP, 0x02: UDP, 0x03: MUX(多路复用)
const command = new Uint8Array(
vlessBuffer.slice(18 + optLength, 18 + optLength + 1)
)[0];

// 0x01 TCP
// 0x02 UDP
// 0x03 MUX
if (command === 1) {
// TCP 命令,不需特殊处理
} else if (command === 2) {
// UDP 命令
isUDP = true;
} else {
// 不支持的命令
return {
hasError: true,
message: `command ${command} is not support, command 01-tcp,02-udp,03-mux`,
};
}

// 解析远程端口(大端序,2 字节)
const portIndex = 18 + optLength + 1;
const portBuffer = vlessBuffer.slice(portIndex, portIndex + 2);
// port is big-Endian in raw data etc 80 == 0x005d
const portRemote = new DataView(portBuffer).getUint16(0);

// 解析地址类型和地址
let addressIndex = portIndex + 2;
const addressBuffer = new Uint8Array(
vlessBuffer.slice(addressIndex, addressIndex + 1)
);

// 地址类型:1-IPv4(4字节), 2-域名(可变长), 3-IPv6(16字节)
const addressType = addressBuffer[0];
let addressLength = 0;
let addressValueIndex = addressIndex + 1;
let addressValue = '';

switch (addressType) {
case 1:
// IPv4 地址
addressLength = 4;
// 将 4 个字节转为点分十进制格式
addressValue = new Uint8Array(
vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength)
).join('.');
break;
case 2:
// 域名
// 第一个字节是域名长度
addressLength = new Uint8Array(
vlessBuffer.slice(addressValueIndex, addressValueIndex + 1)
)[0];
addressValueIndex += 1;
// 解码域名
addressValue = new TextDecoder().decode(
vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength)
);
break;
case 3:
// IPv6 地址
addressLength = 16;
const dataView = new DataView(
vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength)
);
// 每 2 字节构成 IPv6 地址的一部分
const ipv6 = [];
for (let i = 0; i < 8; i++) {
ipv6.push(dataView.getUint16(i * 2).toString(16));
}
addressValue = ipv6.join(':');
// seems no need add [] for ipv6
break;
default:
// 无效的地址类型
return {
hasError: true,
message: `invild addressType is ${addressType}`,
};
}

// 确保地址不为空
if (!addressValue) {
return {
hasError: true,
message: `addressValue is empty, addressType is ${addressType}`,
};
}

// 返回解析结果
return {
hasError: false,
addressRemote: addressValue, // 解析后的远程地址
addressType, // 地址类型
portRemote, // 远程端口
rawDataIndex: addressValueIndex + addressLength, // 原始数据的实际起始位置
vlessVersion: version, // VLESS 协议版本
isUDP, // 是否是 UDP 请求
};
}


/**
* 将远程 Socket 的数据转发到 WebSocket
*
* @param {import("@cloudflare/workers-types").Socket} remoteSocket 远程服务器的 Socket 连接
* @param {import("@cloudflare/workers-types").WebSocket} webSocket 客户端的 WebSocket 连接
* @param {ArrayBuffer} vlessResponseHeader VLESS 协议的响应头部
* @param {(() => Promise<void>) | null} retry 重试函数,当没有数据时调用
* @param {*} log 日志函数
*/
async function remoteSocketToWS(remoteSocket, webSocket, vlessResponseHeader, retry, log) {
// 将数据从远程服务器转发到 WebSocket
let remoteChunkCount = 0;
let chunks = [];
/** @type {ArrayBuffer | null} */
let vlessHeader = vlessResponseHeader;
let hasIncomingData = false; // 检查远程 Socket 是否有传入数据

// 使用管道将远程 Socket 的可读流连接到一个可写流
await remoteSocket.readable
.pipeTo(
new WritableStream({
start() {
// 初始化时不需要任何操作
},
/**
* 处理每个数据块
* @param {Uint8Array} chunk 数据块
* @param {*} controller 控制器
*/
async write(chunk, controller) {
hasIncomingData = true; // 标记已收到数据
// remoteChunkCount++; // 用于流量控制,现在似乎不需要了

// 检查 WebSocket 是否处于开放状态
if (webSocket.readyState !== WS_READY_STATE_OPEN) {
controller.error(
'webSocket.readyState is not open, maybe close'
);
}

if (vlessHeader) {
// 如果有 VLESS 响应头部,将其与第一个数据块一起发送
webSocket.send(await new Blob([vlessHeader, chunk]).arrayBuffer());
vlessHeader = null; // 清空头部,之后不再发送
} else {
// 直接发送数据块
// 以前这里有流量控制代码,限制大量数据的发送速率
// 但现在 Cloudflare 似乎已经修复了这个问题
// if (remoteChunkCount > 20000) {
// // cf one package is 4096 byte(4kb), 4096 * 20000 = 80M
// await delay(1);
// }
webSocket.send(chunk);
}
},
close() {
// 当远程连接的可读流关闭时
log(`remoteConnection!.readable is close with hasIncomingData is ${hasIncomingData}`);
// 不需要主动关闭 WebSocket,因为这可能导致 HTTP ERR_CONTENT_LENGTH_MISMATCH 问题
// 客户端无论如何都会发送关闭事件
// safeCloseWebSocket(webSocket);
},
abort(reason) {
// 当远程连接的可读流中断时
console.error(`remoteConnection!.readable abort`, reason);
},
})
)
.catch((error) => {
// 捕获并记录任何异常
console.error(
`remoteSocketToWS has exception `,
error.stack || error
);
// 发生错误时安全地关闭 WebSocket
safeCloseWebSocket(webSocket);
});

// 处理 Cloudflare 连接 Socket 的特殊错误情况
// 1. Socket.closed 将有错误
// 2. Socket.readable 将关闭,但没有任何数据
if (hasIncomingData === false && retry) {
log(`retry`);
retry(); // 调用重试函数,尝试重新建立连接
}
}

/**
* 将 Base64 编码的字符串转换为 ArrayBuffer
*
* @param {string} base64Str Base64 编码的输入字符串
* @returns {{ earlyData: ArrayBuffer | undefined, error: Error | null }} 返回解码后的 ArrayBuffer 或错误
*/
function base64ToArrayBuffer(base64Str) {
// 如果输入为空,直接返回空结果
if (!base64Str) {
return { error: null };
}
try {
// Go 语言使用了 URL 安全的 Base64 变体(RFC 4648)
// 这种变体使用 '-' 和 '_' 来代替标准 Base64 中的 '+' 和 '/'
// JavaScript 的 atob 函数不直接支持这种变体,所以我们需要先转换
base64Str = base64Str.replace(/-/g, '+').replace(/_/g, '/');

// 使用 atob 函数解码 Base64 字符串
// atob 将 Base64 编码的 ASCII 字符串转换为原始的二进制字符串
const decode = atob(base64Str);

// 将二进制字符串转换为 Uint8Array
// 这是通过遍历字符串中的每个字符并获取其 Unicode 编码值(0-255)来完成的
const arryBuffer = Uint8Array.from(decode, (c) => c.charCodeAt(0));

// 返回 Uint8Array 的底层 ArrayBuffer
// 这是实际的二进制数据,可以用于网络传输或其他二进制操作
return { earlyData: arryBuffer.buffer, error: null };
} catch (error) {
// 如果在任何步骤中出现错误(如非法 Base64 字符),则返回错误
return { error };
}
}

/**
* 这不是真正的 UUID 验证,而是一个简化的版本
* @param {string} uuid 要验证的 UUID 字符串
* @returns {boolean} 如果字符串匹配 UUID 格式则返回 true,否则返回 false
*/
function isValidUUID(uuid) {
// 定义一个正则表达式来匹配 UUID 格式
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;

// 使用正则表达式测试 UUID 字符串
return uuidRegex.test(uuid);
}

// WebSocket 的两个重要状态常量
const WS_READY_STATE_OPEN = 1; // WebSocket 处于开放状态,可以发送和接收消息
const WS_READY_STATE_CLOSING = 2; // WebSocket 正在关闭过程中

/**
* 安全地关闭 WebSocket 连接
* 通常,WebSocket 在关闭时不会抛出异常,但为了以防万一,我们还是用 try-catch 包裹
* @param {import("@cloudflare/workers-types").WebSocket} socket 要关闭的 WebSocket 对象
*/
function safeCloseWebSocket(socket) {
try {
// 只有在 WebSocket 处于开放或正在关闭状态时才调用 close()
// 这避免了在已关闭或连接中的 WebSocket 上调用 close()
if (socket.readyState === WS_READY_STATE_OPEN || socket.readyState === WS_READY_STATE_CLOSING) {
socket.close();
}
} catch (error) {
// 记录任何可能发生的错误,虽然按照规范不应该有错误
console.error('safeCloseWebSocket error', error);
}
}

// 预计算 0-255 每个字节的十六进制表示
const byteToHex = [];
for (let i = 0; i < 256; ++i) {
// (i + 256).toString(16) 确保总是得到两位数的十六进制
// .slice(1) 删除前导的 "1",只保留两位十六进制数
byteToHex.push((i + 256).toString(16).slice(1));
}

/**
* 快速地将字节数组转换为 UUID 字符串,不进行有效性检查
* 这是一个底层函数,直接操作字节,不做任何验证
* @param {Uint8Array} arr 包含 UUID 字节的数组
* @param {number} offset 数组中 UUID 开始的位置,默认为 0
* @returns {string} UUID 字符串
*/
function unsafeStringify(arr, offset = 0) {
// 直接从查找表中获取每个字节的十六进制表示,并拼接成 UUID 格式
// 8-4-4-4-12 的分组是通过精心放置的连字符 "-" 实现的
// toLowerCase() 确保整个 UUID 是小写的
return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" +
byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" +
byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" +
byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" +
byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] +
byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}

/**
* 将字节数组转换为 UUID 字符串,并验证其有效性
* 这是一个安全的函数,它确保返回的 UUID 格式正确
* @param {Uint8Array} arr 包含 UUID 字节的数组
* @param {number} offset 数组中 UUID 开始的位置,默认为 0
* @returns {string} 有效的 UUID 字符串
* @throws {TypeError} 如果生成的 UUID 字符串无效
*/
function stringify(arr, offset = 0) {
// 使用不安全的函数快速生成 UUID 字符串
const uuid = unsafeStringify(arr, offset);
// 验证生成的 UUID 是否有效
if (!isValidUUID(uuid)) {
// 原:throw TypeError("Stringified UUID is invalid");
throw TypeError(`生成的 UUID 不符合规范 ${uuid}`);
//uuid = userID;
}
return uuid;
}

/**
* 处理 DNS 查询的函数
* @param {ArrayBuffer} udpChunk - 客户端发送的 DNS 查询数据
* @param {import("@cloudflare/workers-types").WebSocket} webSocket - 与客户端建立的 WebSocket 连接
* @param {ArrayBuffer} vlessResponseHeader - VLESS 协议的响应头部数据
* @param {(string)=> void} log - 日志记录函数
*/
async function handleDNSQuery(udpChunk, webSocket, vlessResponseHeader, log) {
// 无论客户端发送到哪个 DNS 服务器,我们总是使用硬编码的服务器
// 因为有些 DNS 服务器不支持 DNS over TCP
try {
// 选用 Google 的 DNS 服务器(注:后续可能会改为 Cloudflare 的 1.1.1.1)
const dnsServer = '8.8.4.4'; // 在 Cloudflare 修复连接自身 IP 的 bug 后,将改为 1.1.1.1
const dnsPort = 53; // DNS 服务的标准端口

/** @type {ArrayBuffer | null} */
let vlessHeader = vlessResponseHeader; // 保存 VLESS 响应头部,用于后续发送

/** @type {import("@cloudflare/workers-types").Socket} */
// 与指定的 DNS 服务器建立 TCP 连接
const tcpSocket = connect({
hostname: dnsServer,
port: dnsPort,
});

log(`连接到 ${dnsServer}:${dnsPort}`); // 记录连接信息
const writer = tcpSocket.writable.getWriter();
await writer.write(udpChunk); // 将客户端的 DNS 查询数据发送给 DNS 服务器
writer.releaseLock(); // 释放写入器,允许其他部分使用

// 将从 DNS 服务器接收到的响应数据通过 WebSocket 发送回客户端
await tcpSocket.readable.pipeTo(new WritableStream({
async write(chunk) {
if (webSocket.readyState === WS_READY_STATE_OPEN) {
if (vlessHeader) {
// 如果有 VLESS 头部,则将其与 DNS 响应数据合并后发送
webSocket.send(await new Blob([vlessHeader, chunk]).arrayBuffer());
vlessHeader = null; // 头部只发送一次,之后置为 null
} else {
// 否则直接发送 DNS 响应数据
webSocket.send(chunk);
}
}
},
close() {
log(`DNS 服务器(${dnsServer}) TCP 连接已关闭`); // 记录连接关闭信息
},
abort(reason) {
console.error(`DNS 服务器(${dnsServer}) TCP 连接异常中断`, reason); // 记录异常中断原因
},
}));
} catch (error) {
// 捕获并记录任何可能发生的错误
console.error(
`handleDNSQuery 函数发生异常,错误信息: ${error.message}`
);
}
}

/**
* 建立 SOCKS5 代理连接
* @param {number} addressType 目标地址类型(1: IPv4, 2: 域名, 3: IPv6)
* @param {string} addressRemote 目标地址(可以是 IP 或域名)
* @param {number} portRemote 目标端口
* @param {function} log 日志记录函数
*/
async function socks5Connect(addressType, addressRemote, portRemote, log) {
const { username, password, hostname, port } = parsedSocks5Address;
// 连接到 SOCKS5 代理服务器
const socket = connect({
hostname, // SOCKS5 服务器的主机名
port, // SOCKS5 服务器的端口
});

// 请求头格式(Worker -> SOCKS5 服务器):
// +----+----------+----------+
// |VER | NMETHODS | METHODS |
// +----+----------+----------+
// | 1 | 1 | 1 to 255 |
// +----+----------+----------+

// https://en.wikipedia.org/wiki/SOCKS#SOCKS5
// METHODS 字段的含义:
// 0x00 不需要认证
// 0x02 用户名/密码认证 https://datatracker.ietf.org/doc/html/rfc1929
const socksGreeting = new Uint8Array([5, 2, 0, 2]);
// 5: SOCKS5 版本号, 2: 支持的认证方法数, 0和2: 两种认证方法(无认证和用户名/密码)

const writer = socket.writable.getWriter();

await writer.write(socksGreeting);
log('已发送 SOCKS5 问候消息');

const reader = socket.readable.getReader();
const encoder = new TextEncoder();
let res = (await reader.read()).value;
// 响应格式(SOCKS5 服务器 -> Worker):
// +----+--------+
// |VER | METHOD |
// +----+--------+
// | 1 | 1 |
// +----+--------+
if (res[0] !== 0x05) {
log(`SOCKS5 服务器版本错误: 收到 ${res[0]},期望是 5`);
return;
}
if (res[1] === 0xff) {
log("服务器不接受任何认证方法");
return;
}

// 如果返回 0x0502,表示需要用户名/密码认证
if (res[1] === 0x02) {
log("SOCKS5 服务器需要认证");
if (!username || !password) {
log("请提供用户名和密码");
return;
}
// 认证请求格式:
// +----+------+----------+------+----------+
// |VER | ULEN | UNAME | PLEN | PASSWD |
// +----+------+----------+------+----------+
// | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
// +----+------+----------+------+----------+
const authRequest = new Uint8Array([
1, // 认证子协议版本
username.length, // 用户名长度
...encoder.encode(username), // 用户名
password.length, // 密码长度
...encoder.encode(password) // 密码
]);
await writer.write(authRequest);
res = (await reader.read()).value;
// 期望返回 0x0100 表示认证成功
if (res[0] !== 0x01 || res[1] !== 0x00) {
log("SOCKS5 服务器认证失败");
return;
}
}

// 请求数据格式(Worker -> SOCKS5 服务器):
// +----+-----+-------+------+----------+----------+
// |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
// ATYP: 地址类型
// 0x01: IPv4 地址
// 0x03: 域名
// 0x04: IPv6 地址
// DST.ADDR: 目标地址
// DST.PORT: 目标端口(网络字节序)

// addressType
// 1 --> IPv4 地址长度 = 4
// 2 --> 域名
// 3 --> IPv6 地址长度 = 16
let DSTADDR; // DSTADDR = ATYP + DST.ADDR
switch (addressType) {
case 1: // IPv4
DSTADDR = new Uint8Array(
[1, ...addressRemote.split('.').map(Number)]
);
break;
case 2: // 域名
DSTADDR = new Uint8Array(
[3, addressRemote.length, ...encoder.encode(addressRemote)]
);
break;
case 3: // IPv6
DSTADDR = new Uint8Array(
[4, ...addressRemote.split(':').flatMap(x => [parseInt(x.slice(0, 2), 16), parseInt(x.slice(2), 16)])]
);
break;
default:
log(`无效的地址类型: ${addressType}`);
return;
}
const socksRequest = new Uint8Array([5, 1, 0, ...DSTADDR, portRemote >> 8, portRemote & 0xff]);
// 5: SOCKS5版本, 1: 表示CONNECT请求, 0: 保留字段
// ...DSTADDR: 目标地址, portRemote >> 8 和 & 0xff: 将端口转为网络字节序
await writer.write(socksRequest);
log('已发送 SOCKS5 请求');

res = (await reader.read()).value;
// 响应格式(SOCKS5 服务器 -> Worker):
// +----+-----+-------+------+----------+----------+
// |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
if (res[1] === 0x00) {
log("SOCKS5 连接已建立");
} else {
log("SOCKS5 连接建立失败");
return;
}
writer.releaseLock();
reader.releaseLock();
return socket;
}


/**
* SOCKS5 代理地址解析器
* 此函数用于解析 SOCKS5 代理地址字符串,提取出用户名、密码、主机名和端口号
*
* @param {string} address SOCKS5 代理地址,格式可以是:
* - "username:password@hostname:port" (带认证)
* - "hostname:port" (不需认证)
* - "username:password@[ipv6]:port" (IPv6 地址需要用方括号括起来)
*/
function socks5AddressParser(address) {
// 使用 "@" 分割地址,分为认证部分和服务器地址部分
// reverse() 是为了处理没有认证信息的情况,确保 latter 总是包含服务器地址
let [latter, former] = address.split("@").reverse();
let username, password, hostname, port;

// 如果存在 former 部分,说明提供了认证信息
if (former) {
const formers = former.split(":");
if (formers.length !== 2) {
throw new Error('无效的 SOCKS 地址格式:认证部分必须是 "username:password" 的形式');
}
[username, password] = formers;
}

// 解析服务器地址部分
const latters = latter.split(":");
// 从末尾提取端口号(因为 IPv6 地址中也包含冒号)
port = Number(latters.pop());
if (isNaN(port)) {
throw new Error('无效的 SOCKS 地址格式:端口号必须是数字');
}

// 剩余部分就是主机名(可能是域名、IPv4 或 IPv6 地址)
hostname = latters.join(":");

// 处理 IPv6 地址的特殊情况
// IPv6 地址包含多个冒号,所以必须用方括号括起来,如 [2001:db8::1]
const regex = /^\[.*\]$/;
if (hostname.includes(":") && !regex.test(hostname)) {
throw new Error('无效的 SOCKS 地址格式:IPv6 地址必须用方括号括起来,如 [2001:db8::1]');
}

//if (/^(?:(?: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]?)$/.test(hostname)) hostname = `${atob('d3d3Lg==')}${hostname}${atob('LmlwLjA5MDIyNy54eXo=')}`;
// 返回解析后的结果
return {
username, // 用户名,如果没有则为 undefined
password, // 密码,如果没有则为 undefined
hostname, // 主机名,可以是域名、IPv4 或 IPv6 地址
port, // 端口号,已转换为数字类型
}
}

/**
* 恢复被伪装的信息
* 这个函数用于将内容中的假用户ID和假主机名替换回真实的值
*
* @param {string} content 需要处理的内容
* @param {string} userID 真实的用户ID
* @param {string} hostName 真实的主机名
* @param {boolean} isBase64 内容是否是Base64编码的
* @returns {string} 恢复真实信息后的内容
*/
function revertFakeInfo(content, userID, hostName, isBase64) {
if (isBase64) content = atob(content); // 如果内容是Base64编码的,先解码

// 使用正则表达式全局替换('g'标志)
// 将所有出现的假用户ID和假主机名替换为真实的值
content = content.replace(new RegExp(fakeUserID, 'g'), userID)
.replace(new RegExp(fakeHostName, 'g'), hostName);

if (isBase64) content = btoa(content); // 如果原内容是Base64编码的,处理完后再次编码

return content;
}

/**
* 双重MD5哈希函数
* 这个函数对输入文本进行两次MD5哈希,增强安全性
* 第二次哈希使用第一次哈希结果的一部分作为输入
*
* @param {string} text 要哈希的文本
* @returns {Promise<string>} 双重哈希后的小写十六进制字符串
*/
async function MD5MD5(text) {
const encoder = new TextEncoder();

// 第一次MD5哈希
const firstPass = await crypto.subtle.digest('MD5', encoder.encode(text));
const firstPassArray = Array.from(new Uint8Array(firstPass));
const firstHex = firstPassArray.map(b => b.toString(16).padStart(2, '0')).join('');

// 第二次MD5哈希,使用第一次哈希结果的中间部分(索引7到26)
const secondPass = await crypto.subtle.digest('MD5', encoder.encode(firstHex.slice(7, 27)));
const secondPassArray = Array.from(new Uint8Array(secondPass));
const secondHex = secondPassArray.map(b => b.toString(16).padStart(2, '0')).join('');

return secondHex.toLowerCase(); // 返回小写的十六进制字符串
}

/**
* 解析并清理环境变量中的地址列表
* 这个函数用于处理包含多个地址的环境变量
* 它会移除所有的空白字符、引号等,并将地址列表转换为数组
*
* @param {string} envadd 包含地址列表的环境变量值
* @returns {Promise<string[]>} 清理和分割后的地址数组
*/
async function ADD(envadd) {
// 将制表符、双引号、单引号和换行符都替换为逗号
// 然后将连续的多个逗号替换为单个逗号
var addtext = envadd.replace(/[ |"'\r\n]+/g, ',').replace(/,+/g, ',');

// 删除开头和结尾的逗号(如果有的话)
if (addtext.charAt(0) == ',') addtext = addtext.slice(1);
if (addtext.charAt(addtext.length - 1) == ',') addtext = addtext.slice(0, addtext.length - 1);

// 使用逗号分割字符串,得到地址数组
const add = addtext.split(',');

return add;
}

const 啥啥啥_写的这是啥啊 = 'dmxlc3M=';
function 配置信息(UUID, 域名地址) {
const 协议类型 = atob(啥啥啥_写的这是啥啊);

const 别名 = 域名地址;
let 地址 = 域名地址;
let 端口 = 443;

const 用户ID = UUID;
const 加密方式 = 'none';

const 传输层协议 = 'ws';
const 伪装域名 = 域名地址;
const 路径 = '/?ed=2560';

let 传输层安全 = ['tls',true];
const SNI = 域名地址;
const 指纹 = 'randomized';

if (域名地址.includes('.workers.dev')){
地址 = 'www.wto.org';
端口 = 80 ;
传输层安全 = ['',false];
}

const v2ray = `${协议类型}://${用户ID}@${地址}:${端口}?encryption=${加密方式}&security=${传输层安全[0]}&sni=${SNI}&fp=${指纹}&type=${传输层协议}&host=${伪装域名}&path=${encodeURIComponent(路径)}#${encodeURIComponent(别名)}`;
const clash = `- type: ${协议类型}
name: ${别名}
server: ${地址}
port: ${端口}
uuid: ${用户ID}
network: ${传输层协议}
tls: ${传输层安全[1]}
udp: false
sni: ${SNI}
client-fingerprint: ${指纹}
ws-opts:
path: "${路径}"
headers:
host: ${伪装域名}`;
return [v2ray,clash];
}

let subParams = ['sub','base64','b64','clash','singbox','sb'];

/**
* @param {string} userID
* @param {string | null} hostName
* @param {string} sub
* @param {string} UA
* @returns {Promise<string>}
*/
async function getVLESSConfig(userID, hostName, sub, UA, RproxyIP, _url) {
const userAgent = UA.toLowerCase();
const Config = 配置信息(userID , hostName);
const v2ray = Config[0];
const clash = Config[1];
let proxyhost = "";
if(hostName.includes(".workers.dev") || hostName.includes(".pages.dev")){
if ( proxyhostsURL && (!proxyhosts || proxyhosts.length == 0)) {
try {
const response = await fetch(proxyhostsURL);

if (!response.ok) {
console.error('获取地址时出错:', response.status, response.statusText);
return; // 如果有错误,直接返回
}

const text = await response.text();
const lines = text.split('\n');
// 过滤掉空行或只包含空白字符的行
const nonEmptyLines = lines.filter(line => line.trim() !== '');

proxyhosts = proxyhosts.concat(nonEmptyLines);
} catch (error) {
//console.error('获取地址时出错:', error);
}
}
if (proxyhosts.length != 0) proxyhost = proxyhosts[Math.floor(Math.random() * proxyhosts.length)] + "/";
}

if ( userAgent.includes('mozilla') && !subParams.some(_searchParams => _url.searchParams.has(_searchParams))) {
let 订阅器 = `自动获取ProxyIP: ${RproxyIP}`;
if (!sub || sub == '') {
if (!proxyIP || proxyIP =='') {
订阅器 = '当前使用的ProxyIP为空, 推荐您设置 proxyIP/PROXYIP !!!';
} else {
订阅器 = `当前使用的ProxyIP: ${proxyIPs.join(', ')}`;
}
} else if (RproxyIP != 'true'){
if (enableSocks) 订阅器 += `, 当前使用的Socks5: ${parsedSocks5Address.hostname}:${String(parsedSocks5Address.port)}`;
else 订阅器 += `, 当前使用的ProxyIP: ${proxyIPs.join(', ')}`;
}
return `
################################################################
${订阅器}
---------------------------------------------------------------
################################################################
v2ray
---------------------------------------------------------------
${v2ray}
---------------------------------------------------------------
################################################################
clash-meta
---------------------------------------------------------------
${clash}
---------------------------------------------------------------

`;
} else {
if (typeof fetch != 'function') {
return 'Error: fetch is not available in this environment.';
}

let newAddressesapi ;
let newAddressescsv ;
let newAddressesnotlsapi;
let newAddressesnotlscsv;

// 如果是使用默认域名,则改成一个workers的域名,订阅器会加上代理
if (hostName.includes(".workers.dev")){
fakeHostName = `${fakeHostName}.workers.dev`;
newAddressesnotlsapi = await getAddressesapi(addressesnotlsapi);
newAddressesnotlscsv = await getAddressescsv('FALSE');
} else if (hostName.includes(".pages.dev")){
fakeHostName = `${fakeHostName}.pages.dev`;
} else if (hostName.includes("worker") || hostName.includes("notls") || noTLS == 'true'){
fakeHostName = `notls.${fakeHostName}.net`;
newAddressesnotlsapi = await getAddressesapi(addressesnotlsapi);
newAddressesnotlscsv = await getAddressescsv('FALSE');
} else {
fakeHostName = `${fakeHostName}.xyz`
}

let url = `https://${sub}/sub?host=${fakeHostName}&uuid=${fakeUserID}&edgetunnel=cmliu&proxyip=${RproxyIP}`;
let isBase64 = true;

if (!sub || sub == ""){
if(hostName.includes('workers.dev') || hostName.includes('pages.dev')) {
if (proxyhostsURL && (!proxyhosts || proxyhosts.length == 0)) {
try {
const response = await fetch(proxyhostsURL);

if (!response.ok) {
console.error('获取地址时出错:', response.status, response.statusText);
return; // 如果有错误,直接返回
}

const text = await response.text();
const lines = text.split('\n');
// 过滤掉空行或只包含空白字符的行
const nonEmptyLines = lines.filter(line => line.trim() !== '');

proxyhosts = proxyhosts.concat(nonEmptyLines);
} catch (error) {
console.error('获取地址时出错:', error);
}
}
// 使用Set对象去重
proxyhosts = [...new Set(proxyhosts)];
}

newAddressesapi = await getAddressesapi(addressesapi);
newAddressescsv = await getAddressescsv('TRUE');
url = `https://${hostName}/${fakeUserID}`;
}

if (!userAgent.includes(('CF-Workers-SUB').toLowerCase())){
if ((userAgent.includes('clash') && !userAgent.includes('nekobox')) || ( _url.searchParams.has('clash') && !userAgent.includes('subconverter'))) {
url = `https://${subconverter}/sub?target=clash&url=${encodeURIComponent(url)}&insert=false&config=${encodeURIComponent(subconfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`;
isBase64 = false;
} else if (userAgent.includes('sing-box') || userAgent.includes('singbox') || (( _url.searchParams.has('singbox') || _url.searchParams.has('sb')) && !userAgent.includes('subconverter'))) {
url = `https://${subconverter}/sub?target=singbox&url=${encodeURIComponent(url)}&insert=false&config=${encodeURIComponent(subconfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`;
isBase64 = false;
}
}

try {
let content;
if ((!sub || sub == "") && isBase64 == true) {
content = await subAddresses(fakeHostName,fakeUserID,noTLS,newAddressesapi,newAddressescsv,newAddressesnotlsapi,newAddressesnotlscsv);
} else {
const response = await fetch(url ,{
headers: {
'User-Agent': `${UA} CF-Workers-edgetunnel/cmliu`
}});
content = await response.text();
}
if (!_url.pathname.includes(`/${fakeUserID}`)) content = revertFakeInfo(content, userID, hostName, isBase64);
return content;
} catch (error) {
console.error('Error fetching content:', error);
return `Error fetching content: ${error.message}`;
}

}
}

async function getAccountId(email, key) {
try {
const url = 'https://api.cloudflare.com/client/v4/accounts';
const headers = new Headers({
'X-AUTH-EMAIL': email,
'X-AUTH-KEY': key
});
const response = await fetch(url, { headers });
const data = await response.json();
return data.result[0].id; // 假设我们需要第一个账号ID
} catch (error) {
return false ;
}
}

async function getSum(accountId, accountIndex, email, key, startDate, endDate) {
try {
const startDateISO = new Date(startDate).toISOString();
const endDateISO = new Date(endDate).toISOString();

const query = JSON.stringify({
query: `query getBillingMetrics($accountId: String!, $filter: AccountWorkersInvocationsAdaptiveFilter_InputObject) {
viewer {
accounts(filter: {accountTag: $accountId}) {
pagesFunctionsInvocationsAdaptiveGroups(limit: 1000, filter: $filter) {
sum {
requests
}
}
workersInvocationsAdaptive(limit: 10000, filter: $filter) {
sum {
requests
}
}
}
}
}`,
variables: {
accountId,
filter: { datetime_geq: startDateISO, datetime_leq: endDateISO }
},
});

const headers = new Headers({
'Content-Type': 'application/json',
'X-AUTH-EMAIL': email,
'X-AUTH-KEY': key,
});

const response = await fetch(`https://api.cloudflare.com/client/v4/graphql`, {
method: 'POST',
headers: headers,
body: query
});

if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

const res = await response.json();

const pagesFunctionsInvocationsAdaptiveGroups = res?.data?.viewer?.accounts?.[accountIndex]?.pagesFunctionsInvocationsAdaptiveGroups;
const workersInvocationsAdaptive = res?.data?.viewer?.accounts?.[accountIndex]?.workersInvocationsAdaptive;

if (!pagesFunctionsInvocationsAdaptiveGroups && !workersInvocationsAdaptive) {
throw new Error('找不到数据');
}

const pagesSum = pagesFunctionsInvocationsAdaptiveGroups.reduce((a, b) => a + b?.sum.requests, 0);
const workersSum = workersInvocationsAdaptive.reduce((a, b) => a + b?.sum.requests, 0);

//console.log(`范围: ${startDateISO} ~ ${endDateISO}\n默认取第 ${accountIndex} 项`);

return [pagesSum, workersSum ];
} catch (error) {
return [ 0,0 ];
}
}

async function getAddressesapi(api) {
if (!api || api.length === 0) {
return [];
}

let newapi = "";

// 创建一个AbortController对象,用于控制fetch请求的取消
const controller = new AbortController();

const timeout = setTimeout(() => {
controller.abort(); // 取消所有请求
}, 2000); // 2秒后触发

try {
// 使用Promise.allSettled等待所有API请求完成,无论成功或失败
// 对api数组进行遍历,对每个API地址发起fetch请求
const responses = await Promise.allSettled(api.map(apiUrl => fetch(apiUrl, {
method: 'get',
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;',
'User-Agent': 'CF-Workers-edgetunnel/cmliu'
},
signal: controller.signal // 将AbortController的信号量添加到fetch请求中,以便于需要时可以取消请求
}).then(response => response.ok ? response.text() : Promise.reject())));

// 遍历所有响应
for (const response of responses) {
// 检查响应状态是否为'fulfilled',即请求成功完成
if (response.status === 'fulfilled') {
// 获取响应的内容
const content = await response.value;
newapi += content + '\n';
}
}
} catch (error) {
console.error(error);
} finally {
// 无论成功或失败,最后都清除设置的超时定时器
clearTimeout(timeout);
}

const newAddressesapi = await ADD(newapi);

// 返回处理后的结果
return newAddressesapi;
}

async function getAddressescsv(tls) {
if (!addressescsv || addressescsv.length === 0) {
return [];
}

let newAddressescsv = [];

for (const csvUrl of addressescsv) {
try {
const response = await fetch(csvUrl);

if (!response.ok) {
console.error('获取CSV地址时出错:', response.status, response.statusText);
continue;
}

const text = await response.text();// 使用正确的字符编码解析文本内容
let lines;
if (text.includes('\r\n')){
lines = text.split('\r\n');
} else {
lines = text.split('\n');
}

// 检查CSV头部是否包含必需字段
const header = lines[0].split(',');
const tlsIndex = header.indexOf('TLS');
const speedIndex = header.length - 1; // 最后一个字段

const ipAddressIndex = 0;// IP地址在 CSV 头部的位置
const portIndex = 1;// 端口在 CSV 头部的位置
const dataCenterIndex = tlsIndex + 1; // 数据中心是 TLS 的后一个字段

if (tlsIndex === -1) {
console.error('CSV文件缺少必需的字段');
continue;
}

// 从第二行开始遍历CSV行
for (let i = 1; i < lines.length; i++) {
const columns = lines[i].split(',');

// 检查TLS是否为"TRUE"且速度大于DLS
if (columns[tlsIndex].toUpperCase() === tls && parseFloat(columns[speedIndex]) > DLS) {
const ipAddress = columns[ipAddressIndex];
const port = columns[portIndex];
const dataCenter = columns[dataCenterIndex];

const formattedAddress = `${ipAddress}:${port}#${dataCenter}`;
newAddressescsv.push(formattedAddress);
}
}
} catch (error) {
console.error('获取CSV地址时出错:', error);
continue;
}
}

return newAddressescsv;
}

function subAddresses(host,UUID,noTLS,newAddressesapi,newAddressescsv,newAddressesnotlsapi,newAddressesnotlscsv) {
const regex = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[.*\]):?(\d+)?#?(.*)?$/;
addresses = addresses.concat(newAddressesapi);
addresses = addresses.concat(newAddressescsv);
let notlsresponseBody ;
if (noTLS == 'true'){
addressesnotls = addressesnotls.concat(newAddressesnotlsapi);
addressesnotls = addressesnotls.concat(newAddressesnotlscsv);
const uniqueAddressesnotls = [...new Set(addressesnotls)];

notlsresponseBody = uniqueAddressesnotls.map(address => {
let port = "80";
let addressid = address;

const match = addressid.match(regex);
if (!match) {
if (address.includes(':') && address.includes('#')) {
const parts = address.split(':');
address = parts[0];
const subParts = parts[1].split('#');
port = subParts[0];
addressid = subParts[1];
} else if (address.includes(':')) {
const parts = address.split(':');
address = parts[0];
port = parts[1];
} else if (address.includes('#')) {
const parts = address.split('#');
address = parts[0];
addressid = parts[1];
}

if (addressid.includes(':')) {
addressid = addressid.split(':')[0];
}
} else {
address = match[1];
port = match[2] || port;
addressid = match[3] || address;
}

const httpPorts = ["8080","8880","2052","2082","2086","2095"];
if (!isValidIPv4(address) && port == "80") {
for (let httpPort of httpPorts) {
if (address.includes(httpPort)) {
port = httpPort;
break;
}
}
}

let 伪装域名 = host ;
let 最终路径 = '/?ed=2560' ;
let 节点备注 = '';

if(proxyhosts.length > 0 && (伪装域名.includes('.workers.dev') || 伪装域名.includes('pages.dev'))) {
最终路径 = `/${伪装域名}${最终路径}`;
伪装域名 = proxyhosts[Math.floor(Math.random() * proxyhosts.length)];
节点备注 = ` 已启用临时域名中转服务,请尽快绑定自定义域!`;
}

const vlessLink = `vless://${UUID}@${address}:${port}?encryption=none&security=&type=ws&host=${伪装域名}&path=${encodeURIComponent(最终路径)}#${encodeURIComponent(addressid + 节点备注)}`;

return vlessLink;

}).join('\n');

}

// 使用Set对象去重
const uniqueAddresses = [...new Set(addresses)];

const responseBody = uniqueAddresses.map(address => {
let port = "443";
let addressid = address;

const match = addressid.match(regex);
if (!match) {
if (address.includes(':') && address.includes('#')) {
const parts = address.split(':');
address = parts[0];
const subParts = parts[1].split('#');
port = subParts[0];
addressid = subParts[1];
} else if (address.includes(':')) {
const parts = address.split(':');
address = parts[0];
port = parts[1];
} else if (address.includes('#')) {
const parts = address.split('#');
address = parts[0];
addressid = parts[1];
}

if (addressid.includes(':')) {
addressid = addressid.split(':')[0];
}
} else {
address = match[1];
port = match[2] || port;
addressid = match[3] || address;
}

const httpsPorts = ["2053","2083","2087","2096","8443"];
if (!isValidIPv4(address) && port == "443") {
for (let httpsPort of httpsPorts) {
if (address.includes(httpsPort)) {
port = httpsPort;
break;
}
}
}

let 伪装域名 = host ;
let 最终路径 = '/?ed=2560' ;
let 节点备注 = '';

if(proxyhosts.length > 0 && (伪装域名.includes('.workers.dev') || 伪装域名.includes('pages.dev'))) {
最终路径 = `/${伪装域名}${最终路径}`;
伪装域名 = proxyhosts[Math.floor(Math.random() * proxyhosts.length)];
节点备注 = ` 已启用临时域名中转服务,请尽快绑定自定义域!`;
}

const 协议类型 = atob(啥啥啥_写的这是啥啊);
const vlessLink = `${协议类型}://${UUID}@${address}:${port}?encryption=none&security=tls&sni=${伪装域名}&fp=random&type=ws&host=${伪装域名}&path=${encodeURIComponent(最终路径)}#${encodeURIComponent(addressid + 节点备注)}`;

return vlessLink;
}).join('\n');

let base64Response = responseBody; // 重新进行 Base64 编码
if(noTLS == 'true') base64Response += `\nnotlsresponseBody`;
return btoa(base64Response);
}

async function sendMessage(type, ip, add_data = "") {
if ( BotToken !== '' && ChatID !== ''){
let msg = "";
const response = await fetch(`http://ip-api.com/json/${ip}?lang=zh-CN`);
if (response.status == 200) {
const ipInfo = await response.json();
msg = `${type}\nIP: ${ip}\n国家: ${ipInfo.country}\n<tg-spoiler>城市: ${ipInfo.city}\n组织: ${ipInfo.org}\nASN: ${ipInfo.as}\n${add_data}`;
} else {
msg = `${type}\nIP: ${ip}\n<tg-spoiler>${add_data}`;
}

let url = "https://api.telegram.org/bot"+ BotToken +"/sendMessage?chat_id=" + ChatID + "&parse_mode=HTML&text=" + encodeURIComponent(msg);
return fetch(url, {
method: 'get',
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;',
'Accept-Encoding': 'gzip, deflate, br',
'User-Agent': 'Mozilla/5.0 Chrome/90.0.4430.72'
}
});
}
}

function isValidIPv4(address) {
const ipv4Regex = /^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
return ipv4Regex.test(address);
}

点击查看代码 2:

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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
// <!--GAMFC-->version base on commit 43fad05dcdae3b723c53c226f8181fc5bd47223e, time is 2023-06-22 15:20:02 UTC<!--GAMFC-END-->.
// @ts-ignore
import { connect } from "cloudflare:sockets";

// How to generate your own UUID:
// [Windows] Press "Win + R", input cmd and run: Powershell -NoExit -Command "[guid]::NewGuid()"
let userID = '❗❗❗填写这里❗❗❗';

const proxyIPs = ["cdn.xn--b6gac.eu.org"]; //ts.hpc.tw workers.cloudflare.cyou bestproxy.onecf.eu.org cdn-all.xn--b6gac.eu.org cdn.xn--b6gac.eu.org
const cn_hostnames = [''];
let CDNIP = 'www.visa.com.sg'
// http_ip
let IP1 = 'www.visa.com'
let IP2 = 'cis.visa.com'
let IP3 = 'africa.visa.com'
let IP4 = 'www.visa.com.sg'
let IP5 = 'www.visaeurope.at'
let IP6 = 'www.visa.com.mt'
let IP7 = 'qa.visamiddleeast.com'

// https_ip
let IP8 = 'usa.visa.com'
let IP9 = 'myanmar.visa.com'
let IP10 = 'www.visa.com.tw'
let IP11 = 'www.visaeurope.ch'
let IP12 = 'www.visa.com.br'
let IP13 = 'www.visasoutheasteurope.com'

// http_port
let PT1 = '80'
let PT2 = '8080'
let PT3 = '8880'
let PT4 = '2052'
let PT5 = '2082'
let PT6 = '2086'
let PT7 = '2095'

// https_port
let PT8 = '443'
let PT9 = '8443'
let PT10 = '2053'
let PT11 = '2083'
let PT12 = '2087'
let PT13 = '2096'

let proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)];

if (!isValidUUID(userID)) {
throw new Error("uuid is not valid");
}

export default {
/**
* @param {import("@cloudflare/workers-types").Request} request
* @param {uuid: string, proxyip: string, cdnip: string, ip1: string, ip2: string, ip3: string, ip4: string, ip5: string, ip6: string, ip7: string, ip8: string, ip9: string, ip10: string, ip11: string, ip12: string, ip13: string, pt1: string, pt2: string, pt3: string, pt4: string, pt5: string, pt6: string, pt7: string, pt8: string, pt9: string, pt10: string, pt11: string, pt12: string, pt13: string} env
* @param {import("@cloudflare/workers-types").ExecutionContext} ctx
* @returns {Promise<Response>}
*/
async fetch(request, env, ctx) {
try {
userID = env.uuid || userID;
proxyIP = env.proxyip || proxyIP;
CDNIP = env.cdnip || CDNIP;
IP1 = env.ip1 || IP1;
IP2 = env.ip2 || IP2;
IP3 = env.ip3 || IP3;
IP4 = env.ip4 || IP4;
IP5 = env.ip5 || IP5;
IP6 = env.ip6 || IP6;
IP7 = env.ip7 || IP7;
IP8 = env.ip8 || IP8;
IP9 = env.ip9 || IP9;
IP10 = env.ip10 || IP10;
IP11 = env.ip11 || IP11;
IP12 = env.ip12 || IP12;
IP13 = env.ip13 || IP13;
PT1 = env.pt1 || PT1;
PT2 = env.pt2 || PT2;
PT3 = env.pt3 || PT3;
PT4 = env.pt4 || PT4;
PT5 = env.pt5 || PT5;
PT6 = env.pt6 || PT6;
PT7 = env.pt7 || PT7;
PT8 = env.pt8 || PT8;
PT9 = env.pt9 || PT9;
PT10 = env.pt10 || PT10;
PT11 = env.pt11 || PT11;
PT12 = env.pt12 || PT12;
PT13 = env.pt13 || PT13;
const upgradeHeader = request.headers.get("Upgrade");
const url = new URL(request.url);
if (!upgradeHeader || upgradeHeader !== "websocket") {
const url = new URL(request.url);
switch (url.pathname) {
case `/config`: {
const vlessConfig = getVLESSConfig(userID, request.headers.get("Host"));
return new Response(`${vlessConfig}`, {
status: 200,
headers: {
"Content-Type": "text/html;charset=utf-8",
},
});
}
case `/config/ty`: {
const tyConfig = gettyConfig(userID, request.headers.get('Host'));
return new Response(`${tyConfig}`, {
status: 200,
headers: {
"Content-Type": "text/plain;charset=utf-8",
}
});
}
case `/config/cl`: {
const clConfig = getclConfig(userID, request.headers.get('Host'));
return new Response(`${clConfig}`, {
status: 200,
headers: {
"Content-Type": "text/plain;charset=utf-8",
}
});
}
case `/config/sb`: {
const sbConfig = getsbConfig(userID, request.headers.get('Host'));
return new Response(`${sbConfig}`, {
status: 200,
headers: {
"Content-Type": "application/json;charset=utf-8",
}
});
}
case `/config/pty`: {
const ptyConfig = getptyConfig(userID, request.headers.get('Host'));
return new Response(`${ptyConfig}`, {
status: 200,
headers: {
"Content-Type": "text/plain;charset=utf-8",
}
});
}
case `/config/pcl`: {
const pclConfig = getpclConfig(userID, request.headers.get('Host'));
return new Response(`${pclConfig}`, {
status: 200,
headers: {
"Content-Type": "text/plain;charset=utf-8",
}
});
}
case `/config/psb`: {
const psbConfig = getpsbConfig(userID, request.headers.get('Host'));
return new Response(`${psbConfig}`, {
status: 200,
headers: {
"Content-Type": "application/json;charset=utf-8",
}
});
}
default:
// return new Response('Not found', { status: 404 });
// For any other path, reverse proxy to 'ramdom website' and return the original response, caching it in the process
if (cn_hostnames.includes('')) {
return new Response(JSON.stringify(request.cf, null, 4), {
status: 200,
headers: {
"Content-Type": "application/json;charset=utf-8",
},
});
}
const randomHostname = cn_hostnames[Math.floor(Math.random() * cn_hostnames.length)];
const newHeaders = new Headers(request.headers);
newHeaders.set("cf-connecting-ip", "1.2.3.4");
newHeaders.set("x-forwarded-for", "1.2.3.4");
newHeaders.set("x-real-ip", "1.2.3.4");
newHeaders.set("referer", "https://www.google.com/search?q=edtunnel");
// Use fetch to proxy the request to 15 different domains
const proxyUrl = "https://" + randomHostname + url.pathname + url.search;
let modifiedRequest = new Request(proxyUrl, {
method: request.method,
headers: newHeaders,
body: request.body,
redirect: "manual",
});
const proxyResponse = await fetch(modifiedRequest, { redirect: "manual" });
// Check for 302 or 301 redirect status and return an error response
if ([301, 302].includes(proxyResponse.status)) {
return new Response(`Redirects to ${randomHostname} are not allowed.`, {
status: 403,
statusText: "Forbidden",
});
}
// Return the response from the proxy server
return proxyResponse;
}
} else {
if(url.pathname.includes('/pyip='))
{
const tmp_ip=url.pathname.split("=")[1];
if(isValidIP(tmp_ip))
{
proxyIP=tmp_ip;
}

}
return await vlessOverWSHandler(request);
}
} catch (err) {
/** @type {Error} */ let e = err;
return new Response(e.toString());
}
},
};

function isValidIP(ip) {
var reg = /^[\s\S]*$/;
return reg.test(ip);
}

/**
*
* @param {import("@cloudflare/workers-types").Request} request
*/
async function vlessOverWSHandler(request) {
/** @type {import("@cloudflare/workers-types").WebSocket[]} */
// @ts-ignore
const webSocketPair = new WebSocketPair();
const [client, webSocket] = Object.values(webSocketPair);

webSocket.accept();

let address = "";
let portWithRandomLog = "";
const log = (/** @type {string} */ info, /** @type {string | undefined} */ event) => {
console.log(`[${address}:${portWithRandomLog}] ${info}`, event || "");
};
const earlyDataHeader = request.headers.get("sec-websocket-protocol") || "";

const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log);

/** @type {{ value: import("@cloudflare/workers-types").Socket | null}}*/
let remoteSocketWapper = {
value: null,
};
let udpStreamWrite = null;
let isDns = false;

// ws --> remote
readableWebSocketStream
.pipeTo(
new WritableStream({
async write(chunk, controller) {
if (isDns && udpStreamWrite) {
return udpStreamWrite(chunk);
}
if (remoteSocketWapper.value) {
const writer = remoteSocketWapper.value.writable.getWriter();
await writer.write(chunk);
writer.releaseLock();
return;
}

const {
hasError,
message,
portRemote = 443,
addressRemote = "",
rawDataIndex,
vlessVersion = new Uint8Array([0, 0]),
isUDP,
} = await processVlessHeader(chunk, userID);
address = addressRemote;
portWithRandomLog = `${portRemote}--${Math.random()} ${isUDP ? "udp " : "tcp "} `;
if (hasError) {
// controller.error(message);
throw new Error(message); // cf seems has bug, controller.error will not end stream
// webSocket.close(1000, message);
return;
}
// if UDP but port not DNS port, close it
if (isUDP) {
if (portRemote === 53) {
isDns = true;
} else {
// controller.error('UDP proxy only enable for DNS which is port 53');
throw new Error("UDP proxy only enable for DNS which is port 53"); // cf seems has bug, controller.error will not end stream
return;
}
}
// ["version", "附加信息长度 N"]
const vlessResponseHeader = new Uint8Array([vlessVersion[0], 0]);
const rawClientData = chunk.slice(rawDataIndex);

// TODO: support udp here when cf runtime has udp support
if (isDns) {
const { write } = await handleUDPOutBound(webSocket, vlessResponseHeader, log);
udpStreamWrite = write;
udpStreamWrite(rawClientData);
return;
}
handleTCPOutBound(
remoteSocketWapper,
addressRemote,
portRemote,
rawClientData,
webSocket,
vlessResponseHeader,
log
);
},
close() {
log(`readableWebSocketStream is close`);
},
abort(reason) {
log(`readableWebSocketStream is abort`, JSON.stringify(reason));
},
})
)
.catch((err) => {
log("readableWebSocketStream pipeTo error", err);
});

return new Response(null, {
status: 101,
// @ts-ignore
webSocket: client,
});
}

/**
* Checks if a given UUID is present in the API response.
* @param {string} targetUuid The UUID to search for.
* @returns {Promise<boolean>} A Promise that resolves to true if the UUID is present in the API response, false otherwise.
*/
async function checkUuidInApiResponse(targetUuid) {
// Check if any of the environment variables are empty

try {
const apiResponse = await getApiResponse();
if (!apiResponse) {
return false;
}
const isUuidInResponse = apiResponse.users.some((user) => user.uuid === targetUuid);
return isUuidInResponse;
} catch (error) {
console.error("Error:", error);
return false;
}
}

/**
* Handles outbound TCP connections.
*
* @param {any} remoteSocket
* @param {string} addressRemote The remote address to connect to.
* @param {number} portRemote The remote port to connect to.
* @param {Uint8Array} rawClientData The raw client data to write.
* @param {import("@cloudflare/workers-types").WebSocket} webSocket The WebSocket to pass the remote socket to.
* @param {Uint8Array} vlessResponseHeader The VLESS response header.
* @param {function} log The logging function.
* @returns {Promise<void>} The remote socket.
*/
async function handleTCPOutBound(
remoteSocket,
addressRemote,
portRemote,
rawClientData,
webSocket,
vlessResponseHeader,
log
) {
async function connectAndWrite(address, port) {
if (/^(?:(?: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]?)$/.test(address)) address = `${atob('d3d3Lg==')}${address}${atob('LnNzbGlwLmlv')}`;
/** @type {import("@cloudflare/workers-types").Socket} */
const tcpSocket = connect({
hostname: address,
port: port,
});
remoteSocket.value = tcpSocket;
log(`connected to ${address}:${port}`);
const writer = tcpSocket.writable.getWriter();
await writer.write(rawClientData); // first write, nomal is tls client hello
writer.releaseLock();
return tcpSocket;
}

// if the cf connect tcp socket have no incoming data, we retry to redirect ip
async function retry() {
const tcpSocket = await connectAndWrite(proxyIP || addressRemote, portRemote);
// no matter retry success or not, close websocket
tcpSocket.closed
.catch((error) => {
console.log("retry tcpSocket closed error", error);
})
.finally(() => {
safeCloseWebSocket(webSocket);
});
remoteSocketToWS(tcpSocket, webSocket, vlessResponseHeader, null, log);
}

const tcpSocket = await connectAndWrite(addressRemote, portRemote);

// when remoteSocket is ready, pass to websocket
// remote--> ws
remoteSocketToWS(tcpSocket, webSocket, vlessResponseHeader, retry, log);
}

/**
*
* @param {import("@cloudflare/workers-types").WebSocket} webSocketServer
* @param {string} earlyDataHeader for ws 0rtt
* @param {(info: string)=> void} log for ws 0rtt
*/
function makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) {
let readableStreamCancel = false;
const stream = new ReadableStream({
start(controller) {
webSocketServer.addEventListener("message", (event) => {
if (readableStreamCancel) {
return;
}
const message = event.data;
controller.enqueue(message);
});

// The event means that the client closed the client -> server stream.
// However, the server -> client stream is still open until you call close() on the server side.
// The WebSocket protocol says that a separate close message must be sent in each direction to fully close the socket.
webSocketServer.addEventListener("close", () => {
// client send close, need close server
// if stream is cancel, skip controller.close
safeCloseWebSocket(webSocketServer);
if (readableStreamCancel) {
return;
}
controller.close();
});
webSocketServer.addEventListener("error", (err) => {
log("webSocketServer has error");
controller.error(err);
});
// for ws 0rtt
const { earlyData, error } = base64ToArrayBuffer(earlyDataHeader);
if (error) {
controller.error(error);
} else if (earlyData) {
controller.enqueue(earlyData);
}
},

pull(controller) {
// if ws can stop read if stream is full, we can implement backpressure
// https://streams.spec.whatwg.org/#example-rs-push-backpressure
},
cancel(reason) {
// 1. pipe WritableStream has error, this cancel will called, so ws handle server close into here
// 2. if readableStream is cancel, all controller.close/enqueue need skip,
// 3. but from testing controller.error still work even if readableStream is cancel
if (readableStreamCancel) {
return;
}
log(`ReadableStream was canceled, due to ${reason}`);
readableStreamCancel = true;
safeCloseWebSocket(webSocketServer);
},
});

return stream;
}

// https://xtls.github.io/development/protocols/vless.html
// https://github.com/zizifn/excalidraw-backup/blob/main/v2ray-protocol.excalidraw

/**
*
* @param { ArrayBuffer} vlessBuffer
* @param {string} userID
* @returns
*/
async function processVlessHeader(vlessBuffer, userID) {
if (vlessBuffer.byteLength < 24) {
return {
hasError: true,
message: "invalid data",
};
}
const version = new Uint8Array(vlessBuffer.slice(0, 1));
let isValidUser = false;
let isUDP = false;
const slicedBuffer = new Uint8Array(vlessBuffer.slice(1, 17));
const slicedBufferString = stringify(slicedBuffer);

const uuids = userID.includes(",") ? userID.split(",") : [userID];

const checkUuidInApi = await checkUuidInApiResponse(slicedBufferString);
isValidUser = uuids.some((userUuid) => checkUuidInApi || slicedBufferString === userUuid.trim());

console.log(`checkUuidInApi: ${await checkUuidInApiResponse(slicedBufferString)}, userID: ${slicedBufferString}`);

if (!isValidUser) {
return {
hasError: true,
message: "invalid user",
};
}

const optLength = new Uint8Array(vlessBuffer.slice(17, 18))[0];
//skip opt for now

const command = new Uint8Array(vlessBuffer.slice(18 + optLength, 18 + optLength + 1))[0];

// 0x01 TCP
// 0x02 UDP
// 0x03 MUX
if (command === 1) {
} else if (command === 2) {
isUDP = true;
} else {
return {
hasError: true,
message: `command ${command} is not support, command 01-tcp,02-udp,03-mux`,
};
}
const portIndex = 18 + optLength + 1;
const portBuffer = vlessBuffer.slice(portIndex, portIndex + 2);
// port is big-Endian in raw data etc 80 == 0x005d
const portRemote = new DataView(portBuffer).getUint16(0);

let addressIndex = portIndex + 2;
const addressBuffer = new Uint8Array(vlessBuffer.slice(addressIndex, addressIndex + 1));

// 1--> ipv4 addressLength =4
// 2--> domain name addressLength=addressBuffer[1]
// 3--> ipv6 addressLength =16
const addressType = addressBuffer[0];
let addressLength = 0;
let addressValueIndex = addressIndex + 1;
let addressValue = "";
switch (addressType) {
case 1:
addressLength = 4;
addressValue = new Uint8Array(vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength)).join(".");
break;
case 2:
addressLength = new Uint8Array(vlessBuffer.slice(addressValueIndex, addressValueIndex + 1))[0];
addressValueIndex += 1;
addressValue = new TextDecoder().decode(vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength));
break;
case 3:
addressLength = 16;
const dataView = new DataView(vlessBuffer.slice(addressValueIndex, addressValueIndex + addressLength));
// 2001:0db8:85a3:0000:0000:8a2e:0370:7334
const ipv6 = [];
for (let i = 0; i < 8; i++) {
ipv6.push(dataView.getUint16(i * 2).toString(16));
}
addressValue = ipv6.join(":");
// seems no need add [] for ipv6
break;
default:
return {
hasError: true,
message: `invild addressType is ${addressType}`,
};
}
if (!addressValue) {
return {
hasError: true,
message: `addressValue is empty, addressType is ${addressType}`,
};
}

return {
hasError: false,
addressRemote: addressValue,
addressType,
portRemote,
rawDataIndex: addressValueIndex + addressLength,
vlessVersion: version,
isUDP,
};
}

/**
*
* @param {import("@cloudflare/workers-types").Socket} remoteSocket
* @param {import("@cloudflare/workers-types").WebSocket} webSocket
* @param {ArrayBuffer} vlessResponseHeader
* @param {(() => Promise<void>) | null} retry
* @param {*} log
*/
async function remoteSocketToWS(remoteSocket, webSocket, vlessResponseHeader, retry, log) {
// remote--> ws
let remoteChunkCount = 0;
let chunks = [];
/** @type {ArrayBuffer | null} */
let vlessHeader = vlessResponseHeader;
let hasIncomingData = false; // check if remoteSocket has incoming data
await remoteSocket.readable
.pipeTo(
new WritableStream({
start() {},
/**
*
* @param {Uint8Array} chunk
* @param {*} controller
*/
async write(chunk, controller) {
hasIncomingData = true;
// remoteChunkCount++;
if (webSocket.readyState !== WS_READY_STATE_OPEN) {
controller.error("webSocket.readyState is not open, maybe close");
}
if (vlessHeader) {
webSocket.send(await new Blob([vlessHeader, chunk]).arrayBuffer());
vlessHeader = null;
} else {
// seems no need rate limit this, CF seems fix this??..
// if (remoteChunkCount > 20000) {
// // cf one package is 4096 byte(4kb), 4096 * 20000 = 80M
// await delay(1);
// }
webSocket.send(chunk);
}
},
close() {
log(`remoteConnection!.readable is close with hasIncomingData is ${hasIncomingData}`);
// safeCloseWebSocket(webSocket); // no need server close websocket frist for some case will casue HTTP ERR_CONTENT_LENGTH_MISMATCH issue, client will send close event anyway.
},
abort(reason) {
console.error(`remoteConnection!.readable abort`, reason);
},
})
)
.catch((error) => {
console.error(`remoteSocketToWS has exception `, error.stack || error);
safeCloseWebSocket(webSocket);
});

// seems is cf connect socket have error,
// 1. Socket.closed will have error
// 2. Socket.readable will be close without any data coming
if (hasIncomingData === false && retry) {
log(`retry`);
retry();
}
}

/**
*
* @param {string} base64Str
* @returns
*/
function base64ToArrayBuffer(base64Str) {
if (!base64Str) {
return { error: null };
}
try {
// go use modified Base64 for URL rfc4648 which js atob not support
base64Str = base64Str.replace(/-/g, "+").replace(/_/g, "/");
const decode = atob(base64Str);
const arryBuffer = Uint8Array.from(decode, (c) => c.charCodeAt(0));
return { earlyData: arryBuffer.buffer, error: null };
} catch (error) {
return { error };
}
}

/**
* This is not real UUID validation
* @param {string} uuid
*/
function isValidUUID(uuid) {
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return uuidRegex.test(uuid);
}

const WS_READY_STATE_OPEN = 1;
const WS_READY_STATE_CLOSING = 2;
/**
* Normally, WebSocket will not has exceptions when close.
* @param {import("@cloudflare/workers-types").WebSocket} socket
*/
function safeCloseWebSocket(socket) {
try {
if (socket.readyState === WS_READY_STATE_OPEN || socket.readyState === WS_READY_STATE_CLOSING) {
socket.close();
}
} catch (error) {
console.error("safeCloseWebSocket error", error);
}
}

const byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
return (
byteToHex[arr[offset + 0]] +
byteToHex[arr[offset + 1]] +
byteToHex[arr[offset + 2]] +
byteToHex[arr[offset + 3]] +
"-" +
byteToHex[arr[offset + 4]] +
byteToHex[arr[offset + 5]] +
"-" +
byteToHex[arr[offset + 6]] +
byteToHex[arr[offset + 7]] +
"-" +
byteToHex[arr[offset + 8]] +
byteToHex[arr[offset + 9]] +
"-" +
byteToHex[arr[offset + 10]] +
byteToHex[arr[offset + 11]] +
byteToHex[arr[offset + 12]] +
byteToHex[arr[offset + 13]] +
byteToHex[arr[offset + 14]] +
byteToHex[arr[offset + 15]]
).toLowerCase();
}
function stringify(arr, offset = 0) {
const uuid = unsafeStringify(arr, offset);
if (!isValidUUID(uuid)) {
throw TypeError("Stringified UUID is invalid");
}
return uuid;
}

/**
*
* @param {import("@cloudflare/workers-types").WebSocket} webSocket
* @param {ArrayBuffer} vlessResponseHeader
* @param {(string)=> void} log
*/
async function handleUDPOutBound(webSocket, vlessResponseHeader, log) {
let isVlessHeaderSent = false;
const transformStream = new TransformStream({
start(controller) {},
transform(chunk, controller) {
// udp message 2 byte is the the length of udp data
// TODO: this should have bug, beacsue maybe udp chunk can be in two websocket message
for (let index = 0; index < chunk.byteLength; ) {
const lengthBuffer = chunk.slice(index, index + 2);
const udpPakcetLength = new DataView(lengthBuffer).getUint16(0);
const udpData = new Uint8Array(chunk.slice(index + 2, index + 2 + udpPakcetLength));
index = index + 2 + udpPakcetLength;
controller.enqueue(udpData);
}
},
flush(controller) {},
});

// only handle dns udp for now
transformStream.readable
.pipeTo(
new WritableStream({
async write(chunk) {
const resp = await fetch(
dohURL, // dns server url
{
method: "POST",
headers: {
"content-type": "application/dns-message",
},
body: chunk,
}
);
const dnsQueryResult = await resp.arrayBuffer();
const udpSize = dnsQueryResult.byteLength;
// console.log([...new Uint8Array(dnsQueryResult)].map((x) => x.toString(16)));
const udpSizeBuffer = new Uint8Array([(udpSize >> 8) & 0xff, udpSize & 0xff]);
if (webSocket.readyState === WS_READY_STATE_OPEN) {
log(`doh success and dns message length is ${udpSize}`);
if (isVlessHeaderSent) {
webSocket.send(await new Blob([udpSizeBuffer, dnsQueryResult]).arrayBuffer());
} else {
webSocket.send(await new Blob([vlessResponseHeader, udpSizeBuffer, dnsQueryResult]).arrayBuffer());
isVlessHeaderSent = true;
}
}
},
})
)
.catch((error) => {
log("dns udp has error" + error);
});

const writer = transformStream.writable.getWriter();

return {
/**
*
* @param {Uint8Array} chunk
*/
write(chunk) {
writer.write(chunk);
},
};
}

/**
*
* @param {string} userID
* @param {string | null} hostName
* @returns {string}
*/
function getVLESSConfig(userID, hostName) {
const wvlessws = `vless://${userID}\u0040${CDNIP}:8880?encryption=none&security=none&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#${hostName}`;
const pvlesswstls = `vless://${userID}\u0040${CDNIP}:8443?encryption=none&security=tls&type=ws&host=${hostName}&sni=${hostName}&fp=random&path=%2F%3Fed%3D2560#${hostName}`;
const note = `ProxyIP全局运行中:${proxyIP}`;
const ty = `https://${hostName}/${userID}/ty`
const cl = `https://${hostName}/${userID}/cl`
const sb = `https://${hostName}/${userID}/sb`
const pty = `https://${hostName}/${userID}/pty`
const pcl = `https://${hostName}/${userID}/pcl`
const psb = `https://${hostName}/${userID}/psb`
const noteshow = note.replace(/\n/g, '<br>');
const displayHtml = `
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-YvpcrYf0tY3lHB60NNkmXc5s9fDVZLESaAA55NDzOxhy9GkcIdslK1eN7N6jIeHz" crossorigin="anonymous"></script>
<style>
.limited-width {
max-width: 200px;
overflow: auto;
word-wrap: break-word;
}
</style>
</head>
<script>
function copyToClipboard(text) {
const input = document.createElement('textarea');
input.style.position = 'fixed';
input.style.opacity = 0;
input.value = text;
document.body.appendChild(input);
input.select();
document.execCommand('Copy');
document.body.removeChild(input);
alert('已复制到剪贴板');
}
</script>
`;
if (hostName.includes("workers.dev")) {
return `
<br>
<br>
${displayHtml}
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Cloudflare-workers/pages-vless代理脚本</h1>
<hr>
<p>${noteshow}</p>
<hr>
<hr>
<hr>
<br>
<br>
<h3>1:CF-workers-vless+ws节点</h3>
<table class="table">
<thead>
<tr>
<th>节点特色:</th>
<th>单节点链接如下:</th>
</tr>
</thead>
<tbody>
<tr>
<td class="limited-width">关闭了TLS加密,无视域名阻断</td>
<td class="limited-width">${wvlessws}</td>
<td><button class="btn btn-primary" onclick="copyToClipboard('${wvlessws}')">点击复制链接</button></td>
</tr>
</tbody>
</table>
<h5>客户端参数如下:</h5>
<ul>
<li>客户端地址(address):自定义的域名 或者 优选域名 或者 优选IP 或者 反代IP</li>
<li>端口(port):7个http端口可任意选择(80、8080、8880、2052、2082、2086、2095),或反代IP对应端口</li>
<li>用户ID(uuid):${userID}</li>
<li>传输协议(network):ws 或者 websocket</li>
<li>伪装域名(host):${hostName}</li>
<li>路径(path):/?ed=2560</li>
<li>传输安全(TLS):关闭</li>
</ul>
<hr>
<hr>
<hr>
<br>
<br>
<h3>2:CF-workers-vless+ws+tls节点</h3>
<table class="table">
<thead>
<tr>
<th>节点特色:</th>
<th>单节点链接如下:</th>
</tr>
</thead>
<tbody>
<tr>
<td class="limited-width">启用了TLS加密,<br>如果客户端支持分片(Fragment)功能,建议开启,防止域名阻断</td>
<td class="limited-width">${pvlesswstls}</td>
<td><button class="btn btn-primary" onclick="copyToClipboard('${pvlesswstls}')">点击复制链接</button></td>
</tr>
</tbody>
</table>
<h5>客户端参数如下:</h5>
<ul>
<li>客户端地址(address):自定义的域名 或者 优选域名 或者 优选IP 或者 反代IP</li>
<li>端口(port):6个https端口可任意选择(443、8443、2053、2083、2087、2096),或反代IP对应端口</li>
<li>用户ID(uuid):${userID}</li>
<li>传输协议(network):ws 或者 websocket</li>
<li>伪装域名(host):${hostName}</li>
<li>路径(path):/?ed=2560</li>
<li>传输安全(TLS):开启</li>
<li>跳过证书验证(allowlnsecure):false</li>
</ul>
<hr>
<hr>
<hr>
<br>
<br>
<h3>3:通用、Clash-meta、Sing-box订阅链接如下:</h3>
<hr>
<p>注意:<br>1、默认每个订阅链接包含TLS+非TLS共13个端口节点<br>2、当前workers域名作为订阅链接,需通过代理进行订阅更新<br>3、需要开启分片功能使TLS节点可用,否则仅非TLS节点可用</p>
<hr>
<table class="table">
<thead>
<tr>
<th>通用订阅链接:</th>
</tr>
</thead>
<tbody>
<tr>
<td class="limited-width">${ty}</td>
<td><button class="btn btn-primary" onclick="copyToClipboard('${ty}')">点击复制链接</button></td>
</tr>
</tbody>
</table>

<table class="table">
<thead>
<tr>
<th>Clash-meta订阅链接:</th>
</tr>
</thead>
<tbody>
<tr>
<td class="limited-width">${cl}</td>
<td><button class="btn btn-primary" onclick="copyToClipboard('${cl}')">点击复制链接</button></td>
</tr>
</tbody>
</table>

<table class="table">
<thead>
<tr>
<th>Sing-box订阅链接:</th>
</tr>
</thead>
<tbody>
<tr>
<td class="limited-width">${sb}</td>
<td><button class="btn btn-primary" onclick="copyToClipboard('${sb}')">点击复制链接</button></td>
</tr>
</tbody>
</table>
<br>
<br>
</div>
</div>
</div>
</body>
`;
} else {
return `
<br>
<br>
${displayHtml}
<body>
<div class="container">
<div class="row">
<div class="col-md-12">
<h1>Cloudflare-workers/pages-vless代理脚本</h1>
<hr>
<p>${noteshow}</p>
<hr>
<hr>
<hr>
<br>
<br>
<h3>1:CF-pages/workers/自定义域-vless+ws+tls节点</h3>
<table class="table">
<thead>
<tr>
<th>节点特色:</th>
<th>单节点链接如下:</th>
</tr>
</thead>
<tbody>
<tr>
<td class="limited-width">启用了TLS加密,<br>如果客户端支持分片(Fragment)功能,可开启,防止域名阻断</td>
<td class="limited-width">${pvlesswstls}</td>
<td><button class="btn btn-primary" onclick="copyToClipboard('${pvlesswstls}')">点击复制链接</button></td>
</tr>
</tbody>
</table>
<h5>客户端参数如下:</h5>
<ul>
<li>客户端地址(address):自定义的域名 或者 优选域名 或者 优选IP 或者 反代IP</li>
<li>端口(port):6个https端口可任意选择(443、8443、2053、2083、2087、2096),或反代IP对应端口</li>
<li>用户ID(uuid):${userID}</li>
<li>传输协议(network):ws 或者 websocket</li>
<li>伪装域名(host):${hostName}</li>
<li>路径(path):/?ed=2560</li>
<li>传输安全(TLS):开启</li>
<li>跳过证书验证(allowlnsecure):false</li>
</ul>
<hr>
<hr>
<hr>
<br>
<br>
<h3>2:通用、Clash-meta、Sing-box订阅链接如下:</h3>
<hr>
<p>注意:以下订阅链接仅6个TLS端口节点</p>
<hr>
<table class="table">
<thead>
<tr>
<th>通用订阅链接:</th>
</tr>
</thead>
<tbody>
<tr>
<td class="limited-width">${pty}</td>
<td><button class="btn btn-primary" onclick="copyToClipboard('${pty}')">点击复制链接</button></td>
</tr>
</tbody>
</table>

<table class="table">
<thead>
<tr>
<th>Clash-meta订阅链接:</th>
</tr>
</thead>
<tbody>
<tr>
<td class="limited-width">${pcl}</td>
<td><button class="btn btn-primary" onclick="copyToClipboard('${pcl}')">点击复制链接</button></td>
</tr>
</tbody>
</table>

<table class="table">
<thead>
<tr>
<th>Sing-box订阅链接:</th>
</tr>
</thead>
<tbody>
<tr>
<td class="limited-width">${psb}</td>
<td><button class="btn btn-primary" onclick="copyToClipboard('${psb}')">点击复制链接</button></td>
</tr>
</tbody>
</table>
<br>
<br>
</div>
</div>
</div>
</body>
`;
}
}

function gettyConfig(userID, hostName) {
const vlessshare = btoa(`vless://${userID}\u0040${IP1}:${PT1}?encryption=none&security=none&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V1_${IP1}_${PT1}\nvless://${userID}\u0040${IP2}:${PT2}?encryption=none&security=none&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V2_${IP2}_${PT2}\nvless://${userID}\u0040${IP3}:${PT3}?encryption=none&security=none&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V3_${IP3}_${PT3}\nvless://${userID}\u0040${IP4}:${PT4}?encryption=none&security=none&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V4_${IP4}_${PT4}\nvless://${userID}\u0040${IP5}:${PT5}?encryption=none&security=none&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V5_${IP5}_${PT5}\nvless://${userID}\u0040${IP6}:${PT6}?encryption=none&security=none&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V6_${IP6}_${PT6}\nvless://${userID}\u0040${IP7}:${PT7}?encryption=none&security=none&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V7_${IP7}_${PT7}\nvless://${userID}\u0040${IP8}:${PT8}?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V8_${IP8}_${PT8}\nvless://${userID}\u0040${IP9}:${PT9}?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V9_${IP9}_${PT9}\nvless://${userID}\u0040${IP10}:${PT10}?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V10_${IP10}_${PT10}\nvless://${userID}\u0040${IP11}:${PT11}?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V11_${IP11}_${PT11}\nvless://${userID}\u0040${IP12}:${PT12}?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V12_${IP12}_${PT12}\nvless://${userID}\u0040${IP13}:${PT13}?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V13_${IP13}_${PT13}`);
return `${vlessshare}`
}

function getclConfig(userID, hostName) {
return `
port: 7890
allow-lan: true
mode: rule
log-level: info
unified-delay: true
global-client-fingerprint: chrome
dns:
enable: true
listen: :53
ipv6: true
enhanced-mode: fake-ip
fake-ip-range: 198.18.0.1/16
default-nameserver:
- 223.5.5.5
- 114.114.114.114
- 8.8.8.8
nameserver:
- https://dns.alidns.com/dns-query
- https://doh.pub/dns-query
fallback:
- https://1.0.0.1/dns-query
- tls://dns.google
fallback-filter:
geoip: true
geoip-code: CN
ipcidr:
- 240.0.0.0/4

proxies:
- name: CF_V1_${IP1}_${PT1}
type: vless
server: ${IP1}
port: ${PT1}
uuid: ${userID}
udp: false
tls: false
network: ws
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V2_${IP2}_${PT2}
type: vless
server: ${IP2}
port: ${PT2}
uuid: ${userID}
udp: false
tls: false
network: ws
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V3_${IP3}_${PT3}
type: vless
server: ${IP3}
port: ${PT3}
uuid: ${userID}
udp: false
tls: false
network: ws
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V4_${IP4}_${PT4}
type: vless
server: ${IP4}
port: ${PT4}
uuid: ${userID}
udp: false
tls: false
network: ws
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V5_${IP5}_${PT5}
type: vless
server: ${IP5}
port: ${PT5}
uuid: ${userID}
udp: false
tls: false
network: ws
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V6_${IP6}_${PT6}
type: vless
server: ${IP6}
port: ${PT6}
uuid: ${userID}
udp: false
tls: false
network: ws
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V7_${IP7}_${PT7}
type: vless
server: ${IP7}
port: ${PT7}
uuid: ${userID}
udp: false
tls: false
network: ws
servername: ${hostName}
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V8_${IP8}_${PT8}
type: vless
server: ${IP8}
port: ${PT8}
uuid: ${userID}
udp: false
tls: true
network: ws
servername: ${hostName}
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V9_${IP9}_${PT9}
type: vless
server: ${IP9}
port: ${PT9}
uuid: ${userID}
udp: false
tls: true
network: ws
servername: ${hostName}
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V10_${IP10}_${PT10}
type: vless
server: ${IP10}
port: ${PT10}
uuid: ${userID}
udp: false
tls: true
network: ws
servername: ${hostName}
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V11_${IP11}_${PT11}
type: vless
server: ${IP11}
port: ${PT11}
uuid: ${userID}
udp: false
tls: true
network: ws
servername: ${hostName}
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V12_${IP12}_${PT12}
type: vless
server: ${IP12}
port: ${PT12}
uuid: ${userID}
udp: false
tls: true
network: ws
servername: ${hostName}
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V13_${IP13}_${PT13}
type: vless
server: ${IP13}
port: ${PT13}
uuid: ${userID}
udp: false
tls: true
network: ws
servername: ${hostName}
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

proxy-groups:
- name: 负载均衡
type: load-balance
url: http://www.gstatic.com/generate_204
interval: 300
proxies:
- CF_V1_${IP1}_${PT1}
- CF_V2_${IP2}_${PT2}
- CF_V3_${IP3}_${PT3}
- CF_V4_${IP4}_${PT4}
- CF_V5_${IP5}_${PT5}
- CF_V6_${IP6}_${PT6}
- CF_V7_${IP7}_${PT7}
- CF_V8_${IP8}_${PT8}
- CF_V9_${IP9}_${PT9}
- CF_V10_${IP10}_${PT10}
- CF_V11_${IP11}_${PT11}
- CF_V12_${IP12}_${PT12}
- CF_V13_${IP13}_${PT13}

- name: 自动选择
type: url-test
url: http://www.gstatic.com/generate_204
interval: 300
tolerance: 50
proxies:
- CF_V1_${IP1}_${PT1}
- CF_V2_${IP2}_${PT2}
- CF_V3_${IP3}_${PT3}
- CF_V4_${IP4}_${PT4}
- CF_V5_${IP5}_${PT5}
- CF_V6_${IP6}_${PT6}
- CF_V7_${IP7}_${PT7}
- CF_V8_${IP8}_${PT8}
- CF_V9_${IP9}_${PT9}
- CF_V10_${IP10}_${PT10}
- CF_V11_${IP11}_${PT11}
- CF_V12_${IP12}_${PT12}
- CF_V13_${IP13}_${PT13}

- name: 🌍选择代理
type: select
proxies:
- 负载均衡
- 自动选择
- DIRECT
- CF_V1_${IP1}_${PT1}
- CF_V2_${IP2}_${PT2}
- CF_V3_${IP3}_${PT3}
- CF_V4_${IP4}_${PT4}
- CF_V5_${IP5}_${PT5}
- CF_V6_${IP6}_${PT6}
- CF_V7_${IP7}_${PT7}
- CF_V8_${IP8}_${PT8}
- CF_V9_${IP9}_${PT9}
- CF_V10_${IP10}_${PT10}
- CF_V11_${IP11}_${PT11}
- CF_V12_${IP12}_${PT12}
- CF_V13_${IP13}_${PT13}

rules:
- GEOIP,LAN,DIRECT
- GEOIP,CN,DIRECT
- MATCH,🌍选择代理`
}

function getsbConfig(userID, hostName) {
return `{
"log": {
"disabled": false,
"level": "info",
"timestamp": true
},
"experimental": {
"clash_api": {
"external_controller": "127.0.0.1:9090",
"external_ui": "ui",
"external_ui_download_url": "",
"external_ui_download_detour": "",
"secret": "",
"default_mode": "Rule"
},
"cache_file": {
"enabled": true,
"path": "cache.db",
"store_fakeip": true
}
},
"dns": {
"servers": [
{
"tag": "proxydns",
"address": "tls://8.8.8.8/dns-query",
"detour": "select"
},
{
"tag": "localdns",
"address": "h3://223.5.5.5/dns-query",
"detour": "direct"
},
{
"address": "rcode://refused",
"tag": "block"
},
{
"tag": "dns_fakeip",
"address": "fakeip"
}
],
"rules": [
{
"outbound": "any",
"server": "localdns",
"disable_cache": true
},
{
"clash_mode": "Global",
"server": "proxydns"
},
{
"clash_mode": "Direct",
"server": "localdns"
},
{
"rule_set": "geosite-cn",
"server": "localdns"
},
{
"rule_set": "geosite-geolocation-!cn",
"server": "proxydns"
},
{
"rule_set": "geosite-geolocation-!cn",
"query_type": [
"A",
"AAAA"
],
"server": "dns_fakeip"
}
],
"fakeip": {
"enabled": true,
"inet4_range": "198.18.0.0/15",
"inet6_range": "fc00::/18"
},
"independent_cache": true,
"final": "proxydns"
},
"inbounds": [
{
"type": "tun",
"inet4_address": "172.19.0.1/30",
"inet6_address": "fd00::1/126",
"auto_route": true,
"strict_route": true,
"sniff": true,
"sniff_override_destination": true,
"domain_strategy": "prefer_ipv4"
}
],
"outbounds": [
{
"tag": "select",
"type": "selector",
"default": "auto",
"outbounds": [
"auto",
"CF_V1_${IP1}_${PT1}",
"CF_V2_${IP2}_${PT2}",
"CF_V3_${IP3}_${PT3}",
"CF_V4_${IP4}_${PT4}",
"CF_V5_${IP5}_${PT5}",
"CF_V6_${IP6}_${PT6}",
"CF_V7_${IP7}_${PT7}",
"CF_V8_${IP8}_${PT8}",
"CF_V9_${IP9}_${PT9}",
"CF_V10_${IP10}_${PT10}",
"CF_V11_${IP11}_${PT11}",
"CF_V12_${IP12}_${PT12}",
"CF_V13_${IP13}_${PT13}"
]
},
{
"server": "${IP1}",
"server_port": ${PT1},
"tag": "CF_V1_${IP1}_${PT1}",
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP2}",
"server_port": ${PT2},
"tag": "CF_V2_${IP2}_${PT2}",
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP3}",
"server_port": ${PT3},
"tag": "CF_V3_${IP3}_${PT3}",
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP4}",
"server_port": ${PT4},
"tag": "CF_V4_${IP4}_${PT4}",
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP5}",
"server_port": ${PT5},
"tag": "CF_V5_${IP5}_${PT5}",
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP6}",
"server_port": ${PT6},
"tag": "CF_V6_${IP6}_${PT6}",
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP7}",
"server_port": ${PT7},
"tag": "CF_V7_${IP7}_${PT7}",
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP8}",
"server_port": ${PT8},
"tag": "CF_V8_${IP8}_${PT8}",
"tls": {
"enabled": true,
"server_name": "${hostName}",
"insecure": false,
"utls": {
"enabled": true,
"fingerprint": "chrome"
}
},
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP9}",
"server_port": ${PT9},
"tag": "CF_V9_${IP9}_${PT9}",
"tls": {
"enabled": true,
"server_name": "${hostName}",
"insecure": false,
"utls": {
"enabled": true,
"fingerprint": "chrome"
}
},
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP10}",
"server_port": ${PT10},
"tag": "CF_V10_${IP10}_${PT10}",
"tls": {
"enabled": true,
"server_name": "${hostName}",
"insecure": false,
"utls": {
"enabled": true,
"fingerprint": "chrome"
}
},
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP11}",
"server_port": ${PT11},
"tag": "CF_V11_${IP11}_${PT11}",
"tls": {
"enabled": true,
"server_name": "${hostName}",
"insecure": false,
"utls": {
"enabled": true,
"fingerprint": "chrome"
}
},
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP12}",
"server_port": ${PT12},
"tag": "CF_V12_${IP12}_${PT12}",
"tls": {
"enabled": true,
"server_name": "${hostName}",
"insecure": false,
"utls": {
"enabled": true,
"fingerprint": "chrome"
}
},
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP13}",
"server_port": ${PT13},
"tag": "CF_V13_${IP13}_${PT13}",
"tls": {
"enabled": true,
"server_name": "${hostName}",
"insecure": false,
"utls": {
"enabled": true,
"fingerprint": "chrome"
}
},
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"tag": "direct",
"type": "direct"
},
{
"tag": "block",
"type": "block"
},
{
"tag": "dns-out",
"type": "dns"
},
{
"tag": "auto",
"type": "urltest",
"outbounds": [
"CF_V1_${IP1}_${PT1}",
"CF_V2_${IP2}_${PT2}",
"CF_V3_${IP3}_${PT3}",
"CF_V4_${IP4}_${PT4}",
"CF_V5_${IP5}_${PT5}",
"CF_V6_${IP6}_${PT6}",
"CF_V7_${IP7}_${PT7}",
"CF_V8_${IP8}_${PT8}",
"CF_V9_${IP9}_${PT9}",
"CF_V10_${IP10}_${PT10}",
"CF_V11_${IP11}_${PT11}",
"CF_V12_${IP12}_${PT12}",
"CF_V13_${IP13}_${PT13}"
],
"url": "https://www.gstatic.com/generate_204",
"interval": "1m",
"tolerance": 50,
"interrupt_exist_connections": false
}
],
"route": {
"rule_set": [
{
"tag": "geosite-geolocation-!cn",
"type": "remote",
"format": "binary",
"url": "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@sing/geo/geosite/geolocation-!cn.srs",
"download_detour": "select",
"update_interval": "1d"
},
{
"tag": "geosite-cn",
"type": "remote",
"format": "binary",
"url": "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@sing/geo/geosite/geolocation-cn.srs",
"download_detour": "select",
"update_interval": "1d"
},
{
"tag": "geoip-cn",
"type": "remote",
"format": "binary",
"url": "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@sing/geo/geoip/cn.srs",
"download_detour": "select",
"update_interval": "1d"
}
],
"auto_detect_interface": true,
"final": "select",
"rules": [
{
"outbound": "dns-out",
"protocol": "dns"
},
{
"clash_mode": "Direct",
"outbound": "direct"
},
{
"clash_mode": "Global",
"outbound": "select"
},
{
"rule_set": "geoip-cn",
"outbound": "direct"
},
{
"rule_set": "geosite-cn",
"outbound": "direct"
},
{
"ip_is_private": true,
"outbound": "direct"
},
{
"rule_set": "geosite-geolocation-!cn",
"outbound": "select"
}
]
},
"ntp": {
"enabled": true,
"server": "time.apple.com",
"server_port": 123,
"interval": "30m",
"detour": "direct"
}
}`
}

function getptyConfig(userID, hostName) {
const vlessshare = btoa(`vless://${userID}\u0040${IP8}:${PT8}?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V8_${IP8}_${PT8}\nvless://${userID}\u0040${IP9}:${PT9}?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V9_${IP9}_${PT9}\nvless://${userID}\u0040${IP10}:${PT10}?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V10_${IP10}_${PT10}\nvless://${userID}\u0040${IP11}:${PT11}?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V11_${IP11}_${PT11}\nvless://${userID}\u0040${IP12}:${PT12}?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V12_${IP12}_${PT12}\nvless://${userID}\u0040${IP13}:${PT13}?encryption=none&security=tls&sni=${hostName}&fp=randomized&type=ws&host=${hostName}&path=%2F%3Fed%3D2560#CF_V13_${IP13}_${PT13}`);
return `${vlessshare}`
}

function getpclConfig(userID, hostName) {
return `
port: 7890
allow-lan: true
mode: rule
log-level: info
unified-delay: true
global-client-fingerprint: chrome
dns:
enable: true
listen: :53
ipv6: true
enhanced-mode: fake-ip
fake-ip-range: 198.18.0.1/16
default-nameserver:
- 223.5.5.5
- 114.114.114.114
- 8.8.8.8
nameserver:
- https://dns.alidns.com/dns-query
- https://doh.pub/dns-query
fallback:
- https://1.0.0.1/dns-query
- tls://dns.google
fallback-filter:
geoip: true
geoip-code: CN
ipcidr:
- 240.0.0.0/4

proxies:
- name: CF_V8_${IP8}_${PT8}
type: vless
server: ${IP8}
port: ${PT8}
uuid: ${userID}
udp: false
tls: true
network: ws
servername: ${hostName}
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V9_${IP9}_${PT9}
type: vless
server: ${IP9}
port: ${PT9}
uuid: ${userID}
udp: false
tls: true
network: ws
servername: ${hostName}
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V10_${IP10}_${PT10}
type: vless
server: ${IP10}
port: ${PT10}
uuid: ${userID}
udp: false
tls: true
network: ws
servername: ${hostName}
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V11_${IP11}_${PT11}
type: vless
server: ${IP11}
port: ${PT11}
uuid: ${userID}
udp: false
tls: true
network: ws
servername: ${hostName}
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V12_${IP12}_${PT12}
type: vless
server: ${IP12}
port: ${PT12}
uuid: ${userID}
udp: false
tls: true
network: ws
servername: ${hostName}
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

- name: CF_V13_${IP13}_${PT13}
type: vless
server: ${IP13}
port: ${PT13}
uuid: ${userID}
udp: false
tls: true
network: ws
servername: ${hostName}
ws-opts:
path: "/?ed=2560"
headers:
Host: ${hostName}

proxy-groups:
- name: 负载均衡
type: load-balance
url: http://www.gstatic.com/generate_204
interval: 300
proxies:
- CF_V8_${IP8}_${PT8}
- CF_V9_${IP9}_${PT9}
- CF_V10_${IP10}_${PT10}
- CF_V11_${IP11}_${PT11}
- CF_V12_${IP12}_${PT12}
- CF_V13_${IP13}_${PT13}

- name: 自动选择
type: url-test
url: http://www.gstatic.com/generate_204
interval: 300
tolerance: 50
proxies:
- CF_V8_${IP8}_${PT8}
- CF_V9_${IP9}_${PT9}
- CF_V10_${IP10}_${PT10}
- CF_V11_${IP11}_${PT11}
- CF_V12_${IP12}_${PT12}
- CF_V13_${IP13}_${PT13}

- name: 🌍选择代理
type: select
proxies:
- 负载均衡
- 自动选择
- DIRECT
- CF_V8_${IP8}_${PT8}
- CF_V9_${IP9}_${PT9}
- CF_V10_${IP10}_${PT10}
- CF_V11_${IP11}_${PT11}
- CF_V12_${IP12}_${PT12}
- CF_V13_${IP13}_${PT13}

rules:
- GEOIP,LAN,DIRECT
- GEOIP,CN,DIRECT
- MATCH,🌍选择代理`
}

function getpsbConfig(userID, hostName) {
return `{
"log": {
"disabled": false,
"level": "info",
"timestamp": true
},
"experimental": {
"clash_api": {
"external_controller": "127.0.0.1:9090",
"external_ui": "ui",
"external_ui_download_url": "",
"external_ui_download_detour": "",
"secret": "",
"default_mode": "Rule"
},
"cache_file": {
"enabled": true,
"path": "cache.db",
"store_fakeip": true
}
},
"dns": {
"servers": [
{
"tag": "proxydns",
"address": "tls://8.8.8.8/dns-query",
"detour": "select"
},
{
"tag": "localdns",
"address": "h3://223.5.5.5/dns-query",
"detour": "direct"
},
{
"address": "rcode://refused",
"tag": "block"
},
{
"tag": "dns_fakeip",
"address": "fakeip"
}
],
"rules": [
{
"outbound": "any",
"server": "localdns",
"disable_cache": true
},
{
"clash_mode": "Global",
"server": "proxydns"
},
{
"clash_mode": "Direct",
"server": "localdns"
},
{
"rule_set": "geosite-cn",
"server": "localdns"
},
{
"rule_set": "geosite-geolocation-!cn",
"server": "proxydns"
},
{
"rule_set": "geosite-geolocation-!cn",
"query_type": [
"A",
"AAAA"
],
"server": "dns_fakeip"
}
],
"fakeip": {
"enabled": true,
"inet4_range": "198.18.0.0/15",
"inet6_range": "fc00::/18"
},
"independent_cache": true,
"final": "proxydns"
},
"inbounds": [
{
"type": "tun",
"inet4_address": "172.19.0.1/30",
"inet6_address": "fd00::1/126",
"auto_route": true,
"strict_route": true,
"sniff": true,
"sniff_override_destination": true,
"domain_strategy": "prefer_ipv4"
}
],
"outbounds": [
{
"tag": "select",
"type": "selector",
"default": "auto",
"outbounds": [
"auto",
"CF_V8_${IP8}_${PT8}",
"CF_V9_${IP9}_${PT9}",
"CF_V10_${IP10}_${PT10}",
"CF_V11_${IP11}_${PT11}",
"CF_V12_${IP12}_${PT12}",
"CF_V13_${IP13}_${PT13}"
]
},
{
"server": "${IP8}",
"server_port": ${PT8},
"tag": "CF_V8_${IP8}_${PT8}",
"tls": {
"enabled": true,
"server_name": "${hostName}",
"insecure": false,
"utls": {
"enabled": true,
"fingerprint": "chrome"
}
},
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP9}",
"server_port": ${PT9},
"tag": "CF_V9_${IP9}_${PT9}",
"tls": {
"enabled": true,
"server_name": "${hostName}",
"insecure": false,
"utls": {
"enabled": true,
"fingerprint": "chrome"
}
},
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP10}",
"server_port": ${PT10},
"tag": "CF_V10_${IP10}_${PT10}",
"tls": {
"enabled": true,
"server_name": "${hostName}",
"insecure": false,
"utls": {
"enabled": true,
"fingerprint": "chrome"
}
},
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP11}",
"server_port": ${PT11},
"tag": "CF_V11_${IP11}_${PT11}",
"tls": {
"enabled": true,
"server_name": "${hostName}",
"insecure": false,
"utls": {
"enabled": true,
"fingerprint": "chrome"
}
},
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP12}",
"server_port": ${PT12},
"tag": "CF_V12_${IP12}_${PT12}",
"tls": {
"enabled": true,
"server_name": "${hostName}",
"insecure": false,
"utls": {
"enabled": true,
"fingerprint": "chrome"
}
},
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"server": "${IP13}",
"server_port": ${PT13},
"tag": "CF_V13_${IP13}_${PT13}",
"tls": {
"enabled": true,
"server_name": "${hostName}",
"insecure": false,
"utls": {
"enabled": true,
"fingerprint": "chrome"
}
},
"packet_encoding": "packetaddr",
"transport": {
"headers": {
"Host": [
"${hostName}"
]
},
"path": "/?ed=2560",
"type": "ws"
},
"type": "vless",
"uuid": "${userID}"
},
{
"tag": "direct",
"type": "direct"
},
{
"tag": "block",
"type": "block"
},
{
"tag": "dns-out",
"type": "dns"
},
{
"tag": "auto",
"type": "urltest",
"outbounds": [
"CF_V8_${IP8}_${PT8}",
"CF_V9_${IP9}_${PT9}",
"CF_V10_${IP10}_${PT10}",
"CF_V11_${IP11}_${PT11}",
"CF_V12_${IP12}_${PT12}",
"CF_V13_${IP13}_${PT13}"
],
"url": "https://www.gstatic.com/generate_204",
"interval": "1m",
"tolerance": 50,
"interrupt_exist_connections": false
}
],
"route": {
"rule_set": [
{
"tag": "geosite-geolocation-!cn",
"type": "remote",
"format": "binary",
"url": "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@sing/geo/geosite/geolocation-!cn.srs",
"download_detour": "select",
"update_interval": "1d"
},
{
"tag": "geosite-cn",
"type": "remote",
"format": "binary",
"url": "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@sing/geo/geosite/geolocation-cn.srs",
"download_detour": "select",
"update_interval": "1d"
},
{
"tag": "geoip-cn",
"type": "remote",
"format": "binary",
"url": "https://cdn.jsdelivr.net/gh/MetaCubeX/meta-rules-dat@sing/geo/geoip/cn.srs",
"download_detour": "select",
"update_interval": "1d"
}
],
"auto_detect_interface": true,
"final": "select",
"rules": [
{
"outbound": "dns-out",
"protocol": "dns"
},
{
"clash_mode": "Direct",
"outbound": "direct"
},
{
"clash_mode": "Global",
"outbound": "select"
},
{
"rule_set": "geoip-cn",
"outbound": "direct"
},
{
"rule_set": "geosite-cn",
"outbound": "direct"
},
{
"ip_is_private": true,
"outbound": "direct"
},
{
"rule_set": "geosite-geolocation-!cn",
"outbound": "select"
}
]
},
"ntp": {
"enabled": true,
"server": "time.apple.com",
"server_port": 123,
"interval": "30m",
"detour": "direct"
}
}`;
}

  1. 点击下方生成 UUID 按钮,然后复制生成的字符串,替换代码第 7 行,让 userID = 生成的 UUID,然后点击 Deploy。

获取节点配置

完成部署后,使用你的 UUIDWorker 域名 替换如下字符串来获得分享链接

vless://UUID@www.visa.com.sg:8880?encryption=none&security=none&type=ws&host=Workers domain&path=%2F%3Fed%3D2048#Workers domain

例子:

> vless://60da4750-617a-42a3-97a2-8ccdc2b45589@www.visa.com.sg:8880?encryption=none&security=none&type=ws&host=freedom.wgx.workers.dev&path=%2F%3Fed%3D2048#freedom.wgx.workers.dev

2024-07-06 更新:

你可以访问你的 workers 域名 + /config 路径来获取配置链接。

e.g. https://freedom.wgx.workers.dev/config (这个网址应该是无效的)

如果你的网络无法打开 workers 域名,你可以使用 https://web.dijk.eu.org/ 这个在线代理工具来访问。

获得配置链接后,导入你的代理客户端,就可以开启科学上网之旅了。