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

+2 -1
View File
@@ -375,7 +375,7 @@ async function main(): Promise<void> {
* Stderr lines (in order):
* - "DAEMON_STARTED port=N version=V" (or "DAEMON_ATTACHED port=N ..."
* if a daemon was already running)
* - "BOARD_PUBLISHED: http://127.0.0.1:N/boards/<id>/"
* - "BOARD_PUBLISHED: http://127.0.0.1:N/<secret>/boards/<id>/"
* - "BOARD_URL: <same url>" (alias for grep-friendliness)
* - "SERVE_STARTED: port=N html=<path>" (legacy back-compat alias for
* any external script that scraped the pre-daemon output — note the
@@ -395,6 +395,7 @@ async function publishToDaemon(opts: { html: string; title?: string }): Promise<
);
const result = await publishBoard({
port: ensured.port,
token: ensured.token,
html: opts.html,
title: opts.title,
});
+4 -1
View File
@@ -535,7 +535,10 @@ export function generateCompareHtml(images: string[]): string {
return;
}
fetch('./api/progress')
.then(function(r) { return r.json(); })
.then(function(r) {
if (!r.ok) throw new Error('progress ' + r.status);
return r.json();
})
.then(function(data) {
if (data.status === 'serving') {
clearInterval(pollInterval);
+29 -17
View File
@@ -33,6 +33,7 @@ import { setTimeout as delay } from "timers/promises";
import {
acquireLock,
CMDLINE_MARKER,
type DaemonState,
healthCheck,
isProcessAlive,
readStateFile,
@@ -70,6 +71,7 @@ export interface EnsureDaemonOptions {
export interface EnsureDaemonResult {
port: number;
token: string;
version: string;
spawned: boolean;
}
@@ -97,14 +99,19 @@ export async function ensureDaemon(
if (existing) {
const health = await healthCheck(existing.port);
if (health) {
if (health.version === expectedVersion) {
if (health.version === expectedVersion && existing.token) {
log(verbose, `attached to existing daemon pid=${existing.pid} port=${existing.port}`);
return { port: existing.port, version: health.version, spawned: false };
return { port: existing.port, token: existing.token, version: health.version, spawned: false };
}
// Version mismatch: refuse if active boards exist (Codex finding).
// Version mismatch, or a daemon from before per-daemon secrets: refuse if
// active boards exist (Codex finding).
if (health.activeBoards > 0) {
const mismatch =
health.version === expectedVersion
? `existing daemon (gstack ${health.version}) predates per-daemon secrets`
: `existing daemon is gstack ${health.version}; this CLI is ${expectedVersion}`;
process.stderr.write(
`[design-daemon] WARNING: existing daemon is gstack ${health.version}; this CLI is ${expectedVersion}.\n` +
`[design-daemon] WARNING: ${mismatch}.\n` +
`[design-daemon] ${health.activeBoards} active board(s) detected. Refusing to auto-kill.\n` +
`[design-daemon] Submit or close the open boards, then re-run.\n` +
`[design-daemon] Or force restart: $D daemon stop (will drop in-memory history).\n`,
@@ -113,7 +120,7 @@ export async function ensureDaemon(
}
// No active boards — safe to graceful-shutdown and respawn.
log(verbose, `daemon version mismatch (${health.version} vs ${expectedVersion}); shutting down`);
await gracefulShutdownExistingDaemon(existing.port);
await gracefulShutdownExistingDaemon(existing.port, existing.token);
await killByPidWithIdentity(existing.pid, existing.cmdlineMarker, verbose);
} else {
// State file points at an unresponsive port. Either the daemon
@@ -136,7 +143,7 @@ export async function ensureDaemon(
const fresh = readStateFile(stateFile);
if (fresh) {
const h = await healthCheck(fresh.port);
if (h) return { port: fresh.port, version: h.version, spawned: false };
if (h && fresh.token) return { port: fresh.port, token: fresh.token, version: h.version, spawned: false };
}
await delay(POLL_INTERVAL_MS);
}
@@ -149,20 +156,20 @@ export async function ensureDaemon(
const fresh = readStateFile(stateFile);
if (fresh) {
const h = await healthCheck(fresh.port);
if (h && h.version === expectedVersion) {
if (h && h.version === expectedVersion && fresh.token) {
log(verbose, `another CLI won the lock; attaching pid=${fresh.pid} port=${fresh.port}`);
return { port: fresh.port, version: h.version, spawned: false };
return { port: fresh.port, token: fresh.token, version: h.version, spawned: false };
}
}
log(verbose, "spawning new daemon");
const port = await spawnDaemon({
const spawned = await spawnDaemon({
script: opts.daemonScript,
env: { ...opts.daemonEnv, DESIGN_DAEMON_STATE_FILE: stateFile },
stateFile,
expectedVersion,
});
return { port, version: expectedVersion, spawned: true };
return { port: spawned.port, token: spawned.token, version: expectedVersion, spawned: true };
} finally {
release();
}
@@ -174,6 +181,8 @@ export async function ensureDaemon(
*/
export interface PublishBoardOptions {
port: number;
/** The daemon's secret from its state file (EnsureDaemonResult.token). */
token: string;
html: string;
title?: string;
publisherPid?: number;
@@ -191,7 +200,7 @@ export async function publishBoard(opts: PublishBoardOptions): Promise<PublishBo
publisherPid: opts.publisherPid ?? process.pid,
};
if (opts.title) body.title = opts.title;
const resp = await fetch(`http://127.0.0.1:${opts.port}/api/boards`, {
const resp = await fetch(`http://127.0.0.1:${opts.port}/${opts.token}/api/boards`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
@@ -265,7 +274,7 @@ interface SpawnDaemonOpts {
expectedVersion: string;
}
async function spawnDaemon(opts: SpawnDaemonOpts): Promise<number> {
async function spawnDaemon(opts: SpawnDaemonOpts): Promise<DaemonState> {
const logPath = resolveStartupLogPath();
fs.mkdirSync(path.dirname(logPath), { recursive: true });
// Truncate the startup log on each spawn so a later read finds only THIS
@@ -291,9 +300,9 @@ async function spawnDaemon(opts: SpawnDaemonOpts): Promise<number> {
const deadline = Date.now() + MAX_START_WAIT_MS;
while (Date.now() < deadline) {
const fresh = readStateFile(opts.stateFile);
if (fresh) {
if (fresh?.token) {
const h = await healthCheck(fresh.port);
if (h) return fresh.port;
if (h) return fresh;
}
await delay(POLL_INTERVAL_MS);
}
@@ -312,9 +321,12 @@ async function spawnDaemon(opts: SpawnDaemonOpts): Promise<number> {
);
}
async function gracefulShutdownExistingDaemon(port: number): Promise<void> {
async function gracefulShutdownExistingDaemon(port: number, token: string | undefined): Promise<void> {
// A daemon from before per-daemon secrets has no token; the caller's
// identity-checked SIGTERM stops it instead.
if (!token) return;
try {
await fetch(`http://127.0.0.1:${port}/shutdown`, {
await fetch(`http://127.0.0.1:${port}/${token}/shutdown`, {
method: "POST",
signal: AbortSignal.timeout(2000),
});
@@ -390,7 +402,7 @@ export async function shutdownDaemon(opts: { force?: boolean } = {}): Promise<{
activeBoards: health.activeBoards,
};
}
await gracefulShutdownExistingDaemon(existing.port);
await gracefulShutdownExistingDaemon(existing.port, existing.token);
// Best-effort: SIGTERM if /shutdown didn't take effect
if (isProcessAlive(existing.pid)) {
await killByPidWithIdentity(existing.pid, existing.cmdlineMarker, true);
+1
View File
@@ -20,6 +20,7 @@ export interface DaemonState {
version: string;
serverPath: string;
cmdlineMarker: string;
token: string; // per-daemon secret; every route but /health lives under /<token>
}
// String we grep for in the spawned daemon's cmdline to confirm a pid is
+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,