mirror of
https://github.com/garrytan/gstack.git
synced 2026-09-13 08:29:04 +02:00
feat(browse): tunnel revoke/agents CLI with post-revoke verification
`$B tunnel revoke <name>` was documented in the instruction block, pair-agent/SKILL.md, and REMOTE_BROWSER_ACCESS.md but implemented nowhere: the CLI forwarded it to the daemon as Unknown command 'tunnel', and nothing in the repo called DELETE /token/:clientId or GET /agents. New pre-server short-circuit (#2254 pattern: tokens are memory-only, never boot a daemon to revoke against it). `tunnel revoke <name>` DELETEs the token, prints the deleted count ("(count unknown)" for old daemons that answer {revoked} without tokens_deleted), then RE-READS GET /agents to prove the agent is gone. The still-listed branch is the version-skew net: a new CLI against a still-running old daemon with the first-match revoke bug exits 1 and says to re-run (each old-daemon call deletes the next match) or stop. An alive pid with an unreachable port reports "Could not reach daemon" (exit 1), never a false "no daemon". `tunnel agents` lists sessions plus pending (unexchanged) setup keys, which GET /agents now exposes via listTokens({includeSetup}) — without them the revocation view was blind to a paired-but-never-connected agent. Setup-key tokens never leave the server. DELETE /token/ now decodeURIComponents the clientId (400 on malformed encoding) so CLI-encoded names round-trip. Tests: subprocess CLI coverage (usage paths, no-daemon exit 0 without spawning, live pair/connect/revoke loop, pending-key listing), stub-daemon pins for the skew and unreachable branches, and e2e pins for revoke-all semantics, percent-encoded ids, and the second-DELETE-is-404 regression. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
b9eb108f16
commit
f28bfd0158
@@ -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<ServerState | null> {
|
||||
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<Array<{ clientId: string; scopes: string[]; domains?: string[]; expiresAt: string | null; commandCount: number; pending?: boolean }> | 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<number> {
|
||||
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<number> {
|
||||
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<never> {
|
||||
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 <revoke <agent-name> | agents>');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
async function handlePairAgent(state: ServerState, args: string[]): Promise<void> {
|
||||
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 <id> | newtab [url] | closetab [id]
|
||||
Server: status | cookie <n>=<v> | header <n>:<v>
|
||||
useragent <str> | stop | restart
|
||||
tunnel revoke <name> | 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();
|
||||
|
||||
+14
-2
@@ -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' },
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user