forked from cmliu/edgetunnel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_worker.js
More file actions
1827 lines (1678 loc) · 99.8 KB
/
_worker.js
File metadata and controls
1827 lines (1678 loc) · 99.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { connect } from "cloudflare:sockets";
let config_JSON, 反代IP = '', 启用SOCKS5反代 = null, 启用SOCKS5全局反代 = false, 我的SOCKS5账号 = '', parsedSocks5Address = {};
let SOCKS5白名单 = ['*tapecontent.net', '*cloudatacdn.com', '*loadshare.org', '*cdn-centaurus.com', 'scholar.google.com'];
const Pages静态页面 = 'https://edt-pages.github.io';
///////////////////////////////////////////////////////stallTCP参数///////////////////////////////////////////////
const MAX_PENDING = 8 * 1024 * 1024, // 最大缓冲大小(字节):8MB,超过此值将触发背压控制,防止内存溢出
KEEPALIVE = 15000, // 心跳保活间隔(毫秒):15秒,定期向服务器发送空包保持连接活跃
STALL_TIMEOUT = 8000, // 连接停滞检测超时(毫秒):8秒,检测数据流是否中断
MAX_STALL = 12, // 最大连续停滞次数:触发12次停滞后将重新连接(12 × 8秒 = 96秒)
MAX_RECONNECT = 24; // 最大重连尝试次数:超过24次重连失败后关闭连接
///////////////////////////////////////////////////////主程序入口///////////////////////////////////////////////
export default {
async fetch(request, env) {
const url = new URL(request.url);
const UA = request.headers.get('User-Agent') || 'null';
const upgradeHeader = request.headers.get('Upgrade');
const 管理员密码 = env.ADMIN || env.admin || env.PASSWORD || env.password || env.pswd || env.TOKEN || env.KEY;
const 加密秘钥 = env.KEY || '勿动此默认密钥,有需求请自行通过添加变量KEY进行修改';
const userIDMD5 = await MD5MD5(管理员密码 + 加密秘钥);
const userID = env.UUID || env.uuid || [userIDMD5.slice(0, 8), userIDMD5.slice(8, 12), '4' + userIDMD5.slice(13, 16), userIDMD5.slice(16, 20), userIDMD5.slice(20)].join('-');
if (env.PROXYIP) {
const proxyIPs = await 整理成数组(env.PROXYIP);
反代IP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)];
} else 反代IP = 反代IP ? 反代IP : request.cf.colo + '.PrOxYIp.CmLiUsSsS.nEt';
const 访问IP = request.headers.get('X-Real-IP') || request.headers.get('CF-Connecting-IP') || request.headers.get('X-Forwarded-For') || request.headers.get('True-Client-IP') || request.headers.get('Fly-Client-IP') || request.headers.get('X-Appengine-Remote-Addr') || request.headers.get('X-Forwarded-For') || request.headers.get('X-Real-IP') || request.headers.get('X-Cluster-Client-IP') || request.cf?.clientTcpRtt || '未知IP';
if (env.GO2SOCKS5) SOCKS5白名单 = await 整理成数组(env.GO2SOCKS5);
if (!upgradeHeader || upgradeHeader !== 'websocket') {
if (url.protocol === 'http:') return Response.redirect(url.href.replace(`http://${url.hostname}`, `https://${url.hostname}`), 301);
if (!管理员密码) return fetch(Pages静态页面 + '/noADMIN').then(r => { const headers = new Headers(r.headers); headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate'); headers.set('Pragma', 'no-cache'); headers.set('Expires', '0'); return new Response(r.body, { status: 404, statusText: r.statusText, headers }); });
if (!env.KV) return fetch(Pages静态页面 + '/noKV').then(r => { const headers = new Headers(r.headers); headers.set('Cache-Control', 'no-store, no-cache, must-revalidate, proxy-revalidate'); headers.set('Pragma', 'no-cache'); headers.set('Expires', '0'); return new Response(r.body, { status: 404, statusText: r.statusText, headers }); });
const 访问路径 = url.pathname.slice(1).toLowerCase();
const 区分大小写访问路径 = url.pathname.slice(1);
if (访问路径 === 加密秘钥 && 加密秘钥 !== '勿动此默认密钥,有需求请自行通过添加变量KEY进行修改') {//快速订阅
return new Response('重定向中...', { status: 302, headers: { 'Location': `/sub?token=${await MD5MD5(url.host + userID)}` } });
} else if (访问路径 === 'login') {//处理登录页面和登录请求
const cookies = request.headers.get('Cookie') || '';
const authCookie = cookies.split(';').find(c => c.trim().startsWith('auth='))?.split('=')[1];
if (authCookie == await MD5MD5(UA + 加密秘钥 + 管理员密码)) return new Response('重定向中...', { status: 302, headers: { 'Location': '/admin' } });
if (request.method === 'POST') {
const formData = await request.text();
const params = new URLSearchParams(formData);
const 输入密码 = params.get('password');
if (输入密码 === 管理员密码) {
// 密码正确,设置cookie并返回成功标记
const 响应 = new Response(JSON.stringify({ success: true }), { status: 200, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
响应.headers.set('Set-Cookie', `auth=${await MD5MD5(UA + 加密秘钥 + 管理员密码)}; Path=/; Max-Age=86400; HttpOnly`);
return 响应;
}
}
return fetch(Pages静态页面 + '/login');
} else if (访问路径 == 'admin' || 访问路径.startsWith('admin/')) {//验证cookie后响应管理页面
const cookies = request.headers.get('Cookie') || '';
const authCookie = cookies.split(';').find(c => c.trim().startsWith('auth='))?.split('=')[1];
// 没有cookie或cookie错误,跳转到/login页面
if (!authCookie || authCookie !== await MD5MD5(UA + 加密秘钥 + 管理员密码)) return new Response('重定向中...', { status: 302, headers: { 'Location': '/login' } });
if (访问路径 === 'admin/log.json') {// 读取日志内容
const 读取日志内容 = await env.KV.get('log.json') || '[]';
return new Response(读取日志内容, { status: 200, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
} else if (区分大小写访问路径 === 'admin/getCloudflareUsage') {// 查询请求量
try {
const Usage_JSON = await getCloudflareUsage(url.searchParams.get('Email'), url.searchParams.get('GlobalAPIKey'), url.searchParams.get('AccountID'), url.searchParams.get('APIToken'));
return new Response(JSON.stringify(Usage_JSON, null, 2), { status: 200, headers: { 'Content-Type': 'application/json' } });
} catch (err) {
const errorResponse = { msg: '查询请求量失败,失败原因:' + err.message, error: err.message };
return new Response(JSON.stringify(errorResponse, null, 2), { status: 500, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
}
} else if (区分大小写访问路径 === 'admin/getADDAPI') {// 验证优选API
if (url.searchParams.get('url')) {
const 待验证优选URL = url.searchParams.get('url');
try {
new URL(待验证优选URL);
const 优选API的IP = await 请求优选API([待验证优选URL], url.searchParams.get('port') || '443');
return new Response(JSON.stringify({ success: true, data: 优选API的IP }, null, 2), { status: 200, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
} catch (err) {
const errorResponse = { msg: '验证优选API失败,失败原因:' + err.message, error: err.message };
return new Response(JSON.stringify(errorResponse, null, 2), { status: 500, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
}
}
return new Response(JSON.stringify({ success: false, data: [] }, null, 2), { status: 403, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
} else if (访问路径 === 'admin/check') {// SOCKS5代理检查
let 检测代理响应;
if (url.searchParams.has('socks5')) {
检测代理响应 = await SOCKS5可用性验证('socks5', url.searchParams.get('socks5'));
} else if (url.searchParams.has('http')) {
检测代理响应 = await SOCKS5可用性验证('http', url.searchParams.get('http'));
} else {
return new Response(JSON.stringify({ error: '缺少代理参数' }), { status: 400, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
}
return new Response(JSON.stringify(检测代理响应, null, 2), { status: 200, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
}
config_JSON = await 读取config_JSON(env, url.host, userID);
if (访问路径 === 'admin/init') {// 重置配置为默认值
try {
config_JSON = await 读取config_JSON(env, url.host, userID, true);
await 请求日志记录(env, request, 访问IP, 'Init_Config', config_JSON);
config_JSON.init = '配置已重置为默认值';
return new Response(JSON.stringify(config_JSON, null, 2), { status: 200, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
} catch (err) {
const errorResponse = { msg: '配置重置失败,失败原因:' + err.message, error: err.message };
return new Response(JSON.stringify(errorResponse, null, 2), { status: 500, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
}
} else if (request.method === 'POST') {// 处理 KV 操作(POST 请求)
if (访问路径 === 'admin/config.json') { // 保存config.json配置
try {
const newConfig = await request.json();
// 验证配置完整性
if (!newConfig.UUID || !newConfig.HOST) return new Response(JSON.stringify({ error: '配置不完整' }), { status: 400, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
// 保存到 KV
await env.KV.put('config.json', JSON.stringify(newConfig, null, 2));
await 请求日志记录(env, request, 访问IP, 'Save_Config', config_JSON);
return new Response(JSON.stringify({ success: true, message: '配置已保存' }), { status: 200, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
} catch (error) {
console.error('保存配置失败:', error);
return new Response(JSON.stringify({ error: '保存配置失败: ' + error.message }), { status: 500, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
}
} else if (访问路径 === 'admin/cf.json') { // 保存cf.json配置
try {
const newConfig = await request.json();
const CF_JSON = { Email: null, GlobalAPIKey: null, AccountID: null, APIToken: null };
if (!newConfig.init || newConfig.init !== true) {
if (newConfig.Email && newConfig.GlobalAPIKey) {
CF_JSON.Email = newConfig.Email;
CF_JSON.GlobalAPIKey = newConfig.GlobalAPIKey;
CF_JSON.AccountID = null;
CF_JSON.APIToken = null;
} else if (newConfig.AccountID && newConfig.APIToken) {
CF_JSON.Email = null;
CF_JSON.GlobalAPIKey = null;
CF_JSON.AccountID = newConfig.AccountID;
CF_JSON.APIToken = newConfig.APIToken;
} else {
return new Response(JSON.stringify({ error: '配置不完整' }), { status: 400, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
}
}
// 保存到 KV
await env.KV.put('cf.json', JSON.stringify(CF_JSON, null, 2));
await 请求日志记录(env, request, 访问IP, 'Save_Config', config_JSON);
return new Response(JSON.stringify({ success: true, message: '配置已保存' }), { status: 200, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
} catch (error) {
console.error('保存配置失败:', error);
return new Response(JSON.stringify({ error: '保存配置失败: ' + error.message }), { status: 500, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
}
} else if (访问路径 === 'admin/tg.json') { // 保存tg.json配置
try {
const newConfig = await request.json();
if (newConfig.init && newConfig.init === true) {
const TG_JSON = { BotToken: null, ChatID: null };
await env.KV.put('tg.json', JSON.stringify(TG_JSON, null, 2));
} else {
if (!newConfig.BotToken || !newConfig.ChatID) return new Response(JSON.stringify({ error: '配置不完整' }), { status: 400, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
await env.KV.put('tg.json', JSON.stringify(newConfig, null, 2));
}
await 请求日志记录(env, request, 访问IP, 'Save_Config', config_JSON);
return new Response(JSON.stringify({ success: true, message: '配置已保存' }), { status: 200, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
} catch (error) {
console.error('保存配置失败:', error);
return new Response(JSON.stringify({ error: '保存配置失败: ' + error.message }), { status: 500, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
}
} else if (区分大小写访问路径 === 'admin/ADD.txt') { // 保存自定义优选IP
try {
const customIPs = await request.text();
await env.KV.put('ADD.txt', customIPs);// 保存到 KV
await 请求日志记录(env, request, 访问IP, 'Save_Custom_IPs', config_JSON);
return new Response(JSON.stringify({ success: true, message: '自定义IP已保存' }), { status: 200, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
} catch (error) {
console.error('保存自定义IP失败:', error);
return new Response(JSON.stringify({ error: '保存自定义IP失败: ' + error.message }), { status: 500, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
}
} else return new Response(JSON.stringify({ error: '不支持的POST请求路径' }), { status: 404, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
} else if (访问路径 === 'admin/config.json') {// 处理 admin/config.json 请求,返回JSON
return new Response(JSON.stringify(config_JSON, null, 2), { status: 200, headers: { 'Content-Type': 'application/json' } });
} else if (区分大小写访问路径 === 'admin/ADD.txt') {// 处理 admin/ADD.txt 请求,返回本地优选IP
let 本地优选IP = await env.KV.get('ADD.txt') || 'null';
if (本地优选IP == 'null') 本地优选IP = (await 生成随机IP(request, config_JSON.优选订阅生成.本地IP库.随机数量))[1];
return new Response(本地优选IP, { status: 200, headers: { 'Content-Type': 'text/plain;charset=utf-8', 'asn': request.cf.asn } });
} else if (访问路径 === 'admin/cf.json') {// CF配置文件
return new Response(JSON.stringify(request.cf, null, 2), { status: 200, headers: { 'Content-Type': 'application/json;charset=utf-8' } });
}
await 请求日志记录(env, request, 访问IP, 'Admin_Login', config_JSON);
return fetch(Pages静态页面 + '/admin');
} else if (访问路径 === 'logout') {//清除cookie并跳转到登录页面
const 响应 = new Response('重定向中...', { status: 302, headers: { 'Location': '/login' } });
响应.headers.set('Set-Cookie', 'auth=; Path=/; Max-Age=0; HttpOnly');
return 响应;
} else if (访问路径 === 'sub') {//处理订阅请求
const 订阅TOKEN = await MD5MD5(url.host + userID);
if (url.searchParams.get('token') === 订阅TOKEN) {
config_JSON = await 读取config_JSON(env, url.host, userID);
await 请求日志记录(env, request, 访问IP, 'Get_SUB', config_JSON);
const ua = UA.toLowerCase();
const expire = 4102329600;//2099-12-31 到期时间
const now = Date.now();
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, workersSum = UD, total = 24 * 1099511627776;
if (config_JSON.CF.Usage.success) {
pagesSum = config_JSON.CF.Usage.pages;
workersSum = config_JSON.CF.Usage.workers;
total = 1024 * 100;
}
const responseHeaders = {
"content-type": "text/plain; charset=utf-8",
"Profile-Update-Interval": config_JSON.优选订阅生成.SUBUpdateTime,
"Profile-web-page-url": url.protocol + '//' + url.host + '/admin',
"Subscription-Userinfo": `upload=${pagesSum}; download=${workersSum}; total=${total}; expire=${expire}`,
"Cache-Control": "no-store",
};
const isSubConverterRequest = request.headers.has('b64') || request.headers.has('base64') || request.headers.get('subconverter-request') || request.headers.get('subconverter-version') || ua.includes('subconverter') || ua.includes(('CF-Workers-SUB').toLowerCase());
const 订阅类型 = isSubConverterRequest
? 'mixed'
: url.searchParams.has('target')
? url.searchParams.get('target')
: url.searchParams.has('clash') || ua.includes('clash') || ua.includes('meta') || ua.includes('mihomo')
? 'clash'
: url.searchParams.has('sb') || url.searchParams.has('singbox') || ua.includes('singbox') || ua.includes('sing-box')
? 'singbox'
: url.searchParams.has('surge') || ua.includes('surge')
? 'surge&ver=4'
: 'mixed';
if (!ua.includes('mozilla')) responseHeaders["Content-Disposition"] = `attachment; filename*=utf-8''${encodeURIComponent(config_JSON.优选订阅生成.SUBNAME)}`;
const 协议类型 = (url.searchParams.has('surge') || ua.includes('surge')) ? 'tro' + 'jan' : config_JSON.协议类型;
let 订阅内容 = '';
if (订阅类型 === 'mixed') {
const 节点路径 = (url.searchParams.has('clash') || ua.includes('clash') || ua.includes('meta') || ua.includes('mihomo')) && 协议类型 == 'tro' + 'jan' ? config_JSON.PATH + '?ed=2560' : config_JSON.PATH;
const 完整优选列表 = config_JSON.优选订阅生成.本地IP库.随机IP ? (await 生成随机IP(request, config_JSON.优选订阅生成.本地IP库.随机数量))[0] : await env.KV.get('ADD.txt') ? await 整理成数组(await env.KV.get('ADD.txt')) : (await 生成随机IP(request, config_JSON.优选订阅生成.本地IP库.随机数量))[0];
const 优选API = [], 优选IP = [], 其他节点 = [];
for (const 元素 of 完整优选列表) {
if (元素.toLowerCase().startsWith('https://')) 优选API.push(元素);
else if (元素.toLowerCase().includes('://')) 其他节点.push(元素);
else 优选IP.push(元素);
}
const 其他节点LINK = 其他节点.join('\n') + '\n';
if (!url.searchParams.has('sub') && config_JSON.优选订阅生成.local) { // 本地生成订阅
const 优选API的IP = await 请求优选API(优选API);
const 完整优选IP = [...new Set(优选IP.concat(优选API的IP))];
订阅内容 = 完整优选IP.map(原始地址 => {
// 统一正则: 匹配 域名/IPv4/IPv6地址 + 可选端口 + 可选备注
// 示例:
// - 域名: hj.xmm1993.top:2096#备注 或 example.com
// - IPv4: 166.0.188.128:443#Los Angeles 或 166.0.188.128
// - IPv6: [2606:4700::]:443#CMCC 或 [2606:4700::]
const regex = /^(\[[\da-fA-F:]+\]|[\d.]+|[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?)*)(?::(\d+))?(?:#(.+))?$/;
const match = 原始地址.match(regex);
let 节点地址, 节点端口 = "443", 节点备注;
if (match) {
节点地址 = match[1]; // IP地址或域名(可能带方括号)
节点端口 = match[2] || "443"; // 端口,默认443
节点备注 = match[3] || 节点地址; // 备注,默认为地址本身
} else {
// 不规范的格式,跳过处理返回null
console.warn(`[订阅内容] 不规范的IP格式已忽略: ${原始地址}`);
return null;
}
return `${协议类型}://${config_JSON.UUID}@${节点地址}:${节点端口}?security=tls&type=${config_JSON.传输协议}&host=${config_JSON.HOST}&sni=${config_JSON.HOST}&path=${encodeURIComponent(节点路径)}&fragment=${encodeURIComponent('1,40-60,30-50,tlshello')}&encryption=none${config_JSON.跳过证书验证 ? '&allowInsecure=1' : ''}#${encodeURIComponent(节点备注)}`;
}).filter(item => item !== null).join('\n');
订阅内容 = btoa(其他节点LINK + 订阅内容);
} else { // 优选订阅生成器
let 优选订阅生成器HOST = url.searchParams.get('sub') || config_JSON.优选订阅生成.SUB;
优选订阅生成器HOST = 优选订阅生成器HOST && !/^https?:\/\//i.test(优选订阅生成器HOST) ? `https://${优选订阅生成器HOST}` : 优选订阅生成器HOST;
const 优选订阅生成器URL = `${优选订阅生成器HOST}/sub?host=example.com&${协议类型 === ('v' + 'le' + 'ss') ? 'uuid' : 'pw'}=00000000-0000-4000-0000-000000000000&path=${encodeURIComponent(节点路径)}&type=${config_JSON.传输协议}`;
try {
const response = await fetch(优选订阅生成器URL, { headers: { 'User-Agent': 'v2rayN/edge' + 'tunnel (https://github.com/cmliu/edge' + 'tunnel)' } });
if (response.ok) 订阅内容 = btoa(其他节点LINK + atob(await response.text()));
else return new Response('优选订阅生成器异常:' + response.statusText, { status: response.status });
} catch (error) {
return new Response('优选订阅生成器异常:' + error.message, { status: 403 });
}
}
} else { // 订阅转换
const 订阅转换URL = `${config_JSON.订阅转换配置.SUBAPI}/sub?target=${订阅类型}&url=${encodeURIComponent(url.protocol + '//' + url.host + '/sub?target=mixed&token=' + 订阅TOKEN) + (url.searchParams.has('sub') && url.searchParams.get('sub') != '' ? `&sub=${url.searchParams.get('sub')}` : '')}&config=${encodeURIComponent(config_JSON.订阅转换配置.SUBCONFIG)}&emoji=${config_JSON.订阅转换配置.SUBEMOJI}&scv=${config_JSON.跳过证书验证}`;
try {
const response = await fetch(订阅转换URL, { headers: { 'User-Agent': 'Subconverter for ' + 订阅类型 + ' edge' + 'tunnel(https://github.com/cmliu/edge' + 'tunnel)' } });
if (response.ok) {
订阅内容 = await response.text();
if (url.searchParams.has('surge') || ua.includes('surge')) 订阅内容 = surge(订阅内容, url.protocol + '//' + url.host + '/sub?token=' + 订阅TOKEN + '&surge', config_JSON);
} else return new Response('订阅转换后端异常:' + response.statusText, { status: response.status });
} catch (error) {
return new Response('订阅转换后端异常:' + error.message, { status: 403 });
}
}
if (订阅类型 === 'mixed') {
订阅内容 = atob(订阅内容).replace(/example.com/g, config_JSON.HOST).replace(/00000000-0000-4000-0000-000000000000/g, config_JSON.UUID);
if (!ua.includes('mozilla')) 订阅内容 = btoa(订阅内容);
} else 订阅内容 = 订阅内容.replace(/example.com/g, config_JSON.HOST).replace(/00000000-0000-4000-0000-000000000000/g, config_JSON.UUID);
if (订阅类型 === 'singbox') {
订阅内容 = JSON.stringify(JSON.parse(订阅内容), null, 2);
responseHeaders["content-type"] = 'application/json; charset=utf-8';
} else if (订阅类型 === 'clash') {
responseHeaders["content-type"] = 'application/x-yaml; charset=utf-8';
}
return new Response(订阅内容, { status: 200, headers: responseHeaders });
}
return new Response('无效的订阅TOKEN', { status: 403 });
}
} else if (管理员密码) {// ws代理
await 反代参数获取(request);
const { 0: client, 1: server } = new WebSocketPair();
server.accept();
handleConnection(server, request, userID);
return new Response(null, { status: 101, webSocket: client });
}
let 伪装页URL = env.URL || 'nginx';
if (伪装页URL && 伪装页URL !== 'nginx' && 伪装页URL !== '1101') {
伪装页URL = 伪装页URL.trim().replace(/\/$/, '');
if (!伪装页URL.match(/^https?:\/\//i)) 伪装页URL = 'https://' + 伪装页URL;
if (伪装页URL.toLowerCase().startsWith('http://')) 伪装页URL = 'https://' + 伪装页URL.substring(7);
try { const u = new URL(伪装页URL); 伪装页URL = u.protocol + '//' + u.host; } catch (e) { 伪装页URL = 'nginx'; }
}
if (伪装页URL === '1101') return new Response(await html1101(url.host, 访问IP), { status: 200, headers: { 'Content-Type': 'text/html; charset=UTF-8' } });
try {
const 反代URL = new URL(伪装页URL), 新请求头 = new Headers(request.headers);
新请求头.set('Host', 反代URL.host);
if (新请求头.has('Referer')) { const u = new URL(新请求头.get('Referer')); 新请求头.set('Referer', 反代URL.protocol + '//' + 反代URL.host + u.pathname + u.search); }
if (新请求头.has('Origin')) 新请求头.set('Origin', 反代URL.protocol + '//' + 反代URL.host);
if (!新请求头.has('User-Agent') && UA && UA !== 'null') 新请求头.set('User-Agent', UA);
return fetch(new Request(反代URL.protocol + 反代URL.host + url.pathname + url.search, { method: request.method, headers: 新请求头, body: request.body, cf: request.cf }));
} catch (error) { }
return new Response(await nginx(), { status: 200, headers: { 'Content-Type': 'text/html; charset=UTF-8' } });
}
};
///////////////////////////////////////////////////////////////////////WS传输数据///////////////////////////////////////////////
// 内存池类 - 优化内存分配和回收
class Pool {
constructor() {
this.buf = new ArrayBuffer(16384);
this.ptr = 0;
this.pool = [];
this.max = 8;
this.large = false;
}
alloc = s => {
if (s <= 4096 && s <= 16384 - this.ptr) {
const v = new Uint8Array(this.buf, this.ptr, s);
this.ptr += s;
return v;
}
const r = this.pool.pop();
if (r && r.byteLength >= s) return new Uint8Array(r.buffer, 0, s);
return new Uint8Array(s);
};
free = b => {
if (b.buffer === this.buf) {
this.ptr = Math.max(0, this.ptr - b.length);
return;
}
if (this.pool.length < this.max && b.byteLength >= 1024) this.pool.push(b);
};
enableLarge = () => { this.large = true; };
reset = () => { this.ptr = 0; this.pool.length = 0; this.large = false; };
}
function handleConnection(ws, request, FIXED_UUID) {
const pool = new Pool();
let socket, writer, reader, info;
let isFirstMsg = true, bytesReceived = 0, stallCount = 0, reconnectCount = 0;
let lastData = Date.now();
let isDns = false, udpStreamWrite = null;
const timers = {};
const dataBuffer = [];
let dataBufferBytes = 0;
const earlyDataHeader = request.headers.get("sec-websocket-protocol") || "";
// 新增: 连接状态和性能监控变量
let isConnecting = false, isReading = false;
let score = 1.0, lastCheck = Date.now(), lastRxBytes = 0, successCount = 0, failCount = 0;
let stats = { total: 0, count: 0, bigChunks: 0, window: 0, timestamp: Date.now() };
let mode = 'adaptive', avgSize = 0, throughputs = [];
// 动态调整传输模式
const updateMode = size => {
stats.total += size;
stats.count++;
if (size > 8192) stats.bigChunks++;
avgSize = avgSize * 0.9 + size * 0.1;
const now = Date.now();
if (now - stats.timestamp > 1000) {
const rate = stats.window;
throughputs.push(rate);
if (throughputs.length > 5) throughputs.shift();
stats.window = size;
stats.timestamp = now;
const avg = throughputs.reduce((a, b) => a + b, 0) / throughputs.length;
if (stats.count >= 20) {
if (avg > 20971520 && avgSize > 16384) {
if (mode !== 'buffered') {
mode = 'buffered';
pool.enableLarge();
}
} else if (avg < 10485760 || avgSize < 8192) {
if (mode !== 'direct') mode = 'direct';
} else {
if (mode !== 'adaptive') mode = 'adaptive';
}
}
} else {
stats.window += size;
}
};
async function 处理魏烈思握手(data) {
const bytes = new Uint8Array(data);
ws.send(new Uint8Array([bytes[0], 0]));
if (Array.from(bytes.slice(1, 17)).map(n => n.toString(16).padStart(2, '0')).join('').replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5') !== FIXED_UUID) throw new Error('Auth failed');
const offset1 = 18 + bytes[17] + 1;
const command = bytes[offset1 - 1]; // 获取命令字节: 0x01=TCP, 0x02=UDP, 0x03=MUX
const port = (bytes[offset1] << 8) | bytes[offset1 + 1];
const addrType = bytes[offset1 + 2];
const offset2 = offset1 + 3;
const addressType = addrType === 3 ? 4 : addrType === 2 ? 3 : 1;
const { host, length } = parseAddress(bytes, offset2, addressType);
const payload = bytes.slice(length);
// 处理 UDP 请求
if (command === 2) { // 0x02 = UDP
if (port === 53) {
isDns = true;
const 魏烈思响应头 = new Uint8Array([bytes[0], 0]);
const { write } = await handleUDPOutBound(ws, 魏烈思响应头);
udpStreamWrite = write;
if (payload.length) udpStreamWrite(payload);
return null; // UDP 不需要返回 socket
} else {
throw new Error('UDP proxy only enable for DNS which is port 53');
}
}
if (host.includes(atob('c3BlZWQuY2xvdWRmbGFyZS5jb20='))) throw new Error('Access');
const sock = await createConnection(host, port, addressType, 'V');
await sock.opened;
const w = sock.writable.getWriter();
if (payload.length) await w.write(payload);
return { socket: sock, writer: w, reader: sock.readable.getReader(), info: { host, port } };
}
async function 处理木马握手(data) {
const bytes = new Uint8Array(data);
if (bytes.byteLength < 56 || bytes[56] !== 0x0d || bytes[57] !== 0x0a) throw new Error("invalid data or header format");
if (new TextDecoder().decode(bytes.slice(0, 56)) !== sha224(FIXED_UUID)) throw new Error("invalid password");
const socks5Data = bytes.slice(58);
if (socks5Data.byteLength < 6) throw new Error("invalid SOCKS5 request data");
if (socks5Data[0] !== 1) throw new Error("unsupported command, only TCP (CONNECT) is allowed");
const addressType = socks5Data[1]
const { host, length } = parseAddress(socks5Data, 2, addressType);
if (!host) throw new Error(`address is empty, addressType is ${addressType}`);
if (host.includes(atob('c3BlZWQuY2xvdWRmbGFyZS5jb20='))) throw new Error('Access');
const port = (socks5Data[length] << 8) | socks5Data[length + 1];
const sock = await createConnection(host, port, addressType, 'T');
await sock.opened;
const w = sock.writable.getWriter();
const payload = socks5Data.slice(length + 4);
if (payload.length) await w.write(payload);
return { socket: sock, writer: w, reader: sock.readable.getReader(), info: { host, port } };
}
async function createConnection(host, port, addressType, 协议类型) {
console.log(JSON.stringify({ configJSON: { 协议类型: 协议类型, 目标类型: addressType, 目标地址: host, 目标端口: port, 反代IP: 反代IP, 代理类型: 启用SOCKS5反代, 全局代理: 启用SOCKS5全局反代, 代理账号: 我的SOCKS5账号 } }));
async function useSocks5Pattern(address) {
return SOCKS5白名单.some(pattern => {
let regexPattern = pattern.replace(/\*/g, '.*');
let regex = new RegExp(`^${regexPattern}$`, 'i');
return regex.test(address);
});
}
启用SOCKS5全局反代 = (await useSocks5Pattern(host)) || 启用SOCKS5全局反代;
let sock;
if (启用SOCKS5反代 == 'socks5' && 启用SOCKS5全局反代) {
sock = await socks5Connect(host, port, addressType);
} else if (启用SOCKS5反代 == 'http' && 启用SOCKS5全局反代) {
sock = await httpConnect(host, port);
} else {
try {
sock = connect({ hostname: host, port });
await sock.opened;
} catch {
if (启用SOCKS5反代 == 'socks5') {
sock = await socks5Connect(host, port, addressType);
} else if (启用SOCKS5反代 == 'http') {
sock = await httpConnect(host, port);
} else {
const [反代IP地址, 反代IP端口] = await 解析地址端口(反代IP);
try {
sock = connect({ hostname: 反代IP地址, port: 反代IP端口 });
} catch {
sock = connect({ hostname: atob('UFJPWFlJUC50cDEuMDkwMjI3Lnh5eg=='), port: 1 });
}
}
}
}
return sock;
}
async function readLoop() {
if (isReading) return;
isReading = true;
let batch = [], batchSize = 0, batchTimer = null;
// 批处理发送函数
const flush = () => {
if (!batchSize) return;
const merged = new Uint8Array(batchSize);
let pos = 0;
for (const chunk of batch) {
merged.set(chunk, pos);
pos += chunk.length;
}
if (ws.readyState === 1) ws.send(merged);
batch = [];
batchSize = 0;
if (batchTimer) {
clearTimeout(batchTimer);
batchTimer = null;
}
};
try {
while (true) {
// 背压控制
if (dataBufferBytes > MAX_PENDING) {
await new Promise(res => setTimeout(res, 100));
continue;
}
const { done, value } = await reader.read();
if (value?.length) {
bytesReceived += value.length;
lastData = Date.now();
stallCount = 0;
updateMode(value.length);
// 定期更新网络评分
const now = Date.now();
if (now - lastCheck > 5000) {
const elapsed = now - lastCheck;
const bytes = bytesReceived - lastRxBytes;
const throughput = bytes / elapsed;
if (throughput > 500) score = Math.min(1.0, score + 0.05);
else if (throughput < 50) score = Math.max(0.1, score - 0.05);
lastCheck = now;
lastRxBytes = bytesReceived;
}
// 根据模式选择发送策略
if (mode === 'buffered') {
if (value.length < 32768) {
batch.push(value);
batchSize += value.length;
if (batchSize >= 131072) flush();
else if (!batchTimer) batchTimer = setTimeout(flush, avgSize > 16384 ? 5 : 20);
} else {
flush();
if (ws.readyState === 1) ws.send(value);
}
} else if (mode === 'adaptive') {
if (value.length < 4096) {
batch.push(value);
batchSize += value.length;
if (batchSize >= 32768) flush();
else if (!batchTimer) batchTimer = setTimeout(flush, 15);
} else {
flush();
if (ws.readyState === 1) ws.send(value);
}
} else {
flush();
if (ws.readyState === 1) ws.send(value);
}
}
if (done) {
flush();
isReading = false;
reconnect();
break;
}
}
} catch (err) {
flush();
if (batchTimer) clearTimeout(batchTimer);
isReading = false;
failCount++;
reconnect();
}
}
async function reconnect() {
if (!info || ws.readyState !== 1) {
cleanup();
ws.close(1011, 'Invalid.');
return;
}
if (reconnectCount >= MAX_RECONNECT) {
cleanup();
ws.close(1011, 'Max reconnect.');
return;
}
// 基于网络质量评分的随机退出机制
if (score < 0.3 && reconnectCount > 5 && Math.random() > 0.6) {
cleanup();
ws.close(1011, 'Poor network.');
return;
}
if (isConnecting) return;
reconnectCount++;
// 动态计算重连延迟
let delay = Math.min(50 * Math.pow(1.5, reconnectCount - 1), 3000);
delay *= (1.5 - score * 0.5);
delay += (Math.random() - 0.5) * delay * 0.2;
delay = Math.max(50, Math.floor(delay));
console.log(`Reconnecting (attempt ${reconnectCount})...`);
try {
cleanupSocket();
// 背压控制: 清理过多缓冲数据
if (dataBufferBytes > MAX_PENDING * 2) {
while (dataBufferBytes > MAX_PENDING && dataBuffer.length > 5) {
const drop = dataBuffer.shift();
dataBufferBytes -= drop.length;
pool.free(drop);
}
}
await new Promise(res => setTimeout(res, delay));
isConnecting = true;
socket = connect({ hostname: info.host, port: info.port });
await socket.opened;
writer = socket.writable.getWriter();
reader = socket.readable.getReader();
// 发送缓冲数据 (限制数量防止阻塞)
const buffersToSend = dataBuffer.splice(0, 10);
for (const buf of buffersToSend) {
await writer.write(buf);
dataBufferBytes -= buf.length;
pool.free(buf);
}
isConnecting = false;
reconnectCount = 0;
score = Math.min(1.0, score + 0.15);
successCount++;
stallCount = 0;
lastData = Date.now();
readLoop();
} catch (err) {
isConnecting = false;
failCount++;
score = Math.max(0.1, score - 0.2);
if (reconnectCount < MAX_RECONNECT && ws.readyState === 1) setTimeout(reconnect, 500);
else {
cleanup();
ws.close(1011, 'Exhausted.');
}
}
}
function startTimers() {
timers.keepalive = setInterval(async () => {
if (!isConnecting && writer && Date.now() - lastData > KEEPALIVE) {
try {
await writer.write(new Uint8Array(0));
lastData = Date.now();
} catch (e) {
reconnect();
}
}
}, KEEPALIVE / 3);
timers.health = setInterval(() => {
if (!isConnecting && stats.total > 0 && Date.now() - lastData > STALL_TIMEOUT) {
stallCount++;
if (stallCount >= MAX_STALL) {
if (reconnectCount < MAX_RECONNECT) {
stallCount = 0;
reconnect();
} else {
cleanup();
ws.close(1011, 'Stall.');
}
}
}
}, STALL_TIMEOUT / 2);
}
function cleanupSocket() {
isReading = false;
try {
writer?.releaseLock();
reader?.releaseLock();
socket?.close();
} catch { }
}
function cleanup() {
Object.values(timers).forEach(clearInterval);
cleanupSocket();
while (dataBuffer.length) pool.free(dataBuffer.shift());
dataBufferBytes = 0;
stats = { total: 0, count: 0, bigChunks: 0, window: 0, timestamp: Date.now() };
mode = 'direct';
avgSize = 0;
throughputs = [];
pool.reset();
}
// 处理 early data
function processEarlyData(earlyDataHeader) {
if (!earlyDataHeader) return null;
try {
const base64Str = earlyDataHeader.replace(/-/g, "+").replace(/_/g, "/");
const decode = atob(base64Str);
const arryBuffer = Uint8Array.from(decode, (c) => c.charCodeAt(0));
return arryBuffer;
} catch (error) {
return null;
}
}
ws.addEventListener('message', async evt => {
try {
if (isFirstMsg) {
isFirstMsg = false;
// 合并 early data 和第一条消息
let firstData = evt.data;
const earlyData = processEarlyData(earlyDataHeader);
if (earlyData) {
const combined = new Uint8Array(earlyData.length + firstData.byteLength);
combined.set(earlyData);
combined.set(new Uint8Array(firstData), earlyData.length);
firstData = combined.buffer;
}
const bytes = new Uint8Array(firstData);
let result;
if (bytes.byteLength >= 58 && bytes[56] === 0x0d && bytes[57] === 0x0a) {
result = await 处理木马握手(firstData);
} else {
result = await 处理魏烈思握手(firstData);
}
// 如果是 UDP DNS,result 为 null,不需要启动 TCP 相关逻辑
if (result) {
({ socket, writer, reader, info } = result);
startTimers();
readLoop();
}
} else {
lastData = Date.now();
if (isDns && udpStreamWrite) {
udpStreamWrite(evt.data);
} else if (isConnecting || !writer) {
// 使用内存池分配缓冲区
const buf = pool.alloc(evt.data.byteLength);
buf.set(new Uint8Array(evt.data));
dataBuffer.push(buf);
dataBufferBytes += buf.length;
} else {
await writer.write(evt.data);
}
}
} catch (err) {
cleanup();
ws.close(1006, 'Error.');
}
});
ws.addEventListener('close', cleanup);
ws.addEventListener('error', cleanup);
}
function parseAddress(bytes, offset, addrType) {
let host, length, endOffset;
switch (addrType) {
case 1: // IPv4
length = 4;
host = Array.from(bytes.slice(offset, offset + length)).join('.');
endOffset = offset + length;
break;
case 3: // Domain name
length = bytes[offset];
host = new TextDecoder().decode(bytes.slice(offset + 1, offset + 1 + length));
endOffset = offset + 1 + length;
break;
case 4: // IPv6
length = 16;
const ipv6 = [];
for (let i = 0; i < 8; i++) {
ipv6.push(((bytes[offset + i * 2] << 8) | bytes[offset + i * 2 + 1]).toString(16));
}
host = ipv6.join(':');
endOffset = offset + length;
break;
default:
throw new Error(`Invalid address type: ${addrType}`);
}
return { host, length: endOffset };
}
async function handleUDPOutBound(webSocket, 魏烈思响应头) {
let 是否已发送魏烈思响应头 = false;
const transformStream = new TransformStream({
start(controller) { },
transform(chunk, controller) {
// 确保 chunk 是 Uint8Array
if (!(chunk instanceof Uint8Array)) {
chunk = new Uint8Array(chunk);
}
// UDP 消息前 2 字节是 UDP 数据长度
for (let index = 0; index < chunk.byteLength;) {
// 直接从字节中读取长度,避免使用 DataView
const udpPacketLength = (chunk[index] << 8) | chunk[index + 1];
const udpData = new Uint8Array(
chunk.slice(index + 2, index + 2 + udpPacketLength)
);
index = index + 2 + udpPacketLength;
controller.enqueue(udpData);
}
},
flush(controller) { }
});
// 只处理 DNS UDP 请求
transformStream.readable.pipeTo(new WritableStream({
async write(chunk) {
try {
const startTime = performance.now();
// 解析 DNS 查询域名
const dnsQuery = parseDNSQuery(chunk);
console.log(`[UDP DNS] 查询域名: ${dnsQuery.domain || '未知'}, 类型: ${dnsQuery.type}, 处理时间: ${(performance.now() - startTime).toFixed(2)}ms`);
const resp = await fetch('https://1.1.1.1/dns-query', {
method: 'POST',
headers: {
'content-type': 'application/dns-message',
},
body: chunk,
});
const dnsQueryResult = await resp.arrayBuffer();
const udpSize = dnsQueryResult.byteLength;
const udpSizeBuffer = new Uint8Array([(udpSize >> 8) & 0xff, udpSize & 0xff]);
// 解析 DNS 响应内容
const dnsResponse = parseDNSResponse(new Uint8Array(dnsQueryResult));
const answers = dnsResponse.answers.length > 0 ? dnsResponse.answers.join(', ') : '无记录';
console.log(`[UDP DNS] 响应域名: ${dnsQuery.domain || '未知'}, 答案: ${answers}, 响应时间: ${(performance.now() - startTime).toFixed(2)}ms`);
if (webSocket.readyState === 1) { // WebSocket.OPEN
if (是否已发送魏烈思响应头) {
webSocket.send(await new Blob([udpSizeBuffer, dnsQueryResult]).arrayBuffer());
} else {
webSocket.send(await new Blob([魏烈思响应头, udpSizeBuffer, dnsQueryResult]).arrayBuffer());
是否已发送魏烈思响应头 = true;
}
// DNS 查询完成后关闭 WebSocket 连接
setTimeout(() => {
if (webSocket.readyState === 1) {
webSocket.close(1000, 'DNS query completed');
console.log(`[UDP DNS] 连接已关闭: ${dnsQuery.domain || '未知'}`);
}
}, 10); // 给一点时间让数据发送完成
}
} catch (error) {
console.error('DoH request failed:', error);
// 出错时也关闭连接
if (webSocket.readyState === 1) {
webSocket.close(1000, 'DNS query failed');
}
}
}
})).catch((error) => {
console.error('DNS UDP error:', error);
});
const writer = transformStream.writable.getWriter();
return {
write(chunk) {
writer.write(chunk);
}
};
}
function parseDNSQuery(dnsPacket) {
try {
// 确保 dnsPacket 有 byteLength 属性
if (!dnsPacket || !dnsPacket.byteLength) {
return { domain: null, type: 'Invalid' };
}
// DNS 头部是 12 字节
if (dnsPacket.byteLength < 12) return { domain: null, type: 'Invalid' };
// 从第 12 字节开始是查询部分
let offset = 12;
const labels = [];
// 解析域名标签
while (offset < dnsPacket.byteLength) {
const length = dnsPacket[offset];
if (length === 0) {
offset++;
break;
}
// 检查是否是指针 (压缩格式)
if ((length & 0xC0) === 0xC0) {
offset += 2;
break;
}
offset++;
if (offset + length > dnsPacket.byteLength) break;
const label = new TextDecoder().decode(dnsPacket.slice(offset, offset + length));
labels.push(label);
offset += length;
}
const domain = labels.join('.');
// 查询类型在域名之后的 2 字节 (TYPE)
let queryType = 'Unknown';
if (offset + 2 <= dnsPacket.byteLength) {
const type = (dnsPacket[offset] << 8) | dnsPacket[offset + 1];
const types = { 1: 'A', 2: 'NS', 5: 'CNAME', 6: 'SOA', 12: 'PTR', 15: 'MX', 16: 'TXT', 28: 'AAAA', 33: 'SRV', 65: 'HTTPS' };
queryType = types[type] || `TYPE${type}`;
}
return { domain: domain || null, type: queryType };
} catch (error) {
console.error('[UDP DNS] 解析 DNS 查询失败:', error);
return { domain: null, type: 'Error' };
}
}
function parseDNSResponse(dnsPacket) {
try {
if (!dnsPacket || dnsPacket.byteLength < 12) return { answers: [] };
const answerCount = (dnsPacket[6] << 8) | dnsPacket[7];
if (answerCount === 0) return { answers: [] };
let offset = 12;
// 跳过查询部分
while (offset < dnsPacket.byteLength) {
const length = dnsPacket[offset];
if (length === 0) { offset += 5; break; }
if ((length & 0xC0) === 0xC0) { offset += 6; break; }
offset += 1 + length;
}
const answers = [];
for (let i = 0; i < answerCount && offset < dnsPacket.byteLength; i++) {
try {
// 跳过 NAME
if ((dnsPacket[offset] & 0xC0) === 0xC0) offset += 2;
else { while (offset < dnsPacket.byteLength && dnsPacket[offset] !== 0) offset += 1 + dnsPacket[offset]; offset += 1; }
if (offset + 10 > dnsPacket.byteLength) break;
const type = (dnsPacket[offset] << 8) | dnsPacket[offset + 1];
const dataLength = (dnsPacket[offset + 8] << 8) | dnsPacket[offset + 9];
offset += 10;
if (offset + dataLength > dnsPacket.byteLength) break;
let answer = '';
if (type === 1 && dataLength === 4) answer = `${dnsPacket[offset]}.${dnsPacket[offset + 1]}.${dnsPacket[offset + 2]}.${dnsPacket[offset + 3]}`;
else if (type === 28 && dataLength === 16) answer = Array.from({ length: 8 }, (_, j) => ((dnsPacket[offset + j * 2] << 8) | dnsPacket[offset + j * 2 + 1]).toString(16)).join(':');
else if (type === 5 || type === 2 || type === 12) answer = parseDNSName(dnsPacket, offset);
else if (type === 16) answer = new TextDecoder().decode(dnsPacket.slice(offset + 1, offset + 1 + dnsPacket[offset]));
else answer = `TYPE${type}`;
if (answer) answers.push(answer);
offset += dataLength;
} catch (e) { break; }
}
return { answers };
} catch (error) {
console.error('[UDP DNS] 解析 DNS 响应失败:', error);
return { answers: [] };
}
}