forked from amclubs/am-cf-tunnel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
_worker.src.js
1814 lines (1596 loc) · 56.7 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
/**
* YouTube Channel: https://youtube.com/@AM_CLUB
* GitHub Repository: https://github.com/amclubs
* Telegram Group: https://t.me/AM_CLUBS
* Personal Blog: https://am.809098.xyz
*/
// @ts-ignore
import { connect } from 'cloudflare:sockets';
// Generate your own UUID using the following command in PowerShell:
// Powershell -NoExit -Command "[guid]::NewGuid()"
let userID = '88deb2d4-96e2-448b-b9c6-6e2a5f26fc8f';
// Proxy IPs to choose from
let proxyIPs = [
'proxyip.amclubs.camdvr.org',
'proxyip.amclubs.kozow.com'
];
// Randomly select a proxy IP from the list
let proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)];
let proxyPort = 443;
let proxyIpTxt = atob('aHR0cHM6Ly9yYXcuZ2l0aHVidXNlcmNvbnRlbnQuY29tL2FtY2x1YnMvYW0tY2YtdHVubmVsL21haW4vcHJveHlpcC50eHQ=');
// Setting the socks5 will ignore proxyIP
// Example: user:pass@host:port or host:port
let socks5 = '';
let socks5Enable = false;
let parsedSocks5 = {};
// https://cloudflare-dns.com/dns-query or https://dns.google/dns-query
// DNS-over-HTTPS URL
let dohURL = 'https://sky.rethinkdns.com/1:-Pf_____9_8A_AMAIgE8kMABVDDmKOHTAKg=';
// Preferred address API interface
let ipUrl = [
];
let ipUrlTxt = [
atob('aHR0cHM6Ly9yYXcuZ2l0aHVidXNlcmNvbnRlbnQuY29tL2FtY2x1YnMvYW0tY2YtdHVubmVsL21haW4vaXB2NC50eHQ=')
];
let ipUrlCsv = [
// atob('aHR0cHM6Ly9yYXcuZ2l0aHVidXNlcmNvbnRlbnQuY29tL2FtY2x1YnMvYW0tY2YtdHVubmVsL21haW4vaXB2NC5jc3Y=')
];
// Preferred addresses with optional TLS subscription
let ipLocal = [
'visa.cn:443#youtube.com/@AM_CLUB 订阅频道获取更多教程',
'icook.hk#t.me/AM_CLUBS 加入交流群解锁更多优选节点',
'time.is#github.com/amclubs GitHub仓库查看更多项目'
];
let noTLS = 'false';
let sl = 5;
let tagName = atob('YW1jbHVicw==');
let subUpdateTime = 6; // Subscription update time in hours
let timestamp = 4102329600000; // Timestamp for the end date (2099-12-31)
let total = 99 * 1125899906842624; // PB (perhaps referring to bandwidth or total entries)
let download = Math.floor(Math.random() * 1099511627776);
let upload = download;
// Network protocol type
let network = 'ws'; // WebSocket
// Fake UUID and hostname for configuration generation
let fakeUserID;
let fakeHostName;
// Subscription and conversion details
let subProtocol = 'https';
let subConverter = atob('dXJsLnYxLm1r'); // Subscription conversion backend using Sheep's function
let subConfig = "https://raw.githubusercontent.com/amclubs/ACL4SSR/main/Clash/config/ACL4SSR_Online_Full_MultiMode.ini"; // Subscription profile
let fileName = 'AM%E7%A7%91%E6%8A%80';
let isBase64 = true;
let botToken = '';
let chatID = '';
let projectName = atob('YW1jbHVicy9hbS1jZi10dW5uZWw');
let ytName = atob('aHR0cHM6Ly95b3V0dWJlLmNvbS9AQU1fQ0xVQg==');
const httpPattern = /^http(s)?:\/\/.+/;
if (!isValidUUID(userID)) {
throw new Error('uuid is invalid');
}
export default {
/**
* @param {import("@cloudflare/workers-types").Request} request
* @param {{UUID: string, PROXYIP: string, DNS_RESOLVER_URL: string, NODE_ID: int, API_HOST: string, API_TOKEN: string}} env
* @param {import("@cloudflare/workers-types").ExecutionContext} ctx
* @returns {Promise<Response>}
*/
async fetch(request, env, ctx) {
try {
let {
UUID,
PROXYIP,
SOCKS5,
DNS_RESOLVER_URL,
IP_LOCAL,
IP_URL,
IP_URL_TXT,
IP_URL_CSV,
NO_TLS,
SL,
SUB_CONFIG,
SUB_CONVERTER,
SUB_NAME,
CF_EMAIL,
CF_KEY,
CF_ID = 0,
TG_TOKEN,
TG_ID,
//兼容
ADDRESSESAPI,
} = env;
userID = (UUID || userID).toLowerCase();
const url = new URL(request.url);
PROXYIP = url.searchParams.get('PROXYIP') || PROXYIP;
if (PROXYIP) {
if (httpPattern.test(PROXYIP)) {
let proxyIpTxt = await addIpText(PROXYIP);
let ipUrlTxtAndCsv;
if (PROXYIP.endsWith('.csv')) {
ipUrlTxtAndCsv = await getIpUrlTxtAndCsv(noTLS, null, proxyIpTxt);
} else {
ipUrlTxtAndCsv = await getIpUrlTxtAndCsv(noTLS, proxyIpTxt, null);
}
const uniqueIpTxt = [...new Set([...ipUrlTxtAndCsv.txt, ...ipUrlTxtAndCsv.csv])];
proxyIP = uniqueIpTxt[Math.floor(Math.random() * uniqueIpTxt.length)];
} else {
proxyIPs = await addIpText(PROXYIP);
proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)];
}
} else {
let proxyIpTxts = await addIpText(proxyIpTxt);
let ipUrlTxtAndCsv = await getIpUrlTxtAndCsv(noTLS, proxyIpTxts, null);
let updatedIps = ipUrlTxtAndCsv.txt.map(ip => `${tagName}${download}.${ip}`);
const uniqueIpTxt = [...new Set([...updatedIps, ...proxyIPs])];
proxyIP = uniqueIpTxt[Math.floor(Math.random() * uniqueIpTxt.length)];
}
const [ip, port] = proxyIP.split(':');
proxyIP = ip;
proxyPort = port || proxyPort;
socks5 = url.searchParams.get('SOCKS5') || SOCKS5 || socks5;
parsedSocks5 = await parseSocks5FromUrl(socks5, url);
if (parsedSocks5) {
socks5Enable = true;
}
dohURL = url.searchParams.get('DNS_RESOLVER_URL') || DNS_RESOLVER_URL || dohURL;
IP_LOCAL = url.searchParams.get('IP_LOCAL') || IP_LOCAL;
if (IP_LOCAL) {
ipLocal = await addIpText(IP_LOCAL);
}
const newCsvUrls = [];
const newTxtUrls = [];
IP_URL = url.searchParams.get('IP_URL') || IP_URL;
if (IP_URL) {
ipUrlTxt = [];
ipUrl = await addIpText(IP_URL);
ipUrl = await getIpUrlTxt(ipUrl);
ipUrl.forEach(url => {
if (url.endsWith('.csv')) {
newCsvUrls.push(url);
} else {
newTxtUrls.push(url);
}
});
}
//兼容旧的,如果有IP_URL_TXT新的则不用旧的
ADDRESSESAPI = url.searchParams.get('ADDRESSESAPI') || ADDRESSESAPI;
IP_URL_TXT = url.searchParams.get('IP_URL_TXT') || IP_URL_TXT;
IP_URL_CSV = url.searchParams.get('IP_URL_CSV') || IP_URL_CSV;
if (ADDRESSESAPI) {
ipUrlTxt = await addIpText(ADDRESSESAPI);
}
if (IP_URL_TXT) {
ipUrlTxt = await addIpText(IP_URL_TXT);
}
if (IP_URL_CSV) {
ipUrlCsv = await addIpText(IP_URL_CSV);
}
ipUrlCsv = [...new Set([...ipUrlCsv, ...newCsvUrls])];
ipUrlTxt = [...new Set([...ipUrlTxt, ...newTxtUrls])];
noTLS = url.searchParams.get('NO_TLS') || NO_TLS || noTLS;
sl = url.searchParams.get('SL') || SL || sl;
subConfig = url.searchParams.get('SUB_CONFIG') || SUB_CONFIG || subConfig;
subConverter = url.searchParams.get('SUB_CONVERTER') || SUB_CONVERTER || subConverter;
fileName = url.searchParams.get('SUB_NAME') || SUB_NAME || fileName;
botToken = url.searchParams.get('TG_TOKEN') || TG_TOKEN || botToken;
chatID = url.searchParams.get('TG_ID') || TG_ID || chatID;
// Unified protocol for handling subconverters
const [subProtocol, subConverterWithoutProtocol] = (subConverter.startsWith("http://") || subConverter.startsWith("https://"))
? subConverter.split("://")
: [undefined, subConverter];
subConverter = subConverterWithoutProtocol;
// console.log(`proxyIPs: ${proxyIPs} \n proxyIP: ${proxyIP} \n ipLocal: ${ipLocal} \n ipUrl: ${ipUrl} \n ipUrlTxt: ${ipUrlTxt} `);
//const uuid = url.searchParams.get('uuid')?.toLowerCase() || 'null';
const ua = request.headers.get('User-Agent') || 'null';
const userAgent = ua.toLowerCase();
const host = request.headers.get('Host');
const upgradeHeader = request.headers.get('Upgrade');
const expire = Math.floor(timestamp / 1000);
// If WebSocket upgrade, handle WebSocket request
if (upgradeHeader === 'websocket') {
return await channelOverWSHandler(request);
}
fakeUserID = await getFakeUserID(userID);
fakeHostName = fakeUserID.slice(6, 9) + "." + fakeUserID.slice(13, 19);
console.log(`userID: ${userID}`);
console.log(`fakeUserID: ${fakeUserID}`);
// Handle routes based on the path
switch (url.pathname.toLowerCase()) {
case '/': {
return new Response(await nginx(), {
headers: {
'Content-Type': 'text/html; charset=UTF-8',
'referer': 'https://www.google.com/search?q=' + fileName,
},
});
}
case `/${fakeUserID}`: {
// Disguise UUID node generation
const fakeConfig = await getchannelConfig(userID, host, 'CF-FAKE-UA', url);
return new Response(fakeConfig, { status: 200 });
}
case `/${userID}`: {
// Handle real UUID requests and get node info
await sendMessage(
`#获取订阅 ${fileName}`,
request.headers.get('CF-Connecting-IP'),
`UA: ${userAgent}\n域名: ${url.hostname}\n入口: ${url.pathname + url.search}`
);
const channelConfig = await getchannelConfig(userID, host, userAgent, url);
const isMozilla = userAgent.includes('mozilla');
const config = await getCFConfig(CF_EMAIL, CF_KEY, CF_ID);
if (CF_EMAIL && CF_KEY) {
({ upload, download, total } = config);
}
// Prepare common headers
const commonHeaders = {
"Content-Type": isMozilla ? "text/html;charset=utf-8" : "text/plain;charset=utf-8",
"Profile-Update-Interval": `${subUpdateTime}`,
"Subscription-Userinfo": `upload=${upload}; download=${download}; total=${total}; expire=${expire}`,
};
// Add download headers if not a Mozilla browser
if (!isMozilla) {
commonHeaders["Content-Disposition"] = `attachment; filename=${fileName}; filename*=gbk''${fileName}`;
}
return new Response(channelConfig, {
status: 200,
headers: commonHeaders,
});
}
default: {
// Serve the default nginx disguise page
return new Response(await nginx(), {
headers: {
'Content-Type': 'text/html; charset=UTF-8',
'referer': 'https://www.google.com/search?q=' + fileName,
},
});
}
}
} catch (err) {
// Log error for debugging purposes
console.error('Error processing request:', err);
return new Response(`Error: ${err.message}`, { status: 500 });
}
},
};
/** ---------------------Tools------------------------------ */
export async function hashHex_f(string) {
const encoder = new TextEncoder();
const data = encoder.encode(string);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashArray = Array.from(new Uint8Array(hashBuffer));
const hashHex = hashArray.map(byte => byte.toString(16).padStart(2, '0')).join('');
return hashHex;
}
/**
* Checks if a given string is a valid UUID.
* Note: This is not a real UUID validation.
* @param {string} uuid The string to validate as a UUID.
* @returns {boolean} True if the string is a valid UUID, false otherwise.
*/
function isValidUUID(uuid) {
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return uuidRegex.test(uuid);
}
const byteToHex = [];
for (let i = 0; i < 256; ++i) {
byteToHex.push((i + 256).toString(16).slice(1));
}
function unsafeStringify(arr, offset = 0) {
return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + "-" + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + "-" + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + "-" + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + "-" + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}
function stringify(arr, offset = 0) {
const uuid = unsafeStringify(arr, offset);
if (!isValidUUID(uuid)) {
throw TypeError("Stringified UUID is invalid");
}
return uuid;
}
async function getFakeUserID(userID) {
const date = new Date().toISOString().split('T')[0];
const rawString = `${userID}-${date}`;
const hashBuffer = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(rawString));
const hashArray = Array.from(new Uint8Array(hashBuffer)).map(b => ('00' + b.toString(16)).slice(-2)).join('');
return `${hashArray.substring(0, 8)}-${hashArray.substring(8, 12)}-${hashArray.substring(12, 16)}-${hashArray.substring(16, 20)}-${hashArray.substring(20, 32)}`;
}
function revertFakeInfo(content, userID, hostName) {
//console.log(`revertFakeInfo-->: isBase64 ${isBase64} \n content: ${content}`);
if (isBase64) {
content = atob(content);//Base64 decrypt
}
content = content.replace(new RegExp(fakeUserID, 'g'), userID).replace(new RegExp(fakeHostName, 'g'), hostName);
if (isBase64) {
content = btoa(content);//Base64 encryption
}
return content;
}
/**
* Decodes a base64 string into an ArrayBuffer.
* @param {string} base64Str The base64 string to decode.
* @returns {{earlyData: ArrayBuffer|null, error: Error|null}} An object containing the decoded ArrayBuffer or null if there was an error, and any error that occurred during decoding or null if there was no error.
*/
function base64ToArrayBuffer(base64Str) {
if (!base64Str) {
return { earlyData: null, error: null };
}
try {
// go use modified Base64 for URL rfc4648 which js atob not support
base64Str = base64Str.replace(/-/g, '+').replace(/_/g, '/');
const decode = atob(base64Str);
const arryBuffer = Uint8Array.from(decode, (c) => c.charCodeAt(0));
return { earlyData: arryBuffer.buffer, error: null };
} catch (error) {
return { earlyData: null, error };
}
}
async function addIpText(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;
}
function socks5Parser(socks5) {
let [latter, former] = socks5.split("@").reverse();
let username, password, hostname, port;
if (former) {
const formers = former.split(":");
if (formers.length !== 2) {
throw new Error('Invalid SOCKS address format: authentication must be in the "username:password" format');
}
[username, password] = formers;
}
const latters = latter.split(":");
port = Number(latters.pop());
if (isNaN(port)) {
throw new Error('Invalid SOCKS address format: port must be a number');
}
hostname = latters.join(":");
const isIPv6 = hostname.includes(":") && !/^\[.*\]$/.test(hostname);
if (isIPv6) {
throw new Error('Invalid SOCKS address format: IPv6 addresses must be enclosed in brackets, e.g., [2001:db8::1]');
}
//console.log(`socks5Parser-->: username ${username} \n password: ${password} \n hostname: ${hostname} \n port: ${port}`);
return { username, password, hostname, port };
}
async function parseSocks5FromUrl(socks5, url) {
if (/\/socks5?=/.test(url.pathname)) {
socks5 = url.pathname.split('5=')[1];
} else if (/\/socks[5]?:\/\//.test(url.pathname)) {
socks5 = url.pathname.split('://')[1].split('#')[0];
}
const authIdx = socks5.indexOf('@');
if (authIdx !== -1) {
let userPassword = socks5.substring(0, authIdx);
const base64Regex = /^(?:[A-Z0-9+/]{4})*(?:[A-Z0-9+/]{2}==|[A-Z0-9+/]{3}=)?$/i;
if (base64Regex.test(userPassword) && !userPassword.includes(':')) {
userPassword = atob(userPassword);
}
socks5 = `${userPassword}@${socks5.substring(authIdx + 1)}`;
}
if (socks5) {
try {
return socks5Parser(socks5);
} catch (err) {
console.log(err.toString());
return null;
}
}
return null;
}
/** ---------------------Get data------------------------------ */
let subParams = ['sub', 'base64', 'b64', 'clash', 'singbox', 'sb'];
/**
* @param {string} userID
* @param {string | null} host
* @param {string} userAgent
* @param {string} _url
* @returns {Promise<string>}
*/
async function getchannelConfig(userID, host, userAgent, _url) {
// console.log(`------------getchannelConfig------------------`);
// console.log(`userID: ${userID} \n host: ${host} \n userAgent: ${userAgent} \n _url: ${_url}`);
userAgent = userAgent.toLowerCase();
let port = 443;
if (host.includes('.workers.dev')) {
port = 80;
}
const [v2ray, clash] = getConfigLink(userID, host, host, port, host);
if (userAgent.includes('mozilla') && !subParams.some(param => _url.searchParams.has(param))) {
return getHtmlResponse(socks5Enable, userID, host, v2ray, clash);
}
// Get node information
fakeHostName = getFakeHostName(host);
const ipUrlTxtAndCsv = await getIpUrlTxtAndCsv(noTLS, ipUrlTxt, ipUrlCsv);
// console.log(`txt: ${ipUrlTxtAndCsv.txt} \n csv: ${ipUrlTxtAndCsv.csv}`);
let content = await getSubscribeNode(userAgent, _url, host, fakeHostName, fakeUserID, noTLS, ipUrlTxtAndCsv.txt, ipUrlTxtAndCsv.csv);
return _url.pathname === `/${fakeUserID}` ? content : revertFakeInfo(content, userID, host);
}
function getHtmlResponse(socks5Enable, userID, host, v2ray, clash) {
const subRemark = `IP_LOCAL/IP_URL/IP_URL_TXT/IP_URL_CSV`;
let proxyIPRemark = `PROXYIP: ${proxyIP}`;
if (socks5Enable) {
proxyIPRemark = `socks5: ${parsedSocks5.hostname}:${parsedSocks5.port}`;
}
let remark = `您的订阅节点由设置变量 ${subRemark} 提供, 当前使用反代是${proxyIPRemark}`;
if (!proxyIP && !socks5Enable) {
remark = `您的订阅节点由设置变量 ${subRemark} 提供, 当前没设置反代, 推荐您设置PROXYIP变量或SOCKS5变量或订阅连接带proxyIP`;
}
return getConfigHtml(userID, host, remark, v2ray, clash);
}
function getFakeHostName(host) {
if (host.includes(".pages.dev")) {
return `${fakeHostName}.pages.dev`;
} else if (host.includes(".workers.dev") || host.includes("notls") || noTLS === 'true') {
return `${fakeHostName}.workers.dev`;
}
return `${fakeHostName}.xyz`;
}
async function getIpUrlTxtAndCsv(noTLS, urlTxts, urlCsvs) {
if (noTLS === 'true') {
return {
txt: await getIpUrlTxt(urlTxts),
csv: await getIpUrlCsv(urlCsvs, 'FALSE')
};
}
return {
txt: await getIpUrlTxt(urlTxts),
csv: await getIpUrlCsv(urlCsvs, 'TRUE')
};
}
async function getIpUrlTxt(urlTxts) {
if (!urlTxts || urlTxts.length === 0) {
return [];
}
let ipTxt = "";
// Create an AbortController object to control the cancellation of fetch requests
const controller = new AbortController();
// Set a timeout to trigger the cancellation of all requests after 2 seconds
const timeout = setTimeout(() => {
controller.abort(); // Cancel all requests
}, 2000);
try {
// Use Promise.allSettled to wait for all API requests to complete, regardless of success or failure
// Iterate over the api array and send a fetch request to each API URL
const responses = await Promise.allSettled(urlTxts.map(apiUrl => fetch(apiUrl, {
method: 'GET',
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;',
'User-Agent': projectName
},
signal: controller.signal // Attach the AbortController's signal to the fetch request to allow cancellation when needed
}).then(response => response.ok ? response.text() : Promise.reject())));
// Iterate through all the responses
for (const response of responses) {
// Check if the request was fulfilled successfully
if (response.status === 'fulfilled') {
// Get the response content
const content = await response.value;
ipTxt += content + '\n';
}
}
} catch (error) {
console.error(error);
} finally {
// Clear the timeout regardless of success or failure
clearTimeout(timeout);
}
// Process the result using addIpText function
const newIpTxt = await addIpText(ipTxt);
// console.log(`ipUrlTxts: ${ipUrlTxts} \n ipTxt: ${ipTxt} \n newIpTxt: ${newIpTxt} `);
// Return the processed result
return newIpTxt;
}
async function getIpUrlCsv(urlCsvs, tls) {
// Check if the CSV URLs are valid
if (!urlCsvs || urlCsvs.length === 0) {
return [];
}
const newAddressesCsv = [];
// Fetch and process all CSVs concurrently
const fetchCsvPromises = urlCsvs.map(async (csvUrl) => {
// console.error('getIpUrlCsv--> csvUrl:', csvUrl);
try {
const response = await fetch(csvUrl);
// Ensure the response is successful
if (!response.ok) {
console.error('Error fetching CSV:', response.status, response.statusText);
return;
}
// Parse the CSV content and split it into lines
const text = await response.text();
const lines = text.includes('\r\n') ? text.split('\r\n') : text.split('\n');
// Ensure we have a non-empty CSV
if (lines.length < 2) {
console.error('CSV file is empty or has no data rows');
return;
}
// Extract the header and get required field indexes
const header = lines[0].trim().split(',');
const tlsIndex = header.indexOf('TLS');
const ipAddressIndex = 0; // Assuming the first column is IP address
const portIndex = 1; // Assuming the second column is port
const dataCenterIndex = tlsIndex + 1; // Data center assumed to be right after TLS
const speedIndex = header.length - 1; // Last column for speed
// If the required fields are missing, skip this CSV
if (tlsIndex === -1) {
console.error('CSV file missing required TLS field');
return;
}
// Process the data rows
for (let i = 1; i < lines.length; i++) {
const columns = lines[i].trim().split(',');
// Skip empty or malformed rows
if (columns.length < header.length) {
continue;
}
// Check if TLS matches and speed is greater than sl
const tlsValue = columns[tlsIndex].toUpperCase();
const speedValue = parseFloat(columns[speedIndex]);
if (tlsValue === tls && speedValue > sl) {
const ipAddress = columns[ipAddressIndex];
const port = columns[portIndex];
const dataCenter = columns[dataCenterIndex];
newAddressesCsv.push(`${ipAddress}:${port}#${dataCenter}`);
}
}
} catch (error) {
console.error('Error processing CSV URL:', csvUrl, error);
}
});
// Wait for all CSVs to be processed
await Promise.all(fetchCsvPromises);
return newAddressesCsv;
}
const protocolTypeBase64 = 'dmxlc3M=';
/**
* Get node configuration information
* @param {*} uuid
* @param {*} host
* @param {*} address
* @param {*} port
* @param {*} remarks
* @returns
*/
function getConfigLink(uuid, host, address, port, remarks) {
const protocolType = atob(protocolTypeBase64);
const encryption = 'none';
let path = '/?ed=2560';
const fingerprint = 'randomized';
let tls = ['tls', true];
if (host.includes('.workers.dev') || host.includes('pages.dev')) {
path = `/${host}${path}`;
remarks += ' 请通过绑定自定义域名订阅!';
}
const v2ray = getV2rayLink({ protocolType, host, uuid, address, port, remarks, encryption, path, fingerprint, tls });
const clash = getClashLink(protocolType, host, address, port, uuid, path, tls, fingerprint);
return [v2ray, clash];
}
/**
* Get channel information
* @param {*} param0
* @returns
*/
function getV2rayLink({ protocolType, host, uuid, address, port, remarks, encryption, path, fingerprint, tls }) {
let sniAndFp = `&sni=${host}&fp=${fingerprint}`;
if (portSet_http.has(parseInt(port))) {
tls = ['', false];
sniAndFp = '';
}
const v2rayLink = `${protocolType}://${uuid}@${address}:${port}?encryption=${encryption}&security=${tls[0]}&type=${network}&host=${host}&path=${encodeURIComponent(path)}${sniAndFp}#${encodeURIComponent(remarks)}`;
return v2rayLink;
}
/**
* getClashLink
* @param {*} protocolType
* @param {*} host
* @param {*} address
* @param {*} port
* @param {*} uuid
* @param {*} path
* @param {*} tls
* @param {*} fingerprint
* @returns
*/
function getClashLink(protocolType, host, address, port, uuid, path, tls, fingerprint) {
return `- {type: ${protocolType}, name: ${host}, server: ${address}, port: ${port}, password: ${uuid}, network: ${network}, tls: ${tls[1]}, udp: false, sni: ${host}, client-fingerprint: ${fingerprint}, skip-cert-verify: true, ws-opts: {path: ${path}, headers: {Host: ${host}}}}`;
// return `
// - type: ${protocolType}
// name: ${host}
// server: ${address}
// port: ${port}
// uuid: ${uuid}
// network: ${network}
// tls: ${tls[1]}
// udp: false
// sni: ${host}
// client-fingerprint: ${fingerprint}
// ws-opts:
// path: "${path}"
// headers:
// host: ${host}
// `;
}
/**
* Generate home page
* @param {*} userID
* @param {*} hostName
* @param {*} remark
* @param {*} v2ray
* @param {*} clash
* @returns
*/
function getConfigHtml(userID, host, remark, v2ray, clash) {
// HTML Head with CSS and FontAwesome library
const htmlHead = `
<head>
<title>${projectName}(${fileName})</title>
<meta name='description' content='This is a project to generate free vmess nodes. For more information, please subscribe youtube(AM科技) https://youtube.com/@AM_CLUB and follow GitHub https://github.com/amclubs ' />
<style>
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
color: #333;
padding: 0;
margin: 0;
}
a {
color: #1a0dab;
text-decoration: none;
}
img {
max-width: 100%;
height: auto;
}
pre {
white-space: pre-wrap;
word-wrap: break-word;
background-color: #fff;
border: 1px solid #ddd;
padding: 10px;
margin: 0;
}
/* Dark mode */
@media (prefers-color-scheme: dark) {
body {
background-color: #333;
color: #f0f0f0;
}
a {
color: #9db4ff;
}
pre {
background-color: #282a36;
border-color: #6272a4;
}
}
</style>
</head>
`;
// Prepare header string with left alignment
const header = `
<p align="left" style="padding-left: 20px; margin-top: 20px;">
Telegram交流群 技术大佬~在线交流</br>
<a href="t.me/AM_CLUBS" target="_blank">t.me/AM_CLUBS</a>
</br></br>
GitHub项目地址 点击Star!Star!Star!</br>
<a href="https://github.com/${projectName}" target="_blank">https://github.com/${projectName}</a>
</br></br>
YouTube频道,订阅频道,更多技术分享</br>
<a href="${ytName}" target="_blank">${ytName}</a>
</p>
`;
// Prepare the output string
const httpAddr = `https://${host}/${userID}`;
const output = `
################################################################
订阅地址, 支持 Base64、clash-meta、sing-box、Quantumult X、小火箭、surge 等订阅格式, ${remark}
---------------------------------------------------------------
通用订阅地址: <button onclick='copyToClipboard("${httpAddr}?sub")'><i class="fa fa-clipboard"></i> 点击复制订阅地址 </button>
${httpAddr}?sub
Base64订阅地址: <button onclick='copyToClipboard("${httpAddr}?base64")'><i class="fa fa-clipboard"></i> 点击复制订阅地址 </button>
${httpAddr}?base64
clash订阅地址: <button onclick='copyToClipboard("${httpAddr}?clash")'><i class="fa fa-clipboard"></i> 点击复制订阅地址 </button>
${httpAddr}?clash
singbox订阅地址: <button onclick='copyToClipboard("${httpAddr}?singbox")'><i class="fa fa-clipboard"></i> 点击复制订阅地址 </button>
${httpAddr}?singbox
---------------------------------------------------------------
################################################################
v2ray
---------------------------------------------------------------
${v2ray}
---------------------------------------------------------------
################################################################
clash-meta
---------------------------------------------------------------
${clash}
---------------------------------------------------------------
################################################################
`;
// Final HTML
const html = `
<html>
${htmlHead}
<body>
${header}
<pre>${output}</pre>
<script>
function copyToClipboard(text) {
navigator.clipboard.writeText(text)
.then(() => {
alert("Copied to clipboard");
})
.catch(err => {
console.error("Failed to copy to clipboard:", err);
});
}
</script>
</body>
</html>
`;
return html;
}
let portSet_http = new Set([80, 8080, 8880, 2052, 2086, 2095, 2082]);
let portSet_https = new Set([443, 8443, 2053, 2096, 2087, 2083]);
/**
*
* @param {*} host
* @param {*} uuid
* @param {*} noTLS
* @param {*} ipUrlTxt
* @param {*} ipUrlCsv
* @returns
*/
async function getSubscribeNode(userAgent, _url, host, fakeHostName, fakeUserID, noTLS, ipUrlTxt, ipUrlCsv) {
// Use Set object to remove duplicates
const uniqueIpTxt = [...new Set([...ipLocal, ...ipUrlTxt, ...ipUrlCsv])];
let responseBody = splitNodeData(uniqueIpTxt, noTLS, fakeHostName, fakeUserID, userAgent);
// console.log(`getSubscribeNode---> responseBody: ${responseBody} `);
if (!userAgent.includes(('CF-FAKE-UA').toLowerCase())) {
let url = `https://${host}/${fakeUserID}`;
if (isClashCondition(userAgent, _url)) {
isBase64 = false;
url = createSubConverterUrl('clash', url, subConfig, subConverter, subProtocol);
} else if (isSingboxCondition(userAgent, _url)) {
isBase64 = false;
url = createSubConverterUrl('singbox', url, subConfig, subConverter, subProtocol);
} else {
return responseBody;
}
const response = await fetch(url, {
headers: {
//'Content-Type': 'text/html; charset=UTF-8',
'User-Agent': `${userAgent} ${projectName}`
}
});
responseBody = await response.text();
//console.log(`getSubscribeNode---> url: ${url} `);
}
return responseBody;
}
function createSubConverterUrl(target, url, subConfig, subConverter, subProtocol) {
return `${subProtocol}://${subConverter}/sub?target=${target}&url=${encodeURIComponent(url)}&insert=false&config=${encodeURIComponent(subConfig)}&emoji=true&list=false&tfo=false&scv=true&fdn=false&sort=false&new_name=true`;
}
function isClashCondition(userAgent, _url) {
return (userAgent.includes('clash') && !userAgent.includes('nekobox')) || (_url.searchParams.has('clash') && !userAgent.includes('subConverter'));
}
function isSingboxCondition(userAgent, _url) {
return userAgent.includes('sing-box') || userAgent.includes('singbox') || ((_url.searchParams.has('singbox') || _url.searchParams.has('sb')) && !userAgent.includes('subConverter'));
}
/**
*
* @param {*} uniqueIpTxt
* @param {*} noTLS
* @param {*} host
* @param {*} uuid
* @returns
*/
function splitNodeData(uniqueIpTxt, noTLS, host, uuid, userAgent) {
// Regex to match IPv4 and IPv6
const regex = /^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\[.*\]):?(\d+)?#?(.*)?$/;
// Region codes mapped to corresponding emojis
const regionMap = {
'SG': '🇸🇬 SG',
'HK': '🇭🇰 HK',
'KR': '🇰🇷 KR',
'JP': '🇯🇵 JP',
'GB': '🇬🇧 GB',
'US': '🇺🇸 US',
'TW': '🇼🇸 TW',
'CF': '📶 CF'
};
const responseBody = uniqueIpTxt.map(ipTxt => {
let address = ipTxt;
let port = "443";
let remarks = "";
const match = address.match(regex);
if (match) {
address = match[1];
port = match[2] || port;
remarks = match[3] || host;
} else {
let ip, newPort, extra;
if (ipTxt.includes(':') && ipTxt.includes('#')) {
[ip, newPort, extra] = ipTxt.split(/[:#]/);
} else if (ipTxt.includes(':')) {
[ip, newPort] = ipTxt.split(':');
} else if (ipTxt.includes('#')) {
[ip, extra] = ipTxt.split('#');
} else {
ip = ipTxt;
}
address = ip;
port = newPort || port;
remarks = extra || host;
// console.log(`splitNodeData---> ip: ${ip} \n extra: ${extra} \n port: ${port}`);
}
// Replace region code with corresponding emoji
remarks = regionMap[remarks] || remarks;
// Check if TLS is disabled and if the port is in the allowed set
if (noTLS !== 'true' && portSet_http.has(parseInt(port))) {
return null; // Skip this iteration
}
const [v2ray, clash] = getConfigLink(uuid, host, address, port, remarks);
return v2ray;
}).filter(Boolean).join('\n');
let base64Response = responseBody;
return btoa(base64Response);
}
/** ---------------------Get CF data------------------------------ */
async function getCFConfig(email, key, accountIndex) {
try {
const now = new Date();
const today = new Date(now);
today.setHours(0, 0, 0, 0);
// Calculate default value
const ud = Math.floor(((now - today.getTime()) / 86400000) * 24 * 1099511627776 / 2);
let upload = ud;
let download = ud;
let total = 24 * 1099511627776;
if (email && key) {
const accountId = await getAccountId(email, key);
if (accountId) {
// Calculate start and end time
now.setUTCHours(0, 0, 0, 0);
const startDate = now.toISOString();
const endDate = new Date().toISOString();
// Get summary data
const [pagesSumResult, workersSumResult] = await getCFSum(accountId, accountIndex, email, key, startDate, endDate);
upload = pagesSumResult;
download = workersSumResult;