forked from rusifeng88/stallTCP1.3V2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_worker.js
More file actions
2793 lines (2621 loc) · 132 KB
/
Copy path_worker.js
File metadata and controls
2793 lines (2621 loc) · 132 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';
// =============================================================================
// 🟣 1. 用户配置区域 (优先级: 环境变量 > D1 > KV > 硬编码)
// =============================================================================
// --- 基础账号与网络配置 ---
let UUID = "06b65903-406d-4a41-8463-6fd5c0ee7798"; //修改可用的uuid
const WEB_PASSWORD = "你的登录密码"; //修改你的登录密码
const SUB_PASSWORD = "你的订阅密码"; //修改你的订阅密码
const DEFAULT_PROXY_IP = "ProxyIP.US.CMLiussss.net"; // 支持多ProxyIP,使用逗号分隔
const DEFAULT_SUB_DOMAIN = "sub.cmliussss.net"; // 支持多订阅域名,使用逗号分隔
const DEFAULT_CONVERTER = "https://subapi.cmliussss.net"; // 支持多转换器,使用逗号分隔
// --- 界面与链接配置 ---
const LOGIN_PAGE_TITLE = "Worker Login"; // 修改你的登录页标题
const DASHBOARD_TITLE = "烈火控制台 · Glass LH"; //修改你的管理后台标题
const TG_GROUP_URL = "https://t.me/zyssadmin"; // 登录页“交流群”链接
const SITE_URL = "https://blog.2026565.xyz/"; // 登录页“天诚网站”链接
const GITHUB_URL = "https://github.com/xtgm/stallTCP1.3V1"; // 登录页“项目直达”链接
const PROXY_CHECK_URL = "https://kaic.hidns.co/"; // 后台 ProxyIP 检测跳转地址
// --- 订阅转换配置文件 (支持环境变量覆盖) ---
const CLASH_CONFIG = "https://raw.githubusercontent.com/cmliu/ACL4SSR/main/Clash/config/ACL4SSR_Online_Full_MultiMode.ini"; //修改转换订阅配置文件ini
const SINGBOX_CONFIG_V12 = "https://raw.githubusercontent.com/sinspired/sub-store-template/main/1.12.x/sing-box.json"; //修改singbox的json配置,默认使用1.11,如果无法使用才会切换1.12
const SINGBOX_CONFIG_V11 = "https://raw.githubusercontent.com/sinspired/sub-store-template/main/1.11.x/sing-box.json"; //修改singbox的json配置,默认使用这个,如果无法使用才会切换1.12
// --- 通知与高级参数 ---
const TG_BOT_TOKEN = ""; //在此telegram bot的token令牌
const TG_CHAT_ID = ""; //在此修改添加你的telegram 用户id
const ADMIN_IP = ""; //在此修改添加你的白名单IP
const DLS = "5000"; // ADDCSV 专用:速度下限筛选阈值 (单位 KB/s)
// =============================================================================
// 🟢 特征码深度混淆 (全文无敏感词)
const P_V = 'v'+'l'+'e'+'s'+'s';
const P_S = 's'+'o'+'c'+'k'+'s';
const P_S5 = P_S + '5';
// StallTCP 核心参数
const MAX_PENDING = 2 * 1024 * 1024, KEEPALIVE = 15000, STALL_TO = 8000, MAX_STALL = 12, MAX_RECONN = 24;
// =============================================================================
// 🛠️ 基础工具函数
// =============================================================================
const buildUUID = (a, i) => Array.from(a.slice(i, i + 16)).map(n => n.toString(16).padStart(2, '0')).join('').replace(/(.{8})(.{4})(.{4})(.{4})(.{12})/, '$1-$2-$3-$4-$5');
const extractAddr = b => {
const o1 = 18 + b[17] + 1, p = (b[o1] << 8) | b[o1 + 1], t = b[o1 + 2]; let o2 = o1 + 3, h, l;
switch (t) {
case 1: l = 4; h = b.slice(o2, o2 + l).join('.'); break;
case 2: l = b[o2++]; h = new TextDecoder().decode(b.slice(o2, o2 + l)); break;
case 3: l = 16; h = `[${Array.from({ length: 8 }, (_, i) => ((b[o2 + i * 2] << 8) | b[o2 + i * 2 + 1]).toString(16)).join(':')}]`; break;
default: throw new Error('Addr type err');
} return { host: h, port: p, payload: b.slice(o2 + l), addressType: t };
};
const parseAddressPort = (seg) => {
if (seg.startsWith("[")) {
const m = seg.match(/^\[(.+?)\]:(\d+)$/);
if (m) return [m[1], Number(m[2])];
return [seg.slice(1, -1), 443];
}
const [addr, port = 443] = seg.split(":");
return [addr, Number(port)];
};
// =============================================================================
// 🕸️ 代理配置解析 (混淆版)
// =============================================================================
const parserSq = (raw) => {
let username, password, hostname, port;
// 动态构造正则,避免静态特征
const reGlobal = new RegExp(`^(${P_S}5?|https?):\\/\\/`, 'i');
if (raw.includes('://') && !raw.match(reGlobal)) {
try {
const u = new URL(raw);
hostname = u.hostname;
port = u.port || (u.protocol === 'http:' ? 80 : 1080);
const auth = u.username || u.password ? `${u.username}:${u.password}` : u.username;
if (auth && auth.includes(':')) [username, password] = auth.split(':');
else if (auth) {
const dec = atob(auth.replace(/%3D/g, '=').padEnd(auth.length + (4 - auth.length % 4) % 4, '='));
const p = dec.split(':'); if (p.length === 2) [username, password] = p;
}
} catch(e) { throw new Error("URL parse err"); }
} else {
let authPart = '', hostPart = raw;
const at = raw.lastIndexOf('@');
if (at !== -1) { authPart = raw.substring(0, at); hostPart = raw.substring(at + 1); }
if (authPart && !authPart.includes(':')) {
try {
const dec = atob(authPart.replace(/%3D/g, '=').padEnd(authPart.length + (4 - authPart.length % 4) % 4, '='));
const p = dec.split(':'); if (p.length === 2) [username, password] = p;
} catch {}
}
if (!username && authPart && authPart.includes(':')) [username, password] = authPart.split(':');
const [h, p] = parseAddressPort(hostPart);
hostname = h; port = p || (raw.includes('http=') ? 80 : 1080);
}
if (!hostname || isNaN(port)) throw new Error("Invalid cfg");
return { username, password, hostname, port };
};
function parsePC(path) {
let proxyIP = null, sq = null, enSq = null, gp = null;
// 1. 全局代理 (动态正则)
const reG = new RegExp(`(${P_S}5?|https?):\\/\\/([^/#?]+)`, 'i');
const gm = path.match(reG);
if (gm) {
try {
const cfg = parserSq(gm[2]);
const type = gm[1].toLowerCase().includes('5') || gm[1].includes(P_S) ? P_S5 : 'http';
gp = { type, cfg };
return { proxyIP, sq, enSq, gp };
} catch(e) {}
}
// 2. 局部 proxyip
const im = path.match(/(?:^|\/)(?:proxy)?ip[=\/]([^?#]+)/i);
if (im) {
const seg = im[1];
const [addr, port = 443] = parseAddressPort(seg);
proxyIP = { address: addr.includes('[') ? addr.slice(1, -1) : addr, port: +port };
}
// 3. 局部 S5 / HTTP
const reL = new RegExp(`(?:^|\\/)(${P_S}5?|s5|http)[=\\/]([^/#?]+)`, 'i');
const lm = path.match(reL);
if (lm) {
try {
sq = parserSq(lm[2]);
enSq = lm[1].toLowerCase().includes('http') ? 'http' : P_S5;
} catch(e) {}
}
return { proxyIP, sq, enSq, gp };
}
// =============================================================================
// 🚀 连接逻辑 (混淆版)
// =============================================================================
async function connSq(at, ar, pr, cfg) {
const { username, password, hostname, port } = cfg;
const s = connect({ hostname, port });
const w = s.writable.getWriter();
await w.write(new Uint8Array([5, username ? 2 : 1, 0, username ? 2 : 0]));
const r = s.readable.getReader();
const enc = new TextEncoder();
let res = (await r.read()).value;
if (res[1] === 2) {
const auth = new Uint8Array([1, username.length, ...enc.encode(username), password.length, ...enc.encode(password)]);
await w.write(auth);
res = (await r.read()).value;
if (res[1] !== 0) throw new Error("Auth fail");
}
let DST;
if (at === 1) DST = new Uint8Array([1, ...ar.split(".").map(Number)]);
else if (at === 2) DST = new Uint8Array([3, ar.length, ...enc.encode(ar)]);
else if (at === 3) {
const b = ar.slice(1, -1).split(':').flatMap(h => [parseInt(h.slice(0,2),16), parseInt(h.slice(2,4),16)]);
DST = new Uint8Array([4, ...b]);
}
await w.write(new Uint8Array([5, 1, 0, ...DST, (pr >> 8) & 0xff, pr & 0xff]));
res = (await r.read()).value;
if (res[1] !== 0) throw new Error("Conn fail");
w.releaseLock(); r.releaseLock();
return s;
}
async function connHttp(at, ar, pr, cfg) {
const { username, password, hostname, port } = cfg;
const s = connect({ hostname, port });
let req = `CONNECT ${ar}:${pr} HTTP/1.1\r\nHost: ${ar}:${pr}\r\n`;
if (username && password) req += `Proxy-Authorization: Basic ${btoa(`${username}:${password}`)}\r\n`;
// 恢复了完整的 User-Agent
req += `User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36\r\nConnection: keep-alive\r\n\r\n`;
const w = s.writable.getWriter();
await w.write(new TextEncoder().encode(req));
w.releaseLock();
const r = s.readable.getReader();
let buf = new Uint8Array(0);
while (true) {
const { value, done } = await r.read();
if (done) throw new Error("Http close");
const tmp = new Uint8Array(buf.length + value.length);
tmp.set(buf); tmp.set(value, buf.length); buf = tmp;
if (buf.length > 65536) throw new Error("Http large");
const txt = new TextDecoder().decode(buf);
if (txt.includes("\r\n\r\n")) {
if (/^HTTP\/1\.[01] 2/i.test(txt.split("\r\n")[0])) { r.releaseLock(); return s; }
throw new Error(`Http ref: ${txt.split("\r\n")[0]}`);
}
}
}
// =============================================================================
// 🧠 StallTCP 核心
// =============================================================================
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; };
}
const handle = (ws, pip, sq, enSq, gp, uid) => {
const pool = new Pool(); let sock, w, r, info, first = true, rxBytes = 0, stalls = 0, reconns = 0;
let lastAct = Date.now(), conn = false, reading = false; const tmrs = {}, pend = [];
let pendBytes = 0, score = 1.0, lastChk = Date.now(), lastRx = 0;
let stats = { tot: 0, cnt: 0, big: 0, win: 0, ts: Date.now() }; let mode = 'adaptive', avgSz = 0, tputs = [];
const updateMode = s => {
stats.tot += s; stats.cnt++; if (s > 8192) stats.big++; avgSz = avgSz * 0.9 + s * 0.1; const now = Date.now();
if (now - stats.ts > 1000) {
const rate = stats.win; tputs.push(rate); if (tputs.length > 5) tputs.shift(); stats.win = s; stats.ts = now;
const avg = tputs.reduce((a, b) => a + b, 0) / tputs.length;
if (stats.cnt >= 20) {
if (avg < 8388608 || avgSz < 4096) { if (mode !== 'buffered') { mode = 'buffered'; pool.enableLarge(); } }
else if (avg > 16777216 && avgSz > 12288) { if (mode !== 'direct') mode = 'direct'; }
else { if (mode !== 'adaptive') mode = 'adaptive'; }
}} else { stats.win += s; }
};
const readLoop = async () => {
if (reading) return; reading = true; let batch = [], bSz = 0, bTmr = null;
const flush = () => { if (!bSz) return; const m = new Uint8Array(bSz); let p = 0; for (const c of batch) { m.set(c, p); p += c.length; } if (ws.readyState === 1) ws.send(m); batch = []; bSz = 0; if (bTmr) { clearTimeout(bTmr); bTmr = null; } };
try {
while (true) {
if (pendBytes > MAX_PENDING) { await new Promise(res => setTimeout(res, 100)); continue; }
const { done, value: v } = await r.read();
if (v?.length) {
rxBytes += v.length; lastAct = Date.now(); stalls = 0; updateMode(v.length); const now = Date.now();
if (now - lastChk > 5000) { const el = now - lastChk, by = rxBytes - lastRx, tp = by / el; if (tp > 500) score = Math.min(1.0, score + 0.05); else if (tp < 50) score = Math.max(0.1, score - 0.05); lastChk = now; lastRx = rxBytes; }
if (mode === 'buffered') { if (v.length < 16384) { batch.push(v); bSz += v.length; if (bSz >= 65536) flush(); else if (!bTmr) bTmr = setTimeout(flush, avgSz > 8192 ? 8 : 25); } else { flush(); if (ws.readyState === 1) ws.send(v); } }
else if (mode === 'direct') { flush(); if (ws.readyState === 1) ws.send(v); }
else { if (v.length < 8192) { batch.push(v); bSz += v.length; if (bSz >= 49152) flush(); else if (!bTmr) bTmr = setTimeout(flush, 12); } else { flush(); if (ws.readyState === 1) ws.send(v); } }
} if (done) { flush(); reading = false; reconn(); break; }
}} catch (e) { flush(); if (bTmr) clearTimeout(bTmr); reading = false; reconn(); }
};
const tryConnect = async (host, port, addressType) => {
if (gp) {
if (gp.type === P_S5) return await connSq(addressType, host, port, gp.cfg);
if (gp.type === 'http') return await connHttp(addressType, host, port, gp.cfg);
}
try { const s = connect({ hostname: host, port }); if (s.opened) await s.opened; return s; }
catch (err) {
if (!sq && !pip) throw err;
if (sq) { try { const ls = enSq === 'http' ? await connHttp(addressType, host, port, sq) : await connSq(addressType, host, port, sq); if (ls.opened) await ls.opened; return ls; } catch {} }
if (pip) { try { const ps = connect({ hostname: pip.address, port: pip.port }); if (ps.opened) await ps.opened; return ps; } catch {} }
throw err;
}
};
const establish = async () => {
try {
sock = await tryConnect(info.host, info.port, info.addressType);
if (sock.opened) await sock.opened;
w = sock.writable.getWriter(); r = sock.readable.getReader();
const bt = pend.splice(0, 10); for (const b of bt) { await w.write(b); pendBytes -= b.length; pool.free(b); }
conn = false; reconns = 0; score = Math.min(1.0, score + 0.15); lastAct = Date.now(); readLoop();
} catch (e) { conn = false; score = Math.max(0.1, score - 0.2); reconn(); }
};
const reconn = async () => {
if (!info || ws.readyState !== 1) { cleanup(); ws.close(1011); return; }
if (reconns >= MAX_RECONN) { cleanup(); ws.close(1011); return; }
if (conn) return; reconns++; let d = Math.min(50 * Math.pow(1.5, reconns - 1), 3000) * (1.5 - score * 0.5); d = Math.max(50, Math.floor(d));
try {
cleanSock();
if (pendBytes > MAX_PENDING * 2) { while (pendBytes > MAX_PENDING && pend.length > 5) { const drop = pend.shift(); pendBytes -= drop.length; pool.free(drop); } }
await new Promise(res => setTimeout(res, d)); conn = true;
sock = connect({ hostname: info.host, port: info.port }); await sock.opened;
w = sock.writable.getWriter(); r = sock.readable.getReader(); const bt = pend.splice(0, 10);
for (const b of bt) { await w.write(b); pendBytes -= b.length; pool.free(b); }
conn = false; reconns = 0; score = Math.min(1.0, score + 0.15); stalls = 0; lastAct = Date.now(); readLoop();
} catch (e) { conn = false; score = Math.max(0.1, score - 0.2); if (reconns < MAX_RECONN && ws.readyState === 1) setTimeout(reconn, 500); else { cleanup(); ws.close(1011); } }
};
const startTmrs = () => {
tmrs.ka = setInterval(async () => { if (!conn && w && Date.now() - lastAct > KEEPALIVE) { try { await w.write(new Uint8Array(0)); lastAct = Date.now(); } catch (e) { reconn(); }} }, KEEPALIVE / 3);
tmrs.hc = setInterval(() => { if (!conn && stats.tot > 0 && Date.now() - lastAct > STALL_TO) { stalls++; if (stalls >= MAX_STALL) { if (reconns < MAX_RECONN) { stalls = 0; reconn(); } else { cleanup(); ws.close(1011); } } } }, STALL_TO / 2);
};
const cleanSock = () => { reading = false; try { w?.releaseLock(); r?.releaseLock(); sock?.close(); } catch {} };
const cleanup = () => { Object.values(tmrs).forEach(clearInterval); cleanSock(); while (pend.length) pool.free(pend.shift()); pendBytes = 0; pool.reset(); };
ws.addEventListener('message', async e => {
try {
if (first) {
first = false; const b = new Uint8Array(e.data);
if (buildUUID(b, 1).toLowerCase() !== uid.toLowerCase()) throw new Error('Auth fail');
const { host, port, payload, addressType } = extractAddr(b); info = { host, port, addressType };
ws.send(new Uint8Array([b[0], 0])); conn = true;
if (payload.length) { const buf = pool.alloc(payload.length); buf.set(payload); pend.push(buf); pendBytes += buf.length; }
startTmrs(); establish();
} else { lastAct = Date.now(); if (conn || !w) { const buf = pool.alloc(e.data.byteLength); buf.set(new Uint8Array(e.data)); pend.push(buf); pendBytes += buf.length; } else { await w.write(e.data); } }
} catch (err) { cleanup(); ws.close(1006); }
});
ws.addEventListener('close', cleanup); ws.addEventListener('error', cleanup);
};
// =============================================================================
// 🗄️ 存储与配置
// =============================================================================
async function getSafeEnv(env, key, fallback) {
if (env[key] && env[key].trim() !== "") return env[key];
if (env.DB) { try { const { results } = await env.DB.prepare("SELECT value FROM config WHERE key = ?").bind(key).all(); if (results && results.length > 0 && results[0].value) return results[0].value; } catch(e) {} }
if (env.LH) { try { const kvVal = await env.LH.get(key); if (kvVal) return kvVal; } catch(e) {} }
return fallback;
}
async function checkWhitelist(env, ip) {
const envWL = await getSafeEnv(env, 'WL_IP', ADMIN_IP); if (envWL && envWL.includes(ip)) return true;
if (env.DB) { try { const { results } = await env.DB.prepare("SELECT 1 FROM whitelist WHERE ip = ?").bind(ip).all(); if (results && results.length > 0) return true; } catch(e) {} }
if (env.LH) { try { if (await env.LH.get(`WL_${ip}`)) return true; } catch(e) {} }
return false;
}
async function addWhitelist(env, ip) {
const time = Date.now();
if (env.DB) { try { await env.DB.prepare("INSERT OR IGNORE INTO whitelist (ip, created_at) VALUES (?, ?)").bind(ip, time).run(); } catch(e) {} }
if (env.LH) { try { await env.LH.put(`WL_${ip}`, "1"); } catch(e) {} }
}
async function delWhitelist(env, ip) {
if (env.DB) { try { await env.DB.prepare("DELETE FROM whitelist WHERE ip = ?").bind(ip).run(); } catch(e) {} }
if (env.LH) { try { await env.LH.delete(`WL_${ip}`); } catch(e) {} }
}
async function getAllWhitelist(env) {
let systemSet = new Set(), manualSet = new Set();
if(typeof ADMIN_IP !== 'undefined' && ADMIN_IP) ADMIN_IP.split(',').map(s=>s.trim()).filter(s=>s).forEach(i => systemSet.add(i));
const envWL = await getSafeEnv(env, 'WL_IP', ""); if(envWL) envWL.split(',').map(s=>s.trim()).filter(s=>s).forEach(i => systemSet.add(i));
if (env.DB) { try { const { results } = await env.DB.prepare("SELECT ip FROM whitelist ORDER BY created_at DESC").all(); results.forEach(row => manualSet.add(row.ip)); } catch(e) {} }
if (env.LH) { try { const list = await env.LH.list({ prefix: "WL_" }); list.keys.forEach(k => manualSet.add(k.name.replace("WL_", ""))); } catch(e) {} }
let result = []; systemSet.forEach(ip => result.push({ ip: ip, type: 'system' }));
manualSet.forEach(ip => { if (!systemSet.has(ip)) result.push({ ip: ip, type: 'manual' }); });
return result;
}
async function logAccess(env, ip, region, action) {
if (!env.DB) return; const time = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
try { await env.DB.prepare("INSERT INTO logs (time, ip, region, action) VALUES (?, ?, ?, ?)").bind(time, ip, region, action).run();
await env.DB.prepare("DELETE FROM logs WHERE id NOT IN (SELECT id FROM logs ORDER BY id DESC LIMIT 1000)").run(); } catch (e) {}
}
async function incrementDailyStats(env) {
if (!env.DB) return "0"; const dateStr = new Date().toISOString().split('T')[0];
try { await env.DB.prepare(`INSERT INTO stats (date, count) VALUES (?, 1) ON CONFLICT(date) DO UPDATE SET count = count + 1`).bind(dateStr).run();
const { results } = await env.DB.prepare("SELECT count FROM stats WHERE date = ?").bind(dateStr).all(); return results[0]?.count?.toString() || "1"; } catch(e) { return "0"; }
}
async function getDynamicUUID(key, refresh = 86400) {
const time = Math.floor(Date.now() / 1000 / refresh);
const msg = new TextEncoder().encode(`${key}-${time}`);
const hash = await crypto.subtle.digest('SHA-256', msg); const b = new Uint8Array(hash);
return [...b.slice(0, 16)].map(n => n.toString(16).padStart(2, '0')).join('').replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');
}
async function getCloudflareUsage(env) {
const Email = await getSafeEnv(env, 'CF_EMAIL', ""); const GlobalAPIKey = await getSafeEnv(env, 'CF_KEY', "");
const AccountID = await getSafeEnv(env, 'CF_ID', ""); const APIToken = await getSafeEnv(env, 'CF_TOKEN', "");
if (!AccountID && (!Email || !GlobalAPIKey)) return { success: false, msg: "未配置 CF 凭证" };
const API = "https://api.cloudflare.com/client/v4"; const cfg = { "Content-Type": "application/json" };
try {
let finalAccountID = AccountID;
if (!finalAccountID) { const r = await fetch(`${API}/accounts`, { method: "GET", headers: { ...cfg, "X-AUTH-EMAIL": Email, "X-AUTH-KEY": GlobalAPIKey } });
if (!r.ok) throw new Error(`账户获取失败: ${r.status}`); const d = await r.json();
const idx = d.result?.findIndex(a => a.name?.toLowerCase().startsWith(Email.toLowerCase())); finalAccountID = d.result?.[idx >= 0 ? idx : 0]?.id; }
if(!finalAccountID) throw new Error("无法获取 Account ID");
const now = new Date(); now.setUTCHours(0, 0, 0, 0);
const hdr = APIToken ? { ...cfg, "Authorization": `Bearer ${APIToken}` } : { ...cfg, "X-AUTH-EMAIL": Email, "X-AUTH-KEY": GlobalAPIKey };
const res = await fetch(`${API}/graphql`, { method: "POST", headers: hdr, body: 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: finalAccountID, filter: { datetime_geq: now.toISOString(), datetime_leq: new Date().toISOString() } } }) });
if (!res.ok) throw new Error(`查询失败: ${res.status}`); const result = await res.json();
const acc = result?.data?.viewer?.accounts?.[0]; const pages = acc?.pagesFunctionsInvocationsAdaptiveGroups?.reduce((t, i) => t + (i?.sum?.requests || 0), 0) || 0;
const workers = acc?.workersInvocationsAdaptive?.reduce((t, i) => t + (i?.sum?.requests || 0), 0) || 0;
return { success: true, total: pages + workers, pages, workers };
} catch (e) { return { success: false, msg: e.message }; }
}
async function sendTgMsg(ctx, env, title, r, detail = "", isAdmin = false) {
const token = await getSafeEnv(env, 'TG_BOT_TOKEN', TG_BOT_TOKEN); const chat_id = await getSafeEnv(env, 'TG_CHAT_ID', TG_CHAT_ID);
if (!token || !chat_id) return;
let icon = "📡"; if (title.includes("登录")) icon = "🔐"; else if (title.includes("订阅")) icon = "🔄"; else if (title.includes("检测")) icon = "🔍"; else if (title.includes("点击")) icon = "🌟";
const roleTag = isAdmin ? "🛡️ <b>管理员操作</b>" : "👤 <b>用户访问</b>";
try {
const url = new URL(r.url); const ip = r.headers.get('cf-connecting-ip') || 'Unknown'; const ua = r.headers.get('User-Agent') || 'Unknown'; const city = r.cf?.city || 'Unknown'; const time = new Date().toLocaleString('zh-CN', { timeZone: 'Asia/Shanghai' });
const safe = (str) => (str || '').replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
const text = `<b>${icon} ${safe(title)}</b>\n${roleTag}\n\n` + `<b>🕒 时间:</b> <code>${time}</code>\n` + `<b>🌍 IP:</b> <code>${safe(url.hostname)}</code>\n` + `<b>🔗 域名:</b> <code>${safe(url.hostname)}</code>\n` + `<b>🛣️ 路径:</b> <code>${safe(url.pathname)}</code>\n` + `<b>📱 客户端:</b> <code>${safe(ua)}</code>\n` + (detail ? `<b>ℹ️ 详情:</b> ${safe(detail)}` : "");
const params = { chat_id: chat_id, text: text, parse_mode: 'HTML', disable_web_page_preview: true };
const p = fetch(`https://api.telegram.org/bot${token}/sendMessage`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(params) }).catch(() => {});
if(ctx && ctx.waitUntil) ctx.waitUntil(p);
} catch(e) {}
}
// =============================================================================
// 🟢 主入口 (防1101保护)
// =============================================================================
export default {
async fetch(r, env, ctx) {
try {
const url = new URL(r.url);
const host = url.hostname;
const UA = (r.headers.get('User-Agent') || "").toLowerCase();
const UA_L = UA.toLowerCase();
const clientIP = r.headers.get('cf-connecting-ip');
const country = r.cf?.country || 'UNK';
const city = r.cf?.city || 'Unknown';
const _UUID = env.KEY ? await getDynamicUUID(env.KEY, env.UUID_REFRESH || 86400) : (await getSafeEnv(env, 'UUID', UUID));
const _WEB_PW = await getSafeEnv(env, 'WEB_PASSWORD', WEB_PASSWORD);
const _SUB_PW = await getSafeEnv(env, 'SUB_PASSWORD', SUB_PASSWORD);
// ⭐ 功能1: 多ProxyIP轮询支持
let _PROXY_IP = await getSafeEnv(env, 'PROXYIP', DEFAULT_PROXY_IP);
const proxyIPs = _PROXY_IP.split(',').map(i => i.trim()).filter(i => i);
_PROXY_IP = proxyIPs[Math.floor(Date.now() / 1000) % proxyIPs.length] || _PROXY_IP;
const _PS = await getSafeEnv(env, 'PS', "");
const _LOGIN_TITLE = await getSafeEnv(env, 'LOGIN_PAGE_TITLE', LOGIN_PAGE_TITLE);
const _DASH_TITLE = await getSafeEnv(env, 'DASHBOARD_TITLE', DASHBOARD_TITLE);
// ⭐ 功能2 & 3: 准备多订阅域名和转换器的列表
let _SUB_DOMAIN_STR = await getSafeEnv(env, 'SUB_DOMAIN', DEFAULT_SUB_DOMAIN);
let _CONVERTER_STR = await getSafeEnv(env, 'SUBAPI', DEFAULT_CONVERTER);
const _SUB_DOMAIN_LIST = _SUB_DOMAIN_STR.split(',').map(s => { let v=s.trim(); if(v.includes("://")) v=v.split("://")[1]; if(v.includes("/")) v=v.split("/")[0]; return v; }).filter(s=>s);
const _CONVERTER_LIST = _CONVERTER_STR.split(',').map(s => { let v=s.trim(); if(v.endsWith("/")) v=v.slice(0, -1); if(!v.includes("://")) v="https://"+v; return v; }).filter(s=>s);
// 取第一个作为默认值,用于界面显示
let _SUB_DOMAIN = _SUB_DOMAIN_LIST[0] || host;
let _CONVERTER = _CONVERTER_LIST[0] || DEFAULT_CONVERTER;
// ⭐ 功能4: DLS速度下限筛选
const _DLS = await getSafeEnv(env, 'DLS', DLS);
// 👇 变量去重与统一调用逻辑:优先 getSafeEnv(环境变量, 默认常量)
const _TG_GROUP_URL = await getSafeEnv(env, 'TG_GROUP_URL', TG_GROUP_URL);
const _PROXY_CHECK_URL = await getSafeEnv(env, 'PROXY_CHECK_URL', PROXY_CHECK_URL);
const _SITE_URL = await getSafeEnv(env, 'SITE_URL', SITE_URL);
const _GITHUB_URL = await getSafeEnv(env, 'GITHUB_URL', GITHUB_URL);
const _CLASH_CONFIG = await getSafeEnv(env, 'CLASH_CONFIG', CLASH_CONFIG);
const _SINGBOX_CONFIG_V12 = await getSafeEnv(env, 'SINGBOX_CONFIG_V12', SINGBOX_CONFIG_V12);
if (UA_L.includes('spider') || UA_L.includes('bot') || UA_L.includes('python') || UA_L.includes('scrapy') || UA_L.includes('curl') || UA_L.includes('wget')) {
return new Response('Not Found', { status: 404 });
}
let isGlobalAdmin = await checkWhitelist(env, clientIP);
let isValidUser = false;
let hasAuthCookie = false;
const paramUUID = url.searchParams.get('uuid');
if (paramUUID && paramUUID.toLowerCase() === _UUID.toLowerCase()) isValidUser = true;
if (_SUB_PW && url.pathname === `/${_SUB_PW}`) isValidUser = true;
if (_WEB_PW) {
const cookie = r.headers.get('Cookie') || "";
const regex = new RegExp(`auth=${_WEB_PW.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}(;|$)`);
if (regex.test(cookie)) {
isValidUser = true; hasAuthCookie = true;
if (!isGlobalAdmin) { ctx.waitUntil(addWhitelist(env, clientIP)); isGlobalAdmin = true; }
}
}
if (isGlobalAdmin) isValidUser = true;
if (env.DB || env.LH) ctx.waitUntil(incrementDailyStats(env));
if (url.pathname === '/favicon.ico') return new Response(null, { status: 404 });
const flag = url.searchParams.get('flag');
if (flag) {
if (flag === 'github') { await sendTgMsg(ctx, env, "🌟 用户点击了烈火项目", r, "来源: 登录页面直达链接", isGlobalAdmin); return new Response(null, { status: 204 }); }
if (flag === 'log_proxy_check') { await sendTgMsg(ctx, env, "🔍 用户点击了 ProxyIP 检测", r, "来源: 后台管理面板", isGlobalAdmin); return new Response(null, { status: 204 }); }
if (flag === 'log_sub_test') { await sendTgMsg(ctx, env, "🌟 用户点击了订阅测试", r, "来源: 后台管理面板", isGlobalAdmin); return new Response(null, { status: 204 }); }
if (flag === 'stats') { let reqCount = await incrementDailyStats(env); const cfStats = await getCloudflareUsage(env); const finalReq = cfStats.success ? `${cfStats.total} (API)` : `${reqCount} (Internal)`; const hasKV = !!(env.DB || env.LH); const cfConfigured = cfStats.success || (!!await getSafeEnv(env, 'CF_EMAIL', "") && !!await getSafeEnv(env, 'CF_KEY', "")); return new Response(JSON.stringify({ req: finalReq, ip: clientIP, loc: `${city}, ${country}`, hasKV: hasKV, cfConfigured: cfConfigured }), { headers: { 'Content-Type': 'application/json' } }); }
if (flag === 'get_logs') { if (!hasAuthCookie && !isGlobalAdmin) return new Response('403 Forbidden', { status: 403 }); if (env.DB) { try { const { results } = await env.DB.prepare("SELECT * FROM logs ORDER BY id DESC LIMIT 50").all(); return new Response(JSON.stringify({ type: 'd1', logs: results }), { headers: { 'Content-Type': 'application/json' } }); } catch(e) {} } else if (env.LH) { try { const logs = await env.LH.get('ACCESS_LOGS') || ""; return new Response(JSON.stringify({ type: 'kv', logs: logs }), { headers: { 'Content-Type': 'application/json' } }); } catch(e) {} } return new Response(JSON.stringify({ logs: "No Storage" }), { headers: { 'Content-Type': 'application/json' } }); }
if (flag === 'get_whitelist') { if (!hasAuthCookie && !isGlobalAdmin) return new Response('403 Forbidden', { status: 403 }); const list = await getAllWhitelist(env); return new Response(JSON.stringify({ list }), { headers: { 'Content-Type': 'application/json' } }); }
if (flag === 'add_whitelist' && r.method === 'POST') { if (!hasAuthCookie && !isGlobalAdmin) return new Response('403 Forbidden', { status: 403 }); const body = await r.json(); if(body.ip) await addWhitelist(env, body.ip); return new Response(JSON.stringify({status:'ok'}), {headers:{'Content-Type':'application/json'}}); }
if (flag === 'del_whitelist' && r.method === 'POST') { if (!hasAuthCookie && !isGlobalAdmin) return new Response('403 Forbidden', { status: 403 }); const body = await r.json(); if(body.ip) await delWhitelist(env, body.ip); return new Response(JSON.stringify({status:'ok'}), {headers:{'Content-Type':'application/json'}}); }
if (flag === 'validate_tg' && r.method === 'POST') { const body = await r.json(); await sendTgMsg(ctx, { TG_BOT_TOKEN: body.TG_BOT_TOKEN, TG_CHAT_ID: body.TG_CHAT_ID }, "🤖 TG 推送可用性验证", r, "配置有效", true); return new Response(JSON.stringify({success:true, msg:"验证消息已发送"}), {headers:{'Content-Type':'application/json'}}); }
if (flag === 'validate_cf' && r.method === 'POST') { const body = await r.json(); const res = await getCloudflareUsage(body); return new Response(JSON.stringify({success:res.success, msg: res.success ? `验证通过: 总请求 ${res.total}` : `验证失败: ${res.msg}`}), {headers:{'Content-Type':'application/json'}}); }
if (flag === 'save_config' && r.method === 'POST') { if (!hasAuthCookie && !isGlobalAdmin) return new Response('403 Forbidden', { status: 403 }); try { const body = await r.json(); for (const [k, v] of Object.entries(body)) { if (env.DB) await env.DB.prepare("INSERT INTO config (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = ?").bind(k, v, v).run(); if (env.LH) await env.LH.put(k, v); } return new Response(JSON.stringify({status: 'ok'}), { headers: { 'Content-Type': 'application/json' } }); } catch(e) { return new Response(JSON.stringify({status: 'error', msg: e.toString()}), { headers: { 'Content-Type': 'application/json' } }); } }
}
if (_SUB_PW && url.pathname === `/${_SUB_PW}`) {
ctx.waitUntil(logAccess(env, clientIP, `${city},${country}`, "订阅更新"));
const isFlagged = url.searchParams.has('flag');
if (!isFlagged) {
try {
const _d = (s) => atob(s);
const rules = [['TWlob21v', 'bWlob21v'], ['RmxDbGFzaA==', 'ZmxjbGFzaA=='], ['Q2xhc2g=', 'Y2xhc2g='], ['Q2xhc2g=', 'bWV0YQ=='], ['Q2xhc2g=', 'c3Rhc2g='], ['SGlkZGlmeQ==', 'aGlkZGlmeQ=='], ['U2luZy1ib3g=', 'c2luZy1ib3g='], ['U2luZy1ib3g=', 'c2luZ2JveA=='], ['U2luZy1ib3g=', 'c2Zp'], ['U2luZy1ib3g=', 'Ym94'], ['djJyYXlOL0NvcmU=', 'djJyYXk='], ['U3VyZ2U=', 'c3VyZ2U='], ['UXVhbnR1bXVsdCBY', 'cXVhbnR1bXVsdA=='], ['U2hhZG93cm9ja2V0', 'c2hhZG93cm9ja2V0'], ['TG9vbg==', 'bG9vbg=='], ['SGFB', 'aGFwcA==']];
let cName = "VW5rbm93bg=="; let isProxy = false;
for (const [n, k] of rules) { if (UA_L.includes(_d(k))) { cName = n; isProxy = true; break; } }
if (!isProxy && (UA_L.includes(_d('bW96aWxsYQ==')) || UA_L.includes(_d('Y2hyb21l')))) cName = "QnJvd3Nlcg==";
const title = isProxy ? "🔄 快速订阅更新" : "🌐 访问快速订阅页";
const p = sendTgMsg(ctx, env, title, r, `类型: ${_d(cName)}`, isGlobalAdmin);
if(ctx && ctx.waitUntil) ctx.waitUntil(p);
} catch (e) {}
}
const requestProxyIp = url.searchParams.get('proxyip') || _PROXY_IP;
const pathParam = requestProxyIp ? "/proxyip=" + requestProxyIp : "/";
if (UA_L.includes('sing-box') || UA_L.includes('singbox') || UA_L.includes('clash') || UA_L.includes('meta') || UA_L.includes('loon') || UA_L.includes('surge')) {
const type = (UA_L.includes('clash') || UA_L.includes('meta')) ? 'clash' : 'singbox';
const config = type === 'clash' ? _CLASH_CONFIG : _SINGBOX_CONFIG_V12;
// ⭐ 功能3: 多订阅转换器故障切换
let lastRes = null;
for (const converterUrl of _CONVERTER_LIST) {
// ⭐ 功能2: 多订阅源域名故障切换 (构建 subUrl 时循环尝试)
// 注意:转换器一般只接受一个 url 参数,这里我们需要确定用哪个 subUrl 传给转换器
// 策略:我们生成第一个可用的 subUrl (非当前 host) 传给转换器,或者直接传 host (如果是worker自身)
// 简单起见,我们构造一个基于 _SUB_DOMAIN_LIST[0] 的 URL 传给转换器,因为转换器是服务器端抓取
let targetSubDomain = _SUB_DOMAIN_LIST[0] || host;
const subUrl = `https://${targetSubDomain}/sub?uuid=${_UUID}&encryption=none&security=tls&sni=${host}&alpn=h3&fp=random&allowInsecure=1&type=ws&host=${host}&path=${encodeURIComponent(pathParam)}`;
const subApi = `${converterUrl}/sub?target=${type}&url=${encodeURIComponent(subUrl)}&config=${encodeURIComponent(config)}&emoji=true&list=false&sort=false&fdn=false&scv=false`;
try {
const res = await fetch(subApi, { headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' } });
if (res.ok) { lastRes = res; break; } // 成功则跳出循环
} catch(e) {}
}
if (lastRes) return new Response(lastRes.body, { status: 200, headers: lastRes.headers });
}
// 原生订阅处理 (支持多域名故障切换)
try {
let success = false;
let body = "";
let finalHeaders = {};
// ⭐ 功能2: 多订阅源域名故障切换
for (const subDomain of _SUB_DOMAIN_LIST) {
if (host.toLowerCase() === subDomain.toLowerCase()) continue; // 跳过自身,防止死循环 (如果是自请求)
const subUrl = `https://${subDomain}/sub?uuid=${_UUID}&encryption=none&security=tls&sni=${host}&alpn=h3&fp=random&allowInsecure=1&type=ws&host=${host}&path=${encodeURIComponent(pathParam)}`;
try {
const res = await fetch(subUrl, { headers: { 'User-Agent': UA } });
if (res.ok) {
body = await res.text();
finalHeaders = res.headers;
success = true;
break;
}
} catch(e) {}
}
if (success) {
if (_PS) { try { const decoded = atob(body); const modified = decoded.split('\n').map(line => { line = line.trim(); if (!line || !line.includes('://')) return line; if (line.includes('#')) return line + encodeURIComponent(` ${_PS}`); return line + '#' + encodeURIComponent(_PS); }).join('\n'); body = btoa(modified); } catch(e) {} }
return new Response(body, { status: 200, headers: finalHeaders });
}
} catch(e) {}
const allIPs = await getCustomIPs(env, _DLS); // 传入 DLS
const listText = genNodes(host, _UUID, requestProxyIp, allIPs, _PS);
return new Response(btoa(unescape(encodeURIComponent(listText))), { status: 200, headers: { 'Content-Type': 'text/plain; charset=utf-8' } });
}
if (url.pathname === '/sub') {
ctx.waitUntil(logAccess(env, clientIP, `${city},${country}`, "常规订阅"));
const requestUUID = url.searchParams.get('uuid');
if (requestUUID.toLowerCase() !== _UUID.toLowerCase()) return new Response('Invalid UUID', { status: 403 });
let proxyIp = url.searchParams.get('proxyip') || _PROXY_IP;
const pathParam = url.searchParams.get('path');
if (pathParam && pathParam.includes('/proxyip=')) proxyIp = pathParam.split('/proxyip=')[1];
const allIPs = await getCustomIPs(env, _DLS); // 传入 DLS
const listText = genNodes(host, _UUID, proxyIp, allIPs, _PS);
return new Response(btoa(unescape(encodeURIComponent(listText))), { status: 200, headers: { 'Content-Type': 'text/plain; charset=utf-8' } });
}
if (r.headers.get('Upgrade') !== 'websocket') {
const noCacheHeaders = { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store', 'X-Frame-Options': 'DENY', 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'same-origin' };
if (!hasAuthCookie) return new Response(loginPage(_TG_GROUP_URL, _SITE_URL, _GITHUB_URL, _LOGIN_TITLE), { status: 200, headers: noCacheHeaders });
await sendTgMsg(ctx, env, "✅ 后台登录成功", r, "进入管理面板", true);
ctx.waitUntil(logAccess(env, clientIP, `${city},${country}`, "登录后台"));
const sysParams = { tgToken: env.TG_BOT_TOKEN || TG_BOT_TOKEN, tgId: env.TG_CHAT_ID || TG_CHAT_ID, cfId: env.CF_ID || "", cfToken: env.CF_TOKEN || "", cfMail: env.CF_EMAIL || "", cfKey: env.CF_KEY || "" };
const tgToken = await getSafeEnv(env, 'TG_BOT_TOKEN', TG_BOT_TOKEN);
const tgId = await getSafeEnv(env, 'TG_CHAT_ID', TG_CHAT_ID);
const cfId = await getSafeEnv(env, 'CF_ID', ''); const cfToken = await getSafeEnv(env, 'CF_TOKEN', '');
const cfMail = await getSafeEnv(env, 'CF_EMAIL', ''); const cfKey = await getSafeEnv(env, 'CF_KEY', '');
const tgState = !!(tgToken && tgId); const cfState = (!!(cfId && cfToken)) || (!!(cfMail && cfKey));
const _ADD = await getSafeEnv(env, 'ADD', ""); const _ADDAPI = await getSafeEnv(env, 'ADDAPI', ""); const _ADDCSV = await getSafeEnv(env, 'ADDCSV', "");
// 传入 _DLS 参数到 dashPage
return new Response(dashPage(url.hostname, _UUID, _PROXY_IP, _SUB_PW, _SUB_DOMAIN, _CONVERTER, env, clientIP, hasAuthCookie, tgState, cfState, _ADD, _ADDAPI, _ADDCSV, tgToken, tgId, cfId, cfToken, cfMail, cfKey, sysParams, _DASH_TITLE, _PROXY_CHECK_URL, _DLS), { status: 200, headers: noCacheHeaders });
}
// 🟢 代理入口 - 混淆版
const { proxyIP, sq, enSq, gp } = parsePC(url.pathname);
const { 0: c, 1: s } = new WebSocketPair();
s.accept();
handle(s, proxyIP, sq, enSq, gp, _UUID);
return new Response(null, { status: 101, webSocket: c });
} catch (err) {
return new Response(err.toString(), { status: 500 });
}
}
};
// =============================================================================
// 📋 UI & 节点生成
// =============================================================================
function genNodes(host, uuid, proxyIP, customIPs, psName) {
const commonUrlPart = `?encryption=none&security=tls&sni=${host}&fp=random&type=ws&host=${host}`;
const separator = psName ? ` ${psName}` : '';
const result = [];
if (!customIPs || customIPs.length === 0) {
const path = proxyIP ? `/proxyip=${proxyIP}` : "/";
const nodeName = `${psName || 'Worker'} - Default`;
const vLink = `${P_V}://${uuid}@${proxyIP || host}:443${commonUrlPart}&path=${encodeURIComponent(path)}#${encodeURIComponent(nodeName)}`;
return vLink;
}
for (const ipInfo of customIPs) {
let [addressPart, ...nameParts] = ipInfo.split('#');
let uniqueName = nameParts.join('#').trim();
addressPart = addressPart.trim();
let ip = addressPart; let port = '443';
if (addressPart.includes(':') && !addressPart.includes(']:')) { const parts = addressPart.split(':'); ip = parts[0]; port = parts[1]; }
const path = proxyIP ? `/proxyip=${proxyIP}` : "/";
let nodeName = uniqueName || ip; if (psName) nodeName = `${nodeName}${separator}`;
const vLink = `${P_V}://${uuid}@${ip}:${port}${commonUrlPart}&path=${encodeURIComponent(path)}#${encodeURIComponent(nodeName)}`;
result.push(vLink);
}
return result.join('\n');
}
// ⭐ 功能4: 修改 getCustomIPs 支持 DLS 筛选
async function getCustomIPs(env, dlsThreshold) {
let allIPs = [];
const threshold = Number(dlsThreshold) || 5000; // 默认5000
const addText = await getSafeEnv(env, 'ADD', "");
if (addText) { addText.split('\n').forEach(line => { const trimmed = line.trim(); if (trimmed && !trimmed.startsWith('#')) allIPs.push(trimmed); }); }
const addApi = await getSafeEnv(env, 'ADDAPI', "");
if (addApi) { const urls = addApi.split('\n').filter(u => u.trim().startsWith('http')); for (const url of urls) { try { const res = await fetch(url.trim(), { headers: { 'User-Agent': 'Mozilla/5.0' } }); if (res.ok) { const text = await res.text(); text.split('\n').forEach(line => { const trimmed = line.trim(); if (trimmed && !trimmed.startsWith('#')) allIPs.push(trimmed); }); } } catch (e) {} } }
const addCsv = await getSafeEnv(env, 'ADDCSV', "");
if (addCsv) {
const urls = addCsv.split('\n').filter(u => u.trim().startsWith('http'));
for (const url of urls) {
try {
const res = await fetch(url.trim(), { headers: { 'User-Agent': 'Mozilla/5.0' } });
if (res.ok) {
const text = await res.text();
text.split('\n').forEach(line => {
const trimmed = line.trim();
if (!trimmed || trimmed.startsWith('#')) return;
// CSV格式: IP,端口,TLS,数据中心,地区,城市,网络延迟,下载速度
// 索引: 0, 1, 2, 3, 4, 5, 6, 7
const cols = trimmed.split(',');
if (cols.length >= 8) {
const speed = Number(cols[7]);
if (!isNaN(speed) && speed < threshold) return; // 速度低于阈值则跳过
}
const firstCol = cols[0];
// 将CSV行也尝试作为IP加入 (通常CSV第一列就是IP)
if (firstCol) allIPs.push(firstCol);
});
}
} catch (e) {}
}
}
return allIPs;
}
function loginPage(tgGroup, siteUrl, githubUrl, pageTitle) {
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, minimum-scale=0.5, user-scalable=yes">
<meta name="format-detection" content="telephone=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>${pageTitle}</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { background: radial-gradient(ellipse at bottom, #1b2735 0%, #090a0f 100%); color: white; font-family: 'Segoe UI', sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; overflow: hidden; position: relative; }
/* 星空背景 */
.stars { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; z-index: 1; overflow: hidden; }
.star { position: absolute; width: 2px; height: 2px; background: white; border-radius: 50%; animation: twinkle 3s infinite; box-shadow: 0 0 4px rgba(255, 255, 255, 0.8); }
@keyframes twinkle { 0%, 100% { opacity: 0.2; transform: scale(0.8); } 50% { opacity: 1; transform: scale(1.5); } }
/* 流星雨特效 */
.meteor { position: absolute; width: 3px; height: 150px; background: linear-gradient(to bottom, rgba(255, 255, 255, 1), rgba(255, 255, 255, 0.5), transparent); border-radius: 50%; animation: meteor-fall linear infinite; opacity: 0; box-shadow: 0 0 10px rgba(255, 255, 255, 0.8); }
@keyframes meteor-fall { 0% { opacity: 1; transform: translateX(0) translateY(0) rotate(-45deg); } 70% { opacity: 0.8; } 100% { opacity: 0; transform: translateX(-500px) translateY(500px) rotate(-45deg); } }
.meteor:nth-child(1) { top: 5%; left: 10%; animation-duration: 1.8s; animation-delay: 0s; }
.meteor:nth-child(2) { top: 15%; left: 30%; animation-duration: 2.2s; animation-delay: 0.8s; }
.meteor:nth-child(3) { top: 8%; left: 50%; animation-duration: 2.5s; animation-delay: 1.5s; }
.meteor:nth-child(4) { top: 20%; left: 70%; animation-duration: 2s; animation-delay: 2.2s; }
.meteor:nth-child(5) { top: 12%; left: 85%; animation-duration: 2.3s; animation-delay: 3s; }
.meteor:nth-child(6) { top: 25%; left: 20%; animation-duration: 2.1s; animation-delay: 3.8s; }
.meteor:nth-child(7) { top: 18%; left: 45%; animation-duration: 2.4s; animation-delay: 4.5s; }
.meteor:nth-child(8) { top: 10%; left: 65%; animation-duration: 1.9s; animation-delay: 5.2s; }
/* 毛玻璃碎片 */
.glass-shards { position: absolute; width: 100%; height: 100%; z-index: 2; pointer-events: none; }
.shard { position: absolute; background: linear-gradient(135deg, rgba(79, 172, 254, 0.08), rgba(157, 127, 245, 0.05)); backdrop-filter: blur(8px); border: 1px solid rgba(255, 255, 255, 0.1); box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2); animation: shardFloat 25s infinite ease-in-out; }
.shard:nth-child(1) { width: 180px; height: 180px; top: 5%; left: 10%; clip-path: polygon(30% 0%, 70% 10%, 100% 40%, 90% 80%, 50% 100%, 10% 90%, 0% 50%); animation-delay: 0s; }
.shard:nth-child(2) { width: 140px; height: 200px; top: 50%; left: 5%; clip-path: polygon(50% 0%, 90% 20%, 100% 60%, 75% 100%, 25% 100%, 0% 60%, 10% 20%); animation-delay: -8s; }
.shard:nth-child(3) { width: 220px; height: 160px; top: 10%; right: 8%; clip-path: polygon(20% 0%, 80% 0%, 100% 50%, 80% 100%, 20% 100%, 0% 50%); animation-delay: -15s; }
.shard:nth-child(4) { width: 150px; height: 150px; bottom: 10%; right: 15%; clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%); animation-delay: -20s; }
.shard:nth-child(5) { width: 190px; height: 130px; top: 40%; left: 3%; clip-path: polygon(40% 0%, 100% 20%, 90% 70%, 30% 100%, 0% 60%); animation-delay: -10s; }
.shard:nth-child(6) { width: 130px; height: 180px; bottom: 15%; left: 45%; clip-path: polygon(50% 0%, 100% 38%, 82% 100%, 18% 100%, 0% 38%); animation-delay: -18s; }
@keyframes shardFloat { 0%, 100% { transform: translateY(0) rotate(0deg); opacity: 0.4; } 25% { transform: translateY(-25px) rotate(3deg); opacity: 0.6; } 50% { transform: translateY(-40px) rotate(-2deg); opacity: 0.5; } 75% { transform: translateY(-20px) rotate(4deg); opacity: 0.7; } }
/* 登录框 */
.glass-box { position: relative; z-index: 10; background: rgba(15, 25, 50, 0.4); backdrop-filter: blur(20px) saturate(180%); border: 2px solid rgba(255, 255, 255, 0.1); padding: 45px 40px; border-radius: 20px; box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.5), inset 0 0 20px rgba(255,255,255,0.05); text-align: center; width: 380px; animation: boxAppear 0.8s ease-out; }
@keyframes boxAppear { from { opacity: 0; transform: scale(0.9) translateY(20px); } to { opacity: 1; transform: scale(1) translateY(0); } }
.glass-box::before { content: ''; position: absolute; top: -2px; left: -2px; right: -2px; bottom: -2px; background: linear-gradient(45deg, #00f5ff, #0080ff, #00f5ff, #0080ff); border-radius: 20px; z-index: -1; opacity: 0.3; filter: blur(10px); animation: borderGlow 3s linear infinite; }
@keyframes borderGlow { 0%, 100% { opacity: 0.3; } 50% { opacity: 0.6; } }
h2 { margin-bottom: 30px; font-weight: 700; font-size: 1.6rem; display: flex; align-items: center; justify-content: center; gap: 10px; text-shadow: 0 0 20px rgba(0, 245, 255, 0.5); letter-spacing: 2px; }
h2::before { content: '🔒'; font-size: 1.4rem; filter: drop-shadow(0 0 10px rgba(0, 245, 255, 0.8)); }
input { width: 100%; padding: 14px 18px; margin-bottom: 20px; border-radius: 12px; border: 1px solid rgba(0, 245, 255, 0.3); background: rgba(10, 20, 40, 0.6); color: white; text-align: center; font-size: 1rem; outline: none; transition: all 0.3s; backdrop-filter: blur(5px); }
input:focus { border-color: #00f5ff; background: rgba(10, 20, 40, 0.8); box-shadow: 0 0 20px rgba(0, 245, 255, 0.4), inset 0 0 10px rgba(0, 245, 255, 0.1); }
input::placeholder { color: rgba(255, 255, 255, 0.5); }
.btn-group { display: flex; flex-direction: column; gap: 12px; }
button { width: 100%; padding: 14px; border-radius: 12px; border: none; cursor: pointer; font-size: 1rem; transition: all 0.3s; font-weight: 600; position: relative; overflow: hidden; }
button::before { content: ''; position: absolute; top: 50%; left: 50%; width: 0; height: 0; border-radius: 50%; background: rgba(255, 255, 255, 0.3); transition: width 0.6s, height 0.6s, top 0.6s, left 0.6s; }
button:hover::before { width: 300px; height: 300px; top: -150px; left: -150px; }
.btn-primary { background: linear-gradient(135deg, rgba(0, 128, 255, 0.8), rgba(0, 245, 255, 0.6)); color: white; box-shadow: 0 4px 15px rgba(0, 128, 255, 0.4); border: 1px solid rgba(0, 245, 255, 0.3); }
.btn-primary:hover { box-shadow: 0 6px 25px rgba(0, 245, 255, 0.6); transform: translateY(-2px); }
.btn-unlock { background: linear-gradient(135deg, rgba(138, 43, 226, 0.8), rgba(75, 0, 130, 0.8)); color: white; box-shadow: 0 4px 15px rgba(138, 43, 226, 0.4); border: 1px solid rgba(138, 43, 226, 0.5); }
.btn-unlock:hover { box-shadow: 0 6px 25px rgba(138, 43, 226, 0.6); transform: translateY(-2px); }
/* 修改部分开始:一行两个,平分宽度 */
.social-links {
margin-top: 12px;
display: flex;
gap: 12px; /* 两个按钮之间的间距 */
/* 默认 flex-direction 就是 row,所以这里就是一行显示 */
}
.pill {
flex: 1; /* 让两个按钮自动平分宽度 */
background: linear-gradient(135deg, rgba(138, 43, 226, 0.8), rgba(75, 0, 130, 0.8));
backdrop-filter: blur(10px);
padding: 14px;
border-radius: 12px; /* 保持与上面按钮一致的方圆角 */
color: white;
text-decoration: none;
font-size: 0.9rem;
display: flex;
align-items: center;
justify-content: center; /* 文字居中 */
gap: 4px;
transition: all 0.3s;
border: 1px solid rgba(138, 43, 226, 0.5);
box-shadow: 0 4px 15px rgba(138, 43, 226, 0.4);
font-weight: 600;
white-space: nowrap; /* 防止文字换行 */
}
.pill:hover {
background: linear-gradient(135deg, rgba(138, 43, 226, 1), rgba(75, 0, 130, 1));
border-color: rgba(138, 43, 226, 0.8);
color: white;
box-shadow: 0 6px 25px rgba(138, 43, 226, 0.6);
transform: translateY(-2px);
}
/* 修改部分结束 */
/* 响应式 */
@media (max-width: 768px) {
.glass-box { width: 90%; max-width: 380px; padding: 35px 25px; }
h2 { font-size: 1.4rem; }
input { padding: 12px 15px; font-size: 0.95rem; }
button { padding: 12px; font-size: 0.95rem; }
.pill { font-size: 0.85rem; padding: 12px 8px; } /* 手机端稍微减小内边距 */
}
@media (max-width: 480px) {
.glass-box { width: 95%; padding: 30px 20px; }
h2 { font-size: 1.2rem; margin-bottom: 20px; }
h2::before { font-size: 1.2rem; }
input { padding: 10px 12px; font-size: 0.9rem; margin-bottom: 15px; }
button { padding: 10px; font-size: 0.9rem; }
.btn-group { gap: 10px; }
.social-links { gap: 10px; margin-top: 10px; }
.pill { font-size: 0.8rem; padding: 10px 5px; }
}
</style>
</head>
<body>
<div class="stars" id="starsContainer"></div>
<div class="stars">
<div class="meteor"></div><div class="meteor"></div><div class="meteor"></div><div class="meteor"></div>
<div class="meteor"></div><div class="meteor"></div><div class="meteor"></div><div class="meteor"></div>
</div>
<div class="glass-shards">
<div class="shard"></div><div class="shard"></div><div class="shard"></div>
<div class="shard"></div><div class="shard"></div><div class="shard"></div>
</div>
<div class="glass-box">
<h2>管理员登陆</h2>
<input type="password" id="pwd" placeholder="请输入密码" autofocus autocomplete="new-password" onkeypress="if(event.keyCode===13)verify()">
<div class="btn-group">
<button class="btn-unlock" onclick="verify()">立即登陆</button>
<button class="btn-primary" onclick="window.open('${siteUrl}', '_blank')">天诚网站</button>
</div>
<div class="social-links">
<a href="javascript:void(0)" onclick="gh()" class="pill">🔥 烈火项目直达</a>
<a href="${tgGroup}" target="_blank" class="pill">✈️ 天诚交流群</a>
</div>
</div>
<script>
function generateStars() {
const starsContainer = document.getElementById('starsContainer');
for (let i = 0; i < 200; i++) {
const star = document.createElement('div');
star.className = 'star';
star.style.left = Math.random() * 100 + '%';
star.style.top = Math.random() * 100 + '%';
star.style.animationDelay = Math.random() * 3 + 's';
star.style.animationDuration = (Math.random() * 2 + 2) + 's';
const size = Math.random() * 2 + 1;
star.style.width = size + 'px';
star.style.height = size + 'px';
starsContainer.appendChild(star);
}
}
generateStars();
function gh(){fetch("?flag=github&t="+Date.now(),{keepalive:!0});window.open("${githubUrl}","_blank")}
function verify(){
const p = document.getElementById("pwd").value;
if(!p) return;
document.cookie = "auth=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
document.cookie = "auth=" + p + "; path=/; SameSite=Lax";
sessionStorage.setItem("is_active", "1");
location.reload();
}
window.onload = function() {
if(!sessionStorage.getItem("is_active")) {
document.cookie = "auth=; path=/; expires=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
</script>
</body>
</html>`;
}
// 👇 修改:增加 proxyCheckUrl 参数
function dashPage(host, uuid, proxyip, subpass, subdomain, converter, env, clientIP, hasAuth, tgState, cfState, add, addApi, addCsv, tgToken, tgId, cfId, cfToken, cfMail, cfKey, sysParams, dashTitle, proxyCheckUrl, dls) {
const defaultSubLink = `https://${host}/${subpass}`;
const pathParam = proxyip ? "/proxyip=" + proxyip : "/";
const longLink = `https://${subdomain}/sub?uuid=${uuid}&encryption=none&security=tls&sni=${host}&alpn=h3&fp=random&allowInsecure=1&type=ws&host=${host}&path=${encodeURIComponent(pathParam)}`;
const safeVal = (str) => (str || '').replace(/"/g, '"');
const getStatusLabel = (val, sysVal) => { if (!val) return ""; if (val === sysVal) return `<span class="source-tag sys">🔒 系统预设 (不可删除)</span>`; return `<span class="source-tag man">💾 后台配置 (可清除)</span>`; };
return `<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, minimum-scale=0.5, user-scalable=yes">
<meta name="format-detection" content="telephone=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>${dashTitle}</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { display: none; opacity: 0; transition: opacity 0.3s; overflow-x: hidden; position: relative; }
body.loaded { display: block; opacity: 1; }
/* 玻璃态配色 - 柔和不刺眼 */
:root {
--glass-blue: #4facfe;
--glass-purple: #9d7ff5;
--glass-cyan: #43e9e5;
--glass-pink: #f093fb;
--glass-green: #4ade80;
--bg-dark: #0f0f23;
--bg-darker: #050510;
--card-bg: rgba(15, 20, 40, 0.4);
--text: #e8eaf6;
--text-dim: #9ca3af;
--border: rgba(79, 172, 254, 0.2);
--glow: rgba(79, 172, 254, 0.5);
--success: #4ade80;
--warning: #fbbf24;
--danger: #f87171;
}
body.light {
/* 浅色主题 - 加深颜色变量以增强对比度 */
--glass-blue: #2563eb;
--glass-purple: #7c3aed;
--glass-cyan: #0891b2;
--glass-pink: #db2777;
--glass-green: #059669;
--bg-dark: #f8fafc;
--bg-darker: #f1f5f9;
--card-bg: rgba(255, 255, 255, 0.8);
--text: #0f172a;
--text-dim: #475569;
--border: rgba(37, 99, 235, 0.2);
--glow: rgba(37, 99, 235, 0.3);
--success: #059669;
--warning: #d97706;
--danger: #dc2626;
}
/* 👇 修改:白色主题背景改为天蓝色渐变 */
body.light {
background: linear-gradient(to bottom, #f0f9ff 0%, #bae6fd 50%, #38bdf8 100%);
}
body.light .shard {
background: linear-gradient(135deg, rgba(37, 99, 235, 0.06), rgba(124, 58, 237, 0.04));
border: 1px solid rgba(37, 99, 235, 0.15);
box-shadow: 0 8px 32px rgba(37, 99, 235, 0.1);
}
/* 白色模式输入框优化 */
body.light input,
body.light textarea,
body.light select {
background: rgba(255, 255, 255, 0.95);
color: #0f172a;
border-color: rgba(37, 99, 235, 0.25);
}
body.light input:focus,
body.light textarea:focus,
body.light select:focus {
background: rgba(255, 255, 255, 1);
border-color: var(--glass-blue);
box-shadow: 0 0 0 3px rgba(37, 99, 235, 0.1);
}
/* 白色模式系统状态优化 */
body.light .stat-box {
background: rgba(255, 255, 255, 0.7);
border: 1px solid rgba(37, 99, 235, 0.2);
}
body.light .stat-box:hover {
background: rgba(255, 255, 255, 0.9);
border-color: var(--glass-blue);
}
body.light .stat-value {
color: #1e40af;
font-weight: 700;
}
body.light .stat-label {
color: #1e293b;
font-weight: 600;
}
/* 黑色模式系统状态优化 */
body:not(.light) .stat-value {
color: var(--glass-cyan);
font-weight: 700;
text-shadow: 0 0 10px rgba(67, 233, 229, 0.3);
}
body:not(.light) .stat-label {
color: #cbd5e1;
font-weight: 600;
}
/* 白色模式日志优化 */
body.light .log-entry {
background: rgba(255, 255, 255, 0.9);
border-color: rgba(37, 99, 235, 0.2);
}
body.light .log-entry:hover {
background: rgba(255, 255, 255, 1);
border-color: var(--glass-blue);
}
body.light .log-time {
color: #1e40af;
font-weight: 600;
}
body.light .log-ip {
color: #0891b2;
font-weight: 600;
}
body.light .log-loc {
color: #059669;
font-weight: 500;
}
body.light .log-box {
background: rgba(255, 255, 255, 0.95);
border-color: rgba(37, 99, 235, 0.2);
color: #0f172a;
}
/* 黑色模式日志优化 */
body:not(.light) .log-time {
color: var(--glass-cyan);
font-weight: 600;
}
body:not(.light) .log-ip {
color: var(--glass-blue);
font-weight: 600;
}
body:not(.light) .log-loc {
color: var(--glass-green);
font-weight: 500;
}
/* 深色星空背景 */
body {
background: radial-gradient(ellipse at bottom, #1b2735 0%, #090a0f 100%);
color: var(--text);
font-family: 'Segoe UI', 'Microsoft YaHei', sans-serif;