mirror of
https://github.com/garrytan/gstack.git
synced 2026-08-29 09:20:39 +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
@@ -194,6 +194,217 @@ describe('pair-agent flow end-to-end (HTTP only, no ngrok)', () => {
|
||||
expect(Array.isArray(scopes)).toBe(true);
|
||||
});
|
||||
|
||||
// ─── Pair scope contract: defaults, explicit lists, typo naming ───────
|
||||
|
||||
test('default /connect scopes are exactly read,write,admin,meta', async () => {
|
||||
const pairResp = await fetch(`${daemon.baseUrl}/pair`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${daemon.token}` },
|
||||
body: JSON.stringify({ clientId: 'default-scopes' }),
|
||||
});
|
||||
const { setup_key, scopes: pairScopes } = await pairResp.json() as any;
|
||||
expect(pairScopes).toEqual(['read', 'write', 'admin', 'meta']);
|
||||
const connectResp = await fetch(`${daemon.baseUrl}/connect`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ setup_key }),
|
||||
});
|
||||
const { scopes } = await connectResp.json() as any;
|
||||
expect(scopes).toEqual(['read', 'write', 'admin', 'meta']);
|
||||
});
|
||||
|
||||
test('explicit scopes are honored end-to-end (the --restrict wire contract)', async () => {
|
||||
const pairResp = await fetch(`${daemon.baseUrl}/pair`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${daemon.token}` },
|
||||
body: JSON.stringify({ clientId: 'restricted-scopes', scopes: ['read'] }),
|
||||
});
|
||||
const { setup_key } = await pairResp.json() as any;
|
||||
const connectResp = await fetch(`${daemon.baseUrl}/connect`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ setup_key }),
|
||||
});
|
||||
const { scopes } = await connectResp.json() as any;
|
||||
expect(scopes).toEqual(['read']);
|
||||
});
|
||||
|
||||
test('POST /pair with a scope typo fails fast, naming the scope', async () => {
|
||||
// Regression: pre-fix this returned 200 with a poisoned setup key whose
|
||||
// failure surfaced at /connect as a misleading "Invalid request body".
|
||||
const resp = await fetch(`${daemon.baseUrl}/pair`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${daemon.token}` },
|
||||
body: JSON.stringify({ clientId: 'typo-agent', scopes: ['raed'] }),
|
||||
});
|
||||
expect(resp.status).toBe(400);
|
||||
const body = await resp.json() as any;
|
||||
expect(body.error).toContain('Invalid scope: raed');
|
||||
});
|
||||
|
||||
test('POST /token with a scope typo names the scope too', async () => {
|
||||
const resp = await fetch(`${daemon.baseUrl}/token`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${daemon.token}` },
|
||||
body: JSON.stringify({ clientId: 'typo-token', scopes: ['wirte'] }),
|
||||
});
|
||||
expect(resp.status).toBe(400);
|
||||
const body = await resp.json() as any;
|
||||
expect(body.error).toContain('Invalid scope: wirte');
|
||||
});
|
||||
|
||||
test('control cannot ride in through a /pair scopes list without the control flag', async () => {
|
||||
const resp = await fetch(`${daemon.baseUrl}/pair`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${daemon.token}` },
|
||||
body: JSON.stringify({ clientId: 'sneaky', scopes: ['read', 'control'] }),
|
||||
});
|
||||
expect(resp.status).toBe(400);
|
||||
const body = await resp.json() as any;
|
||||
expect(body.error).toContain('control');
|
||||
});
|
||||
|
||||
test('scope-denied 403 hint points at --restrict/--control, never --admin', async () => {
|
||||
// Regression: the old hint said "re-pair with --admin", which is a legacy
|
||||
// alias for --control — following it over-granted browser-wide control.
|
||||
const pairResp = await fetch(`${daemon.baseUrl}/pair`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${daemon.token}` },
|
||||
body: JSON.stringify({ clientId: 'hint-agent', scopes: ['read'] }),
|
||||
});
|
||||
const { setup_key } = await pairResp.json() as any;
|
||||
const connectResp = await fetch(`${daemon.baseUrl}/connect`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ setup_key }),
|
||||
});
|
||||
const { token } = await connectResp.json() as any;
|
||||
const resp = await fetch(`${daemon.baseUrl}/command`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify({ command: 'goto', args: ['https://example.com'] }),
|
||||
});
|
||||
expect(resp.status).toBe(403);
|
||||
const body = await resp.json() as any;
|
||||
expect(body.hint).toContain('--restrict');
|
||||
expect(body.hint).toContain('--control');
|
||||
expect(body.hint).not.toContain('--admin');
|
||||
});
|
||||
|
||||
// ─── 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',
|
||||
|
||||
@@ -409,3 +409,34 @@ describe('Server auth security', () => {
|
||||
expect(routeSrc).toContain('SameSite=Strict');
|
||||
});
|
||||
});
|
||||
|
||||
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
|
||||
// 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');
|
||||
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.
|
||||
expect(cliBlock).toMatch(/scopes:\s*restrict\s*\?[\s\S]{0,200}?:\s*\[\.\.\.DEFAULT_PAIR_SCOPES\]/);
|
||||
expect(cliBlock).not.toMatch(/\.\.\.\(restrict\s*\?/);
|
||||
});
|
||||
|
||||
// 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')");
|
||||
});
|
||||
|
||||
// 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');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
revokeToken, rotateRoot, listTokens, recordCommand,
|
||||
serializeRegistry, restoreRegistry, checkConnectRateLimit,
|
||||
SCOPE_READ, SCOPE_WRITE, SCOPE_ADMIN, SCOPE_CONTROL, SCOPE_META,
|
||||
DEFAULT_PAIR_SCOPES, InvalidScopeError,
|
||||
__resetRegistry,
|
||||
} from '../src/token-registry';
|
||||
|
||||
@@ -298,12 +299,81 @@ describe('token-registry', () => {
|
||||
describe('revokeToken', () => {
|
||||
it('revokes existing token', () => {
|
||||
const info = createToken({ clientId: 'to-revoke' });
|
||||
expect(revokeToken('to-revoke')).toBe(true);
|
||||
// revokeToken returns the delete count, not a boolean (truthy for callers)
|
||||
expect(revokeToken('to-revoke')).toBe(1);
|
||||
expect(validateToken(info.token)).toBeNull();
|
||||
});
|
||||
|
||||
it('returns false for non-existent client', () => {
|
||||
expect(revokeToken('no-such-client')).toBe(false);
|
||||
it('returns 0 for non-existent client', () => {
|
||||
expect(revokeToken('no-such-client')).toBe(0);
|
||||
});
|
||||
|
||||
// Regression: revokeToken deleted only the FIRST matching Map entry. The
|
||||
// spent setup key (kept for idempotent re-exchange) is inserted before the
|
||||
// session token, so it shadowed the session: revoke reported success while
|
||||
// the live session survived and DELETE /token returned a false 200.
|
||||
it('revokes the session even when a spent setup key precedes it (shape a)', () => {
|
||||
const setup = createSetupKey({ clientId: 'shadowed' });
|
||||
const session = exchangeSetupKey(setup.token)!;
|
||||
expect(revokeToken('shadowed')).toBe(2);
|
||||
expect(validateToken(session.token)).toBeNull();
|
||||
expect(exchangeSetupKey(setup.token)).toBeNull();
|
||||
});
|
||||
|
||||
// Regression: an UNSPENT setup key created after the session survived the
|
||||
// old first-match revoke, so a "revoked" agent could POST /connect and
|
||||
// mint a brand-new session within the key's 5-minute validity window.
|
||||
it('closes the re-grant hole: unspent setup key dies with the revoke (shape b)', () => {
|
||||
const first = createSetupKey({ clientId: 'regrant' });
|
||||
exchangeSetupKey(first.token);
|
||||
const second = createSetupKey({ clientId: 'regrant' });
|
||||
expect(revokeToken('regrant')).toBe(3);
|
||||
expect(exchangeSetupKey(second.token)).toBeNull();
|
||||
expect(listTokens().filter(t => t.clientId === 'regrant')).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('revokes multiple pending setup keys for one clientId in a single call (shape c)', () => {
|
||||
const keys = [1, 2, 3].map(() => createSetupKey({ clientId: 'multi' }));
|
||||
expect(revokeToken('multi')).toBe(3);
|
||||
for (const k of keys) expect(exchangeSetupKey(k.token)).toBeNull();
|
||||
expect(revokeToken('multi')).toBe(0); // idempotent: second call finds nothing
|
||||
});
|
||||
|
||||
it('does not touch other clients\' tokens', () => {
|
||||
const bystander = createToken({ clientId: 'bystander' });
|
||||
createSetupKey({ clientId: 'target' });
|
||||
createToken({ clientId: 'target' });
|
||||
expect(revokeToken('target')).toBe(2);
|
||||
expect(validateToken(bystander.token)).not.toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('pair defaults and option validation', () => {
|
||||
it('DEFAULT_PAIR_SCOPES is exactly read,write,admin,meta (b73f3644: the ceremony is the trust boundary)', () => {
|
||||
expect([...DEFAULT_PAIR_SCOPES]).toEqual(['read', 'write', 'admin', 'meta']);
|
||||
});
|
||||
|
||||
// Regression: only createToken validated options, so a scope typo minted
|
||||
// a poisoned setup key at /pair and surfaced to the REMOTE agent at
|
||||
// /connect as a misleading "Invalid request body".
|
||||
it('createSetupKey rejects an unknown scope with InvalidScopeError naming it', () => {
|
||||
expect(() => createSetupKey({ scopes: ['raed' as never] }))
|
||||
.toThrow(InvalidScopeError);
|
||||
expect(() => createSetupKey({ scopes: ['raed' as never] }))
|
||||
.toThrow('Invalid scope: raed');
|
||||
});
|
||||
|
||||
it('createSetupKey rejects a negative rateLimit', () => {
|
||||
expect(() => createSetupKey({ rateLimit: -5 })).toThrow(InvalidScopeError);
|
||||
});
|
||||
|
||||
// Regression: `opts.rateLimit || 10` coerced the documented "0 = unlimited"
|
||||
// into 10 on the /pair path while /token honored it.
|
||||
it('createSetupKey preserves rateLimit 0 (unlimited)', () => {
|
||||
const setup = createSetupKey({ rateLimit: 0 });
|
||||
expect(setup.rateLimit).toBe(0);
|
||||
const session = exchangeSetupKey(setup.token)!;
|
||||
expect(session.rateLimit).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -326,6 +396,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', () => {
|
||||
|
||||
@@ -0,0 +1,420 @@
|
||||
/**
|
||||
* 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<string, string>, 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<string, string> {
|
||||
const env: Record<string, string> = {};
|
||||
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<number> {
|
||||
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);
|
||||
});
|
||||
|
||||
// pair-agent scope-flag misuse shares this file's subprocess harness: like
|
||||
// tunnel, the validation must run pre-server, so "no daemon spawned" is the
|
||||
// load-bearing assertion.
|
||||
describe('pair-agent scope-flag validation (pre-server)', () => {
|
||||
test('bare --restrict → exit 1 usage error, NO daemon spawned (was: silent FULL grant)', async () => {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-restrict-bare-'));
|
||||
const stateFile = path.join(tmpDir, 'browse.json');
|
||||
try {
|
||||
const result = await runCli(['pair-agent', '--restrict'], baseEnv(stateFile));
|
||||
expect(result.code).toBe(1);
|
||||
expect(result.stderr).toContain('--restrict needs a scope list');
|
||||
expect(fs.existsSync(stateFile)).toBe(false);
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
test('--restrict=read (equals form) → exit 1, NO daemon spawned', async () => {
|
||||
// Regression: hasFlag/parseFlag are exact-token matches, so the equals
|
||||
// form sailed past validatePairAgentFlags AND handlePairAgent's parse —
|
||||
// the user asked for a read-only sandbox and silently got FULL access.
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-restrict-eq-'));
|
||||
const stateFile = path.join(tmpDir, 'browse.json');
|
||||
try {
|
||||
const result = await runCli(['pair-agent', '--restrict=read'], baseEnv(stateFile));
|
||||
expect(result.code).toBe(1);
|
||||
expect(result.stderr).toContain('--restrict takes a space-separated value');
|
||||
expect(fs.existsSync(stateFile)).toBe(false);
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
test('--restrict swallowing the next flag → exit 1, NO daemon spawned', async () => {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-restrict-flag-'));
|
||||
const stateFile = path.join(tmpDir, 'browse.json');
|
||||
try {
|
||||
const result = await runCli(['pair-agent', '--restrict', '--client', 'bob'], baseEnv(stateFile));
|
||||
expect(result.code).toBe(1);
|
||||
expect(result.stderr).toContain('--restrict needs a scope list');
|
||||
expect(fs.existsSync(stateFile)).toBe(false);
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
test('--restrict "read,control" → exit 1 pointing at --control, NO daemon spawned', async () => {
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-restrict-ctl-'));
|
||||
const stateFile = path.join(tmpDir, 'browse.json');
|
||||
try {
|
||||
const result = await runCli(['pair-agent', '--restrict', 'read,control'], baseEnv(stateFile));
|
||||
expect(result.code).toBe(1);
|
||||
expect(result.stderr).toContain('Re-run with --control');
|
||||
expect(fs.existsSync(stateFile)).toBe(false);
|
||||
} finally {
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_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.');
|
||||
|
||||
// Regression: handleTunnel used to trim() the name, but clientIds are
|
||||
// stored verbatim — a space-padded agent became unrevocable by the
|
||||
// documented kill switch (trimmed DELETE 404'd while the grant lived).
|
||||
const padPair = await fetch(`${baseUrl}/pair`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${rootToken}` },
|
||||
body: JSON.stringify({ clientId: ' padded' }),
|
||||
});
|
||||
expect(padPair.status).toBe(200);
|
||||
const padRevoke = await runCli(['tunnel', 'revoke', ' padded'], baseEnv(stateFile));
|
||||
expect(padRevoke.code).toBe(0);
|
||||
expect(padRevoke.stdout).toContain('Verified: not in the active agent list.');
|
||||
} 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('DELETE succeeds but /agents errors → "could not verify", exit 1 (never a silent success)', async () => {
|
||||
// Regression pin: a revoke whose verification read fails must NOT report
|
||||
// clean success — the whole point of the re-read is proving the deletion.
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-tunnel-noverify-'));
|
||||
const stateFile = path.join(tmpDir, 'browse.json');
|
||||
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', tokens_deleted: 1 });
|
||||
}
|
||||
if (url.pathname === '/agents') {
|
||||
return new Response('boom', { status: 500 });
|
||||
}
|
||||
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.stderr).toContain('Revoked, but could not verify against the agent list.');
|
||||
} finally {
|
||||
stub.stop(true);
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
test('DELETE returns 500 → "Revoke failed" with the body error, exit 1', async () => {
|
||||
// Regression pin: a non-404 HTTP failure must surface the daemon's error,
|
||||
// not fall through to a success print.
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-tunnel-500-'));
|
||||
const stateFile = path.join(tmpDir, 'browse.json');
|
||||
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({ error: 'registry exploded' }, { status: 500 });
|
||||
}
|
||||
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.stderr).toContain('Revoke failed: registry exploded');
|
||||
} finally {
|
||||
stub.stop(true);
|
||||
fs.rmSync(tmpDir, { recursive: true, force: true });
|
||||
}
|
||||
}, 30_000);
|
||||
|
||||
test('tunnel agents with a broken /agents → "Could not read the agent list", exit 1', async () => {
|
||||
// Regression pin: a 500 from /agents must not render as "No paired
|
||||
// agents." — an unreadable list is not an empty list.
|
||||
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'browse-tunnel-agents500-'));
|
||||
const stateFile = path.join(tmpDir, 'browse.json');
|
||||
const stub = Bun.serve({
|
||||
hostname: '127.0.0.1',
|
||||
port: 0,
|
||||
fetch(req) {
|
||||
const url = new URL(req.url);
|
||||
if (url.pathname === '/agents') {
|
||||
return new Response('boom', { status: 500 });
|
||||
}
|
||||
return Response.json({ status: 'healthy' });
|
||||
},
|
||||
});
|
||||
try {
|
||||
writeStateFile(stateFile, process.pid, stub.port);
|
||||
const result = await runCli(['tunnel', 'agents'], baseEnv(stateFile));
|
||||
expect(result.code).toBe(1);
|
||||
expect(result.stderr).toContain('Could not read the agent list');
|
||||
expect(result.stdout).not.toContain('No paired agents.');
|
||||
} 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);
|
||||
});
|
||||
Reference in New Issue
Block a user