|
| 1 | +import crypto from "node:crypto"; |
| 2 | +import http from "node:http"; |
| 3 | + |
| 4 | +export const SURFACE_HOST_SUFFIX = ".htty"; |
| 5 | + |
| 6 | +// Hop headers must not be forwarded by any proxy (RFC 2616 §13.5.1). |
| 7 | +const HOP_HEADERS = new Set([ |
| 8 | + "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", |
| 9 | + "te", "trailers", "transfer-encoding", "upgrade", |
| 10 | +]); |
| 11 | + |
| 12 | +// A single HTTP/WSS server shared across all HTTY sessions. |
| 13 | +// |
| 14 | +// Chromium reaches it because host-resolver-rules maps *.htty to |
| 15 | +// 127.0.0.1:<this port>. The Host header identifies which session owns each |
| 16 | +// request. HTTP (not HTTPS) is used so no TLS certificate is needed; the |
| 17 | +// embedded pages use ws:// WebSocket URLs which match their http:// origin. |
| 18 | +// |
| 19 | +// HTTP requests → proxied to the session's HTTY HTTP/2 client. |
| 20 | +// WebSocket upgrades → HTTP/2 extended-CONNECT stream on the HTTY client; |
| 21 | +// raw WebSocket frames are piped bidirectionally. No frame |
| 22 | +// encoding/decoding is needed here: the browser and the HTTY server both |
| 23 | +// speak RFC 8441, so the server is a transparent byte tunnel. |
| 24 | + |
| 25 | +export class HTTYSurfaceServer { |
| 26 | + #sessions = new Map(); // "session-1" → getClient fn |
| 27 | + #wellKnownHandlers = new Map(); // "session-1" → handler fn |
| 28 | + #server = http.createServer((req, res) => this.#handleHttp(req, res)); |
| 29 | + port = null; |
| 30 | + |
| 31 | + constructor() { |
| 32 | + this.#server.on("upgrade", (req, socket, head) => this.#handleUpgrade(req, socket, head)); |
| 33 | + } |
| 34 | + |
| 35 | + register(sessionId, getClient, wellKnownHandler) { |
| 36 | + this.#sessions.set(sessionId, getClient); |
| 37 | + this.#wellKnownHandlers.set(sessionId, wellKnownHandler); |
| 38 | + } |
| 39 | + |
| 40 | + unregister(sessionId) { |
| 41 | + this.#sessions.delete(sessionId); |
| 42 | + this.#wellKnownHandlers.delete(sessionId); |
| 43 | + } |
| 44 | + |
| 45 | + start() { |
| 46 | + return new Promise((resolve, reject) => { |
| 47 | + this.#server.listen(0, "127.0.0.1", () => { |
| 48 | + this.port = this.#server.address().port; |
| 49 | + resolve(this.port); |
| 50 | + }); |
| 51 | + this.#server.once("error", reject); |
| 52 | + }); |
| 53 | + } |
| 54 | + |
| 55 | + close() { |
| 56 | + this.#server.close(); |
| 57 | + } |
| 58 | + |
| 59 | + #sessionId(req) { |
| 60 | + const host = req.headers.host ?? ""; |
| 61 | + const hostname = host.split(":")[0]; |
| 62 | + if (!hostname.endsWith(SURFACE_HOST_SUFFIX)) return null; |
| 63 | + return hostname.slice(0, -SURFACE_HOST_SUFFIX.length); |
| 64 | + } |
| 65 | + |
| 66 | + async #handleHttp(req, res) { |
| 67 | + const sessionId = this.#sessionId(req); |
| 68 | + const client = sessionId ? this.#sessions.get(sessionId)?.() : null; |
| 69 | + if (!client) { |
| 70 | + res.writeHead(410); |
| 71 | + res.end("HTTY session not available"); |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + const requestPath = req.url ?? "/"; |
| 76 | + |
| 77 | + // Chimera-owned .well-known routes are handled locally. |
| 78 | + if (requestPath.startsWith("/.well-known/chimera/")) { |
| 79 | + const handled = this.#wellKnownHandlers.get(sessionId)?.(requestPath, req, res); |
| 80 | + if (handled) return; |
| 81 | + } |
| 82 | + |
| 83 | + const method = (req.method ?? "GET").toUpperCase(); |
| 84 | + const headers = {":scheme": "http", ":authority": req.headers.host ?? ""}; |
| 85 | + for (const [key, value] of Object.entries(req.headers)) { |
| 86 | + if (key !== "host" && !HOP_HEADERS.has(key)) headers[key] = value; |
| 87 | + } |
| 88 | + |
| 89 | + try { |
| 90 | + const response = await client.request({ |
| 91 | + path: requestPath, |
| 92 | + method, |
| 93 | + headers, |
| 94 | + body: method !== "GET" && method !== "HEAD" ? req : undefined, |
| 95 | + }); |
| 96 | + res.writeHead(response.status, response.headers); |
| 97 | + if (response.body) response.body.pipe(res); else res.end(); |
| 98 | + } catch (err) { |
| 99 | + if (!res.headersSent) res.writeHead(500); |
| 100 | + res.end(String(err?.message ?? err)); |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + #handleUpgrade(req, socket, head) { |
| 105 | + const sessionId = this.#sessionId(req); |
| 106 | + const client = sessionId ? this.#sessions.get(sessionId)?.() : null; |
| 107 | + if (!client) { socket.destroy(); return; } |
| 108 | + |
| 109 | + const host = (req.headers.host ?? "").split(":")[0]; |
| 110 | + const requestHeaders = { |
| 111 | + ":method": "CONNECT", |
| 112 | + ":protocol": "websocket", |
| 113 | + ":scheme": "http", |
| 114 | + ":authority": host, |
| 115 | + ":path": req.url ?? "/", |
| 116 | + }; |
| 117 | + if (req.headers["sec-websocket-protocol"]) { |
| 118 | + requestHeaders["sec-websocket-protocol"] = req.headers["sec-websocket-protocol"]; |
| 119 | + } |
| 120 | + |
| 121 | + let stream; |
| 122 | + try { |
| 123 | + stream = client.start().request(requestHeaders); |
| 124 | + } catch { socket.destroy(); return; } |
| 125 | + |
| 126 | + stream.once("response", (responseHeaders) => { |
| 127 | + if (Number(responseHeaders[":status"]) !== 200) { |
| 128 | + socket.destroy(); stream.destroy(); return; |
| 129 | + } |
| 130 | + |
| 131 | + const key = req.headers["sec-websocket-key"] ?? ""; |
| 132 | + const accept = crypto.createHash("sha1") |
| 133 | + .update(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11") |
| 134 | + .digest("base64"); |
| 135 | + const selectedProtocol = responseHeaders["sec-websocket-protocol"]; |
| 136 | + |
| 137 | + socket.write( |
| 138 | + "HTTP/1.1 101 Switching Protocols\r\n" + |
| 139 | + "Upgrade: websocket\r\n" + |
| 140 | + "Connection: Upgrade\r\n" + |
| 141 | + `Sec-WebSocket-Accept: ${accept}\r\n` + |
| 142 | + (selectedProtocol ? `Sec-WebSocket-Protocol: ${selectedProtocol}\r\n` : "") + |
| 143 | + "\r\n", |
| 144 | + ); |
| 145 | + |
| 146 | + // Pipe WebSocket frames transparently — no framing needed here. |
| 147 | + if (head.length > 0) stream.write(head); |
| 148 | + socket.pipe(stream); |
| 149 | + stream.pipe(socket); |
| 150 | + }); |
| 151 | + |
| 152 | + stream.on("error", () => socket.destroy()); |
| 153 | + socket.on("error", () => stream.destroy()); |
| 154 | + } |
| 155 | +} |
0 commit comments