repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

pi/agent/extensions/diff-review/server.ts

Raw
File outline
import { randomBytes, randomUUID } from "node:crypto";
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
import { extname, join, normalize } from "node:path";
import { DEFAULT_TIMEOUT_MS, HEARTBEAT_LOST_MS, TOKEN_COOKIE } from "./constants.js";
import { staticDir } from "./bundle.js";
import type { BrowserResult, CollectedDiff, Finding, FindingDraft, ReviewPayload, ReviewSide, ReviewState } from "./types.js";

export type ReviewServer = {
	id: string;
	url: string;
	result: Promise<BrowserResult>;
	close(reason: Extract<BrowserResult, { type: "cancel" }>["reason"]): void;
};

type StartServerOptions = {
	diff: CollectedDiff;
	state: ReviewState;
	round: number;
	timeoutMs?: number;
	onHeartbeatLost?: () => void;
};

export async function startReviewServer(options: StartServerOptions): Promise<ReviewServer> {
	const token = randomBytes(32).toString("base64url");
	const id = randomUUID();
	let server: Server;
	let finished = false;
	let lastHeartbeatAt = Date.now();
	let heartbeatWarned = false;
	let resolveResult!: (result: BrowserResult) => void;
	const result = new Promise<BrowserResult>((resolve) => { resolveResult = resolve; });

	const finish = (next: BrowserResult) => {
		if (finished) return;
		finished = true;
		clearInterval(heartbeatTimer);
		clearTimeout(timeoutTimer);
		server.close();
		resolveResult(next);
	};

	const heartbeatTimer = setInterval(() => {
		if (!heartbeatWarned && Date.now() - lastHeartbeatAt > HEARTBEAT_LOST_MS) {
			heartbeatWarned = true;
			options.onHeartbeatLost?.();
		}
	}, 10_000);
	heartbeatTimer.unref();

	const timeoutTimer = setTimeout(() => finish({ type: "cancel", reason: "timeout" }), options.timeoutMs ?? DEFAULT_TIMEOUT_MS);
	timeoutTimer.unref();

	server = createServer(async (req, res) => {
		try {
			await handleRequest(req, res, token, options, (result) => {
				if (result.type === "heartbeat") {
					lastHeartbeatAt = Date.now();
					heartbeatWarned = false;
					return;
				}
				finish(result.result);
			});
		} catch (err) {
			json(res, 500, { error: (err as Error).message });
		}
	});

	await new Promise<void>((resolve, reject) => {
		server.once("error", reject);
		server.listen(0, "127.0.0.1", () => resolve());
	});
	const address = server.address();
	if (!address || typeof address === "string") throw new Error("Failed to bind review server");
	const url = `http://127.0.0.1:${address.port}/?token=${encodeURIComponent(token)}`;
	return { id, url, result, close: (reason) => finish({ type: "cancel", reason }) };
}

async function handleRequest(
	req: IncomingMessage,
	res: ServerResponse,
	token: string,
	options: StartServerOptions,
	finish: (result: { type: "heartbeat" } | { type: "submit"; result: BrowserResult } | { type: "cancel"; result: BrowserResult }) => void,
) {
	const url = new URL(req.url ?? "/", "http://127.0.0.1");
	if (req.method === "GET" && url.pathname === "/") return serveIndex(req, res, token, url);
	if (req.method === "GET" && url.pathname.startsWith("/static/")) return serveStatic(req, res, token, url.pathname.slice("/static/".length));

	if (!authorized(req, token)) return json(res, 401, { error: "unauthorized" });
	if (req.method === "GET" && url.pathname === "/api/review") {
		const payload: ReviewPayload = {
			round: options.round,
			source: options.diff.source,
			diffText: options.diff.diffText,
			files: options.diff.files,
			carriedFindings: options.state.findings.filter((finding) => finding.status === "open"),
		};
		return json(res, 200, payload);
	}
	if (req.method === "POST" && url.pathname === "/api/heartbeat") {
		finish({ type: "heartbeat" });
		return json(res, 200, { ok: true });
	}
	if (req.method === "POST" && url.pathname === "/api/cancel") {
		json(res, 200, { ok: true });
		finish({ type: "cancel", result: { type: "cancel", reason: "browser" } });
		return;
	}
	if (req.method === "POST" && url.pathname === "/api/finding/validate") {
		const draft = await readJson<FindingDraft>(req);
		const anchor = anchorForDraft(options.diff, draft);
		return json(res, 200, { ok: true, anchor });
	}
	if (req.method === "POST" && url.pathname === "/api/submit") {
		const body = await readJson<{ notes?: string; findings?: FindingDraft[] }>(req);
		const findings = (body.findings ?? []).map((draft) => findingFromDraft(options.round, options.diff, draft));
		json(res, 200, { ok: true });
		finish({ type: "submit", result: { type: "submit", notes: body.notes, findings } });
		return;
	}
	json(res, 404, { error: "not found" });
}

