MCPcopy Create free account
hub / github.com/SamNet-dev/snix / handleVLESS

Function handleVLESS

cfworker/worker.js:59–125  ·  view source on GitHub ↗

* Handle a VLESS-over-WebSocket upgrade. * Minimal VLESS implementation; supports TCP outbound only (no UDP / Mux).

(request, uuid)

Source from the content-addressed store, hash-verified

57 * Minimal VLESS implementation; supports TCP outbound only (no UDP / Mux).
58 */
59async function handleVLESS(request, uuid) {
60 const pair = new WebSocketPair();
61 const [client, ws] = Object.values(pair);
62 ws.accept();
63
64 // Read the early-data header so the first packet is part of the upgrade.
65 const earlyData = b64UrlToUint8(request.headers.get("sec-websocket-protocol") || "");
66
67 // We buffer incoming WebSocket messages until we've parsed the VLESS
68 // header; after that each message is piped raw to the remote socket.
69 const handshake = { parsed: false, remote: null, writer: null };
70
71 const onMessage = async (data) => {
72 const chunk = toUint8(data);
73 if (!handshake.parsed) {
74 const parsed = parseVLESSHeader(chunk, uuid);
75 if (!parsed.ok) {
76 console.log("vless header parse failed:", parsed.err);
77 safeClose(ws);
78 return;
79 }
80 handshake.parsed = true;
81
82 // Open the upstream TCP connection (Cloudflare 'connect' API).
83 const socket = await cfConnect(parsed.host, parsed.port);
84 handshake.remote = socket;
85 handshake.writer = socket.writable.getWriter();
86
87 // VLESS server reply: version 0, addons length 0.
88 ws.send(new Uint8Array([parsed.version, 0]).buffer);
89
90 // Forward any payload that came after the header.
91 if (parsed.payload.length > 0) {
92 await handshake.writer.write(parsed.payload);
93 }
94 // Pipe server -> WS.
95 socket.readable
96 .pipeTo(new WritableStream({
97 write(data) {
98 if (ws.readyState === WS_READY_STATE_OPEN) {
99 ws.send(data);
100 }
101 },
102 close() { safeClose(ws); },
103 abort() { safeClose(ws); },
104 }))
105 .catch(() => safeClose(ws));
106 return;
107 }
108 // Subsequent WS messages → remote socket.
109 try {
110 await handshake.writer.write(chunk);
111 } catch {
112 safeClose(ws);
113 }
114 };
115
116 ws.addEventListener("message", (ev) => { onMessage(ev.data); });

Callers 1

fetchFunction · 0.85

Calls 2

b64UrlToUint8Function · 0.85
onMessageFunction · 0.85

Tested by

no test coverage detected