repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/ui/server.ts

Raw
File outline
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<void>;
};

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<UiServer> {
	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<void> {
	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 `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pi UI shell</title>
<style>
:root { color-scheme: light dark; font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: Canvas; color: CanvasText; }
main { border: 4px solid CanvasText; padding: 24px; max-width: 720px; }
h1 { margin: 0 0 12px; }
code { border: 1px solid color-mix(in srgb, CanvasText 40%, transparent); padding: 2px 4px; }
</style>
</head>
<body>
<main>
<h1>Pi UI shell</h1>
<p>Phase 1 server is running. RPC stream arrives in a later phase.</p>
<p>Return to terminal and run <code>/ui off</code> to stop.</p>
</main>
</body>
</html>`;
}

function serveUnauthorized(res: ServerResponse): void {
	res.statusCode = 401;
	res.setHeader("Content-Type", "text/html; charset=utf-8");
	res.end(
		"<!doctype html><title>Unauthorized</title><h1>Unauthorized</h1><p>Open the exact /ui link or scan the current QR code again.</p>",
	);
}

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<void> {
	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<void> {
	return new Promise((resolve, reject) => {
		server.close((error) => (error ? reject(error) : resolve()));
	});
}