import { randomBytes } from "node:crypto"; import { createServer, type IncomingMessage, type Server, type ServerResponse, } from "node:http"; import { listenHostFor, uiUrl } from "./network"; export type UiServerState = "waiting" | "connected" | "inactive" | "stopped"; export type UiServer = { baseUrl: string; publicUrl: string; port: number; token: string; state(): UiServerState; clients(): number; close(reason: string): Promise; }; export type StartUiServerOptions = { address: string; token?: string; preferredPort?: number; onClientState?: (state: UiServerState) => void; }; const COOKIE = "pi_ui_token"; const MAX_BODY_BYTES = 1_000_000; export async function startUiServer( options: StartUiServerOptions, ): Promise { const token = options.token ?? randomBytes(32).toString("base64url"); const host = listenHostFor(options.address); let currentState: UiServerState = "waiting"; let clientCount = 0; let closed = false; const server = createServer((req, res) => { void dispatch(req, res, { token, state: () => currentState, clients: () => clientCount, setState(next) { currentState = next; options.onClientState?.(next); }, clientSeen() { clientCount += 1; }, }); }); await listen(server, host, options.preferredPort ?? 0); const address = server.address(); if (!address || typeof address === "string") throw new Error("Failed to bind UI server"); const baseUrl = `http://127.0.0.1:${address.port}`; const publicUrl = uiUrl(options.address, address.port, token); return { baseUrl, publicUrl, port: address.port, token, state: () => currentState, clients: () => clientCount, async close(reason) { void reason; if (closed) return; closed = true; currentState = "stopped"; options.onClientState?.("stopped"); await closeServer(server); }, }; } type RouteContext = { token: string; state(): UiServerState; clients(): number; setState(state: UiServerState): void; clientSeen(): void; }; async function dispatch( req: IncomingMessage, res: ServerResponse, ctx: RouteContext, ): Promise { try { const url = new URL(req.url ?? "/", "http://127.0.0.1"); setSecurityHeaders(res); if (hasOversizedBody(req)) return json(res, 413, { error: "body too large" }); if (req.method === "GET" && url.pathname === "/") { return serveIndex(req, url, res, ctx); } if (!authorized(req, ctx.token)) return serveUnauthorized(res); if (req.method === "GET" && url.pathname === "/api/status") { return json(res, 200, { state: ctx.state(), clients: ctx.clients() }); } return json(res, 404, { error: "not found" }); } catch (error) { return json(res, 500, { error: error instanceof Error ? error.message : String(error), }); } } function serveIndex( req: IncomingMessage, url: URL, res: ServerResponse, ctx: RouteContext, ): void { if ( url.searchParams.get("token") !== ctx.token && !cookieAuthorized(req, ctx.token) ) { serveUnauthorized(res); return; } ctx.clientSeen(); ctx.setState("connected"); res.setHeader( "Set-Cookie", `${COOKIE}=${ctx.token}; SameSite=Strict; Path=/`, ); res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end(renderShellPage()); } function renderShellPage(): string { return ` Pi UI shell

Pi UI shell

Phase 1 server is running. RPC stream arrives in a later phase.

Return to terminal and run /ui off to stop.

`; } function serveUnauthorized(res: ServerResponse): void { res.statusCode = 401; res.setHeader("Content-Type", "text/html; charset=utf-8"); res.end( "Unauthorized

Unauthorized

Open the exact /ui link or scan the current QR code again.

", ); } function authorized(req: IncomingMessage, token: string): boolean { return ( req.headers.authorization === `Bearer ${token}` || cookieAuthorized(req, token) ); } function cookieAuthorized(req: IncomingMessage, token: string): boolean { return (req.headers.cookie ?? "") .split(/;\s*/) .some((cookie) => cookie === `${COOKIE}=${token}`); } function hasOversizedBody(req: IncomingMessage): boolean { const length = req.headers["content-length"]; return typeof length === "string" && Number(length) > MAX_BODY_BYTES; } function setSecurityHeaders(res: ServerResponse): void { res.setHeader("X-Content-Type-Options", "nosniff"); res.setHeader("Referrer-Policy", "no-referrer"); res.setHeader("Cross-Origin-Opener-Policy", "same-origin"); } function json(res: ServerResponse, status: number, body: unknown): void { res.statusCode = status; res.setHeader("Content-Type", "application/json; charset=utf-8"); res.end(JSON.stringify(body)); } function listen(server: Server, host: string, port: number): Promise { return new Promise((resolve, reject) => { const onError = (error: NodeJS.ErrnoException) => { server.off("error", onError); reject(error); }; server.once("error", onError); server.listen(port, host, () => { server.off("error", onError); resolve(); }); }); } function closeServer(server: Server): Promise { return new Promise((resolve, reject) => { server.close((error) => (error ? reject(error) : resolve())); }); }