forked from amclubs/am-cf-tunnel-sub
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path_worker.src.js
More file actions
2876 lines (2614 loc) · 102 KB
/
_worker.src.js
File metadata and controls
2876 lines (2614 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* YouTube : https://youtube.com/@am_clubs
* Telegram : https://t.me/am_clubs
* GitHub : https://github.com/amclubs
* BLog : https://amclubss.com
*/
let id = base64Decode('ZWM4NzJkOGYtNzJiMC00YTA0LWI2MTItMDMyN2Q4NWUxOGVk');
let uuid;
let host;
let paddr;
let s5 = '';
let socks5Enable = false;
let parsedSocks5 = {};
let ipLocal = [
'wto.org:443#youtube.com/@am_clubs 数字套利(视频教程)',
'icook.hk#t.me/am_clubs TG群(加入解锁更多节点)',
'time.is#github.com/amclubs GitHub仓库(关注查看新功能)',
'127.0.0.1:1234#amclubss.com 博客教程(cfnat)'
];
const defaultIpUrlTxt = base64Decode('aHR0cHM6Ly9yYXcuZ2l0aHVidXNlcmNvbnRlbnQuY29tL2FtY2x1YnMvYW0tY2YtdHVubmVsL21haW4vZXhhbXBsZS9pcHY0LnR4dA==');
let randomNum = 25;
let ipUrlTxt = [defaultIpUrlTxt];
let ipUrlCsv = [];
let noTLS = false;
let sl = 5;
let fakeUserId;
let fakeHostName;
let isBase64 = true;
let subConfig = base64Decode('aHR0cHM6Ly9yYXcuZ2l0aHVidXNlcmNvbnRlbnQuY29tL2FtY2x1YnMvQUNMNFNTUi9tYWluL0NsYXNoL2NvbmZpZy9BQ0w0U1NSX09ubGluZV9GdWxsX011bHRpTW9kZS5pbmk=');
let subConverter = base64Decode('dXJsLnYxLm1r');
let subProtocol = 'https';
let subUpdateTime = 6;
let timestamp = 4102329600000;
let total = 99 * 1125899906842624;
let download = Math.floor(Math.random() * 1099511627776);
let upload = download;
let expire = Math.floor(timestamp / 1000);
let nat64 = true;
let nat64Prefix;
let nat64Prefixs = [
'2602:fc59:b0:64::'
];
const protTypeBase64 = 'ZG14bGMzTT0=';
const protTypeBase64Tro = 'ZEhKdmFtRnU=';
const httpPattern = /^http(s)?:\/\/.+/;
let network = 'ws';
let projectName = base64Decode('YW1jbHVicw==');
let fileName = '5pWw5a2X5aWX5Yip';
let ytName = base64Decode('aHR0cHM6Ly95b3V0dWJlLmNvbS9AYW1fY2x1YnM/c3ViX2NvbmZpcm1hdGlvbj0x');
let tgName = base64Decode('aHR0cHM6Ly90Lm1lL2FtX2NsdWJz');
let ghName = base64Decode('aHR0cHM6Ly9naXRodWIuY29tL2FtY2x1YnMvYW0tY2YtdHVubmVs');
let bName = base64Decode('aHR0cHM6Ly9hbWNsdWJzcy5jb20=');
let pName = '5pWw5a2X5aWX5Yip';
let hostRemark;
let enableLog = false;
let enableOpen = true;
const DEFAULT_TARGET_COUNT = 512;
let nipHost = base64Decode('bmlwLmxmcmVlLm9yZw==');
let extraIp;
let extraIpProxy;
export default {
async fetch(request, env) {
try {
const url = new URL(request.url);
const headers = request.headers;
return await mainHandler({ req: request, url, headers, res: null, env });
} catch (err) {
errorLogs('Worker Error:', err);
return new Response('Worker Error: ' + err.message, { status: 500 });
}
},
};
// ======= 主逻辑函数(共用) =======
async function mainHandler({ req, url, headers, res, env }) {
const { ENABLE_LOG, ID, UUID, HOST, SOCKS5, IP_URL, PROXYIP, NAT64, NAT64_PREFIX, HOST_REMARK, PROT_TYPE, RANDOW_NUM, SUB_CONFIG, SUB_CONVERTER, NO_TLS, NIP_HOST, EXTRA_IP, EXTRA_IP_PROXY, ENABLE_OPEN } = env || {};
const rawHost = headers.get('host') || headers.get('Host') || 'localhost';
const userAgent = headers.get('User-Agent') || '';
log(`[mainHandler]-->rawHost: ${rawHost}`);
const rawEnableLog = url.searchParams.get('ENABLE_LOG') || getEnvVar('ENABLE_LOG', env) || enableLog;
enableLog = parseBool(rawEnableLog, enableLog);
const rawEnableOpen = getEnvVar('ENABLE_OPEN', env) || enableOpen;
enableOpen = parseBool(rawEnableOpen, enableOpen);
noTLS = url.searchParams.get('NO_TLS') || getEnvVar('NO_TLS', env) || noTLS;
id = getEnvVar('ID', env) || ID || id;
uuid = url.searchParams.get('UUID') || getEnvVar('UUID', env) || UUID;
host = url.searchParams.get('HOST') || getEnvVar('HOST', env) || HOST;
log(`[mainHandler]-->id: ${id} uuid: ${uuid} host: ${host}`);
s5 = url.searchParams.get('SOCKS5') || getEnvVar('SOCKS5', env) || SOCKS5 || s5;
parsedSocks5 = await parseSocks5FromUrl(s5, url);
if (parsedSocks5) socks5Enable = true;
let ip_url = url.searchParams.get('IP_URL') || getEnvVar('IP_URL', env) || IP_URL;
if (ip_url) {
const result = await parseIpUrl(ip_url);
ipUrlCsv = result.ipUrlCsvResult;
ipUrlTxt = result.ipUrlTxtResult;
}
const existing = await loadFromKV(env, decodeBase64Utf8('Y2Zfbm9ybWFsX2lw'));
if (existing && existing.trim().length > 0) {
ipLocal = existing.split('\n').map(v => v.trim()).filter(v => v);
}
let proxyIPsAll = [];
const proxyIPUrl = url.searchParams.get('PROXYIP') || getEnvVar('PROXYIP', env) || PROXYIP;
if (proxyIPUrl) {
if (httpPattern.test(proxyIPUrl)) {
const proxyIpTxt = await addIpText(proxyIPUrl);
let ipUrlTxtAndCsv;
if (proxyIPUrl.endsWith('.csv')) {
ipUrlTxtAndCsv = await getIpUrlTxtAndCsv(noTLS, null, proxyIpTxt);
} else {
ipUrlTxtAndCsv = await getIpUrlTxtAndCsv(noTLS, proxyIpTxt, null);
}
const uniqueIpTxt = [...new Set([...ipUrlTxtAndCsv.txt, ...ipUrlTxtAndCsv.csv])];
proxyIPsAll.push(...uniqueIpTxt);
} else {
const proxyIPs = await addIpText(proxyIPUrl);
proxyIPsAll.push(...proxyIPs);
}
}
const existingProxy = await loadFromKV(env, decodeBase64Utf8('Y2ZfcHJveHlfaXA='));
if (existingProxy && existingProxy.trim().length > 0) {
const fromKv = existingProxy.split('\n').map(v => v.trim()).filter(v => v).map(v => v.split('#')[0]).map(v => v.trim()).filter(v => v);
proxyIPsAll.push(...fromKv);
}
proxyIPsAll = [...new Set(proxyIPsAll)];
if (proxyIPsAll.length > 0) {
paddr = proxyIPsAll[Math.floor(Math.random() * proxyIPsAll.length)];
}
nat64 = url.searchParams.get('NAT64') || getEnvVar('NAT64', env) || NAT64 || nat64;
const nat64PrefixUrl = url.searchParams.get('NAT64_PREFIX') || getEnvVar('NAT64_PREFIX', env);
if (nat64PrefixUrl) {
if (httpPattern.test(nat64PrefixUrl)) {
const proxyIpTxt = await addIpText(nat64PrefixUrl);
let ipUrlTxtAndCsv;
if (nat64PrefixUrl.endsWith('.csv')) {
ipUrlTxtAndCsv = await getIpUrlTxtAndCsv(noTLS, null, proxyIpTxt);
} else {
ipUrlTxtAndCsv = await getIpUrlTxtAndCsv(noTLS, proxyIpTxt, null);
}
const uniqueIpTxt = [...new Set([...ipUrlTxtAndCsv.txt, ...ipUrlTxtAndCsv.csv])];
nat64Prefix = uniqueIpTxt[Math.floor(Math.random() * uniqueIpTxt.length)];
} else {
nat64Prefixs = await addIpText(nat64PrefixUrl);
nat64Prefix = nat64Prefixs[Math.floor(Math.random() * nat64Prefixs.length)];
}
}
hostRemark = url.searchParams.get('HOST_REMARK') || getEnvVar('HOST_REMARK', env) || hostRemark;
let protType = url.searchParams.get('PROT_TYPE') || getEnvVar('PROT_TYPE', env);
if (protType) protType = protType.toLowerCase();
randomNum = url.searchParams.get('RANDOW_NUM') || getEnvVar('RANDOW_NUM', env) || randomNum;
log(`[handler]-->randomNum: ${randomNum}`);
subConfig = getEnvVar('SUB_CONFIG', env) || SUB_CONFIG || subConfig;
subConverter = getEnvVar('SUB_CONVERTER', env) || SUB_CONVERTER || subConverter;
let subProtocol, subConverterWithoutProtocol;
if (subConverter.startsWith("http://") || subConverter.startsWith("https://")) {
[subProtocol, subConverterWithoutProtocol] = subConverter.split("://");
} else {
[subProtocol, subConverterWithoutProtocol] = [undefined, subConverter];
}
subConverter = subConverterWithoutProtocol;
nipHost = getEnvVar('NIP_HOST', env) || nipHost;
extraIp = getEnvVar('EXTRA_IP', env) || extraIp;
extraIpProxy = getEnvVar('EXTRA_IP_PROXY', env) || extraIpProxy;
fakeUserId = await getFakeUserId(uuid);
fakeHostName = getFakeHostName(rawHost, noTLS);
log(`[handler]-->fakeUserId: ${fakeUserId}`);
// ---------------- 路由 ----------------
if (url.pathname === `/setting` && !enableOpen) {
const html = await getSettingHtml(rawHost);
return sendResponse(html, userAgent, res);
}
if (url.pathname === "/login") {
const result = await login(req, env, res);
return result;
}
if (url.pathname === `/${id}/setting`) {
const html = await getSettingHtml(rawHost);
return sendResponse(html, userAgent, res);
}
if (url.pathname === `/${id}`) {
const html = await getConfig(rawHost, uuid, host, paddr, parsedSocks5, userAgent, url, protType, nat64, hostRemark);
return sendResponse(html, userAgent, res);
}
if (url.pathname === `/${fakeUserId}`) {
const html = await getConfig(rawHost, uuid, host, paddr, parsedSocks5, 'CF-FAKE-UA', url, protType, nat64, hostRemark);
return sendResponse(html, 'CF-FAKE-UA', res);
}
// ✅
if (url.pathname === `/${id}/ips`) {
const html = await htmlPage();
return sendResponse(html, userAgent, res);
}
if (url.pathname === '/ipsFetch') {
const ipSource = url.searchParams.get('ipSource');
const port = url.searchParams.get('port') || '443';
nipHost = getNipHost(nipHost);
log(`[handler]-->nipHost: ${nipHost}`);
let ipData = await loadIpSource(ipSource, port);
log('ipData type:', typeof ipData, ipData);
if (ipData instanceof Response) {
ipData = await ipData.text();
}
if (Array.isArray(ipData)) {
return new Response(JSON.stringify({ ips: ipData.filter(l => l) }), {
headers: { 'Content-Type': 'application/json' }
})
}
return new Response(JSON.stringify({ ips: ipData.split('\n').filter(l => l) }), {
headers: { 'Content-Type': 'application/json' }
})
}
if (url.pathname === `/${id}/save`) {
try {
const body = await readJsonBody(req);
log("[handler]--> save body: ", body);
const { key, items } = body;
await saveToKV(env, key, items);
return sendResponse(JSON.stringify({ ok: true }), userAgent, res);
} catch (e) {
return sendResponse(JSON.stringify({ ok: false, error: e.message || String(e) }), userAgent, res, 500);
}
}
if (url.pathname === `/${id}/append`) {
try {
const body = await readJsonBody(req);
const { key, items } = body;
await appendToKV(env, key, items);
return sendResponse(JSON.stringify({ ok: true }), userAgent, res);
} catch (e) {
return sendResponse(JSON.stringify({ ok: false, error: e.message || String(e) }), userAgent, res, 500);
}
}
if (url.pathname === `/${id}/load`) {
try {
let body = {};
try {
body = await readJsonBody(req);
} catch (e) {
return sendResponse(JSON.stringify({ ok: false, error: "Invalid JSON body" }), userAgent, res, 400);
}
if (!body.key) {
return sendResponse(JSON.stringify({ ok: false, error: "Missing key" }), userAgent, res, 400);
}
const value = await loadFromKV(env, body.key);
if (!value) {
return sendResponse(JSON.stringify({ ok: false, error: "KV key not found" }), userAgent, res, 404);
}
return sendResponse(JSON.stringify({ ok: true, value }), userAgent, res);
} catch (err) {
return sendResponse(JSON.stringify({ ok: false, error: err.message }), userAgent, res, 500);
}
}
return login(req, env, res);
}
/** --------------------- main ------------------------------ */
function getEnvVar(key, env) {
if (env && typeof env[key] !== 'undefined') {
return env[key];
}
if (typeof process !== 'undefined' && process.env && typeof process.env[key] !== 'undefined') {
return process.env[key];
}
return undefined;
}
function isCloudflareRuntime(env) {
const isCFCache = typeof caches !== "undefined" && caches.default;
const isCFEnv = env && Object.prototype.toString.call(env) === "[object Object]";
const isNotNode = typeof process === "undefined" || !process.release || process.release.name !== "node";
if (isCFCache && isCFEnv && isNotNode) {
log("[isCloudflareRuntime]--> ✅ Cloudflare Runtime");
return true;
}
log("[isCloudflareRuntime]--> ❌ Vercel/Node Runtime");
return false;
}
function isCloudflareRequest(req) {
return typeof Request !== 'undefined' && req instanceof Request;
}
async function readJsonBody(req) {
if (isCloudflareRequest(req)) {
return await req.json();
}
return await new Promise((resolve, reject) => {
let raw = '';
req.on('data', chunk => raw += chunk);
req.on('end', () => {
try {
resolve(JSON.parse(raw));
} catch (e) {
reject(new Error('Invalid JSON'));
}
});
req.on('error', reject);
});
}
function parseBool(val, defaultVal = false) {
if (val === undefined || val === null) return defaultVal;
if (typeof val === 'boolean') return val;
if (typeof val === 'string') {
return ['1', 'true', 'yes', 'on'].includes(val.toLowerCase());
}
if (typeof val === 'number') return val === 1;
return defaultVal;
}
/** ---------------------Tools------------------------------ */
function log(...args) {
if (!enableLog) {
return;
}
let prefix = '';
try {
// ✅ 判断 Cloudflare Worker 环境
if (typeof WebSocketPair !== 'undefined' && typeof addEventListener === 'function' && typeof caches !== 'undefined') {
prefix = '[CF]';
}
// ✅ 判断 Vercel / Node 环境
else if (typeof process !== 'undefined' && process.release?.name === 'node') {
prefix = '[VC]';
}
// ✅ 其他未知环境
else {
prefix = '[SYS]';
}
} catch (e) {
prefix = '[LOG]';
}
const timestamp = new Date().toISOString().replace('T', ' ').split('.')[0];
console.log(`${prefix} ${timestamp} →`, ...args);
}
function errorLogs(err, extra = {}) {
let prefix = '';
try {
// 判断 Cloudflare Worker 环境
if (typeof WebSocketPair !== 'undefined' && typeof addEventListener === 'function' && typeof caches !== 'undefined') {
prefix = '[CF-ERR]';
}
// 判断 Vercel / Node.js 环境
else if (typeof process !== 'undefined' && process.release?.name === 'node') {
prefix = '[VC-ERR]';
}
else {
prefix = '[SYS-ERR]';
}
} catch {
prefix = '[ERR]';
}
const timestamp = new Date().toISOString().replace('T', ' ').split('.')[0];
if (err instanceof Error) {
console.error(`${prefix} ${timestamp} →`, err.message, '\nStack:', err.stack, extra);
} else {
console.error(`${prefix} ${timestamp} →`, err, extra);
}
}
function getHeader(req, name) {
try {
if (!req || !req.headers) return '';
// Edge Headers
if (typeof req.headers.get === 'function') {
const v = req.headers.get(name);
return (v === undefined || v === null) ? '' : String(v);
}
// Node.js headers
const v2 = req.headers[name.toLowerCase()];
return (v2 === undefined || v2 === null) ? '' : String(v2);
} catch (e) {
errorLogs('getHeader error:', e);
return '';
}
}
function sendResponse(content, userAgent = '', res = null, status = 200) {
if (!status || typeof status !== 'number') status = 200;
const isMozilla = userAgent.toLowerCase().includes('mozilla');
const headers = {
"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}`,
};
if (!isMozilla) {
const fileNameAscii = encodeURIComponent(decodeBase64Utf8(fileName));
headers["Content-Disposition"] = `attachment; filename=${fileNameAscii}; filename*=gbk''${fileNameAscii}`;
}
// Node / Vercel Serverless
if (res) {
Object.entries(headers).forEach(([k, v]) => res.setHeader(k, v));
if (typeof res.status === 'function') return res.status(status).send(content);
if (typeof res.writeHead === 'function') {
res.writeHead(status, headers);
res.end(content);
return;
}
}
// Edge / CF Worker / Vercel Edge
if (typeof Response !== 'undefined') {
return new Response(content, { status, headers });
}
return content;
}
function base64Encode(input) {
try {
return Buffer.from(input, 'utf-8').toString('base64');
} catch (e) {
if (typeof btoa === 'function') {
const utf8 = new TextEncoder().encode(input);
let binary = '';
utf8.forEach(b => binary += String.fromCharCode(b));
return btoa(binary);
} else {
throw new Error('Base64 encode not supported in this environment');
}
}
}
function base64Decode(input) {
if (typeof atob === 'function') {
// Edge Runtime
return atob(input);
} else if (typeof Buffer === 'function') {
// Node.js
return Buffer.from(input, 'base64').toString('utf-8');
} else {
throw new Error('Base64 decode not supported in this environment');
}
}
function doubleBase64Decode(input) {
const first = base64Decode(input);
return base64Decode(first);
}
function getFileType(url) {
const baseUrl = url.split('@')[0];
const extension = baseUrl.match(/\.(csv|txt)$/i);
if (extension) {
return extension[1].toLowerCase();
} else {
return 'txt';
}
}
async function addIpText(envAdd) {
var addText = envAdd.replace(/[ |"'\r\n]+/g, ',').replace(/,+/g, ',');
//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(',');
// 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]');
}
//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) {
log(err.toString());
return null;
}
}
return null;
}
function getRandomItems(arr, count) {
if (!Array.isArray(arr)) return [];
const shuffled = [...arr].sort(() => 0.5 - Math.random());
return shuffled.slice(0, count);
}
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 getFakeHostName(host, noTLS) {
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`;
}
function revertFakeInfo(content, userId, hostName) {
log(`revertFakeInfo-->: isBase64 ${isBase64} \n content: ${content}`);
if (isBase64) {
content = base64Decode(content);
}
content = content.replace(new RegExp(fakeUserId, 'g'), userId).replace(new RegExp(fakeHostName, 'g'), hostName);
if (isBase64) {
content = base64Encode(content);
}
return content;
}
function decodeBase64Utf8(str) {
const bytes = Uint8Array.from(atob(str), c => c.charCodeAt(0));
return new TextDecoder('utf-8').decode(bytes);
}
function xEn(plain, key) {
const encoder = new TextEncoder();
const p = encoder.encode(plain);
const k = encoder.encode(key);
const out = new Uint8Array(p.length);
for (let i = 0; i < p.length; i++) {
out[i] = p[i] ^ k[i % k.length];
}
return btoa(String.fromCharCode(...out));
}
function xDe(b64, key) {
const data = Uint8Array.from(atob(b64), c => c.charCodeAt(0));
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const k = encoder.encode(key);
const out = new Uint8Array(data.length);
for (let i = 0; i < data.length; i++) {
out[i] = data[i] ^ k[i % k.length];
}
return decoder.decode(out);
}
async function parseIpUrl(ip_url) {
const newCsvUrls = [];
const newTxtUrls = [];
try {
const response = await fetch(ip_url);
const text = await response.text();
const lines = text.split(/\r?\n/).map(l => l.trim()).filter(Boolean);
const hasHttpLinks = lines.some(line => /^https?:\/\//i.test(line));
if (hasHttpLinks) {
lines.forEach(u => {
if (/^https?:\/\//i.test(u)) {
if (getFileType(u) === 'csv') {
newCsvUrls.push(u);
} else {
newTxtUrls.push(u);
}
}
});
} else {
if (getFileType(ip_url) === 'csv') {
newCsvUrls.push(ip_url);
} else {
newTxtUrls.push(ip_url);
}
}
const ipUrlCsvResult = [...new Set(newCsvUrls)];
const ipUrlTxtResult = [...new Set(newTxtUrls)];
return { ipUrlCsvResult, ipUrlTxtResult };
} catch (err) {
errorLogs('获取 IP_URL 文件内容失败:', err);
return { ipUrlCsvResult: [], ipUrlTxtResult: [] };
}
}
/** ---------------------Get data------------------------------ */
let subParams = ['sub', 'base64', 'b64', 'clash', 'singbox', 'sb'];
let portSet_http = new Set([80, 8080, 8880, 2052, 2086, 2095, 2082]);
let portSet_https = new Set([443, 8443, 2053, 2096, 2087, 2083]);
async function getConfig(rawHost, userId, host, proxyIP, parsedSocks5, userAgent, _url, protType, nat64, hostRemark) {
log(`------------getConfig------------------`);
log(`userId: ${userId} \n host: ${host} \n proxyIP: ${proxyIP} \n userAgent: ${userAgent} \n _url: ${_url} \n protType: ${protType} \n nat64: ${nat64} \n hostRemark: ${hostRemark} `);
userAgent = userAgent.toLowerCase();
let port = 443;
if (host.includes('.workers.dev')) {
port = 80;
}
if (userAgent.includes('mozilla') && !subParams.some(param => _url.searchParams.has(param))) {
if (!protType) {
protType = doubleBase64Decode(protTypeBase64);
}
const [v2, clash] = getConfigLink(userId, host, host, port, host, proxyIP, protType, nat64);
return getHtmlRes(rawHost, proxyIP, socks5Enable, parsedSocks5, host, v2, clash);
}
let num = randomNum || 25;
if (protType && !randomNum) {
num = num * 2;
}
const ipUrlTxtAndCsv = await getIpUrlTxtAndCsv(noTLS, ipUrlTxt, ipUrlCsv, num);
log(`txt: ${ipUrlTxtAndCsv.txt} \n csv: ${ipUrlTxtAndCsv.csv}`);
let content = await getConfigContent(rawHost, userAgent, _url, host, fakeHostName, fakeUserId, noTLS, ipUrlTxtAndCsv.txt, ipUrlTxtAndCsv.csv, protType, nat64, hostRemark);
return _url.pathname === `/${fakeUserId}` ? content : revertFakeInfo(content, userId, host);
}
function getHtmlRes(rawHost, proxyIP, socks5Enable, parsedSocks5, host, v2, clash) {
const subRemark = `IP_LOCAL/IP_URL`;
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(rawHost, remark, v2, clash);
}
function getConfigLink(uuid, host, address, port, remarks, proxyip, protType, nat64) {
const ep = 'none';
let pathParm = `&PROT_TYPE=${protType}`;
if (proxyip) {
pathParm = pathParm + `&PADDR=${proxyip}`;
}
if (nat64) {
pathParm = pathParm + `&P64=${nat64}`;
}
if (nat64Prefix) {
pathParm = pathParm + `&P64PREFIX=${nat64Prefix}`;
}
if (s5) {
pathParm = pathParm + `&S5=${s5}`;
}
let path = `/?ed=2560` + pathParm;
const fp = 'randomized';
let tls = ['tls', true];
if (host.includes('.workers.dev') || host.includes('pages.dev')) {
path = `/${host}${path}`;
remarks += ' 请用绑定自定义域名访问再订阅!';
}
const v2 = getv2LinkConfig({ protType, host, uuid, address, port, remarks, ep, path, fp, tls });
const clash = getCLinkConfig(protType, host, address, port, uuid, path, tls, fp);
return [v2, clash];
}
function getv2LinkConfig({ protType, host, uuid, address, port, remarks, ep, path, fp, tls }) {
log(`------------getv2LinkConfig------------------`);
log(`protType: ${protType} \n host: ${host} \n uuid: ${uuid} \n address: ${address} \n port: ${port} \n remarks: ${remarks} \n ep: ${ep} \n path: ${path} \n fp: ${fp} \n tls: ${tls} `);
let sAndp = `&sni=${host}&fp=${fp}`;
if (portSet_http.has(parseInt(port))) {
tls = ['', false];
sAndp = '';
}
const k = 'id';
const t = xEn(protType, k);
const u = xEn(uuid, k);
const a = xEn(address, k);
const p = xEn(port, k);
const v2 = `${xDe(t, k)}://${xDe(u, k)}@${xDe(a, k)}:${xDe(p, k)}\u003f\u0065\u006e\u0063\u0072\u0079` + 'p' + `${atob('dGlvbj0=')}${ep}\u0026\u0073\u0065\u0063\u0075\u0072\u0069\u0074\u0079\u003d${tls[0]}&type=${network}&host=${host}&path=${encodeURIComponent(path)}${sAndp}#${encodeURIComponent(remarks)}`;
return v2;
}
function getCLinkConfig(protType, host, address, port, uuid, path, tls, fp) {
log(`------------getCLinkConfig------------------`);
log(`protType: ${protType} \n host: ${host} \n address: ${address} \n port: ${port} \n uuid: ${uuid} \n path: ${path} \n tls: ${tls} \n fp: ${fp} `);
const k = 'idc';
const t = xEn(protType, k);
const u = xEn(uuid, k);
const a = xEn(address, k);
const p = xEn(port, k);
return `- {type: ${xDe(t, k)}, name: ${host}, server: ${xDe(a, k)}, port: ${xDe(p, k)}, password: ${xDe(u, k)}, network: ${network}, tls: ${tls[1]}, udp: false, sni: ${host}, client-fingerprint: ${fp}, skip-cert-verify: true, ws-opts: {path: ${path}, headers: {Host: ${host}}}}`;
}
async function getConfigContent(rawHost, userAgent, _url, host, fakeHostName, fakeUserId, noTLS, ipUrlTxt, ipUrlCsv, protType, nat64, hostRemark) {
log(`------------getConfigContent------------------`);
const uniqueIpTxt = [...new Set([...ipUrlTxt, ...ipUrlCsv])];
let responseBody;
log(`[getConfigContent]---> protType: ${protType}`);
if (!protType) {
protType = doubleBase64Decode(protTypeBase64);
const responseBody1 = splitNodeData(uniqueIpTxt, noTLS, fakeHostName, fakeUserId, userAgent, protType, nat64, hostRemark);
const responseBodyTop = splitNodeData(ipLocal, noTLS, fakeHostName, fakeUserId, userAgent, protType, nat64, hostRemark);
protType = doubleBase64Decode(protTypeBase64Tro);
const responseBody2 = splitNodeData(uniqueIpTxt, noTLS, fakeHostName, fakeUserId, userAgent, protType, nat64, hostRemark);
responseBody = [responseBodyTop, responseBody1, responseBody2].join('\n');
} else {
const responseBodyTop = splitNodeData(ipLocal, noTLS, fakeHostName, fakeUserId, userAgent, protType, nat64, hostRemark);
responseBody = splitNodeData(uniqueIpTxt, noTLS, fakeHostName, fakeUserId, userAgent, protType, nat64, hostRemark);
responseBody = [responseBodyTop, responseBody].join('\n');
}
responseBody = base64Encode(responseBody);
if (!userAgent.includes(('CF-FAKE-UA').toLowerCase())) {
const safeHost = (rawHost || '').replace(/^https?:\/\//, '');
let url = `https://${safeHost}/${fakeUserId}`;
log(`[getConfigContent]---> url: ${url}`);
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;
}
try {
const finalUrl = new URL(url).toString();
log(`[getConfigContent] Fetching from: ${finalUrl}`);
const response = await fetch(finalUrl, {
headers: {
'User-Agent': `${userAgent} ${projectName}`
}
});
responseBody = await response.text();
} catch (err) {
errorLogs(`[getConfigContent][fetch error] ${err.message}`);
}
}
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'));
}
function splitNodeData(uniqueIpTxt, noTLS, host, uuid, userAgent, protType, nat64, hostRemark) {
log(`splitNodeData----> \n host: ${host} \n uuid: ${uuid} \n protType: ${protType} \n hostRemark: ${hostRemark}`);
const regionMap = {
'SG': '🇸🇬 SG',
'HK': '🇭🇰 HK',
'KR': '🇰🇷 KR',
'JP': '🇯🇵 JP',
'GB': '🇬🇧 GB',
'US': '🇺🇸 US',
'TW': '🇼🇸 TW',
'CF': '📶 CF'
};
function isLikelyHost(str) {
if (!str) return false;
str = str.trim();
if (/\s|\/|\\|\(|\)|[\u4e00-\u9fff]/.test(str)) return false;
if (/^(\d{1,3}\.){3}\d{1,3}(:\d+)?$/.test(str)) return true;
if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(:\d+)?$/.test(str)) return true;
return false;
}
const responseBody = uniqueIpTxt.map(raw => {
const ipTxt = String(raw).trim();
log(`splitNodeData---> ipTxt: ${ipTxt}`);
let proxyip = "";
let port = "443";
let remarks = "";
let address = "";
const lastAt = ipTxt.lastIndexOf('@');
let main = ipTxt;
if (lastAt !== -1) {
const candidate = ipTxt.slice(lastAt + 1).trim();
if (isLikelyHost(candidate)) {
proxyip = candidate;
main = ipTxt.slice(0, lastAt);
log(`splitNodeData--detected-proxy--> proxyip: ${proxyip} main: ${main}`);
} else {
log(`splitNodeData--at-in-remark--> ignored candidate after @: ${candidate}`);
}
}
const mainMatch = main.match(/^(\[.*\]|[^:#\s]+)(?::(\d+))?(?:#(.*))?$/);
if (mainMatch) {
address = mainMatch[1];
port = mainMatch[2] || port;
remarks = mainMatch[3] || "";
} else {
address = main;
remarks = "";
}
if (hostRemark) {
remarks = hostRemark;
} else {
remarks = (remarks && remarks.trim()) ? remarks.trim() : address;
}
const rmKey = String(remarks).trim().toUpperCase();
if (regionMap[rmKey]) {
remarks = regionMap[rmKey];
}
proxyip = proxyip || paddr;
log(`splitNodeData--final--> \n address: ${address} \n port: ${port} \n remarks: ${remarks} \n proxyip: ${proxyip}`);
if (noTLS !== 'true' && portSet_http.has(parseInt(port))) {
return null;
}
const [v2, clash] = getConfigLink(uuid, host, address, port, remarks, proxyip, protType, nat64);
return v2;
}).filter(Boolean).join('\n');
return responseBody;
}
async function getIpUrlTxtAndCsv(noTLS, urlTxts, urlCsvs, num) {
if (noTLS === 'true') {
return {
txt: await getIpUrlTxt(urlTxts, num),
csv: await getIpUrlCsv(urlCsvs, 'FALSE')
};
}
return {
txt: await getIpUrlTxt(urlTxts, num),
csv: await getIpUrlCsv(urlCsvs, 'TRUE')
};
}
async function getIpUrlTxt(urlTxts, num) {
if (!urlTxts || urlTxts.length === 0) {
return [];
}
let ipTxt = "";
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort();
}, 2000);
try {
const urlMappings = urlTxts.map(entry => {
const [url, suffix] = entry.split('@');
return { url, suffix: suffix ? `@${suffix}` : '' };
});
const responses = await Promise.allSettled(
urlMappings.map(({ url }) =>
fetch(url, {
method: 'GET',
headers: {
'Accept': 'text/html,application/xhtml+xml,application/xml;',
'User-Agent': projectName
},
signal: controller.signal
}).then(response => response.ok ? response.text() : Promise.reject())
)
);
for (let i = 0; i < responses.length; i++) {
const response = responses[i];
if (response.status === 'fulfilled') {
const suffix = urlMappings[i].suffix;
const content = response.value
.split('\n')
.filter(line => line.trim() !== "")
.map(line => line + suffix)
.join('\n');
ipTxt += content + '\n';
}
}
} catch (error) {
errorLogs(error);
} finally {
clearTimeout(timeout);
}
log(`getIpUrlTxt-->ipTxt: ${ipTxt} \n `);
let newIpTxt = await addIpText(ipTxt);
const hasAcCom = urlTxts.includes(defaultIpUrlTxt);
if (hasAcCom && typeof randomNum === 'number' && randomNum !== 0) {
newIpTxt = getRandomItems(newIpTxt, num);
}
return newIpTxt;
}
async function getIpUrlTxtToArry(urlTxts) {
if (!urlTxts || urlTxts.length === 0) {
return [];
}
let ipTxt = "";
const controller = new AbortController();
const timeout = setTimeout(() => {
controller.abort();
}, 2000);
try {
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
}).then(response => response.ok ? response.text() : Promise.reject())));
for (const response of responses) {
if (response.status === 'fulfilled') {
const content = await response.value;
ipTxt += content + '\n';
}
}
} catch (error) {
errorLogs(error);
} finally {
clearTimeout(timeout);
}
const newIpTxt = await addIpText(ipTxt);
log(`urlTxts: ${urlTxts} \n ipTxt: ${ipTxt} \n newIpTxt: ${newIpTxt} `);
return newIpTxt;