function serveIndex(_req: IncomingMessage, res: ServerResponse, token: string, url: URL) {
	if (url.searchParams.get("token") !== token) return json(res, 401, { error: "unauthorized" });
	res.setHeader("Set-Cookie", `${TOKEN_COOKIE}=${token}; SameSite=Strict; Path=/`);
	serveFile(res, join(staticDir(), "index.html"));
}

function serveStatic(req: IncomingMessage, res: ServerResponse, token: string, path: string) {
	if (!cookieAuthorized(req, token)) return json(res, 401, { error: "unauthorized" });
	const clean = normalize(path).replace(/^(\.\.(\/|\\|$))+/, "");
	serveFile(res, join(staticDir(), clean));
}

async function serveFile(res: ServerResponse, path: string) {
	try {
		const info = await stat(path);
		if (!info.isFile()) return json(res, 404, { error: "not found" });
		res.statusCode = 200;
		res.setHeader("Content-Type", contentType(path));
		res.setHeader("Cache-Control", "no-store");
		createReadStream(path).pipe(res);
	} catch {
		json(res, 404, { error: "not found" });
	}
}

function authorized(req: IncomingMessage, token: string) {
	return req.headers.authorization === `Bearer ${token}`;
}

function cookieAuthorized(req: IncomingMessage, token: string) {
	return (req.headers.cookie ?? "").split(/;\s*/).some((cookie) => cookie === `${TOKEN_COOKIE}=${token}`);
}

function json(res: ServerResponse, status: number, data: unknown) {
	res.statusCode = status;
	res.setHeader("Content-Type", "application/json; charset=utf-8");
	res.end(JSON.stringify(data));
}

function contentType(path: string) {
	switch (extname(path)) {
		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 ".json": return "application/json; charset=utf-8";
		case ".svg": return "image/svg+xml";
		default: return "application/octet-stream";
	}
}

function readJson<T>(req: IncomingMessage): Promise<T> {
	return new Promise((resolve, reject) => {
		let body = "";
		req.setEncoding("utf8");
		req.on("data", (chunk) => {
			body += chunk;
			if (body.length > 1024 * 1024) reject(new Error("request body too large"));
		});
		req.on("end", () => {
			try { resolve(body ? JSON.parse(body) as T : {} as T); }
			catch { reject(new Error("invalid JSON")); }
		});
		req.on("error", reject);
	});
}

function findingFromDraft(round: number, diff: CollectedDiff, draft: FindingDraft): Finding {
	return {
		id: randomUUID(),
		round,
		file: draft.file,
		...(draft.prevFile && { prevFile: draft.prevFile }),
		side: draft.side,
		startLine: draft.startLine,
		endLine: draft.endLine,
		category: draft.category,
		severity: draft.severity,
		comment: draft.comment.trim(),
		...(draft.notes?.trim() && { notes: draft.notes.trim() }),
		status: "open",
		anchor: anchorForDraft(diff, draft),
	};
}

function anchorForDraft(diff: CollectedDiff, draft: FindingDraft) {
	const file = diff.diffIndex.get(draft.file);
	if (!file) throw new Error(`Unknown file: ${draft.file}`);
	const lines = draft.side === "additions" ? file.additions : file.deletions;
	const selected: string[] = [];
	for (let line = draft.startLine; line <= draft.endLine; line++) {
		const text = lines.get(line);
		if (text === undefined) throw new Error(`Selected ${draft.side} line not found: ${draft.file}:${line}`);
		selected.push(text);
	}
	return {
		before: nearby(lines, draft.startLine - 3, draft.startLine - 1),
		selected: selected.join("\n"),
		after: nearby(lines, draft.endLine + 1, draft.endLine + 3),
	};
}

function nearby(lines: Map<number, string>, start: number, end: number) {
	const out: string[] = [];
	for (let line = start; line <= end; line++) {
		const text = lines.get(line);
		if (text !== undefined) out.push(text);
	}
	return out.join("\n");
}