forked from cmliu/epeius
-
Notifications
You must be signed in to change notification settings - Fork 0
/
明文源码.js
1845 lines (1696 loc) · 70.5 KB
/
明文源码.js
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 password = '';
let proxyIP = '';
let sub = '';
let subConverter = 'SUBAPI.fxxk.dedyn.io';// clash订阅转换后端,目前使用CM的订阅转换功能。自带虚假节点信息防泄露
let subConfig = "https://raw.githubusercontent.com/ACL4SSR/ACL4SSR/master/Clash/config/ACL4SSR_Online_Mini_MultiMode.ini"; //订阅配置文件
let subProtocol = 'https';
let subEmoji = 'true';
let socks5Address = '';
let parsedSocks5Address = {};
let enableSocks = false;
let fakeUserID;
let fakeHostName;
const expire = 4102329600;//2099-12-31
let proxyIPs;
let socks5s;
let go2Socks5s = [
'*ttvnw.net',
'*tapecontent.net',
'*cloudatacdn.com',
'*.loadshare.org',
];
let addresses = [];
let addressesapi = [];
let addressescsv = [];
let DLS = 8;
let remarkIndex = 1;//CSV备注所在列偏移量
let FileName = 'epeius';
let BotToken = '';
let ChatID = '';
let proxyhosts = [];
let proxyhostsURL = '';
let RproxyIP = 'false';
let httpsPorts = ["2053", "2083", "2087", "2096", "8443"];
let sha224Password;
const regex = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[.*\]):?(\d+)?#?(.*)?$/;
let proxyIPPool = [];
let path = '/?ed=2560';
let link = [];
let banHosts = [atob('c3BlZWQuY2xvdWRmbGFyZS5jb20=')];
export default {
async fetch(request, env, ctx) {
try {
const UA = request.headers.get('User-Agent') || 'null';
const userAgent = UA.toLowerCase();
password = env.PASSWORD || env.pswd || env.UUID || env.uuid || env.TOKEN || password;
if (!password) {
return new Response('请设置你的PASSWORD变量,或尝试重试部署,检查变量是否生效?', {
status: 404,
headers: {
"Content-Type": "text/plain;charset=utf-8",
}
});
}
sha224Password = env.SHA224 || env.SHA224PASS || sha224(password);
//console.log(sha224Password);
const currentDate = new Date();
currentDate.setHours(0, 0, 0, 0); // 设置时间为当天
const timestamp = Math.ceil(currentDate.getTime() / 1000);
const fakeUserIDMD5 = await MD5MD5(`${password}${timestamp}`);
fakeUserID = [
fakeUserIDMD5.slice(0, 8),
fakeUserIDMD5.slice(8, 12),
fakeUserIDMD5.slice(12, 16),
fakeUserIDMD5.slice(16, 20),
fakeUserIDMD5.slice(20)
].join('-');
fakeHostName = `${fakeUserIDMD5.slice(6, 9)}.${fakeUserIDMD5.slice(13, 19)}`;
proxyIP = env.PROXYIP || env.proxyip || proxyIP;
proxyIPs = await ADD(proxyIP);
proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)];
socks5Address = env.SOCKS5 || socks5Address;
socks5s = await ADD(socks5Address);
socks5Address = socks5s[Math.floor(Math.random() * socks5s.length)];
socks5Address = socks5Address.split('//')[1] || socks5Address;
if (env.GO2SOCKS5) go2Socks5s = await ADD(env.GO2SOCKS5);
if (env.CFPORTS) httpsPorts = await ADD(env.CFPORTS);
if (env.BAN) banHosts = await 整理(env.BAN);
if (socks5Address) {
try {
parsedSocks5Address = socks5AddressParser(socks5Address);
RproxyIP = env.RPROXYIP || 'false';
enableSocks = true;
} catch (err) {
/** @type {Error} */
let e = err;
console.log(e.toString());
RproxyIP = env.RPROXYIP || !proxyIP ? 'true' : 'false';
enableSocks = false;
}
} else {
RproxyIP = env.RPROXYIP || !proxyIP ? 'true' : 'false';
}
const upgradeHeader = request.headers.get("Upgrade");
const url = new URL(request.url);
if (!upgradeHeader || upgradeHeader !== "websocket") {
if (env.ADD) addresses = await ADD(env.ADD);
if (env.ADDAPI) addressesapi = await ADD(env.ADDAPI);
if (env.ADDCSV) addressescsv = await ADD(env.ADDCSV);
DLS = Number(env.DLS) || DLS;
remarkIndex = Number(env.CSVREMARK) || remarkIndex;
BotToken = env.TGTOKEN || BotToken;
ChatID = env.TGID || ChatID;
FileName = env.SUBNAME || FileName;
subEmoji = env.SUBEMOJI || env.EMOJI || subEmoji;
if (subEmoji == '0') subEmoji = 'false';
if (env.LINK) link = await ADD(env.LINK);
sub = env.SUB || sub;
subConverter = env.SUBAPI || subConverter;
if (subConverter.includes("http://")) {
subConverter = subConverter.split("//")[1];
subProtocol = 'http';
} else {
subConverter = subConverter.split("//")[1] || subConverter;
}
subConfig = env.SUBCONFIG || subConfig;
if (url.searchParams.has('sub') && url.searchParams.get('sub') !== '') sub = url.searchParams.get('sub');
if (url.searchParams.has('proxyip')) {
path = `/?ed=2560&proxyip=${url.searchParams.get('proxyip')}`;
RproxyIP = 'false';
} else if (url.searchParams.has('socks5')) {
path = `/?ed=2560&socks5=${url.searchParams.get('socks5')}`;
RproxyIP = 'false';
} else if (url.searchParams.has('socks')) {
path = `/?ed=2560&socks5=${url.searchParams.get('socks')}`;
RproxyIP = 'false';
}
switch (url.pathname) {
case '/':
if (env.URL302) return Response.redirect(env.URL302, 302);
else if (env.URL) return await proxyURL(env.URL, url);
else return new Response(JSON.stringify(request.cf, null, 4), {
status: 200,
headers: {
'content-type': 'application/json',
},
});
case `/${fakeUserID}`:
const fakeConfig = await get特洛伊Config(password, request.headers.get('Host'), sub, 'CF-Workers-SUB', RproxyIP, url, env);
return new Response(`${fakeConfig}`, { status: 200 });
case `/${password}/edit`:
const html = await KV(request, env);
return html;
case `/${password}`:
await sendMessage(`#获取订阅 ${FileName}`, request.headers.get('CF-Connecting-IP'), `UA: ${UA}</tg-spoiler>\n域名: ${url.hostname}\n<tg-spoiler>入口: ${url.pathname + url.search}</tg-spoiler>`);
const 特洛伊Config = await get特洛伊Config(password, request.headers.get('Host'), sub, UA, RproxyIP, url, env);
const now = Date.now();
//const timestamp = Math.floor(now / 1000);
const today = new Date(now);
today.setHours(0, 0, 0, 0);
const UD = Math.floor(((now - today.getTime()) / 86400000) * 24 * 1099511627776 / 2);
let pagesSum = UD;
let workersSum = UD;
let total = 24 * 1099511627776;
if (userAgent && (userAgent.includes('mozilla') || userAgent.includes('subconverter'))) {
return new Response(`<div style="font-size:13px;">${特洛伊Config}</div>`, {
status: 200,
headers: {
"Content-Type": "text/html;charset=utf-8",
"Profile-Update-Interval": "6",
"Subscription-Userinfo": `upload=${pagesSum}; download=${workersSum}; total=${total}; expire=${expire}`,
"Cache-Control": "no-store",
}
});
} else {
return new Response(`${特洛伊Config}`, {
status: 200,
headers: {
"Content-Disposition": `attachment; filename=${FileName}; filename*=utf-8''${encodeURIComponent(FileName)}`,
"Content-Type": "text/plain;charset=utf-8",
"Profile-Update-Interval": "6",
"Subscription-Userinfo": `upload=${pagesSum}; download=${workersSum}; total=${total}; expire=${expire}`,
}
});
}
default:
if (env.URL302) return Response.redirect(env.URL302, 302);
else if (env.URL) return await proxyURL(env.URL, url);
else return new Response('不用怀疑!你PASSWORD就是错的!!!', { status: 404 });
}
} else {
socks5Address = url.searchParams.get('socks5') || socks5Address;
if (new RegExp('/socks5=', 'i').test(url.pathname)) socks5Address = url.pathname.split('5=')[1];
else if (new RegExp('/socks://', 'i').test(url.pathname) || new RegExp('/socks5://', 'i').test(url.pathname)) {
socks5Address = url.pathname.split('://')[1].split('#')[0];
if (socks5Address.includes('@')) {
let userPassword = socks5Address.split('@')[0];
const base64Regex = /^(?:[A-Z0-9+/]{4})*(?:[A-Z0-9+/]{2}==|[A-Z0-9+/]{3}=)?$/i;
if (base64Regex.test(userPassword) && !userPassword.includes(':')) userPassword = atob(userPassword);
socks5Address = `${userPassword}@${socks5Address.split('@')[1]}`;
}
}
if (socks5Address) {
try {
parsedSocks5Address = socks5AddressParser(socks5Address);
enableSocks = true;
} catch (err) {
/** @type {Error} */
let e = err;
console.log(e.toString());
enableSocks = false;
}
} else {
enableSocks = false;
}
if (url.searchParams.has('proxyip')) {
proxyIP = url.searchParams.get('proxyip');
enableSocks = false;
} else if (new RegExp('/proxyip=', 'i').test(url.pathname)) {
proxyIP = url.pathname.toLowerCase().split('/proxyip=')[1];
enableSocks = false;
} else if (new RegExp('/proxyip.', 'i').test(url.pathname)) {
proxyIP = `proxyip.${url.pathname.toLowerCase().split("/proxyip.")[1]}`;
enableSocks = false;
} else if (new RegExp('/pyip=', 'i').test(url.pathname)) {
proxyIP = url.pathname.toLowerCase().split('/pyip=')[1];
enableSocks = false;
}
return await 特洛伊OverWSHandler(request);
}
} catch (err) {
let e = err;
return new Response(e.toString());
}
}
};
async function 特洛伊OverWSHandler(request) {
const webSocketPair = new WebSocketPair();
const [client, webSocket] = Object.values(webSocketPair);
webSocket.accept();
let address = "";
let portWithRandomLog = "";
const log = (info, event) => {
console.log(`[${address}:${portWithRandomLog}] ${info}`, event || "");
};
const earlyDataHeader = request.headers.get("sec-websocket-protocol") || "";
const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log);
let remoteSocketWapper = {
value: null
};
let udpStreamWrite = null;
readableWebSocketStream.pipeTo(new WritableStream({
async write(chunk, controller) {
if (udpStreamWrite) {
return udpStreamWrite(chunk);
}
if (remoteSocketWapper.value) {
const writer = remoteSocketWapper.value.writable.getWriter();
await writer.write(chunk);
writer.releaseLock();
return;
}
const {
hasError,
message,
portRemote = 443,
addressRemote = "",
rawClientData,
addressType
} = await parse特洛伊Header(chunk);
address = addressRemote;
portWithRandomLog = `${portRemote}--${Math.random()} tcp`;
if (hasError) {
throw new Error(message);
return;
}
if (!banHosts.includes(addressRemote)) {
log(`处理 TCP 出站连接 ${addressRemote}:${portRemote}`);
handleTCPOutBound(remoteSocketWapper, addressRemote, portRemote, rawClientData, webSocket, log, addressType);
} else {
throw new Error(`黑名单关闭 TCP 出站连接 ${addressRemote}:${portRemote}`);
}
},
close() {
log(`readableWebSocketStream is closed`);
},
abort(reason) {
log(`readableWebSocketStream is aborted`, JSON.stringify(reason));
}
})).catch((err) => {
log("readableWebSocketStream pipeTo error", err);
});
return new Response(null, {
status: 101,
// @ts-ignore
webSocket: client
});
}
async function parse特洛伊Header(buffer) {
if (buffer.byteLength < 56) {
return {
hasError: true,
message: "invalid data"
};
}
let crLfIndex = 56;
if (new Uint8Array(buffer.slice(56, 57))[0] !== 0x0d || new Uint8Array(buffer.slice(57, 58))[0] !== 0x0a) {
return {
hasError: true,
message: "invalid header format (missing CR LF)"
};
}
const password = new TextDecoder().decode(buffer.slice(0, crLfIndex));
if (password !== sha224Password) {
return {
hasError: true,
message: "invalid password"
};
}
const socks5DataBuffer = buffer.slice(crLfIndex + 2);
if (socks5DataBuffer.byteLength < 6) {
return {
hasError: true,
message: "invalid SOCKS5 request data"
};
}
const view = new DataView(socks5DataBuffer);
const cmd = view.getUint8(0);
if (cmd !== 1) {
return {
hasError: true,
message: "unsupported command, only TCP (CONNECT) is allowed"
};
}
const atype = view.getUint8(1);
// 0x01: IPv4 address
// 0x03: Domain name
// 0x04: IPv6 address
let addressLength = 0;
let addressIndex = 2;
let address = "";
switch (atype) {
case 1:
addressLength = 4;
address = new Uint8Array(
socks5DataBuffer.slice(addressIndex, addressIndex + addressLength)
).join(".");
break;
case 3:
addressLength = new Uint8Array(
socks5DataBuffer.slice(addressIndex, addressIndex + 1)
)[0];
addressIndex += 1;
address = new TextDecoder().decode(
socks5DataBuffer.slice(addressIndex, addressIndex + addressLength)
);
break;
case 4:
addressLength = 16;
const dataView = new DataView(socks5DataBuffer.slice(addressIndex, addressIndex + addressLength));
const ipv6 = [];
for (let i = 0; i < 8; i++) {
ipv6.push(dataView.getUint16(i * 2).toString(16));
}
address = ipv6.join(":");
break;
default:
return {
hasError: true,
message: `invalid addressType is ${atype}`
};
}
if (!address) {
return {
hasError: true,
message: `address is empty, addressType is ${atype}`
};
}
const portIndex = addressIndex + addressLength;
const portBuffer = socks5DataBuffer.slice(portIndex, portIndex + 2);
const portRemote = new DataView(portBuffer).getUint16(0);
return {
hasError: false,
addressRemote: address,
portRemote,
rawClientData: socks5DataBuffer.slice(portIndex + 4),
addressType: atype
};
}
async function handleTCPOutBound(remoteSocket, addressRemote, portRemote, rawClientData, webSocket, log, addressType) {
async function useSocks5Pattern(address) {
if (go2Socks5s.includes(atob('YWxsIGlu')) || go2Socks5s.includes(atob('Kg=='))) return true;
return go2Socks5s.some(pattern => {
let regexPattern = pattern.replace(/\*/g, '.*');
let regex = new RegExp(`^${regexPattern}$`, 'i');
return regex.test(address);
});
}
async function connectAndWrite(address, port, socks = false) {
log(`connected to ${address}:${port}`);
//if (/^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?).){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(address)) address = `${atob('d3d3Lg==')}${address}${atob('LmlwLjA5MDIyNy54eXo=')}`;
const tcpSocket = socks ? await socks5Connect(addressType, address, port, log)
: connect({
hostname: address,
port
});
remoteSocket.value = tcpSocket;
//log(`connected to ${address}:${port}`);
const writer = tcpSocket.writable.getWriter();
await writer.write(rawClientData);
writer.releaseLock();
return tcpSocket;
}
async function retry() {
if (enableSocks) {
tcpSocket = await connectAndWrite(addressRemote, portRemote, true);
} else {
if (!proxyIP || proxyIP == '') {
proxyIP = atob('UFJPWFlJUC50cDEuZnh4ay5kZWR5bi5pbw==');
} else if (proxyIP.includes(']:')) {
portRemote = proxyIP.split(']:')[1] || portRemote;
proxyIP = proxyIP.split(']:')[0] || proxyIP;
} else if (proxyIP.split(':').length === 2) {
portRemote = proxyIP.split(':')[1] || portRemote;
proxyIP = proxyIP.split(':')[0] || proxyIP;
}
if (proxyIP.includes('.tp')) portRemote = proxyIP.split('.tp')[1].split('.')[0] || portRemote;
tcpSocket = await connectAndWrite(proxyIP || addressRemote, portRemote);
}
tcpSocket.closed.catch((error) => {
console.log("retry tcpSocket closed error", error);
}).finally(() => {
safeCloseWebSocket(webSocket);
});
remoteSocketToWS(tcpSocket, webSocket, null, log);
}
let useSocks = false;
if (go2Socks5s.length > 0 && enableSocks) useSocks = await useSocks5Pattern(addressRemote);
let tcpSocket = await connectAndWrite(addressRemote, portRemote, useSocks);
remoteSocketToWS(tcpSocket, webSocket, retry, log);
}
function makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) {
let readableStreamCancel = false;
const stream = new ReadableStream({
start(controller) {
webSocketServer.addEventListener("message", (event) => {
if (readableStreamCancel) {
return;
}
const message = event.data;
controller.enqueue(message);
});
webSocketServer.addEventListener("close", () => {
safeCloseWebSocket(webSocketServer);
if (readableStreamCancel) {
return;
}
controller.close();
});
webSocketServer.addEventListener("error", (err) => {
log("webSocketServer error");
controller.error(err);
});
const { earlyData, error } = base64ToArrayBuffer(earlyDataHeader);
if (error) {
controller.error(error);
} else if (earlyData) {
controller.enqueue(earlyData);
}
},
pull(controller) { },
cancel(reason) {
if (readableStreamCancel) {
return;
}
log(`readableStream was canceled, due to ${reason}`);
readableStreamCancel = true;
safeCloseWebSocket(webSocketServer);
}
});
return stream;
}
async function remoteSocketToWS(remoteSocket, webSocket, retry, log) {
let hasIncomingData = false;
await remoteSocket.readable.pipeTo(
new WritableStream({
start() { },
/**
*
* @param {Uint8Array} chunk
* @param {*} controller
*/
async write(chunk, controller) {
hasIncomingData = true;
if (webSocket.readyState !== WS_READY_STATE_OPEN) {
controller.error(
"webSocket connection is not open"
);
}
webSocket.send(chunk);
},
close() {
log(`remoteSocket.readable is closed, hasIncomingData: ${hasIncomingData}`);
},
abort(reason) {
console.error("remoteSocket.readable abort", reason);
}
})
).catch((error) => {
console.error(
`remoteSocketToWS error:`,
error.stack || error
);
safeCloseWebSocket(webSocket);
});
if (hasIncomingData === false && retry) {
log(`retry`);
retry();
}
}
/*
function isValidSHA224(hash) {
const sha224Regex = /^[0-9a-f]{56}$/i;
return sha224Regex.test(hash);
}
*/
function base64ToArrayBuffer(base64Str) {
if (!base64Str) {
return { earlyData: undefined, error: null };
}
try {
base64Str = base64Str.replace(/-/g, "+").replace(/_/g, "/");
const decode = atob(base64Str);
const arryBuffer = Uint8Array.from(decode, (c) => c.charCodeAt(0));
return { earlyData: arryBuffer.buffer, error: null };
} catch (error) {
return { earlyData: undefined, error };
}
}
let WS_READY_STATE_OPEN = 1;
let WS_READY_STATE_CLOSING = 2;
function safeCloseWebSocket(socket) {
try {
if (socket.readyState === WS_READY_STATE_OPEN || socket.readyState === WS_READY_STATE_CLOSING) {
socket.close();
}
} catch (error) {
console.error("safeCloseWebSocket error", error);
}
}
/*
export {
worker_default as
default
};
//# sourceMappingURL=worker.js.map
*/
function revertFakeInfo(content, userID, hostName, isBase64) {
if (isBase64) content = atob(content);//Base64解码
content = content.replace(new RegExp(fakeUserID, 'g'), userID).replace(new RegExp(fakeHostName, 'g'), hostName);
//console.log(content);
if (isBase64) content = btoa(content);//Base64编码
return content;
}
async function MD5MD5(text) {
const encoder = new TextEncoder();
const firstPass = await crypto.subtle.digest('MD5', encoder.encode(text));
const firstPassArray = Array.from(new Uint8Array(firstPass));
const firstHex = firstPassArray.map(b => b.toString(16).padStart(2, '0')).join('');
const secondPass = await crypto.subtle.digest('MD5', encoder.encode(firstHex.slice(7, 27)));
const secondPassArray = Array.from(new Uint8Array(secondPass));
const secondHex = secondPassArray.map(b => b.toString(16).padStart(2, '0')).join('');
return secondHex.toLowerCase();
}
async function ADD(内容) {
// 将制表符、双引号、单引号和换行符都替换为逗号
// 然后将连续的多个逗号替换为单个逗号
var 替换后的内容 = 内容.replace(/[ |"'\r\n]+/g, ',').replace(/,+/g, ',');
// 删除开头和结尾的逗号(如果有的话)
if (替换后的内容.charAt(0) == ',') 替换后的内容 = 替换后的内容.slice(1);
if (替换后的内容.charAt(替换后的内容.length - 1) == ',') 替换后的内容 = 替换后的内容.slice(0, 替换后的内容.length - 1);
// 使用逗号分割字符串,得到地址数组
const 地址数组 = 替换后的内容.split(',');
return 地址数组;
}
async function proxyURL(proxyURL, url) {
const URLs = await ADD(proxyURL);
const fullURL = URLs[Math.floor(Math.random() * URLs.length)];
// 解析目标 URL
let parsedURL = new URL(fullURL);
console.log(parsedURL);
// 提取并可能修改 URL 组件
let URLProtocol = parsedURL.protocol.slice(0, -1) || 'https';
let URLHostname = parsedURL.hostname;
let URLPathname = parsedURL.pathname;
let URLSearch = parsedURL.search;
// 处理 pathname
if (URLPathname.charAt(URLPathname.length - 1) == '/') {
URLPathname = URLPathname.slice(0, -1);
}
URLPathname += url.pathname;
// 构建新的 URL
let newURL = `${URLProtocol}://${URLHostname}${URLPathname}${URLSearch}`;
// 反向代理请求
let response = await fetch(newURL);
// 创建新的响应
let newResponse = new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers: response.headers
});
// 添加自定义头部,包含 URL 信息
//newResponse.headers.set('X-Proxied-By', 'Cloudflare Worker');
//newResponse.headers.set('X-Original-URL', fullURL);
newResponse.headers.set('X-New-URL', newURL);
return newResponse;
}
function 配置信息(密码, 域名地址) {
const 啥啥啥_写的这是啥啊 = 'dHJvamFu';
const 协议类型 = atob(啥啥啥_写的这是啥啊);
const 别名 = FileName;
let 地址 = 域名地址;
let 端口 = 443;
const 传输层协议 = 'ws';
const 伪装域名 = 域名地址;
const 路径 = path;
let 传输层安全 = ['tls', true];
const SNI = 域名地址;
const 指纹 = 'randomized';
const v2ray = `${协议类型}://${encodeURIComponent(密码)}@${地址}:${端口}?security=${传输层安全[0]}&sni=${SNI}&alpn=h3&fp=${指纹}&allowInsecure=1&type=${传输层协议}&host=${伪装域名}&path=${encodeURIComponent(路径)}#${encodeURIComponent(别名)}`
const clash = `- {name: ${别名}, server: ${地址}, port: ${端口}, udp: false, client-fingerprint: ${指纹}, type: ${协议类型}, password: ${密码}, sni: ${SNI}, alpn: [h3], skip-cert-verify: true, network: ${传输层协议}, ws-opts: {path: "${路径}", headers: {Host: ${伪装域名}}}}`;
return [v2ray, clash];
}
let subParams = ['sub', 'base64', 'b64', 'clash', 'singbox', 'sb', 'surge'];
const cmad = decodeURIComponent(atob(`dGVsZWdyYW0lMjAlRTQlQkElQTQlRTYlQjUlODElRTclQkUlQTQlMjAlRTYlOEElODAlRTYlOUMlQUYlRTUlQTQlQTclRTQlQkQlQUMlN0UlRTUlOUMlQTglRTclQkElQkYlRTUlOEYlOTElRTclODklOEMhJTNDYnIlM0UKJTNDYSUyMGhyZWYlM0QlMjdodHRwcyUzQSUyRiUyRnQubWUlMkZDTUxpdXNzc3MlMjclM0VodHRwcyUzQSUyRiUyRnQubWUlMkZDTUxpdXNzc3MlM0MlMkZhJTNFJTNDYnIlM0UKLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tJTNDYnIlM0UKZ2l0aHViJTIwJUU5JUExJUI5JUU3JTlCJUFFJUU1JTlDJUIwJUU1JTlEJTgwJTIwU3RhciFTdGFyIVN0YXIhISElM0NiciUzRQolM0NhJTIwaHJlZiUzRCUyN2h0dHBzJTNBJTJGJTJGZ2l0aHViLmNvbSUyRmNtbGl1JTJGZXBlaXVzJTI3JTNFaHR0cHMlM0ElMkYlMkZnaXRodWIuY29tJTJGY21saXUlMkZlcGVpdXMlM0MlMkZhJTNFJTNDYnIlM0UKLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tLS0tJTNDYnIlM0UKJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIzJTIz`));
async function get特洛伊Config(password, hostName, sub, UA, RproxyIP, _url, env) {
if (sub) {
const match = sub.match(/^(?:https?:\/\/)?([^\/]+)/);
if (match) {
sub = match[1];
}
const subs = await ADD(sub);
if (subs.length > 1) sub = subs[0];
} else {
if (env.KV) {
await 迁移地址列表(env);
const 优选地址列表 = await env.KV.get('ADD.txt');
if (优选地址列表) {
const 优选地址数组 = await ADD(优选地址列表);
const 分类地址 = {
接口地址: new Set(),
链接地址: new Set(),
优选地址: new Set()
};
for (const 元素 of 优选地址数组) {
if (元素.startsWith('https://')) {
分类地址.接口地址.add(元素);
} else if (元素.includes('://')) {
分类地址.链接地址.add(元素);
} else {
分类地址.优选地址.add(元素);
}
}
addressesapi = [...分类地址.接口地址];
link = [...分类地址.链接地址];
addresses = [...分类地址.优选地址];
}
}
if ((addresses.length + addressesapi.length + addressescsv.length) == 0) {
// 定义 Cloudflare IP 范围的 CIDR 列表
let cfips = [
'103.21.244.0/23',
'104.16.0.0/13',
'104.24.0.0/14',
'172.64.0.0/14',
'103.21.244.0/23',
'104.16.0.0/14',
'104.24.0.0/15',
'141.101.64.0/19',
'172.64.0.0/14',
'188.114.96.0/21',
'190.93.240.0/21',
];
// 生成符合给定 CIDR 范围的随机 IP 地址
function generateRandomIPFromCIDR(cidr) {
const [base, mask] = cidr.split('/');
const baseIP = base.split('.').map(Number);
const subnetMask = 32 - parseInt(mask, 10);
const maxHosts = Math.pow(2, subnetMask) - 1;
const randomHost = Math.floor(Math.random() * maxHosts);
const randomIP = baseIP.map((octet, index) => {
if (index < 2) return octet;
if (index === 2) return (octet & (255 << (subnetMask - 8))) + ((randomHost >> 8) & 255);
return (octet & (255 << subnetMask)) + (randomHost & 255);
});
return randomIP.join('.');
}
addresses = addresses.concat('127.0.0.1:1234#CFnat');
addresses = addresses.concat(cfips.map(cidr => generateRandomIPFromCIDR(cidr) + '#CF随机节点'));
}
}
const userAgent = UA.toLowerCase();
const Config = 配置信息(password, hostName);
const v2ray = Config[0];
const clash = Config[1];
let proxyhost = "";
if (hostName.includes(".workers.dev")) {
if (proxyhostsURL && (!proxyhosts || proxyhosts.length == 0)) {
try {
const response = await fetch(proxyhostsURL);
if (!response.ok) {
console.error('获取地址时出错:', response.status, response.statusText);
return; // 如果有错误,直接返回
}
const text = await response.text();
const lines = text.split('\n');
// 过滤掉空行或只包含空白字符的行
const nonEmptyLines = lines.filter(line => line.trim() !== '');
proxyhosts = proxyhosts.concat(nonEmptyLines);
} catch (error) {
//console.error('获取地址时出错:', error);
}
}
if (proxyhosts.length != 0) proxyhost = proxyhosts[Math.floor(Math.random() * proxyhosts.length)] + "/";
}
if (userAgent.includes('mozilla') && !subParams.some(_searchParams => _url.searchParams.has(_searchParams))) {
let surge = `Surge订阅地址:<br><a href="javascript:void(0)" onclick="copyToClipboard('https://${proxyhost}${hostName}/${password}?surge','qrcode_4')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${proxyhost}${hostName}/${password}?surge</a><br><div id="qrcode_4" style="margin: 10px 10px 10px 10px;"></div>`;
if (hostName.includes(".workers.dev")) surge = "Surge订阅必须绑定自定义域";
const newSocks5s = socks5s.map(socks5Address => {
if (socks5Address.includes('@')) return socks5Address.split('@')[1];
else if (socks5Address.includes('//')) return socks5Address.split('//')[1];
else return socks5Address;
});
let socks5List = '';
if (go2Socks5s.length > 0 && enableSocks) {
socks5List = `${decodeURIComponent('SOCKS5%EF%BC%88%E7%99%BD%E5%90%8D%E5%8D%95%EF%BC%89%3A%20')}`;
if (go2Socks5s.includes(atob('YWxsIGlu')) || go2Socks5s.includes(atob('Kg=='))) socks5List += `${decodeURIComponent('%E6%89%80%E6%9C%89%E6%B5%81%E9%87%8F')}<br>`;
else socks5List += `<br> ${go2Socks5s.join('<br> ')}<br>`;
}
let 订阅器 = '';
if (sub) {
if (enableSocks) 订阅器 += `CFCDN(访问方式): Socks5<br> ${newSocks5s.join('<br> ')}<br>${socks5List}`;
else if (proxyIP && proxyIP != '') 订阅器 += `CFCDN(访问方式): ProxyIP<br> ${proxyIPs.join('<br> ')}<br>`;
else if (RproxyIP == 'true') 订阅器 += `CFCDN(访问方式): 自动获取ProxyIP<br>`;
else 订阅器 += `CFCDN(访问方式): 无法访问, 需要您设置 proxyIP/PROXYIP !!!<br>`
订阅器 += `<br>SUB(优选订阅生成器): ${sub}`;
} else {
if (enableSocks) 订阅器 += `CFCDN(访问方式): Socks5<br> ${newSocks5s.join('<br> ')}<br>${socks5List}`;
else if (proxyIP && proxyIP != '') 订阅器 += `CFCDN(访问方式): ProxyIP<br> ${proxyIPs.join('<br> ')}<br>`;
else 订阅器 += `CFCDN(访问方式): 无法访问, 需要您设置 proxyIP/PROXYIP !!!<br>`;
let 判断是否绑定KV空间 = '';
if (env.KV) 判断是否绑定KV空间 = ` <a href='${_url.pathname}/edit'>编辑优选列表</a>`;
订阅器 += `<br>您的订阅内容由 内置 addresses/ADD* 参数变量提供${判断是否绑定KV空间}<br>`;
if (addresses.length > 0) 订阅器 += `ADD(TLS优选域名&IP): <br> ${addresses.join('<br> ')}<br>`;
if (addressesapi.length > 0) 订阅器 += `ADDAPI(TLS优选域名&IP 的 API): <br> ${addressesapi.join('<br> ')}<br>`;
if (addressescsv.length > 0) 订阅器 += `ADDCSV(IPTest测速csv文件 限速 ${DLS} ): <br> ${addressescsv.join('<br> ')}<br>`;
}
const 节点配置页 = `
################################################################<br>
Subscribe / sub 订阅地址, 点击链接自动 <strong>复制订阅链接</strong> 并 <strong>生成订阅二维码</strong> <br>
---------------------------------------------------------------<br>
自适应订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${proxyhost}${hostName}/${password}?sub','qrcode_0')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${proxyhost}${hostName}/${password}</a><br>
<div id="qrcode_0" style="margin: 10px 10px 10px 10px;"></div>
Base64订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${proxyhost}${hostName}/${password}?b64','qrcode_1')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${proxyhost}${hostName}/${password}?b64</a><br>
<div id="qrcode_1" style="margin: 10px 10px 10px 10px;"></div>
clash订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${proxyhost}${hostName}/${password}?clash','qrcode_2')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${proxyhost}${hostName}/${password}?clash</a><br>
<div id="qrcode_2" style="margin: 10px 10px 10px 10px;"></div>
singbox订阅地址:<br>
<a href="javascript:void(0)" onclick="copyToClipboard('https://${proxyhost}${hostName}/${password}?sb','qrcode_3')" style="color:blue;text-decoration:underline;cursor:pointer;">https://${proxyhost}${hostName}/${password}?sb</a><br>
<div id="qrcode_3" style="margin: 10px 10px 10px 10px;"></div>
${surge}
<strong><a href="javascript:void(0);" id="noticeToggle" onclick="toggleNotice()">实用订阅技巧∨</a></strong><br>
<div id="noticeContent" class="notice-content" style="display: none;">
<strong>1.</strong> 如您使用的是 PassWall、SSR+ 等路由插件,推荐使用 <strong>Base64订阅地址</strong> 进行订阅;<br>
<br>
<strong>2.</strong> 快速切换 <a href='${atob('aHR0cHM6Ly9naXRodWIuY29tL2NtbGl1L1dvcmtlclZsZXNzMnN1Yg==')}'>优选订阅生成器</a> 至:sub.google.com,您可将"?sub=sub.google.com"参数添加到链接末尾,例如:<br>
https://${proxyhost}${hostName}/${password}<strong>?sub=sub.google.com</strong><br>
<br>
<strong>3.</strong> 快速更换 PROXYIP 至:proxyip.fxxk.dedyn.io:443,您可将"?proxyip=proxyip.fxxk.dedyn.io:443"参数添加到链接末尾,例如:<br>
https://${proxyhost}${hostName}/${password}<strong>?proxyip=proxyip.fxxk.dedyn.io:443</strong><br>
<br>
<strong>4.</strong> 快速更换 SOCKS5 至:user:[email protected]:1080,您可将"?socks5=user:[email protected]:1080"参数添加到链接末尾,例如:<br>
https://${proxyhost}${hostName}/${password}<strong>?socks5=user:[email protected]:1080</strong><br>
<br>
<strong>5.</strong> 如需指定多个参数则需要使用'&'做间隔,例如:<br>
https://${proxyhost}${hostName}/${password}?sub=sub.google.com<strong>&</strong>proxyip=proxyip.fxxk.dedyn.io<br>
</div>
<script src="https://cdn.jsdelivr.net/npm/@keeex/[email protected]/qrcode.min.js"></script>
<script>
function copyToClipboard(text, qrcode) {
navigator.clipboard.writeText(text).then(() => {
alert('已复制到剪贴板');
}).catch(err => {
console.error('复制失败:', err);
});
const qrcodeDiv = document.getElementById(qrcode);
qrcodeDiv.innerHTML = '';
new QRCode(qrcodeDiv, {
text: text,
width: 220, // 调整宽度
height: 220, // 调整高度
colorDark: "#000000", // 二维码颜色
colorLight: "#ffffff", // 背景颜色
correctLevel: QRCode.CorrectLevel.Q, // 设置纠错级别
scale: 1 // 调整像素颗粒度
});
}
function toggleNotice() {
const noticeContent = document.getElementById('noticeContent');
const noticeToggle = document.getElementById('noticeToggle');
if (noticeContent.style.display === 'none') {
noticeContent.style.display = 'block';
noticeToggle.textContent = '实用订阅技巧∧';
} else {
noticeContent.style.display = 'none';
noticeToggle.textContent = '实用订阅技巧∨';
}
}
</script>
---------------------------------------------------------------<br>
################################################################<br>
${FileName} 配置信息<br>
---------------------------------------------------------------<br>
HOST: ${hostName}<br>
PASSWORD: ${password}<br>
SHA224: ${sha224Password}<br>
FAKEPASS: ${fakeUserID}<br>
UA: ${UA}<br>
<br>
${订阅器}<br>
SUBAPI(订阅转换后端): ${subProtocol}://${subConverter}<br>
SUBCONFIG(订阅转换配置文件): ${subConfig}<br>
---------------------------------------------------------------<br>
################################################################<br>
v2ray<br>
---------------------------------------------------------------<br>
<a href="javascript:void(0)" onclick="copyToClipboard('${v2ray}','qrcode_v2ray')" style="color:blue;text-decoration:underline;cursor:pointer;">${v2ray}</a><br>
<div id="qrcode_v2ray" style="margin: 10px 10px 10px 10px;"></div>
---------------------------------------------------------------<br>
################################################################<br>
clash-meta<br>
---------------------------------------------------------------<br>
${clash}<br>
---------------------------------------------------------------<br>
################################################################<br>
${cmad}
`;
return 节点配置页;
} else {
if (typeof fetch != 'function') {
return 'Error: fetch is not available in this environment.';
}
// 如果是使用默认域名,则改成一个workers的域名,订阅器会加上代理
if (hostName.includes(".workers.dev")) {
fakeHostName = `${fakeHostName}.workers.dev`;
} else {
fakeHostName = `${fakeHostName}.xyz`
}
let url = `https://${sub}/sub?host=${fakeHostName}&pw=${fakeUserID}&password=${fakeUserID + atob('JmVwZWl1cz1jbWxpdSZwcm94eWlwPQ==') + RproxyIP}&path=${encodeURIComponent(path)}`;
let isBase64 = true;
let newAddressesapi = [];
let newAddressescsv = [];
if (!sub || sub == "") {
if (hostName.includes('workers.dev')) {
if (proxyhostsURL && (!proxyhosts || proxyhosts.length == 0)) {
try {
const response = await fetch(proxyhostsURL);
if (!response.ok) {
console.error('获取地址时出错:', response.status, response.statusText);
return; // 如果有错误,直接返回
}
const text = await response.text();
const lines = text.split('\n');
// 过滤掉空行或只包含空白字符的行
const nonEmptyLines = lines.filter(line => line.trim() !== '');
proxyhosts = proxyhosts.concat(nonEmptyLines);
} catch (error) {
console.error('获取地址时出错:', error);
}
}
// 使用Set对象去重
proxyhosts = [...new Set(proxyhosts)];
}
newAddressesapi = await getAddressesapi(addressesapi);
newAddressescsv = await getAddressescsv('TRUE');
url = `https://${hostName}/${fakeUserID + _url.search}`;
}
if (!userAgent.includes(('CF-Workers-SUB').toLowerCase())) {
if ((userAgent.includes('clash') && !userAgent.includes('nekobox')) || (_url.searchParams.has('clash'))) {
url = `${subProtocol}://${subConverter}/sub?target=clash&url=${encodeURIComponent(url)}&insert=false&config=${encodeURIComponent(subConfig)}&emoji=${subEmoji}&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`;
isBase64 = false;
} else if (userAgent.includes('sing-box') || userAgent.includes('singbox') || _url.searchParams.has('singbox') || _url.searchParams.has('sb')) {
url = `${subProtocol}://${subConverter}/sub?target=singbox&url=${encodeURIComponent(url)}&insert=false&config=${encodeURIComponent(subConfig)}&emoji=${subEmoji}&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`;
isBase64 = false;
} else if (userAgent.includes('surge') || _url.searchParams.has('surge')) {
url = `${subProtocol}://${subConverter}/sub?target=surge&ver=4&url=${encodeURIComponent(url)}&insert=false&config=${encodeURIComponent(subConfig)}&emoji=${subEmoji}&list=false&xudp=false&udp=false&tfo=false&expand=true&scv=true&fdn=false`;
isBase64 = false;
}
}
try {
let content;
if ((!sub || sub == "") && isBase64 == true) {
content = await subAddresses(fakeHostName, fakeUserID, userAgent, newAddressesapi, newAddressescsv);
} else {
const response = await fetch(url, {
headers: {
'User-Agent': atob('Q0YtV29ya2Vycy1lcGVpdXMvY21saXU='),
}
});
content = await response.text();
}
if (_url.pathname == `/${fakeUserID}`) return content;
content = revertFakeInfo(content, password, hostName, isBase64);
if (userAgent.includes('surge') || _url.searchParams.has('surge')) content = surge(content, `https://${hostName}/${password}?surge`);
return content;
} catch (error) {
console.error('Error fetching content:', error);
return `Error fetching content: ${error.message}`;
}
}
}
async function sendMessage(type, ip, add_data = "") {
if (BotToken !== '' && ChatID !== '') {
let msg = "";
const response = await fetch(`http://ip-api.com/json/${ip}?lang=zh-CN`);
if (response.status == 200) {
const ipInfo = await response.json();
msg = `${type}\nIP: ${ip}\n国家: ${ipInfo.country}\n<tg-spoiler>城市: ${ipInfo.city}\n组织: ${ipInfo.org}\nASN: ${ipInfo.as}\n${add_data}`;
} else {
msg = `${type}\nIP: ${ip}\n<tg-spoiler>${add_data}`;
}
let url = "https://api.telegram.org/bot" + BotToken + "/sendMessage?chat_id=" + ChatID + "&parse_mode=HTML&text=" + encodeURIComponent(msg);
return fetch(url, {
method: 'get',
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;',