#!/usr/bin/env node // Plan2Code Web Console - the HTTP server. // // Spawned DETACHED by console.mjs, never as a harness-managed background task: // those get killed on compaction, on a new prompt, and at assorted timeouts, // which would take the human's half-finished answers with them. // // It owns no durable state of its own. Everything lives in the session // directory, which is what makes the console survivable: the human can finish // the form even if the agent session died, and a fresh agent picks the result up. // // Node built-ins only. import fs from "node:fs"; import http from "node:http"; import os from "node:os"; import path from "node:path"; import crypto from "node:crypto"; import { CHAT_CURSOR_FILE, CHAT_FILE, LEDGER_FILE, LOOKS_FILE, PUBLIC_DIR, WORKSPACE_FILE, appendChat, appendEvent, chatForFrame, checkDocument, currentConversation, ensureDir, fileStamp, handleFile, initialWorkspace, nowIso, parseArgs, pendingChatCount, readChat, readCursor, readJson, readLedger, readOverview, readWorkspace, remoteWarning, typedCount, writeJsonAtomic, writeWorkspace, } from "./lib.mjs"; import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js"; import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js"; import { meterView } from "./public/meter.js"; import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js"; import { defaultName, freeName, nameProblem } from "./public/workspace.js"; import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs"; const args = parseArgs(process.argv.slice(2)); // Canonicalise before anything derives a path from it: a session dir reached // through a junction or a subst'd drive is watched under the wrong spelling, // which is the libuv assert described below. The native realpath resolves // those AND expands 8.3 short names, which lets the watcher run in a TEMP // spelled C:\Users\JUSTIN~1.PAR; the JS one is the fallback, and the watcher // still checks what it was given. const DIR = (() => { for (const real of [fs.realpathSync.native, fs.realpathSync]) { try { return real(args.session); } catch {} } return args.session; })(); if (!DIR) { process.stderr.write("server: --session is required\n"); process.exit(2); } const SID = path.basename(DIR); // No token, no server: authed() waves everything through on an empty one. A // bare `--token` (or one whose value parseArgs took for a flag) arrives as // `true`, so anything but a non-empty string is refused here, at boot. if (typeof args.token !== "string" || !args.token) { process.stderr.write("server: --token= is required (a non-empty string)\n"); process.exit(2); } const TOKEN = args.token; const PROJECT = args.project || process.cwd(); const IDLE_MS = Number(args["idle-ms"] || 30 * 60 * 1000); const MAX_LIFE_MS = Number(args["max-life-ms"] || 4 * 60 * 60 * 1000); const STATE_FILE = path.join(DIR, "state.json"); const DRAFT_FILE = path.join(DIR, "draft.json"); const RESULT_FILE = path.join(DIR, "result.json"); const CHAT_PATH = path.join(DIR, CHAT_FILE); const CURSOR_PATH = path.join(DIR, CHAT_CURSOR_FILE); // Images and documents attached to notes and quick questions. Only ever named // by the server (a UUID, plus `jpg` or an extension from DOC_TYPES), and only // ever resolved inside this directory: the client's file name is a label. // Only images are served back; a document is written, read by the agent from // disk, and deleted, never handed to a browser. const UPLOADS_DIR = path.join(DIR, "uploads"); const UPLOAD_EXTS = ["jpg", ...Object.keys(DOC_TYPES)]; const EXT_ALT = UPLOAD_EXTS.join("|"); const UPLOAD_ROUTE = /^\/uploads\/([0-9a-f-]{36})\.jpg$/; const UPLOAD_ANY_ROUTE = new RegExp(`^/uploads/([0-9a-f-]{36})\\.(${EXT_ALT})$`); const UPLOAD_NAME = new RegExp(`^[0-9a-f-]{36}\\.(${EXT_ALT})$`); function uploadPath(id, ext = "jpg") { if (!UPLOAD_EXTS.includes(ext)) return null; const result = path.join(UPLOADS_DIR, id + "." + ext); return path.resolve(result).startsWith(path.resolve(UPLOADS_DIR) + path.sep) ? result : null; } // "image" for one of this session's JPEGs, "file" for one of its documents, // false for anything else. function isOwnUpload(p) { if (typeof p !== "string") return false; const fold = (s) => (process.platform === "win32" ? s.toLowerCase() : s); const abs = path.resolve(p); const base = fold(path.basename(abs)); if (fold(path.dirname(abs)) !== fold(path.resolve(UPLOADS_DIR)) || !UPLOAD_NAME.test(base)) return false; return base.endsWith(".jpg") ? "image" : "file"; } // A client-supplied label, safe to put on a reply line: control characters // become spaces, since a newline in a file name would split the line in two. function cleanLabel(name, fallback) { return ( (typeof name === "string" ? name : "") .replace(/[\u0000-\u001f\u007f]/g, " ") .trim() .slice(0, 200) || fallback ); } // The file name the page sent, decoded but not yet cleaned or cut short. function rawUploadName(req) { try { return decodeURIComponent(req.headers["x-p2c-name"] || ""); } catch { return ""; } } function uploadLabel(req, fallback) { return cleanLabel(rawUploadName(req), fallback); } // Whether a send's `images` and `files` are this session's uploads of the // right kind, within the combined cap. Absent lists are fine. function attachmentsOk(images, files) { const listOk = (list, kind) => list === undefined || (Array.isArray(list) && list.every( (a) => a && typeof a === "object" && isOwnUpload(a.path) === kind && fs.existsSync(a.path) && (a.name === undefined || typeof a.name === "string") )); const count = (Array.isArray(images) ? images.length : 0) + (Array.isArray(files) ? files.length : 0); return { images: listOk(images, "image"), files: listOk(files, "file"), count: count <= MAX_ATTACHMENTS }; } const STARTED = Date.now(); let lastContact = Date.now(); let browsers = 0; let rev = 0; let seq = 0; /* ------------------------------------------------------------ mime types */ const TYPES = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".svg": "image/svg+xml", ".mp3": "audio/mpeg", ".png": "image/png", }; // A hardcoded allow-list, not a filesystem lookup. Nothing to traverse. const SERVABLE = new Set([ "app.js", "answers.js", "app.css", "render.js", "palette.js", "labels.js", "boot.js", "chat.js", "help.js", "starters.js", "workspace.js", "meter.js", "mentions.js", "favicon.js", "start-stop.mp3", "next.mp3", "insert.mp3", "sleeping.mp3", "bootup.mp3", "start-skill.mp3", "favicon.svg", "favicon.png", "vendor/marked.esm.js", ]); /* -------------------------------------------------------------- helpers */ // The state as last read, re-read only when its file has changed. Every // request, every SSE frame and the one-second poll used to read and parse // state.json afresh, and the state grows with the session (whole documents // live in it). A stat says whether anything moved; refreshing through // checkState also means a request that sees a new state first still counts // it as a new revision and tells every other tab. Callers must not mutate // what this returns -- /submit clones before it edits. function readState() { checkState(); return stateNow; } // Both facts about result.json from one read, cached the same way. The page's // heartbeat, every state frame and /submit's guard each asked for them, and // each used to read and parse the file twice. // // An answered-but-not-yet-collected result: while one exists the session is // mid-handoff, and the page must not send again and must say why. // A stop the person asked for that nothing has collected yet. Reported from // here rather than remembered by the page, because the page's memory is per // origin and a resumed session comes back on a new port: the one place that // still knows a stop is on its way is the result sitting on this disk. let resultSeen = { stamp: null, pending: false, stop: false }; function resultFlags() { const stamp = fileStamp(RESULT_FILE); if (stamp !== resultSeen.stamp) { let text = null; try { text = stamp ? fs.readFileSync(RESULT_FILE, "utf8") : null; } catch (err) { // There but unreadable for now (an antivirus lock, say). Never cached, // so the next call reads it again, and meanwhile it counts as pending: // a result nobody could read is exactly the one /submit must not // overwrite. if (err.code !== "ENOENT") return { ...resultSeen, pending: true }; } let r = null; try { r = text ? JSON.parse(text) : null; } catch {} const pending = Boolean(r && !r.consumedAt); resultSeen = { stamp, pending, stop: pending && Array.isArray(r.actions) && r.actions.some((a) => a && a.type === "stop"), }; } return resultSeen; } const pendingResult = () => resultFlags().pending; const pendingStop = () => resultFlags().stop; // The chat inbox as last parsed, re-read only when the file has moved: every // frame carries the conversation, and frames go out on every change. let chatSeen = { stamp: null, entries: [] }; function chatEntries() { const stamp = fileStamp(CHAT_PATH); if (stamp !== chatSeen.stamp) chatSeen = { stamp, entries: readChat(DIR) }; return chatSeen.entries; } // How far the agent has collected the inbox. console.mjs writes the cursor // when it hands entries over, so this is the "picked up, answering" signal the // Ask pane shows a spinner for. let cursorSeen = { stamp: null, seq: 0 }; function chatPickedUp() { const stamp = fileStamp(CURSOR_PATH); if (stamp !== cursorSeen.stamp) cursorSeen = { stamp, seq: readCursor(DIR) }; return cursorSeen.seq; } function chatOfflineNow(state) { return chatOffline({ finish: state && state.finish, agent: state && state.agent, agentLastSeenMs: agentSeenAt, now: Date.now(), }); } /* ------------------------------------------------------------ workspace */ // workspace.json has one writer, this server; ledger.ndjson has one, // console.mjs. Both are re-read only when their file has moved. const WORKSPACE_PATH = path.join(DIR, WORKSPACE_FILE); const LEDGER_PATH = path.join(DIR, LEDGER_FILE); const FOLD_CASE = process.platform === "win32" || process.platform === "darwin"; const foldPath = (p) => (FOLD_CASE ? p.toLowerCase() : p); let workspaceSeen = { stamp: null, ws: null }; // The session's workspace, created with just the original folder when absent. function workspaceNow() { const stamp = fileStamp(WORKSPACE_PATH); if (stamp && stamp === workspaceSeen.stamp) return workspaceSeen.ws; const ws = (stamp && readWorkspace(DIR)) || null; if (ws) { workspaceSeen = { stamp, ws }; return ws; } const fresh = initialWorkspace(stateNow?.worktree || PROJECT); // There but unreadable for now (a scanner's lock): never written over, and // never cached, so the next call reads it again. if (stamp) return workspaceSeen.ws || fresh; try { saveWorkspace(fresh); } catch {} return fresh; } function saveWorkspace(ws) { writeWorkspace(DIR, ws); workspaceSeen = { stamp: fileStamp(WORKSPACE_PATH), ws }; } // One change: a new version, an entry in the change log the agent is handed, // the file, and every open page. function bumpWorkspace(ws, change) { ws.version = (ws.version || 0) + 1; ws.changes = [...(ws.changes || []), { ...change, version: ws.version }]; saveWorkspace(ws); pushState(); } function isFolder(p) { try { return fs.statSync(p).isDirectory(); } catch { return false; } } // A folder deleted on disk is marked missing, and unmarked when it comes back. function checkFolders(ws) { ws.missing = ws.missing || []; for (const f of ws.folders) { const there = isFolder(f.path); const marked = ws.missing.includes(f.id); if (!there && !marked) { ws.missing = [...ws.missing, f.id]; bumpWorkspace(ws, { kind: "missing", name: f.name, path: f.path }); } else if (there && marked) { ws.missing = ws.missing.filter((id) => id !== f.id); bumpWorkspace(ws, { kind: "found", name: f.name, path: f.path }); } } } let ledgerSeen = { stamp: null, entries: [], launches: 0 }; function ledgerEntries() { const stamp = fileStamp(LEDGER_PATH); if (stamp !== ledgerSeen.stamp) { const entries = readLedger(DIR); ledgerSeen = { stamp, entries, launches: entries.filter((e) => e.kind === "launch").length }; } return ledgerSeen.entries; } // What the agent reported it could not read during the current skill run: // folder-issue entries after the last launch, the latest per folder name. function folderIssues(entries) { let from = 0; entries.forEach((e, i) => e.kind === "launch" && (from = i + 1)); const latest = new Map(); for (const e of entries.slice(from)) { if (e.kind !== "folder-issue") continue; latest.set(e.name, { name: e.name, reason: e.reason, ...(e.hint ? { hint: e.hint } : {}) }); } return [...latest.values()]; } function workspaceView() { const { folders, missing, remote } = workspaceNow(); return { folders, missing: missing || [], remote: remote || "", issues: folderIssues(ledgerEntries()) }; } // Whether child sits strictly under parent. function within(parent, child) { const rel = path.relative(foldPath(parent), foldPath(child)); return rel !== "" && rel !== ".." && !rel.startsWith(".." + path.sep) && !path.isAbsolute(rel); } const cleanDescription = (d) => (typeof d === "string" ? d.trim().slice(0, 200) : ""); function nextFolderId(ws) { const ns = ws.folders.map((f) => Number.parseInt(String(f.id).slice(1), 10)).filter(Number.isInteger); return "f" + (Math.max(-1, ...ns) + 1); } // Each route below answers with [status, body]; validation always comes // before any change, so a refusal leaves the file as it was. function addFolder(ws, body) { const raw = typeof body.path === "string" ? body.path.trim().replace(/^(["'])(.*)\1$/, "$2").trim() : ""; const input = raw.replace(/^~(?=$|[\\/])/, () => os.homedir()); const resolved = raw ? path.resolve(stateNow?.worktree || PROJECT, input) : ""; if (!resolved || !isFolder(resolved)) return [400, { reason: "not-a-folder" }]; const same = ws.folders.find((f) => foldPath(path.resolve(f.path)) === foldPath(resolved)); if (same) return [400, { reason: "duplicate", name: same.name }]; const nested = ws.folders.some((f) => within(f.path, resolved)); const name = typeof body.name === "string" && body.name ? body.name : defaultName(resolved); if (nameProblem(name)) return [400, { reason: "bad-name" }]; const taken = new Set(ws.folders.map((f) => f.name)); if (taken.has(name)) return [400, { reason: "name-taken", suggest: freeName(name, taken) }]; const entry = { id: nextFolderId(ws), path: resolved, name, description: cleanDescription(body.description), nested }; ws.folders = [...ws.folders, entry]; bumpWorkspace(ws, { kind: "added", name, path: resolved, description: entry.description }); return [200, entry]; } function editFolder(ws, body) { const entry = ws.folders.find((f) => f.id === body.id); if (!entry) return [404, { reason: "unknown" }]; const rename = typeof body.name === "string" && body.name !== entry.name; if (rename) { if (nameProblem(body.name)) return [400, { reason: "bad-name" }]; const taken = new Set(ws.folders.filter((f) => f !== entry).map((f) => f.name)); if (taken.has(body.name)) return [400, { reason: "name-taken", suggest: freeName(body.name, taken) }]; } const description = typeof body.description === "string" ? cleanDescription(body.description) : entry.description; if (rename) { const from = entry.name; entry.name = body.name; bumpWorkspace(ws, { kind: "renamed", from, name: entry.name, path: entry.path }); } if (description !== entry.description) { entry.description = description; bumpWorkspace(ws, { kind: "described", name: entry.name, path: entry.path, description }); } return [200, entry]; } function removeFolder(ws, body) { const entry = ws.folders.find((f) => f.id === body.id); if (entry && entry.original) return [400, { reason: "original" }]; if (!entry) return [404, { reason: "unknown" }]; ws.folders = ws.folders.filter((f) => f !== entry); ws.missing = (ws.missing || []).filter((id) => id !== entry.id); bumpWorkspace(ws, { kind: "removed", name: entry.name, path: entry.path }); return [200, { ok: true }]; } // Where the picker opens: beside the last folder added, else the original. function pickerStart(ws) { const added = ws.folders.filter((f) => !f.original); return added.length ? path.dirname(added[added.length - 1].path) : ws.folders[0]?.path || PROJECT; } // One picker at a time. Spawned, never spawnSync: the dialog can sit open for // minutes, and every poll, chat message and `wait` health check has to keep // being answered meanwhile. let pickerBusy = false; function bootWorkspace() { const ws = workspaceNow(); const remote = remoteWarning().remote || ""; if ((ws.remote || "") !== remote) { ws.remote = remote; saveWorkspace(ws); } checkFolders(ws); } /** * Open a conversation when there is none, and a new one whenever the page * passes through the dashboard. The reset line carries the workflow it was * opened under, so a server that restarts across a hop still sees the switch. * A resume that keeps its workflow keeps its conversation. */ function ensureConversation(state) { if (!state) return; const last = currentConversation(readChat(DIR)); let entry = null; if (!last.conversation) { entry = appendChat(DIR, { kind: "reset", conversation: 1, workflow: state.workflow, reason: "start" }); } else if (last.workflow !== state.workflow && (last.workflow === "dashboard" || state.workflow === "dashboard")) { entry = appendChat(DIR, { kind: "reset", conversation: last.conversation + 1, workflow: state.workflow, reason: "switch", }); } if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason }); } // What the page needs to draw itself, in the shape of the SSE state frame. // `have` names that exact view, for the page to hand back when it opens its // stream (see /events). function stateFrame(state) { const { pending, stop } = resultFlags(); return { rev, state, agentLastSeen: agentLastSeen(), pendingResult: pending, pendingStop: stop, chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) }, workspace: workspaceView(), meter: meterView(ledgerEntries()), have: haveKey(), }; } function haveKey() { const { pending, stop } = resultFlags(); chatEntries(); chatPickedUp(); workspaceNow(); ledgerEntries(); return ( `${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` + `.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}` ); } /** * Write what the person sent onto the item itself. * * The page shows a settled question's answer back to them, and the agent is * supposed to record one when it settles the question. This is the belt to that * braces: a model that forgets the `answer` field leaves someone staring at a * card marked "Settled" with nothing in it, and they cannot tell what they said. * * It never touches `status`. Only the agent decides when a question is settled, * and this must not look like an answer the agent has read. */ function recordSubmitted(state, actions) { if (!Array.isArray(state.items)) return; const at = nowIso(); for (const action of actions) { if (!action || typeof action !== "object" || action.type === "comment") continue; const item = state.items.find((i) => i && i.id === action.i); if (!item) continue; const { i, type, ...rest } = action; // JSON.parse makes "__proto__" an own property, and it would then be // written back into state.json and re-read forever. if (Object.prototype.hasOwnProperty.call(rest, "__proto__")) delete rest["__proto__"]; item.submitted = { at, ...rest }; } } function baseHeaders(extra = {}) { return { "cache-control": "no-store", "x-content-type-options": "nosniff", "referrer-policy": "no-referrer", ...extra, }; } function send(res, code, body, type = "application/json", extra = {}) { res.writeHead(code, baseHeaders({ "content-type": type, ...extra })); res.end(body); } function json(res, code, obj, extra = {}) { send(res, code, JSON.stringify(obj), "application/json", extra); } function timingSafeEq(a, b) { const ab = Buffer.from(String(a)); const bb = Buffer.from(String(b)); if (ab.length !== bb.length) return false; return crypto.timingSafeEqual(ab, bb); } // Named per port. Cookies ignore the port, so every console on 127.0.0.1 shares // one jar: under a single name, opening a second session overwrote the first // one's cookie and locked its tab out. function cookieName(port = PORT) { return `p2c_console_${port}`; } function cookieToken(req) { const raw = req.headers.cookie || ""; const name = cookieName(); for (const part of raw.split(";")) { const [k, ...v] = part.trim().split("="); if (k === name) return v.join("="); } return null; } function authed(req) { if (!TOKEN) return true; const c = cookieToken(req); return c ? timingSafeEq(c, TOKEN) : false; } /** * The DNS-rebinding defence, and the highest-value check in this file. * * Without it, any page the user visits can resolve its own hostname to * 127.0.0.1 and then talk to this server as same-origin. That is not * theoretical: it is the exact shape of Vite's GHSA-vg6x-rcgg-rjx6. */ function hostOk(req, port) { const host = req.headers.host; if (!host) return false; return host === `127.0.0.1:${port}` || host === `localhost:${port}`; } function originOk(req, port) { const origin = req.headers.origin; if (!origin) return true; // same-origin fetches and plain navigations send none return origin === `http://127.0.0.1:${port}` || origin === `http://localhost:${port}`; } function touch() { lastContact = Date.now(); } /** * Whittle a POSTed settings object down to what a settings file may hold. * The page only sends { theme, accent } today, but the file is shared and * forward-compatible: any flat string/number/boolean may live in it. Nested * objects, arrays and a hundred-key dump may not — this is a preference file, * not free storage, and it is read back into the page unfiltered. */ function cleanLooks(input) { if (!input || typeof input !== "object" || Array.isArray(input)) return null; const out = {}; for (const [k, v] of Object.entries(input)) { if (k === "__proto__" || k.length > 64) continue; const t = typeof v; if (t === "number" || t === "boolean" || (t === "string" && v.length <= 256)) out[k] = v; if (Object.keys(out).length > 40) return null; } return Object.keys(out).length ? out : null; } /* ---------------------------------------------------------------- assets */ // Read once per server, from memory after that. Held for the server's whole // life on purpose: a skill reinstalled under a running session must not hand // one page a new app.js beside the old answers.js it imports. // // Revalidated rather than stored: `no-cache` plus an ETag makes a reload a // round of 304s instead of 400KB again. Every session is a new port, and so a // new origin with a cold cache, which is why the first load is made cheap by // other means (preload hints, the inline boot state) rather than by caching. const assets = new Map(); function asset(rel) { let a = assets.get(rel); if (!a) { let body = fs.readFileSync(path.join(PUBLIC_DIR, rel)); if (rel === "app.css") body = Buffer.concat([body, Buffer.from(accentCss())]); const etag = `"${crypto.createHash("sha1").update(body).digest("base64url").slice(0, 20)}"`; a = { body, etag, type: TYPES[path.extname(rel)] || "application/octet-stream" }; assets.set(rel, a); } return a; } // The saved highlight color, painted from the very first frame. The page's // script owns the colors once it runs (applyLooks clears the attribute these // hang off), but until then the only way to avoid flashing the default rust // at someone who picked ocean is a stylesheet rule the server can switch on // with an attribute: the CSP forbids inline styles, and the colors live in // palette.js, so they are generated from there rather than copied into CSS. function accentCss() { const vars = (shades) => ["--accent", "--accent-soft", "--accent-ink", "--accent-line"].map((n, i) => `${n}:${shades[i]}`).join(";"); let css = "\n/* Generated by server.mjs from palette.js: the saved accent before app.js runs. */\n"; for (const [id, a] of Object.entries(ACCENTS)) { if (id === DEFAULT_ACCENT) continue; const sel = `:root[data-looks-accent="${id}"]`; css += `${sel}{${vars(a.light)}}\n`; css += `@media (prefers-color-scheme: dark){${sel}:not([data-theme="light"]){${vars(a.dark)}}}\n`; css += `${sel}[data-theme="dark"]{${vars(a.dark)}}\n`; } return css; } // looks.json, re-read only when it changes: it is read into every page load. let looksSeen = { stamp: null, looks: null }; function savedLooks() { const stamp = fileStamp(LOOKS_FILE); if (stamp !== looksSeen.stamp) { const saved = stamp ? readJson(LOOKS_FILE, null) : null; looksSeen = { stamp, looks: saved && saved.looks && typeof saved.looks === "object" ? saved.looks : null }; } return looksSeen.looks; } const escHtml = (s) => String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]); let indexTemplate = null; /** * The page, with everything the first paint needs already in it. * * The page used to arrive as a blank template that said "Pathfinder" and * "Connecting…" whatever the session was, then fetch /state, then /looks, and * only then draw anything real. Now the server writes the session's name, * badge and theme into the markup and the whole first state into an inline * JSON block, so the script draws the real screen the moment it runs, with no * round trip in between. The block is data, not script: `application/json` * is never executed, so the CSP's ban on inline script stands untouched. * Every `<` in it is escaped, which is what keeps a `` inside some * agent-written text from closing the block early. */ function renderIndex() { if (indexTemplate === null) indexTemplate = fs.readFileSync(path.join(PUBLIC_DIR, "index.html"), "utf8"); const state = readState(); const looks = savedLooks(); const boot = { ...stateFrame(state), draft: readJson(DRAFT_FILE, {}), looks, }; let htmlAttrs = ""; if (looks && (looks.theme === "light" || looks.theme === "dark")) htmlAttrs += ` data-theme="${looks.theme}"`; if (looks && looks.accent !== DEFAULT_ACCENT && Object.hasOwn(ACCENTS, String(looks.accent))) { htmlAttrs += ` data-looks-accent="${looks.accent}"`; } // The same first-paint reasoning as the accent: a Wide user never sees the // column jump from the default width. The value is one of the fixed preset // keys, so there is nothing to escape. if (looks && cardWidth(looks.width) !== DEFAULT_CARD_WIDTH) { htmlAttrs += ` data-width="${cardWidth(looks.width)}"`; } const title = (state && state.title) || "Session"; const workflow = state && state.workflow; const json = JSON.stringify(boot).replace(/', () => ``) .replace("Plan2Code Console", () => `${escHtml(title)} · Plan2Code`) .replace('

