Require the daemon secret and loopback Host/Origin on the design and iOS QA daemons (#4117)

* Require the daemon secret and loopback Host/Origin on the design and iOS QA daemons (GST-1747)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Name the changelog fragment after the branch (GST-1747)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: pre-landing review fixes

Review-Finding: p1/red-team#2 reader=red-team
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* fix: refuse cross-site browser requests on the iOS QA loopback, show the expired page for a stale board secret, refuse requests without a Host (GST-1747)

Review-Finding: v1/outside-voice#1 reader=outside-voice
Review-Finding: v1/adversarial-native#2 reader=adversarial-native
Review-Finding: v1/adversarial-native#5 reader=adversarial-native
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: show the secret segment in the documented design board URL (GST-1747)

Review-Finding: v1/adversarial-native#1 reader=adversarial-native
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* test: keep the daemon token fixtures on one line so the credential scan reads them as code (GST-1747)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* docs: cover the Sec-Fetch-Site refusal, the expired board page and the no-Host 403 in the changelog fragment (GST-1747)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-07 07:39:51 +00:00
1 parent de5cb247e0
commit 6cf00aee9c
21 files changed
+413 -89

No files matched your search

+54 -23
View File
@@ -7,16 +7,20 @@
* serve.ts as the default for `$D compare --serve`; serve.ts is kept as
* the --no-daemon legacy/test path.
*
* Endpoints (see plan docs/designs path for full table):
* GET / index of boards
* GET /health liveness + version (unauth)
* POST /api/boards publish a new board
* POST /shutdown graceful exit (refused if active)
* GET /boards/<id> 301 → /boards/<id>/
* GET /boards/<id>/ render board HTML
* GET /boards/<id>/api/progress state machine status
* POST /boards/<id>/api/feedback submit/regenerate
* POST /boards/<id>/api/reload swap board HTML
* Endpoints (see plan docs/designs path for full table). Every route but
* /health lives under /<secret>, the per-daemon token kept in the 0600 state
* file; published board URLs carry it, so board JS and the agent reach the
* board through the URL alone. Requests with a non-loopback Host or a
* cross-origin Origin are refused before routing.
* GET /health liveness + version (no secret)
* GET /<secret>/ index of boards
* POST /<secret>/api/boards publish a new board
* POST /<secret>/shutdown graceful exit (refused if active)
* GET /<secret>/boards/<id> 301 → /<secret>/boards/<id>/
* GET /<secret>/boards/<id>/ render board HTML
* GET /<secret>/boards/<id>/api/progress state machine status
* POST /<secret>/boards/<id>/api/feedback submit/regenerate
* POST /<secret>/boards/<id>/api/reload swap board HTML
*
* Lifecycle:
* start → bind 127.0.0.1:N → write state file → serve until 24h idle or
@@ -27,9 +31,12 @@
* Both are Codex-flagged guards against silent loss of in-memory history.
*/
import { randomBytes, timingSafeEqual } from "crypto";
import fs from "fs";
import path from "path";
import { loopbackRequestRefusal } from "../../lib/loopback-request";
import {
CMDLINE_MARKER,
DaemonState,
@@ -58,6 +65,8 @@ const IDLE_CHECK_INTERVAL_MS = parseInt(
const MAX_BOARDS = parseInt(process.env.DESIGN_DAEMON_MAX_BOARDS || "50", 10);
const VERSION = readVersionString();
const DAEMON_TOKEN = randomBytes(32).toString("hex");
const ROUTE_PREFIX = `/${DAEMON_TOKEN}`;
// ─── Per-board state ─────────────────────────────────────────────
@@ -252,7 +261,7 @@ function handleIndex(): Response {
.map((b) => {
const ts = new Date(b.publishedAt).toISOString();
const titleSuffix = b.title ? ` — ${escapeHtml(b.title)}` : "";
return `<li><a href="/boards/${b.id}/">${b.id}</a> <span class="state state-${b.state}">${b.state}</span> <time>${ts}</time>${titleSuffix}</li>`;
return `<li><a href="${ROUTE_PREFIX}/boards/${b.id}/">${b.id}</a> <span class="state state-${b.state}">${b.state}</span> <time>${ts}</time>${titleSuffix}</li>`;
})
.join("\n");
const empty = `<p class="empty">No boards yet. Run <code>$D compare --serve</code> to publish one.</p>`;
@@ -280,7 +289,7 @@ ${list}
return new Response(html, { headers: { "Content-Type": "text/html; charset=utf-8" } });
}
async function handlePublish(req: Request, origin: string): Promise<Response> {
async function handlePublish(req: Request, baseUrl: string): Promise<Response> {
let body: any;
try {
body = await req.json();
@@ -319,7 +328,7 @@ async function handlePublish(req: Request, origin: string): Promise<Response> {
error: "Source directory already in use by an active board",
existing: {
id: existing.id,
url: `${origin}/boards/${existing.id}/`,
url: `${baseUrl}/boards/${existing.id}/`,
state: existing.state,
},
},
@@ -355,7 +364,7 @@ async function handlePublish(req: Request, origin: string): Promise<Response> {
dlog(`published board ${id} sourceDir=${sourceDir} pid=${board.publisherPid}`);
return Response.json({
id,
url: `${origin}/boards/${id}/`,
url: `${baseUrl}/boards/${id}/`,
sourceDir,
});
}
@@ -458,14 +467,14 @@ async function handleBoardReload(board: Board, req: Request): Promise<Response>
return Response.json({ reloaded: true });
}
function boardExpiredHtml(id: string): string {
function boardExpiredHtml(id: string, indexLink = true): string {
return `<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>Board expired — gstack</title>
<style>body{font:14px/1.5 -apple-system,system-ui,sans-serif;max-width:600px;margin:80px auto;padding:0 20px;color:#1a1a1a;text-align:center}
h1{font-size:20px}.id{font-family:ui-monospace,monospace;color:#888;font-size:13px}
a{color:#0070f3;text-decoration:none}a:hover{text-decoration:underline}</style></head><body>
<h1>Board expired</h1>
<p>Board <span class="id">${escapeHtml(id)}</span> is no longer hosted by this daemon (evicted or the daemon restarted).</p>
<p><a href="/">← see active boards</a></p>
${indexLink ? `<p><a href="${ROUTE_PREFIX}/">← see active boards</a></p>` : ""}
</body></html>`;
}
@@ -474,14 +483,34 @@ a{color:#0070f3;text-decoration:none}a:hover{text-decoration:underline}</style><
const BOARD_RE = /^\/boards\/([A-Za-z0-9_-]+)(\/.*)?$/;
export async function fetchHandler(req: Request): Promise<Response> {
// Without a Host header Bun's req.url is a bare path; refuse it before parsing.
if (!URL.canParse(req.url)) return Response.json({ error: "host_not_loopback" }, { status: 403 });
const url = new URL(req.url);
const origin = url.origin;
const refusal = loopbackRequestRefusal(url.host, req.headers.get("origin"), serverRef?.port ?? Number(url.port));
if (refusal) return Response.json({ error: refusal }, { status: 403 });
if (req.method === "GET" && url.pathname === "/health") return handleHealth();
if (req.method === "GET" && url.pathname === "/") return handleIndex();
if (req.method === "POST" && url.pathname === "/api/boards") return handlePublish(req, origin);
if (req.method === "POST" && url.pathname === "/shutdown") {
const [, secret = "", ...rest] = url.pathname.split("/");
const presented = Buffer.from(secret);
const expected = Buffer.from(DAEMON_TOKEN);
if (presented.length !== expected.length || !timingSafeEqual(presented, expected)) {
// A board page opened from before a daemon restart carries the old
// secret: show the expired page, minus the link that would carry this one.
const stale = `/${rest.join("/")}`.match(BOARD_RE);
if (req.method === "GET" && stale && (stale[2] ?? "/") === "/") {
return new Response(boardExpiredHtml(stale[1]!, false), {
status: 401,
headers: { "Content-Type": "text/html; charset=utf-8" },
});
}
return Response.json({ error: "unauthorized" }, { status: 401 });
}
const pathname = `/${rest.join("/")}`;
if (req.method === "GET" && pathname === "/") return handleIndex();
if (req.method === "POST" && pathname === "/api/boards") return handlePublish(req, url.origin + ROUTE_PREFIX);
if (req.method === "POST" && pathname === "/shutdown") {
if (hasActiveBoards()) {
return Response.json(
{
@@ -495,7 +524,7 @@ export async function fetchHandler(req: Request): Promise<Response> {
return Response.json({ shuttingDown: true });
}
const m = url.pathname.match(BOARD_RE);
const m = pathname.match(BOARD_RE);
if (m) {
const id = m[1]!;
const subpath = m[2] || "";
@@ -511,7 +540,7 @@ export async function fetchHandler(req: Request): Promise<Response> {
if (req.method === "GET" && subpath === "") {
return new Response(null, {
status: 301,
headers: { Location: `/boards/${id}/` },
headers: { Location: `${ROUTE_PREFIX}/boards/${id}/` },
});
}
if (req.method === "GET" && subpath === "/") return handleBoardGet(board);
@@ -546,6 +575,7 @@ export function start(): { port: number } {
version: VERSION,
serverPath: process.argv[1] || "",
cmdlineMarker: CMDLINE_MARKER,
token: DAEMON_TOKEN,
};
writeStateFile(state);
dlog(`DAEMON_STARTED port=${actualPort} pid=${process.pid} version=${VERSION}`);
@@ -574,6 +604,7 @@ if (import.meta.main) {
// Exported for tests. Keep this small and stable.
export const __testInternals__ = {
token: DAEMON_TOKEN,
boards,
fetchHandler,
idleCheckTick,