import { randomUUID } from "node:crypto"; import { createReadStream, lstatSync, realpathSync, rmSync } from "node:fs"; import { createServer, type IncomingMessage, type Server, type ServerResponse, } from "node:http"; import path from "node:path"; import { type BoardItemState, type BoardProposal, readBoardState, updateBoardState, writeBoardState, } from "./board-state.ts"; import type { ProjectIndex } from "./project-index.ts"; const BODY_LIMIT = 64 * 1024; const COOKIE = "the_system_board"; const STATES = ["todo", "done", "open"] as const; export type BoardServer = Readonly<{ url: string; close(): void }>; export async function startBoardServer( directory: string, index: ProjectIndex, proposals: Map, ): Promise { const token = `${randomUUID()}-${randomUUID()}`; const cookieName = `${COOKIE}_${token.slice(0, 8)}`; let server!: Server; let mutation = Promise.resolve(); const enqueue = (work: () => T): Promise => { const result = mutation.then(work, work); mutation = result.then( () => undefined, () => undefined, ); return result; }; server = createServer((request, response) => { void dispatch(request, response, { directory, index, proposals, token, cookieName, enqueue, }); }); await new Promise((resolve, reject) => { server.once("error", reject); server.listen(0, "127.0.0.1", () => { server.off("error", reject); resolve(); }); }); const address = server.address(); if (!address || typeof address === "string") throw new Error("Failed to bind System board server"); return { url: `http://127.0.0.1:${address.port}/?k=${token}`, close() { server.close(); rmSync(directory, { recursive: true, force: true }); }, }; } type DispatchState = Readonly<{ directory: string; index: ProjectIndex; proposals: Map; token: string; cookieName: string; enqueue(work: () => T): Promise; }>; async function dispatch( request: IncomingMessage, response: ServerResponse, state: DispatchState, ): Promise { try { const url = new URL(request.url ?? "/", "http://127.0.0.1"); const queryToken = url.searchParams.get("k"); const cookieToken = cookie(request.headers.cookie ?? "", state.cookieName); if (queryToken === state.token) { response.statusCode = 303; response.setHeader("Location", url.pathname); response.setHeader( "Set-Cookie", `${state.cookieName}=${state.token}; HttpOnly; SameSite=Strict; Path=/`, ); response.end(); return; } if (cookieToken !== state.token) { respondJson(response, 403, { error: "Forbidden" }); return; } if ( request.method === "POST" && request.headers.origin !== `http://${request.headers.host}` ) { respondJson(response, 403, { error: "Invalid board origin" }); return; } if (request.method === "POST" && url.pathname === "/api/state") { const input = await readJsonBody(request); const result = await state.enqueue(() => applyState(state.index, input, "manual"), ); respondJson(response, 200, result); return; } if (request.method === "POST" && url.pathname === "/api/proposal") { const input = await readJsonBody(request); if (typeof input.id !== "string" || typeof input.state !== "string") throw new Error("Expected assessment proposal with id and state"); const proposal = state.proposals.get(input.id); if (!proposal || proposal.state !== input.state) throw new Error(`No matching assessment proposal: ${input.id}`); const result = await state.enqueue(() => applyState(state.index, input, "assess"), ); state.proposals.delete(input.id); respondJson(response, 200, result); return; } if (request.method !== "GET") { respondJson(response, 405, { error: "Method not allowed" }); return; } serveFile(response, state.directory, url.pathname); } catch (error) { respondJson(response, 400, { error: error instanceof Error ? error.message : String(error), }); } } function applyState( index: ProjectIndex, input: Record, source: "manual" | "assess", ) { if ( Object.keys(input).some((key) => key !== "id" && key !== "state") || typeof input.id !== "string" || typeof input.state !== "string" || !STATES.includes(input.state as (typeof STATES)[number]) ) throw new Error("Expected board update with id and state"); const current = readBoardState(index.root, index.prefix); const updated = updateBoardState( current, index.documents, input.id, input.state as BoardItemState, source, ); writeBoardState(index.root, updated); return { items: updated.items }; } function readJsonBody( request: IncomingMessage, ): Promise> { return new Promise((resolve, reject) => { let source = ""; request.setEncoding("utf8"); request.on("data", (chunk: string) => { source += chunk; if (Buffer.byteLength(source) > BODY_LIMIT) { request.destroy(); reject(new Error("Board request body is too large")); } }); request.on("end", () => { try { const parsed = JSON.parse(source); if ( typeof parsed !== "object" || parsed === null || Array.isArray(parsed) ) throw new Error("Board request body must be an object"); resolve(parsed as Record); } catch (error) { reject(error); } }); request.on("error", reject); }); } function serveFile( response: ServerResponse, directory: string, pathname: string, ): void { const relative = decodeURIComponent( pathname === "/" ? "index.html" : pathname.slice(1), ); const target = path.resolve(directory, relative); const inside = path.relative(directory, target); if ( inside === ".." || inside.startsWith(`..${path.sep}`) || path.isAbsolute(inside) ) { respondJson(response, 404, { error: "Not found" }); return; } const stats = lstatSync(target, { throwIfNoEntry: false }); if (!stats?.isFile() || stats.isSymbolicLink()) { respondJson(response, 404, { error: "Not found" }); return; } const realRoot = realpathSync(directory); const realTarget = realpathSync(target); const realInside = path.relative(realRoot, realTarget); if ( realInside === ".." || realInside.startsWith(`..${path.sep}`) || path.isAbsolute(realInside) ) { respondJson(response, 404, { error: "Not found" }); return; } response.statusCode = 200; response.setHeader("Content-Type", contentType(target)); response.setHeader("Cache-Control", "no-store"); createReadStream(target).pipe(response); } function contentType(file: string): string { switch (path.extname(file).toLowerCase()) { case ".html": return "text/html; charset=utf-8"; case ".js": return "text/javascript; charset=utf-8"; case ".css": return "text/css; charset=utf-8"; case ".svg": return "image/svg+xml"; case ".png": return "image/png"; case ".jpg": case ".jpeg": return "image/jpeg"; case ".gif": return "image/gif"; case ".webp": return "image/webp"; default: return "application/octet-stream"; } } function respondJson( response: ServerResponse, status: number, value: unknown, ): void { if (response.headersSent) return; response.statusCode = status; response.setHeader("Content-Type", "application/json; charset=utf-8"); response.setHeader("Cache-Control", "no-store"); response.end(JSON.stringify(value)); } function cookie(source: string, name: string): string | undefined { for (const part of source.split(";")) { const [key, ...value] = part.trim().split("="); if (key === name) return value.join("="); } return undefined; }