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 { type WebSocket, WebSocketServer } from "ws";
import type { EventStore } from "./events";
import { listenHostFor, uiUrl } from "./network";
import type { UiCommandInfo, UiConnectionStatus, UiEvent } from "./protocol";
import { renderAppCss } from "./web/app.css";
import { renderAppHtml } from "./web/app.html";
import { renderAppJs } from "./web/app.js";

export type UiServerState = "waiting" | "connected" | "inactive" | "stopped";

export type UiServer = {
	baseUrl: string;
	publicUrl: string;
	port: number;
	token: string;
	state(): UiServerState;
	clients(): number;
	publish(event: UiEvent): void;
	close(reason: string): Promise<void>;
};

export type StartUiServerOptions = {
	address: string;
	token?: string;
	preferredPort?: number;
	onClientState?: (state: UiServerState) => void;
	events?: EventStore;
	snapshotStatus?: UiConnectionStatus;
	onBrowserMessage?: (message: unknown) => void | Promise<void>;
	commands?: UiCommandInfo[];
};

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 clientSeq = 0;
	let closed = false;
	const sockets = new Set<WebSocket>();
	const wss = new WebSocketServer({ noServer: true });
	const server = createServer((req, res) => {
		void dispatch(req, res, {
			token,
			events: options.events,
			snapshotStatus: options.snapshotStatus,
			commands: options.commands,
			state: () => currentState,
			clients: () => sockets.size,
			setState(next) {
				currentState = next;
				options.onClientState?.(next);
			},
		});
	});

	server.on("upgrade", (req, socket, head) => {
		const url = new URL(req.url ?? "/", "http://127.0.0.1");
		if (url.pathname !== "/ws" || !authorizedUrlOrRequest(url, req, token)) {
			socket.write("HTTP/1.1 401 Unauthorized\r\nConnection: close\r\n\r\n");
			socket.destroy();
			return;
		}
		wss.handleUpgrade(req, socket, head, (ws) => {
			const clientId = `client-${++clientSeq}`;
			sockets.add(ws);
			currentState = "connected";
			options.onClientState?.("connected");
			void options.onBrowserMessage?.({
				type: "lifecycle_reconnect",
				clientId,
			});
			const after = Number(url.searchParams.get("after") ?? 0);
			ws.send(
				JSON.stringify({
					type: "events",
					events:
						options.events?.replayAfter(Number.isFinite(after) ? after : 0) ??
						[],
				}),
			);
			ws.on("message", (data) => {
				try {
					const message = JSON.parse(String(data));
					if (
						message &&
						typeof message === "object" &&
						!("clientId" in message)
					) {
						message.clientId = clientId;
					}
					void options.onBrowserMessage?.(message);
				} catch {
					ws.send(JSON.stringify({ type: "error", message: "invalid json" }));
				}
			});
			ws.on("close", () => {
				sockets.delete(ws);
				currentState = sockets.size > 0 ? "connected" : "inactive";
				options.onClientState?.(currentState);
				void options.onBrowserMessage?.({ type: "lifecycle_close", clientId });
			});
		});
	});

	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: () => sockets.size,
		publish(event) {
			const payload = JSON.stringify({ type: "events", events: [event] });
			for (const ws of sockets) {
				if (ws.readyState === ws.OPEN) ws.send(payload);
			}
		},
		async close(reason) {
			void reason;
			if (closed) return;
			closed = true;
			currentState = "stopped";
			options.onClientState?.("stopped");
			for (const ws of sockets) ws.close();
			sockets.clear();
			wss.close();
			await closeServer(server);
		},
	};
}

type RouteContext = {
	token: string;
	events?: EventStore;
	snapshotStatus?: UiConnectionStatus;
	commands?: UiCommandInfo[];
	state(): UiServerState;
	clients(): number;
	setState(state: UiServerState): 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 === "/assets/app.js") {
			return text(res, 200, "text/javascript; charset=utf-8", renderAppJs());
		}
		if (req.method === "GET" && url.pathname === "/assets/app.css") {
			return text(res, 200, "text/css; charset=utf-8", renderAppCss());
		}
		if (req.method === "GET" && url.pathname === "/api/status") {
			return json(res, 200, { state: ctx.state(), clients: ctx.clients() });
		}
		if (req.method === "GET" && url.pathname === "/api/snapshot") {
			return json(
				res,
				200,
				ctx.events?.snapshot({
					status: ctx.snapshotStatus ?? ctx.state(),
					commands: ctx.commands,
				}) ?? {
					version: 1,
					lastEventId: 0,
					status: ctx.snapshotStatus ?? ctx.state(),
					commands: ctx.commands ?? [],
					events: [],
				},
			);
		}
		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 {
	void req;
	void url;
	res.setHeader(
		"Set-Cookie",
		`${COOKIE}=${ctx.token}; SameSite=Strict; Path=/`,
	);
	res.setHeader("Content-Type", "text/html; charset=utf-8");
	res.end(renderAppHtml());
}

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 authorizedUrlOrRequest(
	url: URL,
	req: IncomingMessage,
	token: string,
): boolean {
	return url.searchParams.get("token") === token || authorized(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 {
	text(res, status, "application/json; charset=utf-8", JSON.stringify(body));
}

function text(
	res: ServerResponse,
	status: number,
	contentType: string,
	body: string,
): void {
	res.statusCode = status;
	res.setHeader("Content-Type", contentType);
	res.end(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()));
	});
}