Repository navigation
Expand file tree
/
Copy pathscript.js
More file actions
2115 lines (1949 loc) · 90.8 KB
/
Copy pathscript.js
File metadata and controls
2115 lines (1949 loc) · 90.8 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
// ===================================================================
// Proxy Builder — script.js
// Enhances proxy URLs (fragment & fingerprint) and chains two proxy
// URLs into Xray & Sing-box configs
// ===================================================================
(function () {
'use strict';
// ===== DOM Elements =====
const config1Input = document.getElementById('config1-input');
const config2Input = document.getElementById('config2-input');
const protocol1Tag = document.getElementById('protocol1-tag');
const protocol2Tag = document.getElementById('protocol2-tag');
const parsed1 = document.getElementById('parsed1');
const parsed2 = document.getElementById('parsed2');
const clear1 = document.getElementById('clear1');
const clear2 = document.getElementById('clear2');
const btnGenerate = document.getElementById('btn-generate');
const generateHint = document.getElementById('generate-hint');
const outputSection = document.getElementById('output-section');
const flowProxyLabel = document.getElementById('flow-proxy-label');
const flowChainLabel = document.getElementById('flow-chain-label');
const config1Card = document.getElementById('config1-card');
const config2Card = document.getElementById('config2-card');
// SSH elements
const sshToggle1 = document.getElementById('ssh-toggle1');
const sshToggle2 = document.getElementById('ssh-toggle2');
const sshForm1 = document.getElementById('ssh-form1');
const sshForm2 = document.getElementById('ssh-form2');
const urlInputGroup1 = document.getElementById('url-input-group1');
const urlInputGroup2 = document.getElementById('url-input-group2');
// Xray output elements
const outputJsonXray = document.getElementById('output-json-xray');
const outputRemarkXray = document.getElementById('output-remark-xray');
const btnCopyXray = document.getElementById('btn-copy-xray');
const btnDownloadXray = document.getElementById('btn-download-xray');
// Sing-box output elements
const outputJsonSingbox = document.getElementById('output-json-singbox');
const outputRemarkSingbox = document.getElementById('output-remark-singbox');
const btnCopySingbox = document.getElementById('btn-copy-singbox');
const btnDownloadSingbox = document.getElementById('btn-download-singbox');
// Nekoray output elements
const outputJsonSingboxClient = document.getElementById('output-json-singbox-client');
const outputRemarkSingboxClient = document.getElementById('output-remark-singbox-client');
const btnCopySingboxClient = document.getElementById('btn-copy-singbox-client');
const btnDownloadSingboxClient = document.getElementById('btn-download-singbox-client');
// Nekobox output elements
const outputJsonNekobox = document.getElementById('output-json-nekobox');
const outputRemarkNekobox = document.getElementById('output-remark-nekobox');
const btnCopyNekobox = document.getElementById('btn-copy-nekobox');
const btnDownloadNekobox = document.getElementById('btn-download-nekobox');
// Tab elements
const tabXray = document.getElementById('tab-xray');
const tabSingbox = document.getElementById('tab-singbox');
const panelXray = document.getElementById('panel-xray');
const panelSingbox = document.getElementById('panel-singbox');
// Main tab elements
const mainTabs = document.querySelectorAll('.main-tab');
const viewChain = document.getElementById('view-chain');
const viewEnhancer = document.getElementById('view-enhancer');
const viewEch = document.getElementById('view-ech');
// Enhancer elements
const enhancerInput = document.getElementById('enhancer-input');
const enhancerClear = document.getElementById('enhancer-clear');
const enhancerParsed = document.getElementById('enhancer-parsed');
const enhancerProtocolTag = document.getElementById('enhancer-protocol-tag');
const enhancerFp = document.getElementById('enhancer-fp');
const enhancerCs = document.getElementById('enhancer-cs');
const enhancerFm = document.getElementById('enhancer-fm');
const enhancerFmPreset = document.getElementById('enhancer-fm-preset');
const enhancerServer = document.getElementById('enhancer-server');
const btnEnhance = document.getElementById('btn-enhance');
const enhanceHint = document.getElementById('enhance-hint');
const enhancerCard = document.getElementById('enhancer-card');
// ECH tab elements (own card — not shared with other tabs)
const echInput = document.getElementById('ech-input');
const echClear = document.getElementById('ech-clear');
const echParsed = document.getElementById('ech-parsed');
const echProtocolTag = document.getElementById('ech-protocol-tag');
const echServer = document.getElementById('ech-server');
const echFp = document.getElementById('ech-fp');
const echPreset = document.getElementById('ech-preset');
const echText = document.getElementById('ech-text');
const btnEchEnhance = document.getElementById('btn-ech-enhance');
const echHint = document.getElementById('ech-hint');
const echOutputSection = document.getElementById('ech-output-section');
const echOutputUrl = document.getElementById('ech-output-url');
const echOutputRemark = document.getElementById('ech-output-remark');
const btnCopyEch = document.getElementById('btn-copy-ech');
const echCard = document.getElementById('ech-card');
// ECH subscription input (paste contents or fetch a link — shared output)
const echSubCard = document.getElementById('ech-sub-card');
const echSubInput = document.getElementById('ech-sub-input');
const echSubClear = document.getElementById('ech-sub-clear');
const echSubParsed = document.getElementById('ech-sub-parsed');
const btnEchSub = document.getElementById('btn-ech-sub');
const echSubHint = document.getElementById('ech-sub-hint');
const btnEchOpenSub = document.getElementById('btn-ech-open-sub');
const btnDownloadEch = document.getElementById('btn-download-ech');
const btnDownloadEchB64 = document.getElementById('btn-download-ech-b64');
// ECH per-tab state lives in its createEnhanceTab instance (026); globals removed.
let parsedConfig1 = null;
let parsedConfig2 = null;
let sshMode1 = false;
let sshMode2 = false;
// lastAutoServer / lastAutoEchServer removed (026): per-instance closures
// in the tab controllers.
// ===== SSH Parser (reads from form fields) =====
function parseSSH(configNum) {
const server = document.getElementById(`ssh-server${configNum}`).value.trim();
const port = parseInt(document.getElementById(`ssh-port${configNum}`).value) || 22;
const user = document.getElementById(`ssh-user${configNum}`).value.trim() || 'root';
const password = document.getElementById(`ssh-pass${configNum}`).value;
if (!server) return null;
if (!password) return { error: 'Password is required for SSH' };
return {
protocol: 'ssh',
server: server,
port: port,
user: user,
password: password,
remark: `SSH ${server}:${port}`
};
}
// ===== URL Enhancer (Fragment + Fingerprint) =====
function enhanceURL(raw, opts) {
return enhanceUrlCore(raw, {
server: enhancerServer.value,
fp: enhancerFp.value,
cs: enhancerCs.value,
fm: enhancerFm.value,
ignoreServer: !!(opts && opts.ignoreServer)
});
}
// Fragment URL-input/enhance originals removed (026): the fragTab
// createEnhanceTab instance below owns this tab now (IDs, filenames,
// option controls kept).
// ===== ECH Enhancer (own tab — fp + ech only) =====
function enhanceEchURL(raw, opts) {
return enhanceEchUrlCore(raw, {
server: echServer.value,
fp: echFp.value,
ech: echText.value,
ignoreServer: !!(opts && opts.ignoreServer)
});
}
// ECH URL-input/enhance originals removed (026): the echTab createEnhanceTab
// instance below owns this tab now (IDs, filenames, option controls kept).
// ===== ECH subscription input (link fetch or pasted contents, shared output) =====
// setEchSubError removed (026): closure setTabSubError in the ECH tab controller.
// Manual-fetch fallback for providers that block browser fetches (no CORS
// headers): an "Open link" button + 3 steps, mirroring the Subscription tab.
// Built with DOM APIs only (no innerHTML).
// ECH CORS guide helper removed (026): closure in the tab controller.
// syncEchOpenButton removed (026): closure syncTabOpenButton in the ECH tab controller.
// ECH subscription originals removed (026): owned by the echTab instance.
// ===== Xray Outbound Builders =====
// ===== Full Config Generator =====
function generateFullConfig(config1, config2) {
const dnsServer = document.getElementById('dns-server').value;
const socksPort = parseInt(document.getElementById('socks-port').value) || 10808;
const logLevel = document.getElementById('log-level').value;
const proxyOutbound = buildProxyOutbound(config1);
const chainOutbound = buildChainOutbound(config2);
const remark = `🔗 ${config1.protocol.toUpperCase()} → ${config2.protocol.toUpperCase()} | ${config2.server}:${config2.port}`;
const fullConfig = {
remarks: remark,
log: {
loglevel: logLevel
},
dns: {
servers: [
{
address: dnsServer,
tag: 'remote-dns'
}
],
queryStrategy: 'UseIP',
tag: 'dns'
},
inbounds: [
{
listen: '127.0.0.1',
port: socksPort,
protocol: 'socks',
settings: {
auth: 'noauth',
udp: true
},
tag: 'mixed-in',
sniffing: {
enabled: true,
destOverride: ['http', 'tls']
}
}
],
outbounds: [
chainOutbound,
proxyOutbound,
{
protocol: 'dns',
tag: 'dns-out'
},
{
protocol: 'freedom',
tag: 'direct',
settings: {
domainStrategy: 'UseIP'
}
},
{
protocol: 'blackhole',
tag: 'block'
}
],
routing: {
domainStrategy: 'IPIfNonMatch',
rules: [
{
inboundTag: ['remote-dns'],
outboundTag: 'proxy',
type: 'field'
},
{
network: 'tcp',
outboundTag: 'chain',
type: 'field'
},
{
protocol: ['dns'],
outboundTag: 'dns-out',
type: 'field'
}
]
}
};
return { config: fullConfig, remark };
}
// ===== Sing-box Config Generator =====
function generateSingboxConfig(config1, config2) {
const dnsServer = document.getElementById('dns-server').value;
const socksPort = parseInt(document.getElementById('socks-port').value) || 10808;
const logLevel = document.getElementById('log-level').value;
const remark = `🔗 ${config1.protocol.toUpperCase()} → ${config2.protocol.toUpperCase()} | ${config2.server}:${config2.port}`;
// Build proxy outbound (config1)
const proxyOutbound = buildSingboxOutbound(config1, 'proxy', null);
// Build chain outbound (config2) — detours through proxy
const chainOutbound = buildSingboxOutbound(config2, 'chain', 'proxy');
// Map log level for Sing-box
const sbLogLevel = logLevel === 'none' ? undefined : (logLevel === 'warning' ? 'warn' : logLevel);
// Parse DNS host from URL
let dnsHost = '8.8.8.8';
let dnsType = 'https';
try {
const dnsUrl = new URL(dnsServer);
dnsHost = dnsUrl.hostname;
dnsType = dnsUrl.protocol.replace(':', '');
} catch { }
// Collect domains to bypass DNS (to prevent loopback)
const bypassDomains = new Set();
[config1, config2].forEach(cfg => {
if (cfg.server && !cfg.server.match(/^(?:\d{1,3}\.){3}\d{1,3}$/)) bypassDomains.add(cfg.server);
if (cfg.sni) bypassDomains.add(cfg.sni);
if (cfg.host) {
cfg.host.split(',').forEach(h => bypassDomains.add(h.trim()));
}
if (cfg.ech) {
const echDomain = getEchQueryServer(cfg.ech);
if (echDomain) bypassDomains.add(echDomain);
}
});
const singboxConfig = {
log: {
disabled: logLevel === 'none',
level: sbLogLevel,
timestamp: true
},
dns: {
servers: [
{
type: dnsType,
server: dnsHost,
detour: 'chain',
tag: 'dns-remote'
},
{
type: 'local',
tag: 'dns-direct'
}
],
rules: [
{
clash_mode: 'Direct',
server: 'dns-direct'
},
{
clash_mode: 'Global',
server: 'dns-remote'
},
{
domain: Array.from(bypassDomains),
server: 'dns-direct'
}
],
strategy: 'ipv4_only',
independent_cache: true
},
inbounds: [
{
type: 'tun',
tag: 'tun-in',
address: ['172.19.0.1/28'],
mtu: 9000,
auto_route: true,
strict_route: true,
stack: 'mixed'
},
{
type: 'mixed',
tag: 'mixed-in',
listen: '127.0.0.1',
listen_port: socksPort
}
],
outbounds: [
chainOutbound,
proxyOutbound,
{
type: 'direct',
tag: 'direct'
}
],
route: {
rules: [
{
ip_cidr: '172.19.0.2',
action: 'hijack-dns'
},
{
domain: Array.from(bypassDomains),
outbound: 'direct'
},
{
clash_mode: 'Direct',
outbound: 'direct'
},
{
action: 'sniff'
},
{
protocol: 'dns',
action: 'hijack-dns'
},
{
ip_is_private: true,
outbound: 'direct'
},
{
network: 'udp',
action: 'reject'
}
],
auto_detect_interface: true,
default_domain_resolver: {
server: 'dns-direct',
strategy: 'ipv4_only',
rewrite_ttl: 60
},
final: 'chain'
},
ntp: {
enabled: true,
server: 'time.cloudflare.com',
server_port: 123,
domain_resolver: 'dns-direct',
interval: '30m',
write_to_system: false
},
experimental: {
cache_file: {
enabled: true,
store_fakeip: true
},
clash_api: {
external_controller: '127.0.0.1:9090',
external_ui: 'ui',
default_mode: 'Rule',
external_ui_download_url: 'https://github.com/MetaCubeX/metacubexd/archive/refs/heads/gh-pages.zip',
external_ui_download_detour: 'direct'
}
}
};
return { config: singboxConfig, remark };
}
// ===== Nekoray Config Generator (Sing-box compatible) =====
function generateSingboxClientConfig(config1, config2) {
const dnsServer = document.getElementById('dns-server').value;
const socksPort = parseInt(document.getElementById('socks-port').value) || 10808;
const logLevel = document.getElementById('log-level').value;
const remark = `🔗 NEKORAY: ${config1.protocol.toUpperCase()} → ${config2.protocol.toUpperCase()} | ${config2.server}:${config2.port}`;
// Build hop-1 outbound (config1)
const hop1Outbound = buildSingboxOutbound(config1, 'hop-1', null);
// Force xudp for vless if not set
if (config1.protocol === 'vless' && !hop1Outbound.packet_encoding) {
hop1Outbound.packet_encoding = 'xudp';
}
// Build proxy outbound (config2) — detours through hop-1
const proxyOutbound = buildSingboxOutbound(config2, 'proxy', 'hop-1');
if (config2.protocol === 'vless' && !proxyOutbound.packet_encoding) {
proxyOutbound.packet_encoding = 'xudp';
}
// Map log level for Sing-box
const sbLogLevel = logLevel === 'none' ? 'info' : (logLevel === 'warning' ? 'warn' : logLevel);
const singboxClientConfig = {
log: {
level: sbLogLevel
},
dns: {
servers: [
{
address: dnsServer,
detour: 'proxy',
tag: 'dns-remote'
},
{
address: '1.1.1.1',
detour: 'direct',
tag: 'dns-direct'
}
],
rules: [
{
outbound: 'any',
server: 'dns-direct'
}
]
},
inbounds: [
{
listen: '127.0.0.1',
listen_port: socksPort,
sniff: true,
tag: 'mixed-in',
type: 'mixed'
}
],
outbounds: [
hop1Outbound,
proxyOutbound,
{
tag: 'direct',
type: 'direct'
},
{
tag: 'dns-out',
type: 'dns'
}
],
route: {
auto_detect_interface: true,
final: 'proxy',
rules: [
{
outbound: 'dns-out',
protocol: 'dns'
}
]
}
};
return { config: singboxClientConfig, remark };
}
// ===== Nekobox Config Generator (Android Optimized) =====
function generateNekoboxConfig(config1, config2) {
const dnsServer = document.getElementById('dns-server').value;
const logLevel = document.getElementById('log-level').value;
const remark = `🔗 NEKOBOX: ${config1.protocol.toUpperCase()} → ${config2.protocol.toUpperCase()} | ${config2.server}:${config2.port}`;
// Build hop-1 outbound (config1)
const hop1Outbound = buildSingboxOutbound(config1, 'hop-1', null);
if (config1.protocol === 'vless' && !hop1Outbound.packet_encoding) {
hop1Outbound.packet_encoding = 'xudp';
}
// Build proxy outbound (config2) — detours through hop-1
const proxyOutbound = buildSingboxOutbound(config2, 'proxy', 'hop-1');
if (config2.protocol === 'vless' && !proxyOutbound.packet_encoding) {
proxyOutbound.packet_encoding = 'xudp';
}
// Map log level for Sing-box
const sbLogLevel = logLevel === 'none' ? 'info' : (logLevel === 'warning' ? 'warn' : logLevel);
const nekoboxConfig = {
log: {
level: sbLogLevel
},
dns: {
servers: [
{
tag: 'dns-remote',
address: dnsServer,
detour: 'proxy'
},
{
tag: 'dns-direct',
address: '1.1.1.1',
detour: 'direct'
}
],
rules: [
{
outbound: 'any',
server: 'dns-direct'
}
]
},
inbounds: [
{
type: 'tun',
tag: 'tun-in',
interface_name: 'tun0',
inet4_address: '172.19.0.1/30',
auto_route: true,
strict_route: true,
stack: 'system',
sniff: true,
sniff_override_destination: false
}
],
outbounds: [
hop1Outbound,
proxyOutbound,
{
type: 'direct',
tag: 'direct'
},
{
type: 'dns',
tag: 'dns-out'
}
],
route: {
auto_detect_interface: true,
final: 'proxy',
rules: [
{
protocol: 'dns',
outbound: 'dns-out'
}
]
}
};
return { config: nekoboxConfig, remark };
}
// ===== UI Render Helpers =====
function renderParsedInfo(params, container) {
if (!params || params.error) {
container.innerHTML = params
? `<div class="error-msg">⚠️ ${escapeHtml(String(params.error))}</div>`
: '';
return;
}
if (Array.isArray(params)) {
if (params.length === 0) {
container.innerHTML = '';
return;
}
if (params.length === 1) {
renderParsedInfo(params[0], container);
return;
}
const rows = [];
rows.push(['Loaded Configs', `Found ${params.length} URLs`]);
params.forEach((cfg, i) => {
const label = `#${i + 1} ${cfg.protocol ? cfg.protocol.toUpperCase() : ''}`;
const val = `${cfg.server || ''}:${cfg.port || ''}${cfg.remark ? ' (' + truncateStr(cfg.remark, 30) + ')' : ''}`;
rows.push([label, val]);
});
container.innerHTML = rows.map(([label, value]) =>
`<div class="info-row">
<span class="info-label">${escapeHtml(String(label))}</span>
<span class="info-value">${escapeHtml(String(value))}</span>
</div>`
).join('');
return;
}
const rows = [];
rows.push(['Protocol', params.protocol.toUpperCase()]);
rows.push(['Server', params.server]);
rows.push(['Port', params.port]);
if (params.uuid) rows.push(['UUID', params.uuid]);
const passVal = params.password || params.pass;
if (passVal) rows.push(['Password', maskString(passVal)]);
if (params.method) rows.push(['Method', params.method]);
if (params.user) rows.push(['User', params.user]);
if (params.type && params.type !== 'tcp') rows.push(['Transport', params.type]);
if (params.security && params.security !== 'none') rows.push(['Security', params.security]);
if (params.sni) rows.push(['SNI', params.sni]);
if (params.host) rows.push(['Host', params.host]);
if (params.path) rows.push(['Path', truncateStr(params.path, 50)]);
if (params.ech) rows.push(['ECH', '✅ Enabled']);
if (params.allowInsecure) rows.push(['Insecure', '⚠️ Allowed']);
if (params.remark) rows.push(['Remark', params.remark]);
container.innerHTML = rows.map(([label, value]) =>
`<div class="info-row">
<span class="info-label">${escapeHtml(String(label))}</span>
<span class="info-value">${escapeHtml(String(value))}</span>
</div>`
).join('');
}
function escapeHtml(str) {
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
function getProtocolColor(protocol) {
const colors = {
vless: '#7c5cff',
vmess: '#5c8cff',
trojan: '#f05050',
shadowsocks: '#3cd4f0',
socks: '#4cdf86',
http: '#f0c040',
ssh: '#ff8c42'
};
return colors[protocol] || '#9090b0';
}
function updateProtocolTag(tag, protocol) {
if (protocol && !protocol.error) {
tag.textContent = protocol.protocol.toUpperCase();
tag.classList.add('active');
tag.style.color = getProtocolColor(protocol.protocol);
tag.style.borderColor = getProtocolColor(protocol.protocol) + '4d';
tag.style.background = getProtocolColor(protocol.protocol) + '1a';
} else {
tag.textContent = '—';
tag.classList.remove('active');
tag.style.color = '';
tag.style.borderColor = '';
tag.style.background = '';
}
}
// ===== JSON Syntax Highlighting =====
function highlightJSON(json) {
const str = JSON.stringify(json, null, 2);
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"([^"]+)"(?=\s*:)/g, '<span class="json-key">"$1"</span>')
.replace(/:\s*"([^"]*)"/g, ': <span class="json-string">"$1"</span>')
.replace(/:\s*(\d+\.?\d*)/g, ': <span class="json-number">$1</span>')
.replace(/:\s*(true|false)/g, ': <span class="json-boolean">$1</span>')
.replace(/:\s*(null)/g, ': <span class="json-null">$1</span>')
.replace(/([{}[\]])/g, '<span class="json-brace">$1</span>');
}
// ===== Event Handlers =====
function onInputChange(inputEl, parsedContainer, protocolTag, card, isConfig1) {
let parsed;
if (isConfig1 && sshMode1) {
parsed = parseSSH(1);
} else if (!isConfig1 && sshMode2) {
parsed = parseSSH(2);
} else {
const val = inputEl.value.trim();
parsed = val ? parseProxyURL(val) : null;
}
let singleConfig = null;
if (Array.isArray(parsed)) {
singleConfig = parsed[0];
} else if (parsed && !parsed.error) {
singleConfig = parsed;
}
if (isConfig1) {
parsedConfig1 = singleConfig;
} else {
parsedConfig2 = singleConfig;
}
renderParsedInfo(parsed, parsedContainer);
updateProtocolTag(protocolTag, singleConfig || (parsed && !Array.isArray(parsed) ? parsed : null));
// For SSH mode, we also consider the card valid if server is filled
card.classList.remove('valid', 'invalid');
if (isConfig1 && sshMode1) {
const server = document.getElementById('ssh-server1').value.trim();
if (server && parsed) {
card.classList.add(parsed.error ? 'invalid' : 'valid');
}
} else if (!isConfig1 && sshMode2) {
const server = document.getElementById('ssh-server2').value.trim();
if (server && parsed) {
card.classList.add(parsed.error ? 'invalid' : 'valid');
}
} else {
const val = inputEl.value.trim();
if (val && (singleConfig || (parsed && !parsed.error))) {
card.classList.add('valid');
} else if (val) {
card.classList.add('invalid');
}
}
if (isConfig1 && parsedConfig1) {
flowProxyLabel.textContent = `${parsedConfig1.protocol.toUpperCase()} ${parsedConfig1.server}`;
} else if (isConfig1) {
flowProxyLabel.textContent = 'Config 1';
}
if (!isConfig1 && parsedConfig2) {
flowChainLabel.textContent = `${parsedConfig2.protocol.toUpperCase()} ${parsedConfig2.server}`;
} else if (!isConfig1) {
flowChainLabel.textContent = 'Config 2';
}
updateGenerateButton();
}
function updateGenerateButton() {
const enabled = parsedConfig1 && parsedConfig2;
btnGenerate.disabled = !enabled;
generateHint.textContent = enabled
? 'Ready to generate!'
: (!parsedConfig1 && !parsedConfig2)
? 'Paste both configs above to enable'
: !parsedConfig1
? 'Config 1 is missing or invalid'
: 'Config 2 is missing or invalid';
generateHint.style.color = enabled ? '#4cdf86' : '';
}
function onGenerate() {
// Flush any debounced chain-input parse still waiting on its 150 ms
// timer, so a Generate click within the delay consumes the visible
// field contents, never stale parsedConfig1/2 (plan 027).
if (config1InputTimer) {
clearTimeout(config1InputTimer);
config1InputTimer = null;
onInputChange(config1Input, parsed1, protocol1Tag, config1Card, true);
}
if (config2InputTimer) {
clearTimeout(config2InputTimer);
config2InputTimer = null;
onInputChange(config2Input, parsed2, protocol2Tag, config2Card, false);
}
if (!parsedConfig1 || !parsedConfig2) return;
const hasSSH = parsedConfig1.protocol === 'ssh' || parsedConfig2.protocol === 'ssh';
// Handle tabs visibility for SSH
if (hasSSH) {
tabXray.classList.add('disabled');
tabXray.title = 'SSH is not supported by Xray';
btnCopyXray.disabled = true;
btnDownloadXray.disabled = true;
switchTab('singbox');
} else {
tabXray.classList.remove('disabled');
tabXray.title = '';
btnCopyXray.disabled = false;
btnDownloadXray.disabled = false;
}
// Generate Xray config (skip if SSH is involved)
if (!hasSSH) {
const xrayResult = generateFullConfig(parsedConfig1, parsedConfig2);
if (!xrayResult) {
outputSection.style.display = 'none';
return;
}
outputRemarkXray.textContent = xrayResult.remark;
outputJsonXray.innerHTML = highlightJSON(xrayResult.config);
} else {
outputRemarkXray.textContent = '';
outputJsonXray.innerHTML = '<span style="color:#ff8c42">⚠️ SSH protocol is only supported by Sing-box. Xray config is not available.</span>';
}
// Generate Sing-box config
const singboxResult = generateSingboxConfig(parsedConfig1, parsedConfig2);
if (singboxResult) {
outputRemarkSingbox.textContent = singboxResult.remark;
outputJsonSingbox.innerHTML = highlightJSON(singboxResult.config);
}
// Generate Nekoray config
const singboxClientResult = generateSingboxClientConfig(parsedConfig1, parsedConfig2);
if (singboxClientResult) {
outputRemarkSingboxClient.textContent = singboxClientResult.remark;
outputJsonSingboxClient.innerHTML = highlightJSON(singboxClientResult.config);
}
// Generate Nekobox config
const nekoboxResult = generateNekoboxConfig(parsedConfig1, parsedConfig2);
if (nekoboxResult) {
outputRemarkNekobox.textContent = nekoboxResult.remark;
outputJsonNekobox.innerHTML = highlightJSON(nekoboxResult.config);
}
outputSection.style.display = 'block';
outputSection.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
function doCopy(btn, configGenerator) {
// Flush any debounced chain-input parse still waiting on its 150 ms
// timer, so a Generate click within the delay consumes the visible
// field contents, never stale parsedConfig1/2 (plan 027 + copy/download (plan 032)).
if (config1InputTimer) {
clearTimeout(config1InputTimer);
config1InputTimer = null;
onInputChange(config1Input, parsed1, protocol1Tag, config1Card, true);
}
if (config2InputTimer) {
clearTimeout(config2InputTimer);
config2InputTimer = null;
onInputChange(config2Input, parsed2, protocol2Tag, config2Card, false);
}
if (!parsedConfig1 || !parsedConfig2) return;
// Defense in depth: block Xray output for SSH configs even if the
// buttons are enabled. NOTE: the function-identity check breaks if a
// later plan wraps generators — prefer an explicit isXray boolean
// parameter then. Safe for now: plan 016 passes values, not wrappers.
if (configGenerator === generateFullConfig && (parsedConfig1?.protocol === 'ssh' || parsedConfig2?.protocol === 'ssh')) return;
const result = configGenerator(parsedConfig1, parsedConfig2);
if (!result) return;
const text = JSON.stringify(result.config, null, 2);
copyTextWithFeedback(btn, text, generateHint);
}
function doDownload(configGenerator, prefix) {
// Flush any debounced chain-input parse still waiting on its 150 ms
// timer, so a Generate click within the delay consumes the visible
// field contents, never stale parsedConfig1/2 (plan 027 + copy/download (plan 032)).
if (config1InputTimer) {
clearTimeout(config1InputTimer);
config1InputTimer = null;
onInputChange(config1Input, parsed1, protocol1Tag, config1Card, true);
}
if (config2InputTimer) {
clearTimeout(config2InputTimer);
config2InputTimer = null;
onInputChange(config2Input, parsed2, protocol2Tag, config2Card, false);
}
if (!parsedConfig1 || !parsedConfig2) return;
// Defense in depth: block Xray output for SSH configs even if the
// buttons are enabled. NOTE: the function-identity check breaks if a
// later plan wraps generators — prefer an explicit isXray boolean
// parameter then. Safe for now: plan 016 passes values, not wrappers.
if (configGenerator === generateFullConfig && (parsedConfig1?.protocol === 'ssh' || parsedConfig2?.protocol === 'ssh')) return;
const result = configGenerator(parsedConfig1, parsedConfig2);
if (!result) return;
const text = JSON.stringify(result.config, null, 2);
downloadText(`${prefix}-${parsedConfig1.protocol}-${parsedConfig2.protocol}-${parsedConfig2.server}.json`, text, 'application/json');
}
// ===== Subscription Import =====
const subUrl = document.getElementById('sub-url');
const subClear = document.getElementById('sub-clear');
const subParsed = document.getElementById('sub-parsed');
const subProtocolTag = document.getElementById('sub-protocol-tag');
const subCard = document.getElementById('sub-card');
const btnSub = document.getElementById('btn-sub');
const btnOpenSub = document.getElementById('btn-open-sub');
const subHint = document.getElementById('sub-hint');
const subOutputSection = document.getElementById('sub-output-section');
const subOutputUrl = document.getElementById('sub-output-url');
const subOutputRemark = document.getElementById('sub-output-remark');
const btnCopySub = document.getElementById('btn-copy-sub');
const btnDownloadSub = document.getElementById('btn-download-sub');
const btnDownloadSubB64 = document.getElementById('btn-download-sub-b64');
// Bodies can be several hundred KB and arrive slowly, so we abort on
// silence rather than after a fixed total time.
// SUB_IDLE_MS / SUB_TOTAL_MS live in pure.js (shared with subErrorText).
const SUB_MAX_FILE_BYTES = 2 * 1024 * 1024;
// SUB_TOO_LARGE_MSG lives in pure.js (shared with subErrorText).
// Fragment per-tab state lives in its createEnhanceTab instance (026); globals removed.
// extractSubConfigs() lives in pure.js (shared global scope).
// Streams the response so a large body can arrive over a slow link without
// hitting a fixed timeout; the connection is aborted after SUB_IDLE_MS of
// silence, with SUB_TOTAL_MS as a backstop so a trickle that never goes
// silent for a full 30s still ends. onProgress(receivedBytes, totalBytes)
// drives the status line.
async function fetchTextWithProgress(url, onProgress) {
const ctrl = new AbortController();
const abortIdle = () => ctrl.abort('idle-timeout');
const abortTotal = () => ctrl.abort('total-timeout');
let timer = setTimeout(abortIdle, SUB_IDLE_MS);
const totalTimer = setTimeout(abortTotal, SUB_TOTAL_MS);
const kick = () => {
clearTimeout(timer);
timer = setTimeout(abortIdle, SUB_IDLE_MS);
};
try {
const res = await fetch(url, { signal: ctrl.signal, redirect: 'follow' });
if (!res.ok) throw new Error('HTTP ' + res.status);
const total = parseInt(res.headers.get('content-length') || '0', 10);
// No streaming support — fall back to buffering the whole body.
// Without progress events a slow-but-active transfer cannot be told
// apart from a stalled one, so keep resetting the idle timer and
// rely on the total-timeout backstop to end true stalls (worst case
// for a stall here is the 5-minute total timeout, not the idle one).
if (!res.body || typeof res.body.getReader !== 'function') {
// Garbage/missing header parses to NaN (or 0 via the || '0'
// fallback); NaN comparisons are always false, so throw
// pre-read ONLY on a known over-budget size — otherwise fall
// through to buffering, where the post-decode byte check
// (textBytes) enforces the cap (plan 030).
if (Number.isFinite(total) && total > SUB_MAX_FILE_BYTES) {
throw Object.assign(new Error('Subscription body exceeds 2 MiB'), { name: 'SubTooLarge' });
}
const keepAlive = setInterval(kick, Math.min(10000, SUB_IDLE_MS));
try {
const text = await res.text();
const textBytes = new TextEncoder().encode(text).length;
if (textBytes > SUB_MAX_FILE_BYTES) {
throw Object.assign(new Error('Subscription body exceeds 2 MiB'), { name: 'SubTooLarge' });
}
onProgress(textBytes, total);
return text;
} finally {
clearInterval(keepAlive);
}
}
const reader = res.body.getReader();
const parts = [];
let loaded = 0;
for (;;) {
const { done, value } = await reader.read();