From 2c3571ad445d1e5e942251271ffed422485381e8 Mon Sep 17 00:00:00 2001 From: garrytan Date: Wed, 30 Sep 2026 05:45:25 +0000 Subject: [PATCH 1/5] test(browse): black-box auth matrix for every server route and both surfaces Drives buildFetchHandler fetchLocal/fetchTunnel with no token, wrong token, root token, scoped token and the SSE cookie for all 33 routes, plus unmatched paths and wrong methods. Denials assert today's exact status, body and content type; allowed credentials assert the handler was reached. Written against the unchanged if-chain server so the W3 route-table refactor must keep it green. --- .../test/server-route-auth-blackbox.test.ts | 267 ++++++++++++++++++ 1 file changed, 267 insertions(+) create mode 100644 browse/test/server-route-auth-blackbox.test.ts diff --git a/browse/test/server-route-auth-blackbox.test.ts b/browse/test/server-route-auth-blackbox.test.ts new file mode 100644 index 000000000..a1b0e5fa7 --- /dev/null +++ b/browse/test/server-route-auth-blackbox.test.ts @@ -0,0 +1,267 @@ +/** + * Black-box auth matrix for the browse daemon's HTTP surface. + * + * Drives buildFetchHandler(...).fetchLocal / fetchTunnel for every route the + * daemon serves, on both surfaces, with no token, a wrong token, the root + * token, a scoped token and the view-only SSE cookie. Denials assert the exact + * status, body and content type the server returns; allowed credentials assert + * that the response is not one of the gate denials (the handler was reached). + * + * This file is deliberately independent of how server.ts is organized: it was + * written against the if-chain server and must pass unchanged against the + * route-table server. Do not edit it to follow a refactor; a failing row here + * means a route's observable auth behavior changed. + */ + +import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; +import * as crypto from 'crypto'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { buildFetchHandler, GSTACK_EXTENSION_ID, type ServerConfig, type ServerHandle } from '../src/server'; +import { __resetRegistry, __resetConnectRateLimit, createToken } from '../src/token-registry'; +import { mintSseSessionToken, SSE_COOKIE_NAME } from '../src/sse-session-cookie'; +import { BrowserManager } from '../src/browser-manager'; +import { resolveConfig } from '../src/config'; + +const fixtureDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-route-blackbox-')); +const fixtureConfig = resolveConfig({ BROWSE_STATE_FILE: path.join(fixtureDir, 'state/browse.json') }); + +type Cred = 'none' | 'wrong' | 'root' | 'scoped' | 'sse-cookie'; +const CREDS: Cred[] = ['none', 'wrong', 'root', 'scoped', 'sse-cookie']; + +interface Denial { status: number; body: string; contentType: string } +const JSON_CT = 'application/json'; +const json = (status: number, body: unknown): Denial => ({ status, body: JSON.stringify(body), contentType: JSON_CT }); + +const UNAUTHORIZED = json(401, { error: 'Unauthorized' }); +const ROOT_REQUIRED = json(403, { error: 'Root token required' }); +const FORBIDDEN = json(403, { error: 'Forbidden' }); +const MINT_ROOT_ONLY = json(403, { error: 'Only the root token can mint sub-tokens' }); +const TUNNEL_NOT_FOUND = json(404, { error: 'Not found' }); +const TUNNEL_ROOT_REJECTED = json(403, { + error: 'Root token rejected on tunnel surface', + hint: 'Remote agents must pair via /connect to receive a scoped token.', +}); +// A bare string Response carries no explicit Content-Type header until Bun serializes it. +const LOCAL_NOT_FOUND: Denial = { status: 404, body: 'Not found', contentType: '' }; +const PICKER_ACCESS_DENIED: Denial = { + status: 403, body: 'Access denied. Open the cookie picker from gstack.', contentType: 'text/plain', +}; +const GATE_DENIALS = [UNAUTHORIZED, ROOT_REQUIRED, FORBIDDEN, MINT_ROOT_ONLY, TUNNEL_NOT_FOUND, TUNNEL_ROOT_REJECTED]; + +/** + * How a route authenticates today, as observed from outside. `open` routes + * admit every credential; the rest deny every credential except the listed + * ones with the listed denial. + */ +type Policy = + | { kind: 'open' } + | { kind: 'deny'; allow: Cred[]; denial: Denial }; + +const OPEN: Policy = { kind: 'open' }; +const ROOT_BEARER: Policy = { kind: 'deny', allow: ['root'], denial: UNAUTHORIZED }; +const ROOT_TOKEN: Policy = { kind: 'deny', allow: ['root'], denial: ROOT_REQUIRED }; +const SCOPED: Policy = { kind: 'deny', allow: ['root', 'scoped'], denial: UNAUTHORIZED }; +const ROOT_OR_SSE_COOKIE: Policy = { kind: 'deny', allow: ['root', 'sse-cookie'], denial: UNAUTHORIZED }; + +interface RouteRow { + method: string; + path: string; + /** Request body for every credential; keeps allowed calls on a cheap, side-effect-free branch. */ + body?: string; + local: Policy; + /** True for the two paths the tunnel surface admits (TUNNEL_PATHS). */ + tunnel?: 'connect' | 'command'; + /** SSE responses stream forever; the test cancels them after the status line. */ + stream?: boolean; +} + +const ROUTES: RouteRow[] = [ + { method: 'GET', path: '/connect', local: OPEN, tunnel: 'connect' }, + { method: 'POST', path: '/connect', body: '{}', local: OPEN, tunnel: 'connect' }, + { method: 'GET', path: '/cookie-picker', local: { kind: 'deny', allow: [], denial: PICKER_ACCESS_DENIED } }, + { method: 'GET', path: '/cookie-picker/imported', local: ROOT_BEARER }, + { method: 'OPTIONS', path: '/cookie-picker/imported', local: OPEN }, + { method: 'GET', path: '/welcome', local: OPEN }, + { method: 'POST', path: '/extension-token', local: { kind: 'deny', allow: [], denial: FORBIDDEN } }, + { method: 'GET', path: '/health', local: OPEN }, + { method: 'POST', path: '/pty-session', local: ROOT_BEARER }, + { method: 'POST', path: '/pty-session/reattach', body: '{}', local: ROOT_BEARER }, + { method: 'POST', path: '/pty-restart', body: '{}', local: ROOT_BEARER }, + { method: 'POST', path: '/pty-dispose', body: '{}', local: ROOT_BEARER }, + { method: 'POST', path: '/internal/lease-refresh', body: '{}', local: ROOT_BEARER }, + { method: 'POST', path: '/pty-inject-scan', local: ROOT_BEARER }, + { method: 'POST', path: '/token', body: 'not json', local: { kind: 'deny', allow: ['root'], denial: MINT_ROOT_ONLY } }, + { method: 'DELETE', path: '/token/matrix-nobody', local: ROOT_TOKEN }, + { method: 'GET', path: '/agents', local: ROOT_TOKEN }, + { method: 'POST', path: '/pair', body: 'not json', local: ROOT_TOKEN }, + { method: 'POST', path: '/tunnel/start', local: ROOT_TOKEN }, + { method: 'POST', path: '/sse-session', local: ROOT_BEARER }, + { method: 'GET', path: '/refs', local: ROOT_BEARER }, + { method: 'GET', path: '/activity/stream', local: ROOT_OR_SSE_COOKIE, stream: true }, + { method: 'GET', path: '/activity/history', local: ROOT_BEARER }, + { method: 'POST', path: '/batch', body: '{"commands":[]}', local: SCOPED }, + { method: 'GET', path: '/file', local: SCOPED }, + { method: 'POST', path: '/command', body: '{"command":"__matrix_unknown__"}', local: SCOPED, tunnel: 'command' }, + { method: 'POST', path: '/inspector/pick', body: '{}', local: ROOT_BEARER }, + { method: 'GET', path: '/inspector', local: ROOT_BEARER }, + { method: 'POST', path: '/inspector/apply', body: '{}', local: ROOT_BEARER }, + { method: 'POST', path: '/inspector/reset', local: ROOT_BEARER }, + { method: 'GET', path: '/inspector/history', local: ROOT_BEARER }, + // /memory and /inspector/events sit behind the blanket root-bearer check, so + // the SSE cookie their handlers mention never reaches them today. + { method: 'GET', path: '/memory', local: ROOT_BEARER }, + { method: 'GET', path: '/inspector/events', local: ROOT_BEARER, stream: true }, +]; + +/** Requests no route accepts: unknown paths and known paths with a method no route takes. */ +const UNMATCHED: Array<{ method: string; path: string }> = [ + { method: 'GET', path: '/no-such-route' }, + { method: 'POST', path: '/no-such-route' }, + { method: 'GET', path: '/command' }, + { method: 'GET', path: '/pty-session' }, + { method: 'PUT', path: '/token' }, + { method: 'GET', path: '/token/someone' }, + { method: 'GET', path: '/inspector/pick' }, + { method: 'POST', path: '/inspector' }, + { method: 'PUT', path: '/connect' }, + { method: 'DELETE', path: '/command' }, +]; + +let handle: ServerHandle; +let rootToken = ''; +let scopedToken = ''; +let sseCookie = ''; +const savedPairAgent = process.env.GSTACK_PAIR_AGENT; + +beforeAll(() => { + // /tunnel/start's allowed branch must stop at the consent gate, never ngrok. + process.env.GSTACK_PAIR_AGENT = 'off'; + __resetRegistry(); + rootToken = 'route-blackbox-' + crypto.randomBytes(16).toString('hex'); + const cfg: ServerConfig = { + authToken: rootToken, + browsePort: 34567, + config: fixtureConfig, + browserManager: new BrowserManager(), + ownsTerminalAgent: false, + startTime: Date.now(), + }; + handle = buildFetchHandler(cfg); + scopedToken = createToken({ clientId: 'matrix-agent', scopes: ['read', 'write'] }).token; + sseCookie = mintSseSessionToken().token; +}); + +afterAll(() => { + if (savedPairAgent === undefined) delete process.env.GSTACK_PAIR_AGENT; + else process.env.GSTACK_PAIR_AGENT = savedPairAgent; + fs.rmSync(fixtureDir, { recursive: true, force: true }); +}); + +function credHeaders(cred: Cred): Record { + switch (cred) { + case 'none': return {}; + case 'wrong': return { Authorization: `Bearer ${'w'.repeat(rootToken.length)}` }; + case 'root': return { Authorization: `Bearer ${rootToken}` }; + case 'scoped': return { Authorization: `Bearer ${scopedToken}` }; + case 'sse-cookie': return { Cookie: `${SSE_COOKIE_NAME}=${sseCookie}` }; + } +} + +async function call( + surface: 'local' | 'tunnel', + method: string, + urlPath: string, + headers: Record, + body?: string, + stream = false, +): Promise<{ status: number; body: string; contentType: string }> { + __resetConnectRateLimit(); + const req = new Request(`http://127.0.0.1:34567${urlPath}`, { + method, + headers: body !== undefined ? { 'Content-Type': 'application/json', ...headers } : headers, + body: method === 'GET' || method === 'HEAD' ? undefined : body, + }); + const resp = surface === 'local' ? await handle.fetchLocal(req, null) : await handle.fetchTunnel(req, null); + const contentType = resp.headers.get('content-type') ?? ''; + if (stream && resp.status === 200) { + await resp.body?.cancel(); + return { status: resp.status, body: '', contentType }; + } + return { status: resp.status, body: await resp.text(), contentType }; +} + +function expectDenial(got: { status: number; body: string; contentType: string }, want: Denial): void { + expect({ status: got.status, body: got.body }).toEqual({ status: want.status, body: want.body }); + expect(got.contentType).toBe(want.contentType); +} + +function expectReached(got: { status: number; body: string }): void { + for (const d of GATE_DENIALS) { + expect(got.status === d.status && got.body === d.body, `gate denial ${d.status} ${d.body}`).toBe(false); + } +} + +function tunnelPolicy(route: RouteRow): Policy | Denial { + if (route.tunnel === 'connect') return OPEN; + if (route.tunnel === 'command') return { kind: 'deny', allow: ['scoped'], denial: UNAUTHORIZED }; + return TUNNEL_NOT_FOUND; +} + +describe('browse route auth matrix (black-box)', () => { + for (const route of ROUTES) { + for (const cred of CREDS) { + test(`local ${route.method} ${route.path} with ${cred}`, async () => { + const got = await call('local', route.method, route.path, credHeaders(cred), route.body, route.stream); + const p = route.local; + if (p.kind === 'open' || p.allow.includes(cred)) expectReached(got); + else expectDenial(got, p.denial); + }); + + test(`tunnel ${route.method} ${route.path} with ${cred}`, async () => { + const got = await call('tunnel', route.method, route.path, credHeaders(cred), route.body, route.stream); + const p = tunnelPolicy(route); + if ('status' in p) return expectDenial(got, p); + if (cred === 'root') return expectDenial(got, TUNNEL_ROOT_REJECTED); + if (p.kind === 'open' || p.allow.includes(cred)) expectReached(got); + else expectDenial(got, p.denial); + }); + } + } + + test('POST /pty-dispose accepts the root token in the body (sendBeacon path)', async () => { + const got = await call('local', 'POST', '/pty-dispose', {}, JSON.stringify({ authToken: rootToken })); + expect(got.status).toBe(200); + expect(JSON.parse(got.body)).toEqual({ ok: true }); + const wrong = await call('local', 'POST', '/pty-dispose', {}, JSON.stringify({ authToken: 'w'.repeat(rootToken.length) })); + expectDenial(wrong, UNAUTHORIZED); + }); + + test('POST /extension-token releases the token only to the pinned Origin on a loopback Host', async () => { + const origin = `chrome-extension://${GSTACK_EXTENSION_ID}`; + const ok = await call('local', 'POST', '/extension-token', { Origin: origin, Host: '127.0.0.1:34567' }); + expect(ok.status).toBe(200); + expect(JSON.parse(ok.body)).toEqual({ token: rootToken }); + expectDenial(await call('local', 'POST', '/extension-token', { Origin: 'chrome-extension://someone-else', Host: '127.0.0.1:34567' }), FORBIDDEN); + expectDenial(await call('local', 'POST', '/extension-token', { Origin: origin, Host: 'evil.example:34567' }), FORBIDDEN); + expectDenial(await call('tunnel', 'POST', '/extension-token', { Origin: origin, Host: '127.0.0.1:34567' }), TUNNEL_NOT_FOUND); + }); + + for (const row of UNMATCHED) { + for (const cred of CREDS) { + test(`unmatched local ${row.method} ${row.path} with ${cred}`, async () => { + const got = await call('local', row.method, row.path, credHeaders(cred), row.method === 'GET' ? undefined : '{}'); + expectDenial(got, cred === 'root' ? LOCAL_NOT_FOUND : UNAUTHORIZED); + }); + + test(`unmatched tunnel ${row.method} ${row.path} with ${cred}`, async () => { + const got = await call('tunnel', row.method, row.path, credHeaders(cred), row.method === 'GET' ? undefined : '{}'); + const onTunnelPath = row.path === '/connect' || row.path === '/command'; + if (!onTunnelPath) return expectDenial(got, TUNNEL_NOT_FOUND); + if (cred === 'root') return expectDenial(got, TUNNEL_ROOT_REJECTED); + expectDenial(got, UNAUTHORIZED); + }); + } + } +}); From 3b31ea68383cea18f8647dd2f3df0e19275e221d Mon Sep 17 00:00:00 2001 From: garrytan Date: Wed, 30 Sep 2026 06:11:51 +0000 Subject: [PATCH 2/5] refactor(browse): declared route table replaces the buildFetchHandler if-chain The ~1,300-line if-chain in buildFetchHandler becomes a route table: each entry declares method, path, auth kind and surfaces, and one auth gate in browse/src/routes/table.ts returns the per-kind denial (root-bearer, scoped, root-or-sse-cookie: 401 Unauthorized; root-token: 403 Root token required; extension-origin: 403 Forbidden). Unmatched requests take the declared fallthrough (root-bearer check, then plain-text 404). Handlers move to browse/src/routes/{core,pairing,pty,tokens,tunnel,activity,commands,files, inspector}.ts and receive a RouteContext with auth checks as functions instead of closing over factory locals. Dispatch order is unchanged: tunnel filter, beforeRoute overlay, gate, handler. TUNNEL_PATHS stays a literal in server.ts. Behavior-preserving: the black-box auth matrix from the previous commit passes unchanged. /memory and /inspector/events are declared root-bearer because the blanket check always ran before their SSE-cookie branch. Source-text route tests are rewritten as behavioral tests through buildFetchHandler or a route's real handler with a stub RouteContext (browse/test/route-test-harness.ts). Checks with no runtime seam are re-pointed to the route modules: Surface type, /inspector/events SSE helper, sanitizeReplacer imports, /pty-inject-scan sidecar-client import, and the ngrok config lookup and startTunnel wiring that stay in server.ts. --- browse/src/routes/activity.ts | 63 + browse/src/routes/commands.ts | 154 ++ browse/src/routes/core.ts | 121 ++ browse/src/routes/files.ts | 47 + browse/src/routes/index.ts | 27 + browse/src/routes/inspector.ts | 132 ++ browse/src/routes/pairing.ts | 158 ++ browse/src/routes/pty.ts | 254 +++ browse/src/routes/table.ts | 182 +++ browse/src/routes/tokens.ts | 86 + browse/src/routes/tunnel.ts | 62 + browse/src/server.ts | 1380 +---------------- browse/test/dual-listener.test.ts | 249 +-- browse/test/pair-agent-optin-gate.test.ts | 20 +- browse/test/pty-inject-scan.test.ts | 68 +- browse/test/route-test-harness.ts | 121 ++ browse/test/server-auth.test.ts | 496 ++++-- browse/test/server-pty-lease-routes.test.ts | 162 +- .../test/server-sanitize-surrogates.test.ts | 58 +- browse/test/sidebar-tabs.test.ts | 25 +- browse/test/sidebar-ux.test.ts | 42 +- browse/test/terminal-agent.test.ts | 60 +- 22 files changed, 2234 insertions(+), 1733 deletions(-) create mode 100644 browse/src/routes/activity.ts create mode 100644 browse/src/routes/commands.ts create mode 100644 browse/src/routes/core.ts create mode 100644 browse/src/routes/files.ts create mode 100644 browse/src/routes/index.ts create mode 100644 browse/src/routes/inspector.ts create mode 100644 browse/src/routes/pairing.ts create mode 100644 browse/src/routes/pty.ts create mode 100644 browse/src/routes/table.ts create mode 100644 browse/src/routes/tokens.ts create mode 100644 browse/src/routes/tunnel.ts create mode 100644 browse/test/route-test-harness.ts diff --git a/browse/src/routes/activity.ts b/browse/src/routes/activity.ts new file mode 100644 index 000000000..44ad36ce1 --- /dev/null +++ b/browse/src/routes/activity.ts @@ -0,0 +1,63 @@ +/** + * Activity feed routes: the SSE session cookie mint, the activity SSE stream + * and the REST history. None reset the idle timer. + */ + +import { json, type RouteEntry } from './table'; +import { subscribe, getActivityAfter, getActivityHistory, getSubscriberCount } from '../activity'; +import { createSseEndpoint } from '../sse-helpers'; +import { mintSseSessionToken, buildSseSetCookie, SSE_COOKIE_NAME } from '../sse-session-cookie'; + +export const activityRoutes: RouteEntry[] = [ + // ─── SSE session cookie mint (auth required) ────────────────── + // + // Issues a short-lived view-only token in an HttpOnly SameSite=Strict + // cookie so EventSource calls can authenticate without putting the + // root token in a URL. It is not a scoped token and cannot be used + // against /command. The extension calls this once at bootstrap with the + // root Bearer header, then opens EventSource with `withCredentials: true` + // which sends the cookie back automatically. + { + method: 'POST', path: '/sse-session', auth: 'root-bearer', surfaces: ['local'], + handler: () => { + const minted = mintSseSessionToken(); + return json({ + expiresAt: minted.expiresAt, + cookie: SSE_COOKIE_NAME, + }, { headers: { 'Set-Cookie': buildSseSetCookie(minted.token) } }); + }, + }, + + // Activity stream — SSE. Auth: Bearer header OR view-only SSE session + // cookie (EventSource can't send Authorization headers). The ?token= query + // param is NO LONGER accepted — URLs leak to logs/referer/history. + { + method: '*', path: '/activity/stream', auth: 'root-or-sse-cookie', surfaces: ['local'], + handler: (req, { url }) => { + const afterId = parseInt(url.searchParams.get('after') || '0', 10); + // Cleanup contract (abort + enqueue-fail + heartbeat-fail, all + // idempotent) lives in createSseEndpoint; sanitizeReplacer is applied + // to every JSON.stringify inside the helper, so page-content-derived + // fields stay surrogate-safe per the CLAUDE.md egress invariant. + return createSseEndpoint(req, { + initialReplay: (send) => { + const { entries, gap, gapFrom, availableFrom } = getActivityAfter(afterId); + if (gap) send('gap', { gapFrom, availableFrom }); + for (const entry of entries) send('activity', entry); + }, + subscribe, + liveEventName: 'activity', + }); + }, + }, + + // Activity history — REST + { + method: '*', path: '/activity/history', auth: 'root-bearer', surfaces: ['local'], + handler: (_req, { url }) => { + const limit = parseInt(url.searchParams.get('limit') || '50', 10); + const { entries, totalAdded } = getActivityHistory(limit); + return json({ entries, totalAdded, subscribers: getSubscriberCount() }); + }, + }, +]; diff --git a/browse/src/routes/commands.ts b/browse/src/routes/commands.ts new file mode 100644 index 000000000..9cc0f1a09 --- /dev/null +++ b/browse/src/routes/commands.ts @@ -0,0 +1,154 @@ +/** + * Command routes: POST /command (one command; the only non-/connect tunnel + * route) and POST /batch (N commands in one round trip). Both accept root and + * scoped tokens and run through the full command security pipeline. Also owns + * the tunnel command allowlist. + */ + +import { type RouteEntry, jsonError } from './table'; +import { canonicalizeCommand } from '../commands'; +import { hasOutArg } from '../read-commands'; +import { emitActivity } from '../activity'; +import { logTunnelDenial } from '../tunnel-denial-log'; +import { sanitizeBody, stripLoneSurrogateEscapes } from '../sanitize'; + +/** + * Commands reachable via POST /command over the tunnel surface. A paired + * remote agent can drive the browser (goto, click, text, etc.) but cannot + * configure the daemon, bootstrap new sessions, import cookies, or reach + * extension-inspector state. This allowlist maps to the eng-review decision + * logged in the CEO plan for sec-wave v1.6.0.0. + */ +export const TUNNEL_COMMANDS = new Set([ + // Original 17 + 'goto', 'click', 'text', 'screenshot', + 'html', 'links', 'forms', 'accessibility', + 'attrs', 'media', 'data', + 'scroll', 'press', 'type', 'select', 'wait', 'eval', + // Tab + navigation primitives operator docs and CLI hints already promised + 'newtab', 'tabs', 'back', 'forward', 'reload', + // Read/inspect/write operators paired agents need to be useful + 'snapshot', 'fill', 'url', 'closetab', +]); + +/** + * Pure gate: returns true iff the command is reachable over the tunnel surface. + * Canonicalizes the command (so aliases hit the same set) and returns false + * for null/undefined input. + * + * `args` is consulted so an `--out` invocation (e.g. `eval --out `) is + * NEVER tunnel-dispatchable: `--out` turns an otherwise-readable command into a + * local-disk WRITE, and the tunnel surface never grants disk-write capability to + * remote paired agents. Omitting `args` preserves the old command-only behavior. + */ +export function canDispatchOverTunnel(command: string | undefined | null, args?: string[]): boolean { + if (typeof command !== 'string' || command.length === 0) return false; + if (Array.isArray(args) && hasOutArg(args)) return false; + const cmd = canonicalizeCommand(command); + return TUNNEL_COMMANDS.has(cmd); +} + +export const commandRoutes: RouteEntry[] = [ + // ─── Batch endpoint — N commands, 1 HTTP round-trip ───────────── + // Executes commands sequentially through the full security pipeline. + // Designed for remote agents where tunnel latency dominates. + { + method: 'POST', path: '/batch', auth: 'scoped', surfaces: ['local'], + handler: async (req, { tokenInfo }, ctx) => { + const { browserManager } = ctx; + ctx.resetIdleTimer(); + const body = await req.json(); + const { commands } = body; + if (!Array.isArray(commands) || commands.length === 0) return jsonError(400, '"commands" must be a non-empty array'); + if (commands.length > 50) return jsonError(400, 'Max 50 commands per batch'); + + const startTime = Date.now(); + emitActivity({ + type: 'command_start', + command: 'batch', + args: [`${commands.length} commands`], + url: browserManager.getCurrentUrl(), + tabs: browserManager.getTabCount(), + mode: browserManager.getConnectionMode(), + clientId: tokenInfo?.clientId, + }); + + const results: Array<{ index: number; status: number; result: string; command: string; tabId?: number }> = []; + for (let i = 0; i < commands.length; i++) { + const cmd = commands[i]; + if (!cmd || typeof cmd.command !== 'string') { + results.push({ index: i, status: 400, result: JSON.stringify({ error: 'Missing "command" field' }), command: '' }); + continue; + } + // Reject nested batches + if (cmd.command === 'batch') { + results.push({ index: i, status: 400, result: JSON.stringify({ error: 'Nested batch commands are not allowed' }), command: 'batch' }); + continue; + } + const cr = await ctx.commands.handleInternal( + { command: cmd.command, args: cmd.args, tabId: cmd.tabId }, + tokenInfo, + { skipRateCheck: true, skipActivity: true }, + ); + // Sanitize lone surrogates per-result (#1440 — /batch bypasses the + // handleCommand chokepoint, so it needs its own sanitization). + const safeResult = typeof cr.result === 'string' ? sanitizeBody(cr.result, !!cr.json) : cr.result; + results.push({ + index: i, + status: cr.status, + result: safeResult, + command: cmd.command, + tabId: cmd.tabId, + }); + } + + const duration = Date.now() - startTime; + emitActivity({ + type: 'command_end', + command: 'batch', + args: [`${commands.length} commands`], + url: browserManager.getCurrentUrl(), + duration, + status: 'ok', + result: `${results.filter(r => r.status === 200).length}/${commands.length} succeeded`, + tabs: browserManager.getTabCount(), + mode: browserManager.getConnectionMode(), + clientId: tokenInfo?.clientId, + }); + + // Sanitize the JSON envelope a second time (defense in depth) — catches + // any \uXXXX escape sequences for lone surrogates that survived the + // per-result pass. + const batchBody = stripLoneSurrogateEscapes(JSON.stringify({ + results, + duration, + total: commands.length, + succeeded: results.filter(r => r.status === 200).length, + failed: results.filter(r => r.status !== 200).length, + })); + return new Response(batchBody, { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + }, + }, + + // ─── Command endpoint ─────────────────────────────────────────── + { + method: 'POST', path: '/command', auth: 'scoped', surfaces: ['local', 'tunnel'], + handler: async (req, { url, surface, tokenInfo }, ctx) => { + ctx.resetIdleTimer(); + const body = await req.json() as any; + // Tunnel surface: only commands in TUNNEL_COMMANDS are allowed. + // Paired remote agents drive the browser but cannot configure the + // daemon, launch new browsers, import cookies, or rotate tokens. + if (surface === 'tunnel' && !canDispatchOverTunnel(body?.command, body?.args)) { + logTunnelDenial(req, url, `disallowed_command:${body?.command}`); + return jsonError(403, `Command '${body?.command}' is not allowed over the tunnel surface`, { + hint: `Tunnel commands: ${[...TUNNEL_COMMANDS].sort().join(', ')}. Note: --out (disk write) is never allowed over the tunnel.`, + }); + } + return ctx.commands.handle(body, tokenInfo); + }, + }, +]; diff --git a/browse/src/routes/core.ts b/browse/src/routes/core.ts new file mode 100644 index 000000000..c08074fa5 --- /dev/null +++ b/browse/src/routes/core.ts @@ -0,0 +1,121 @@ +/** + * Daemon routes outside the named areas: the cookie-picker sub-router, the + * welcome page, the pinned-origin token bootstrap, liveness, refs and the + * memory diagnostic. + */ + +import * as fs from 'fs'; +import { json, type RouteEntry } from './table'; +import { handleCookiePickerRoute } from '../cookie-picker-routes'; +import { sanitizeReplacer } from '../sanitize'; + +function resolveWelcomePath(): string | null { + // Gate GSTACK_SLUG on a strict regex BEFORE interpolating it into the + // filesystem path. Without this, a slug like "../../etc/passwd" would + // resolve to ~/.gstack/projects/../../etc/passwd/... — path traversal. + const rawSlug = process.env.GSTACK_SLUG || 'unknown'; + const slug = /^[a-z0-9_-]+$/.test(rawSlug) ? rawSlug : 'unknown'; + const homeDir = process.env.HOME || process.env.USERPROFILE || '/tmp'; + const projectWelcome = `${homeDir}/.gstack/projects/${slug}/designs/welcome-page-20260331/finalized.html`; + if (fs.existsSync(projectWelcome)) return projectWelcome; + // Fallback: built-in welcome page from gstack install. Reject SKILL_ROOT + // values containing '..' for the same defense-in-depth reason. + const rawSkillRoot = process.env.GSTACK_SKILL_ROOT || `${homeDir}/.claude/skills/gstack`; + if (rawSkillRoot.includes('..')) return null; + const builtinWelcome = `${rawSkillRoot}/browse/src/welcome.html`; + if (fs.existsSync(builtinWelcome)) return builtinWelcome; + return null; +} + +export const coreRoutes: RouteEntry[] = [ + // Cookie picker sub-router — HTML page unauthenticated, data/action routes require auth + { + method: '*', path: '/cookie-picker', prefix: true, auth: 'handler', surfaces: ['local'], + handlerAuth: 'sub-router in cookie-picker-routes.ts: OPTIONS preflight open; GET /cookie-picker needs a one-time code or picker session cookie (403 text); every other /cookie-picker/* needs the root bearer or a picker session (401 Unauthorized)', + handler: (req, { url }, ctx) => handleCookiePickerRoute(url, req, ctx.browserManager, ctx.bootstrapRootToken), + }, + + // Welcome page — served when GStack Browser launches in headed mode + { + method: '*', path: '/welcome', auth: 'none', surfaces: ['local'], + handler: () => { + const welcomePath = resolveWelcomePath(); + if (welcomePath) { + try { + const html = fs.readFileSync(welcomePath, 'utf-8'); + return new Response(html, { headers: { 'Content-Type': 'text/html; charset=utf-8' } }); + } catch (err: any) { + console.error('[browse] Failed to read welcome page:', welcomePath, err.message); + } + } + // No welcome page found — serve a simple fallback (avoid ERR_UNSAFE_REDIRECT on Windows) + return new Response( + `GStack Browser + +
◈

GStack Browser ready.

Waiting for commands from Claude Code.

