The best way to control Claude Code, Codex and more from any computer or phone

main
ts 229 lines 9.17 KB
Raw
1 import type { IncomingMessage } from "node:http";
2 import * as NodeNet from "node:net";
3 import type { Duplex } from "node:stream";
4 import type * as vite from "vite";
5 import { proxyRequestHeaders, resolveForwardedHost } from "./forwarded-host.ts";
6 import { workerRequestUrl } from "./worker-request.ts";
7
8 /**
9 * Handles 'upgrade' requests on the Vite HTTP server and forwards the
10 * WebSocket handshake to the local workerd address as a raw HTTP upgrade.
11 *
12 * Returns a cleanup function that removes the listener (used on server restart).
13 */
14 export function handleWebSocket(
15 httpServer: vite.HttpServer,
16 address: string | URL,
17 proxySharedSecret: string,
18 ): () => void {
19 const upstreamBase = typeof address === "string" ? new URL(address) : address;
20
21 // Sockets hijacked by an `upgrade` are not reaped by `server.closeAllConnections()`,
22 // yet `server.close()` still waits on them — so a lingering proxied WebSocket blocks
23 // the HTTP server from closing on restart. Track live sockets and destroy them in the
24 // cleanup function to close deterministically.
25 const sockets = new Set<Duplex>();
26 const track = (socket: Duplex) => {
27 sockets.add(socket);
28 socket.on("close", () => sockets.delete(socket));
29 };
30
31 // An `async` listener (Vite's `server.proxy` awaiting its `bypass`, a
32 // plugin authenticating first) may take an upgrade only after the Worker
33 // has answered it, without touching the socket before. `emit` is wrapped to
34 // keep the promises the other listeners return for each socket, and the
35 // Worker's answer waits for them to settle.
36 const pending = new WeakMap<Duplex, Promise<unknown>>();
37 const emit = httpServer.emit;
38 const emitUpgrade = function (
39 this: vite.HttpServer,
40 event: string | symbol,
41 ...args: Array<any>
42 ) {
43 if (event !== "upgrade") return emit.call(this, event, ...args);
44 const settling: Array<PromiseLike<unknown>> = [];
45 for (const listener of this.rawListeners("upgrade")) {
46 const result: unknown = listener.apply(this, args);
47 if (isPromiseLike(result)) settling.push(result);
48 }
49 if (settling.length > 0) pending.set(args[1] as Duplex, Promise.allSettled(settling));
50 return true;
51 } as typeof emit;
52 httpServer.emit = emitUpgrade;
53
54 const onUpgrade = (request: IncomingMessage, socket: Duplex, head: Buffer) => {
55 // Unhandled socket errors crash Node.
56 socket.on("error", () => socket.destroy());
57
58 // The URL — and thus the Sandbox-origin check below — is built from the
59 // resolved (forwarded) host, not the raw `Host` header. This diverges from
60 // upstream, which keys the origin off `Host`; here it's intentional so a
61 // tunnel-fronted Sandbox preview still matches. Direct Sandbox hits carry no
62 // `X-Forwarded-Host`, so they fall back to `Host` and behave identically.
63 const rawHost = resolveForwardedHost(request.headers, "localhost");
64 const base = /^https?:\/\//i.test(rawHost) ? rawHost : `http://${rawHost}`;
65 const url = workerRequestUrl(request.url, base);
66
67 const isViteRequest = request.headers["sec-websocket-protocol"]?.startsWith("vite") ?? false;
68 const isSandboxRequest = hasSandboxOrigin(url.origin);
69
70 // Vite handles its own HMR upgrades; forward Sandbox preview URLs anyway.
71 if (isViteRequest && !isSandboxRequest) {
72 return;
73 }
74
75 const target = new URL(url.pathname + url.search, upstreamBase);
76 // A raw TCP tunnel rather than a `node:http` client request: Bun's
77 // `node:http` client never emits `upgrade`, so the handshake would hang
78 // there. Writing the request head and piping both ways relays the
79 // Worker's answer byte for byte, whether a 101 or a refusal (a 403, a
80 // 404, ...) that must reach the client rather than a connection reset.
81 const upstream = NodeNet.connect({ host: target.hostname, port: Number(target.port) });
82 track(socket);
83 track(upstream);
84 socket.on("close", () => upstream.destroy());
85
86 // Other plugins serve their own WebSockets on the dev server (a DevTools
87 // relay, `server.proxy` with `ws: true`), and every `upgrade` listener sees
88 // every upgrade. This listener runs first (see `prependListener` below),
89 // so it records the socket's state before any other listener can touch
90 // it. A socket another listener has since written to, ended, or attached
91 // its own listeners to belongs to that listener: the Worker's answer is
92 // dropped rather than written over the other listener's handshake.
93 const before = socketActivity(socket);
94 const claimed = () => isClaimed(socket, before);
95
96 // The Worker's answer is buffered until it is known who answers the
97 // client: an asynchronous listener may claim the socket while the request
98 // is in flight, or may still be deciding when the Worker answers.
99 const answer: Array<Buffer> = [];
100 const buffer = (chunk: Buffer) => answer.push(chunk);
101 let relaying = false;
102 const relay = () => {
103 upstream.off("data", buffer);
104 if (claimed()) {
105 // Leaves the socket to the listener that claimed it.
106 sockets.delete(socket);
107 upstream.destroy();
108 return;
109 }
110 if (upstream.destroyed) {
111 // The Worker closed: relay its whole (buffered) answer, or reset the
112 // client if it never answered.
113 if (answer.length === 0) {
114 socket.destroy();
115 return;
116 }
117 for (const chunk of answer) socket.write(chunk);
118 socket.end();
119 return;
120 }
121 relaying = true;
122 for (const chunk of answer) socket.write(chunk);
123 // oxlint-disable-next-line effecttsgo/unnecessary-pipe-chain -- Node stream piping (socket -> upstream -> socket), not Effect pipe
124 socket.pipe(upstream).pipe(socket);
125 };
126 let decided = false;
127 const decide = () => {
128 if (decided) return;
129 decided = true;
130 const settled = pending.get(socket);
131 if (settled === undefined) return relay();
132 void settled.then(relay);
133 };
134 upstream.on("data", buffer);
135 upstream.once("data", decide);
136 upstream.on("error", () => upstream.destroy());
137 upstream.on("close", () => {
138 if (relaying) socket.destroy();
139 else decide();
140 });
141 upstream.once("connect", () => {
142 if (socket.destroyed || claimed()) {
143 sockets.delete(socket);
144 upstream.destroy();
145 return;
146 }
147 const lines = [`${request.method ?? "GET"} ${target.pathname}${target.search} HTTP/1.1`];
148 for (const [name, value] of Object.entries(
149 proxyRequestHeaders(request, url, proxySharedSecret),
150 )) {
151 if (value === undefined) continue;
152 for (const item of Array.isArray(value) ? value : [value]) {
153 lines.push(`${name}: ${item}`);
154 }
155 }
156 upstream.write(`${lines.join("\r\n")}\r\n\r\n`);
157 if (head.length > 0) {
158 upstream.write(head);
159 }
160 });
161 };
162
163 httpServer.prependListener("upgrade", onUpgrade);
164 return () => {
165 if (httpServer.emit === emitUpgrade) httpServer.emit = emit;
166 httpServer.off("upgrade", onUpgrade);
167 for (const socket of sockets) {
168 socket.destroy();
169 }
170 sockets.clear();
171 };
172 }
173
174 const isPromiseLike = (value: unknown): value is PromiseLike<unknown> =>
175 typeof value === "object" &&
176 value !== null &&
177 "then" in value &&
178 typeof value.then === "function";
179
180 interface SocketActivity {
181 readonly written: number;
182 readonly listeners: number;
183 }
184
185 // `bytesWritten` counts what Node has queued; Bun counts only what it has
186 // flushed, so the queued `writableLength` is added for both.
187 const socketActivity = (socket: Duplex): SocketActivity => ({
188 written: ((socket as Partial<NodeNet.Socket>).bytesWritten ?? 0) + socket.writableLength,
189 listeners: (["data", "error", "close", "end"] as const).reduce(
190 (count, event) =>
191 count + socket.rawListeners(event).filter((listener) => !isNoop(listener)).length,
192 0,
193 ),
194 });
195
196 // An empty listener can't take the socket. Vite 8.3.5's HMR `upgrade` listener
197 // attaches `socket.on("error", noop)` to every upgrade it doesn't handle.
198 const isNoop = (listener: Function) =>
199 /^(?:function\s*[\w$]*\s*)?\(\s*\)\s*(?:=>\s*)?\{\s*\}$/.test(listener.toString());
200
201 // A listener that takes an upgrade writes its handshake or refusal, or
202 // subscribes to the socket synchronously, before it answers: `ws` listens for
203 // `error` before an async `verifyClient`, and Vite's `server.proxy` for
204 // `close` and `error` before it dials its target.
205 const isClaimed = (socket: Duplex, before: SocketActivity) => {
206 const now = socketActivity(socket);
207 return (
208 socket.destroyed ||
209 socket.writableEnded ||
210 now.written > before.written ||
211 now.listeners > before.listeners
212 );
213 };
214
215 /**
216 * Matches the origin of a Sandbox SDK preview URL.
217 * See: https://developers.cloudflare.com/sandbox/concepts/preview-urls/
218 *
219 * Pattern: https?://<port(4+ digits)>-<id(no dots)>-<token>.localhost
220 *
221 * IMPORTANT: The token segment is [a-z0-9_]+ (no hyphens) to prevent ReDoS — two adjacent
222 * [^.]+ groups separated by - cause quadratic backtracking on hyphen-heavy input. Tokens
223 * are documented as letters/digits/underscores only.
224 */
225 export const SANDBOX_ORIGIN_REGEXP = /^https?:\/\/\d{4,}-[^.]+-[a-z0-9_]+\.localhost(:\d+)?$/i;
226
227 function hasSandboxOrigin(origin: string) {
228 return SANDBOX_ORIGIN_REGEXP.test(origin);
229 }