MCPcopy Index your code
hub / github.com/SamNet-dev/snix / onMessage

Function onMessage

cfworker/worker.js:71–114  ·  view source on GitHub ↗
(data)

Source from the content-addressed store, hash-verified

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); });
117 ws.addEventListener("close", () => { try { handshake.remote && handshake.remote.close(); } catch {} });

Callers 1

handleVLESSFunction · 0.85

Calls 4

toUint8Function · 0.85
parseVLESSHeaderFunction · 0.85
safeCloseFunction · 0.85
cfConnectFunction · 0.85

Tested by

no test coverage detected