`, + { status: 200, headers: { 'Content-Type': 'text/html; charset=utf-8' } } + ); + }, + }, + + // ─── POST /extension-token — pinned-origin token bootstrap ────── + // + // The ONLY endpoint that hands out AUTH_TOKEN. The token is released only + // to the one extension identity we ship: the Origin header must be exactly + // `chrome-extension://` and the Host must be loopback + // (the extension-origin gate). Chrome sets Origin on cross-origin POSTs + // from extension contexts and web pages cannot forge a chrome-extension:// + // Origin. Local listener only: NEVER added to TUNNEL_PATHS. + { + method: 'POST', path: '/extension-token', auth: 'extension-origin', surfaces: ['local'], + handler: (_req, _r, ctx) => json({ token: ctx.bootstrapRootToken }), + }, + + // Health check — no auth required, does NOT reset idle timer. NEVER carries + // a token in any mode: token bootstrap is POST /extension-token and shell + // auth is POST /pty-session. Liveness/status only. + { + method: '*', path: '/health', auth: 'none', surfaces: ['local'], + handler: async (_req, _r, ctx) => { + const { browserManager } = ctx; + const healthy = await browserManager.isHealthy(); + return json({ + status: healthy ? 'healthy' : 'unhealthy', + mode: browserManager.getConnectionMode(), + uptime: Math.floor((Date.now() - ctx.startTime) / 1000), + tabs: browserManager.getTabCount(), + // No `security` field (#2557): the live defenses report through + // their own call sites, not through /health. + // Terminal-agent discovery. ONLY a port number — never a token. + // Tokens flow via the /pty-session HttpOnly cookie path. + terminalPort: ctx.terminal.readPort(), + }); + }, + }, + + // Refs endpoint — does NOT reset idle timer + { + method: '*', path: '/refs', auth: 'root-bearer', surfaces: ['local'], + handler: (_req, _r, { browserManager }) => json({ + refs: browserManager.getRefMap(), + url: browserManager.getCurrentUrl(), + mode: browserManager.getConnectionMode(), + }), + }, + + // GET /memory — diagnostic snapshot, does NOT reset idle. Root-bearer: it + // sat behind the if-chain's blanket root-bearer check, so the SSE cookie + // its handler also accepted never reached it. + { + method: 'GET', path: '/memory', auth: 'root-bearer', surfaces: ['local'], + handler: async (_req, _r, ctx) => { + const { buildMemorySnapshotJson } = await import('../memory-command'); + const snapshot = await buildMemorySnapshotJson(ctx.browserManager); + // sanitizeReplacer is required at every JSON egress that ships + // page-content-derived strings — tab.url and tab.title come from page + // content. + return json(snapshot, { replacer: sanitizeReplacer }); + }, + }, +]; diff --git a/browse/src/routes/files.ts b/browse/src/routes/files.ts new file mode 100644 index 000000000..cc43a0485 --- /dev/null +++ b/browse/src/routes/files.ts @@ -0,0 +1,47 @@ +/** + * GET /file — serve a downloaded file from the temp roots so remote agents + * can retrieve screenshots, PDFs and media. Accepts root and scoped tokens. + */ + +import * as fs from 'fs'; +import * as path from 'path'; +import { jsonError, type RouteEntry } from './table'; +import { validateTempPath } from '../path-security'; + +const MIME_MAP: Record = { + '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', + '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml', + '.avif': 'image/avif', + '.mp4': 'video/mp4', '.webm': 'video/webm', '.mov': 'video/quicktime', + '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.ogg': 'audio/ogg', + '.pdf': 'application/pdf', '.json': 'application/json', + '.html': 'text/html', '.txt': 'text/plain', '.mhtml': 'message/rfc822', +}; + +export const fileRoutes: RouteEntry[] = [ + { + method: 'GET', path: '/file', auth: 'scoped', surfaces: ['local'], + handler: (_req, { url }, ctx) => { + const filePath = url.searchParams.get('path'); + if (!filePath) return jsonError(400, 'Missing "path" query parameter'); + try { + validateTempPath(filePath); + } catch (err: any) { + return jsonError(403, err.message); + } + if (!fs.existsSync(filePath)) return jsonError(404, 'File not found'); + const stat = fs.statSync(filePath); + if (stat.size > 200 * 1024 * 1024) return jsonError(413, 'File too large (max 200MB)'); + const contentType = MIME_MAP[path.extname(filePath).toLowerCase()] || 'application/octet-stream'; + ctx.resetIdleTimer(); + return new Response(Bun.file(filePath), { + headers: { + 'Content-Type': contentType, + 'Content-Length': String(stat.size), + 'Content-Disposition': `inline; filename="${path.basename(filePath)}"`, + 'Cache-Control': 'no-cache', + }, + }); + }, + }, +]; diff --git a/browse/src/routes/index.ts b/browse/src/routes/index.ts new file mode 100644 index 000000000..dea0eabf9 --- /dev/null +++ b/browse/src/routes/index.ts @@ -0,0 +1,27 @@ +/** + * The browse daemon's route table, in dispatch order. See ./table.ts for the + * entry shape, auth kinds and the unmatched fallthrough. + */ + +import type { RouteEntry } from './table'; +import { pairingRoutes } from './pairing'; +import { coreRoutes } from './core'; +import { ptyRoutes } from './pty'; +import { tokenRoutes } from './tokens'; +import { tunnelRoutes } from './tunnel'; +import { activityRoutes } from './activity'; +import { commandRoutes } from './commands'; +import { fileRoutes } from './files'; +import { inspectorRoutes } from './inspector'; + +export const ROUTES: readonly RouteEntry[] = [ + ...pairingRoutes, + ...coreRoutes, + ...ptyRoutes, + ...tokenRoutes, + ...tunnelRoutes, + ...activityRoutes, + ...commandRoutes, + ...fileRoutes, + ...inspectorRoutes, +]; diff --git a/browse/src/routes/inspector.ts b/browse/src/routes/inspector.ts new file mode 100644 index 000000000..fd58530b3 --- /dev/null +++ b/browse/src/routes/inspector.ts @@ -0,0 +1,132 @@ +/** + * CSS inspector routes and the in-memory inspector state they share: pick, + * read, apply, reset, history and the inspector SSE stream. + * + * GET /inspector/events is root-bearer: it sat behind the if-chain's blanket + * root-bearer check, so the SSE cookie its handler also accepted never reached + * it. The declaration keeps that behavior. + */ + +import { json, jsonError, type RouteEntry } from './table'; +import { inspectElement, modifyStyle, resetModifications, getModificationHistory, type InspectorResult } from '../cdp-inspector'; +import { createSseEndpoint } from '../sse-helpers'; + +let inspectorData: InspectorResult | null = null; +let inspectorTimestamp = 0; + +type InspectorSubscriber = (event: any) => void; +const inspectorSubscribers = new Set(); + +/** Diagnostic accessor used by the $B memory snapshot. */ +export function getInspectorSubscriberCount(): number { + return inspectorSubscribers.size; +} + +/** Drops every inspector SSE subscriber (daemon shutdown). */ +export function clearInspectorSubscribers(): void { + inspectorSubscribers.clear(); +} + +function emitInspectorEvent(event: any): void { + for (const notify of inspectorSubscribers) { + queueMicrotask(() => { + try { notify(event); } catch (err: any) { + console.error('[browse] Inspector event subscriber threw:', err.message); + } + }); + } +} + +export const inspectorRoutes: RouteEntry[] = [ + // POST /inspector/pick — receive element pick from extension, run CDP inspection + { + method: 'POST', path: '/inspector/pick', auth: 'root-bearer', surfaces: ['local'], + handler: async (req, _r, ctx) => { + const body = await req.json(); + const { selector, activeTabUrl } = body; + if (!selector) return jsonError(400, 'Missing selector'); + try { + const page = ctx.browserManager.getPage(); + const result = await inspectElement(page, selector); + inspectorData = result; + inspectorTimestamp = Date.now(); + // Also store on browserManager for CLI access + (ctx.browserManager as any)._inspectorData = result; + (ctx.browserManager as any)._inspectorTimestamp = inspectorTimestamp; + emitInspectorEvent({ type: 'pick', selector, timestamp: inspectorTimestamp }); + return json(result); + } catch (err: any) { + return jsonError(500, err.message); + } + }, + }, + + // GET /inspector — return latest inspector data + { + method: 'GET', path: '/inspector', auth: 'root-bearer', surfaces: ['local'], + handler: () => { + if (!inspectorData) return json({ data: null }); + const stale = inspectorTimestamp > 0 && (Date.now() - inspectorTimestamp > 60000); + return json({ data: inspectorData, timestamp: inspectorTimestamp, stale }); + }, + }, + + // POST /inspector/apply — apply a CSS modification + { + method: 'POST', path: '/inspector/apply', auth: 'root-bearer', surfaces: ['local'], + handler: async (req, _r, ctx) => { + const body = await req.json(); + const { selector, property, value } = body; + if (!selector || !property || value === undefined) return jsonError(400, 'Missing selector, property, or value'); + try { + const page = ctx.browserManager.getPage(); + const mod = await modifyStyle(page, selector, property, value); + emitInspectorEvent({ type: 'apply', modification: mod, timestamp: Date.now() }); + return json(mod); + } catch (err: any) { + return jsonError(500, err.message); + } + }, + }, + + // POST /inspector/reset — clear all modifications + { + method: 'POST', path: '/inspector/reset', auth: 'root-bearer', surfaces: ['local'], + handler: async (_req, _r, ctx) => { + try { + const page = ctx.browserManager.getPage(); + await resetModifications(page); + emitInspectorEvent({ type: 'reset', timestamp: Date.now() }); + return json({ ok: true }); + } catch (err: any) { + return jsonError(500, err.message); + } + }, + }, + + // GET /inspector/history — return modification list + { + method: 'GET', path: '/inspector/history', auth: 'root-bearer', surfaces: ['local'], + handler: () => json({ history: getModificationHistory() }), + }, + + // GET /inspector/events — SSE for inspector state changes + { + method: 'GET', path: '/inspector/events', auth: 'root-bearer', surfaces: ['local'], + handler: (req) => { + // Cleanup contract (abort + enqueue-fail + heartbeat-fail, idempotent) + // lives in createSseEndpoint; sanitizeReplacer is applied to every + // JSON.stringify inside the helper. + return createSseEndpoint(req, { + initialReplay: inspectorData + ? (send) => send('state', { data: inspectorData, timestamp: inspectorTimestamp }) + : undefined, + subscribe: (notify) => { + inspectorSubscribers.add(notify); + return () => inspectorSubscribers.delete(notify); + }, + liveEventName: 'inspector', + }); + }, + }, +]; diff --git a/browse/src/routes/pairing.ts b/browse/src/routes/pairing.ts new file mode 100644 index 000000000..91ff66760 --- /dev/null +++ b/browse/src/routes/pairing.ts @@ -0,0 +1,158 @@ +/** + * Pair-agent ceremony routes: the /connect alive probe and setup-key + * exchange (the only unauthenticated tunnel endpoints) and root-only /pair. + */ + +import { json, jsonError, type RouteEntry } from './table'; +import { + checkConnectRateLimit, exchangeSetupKey, createSetupKey, revokeToken, revokeSetupKeys, + getClientSession, grantReducesAccess, assertValidClientId, assertValidTokenOptions, + DEFAULT_PAIR_SCOPES, InvalidScopeError, ReservedClientIdError, type ScopeCategory, +} from '../token-registry'; + +export const pairingRoutes: RouteEntry[] = [ + // GET /connect — alive probe. Unauth on both surfaces. Used by /pair and + // /tunnel/start to detect dead ngrok tunnels via the tunnel URL, since + // /health is not tunnel-reachable under the dual-listener design. + // + // Shares the same rate limit as POST /connect — otherwise a tunnel caller + // can probe unlimited GETs, which makes the endpoint a free + // daemon-enumeration surface. + { + method: 'GET', path: '/connect', auth: 'none', surfaces: ['local', 'tunnel'], + handler: () => { + if (!checkConnectRateLimit()) return jsonError(429, 'Rate limited'); + return json({ alive: true }); + }, + }, + + // ─── /connect — setup key exchange for /pair-agent ceremony ──── + { + method: 'POST', path: '/connect', auth: 'none', surfaces: ['local', 'tunnel'], + handler: async (req) => { + if (!checkConnectRateLimit()) return jsonError(429, 'Too many connection attempts. Wait 1 minute.'); + try { + const connectBody = await req.json() as { setup_key?: string }; + if (!connectBody.setup_key) return jsonError(400, 'Missing setup_key'); + const session = exchangeSetupKey(connectBody.setup_key); + if (!session) return jsonError(401, 'Invalid, expired, or already-used setup key'); + console.log(`[browse] Remote agent connected: ${session.clientId} (scopes: ${session.scopes.join(',')})`); + return json({ + token: session.token, + expires: session.expiresAt, + scopes: session.scopes, + agent: session.clientId, + }); + } catch { + return jsonError(400, 'Invalid request body'); + } + }, + }, + + // ─── /pair — create setup key for pair-agent ceremony (root-only) ─── + { + method: 'POST', path: '/pair', auth: 'root-token', surfaces: ['local'], + handler: async (req, _r, ctx) => { + try { + const pairBody = await req.json() as any; + // Reject a reserved/invalid clientId up front (createSetupKey enforces + // it too, but this makes the 400 unambiguous and skips the teardown). + if (pairBody.clientId !== undefined) assertValidClientId(pairBody.clientId); + // Default: DEFAULT_PAIR_SCOPES (full page access). The trust boundary + // is the pairing ceremony itself, not the scope. --control adds + // browser-wide destructive commands (stop, restart, disconnect). + // --restrict limits scope — but can never grant control: that scope + // stays behind the explicit control flag. + if (!pairBody.control && !pairBody.admin + && Array.isArray(pairBody.scopes) && pairBody.scopes.includes('control')) { + return jsonError(400, 'The control scope requires the control flag (--control); it cannot be granted via a scopes list.'); + } + const scopes = pairBody.control || pairBody.admin + ? [...DEFAULT_PAIR_SCOPES, 'control' as const] + : ((pairBody.scopes || [...DEFAULT_PAIR_SCOPES]) as ScopeCategory[]); + // D1: a re-pair supersedes prior grants. ALWAYS drop stale setup keys + // so a superseded broad key can never be exchanged — this closes the + // shadow-key hole where a narrowing re-pair before the agent connects + // would otherwise leave the old broad key live. Revoke the live + // SESSION only when the new grant actually reduces access, so a + // broaden/refresh never strands a working agent mid-task. Compare + // against the resolved grant (not raw pairBody) so dropping 'control' + // or a default re-pair is classified correctly. Revoke runs BEFORE + // createSetupKey — revokeToken deletes all of a clientId's tokens, so + // minting first would nuke the fresh key. + const grant = { + scopes: [...scopes] as ScopeCategory[], + domains: pairBody.domains as string[] | undefined, + rateLimit: pairBody.rateLimit ?? 10, + tabPolicy: 'own-only' as const, + }; + // Validate BEFORE any revoke (createSetupKey validates too, but that + // runs after the teardown below). A bad scope or negative rateLimit + // must 400 without knocking a live session offline — otherwise a + // reducing re-pair with a typo (--restrict red) destroys the session + // and mints no replacement. + assertValidTokenOptions(grant.scopes, grant.rateLimit); + const priorSession = pairBody.clientId ? getClientSession(pairBody.clientId) : null; + let superseded: { tokens_deleted: number; tabs_released: number } | undefined; + if (priorSession && grantReducesAccess(priorSession, grant)) { + const tokensDeleted = revokeToken(pairBody.clientId); + const tabsReleased = ctx.browserManager.releaseClientTabs(pairBody.clientId).length; + superseded = { tokens_deleted: tokensDeleted, tabs_released: tabsReleased }; + console.log(`[browse] Superseded ${tokensDeleted} token(s), released ${tabsReleased} tab(s) for reducing re-pair: ${pairBody.clientId}`); + } else if (pairBody.clientId) { + revokeSetupKeys(pairBody.clientId); + // No live session, but tab ownership outlives token expiry: free any + // tabs orphaned by an expired session so this re-pair can't inherit + // an earlier incarnation's authenticated pages (mirrors DELETE + // /token's unconditional release). A live-session broaden keeps its + // tabs — the working agent still owns them. + if (!priorSession) ctx.browserManager.releaseClientTabs(pairBody.clientId); + } + const setupKey = createSetupKey({ + clientId: pairBody.clientId, + scopes: [...scopes], + domains: pairBody.domains, + rateLimit: pairBody.rateLimit, + }); + // Verify tunnel is actually alive before reporting it (ngrok may have died externally). + // Probe via GET /connect — under dual-listener /health is NOT on the tunnel allowlist, + // so the old probe would return 404 and always mark the tunnel as dead. + let verifiedTunnelUrl: string | null = null; + const tunnel = ctx.tunnel.state(); + if (tunnel.active && tunnel.url) { + try { + const probe = await fetch(`${tunnel.url}/connect`, { + method: 'GET', + headers: { 'ngrok-skip-browser-warning': 'true' }, + signal: AbortSignal.timeout(5000), + }); + if (probe.ok) { + verifiedTunnelUrl = tunnel.url; + } else { + console.warn(`[browse] Tunnel probe failed (HTTP ${probe.status}), marking tunnel as dead`); + await ctx.tunnel.close(); + } + } catch { + console.warn('[browse] Tunnel probe timed out or unreachable, marking tunnel as dead'); + await ctx.tunnel.close(); + } + } + return json({ + setup_key: setupKey.token, + expires_at: setupKey.expiresAt, + scopes: setupKey.scopes, + tunnel_url: verifiedTunnelUrl, + server_url: `http://127.0.0.1:${ctx.browsePort}`, + ...(superseded ? { superseded } : {}), + }); + } catch (err) { + // Name the caller's typo (bad scope, negative rateLimit, reserved + // clientId) instead of hiding it behind the generic body error. + if (err instanceof InvalidScopeError || err instanceof ReservedClientIdError) { + return jsonError(400, err.message); + } + return jsonError(400, 'Invalid request body'); + } + }, + }, +]; diff --git a/browse/src/routes/pty.ts b/browse/src/routes/pty.ts new file mode 100644 index 000000000..a62dd93e4 --- /dev/null +++ b/browse/src/routes/pty.ts @@ -0,0 +1,254 @@ +/** + * Terminal (PTY) routes: session mint, re-attach, restart, dispose, lease + * refresh from terminal-agent, and the pre-inject prompt-injection scan. + * All are local-only: the tunnel surface 404s them by default-deny. + */ + +import { json, jsonError, type RouteEntry } from './table'; +import { mintPtySessionToken, buildPtySetCookie, revokePtySessionToken } from '../pty-session-cookie'; +import { mintLease, validateLease, refreshLease, revokeLease } from '../pty-session-lease'; +import { isSidecarAvailable, scanWithSidecar } from '../security-sidecar-client'; +import { sanitizeReplacer } from '../sanitize'; + +async function readJsonOrNull(req: Request): Promise { + try { return await req.json(); } catch { return null; } +} + +export const ptyRoutes: RouteEntry[] = [ + // ─── /pty-session — mint sessionId + lease + attachToken ───────── + // + // v1.44+ four-tuple shape: + // { terminalPort, sessionId, attachToken, leaseExpiresAt } + // + // - sessionId : stable, non-secret. Safe to log. Identifies "this + // terminal" across re-attaches. + // - attachToken : short-lived (30 min wall, single attach in practice + // since the agent revokes on WS close). Bearer for + // the /ws upgrade. + // - leaseExpiresAt: client-visible deadline for the lease. Re-attach + // only works inside this window. + // + // The lease + attachToken are minted together so a successful + // /pty-session is one round trip. Re-attach mints a fresh attachToken + // for the SAME sessionId via /pty-session/reattach. + { + method: 'POST', path: '/pty-session', auth: 'root-bearer', surfaces: ['local'], + handler: async (_req, _r, ctx) => { + const port = ctx.terminal.readPort(); + if (!port) return jsonError(503, 'terminal-agent not ready'); + const lease = mintLease(); + const minted = mintPtySessionToken(); + const granted = await ctx.terminal.grantToken(minted.token, lease.sessionId); + if (!granted) { + revokePtySessionToken(minted.token); + revokeLease(lease.sessionId); + return jsonError(503, 'failed to grant terminal session'); + } + return json({ + terminalPort: port, + sessionId: lease.sessionId, + attachToken: minted.token, + leaseExpiresAt: lease.expiresAt, + // Legacy alias — extensions still on the v1.43 wire shape keep + // working. Drop after one minor release once dogfood confirms. + ptySessionToken: minted.token, + expiresAt: minted.expiresAt, + }, { headers: { 'Set-Cookie': buildPtySetCookie(minted.token) } }); + }, + }, + + // ─── /pty-session/reattach — mint fresh attachToken for existing sessionId + // + // Validates the lease (rejects unknown/expired sessionId with 410 Gone), + // mints a fresh short-lived attachToken bound to the same sessionId, and + // pushes it to the agent. The client opens a new WS with the new token; + // the agent matches the sessionId binding and re-attaches to the existing + // PtySession (kept alive for the 60s detach window). + { + method: 'POST', path: '/pty-session/reattach', auth: 'root-bearer', surfaces: ['local'], + handler: async (req, _r, ctx) => { + const port = ctx.terminal.readPort(); + if (!port) return jsonError(503, 'terminal-agent not ready'); + const body = await readJsonOrNull(req); + const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : null; + const v = sessionId ? validateLease(sessionId) : { ok: false as const }; + // 410 Gone — session window has closed (lease expired or never + // existed). Client must fall back to /pty-session for a brand-new + // session. + if (!v.ok) return jsonError(410, 'lease expired or unknown'); + const minted = mintPtySessionToken(); + const granted = await ctx.terminal.grantToken(minted.token, sessionId!); + if (!granted) { + revokePtySessionToken(minted.token); + return jsonError(503, 'failed to grant attach token'); + } + return json({ + terminalPort: port, + sessionId, + attachToken: minted.token, + leaseExpiresAt: v.ok ? v.expiresAt : 0, + }); + }, + }, + + // ─── /pty-restart — one-transaction kill + fresh mint ──────────── + // + // The Restart button. Synchronously disposes the caller's existing + // PtySession on the agent, revokes the old lease, mints a fresh + // sessionId + lease + attachToken, and returns the new 4-tuple in + // one response. Zero race window between kill and mint. + { + method: 'POST', path: '/pty-restart', auth: 'root-bearer', surfaces: ['local'], + handler: async (req, _r, ctx) => { + const port = ctx.terminal.readPort(); + if (!port) return jsonError(503, 'terminal-agent not ready'); + const body = await readJsonOrNull(req); + const oldSessionId = typeof body?.sessionId === 'string' ? body.sessionId : null; + // Best-effort dispose. Missing/unknown sessionId is non-fatal — + // the client may be doing a "restart from scratch" with no prior + // session (e.g. ENDED state). The fresh mint always proceeds. + if (oldSessionId) { + await ctx.terminal.restartSession(oldSessionId); + revokeLease(oldSessionId); + } + const lease = mintLease(); + const minted = mintPtySessionToken(); + const granted = await ctx.terminal.grantToken(minted.token, lease.sessionId); + if (!granted) { + revokePtySessionToken(minted.token); + revokeLease(lease.sessionId); + return jsonError(503, 'failed to grant terminal session'); + } + return json({ + terminalPort: port, + sessionId: lease.sessionId, + attachToken: minted.token, + leaseExpiresAt: lease.expiresAt, + }); + }, + }, + + // ─── /pty-dispose — explicit teardown (pagehide / browser quit) ── + // + // sendBeacon-compatible: accepts the auth token in the BODY so the + // extension's pagehide handler can fire it without setting headers + // (sendBeacon doesn't support custom headers). Without this, every + // browser quit + sidebar close leaves a zombie PTY alive for the 60s + // detach window. + { + method: 'POST', path: '/pty-dispose', auth: 'handler', surfaces: ['local'], + handlerAuth: 'root token as Authorization: Bearer or as the JSON body authToken (sendBeacon); 401 Unauthorized otherwise', + handler: async (req, _r, ctx) => { + const body = await readJsonOrNull(req); + const authTokenFromBody = typeof body?.authToken === 'string' ? body.authToken : null; + const header = req.headers.get('authorization'); + const headerToken = header?.startsWith('Bearer ') ? header.slice(7) : null; + if (!ctx.isRootTokenValue(headerToken) && !ctx.isRootTokenValue(authTokenFromBody)) { + return jsonError(401, 'Unauthorized'); + } + const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : null; + if (sessionId) { + await ctx.terminal.restartSession(sessionId); + revokeLease(sessionId); + } + return json({ ok: true }); + }, + }, + + // ─── /internal/lease-refresh — loopback from terminal-agent on keepalive + // + // PTY-only idle reset: the headless daemon's idle timer must reset only + // on active PTY usage, not on every passive SSE consumer. Terminal-agent + // calls this endpoint (lazily, only when its cached lease is within 5 min + // of expiry) on its 25s keepalive cycle. Refreshing the lease here also + // bumps lastActivity so the daemon stays alive while a sidebar terminal + // is actively in use. Bound to the root authToken so an external caller + // can't refresh another user's lease. Body: {sessionId}. + { + method: 'POST', path: '/internal/lease-refresh', auth: 'root-bearer', surfaces: ['local'], + handler: async (req, _r, ctx) => { + const body = await readJsonOrNull(req); + const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : null; + const r = sessionId ? refreshLease(sessionId) : { ok: false as const }; + if (!r.ok) return jsonError(410, 'lease expired or unknown'); + ctx.resetIdleTimer(); + return json({ ok: true, expiresAt: r.expiresAt }); + }, + }, + + // ─── /pty-inject-scan — pre-inject prompt-injection scan for the + // extension's gstackInjectToTerminal callers. The extension routes + // every page-derived text through this endpoint BEFORE writing to + // the PTY (#1370). Sidecar absence degrades to L4 unavailable + // (extension shows WARN + user confirm per D7). + { + method: 'POST', path: '/pty-inject-scan', auth: 'root-bearer', surfaces: ['local'], + handler: async (req) => { + const reply = (body: unknown, status: number) => json(body, { status, replacer: sanitizeReplacer }); + // 64KB request cap. Defense against accidentally posting an + // entire page DOM into the PTY path. + const contentLength = Number(req.headers.get('content-length') || '0'); + if (contentLength > 64 * 1024) return reply({ error: 'payload-too-large', limit: 65536 }, 413); + let body: { text?: unknown; origin?: unknown } = {}; + try { + body = (await req.json()) as { text?: unknown; origin?: unknown }; + } catch { + return reply({ error: 'malformed-json' }, 400); + } + const text = typeof body.text === 'string' ? body.text : ''; + if (text.length === 0) return reply({ error: 'missing-text' }, 400); + + // L1-L3 honest accounting: + // - URL blocklist forced to BLOCK in PTY context (override + // BROWSE_CONTENT_FILTER default — page-derived text in the + // REPL is a higher-risk surface than ordinary tool output). + // - L4 ML classifier via the sidecar when available. + // - L1-L3 envelope/datamarking is INFORMATIONAL only; the + // verdict is driven by the URL blocklist + L4. + // See CLAUDE.md "Sidebar security stack". + let verdict: 'PASS' | 'WARN' | 'BLOCK' = 'PASS'; + const reasons: string[] = []; + + // Quick URL-blocklist check: text containing a known bad-actor + // domain → BLOCK. + if (/(\bbit\.ly|\btinyurl\.com|\bdiscord\.gg)/i.test(text)) { + verdict = 'BLOCK'; + reasons.push('url-blocklist'); + } + + const sidecarAvail = isSidecarAvailable(); + let l4: { available: boolean; verdict?: unknown; error?: string } = { + available: sidecarAvail.available, + }; + if (sidecarAvail.available && verdict !== 'BLOCK') { + try { + const { verdict: layerVerdict } = await scanWithSidecar(text, { timeoutMs: 5000 }); + l4 = { available: true, verdict: layerVerdict }; + // LayerSignal shape: { verdict: 'safe'|'suspicious'|'unsafe', ... } + const lv = (layerVerdict as { verdict?: string })?.verdict; + if (lv === 'unsafe') { + verdict = 'BLOCK'; + reasons.push('l4-unsafe'); + } else if (lv === 'suspicious') { + verdict = 'WARN'; + reasons.push('l4-suspicious'); + } + } catch (err) { + l4 = { available: false, error: err instanceof Error ? err.message : String(err) }; + // L4 failure during scan: degrade to WARN per D7. + if (verdict === 'PASS') { + verdict = 'WARN'; + reasons.push('l4-unavailable'); + } + } + } else if (!sidecarAvail.available && verdict === 'PASS') { + verdict = 'WARN'; + reasons.push(`l4-unavailable:${sidecarAvail.reason ?? 'unknown'}`); + } + + // BLOCK decisions are surfaced in the response shape; the extension + // logs the BLOCK event into its own activity feed on receipt. + return reply({ verdict, reasons, l4, datamark: '' }, 200); + }, + }, +]; diff --git a/browse/src/routes/table.ts b/browse/src/routes/table.ts new file mode 100644 index 000000000..cabae2f41 --- /dev/null +++ b/browse/src/routes/table.ts @@ -0,0 +1,182 @@ +/** + * Browse route table: owns route entries, the one auth gate, the per-kind + * denials, json()/jsonError() and the unmatched fallthrough. Moved from the + * if-chain in server.ts buildFetchHandler; handlers live in routes/.ts + * and the ordered list is ROUTES in routes/index.ts. Add a route: + * { method: 'GET', path: '/thing', auth: 'root-bearer', surfaces: ['local'], + * handler: (req, r, ctx) => json({ ok: true }) } + * A 'tunnel' surface also needs the TUNNEL_PATHS literal in server.ts. + * Enforced by browse/test/server-route-dispatch-ratchet.test.ts. + */ + +import type { BrowserManager } from '../browser-manager'; +import type { TokenInfo } from '../token-registry'; + +/** Which HTTP listener accepted this request. */ +export type Surface = 'local' | 'tunnel'; + +/** + * The check the gate runs before a handler. `handler` means the gate admits + * the request and the handler authenticates it itself; the entry's + * `handlerAuth` says how (used only where today's denial differs from every + * gate kind: POST /token, POST /pty-dispose and the /cookie-picker sub-router). + */ +export type AuthKind = + | 'none' + | 'root-bearer' + | 'root-token' + | 'scoped' + | 'extension-origin' + | 'root-or-sse-cookie' + | 'handler'; + +type GatedKind = Exclude; + +/** Every gate-level denial, defined once per auth kind. */ +export const AUTH_DENIALS: Record = { + 'root-bearer': { status: 401, error: 'Unauthorized' }, + 'scoped': { status: 401, error: 'Unauthorized' }, + 'root-or-sse-cookie': { status: 401, error: 'Unauthorized' }, + 'root-token': { status: 403, error: 'Root token required' }, + 'extension-origin': { status: 403, error: 'Forbidden' }, +}; + +/** + * What handlers may use instead of closing over buildFetchHandler locals. + * Auth arrives as check functions; the raw root token is only + * `bootstrapRootToken`, read by POST /extension-token (returns it) and + * /cookie-picker* (passes it to its sub-router). + */ +export interface RouteContext { + browserManager: BrowserManager; + startTime: number; + browsePort: number; + /** Constant-time `Authorization: Bearer ` check. */ + validateAuth(req: Request): boolean; + /** Bearer token equals the token registry's root token. */ + isRootRequest(req: Request): boolean; + /** Root or scoped TokenInfo for the bearer token, or null. */ + getTokenInfo(req: Request): TokenInfo | null; + /** The request carries a live view-only SSE session cookie. */ + hasSseCookie(req: Request): boolean; + /** Origin is the pinned gstack extension and Host is loopback. */ + isPinnedExtensionRequest(req: Request): boolean; + /** A token string (header or sendBeacon body) equals cfg.authToken. */ + isRootTokenValue(token: string | null): boolean; + bootstrapRootToken: string; + resetIdleTimer(): void; + terminal: { + readPort(): number | null; + grantToken(token: string, sessionId?: string): Promise; + restartSession(sessionId: string): Promise; + }; + tunnel: { + state(): { active: boolean; url: string | null; hasListener: boolean }; + close(): Promise; + resolveAuthtoken(): string | null; + start(authtoken: string): Promise<{ ok: true; url: string } | { ok: false; stage: 'bind' | 'ngrok'; error: Error }>; + }; + commands: { + handle(body: any, tokenInfo: TokenInfo | null): Promise; + handleInternal( + body: any, + tokenInfo: TokenInfo | null, + opts: { skipRateCheck?: boolean; skipActivity?: boolean }, + ): Promise<{ status: number; result: string; json?: boolean }>; + }; +} + +/** Per-request facts the dispatcher hands a handler. */ +export interface RouteRequest { + url: URL; + surface: Surface; + /** TokenInfo resolved by a 'scoped' gate; null for every other kind. */ + tokenInfo: TokenInfo | null; +} + +export type RouteHandler = (req: Request, r: RouteRequest, ctx: RouteContext) => Promise | Response; + +export interface RouteEntry { + /** HTTP method, or '*' for any method. */ + method: string; + path: string; + /** Match every pathname starting with `path` (sub-routers). */ + prefix?: true; + auth: AuthKind; + surfaces: readonly Surface[]; + /** Required when auth is 'handler': where and how the handler authenticates. */ + handlerAuth?: string; + handler: RouteHandler; +} + +export function json( + body: unknown, + init: { status?: number; headers?: Record; replacer?: (key: string, value: unknown) => unknown } = {}, +): Response { + return new Response(JSON.stringify(body, init.replacer as any), { + status: init.status ?? 200, + headers: { 'Content-Type': 'application/json', ...init.headers }, + }); +} + +export function jsonError(status: number, error: string, extra: Record = {}): Response { + return json({ error, ...extra }, { status }); +} + +/** Runs an entry's auth kind. Returns the resolved TokenInfo, or the kind's denial. */ +export function checkRouteAuth(auth: AuthKind, req: Request, ctx: RouteContext): { tokenInfo: TokenInfo | null } | Response { + const admitted = { tokenInfo: null }; + switch (auth) { + case 'none': + case 'handler': + return admitted; + case 'root-bearer': + return ctx.validateAuth(req) ? admitted : deny(auth); + case 'root-or-sse-cookie': + return ctx.validateAuth(req) || ctx.hasSseCookie(req) ? admitted : deny(auth); + case 'root-token': + return ctx.isRootRequest(req) ? admitted : deny(auth); + case 'extension-origin': + return ctx.isPinnedExtensionRequest(req) ? admitted : deny(auth); + case 'scoped': { + const tokenInfo = ctx.getTokenInfo(req); + return tokenInfo ? { tokenInfo } : deny(auth); + } + } +} + +function deny(auth: GatedKind): Response { + const { status, error } = AUTH_DENIALS[auth]; + return jsonError(status, error); +} + +/** + * The declared fallthrough for a request no entry matches (unknown path, or a + * known path with a method no entry accepts): the root-bearer check, then a + * plain-text 404. + */ +export const UNMATCHED_ROUTE = { + auth: 'root-bearer', + handler: () => new Response('Not found', { status: 404 }), +} as const satisfies Pick; + +export function findRoute(routes: readonly RouteEntry[], method: string, pathname: string, surface: Surface): RouteEntry | null { + return routes.find(r => + r.surfaces.includes(surface) + && (r.method === '*' || r.method === method) + && (r.prefix ? pathname.startsWith(r.path) : pathname === r.path), + ) ?? null; +} + +export async function dispatchRoute( + routes: readonly RouteEntry[], + req: Request, + url: URL, + surface: Surface, + ctx: RouteContext, +): Promise { + const entry = findRoute(routes, req.method, url.pathname, surface) ?? UNMATCHED_ROUTE; + const gate = checkRouteAuth(entry.auth, req, ctx); + if (gate instanceof Response) return gate; + return entry.handler(req, { url, surface, tokenInfo: gate.tokenInfo }, ctx); +} diff --git a/browse/src/routes/tokens.ts b/browse/src/routes/tokens.ts new file mode 100644 index 000000000..e4a562863 --- /dev/null +++ b/browse/src/routes/tokens.ts @@ -0,0 +1,86 @@ +/** + * Scoped-token administration: mint (POST /token), revoke (the /token/* + * sub-router, DELETE /token/:clientId) and list (GET /agents). Root-only. + */ + +import { json, jsonError, type RouteEntry } from './table'; +import { createToken, revokeToken, listTokens, InvalidScopeError, ReservedClientIdError } from '../token-registry'; + +export const tokenRoutes: RouteEntry[] = [ + // ─── /token — mint scoped tokens (root-only) ────────────────── + { + method: 'POST', path: '/token', auth: 'handler', surfaces: ['local'], + handlerAuth: 'root token (token registry); 403 "Only the root token can mint sub-tokens" otherwise', + handler: async (req, _r, ctx) => { + if (!ctx.isRootRequest(req)) return jsonError(403, 'Only the root token can mint sub-tokens'); + try { + const tokenBody = await req.json() as any; + if (!tokenBody.clientId) return jsonError(400, 'Missing clientId'); + const session = createToken({ + clientId: tokenBody.clientId, + scopes: tokenBody.scopes, + domains: tokenBody.domains, + tabPolicy: tokenBody.tabPolicy, + rateLimit: tokenBody.rateLimit, + expiresSeconds: tokenBody.expiresSeconds, + }); + return json({ + token: session.token, + expires: session.expiresAt, + scopes: session.scopes, + agent: session.clientId, + }); + } catch (err) { + // Name the caller's typo (bad scope, negative rateLimit, reserved + // clientId) instead of hiding it behind the generic body error. + if (err instanceof InvalidScopeError || err instanceof ReservedClientIdError) { + return jsonError(400, err.message); + } + return jsonError(400, 'Invalid request body'); + } + }, + }, + + // ─── /token/:clientId — revoke a scoped token (root-only) ───── + { + method: 'DELETE', path: '/token/', prefix: true, auth: 'root-token', surfaces: ['local'], + handler: (_req, { url }, ctx) => { + // decodeURIComponent so CLI-encoded names (spaces, UTF-8) round-trip. + let clientId: string; + try { + clientId = decodeURIComponent(url.pathname.slice('/token/'.length)); + } catch { + return jsonError(400, 'Malformed client ID encoding'); + } + const revoked = revokeToken(clientId); + // Release tabs UNCONDITIONALLY: ownership outlives the token (it clears + // only on tab close), so a client whose token already expired can still + // own tabs. Gating release on a revoke hit would orphan that ownership + // and let a same-name re-pair inherit an authenticated tab. + const tabsReleased = ctx.browserManager.releaseClientTabs(clientId).length; + if (!revoked && tabsReleased === 0) return jsonError(404, `Agent "${clientId}" not found`); + console.log(`[browse] Revoked ${revoked} token(s), released ${tabsReleased} tab(s) for: ${clientId}`); + return json({ revoked: clientId, tokens_deleted: revoked, tabs_released: tabsReleased }); + }, + }, + + // ─── /agents — list connected agents (root-only) ────────────── + { + method: 'GET', path: '/agents', auth: 'root-token', surfaces: ['local'], + handler: () => { + // includeSetup: pending (unexchanged) setup keys are live grants the + // operator must be able to see — without them, revoking a paired-but- + // never-connected agent "works" while the list shows nothing. + const agents = listTokens({ includeSetup: true }).map(t => ({ + clientId: t.clientId, + scopes: t.scopes, + domains: t.domains, + expiresAt: t.expiresAt, + commandCount: t.commandCount, + createdAt: t.createdAt, + pending: t.type === 'setup', + })); + return json({ agents }); + }, + }, +]; diff --git a/browse/src/routes/tunnel.ts b/browse/src/routes/tunnel.ts new file mode 100644 index 000000000..32c4ab522 --- /dev/null +++ b/browse/src/routes/tunnel.ts @@ -0,0 +1,62 @@ +/** + * POST /tunnel/start — start the ngrok tunnel on demand (root-only). + * + * Dual-listener model: binds a SECOND Bun.serve listener on an ephemeral + * 127.0.0.1 port dedicated to tunnel traffic, then points ngrok.forward() at + * THAT port. The local listener (which serves /extension-token, + * /cookie-picker, /inspector/*, welcome, etc.) is never exposed to ngrok. + * Hard fail if the tunnel listener bind fails — NEVER fall back to the local + * port, which would silently defeat the whole security property. + */ + +import { json, jsonError, type RouteEntry } from './table'; +import { isPairAgentEnabled } from '../config'; + +export const tunnelRoutes: RouteEntry[] = [ + { + method: 'POST', path: '/tunnel/start', auth: 'root-token', surfaces: ['local'], + handler: async (_req, _r, ctx) => { + if (!isPairAgentEnabled()) { + // Consent-on-first-use: the /pair-agent skill asks once and sets the + // key; a direct API caller gets the same hint instead of a tunnel. + return jsonError(403, 'pair-agent is off (tunnel exposes this browser beyond the machine)', { + hint: 'enable once with: gstack-config set pair_agent on — or run /pair-agent, which asks for consent and sets it', + }); + } + const tunnel = ctx.tunnel.state(); + if (tunnel.active && tunnel.url && tunnel.hasListener) { + // Verify tunnel is still alive before returning cached URL. + // Probe GET /connect (the only unauth-reachable path on the tunnel + // surface); /health is NOT tunnel-reachable under dual-listener. + try { + const probe = await fetch(`${tunnel.url}/connect`, { + method: 'GET', + headers: { 'ngrok-skip-browser-warning': 'true' }, + signal: AbortSignal.timeout(5000), + }); + if (probe.ok) return json({ url: tunnel.url, already_active: true }); + } catch {} + // Tunnel is dead — tear down cleanly before restarting + console.warn('[browse] Cached tunnel is dead, restarting...'); + await ctx.tunnel.close(); + } + + // 1) Resolve ngrok authtoken from env / .gstack / native config + const authtoken = ctx.tunnel.resolveAuthtoken(); + if (!authtoken) { + return jsonError(400, 'No ngrok authtoken found', { hint: 'Run: ngrok config add-authtoken YOUR_TOKEN' }); + } + + // 2) Bind the tunnel listener + open ngrok via the shared startTunnel + // helper (hard-fails the bind, cleans up both ngrok and the Bun + // listener on any post-bind failure). + const started = await ctx.tunnel.start(authtoken); + if (!started.ok) { + return jsonError(500, started.stage === 'bind' + ? `Failed to bind tunnel listener: ${started.error.message}` + : `Failed to open ngrok tunnel: ${started.error.message}`); + } + return json({ url: started.url }); + }, + }, +]; diff --git a/browse/src/server.ts b/browse/src/server.ts index c5ba7a783..b86bb7e69 100644 --- a/browse/src/server.ts +++ b/browse/src/server.ts @@ -17,34 +17,27 @@ import { BrowserManager, markDaemonProcess } from './browser-manager'; import { handleReadCommand, hasOutArg } from './read-commands'; import { handleWriteCommand } from './write-commands'; import { handleMetaCommand } from './meta-commands'; -import { handleCookiePickerRoute, hasActivePicker } from './cookie-picker-routes'; +import { hasActivePicker } from './cookie-picker-routes'; import { COMMAND_DESCRIPTIONS, PAGE_CONTENT_COMMANDS, DOM_CONTENT_COMMANDS, wrapUntrustedContent, canonicalizeCommand, buildUnknownCommandError, ALL_COMMANDS } from './commands'; import { wrapUntrustedPageContent, datamarkContent, runContentFilters, type ContentFilterResult, markHiddenElements, getCleanTextWithStripping, cleanupHiddenMarkers, } from './content-security'; -import { isSidecarAvailable, scanWithSidecar } from './security-sidecar-client'; import { writeSecureFile, mkdirSecure, appendSecureFile } from './file-permissions'; import { handleSnapshot, SNAPSHOT_FLAGS } from './snapshot'; import { initRegistry, validateToken as validateScopedToken, checkScope, checkDomain, - checkRate, createToken, createSetupKey, exchangeSetupKey, revokeToken, - listTokens, recordCommand, - isRootToken, checkConnectRateLimit, type TokenInfo, type ScopeCategory, - DEFAULT_PAIR_SCOPES, InvalidScopeError, ReservedClientIdError, assertValidClientId, - assertValidTokenOptions, revokeSetupKeys, getClientSession, grantReducesAccess, + checkRate, recordCommand, isRootToken, type TokenInfo, } from './token-registry'; -import { validateTempPath } from './path-security'; import { resolveConfig, ensureStateDir, readVersionHash, resolveChromiumProfile, cleanSingletonLocks, isPairAgentEnabled } from './config'; import { isSessionPersistEnabled, persistSessionState, restoreSessionState, sessionPersistIntervalMs, SESSION_STATE_FILE, } from './session-persist'; -import { emitActivity, subscribe, getActivityAfter, getActivityHistory, getSubscriberCount } from './activity'; -import { createSseEndpoint } from './sse-helpers'; +import { emitActivity } from './activity'; import { initAuditLog, writeAuditEntry } from './audit'; -import { inspectElement, modifyStyle, resetModifications, getModificationHistory, detachSession, type InspectorResult } from './cdp-inspector'; +import { detachSession } from './cdp-inspector'; // Bun.spawn used instead of child_process.spawn (compiled bun binaries // fail posix_spawn on all executables including /bin/bash) import { safeUnlink, safeUnlinkQuiet, safeKill } from './error-handling'; @@ -53,23 +46,18 @@ import { } from './port-allocator'; import { acquireAgentStateLock, readAgentRecord, clearAgentRecord, isOurAgent, isAgentRecordLive, isAgentRecordGone, stopAgentByRecord, spawnTerminalAgent } from './terminal-agent-control'; import { isProcessAlive } from './error-handling'; -import { sanitizeBody, stripLoneSurrogateEscapes, stripLoneSurrogates, sanitizeReplacer } from './sanitize'; +import { sanitizeBody, stripLoneSurrogates } from './sanitize'; import { startSocksBridge, testUpstream, type BridgeHandle } from './socks-bridge'; import { parseProxyConfig, toUpstreamConfig, ProxyConfigError } from './proxy-config'; import { writeReceipt } from '../../lib/egress-receipt'; import { redactProxyUrl } from './proxy-redact'; import { type XvfbHandle } from './xvfb'; import { logTunnelDenial } from './tunnel-denial-log'; -import { - mintSseSessionToken, validateSseSessionToken, extractSseCookie, - buildSseSetCookie, SSE_COOKIE_NAME, -} from './sse-session-cookie'; -import { - mintPtySessionToken, buildPtySetCookie, revokePtySessionToken, -} from './pty-session-cookie'; -import { - mintLease, validateLease, refreshLease, revokeLease, -} from './pty-session-lease'; +import { validateSseSessionToken, extractSseCookie } from './sse-session-cookie'; +import { ROUTES } from './routes'; +import { dispatchRoute, type RouteContext, type Surface } from './routes/table'; +import { TUNNEL_COMMANDS, canDispatchOverTunnel } from './routes/commands'; +import { getInspectorSubscriberCount, clearInspectorSubscribers } from './routes/inspector'; import * as fs from 'fs'; import * as net from 'net'; import * as path from 'path'; @@ -167,8 +155,7 @@ let tunnelUrl: string | null = null; let tunnelListener: any = null; // ngrok listener handle let tunnelServer: ReturnType | null = null; // tunnel HTTP listener -/** Which HTTP listener accepted this request. */ -export type Surface = 'local' | 'tunnel'; +export type { Surface }; /** * Factory contract for embedders (gbrowser phoenix overlay). @@ -199,7 +186,7 @@ export interface ServerConfig { // were documented but never read (the idle timer, activity state, and // shutdown target are module-global, so per-factory wiring would lie for // any embedder running >1 handler). Real support belongs to the deferred - // server.ts singleton/route-table refactor. Until then: BROWSE_IDLE_TIMEOUT + // server.ts singleton refactor. Until then: BROWSE_IDLE_TIMEOUT // and CHROMIUM_PROFILE env are the honest knobs. /** Caller-owned. shutdown() does NOT call xvfb.stop(); caller is responsible. */ xvfb?: XvfbHandle | null; @@ -299,7 +286,9 @@ export function resolveConfigFromEnv(): Omit([ '/connect', @@ -318,43 +307,26 @@ const TUNNEL_PATHS = new Set([ export const GSTACK_EXTENSION_ID = 'dgbkdbjebeiblbajiilljmhjdpmiglep'; /** - * Commands reachable via POST /command over the tunnel surface. A paired - * remote agent can drive the browser (goto, click, text, etc.) but cannot - * configure the daemon, bootstrap new sessions, import cookies, or reach - * extension-inspector state. This allowlist maps to the eng-review decision - * logged in the CEO plan for sec-wave v1.6.0.0. + * The extension-origin auth check (POST /extension-token): Origin is exactly + * the pinned extension and Host is loopback. Defense-in-depth alongside the + * 127.0.0.1 bind: a DNS-rebinding page can't present a localhost Host header. + * Host arrives as '127.0.0.1:34567', so parse out the hostname — never compare + * the raw header (which carries the port) against a literal. */ -export const TUNNEL_COMMANDS = new Set([ - // Original 17 - 'goto', 'click', 'text', 'screenshot', - 'html', 'links', 'forms', 'accessibility', - 'attrs', 'media', 'data', - 'scroll', 'press', 'type', 'select', 'wait', 'eval', - // Tab + navigation primitives operator docs and CLI hints already promised - 'newtab', 'tabs', 'back', 'forward', 'reload', - // Read/inspect/write operators paired agents need to be useful - 'snapshot', 'fill', 'url', 'closetab', -]); - -/** - * Pure gate: returns true iff the command is reachable over the tunnel surface. - * Extracted from the inline /command handler so the gate logic is unit-testable - * without standing up an HTTP listener. Behavior is identical to the inline - * check; the function canonicalizes the command (so aliases hit the same set) - * and returns false for null/undefined input. - * - * `args` is consulted so an `--out` invocation (e.g. `eval --out `) is - * NEVER tunnel-dispatchable: `--out` turns an otherwise-readable command into a - * local-disk WRITE, and the tunnel surface never grants disk-write capability to - * remote paired agents. Omitting `args` preserves the old command-only behavior. - */ -export function canDispatchOverTunnel(command: string | undefined | null, args?: string[]): boolean { - if (typeof command !== 'string' || command.length === 0) return false; - if (Array.isArray(args) && hasOutArg(args)) return false; - const cmd = canonicalizeCommand(command); - return TUNNEL_COMMANDS.has(cmd); +function isPinnedExtensionRequest(req: Request): boolean { + let hostname: string | null = null; + try { + hostname = new URL(`http://${req.headers.get('host') ?? ''}`).hostname; + } catch (err) { + if (!(err instanceof TypeError)) throw err; // TypeError = malformed Host + } + const originOk = req.headers.get('origin') === `chrome-extension://${GSTACK_EXTENSION_ID}`; + const hostOk = hostname === '127.0.0.1' || hostname === 'localhost'; + return originOk && hostOk; } +export { TUNNEL_COMMANDS, canDispatchOverTunnel }; + /** * Read ngrok authtoken from env var, ~/.gstack/ngrok.env, or ngrok's native * config files. Returns null if nothing found. Shared between the @@ -639,6 +611,7 @@ function generateHelpText(): string { // ─── Buffer (from buffers.ts) ──────────────────────────────────── import { consoleBuffer, networkBuffer, dialogBuffer, addConsoleEntry, addNetworkEntry, addDialogEntry, type LogEntry, type NetworkEntry, type DialogEntry } from './buffers'; + export { consoleBuffer, networkBuffer, dialogBuffer, addConsoleEntry, addNetworkEntry, addDialogEntry, type LogEntry, type NetworkEntry, type DialogEntry }; const CONSOLE_LOG_PATH = config.consoleLog; @@ -752,6 +725,7 @@ const idleCheckInterval = setInterval(idleCheckTick, 60_000); // dual-instance fix` describe block for usage. export const __testInternals__ = { serverInstanceId: SERVER_INSTANCE_ID, + tunnelPaths: TUNNEL_PATHS as ReadonlySet, idleCheckTick, // Watchdog seams (watchdog.test.ts): drive the 15s poll against an // arbitrary (dead) PID, trigger the handoff-promotion suppression exactly @@ -896,6 +870,7 @@ function suppressHeadedParentShutdown(stateConfig: ServerConfig['config'] = conf // ─── Command Sets (from commands.ts — single source of truth) ─── import { READ_COMMANDS, WRITE_COMMANDS, META_COMMANDS } from './commands'; + export { READ_COMMANDS, WRITE_COMMANDS, META_COMMANDS }; /** @@ -911,28 +886,7 @@ function isWriteInvocation(command: string, args: string[]): boolean { return WRITE_COMMANDS.has(command) || hasOutArg(args); } -// ─── Inspector State (in-memory) ────────────────────────────── -let inspectorData: InspectorResult | null = null; -let inspectorTimestamp: number = 0; - -// Inspector SSE subscribers -type InspectorSubscriber = (event: any) => void; -const inspectorSubscribers = new Set(); - -/** Diagnostic accessor used by the $B memory snapshot. */ -export function getInspectorSubscriberCount(): number { - return inspectorSubscribers.size; -} - -function emitInspectorEvent(event: any): void { - for (const notify of inspectorSubscribers) { - queueMicrotask(() => { - try { notify(event); } catch (err: any) { - console.error('[browse] Inspector event subscriber threw:', err.message); - } - }); - } -} +export { getInspectorSubscriberCount }; // ─── Server ──────────────────────────────────────────────────── const browserManager = new BrowserManager(); @@ -1408,7 +1362,7 @@ export function buildCommandResponse(cr: CommandResult): Response { } /** HTTP wrapper — converts CommandResult to Response. Used by the /command - * route dispatcher (line ~2158). The wrapper layer exists so + * route (routes/commands.ts, via RouteContext). The wrapper layer exists so * `buildCommandResponse` is independently unit-testable (v1.38.1.0). */ async function handleCommand(body: any, tokenInfo?: TokenInfo | null): Promise { @@ -1740,7 +1694,7 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle { try { detachSession(); } catch (err: any) { console.warn('[browse] Failed to detach CDP session:', err.message); } - inspectorSubscribers.clear(); + clearInspectorSubscribers(); if (cfgBrowserManager.isWatching()) cfgBrowserManager.stopWatch(); clearInterval(flushInterval); clearInterval(idleCheckInterval); @@ -1838,13 +1792,37 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle { await activeShutdown?.(code ?? 2); }; - // Substitute cfgBrowserManager for module-level browserManager in the - // dispatcher body so all browser-state reads/writes go through the cfg - // instance. Other module-level references (handleCommand, getTokenInfo, - // isRootRequest, etc.) take the token as a parameter and are passed - // `authToken` (the cfg-derived value) explicitly. - const browserManager = cfgBrowserManager; - + // Everything a route handler may use. Handlers get the cfg-provided + // BrowserManager and auth checks as functions; the raw token reaches only + // the two bootstrap routes that hand it on (see RouteContext). + const routeCtx: RouteContext = { + browserManager: cfgBrowserManager, + startTime, + browsePort, + validateAuth, + isRootRequest, + getTokenInfo, + hasSseCookie: (req) => validateSseSessionToken(extractSseCookie(req)), + isPinnedExtensionRequest, + isRootTokenValue: (token) => token !== null && token === authToken, + bootstrapRootToken: authToken, + resetIdleTimer, + terminal: { readPort: readTerminalPort, grantToken: grantPtyToken, restartSession: restartPtySession }, + tunnel: { + state: () => ({ active: tunnelActive, url: tunnelUrl, hasListener: tunnelServer !== null }), + close: closeTunnel, + resolveAuthtoken: resolveNgrokAuthtoken, + start: (authtoken) => startTunnel({ + fetchHandler: makeFetchHandler('tunnel'), + authtoken, + consent: 'pair_agent=on (isPairAgentEnabled gate at /tunnel/start)', + }), + }, + commands: { + handle: handleCommand, + handleInternal: (body, tokenInfo, opts) => handleCommandInternal(body, tokenInfo, opts), + }, + }; const makeFetchHandler = (surface: Surface) => async (req: Request): Promise => { const url = new URL(req.url); @@ -1885,1225 +1863,7 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle { if (overlayResp) return overlayResp; } - // GET /connect — alive probe. Unauth on both surfaces. Used by /pair - // and /tunnel/start to detect dead ngrok tunnels via the tunnel URL, - // since /health is not tunnel-reachable under the dual-listener design. - // - // Shares the same rate limit as POST /connect — otherwise a tunnel - // caller can probe unlimited GETs and lock out nothing, which makes - // the endpoint a free daemon-enumeration surface. - if (url.pathname === '/connect' && req.method === 'GET') { - if (!checkConnectRateLimit()) { - return new Response(JSON.stringify({ error: 'Rate limited' }), { - status: 429, headers: { 'Content-Type': 'application/json' }, - }); - } - return new Response(JSON.stringify({ alive: true }), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } - - // Cookie picker routes — HTML page unauthenticated, data/action routes require auth - if (url.pathname.startsWith('/cookie-picker')) { - return handleCookiePickerRoute(url, req, browserManager, authToken); - } - - // Welcome page — served when GStack Browser launches in headed mode - if (url.pathname === '/welcome') { - const welcomePath = (() => { - // Gate GSTACK_SLUG on a strict regex BEFORE interpolating it into - // the filesystem path. Without this, a slug like "../../etc/passwd" - // would resolve to ~/.gstack/projects/../../etc/passwd/... — path - // traversal. Not exploitable today (attacker needs local env-var - // access), but the gate is one regex and buys us defense-in-depth. - const rawSlug = process.env.GSTACK_SLUG || 'unknown'; - const slug = /^[a-z0-9_-]+$/.test(rawSlug) ? rawSlug : 'unknown'; - const homeDir = process.env.HOME || process.env.USERPROFILE || '/tmp'; - const projectWelcome = `${homeDir}/.gstack/projects/${slug}/designs/welcome-page-20260331/finalized.html`; - if (fs.existsSync(projectWelcome)) return projectWelcome; - // Fallback: built-in welcome page from gstack install. Reject - // SKILL_ROOT values containing '..' for the same defense-in-depth - // reason as the GSTACK_SLUG regex above. Not exploitable today - // (env set at install time), but the gate is one check. - const rawSkillRoot = process.env.GSTACK_SKILL_ROOT || `${homeDir}/.claude/skills/gstack`; - if (rawSkillRoot.includes('..')) return null; - const builtinWelcome = `${rawSkillRoot}/browse/src/welcome.html`; - if (fs.existsSync(builtinWelcome)) return builtinWelcome; - return null; - })(); - if (welcomePath) { - try { - const html = require('fs').readFileSync(welcomePath, 'utf-8'); - return new Response(html, { headers: { 'Content-Type': 'text/html; charset=utf-8' } }); - } catch (err: any) { - console.error('[browse] Failed to read welcome page:', welcomePath, err.message); - } - } - // No welcome page found — serve a simple fallback (avoid ERR_UNSAFE_REDIRECT on Windows) - return new Response( - `GStack Browser - -
◈

