forked from ca110us/epeius
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
_worker.src.js
1910 lines (1751 loc) · 63 KB
/
_worker.src.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
// _worker.src.js
import { connect } from "cloudflare:sockets";
let password = 'auto';
let proxyIP = '';
// The user name and password do not contain special characters
// Setting the address will ignore proxyIP
// Example: user:pass@host:port or host:port
let socks5Address = '';
let addresses = [
//当sub为空时启用本地优选域名/优选IP,若不带端口号 TLS默认端口为443,#号后为备注别名
/*
'Join.my.Telegram.channel.CMLiussss.to.unlock.more.premium.nodes.cf.090227.xyz#加入我的频道t.me/CMLiussss解锁更多优选节点',
'visa.cn:443',
'www.visa.com:8443',
'cis.visa.com:2053',
'africa.visa.com:2083',
'www.visa.com.sg:2087',
'www.visaeurope.at:2096',
'www.visa.com.mt:8443',
'qa.visamiddleeast.com',
'time.is',
'www.wto.org:8443',
'chatgpt.com:2087',
'icook.hk',
'104.17.0.0#IPv4',
'[2606:4700::]#IPv6'
*/
];
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 RproxyIP = 'false';
let addressesapi = [];
let addressescsv = [];
let DLS = 8;
let FileName = 'epeius';
let BotToken ='';
let ChatID ='';
let proxyhosts = [];//本地代理域名池
let proxyhostsURL = 'https://raw.githubusercontent.com/cmliu/CFcdnVmess2sub/main/proxyhosts';//在线代理域名池URL
let go2Socks5s = [
'*ttvnw.net',
'*tapecontent.net',
'*cloudatacdn.com',
'*.loadshare.org',
];
let fakeUserID ;
let fakeHostName ;
let proxyIPs ;
let socks5s;
let sha224Password ;
const expire = 4102329600;//2099-12-31
const regex = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[.*\]):?(\d+)?#?(.*)?$/;
let parsedSocks5Address = {};
let enableSocks = false;
let httpsPorts = ["2053","2083","2087","2096","8443"];
/*Obfuscate-cmliu*/
/*
if (!isValidSHA224(sha224Password)) {
throw new Error('sha224Password is not valid');
}
*/
export default {
async fetch(request, env, ctx) {
try {
const UA = request.headers.get('User-Agent') || 'null';
const userAgent = UA.toLowerCase();
password = env.PASSWORD || password;
sha224Password = env.SHA224 || env.SHA224PASS || sha256.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);
fakeHostName = fakeUserIDMD5.slice(6, 9) + "." + fakeUserIDMD5.slice(13, 19);
//console.log(fakeUserID); // 打印fakeID
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.CFPORTS) httpsPorts = await ADD(env.CFPORTS);
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 (socks5Address) {
try {
parsedSocks5Address = socks5AddressParser(socks5Address);
RproxyIP = env.RPROXYIP || 'false';
enableSocks = true;
} catch (err) {
/** @type {Error} */
let e = err;
console.log(e.toString());
RproxyIP = env.RPROXYIP || !proxyIP ? 'true' : 'false';
enableSocks = false;
}
} else {
RproxyIP = env.RPROXYIP || !proxyIP ? 'true' : 'false';
}
if (env.ADD) addresses = await ADD(env.ADD);
if (env.ADDAPI) addressesapi = await ADD(env.ADDAPI);
if (env.ADDCSV) addressescsv = await ADD(env.ADDCSV);
DLS = env.DLS || DLS;
BotToken = env.TGTOKEN || BotToken;
ChatID = env.TGID || ChatID;
if(env.GO2SOCKS5) go2Socks5s = await ADD(env.GO2SOCKS5);
const upgradeHeader = request.headers.get("Upgrade");
const url = new URL(request.url);
if (url.searchParams.has('sub') && url.searchParams.get('sub') !== '') sub = url.searchParams.get('sub');
FileName = env.SUBNAME || FileName;
if (!upgradeHeader || upgradeHeader !== "websocket") {
//const url = new URL(request.url);
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 getTrojanConfig(password, request.headers.get('Host'), sub, 'CF-Workers-SUB', RproxyIP, url);
return new Response(`${fakeConfig}`, { status: 200 });
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 trojanConfig = await getTrojanConfig(password, request.headers.get('Host'), sub, UA, RproxyIP, url);
const now = Date.now();
//const timestamp = Math.floor(now / 1000);
const today = new Date(now);
today.setHours(0, 0, 0, 0);
const UD = Math.floor(((now - today.getTime())/86400000) * 24 * 1099511627776 / 2);
let pagesSum = UD;
let workersSum = UD;
let total = 24 * 1099511627776 ;
if (env.CFEMAIL && env.CFKEY){
const email = env.CFEMAIL;
const key = env.CFKEY;
const accountIndex = env.CFID || 0;
const accountId = await getAccountId(email, key);
if (accountId){
const now = new Date()
now.setUTCHours(0, 0, 0, 0)
const startDate = now.toISOString()
const endDate = new Date().toISOString();
const Sum = await getSum(accountId, accountIndex, email, key, startDate, endDate);
pagesSum = Sum[0];
workersSum = Sum[1];
total = 102400 ;
}
}
//console.log(`pagesSum: ${pagesSum}\nworkersSum: ${workersSum}\ntotal: ${total}`);
if (userAgent && (userAgent.includes('mozilla') || userAgent.includes('subconverter'))){
return new Response(`${trojanConfig}`, {
status: 200,
headers: {
"Content-Type": "text/plain;charset=utf-8",
"Profile-Update-Interval": "6",
"Subscription-Userinfo": `upload=${pagesSum}; download=${workersSum}; total=${total}; expire=${expire}`,
}
});
} else {
return new Response(`${trojanConfig}`, {
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 {
proxyIP = url.searchParams.get('proxyip') || proxyIP;
if (new RegExp('/proxyip=', 'i').test(url.pathname)) proxyIP = url.pathname.toLowerCase().split('/proxyip=')[1];
else if (new RegExp('/proxyip.', 'i').test(url.pathname)) proxyIP = `proxyip.${url.pathname.toLowerCase().split("/proxyip.")[1]}`;
socks5Address = url.searchParams.get('socks5') || socks5Address;
if (new RegExp('/socks5=', 'i').test(url.pathname)) socks5Address = url.pathname.split('5=')[1];
else if (new RegExp('/socks://', 'i').test(url.pathname) || new RegExp('/socks5://', 'i').test(url.pathname)) {
socks5Address = url.pathname.split('://')[1].split('#')[0];
if (socks5Address.includes('@')){
let userPassword = socks5Address.split('@')[0];
const base64Regex = /^(?:[A-Z0-9+/]{4})*(?:[A-Z0-9+/]{2}==|[A-Z0-9+/]{3}=)?$/i;
if (base64Regex.test(userPassword) && !userPassword.includes(':')) userPassword = atob(userPassword);
socks5Address = `${userPassword}@${socks5Address.split('@')[1]}`;
}
}
if (socks5Address) {
try {
parsedSocks5Address = socks5AddressParser(socks5Address);
enableSocks = true;
} catch (err) {
/** @type {Error} */
let e = err;
console.log(e.toString());
enableSocks = false;
}
} else {
enableSocks = false;
}
return await trojanOverWSHandler(request);
}
} catch (err) {
let e = err;
return new Response(e.toString());
}
}
};
async function trojanOverWSHandler(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 parseTrojanHeader(chunk);
address = addressRemote;
portWithRandomLog = `${portRemote}--${Math.random()} tcp`;
if (hasError) {
throw new Error(message);
return;
}
handleTCPOutBound(remoteSocketWapper, addressRemote, portRemote, rawClientData, webSocket, log, addressType);
},
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 parseTrojanHeader(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('cHJveHlpcC50cDEuY21saXVzc3NzLmNvbQ==');
} 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 { 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 { 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(envadd) {
var addtext = envadd.replace(/[ |"'\r\n]+/g, ',').replace(/,+/g, ','); // 双引号、单引号和换行符替换为逗号
//console.log(addtext);
if (addtext.charAt(0) == ',') addtext = addtext.slice(1);
if (addtext.charAt(addtext.length -1) == ',') addtext = addtext.slice(0, addtext.length - 1);
const add = addtext.split(',');
//console.log(add);
return add ;
}
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 checkSUB(host) {
if ((!sub || sub == '') && (addresses.length + addressesapi.length + addressescsv.length) == 0){
addresses = [
'Join.my.Telegram.channel.CMLiussss.to.unlock.more.premium.nodes.cf.090227.xyz#加入我的频道t.me/CMLiussss解锁更多优选节点',
'127.0.0.1:1234#CFnat',
'visa.cn:443',
'singapore.com:8443',
'japan.com:2053',
'brazil.com:2083',
'russia.com:2087',
'www.gov.ua:2096',
'www.gco.gov.qa:8443',
'www.gov.se',
'time.is',
'www.wto.org:8443',
'fbi.gov:2087',
'icook.hk',
//'104.17.0.0#IPv4',
'[2606:4700::]#IPv6'
];
}
}
function 配置信息(密码, 域名地址) {
const 啥啥啥_写的这是啥啊 = 'dHJvamFu';
const 协议类型 = atob(啥啥啥_写的这是啥啊);
const 别名 = FileName;
let 地址 = 域名地址;
let 端口 = 443;
const 传输层协议 = 'ws';
const 伪装域名 = 域名地址;
const 路径 = '/?ed=2560';
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'];
async function getTrojanConfig(password, hostName, sub, UA, RproxyIP, _url) {
checkSUB(hostName);
const userAgent = UA.toLowerCase();
const Config = 配置信息(password , hostName);
const v2ray = Config[0];
const clash = Config[1];
let proxyhost = "";
if(hostName.includes(".workers.dev") || hostName.includes(".pages.dev")){
if ( proxyhostsURL && (!proxyhosts || proxyhosts.length == 0)) {
try {
const response = await fetch(proxyhostsURL);
if (!response.ok) {
console.error('获取地址时出错:', response.status, response.statusText);
return; // 如果有错误,直接返回
}
const text = await response.text();
const lines = text.split('\n');
// 过滤掉空行或只包含空白字符的行
const nonEmptyLines = lines.filter(line => line.trim() !== '');
proxyhosts = proxyhosts.concat(nonEmptyLines);
} catch (error) {
//console.error('获取地址时出错:', error);
}
}
if (proxyhosts.length != 0) proxyhost = proxyhosts[Math.floor(Math.random() * proxyhosts.length)] + "/";
}
if ( userAgent.includes('mozilla') && !subParams.some(_searchParams => _url.searchParams.has(_searchParams))) {
let surge = `Surge订阅地址:\nhttps://${proxyhost}${hostName}/${password}?surge`;
if (hostName.includes(".workers.dev") || hostName.includes(".pages.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')}\n`;
else socks5List += `\n ${go2Socks5s.join('\n ')}\n`;
}
let 订阅器 = '';
if (!sub || sub == '') {
if (enableSocks) 订阅器 += `CFCDN(访问方式): Socks5\n ${newSocks5s.join('\n ')}\n${socks5List}`;
else if (proxyIP && proxyIP != '') 订阅器 += `CFCDN(访问方式): ProxyIP\n ${proxyIPs.join('\n ')}\n`;
else 订阅器 += `CFCDN(访问方式): 无法访问, 需要您设置 proxyIP/PROXYIP !!!\n`;
订阅器 += `\n您的订阅内容由 内置 addresses/ADD* 参数变量提供\n`;
if (addresses.length > 0) 订阅器 += `ADD(TLS优选域名&IP): \n ${addresses.join('\n ')}\n`;
if (addressesapi.length > 0) 订阅器 += `ADDAPI(TLS优选域名&IP 的 API): \n ${addressesapi.join('\n ')}\n`;
if (addressescsv.length > 0) 订阅器 += `ADDCSV(IPTest测速csv文件 限速 ${DLS} ): \n ${addressescsv.join('\n ')}\n`;
} else {
if (enableSocks) 订阅器 += `CFCDN(访问方式): Socks5\n ${newSocks5s.join('\n ')}\n${socks5List}`;
else if (proxyIP && proxyIP != '') 订阅器 += `CFCDN(访问方式): ProxyIP\n ${proxyIPs.join('\n ')}\n`;
else if (RproxyIP == 'true') 订阅器 += `CFCDN(访问方式): 自动获取ProxyIP\n`;
else 订阅器 += `CFCDN(访问方式): 无法访问, 需要您设置 proxyIP/PROXYIP !!!\n`
订阅器 += `\nSUB(优选订阅生成器): ${sub}`;
}
return `
################################################################
Subscribe / sub 订阅地址, 支持 Base64、clash-meta、sing-box 订阅格式
---------------------------------------------------------------
快速自适应订阅地址:
https://${proxyhost}${hostName}/${password}
https://${proxyhost}${hostName}/${password}?sub
Base64订阅地址:
https://${proxyhost}${hostName}/${password}?b64
https://${proxyhost}${hostName}/${password}?base64
clash订阅地址:
https://${proxyhost}${hostName}/${password}?clash
singbox订阅地址:
https://${proxyhost}${hostName}/${password}?sb
https://${proxyhost}${hostName}/${password}?singbox
${surge}
---------------------------------------------------------------
################################################################
${FileName} 配置信息
---------------------------------------------------------------
HOST: ${hostName}
PASSWORD: ${password}
SHA224: ${sha224Password}
FAKEPASS: ${fakeUserID}
UA: ${UA}
${订阅器}
SUBAPI(订阅转换后端): ${subProtocol}://${subconverter}
SUBCONFIG(订阅转换配置文件): ${subconfig}
---------------------------------------------------------------
################################################################
v2ray
---------------------------------------------------------------
${v2ray}
---------------------------------------------------------------
################################################################
clash-meta
---------------------------------------------------------------
${clash}
---------------------------------------------------------------
################################################################
telegram 交流群 技术大佬~在线发牌!
https://t.me/CMLiussss
---------------------------------------------------------------
github 项目地址 Star!Star!Star!!!
https://github.com/cmliu/epeius
---------------------------------------------------------------
################################################################
`;
} else {
if (typeof fetch != 'function') {
return 'Error: fetch is not available in this environment.';
}
// 如果是使用默认域名,则改成一个workers的域名,订阅器会加上代理
if (hostName.includes(".workers.dev") || hostName.includes(".pages.dev")){
fakeHostName = `${fakeHostName}.workers.dev`;
} else {
fakeHostName = `${fakeHostName}.xyz`
}
let url = `https://${sub}/sub?host=${fakeHostName}&pw=${fakeUserID}&password=${fakeUserID}&epeius=cmliu&proxyip=${RproxyIP}`;
let isBase64 = true;
let newAddressesapi = [];
let newAddressescsv = [];
if (!sub || sub == "") {
if(hostName.includes('workers.dev') || hostName.includes('pages.dev')) {
if (proxyhostsURL && (!proxyhosts || proxyhosts.length == 0)) {
try {
const response = await fetch(proxyhostsURL);
if (!response.ok) {
console.error('获取地址时出错:', response.status, response.statusText);
return; // 如果有错误,直接返回
}
const text = await response.text();
const lines = text.split('\n');
// 过滤掉空行或只包含空白字符的行
const nonEmptyLines = lines.filter(line => line.trim() !== '');
proxyhosts = proxyhosts.concat(nonEmptyLines);
} catch (error) {
console.error('获取地址时出错:', error);
}
}
// 使用Set对象去重
proxyhosts = [...new Set(proxyhosts)];
}
newAddressesapi = await getAddressesapi(addressesapi);
newAddressescsv = await getAddressescsv('TRUE');
url = `https://${hostName}/${fakeUserID}`;
}
if (!userAgent.includes(('CF-Workers-SUB').toLowerCase())){
if ((userAgent.includes('clash') && !userAgent.includes('nekobox')) || ( _url.searchParams.has('clash'))) {
url = `${subProtocol}://${subconverter}/sub?target=clash&url=${encodeURIComponent(url)}&insert=false&config=${encodeURIComponent(subconfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`;
isBase64 = false;
} else if (userAgent.includes('sing-box') || userAgent.includes('singbox') || _url.searchParams.has('singbox') || _url.searchParams.has('sb')) {
url = `${subProtocol}://${subconverter}/sub?target=singbox&url=${encodeURIComponent(url)}&insert=false&config=${encodeURIComponent(subconfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`;
isBase64 = false;
} 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=true&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': `CF-Workers-epeius/cmliu`
}});
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;',
'Accept-Encoding': 'gzip, deflate, br',
'User-Agent': 'Mozilla/5.0 Chrome/90.0.4430.72'
}
});
}
}
let proxyIPPool = [];
function subAddresses(host,pw,userAgent,newAddressesapi,newAddressescsv) {
addresses = addresses.concat(newAddressesapi);
addresses = addresses.concat(newAddressescsv);
// 使用Set对象去重
const uniqueAddresses = [...new Set(addresses)];
const responseBody = uniqueAddresses.map(address => {
let port = "-1";
let addressid = address;
const match = addressid.match(regex);
if (!match) {
if (address.includes(':') && address.includes('#')) {
const parts = address.split(':');
address = parts[0];
const subParts = parts[1].split('#');
port = subParts[0];
addressid = subParts[1];
} else if (address.includes(':')) {
const parts = address.split(':');
address = parts[0];
port = parts[1];
} else if (address.includes('#')) {
const parts = address.split('#');
address = parts[0];
addressid = parts[1];
}
if (addressid.includes(':')) {
addressid = addressid.split(':')[0];
}
} else {
address = match[1];
port = match[2] || port;
addressid = match[3] || address;
}
const httpsPorts = ["2053","2083","2087","2096","8443"];
if (!isValidIPv4(address) && port == "-1") {
for (let httpsPort of httpsPorts) {
if (address.includes(httpsPort)) {
port = httpsPort;
break;
}
}
}
if (port == "-1") port = "443";
let 伪装域名 = host ;
let 最终路径 = '/?ed=2560' ;
let 节点备注 = '';
if(proxyhosts.length > 0 && (伪装域名.includes('.workers.dev') || 伪装域名.includes('pages.dev'))) {
最终路径 = `/${伪装域名}${最终路径}`;
伪装域名 = proxyhosts[Math.floor(Math.random() * proxyhosts.length)];
节点备注 = ` 已启用临时域名中转服务,请尽快绑定自定义域!`;
}
const matchingProxyIP = proxyIPPool.find(proxyIP => proxyIP.includes(address));
if (matchingProxyIP) 最终路径 += `&proxyip=${matchingProxyIP}`;
let 密码 = pw;
if (!userAgent.includes('subconverter')) 密码 = encodeURIComponent(pw);
const 啥啥啥_写的这是啥啊 = 'dHJvamFu';
const 协议类型 = atob(啥啥啥_写的这是啥啊);
const trojanLink = `${协议类型}://${密码}@${address}:${port}?security=tls&sni=${伪装域名}&fp=randomized&type=ws&host=${伪装域名}&path=${encodeURIComponent(最终路径)}#${encodeURIComponent(addressid + 节点备注)}`;
return trojanLink;
}).join('\n');
const base64Response = btoa(responseBody); // 重新进行 Base64 编码
return base64Response;
}
async function getAddressesapi(api) {
if (!api || api.length === 0) return [];
let newapi = "";
// 创建一个AbortController对象,用于控制fetch请求的取消
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort(); // 取消所有请求
}, 2000); // 2秒后触发
try {
// 使用Promise.allSettled等待所有API请求完成,无论成功或失败
// 对api数组进行遍历,对每个API地址发起fetch请求
const responses = await Promise.allSettled(api.map(apiUrl => fetch(apiUrl, {
method: 'get',
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;',
'User-Agent': 'CF-Workers-epeius/cmliu'
},
signal: controller.signal // 将AbortController的信号量添加到fetch请求中,以便于需要时可以取消请求
}).then(response => response.ok ? response.text() : Promise.reject())));
// 遍历所有响应
for (const [index, response] of responses.entries()) {
// 检查响应状态是否为'fulfilled',即请求成功完成
if (response.status === 'fulfilled') {