-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy path_worker.js
More file actions
1168 lines (1023 loc) · 36.6 KB
/
_worker.js
File metadata and controls
1168 lines (1023 loc) · 36.6 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
import { connect } from "cloudflare:sockets";
// Variables
let serviceName = "";
let APP_DOMAIN = "";
let prxIP = "";
let cachedPrxList = [];
// Constant
const horse = "dHJvamFu";
const flash = "dm1lc3M=";
const neko = "dmxlc3M=";
const v2 = "djJyYXk=";
const PORTS = [443, 80];
const PROTOCOLS = [atob(horse), atob(flash), atob(neko), "ss"];
const SUB_PAGE_URL = "https://foolvpn.web.id/nautica";
const KV_PRX_URL = "https://raw.githubusercontent.com/FoolVPN-ID/Nautica/refs/heads/main/kvProxyList.json";
const PRX_BANK_URL = "https://raw.githubusercontent.com/FoolVPN-ID/Nautica/refs/heads/main/proxyList.txt";
const DNS_SERVER_ADDRESS = "8.8.8.8";
const DNS_SERVER_PORT = 53;
const RELAY_SERVER_UDP = {
host: "udp-relay.hobihaus.space", // Kontribusi atau cek relay publik disini: https://hub.docker.com/r/kelvinzer0/udp-relay
port: 7300,
};
const PRX_HEALTH_CHECK_API = "https://id1.foolvpn.web.id/api/v1/check";
const CONVERTER_URL = "https://api.foolvpn.web.id/convert";
const WS_READY_STATE_OPEN = 1;
const WS_READY_STATE_CLOSING = 2;
const CORS_HEADER_OPTIONS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Max-Age": "86400",
};
// Encrypted Stream Constants (Base64 Encoded)
const SALT_A1 = atob("Vk1lc3MgSGVhZGVyIEFFQUQgS2V5X0xlbmd0aA==");
const SALT_A2 = atob("Vk1lc3MgSGVhZGVyIEFFQUQgTm9uY2VfTGVuZ3Ro");
const SALT_A3 = atob("Vk1lc3MgSGVhZGVyIEFFQUQgS2V5");
const SALT_A4 = atob("Vk1lc3MgSGVhZGVyIEFFQUQgTm9uY2U=");
const SALT_B1 = atob("QUVBRCBSZXNwIEhlYWRlciBMZW4gS2V5");
const SALT_B2 = atob("QUVBRCBSZXNwIEhlYWRlciBMZW4gSVY=");
const SALT_B3 = atob("QUVBRCBSZXNwIEhlYWRlciBLZXk=");
const SALT_B4 = atob("QUVBRCBSZXNwIEhlYWRlciBJVg==");
async function getKVPrxList(kvPrxUrl = KV_PRX_URL) {
if (!kvPrxUrl) {
throw new Error("No URL Provided!");
}
const kvPrx = await fetch(kvPrxUrl);
if (kvPrx.status == 200) {
return await kvPrx.json();
} else {
return {};
}
}
async function getPrxList(prxBankUrl = PRX_BANK_URL) {
/**
* Format:
*
* <IP>,<Port>,<Country ID>,<ORG>
* Contoh:
* 1.1.1.1,443,SG,Cloudflare Inc.
*/
if (!prxBankUrl) {
throw new Error("No URL Provided!");
}
const prxBank = await fetch(prxBankUrl);
if (prxBank.status == 200) {
const text = (await prxBank.text()) || "";
const prxString = text.split("\n").filter(Boolean);
cachedPrxList = prxString
.map((entry) => {
const [prxIP, prxPort, country, org] = entry.split(",");
return {
prxIP: prxIP || "Unknown",
prxPort: prxPort || "Unknown",
country: country || "Unknown",
org: org || "Unknown Org",
};
})
.filter(Boolean);
}
return cachedPrxList;
}
async function reverseWeb(request, target, targetPath) {
const targetUrl = new URL(request.url);
const targetChunk = target.split(":");
targetUrl.hostname = targetChunk[0];
targetUrl.port = targetChunk[1]?.toString() || "443";
targetUrl.pathname = targetPath || targetUrl.pathname;
const modifiedRequest = new Request(targetUrl, request);
modifiedRequest.headers.set("X-Forwarded-Host", request.headers.get("Host"));
const response = await fetch(modifiedRequest);
const newResponse = new Response(response.body, response);
for (const [key, value] of Object.entries(CORS_HEADER_OPTIONS)) {
newResponse.headers.set(key, value);
}
newResponse.headers.set("X-Proxied-By", "Cloudflare Worker");
return newResponse;
}
export default {
async fetch(request, env, ctx) {
try {
const url = new URL(request.url);
APP_DOMAIN = url.hostname;
serviceName = APP_DOMAIN.split(".")[0];
const upgradeHeader = request.headers.get("Upgrade");
// Handle prx client
if (upgradeHeader === "websocket") {
const prxMatch = url.pathname.match(/^\/(.+[:=-]\d+)$/);
if (url.pathname.length == 3 || url.pathname.match(",")) {
// Contoh: /ID, /SG, dll
const prxKeys = url.pathname.replace("/", "").toUpperCase().split(",");
const prxKey = prxKeys[Math.floor(Math.random() * prxKeys.length)];
const kvPrx = await getKVPrxList();
prxIP = kvPrx[prxKey][Math.floor(Math.random() * kvPrx[prxKey].length)];
return await websocketHandler(request);
} else if (prxMatch) {
prxIP = prxMatch[1];
return await websocketHandler(request);
}
}
if (url.pathname.startsWith("/sub")) {
return Response.redirect(SUB_PAGE_URL + `?host=${APP_DOMAIN}`, 301);
} else if (url.pathname.startsWith("/check")) {
const target = url.searchParams.get("target").split(":");
const result = await checkPrxHealth(target[0], target[1] || "443");
return new Response(JSON.stringify(result), {
status: 200,
headers: {
...CORS_HEADER_OPTIONS,
"Content-Type": "application/json",
},
});
} else if (url.pathname.startsWith("/api/v1")) {
const apiPath = url.pathname.replace("/api/v1", "");
if (apiPath.startsWith("/sub")) {
const filterCC = url.searchParams.get("cc")?.split(",") || [];
const filterPort = url.searchParams.get("port")?.split(",") || PORTS;
const filterVPN = url.searchParams.get("vpn")?.split(",") || PROTOCOLS;
const filterLimit = parseInt(url.searchParams.get("limit")) || 10;
const filterFormat = url.searchParams.get("format") || "raw";
const fillerDomain = url.searchParams.get("domain") || APP_DOMAIN;
const prxBankUrl = url.searchParams.get("prx-list") || env.PRX_BANK_URL;
const prxList = await getPrxList(prxBankUrl)
.then((prxs) => {
// Filter CC
if (filterCC.length) {
return prxs.filter((prx) => filterCC.includes(prx.country));
}
return prxs;
})
.then((prxs) => {
// shuffle result
shuffleArray(prxs);
return prxs;
});
const uuid = crypto.randomUUID();
const result = [];
for (const prx of prxList) {
const uri = new URL(`${atob(horse)}://${fillerDomain}`);
uri.searchParams.set("encryption", "none");
uri.searchParams.set("type", "ws");
uri.searchParams.set("host", APP_DOMAIN);
for (const port of filterPort) {
for (const protocol of filterVPN) {
if (result.length >= filterLimit) break;
uri.protocol = protocol;
uri.port = port.toString();
if (protocol == "ss") {
uri.username = btoa(`none:${uuid}`);
uri.searchParams.set(
"plugin",
`${atob(v2)}-plugin${port == 80 ? "" : ";tls"};mux=0;mode=websocket;path=/${prx.prxIP}-${
prx.prxPort
};host=${APP_DOMAIN}`,
);
} else {
uri.username = uuid;
}
uri.searchParams.set("security", port == 443 ? "tls" : "none");
uri.searchParams.set("sni", port == 80 && protocol == atob(flash) ? "" : APP_DOMAIN);
uri.searchParams.set("path", `/${prx.prxIP}-${prx.prxPort}`);
uri.hash = `${result.length + 1} ${getFlagEmoji(prx.country)} ${prx.org} WS ${
port == 443 ? "TLS" : "NTLS"
} [${serviceName}]`;
result.push(uri.toString());
}
}
}
let finalResult = "";
switch (filterFormat) {
case "raw":
finalResult = result.join("\n");
break;
case atob(v2):
finalResult = btoa(result.join("\n"));
break;
case atob(neko):
case "sfa":
case "bfr":
const res = await fetch(CONVERTER_URL, {
method: "POST",
body: JSON.stringify({
url: result.join(","),
format: filterFormat,
template: "cf",
}),
});
if (res.status == 200) {
finalResult = await res.text();
} else {
return new Response(res.statusText, {
status: res.status,
headers: {
...CORS_HEADER_OPTIONS,
},
});
}
break;
}
return new Response(finalResult, {
status: 200,
headers: {
...CORS_HEADER_OPTIONS,
},
});
} else if (apiPath.startsWith("/myip")) {
return new Response(
JSON.stringify({
ip:
request.headers.get("cf-connecting-ipv6") ||
request.headers.get("cf-connecting-ip") ||
request.headers.get("x-real-ip"),
colo: request.headers.get("cf-ray")?.split("-")[1],
...request.cf,
}),
{
headers: {
...CORS_HEADER_OPTIONS,
},
},
);
}
}
const targetReversePrx = env.REVERSE_PRX_TARGET || "example.com";
return await reverseWeb(request, targetReversePrx);
} catch (err) {
return new Response(`An error occurred: ${err.toString()}`, {
status: 500,
headers: {
...CORS_HEADER_OPTIONS,
},
});
}
},
};
async function websocketHandler(request) {
const webSocketPair = new WebSocketPair();
const [client, webSocket] = Object.values(webSocketPair);
webSocket.accept();
let addressLog = "";
let portLog = "";
const log = (info, event) => {
console.log(`[${addressLog}:${portLog}] ${info}`, event || "");
};
const earlyDataHeader = request.headers.get("sec-websocket-protocol") || "";
const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log);
let remoteSocketWrapper = {
value: null,
};
let isDNS = false;
readableWebSocketStream
.pipeTo(
new WritableStream({
async write(chunk, controller) {
if (isDNS) {
return handleUDPOutbound(
DNS_SERVER_ADDRESS,
DNS_SERVER_PORT,
chunk,
webSocket,
null,
log,
RELAY_SERVER_UDP,
);
}
if (remoteSocketWrapper.value) {
const writer = remoteSocketWrapper.value.writable.getWriter();
await writer.write(chunk);
writer.releaseLock();
return;
}
const protocol = await protocolSniffer(chunk);
let protocolHeader;
if (protocol === atob(horse)) {
protocolHeader = readHorseHeader(chunk);
} else if (protocol === atob(flash)) {
protocolHeader = await readStreamHeader(chunk);
} else if (protocol === atob(neko)) {
protocolHeader = readNekoHeader(chunk);
} else if (protocol === "ss") {
protocolHeader = readSsHeader(chunk);
} else {
throw new Error("Unknown Protocol!");
}
addressLog = protocolHeader.addressRemote;
portLog = `${protocolHeader.portRemote} -> ${protocolHeader.isUDP ? "UDP" : "TCP"}`;
if (protocolHeader.hasError) {
throw new Error(protocolHeader.message);
}
// Generate stream response header if needed
let responseHeader = protocolHeader.version;
if (protocol === atob(flash) && protocolHeader.needsResponse) {
responseHeader = await generateStreamResponseHeader(
protocolHeader.responseOptions,
protocolHeader.encKey,
protocolHeader.encIv,
);
}
if (protocolHeader.isUDP) {
if (protocolHeader.portRemote === 53) {
isDNS = true;
return handleUDPOutbound(
DNS_SERVER_ADDRESS,
DNS_SERVER_PORT,
chunk,
webSocket,
responseHeader,
log,
RELAY_SERVER_UDP,
);
}
return handleUDPOutbound(
protocolHeader.addressRemote,
protocolHeader.portRemote,
chunk,
webSocket,
responseHeader,
log,
RELAY_SERVER_UDP,
);
}
handleTCPOutBound(
remoteSocketWrapper,
protocolHeader.addressRemote,
protocolHeader.portRemote,
protocolHeader.rawClientData,
webSocket,
responseHeader,
log,
);
},
close() {
log(`readableWebSocketStream is close`);
},
abort(reason) {
log(`readableWebSocketStream is abort`, JSON.stringify(reason));
},
}),
)
.catch((err) => {
log("readableWebSocketStream pipeTo error", err);
});
return new Response(null, {
status: 101,
webSocket: client,
});
}
async function protocolSniffer(buffer) {
if (buffer.byteLength >= 62) {
const horseDelimiter = new Uint8Array(buffer.slice(56, 60));
if (horseDelimiter[0] === 0x0d && horseDelimiter[1] === 0x0a) {
if (horseDelimiter[2] === 0x01 || horseDelimiter[2] === 0x03 || horseDelimiter[2] === 0x7f) {
if (horseDelimiter[3] === 0x01 || horseDelimiter[3] === 0x03 || horseDelimiter[3] === 0x04) {
return atob(horse);
}
}
}
}
// Light protocol detection (VLESS) - check UUID v4 pattern
if (buffer.byteLength >= 18) {
const version = new Uint8Array(buffer.slice(0, 1))[0];
if (version === 0) {
const protocolUuid = new Uint8Array(buffer.slice(1, 17));
// Hanya mendukung UUID v4
if (arrayBufferToHex(protocolUuid).match(/^[0-9a-f]{8}[0-9a-f]{4}4[0-9a-f]{3}[89ab][0-9a-f]{3}[0-9a-f]{12}$/i)) {
return atob(neko);
}
}
}
// VMess AEAD detection: minimum 42 bytes (authId 16 + encLen 18 + nonce 8)
// But we need to be more selective - check if it's NOT shadowsocks first
if (buffer.byteLength >= 42) {
// Shadowsocks ATYP is always 1, 3, or 4 at first byte
const firstByte = new Uint8Array(buffer.slice(0, 1))[0];
// If first byte looks like SS address type, it's probably SS
if (firstByte === 0x01 || firstByte === 0x03 || firstByte === 0x04) {
// Likely Shadowsocks, not VMess
return "ss";
}
// Otherwise, assume it's VMess AEAD
return atob(flash);
}
return "ss"; // default
}
async function generateStreamResponseHeader(responseOptions, encKey, encIv) {
try {
// Hash the key and IV from request header - NOTE: swapped compared to variable names!
// In Rust: key = SHA256(key)[..16], iv = SHA256(iv)[..16]
// Then use these for KDF base
const key = (await sha256(encKey)).slice(0, 16);
const iv = (await sha256(encIv)).slice(0, 16);
// Encrypt length (2 bytes for value 4)
const lengthKey = (await kdf(key, [SALT_B1])).slice(0, 16);
const lengthIv = (await kdf(iv, [SALT_B2])).slice(0, 12);
const lengthData = new Uint8Array(2);
lengthData[0] = 0;
lengthData[1] = 4;
const encryptedLength = await aesGcmEncrypt(lengthKey, lengthIv, lengthData, new Uint8Array(0));
// Create header payload (4 bytes)
const headerPayload = new Uint8Array([
responseOptions[0], // options[0] from request
0x00,
0x00,
0x00, // padding
]);
const payloadKey = (await kdf(key, [SALT_B3])).slice(0, 16);
const payloadIv = (await kdf(iv, [SALT_B4])).slice(0, 12);
const encryptedPayload = await aesGcmEncrypt(payloadKey, payloadIv, headerPayload, new Uint8Array(0));
// Combine length + payload
const response = new Uint8Array(encryptedLength.length + encryptedPayload.length);
response.set(encryptedLength, 0);
response.set(encryptedPayload, encryptedLength.length);
return response;
} catch (e) {
console.error("Failed to generate stream response:", e);
return new Uint8Array(0);
}
}
async function handleTCPOutBound(
remoteSocket,
addressRemote,
portRemote,
rawClientData,
webSocket,
responseHeader,
log,
) {
async function connectAndWrite(address, port) {
const tcpSocket = connect({
hostname: address,
port: port,
});
remoteSocket.value = tcpSocket;
log(`connected to ${address}:${port}`);
const writer = tcpSocket.writable.getWriter();
await writer.write(rawClientData);
writer.releaseLock();
return tcpSocket;
}
async function retry() {
const tcpSocket = await connectAndWrite(
prxIP.split(/[:=-]/)[0] || addressRemote,
prxIP.split(/[:=-]/)[1] || portRemote,
);
tcpSocket.closed
.catch((error) => {
console.log("retry tcpSocket closed error", error);
})
.finally(() => {
safeCloseWebSocket(webSocket);
});
remoteSocketToWS(tcpSocket, webSocket, responseHeader, null, log);
}
const tcpSocket = await connectAndWrite(addressRemote, portRemote);
remoteSocketToWS(tcpSocket, webSocket, responseHeader, retry, log);
}
async function handleUDPOutbound(targetAddress, targetPort, dataChunk, webSocket, responseHeader, log, relay) {
try {
let protocolHeader = responseHeader;
const tcpSocket = connect({
hostname: relay.host,
port: relay.port,
});
const header = `udp:${targetAddress}:${targetPort}`;
const headerBuffer = new TextEncoder().encode(header);
const separator = new Uint8Array([0x7c]);
const relayMessage = new Uint8Array(headerBuffer.length + separator.length + dataChunk.byteLength);
relayMessage.set(headerBuffer, 0);
relayMessage.set(separator, headerBuffer.length);
relayMessage.set(new Uint8Array(dataChunk), headerBuffer.length + separator.length);
const writer = tcpSocket.writable.getWriter();
await writer.write(relayMessage);
writer.releaseLock();
await tcpSocket.readable.pipeTo(
new WritableStream({
async write(chunk) {
if (webSocket.readyState === WS_READY_STATE_OPEN) {
if (protocolHeader) {
webSocket.send(await new Blob([protocolHeader, chunk]).arrayBuffer());
protocolHeader = null;
} else {
webSocket.send(chunk);
}
}
},
close() {
log(`UDP connection to ${targetAddress} closed`);
},
abort(reason) {
console.error(`UDP connection aborted due to ${reason}`);
},
}),
);
} catch (e) {
console.error(`Error while handling UDP outbound: ${e.message}`);
}
}
function makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) {
let readableStreamCancel = false;
const stream = new ReadableStream({
start(controller) {
webSocketServer.addEventListener("message", (event) => {
if (readableStreamCancel) {
return;
}
const message = event.data;
controller.enqueue(message);
});
webSocketServer.addEventListener("close", () => {
safeCloseWebSocket(webSocketServer);
if (readableStreamCancel) {
return;
}
controller.close();
});
webSocketServer.addEventListener("error", (err) => {
log("webSocketServer has error");
controller.error(err);
});
const { earlyData, error } = base64ToArrayBuffer(earlyDataHeader);
if (error) {
controller.error(error);
} else if (earlyData) {
controller.enqueue(earlyData);
}
},
pull(controller) {},
cancel(reason) {
if (readableStreamCancel) {
return;
}
log(`ReadableStream was canceled, due to ${reason}`);
readableStreamCancel = true;
safeCloseWebSocket(webSocketServer);
},
});
return stream;
}
// Crypto Helper Functions
async function md5(...inputs) {
const combined = new Uint8Array(inputs.reduce((acc, input) => acc + input.length, 0));
let offset = 0;
for (const input of inputs) {
combined.set(new Uint8Array(input), offset);
offset += input.length;
}
const hashBuffer = await crypto.subtle.digest("MD5", combined);
return new Uint8Array(hashBuffer);
}
async function sha256(input) {
const hashBuffer = await crypto.subtle.digest("SHA-256", input);
return new Uint8Array(hashBuffer);
}
async function kdf(key, path) {
// VMess KDF uses custom recursive HMAC
// Reference: https://github.com/v2ray/v2ray-core/blob/master/common/crypto/auth.go
// Create HMAC-SHA256
async function hmacSha256(key, data) {
const hmacKey = await crypto.subtle.importKey("raw", key, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
const signature = await crypto.subtle.sign("HMAC", hmacKey, data);
return new Uint8Array(signature);
}
// RecursiveHash implementation matching Rust code
async function recursiveHash(keyBytes, innerHashFn) {
return async (data) => {
// Prepare HMAC pads
const ipad = new Uint8Array(64);
const opad = new Uint8Array(64);
// Copy key into pads
ipad.set(keyBytes.slice(0, Math.min(64, keyBytes.length)));
opad.set(keyBytes.slice(0, Math.min(64, keyBytes.length)));
// XOR with HMAC constants
for (let i = 0; i < 64; i++) {
ipad[i] ^= 0x36;
opad[i] ^= 0x5c;
}
// Compute inner hash: H(ipad || data)
const innerData = new Uint8Array(ipad.length + data.length);
innerData.set(ipad);
innerData.set(data, ipad.length);
const innerResult = await innerHashFn(innerData);
// Compute outer hash: H(opad || innerResult)
const outerData = new Uint8Array(opad.length + innerResult.length);
outerData.set(opad);
outerData.set(innerResult, opad.length);
return await innerHashFn(outerData);
};
}
// Base SHA256 hash function
const sha256Hash = async (data) => {
return new Uint8Array(await crypto.subtle.digest("SHA-256", data));
};
// Build recursive hash chain
let currentHashFn = await recursiveHash(new TextEncoder().encode("VMess AEAD KDF"), sha256Hash);
for (const salt of path) {
const saltBytes = typeof salt === "string" ? new TextEncoder().encode(salt) : new Uint8Array(salt);
currentHashFn = await recursiveHash(saltBytes, currentHashFn);
}
// Final hash with key
return await currentHashFn(key);
}
async function aesGcmDecrypt(key, nonce, data, aad) {
const cryptoKey = await crypto.subtle.importKey("raw", key, { name: "AES-GCM" }, false, ["decrypt"]);
try {
const decrypted = await crypto.subtle.decrypt({ name: "AES-GCM", iv: nonce, additionalData: aad }, cryptoKey, data);
return new Uint8Array(decrypted);
} catch (e) {
throw new Error("AEAD decryption failed: " + e.message);
}
}
async function aesGcmEncrypt(key, nonce, data, aad) {
const cryptoKey = await crypto.subtle.importKey("raw", key, { name: "AES-GCM" }, false, ["encrypt"]);
const encrypted = await crypto.subtle.encrypt({ name: "AES-GCM", iv: nonce, additionalData: aad }, cryptoKey, data);
return new Uint8Array(encrypted);
}
// Stream Protocol Handler
async function readStreamHeader(buffer) {
try {
// For simplicity, we'll use a fixed UUID for decryption
// In production, this should be configured
const uuidString = "00000000-0000-0000-0000-000000000000";
const uuidBytes = new Uint8Array(
uuidString
.replace(/-/g, "")
.match(/.{1,2}/g)
.map((byte) => parseInt(byte, 16)),
);
// Create MD5 hash of UUID + constant
const authKey = await md5(
uuidBytes,
new TextEncoder().encode(atob("YzQ4NjE5ZmUtOGYwMi00OWUwLWI5ZTktZWRmNzYzZTE3ZTIx")),
);
// Read AEAD header structure
const authId = new Uint8Array(buffer.slice(0, 16));
const encryptedLength = new Uint8Array(buffer.slice(16, 34));
const nonce = new Uint8Array(buffer.slice(34, 42));
// Derive keys for length decryption
const lengthKey = (await kdf(authKey, [SALT_A1, authId, nonce])).slice(0, 16);
const lengthIv = (await kdf(authKey, [SALT_A2, authId, nonce])).slice(0, 12);
// Decrypt header length (AAD is authId)
const lengthBytes = await aesGcmDecrypt(lengthKey, lengthIv, encryptedLength, authId);
const headerLength = (lengthBytes[0] << 8) | lengthBytes[1];
// Read encrypted header payload (with 16 bytes GCM tag)
const encryptedHeader = new Uint8Array(buffer.slice(42, 42 + headerLength + 16));
// Derive keys for payload decryption
const payloadKey = (await kdf(authKey, [SALT_A3, authId, nonce])).slice(0, 16);
const payloadIv = (await kdf(authKey, [SALT_A4, authId, nonce])).slice(0, 12);
// Decrypt header payload (AAD is authId)
const headerPayload = await aesGcmDecrypt(payloadKey, payloadIv, encryptedHeader, authId);
// Debug logging
console.log("Header payload length:", headerPayload.length);
console.log("Header payload (hex):", arrayBufferToHex(headerPayload.buffer));
// Parse decrypted header - following exact Rust implementation order
const view = new DataView(headerPayload.buffer);
let offset = 0;
// Version (1 byte)
const version = view.getUint8(offset);
offset += 1;
console.log("[0] Version:", version, "| offset now:", offset);
if (version !== 1) {
return { hasError: true, message: `Invalid protocol version: ${version}` };
}
// IV (16 bytes)
const encIv = new Uint8Array(headerPayload.slice(offset, offset + 16));
offset += 16;
console.log("[1-16] IV read | offset now:", offset);
// Key (16 bytes)
const encKey = new Uint8Array(headerPayload.slice(offset, offset + 16));
offset += 16;
console.log("[17-32] Key read | offset now:", offset);
// Options (4 bytes total - Rust reads as array)
const options = new Uint8Array(headerPayload.slice(offset, offset + 4));
offset += 4;
console.log("[33-36] Options:", Array.from(options), "| offset now:", offset);
// Command (1 byte)
const cmd = view.getUint8(offset);
offset += 1;
console.log("[37] Command:", cmd, "| offset now:", offset);
const isUDP = cmd !== 0x01;
// Port (2 bytes, big-endian)
const portRemote = view.getUint16(offset, false);
offset += 2;
console.log("[38-39] Port:", portRemote, "| offset now:", offset);
// Address Type (1 byte)
const addressType = view.getUint8(offset);
offset += 1;
console.log("[40] Address type:", addressType, "| offset now:", offset);
let addressRemote = "";
// Parse address following Rust implementation
switch (addressType) {
case 1: // IPv4
addressRemote = `${view.getUint8(offset)}.${view.getUint8(offset + 1)}.${view.getUint8(offset + 2)}.${view.getUint8(offset + 3)}`;
offset += 4;
break;
case 2: // Domain (same as case 3 in Rust)
case 3: // Domain
const domainLength = view.getUint8(offset);
offset += 1;
addressRemote = new TextDecoder().decode(headerPayload.slice(offset, offset + domainLength));
offset += domainLength;
break;
case 4: // IPv6
const ipv6Parts = [];
for (let i = 0; i < 8; i++) {
ipv6Parts.push(view.getUint16(offset + i * 2, false).toString(16));
}
addressRemote = ipv6Parts.join(":");
offset += 16;
break;
default:
console.log("ERROR: Invalid address type:", addressType, "at offset:", offset - 1);
return { hasError: true, message: `Invalid address type: ${addressType} (hex: 0x${addressType.toString(16)})` };
}
console.log("Final parsed address:", addressRemote);
// Calculate raw data index: authId (16) + encryptedLength (18) + nonce (8) + encrypted header payload (headerLength + 16 GCM tag)
const rawDataIndex = 42 + headerLength + 16;
return {
hasError: false,
addressRemote,
addressType,
portRemote,
rawDataIndex,
rawClientData: buffer.slice(rawDataIndex),
version: new Uint8Array([options[0], 0]),
isUDP,
needsResponse: true,
responseOptions: options,
encKey: encKey,
encIv: encIv,
};
} catch (e) {
return {
hasError: true,
message: "Stream header parsing failed: " + e.message,
};
}
}
function readSsHeader(ssBuffer) {
const view = new DataView(ssBuffer);
const addressType = view.getUint8(0);
let addressLength = 0;
let addressValueIndex = 1;
let addressValue = "";
switch (addressType) {
case 1:
addressLength = 4;
addressValue = new Uint8Array(ssBuffer.slice(addressValueIndex, addressValueIndex + addressLength)).join(".");
break;
case 3:
addressLength = new Uint8Array(ssBuffer.slice(addressValueIndex, addressValueIndex + 1))[0];
addressValueIndex += 1;
addressValue = new TextDecoder().decode(ssBuffer.slice(addressValueIndex, addressValueIndex + addressLength));
break;
case 4:
addressLength = 16;
const dataView = new DataView(ssBuffer.slice(addressValueIndex, addressValueIndex + addressLength));
const ipv6 = [];
for (let i = 0; i < 8; i++) {
ipv6.push(dataView.getUint16(i * 2).toString(16));
}
addressValue = ipv6.join(":");
break;
default:
return {
hasError: true,
message: `Invalid addressType for SS: ${addressType}`,
};
}
if (!addressValue) {
return {
hasError: true,
message: `Destination address empty, address type is: ${addressType}`,
};
}
const portIndex = addressValueIndex + addressLength;
const portBuffer = ssBuffer.slice(portIndex, portIndex + 2);
const portRemote = new DataView(portBuffer).getUint16(0);
return {
hasError: false,
addressRemote: addressValue,
addressType: addressType,
portRemote: portRemote,
rawDataIndex: portIndex + 2,
rawClientData: ssBuffer.slice(portIndex + 2),
version: null,
isUDP: portRemote == 53,
};
}
function readNekoHeader(buffer) {
const version = new Uint8Array(buffer.slice(0, 1));
let isUDP = false;
const optLength = new Uint8Array(buffer.slice(17, 18))[0];
const cmd = new Uint8Array(buffer.slice(18 + optLength, 18 + optLength + 1))[0];
if (cmd === 1) {
} else if (cmd === 2) {
isUDP = true;
} else {
return {
hasError: true,
message: `command ${cmd} is not supported`,
};
}
const portIndex = 18 + optLength + 1;
const portBuffer = buffer.slice(portIndex, portIndex + 2);
const portRemote = new DataView(portBuffer).getUint16(0);
let addressIndex = portIndex + 2;
const addressBuffer = new Uint8Array(buffer.slice(addressIndex, addressIndex + 1));
const addressType = addressBuffer[0];
let addressLength = 0;
let addressValueIndex = addressIndex + 1;
let addressValue = "";
switch (addressType) {
case 1: // For IPv4
addressLength = 4;
addressValue = new Uint8Array(buffer.slice(addressValueIndex, addressValueIndex + addressLength)).join(".");
break;
case 2: // For Domain
addressLength = new Uint8Array(buffer.slice(addressValueIndex, addressValueIndex + 1))[0];
addressValueIndex += 1;
addressValue = new TextDecoder().decode(buffer.slice(addressValueIndex, addressValueIndex + addressLength));
break;
case 3: // For IPv6
addressLength = 16;
const dataView = new DataView(buffer.slice(addressValueIndex, addressValueIndex + addressLength));
const ipv6 = [];
for (let i = 0; i < 8; i++) {
ipv6.push(dataView.getUint16(i * 2).toString(16));
}
addressValue = ipv6.join(":");
break;
default:
return {
hasError: true,
message: `invild addressType is ${addressType}`,
};
}
if (!addressValue) {
return {
hasError: true,
message: `addressValue is empty, addressType is ${addressType}`,
};
}
return {
hasError: false,
addressRemote: addressValue,
addressType: addressType,
portRemote: portRemote,
rawDataIndex: addressValueIndex + addressLength,
rawClientData: buffer.slice(addressValueIndex + addressLength),
version: new Uint8Array([version[0], 0]),
isUDP: isUDP,
};