Plan2Code Console

', () => `

${escHtml(title)}

`) .replace( 'Pathfinder', () => `${escHtml(workflowLabel(workflow))}` ) .replace( '

Opening the console

', () => `

${escHtml( workflow === "dashboard" ? "Opening the dashboard" : `Starting ${workflowTitle(workflow)}` )}

` ) .replace("", () => ``); } /* ------------------------------------------------------------------ SSE */ // Exactly one stream per page. Browsers cap HTTP/1.1 at ~6 connections per // origin, and an open stream holds one permanently; a second stream per tab // across three tabs wedges the origin with no error and no timeout. Everything // is multiplexed through this one channel with a `type` field. const clients = new Set(); function broadcast(type, data) { seq++; const payload = `id: ${seq}\nevent: ${type}\ndata: ${JSON.stringify(data)}\n\n`; for (const res of clients) { try { res.write(payload); } catch { clients.delete(res); } } } function pushState() { if (stateNow) broadcast("state", stateFrame(stateNow)); } let agentSeenAt = Date.now(); function agentLastSeen() { return new Date(agentSeenAt).toISOString(); } /* --------------------------------------------------------------- routes */ // The port this server answers on. Known before the server is: a handed-over // socket was bound by console.mjs, so `server.address()` has nothing to say. let PORT = 0; const server = http.createServer((req, res) => { const port = PORT; const url = new URL(req.url, `http://127.0.0.1:${port}`); const pathname = url.pathname; if (!hostOk(req, port)) return send(res, 403, "", "text/plain"); // /health is the liveness probe the CLI uses to distinguish "our server" // from a process that merely inherited the PID. Deliberately unauthenticated // and deliberately tells you nothing but the session id. if (pathname === "/health") { touch(); agentSeenAt = Date.now(); return json(res, 200, { ok: true, sid: SID, browsers, rev, phase: readState()?.phase || "unknown" }); } // Token in the PATH, not the query string. Two reasons: a query string would // put an `&` in the URL, and `cmd /c start ` on Windows parses `&` as a // command separator; and the 302 below gets the secret out of the address bar, // out of history, and out of any screenshot the user pastes into a ticket. if (pathname.startsWith("/s/")) { const given = pathname.slice(3).replace(/\/$/, ""); if (!TOKEN || !timingSafeEq(given, TOKEN)) return send(res, 403, "Not found", "text/plain"); touch(); res.writeHead( 302, baseHeaders({ location: "/", "set-cookie": `${cookieName(port)}=${TOKEN}; HttpOnly; SameSite=Strict; Path=/`, }) ); return res.end(); } if (!authed(req)) return send(res, 403, "Open the link the terminal printed.", "text/plain"); touch(); if (pathname === "/" && req.method === "GET") { let html; try { html = renderIndex(); } catch { return send(res, 500, "index.html missing", "text/plain"); } // No 'unsafe-inline'. That is why the client is separate .js/.css files // rather than one inlined page: it makes an injected inline