mirror of
https://github.com/garrytan/gstack.git
synced 2026-09-02 03:10:59 +02:00
v1.68.2.0 fix: tunnel revoke exists and revokes everything — setup keys included, verified live (#2646)
* fix(browse): revokeToken deletes ALL tokens for a clientId, not the first Map hit
revokeToken deleted the first Map entry matching the clientId and returned
true. After a normal pairing, two entries share one clientId: the spent setup
key (kept by exchangeSetupKey for idempotent re-exchange) and the session
token, in that insertion order. Revoke ate the setup key, reported success,
and the live session survived: DELETE /token/<id> returned a false 200 while
/agents kept listing the agent. Worse, an unspent setup key created after the
session survived revoke, so a "revoked" agent could POST /connect and mint a
fresh session within the key's 5-minute validity window.
revokeToken now deletes every matching entry and returns the delete count
(truthy-compatible with the old boolean). The DELETE /token handler logs
"Revoked N token(s)" and returns tokens_deleted so the multi-token class
stays visible; revokeSkillToken wraps Boolean() to keep its documented
contract. Regression tests pin shapes a (spent-key shadowing), b (re-grant
hole), c (multiple pending keys), and bystander isolation.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* 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>
* fix(browse): CLI always sends explicit pair scopes via shared DEFAULT_PAIR_SCOPES
The effective pairing default lived in two places: the CLI omitted scopes
unless --restrict was passed, and the server filled in its own literal.
handlePairAgent now always sends an explicit scopes list and both sides
reference one exported constant, DEFAULT_PAIR_SCOPES, so the default cannot
silently drift again (pinned by a server-auth source tripwire).
Three input traps closed in the same surface:
- Bare --restrict (or --restrict swallowing the next flag) parsed as "no
restriction" and silently granted FULL access, the opposite of the user's
intent. validatePairAgentFlags rejects it pre-server, before any consent
gate, so an arg error never boots a daemon.
- A scopes list could smuggle the control scope past the explicit flag:
--restrict "read,control" minted a control-scoped session with no
--control. /pair now 400s on control in a scopes list without the control
flag, and the CLI points the user at --control.
- Option typos validated only at exchange time: createSetupKey stored any
scope string and any rateLimit, so /pair returned 200 with a poisoned
setup key whose failure surfaced to the REMOTE agent at /connect as a
misleading "Invalid request body". Shared validation now runs in both
creators and throws typed InvalidScopeError; /pair and /token 400 with the
message, naming the bad scope or negative rateLimit. Also
`opts.rateLimit || 10` became `?? 10` so the documented "0 = unlimited"
survives the /pair path.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(browse): 403 hint stops recommending --admin; invariant names both scope defaults
The scope-denied hint told restricted agents to "re-pair with --admin for
eval/cookies/storage" — but --admin is a legacy alias for --control, so
following it over-granted browser-wide destructive commands on top of the
admin scope the default already carries. The hint now matches the CLI's
sibling wording: re-pair without --restrict for page access, --control for
browser control.
Registry invariant #2 claimed "admin scope denied by default" three releases
after b73f3644 deliberately made /pair grant admin. It now names BOTH
defaults precisely (registry API functions default read+write; the /pair
ceremony grants DEFAULT_PAIR_SCOPES) so the header cannot lie one layer down.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs(pair-agent): document the full-access default, --restrict, and real revocation
The pairing docs still described the pre-b73f3644 model: read+write default,
--admin as the opt-in for JS/cookies/storage. Reality for three releases:
/pair grants read+write+admin+meta (the pairing ceremony is the trust
boundary) and --admin is a legacy alias for --control. A user following the
skill believed they granted a sandboxed session and actually granted JS
execution on their logged-in browser.
pair-agent/SKILL.md.tmpl (SKILL.md regenerated in this commit) now states
the real default, the tunnel-allowlist nuance (eval works remotely; the
js/cookies/storage commands are local-only), --restrict for sandboxed
sessions with an untrusted-content advisory (scope caps prompt-injection
blast radius), and --control for browser-wide ops. "Revoking access"
documents the now-real tunnel revoke (deletes session + pending setup keys,
verifies against the agent list) and tunnel agents, and replaces the
never-implemented `tunnel rotate` with `$B stop` — tokens are memory-only,
so a daemon restart already rotates everything.
REMOTE_BROWSER_ACCESS.md: /connect example shows the real default scopes,
the scope table gains the control row, the 403 hint row matches the new
server wording, and the false claim that /sidebar-chat is on the tunnel
allowlist is gone (TUNNEL_PATHS is /connect + /command; /sidebar-chat no
longer exists in server.ts at all). ARCHITECTURE.md drops the same phantom
endpoint from the allowlist prose and endpoint table.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* v1.68.2.0: revoke-all, real tunnel revoke, truthful pairing docs
Version slot allocated against the live remote via bin/gstack-next-version
(clean patch bump from 1.68.1.0, no collision). CHANGELOG entry covers the
revoke-all fix, the new tunnel revoke/agents CLI, the explicit-scopes wire
contract, and the pairing-docs truth pass.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* fix(browse): adversarial-review hardening — 6 findings fixed, regression-pinned
Pre-push adversarial review (4 lenses, refute-style verification: 13 raw
findings, 7 refuted, 6 confirmed) caught these; each fix carries a pin:
1. --restrict=read (equals form) sailed past validatePairAgentFlags —
hasFlag/parseFlag are exact-token matches — so the user asked for a
read-only sandbox and silently got FULL access: the exact failure mode
this branch claims to close. The equals form is now a hard error before
any server work.
2. handleTunnel trimmed the agent name but clientIds are stored verbatim,
so a space-padded agent was unrevocable by the documented kill switch
(trimmed DELETE 404'd while the grant stayed live). Names now pass
through verbatim; the live-daemon test revokes ' padded'.
3. The sole pin for "CLI always sends explicit scopes" passed vacuously on
a simulated revert: toContain('DEFAULT_PAIR_SCOPES') was satisfied by a
comment. The tripwire now matches the code shape with a regex and bans
the conditional spread formatting-insensitively.
4. The rewritten 403 scope hint was unpinned — new e2e asserts it names
--restrict and --control and never --admin.
5. tunnelRevoke's verify-failure and HTTP-error branches and tunnelAgents'
unreadable-list branch had no coverage — three stub-daemon pins added
(an unreadable list must never render as "No paired agents").
6. CHANGELOG claimed "40+ new test cases"; the honest count is 35.
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
---------
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5
parent
9da6692930
commit
51932eceef
+180
-2
@@ -18,6 +18,9 @@ import { resolveConfig, ensureStateDir, readVersionHash, isPairAgentEnabled } fr
|
||||
import { parseProxyConfig, computeConfigHash, ProxyConfigError } from './proxy-config';
|
||||
import { redactProxyUrl } from './proxy-redact';
|
||||
import { spawnTerminalAgent } from './terminal-agent-control';
|
||||
// Zero side effects on import (documented invariant in token-registry.ts) —
|
||||
// safe to pull the shared pairing default into the CLI.
|
||||
import { DEFAULT_PAIR_SCOPES } from './token-registry';
|
||||
|
||||
const config = resolveConfig();
|
||||
const IS_WINDOWS = process.platform === 'win32';
|
||||
@@ -1101,6 +1104,164 @@ 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;
|
||||
}
|
||||
|
||||
/** Reject pair-agent scope-flag misuse BEFORE any consent or server work.
|
||||
* Bare `--restrict` (or a flag-shaped value from a forgotten argument) used
|
||||
* to parse as "no restriction" and silently grant FULL access — the exact
|
||||
* opposite of the user's intent. And `control` never rides in via --restrict:
|
||||
* browser-wide destructive ops stay behind the explicit --control flag. */
|
||||
function validatePairAgentFlags(args: string[]): void {
|
||||
// hasFlag/parseFlag are exact-token matches, so `--restrict=read` would
|
||||
// sail past every check below and silently grant FULL access.
|
||||
if (args.some(a => a.startsWith('--restrict='))) {
|
||||
console.error('[browse] --restrict takes a space-separated value: --restrict read or --restrict "read,write". The --restrict=... form is not supported.');
|
||||
process.exit(1);
|
||||
}
|
||||
if (!hasFlag(args, '--restrict')) return;
|
||||
const restrict = parseFlag(args, '--restrict');
|
||||
if (!restrict || !restrict.trim() || restrict.startsWith('--')) {
|
||||
console.error('[browse] --restrict needs a scope list, e.g. --restrict read or --restrict "read,write". Bare --restrict would silently grant FULL access.');
|
||||
process.exit(1);
|
||||
}
|
||||
if (hasFlag(args, '--control') || hasFlag(args, '--admin')) {
|
||||
// Server-side, the control flag wins and the scopes list is ignored.
|
||||
console.warn('[browse] --restrict is ignored when --control/--admin is set (control implies full access).');
|
||||
return;
|
||||
}
|
||||
if (restrict.split(',').map(s => s.trim()).includes('control')) {
|
||||
console.error('[browse] The control scope is not granted via --restrict. Re-run with --control.');
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleTunnel(args: string[]): Promise<never> {
|
||||
const sub = args[0];
|
||||
// The name passes through VERBATIM: clientIds are stored untrimmed, so a
|
||||
// space-padded name must stay revocable (encodeURIComponent handles it).
|
||||
if (sub === 'revoke' && args.length === 2 && args[1]) {
|
||||
process.exit(await tunnelRevoke(args[1]));
|
||||
}
|
||||
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());
|
||||
@@ -1109,8 +1270,12 @@ async function handlePairAgent(state: ServerState, args: string[]): Promise<void
|
||||
const localHost = parseFlag(args, '--local');
|
||||
|
||||
// Call POST /pair to create a setup key
|
||||
// Default: full access (read+write+admin+meta). --control adds browser-wide ops.
|
||||
// Default: DEFAULT_PAIR_SCOPES (full page access). --control adds browser-wide ops.
|
||||
// --restrict limits: --restrict read (read-only), --restrict "read,write" (no admin)
|
||||
// Scopes are ALWAYS sent explicitly so the effective default lives in one
|
||||
// place (token-registry) instead of drifting between CLI omission and
|
||||
// server fallback. Flag misuse was rejected pre-server by
|
||||
// validatePairAgentFlags.
|
||||
const pairResp = await fetch(`http://127.0.0.1:${state.port}/pair`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -1121,7 +1286,9 @@ async function handlePairAgent(state: ServerState, args: string[]): Promise<void
|
||||
domains,
|
||||
clientId: clientName,
|
||||
control,
|
||||
...(restrict ? { scopes: restrict.split(',').map(s => s.trim()) } : {}),
|
||||
scopes: restrict
|
||||
? restrict.split(',').map(s => s.trim())
|
||||
: [...DEFAULT_PAIR_SCOPES],
|
||||
}),
|
||||
signal: AbortSignal.timeout(5000),
|
||||
});
|
||||
@@ -1303,6 +1470,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 +1809,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();
|
||||
@@ -1656,6 +1831,9 @@ Refs: After 'snapshot', use @e1, @e2... as selectors:
|
||||
// state, so replacing it kills nothing the user had.
|
||||
let pairAgentPreexistingDaemonAlive = false;
|
||||
if (command === 'pair-agent') {
|
||||
// Scope-flag misuse is rejected before consent gates and ensureServer —
|
||||
// an arg error must never boot a daemon.
|
||||
validatePairAgentFlags(commandArgs);
|
||||
const preState = readState();
|
||||
pairAgentPreexistingDaemonAlive = Boolean(preState?.pid && isProcessAlive(preState.pid));
|
||||
}
|
||||
|
||||
+48
-13
@@ -31,7 +31,8 @@ import {
|
||||
initRegistry, validateToken as validateScopedToken, checkScope, checkDomain,
|
||||
checkRate, createToken, createSetupKey, exchangeSetupKey, revokeToken,
|
||||
listTokens, recordCommand,
|
||||
isRootToken, checkConnectRateLimit, type TokenInfo,
|
||||
isRootToken, checkConnectRateLimit, type TokenInfo, type ScopeCategory,
|
||||
DEFAULT_PAIR_SCOPES, InvalidScopeError,
|
||||
} from './token-registry';
|
||||
import { validateTempPath } from './path-security';
|
||||
import { resolveConfig, ensureStateDir, readVersionHash, resolveChromiumProfile, cleanSingletonLocks, isPairAgentEnabled } from './config';
|
||||
@@ -999,7 +1000,7 @@ async function handleCommandInternalImpl(
|
||||
status: 403, json: true,
|
||||
result: JSON.stringify({
|
||||
error: `Command "${command}" not allowed by your token scope`,
|
||||
hint: `Your scopes: ${tokenInfo.scopes.join(', ')}. Ask the user to re-pair with --admin for eval/cookies/storage access.`,
|
||||
hint: `Your scopes: ${tokenInfo.scopes.join(', ')}. Ask the user to re-pair without --restrict for full page access, or with --control for browser control commands.`,
|
||||
}),
|
||||
};
|
||||
}
|
||||
@@ -2316,7 +2317,14 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {
|
||||
scopes: session.scopes,
|
||||
agent: session.clientId,
|
||||
}), { status: 200, headers: { 'Content-Type': 'application/json' } });
|
||||
} catch {
|
||||
} catch (err) {
|
||||
// Name the caller's typo (bad scope, negative rateLimit) instead of
|
||||
// hiding it behind the generic body error.
|
||||
if (err instanceof InvalidScopeError) {
|
||||
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' },
|
||||
});
|
||||
@@ -2330,15 +2338,23 @@ 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` }), {
|
||||
status: 404, headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
console.log(`[browse] Revoked token for: ${clientId}`);
|
||||
return new Response(JSON.stringify({ revoked: clientId }), {
|
||||
console.log(`[browse] Revoked ${revoked} token(s) for: ${clientId}`);
|
||||
return new Response(JSON.stringify({ revoked: clientId, tokens_deleted: revoked }), {
|
||||
status: 200, headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
}
|
||||
@@ -2350,13 +2366,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' },
|
||||
@@ -2372,12 +2392,20 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {
|
||||
}
|
||||
try {
|
||||
const pairBody = await req.json() as any;
|
||||
// Default: full access (read+write+admin+meta). The trust boundary is
|
||||
// the pairing ceremony itself, not the scope. --control adds browser-wide
|
||||
// destructive commands (stop, restart, disconnect). --restrict limits scope.
|
||||
// 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
|
||||
? ['read', 'write', 'admin', 'meta', 'control'] as const
|
||||
: (pairBody.scopes || ['read', 'write', 'admin', 'meta']) as const;
|
||||
? [...DEFAULT_PAIR_SCOPES, 'control' as const]
|
||||
: ((pairBody.scopes || [...DEFAULT_PAIR_SCOPES]) as ScopeCategory[]);
|
||||
const setupKey = createSetupKey({
|
||||
clientId: pairBody.clientId,
|
||||
scopes: [...scopes],
|
||||
@@ -2413,7 +2441,14 @@ export function buildFetchHandler(cfg: ServerConfig): ServerHandle {
|
||||
tunnel_url: verifiedTunnelUrl,
|
||||
server_url: `http://127.0.0.1:${browsePort}`,
|
||||
}), { status: 200, headers: { 'Content-Type': 'application/json' } });
|
||||
} catch {
|
||||
} catch (err) {
|
||||
// Name the caller's typo (bad scope, negative rateLimit) instead of
|
||||
// hiding it behind the generic body error.
|
||||
if (err instanceof InvalidScopeError) {
|
||||
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' },
|
||||
});
|
||||
|
||||
@@ -87,5 +87,5 @@ export function mintSkillToken(opts: MintSkillTokenOptions): TokenInfo {
|
||||
* token returns false but is not an error.
|
||||
*/
|
||||
export function revokeSkillToken(skillName: string, spawnId: string): boolean {
|
||||
return revokeToken(skillClientId(skillName, spawnId));
|
||||
return Boolean(revokeToken(skillClientId(skillName, spawnId)));
|
||||
}
|
||||
|
||||
@@ -19,7 +19,12 @@
|
||||
*
|
||||
* Security invariants:
|
||||
* 1. Only root token can mint sub-tokens (POST /token, POST /connect)
|
||||
* 2. admin scope denied by default — must be explicitly granted
|
||||
* 2. control scope denied by default — must be explicitly flagged.
|
||||
* Registry API defaults (createToken/createSetupKey with no scopes)
|
||||
* stay ['read','write']; the /pair ceremony explicitly grants
|
||||
* DEFAULT_PAIR_SCOPES (read+write+admin+meta — the pairing ceremony
|
||||
* is the trust boundary; --restrict narrows, --control must be
|
||||
* explicit and never rides in via a scopes list)
|
||||
* 3. chain command scope-checks each subcommand individually
|
||||
* 4. Root token never in connection strings or pasted instructions
|
||||
*
|
||||
@@ -82,6 +87,35 @@ const SCOPE_MAP: Record<ScopeCategory, Set<string>> = {
|
||||
meta: SCOPE_META,
|
||||
};
|
||||
|
||||
/**
|
||||
* Scopes granted by POST /pair when nothing narrower is requested.
|
||||
* Deliberately full page access (b73f3644 / #907): the trust boundary is the
|
||||
* pairing ceremony, not the scope. 'control' (browser-wide destructive ops)
|
||||
* is the only scope that stays opt-in via the control flag. Referenced by
|
||||
* BOTH server.ts (/pair default) and cli.ts (explicit send) so the two
|
||||
* defaults cannot silently drift apart again.
|
||||
*/
|
||||
export const DEFAULT_PAIR_SCOPES: readonly ScopeCategory[] = ['read', 'write', 'admin', 'meta'];
|
||||
|
||||
/**
|
||||
* Typed error for caller-supplied token options (unknown scope, negative
|
||||
* rateLimit). HTTP handlers catch it to 400 with the message at the endpoint
|
||||
* where the typo happened — pre-fix, a bad scope sailed through /pair into a
|
||||
* poisoned setup key and surfaced as a misleading "Invalid request body" to
|
||||
* the remote agent at /connect.
|
||||
*/
|
||||
export class InvalidScopeError extends Error {}
|
||||
|
||||
function assertValidTokenOptions(scopes: readonly string[], rateLimit: number): void {
|
||||
const validScopes: ScopeCategory[] = ['read', 'write', 'admin', 'meta', 'control'];
|
||||
for (const s of scopes) {
|
||||
if (!validScopes.includes(s as ScopeCategory)) {
|
||||
throw new InvalidScopeError(`Invalid scope: ${s}. Valid: ${validScopes.join(', ')}`);
|
||||
}
|
||||
}
|
||||
if (rateLimit < 0) throw new InvalidScopeError('rateLimit must be >= 0');
|
||||
}
|
||||
|
||||
// ─── Types ──────────────────────────────────────────────────────
|
||||
|
||||
export interface TokenInfo {
|
||||
@@ -200,13 +234,7 @@ export function createToken(opts: CreateTokenOptions): TokenInfo {
|
||||
} = opts;
|
||||
|
||||
// Validate inputs
|
||||
const validScopes: ScopeCategory[] = ['read', 'write', 'admin', 'meta', 'control'];
|
||||
for (const s of scopes) {
|
||||
if (!validScopes.includes(s as ScopeCategory)) {
|
||||
throw new Error(`Invalid scope: ${s}. Valid: ${validScopes.join(', ')}`);
|
||||
}
|
||||
}
|
||||
if (rateLimit < 0) throw new Error('rateLimit must be >= 0');
|
||||
assertValidTokenOptions(scopes, rateLimit);
|
||||
if (expiresSeconds !== null && expiresSeconds !== undefined && expiresSeconds < 0) {
|
||||
throw new Error('expiresSeconds must be >= 0 or null');
|
||||
}
|
||||
@@ -248,6 +276,13 @@ export function createToken(opts: CreateTokenOptions): TokenInfo {
|
||||
* Setup keys expire in 5 minutes and can only be exchanged once.
|
||||
*/
|
||||
export function createSetupKey(opts: Omit<CreateTokenOptions, 'clientId'> & { clientId?: string }): TokenInfo {
|
||||
const scopes = opts.scopes || ['read', 'write'];
|
||||
// ?? not ||: rateLimit 0 is documented as "unlimited" and must survive.
|
||||
const rateLimit = opts.rateLimit ?? 10;
|
||||
// Validate HERE, not only at exchange time in createToken — otherwise a
|
||||
// typo mints a poisoned setup key whose failure surfaces to the wrong
|
||||
// party (the remote agent, at /connect, as "Invalid request body").
|
||||
assertValidTokenOptions(scopes, rateLimit);
|
||||
const token = generateToken('gsk_setup_');
|
||||
const now = new Date();
|
||||
const expiresAt = new Date(now.getTime() + 5 * 60 * 1000).toISOString(); // 5 min
|
||||
@@ -256,10 +291,10 @@ export function createSetupKey(opts: Omit<CreateTokenOptions, 'clientId'> & { cl
|
||||
token,
|
||||
clientId: opts.clientId || `remote-${Date.now()}`,
|
||||
type: 'setup',
|
||||
scopes: opts.scopes || ['read', 'write'],
|
||||
scopes,
|
||||
domains: opts.domains,
|
||||
tabPolicy: opts.tabPolicy || 'own-only',
|
||||
rateLimit: opts.rateLimit || 10,
|
||||
rateLimit,
|
||||
expiresAt,
|
||||
createdAt: now.toISOString(),
|
||||
usesRemaining: 1,
|
||||
@@ -417,17 +452,23 @@ export function recordCommand(token: string): void {
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke a token by client ID. Returns true if found and revoked.
|
||||
* Revoke ALL tokens for a client ID — the session token and every setup key,
|
||||
* spent or unspent. Deleting only the first match left two holes: a spent
|
||||
* setup key (kept for idempotent re-exchange) shadowed the session token, so
|
||||
* revoke reported success while the live session survived; and an unspent
|
||||
* setup key surviving revoke let a "revoked" agent POST /connect into a
|
||||
* fresh session. Returns the number of tokens deleted (0 = nothing found).
|
||||
*/
|
||||
export function revokeToken(clientId: string): boolean {
|
||||
export function revokeToken(clientId: string): number {
|
||||
let deleted = 0;
|
||||
for (const [token, info] of tokens) {
|
||||
if (info.clientId === clientId) {
|
||||
tokens.delete(token);
|
||||
rateBuckets.delete(clientId);
|
||||
return true;
|
||||
tokens.delete(token); // Map tolerates delete during for...of iteration
|
||||
deleted++;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
if (deleted > 0) rateBuckets.delete(clientId);
|
||||
return deleted;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -443,8 +484,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[] = [];
|
||||
|
||||
@@ -455,6 +500,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