import { acceptKey, upgradeResponse, httpRefusal } from "./ws-frames.mjs"; import { killTree } from "./exec.mjs"; const MAX_HEADER = 8192; /** Pass only WebSocket frames through the SSH channel. Both HTTP handshakes * are constructed here, so no remote HTTP header can change local cookies, * origin, extensions, redirects, or anything else on the local deck. */ export function relayDeviceWorkspace({ socket, head, key, port, ticket, connect, onClose }) { let child; let done = false; let upgraded = false; let buffered = Buffer.alloc(0); function close(status = 503) { if (done) return; done = true; clearTimeout(deadline); if (child) killTree(child, "SIGTERM"); if (!socket.destroyed) { if (upgraded) socket.destroy(); else socket.end(httpRefusal(status)); } onClose(); } const deadline = setTimeout(close, 12_000); deadline.unref?.(); socket.once("close", () => close()); socket.once("error", () => close()); socket.pause(); const readHandshake = (chunk) => { buffered = Buffer.concat([buffered, chunk]); const end = buffered.indexOf("\r\n\r\n"); if (end < 0) { if (buffered.length >= MAX_HEADER) close(); return; } if (end > MAX_HEADER) return close(); const [status, ...headers] = buffered.subarray(0, end).toString("latin1").split("\r\n"); const accepted = headers.some(line => /^sec-websocket-accept:/i.test(line) && line.slice(line.indexOf(":") + 1).trim() === acceptKey(key)); if (!/^HTTP\/1\.1 101(?: |$)/.test(status) || !accepted || headers.some(line => /^(sec-websocket-extensions|sec-websocket-protocol):/i.test(line))) return close(); clearTimeout(deadline); child.stdout.off("data", readHandshake); upgraded = true; socket.setTimeout(0); socket.write(upgradeResponse(key)); const tail = buffered.subarray(end + 4); if (tail.length) socket.write(tail); buffered = Buffer.alloc(0); child.stdout.pipe(socket); if (head.length) child.stdin.write(head); socket.pipe(child.stdin); socket.resume(); }; void Promise.resolve().then(connect).then(stream => { if (!stream) return close(); child = stream; child.on("error", () => close()); child.once("close", () => close()); child.stdin.on("error", () => close()); child.stdout.on("error", () => close()); child.stderr.resume(); if (done) { killTree(child, "SIGTERM"); return; } child.stdout.on("data", readHandshake); const host = `127.0.0.1:${port}`; child.stdin.write([ `GET /api/terminal/attach?ticket=${ticket} HTTP/1.1`, `Host: ${host}`, `Origin: http://${host}`, "Upgrade: websocket", "Connection: Upgrade", "Sec-WebSocket-Version: 13", `Sec-WebSocket-Key: ${key}`, "", "", ].join("\r\n")); }).catch(() => close()); return { shutdown: () => close() }; }