GStack Browser ready.

Waiting for commands from Claude Code.

`, - { status: 200, headers: { 'Content-Type': 'text/html; charset=utf-8' } } - ); - } - - // ─── POST /extension-token — pinned-origin token bootstrap ────── - // - // The ONLY endpoint that hands out AUTH_TOKEN. GET /health used to - // carry the token (headed mode + any chrome-extension:// Origin), - // which meant ANY extension — or any localhost caller in headed - // mode — could read the root token. Now the token is released only - // to the one extension identity we ship: the Origin header must be - // exactly `chrome-extension://`, where the ID - // is pinned by the "key" field in extension/manifest.json (derive - // it with `bun browse/scripts/extension-id.ts`). Chrome sets Origin - // on cross-origin POSTs from extension contexts and web pages - // cannot forge a chrome-extension:// Origin. - // - // Local listener only: NEVER added to TUNNEL_PATHS, so the tunnel - // surface 404s it by default-deny. - if (url.pathname === '/extension-token' && req.method === 'POST') { - // Defense-in-depth alongside the 127.0.0.1 bind: a DNS-rebinding - // page can't present a localhost Host header. Host arrives as - // '127.0.0.1:34567', so parse out the hostname — never compare - // the raw header (which carries the port) against a literal. - let hostname: string | null = null; - try { - hostname = new URL(`http://${req.headers.get('host') ?? ''}`).hostname; - } catch (err) { - if (!(err instanceof TypeError)) throw err; // TypeError = malformed Host - } - const originOk = - req.headers.get('origin') === `chrome-extension://${GSTACK_EXTENSION_ID}`; - const hostOk = hostname === '127.0.0.1' || hostname === 'localhost'; - if (!originOk || !hostOk) { - // No detail in the body — don't teach a probing caller which - // check failed. - return new Response(JSON.stringify({ error: 'Forbidden' }), { - status: 403, headers: { 'Content-Type': 'application/json' }, - }); - } - return new Response(JSON.stringify({ token: authToken }), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } - - // Health check — no auth required, does NOT reset idle timer. - // NEVER carries a token in any mode: token bootstrap is - // POST /extension-token (pinned extension Origin) and shell auth - // is POST /pty-session. Liveness/status only. - if (url.pathname === '/health') { - const healthy = await browserManager.isHealthy(); - return new Response(JSON.stringify({ - status: healthy ? 'healthy' : 'unhealthy', - mode: browserManager.getConnectionMode(), - uptime: Math.floor((Date.now() - startTime) / 1000), - tabs: browserManager.getTabCount(), - // No `security` field (#2557): the only writer of the status it - // reported (sidebar-agent.ts's session-state file) went away with - // the chat path, so it read from a file nothing wrote — reporting - // a permanent 'inactive', or a stale false-green 'protected' - // wherever an old state file survived on disk. The live defenses - // (content-security L1-L3, the L4 sidecar on /pty-inject-scan) - // report through their own call sites, not through /health. - // Terminal-agent discovery. ONLY a port number — never a token. - // Tokens flow via the /pty-session HttpOnly cookie path. See - // `pty-session-cookie.ts` for the rationale (codex outside-voice - // finding #2: don't reuse this endpoint for shell auth). - terminalPort: readTerminalPort(), - }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - } - - // ─── /pty-session — mint sessionId + lease + attachToken ───────── - // - // v1.44+ four-tuple shape: - // { terminalPort, sessionId, attachToken, leaseExpiresAt } - // - // - sessionId : stable, non-secret. Safe to log. Identifies "this - // terminal" across re-attaches. - // - attachToken : short-lived (30 min wall, single attach in practice - // since the agent revokes on WS close). Bearer for - // the /ws upgrade. - // - leaseExpiresAt: client-visible deadline for the lease. Re-attach - // only works inside this window. - // - // The lease + attachToken are minted together so a successful - // /pty-session is one round trip. Re-attach mints a fresh attachToken - // for the SAME sessionId via /pty-session/reattach. - // - // NEVER added to TUNNEL_PATHS — the tunnel surface 404s any - // /pty-session attempt by default-deny. - if (url.pathname === '/pty-session' && req.method === 'POST') { - if (!validateAuth(req)) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, headers: { 'Content-Type': 'application/json' }, - }); - } - const port = readTerminalPort(); - if (!port) { - return new Response(JSON.stringify({ - error: 'terminal-agent not ready', - }), { status: 503, headers: { 'Content-Type': 'application/json' } }); - } - const lease = mintLease(); - const minted = mintPtySessionToken(); - const granted = await grantPtyToken(minted.token, lease.sessionId); - if (!granted) { - revokePtySessionToken(minted.token); - revokeLease(lease.sessionId); - return new Response(JSON.stringify({ - error: 'failed to grant terminal session', - }), { status: 503, headers: { 'Content-Type': 'application/json' } }); - } - return new Response(JSON.stringify({ - terminalPort: port, - sessionId: lease.sessionId, - attachToken: minted.token, - leaseExpiresAt: lease.expiresAt, - // Legacy alias — extensions still on the v1.43 wire shape keep - // working. Drop after one minor release once dogfood confirms. - ptySessionToken: minted.token, - expiresAt: minted.expiresAt, - }), { - status: 200, - headers: { - 'Content-Type': 'application/json', - 'Set-Cookie': buildPtySetCookie(minted.token), - }, - }); - } - - // ─── /pty-session/reattach — mint fresh attachToken for existing sessionId - // - // Used by Commit 3's re-attach loop on the client. Validates the - // lease (rejects unknown/expired sessionId with 410 Gone), mints a - // fresh short-lived attachToken bound to the same sessionId, and - // pushes it to the agent. The client opens a new WS with the new - // token; the agent matches the sessionId binding and re-attaches - // to the existing PtySession (kept alive for the 60s detach - // window — Commit 3 wires that side). - if (url.pathname === '/pty-session/reattach' && req.method === 'POST') { - if (!validateAuth(req)) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, headers: { 'Content-Type': 'application/json' }, - }); - } - const port = readTerminalPort(); - if (!port) { - return new Response(JSON.stringify({ error: 'terminal-agent not ready' }), { - status: 503, headers: { 'Content-Type': 'application/json' }, - }); - } - let body: any; - try { body = await req.json(); } catch { body = null; } - const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : null; - const v = sessionId ? validateLease(sessionId) : { ok: false }; - if (!v.ok) { - // 410 Gone — session window has closed (lease expired or never - // existed). Client must fall back to /pty-session for a brand-new - // session. - return new Response(JSON.stringify({ error: 'lease expired or unknown' }), { - status: 410, headers: { 'Content-Type': 'application/json' }, - }); - } - const minted = mintPtySessionToken(); - const granted = await grantPtyToken(minted.token, sessionId!); - if (!granted) { - revokePtySessionToken(minted.token); - return new Response(JSON.stringify({ error: 'failed to grant attach token' }), { - status: 503, headers: { 'Content-Type': 'application/json' }, - }); - } - return new Response(JSON.stringify({ - terminalPort: port, - sessionId, - attachToken: minted.token, - leaseExpiresAt: v.ok ? v.expiresAt : 0, - }), { status: 200, headers: { 'Content-Type': 'application/json' } }); - } - - // ─── /pty-restart — one-transaction kill + fresh mint ──────────── - // - // The Restart button. Synchronously disposes the caller's existing - // PtySession on the agent, revokes the old lease, mints a fresh - // sessionId + lease + attachToken, and returns the new 4-tuple in - // one response. Zero race window between kill and mint (codex T2 - // + D8 of the eng review). - if (url.pathname === '/pty-restart' && req.method === 'POST') { - if (!validateAuth(req)) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, headers: { 'Content-Type': 'application/json' }, - }); - } - const port = readTerminalPort(); - if (!port) { - return new Response(JSON.stringify({ error: 'terminal-agent not ready' }), { - status: 503, headers: { 'Content-Type': 'application/json' }, - }); - } - let body: any; - try { body = await req.json(); } catch { body = null; } - const oldSessionId = typeof body?.sessionId === 'string' ? body.sessionId : null; - // Best-effort dispose. Missing/unknown sessionId is non-fatal — - // the client may be doing a "restart from scratch" with no prior - // session (e.g. ENDED state). The fresh mint always proceeds. - if (oldSessionId) { - await restartPtySession(oldSessionId); - revokeLease(oldSessionId); - } - const lease = mintLease(); - const minted = mintPtySessionToken(); - const granted = await grantPtyToken(minted.token, lease.sessionId); - if (!granted) { - revokePtySessionToken(minted.token); - revokeLease(lease.sessionId); - return new Response(JSON.stringify({ error: 'failed to grant terminal session' }), { - status: 503, headers: { 'Content-Type': 'application/json' }, - }); - } - return new Response(JSON.stringify({ - terminalPort: port, - sessionId: lease.sessionId, - attachToken: minted.token, - leaseExpiresAt: lease.expiresAt, - }), { status: 200, headers: { 'Content-Type': 'application/json' } }); - } - - // ─── /pty-dispose — explicit teardown (pagehide / browser quit) ── - // - // sendBeacon-compatible: accepts the auth token in the BODY so the - // extension's pagehide handler can fire it without setting headers - // (sendBeacon doesn't support custom headers). Codex T3 fix — - // without this, every browser quit + sidebar close leaves a zombie - // PTY alive for the 60s detach window (Commit 3). - if (url.pathname === '/pty-dispose' && req.method === 'POST') { - let body: any; - try { body = await req.json(); } catch { body = null; } - const authTokenFromBody = typeof body?.authToken === 'string' ? body.authToken : null; - // Accept either header bearer OR body authToken. Both must match - // the root auth token; otherwise reject. - const headerToken = extractToken(req); - const authedByHeader = headerToken !== null && headerToken === authToken; - const authedByBody = authTokenFromBody !== null && authTokenFromBody === authToken; - if (!authedByHeader && !authedByBody) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, headers: { 'Content-Type': 'application/json' }, - }); - } - const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : null; - if (sessionId) { - await restartPtySession(sessionId); - revokeLease(sessionId); - } - return new Response(JSON.stringify({ ok: true }), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } - - // ─── /internal/lease-refresh — loopback from terminal-agent on keepalive - // - // T6 PTY-only idle reset (codex outside-voice fix): the headless - // daemon's idle timer must reset only on active PTY usage, not on - // every passive SSE consumer. Terminal-agent calls this endpoint - // (lazily, only when its cached lease is within 5 min of expiry) - // on its 25s keepalive cycle. Refreshing the lease here also bumps - // lastActivity so the daemon stays alive while a sidebar terminal - // is actively in use. - // - // INTERNAL endpoint — bound to the root authToken so an external - // caller can't refresh another user's lease. Body: {sessionId}. - if (url.pathname === '/internal/lease-refresh' && req.method === 'POST') { - if (!validateAuth(req)) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, headers: { 'Content-Type': 'application/json' }, - }); - } - let body: any; - try { body = await req.json(); } catch { body = null; } - const sessionId = typeof body?.sessionId === 'string' ? body.sessionId : null; - const r = sessionId ? refreshLease(sessionId) : { ok: false }; - if (!r.ok) { - return new Response(JSON.stringify({ error: 'lease expired or unknown' }), { - status: 410, headers: { 'Content-Type': 'application/json' }, - }); - } - // T6: PTY activity resets the daemon idle timer. - resetIdleTimer(); - return new Response(JSON.stringify({ ok: true, expiresAt: r.expiresAt }), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } - - // ─── /pty-inject-scan — pre-inject prompt-injection scan for the - // extension's gstackInjectToTerminal callers. The extension routes - // every page-derived text through this endpoint BEFORE writing to - // the PTY (#1370). Local-only by intent: not added to the tunnel - // allowlist; root-token auth required. Sidecar absence degrades to - // L4 unavailable (extension shows WARN + user confirm per D7). - if (url.pathname === '/pty-inject-scan' && req.method === 'POST') { - if (!validateAuth(req)) { - return new Response( - JSON.stringify({ error: 'Unauthorized' }, sanitizeReplacer), - { status: 401, headers: { 'Content-Type': 'application/json' } }, - ); - } - // 64KB request cap. Defense against accidentally posting an - // entire page DOM into the PTY path. - const contentLength = Number(req.headers.get('content-length') || '0'); - if (contentLength > 64 * 1024) { - return new Response( - JSON.stringify({ error: 'payload-too-large', limit: 65536 }, sanitizeReplacer), - { status: 413, headers: { 'Content-Type': 'application/json' } }, - ); - } - let body: { text?: unknown; origin?: unknown } = {}; - try { - body = (await req.json()) as { text?: unknown; origin?: unknown }; - } catch { - return new Response( - JSON.stringify({ error: 'malformed-json' }, sanitizeReplacer), - { status: 400, headers: { 'Content-Type': 'application/json' } }, - ); - } - const text = typeof body.text === 'string' ? body.text : ''; - const origin = typeof body.origin === 'string' ? body.origin : 'unknown'; - if (text.length === 0) { - return new Response( - JSON.stringify({ error: 'missing-text' }, sanitizeReplacer), - { status: 400, headers: { 'Content-Type': 'application/json' } }, - ); - } - - // L1-L3 honest accounting (codex review correction): - // - URL blocklist forced to BLOCK in PTY context (override - // BROWSE_CONTENT_FILTER default — page-derived text in the - // REPL is a higher-risk surface than ordinary tool output). - // - L4 ML classifier via the sidecar when available. - // - L1-L3 envelope/datamarking is INFORMATIONAL only; the - // verdict is driven by the URL blocklist + L4. - // See CLAUDE.md "Sidebar security stack" + plan §"L1-L3 honest - // accounting". - let verdict: 'PASS' | 'WARN' | 'BLOCK' = 'PASS'; - const reasons: string[] = []; - - // Quick URL-blocklist check (re-uses the security module's - // pure-string helpers — no @huggingface/transformers dep). - // Pattern: text containing a known bad-actor domain → BLOCK. - if (/(\bbit\.ly|\btinyurl\.com|\bdiscord\.gg)/i.test(text)) { - verdict = 'BLOCK'; - reasons.push('url-blocklist'); - } - - // L4 sidecar scan if available. - const sidecarAvail = isSidecarAvailable(); - let l4: { available: boolean; verdict?: unknown; error?: string } = { - available: sidecarAvail.available, - }; - if (sidecarAvail.available && verdict !== 'BLOCK') { - try { - const { verdict: layerVerdict } = await scanWithSidecar(text, { - timeoutMs: 5000, - }); - l4 = { available: true, verdict: layerVerdict }; - // LayerSignal shape: { verdict: 'safe'|'suspicious'|'unsafe', ... } - const lv = (layerVerdict as { verdict?: string })?.verdict; - if (lv === 'unsafe') { - verdict = 'BLOCK'; - reasons.push('l4-unsafe'); - } else if (lv === 'suspicious') { - verdict = 'WARN'; - reasons.push('l4-suspicious'); - } - } catch (err) { - l4 = { - available: false, - error: err instanceof Error ? err.message : String(err), - }; - // L4 failure during scan: degrade to WARN per D7. - if (verdict === 'PASS') { - verdict = 'WARN'; - reasons.push('l4-unavailable'); - } - } - } else if (!sidecarAvail.available && verdict === 'PASS') { - verdict = 'WARN'; - reasons.push(`l4-unavailable:${sidecarAvail.reason ?? 'unknown'}`); - } - - // BLOCK decisions are surfaced in the response shape; the - // existing writeDecision audit log is tab-scoped (per-page) and - // doesn't fit the PTY surface. The extension logs the BLOCK - // event into its own activity feed on receipt, which keeps the - // audit signal observable without bolting a new attempts.jsonl - // onto the server. - - return new Response( - JSON.stringify( - { verdict, reasons, l4, datamark: '' }, - sanitizeReplacer, - ), - { status: 200, headers: { 'Content-Type': 'application/json' } }, - ); - } - - // ─── /connect — setup key exchange for /pair-agent ceremony ──── - if (url.pathname === '/connect' && req.method === 'POST') { - if (!checkConnectRateLimit()) { - return new Response(JSON.stringify({ - error: 'Too many connection attempts. Wait 1 minute.', - }), { status: 429, headers: { 'Content-Type': 'application/json' } }); - } - try { - const connectBody = await req.json() as { setup_key?: string }; - if (!connectBody.setup_key) { - return new Response(JSON.stringify({ error: 'Missing setup_key' }), { - status: 400, headers: { 'Content-Type': 'application/json' }, - }); - } - const session = exchangeSetupKey(connectBody.setup_key); - if (!session) { - return new Response(JSON.stringify({ - error: 'Invalid, expired, or already-used setup key', - }), { status: 401, headers: { 'Content-Type': 'application/json' } }); - } - console.log(`[browse] Remote agent connected: ${session.clientId} (scopes: ${session.scopes.join(',')})`); - return new Response(JSON.stringify({ - token: session.token, - expires: session.expiresAt, - scopes: session.scopes, - agent: session.clientId, - }), { status: 200, headers: { 'Content-Type': 'application/json' } }); - } catch { - return new Response(JSON.stringify({ error: 'Invalid request body' }), { - status: 400, headers: { 'Content-Type': 'application/json' }, - }); - } - } - - // ─── /token — mint scoped tokens (root-only) ────────────────── - if (url.pathname === '/token' && req.method === 'POST') { - if (!isRootRequest(req)) { - return new Response(JSON.stringify({ - error: 'Only the root token can mint sub-tokens', - }), { status: 403, headers: { 'Content-Type': 'application/json' } }); - } - try { - const tokenBody = await req.json() as any; - if (!tokenBody.clientId) { - return new Response(JSON.stringify({ error: 'Missing clientId' }), { - status: 400, headers: { 'Content-Type': 'application/json' }, - }); - } - const session = createToken({ - clientId: tokenBody.clientId, - scopes: tokenBody.scopes, - domains: tokenBody.domains, - tabPolicy: tokenBody.tabPolicy, - rateLimit: tokenBody.rateLimit, - expiresSeconds: tokenBody.expiresSeconds, - }); - return new Response(JSON.stringify({ - token: session.token, - expires: session.expiresAt, - scopes: session.scopes, - agent: session.clientId, - }), { status: 200, headers: { 'Content-Type': 'application/json' } }); - } catch (err) { - // Name the caller's typo (bad scope, negative rateLimit, reserved - // clientId) instead of hiding it behind the generic body error. - if (err instanceof InvalidScopeError || err instanceof ReservedClientIdError) { - return new Response(JSON.stringify({ error: err.message }), { - status: 400, headers: { 'Content-Type': 'application/json' }, - }); - } - return new Response(JSON.stringify({ error: 'Invalid request body' }), { - status: 400, headers: { 'Content-Type': 'application/json' }, - }); - } - } - - // ─── /token/:clientId — revoke a scoped token (root-only) ───── - if (url.pathname.startsWith('/token/') && req.method === 'DELETE') { - if (!isRootRequest(req)) { - return new Response(JSON.stringify({ error: 'Root token required' }), { - status: 403, headers: { 'Content-Type': 'application/json' }, - }); - } - // decodeURIComponent so CLI-encoded names (spaces, UTF-8) round-trip. - let clientId: string; - try { - clientId = decodeURIComponent(url.pathname.slice('/token/'.length)); - } catch { - return new Response(JSON.stringify({ error: 'Malformed client ID encoding' }), { - status: 400, headers: { 'Content-Type': 'application/json' }, - }); - } - const revoked = revokeToken(clientId); - // Release tabs UNCONDITIONALLY: ownership outlives the token (it clears - // only on tab close), so a client whose token already expired can still - // own tabs. Gating release on a revoke hit would orphan that ownership - // and let a same-name re-pair inherit an authenticated tab. - const tabsReleased = browserManager.releaseClientTabs(clientId).length; - if (!revoked && tabsReleased === 0) { - return new Response(JSON.stringify({ error: `Agent "${clientId}" not found` }), { - status: 404, headers: { 'Content-Type': 'application/json' }, - }); - } - console.log(`[browse] Revoked ${revoked} token(s), released ${tabsReleased} tab(s) for: ${clientId}`); - return new Response(JSON.stringify({ revoked: clientId, tokens_deleted: revoked, tabs_released: tabsReleased }), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } - - // ─── /agents — list connected agents (root-only) ────────────── - if (url.pathname === '/agents' && req.method === 'GET') { - if (!isRootRequest(req)) { - return new Response(JSON.stringify({ error: 'Root token required' }), { - status: 403, headers: { 'Content-Type': 'application/json' }, - }); - } - // includeSetup: pending (unexchanged) setup keys are live grants the - // operator must be able to see — without them, revoking a paired-but- - // never-connected agent "works" while the list shows nothing. - const agents = listTokens({ includeSetup: true }).map(t => ({ - clientId: t.clientId, - scopes: t.scopes, - domains: t.domains, - expiresAt: t.expiresAt, - commandCount: t.commandCount, - createdAt: t.createdAt, - pending: t.type === 'setup', - })); - return new Response(JSON.stringify({ agents }), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } - - // ─── /pair — create setup key for pair-agent ceremony (root-only) ─── - if (url.pathname === '/pair' && req.method === 'POST') { - if (!isRootRequest(req)) { - return new Response(JSON.stringify({ error: 'Root token required' }), { - status: 403, headers: { 'Content-Type': 'application/json' }, - }); - } - try { - const pairBody = await req.json() as any; - // Reject a reserved/invalid clientId up front (createSetupKey enforces - // it too, but this makes the 400 unambiguous and skips the teardown). - if (pairBody.clientId !== undefined) assertValidClientId(pairBody.clientId); - // Default: DEFAULT_PAIR_SCOPES (full page access). The trust boundary - // is the pairing ceremony itself, not the scope. --control adds - // browser-wide destructive commands (stop, restart, disconnect). - // --restrict limits scope — but can never grant control: that scope - // stays behind the explicit control flag. - if (!pairBody.control && !pairBody.admin - && Array.isArray(pairBody.scopes) && pairBody.scopes.includes('control')) { - return new Response(JSON.stringify({ - error: 'The control scope requires the control flag (--control); it cannot be granted via a scopes list.', - }), { status: 400, headers: { 'Content-Type': 'application/json' } }); - } - const scopes = pairBody.control || pairBody.admin - ? [...DEFAULT_PAIR_SCOPES, 'control' as const] - : ((pairBody.scopes || [...DEFAULT_PAIR_SCOPES]) as ScopeCategory[]); - // D1: a re-pair supersedes prior grants. ALWAYS drop stale setup keys - // so a superseded broad key can never be exchanged — this closes the - // shadow-key hole where a narrowing re-pair before the agent connects - // would otherwise leave the old broad key live. Revoke the live - // SESSION only when the new grant actually reduces access, so a - // broaden/refresh never strands a working agent mid-task. Compare - // against the resolved grant (not raw pairBody) so dropping 'control' - // or a default re-pair is classified correctly. Revoke runs BEFORE - // createSetupKey — revokeToken deletes all of a clientId's tokens, so - // minting first would nuke the fresh key. - const grant = { - scopes: [...scopes] as ScopeCategory[], - domains: pairBody.domains as string[] | undefined, - rateLimit: pairBody.rateLimit ?? 10, - tabPolicy: 'own-only' as const, - }; - // Validate BEFORE any revoke (createSetupKey validates too, but that - // runs after the teardown below). A bad scope or negative rateLimit - // must 400 without knocking a live session offline — otherwise a - // reducing re-pair with a typo (--restrict red) destroys the session - // and mints no replacement. - assertValidTokenOptions(grant.scopes, grant.rateLimit); - const priorSession = pairBody.clientId ? getClientSession(pairBody.clientId) : null; - let superseded: { tokens_deleted: number; tabs_released: number } | undefined; - if (priorSession && grantReducesAccess(priorSession, grant)) { - const tokensDeleted = revokeToken(pairBody.clientId); - const tabsReleased = browserManager.releaseClientTabs(pairBody.clientId).length; - superseded = { tokens_deleted: tokensDeleted, tabs_released: tabsReleased }; - console.log(`[browse] Superseded ${tokensDeleted} token(s), released ${tabsReleased} tab(s) for reducing re-pair: ${pairBody.clientId}`); - } else if (pairBody.clientId) { - revokeSetupKeys(pairBody.clientId); - // No live session, but tab ownership outlives token expiry: free any - // tabs orphaned by an expired session so this re-pair can't inherit - // an earlier incarnation's authenticated pages (mirrors DELETE - // /token's unconditional release). A live-session broaden keeps its - // tabs — the working agent still owns them. - if (!priorSession) browserManager.releaseClientTabs(pairBody.clientId); - } - const setupKey = createSetupKey({ - clientId: pairBody.clientId, - scopes: [...scopes], - domains: pairBody.domains, - rateLimit: pairBody.rateLimit, - }); - // Verify tunnel is actually alive before reporting it (ngrok may have died externally). - // Probe via GET /connect — under dual-listener /health is NOT on the tunnel allowlist, - // so the old probe would return 404 and always mark the tunnel as dead. - let verifiedTunnelUrl: string | null = null; - if (tunnelActive && tunnelUrl) { - try { - const probe = await fetch(`${tunnelUrl}/connect`, { - method: 'GET', - headers: { 'ngrok-skip-browser-warning': 'true' }, - signal: AbortSignal.timeout(5000), - }); - if (probe.ok) { - verifiedTunnelUrl = tunnelUrl; - } else { - console.warn(`[browse] Tunnel probe failed (HTTP ${probe.status}), marking tunnel as dead`); - await closeTunnel(); - } - } catch { - console.warn('[browse] Tunnel probe timed out or unreachable, marking tunnel as dead'); - await closeTunnel(); - } - } - return new Response(JSON.stringify({ - setup_key: setupKey.token, - expires_at: setupKey.expiresAt, - scopes: setupKey.scopes, - tunnel_url: verifiedTunnelUrl, - server_url: `http://127.0.0.1:${browsePort}`, - ...(superseded ? { superseded } : {}), - }), { status: 200, headers: { 'Content-Type': 'application/json' } }); - } catch (err) { - // Name the caller's typo (bad scope, negative rateLimit, reserved - // clientId) instead of hiding it behind the generic body error. - if (err instanceof InvalidScopeError || err instanceof ReservedClientIdError) { - return new Response(JSON.stringify({ error: err.message }), { - status: 400, headers: { 'Content-Type': 'application/json' }, - }); - } - return new Response(JSON.stringify({ error: 'Invalid request body' }), { - status: 400, headers: { 'Content-Type': 'application/json' }, - }); - } - } - - // ─── /tunnel/start — start ngrok tunnel on demand (root-only) ── - // - // Dual-listener model: binds a SECOND Bun.serve listener on an - // ephemeral 127.0.0.1 port dedicated to tunnel traffic, then points - // ngrok.forward() at THAT port. The existing local listener (which - // serves /extension-token, /cookie-picker, /inspector/*, welcome, etc.) - // is never exposed to ngrok. - // - // Hard fail if the tunnel listener bind fails — NEVER fall back to - // the local port, which would silently defeat the whole security - // property. - if (url.pathname === '/tunnel/start' && req.method === 'POST') { - if (!isRootRequest(req)) { - return new Response(JSON.stringify({ error: 'Root token required' }), { - status: 403, headers: { 'Content-Type': 'application/json' }, - }); - } - if (!isPairAgentEnabled()) { - // Consent-on-first-use: the /pair-agent skill asks once and sets the - // key; a direct API caller gets the same hint instead of a tunnel. - return new Response(JSON.stringify({ - error: 'pair-agent is off (tunnel exposes this browser beyond the machine)', - hint: 'enable once with: gstack-config set pair_agent on — or run /pair-agent, which asks for consent and sets it', - }), { status: 403, headers: { 'Content-Type': 'application/json' } }); - } - if (tunnelActive && tunnelUrl && tunnelServer) { - // Verify tunnel is still alive before returning cached URL. - // Probe GET /connect (the only unauth-reachable path on the tunnel - // surface); /health is NOT tunnel-reachable under dual-listener. - try { - const probe = await fetch(`${tunnelUrl}/connect`, { - method: 'GET', - headers: { 'ngrok-skip-browser-warning': 'true' }, - signal: AbortSignal.timeout(5000), - }); - if (probe.ok) { - return new Response(JSON.stringify({ url: tunnelUrl, already_active: true }), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } - } catch {} - // Tunnel is dead — tear down cleanly before restarting - console.warn('[browse] Cached tunnel is dead, restarting...'); - await closeTunnel(); - } - - // 1) Resolve ngrok authtoken from env / .gstack / native config - const authtoken = resolveNgrokAuthtoken(); - if (!authtoken) { - return new Response(JSON.stringify({ - error: 'No ngrok authtoken found', - hint: 'Run: ngrok config add-authtoken YOUR_TOKEN', - }), { status: 400, headers: { 'Content-Type': 'application/json' } }); - } - - // 2) Bind the tunnel listener + open ngrok via the shared helper - // (see startTunnel — hard-fails the bind, cleans up both ngrok - // and the Bun listener on any post-bind failure). - const started = await startTunnel({ - fetchHandler: makeFetchHandler('tunnel'), - authtoken, - consent: 'pair_agent=on (isPairAgentEnabled gate at /tunnel/start)', - }); - if (!started.ok) { - return new Response(JSON.stringify({ - error: started.stage === 'bind' - ? `Failed to bind tunnel listener: ${started.error.message}` - : `Failed to open ngrok tunnel: ${started.error.message}`, - }), { status: 500, headers: { 'Content-Type': 'application/json' } }); - } - return new Response(JSON.stringify({ url: started.url }), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } - - // ─── SSE session cookie mint (auth required) ────────────────── - // - // Issues a short-lived view-only token in an HttpOnly SameSite=Strict - // cookie so EventSource calls can authenticate without putting the - // root token in a URL. The returned cookie is valid ONLY on the SSE - // endpoints (/activity/stream, /inspector/events); it is not a - // scoped token and cannot be used against /command. - // - // The extension calls this once at bootstrap with the root Bearer - // header, then opens EventSource with `withCredentials: true` which - // sends the cookie back automatically. - if (url.pathname === '/sse-session' && req.method === 'POST') { - if (!validateAuth(req)) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, - headers: { 'Content-Type': 'application/json' }, - }); - } - const minted = mintSseSessionToken(); - return new Response(JSON.stringify({ - expiresAt: minted.expiresAt, - cookie: SSE_COOKIE_NAME, - }), { - status: 200, - headers: { - 'Content-Type': 'application/json', - 'Set-Cookie': buildSseSetCookie(minted.token), - }, - }); - } - - // Refs endpoint — auth required, does NOT reset idle timer - if (url.pathname === '/refs') { - if (!validateAuth(req)) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, - headers: { 'Content-Type': 'application/json' }, - }); - } - const refs = browserManager.getRefMap(); - return new Response(JSON.stringify({ - refs, - url: browserManager.getCurrentUrl(), - mode: browserManager.getConnectionMode(), - }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - } - - // Activity stream — SSE, auth required, does NOT reset idle timer - if (url.pathname === '/activity/stream') { - // Auth: Bearer header OR view-only SSE session cookie (EventSource - // can't send Authorization headers, so the extension fetches a cookie - // via POST /sse-session first, then opens EventSource with - // withCredentials: true). The ?token= query param is NO LONGER - // accepted — URLs leak to logs/referer/history. See N1 in the - // v1.6.0.0 security wave plan. - const cookieToken = extractSseCookie(req); - if (!validateAuth(req) && !validateSseSessionToken(cookieToken)) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, - headers: { 'Content-Type': 'application/json' }, - }); - } - const afterId = parseInt(url.searchParams.get('after') || '0', 10); - // Cleanup contract (abort + enqueue-fail + heartbeat-fail, all - // idempotent) lives in createSseEndpoint; sanitizeReplacer is - // applied to every JSON.stringify inside the helper, so - // page-content-derived fields (URLs, command args, errors) - // stay surrogate-safe per CLAUDE.md egress invariant. - return createSseEndpoint(req, { - initialReplay: (send) => { - const { entries, gap, gapFrom, availableFrom } = getActivityAfter(afterId); - if (gap) send('gap', { gapFrom, availableFrom }); - for (const entry of entries) send('activity', entry); - }, - subscribe, - liveEventName: 'activity', - }); - } - - // Activity history — REST, auth required, does NOT reset idle timer - if (url.pathname === '/activity/history') { - if (!validateAuth(req)) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, - headers: { 'Content-Type': 'application/json' }, - }); - } - const limit = parseInt(url.searchParams.get('limit') || '50', 10); - const { entries, totalAdded } = getActivityHistory(limit); - return new Response(JSON.stringify({ entries, totalAdded, subscribers: getSubscriberCount() }), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - } - - - // ─── Batch endpoint — N commands, 1 HTTP round-trip ───────────── - // Accepts both root AND scoped tokens (same as /command). - // Executes commands sequentially through the full security pipeline. - // Designed for remote agents where tunnel latency dominates. - if (url.pathname === '/batch' && req.method === 'POST') { - const tokenInfo = getTokenInfo(req); - if (!tokenInfo) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, - headers: { 'Content-Type': 'application/json' }, - }); - } - resetIdleTimer(); - const body = await req.json(); - const { commands } = body; - - if (!Array.isArray(commands) || commands.length === 0) { - return new Response(JSON.stringify({ error: '"commands" must be a non-empty array' }), { - status: 400, - headers: { 'Content-Type': 'application/json' }, - }); - } - if (commands.length > 50) { - return new Response(JSON.stringify({ error: 'Max 50 commands per batch' }), { - status: 400, - headers: { 'Content-Type': 'application/json' }, - }); - } - - const startTime = Date.now(); - emitActivity({ - type: 'command_start', - command: 'batch', - args: [`${commands.length} commands`], - url: browserManager.getCurrentUrl(), - tabs: browserManager.getTabCount(), - mode: browserManager.getConnectionMode(), - clientId: tokenInfo?.clientId, - }); - - const results: Array<{ index: number; status: number; result: string; command: string; tabId?: number }> = []; - for (let i = 0; i < commands.length; i++) { - const cmd = commands[i]; - if (!cmd || typeof cmd.command !== 'string') { - results.push({ index: i, status: 400, result: JSON.stringify({ error: 'Missing "command" field' }), command: '' }); - continue; - } - // Reject nested batches - if (cmd.command === 'batch') { - results.push({ index: i, status: 400, result: JSON.stringify({ error: 'Nested batch commands are not allowed' }), command: 'batch' }); - continue; - } - const cr = await handleCommandInternal( - { command: cmd.command, args: cmd.args, tabId: cmd.tabId }, - tokenInfo, - { skipRateCheck: true, skipActivity: true }, - ); - // Sanitize lone surrogates per-result (#1440 — /batch bypasses the - // handleCommand chokepoint, so it needs its own sanitization). - const safeResult = typeof cr.result === 'string' ? sanitizeBody(cr.result, !!cr.json) : cr.result; - results.push({ - index: i, - status: cr.status, - result: safeResult, - command: cmd.command, - tabId: cmd.tabId, - }); - } - - const duration = Date.now() - startTime; - emitActivity({ - type: 'command_end', - command: 'batch', - args: [`${commands.length} commands`], - url: browserManager.getCurrentUrl(), - duration, - status: 'ok', - result: `${results.filter(r => r.status === 200).length}/${commands.length} succeeded`, - tabs: browserManager.getTabCount(), - mode: browserManager.getConnectionMode(), - clientId: tokenInfo?.clientId, - }); - - // Sanitize the JSON envelope a second time (defense in depth) — catches - // any \uXXXX escape sequences for lone surrogates that survived the - // per-result pass. - const batchBody = stripLoneSurrogateEscapes(JSON.stringify({ - results, - duration, - total: commands.length, - succeeded: results.filter(r => r.status === 200).length, - failed: results.filter(r => r.status !== 200).length, - })); - return new Response(batchBody, { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - } - - // ─── File serving endpoint (for remote agents to retrieve downloaded files) ──── - if (url.pathname === '/file' && req.method === 'GET') { - const tokenInfo = getTokenInfo(req); - if (!tokenInfo) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, headers: { 'Content-Type': 'application/json' }, - }); - } - const filePath = url.searchParams.get('path'); - if (!filePath) { - return new Response(JSON.stringify({ error: 'Missing "path" query parameter' }), { - status: 400, headers: { 'Content-Type': 'application/json' }, - }); - } - try { - validateTempPath(filePath); - } catch (err: any) { - return new Response(JSON.stringify({ error: err.message }), { - status: 403, headers: { 'Content-Type': 'application/json' }, - }); - } - if (!fs.existsSync(filePath)) { - return new Response(JSON.stringify({ error: 'File not found' }), { - status: 404, headers: { 'Content-Type': 'application/json' }, - }); - } - const stat = fs.statSync(filePath); - if (stat.size > 200 * 1024 * 1024) { - return new Response(JSON.stringify({ error: 'File too large (max 200MB)' }), { - status: 413, headers: { 'Content-Type': 'application/json' }, - }); - } - const ext = path.extname(filePath).toLowerCase(); - const MIME_MAP: Record = { - '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', - '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml', - '.avif': 'image/avif', - '.mp4': 'video/mp4', '.webm': 'video/webm', '.mov': 'video/quicktime', - '.mp3': 'audio/mpeg', '.wav': 'audio/wav', '.ogg': 'audio/ogg', - '.pdf': 'application/pdf', '.json': 'application/json', - '.html': 'text/html', '.txt': 'text/plain', '.mhtml': 'message/rfc822', - }; - const contentType = MIME_MAP[ext] || 'application/octet-stream'; - resetIdleTimer(); - return new Response(Bun.file(filePath), { - headers: { - 'Content-Type': contentType, - 'Content-Length': String(stat.size), - 'Content-Disposition': `inline; filename="${path.basename(filePath)}"`, - 'Cache-Control': 'no-cache', - }, - }); - } - - // ─── Command endpoint (accepts both root AND scoped tokens) ──── - // Must be checked BEFORE the blanket root-only auth gate below, - // because scoped tokens from /connect are valid for /command. - if (url.pathname === '/command' && req.method === 'POST') { - const tokenInfo = getTokenInfo(req); - if (!tokenInfo) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, - headers: { 'Content-Type': 'application/json' }, - }); - } - resetIdleTimer(); - const body = await req.json() as any; - // Tunnel surface: only commands in TUNNEL_COMMANDS are allowed. - // Paired remote agents drive the browser but cannot configure the - // daemon, launch new browsers, import cookies, or rotate tokens. - if (surface === 'tunnel') { - if (!canDispatchOverTunnel(body?.command, body?.args)) { - logTunnelDenial(req, url, `disallowed_command:${body?.command}`); - return new Response(JSON.stringify({ - error: `Command '${body?.command}' is not allowed over the tunnel surface`, - hint: `Tunnel commands: ${[...TUNNEL_COMMANDS].sort().join(', ')}. Note: --out (disk write) is never allowed over the tunnel.`, - }), { status: 403, headers: { 'Content-Type': 'application/json' } }); - } - } - return handleCommand(body, tokenInfo); - } - - // ─── Auth-required endpoints (root token only) ───────────────── - - if (!validateAuth(req)) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, - headers: { 'Content-Type': 'application/json' }, - }); - } - - // ─── Inspector endpoints ────────────────────────────────────── - - // POST /inspector/pick — receive element pick from extension, run CDP inspection - if (url.pathname === '/inspector/pick' && req.method === 'POST') { - const body = await req.json(); - const { selector, activeTabUrl } = body; - if (!selector) { - return new Response(JSON.stringify({ error: 'Missing selector' }), { - status: 400, headers: { 'Content-Type': 'application/json' }, - }); - } - try { - const page = browserManager.getPage(); - const result = await inspectElement(page, selector); - inspectorData = result; - inspectorTimestamp = Date.now(); - // Also store on browserManager for CLI access - (browserManager as any)._inspectorData = result; - (browserManager as any)._inspectorTimestamp = inspectorTimestamp; - emitInspectorEvent({ type: 'pick', selector, timestamp: inspectorTimestamp }); - return new Response(JSON.stringify(result), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } catch (err: any) { - return new Response(JSON.stringify({ error: err.message }), { - status: 500, headers: { 'Content-Type': 'application/json' }, - }); - } - } - - // GET /inspector — return latest inspector data - if (url.pathname === '/inspector' && req.method === 'GET') { - if (!inspectorData) { - return new Response(JSON.stringify({ data: null }), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } - const stale = inspectorTimestamp > 0 && (Date.now() - inspectorTimestamp > 60000); - return new Response(JSON.stringify({ data: inspectorData, timestamp: inspectorTimestamp, stale }), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } - - // POST /inspector/apply — apply a CSS modification - if (url.pathname === '/inspector/apply' && req.method === 'POST') { - const body = await req.json(); - const { selector, property, value } = body; - if (!selector || !property || value === undefined) { - return new Response(JSON.stringify({ error: 'Missing selector, property, or value' }), { - status: 400, headers: { 'Content-Type': 'application/json' }, - }); - } - try { - const page = browserManager.getPage(); - const mod = await modifyStyle(page, selector, property, value); - emitInspectorEvent({ type: 'apply', modification: mod, timestamp: Date.now() }); - return new Response(JSON.stringify(mod), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } catch (err: any) { - return new Response(JSON.stringify({ error: err.message }), { - status: 500, headers: { 'Content-Type': 'application/json' }, - }); - } - } - - // POST /inspector/reset — clear all modifications - if (url.pathname === '/inspector/reset' && req.method === 'POST') { - try { - const page = browserManager.getPage(); - await resetModifications(page); - emitInspectorEvent({ type: 'reset', timestamp: Date.now() }); - return new Response(JSON.stringify({ ok: true }), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } catch (err: any) { - return new Response(JSON.stringify({ error: err.message }), { - status: 500, headers: { 'Content-Type': 'application/json' }, - }); - } - } - - // GET /inspector/history — return modification list - if (url.pathname === '/inspector/history' && req.method === 'GET') { - return new Response(JSON.stringify({ history: getModificationHistory() }), { - status: 200, headers: { 'Content-Type': 'application/json' }, - }); - } - - // GET /memory — diagnostic snapshot (auth required, does NOT reset idle). - // Same auth model as /activity/stream and /inspector/events: Bearer header - // OR view-only SSE-session cookie. Does NOT extend /health (which is - // unauthenticated liveness-only — token bootstrap moved to the pinned - // POST /extension-token); a separate endpoint with the standard SSE auth - // keeps /health free of anything worth stealing. - if (url.pathname === '/memory' && req.method === 'GET') { - const cookieToken = extractSseCookie(req); - if (!validateAuth(req) && !validateSseSessionToken(cookieToken)) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, headers: { 'Content-Type': 'application/json' }, - }); - } - const { buildMemorySnapshotJson } = await import('./memory-command'); - const snapshot = await buildMemorySnapshotJson(cfgBrowserManager); - // sanitizeReplacer is required at every SSE/JSON egress that ships - // page-content-derived strings — tab.url and tab.title come from - // page content, so lone-surrogate bytes from broken emoji or - // mid-emoji splits could otherwise reach the sidebar / Claude API. - return new Response(JSON.stringify(snapshot, sanitizeReplacer), { - status: 200, - headers: { 'Content-Type': 'application/json' }, - }); - } - - // GET /inspector/events — SSE for inspector state changes (auth required) - if (url.pathname === '/inspector/events' && req.method === 'GET') { - // Same auth model as /activity/stream: Bearer OR view-only cookie. - // ?token= query param dropped (see N1 in the v1.6.0.0 security plan). - const cookieToken = extractSseCookie(req); - if (!validateAuth(req) && !validateSseSessionToken(cookieToken)) { - return new Response(JSON.stringify({ error: 'Unauthorized' }), { - status: 401, headers: { 'Content-Type': 'application/json' }, - }); - } - // Cleanup contract (abort + enqueue-fail + heartbeat-fail, - // idempotent) lives in createSseEndpoint; sanitizeReplacer is - // applied to every JSON.stringify inside the helper. The - // inspector subscriber set stays here because it's also written - // to by emitInspectorEvent above. - return createSseEndpoint(req, { - initialReplay: inspectorData - ? (send) => send('state', { data: inspectorData, timestamp: inspectorTimestamp }) - : undefined, - subscribe: (notify) => { - inspectorSubscribers.add(notify); - return () => inspectorSubscribers.delete(notify); - }, - liveEventName: 'inspector', - }); - } - - return new Response('Not found', { status: 404 }); + return dispatchRoute(ROUTES, req, url, surface, routeCtx); }; return { diff --git a/browse/test/dual-listener.test.ts b/browse/test/dual-listener.test.ts index 77f9ee2f0..1270a8af7 100644 --- a/browse/test/dual-listener.test.ts +++ b/browse/test/dual-listener.test.ts @@ -1,22 +1,45 @@ /** - * Dual-listener source-level guards. + * Dual-listener guards. * * Verifies the F1 refactor: the server binds TWO Bun.serve listeners (local * bootstrap + tunnel surface), the tunnel surface has a closed path allowlist, * root tokens are rejected on the tunnel, and the command allowlist restricts * which browser operations remote paired agents can invoke. * - * These are source-level assertions — they keep future contributors from - * silently widening the tunnel surface during a routine refactor. Behavioral - * integration tests live in the E2E suite (browse/test/pair-agent-e2e.test.ts, - * added in a later wave commit). + * Tunnel-surface behavior is asserted through a real buildFetchHandler() and + * the route handlers; the remaining source-level assertions cover listener + * wiring in start() and the tunnel helpers, which have no seam without ngrok. + * Real-HTTP integration lives in browse/test/pair-agent-e2e.test.ts. */ -import { describe, test, expect } from 'bun:test'; +import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; import * as fs from 'fs'; +import * as os from 'os'; import * as path from 'path'; +import { TUNNEL_COMMANDS } from '../src/server'; +import { __resetConnectRateLimit } from '../src/token-registry'; +import { makeServer, stubRouteContext, callRoute, fakeTunnel, type TestServer } from './route-test-harness'; const SERVER_SRC = fs.readFileSync(path.join(import.meta.dir, '../src/server.ts'), 'utf-8'); +const TABLE_SRC = fs.readFileSync(path.join(import.meta.dir, '../src/routes/table.ts'), 'utf-8'); + +let server: TestServer; +let scoped = ''; +const overlayCalls: string[] = []; +beforeAll(() => { + server = makeServer({ beforeRoute: async (req, surface) => { overlayCalls.push(`${surface} ${new URL(req.url).pathname}`); return null; } }); + scoped = server.scopedToken('dual-listener-agent'); +}); +const savedPairAgent = process.env.GSTACK_PAIR_AGENT; +const restorePairAgent = () => { + if (savedPairAgent === undefined) delete process.env.GSTACK_PAIR_AGENT; + else process.env.GSTACK_PAIR_AGENT = savedPairAgent; +}; +afterAll(() => server.cleanup()); +const bearer = (token: string) => ({ Authorization: `Bearer ${token}` }); +async function statusAndJson(resp: Response): Promise<{ status: number; body: any }> { + return { status: resp.status, body: await resp.json() }; +} function sliceBetween(source: string, start: string, end: string): string { const s = source.indexOf(start); @@ -37,7 +60,10 @@ function extractSetContents(source: string, constName: string): Set { describe('Dual-listener surface types', () => { test('Surface type is a union of local and tunnel', () => { - expect(SERVER_SRC).toContain("export type Surface = 'local' | 'tunnel'"); + // Types have no runtime seam; the owner moved to the route table and + // server.ts re-exports it. + expect(TABLE_SRC).toContain("export type Surface = 'local' | 'tunnel'"); + expect(SERVER_SRC).toContain('export type { Surface };'); }); test('tunnelServer state variable exists alongside tunnelActive/tunnelUrl/tunnelListener', () => { @@ -92,7 +118,7 @@ describe('Tunnel command allowlist', () => { ]); test('TUNNEL_COMMANDS literal matches the closed allowlist exactly (catches additions/removals without test update)', () => { - const cmds = extractSetContents(SERVER_SRC, 'TUNNEL_COMMANDS'); + const cmds = new Set(TUNNEL_COMMANDS); // Both directions: anything in the source must be expected, and anything // expected must be in the source. The intersection-only style of the old // must-include / must-exclude tests let new commands sneak into the source @@ -107,7 +133,7 @@ describe('Tunnel command allowlist', () => { }); test('TUNNEL_COMMANDS does NOT include daemon-configuration or bootstrap commands', () => { - const cmds = extractSetContents(SERVER_SRC, 'TUNNEL_COMMANDS'); + const cmds = TUNNEL_COMMANDS; const forbidden = [ 'launch', 'launch-browser', 'connect', 'disconnect', 'restart', 'stop', 'tunnel-start', 'tunnel-stop', @@ -156,80 +182,67 @@ describe('Request handler factory', () => { }); describe('Tunnel surface filter', () => { - test('tunnel surface filter runs before route dispatch', () => { - // The filter must appear inside makeFetchHandler BEFORE the first route - // handler (/cookie-picker is the earliest route). - const fetchBody = sliceBetween( - SERVER_SRC, - 'makeFetchHandler = (surface: Surface)', - "url.pathname.startsWith('/cookie-picker')" - ); - expect(fetchBody).toContain("surface === 'tunnel'"); - expect(fetchBody).toContain('path_not_on_tunnel'); - expect(fetchBody).toContain('root_token_on_tunnel'); - expect(fetchBody).toContain('missing_scoped_token'); + const NOT_FOUND = { status: 404, body: { error: 'Not found' } }; + + test('tunnel surface filter runs before route dispatch', async () => { + // Denied tunnel requests never reach the beforeRoute overlay or a route. + overlayCalls.length = 0; + expect(await statusAndJson(await server.tunnel('/health'))).toEqual(NOT_FOUND); + expect((await server.tunnel('/command', { method: 'POST', headers: bearer(server.rootToken), body: '{}' })).status).toBe(403); + expect((await server.tunnel('/command', { method: 'POST', body: '{}' })).status).toBe(401); + expect(overlayCalls).toEqual([]); + __resetConnectRateLimit(); + await server.tunnel('/connect'); + expect(overlayCalls).toEqual(['tunnel /connect']); }); - test('tunnel surface 404s paths not on allowlist', () => { - const filterBlock = sliceBetween( - SERVER_SRC, - "surface === 'tunnel'", - "if (url.pathname === '/connect' && req.method === 'GET')" - ); - expect(filterBlock).toContain('TUNNEL_PATHS.has'); - expect(filterBlock).toContain('status: 404'); + test('tunnel surface 404s paths not on allowlist', async () => { + for (const p of ['/health', '/pty-session', '/extension-token', '/inspector', '/token', '/no-such-route']) { + for (const headers of [{}, bearer(scoped)]) { + expect(await statusAndJson(await server.tunnel(p, { method: 'POST', headers }))).toEqual(NOT_FOUND); + } + } }); - test('tunnel surface 403s root token bearers with clear hint', () => { - const filterBlock = sliceBetween( - SERVER_SRC, - "surface === 'tunnel'", - "if (url.pathname === '/connect' && req.method === 'GET')" - ); - expect(filterBlock).toContain('isRootRequest(req)'); - expect(filterBlock).toContain('Root token rejected on tunnel surface'); - expect(filterBlock).toContain('pair via /connect'); - expect(filterBlock).toContain('status: 403'); + test('tunnel surface 403s root token bearers with clear hint', async () => { + for (const p of ['/connect', '/command']) { + const resp = await statusAndJson(await server.tunnel(p, { method: 'POST', headers: bearer(server.rootToken), body: '{}' })); + expect(resp.status).toBe(403); + expect(resp.body.error).toBe('Root token rejected on tunnel surface'); + expect(resp.body.hint).toContain('pair via /connect'); + } }); - test('tunnel surface 401s when non-/connect request lacks scoped token', () => { - const filterBlock = sliceBetween( - SERVER_SRC, - "surface === 'tunnel'", - "if (url.pathname === '/connect' && req.method === 'GET')" - ); - expect(filterBlock).toContain("url.pathname !== '/connect'"); - expect(filterBlock).toContain('getTokenInfo(req)'); - expect(filterBlock).toContain('status: 401'); + test('tunnel surface 401s when non-/connect request lacks scoped token', async () => { + const denied = await statusAndJson(await server.tunnel('/command', { method: 'POST', body: '{}' })); + expect(denied).toEqual({ status: 401, body: { error: 'Unauthorized' } }); + __resetConnectRateLimit(); + const connect = await statusAndJson(await server.tunnel('/connect', { method: 'POST', body: '{}' })); + expect(connect).toEqual({ status: 400, body: { error: 'Missing setup_key' } }); }); }); describe('GET /connect alive probe', () => { - test('GET /connect returns {alive: true} unauth on both surfaces', () => { - const getConnect = sliceBetween( - SERVER_SRC, - "if (url.pathname === '/connect' && req.method === 'GET')", - "// Cookie picker routes" - ); - expect(getConnect).toContain('alive: true'); - expect(getConnect).toContain('status: 200'); + test('GET /connect returns {alive: true} unauth on both surfaces', async () => { + for (const call of [server.local, server.tunnel]) { + __resetConnectRateLimit(); + expect(await statusAndJson(await call('/connect'))).toEqual({ status: 200, body: { alive: true } }); + } }); }); describe('/command tunnel command allowlist', () => { - test('/command handler delegates to canDispatchOverTunnel when surface is tunnel', () => { - const commandBlock = sliceBetween( - SERVER_SRC, - "url.pathname === '/command' && req.method === 'POST'", - 'return handleCommand(body, tokenInfo)' - ); - expect(commandBlock).toContain("surface === 'tunnel'"); + test('/command handler delegates to canDispatchOverTunnel when surface is tunnel', async () => { // Args-aware since the --out (disk write) tunnel ban: the dispatch gate // takes both the command and its args. - expect(commandBlock).toContain('canDispatchOverTunnel(body?.command, body?.args)'); - expect(commandBlock).toContain('disallowed_command'); - expect(commandBlock).toContain('is not allowed over the tunnel surface'); - expect(commandBlock).toContain('status: 403'); + for (const body of [{ command: 'launch' }, { command: 'eval', args: ['--out', '/tmp/dual-listener-out', '1'] }]) { + const resp = await statusAndJson(await server.tunnel('/command', { + method: 'POST', headers: bearer(scoped), body: JSON.stringify(body), + })); + expect(resp.status).toBe(403); + expect(resp.body.error).toBe(`Command '${body.command}' is not allowed over the tunnel surface`); + expect(resp.body.hint).toContain('Tunnel commands: '); + } }); }); @@ -245,14 +258,10 @@ describe('Tunnel listener lifecycle', () => { }); test('/tunnel/start binds the tunnel listener on an ephemeral port (via startTunnel)', () => { - const startBlock = sliceBetween( - SERVER_SRC, - "url.pathname === '/tunnel/start' && req.method === 'POST'", - "url.pathname === '/refs'" - ); - // The route delegates to the shared startTunnel() helper, passing the + // The route calls ctx.tunnel.start (server-auth.test.ts pins that call); + // the factory wires it to the shared startTunnel() helper with the // factory-scoped tunnel-surface handler. - expect(startBlock).toContain('startTunnel('); + const startBlock = sliceBetween(SERVER_SRC, 'start: (authtoken) => startTunnel({', 'commands: {'); expect(startBlock).toContain("makeFetchHandler('tunnel')"); // The helper owns the ephemeral bind and points ngrok at the TUNNEL // port — never the local daemon port. @@ -266,30 +275,38 @@ describe('Tunnel listener lifecycle', () => { expect(helperBlock).toContain("addr: tunnelPort"); }); - test('/tunnel/start hard-fails on tunnel listener bind error (no local fallback)', () => { - const startBlock = sliceBetween( - SERVER_SRC, - "url.pathname === '/tunnel/start' && req.method === 'POST'", - "url.pathname === '/refs'" - ); - // Must return 500 on bind failure, not silently continue - expect(startBlock).toContain('Failed to bind tunnel listener'); - expect(startBlock).toContain('status: 500'); + function startCtx(result: { ok: false; stage: 'bind' | 'ngrok'; error: Error }) { + return stubRouteContext({ + tunnel: { + state: () => ({ active: false, url: null, hasListener: false }), + close: async () => {}, resolveAuthtoken: () => 'ngrok-token', start: async () => result, + }, + }); + } + + test('/tunnel/start hard-fails on tunnel listener bind error (no local fallback)', async () => { + process.env.GSTACK_PAIR_AGENT = 'on'; + try { + const resp = await callRoute('POST', '/tunnel/start', startCtx({ ok: false, stage: 'bind', error: new Error('EADDRINUSE') })); + expect(await statusAndJson(resp)).toEqual({ status: 500, body: { error: 'Failed to bind tunnel listener: EADDRINUSE' } }); + } finally { restorePairAgent(); } }); - test('/tunnel/start probes the cached tunnel via GET /connect, not /health', () => { - const startBlock = sliceBetween( - SERVER_SRC, - "url.pathname === '/tunnel/start' && req.method === 'POST'", - "url.pathname === '/refs'" - ); - expect(startBlock).toContain('${tunnelUrl}/connect'); - expect(startBlock).toContain("method: 'GET'"); - // The old /health probe must NOT reappear - expect(startBlock).not.toContain('${tunnelUrl}/health'); + test('/tunnel/start probes the cached tunnel via GET /connect, not /health', async () => { + process.env.GSTACK_PAIR_AGENT = 'on'; + const tunnel = fakeTunnel(200); + try { + await callRoute('POST', '/tunnel/start', stubRouteContext({ + tunnel: { + state: () => ({ active: true, url: tunnel.url, hasListener: true }), + close: async () => {}, resolveAuthtoken: () => null, start: async () => { throw new Error('unused'); }, + }, + })); + expect(tunnel.hits).toEqual(['GET /connect']); + } finally { tunnel.stop(); restorePairAgent(); } }); - test('/tunnel/start tears down tunnel listener when ngrok.forward fails', () => { + test('/tunnel/start tears down tunnel listener when ngrok.forward fails', async () => { // startTunnel owns the error-path teardown: boundTunnel.stop(true) plus // the ngrok listener close must both run on any post-bind failure, so a // failed start can't leak sockets or an active ngrok session. @@ -301,12 +318,11 @@ describe('Tunnel listener lifecycle', () => { expect(helperBlock).toContain('boundTunnel.stop(true)'); expect(helperBlock).toContain('tunnelListener.close()'); // ...and the route maps that failure to the 500 response. - const startBlock = sliceBetween( - SERVER_SRC, - "url.pathname === '/tunnel/start' && req.method === 'POST'", - "url.pathname === '/refs'" - ); - expect(startBlock).toContain('Failed to open ngrok tunnel'); + process.env.GSTACK_PAIR_AGENT = 'on'; + try { + const resp = await callRoute('POST', '/tunnel/start', startCtx({ ok: false, stage: 'ngrok', error: new Error('forward refused') })); + expect(await statusAndJson(resp)).toEqual({ status: 500, body: { error: 'Failed to open ngrok tunnel: forward refused' } }); + } finally { restorePairAgent(); } }); test('BROWSE_TUNNEL=1 startup uses dual-listener pattern', () => { @@ -354,15 +370,28 @@ describe('Rate limit + denial log wiring', () => { }); describe('E3: /welcome GSTACK_SLUG path traversal gate', () => { - test('/welcome validates GSTACK_SLUG against ^[a-z0-9_-]+$ before interpolating into path', () => { - const welcomeBlock = sliceBetween( - SERVER_SRC, - "url.pathname === '/welcome'", - 'if (fs.existsSync(projectWelcome)) return projectWelcome;' - ); - // Must validate the slug before using it in a path - expect(welcomeBlock).toMatch(/\/\^\[a-z0-9_-\]\+\$\/\.test\(rawSlug\)/); - // Must fall back to a safe default when the slug fails validation - expect(welcomeBlock).toContain("'unknown'"); + test('/welcome validates GSTACK_SLUG against ^[a-z0-9_-]+$ before interpolating into path', async () => { + const home = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-welcome-slug-')); + const page = (slug: string) => path.join(home, '.gstack/projects', slug, 'designs/welcome-page-20260331/finalized.html'); + for (const [slug, body] of [['unknown', 'UNKNOWN-SLUG-PAGE'], ['good-slug_1', 'GOOD-SLUG-PAGE']]) { + fs.mkdirSync(path.dirname(page(slug)), { recursive: true }); + fs.writeFileSync(page(slug), body); + } + const saved = { HOME: process.env.HOME, GSTACK_SLUG: process.env.GSTACK_SLUG }; + try { + process.env.HOME = home; + process.env.GSTACK_SLUG = 'good-slug_1'; + expect(await (await server.local('/welcome')).text()).toBe('GOOD-SLUG-PAGE'); + // A traversal slug (and any slug outside the charset) falls back to 'unknown'. + for (const slug of ['../../good-slug_1', 'Good-Slug', 'a/b']) { + process.env.GSTACK_SLUG = slug; + expect(await (await server.local('/welcome')).text()).toBe('UNKNOWN-SLUG-PAGE'); + } + } finally { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; else process.env[k] = v; + } + fs.rmSync(home, { recursive: true, force: true }); + } }); }); diff --git a/browse/test/pair-agent-optin-gate.test.ts b/browse/test/pair-agent-optin-gate.test.ts index 7e89d4b42..6878512f4 100644 --- a/browse/test/pair-agent-optin-gate.test.ts +++ b/browse/test/pair-agent-optin-gate.test.ts @@ -13,6 +13,7 @@ import * as fs from 'fs'; import * as os from 'os'; import * as path from 'path'; import { isPairAgentEnabled } from '../src/config'; +import { stubRouteContext, callRoute } from './route-test-harness'; const SERVER_SRC = fs.readFileSync(path.join(import.meta.dir, '../src/server.ts'), 'utf-8'); const CLI_SRC = fs.readFileSync(path.join(import.meta.dir, '../src/cli.ts'), 'utf-8'); @@ -111,11 +112,20 @@ describe('gate wiring — every tunnel activation point consults the guard', () expect(branch).not.toContain('install ngrok'); }); - test('/tunnel/start refuses with the enable hint when disabled', () => { - const startIdx = SERVER_SRC.indexOf("url.pathname === '/tunnel/start'"); - const block = SERVER_SRC.slice(startIdx, startIdx + 1200); - expect(block).toContain('if (!isPairAgentEnabled())'); - expect(block).toContain('gstack-config set pair_agent on'); + test('/tunnel/start refuses with the enable hint when disabled', async () => { + const neverTunnel = () => { throw new Error('a disabled gate must not touch the tunnel'); }; + const ctx = stubRouteContext({ + tunnel: { state: neverTunnel, close: neverTunnel, resolveAuthtoken: neverTunnel, start: neverTunnel }, + }); + tmpHomeWith({ pair_agent: 'off' }); + const resp = await callRoute('POST', '/tunnel/start', ctx); + expect(resp.status).toBe(403); + expect(await resp.json()).toEqual({ + error: 'pair-agent is off (tunnel exposes this browser beyond the machine)', + hint: 'enable once with: gstack-config set pair_agent on — or run /pair-agent, which asks for consent and sets it', + }); + tmpHomeWith(null); + expect((await callRoute('POST', '/tunnel/start', ctx)).status).toBe(403); }); test('BROWSE_TUNNEL=1 startup skips tunnel bind when disabled', () => { diff --git a/browse/test/pty-inject-scan.test.ts b/browse/test/pty-inject-scan.test.ts index f62ace7c3..25ec3eb2d 100644 --- a/browse/test/pty-inject-scan.test.ts +++ b/browse/test/pty-inject-scan.test.ts @@ -10,40 +10,43 @@ * invariants codex's plan review specifically called out. */ -import { describe, test, expect } from 'bun:test'; -import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'; +import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; +import { mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'fs'; import { tmpdir } from 'os'; import { join } from 'path'; +import { makeServer, routeEntry, type TestServer } from './route-test-harness'; const SERVER_SRC = readFileSync( join(import.meta.dir, '..', 'src', 'server.ts'), 'utf-8', ); +const PTY_ROUTES_SRC = readFileSync(join(import.meta.dir, '..', 'src', 'routes', 'pty.ts'), 'utf-8'); -describe('/pty-inject-scan — server.ts static invariants', () => { - test('endpoint is defined as a POST handler', () => { - expect(SERVER_SRC).toContain( - "url.pathname === '/pty-inject-scan' && req.method === 'POST'", - ); +describe('/pty-inject-scan — route invariants', () => { + let server: TestServer; + beforeAll(() => { server = makeServer(); }); + afterAll(() => server.cleanup()); + const post = (headers: Record, body?: string) => + server.local('/pty-inject-scan', { method: 'POST', headers, body }); + + test('endpoint is defined as a local-only POST route', () => { + expect(routeEntry('POST', '/pty-inject-scan')).toMatchObject({ method: 'POST', surfaces: ['local'] }); }); - test('endpoint requires auth (validateAuth gate)', () => { - // Find the endpoint block, verify it calls validateAuth before doing - // any work. - const start = SERVER_SRC.indexOf("'/pty-inject-scan'"); - expect(start).toBeGreaterThan(-1); - const blockEnd = SERVER_SRC.indexOf("\n // ─", start); - const block = SERVER_SRC.slice(start, blockEnd > start ? blockEnd : start + 5000); - expect(block).toContain('validateAuth(req)'); - expect(block).toContain('401'); + test('endpoint requires auth (root bearer gate)', async () => { + for (const headers of [{}, { Authorization: 'Bearer not-the-root-token-0123456789' }]) { + const resp = await post(headers, JSON.stringify({ text: 'hi' })); + expect(resp.status).toBe(401); + expect(await resp.json()).toEqual({ error: 'Unauthorized' }); + } + expect(routeEntry('POST', '/pty-inject-scan').auth).toBe('root-bearer'); }); - test('endpoint caps payload at 64KB', () => { - const start = SERVER_SRC.indexOf("'/pty-inject-scan'"); - const block = SERVER_SRC.slice(start, start + 5000); - expect(block).toContain('64 * 1024'); - expect(block).toContain('payload-too-large'); - expect(block).toContain('413'); + test('endpoint caps payload at 64KB', async () => { + const auth = { Authorization: `Bearer ${server.rootToken}`, 'Content-Length': String(64 * 1024 + 1) }; + const resp = await post(auth, JSON.stringify({ text: 'x'.repeat(64 * 1024) })); + expect(resp.status).toBe(413); + expect(await resp.json()).toEqual({ error: 'payload-too-large', limit: 65536 }); }); test('endpoint is NOT in the tunnel listener allowlist', () => { @@ -54,24 +57,27 @@ describe('/pty-inject-scan — server.ts static invariants', () => { expect(tunnelAllowlist).not.toContain('/pty-inject-scan'); }); + // Source checks re-pointed to routes/pty.ts: a lone surrogate cannot reach + // this response through its public inputs without the mocked sidecar below, + // and module-import rules have no runtime seam. test('response goes through sanitizeReplacer (Unicode egress hardening)', () => { - const start = SERVER_SRC.indexOf("'/pty-inject-scan'"); - const block = SERVER_SRC.slice(start, start + 5000); - expect(block).toContain('sanitizeReplacer'); + const block = PTY_ROUTES_SRC.slice(PTY_ROUTES_SRC.indexOf("path: '/pty-inject-scan'")); + expect(block).toContain('replacer: sanitizeReplacer'); }); test('endpoint surfaces l4 availability shape for D7 degrade-to-WARN path', () => { - const start = SERVER_SRC.indexOf("'/pty-inject-scan'"); - const block = SERVER_SRC.slice(start, start + 5000); + const block = PTY_ROUTES_SRC.slice(PTY_ROUTES_SRC.indexOf("path: '/pty-inject-scan'")); expect(block).toContain('isSidecarAvailable'); expect(block).toContain('available'); }); test('endpoint uses the sidecar client, not direct security-classifier import', () => { - // Static check that server.ts imports from security-sidecar-client.ts, - // NOT from security-classifier.ts directly (would brick the compiled - // binary per CLAUDE.md). - expect(SERVER_SRC).toContain("from './security-sidecar-client'"); + // The route imports security-sidecar-client.ts, NOT security-classifier.ts + // directly (would brick the compiled binary per CLAUDE.md). + expect(PTY_ROUTES_SRC).toContain("from '../security-sidecar-client'"); + for (const file of readdirSync(join(import.meta.dir, '..', 'src', 'routes'))) { + expect(readFileSync(join(import.meta.dir, '..', 'src', 'routes', file), 'utf-8')).not.toContain('security-classifier'); + } expect(SERVER_SRC).not.toContain("from './security-classifier'"); }); }); diff --git a/browse/test/route-test-harness.ts b/browse/test/route-test-harness.ts new file mode 100644 index 000000000..137dab742 --- /dev/null +++ b/browse/test/route-test-harness.ts @@ -0,0 +1,121 @@ +/** + * Shared seams for behavioral browse route tests. + * + * makeServer() builds a real buildFetchHandler() instance over a temp state + * dir; callRoute() runs one route-table entry's real handler against a stub + * RouteContext, so a test can observe what the handler asks of the daemon + * (terminal grants, tunnel probes, command dispatch) without a live + * terminal-agent, ngrok or browser. + */ + +import * as crypto from 'crypto'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { buildFetchHandler, type ServerConfig, type ServerHandle } from '../src/server'; +import { ROUTES } from '../src/routes'; +import type { RouteContext, RouteEntry, Surface } from '../src/routes/table'; +import { __resetRegistry, createToken, type ScopeCategory, type TokenInfo } from '../src/token-registry'; +import { BrowserManager } from '../src/browser-manager'; +import { resolveConfig } from '../src/config'; + +export interface TestServer { + handle: ServerHandle; + rootToken: string; + local(urlPath: string, init?: RequestInit): Promise; + tunnel(urlPath: string, init?: RequestInit): Promise; + scopedToken(clientId?: string, scopes?: ScopeCategory[]): string; + cleanup(): void; +} + +export function makeServer(opts: { browserManager?: BrowserManager; beforeRoute?: ServerConfig['beforeRoute'] } = {}): TestServer { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-route-harness-')); + __resetRegistry(); + const rootToken = 'route-harness-' + crypto.randomBytes(16).toString('hex'); + const handle = buildFetchHandler({ + authToken: rootToken, + browsePort: 34567, + config: resolveConfig({ BROWSE_STATE_FILE: path.join(dir, 'state/browse.json') }), + browserManager: opts.browserManager ?? new BrowserManager(), + ownsTerminalAgent: false, + startTime: Date.now(), + beforeRoute: opts.beforeRoute, + }); + const request = (urlPath: string, init?: RequestInit) => new Request(`http://127.0.0.1:34567${urlPath}`, init); + return { + handle, + rootToken, + local: (urlPath, init) => handle.fetchLocal(request(urlPath, init), null), + tunnel: (urlPath, init) => handle.fetchTunnel(request(urlPath, init), null), + scopedToken: (clientId = 'harness-agent', scopes = ['read', 'write']) => createToken({ clientId, scopes }).token, + cleanup: () => fs.rmSync(dir, { recursive: true, force: true }), + }; +} + +const unexpected = (name: string) => () => { throw new Error(`route handler unexpectedly called ctx.${name}`); }; + +/** A RouteContext whose every dependency throws unless the test supplies it. */ +export function stubRouteContext(overrides: Partial = {}): RouteContext { + return { + browserManager: {} as BrowserManager, + startTime: Date.now(), + browsePort: 34567, + validateAuth: () => true, + isRootRequest: () => true, + getTokenInfo: () => null, + hasSseCookie: () => false, + isPinnedExtensionRequest: () => false, + isRootTokenValue: () => false, + bootstrapRootToken: 'stub-root-token-0123456789', + resetIdleTimer: unexpected('resetIdleTimer'), + terminal: { + readPort: unexpected('terminal.readPort'), + grantToken: unexpected('terminal.grantToken'), + restartSession: unexpected('terminal.restartSession'), + }, + tunnel: { + state: unexpected('tunnel.state'), + close: unexpected('tunnel.close'), + resolveAuthtoken: unexpected('tunnel.resolveAuthtoken'), + start: unexpected('tunnel.start'), + }, + commands: { handle: unexpected('commands.handle'), handleInternal: unexpected('commands.handleInternal') }, + ...overrides, + }; +} + +export function routeEntry(method: string, urlPath: string, surface: Surface = 'local'): RouteEntry { + const entry = ROUTES.find(r => + r.surfaces.includes(surface) + && (r.method === '*' || r.method === method) + && (r.prefix ? urlPath.startsWith(r.path) : urlPath === r.path)); + if (!entry) throw new Error(`no route-table entry for ${method} ${urlPath}`); + return entry; +} + +/** Runs one entry's real handler (the auth gate is not involved). */ +export async function callRoute( + method: string, + urlPathAndQuery: string, + ctx: RouteContext, + init: { headers?: Record; body?: unknown; surface?: Surface; tokenInfo?: TokenInfo | null } = {}, +): Promise { + const url = new URL(`http://127.0.0.1:34567${urlPathAndQuery}`); + const body = init.body === undefined ? undefined : typeof init.body === 'string' ? init.body : JSON.stringify(init.body); + const req = new Request(url, { method, headers: init.headers, body }); + const surface = init.surface ?? 'local'; + return routeEntry(method, url.pathname, surface).handler(req, { url, surface, tokenInfo: init.tokenInfo ?? null }, ctx); +} + +/** A throwaway HTTP server standing in for an ngrok tunnel URL; records each request. */ +export function fakeTunnel(connectStatus: number): { url: string; hits: string[]; stop(): void } { + const hits: string[] = []; + const srv = Bun.serve({ + port: 0, hostname: '127.0.0.1', + fetch: (req) => { + hits.push(`${req.method} ${new URL(req.url).pathname}`); + return new Response('{}', { status: connectStatus }); + }, + }); + return { url: `http://127.0.0.1:${srv.port}`, hits, stop: () => srv.stop(true) }; +} diff --git a/browse/test/server-auth.test.ts b/browse/test/server-auth.test.ts index a4d3c593b..4fbcff020 100644 --- a/browse/test/server-auth.test.ts +++ b/browse/test/server-auth.test.ts @@ -1,13 +1,21 @@ /** - * Server auth security tests — verify security remediation in server.ts + * Server auth security tests. * - * Tests are source-level: they read server.ts and verify that auth checks, - * CORS restrictions, and token removal are correctly in place. + * Route auth is asserted behaviorally: requests go through a real + * buildFetchHandler() (makeServer) or through one route's real handler with a + * stub RouteContext (callRoute), so the tests pin what each route does, not + * where its code sits. The remaining source-level checks cover code with no + * behavioral seam (command-pipeline internals, cli.ts, the cookie-picker UI, + * the constant-time compare, the ngrok authtoken file lookup). */ -import { describe, test, expect } from 'bun:test'; +import { describe, test, expect, beforeAll, afterAll } from 'bun:test'; import * as fs from 'fs'; import * as path from 'path'; +import { GSTACK_EXTENSION_ID } from '../src/server'; +import { DEFAULT_PAIR_SCOPES, createToken } from '../src/token-registry'; +import { getActivityHistory } from '../src/activity'; +import { makeServer, stubRouteContext, callRoute, fakeTunnel, type TestServer } from './route-test-harness'; const SERVER_SRC = fs.readFileSync(path.join(import.meta.dir, '../src/server.ts'), 'utf-8'); const CLI_SRC = fs.readFileSync(path.join(import.meta.dir, '../src/cli.ts'), 'utf-8'); @@ -21,19 +29,51 @@ function sliceBetween(source: string, startMarker: string, endMarker: string): s return source.slice(startIdx, endIdx); } +const UNAUTHORIZED = { status: 401, body: { error: 'Unauthorized' } }; +const ROOT_REQUIRED = { status: 403, body: { error: 'Root token required' } }; + +async function statusAndJson(resp: Response): Promise<{ status: number; body: any }> { + const text = await resp.text(); + let body: any = text; + try { body = JSON.parse(text); } catch {} + return { status: resp.status, body }; +} + +let server: TestServer; +let scoped = ''; +const bearer = (token: string) => ({ Authorization: `Bearer ${token}` }); +const savedPairAgent = process.env.GSTACK_PAIR_AGENT; + +beforeAll(() => { + server = makeServer(); + scoped = server.scopedToken('auth-suite-agent'); +}); +afterAll(() => { + server.cleanup(); + if (savedPairAgent === undefined) delete process.env.GSTACK_PAIR_AGENT; + else process.env.GSTACK_PAIR_AGENT = savedPairAgent; +}); + describe('Server auth security', () => { - // Test 1a: the pinned-origin bootstrap endpoint exists and gates on both - // the exact extension Origin and a loopback Host. - test('POST /extension-token gates on pinned Origin and loopback Host', () => { - const tokenBlock = sliceBetween(SERVER_SRC, "url.pathname === '/extension-token'", "url.pathname === '/health'"); - expect(tokenBlock).toContain('GSTACK_EXTENSION_ID'); - expect(tokenBlock).toContain('token: authToken'); - // Host is parsed to a hostname (arrives as '127.0.0.1:34567'), never - // compared literally against the raw header. - expect(tokenBlock).toContain('.hostname'); - expect(tokenBlock).toContain("'127.0.0.1'"); - expect(tokenBlock).toContain("'localhost'"); - expect(tokenBlock).toContain('403'); + // Test 1a: the pinned-origin bootstrap endpoint releases the token only to + // the exact extension Origin with a loopback Host (parsed from host:port, + // never compared literally against the raw header). + test('POST /extension-token gates on pinned Origin and loopback Host', async () => { + const pinned = `chrome-extension://${GSTACK_EXTENSION_ID}`; + const post = (headers: Record) => server.local('/extension-token', { method: 'POST', headers }); + for (const host of ['127.0.0.1:34567', 'localhost:34567']) { + const ok = await statusAndJson(await post({ Origin: pinned, Host: host })); + expect(ok).toEqual({ status: 200, body: { token: server.rootToken } }); + } + for (const headers of [ + { Origin: pinned, Host: 'evil.example:34567' }, + { Origin: pinned }, + { Origin: 'chrome-extension://aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa', Host: '127.0.0.1:34567' }, + { Host: '127.0.0.1:34567', ...bearer(server.rootToken) }, + ]) { + const denied = await statusAndJson(await post(headers)); + expect(denied).toEqual({ status: 403, body: { error: 'Forbidden' } }); + } }); // Test 1c: newtab must check domain restrictions (CSO finding #5) @@ -62,94 +102,140 @@ describe('Server auth security', () => { expect(authBlock).not.toContain('header === `Bearer ${authToken}`'); }); - // Test 2: /refs endpoint requires auth via validateAuth - test('/refs endpoint requires authentication', () => { - const refsBlock = sliceBetween(SERVER_SRC, "url.pathname === '/refs'", "url.pathname === '/activity/stream'"); - expect(refsBlock).toContain('validateAuth'); - }); + // Tests 2-5: /refs and /activity/history require the root bearer and never + // send a wildcard CORS header, on the denial or the success path. + for (const route of ['/refs', '/activity/history']) { + test(`${route} endpoint requires authentication`, async () => { + expect(await statusAndJson(await server.local(route))).toEqual(UNAUTHORIZED); + expect(await statusAndJson(await server.local(route, { headers: bearer(scoped) }))).toEqual(UNAUTHORIZED); + expect((await server.local(route, { headers: bearer(server.rootToken) })).status).toBe(200); + }); - // Test 3: /refs has no wildcard CORS header - test('/refs has no wildcard CORS header', () => { - const refsBlock = sliceBetween(SERVER_SRC, "url.pathname === '/refs'", "url.pathname === '/activity/stream'"); - expect(refsBlock).not.toContain("'*'"); - }); - - // Test 4: /activity/history requires auth via validateAuth - test('/activity/history requires authentication', () => { - const historyBlock = sliceBetween(SERVER_SRC, "url.pathname === '/activity/history'", 'Batch endpoint'); - expect(historyBlock).toContain('validateAuth'); - }); - - // Test 5: /activity/history has no wildcard CORS header - test('/activity/history has no wildcard CORS header', () => { - const historyBlock = sliceBetween(SERVER_SRC, "url.pathname === '/activity/history'", 'Batch endpoint'); - expect(historyBlock).not.toContain("'*'"); - }); + test(`${route} has no wildcard CORS header`, async () => { + for (const headers of [{}, bearer(server.rootToken)]) { + const resp = await server.local(route, { headers: { Origin: 'https://evil.example', ...headers } }); + expect(resp.headers.get('access-control-allow-origin')).toBeNull(); + } + }); + } // Test 6: /activity/stream requires auth via Bearer OR view-only session cookie // (N1: ?token= query param was dropped in v1.6.0.0 — URLs leak to logs/referer) - test('/activity/stream requires authentication with inline token check', () => { - const streamBlock = sliceBetween(SERVER_SRC, "url.pathname === '/activity/stream'", "url.pathname === '/activity/history'"); - expect(streamBlock).toContain('validateAuth'); - expect(streamBlock).toContain('validateSseSessionToken'); - // Should not have wildcard CORS for the SSE stream - expect(streamBlock).not.toContain("Access-Control-Allow-Origin': '*'"); - // ?token= query param must NOT be accepted anymore - expect(streamBlock).not.toContain("searchParams.get('token')"); + test('/activity/stream requires authentication with inline token check', async () => { + expect(await statusAndJson(await server.local('/activity/stream'))).toEqual(UNAUTHORIZED); + const viaQuery = await server.local(`/activity/stream?token=${server.rootToken}`); + expect(await statusAndJson(viaQuery)).toEqual(UNAUTHORIZED); + + const viaBearer = await server.local('/activity/stream', { headers: bearer(server.rootToken) }); + expect(viaBearer.status).toBe(200); + expect(viaBearer.headers.get('access-control-allow-origin')).toBeNull(); + await viaBearer.body?.cancel(); + + const minted = await server.local('/sse-session', { method: 'POST', headers: bearer(server.rootToken) }); + const cookie = (minted.headers.get('set-cookie') ?? '').split(';')[0]; + expect(cookie).toStartWith('gstack_sse='); + const viaCookie = await server.local('/activity/stream', { headers: { Cookie: cookie } }); + expect(viaCookie.status).toBe(200); + expect(viaCookie.headers.get('access-control-allow-origin')).toBeNull(); + await viaCookie.body?.cancel(); }); - // Test 7: /command accepts scoped tokens (not just root) - // This was the Wintermute bug — /command was BELOW the blanket validateAuth gate - // which only accepts root tokens. Scoped tokens got 401'd before reaching getTokenInfo. - test('/command endpoint sits ABOVE the blanket root-only auth gate', () => { - const commandIdx = SERVER_SRC.indexOf("url.pathname === '/command'"); - const blanketGateIdx = SERVER_SRC.indexOf("Auth-required endpoints (root token only)"); - // /command must appear BEFORE the blanket gate in source order - expect(commandIdx).toBeGreaterThan(0); - expect(blanketGateIdx).toBeGreaterThan(0); - expect(commandIdx).toBeLessThan(blanketGateIdx); + // Test 7: /command accepts scoped tokens (not just root). This was the + // Wintermute bug — /command sat below the blanket root-only check, so scoped + // tokens got 401'd before reaching getTokenInfo. + test('/command endpoint sits ABOVE the blanket root-only auth gate', async () => { + const resp = await statusAndJson(await server.local('/command', { + method: 'POST', headers: bearer(scoped), body: JSON.stringify({ command: '__auth_suite_unknown__' }), + })); + expect(resp.status).not.toBe(401); + expect(resp.body).not.toEqual({ error: 'Unauthorized' }); }); - // Test 7b: /command uses getTokenInfo (accepts scoped tokens), not validateAuth (root-only) - test('/command uses getTokenInfo for auth, not validateAuth', () => { - const commandBlock = sliceBetween(SERVER_SRC, "url.pathname === '/command'", "Auth-required endpoints"); - expect(commandBlock).toContain('getTokenInfo'); - expect(commandBlock).not.toContain('validateAuth'); + // Test 7b: /command authenticates with getTokenInfo (root or scoped), so an + // unknown bearer is still rejected. + test('/command uses getTokenInfo for auth, not validateAuth', async () => { + const body = JSON.stringify({ command: '__auth_suite_unknown__' }); + expect(await statusAndJson(await server.local('/command', { method: 'POST', body }))).toEqual(UNAUTHORIZED); + expect(await statusAndJson(await server.local('/command', { + method: 'POST', body, headers: bearer('gsk_sess_not-a-real-token'), + }))).toEqual(UNAUTHORIZED); + expect((await server.local('/command', { method: 'POST', body, headers: bearer(server.rootToken) })).status).not.toBe(401); }); // Test 8: /tunnel/start requires root token - test('/tunnel/start requires root token', () => { - const tunnelBlock = sliceBetween(SERVER_SRC, "/tunnel/start", "Refs endpoint"); - expect(tunnelBlock).toContain('isRootRequest'); - expect(tunnelBlock).toContain('Root token required'); + test('/tunnel/start requires root token', async () => { + for (const headers of [{}, bearer(scoped)]) { + expect(await statusAndJson(await server.local('/tunnel/start', { method: 'POST', headers }))).toEqual(ROOT_REQUIRED); + } }); - // Test 8b: /tunnel/start checks ngrok native config paths - test('/tunnel/start reads ngrok native config files', () => { - const tunnelBlock = sliceBetween(SERVER_SRC, "/tunnel/start", "Refs endpoint"); - expect(tunnelBlock).toContain("'ngrok.yml'"); - expect(tunnelBlock).toContain('authtoken'); + // Test 8b: the ngrok authtoken lookup reads ngrok's native config files, and + // /tunnel/start asks for it only after the cached-tunnel check. The file + // lookup (resolveNgrokAuthtoken in server.ts) has no seam without a real + // ngrok config, so that half stays a source check. + test('/tunnel/start reads ngrok native config files', async () => { + const lookup = sliceBetween(SERVER_SRC, 'function resolveNgrokAuthtoken', 'async function closeTunnel'); + expect(lookup).toContain("'ngrok.yml'"); + expect(lookup).toContain('authtoken'); + + process.env.GSTACK_PAIR_AGENT = 'on'; + const inactive = { active: false, url: null, hasListener: false }; + const missing = await statusAndJson(await callRoute('POST', '/tunnel/start', stubRouteContext({ + tunnel: { state: () => inactive, close: async () => {}, resolveAuthtoken: () => null, start: async () => { throw new Error('must not start'); } }, + }))); + expect(missing).toEqual({ status: 400, body: { error: 'No ngrok authtoken found', hint: 'Run: ngrok config add-authtoken YOUR_TOKEN' } }); + + const started: string[] = []; + const ok = await statusAndJson(await callRoute('POST', '/tunnel/start', stubRouteContext({ + tunnel: { + state: () => inactive, close: async () => {}, resolveAuthtoken: () => 'ngrok-token-from-config', + start: async (authtoken) => { started.push(authtoken); return { ok: true, url: 'https://fresh.ngrok.example' }; }, + }, + }))); + expect(ok).toEqual({ status: 200, body: { url: 'https://fresh.ngrok.example' } }); + expect(started).toEqual(['ngrok-token-from-config']); }); - // Test 8c: /tunnel/start returns already_active if tunnel is running - test('/tunnel/start returns already_active when tunnel exists', () => { - const tunnelBlock = sliceBetween(SERVER_SRC, "/tunnel/start", "Refs endpoint"); - expect(tunnelBlock).toContain('already_active'); - expect(tunnelBlock).toContain('tunnelActive'); + // Test 8c: /tunnel/start returns already_active if the cached tunnel answers + test('/tunnel/start returns already_active when tunnel exists', async () => { + process.env.GSTACK_PAIR_AGENT = 'on'; + const tunnel = fakeTunnel(200); + try { + const resp = await statusAndJson(await callRoute('POST', '/tunnel/start', stubRouteContext({ + tunnel: { + state: () => ({ active: true, url: tunnel.url, hasListener: true }), + close: async () => { throw new Error('a live tunnel must not be closed'); }, + resolveAuthtoken: () => { throw new Error('a live tunnel must not be restarted'); }, + start: async () => { throw new Error('a live tunnel must not be restarted'); }, + }, + }))); + expect(resp).toEqual({ status: 200, body: { url: tunnel.url, already_active: true } }); + expect(tunnel.hits).toEqual(['GET /connect']); + } finally { tunnel.stop(); } }); // Test 9: /pair requires root token - test('/pair requires root token', () => { - const pairBlock = sliceBetween(SERVER_SRC, "url.pathname === '/pair'", "/tunnel/start"); - expect(pairBlock).toContain('isRootRequest'); - expect(pairBlock).toContain('Root token required'); + test('/pair requires root token', async () => { + for (const headers of [{}, bearer(scoped)]) { + expect(await statusAndJson(await server.local('/pair', { method: 'POST', headers, body: '{}' }))).toEqual(ROOT_REQUIRED); + } }); - // Test 9b: /pair calls createSetupKey (not createToken) - test('/pair creates setup keys, not session tokens', () => { - const pairBlock = sliceBetween(SERVER_SRC, "url.pathname === '/pair'", "/tunnel/start"); - expect(pairBlock).toContain('createSetupKey'); - expect(pairBlock).not.toContain('createToken'); + // Test 9b: /pair mints a one-time setup key (pending until /connect), never a + // session token a caller could use directly. + test('/pair creates setup keys, not session tokens', async () => { + const pair = await statusAndJson(await server.local('/pair', { + method: 'POST', headers: bearer(server.rootToken), body: JSON.stringify({ clientId: 'pair-setup-check' }), + })); + expect(pair.status).toBe(200); + expect(pair.body.setup_key).toStartWith('gsk_setup_'); + const agents = await statusAndJson(await server.local('/agents', { headers: bearer(server.rootToken) })); + expect(agents.body.agents.find((a: any) => a.clientId === 'pair-setup-check')?.pending).toBe(true); + const exchanged = await statusAndJson(await server.local('/connect', { + method: 'POST', body: JSON.stringify({ setup_key: pair.body.setup_key }), + })); + expect(exchanged.status).toBe(200); + expect(exchanged.body.token).toStartWith('gsk_sess_'); }); // Test 10: tab ownership check happens before command dispatch @@ -220,36 +306,68 @@ describe('Server auth security', () => { // ─── Tunnel liveness verification ───────────────────────────── - // Test 11a: /pair endpoint probes tunnel before returning tunnel_url - test('/pair verifies tunnel is alive before returning tunnel_url', () => { - const pairBlock = sliceBetween(SERVER_SRC, "url.pathname === '/pair'", "url.pathname === '/tunnel/start'"); - // Must probe the tunnel URL - expect(pairBlock).toContain('verifiedTunnelUrl'); - expect(pairBlock).toContain('Tunnel probe failed'); - expect(pairBlock).toContain('marking tunnel as dead'); - // Must tear down tunnel state on failure (via closeTunnel helper — clears - // tunnelActive, tunnelUrl, tunnelListener, and the tunnel Bun.serve listener) - expect(pairBlock).toContain('closeTunnel()'); + // Tests 11a/11b: /pair probes the tunnel before reporting tunnel_url, tears + // the tunnel down when the probe fails, and never reports a raw + // tunnelActive flag. + test('/pair verifies tunnel is alive before returning tunnel_url', async () => { + for (const [status, expectUrl] of [[200, true], [503, false]] as const) { + const tunnel = fakeTunnel(status); + let closed = 0; + try { + const resp = await statusAndJson(await callRoute('POST', '/pair', stubRouteContext({ + tunnel: { + state: () => ({ active: true, url: tunnel.url, hasListener: true }), + close: async () => { closed++; }, + resolveAuthtoken: () => null, start: async () => { throw new Error('unused'); }, + }, + }), { body: {} })); + expect(resp.status).toBe(200); + expect(resp.body.tunnel_url).toBe(expectUrl ? tunnel.url : null); + expect(tunnel.hits).toEqual(['GET /connect']); + expect(closed).toBe(expectUrl ? 0 : 1); + } finally { tunnel.stop(); } + } }); - // Test 11b: /pair returns null tunnel_url when tunnel is dead - test('/pair returns verified tunnel URL, not raw tunnelActive flag', () => { - const pairBlock = sliceBetween(SERVER_SRC, "url.pathname === '/pair'", "url.pathname === '/tunnel/start'"); - // Should use verifiedTunnelUrl (probe result), not raw tunnelUrl - expect(pairBlock).toContain('tunnel_url: verifiedTunnelUrl'); - // Must NOT use raw tunnelActive check for the response - expect(pairBlock).not.toContain('tunnel_url: tunnelActive ? tunnelUrl'); + test('/pair returns verified tunnel URL, not raw tunnelActive flag', async () => { + const resp = await statusAndJson(await callRoute('POST', '/pair', stubRouteContext({ + tunnel: { + state: () => ({ active: true, url: 'http://127.0.0.1:1', hasListener: true }), + close: async () => {}, resolveAuthtoken: () => null, start: async () => { throw new Error('unused'); }, + }, + }), { body: {} })); + expect(resp.status).toBe(200); + expect(resp.body.tunnel_url).toBeNull(); + const inactive = await statusAndJson(await callRoute('POST', '/pair', stubRouteContext({ + tunnel: { + state: () => ({ active: false, url: null, hasListener: false }), + close: async () => { throw new Error('nothing to close'); }, + resolveAuthtoken: () => null, start: async () => { throw new Error('unused'); }, + }, + }), { body: {} })); + expect(inactive.body.tunnel_url).toBeNull(); + expect(inactive.body.server_url).toBe('http://127.0.0.1:34567'); }); - // Test 11c: /tunnel/start probes cached tunnel before returning already_active - test('/tunnel/start verifies cached tunnel is alive before returning already_active', () => { - const tunnelBlock = sliceBetween(SERVER_SRC, "url.pathname === '/tunnel/start'", "url.pathname === '/refs'"); - // Must probe before returning cached URL - expect(tunnelBlock).toContain('Cached tunnel is dead'); - // Must tear down tunnel state on stale detection (via closeTunnel helper) - expect(tunnelBlock).toContain('closeTunnel()'); - // Must fall through to restart when dead - expect(tunnelBlock).toContain('restarting'); + // Test 11c: /tunnel/start probes the cached tunnel before returning + // already_active; a dead one is torn down and restarted. + test('/tunnel/start verifies cached tunnel is alive before returning already_active', async () => { + process.env.GSTACK_PAIR_AGENT = 'on'; + const tunnel = fakeTunnel(502); + const calls: string[] = []; + try { + const resp = await statusAndJson(await callRoute('POST', '/tunnel/start', stubRouteContext({ + tunnel: { + state: () => ({ active: true, url: tunnel.url, hasListener: true }), + close: async () => { calls.push('close'); }, + resolveAuthtoken: () => { calls.push('resolve'); return 'ngrok-token'; }, + start: async () => { calls.push('start'); return { ok: true, url: 'https://restarted.ngrok.example' }; }, + }, + }))); + expect(resp).toEqual({ status: 200, body: { url: 'https://restarted.ngrok.example' } }); + expect(calls).toEqual(['close', 'resolve', 'start']); + expect(tunnel.hits).toEqual(['GET /connect']); + } finally { tunnel.stop(); } }); // Test 11d: CLI verifies tunnel_url from server before printing instruction block @@ -264,62 +382,104 @@ describe('Server auth security', () => { // ─── Batch endpoint security ───────────────────────────────── - // Test 12a: /batch endpoint sits ABOVE the blanket root-only auth gate (same as /command) - test('/batch endpoint sits ABOVE the blanket root-only auth gate', () => { - const batchIdx = SERVER_SRC.indexOf("url.pathname === '/batch'"); - const blanketGateIdx = SERVER_SRC.indexOf("Auth-required endpoints (root token only)"); - expect(batchIdx).toBeGreaterThan(0); - expect(blanketGateIdx).toBeGreaterThan(0); - expect(batchIdx).toBeLessThan(blanketGateIdx); + // Tests 12a/12b: /batch accepts root and scoped tokens (like /command) and + // rejects an unknown bearer. + test('/batch endpoint sits ABOVE the blanket root-only auth gate', async () => { + const resp = await statusAndJson(await server.local('/batch', { + method: 'POST', headers: bearer(scoped), body: JSON.stringify({ commands: [] }), + })); + expect(resp).toEqual({ status: 400, body: { error: '"commands" must be a non-empty array' } }); }); - // Test 12b: /batch uses getTokenInfo (accepts scoped tokens), not validateAuth (root-only) - test('/batch uses getTokenInfo for auth, not validateAuth', () => { - const batchBlock = sliceBetween(SERVER_SRC, "url.pathname === '/batch'", "url.pathname === '/command'"); - expect(batchBlock).toContain('getTokenInfo'); - expect(batchBlock).not.toContain('validateAuth'); + test('/batch uses getTokenInfo for auth, not validateAuth', async () => { + const body = JSON.stringify({ commands: [] }); + expect(await statusAndJson(await server.local('/batch', { method: 'POST', body }))).toEqual(UNAUTHORIZED); + expect(await statusAndJson(await server.local('/batch', { + method: 'POST', body, headers: bearer('gsk_sess_not-a-real-token'), + }))).toEqual(UNAUTHORIZED); + expect((await server.local('/batch', { method: 'POST', body, headers: bearer(server.rootToken) })).status).toBe(400); }); + function batchContext(calls: Array<{ body: any; opts: any }>) { + return stubRouteContext({ + browserManager: { getCurrentUrl: () => 'about:blank', getTabCount: () => 1, getConnectionMode: () => 'launched' } as any, + resetIdleTimer: () => {}, + commands: { + handle: async () => { throw new Error('/batch must not use the single-command wrapper'); }, + handleInternal: async (body, _tokenInfo, opts) => { calls.push({ body, opts }); return { status: 200, result: 'ok' }; }, + }, + }); + } + // Test 12c: /batch enforces max command limit - test('/batch enforces max 50 commands per batch', () => { - const batchBlock = sliceBetween(SERVER_SRC, "url.pathname === '/batch'", "url.pathname === '/command'"); - expect(batchBlock).toContain('commands.length > 50'); - expect(batchBlock).toContain('Max 50 commands per batch'); + test('/batch enforces max 50 commands per batch', async () => { + const calls: Array<{ body: any; opts: any }> = []; + const commands = Array.from({ length: 51 }, () => ({ command: 'url' })); + const resp = await statusAndJson(await callRoute('POST', '/batch', batchContext(calls), { body: { commands } })); + expect(resp).toEqual({ status: 400, body: { error: 'Max 50 commands per batch' } }); + expect(calls).toEqual([]); }); // Test 12d: /batch rejects nested batches - test('/batch rejects nested batch commands', () => { - const batchBlock = sliceBetween(SERVER_SRC, "url.pathname === '/batch'", "url.pathname === '/command'"); - expect(batchBlock).toContain("cmd.command === 'batch'"); - expect(batchBlock).toContain('Nested batch commands are not allowed'); + test('/batch rejects nested batch commands', async () => { + const calls: Array<{ body: any; opts: any }> = []; + const resp = await statusAndJson(await callRoute('POST', '/batch', batchContext(calls), { + body: { commands: [{ command: 'batch', args: [] }, { command: 'url' }] }, + })); + expect(resp.status).toBe(200); + expect(resp.body.results[0]).toMatchObject({ index: 0, status: 400, command: 'batch' }); + expect(JSON.parse(resp.body.results[0].result)).toEqual({ error: 'Nested batch commands are not allowed' }); + expect(calls.map(c => c.body.command)).toEqual(['url']); }); - // Test 12e: /batch skips per-command rate limiting (batch counts as 1 request) - test('/batch skips per-command rate limiting', () => { - const batchBlock = sliceBetween(SERVER_SRC, "url.pathname === '/batch'", "url.pathname === '/command'"); - expect(batchBlock).toContain('skipRateCheck: true'); + // Tests 12e/12f/12h: each sub-command runs through handleCommandInternal + // with per-command rate limiting and activity suppressed, tabId passed + // through, and one batch-level command_start/command_end pair emitted. + test('/batch skips per-command rate limiting', async () => { + const calls: Array<{ body: any; opts: any }> = []; + await callRoute('POST', '/batch', batchContext(calls), { body: { commands: [{ command: 'url' }, { command: 'text' }] } }); + expect(calls.map(c => c.opts.skipRateCheck)).toEqual([true, true]); }); - // Test 12f: /batch skips per-command activity events (emits batch-level events) - test('/batch emits batch-level activity, not per-command', () => { - const batchBlock = sliceBetween(SERVER_SRC, "url.pathname === '/batch'", "url.pathname === '/command'"); - expect(batchBlock).toContain('skipActivity: true'); - // Should emit batch-level start and end events - expect(batchBlock).toContain("command: 'batch'"); + test('/batch emits batch-level activity, not per-command', async () => { + const calls: Array<{ body: any; opts: any }> = []; + const before = getActivityHistory(1000).totalAdded; + await callRoute('POST', '/batch', batchContext(calls), { + body: { commands: [{ command: 'url' }, { command: 'text' }] }, + tokenInfo: { clientId: 'batch-activity-agent' } as any, + }); + expect(calls.map(c => c.opts.skipActivity)).toEqual([true, true]); + const { entries, totalAdded } = getActivityHistory(1000); + const added = entries.slice(-(totalAdded - before)); + expect(added.map(e => [e.type, e.command, e.clientId])).toEqual([ + ['command_start', 'batch', 'batch-activity-agent'], + ['command_end', 'batch', 'batch-activity-agent'], + ]); }); // Test 12g: /batch validates command field in each command - test('/batch validates each command has a command field', () => { - const batchBlock = sliceBetween(SERVER_SRC, "url.pathname === '/batch'", "url.pathname === '/command'"); - expect(batchBlock).toContain("typeof cmd.command !== 'string'"); - expect(batchBlock).toContain('Missing "command" field'); + test('/batch validates each command has a command field', async () => { + const calls: Array<{ body: any; opts: any }> = []; + const resp = await statusAndJson(await callRoute('POST', '/batch', batchContext(calls), { + body: { commands: [{}, { command: 42 }] }, + })); + expect(resp.body.results.map((r: any) => [r.status, JSON.parse(r.result).error])).toEqual([ + [400, 'Missing "command" field'], + [400, 'Missing "command" field'], + ]); + expect(calls).toEqual([]); }); - // Test 12h: /batch passes tabId through to handleCommandInternal - test('/batch passes tabId to handleCommandInternal for multi-tab support', () => { - const batchBlock = sliceBetween(SERVER_SRC, "url.pathname === '/batch'", "url.pathname === '/command'"); - expect(batchBlock).toContain('tabId: cmd.tabId'); - expect(batchBlock).toContain('handleCommandInternal'); + test('/batch passes tabId to handleCommandInternal for multi-tab support', async () => { + const calls: Array<{ body: any; opts: any }> = []; + const resp = await statusAndJson(await callRoute('POST', '/batch', batchContext(calls), { + body: { commands: [{ command: 'url', tabId: 7 }, { command: 'text', args: ['x'], tabId: 9 }] }, + })); + expect(calls.map(c => c.body)).toEqual([ + { command: 'url', args: undefined, tabId: 7 }, + { command: 'text', args: ['x'], tabId: 9 }, + ]); + expect(resp.body.results.map((r: any) => r.tabId)).toEqual([7, 9]); }); // ─── Pair-agent regression tests ────────────────────────── @@ -395,12 +555,15 @@ describe('Server auth security', () => { describe('Pair scope defaults and revocation surface', () => { // Regression: the CLI only sent scopes when --restrict was passed, so the // effective pairing default lived in two places (CLI omission + server - // fallback) and could silently drift. Both sides must reference the shared + // fallback) and could silently drift. Both sides must use the shared // DEFAULT_PAIR_SCOPES constant, and the CLI must send scopes // unconditionally (the old conditional-spread shape is banned). - test('/pair default and CLI pairing body share DEFAULT_PAIR_SCOPES', () => { - const pairBlock = sliceBetween(SERVER_SRC, "url.pathname === '/pair'", "url.pathname === '/tunnel/start'"); - expect(pairBlock).toContain('DEFAULT_PAIR_SCOPES'); + test('/pair default and CLI pairing body share DEFAULT_PAIR_SCOPES', async () => { + const pair = await statusAndJson(await server.local('/pair', { + method: 'POST', headers: bearer(server.rootToken), body: '{}', + })); + expect(pair.status).toBe(200); + expect(pair.body.scopes).toEqual([...DEFAULT_PAIR_SCOPES]); const cliBlock = sliceBetween(CLI_SRC, 'async function handlePairAgent', 'Determine the URL to use'); // Match the CODE shape, not a comment: a bare toContain('DEFAULT_PAIR_SCOPES') // is satisfied by the explanatory comment and passes vacuously on a revert. @@ -410,15 +573,30 @@ describe('Pair scope defaults and revocation surface', () => { // control is the only scope behind an explicit flag; a scopes list must // not be able to smuggle it into a pairing grant. - test('/pair rejects control inside a scopes list without the control flag', () => { - const pairBlock = sliceBetween(SERVER_SRC, "url.pathname === '/pair'", "url.pathname === '/tunnel/start'"); - expect(pairBlock).toContain("pairBody.scopes.includes('control')"); + test('/pair rejects control inside a scopes list without the control flag', async () => { + const pair = (body: unknown) => server.local('/pair', { + method: 'POST', headers: bearer(server.rootToken), body: JSON.stringify(body), + }); + expect(await statusAndJson(await pair({ scopes: ['read', 'control'] }))).toEqual({ + status: 400, + body: { error: 'The control scope requires the control flag (--control); it cannot be granted via a scopes list.' }, + }); + const flagged = await statusAndJson(await pair({ control: true })); + expect(flagged.status).toBe(200); + expect(flagged.body.scopes).toContain('control'); }); // CLI-encoded clientIds (spaces, UTF-8) must round-trip through the revoke // route; slicing the raw pathname 404s on every encoded name. - test('DELETE /token decodes the clientId path segment', () => { - const revokeBlock = sliceBetween(SERVER_SRC, "url.pathname.startsWith('/token/')", "url.pathname === '/agents'"); - expect(revokeBlock).toContain('decodeURIComponent'); + test('DELETE /token decodes the clientId path segment', async () => { + createToken({ clientId: 'encoded agent é', scopes: ['read'] }); + const resp = await statusAndJson(await server.local(`/token/${encodeURIComponent('encoded agent é')}`, { + method: 'DELETE', headers: bearer(server.rootToken), + })); + expect(resp).toEqual({ status: 200, body: { revoked: 'encoded agent é', tokens_deleted: 1, tabs_released: 0 } }); + const malformed = await statusAndJson(await server.local('/token/%E0%A4%A', { + method: 'DELETE', headers: bearer(server.rootToken), + })); + expect(malformed).toEqual({ status: 400, body: { error: 'Malformed client ID encoding' } }); }); }); diff --git a/browse/test/server-pty-lease-routes.test.ts b/browse/test/server-pty-lease-routes.test.ts index aad16ff90..d188cc1c8 100644 --- a/browse/test/server-pty-lease-routes.test.ts +++ b/browse/test/server-pty-lease-routes.test.ts @@ -1,74 +1,136 @@ import { describe, test, expect } from 'bun:test'; import * as fs from 'fs'; import * as path from 'path'; +import { stubRouteContext, callRoute } from './route-test-harness'; +import { mintLease, validateLease } from '../src/pty-session-lease'; +import { validatePtySessionToken } from '../src/pty-session-cookie'; +import type { RouteContext } from '../src/routes/table'; -// Server-side route shape for the v1.44 lease + restart + dispose + -// lease-refresh wiring. Live route exercises require the terminal-agent -// loopback to be live (e2e-tier); these static-grep tripwires pin the -// load-bearing protocol invariants. +// Server-side route behavior for the v1.44 lease + restart + dispose + +// lease-refresh wiring. The routes reach the terminal-agent only through +// RouteContext.terminal, so a stub records every grant and restart the +// daemon would send over loopback. The loopback helpers themselves +// (grantPtyToken / restartPtySession in server.ts) keep source tripwires. const SERVER_TS = path.resolve(import.meta.path, '..', '..', 'src', 'server.ts'); +const ROOT = 'lease-routes-root-token-0123456789'; + +function terminalContext(port: number | null = 4242, granted = true) { + const grants: Array<{ token: string; sessionId?: string }> = []; + const restarts: string[] = []; + let idleResets = 0; + const ctx = stubRouteContext({ + isRootTokenValue: (token) => token === ROOT, + resetIdleTimer: () => { idleResets++; }, + terminal: { + readPort: () => port, + grantToken: async (token, sessionId) => { grants.push({ token, sessionId }); return granted; }, + restartSession: async (sessionId) => { restarts.push(sessionId); return true; }, + }, + }); + return { ctx, grants, restarts, idleResets: () => idleResets }; +} + +async function post(ctx: RouteContext, route: string, body?: unknown, headers?: Record) { + const resp = await callRoute('POST', route, ctx, { body, headers }); + return { status: resp.status, body: await resp.json() as any, headers: resp.headers }; +} describe('server: PTY lease routes (v1.44+ Commit 2)', () => { - test('1. /pty-session returns the 4-tuple shape (sessionId, attachToken, leaseExpiresAt)', () => { - const src = fs.readFileSync(SERVER_TS, 'utf-8'); - const block = sliceBetween(src, "url.pathname === '/pty-session' &&", "url.pathname === '/pty-session/reattach'"); - expect(block).toContain('mintLease()'); - expect(block).toContain('grantPtyToken(minted.token, lease.sessionId)'); - expect(block).toContain('sessionId: lease.sessionId'); - expect(block).toContain('attachToken: minted.token'); - expect(block).toContain('leaseExpiresAt: lease.expiresAt'); + test('1. /pty-session returns the 4-tuple shape (sessionId, attachToken, leaseExpiresAt)', async () => { + const t = terminalContext(); + const resp = await post(t.ctx, '/pty-session'); + expect(resp.status).toBe(200); + expect(resp.body.terminalPort).toBe(4242); + expect(validateLease(resp.body.sessionId).ok).toBe(true); + expect(resp.body.leaseExpiresAt).toBeGreaterThan(Date.now()); + // The attach token is granted to the agent bound to the new sessionId. + expect(t.grants).toEqual([{ token: resp.body.attachToken, sessionId: resp.body.sessionId }]); + expect(validatePtySessionToken(resp.body.attachToken)).toBe(true); // Backward compat: legacy ptySessionToken alias preserved for one release. - expect(block).toContain('ptySessionToken: minted.token'); + expect(resp.body.ptySessionToken).toBe(resp.body.attachToken); + expect(resp.headers.get('set-cookie')).toContain(resp.body.attachToken); + + const notReady = await post(terminalContext(null).ctx, '/pty-session'); + expect(notReady).toMatchObject({ status: 503, body: { error: 'terminal-agent not ready' } }); + const refused = terminalContext(4242, false); + const failed = await post(refused.ctx, '/pty-session'); + expect(failed).toMatchObject({ status: 503, body: { error: 'failed to grant terminal session' } }); + // A refused grant revokes both the token and the lease it minted. + expect(validatePtySessionToken(refused.grants[0].token)).toBe(false); + expect(validateLease(refused.grants[0].sessionId!).ok).toBe(false); }); - test('2. /pty-session/reattach validates lease + mints fresh attachToken', () => { - const src = fs.readFileSync(SERVER_TS, 'utf-8'); - const block = sliceBetween(src, "url.pathname === '/pty-session/reattach'", "url.pathname === '/pty-restart'"); + test('2. /pty-session/reattach validates lease + mints fresh attachToken', async () => { + const t = terminalContext(); // Validate-first: rejects unknown/expired sessionId with 410 Gone so // the client knows to fall back to a fresh /pty-session. - expect(block).toContain('validateLease(sessionId)'); - expect(block).toContain('status: 410'); + expect(await post(t.ctx, '/pty-session/reattach', { sessionId: 'no-such-session' })) + .toMatchObject({ status: 410, body: { error: 'lease expired or unknown' } }); + expect(await post(t.ctx, '/pty-session/reattach', {})).toMatchObject({ status: 410 }); + expect(t.grants).toEqual([]); // Mint fresh token bound to SAME sessionId. - expect(block).toContain('grantPtyToken(minted.token, sessionId!)'); + const lease = mintLease(); + const resp = await post(t.ctx, '/pty-session/reattach', { sessionId: lease.sessionId }); + expect(resp.status).toBe(200); + expect(resp.body.sessionId).toBe(lease.sessionId); + expect(t.grants).toEqual([{ token: resp.body.attachToken, sessionId: lease.sessionId }]); }); - test('3. /pty-restart is one transaction — dispose + revoke + fresh mint', () => { - const src = fs.readFileSync(SERVER_TS, 'utf-8'); - const block = sliceBetween(src, "url.pathname === '/pty-restart'", "url.pathname === '/pty-dispose'"); - // Disposes old session (best-effort — missing sessionId is non-fatal). - expect(block).toContain('restartPtySession(oldSessionId)'); - expect(block).toContain('revokeLease(oldSessionId)'); - // Then mints fresh sessionId + lease + attachToken in the same handler. - expect(block).toContain('mintLease()'); - expect(block).toContain('grantPtyToken(minted.token, lease.sessionId)'); - // Returns the same 4-tuple shape so the client doesn't need a - // separate /pty-session round-trip. - expect(block).toContain('attachToken: minted.token'); - expect(block).toContain('leaseExpiresAt: lease.expiresAt'); + test('3. /pty-restart is one transaction — dispose + revoke + fresh mint', async () => { + const t = terminalContext(); + const old = mintLease(); + const resp = await post(t.ctx, '/pty-restart', { sessionId: old.sessionId }); + // Disposes the old session on the agent and revokes its lease... + expect(t.restarts).toEqual([old.sessionId]); + expect(validateLease(old.sessionId).ok).toBe(false); + // ...then returns a fresh 4-tuple from the same handler, so the client + // doesn't need a separate /pty-session round-trip. + expect(resp.status).toBe(200); + expect(resp.body.sessionId).not.toBe(old.sessionId); + expect(validateLease(resp.body.sessionId).ok).toBe(true); + expect(t.grants).toEqual([{ token: resp.body.attachToken, sessionId: resp.body.sessionId }]); + expect(resp.body.leaseExpiresAt).toBeGreaterThan(Date.now()); + // Missing sessionId is non-fatal: no dispose, fresh mint still happens. + const fresh = terminalContext(); + expect((await post(fresh.ctx, '/pty-restart', {})).status).toBe(200); + expect(fresh.restarts).toEqual([]); }); - test('4. /pty-dispose accepts body-token (sendBeacon-compatible)', () => { - const src = fs.readFileSync(SERVER_TS, 'utf-8'); - const block = sliceBetween(src, "url.pathname === '/pty-dispose'", "url.pathname === '/internal/lease-refresh'"); + test('4. /pty-dispose accepts body-token (sendBeacon-compatible)', async () => { // sendBeacon can't set custom headers, so the route MUST accept the - // auth token in the request body. Otherwise pagehide cleanup fails - // silently every time the user closes the browser. - expect(block).toContain('body?.authToken'); - expect(block).toContain('authedByBody'); - // Both auth paths must validate against authToken — never just trust - // a body-supplied token without the equality check. - expect(block).toContain('authTokenFromBody === authToken'); + // auth token in the request body — and both paths must match the root + // token, never just trust a body-supplied value. + const lease = mintLease(); + const t = terminalContext(); + expect(await post(t.ctx, '/pty-dispose', { authToken: ROOT, sessionId: lease.sessionId })) + .toMatchObject({ status: 200, body: { ok: true } }); + expect(t.restarts).toEqual([lease.sessionId]); + expect(validateLease(lease.sessionId).ok).toBe(false); + expect(await post(t.ctx, '/pty-dispose', {}, { Authorization: `Bearer ${ROOT}` })).toMatchObject({ status: 200 }); + for (const [body, headers] of [ + [{ authToken: 'not-the-root-token', sessionId: 'x' }, undefined], + [{ sessionId: 'x' }, { Authorization: 'Bearer not-the-root-token' }], + [{ sessionId: 'x' }, undefined], + ] as const) { + expect(await post(t.ctx, '/pty-dispose', body, headers as any)).toMatchObject({ status: 401, body: { error: 'Unauthorized' } }); + } + expect(t.restarts).toEqual([lease.sessionId]); }); - test('5. /internal/lease-refresh resets the daemon idle timer (T6)', () => { - const src = fs.readFileSync(SERVER_TS, 'utf-8'); - const block = sliceBetween(src, "url.pathname === '/internal/lease-refresh'", '─── /pty-inject-scan'); - expect(block).toContain('refreshLease(sessionId)'); - expect(block).toContain('resetIdleTimer()'); - // Refresh failure (unknown / expired) MUST 410, not 200, so the - // agent knows to close the WS and force a clean re-auth. - expect(block).toContain('status: 410'); + test('5. /internal/lease-refresh resets the daemon idle timer (T6)', async () => { + const t = terminalContext(); + // Refresh failure (unknown / expired) MUST 410, not 200, so the agent + // knows to close the WS and force a clean re-auth. + expect(await post(t.ctx, '/internal/lease-refresh', { sessionId: 'no-such-session' })) + .toMatchObject({ status: 410, body: { error: 'lease expired or unknown' } }); + expect(t.idleResets()).toBe(0); + const lease = mintLease(); + const resp = await post(t.ctx, '/internal/lease-refresh', { sessionId: lease.sessionId }); + expect(resp.status).toBe(200); + expect(resp.body.ok).toBe(true); + expect(resp.body.expiresAt).toBeGreaterThanOrEqual(lease.expiresAt); + expect(t.idleResets()).toBe(1); }); test('6. grantPtyToken loopback carries sessionId binding', () => { diff --git a/browse/test/server-sanitize-surrogates.test.ts b/browse/test/server-sanitize-surrogates.test.ts index 7513c05ca..35579a8ef 100644 --- a/browse/test/server-sanitize-surrogates.test.ts +++ b/browse/test/server-sanitize-surrogates.test.ts @@ -1,4 +1,6 @@ import { describe, test, expect } from 'bun:test'; +import { emitActivity } from '../src/activity'; +import { stubRouteContext, callRoute } from './route-test-harness'; import * as fs from 'fs'; import * as path from 'path'; @@ -10,6 +12,8 @@ import { stripLoneSurrogates as sanitizeLoneSurrogates } from '../src/sanitize'; const SERVER_PATH = path.resolve(import.meta.dir, '..', 'src', 'server.ts'); const SERVER_SRC = fs.readFileSync(SERVER_PATH, 'utf-8'); +const ROUTE_SRC = (file: string) => fs.readFileSync(path.resolve(import.meta.dir, '..', 'src', 'routes', file), 'utf-8'); +const LONE = 'bad \uD800 value'; describe('sanitizeLoneSurrogates — unit cases', () => { test('passthrough ASCII', () => { @@ -105,22 +109,27 @@ describe('sanitizeLoneSurrogates — wiring invariants', () => { expect(SERVER_SRC).toContain('result: stripLoneSurrogates(cr.result)'); }); - test('SSE activity feed routes outbound frames through createSseEndpoint', () => { - // v1.51 refactor: /activity/stream no longer inlines its own - // ReadableStream/sanitizer wiring; it routes through createSseEndpoint - // which applies sanitizeReplacer to every JSON.stringify. The grep - // pins both halves of the contract: the endpoint uses the helper, - // and the helper does the sanitization. - const activityBlock = SERVER_SRC.match( - /if \(url\.pathname === '\/activity\/stream'\)[\s\S]*?createSseEndpoint\(/, - ); - expect(activityBlock).not.toBeNull(); + test('SSE activity feed routes outbound frames through createSseEndpoint', async () => { + // v1.51 refactor: /activity/stream routes through createSseEndpoint, + // which applies sanitizeReplacer to every JSON.stringify. Replaying an + // activity entry that carries a lone surrogate must emit U+FFFD, never + // the lone code unit or its \uXXXX escape. + const entry = emitActivity({ type: 'command_start', command: 'goto', url: `https://example.com/${LONE}` }); + const resp = await callRoute('GET', `/activity/stream?after=${entry.id - 1}`, stubRouteContext()); + const reader = resp.body!.getReader(); + let text = ''; + while (!text.includes(`"id":${entry.id}`)) text += new TextDecoder().decode((await reader.read()).value); + await reader.cancel(); + expect(text).toContain('bad \uFFFD value'); + expect(text).not.toMatch(/\\ud800/i); }); test('SSE inspector stream routes outbound frames through createSseEndpoint', () => { - // Same v1.51 refactor invariant for /inspector/events. - const inspectorBlock = SERVER_SRC.match( - /if \(url\.pathname === '\/inspector\/events'[\s\S]*?createSseEndpoint\(/, + // Same v1.51 invariant for /inspector/events. Inspector state only fills + // from a live CDP pick, so this stays a source check, re-pointed to the + // route module. + const inspectorBlock = ROUTE_SRC('inspector.ts').match( + /path: '\/inspector\/events'[\s\S]*?createSseEndpoint\(/, ); expect(inspectorBlock).not.toBeNull(); }); @@ -152,13 +161,22 @@ describe('sanitizeLoneSurrogates — wiring invariants', () => { ); }); - test('server.ts imports sanitizeReplacer for non-SSE JSON egress and still uses it', () => { - // server.ts used to define its own private sanitizeReplacer for the - // non-SSE JSON egress paths (/pty-inject-scan, /memory snapshot, etc.). - // It now imports the canonical one — and must still pass it at those - // JSON.stringify egress sites. - expect(SERVER_SRC).toMatch(/import \{[^}]*sanitizeReplacer[^}]*\} from '\.\/sanitize'/); + test('non-SSE JSON egress routes use the canonical sanitizeReplacer', async () => { + // The non-SSE JSON egress paths (/memory snapshot, /pty-inject-scan) + // moved to route modules; they pass the canonical replacer from + // sanitize.ts through json(). /memory is exercised end to end with a + // page-derived tab title carrying a lone surrogate. + const ctx = stubRouteContext({ + browserManager: { getMemorySnapshot: async () => ({ tabs: [{ title: LONE }] }) } as any, + }); + const text = await (await callRoute('GET', '/memory', ctx)).text(); + expect(JSON.parse(text).tabs[0].title).toBe('bad \uFFFD value'); + expect(text).not.toMatch(/\\ud800/i); + for (const file of ['core.ts', 'pty.ts']) { + const src = ROUTE_SRC(file); + expect(src).toMatch(/import \{[^}]*sanitizeReplacer[^}]*\} from '\.\.\/sanitize'/); + expect(src).toContain('replacer: sanitizeReplacer'); + } expect(SERVER_SRC).not.toContain('function sanitizeReplacer('); - expect(SERVER_SRC).toContain(', sanitizeReplacer)'); }); }); diff --git a/browse/test/sidebar-tabs.test.ts b/browse/test/sidebar-tabs.test.ts index 336aea583..a7d2fc93f 100644 --- a/browse/test/sidebar-tabs.test.ts +++ b/browse/test/sidebar-tabs.test.ts @@ -15,6 +15,8 @@ import { describe, test, expect } from 'bun:test'; import * as fs from 'fs'; import * as path from 'path'; +import { ROUTES } from '../src/routes'; +import { makeServer } from './route-test-harness'; const HTML = fs.readFileSync(path.join(import.meta.dir, '../../extension/sidepanel.html'), 'utf-8'); const JS = fs.readFileSync(path.join(import.meta.dir, '../../extension/sidepanel.js'), 'utf-8'); @@ -174,13 +176,22 @@ describe('sidepanel-terminal.js: eager auto-connect + injection API', () => { describe('server.ts: chat / sidebar-agent endpoints are gone', () => { const SERVER_SRC = fs.readFileSync(path.join(import.meta.dir, '../src/server.ts'), 'utf-8'); - test('No /sidebar-command, /sidebar-chat, /sidebar-agent/* routes', () => { - expect(SERVER_SRC).not.toMatch(/url\.pathname === ['"]\/sidebar-command['"]/); - expect(SERVER_SRC).not.toMatch(/url\.pathname === ['"]\/sidebar-chat['"]/); - expect(SERVER_SRC).not.toMatch(/url\.pathname\.startsWith\(['"]\/sidebar-agent\//); - expect(SERVER_SRC).not.toMatch(/url\.pathname === ['"]\/sidebar-agent\/event['"]/); - expect(SERVER_SRC).not.toMatch(/url\.pathname === ['"]\/sidebar-tabs['"]/); - expect(SERVER_SRC).not.toMatch(/url\.pathname === ['"]\/sidebar-session['"]/); + test('No /sidebar-command, /sidebar-chat, /sidebar-agent/* routes', async () => { + // Routes are dispatched only through the route table, so absence from + // the table plus the unmatched 404 with the root token is the contract. + const gone = ['/sidebar-command', '/sidebar-chat', '/sidebar-agent/event', '/sidebar-agent/x', '/sidebar-tabs', '/sidebar-session']; + for (const p of gone) { + expect(ROUTES.some(r => r.prefix ? p.startsWith(r.path) : r.path === p), p).toBe(false); + } + const server = makeServer(); + try { + for (const p of gone) { + for (const method of ['GET', 'POST']) { + const resp = await server.local(p, { method, headers: { Authorization: `Bearer ${server.rootToken}` } }); + expect([p, method, resp.status, await resp.text()]).toEqual([p, method, 404, 'Not found']); + } + } + } finally { server.cleanup(); } }); test('No chat-related state declarations or helpers', () => { diff --git a/browse/test/sidebar-ux.test.ts b/browse/test/sidebar-ux.test.ts index b189ec525..65c55fc30 100644 --- a/browse/test/sidebar-ux.test.ts +++ b/browse/test/sidebar-ux.test.ts @@ -23,6 +23,8 @@ import { describe, test, expect } from 'bun:test'; import * as fs from 'fs'; import * as path from 'path'; +import * as os from 'os'; +import { stubRouteContext, callRoute, routeEntry } from './route-test-harness'; import { EventEmitter } from 'node:events'; import { BrowserManager } from '../src/browser-manager'; @@ -676,29 +678,37 @@ describe('welcome page', () => { }); describe('server /welcome endpoint', () => { - const serverSrc = fs.readFileSync(path.join(ROOT, 'src', 'server.ts'), 'utf-8'); + // Resolve against empty HOME / skill-root dirs so neither the project + // welcome page nor the installed one exists. + async function welcomeWithoutPages(): Promise { + const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-welcome-empty-')); + const saved = { HOME: process.env.HOME, GSTACK_SKILL_ROOT: process.env.GSTACK_SKILL_ROOT }; + try { + process.env.HOME = empty; + process.env.GSTACK_SKILL_ROOT = empty; + return await callRoute('GET', '/welcome', stubRouteContext()); + } finally { + for (const [k, v] of Object.entries(saved)) { + if (v === undefined) delete process.env[k]; else process.env[k] = v; + } + fs.rmSync(empty, { recursive: true, force: true }); + } + } - test('/welcome endpoint exists in server.ts', () => { - expect(serverSrc).toContain("url.pathname === '/welcome'"); + test('/welcome endpoint exists in the route table', () => { + expect(routeEntry('GET', '/welcome')).toMatchObject({ path: '/welcome', auth: 'none', surfaces: ['local'] }); }); - test('/welcome serves HTML content type', () => { - const welcomeSection = serverSrc.slice( - serverSrc.indexOf("url.pathname === '/welcome'"), - serverSrc.indexOf("url.pathname === '/health'"), - ); - expect(welcomeSection).toContain("'Content-Type': 'text/html"); + test('/welcome serves HTML content type', async () => { + expect((await welcomeWithoutPages()).headers.get('content-type')).toBe('text/html; charset=utf-8'); }); - test('/welcome serves fallback HTML if no welcome file found', () => { - const welcomeSection = serverSrc.slice( - serverSrc.indexOf("url.pathname === '/welcome'"), - serverSrc.indexOf("url.pathname === '/health'"), - ); + test('/welcome serves fallback HTML if no welcome file found', async () => { // Changed from 302 redirect to about:blank (ERR_UNSAFE_REDIRECT on Windows) // to inline HTML fallback page (PR #822) - expect(welcomeSection).toContain('GStack Browser ready'); - expect(welcomeSection).toContain('status: 200'); + const resp = await welcomeWithoutPages(); + expect(resp.status).toBe(200); + expect(await resp.text()).toContain('GStack Browser ready'); }); }); diff --git a/browse/test/terminal-agent.test.ts b/browse/test/terminal-agent.test.ts index dd3e4fcf1..c4ef37bc3 100644 --- a/browse/test/terminal-agent.test.ts +++ b/browse/test/terminal-agent.test.ts @@ -23,6 +23,7 @@ import { extractPtyCookie, buildPtySetCookie, PTY_COOKIE_NAME, __resetPtySessions, } from '../src/pty-session-cookie'; +import { makeServer, stubRouteContext, callRoute, routeEntry } from './route-test-harness'; const SERVER_SRC = fs.readFileSync(path.join(import.meta.dir, '../src/server.ts'), 'utf-8'); const AGENT_SRC = fs.readFileSync(path.join(import.meta.dir, '../src/terminal-agent.ts'), 'utf-8'); @@ -89,17 +90,19 @@ describe('Source-level guard: /pty-session is not on the tunnel surface', () => }); }); -describe('Source-level guard: /health does NOT surface ptyToken', () => { - test('/health response body does not include ptyToken', () => { - const healthIdx = SERVER_SRC.indexOf("url.pathname === '/health'"); - expect(healthIdx).toBeGreaterThan(-1); - // Slice from /health through the response close-bracket. - const slice = SERVER_SRC.slice(healthIdx, healthIdx + 2000); - // The /health JSON.stringify body must not mention the cookie token. +describe('/health does NOT surface ptyToken', () => { + test('/health response body does not include ptyToken', async () => { // It's allowed to include `terminalPort` (a port number, not auth). - expect(slice).not.toContain('ptyToken'); - expect(slice).not.toContain('gstack_pty'); - expect(slice).toContain('terminalPort'); + const ctx = stubRouteContext({ + browserManager: { isHealthy: async () => true, getConnectionMode: () => 'launched', getTabCount: () => 1 } as any, + terminal: { readPort: () => 4242, grantToken: async () => true, restartSession: async () => true }, + }); + const text = await (await callRoute('GET', '/health', ctx)).text(); + const body = JSON.parse(text); + expect(body.terminalPort).toBe(4242); + expect(Object.keys(body).sort()).toEqual(['mode', 'status', 'tabs', 'terminalPort', 'uptime']); + expect(text).not.toContain('ptyToken'); + expect(text).not.toContain('gstack_pty'); }); }); @@ -229,21 +232,28 @@ describe('Source-level guard: terminal-agent', () => { }); }); -describe('Source-level guard: server.ts /pty-session route', () => { - test('validates AUTH_TOKEN, grants over loopback, returns token + Set-Cookie', () => { - const route = SERVER_SRC.slice(SERVER_SRC.indexOf("url.pathname === '/pty-session'")); +describe('/pty-session route', () => { + test('validates AUTH_TOKEN, grants over loopback, returns token + Set-Cookie', async () => { // Must check auth before minting. - const beforeMint = route.slice(0, route.indexOf('mintPtySessionToken')); - expect(beforeMint).toContain('validateAuth'); - // Must call the loopback grant before responding (otherwise the - // agent's validTokens Set never sees the token and /ws would 401). - expect(route).toContain('grantPtyToken'); - // Must return the token in the JSON body for the - // Sec-WebSocket-Protocol auth path (cross-port cookies don't survive - // SameSite=Strict from a chrome-extension origin). - expect(route).toContain('ptySessionToken'); - // Set-Cookie is kept as a fallback for non-browser callers. - expect(route).toContain('Set-Cookie'); - expect(route).toContain('buildPtySetCookie'); + expect(routeEntry('POST', '/pty-session').auth).toBe('root-bearer'); + const server = makeServer(); + try { + const denied = await server.local('/pty-session', { method: 'POST' }); + expect(denied.status).toBe(401); + } finally { server.cleanup(); } + // Must call the loopback grant before responding (otherwise the agent's + // validTokens Set never sees the token and /ws would 401), return the + // token in the JSON body for the Sec-WebSocket-Protocol auth path + // (cross-port cookies don't survive SameSite=Strict from a + // chrome-extension origin), and keep Set-Cookie as a fallback for + // non-browser callers. + const granted: string[] = []; + const ctx = stubRouteContext({ + terminal: { readPort: () => 4242, grantToken: async (token) => { granted.push(token); return true; }, restartSession: async () => true }, + }); + const resp = await callRoute('POST', '/pty-session', ctx); + const body = await resp.json() as any; + expect(granted).toEqual([body.ptySessionToken]); + expect(resp.headers.get('set-cookie')).toBe(buildPtySetCookie(body.ptySessionToken)); }); }); From 25d0708d9b9e6b96f9af64037d379150d3aee7d0 Mon Sep 17 00:00:00 2001 From: garrytan Date: Wed, 30 Sep 2026 06:12:00 +0000 Subject: [PATCH 3/5] test(browse): stubbed-handler auth matrix and route inventory for the route table Every ROUTES entry runs through the real dispatcher and gate with stub handlers on each declared surface and six credentials; denials assert the exact status and body each auth kind returned at 96764e8, admitted credentials assert the handler ran (with the gate's TokenInfo for scoped routes). Also pins the reviewed route inventory (method, path, auth kind, surfaces), that every entry declares auth and surfaces, that the table's tunnel paths equal the TUNNEL_PATHS literal with GET /connect admitted, the unmatched fallthrough, and that the root token is rejected on every tunnel route through buildFetchHandler. --- browse/test/server-route-table.test.ts | 235 +++++++++++++++++++++++++ 1 file changed, 235 insertions(+) create mode 100644 browse/test/server-route-table.test.ts diff --git a/browse/test/server-route-table.test.ts b/browse/test/server-route-table.test.ts new file mode 100644 index 000000000..0fbbc80fa --- /dev/null +++ b/browse/test/server-route-table.test.ts @@ -0,0 +1,235 @@ +/** + * Route-table contract tests (stubbed handlers). + * + * Every entry in ROUTES runs through the real dispatcher and auth gate with a + * stub RouteContext and stub handlers, on every surface it declares, with no + * token, a wrong token, the root token, a scoped token, the SSE cookie and the + * pinned extension Origin. Denials assert the exact status and body each auth + * kind returned at 96764e8; admitted credentials assert the handler ran. + * + * Real-handler coverage for the same routes lives in + * server-route-auth-blackbox.test.ts (every route, both surfaces, through + * buildFetchHandler), plus the route-specific suites (extension-token, + * pair-agent-e2e, server-pty-lease-routes, pty-inject-scan, dual-listener). + */ + +import { describe, test, expect } from 'bun:test'; +import * as crypto from 'crypto'; +import * as fs from 'node:fs'; +import * as os from 'node:os'; +import * as path from 'node:path'; +import { ROUTES } from '../src/routes'; +import { + dispatchRoute, findRoute, UNMATCHED_ROUTE, + type AuthKind, type RouteContext, type RouteEntry, type Surface, +} from '../src/routes/table'; +import { buildFetchHandler, __testInternals__ } from '../src/server'; +import { __resetRegistry } from '../src/token-registry'; +import { BrowserManager } from '../src/browser-manager'; +import { resolveConfig } from '../src/config'; + +type Cred = 'none' | 'wrong' | 'root' | 'scoped' | 'sse-cookie' | 'extension-origin'; +const CREDS: Cred[] = ['none', 'wrong', 'root', 'scoped', 'sse-cookie', 'extension-origin']; + +const ROOT = 'stub-root-token-0123456789'; +const SCOPED = 'stub-scoped-token-0123456789'; +const COOKIE = 'stub-sse-cookie'; + +function credHeaders(cred: Cred): Record { + switch (cred) { + case 'none': return {}; + case 'wrong': return { Authorization: 'Bearer stub-wrong-token-0123456789' }; + case 'root': return { Authorization: `Bearer ${ROOT}` }; + case 'scoped': return { Authorization: `Bearer ${SCOPED}` }; + case 'sse-cookie': return { Cookie: `gstack_sse=${COOKIE}` }; + case 'extension-origin': return { Origin: 'pinned-extension', Host: '127.0.0.1:34567' }; + } +} + +const ROOT_INFO = { clientId: 'root', scopes: ['admin'] } as any; +const SCOPED_INFO = { clientId: 'stub-agent', scopes: ['read'] } as any; + +function stubContext(): RouteContext { + const bearer = (req: Request) => req.headers.get('authorization'); + const unused = () => { throw new Error('stub handlers never reach the context'); }; + return { + browserManager: {} as any, + startTime: 0, + browsePort: 34567, + validateAuth: (req) => bearer(req) === `Bearer ${ROOT}`, + isRootRequest: (req) => bearer(req) === `Bearer ${ROOT}`, + getTokenInfo: (req) => bearer(req) === `Bearer ${ROOT}` ? ROOT_INFO : bearer(req) === `Bearer ${SCOPED}` ? SCOPED_INFO : null, + hasSseCookie: (req) => req.headers.get('cookie') === `gstack_sse=${COOKIE}`, + isPinnedExtensionRequest: (req) => req.headers.get('origin') === 'pinned-extension', + isRootTokenValue: (token) => token === ROOT, + bootstrapRootToken: ROOT, + resetIdleTimer: unused, + terminal: { readPort: unused, grantToken: unused, restartSession: unused }, + tunnel: { state: unused, close: unused, resolveAuthtoken: unused, start: unused }, + commands: { handle: unused, handleInternal: unused }, + }; +} + +const REACHED = 'stub-handler-reached'; +function stubbed(routes: readonly RouteEntry[]): RouteEntry[] { + return routes.map(r => ({ + ...r, + handler: (_req, { tokenInfo }) => new Response(JSON.stringify({ reached: REACHED, tokenInfo }), { status: 299 }), + })); +} + +/** Denials exactly as the if-chain server returned them for each gate-level check at 96764e8. */ +const EXPECTED_DENIAL: Record, { status: number; body: string }> = { + 'root-bearer': { status: 401, body: '{"error":"Unauthorized"}' }, + 'scoped': { status: 401, body: '{"error":"Unauthorized"}' }, + 'root-or-sse-cookie': { status: 401, body: '{"error":"Unauthorized"}' }, + 'root-token': { status: 403, body: '{"error":"Root token required"}' }, + 'extension-origin': { status: 403, body: '{"error":"Forbidden"}' }, +}; + +const ADMITTED: Record = { + 'none': CREDS, + 'handler': CREDS, + 'root-bearer': ['root'], + 'root-token': ['root'], + 'scoped': ['root', 'scoped'], + 'root-or-sse-cookie': ['root', 'sse-cookie'], + 'extension-origin': ['extension-origin'], +}; + +/** Every route the daemon serves, with the auth kind and surfaces a security review signed off on. */ +const EXPECTED_ROUTES: Array<[method: string, path: string, auth: AuthKind, surfaces: Surface[]]> = [ + ['GET', '/connect', 'none', ['local', 'tunnel']], + ['POST', '/connect', 'none', ['local', 'tunnel']], + ['*', '/cookie-picker*', 'handler', ['local']], + ['*', '/welcome', 'none', ['local']], + ['POST', '/extension-token', 'extension-origin', ['local']], + ['*', '/health', 'none', ['local']], + ['POST', '/pty-session', 'root-bearer', ['local']], + ['POST', '/pty-session/reattach', 'root-bearer', ['local']], + ['POST', '/pty-restart', 'root-bearer', ['local']], + ['POST', '/pty-dispose', 'handler', ['local']], + ['POST', '/internal/lease-refresh', 'root-bearer', ['local']], + ['POST', '/pty-inject-scan', 'root-bearer', ['local']], + ['POST', '/token', 'handler', ['local']], + ['DELETE', '/token/*', 'root-token', ['local']], + ['GET', '/agents', 'root-token', ['local']], + ['POST', '/pair', 'root-token', ['local']], + ['POST', '/tunnel/start', 'root-token', ['local']], + ['POST', '/sse-session', 'root-bearer', ['local']], + ['*', '/refs', 'root-bearer', ['local']], + ['*', '/activity/stream', 'root-or-sse-cookie', ['local']], + ['*', '/activity/history', 'root-bearer', ['local']], + ['POST', '/batch', 'scoped', ['local']], + ['GET', '/file', 'scoped', ['local']], + ['POST', '/command', 'scoped', ['local', 'tunnel']], + ['POST', '/inspector/pick', 'root-bearer', ['local']], + ['GET', '/inspector', 'root-bearer', ['local']], + ['POST', '/inspector/apply', 'root-bearer', ['local']], + ['POST', '/inspector/reset', 'root-bearer', ['local']], + ['GET', '/inspector/history', 'root-bearer', ['local']], + ['GET', '/memory', 'root-bearer', ['local']], + ['GET', '/inspector/events', 'root-bearer', ['local']], +]; + +const routeKey = (r: RouteEntry) => `${r.method} ${r.path}${r.prefix ? '*' : ''}`; +const requestPath = (r: RouteEntry) => r.prefix ? `${r.path}${r.path.endsWith('/') ? 'probe' : '/probe'}` : r.path; +const requestMethod = (r: RouteEntry) => r.method === '*' ? 'GET' : r.method; + +describe('route table declarations', () => { + test('the table is exactly the reviewed route inventory, auth kinds and surfaces', () => { + const describe = (method: string, p: string, auth: AuthKind, surfaces: readonly Surface[]) => + `${method} ${p} auth=${auth} surfaces=${surfaces.join(',')}`; + const actual = ROUTES.map(r => describe(r.method, `${r.path}${r.prefix ? '*' : ''}`, r.auth, r.surfaces)).sort(); + const expected = EXPECTED_ROUTES.map(([m, p, a, s]) => describe(m, p, a, s)).sort(); + expect(actual).toEqual(expected); + }); + + test('every route declares an auth kind and at least one surface; only handler-auth routes carry handlerAuth', () => { + const kinds = new Set(['none', 'root-bearer', 'root-token', 'scoped', 'extension-origin', 'root-or-sse-cookie', 'handler']); + for (const r of ROUTES) { + expect(kinds.has(r.auth), routeKey(r)).toBe(true); + expect(r.surfaces.length, routeKey(r)).toBeGreaterThan(0); + expect(typeof r.handler, routeKey(r)).toBe('function'); + if (r.auth === 'handler') expect(r.handlerAuth?.length ?? 0, routeKey(r)).toBeGreaterThan(20); + else expect(r.handlerAuth, routeKey(r)).toBeUndefined(); + } + }); + + test('no two entries claim the same method and path', () => { + const keys = ROUTES.map(routeKey); + expect(new Set(keys).size).toBe(keys.length); + }); + + test('the tunnel-surface paths in the table equal the TUNNEL_PATHS literal', () => { + const tableTunnelPaths = new Set(ROUTES.filter(r => r.surfaces.includes('tunnel')).map(r => r.path)); + expect([...tableTunnelPaths].sort()).toEqual([...__testInternals__.tunnelPaths].sort()); + expect(findRoute(ROUTES, 'GET', '/connect', 'tunnel')?.auth).toBe('none'); + }); +}); + +describe('route table auth matrix (stubbed handlers)', () => { + const ctx = stubContext(); + const routes = stubbed(ROUTES); + for (const route of routes) { + for (const surface of route.surfaces) { + for (const cred of CREDS) { + test(`${surface} ${routeKey(route)} with ${cred}`, async () => { + const url = new URL(`http://127.0.0.1:34567${requestPath(route)}`); + const req = new Request(url, { method: requestMethod(route), headers: credHeaders(cred) }); + const resp = await dispatchRoute(routes, req, url, surface, ctx); + const body = await resp.text(); + if (ADMITTED[route.auth].includes(cred)) { + expect(resp.status).toBe(299); + const parsed = JSON.parse(body); + expect(parsed.reached).toBe(REACHED); + if (route.auth === 'scoped') expect(parsed.tokenInfo).toEqual(cred === 'root' ? ROOT_INFO : SCOPED_INFO); + return; + } + const denial = EXPECTED_DENIAL[route.auth as keyof typeof EXPECTED_DENIAL]; + expect({ status: resp.status, body }).toEqual(denial); + expect(resp.headers.get('content-type')).toBe('application/json'); + }); + } + } + } + + test('a local-only entry is not matched on the tunnel surface', () => { + for (const r of ROUTES.filter(r => !r.surfaces.includes('tunnel'))) { + expect(findRoute(ROUTES, requestMethod(r), requestPath(r), 'tunnel'), routeKey(r)).toBeNull(); + } + }); + + for (const [method, pathname] of [['GET', '/no-such-route'], ['GET', '/command'], ['PUT', '/token'], ['GET', '/token/x']]) { + test(`unmatched ${method} ${pathname}: root-bearer check, then plain-text 404`, async () => { + expect(UNMATCHED_ROUTE.auth).toBe('root-bearer'); + const url = new URL(`http://127.0.0.1:34567${pathname}`); + for (const cred of CREDS) { + const resp = await dispatchRoute(routes, new Request(url, { method, headers: credHeaders(cred) }), url, 'local', ctx); + const body = await resp.text(); + if (cred === 'root') expect({ status: resp.status, body }).toEqual({ status: 404, body: 'Not found' }); + else expect({ status: resp.status, body }).toEqual(EXPECTED_DENIAL['root-bearer']); + } + }); + } +}); + +describe('tunnel surface rejects the root token on every tunnel route', () => { + const fixtureDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-route-table-')); + const config = resolveConfig({ BROWSE_STATE_FILE: path.join(fixtureDir, 'state/browse.json') }); + for (const route of ROUTES.filter(r => r.surfaces.includes('tunnel'))) { + test(`${routeKey(route)}`, async () => { + __resetRegistry(); + const authToken = 'route-table-' + crypto.randomBytes(16).toString('hex'); + const handle = buildFetchHandler({ + authToken, browsePort: 34567, config, browserManager: new BrowserManager(), + ownsTerminalAgent: false, startTime: Date.now(), + }); + const resp = await handle.fetchTunnel(new Request(`http://127.0.0.1:34567${route.path}`, { + method: route.method, headers: { Authorization: `Bearer ${authToken}` }, + }), null); + expect(resp.status).toBe(403); + expect((await resp.json() as { error: string }).error).toBe('Root token rejected on tunnel surface'); + }); + } +}); From 14d0280f2cdaaedec948a36e7e184d5c332cfbbb Mon Sep 17 00:00:00 2001 From: garrytan Date: Wed, 30 Sep 2026 06:12:01 +0000 Subject: [PATCH 4/5] test(browse): ratchet (b) keeps route dispatch inside the route table Scans browse/src/server.ts and browse/src/routes/*.ts for pathname comparisons; only the table matcher and the tunnel-surface filter are allowed, listed with reasons in browse/test/fixtures/route-dispatch-allowlist.json (keyed on file plus line text). Also checks every entry declares auth and surfaces and that gstack registers no beforeRoute overlay itself. Self-tests plant a violation and assert the file:line, Fix: and allowlist path in the message, that a shifted line stays allowlisted, and that a reasonless entry is rejected. --- .../fixtures/route-dispatch-allowlist.json | 22 +++ .../server-route-dispatch-ratchet.test.ts | 129 ++++++++++++++++++ 2 files changed, 151 insertions(+) create mode 100644 browse/test/fixtures/route-dispatch-allowlist.json create mode 100644 browse/test/server-route-dispatch-ratchet.test.ts diff --git a/browse/test/fixtures/route-dispatch-allowlist.json b/browse/test/fixtures/route-dispatch-allowlist.json new file mode 100644 index 000000000..4dd117db8 --- /dev/null +++ b/browse/test/fixtures/route-dispatch-allowlist.json @@ -0,0 +1,22 @@ +[ + { + "file": "browse/src/server.ts", + "match": "const isGetConnect = req.method === 'GET' && url.pathname === '/connect';", + "reason": "Tunnel-surface filter: admits the GET /connect liveness probe before any route dispatch." + }, + { + "file": "browse/src/server.ts", + "match": "const allowed = TUNNEL_PATHS.has(url.pathname);", + "reason": "Tunnel-surface filter: default-deny path allowlist (the TUNNEL_PATHS literal)." + }, + { + "file": "browse/src/server.ts", + "match": "if (url.pathname !== '/connect' && !getTokenInfo(req)) {", + "reason": "Tunnel-surface filter: every tunnel path except /connect needs a scoped token." + }, + { + "file": "browse/src/routes/table.ts", + "match": "&& (r.prefix ? pathname.startsWith(r.path) : pathname === r.path),", + "reason": "The route table's own matcher (findRoute)." + } +] diff --git a/browse/test/server-route-dispatch-ratchet.test.ts b/browse/test/server-route-dispatch-ratchet.test.ts new file mode 100644 index 000000000..5d67c1796 --- /dev/null +++ b/browse/test/server-route-dispatch-ratchet.test.ts @@ -0,0 +1,129 @@ +/** + * Ratchet (b): browse routes are dispatched only by the route table. + * + * Scans buildFetchHandler's listener code (browse/src/server.ts) and the + * route modules (browse/src/routes/*.ts) for pathname comparisons. Every one + * must be the table's matcher or the tunnel-surface filter, listed with a + * reason in browse/test/fixtures/route-dispatch-allowlist.json (keyed on file + * plus matched line text, never line numbers). terminal-agent.ts, cli.ts and + * memory-command.ts are separate listeners and out of scope. Also checks that + * every table entry declares auth and surfaces and that gstack registers no + * beforeRoute overlay of its own (overlays are for embedders). + */ + +import { describe, test, expect } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { ROUTES } from '../src/routes'; + +const ROOT = path.resolve(import.meta.dir, '..', '..'); +const ALLOWLIST_PATH = 'browse/test/fixtures/route-dispatch-allowlist.json'; + +interface AllowEntry { file: string; match: string; reason?: string } +interface Violation { file: string; line: number; text: string } + +const PATHNAME_DISPATCH = /\bpathname\s*(?:===|!==|==|!=)|(?:===|!==|==|!=)\s*(?:url\.)?pathname\b|\bpathname\.startsWith\(|\.has\(\s*(?:url\.)?pathname\s*\)/; +const COMMENT_LINE = /^\s*(?:\/\/|\*|\/\*)/; + +export function scanRouteDispatch(files: Array<{ file: string; source: string }>, allowlist: AllowEntry[]): Violation[] { + const allowed = new Set(allowlist.map(e => `${e.file}\0${e.match}`)); + const violations: Violation[] = []; + for (const { file, source } of files) { + source.split('\n').forEach((raw, i) => { + if (COMMENT_LINE.test(raw) || !PATHNAME_DISPATCH.test(raw)) return; + const text = raw.trim(); + if (!allowed.has(`${file}\0${text}`)) violations.push({ file, line: i + 1, text }); + }); + } + return violations; +} + +export function formatViolations(violations: Violation[]): string { + return [ + 'Route dispatch outside the browse route table:', + ...violations.map(v => ` ${v.file}:${v.line} ${v.text}`), + 'Rule: every browse HTTP route is dispatched by the route table, because an inline pathname check bypasses the one auth gate and the declared surfaces.', + 'Fix: add a route-table entry with auth and surfaces (shape in browse/src/routes/table.ts) instead of comparing url.pathname.', + `Allowlist: ${ALLOWLIST_PATH} — only for the tunnel-surface filter and the table's own matcher; every entry needs a reason.`, + ].join('\n'); +} + +function entriesWithoutReason(allowlist: AllowEntry[]): AllowEntry[] { + return allowlist.filter(e => typeof e.reason !== 'string' || e.reason.trim().length === 0); +} + +function listenerSources(): Array<{ file: string; source: string }> { + const routeDir = path.join(ROOT, 'browse/src/routes'); + const files = ['browse/src/server.ts', ...fs.readdirSync(routeDir).filter(f => f.endsWith('.ts')).map(f => `browse/src/routes/${f}`)]; + return files.map(file => ({ file, source: fs.readFileSync(path.join(ROOT, file), 'utf-8') })); +} + +const ALLOWLIST: AllowEntry[] = JSON.parse(fs.readFileSync(path.join(ROOT, ALLOWLIST_PATH), 'utf-8')); + +describe('ratchet (b): route dispatch goes through the table', () => { + test('no pathname comparison outside the table matcher and the tunnel filter', () => { + const violations = scanRouteDispatch(listenerSources(), ALLOWLIST); + if (violations.length) throw new Error(formatViolations(violations)); + }); + + test('every allowlist entry carries a reason and still matches a line', () => { + const missing = entriesWithoutReason(ALLOWLIST); + if (missing.length) throw new Error(`Allowlist entries without a reason in ${ALLOWLIST_PATH}:\n${missing.map(e => ` ${e.file} ${e.match}`).join('\n')}`); + const sources = new Map(listenerSources().map(s => [s.file, s.source.split('\n').map(l => l.trim())])); + for (const e of ALLOWLIST) expect(sources.get(e.file)?.includes(e.match), `${e.file} ${e.match}`).toBe(true); + }); + + test('every table entry declares auth and surfaces', () => { + for (const r of ROUTES) { + expect(typeof r.auth, `${r.method} ${r.path}`).toBe('string'); + expect(Array.isArray(r.surfaces) && r.surfaces.length > 0, `${r.method} ${r.path}`).toBe(true); + } + }); + + test('gstack registers no beforeRoute overlay of its own', () => { + const code = fs.readFileSync(path.join(ROOT, 'browse/src/server.ts'), 'utf-8') + .split('\n').filter(l => !COMMENT_LINE.test(l)).join('\n'); + expect(code).not.toMatch(/\bbeforeRoute\s*:/); + }); +}); + +describe('ratchet (b) self-test', () => { + const planted = { + file: 'browse/src/routes/planted.ts', + source: [ + "import { json } from './table';", + 'export function sneaky(url: URL) {', + " if (url.pathname === '/backdoor') return json({ ok: true });", + '}', + ].join('\n'), + }; + + test('a planted inline route fails with file:line, the Fix, and the allowlist path', () => { + const violations = scanRouteDispatch([planted], ALLOWLIST); + expect(violations).toEqual([{ file: planted.file, line: 3, text: "if (url.pathname === '/backdoor') return json({ ok: true });" }]); + const message = formatViolations(violations); + expect(message).toContain("browse/src/routes/planted.ts:3 if (url.pathname === '/backdoor')"); + expect(message).toContain('Fix: add a route-table entry with auth and surfaces'); + expect(message).toContain(ALLOWLIST_PATH); + }); + + test('startsWith and Set.has dispatch are caught too; comments are not', () => { + const source = [ + "// url.pathname === '/documented' in a comment", + "if (url.pathname.startsWith('/prefix')) {}", + 'if (PATHS.has(url.pathname)) {}', + ].join('\n'); + expect(scanRouteDispatch([{ file: 'x.ts', source }], []).map(v => v.line)).toEqual([2, 3]); + }); + + test('allowlist entries are keyed on text, so inserting a line above one still passes', () => { + const entry = { file: 'browse/src/server.ts', match: 'const allowed = TUNNEL_PATHS.has(url.pathname);', reason: 'tunnel filter' }; + const shifted = { file: entry.file, source: `// new line\nconst x = 1;\n ${entry.match}\n` }; + expect(scanRouteDispatch([shifted], [entry])).toEqual([]); + }); + + test('an allowlist entry without a reason is rejected', () => { + expect(entriesWithoutReason([{ file: 'a.ts', match: 'x' }, { file: 'b.ts', match: 'y', reason: ' ' }, { file: 'c.ts', match: 'z', reason: 'ok' }])) + .toEqual([{ file: 'a.ts', match: 'x' }, { file: 'b.ts', match: 'y', reason: ' ' }]); + }); +}); From 4ce37c3764b36ac04468ef4c35d6f1abf7578941 Mon Sep 17 00:00:00 2001 From: garrytan Date: Wed, 30 Sep 2026 06:12:01 +0000 Subject: [PATCH 5/5] test: touchfile superset check for modules moved out of browse/src/server.ts Records the paid evals selected by touching browse/src/server.ts at 96764e80 (17 E2E, 1 LLM judge) and asserts every browse/src/routes/*.ts module selects a superset. The test reads every golden in test/fixtures/moved-module-selection/ so other moved-code goldens can sit beside it. --- .../w3-browse-routes.json | 40 ++++++++++++ test/touchfile-moved-module-selection.test.ts | 61 +++++++++++++++++++ 2 files changed, 101 insertions(+) create mode 100644 test/fixtures/moved-module-selection/w3-browse-routes.json create mode 100644 test/touchfile-moved-module-selection.test.ts diff --git a/test/fixtures/moved-module-selection/w3-browse-routes.json b/test/fixtures/moved-module-selection/w3-browse-routes.json new file mode 100644 index 000000000..2ff76d858 --- /dev/null +++ b/test/fixtures/moved-module-selection/w3-browse-routes.json @@ -0,0 +1,40 @@ +{ + "workstream": "W3 browse route table", + "recordedAt": "96764e80", + "source": "browse/src/server.ts", + "modules": [ + "browse/src/routes/activity.ts", + "browse/src/routes/commands.ts", + "browse/src/routes/core.ts", + "browse/src/routes/files.ts", + "browse/src/routes/index.ts", + "browse/src/routes/inspector.ts", + "browse/src/routes/pairing.ts", + "browse/src/routes/pty.ts", + "browse/src/routes/table.ts", + "browse/src/routes/tokens.ts", + "browse/src/routes/tunnel.ts" + ], + "e2e": [ + "aside-browse-basic", + "aside-browse-flow", + "benchmark-workflow", + "browse-basic", + "browse-snapshot", + "canary-workflow", + "carve-section-loading", + "design-review-detector-shim-dom", + "design-review-fix", + "diagram-authoring-quality", + "diagram-triplet", + "qa-b6-static", + "qa-b7-spa", + "qa-b8-checkout", + "qa-fix-loop", + "qa-only-no-fix", + "qa-quick" + ], + "llmJudge": [ + "browse/SKILL.md reference" + ] +} diff --git a/test/touchfile-moved-module-selection.test.ts b/test/touchfile-moved-module-selection.test.ts new file mode 100644 index 000000000..1b7421e38 --- /dev/null +++ b/test/touchfile-moved-module-selection.test.ts @@ -0,0 +1,61 @@ +/** + * Touchfile coverage for moved code. + * + * Each JSON file in test/fixtures/moved-module-selection/ records, before a + * refactor moved code out of `source`, the paid evals selected by touching + * that source file. Touching any module the code moved into must select a + * superset, so a move can never silently drop eval coverage. + */ + +import { describe, test, expect } from 'bun:test'; +import * as fs from 'node:fs'; +import * as path from 'node:path'; +import { E2E_TOUCHFILES, LLM_JUDGE_TOUCHFILES, GLOBAL_TOUCHFILES, selectTests } from './helpers/touchfiles'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const GOLDEN_DIR = 'test/fixtures/moved-module-selection'; + +interface Golden { workstream: string; source: string; modules: string[]; e2e: string[]; llmJudge: string[] } + +const goldens = fs.readdirSync(path.join(ROOT, GOLDEN_DIR)) + .filter(f => f.endsWith('.json')) + .map(f => ({ file: `${GOLDEN_DIR}/${f}`, golden: JSON.parse(fs.readFileSync(path.join(ROOT, GOLDEN_DIR, f), 'utf-8')) as Golden })); + +function missingSelections(module: string, golden: Golden): string[] { + const e2e = new Set(selectTests([module], E2E_TOUCHFILES, GLOBAL_TOUCHFILES).selected); + const judge = new Set(selectTests([module], LLM_JUDGE_TOUCHFILES, GLOBAL_TOUCHFILES).selected); + return [ + ...golden.e2e.filter(t => !e2e.has(t)).map(t => `E2E ${t}`), + ...golden.llmJudge.filter(t => !judge.has(t)).map(t => `LLM judge ${t}`), + ]; +} + +describe('moved modules keep their source file\'s paid-eval selection', () => { + test('at least one golden is recorded', () => { + expect(goldens.length).toBeGreaterThan(0); + }); + + for (const { file, golden } of goldens) { + test(`${golden.workstream}: every module moved out of ${golden.source} selects a superset`, () => { + const problems: string[] = []; + for (const module of golden.modules) { + if (!fs.existsSync(path.join(ROOT, module))) problems.push(`${module} (listed in ${file} but missing)`); + for (const miss of missingSelections(module, golden)) problems.push(`${module} does not select ${miss}`); + } + if (problems.length) { + throw new Error([ + 'Moved modules lost paid-eval selection:', + ...problems.map(p => ` ${p}`), + `Rule: code moved out of ${golden.source} must keep every eval that touching ${golden.source} selected, or a regression in the moved code ships unevaluated.`, + `Fix: add the new module to ${golden.source}'s touchfile entries in test/helpers/touchfiles-data.ts (a directory glob is fine).`, + `Golden: ${file} — re-record it only when the source file's own selection legitimately changes.`, + ].join('\n')); + } + }); + } + + test('a module outside every touchfile entry is reported', () => { + const golden: Golden = { workstream: 'self-test', source: 'browse/src/server.ts', modules: [], e2e: ['browse-basic'], llmJudge: [] }; + expect(missingSelections('nowhere/planted-module.ts', golden)).toEqual(['E2E browse-basic']); + }); +});