diff --git a/browse/src/cli.ts b/browse/src/cli.ts index 0827c8ae6..18cee9b3e 100644 --- a/browse/src/cli.ts +++ b/browse/src/cli.ts @@ -1101,6 +1101,133 @@ export function extractGlobalFlags(rawArgs: string[], env: NodeJS.ProcessEnv): G }; } +// ─── Tunnel token management (pre-server, #2254 pattern) ──────── +// Tokens live in daemon memory, so a dead daemon means "nothing is paired" — +// a success state, not an error. Never boot a daemon to serve these, and +// never mutate the state file (stale-state cleanup stays stop's job). + +/** Live-daemon check for tunnel subcommands. Dead pid AND failed health → + * null. An alive pid with an unreachable port falls through to the HTTP + * call, whose failure is reported truthfully (exit 1), not as "no daemon". */ +async function tunnelDaemonState(): Promise { + const state = readState(); + if (!state) return null; + if (!isProcessAlive(state.pid) && !(await isServerHealthy(state.port))) return null; + return state; +} + +/** Fetch active agent clientIds (sessions + pending setup keys). Returns + * null when the list can't be read — callers must not treat that as empty. */ +async function fetchAgentList(state: ServerState): Promise | null> { + try { + const resp = await fetch(`http://127.0.0.1:${state.port}/agents`, { + headers: { 'Authorization': `Bearer ${state.token}` }, + signal: AbortSignal.timeout(5000), + }); + if (!resp.ok) return null; + const body = await resp.json() as { agents?: unknown }; + if (!Array.isArray(body.agents)) return null; + return body.agents as Array<{ clientId: string; scopes: string[]; domains?: string[]; expiresAt: string | null; commandCount: number; pending?: boolean }>; + } catch { + return null; + } +} + +async function tunnelRevoke(name: string): Promise { + const state = await tunnelDaemonState(); + if (!state) { + console.log('No daemon running - tokens live in daemon memory, so nothing is paired.'); + return 0; + } + let resp: Response; + try { + resp = await fetch(`http://127.0.0.1:${state.port}/token/${encodeURIComponent(name)}`, { + method: 'DELETE', + headers: { 'Authorization': `Bearer ${state.token}` }, + signal: AbortSignal.timeout(5000), + }); + } catch (err) { + console.error(`[browse] Could not reach daemon: ${err instanceof Error ? err.message : String(err)}`); + return 1; + } + if (resp.status === 404) { + console.error(`No paired agent named "${name}".`); + const agents = await fetchAgentList(state); + if (agents && agents.length) { + console.error(`Active agents: ${agents.map(a => a.clientId).join(', ')}`); + } else if (agents) { + console.error('No agents are currently paired.'); + } + return 1; + } + if (!resp.ok) { + let msg = `HTTP ${resp.status}`; + try { + const body = await resp.json() as { error?: string }; + if (body.error) msg = body.error; + } catch { /* keep the status-line message */ } + console.error(`[browse] Revoke failed: ${msg}`); + return 1; + } + let deleted: number | undefined; + try { + const body = await resp.json() as { tokens_deleted?: number }; + if (typeof body.tokens_deleted === 'number') deleted = body.tokens_deleted; + } catch { /* old daemons answer {revoked} only — count stays unknown */ } + console.log(deleted === undefined + ? `Revoked "${name}" (count unknown).` + : `Revoked "${name}" (${deleted} token${deleted === 1 ? '' : 's'}).`); + // Post-revoke verification: re-read the agent list to PROVE it's gone. + // This is also the version-skew net — an old daemon with the first-match + // revoke bug returns 200 while the session survives; catch it here. + const agents = await fetchAgentList(state); + if (agents === null) { + console.error('[browse] Revoked, but could not verify against the agent list.'); + return 1; + } + if (agents.some(a => a.clientId === name)) { + console.error(`[browse] Revocation incomplete: "${name}" is still listed (old daemon or concurrent re-pair). Re-run "tunnel revoke ${name}", or run "stop" to clear every token.`); + return 1; + } + console.log('Verified: not in the active agent list.'); + return 0; +} + +async function tunnelAgents(): Promise { + const state = await tunnelDaemonState(); + if (!state) { + console.log('No daemon running - no paired agents.'); + return 0; + } + const agents = await fetchAgentList(state); + if (agents === null) { + console.error('[browse] Could not read the agent list from the daemon.'); + return 1; + } + if (agents.length === 0) { + console.log('No paired agents.'); + return 0; + } + for (const a of agents) { + const pending = a.pending ? ' (pending setup key)' : ''; + const domains = a.domains && a.domains.length ? a.domains.join(',') : 'any'; + console.log(`${a.clientId}${pending} scopes=${(a.scopes || []).join(',')} domains=${domains} expires=${a.expiresAt ?? 'never'} commands=${a.commandCount ?? 0}`); + } + return 0; +} + +async function handleTunnel(args: string[]): Promise { + const sub = args[0]; + if (sub === 'revoke' && args.length === 2 && args[1].trim()) { + process.exit(await tunnelRevoke(args[1].trim())); + } + if (sub === 'agents' && args.length === 1) { + process.exit(await tunnelAgents()); + } + console.error('usage: browse tunnel | agents>'); + process.exit(1); +} + async function handlePairAgent(state: ServerState, args: string[]): Promise { const clientName = parseFlag(args, '--client') || `remote-${Date.now()}`; const domains = parseFlag(args, '--domain')?.split(',').map(d => d.trim()); @@ -1303,6 +1430,7 @@ Multi-step: chain (reads JSON from stdin) Tabs: tabs | tab | newtab [url] | closetab [id] Server: status | cookie = | header : useragent | stop | restart + tunnel revoke | tunnel agents (paired-agent tokens) --force-restart: replace a live-but-busy daemon (any command; LOSES tabs/cookies/logins — never done automatically) Dialogs: dialog-accept [text] | dialog-dismiss @@ -1641,6 +1769,13 @@ Refs: After 'snapshot', use @e1, @e2... as selectors: // sendCommand('stop') path (graceful shutdown; busy semantics apply). } + // ─── Tunnel token management (pre-server short-circuit, #2254) ── + // Tokens live in daemon memory; a dead daemon has nothing to revoke or + // list, so never boot one to serve these. + if (command === 'tunnel') { + await handleTunnel(commandArgs); // always exits + } + // Special case: chain reads from stdin if (command === 'chain' && commandArgs.length === 0) { const stdin = await Bun.stdin.text(); diff --git a/browse/src/server.ts b/browse/src/server.ts index 7efaf13c0..3f551e244 100644 --- a/browse/src/server.ts +++ b/browse/src/server.ts @@ -2330,7 +2330,15 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle { status: 403, headers: { 'Content-Type': 'application/json' }, }); } - const clientId = url.pathname.slice('/token/'.length); + // 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); if (!revoked) { return new Response(JSON.stringify({ error: `Agent "${clientId}" not found` }), { @@ -2350,13 +2358,17 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle { status: 403, headers: { 'Content-Type': 'application/json' }, }); } - const agents = listTokens().map(t => ({ + // 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' }, diff --git a/browse/src/token-registry.ts b/browse/src/token-registry.ts index 439a11a3e..21bce0739 100644 --- a/browse/src/token-registry.ts +++ b/browse/src/token-registry.ts @@ -449,8 +449,12 @@ export function rotateRoot(): string { /** * List all active (non-expired) scoped tokens. + * With includeSetup, unexchanged ("pending") setup keys are listed too — + * they are live grants an operator must be able to see and revoke. Spent + * keys stay hidden: they are re-exchange bookkeeping for a session that is + * already listed. */ -export function listTokens(): TokenInfo[] { +export function listTokens(opts?: { includeSetup?: boolean }): TokenInfo[] { const now = new Date(); const result: TokenInfo[] = []; @@ -461,6 +465,8 @@ export function listTokens(): TokenInfo[] { } if (info.type === 'session') { result.push(info); + } else if (opts?.includeSetup && info.type === 'setup' && info.usesRemaining !== 0) { + result.push(info); } } diff --git a/browse/test/pair-agent-e2e.test.ts b/browse/test/pair-agent-e2e.test.ts index 2f5c9169e..6e58123d6 100644 --- a/browse/test/pair-agent-e2e.test.ts +++ b/browse/test/pair-agent-e2e.test.ts @@ -194,6 +194,120 @@ describe('pair-agent flow end-to-end (HTTP only, no ngrok)', () => { expect(Array.isArray(scopes)).toBe(true); }); + // ─── Revocation e2e: revoke-all + the /agents verification surface ──── + + test('DELETE /token revokes session AND setup keys; agent leaves /agents; token 401s; re-connect fails', async () => { + const pair = async () => { + const resp = await fetch(`${daemon.baseUrl}/pair`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${daemon.token}` }, + body: JSON.stringify({ clientId: 'revoke-e2e' }), + }); + return (await resp.json() as any).setup_key as string; + }; + const key1 = await pair(); + const connectResp = await fetch(`${daemon.baseUrl}/connect`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ setup_key: key1 }), + }); + const { token: scopedToken } = await connectResp.json() as any; + + // A second, UNSPENT setup key for the same clientId (the re-grant hole). + const key2 = await pair(); + + const pre = await fetch(`${daemon.baseUrl}/command`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${scopedToken}` }, + body: JSON.stringify({ command: 'status', args: [] }), + }); + expect(pre.status).not.toBe(401); + + // /agents lists the session AND the pending setup key, never the token. + const agentsPre = await (await fetch(`${daemon.baseUrl}/agents`, { + headers: { Authorization: `Bearer ${daemon.token}` }, + })).json() as any; + expect(agentsPre.agents.some((a: any) => a.clientId === 'revoke-e2e' && !a.pending)).toBe(true); + expect(agentsPre.agents.some((a: any) => a.clientId === 'revoke-e2e' && a.pending)).toBe(true); + for (const a of agentsPre.agents) expect(a.token).toBeUndefined(); + + // Regression: pre-fix this deleted only the spent setup key and returned + // a false 200 while the session survived. Count covers session + spent + // key + pending key. + const del = await fetch(`${daemon.baseUrl}/token/revoke-e2e`, { + method: 'DELETE', + headers: { Authorization: `Bearer ${daemon.token}` }, + }); + expect(del.status).toBe(200); + const delBody = await del.json() as any; + expect(delBody.revoked).toBe('revoke-e2e'); + expect(delBody.tokens_deleted).toBe(3); + + // Assert per-clientId absence, NOT list-empty: this file shares one + // daemon and other tests' agents remain listed. + const agentsPost = await (await fetch(`${daemon.baseUrl}/agents`, { + headers: { Authorization: `Bearer ${daemon.token}` }, + })).json() as any; + expect(agentsPost.agents.some((a: any) => a.clientId === 'revoke-e2e')).toBe(false); + + const post = await fetch(`${daemon.baseUrl}/command`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${scopedToken}` }, + body: JSON.stringify({ command: 'status', args: [] }), + }); + expect(post.status).toBe(401); + + // The leftover unspent key is dead too (re-grant hole closed). + const reconnect = await fetch(`${daemon.baseUrl}/connect`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ setup_key: key2 }), + }); + expect(reconnect.status).toBe(401); + }); + + test('second DELETE /token for the same clientId returns 404, not a false 200', async () => { + // Regression: pre-fix, consecutive DELETEs both returned 200 — the first + // consumed the spent setup key, the second the session. Depends on the + // previous test having revoked 'revoke-e2e' (bun runs file tests in order). + const del = await fetch(`${daemon.baseUrl}/token/revoke-e2e`, { + method: 'DELETE', + headers: { Authorization: `Bearer ${daemon.token}` }, + }); + expect(del.status).toBe(404); + }); + + test('DELETE /token decodes percent-encoded clientIds', async () => { + const pairResp = await fetch(`${daemon.baseUrl}/pair`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${daemon.token}` }, + body: JSON.stringify({ clientId: 'space agent' }), + }); + const { setup_key } = await pairResp.json() as any; + await fetch(`${daemon.baseUrl}/connect`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ setup_key }), + }); + const del = await fetch(`${daemon.baseUrl}/token/${encodeURIComponent('space agent')}`, { + method: 'DELETE', + headers: { Authorization: `Bearer ${daemon.token}` }, + }); + expect(del.status).toBe(200); + const agents = await (await fetch(`${daemon.baseUrl}/agents`, { + headers: { Authorization: `Bearer ${daemon.token}` }, + })).json() as any; + expect(agents.agents.some((a: any) => a.clientId === 'space agent')).toBe(false); + }); + + test('DELETE /token with malformed percent-encoding returns 400', async () => { + const del = await fetch(`${daemon.baseUrl}/token/%E0%A4%A`, { + method: 'DELETE', + headers: { Authorization: `Bearer ${daemon.token}` }, + }); + expect(del.status).toBe(400); + }); + test('POST /command with no auth returns 401', async () => { const resp = await fetch(`${daemon.baseUrl}/command`, { method: 'POST', diff --git a/browse/test/token-registry.test.ts b/browse/test/token-registry.test.ts index 9df4f5d83..f68b6248b 100644 --- a/browse/test/token-registry.test.ts +++ b/browse/test/token-registry.test.ts @@ -366,6 +366,18 @@ describe('token-registry', () => { createSetupKey({}); // setup keys not listed expect(listTokens()).toHaveLength(2); }); + + it('includeSetup lists pending setup keys but hides spent ones', () => { + createToken({ clientId: 'sess' }); + createSetupKey({ clientId: 'pending' }); + const spent = createSetupKey({ clientId: 'spent' }); + exchangeSetupKey(spent.token); + expect(listTokens().map(t => t.clientId).sort()).toEqual(['sess', 'spent']); + const withSetup = listTokens({ includeSetup: true }); + // Pending key = a live grant the operator must see; the SPENT key is + // re-exchange bookkeeping for the already-listed session and stays hidden. + expect(withSetup.filter(t => t.type === 'setup').map(t => t.clientId)).toEqual(['pending']); + }); }); describe('serialization', () => { diff --git a/browse/test/tunnel-revoke-cli.test.ts b/browse/test/tunnel-revoke-cli.test.ts new file mode 100644 index 000000000..20cb3d33c --- /dev/null +++ b/browse/test/tunnel-revoke-cli.test.ts @@ -0,0 +1,262 @@ +/** + * Behavior tests for the `tunnel revoke` / `tunnel agents` CLI subcommands. + * + * Three harness shapes: + * 1. No/dead daemon — scratch BROWSE_STATE_FILE, no processes (the + * stop-dead-daemon.test.ts pattern): tunnel must exit 0 WITHOUT booting + * a daemon (#2254 — tokens are memory-only, a dead daemon has nothing + * to revoke). + * 2. Live daemon — real server subprocess with BROWSE_HEADLESS_SKIP=1 + * (the pair-agent-e2e.test.ts pattern): the full revoke + verify loop. + * 3. Stub daemon — a test-local Bun.serve behind a hand-written state file + * with an ALIVE pid (this test process). Pins the version-skew net (an + * OLD daemon with the first-match revoke bug returns 200 while /agents + * keeps listing the agent) and the unreachable-daemon branch. The pid + * decides the dead-daemon vs unreachable branch, so stubs MUST carry an + * alive pid. + */ + +import { describe, test, expect } from 'bun:test'; +import { spawn } from 'child_process'; +import * as fs from 'fs'; +import * as net from 'net'; +import * as os from 'os'; +import * as path from 'path'; + +const ROOT = path.resolve(import.meta.dir, '../..'); +const SERVER_ENTRY = path.join(ROOT, 'browse/src/server.ts'); + +function runCli(args: string[], env: Record, timeoutMs = 30_000): + Promise<{ code: number; stdout: string; stderr: string }> { + const cliPath = path.resolve(import.meta.dir, '../src/cli.ts'); + return new Promise((resolve) => { + const proc = spawn('bun', ['run', cliPath, ...args], { timeout: timeoutMs, env }); + let stdout = ''; let stderr = ''; + proc.stdout.on('data', (d) => stdout += d.toString()); + proc.stderr.on('data', (d) => stderr += d.toString()); + proc.on('close', (code) => resolve({ code: code ?? 1, stdout, stderr })); + }); +} + +function baseEnv(stateFile: string): Record { + const env: Record = {}; + for (const [k, v] of Object.entries(process.env)) { + if (v !== undefined) env[k] = v; + } + env.BROWSE_STATE_FILE = stateFile; + return env; +} + +/** Grab a port that is definitely closed (bind, read, release). */ +async function closedPort(): Promise { + return new Promise((resolve, reject) => { + const srv = net.createServer(); + srv.once('error', reject); + srv.listen(0, '127.0.0.1', () => { + const addr = srv.address(); + if (!addr || typeof addr === 'string') { reject(new Error('bad address')); return; } + const port = addr.port; + srv.close(() => resolve(port)); + }); + }); +} + +function writeStateFile(stateFile: string, pid: number, port: number): void { + fs.writeFileSync(stateFile, JSON.stringify({ + pid, + port, + token: 'fake-root-token', + startedAt: new Date().toISOString(), + serverPath: '', + mode: 'launched' as const, + }, null, 2)); +} + +describe('tunnel subcommand parsing', () => { + test('bare tunnel / unknown sub / empty name / extra args → usage, exit 1', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-tunnel-usage-')); + const stateFile = path.join(tmpDir, 'browse.json'); + try { + for (const args of [ + ['tunnel'], + ['tunnel', 'rotate'], + ['tunnel', 'revoke'], + ['tunnel', 'revoke', ''], + ['tunnel', 'revoke', 'a', 'b'], + ['tunnel', 'agents', 'extra'], + ]) { + const result = await runCli(args, baseEnv(stateFile)); + expect(result.code).toBe(1); + expect(result.stderr).toContain('usage: browse tunnel'); + } + // Arg errors must never boot a daemon. + expect(fs.existsSync(stateFile)).toBe(false); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, 60_000); +}); + +describe('tunnel against no daemon (#2254 — never boot one)', () => { + test('revoke → exit 0, "No daemon running", nothing spawned', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-tunnel-dead-')); + const stateFile = path.join(tmpDir, 'browse.json'); + try { + const result = await runCli(['tunnel', 'revoke', 'ghost'], baseEnv(stateFile)); + expect(result.code).toBe(0); + expect(result.stdout).toContain('No daemon running'); + // A spawned daemon would have written the state file. + expect(fs.existsSync(stateFile)).toBe(false); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, 30_000); + + test('agents → exit 0; stale state (dead pid + closed port) is NOT mutated — cleanup stays stop\'s job', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-tunnel-stale-')); + const stateFile = path.join(tmpDir, 'browse.json'); + try { + writeStateFile(stateFile, 2147483646, await closedPort()); + const before = fs.readFileSync(stateFile, 'utf-8'); + const result = await runCli(['tunnel', 'agents'], baseEnv(stateFile)); + expect(result.code).toBe(0); + expect(result.stdout).toContain('No daemon running'); + expect(fs.readFileSync(stateFile, 'utf-8')).toBe(before); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, 30_000); +}); + +describe('tunnel against a live daemon (HTTP only, no browser)', () => { + test('pair → connect → revoke: verified gone, token 401s; agents lists pending keys', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-tunnel-live-')); + const stateFile = path.join(tmpDir, 'browse.json'); + const port = 20000 + Math.floor(Math.random() * 20000); + const daemon = Bun.spawn(['bun', 'run', SERVER_ENTRY], { + cwd: ROOT, + env: { + ...process.env, + BROWSE_HEADLESS_SKIP: '1', + BROWSE_PORT: String(port), + BROWSE_STATE_FILE: stateFile, + BROWSE_PARENT_PID: '0', + BROWSE_IDLE_TIMEOUT: '600000', + }, + stdio: ['ignore', 'pipe', 'pipe'], + }); + const baseUrl = `http://127.0.0.1:${port}`; + try { + const deadline = Date.now() + 15_000; + let ready = false; + while (Date.now() < deadline && !ready) { + try { + const resp = await fetch(`${baseUrl}/health`, { signal: AbortSignal.timeout(1000) }); + ready = resp.ok; + } catch { /* not ready yet */ } + if (!ready) await new Promise(r => setTimeout(r, 200)); + } + expect(ready).toBe(true); + const rootToken = (JSON.parse(fs.readFileSync(stateFile, 'utf-8')) as { token: string }).token; + + // Pair + connect a session, plus a second pending setup key. + const pair = async () => { + const resp = await fetch(`${baseUrl}/pair`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${rootToken}` }, + body: JSON.stringify({ clientId: 'cli-agent' }), + }); + return (await resp.json() as { setup_key: string }).setup_key; + }; + const key1 = await pair(); + const connectResp = await fetch(`${baseUrl}/connect`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ setup_key: key1 }), + }); + const { token: scopedToken } = await connectResp.json() as { token: string }; + await pair(); // pending key + + // tunnel agents shows the session AND the pending key. + const list = await runCli(['tunnel', 'agents'], baseEnv(stateFile)); + expect(list.code).toBe(0); + expect(list.stdout).toContain('cli-agent'); + expect(list.stdout).toContain('(pending setup key)'); + + // Unknown name → truthful failure with the active list. + const miss = await runCli(['tunnel', 'revoke', 'nobody'], baseEnv(stateFile)); + expect(miss.code).toBe(1); + expect(miss.stderr).toContain('No paired agent named "nobody"'); + expect(miss.stderr).toContain('cli-agent'); + + // The real revoke: counted, verified, and the token actually dies. + const revoke = await runCli(['tunnel', 'revoke', 'cli-agent'], baseEnv(stateFile)); + expect(revoke.code).toBe(0); + expect(revoke.stdout).toContain('Revoked "cli-agent" (3 tokens)'); + expect(revoke.stdout).toContain('Verified: not in the active agent list.'); + const post = await fetch(`${baseUrl}/command`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${scopedToken}` }, + body: JSON.stringify({ command: 'status', args: [] }), + }); + expect(post.status).toBe(401); + + const empty = await runCli(['tunnel', 'agents'], baseEnv(stateFile)); + expect(empty.code).toBe(0); + expect(empty.stdout).toContain('No paired agents.'); + } finally { + try { daemon.kill('SIGKILL'); } catch { /* already gone */ } + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, 60_000); +}); + +describe('tunnel against a lying or unreachable daemon (stub harness)', () => { + test('old daemon 200s the DELETE but keeps listing the agent → "Revocation incomplete", exit 1', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-tunnel-skew-')); + const stateFile = path.join(tmpDir, 'browse.json'); + // Old daemons answer {revoked} with no tokens_deleted — this also pins + // the "(count unknown)" print (never undefined/NaN). + const stub = Bun.serve({ + hostname: '127.0.0.1', + port: 0, + fetch(req) { + const url = new URL(req.url); + if (req.method === 'DELETE' && url.pathname.startsWith('/token/')) { + return Response.json({ revoked: 'mallory' }); + } + if (url.pathname === '/agents') { + return Response.json({ + agents: [{ clientId: 'mallory', scopes: ['read'], expiresAt: null, commandCount: 1, createdAt: '' }], + }); + } + return Response.json({ status: 'healthy' }); + }, + }); + try { + writeStateFile(stateFile, process.pid, stub.port); + const result = await runCli(['tunnel', 'revoke', 'mallory'], baseEnv(stateFile)); + expect(result.code).toBe(1); + expect(result.stdout).toContain('count unknown'); + expect(result.stderr).toContain('Revocation incomplete: "mallory" is still listed'); + } finally { + stub.stop(true); + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, 30_000); + + test('alive pid but unreachable port → "Could not reach daemon", exit 1 (NOT "no daemon")', async () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-tunnel-unreach-')); + const stateFile = path.join(tmpDir, 'browse.json'); + try { + // Alive pid (this test process) is what routes to the fetch-failure + // branch; a dead pid + dead port would be the exit-0 "no daemon" path. + writeStateFile(stateFile, process.pid, await closedPort()); + const result = await runCli(['tunnel', 'revoke', 'anyone'], baseEnv(stateFile)); + expect(result.code).toBe(1); + expect(result.stderr).toContain('Could not reach daemon'); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, 30_000); +});