forked from 6Kmfi6HP/EDtunnel
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1458 lines (1327 loc) · 50.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-ignore
import { connect } from 'cloudflare:sockets';
// How to generate your own UUID:
// [Windows] Press "Win + R", input cmd and run: Powershell -NoExit -Command "[guid]::NewGuid()"
let userID = 'd342d11e-d424-4583-b36e-524ab1f0afa4';
const proxyIPs = ['cdn.xn--b6gac.eu.org', 'cdn-all.xn--b6gac.eu.org', 'workers.cloudflare.cyou'];
// if you want to use ipv6 or single proxyIP, please add comment at this line and remove comment at the next line
let proxyIP = proxyIPs[Math.floor(Math.random() * proxyIPs.length)];
// use single proxyip instead of random
// let proxyIP = 'cdn.xn--b6gac.eu.org';
// ipv6 proxyIP example remove comment to use
// let proxyIP = "[2a01:4f8:c2c:123f:64:5:6810:c55a]"
// Example: user:pass@host:port or host:port
let socks5Address = '';
// socks5Relay is true, will proxy all traffic to socks5Address, otherwise socks5Address only be used for cloudflare ips
let socks5Relay = false;
if (!isValidUUID(userID)) {
throw new Error('uuid is not valid');
}
let parsedSocks5Address = {};
let enableSocks = false;
export default {
/**
* @param {import("@cloudflare/workers-types").Request} request
* @param {{UUID: string, PROXYIP: string, SOCKS5: string, SOCKS5_RELAY: string}} env
* @param {import("@cloudflare/workers-types").ExecutionContext} _ctx
* @returns {Promise<Response>}
*/
async fetch(request, env, _ctx) {
try {
const { UUID, PROXYIP, SOCKS5, SOCKS5_RELAY } = env;
userID = UUID || userID;
proxyIP = PROXYIP || proxyIP;
socks5Address = SOCKS5 || socks5Address;
socks5Relay = SOCKS5_RELAY || socks5Relay;
if (socks5Address) {
try {
parsedSocks5Address = socks5AddressParser(socks5Address);
enableSocks = true;
} catch (err) {
console.log(err.toString());
enableSocks = false;
}
}
const userID_Path = userID.includes(',') ? userID.split(',')[0] : userID;
const url = new URL(request.url);
const host = request.headers.get('Host');
if (request.headers.get('Upgrade') !== 'websocket') {
switch (url.pathname) {
case '/cf':
return new Response(JSON.stringify(request.cf, null, 4), {
status: 200,
headers: { "Content-Type": "application/json;charset=utf-8" },
});
case `/${userID_Path}`:
return new Response(getConfig(userID, host), {
status: 200,
headers: { "Content-Type": "text/html; charset=utf-8" },
});
case `/sub/${userID_Path}`:
return new Response(btoa(GenSub(userID, host)), {
status: 200,
headers: { "Content-Type": "text/plain;charset=utf-8" },
});
case `/bestip/${userID_Path}`:
return fetch(`https://sub.xf.free.hr/auto?host=${host}&uuid=${userID}&path=/`, { headers: request.headers });
default:
return handleDefaultPath(url, request);
}
} else {
return await ProtocolOverWSHandler(request);
}
} catch (err) {
return new Response(err.toString());
}
},
};
async function handleDefaultPath(url, request) {
const randomHostname = hostnames[Math.floor(Math.random() * hostnames.length)];
const newHeaders = new Headers(request.headers);
newHeaders.set('cf-connecting-ip', '1.2.3.4');
newHeaders.set('x-forwarded-for', '1.2.3.4');
newHeaders.set('x-real-ip', '1.2.3.4');
newHeaders.set('referer', 'https://www.google.com/search?q=edtunnel');
const proxyUrl = 'https://' + randomHostname + url.pathname + url.search;
const modifiedRequest = new Request(proxyUrl, {
method: request.method,
headers: newHeaders,
body: request.body,
redirect: 'manual',
});
const proxyResponse = await fetch(modifiedRequest, { redirect: 'manual' });
if ([301, 302].includes(proxyResponse.status)) {
return new Response(`Redirects to ${randomHostname} are not allowed.`, {
status: 403,
statusText: 'Forbidden',
});
}
return proxyResponse;
}
/**
* Handles protocol over WebSocket requests by creating a WebSocket pair, accepting the WebSocket connection, and processing the protocol header.
* @param {import("@cloudflare/workers-types").Request} request The incoming request object.
* @returns {Promise<Response>} A Promise that resolves to a WebSocket response object.
*/
async function ProtocolOverWSHandler(request) {
/** @type {import("@cloudflare/workers-types").WebSocket[]} */
// @ts-ignore
const webSocketPair = new WebSocketPair();
const [client, webSocket] = Object.values(webSocketPair);
webSocket.accept();
let address = '';
let portWithRandomLog = '';
const log = (/** @type {string} */ info, /** @type {string | undefined} */ event) => {
console.log(`[${address}:${portWithRandomLog}] ${info}`, event || '');
};
const earlyDataHeader = request.headers.get('sec-websocket-protocol') || '';
const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log);
/** @type {{ value: import("@cloudflare/workers-types").Socket | null}}*/
let remoteSocketWapper = {
value: null,
};
let isDns = false;
// ws --> remote
readableWebSocketStream.pipeTo(new WritableStream({
async write(chunk, controller) {
if (isDns) {
return await handleDNSQuery(chunk, webSocket, null, log);
}
if (remoteSocketWapper.value) {
const writer = remoteSocketWapper.value.writable.getWriter()
await writer.write(chunk);
writer.releaseLock();
return;
}
const {
hasError,
message,
addressType,
portRemote = 443,
addressRemote = '',
rawDataIndex,
ProtocolVersion = new Uint8Array([0, 0]),
isUDP,
} = processProtocolHeader(chunk, userID);
address = addressRemote;
portWithRandomLog = `${portRemote}--${Math.random()} ${isUDP ? 'udp ' : 'tcp '
} `;
if (hasError) {
// controller.error(message);
throw new Error(message); // cf seems has bug, controller.error will not end stream
// webSocket.close(1000, message);
return;
}
// if UDP but port not DNS port, close it
if (isUDP) {
if (portRemote === 53) {
isDns = true;
} else {
// controller.error('UDP proxy only enable for DNS which is port 53');
throw new Error('UDP proxy only enable for DNS which is port 53'); // cf seems has bug, controller.error will not end stream
return;
}
}
// ["version", "附加信息长度 N"]
const ProtocolResponseHeader = new Uint8Array([ProtocolVersion[0], 0]);
const rawClientData = chunk.slice(rawDataIndex);
if (isDns) {
return handleDNSQuery(rawClientData, webSocket, ProtocolResponseHeader, log);
}
handleTCPOutBound(remoteSocketWapper, addressType, addressRemote, portRemote, rawClientData, webSocket, ProtocolResponseHeader, 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,
// @ts-ignore
webSocket: client,
});
}
async function trojanOverWSHandler(request) {
const webSocketPair = new WebSocketPair();
const [client, webSocket] = Object.values(webSocketPair);
webSocket.accept();
let address = "";
let portWithRandomLog = "";
const log = (info, event) => {
console.log(`[${address}:${portWithRandomLog}] ${info}`, event || "");
};
const earlyDataHeader = request.headers.get("sec-websocket-protocol") || "";
const readableWebSocketStream = makeReadableWebSocketStream(webSocket, earlyDataHeader, log);
let remoteSocketWapper = {
value: null
};
let udpStreamWrite = null;
readableWebSocketStream.pipeTo(new WritableStream({
async write(chunk, controller) {
if (udpStreamWrite) {
return udpStreamWrite(chunk);
}
if (remoteSocketWapper.value) {
const writer = remoteSocketWapper.value.writable.getWriter();
await writer.write(chunk);
writer.releaseLock();
return;
}
const {
hasError,
message,
portRemote = 443,
addressRemote = "",
rawClientData,
addressType
} = await parseTrojanHeader(chunk);
address = addressRemote;
portWithRandomLog = `${portRemote}--${Math.random()} tcp`;
if (hasError) {
throw new Error(message);
return;
}
handleTCPOutBound(remoteSocketWapper, addressRemote, portRemote, rawClientData, webSocket, log, addressType);
},
close() {
log(`readableWebSocketStream is closed`);
},
abort(reason) {
log(`readableWebSocketStream is aborted`, JSON.stringify(reason));
}
})).catch((err) => {
log("readableWebSocketStream pipeTo error", err);
});
return new Response(null, {
status: 101,
// @ts-ignore
webSocket: client
});
}
/**
* Handles outbound TCP connections.
*
* @param {any} remoteSocket
* @param {string} addressRemote The remote address to connect to.
* @param {number} portRemote The remote port to connect to.
* @param {Uint8Array} rawClientData The raw client data to write.
* @param {import("@cloudflare/workers-types").WebSocket} webSocket The WebSocket to pass the remote socket to.
* @param {Uint8Array} protocolResponseHeader The protocol response header.
* @param {function} log The logging function.
* @returns {Promise<void>} The remote socket.
*/
async function handleTCPOutBound(remoteSocket, addressType, addressRemote, portRemote, rawClientData, webSocket, ProtocolResponseHeader, log,) {
async function connectAndWrite(address, port, socks = false) {
/** @type {import("@cloudflare/workers-types").Socket} */
let tcpSocket;
if (socks5Relay) {
tcpSocket = await socks5Connect(addressType, address, port, log)
} else {
tcpSocket = socks ? await socks5Connect(addressType, address, port, log)
: connect({
hostname: address,
port: port,
});
}
remoteSocket.value = tcpSocket;
log(`connected to ${address}:${port}`);
const writer = tcpSocket.writable.getWriter();
await writer.write(rawClientData); // first write, normal is tls client hello
writer.releaseLock();
return tcpSocket;
}
// if the cf connect tcp socket have no incoming data, we retry to redirect ip
async function retry() {
if (enableSocks) {
tcpSocket = await connectAndWrite(addressRemote, portRemote, true);
} else {
tcpSocket = await connectAndWrite(proxyIP || addressRemote, portRemote);
}
// no matter retry success or not, close websocket
tcpSocket.closed.catch(error => {
console.log('retry tcpSocket closed error', error);
}).finally(() => {
safeCloseWebSocket(webSocket);
})
remoteSocketToWS(tcpSocket, webSocket, ProtocolResponseHeader, null, log);
}
let tcpSocket = await connectAndWrite(addressRemote, portRemote);
// when remoteSocket is ready, pass to websocket
// remote--> ws
remoteSocketToWS(tcpSocket, webSocket, ProtocolResponseHeader, retry, log);
}
/**
* Creates a readable stream from a WebSocket server, allowing for data to be read from the WebSocket.
* @param {import("@cloudflare/workers-types").WebSocket} webSocketServer The WebSocket server to create the readable stream from.
* @param {string} earlyDataHeader The header containing early data for WebSocket 0-RTT.
* @param {(info: string)=> void} log The logging function.
* @returns {ReadableStream} A readable stream that can be used to read data from the WebSocket.
*/
function makeReadableWebSocketStream(webSocketServer, earlyDataHeader, log) {
let readableStreamCancel = false;
const stream = new ReadableStream({
start(controller) {
webSocketServer.addEventListener('message', (event) => {
const message = event.data;
controller.enqueue(message);
});
webSocketServer.addEventListener('close', () => {
safeCloseWebSocket(webSocketServer);
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) {
// if ws can stop read if stream is full, we can implement backpressure
// https://streams.spec.whatwg.org/#example-rs-push-backpressure
},
cancel(reason) {
log(`ReadableStream was canceled, due to ${reason}`)
readableStreamCancel = true;
safeCloseWebSocket(webSocketServer);
}
});
return stream;
}
// https://xtls.github.io/development/protocols/protocol.html
// https://github.com/zizifn/excalidraw-backup/blob/main/v2ray-protocol.excalidraw
/**
* Processes the protocol header buffer and returns an object with the relevant information.
* @param {ArrayBuffer} protocolBuffer The protocol header buffer to process.
* @param {string} userID The user ID to validate against the UUID in the protocol header.
* @returns {{
* hasError: boolean,
* message?: string,
* addressRemote?: string,
* addressType?: number,
* portRemote?: number,
* rawDataIndex?: number,
* protocolVersion?: Uint8Array,
* isUDP?: boolean
* }} An object with the relevant information extracted from the protocol header buffer.
*/
function processProtocolHeader(protocolBuffer, userID) {
if (protocolBuffer.byteLength < 24) {
return { hasError: true, message: 'invalid data' };
}
const dataView = new DataView(protocolBuffer);
const version = dataView.getUint8(0);
const slicedBufferString = stringify(new Uint8Array(protocolBuffer.slice(1, 17)));
const uuids = userID.includes(',') ? userID.split(",") : [userID];
const isValidUser = uuids.some(uuid => slicedBufferString === uuid.trim()) ||
(uuids.length === 1 && slicedBufferString === uuids[0].trim());
console.log(`userID: ${slicedBufferString}`);
if (!isValidUser) {
return { hasError: true, message: 'invalid user' };
}
const optLength = dataView.getUint8(17);
const command = dataView.getUint8(18 + optLength);
if (command !== 1 && command !== 2) {
return { hasError: true, message: `command ${command} is not supported, command 01-tcp,02-udp,03-mux` };
}
const portIndex = 18 + optLength + 1;
const portRemote = dataView.getUint16(portIndex);
const addressType = dataView.getUint8(portIndex + 2);
let addressValue, addressLength, addressValueIndex;
switch (addressType) {
case 1:
addressLength = 4;
addressValueIndex = portIndex + 3;
addressValue = new Uint8Array(protocolBuffer.slice(addressValueIndex, addressValueIndex + addressLength)).join('.');
break;
case 2:
addressLength = dataView.getUint8(portIndex + 3);
addressValueIndex = portIndex + 4;
addressValue = new TextDecoder().decode(protocolBuffer.slice(addressValueIndex, addressValueIndex + addressLength));
break;
case 3:
addressLength = 16;
addressValueIndex = portIndex + 3;
addressValue = Array.from({ length: 8 }, (_, i) => dataView.getUint16(addressValueIndex + i * 2).toString(16)).join(':');
break;
default:
return { hasError: true, message: `invalid addressType: ${addressType}` };
}
if (!addressValue) {
return { hasError: true, message: `addressValue is empty, addressType is ${addressType}` };
}
return {
hasError: false,
addressRemote: addressValue,
addressType,
portRemote,
rawDataIndex: addressValueIndex + addressLength,
protocolVersion: new Uint8Array([version]),
isUDP: command === 2
};
}
/**
* Converts a remote socket to a WebSocket connection.
* @param {import("@cloudflare/workers-types").Socket} remoteSocket The remote socket to convert.
* @param {import("@cloudflare/workers-types").WebSocket} webSocket The WebSocket to connect to.
* @param {ArrayBuffer | null} protocolResponseHeader The protocol response header.
* @param {(() => Promise<void>) | null} retry The function to retry the connection if it fails.
* @param {(info: string) => void} log The logging function.
* @returns {Promise<void>} A Promise that resolves when the conversion is complete.
*/
async function remoteSocketToWS(remoteSocket, webSocket, protocolResponseHeader, retry, log) {
let hasIncomingData = false;
try {
await remoteSocket.readable.pipeTo(
new WritableStream({
async write(chunk) {
if (webSocket.readyState !== WS_READY_STATE_OPEN) {
throw new Error('WebSocket is not open');
}
hasIncomingData = true;
if (protocolResponseHeader) {
webSocket.send(await new Blob([protocolResponseHeader, chunk]).arrayBuffer());
protocolResponseHeader = null;
} else {
webSocket.send(chunk);
}
},
close() {
log(`Remote connection readable closed. Had incoming data: ${hasIncomingData}`);
},
abort(reason) {
console.error(`Remote connection readable aborted:`, reason);
},
})
);
} catch (error) {
console.error(`remoteSocketToWS error:`, error.stack || error);
safeCloseWebSocket(webSocket);
}
if (!hasIncomingData && retry) {
log(`No incoming data, retrying`);
await retry();
}
}
/**
* Decodes a base64 string into an ArrayBuffer.
* @param {string} base64Str The base64 string to decode.
* @returns {{earlyData: ArrayBuffer|null, error: Error|null}} An object containing the decoded ArrayBuffer or null if there was an error, and any error that occurred during decoding or null if there was no error.
*/
function base64ToArrayBuffer(base64Str) {
if (!base64Str) {
return { earlyData: null, error: null };
}
try {
// Convert modified Base64 for URL (RFC 4648) to standard Base64
base64Str = base64Str.replace(/-/g, '+').replace(/_/g, '/');
// Decode Base64 string
const binaryStr = atob(base64Str);
// Convert binary string to ArrayBuffer
const buffer = new ArrayBuffer(binaryStr.length);
const view = new Uint8Array(buffer);
for (let i = 0; i < binaryStr.length; i++) {
view[i] = binaryStr.charCodeAt(i);
}
return { earlyData: buffer, error: null };
} catch (error) {
return { earlyData: null, error };
}
}
/**
* Checks if a given string is a valid UUID.
* @param {string} uuid The string to validate as a UUID.
* @returns {boolean} True if the string is a valid UUID, false otherwise.
*/
function isValidUUID(uuid) {
// More precise UUID regex pattern
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
return uuidRegex.test(uuid);
}
const WS_READY_STATE_OPEN = 1;
const WS_READY_STATE_CLOSING = 2;
/**
* Closes a WebSocket connection safely without throwing exceptions.
* @param {import("@cloudflare/workers-types").WebSocket} socket The WebSocket connection to close.
*/
function safeCloseWebSocket(socket) {
try {
if (socket.readyState === WS_READY_STATE_OPEN || socket.readyState === WS_READY_STATE_CLOSING) {
socket.close();
}
} catch (error) {
console.error('safeCloseWebSocket error:', error);
}
}
const byteToHex = Array.from({ length: 256 }, (_, i) => (i + 0x100).toString(16).slice(1));
function unsafeStringify(arr, offset = 0) {
return [
byteToHex[arr[offset]],
byteToHex[arr[offset + 1]],
byteToHex[arr[offset + 2]],
byteToHex[arr[offset + 3]],
'-',
byteToHex[arr[offset + 4]],
byteToHex[arr[offset + 5]],
'-',
byteToHex[arr[offset + 6]],
byteToHex[arr[offset + 7]],
'-',
byteToHex[arr[offset + 8]],
byteToHex[arr[offset + 9]],
'-',
byteToHex[arr[offset + 10]],
byteToHex[arr[offset + 11]],
byteToHex[arr[offset + 12]],
byteToHex[arr[offset + 13]],
byteToHex[arr[offset + 14]],
byteToHex[arr[offset + 15]]
].join('').toLowerCase();
}
function stringify(arr, offset = 0) {
const uuid = unsafeStringify(arr, offset);
if (!isValidUUID(uuid)) {
throw new TypeError("Stringified UUID is invalid");
}
return uuid;
}
/**
* Handles outbound UDP traffic by transforming the data into DNS queries and sending them over a WebSocket connection.
* @param {import("@cloudflare/workers-types").WebSocket} webSocket The WebSocket connection to send the DNS queries over.
* @param {ArrayBuffer} protocolResponseHeader The protocol response header.
* @param {(string) => void} log The logging function.
* @returns {{write: (chunk: Uint8Array) => void}} An object with a write method that accepts a Uint8Array chunk to write to the transform stream.
*/
async function handleUDPOutBound(webSocket, protocolResponseHeader, log) {
let isprotocolHeaderSent = false;
const transformStream = new TransformStream({
start(_controller) {
},
transform(chunk, controller) {
// udp message 2 byte is the the length of udp data
// TODO: this should have bug, beacsue maybe udp chunk can be in two websocket message
for (let index = 0; index < chunk.byteLength;) {
const lengthBuffer = chunk.slice(index, index + 2);
const udpPakcetLength = new DataView(lengthBuffer).getUint16(0);
const udpData = new Uint8Array(
chunk.slice(index + 2, index + 2 + udpPakcetLength)
);
index = index + 2 + udpPakcetLength;
controller.enqueue(udpData);
}
},
flush(_controller) {
}
});
// only handle dns udp for now
transformStream.readable.pipeTo(new WritableStream({
async write(chunk) {
const resp = await fetch(dohURL, // dns server url
{
method: 'POST',
headers: {
'content-type': 'application/dns-message',
},
body: chunk,
})
const dnsQueryResult = await resp.arrayBuffer();
const udpSize = dnsQueryResult.byteLength;
// console.log([...new Uint8Array(dnsQueryResult)].map((x) => x.toString(16)));
const udpSizeBuffer = new Uint8Array([(udpSize >> 8) & 0xff, udpSize & 0xff]);
if (webSocket.readyState === WS_READY_STATE_OPEN) {
log(`doh success and dns message length is ${udpSize}`);
if (isprotocolHeaderSent) {
webSocket.send(await new Blob([udpSizeBuffer, dnsQueryResult]).arrayBuffer());
} else {
webSocket.send(await new Blob([protocolResponseHeader, udpSizeBuffer, dnsQueryResult]).arrayBuffer());
isprotocolHeaderSent = true;
}
}
}
})).catch((error) => {
log('dns udp has error' + error)
});
const writer = transformStream.writable.getWriter();
return {
/**
*
* @param {Uint8Array} chunk
*/
write(chunk) {
writer.write(chunk);
}
};
}
/**
*
* @param {ArrayBuffer} udpChunk
* @param {import("@cloudflare/workers-types").WebSocket} webSocket
* @param {ArrayBuffer} protocolResponseHeader
* @param {(string)=> void} log
*/
async function handleDNSQuery(udpChunk, webSocket, protocolResponseHeader, log) {
// no matter which DNS server client send, we alwasy use hard code one.
// beacsue someof DNS server is not support DNS over TCP
try {
const dnsServer = '8.8.4.4'; // change to 1.1.1.1 after cf fix connect own ip bug
const dnsPort = 53;
/** @type {ArrayBuffer | null} */
let vlessHeader = protocolResponseHeader;
/** @type {import("@cloudflare/workers-types").Socket} */
const tcpSocket = connect({
hostname: dnsServer,
port: dnsPort,
});
log(`connected to ${dnsServer}:${dnsPort}`);
const writer = tcpSocket.writable.getWriter();
await writer.write(udpChunk);
writer.releaseLock();
await tcpSocket.readable.pipeTo(new WritableStream({
async write(chunk) {
if (webSocket.readyState === WS_READY_STATE_OPEN) {
if (vlessHeader) {
webSocket.send(await new Blob([vlessHeader, chunk]).arrayBuffer());
vlessHeader = null;
} else {
webSocket.send(chunk);
}
}
},
close() {
log(`dns server(${dnsServer}) tcp is close`);
},
abort(reason) {
console.error(`dns server(${dnsServer}) tcp is abort`, reason);
},
}));
} catch (error) {
console.error(
`handleDNSQuery have exception, error: ${error.message}`
);
}
}
/**
*
* @param {number} addressType
* @param {string} addressRemote
* @param {number} portRemote
* @param {function} log The logging function.
*/
async function socks5Connect(addressType, addressRemote, portRemote, log) {
const { username, password, hostname, port } = parsedSocks5Address;
// Connect to the SOCKS server
const socket = connect({
hostname,
port,
});
// Request head format (Worker -> Socks Server):
// +----+----------+----------+
// |VER | NMETHODS | METHODS |
// +----+----------+----------+
// | 1 | 1 | 1 to 255 |
// +----+----------+----------+
// https://en.wikipedia.org/wiki/SOCKS#SOCKS5
// For METHODS:
// 0x00 NO AUTHENTICATION REQUIRED
// 0x02 USERNAME/PASSWORD https://datatracker.ietf.org/doc/html/rfc1929
const socksGreeting = new Uint8Array([5, 2, 0, 2]);
const writer = socket.writable.getWriter();
await writer.write(socksGreeting);
log('sent socks greeting');
const reader = socket.readable.getReader();
const encoder = new TextEncoder();
let res = (await reader.read()).value;
// Response format (Socks Server -> Worker):
// +----+--------+
// |VER | METHOD |
// +----+--------+
// | 1 | 1 |
// +----+--------+
if (res[0] !== 0x05) {
log(`socks server version error: ${res[0]} expected: 5`);
return;
}
if (res[1] === 0xff) {
log("no acceptable methods");
return;
}
// if return 0x0502
if (res[1] === 0x02) {
log("socks server needs auth");
if (!username || !password) {
log("please provide username/password");
return;
}
// +----+------+----------+------+----------+
// |VER | ULEN | UNAME | PLEN | PASSWD |
// +----+------+----------+------+----------+
// | 1 | 1 | 1 to 255 | 1 | 1 to 255 |
// +----+------+----------+------+----------+
const authRequest = new Uint8Array([
1,
username.length,
...encoder.encode(username),
password.length,
...encoder.encode(password)
]);
await writer.write(authRequest);
res = (await reader.read()).value;
// expected 0x0100
if (res[0] !== 0x01 || res[1] !== 0x00) {
log("fail to auth socks server");
return;
}
}
// Request data format (Worker -> Socks Server):
// +----+-----+-------+------+----------+----------+
// |VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
// ATYP: address type of following address
// 0x01: IPv4 address
// 0x03: Domain name
// 0x04: IPv6 address
// DST.ADDR: desired destination address
// DST.PORT: desired destination port in network octet order
// addressType
// 1--> ipv4 addressLength =4
// 2--> domain name
// 3--> ipv6 addressLength =16
let DSTADDR; // DSTADDR = ATYP + DST.ADDR
switch (addressType) {
case 1:
DSTADDR = new Uint8Array(
[1, ...addressRemote.split('.').map(Number)]
);
break;
case 2:
DSTADDR = new Uint8Array(
[3, addressRemote.length, ...encoder.encode(addressRemote)]
);
break;
case 3:
DSTADDR = new Uint8Array(
[4, ...addressRemote.split(':').flatMap(x => [parseInt(x.slice(0, 2), 16), parseInt(x.slice(2), 16)])]
);
break;
default:
log(`invild addressType is ${addressType}`);
return;
}
const socksRequest = new Uint8Array([5, 1, 0, ...DSTADDR, portRemote >> 8, portRemote & 0xff]);
await writer.write(socksRequest);
log('sent socks request');
res = (await reader.read()).value;
// Response format (Socks Server -> Worker):
// +----+-----+-------+------+----------+----------+
// |VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
// +----+-----+-------+------+----------+----------+
// | 1 | 1 | X'00' | 1 | Variable | 2 |
// +----+-----+-------+------+----------+----------+
if (res[1] === 0x00) {
log("socks connection opened");
} else {
log("fail to open socks connection");
return;
}
writer.releaseLock();
reader.releaseLock();
return socket;
}
/**
*
* @param {string} address
*/
function socks5AddressParser(address) {
let [latter, former] = address.split("@").reverse();
let username, password, hostname, port;
if (former) {
const formers = former.split(":");
if (formers.length !== 2) {
throw new Error('Invalid SOCKS address format');
}
[username, password] = formers;
}
const latters = latter.split(":");
port = Number(latters.pop());
if (isNaN(port)) {
throw new Error('Invalid SOCKS address format');
}
hostname = latters.join(":");
const regex = /^\[.*\]$/;
if (hostname.includes(":") && !regex.test(hostname)) {
throw new Error('Invalid SOCKS address format');
}
return {
username,
password,
hostname,
port,
}
}
async function parseTrojanHeader(buffer) {
if (buffer.byteLength < 58) {
return { hasError: true, message: "Invalid data length" };
}
const view = new DataView(buffer);
if (view.getUint8(56) !== 0x0d || view.getUint8(57) !== 0x0a) {
return { hasError: true, message: "Invalid header format (missing CR LF)" };
}
const password = new TextDecoder().decode(buffer.slice(0, 56));
if (password !== Sha256.sha224(userID)) {
return { hasError: true, message: "Invalid password" };
}
const socks5Data = new DataView(buffer, 58);
if (socks5Data.byteLength < 6) {
return { hasError: true, message: "Invalid SOCKS5 request data" };
}
if (socks5Data.getUint8(0) !== 1) {
return { hasError: true, message: "Unsupported command, only TCP (CONNECT) is allowed" };
}
const atype = socks5Data.getUint8(1);
let address;
let addressEnd;
switch (atype) {
case 1: // IPv4
address = Array.from(new Uint8Array(socks5Data.buffer, socks5Data.byteOffset + 2, 4)).join('.');
addressEnd = 6;
break;
case 3: // Domain name
const domainLength = socks5Data.getUint8(2);
address = new TextDecoder().decode(socks5Data.buffer.slice(socks5Data.byteOffset + 3, socks5Data.byteOffset + 3 + domainLength));
addressEnd = 3 + domainLength;
break;
case 4: // IPv6
address = Array.from(new Uint8Array(socks5Data.buffer, socks5Data.byteOffset + 2, 16))
.map(x => x.toString(16).padStart(2, '0'))
.join(':')
.replace(/(:0)+:/, '::');
addressEnd = 18;
break;
default:
return { hasError: true, message: `Invalid address type: ${atype}` };
}
const port = socks5Data.getUint16(addressEnd);
return {
hasError: false,
address,
port,
data: buffer.slice(58 + addressEnd + 2)
};
}
const VlessCmd = {
TCP: 1,
UDP: 2,
MUX: 3,
};
const VlessAddrType = {
IPv4: 1, // 4-bytes
DomainName: 2, // The first byte indicates the length of the following domain name
IPv6: 3, // 16-bytes
};
/**
* Generate a vless request header.
* @param {number} command - The command to execute (see VlessCmd).
* @param {number} destType - The type of destination address (see VlessAddrType).
* @param {string} destAddr - The destination address.
* @param {number} destPort - The destination port.
* @param {string} uuid - The UUID of the request.
* @returns {Uint8Array} - The vless request header as a Uint8Array.
* @throws {Error} - If the address type is unknown.
*/
function makeVlessReqHeader(command, destType, destAddr, destPort, uuid) {
/** @type {number} */
let addressFieldLength;
/** @type {Uint8Array | undefined} */
let addressEncoded;
switch (destType) {
case VlessAddrType.IPv4:
addressFieldLength = 4;
break;
case VlessAddrType.DomainName:
addressEncoded = new TextEncoder().encode(destAddr);
addressFieldLength = addressEncoded.length + 1;
break;
case VlessAddrType.IPv6:
addressFieldLength = 16;
break;
default:
throw new Error(`Unknown address type: ${destType}`);
}
const uuidString = uuid.replace(/-/g, '');
const uuidOffset = 1;
const vlessHeader = new Uint8Array(22 + addressFieldLength);
// Protocol Version = 0
vlessHeader[0] = 0x00;