From a7ce189474766dd2bdac7396cdfe682fe2208228 Mon Sep 17 00:00:00 2001 From: felix Date: Tue, 24 Nov 2026 17:03:13 +0000 Subject: [PATCH 1/3] =?UTF-8?q?bridge=20S10=20(#14376):=20console=20provis?= =?UTF-8?q?ioning=20=E2=80=94=20enroll=20+=20credential=20mints=20shown=20?= =?UTF-8?q?once,=20token=20state,=20revoke=20by=20agent?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Worker: GET enroll-token state list (owner route + read-scope credential route) over a new enrollTokenList store op on both stores; states pending/used/expired/revoked folded with their closing times, never a hash or value. Revoke-by-agent on the enroll revoke route (the console's form: its list shows no hash); the hash/value forms stand. fleet-bridge: mint-enroll, enroll-tokens, revoke-enroll (--agent | --token-hash), mint-credential central verbs. Console: Agents screen gains Provisioning — new-agent enroll mint (token + exact enroll command shown once, in the DOM only, never in state/audit/outbox), direct credential mint (scopes, service binding), per-agent token state list, take-back of unused tokens. Mints are never HOLDABLE (their answer is the secret); the enroll revoke is, like agent.revoke. Edge reads enroll-tokens through the PM credential; the provisioning verbs are never translated there. Book: reference/bridge.md gains the four verbs. --- pkgs/fleet/book/reference/bridge.md | 111 ++++++++ pkgs/fleet/crates/fleet-bridge/src/lib.rs | 146 ++++++++++ pkgs/fleet/crates/fleet-bridge/src/tests.rs | 84 ++++++ pkgs/message-bridge/worker/README.md | 2 + pkgs/message-bridge/worker/src/fleet.js | 93 ++++++- pkgs/message-bridge/worker/src/index.js | 12 + pkgs/message-bridge/worker/src/messages.js | 29 ++ pkgs/message-bridge/worker/src/routes.js | 12 +- .../worker/test/provisioning.test.mjs | 252 ++++++++++++++++++ pm-stack/console/edge/src/direct.ts | 9 +- pm-stack/console/edge/src/edge.ts | 4 +- pm-stack/console/public/app.js | 208 +++++++++++++++ pm-stack/console/public/outbox.js | 13 + pm-stack/console/src/actions.ts | 31 +++ pm-stack/console/src/edge-proto.ts | 12 + pm-stack/console/src/ops.ts | 154 +++++++++++ pm-stack/console/src/reads.ts | 5 + pm-stack/console/test/console.test.ts | 107 +++++++- pm-stack/console/test/direct.test.ts | 26 ++ pm-stack/console/test/edge.test.ts | 27 +- 20 files changed, 1329 insertions(+), 8 deletions(-) create mode 100644 pkgs/message-bridge/worker/test/provisioning.test.mjs diff --git a/pkgs/fleet/book/reference/bridge.md b/pkgs/fleet/book/reference/bridge.md index b3403f419b..c66ecb1509 100644 --- a/pkgs/fleet/book/reference/bridge.md +++ b/pkgs/fleet/book/reference/bridge.md @@ -110,6 +110,117 @@ $ fleet bridge log --kind command --limit 5 Shows the five most recent commands in the central log. +## fleet bridge mint-enroll + +``` +fleet bridge mint-enroll --agent A [--kind K] [--groups g1,g2] [--notes-identity I] [--ttl SECS] +``` + +| Flag | Argument | Default | Meaning | +| ------------------ | -------- | -------- | ------------------------------------------------------------------------------------------- | +| `--agent` | `A` | required | The new agent's name; the token is bound to it and enrolls no other. | +| `--kind` | `K` | `agent` | The agent kind the token is bound to. | +| `--groups` | `g1,g2` | — | Groups the mailbox registers with at exchange. | +| `--notes-identity` | `I` | — | A class/name notes identity to register at exchange. | +| `--ttl` | `SECS` | `86400` | The token's lifetime in seconds (60 to 604800). | + +### Behaviour + +Central verb (owner token). Mints a bootstrap enroll token. Route: `POST /api//enroll-tokens`. The answer carries the token value **once**: the bridge stores only its SHA-256 hash and can never show it again. Hand the value to the new seat, which runs `fleet agent enroll --name A --kind K --bootstrap `; the exchange burns the token and returns the agent's fleet credential and notes token, likewise once. The PM console's Agents screen mints these from its Provisioning section and shows the value and the command once, on that screen only. + +### Exit codes + +`0` ok · `2` usage · `3` transport or credentials · `4` the bridge refused the request. + +### Example + +```console +$ fleet bridge mint-enroll --agent scout-2 --kind muse --groups muse +``` + +Mints a day-long bootstrap token for `scout-2` and prints it, once. + +## fleet bridge enroll-tokens + +``` +fleet bridge enroll-tokens +``` + +| Flag | Argument | Default | Meaning | +| ---- | -------- | ------- | -------------------------------- | +| — | — | — | Takes no arguments and no flags. | + +### Behaviour + +Central verb (owner token). Lists every minted bootstrap token's state: `pending`, `used` (with the exchange's time), `expired` (its TTL lapsed), or `revoked` (with the revocation time), each with its binding (agent, kind, groups, notes identity) and mint/expiry times. Route: `GET /api//enroll-tokens`. State only: no hash or value is ever shown — the value existed once, in the mint answer. + +### Exit codes + +`0` ok · `2` usage · `3` transport or credentials · `4` the bridge refused the request. + +### Example + +```console +$ fleet bridge enroll-tokens +``` + +Shows which minted tokens are still outstanding, and how each closed one ended. + +## fleet bridge revoke-enroll + +``` +fleet bridge revoke-enroll (--agent A | --token-hash H) +``` + +| Flag | Argument | Default | Meaning | +| -------------- | -------- | ------- | ------------------------------------------------------------------------------------------------ | +| `--agent` | `A` | — | Take back every still-pending token minted for this agent; the answer counts them. | +| `--token-hash` | `H` | — | Revoke the one token stored under this SHA-256 hash; the answer is `{revoked: true\|false}`. | + +### Behaviour + +Central verb (owner token). Revokes unused bootstrap tokens. Route: `POST /api//enroll-tokens/revoke`. Exactly one form is required. The hash is not a credential — it cannot enroll anything — so it may travel where a token value never may. Used tokens are untouched: they became credentials, revoked with `fleet bridge revoke --agent`. Expired tokens are already dead and keep their state. + +### Exit codes + +`0` ok · `2` usage · `3` transport or credentials · `4` the bridge refused the request. + +### Example + +```console +$ fleet bridge revoke-enroll --agent scout-2 +``` + +Takes back every outstanding token minted for `scout-2`. + +## fleet bridge mint-credential + +``` +fleet bridge mint-credential --agent A [--scopes s1,s2] [--addr service:] +``` + +| Flag | Argument | Default | Meaning | +| ---------- | --------------- | ------------ | ------------------------------------------------------------------------------------------------ | +| `--agent` | `A` | required | The agent (or service) the credential belongs to; it acts only as itself. | +| `--scopes` | `s1,s2` | see below | Any of `inbox`, `send`, `read`. Agent mints default to `inbox, send`; service mints to `send, read`. | +| `--addr` | `service:` | — | Make it a service credential, bound to that address; the name must be the agent's own. | + +### Behaviour + +Central verb (owner token). Mints a per-agent credential directly, for an agent already enrolled or for a service. Route: `POST /api//fleet/credentials/mint`. Like the enroll mint, the answer carries the credential value **once** and the bridge stores only its hash. Enroll-minted credentials never carry `read`; that scope is for service credentials like the PM stack's. + +### Exit codes + +`0` ok · `2` usage · `3` transport or credentials · `4` the bridge refused the request. + +### Example + +```console +$ fleet bridge mint-credential --agent pm-stack --addr service:pm-stack +``` + +Mints the PM stack's service credential and prints it, once, to be stored in the vault as `bridge.pm-stack-token`. + ## fleet bridge hello ``` diff --git a/pkgs/fleet/crates/fleet-bridge/src/lib.rs b/pkgs/fleet/crates/fleet-bridge/src/lib.rs index d3e57defec..433f75eb9e 100644 --- a/pkgs/fleet/crates/fleet-bridge/src/lib.rs +++ b/pkgs/fleet/crates/fleet-bridge/src/lib.rs @@ -79,6 +79,21 @@ central (owner token): revoke (--agent A | --identity I) revoke an agent's fleet credentials, or a notes identity's tokens (the owner's kill switch, #14368) + mint-enroll --agent A [--kind K] [--groups g1,g2] + [--notes-identity I] [--ttl SECS] + mint a bootstrap enroll token bound to the agent (and kind, + groups, notes identity); the value is printed once, in this + answer only — hand it to the new seat's enroll --bootstrap + enroll-tokens every minted bootstrap token's state + (pending, used, expired, revoked, with its closing times; + never a hash or a value) + revoke-enroll (--agent A | --token-hash H) + revoke unused bootstrap tokens: an agent's pending ones, or + one token by its stored hash (a token value is never needed, + and never travels) + mint-credential --agent A [--scopes s1,s2] [--addr service:] + mint a per-agent credential directly; the value is printed + once, in this answer only agent (fleet token): hello [--agent A] [--groups g1,g2] register / refresh groups @@ -179,6 +194,51 @@ usage: fleet bridge revoke (--agent A | --identity I) central (owner token). Revoke every live fleet credential of an agent (--agent), or every notes token of an identity (--identity): the per-agent kill switch (#14368). Prints how many were revoked." + } + "mint-enroll" => { + "\ +usage: fleet bridge mint-enroll --agent A [--kind K] [--groups g1,g2] + [--notes-identity I] [--ttl SECS] + +central (owner token). Mint a bootstrap enroll token (#14368) bound +at mint to the agent's name, kind (default: agent), groups and class +notes identity, expiring after --ttl seconds (60 to 604800, default +86400). The answer carries the token value once: it is stored +hash-only and can never be shown again. Hand the value to the new +seat: fleet agent enroll --name A --kind K --bootstrap ." + } + "enroll-tokens" => { + "\ +usage: fleet bridge enroll-tokens + +central (owner token). Every minted bootstrap token's state +(#14376): pending, used by the exchange, expired, or revoked, each +with the times that closed it. State only: no hash or value is ever +shown — the value existed once, in the mint answer." + } + "revoke-enroll" => { + "\ +usage: fleet bridge revoke-enroll (--agent A | --token-hash H) + +central (owner token). Revoke unused bootstrap tokens (#14376): +--agent takes back every still-pending token minted for that agent +(the console's form — its list shows no hash); --token-hash revokes +the one token stored under that SHA-256 hash. The hash is not a +credential — it cannot enroll anything — so it may travel where the +token value never may. By hash, a used or already-revoked token +answers {revoked: false}; by agent, the answer counts what was +taken back." + } + "mint-credential" => { + "\ +usage: fleet bridge mint-credential --agent A [--scopes s1,s2] [--addr service:] + +central (owner token). Mint a per-agent credential directly +(#14368): scopes default to inbox + send; with --addr the credential +is a service credential bound to that address (its own name only), +and service mints default to send + read. The answer carries the +credential value once: it is stored hash-only and can never be shown +again." } "hello" => { "\ @@ -539,6 +599,11 @@ const VALUE_FLAGS: &[&str] = &[ "--interval", "--reply-to", "--up-to", + "--scopes", + "--ttl", + "--notes-identity", + "--token-hash", + "--addr", ]; fn parse(args: &[String], switches: &[&str], values: &[&str]) -> R { @@ -834,6 +899,87 @@ pub fn execute(ctx: &mut Ctx, args: &[String]) -> R { ), } } + "mint-enroll" => { + let a = parse( + rest, + &[], + &["--agent", "--kind", "--groups", "--notes-identity", "--ttl"], + )?; + a.no_positional("mint-enroll")?; + // Checked before any credential is resolved: a usage error + // is a usage error even on a seat with no tokens. + let agent = a + .last("--agent") + .ok_or_else(|| usage("mint-enroll needs --agent NAME"))?; + let mut payload = json!({ "agent": agent }); + if let Some(kind) = a.last("--kind") { + payload["kind"] = json!(kind); + } + if let Some(groups) = a.last("--groups") { + payload["groups"] = json!(split_list(groups)); + } + if let Some(identity) = a.last("--notes-identity") { + payload["notes_identity"] = json!(identity); + } + if let Some(ttl) = a.uint("--ttl")? { + payload["ttl_seconds"] = json!(ttl); + } + let token = owner_token(ctx)?; + client_with(ctx, &token).call( + "POST", + &format!("/api/{token}/enroll-tokens"), + Some(&payload), + ) + } + "enroll-tokens" => { + let a = parse(rest, &[], &[])?; + a.no_positional("enroll-tokens")?; + let token = owner_token(ctx)?; + client_with(ctx, &token).call("GET", &format!("/api/{token}/enroll-tokens"), None) + } + "revoke-enroll" => { + let a = parse(rest, &[], &["--agent", "--token-hash"])?; + a.no_positional("revoke-enroll")?; + // Exactly one form, checked before any credential is + // resolved, like every usage error here. The hash is not + // a credential (it cannot enroll anything), so it may + // ride in an argument where a token value never may. + let body = match (a.last("--agent"), a.last("--token-hash")) { + (Some(agent), None) => json!({ "agent": agent }), + (None, Some(hash)) => json!({ "token_hash": hash }), + _ => { + return Err(usage( + "revoke-enroll needs exactly one of --agent or --token-hash", + )); + } + }; + let token = owner_token(ctx)?; + client_with(ctx, &token).call( + "POST", + &format!("/api/{token}/enroll-tokens/revoke"), + Some(&body), + ) + } + "mint-credential" => { + let a = parse(rest, &[], &["--agent", "--scopes", "--addr"])?; + a.no_positional("mint-credential")?; + let agent = a + .last("--agent") + .ok_or_else(|| usage("mint-credential needs --agent NAME"))?; + let mut payload = json!({ "agent": agent }); + if let Some(scopes) = a.last("--scopes") { + payload["scopes"] = json!(split_list(scopes)); + } + if let Some(addr) = a.last("--addr") { + payload["addr"] = json!(addr); + } + let token = owner_token(ctx)?; + client_with(ctx, &token).call( + "POST", + &format!("/api/{token}/fleet/credentials/mint"), + Some(&payload), + ) + } "hello" => { let a = parse(rest, &[], &["--agent", "--groups"])?; a.no_positional("hello")?; diff --git a/pkgs/fleet/crates/fleet-bridge/src/tests.rs b/pkgs/fleet/crates/fleet-bridge/src/tests.rs index a36b2cbd70..dbe8b8aa30 100644 --- a/pkgs/fleet/crates/fleet-bridge/src/tests.rs +++ b/pkgs/fleet/crates/fleet-bridge/src/tests.rs @@ -165,6 +165,10 @@ fn every_verb_has_its_own_help() { "directory", "credentials", "revoke", + "mint-enroll", + "enroll-tokens", + "revoke-enroll", + "mint-credential", "hello", "inbox", "post", @@ -218,6 +222,13 @@ fn usage_errors_exit_2_before_any_request() { vec!["revoke"], vec!["revoke", "--agent", "a", "--identity", "muse/a"], vec!["revoke", "felix"], + vec!["mint-enroll"], + vec!["mint-enroll", "--agent", "a", "--ttl", "soon"], + vec!["mint-enroll", "--agent", "a", "extra"], + vec!["enroll-tokens", "extra"], + vec!["revoke-enroll"], + vec!["revoke-enroll", "--agent", "a", "--token-hash", "ab12"], + vec!["mint-credential"], ] { let e = run_with(url, &s, &args, "").unwrap_err(); assert_eq!(e.exit_code(), EXIT_USAGE, "{args:?}: {e}"); @@ -489,6 +500,79 @@ fn pipeline_directory_credentials_and_revoke_shapes() { ); } +#[test] +fn provisioning_verb_shapes() { + // #14376: the console's provisioning verbs, as owner-token calls on + // the bridge's own routes. The mint answers carry the values; the + // CLI passes them through untouched and keeps nothing. + let (url, seen) = fake_bridge(|_, _, _| (201, r#"{"ok":true}"#.into())); + let s = secrets(&[(DEFAULT_BRIDGE_OWNER_TOKEN_NAME, OWNER)]); + run_with( + &url, + &s, + &[ + "mint-enroll", + "--agent", + "new-1", + "--kind", + "muse", + "--groups", + "muse,code-lanes", + "--notes-identity", + "muse/new-1", + "--ttl", + "3600", + ], + "", + ) + .unwrap(); + run_with(&url, &s, &["enroll-tokens"], "").unwrap(); + run_with(&url, &s, &["revoke-enroll", "--token-hash", "ab12"], "").unwrap(); + run_with(&url, &s, &["revoke-enroll", "--agent", "new-1"], "").unwrap(); + run_with( + &url, + &s, + &[ + "mint-credential", + "--agent", + "pm-stack", + "--scopes", + "send,read", + "--addr", + "service:pm-stack", + ], + "", + ) + .unwrap(); + let seen = seen.lock().unwrap(); + assert_eq!(seen[0].method, "POST"); + assert_eq!(seen[0].url, format!("/api/{OWNER}/enroll-tokens")); + assert_eq!( + seen[0].body.as_ref().unwrap(), + &json!({"agent": "new-1", "kind": "muse", "groups": ["muse", "code-lanes"], "notes_identity": "muse/new-1", "ttl_seconds": 3600}) + ); + assert_eq!(seen[1].method, "GET"); + assert_eq!(seen[1].url, format!("/api/{OWNER}/enroll-tokens")); + assert_eq!(seen[2].url, format!("/api/{OWNER}/enroll-tokens/revoke")); + assert_eq!( + seen[2].body.as_ref().unwrap(), + &json!({"token_hash": "ab12"}) + ); + assert_eq!(seen[3].url, format!("/api/{OWNER}/enroll-tokens/revoke")); + assert_eq!( + seen[3].body.as_ref().unwrap(), + &json!({"agent": "new-1"}) + ); + assert_eq!( + seen[4].url, + format!("/api/{OWNER}/fleet/credentials/mint") + ); + assert_eq!( + seen[4].body.as_ref().unwrap(), + &json!({"agent": "pm-stack", "scopes": ["send", "read"], "addr": "service:pm-stack"}) + ); +} + #[test] fn http_errors_exit_4_and_never_show_the_token() { let (url, _) = fake_bridge(|_, path, _| { diff --git a/pkgs/message-bridge/worker/README.md b/pkgs/message-bridge/worker/README.md index b926f40155..2ff2de8a9a 100644 --- a/pkgs/message-bridge/worker/README.md +++ b/pkgs/message-bridge/worker/README.md @@ -114,6 +114,8 @@ their mailbox, mark what they handled, and post replies and reports back | `GET /fleet//pipeline` | credential (`read`) | the unified pipeline feed, as the owner's `/api//pipeline` (#14374) | | `GET /fleet//directory` | credential (`read`) | the unified agents list, as the owner's `/api//agents` (#14374) | | `GET /fleet//credentials` | credential (`read`) | per-agent credential state, as the owner's (state only: a credential can see a revocation, never make one) | +| `GET /api//enroll-tokens` | owner | every minted bootstrap token's state: pending, used, expired or revoked, with its closing times — never a hash (#14376) | +| `GET /fleet//enroll-tokens` | credential (`read`) | the same enroll-token state list, as the owner's (#14376) | | `POST /api//fleet/offer` | owner | `{body, to, kind?, slots, sender?, ttl_seconds?}`: post an offer (below) | | `GET /api//fleet/offers` | owner | every offer with its claims (agent, time, delivered row) | | `POST /fleet//offer` | fleet | `{agent, body, to, kind?, slots, ttl_seconds?}`: an agent posts an offer | diff --git a/pkgs/message-bridge/worker/src/fleet.js b/pkgs/message-bridge/worker/src/fleet.js index 06ca959bc7..9a37818f78 100644 --- a/pkgs/message-bridge/worker/src/fleet.js +++ b/pkgs/message-bridge/worker/src/fleet.js @@ -1263,6 +1263,49 @@ export function enrollTokenMintSql(sql, row) { }; } +/** Every minted enroll token's state for the owner's list (fleet.js, + * #14376): every column but the hash. The hash names a token only to + * the revoke route; the list never carries it, and no value was ever + * stored to show. */ +export function enrollTokenListSql(sql) { + return sql + .exec( + `SELECT agent, kind, groups, notes_identity, created, expires_at, used_at, revoked_at + FROM enroll_token ORDER BY created DESC, agent`, + ) + .toArray() + .map((r) => ({ + agent: r.agent, + kind: r.kind, + groups: parseJson(r.groups, []), + notes_identity: r.notes_identity, + created: r.created, + expires_at: r.expires_at, + used_at: r.used_at, + revoked_at: r.revoked_at, + })); +} + +/** The state a minted enroll token stands in, derived the same way + * over either store's rows (#14376): revoked by the owner, used by the + * exchange that burned it, expired by the clock, else pending. The + * closing times ride along, so the console can say when each token + * closed and by what: the exchange (used_at), the owner's revoke + * (revoked_at), or the lapse of its TTL (expires_at). */ +export function foldEnrollTokens(rows, now) { + return rows.map((r) => ({ + agent: r.agent, + kind: r.kind, + groups: r.groups ?? [], + notes_identity: r.notes_identity ?? null, + created: r.created, + expires_at: r.expires_at, + used_at: r.used_at ?? null, + revoked_at: r.revoked_at ?? null, + state: r.revoked_at ? "revoked" : r.used_at ? "used" : r.expires_at <= now ? "expired" : "pending", + })); +} + export function enrollTokenGetSql(sql, token_hash) { const r = sql.exec("SELECT * FROM enroll_token WHERE token_hash = ?", token_hash).toArray()[0]; return r @@ -1314,6 +1357,23 @@ export function enrollTokenRevokeSql(sql, token_hash, now) { ); } +/** Revokes every still-pending bootstrap token minted for one agent + * (#14376); returns how many. The console's revoke works by name: the + * token list never shows a hash, so the owner's "take back what I + * minted for this agent" cannot name one. Used tokens are untouched + * (they became credentials — revoking those is the credential + * revoke), and expired ones are already dead and keep their state. */ +export function enrollTokenRevokeAgentSql(sql, agent, now) { + return sql + .exec( + "UPDATE enroll_token SET revoked_at = ? WHERE agent = ? AND used_at IS NULL AND revoked_at IS NULL AND expires_at > ? RETURNING token_hash", + now, + agent, + now, + ) + .toArray().length; +} + /** Validates a bootstrap mint body; the token is bound to what this returns. */ export function normalizeEnrollMint(data) { if (!data || typeof data !== "object" || Array.isArray(data)) throw new InputError("body must be a JSON object"); @@ -1362,6 +1422,16 @@ export async function mintEnrollToken(store, data, nowMs = Date.now()) { }; } +/** + * The owner's list of minted bootstrap tokens (#14376): state only — + * pending, used, expired or revoked, with the times that closed each + * one. No hash and no value: the value was shown once at mint and + * exists nowhere on the bridge to show again. + */ +export async function listEnrollTokens(store, now = new Date().toISOString()) { + return { enroll_tokens: foldEnrollTokens(await store.enrollTokenList(), now) }; +} + /** * Exchanges a bootstrap token for the agent's working credentials. * Every failure — wrong, used, expired or revoked token, or a name @@ -1612,19 +1682,28 @@ async function agentRoute(request, store, what, url, delivered, cred = null) { // answer, nothing more. #14374 adds the unified projections the // console's Messages and Agents surfaces read — the pipeline feed, // the unified agents list and per-agent credential state — the very - // functions the owner's /api routes answer with. All are reads; no + // functions the owner's /api routes answer with. #14376 adds the + // minted enroll tokens' state the same way. All are reads; no // credential value or hash is in any of them, and revoking stays an // owner-token route: a service credential can see that a credential // stands revoked, never revoke one. Enroll-minted agent credentials // never hold the scope, and the shared fleet token does not open // these. - if (what === "agents" || what === "messages" || what === "pipeline" || what === "directory" || what === "credentials") { + if ( + what === "agents" || + what === "messages" || + what === "pipeline" || + what === "directory" || + what === "credentials" || + what === "enroll-tokens" + ) { if (request.method !== "GET") return notAllowed("GET"); if (!cred || !scoped("read")) return notFound(); if (what === "agents") return json(await store.fleet("agents", {})); if (what === "messages") return json(await store.fleet("messages", query(url))); if (what === "pipeline") return json(await pipelineFeed(store, Object.fromEntries(url.searchParams.entries()))); if (what === "directory") return json(await unifiedAgents(store)); + if (what === "enroll-tokens") return json(await listEnrollTokens(store)); return json({ credentials: await store.fleetCredentialState() }); } return notFound(); @@ -1730,12 +1809,20 @@ export async function handleFleet(request, env, url, getStore, deliveredFor = () } if (parts[2] === "enroll-tokens") { if (parts.length === 3) { + if (request.method === "GET") return json(await listEnrollTokens(store)); if (request.method !== "POST") return notAllowed("POST"); return json(await mintEnrollToken(store, await readJson(request)), 201); } if (parts.length === 4 && parts[3] === "revoke") { if (request.method !== "POST") return notAllowed("POST"); - const hash = await enrollRevokeHash(await readJson(request)); + const data = await readJson(request); + // By name (#14376): revoke the agent's outstanding tokens. + // The hash forms below name one token exactly. + if (typeof data.agent === "string" && data.agent !== "") { + const agent = normalizeName(data.agent); + return json({ agent, revoked: await store.enrollTokenRevokeAgent(agent) }); + } + const hash = await enrollRevokeHash(data); return json({ revoked: await store.enrollTokenRevoke(hash) }); } return notFound(); diff --git a/pkgs/message-bridge/worker/src/index.js b/pkgs/message-bridge/worker/src/index.js index 6609586306..b7ed693a97 100644 --- a/pkgs/message-bridge/worker/src/index.js +++ b/pkgs/message-bridge/worker/src/index.js @@ -12,7 +12,9 @@ import { OAUTH_CLIENT_IDLE, OAUTH_MAX_CLIENTS, OAUTH_MAX_EVENTS, OAUTH_PENDING_G import { enrollTokenClaimSql, enrollTokenGetSql, + enrollTokenListSql, enrollTokenMintSql, + enrollTokenRevokeAgentSql, enrollTokenRevokeSql, fleetCall, fleetCredentialAuthSql, @@ -161,6 +163,14 @@ export class MessageStore extends DurableObject { return enrollTokenRevokeSql(this.sql, token_hash, new Date().toISOString()); } + enrollTokenRevokeAgent(agent) { + return enrollTokenRevokeAgentSql(this.sql, agent, new Date().toISOString()); + } + + enrollTokenList() { + return enrollTokenListSql(this.sql); + } + /** Deletes an identity's notes token(s); returns how many were revoked. */ noteRevoke(identity) { return this.sql.exec("DELETE FROM note_token WHERE identity = ? RETURNING token_hash", identity).toArray().length; @@ -647,6 +657,8 @@ function storeFor(env) { enrollTokenGet: (token_hash) => stub.enrollTokenGet(token_hash), enrollTokenClaim: (token_hash, agent, now) => stub.enrollTokenClaim(token_hash, agent, now), enrollTokenRevoke: (token_hash) => stub.enrollTokenRevoke(token_hash), + enrollTokenRevokeAgent: (agent) => stub.enrollTokenRevokeAgent(agent), + enrollTokenList: () => stub.enrollTokenList(), }; } diff --git a/pkgs/message-bridge/worker/src/messages.js b/pkgs/message-bridge/worker/src/messages.js index 4a085b3b6b..67b1387862 100644 --- a/pkgs/message-bridge/worker/src/messages.js +++ b/pkgs/message-bridge/worker/src/messages.js @@ -275,6 +275,35 @@ export class MemoryStore { r.revoked_at = this.now(); return true; } + // Revokes an agent's still-pending tokens (fleet.js + // enrollTokenRevokeAgentSql, #14376); returns how many. + async enrollTokenRevokeAgent(agent) { + const now = this.now(); + let n = 0; + for (const r of this.enrollTokens.values()) { + if (r.agent === agent && !r.used_at && !r.revoked_at && r.expires_at > now) { + r.revoked_at = now; + n++; + } + } + return n; + } + // Minted enroll tokens' state (fleet.js enrollTokenListSql, #14376): + // every field but the hash, newest first as the SQL orders them. + async enrollTokenList() { + return [...this.enrollTokens.values()] + .map((r) => ({ + agent: r.agent, + kind: r.kind, + groups: [...r.groups], + notes_identity: r.notes_identity, + created: r.created, + expires_at: r.expires_at, + used_at: r.used_at, + revoked_at: r.revoked_at, + })) + .sort((a, b) => (a.created === b.created ? (a.agent < b.agent ? -1 : 1) : a.created < b.created ? 1 : -1)); + } async noteRevoke(identity) { let n = 0; for (const [hash, t] of this.noteTokens) { diff --git a/pkgs/message-bridge/worker/src/routes.js b/pkgs/message-bridge/worker/src/routes.js index 5eb0bf4f88..a55220af04 100644 --- a/pkgs/message-bridge/worker/src/routes.js +++ b/pkgs/message-bridge/worker/src/routes.js @@ -56,8 +56,18 @@ // POST /api//enroll-tokens owner: mint a bootstrap enroll // token bound to a name/kind/groups; // the value is returned once +// GET /api//enroll-tokens owner: every minted token's state +// (pending/used/expired/revoked with +// its closing times; never a hash) +// GET /fleet//enroll-tokens credential ("read"): the +// same state list, for the console's +// edge reads (#14376) // POST /api//enroll-tokens/revoke owner: revoke an unused -// bootstrap token +// bootstrap token, by {agent} (all +// of the agent's pending tokens — +// the console's form, since the +// list shows no hash) or by +// {bootstrap_token | token_hash} // POST /enroll/exchange {bootstrap_token, agent}: burn the // token, register the mailbox (and // notes identity), return the agent's diff --git a/pkgs/message-bridge/worker/test/provisioning.test.mjs b/pkgs/message-bridge/worker/test/provisioning.test.mjs new file mode 100644 index 0000000000..11527c8bc2 --- /dev/null +++ b/pkgs/message-bridge/worker/test/provisioning.test.mjs @@ -0,0 +1,252 @@ +// The console provisioning reads (src/fleet.js, #14376, design §4.9): +// the owner — and, through the read scope, the PM stack's service +// credential — can list every minted bootstrap enroll token with its +// state: pending, used by the exchange, expired by the clock, or +// revoked by the owner, each with the time that closed it. Oracles: +// the list never carries a hash or a token value (the value was shown +// once at mint and exists nowhere on the bridge to show again); a +// token minted for one name shows as that name's, and the exchange +// still refuses every other name (the S3 oracle, exercised from the +// console's own path: mint → list → exchange); the views stay shut to +// a credential without the read scope, to the shared fleet token, and +// to a revoke attempted at the credential address. Harness as in +// credentials.test.mjs: real fleetOp SQL on node:sqlite, MemoryStore +// for the rest; a second block drives the Durable Object's SQL helpers +// directly for store parity. All token values are fixtures or values +// the Worker itself generated inside the test. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { DatabaseSync } from "node:sqlite"; +import { + enrollTokenClaimSql, + enrollTokenListSql, + enrollTokenMintSql, + enrollTokenRevokeAgentSql, + enrollTokenRevokeSql, + fleetCall, + fleetOp, + fleetSchema, + fleetToken, + foldEnrollTokens, + mintEnrollToken, +} from "../src/fleet.js"; +import { MemoryStore } from "../src/messages.js"; +import { route } from "../src/routes.js"; + +const TOKEN = "o".repeat(20) + "0123456789abcdefXYZ_-"; +const CHATGPT = "c".repeat(40); +const env = { ACCESS_TOKEN: TOKEN, CHATGPT_TOKEN: CHATGPT }; +const BASE = "https://bridge.example"; + +/** The Durable Object's sql.exec over node:sqlite. */ +function sqlite() { + const db = new DatabaseSync(":memory:"); + return { + exec(q, ...args) { + const out = db.prepare(q).all(...args); + return { toArray: () => out, one: () => out[0] }; + }, + }; +} + +async function harness() { + const sql = sqlite(); + fleetSchema(sql); + let clock = 0; + const stub = { fleet: (op, args) => fleetOp(sql, op, args, `2026-11-24T00:00:${String(clock++).padStart(2, "0")}Z`) }; + const store = new MemoryStore(); + store.fleet = (op, args) => fleetCall(stub, op, args); + const call = (path, init) => route(new Request(BASE + path, init), env, () => store); + const ft = await fleetToken(env); + const post = (path, body) => + call(path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const api = { + mint: (body) => post(`/api/${TOKEN}/enroll-tokens`, body), + revokeEnroll: (body) => post(`/api/${TOKEN}/enroll-tokens/revoke`, body), + list: () => call(`/api/${TOKEN}/enroll-tokens`), + mintCred: (body) => post(`/api/${TOKEN}/fleet/credentials/mint`, body), + }; + const exchange = (bootstrap_token, agent) => post(`/enroll/exchange`, { bootstrap_token, agent }); + const as = (cred) => ({ + list: () => call(`/fleet/${cred}/enroll-tokens`), + revokeEnroll: (body) => post(`/fleet/${cred}/enroll-tokens/revoke`, body), + }); + return { store, call, post, ft, api, exchange, as }; +} + +/** Mints one token through the owner's route; returns the mint body. */ +async function minted(h, body) { + const res = await h.api.mint(body); + assert.equal(res.status, 201, JSON.stringify(body)); + return res.json(); +} + +test("the list shows each minted token's state and closing time, and never a hash or a value", async () => { + const h = await harness(); + const pending = await minted(h, { agent: "pend-1", kind: "muse", groups: ["muse"] }); + const used = await minted(h, { agent: "used-1" }); + const ex = await h.exchange(used.bootstrap_token, "used-1"); + assert.equal(ex.status, 201); + const revoked = await minted(h, { agent: "rev-1" }); + // The console revokes an unused token by the hash it derives from + // nothing: the revoke route takes the stored hash, which the list + // never shows — the owner's own hand-off copy is hashed here the + // way the route accepts it. + const byValue = await h.api.revokeEnroll({ bootstrap_token: revoked.bootstrap_token }); + assert.equal((await byValue.json()).revoked, true); + // A token whose TTL has lapsed: minted two minutes in the past with + // a one-minute TTL, straight into the store the route reads. + await mintEnrollToken(h.store, { agent: "old-1", ttl_seconds: 60 }, Date.now() - 120_000); + + const res = await h.api.list(); + assert.equal(res.status, 200); + const text = await res.text(); + const { enroll_tokens } = JSON.parse(text); + const byAgent = new Map(enroll_tokens.map((t) => [t.agent, t])); + + assert.equal(byAgent.get("pend-1").state, "pending"); + assert.equal(byAgent.get("pend-1").kind, "muse"); + assert.deepEqual(byAgent.get("pend-1").groups, ["muse"]); + assert.equal(byAgent.get("pend-1").used_at, null); + assert.equal(byAgent.get("pend-1").revoked_at, null); + + assert.equal(byAgent.get("used-1").state, "used"); + assert.ok(byAgent.get("used-1").used_at, "the exchange's time is the closing time"); + + assert.equal(byAgent.get("rev-1").state, "revoked"); + assert.ok(byAgent.get("rev-1").revoked_at, "the revoke's time is the closing time"); + + assert.equal(byAgent.get("old-1").state, "expired"); + assert.ok(byAgent.get("old-1").expires_at <= new Date().toISOString(), "the lapse time is the expiry itself"); + assert.equal(byAgent.get("old-1").used_at, null); + assert.equal(byAgent.get("old-1").revoked_at, null); + + // No hash, no value: neither the stored hashes nor any minted value + // appears anywhere in the answer, and no row carries a hash field. + for (const t of enroll_tokens) assert.ok(!("token_hash" in t), "no hash field on a row"); + for (const m of [pending, used, revoked]) assert.ok(!text.includes(m.bootstrap_token), "no minted value in the list"); + assert.ok(!/[0-9a-f]{64}/.test(text), "no SHA-256-shaped string in the list"); +}); + +test("the console path: a token minted for one name enrolls that name only, and the list follows it", async () => { + const h = await harness(); + const mint = await minted(h, { agent: "console-1", kind: "muse", groups: ["muse"], notes_identity: "muse/console-1" }); + + // Before the exchange the list shows the pending token, bound to + // the name it was minted for. + let rows = (await (await h.api.list()).json()).enroll_tokens; + const row = rows.find((t) => t.agent === "console-1"); + assert.equal(row.state, "pending"); + assert.equal(row.notes_identity, "muse/console-1"); + + // The exchange refuses any other name (the S3 oracle), and the + // token stays pending for its own. + assert.equal((await h.exchange(mint.bootstrap_token, "other-1")).status, 404); + rows = (await (await h.api.list()).json()).enroll_tokens; + assert.equal(rows.find((t) => t.agent === "console-1").state, "pending"); + + // Its own name exchanges, and the list then shows it used. + const ex = await h.exchange(mint.bootstrap_token, "console-1"); + assert.equal(ex.status, 201); + const creds = await ex.json(); + assert.equal(creds.agent, "console-1"); + assert.ok(creds.fleet_token && creds.notes_token, "the hand-off credentials came back once"); + rows = (await (await h.api.list()).json()).enroll_tokens; + const after = rows.find((t) => t.agent === "console-1"); + assert.equal(after.state, "used"); + assert.ok(after.used_at); +}); + +test("revoking by agent name takes back that agent's pending tokens and no others", async () => { + const h = await harness(); + await minted(h, { agent: "multi-1" }); + await minted(h, { agent: "multi-1" }); + const used = await minted(h, { agent: "multi-1" }); + assert.equal((await h.exchange(used.bootstrap_token, "multi-1")).status, 201); + await minted(h, { agent: "other-2" }); + // A lapsed token for the same agent is already dead: not counted, + // and its state stays expired rather than becoming revoked. + await mintEnrollToken(h.store, { agent: "multi-1", ttl_seconds: 60 }, Date.now() - 120_000); + + const res = await h.api.revokeEnroll({ agent: "multi-1" }); + assert.equal(res.status, 200); + assert.deepEqual(await res.json(), { agent: "multi-1", revoked: 2 }); + + const rows = (await (await h.api.list()).json()).enroll_tokens; + const mine = rows.filter((t) => t.agent === "multi-1"); + assert.equal(mine.filter((t) => t.state === "revoked").length, 2); + assert.equal(mine.filter((t) => t.state === "used").length, 1, "the used token became a credential; it is not this revoke's"); + assert.equal(mine.filter((t) => t.state === "expired").length, 1); + assert.equal(rows.find((t) => t.agent === "other-2").state, "pending"); + // And again: nothing left to take back. + assert.deepEqual(await (await h.api.revokeEnroll({ agent: "multi-1" })).json(), { agent: "multi-1", revoked: 0 }); +}); + +test("the read scope sees the same state list; plainer doors stay shut, and revoking stays the owner's", async () => { + const h = await harness(); + await minted(h, { agent: "pend-1" }); + + // The PM stack's service credential (direct mint, service addr). + const pmRes = await h.api.mintCred({ agent: "pm-stack", addr: "service:pm-stack" }); + assert.equal(pmRes.status, 201); + const pm = (await pmRes.json()).credential; + const viaPm = await h.as(pm).list(); + assert.equal(viaPm.status, 200); + const rows = (await viaPm.json()).enroll_tokens; + assert.equal(rows.find((t) => t.agent === "pend-1")?.state, "pending"); + + // An enroll-minted agent credential (inbox + send, no read) is refused. + const agentMint = await minted(h, { agent: "plain-1" }); + const ex = await h.exchange(agentMint.bootstrap_token, "plain-1"); + const agentCred = (await ex.json()).fleet_token; + assert.equal((await h.as(agentCred).list()).status, 404); + + // The shared fleet token and a junk token are refused too. + assert.equal((await h.call(`/fleet/${h.ft}/enroll-tokens`)).status, 404); + assert.equal((await h.call(`/fleet/${"x".repeat(43)}/enroll-tokens`)).status, 404); + + // Minting and revoking never open at the credential address. + assert.equal((await h.as(pm).revokeEnroll({ token_hash: "0".repeat(64) })).status, 404); + assert.equal((await h.post(`/fleet/${pm}/enroll-tokens`, { agent: "x-1" })).status, 404); +}); + +test("the Durable Object's SQL folds the same states, hash-free (store parity)", async () => { + const sql = sqlite(); + fleetSchema(sql); + const t0 = "2026-11-24T00:00:00.000Z"; + const row = (hash, agent, created, expires_at) => ({ + token_hash: hash, + agent, + kind: "agent", + groups: [], + notes_identity: null, + expires_at, + created, + }); + enrollTokenMintSql(sql, row("a".repeat(64), "pend-1", t0, "2026-11-25T00:00:00.000Z")); + enrollTokenMintSql(sql, row("b".repeat(64), "used-1", t0, "2026-11-25T00:00:00.000Z")); + enrollTokenClaimSql(sql, "b".repeat(64), "used-1", "2026-11-24T01:00:00.000Z"); + enrollTokenMintSql(sql, row("c".repeat(64), "rev-1", t0, "2026-11-25T00:00:00.000Z")); + enrollTokenRevokeSql(sql, "c".repeat(64), "2026-11-24T02:00:00.000Z"); + enrollTokenMintSql(sql, row("d".repeat(64), "old-1", t0, "2026-11-24T00:30:00.000Z")); + + const folded = foldEnrollTokens(enrollTokenListSql(sql), "2026-11-24T03:00:00.000Z"); + const byAgent = new Map(folded.map((t) => [t.agent, t])); + assert.equal(byAgent.get("pend-1").state, "pending"); + assert.equal(byAgent.get("used-1").state, "used"); + assert.equal(byAgent.get("used-1").used_at, "2026-11-24T01:00:00.000Z"); + assert.equal(byAgent.get("rev-1").state, "revoked"); + assert.equal(byAgent.get("rev-1").revoked_at, "2026-11-24T02:00:00.000Z"); + assert.equal(byAgent.get("old-1").state, "expired"); + for (const t of folded) assert.ok(!("token_hash" in t)); + // The hashes the test itself stored never come back out. + const text = JSON.stringify(folded); + for (const hash of ["a", "b", "c", "d"]) assert.ok(!text.includes(hash.repeat(64))); + + // The by-agent revoke, same semantics: the pending token only. + assert.equal(enrollTokenRevokeAgentSql(sql, "pend-1", "2026-11-24T04:00:00.000Z"), 1); + assert.equal(enrollTokenRevokeAgentSql(sql, "used-1", "2026-11-24T04:00:00.000Z"), 0); + const after = new Map(foldEnrollTokens(enrollTokenListSql(sql), "2026-11-24T05:00:00.000Z").map((t) => [t.agent, t])); + assert.equal(after.get("pend-1").state, "revoked"); + assert.equal(after.get("pend-1").revoked_at, "2026-11-24T04:00:00.000Z"); +}); diff --git a/pm-stack/console/edge/src/direct.ts b/pm-stack/console/edge/src/direct.ts index 08019a6f86..d20bb8f9e2 100644 --- a/pm-stack/console/edge/src/direct.ts +++ b/pm-stack/console/edge/src/direct.ts @@ -736,7 +736,11 @@ export const BRIDGE_AGENT = "pm-stack"; * carry. `revoke` is deliberately not among them: the PM credential * holds the read scope, and revoking is the owner's act through the * owner token on a machine — the action is held for one instead - * (src/edge-proto.ts). + * (src/edge-proto.ts). The provisioning verbs stand with it: + * `enroll-tokens` is read here (state only, #14376), while + * mint-enroll, mint-credential and revoke-enroll are never translated + * — a mint's value must reach the owner's screen from the machine + * that minted it, and a revoke is held for a machine. * A failed call answers the way the fleet binary would: a non-zero * code with the reason on stderr. The bridge's plain 404 for a wrong * token is said plainly here — the credential unknown or revoked — @@ -808,6 +812,9 @@ async function bridgeCall( } else if (what === "credentials") { if (rest.length > 0) throw new OpError(502, "fleet bridge credentials takes no arguments here"); path = `/fleet/${token}/credentials`; + } else if (what === "enroll-tokens") { + if (rest.length > 0) throw new OpError(502, "fleet bridge enroll-tokens takes no arguments here"); + path = `/fleet/${token}/enroll-tokens`; } else if (what === "send") { const to: string[] = []; let kind = "message"; diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index cfa184d2da..18514f77bd 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -2508,7 +2508,9 @@ export class Edge { // a machine's to read, and the request goes to the host // below as it did before. const mine = this.mine(cfg); - const bridgeRead = seg.length === 1 && (seg[0] === "messages" || seg[0] === "pipeline" || seg[0] === "directory"); + const bridgeRead = + seg.length === 1 && + (seg[0] === "messages" || seg[0] === "pipeline" || seg[0] === "directory" || seg[0] === "enroll-tokens"); if (mine && !(bridgeRead && !this.bridgeReady())) { const from = this.outwardN; let read: unknown; diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index d4dcf843fe..6af114a8df 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -3771,12 +3771,220 @@ async function viewAgents() { : null, ); }; + // ---- provisioning (#14376, design §4.9) ------------------------------- + // Minted enroll tokens, by state. Where the read cannot be made the + // screen says so, as it does for the directory. + let enroll = null; + try { + const got = await api("enroll-tokens"); + if (Array.isArray(got)) enroll = got; + } catch { + enroll = null; + } + // A minted value, shown once: the card is built from the mint's + // answer and put straight into the page — never into this screen's + // state, the documents, or the outbox — so the next draw (leaving + // the screen, a refresh) takes it with it, and neither the bridge + // nor this console can show it again. That is the property, not a + // courtesy: the bridge keeps only the value's hash. + const showOnce = (title, note, value, command) => { + const copy = (what, label) => + h( + "button", + { + class: "small", + onclick: () => + navigator.clipboard + .writeText(what) + .then(() => toast("Copied")) + .catch(() => toast("Copying failed — select the text and copy it by hand", true)), + }, + label, + ); + const node = card( + h("h3", {}, title), + h("p", { class: "why" }, note), + h("pre", {}, value), + command ? h("pre", {}, command) : null, + h( + "div", + { class: "row end" }, + copy(value, "Copy the value"), + command ? copy(command, "Copy the command") : null, + h("button", { class: "small ghost", onclick: () => node.remove() }, "Hide it"), + ), + ); + view.prepend(node); + node.scrollIntoView(); + }; + const pName = h("input", { type: "text", "aria-label": "New agent name", placeholder: "new agent's name" }); + const pKind = h("input", { type: "text", "aria-label": "Kind", list: "agent-kinds", placeholder: "kind — muse, codex, …" }); + const pGroups = h("input", { type: "text", "aria-label": "Groups", placeholder: "groups, comma-separated" }); + const pNotes = h("input", { type: "text", "aria-label": "Notes identity", placeholder: "notes identity (class/name) — blank for none" }); + const pTtl = h( + "select", + { "aria-label": "Token lifetime" }, + h("option", { value: "3600" }, "For an hour"), + h("option", { value: "86400" }, "For a day"), + h("option", { value: "604800" }, "For a week"), + ); + pTtl.value = "86400"; + const newAgent = card( + h("h3", {}, "New agent"), + h( + "p", + { class: "meta" }, + "Mint a bootstrap enroll token, bound to the name, kind, groups and notes identity below. The token and the enroll command are shown once, when it is minted.", + ), + pName, + pKind, + h("datalist", { id: "agent-kinds" }, ["muse", "claude-code", "codex", "opencode", "openchamber", "openclaw", "gemini", "antigravity", "grok", "chatgpt", "generic"].map((k) => h("option", { value: k }))), + pGroups, + pNotes, + pTtl, + h( + "div", + { class: "row end" }, + h( + "button", + { + onclick: async (e) => { + const agent = pName.value.trim(); + if (!agent) return toast("Name the new agent first", true); + const result = await act( + "agent.mint-enroll", + { + agent, + kind: pKind.value.trim() || undefined, + groups: pGroups.value.split(",").map((g) => g.trim()).filter(Boolean), + notesIdentity: pNotes.value.trim() || undefined, + ttlSeconds: Number(pTtl.value) || undefined, + }, + `Enroll token minted for ${agent}`, + e.target, + ); + if (result && typeof result.bootstrap_token === "string") { + const groups = Array.isArray(result.groups) && result.groups.length ? ` --groups ${result.groups.join(",")}` : ""; + showOnce( + `Enroll token for ${result.agent}`, + `Shown once: the bridge keeps only its hash, and it can never be shown again. It works until ${result.expires_at}. Run this on the new seat:`, + result.bootstrap_token, + `fleet agent enroll --name ${result.agent} --kind ${result.kind}${groups} --bootstrap ${result.bootstrap_token}`, + ); + } + }, + }, + "Mint enroll token", + ), + ), + ); + const cName = h("input", { type: "text", "aria-label": "Agent for the credential", list: "agent-names", placeholder: "agent's name" }); + const cScope = (value, label, on) => { + const box = h("input", { type: "checkbox", value }); + box.checked = on; + return { box, label: h("label", { class: "row check meta" }, box, label) }; + }; + const cInbox = cScope("inbox", "inbox", true); + const cSend = cScope("send", "send", true); + const cRead = cScope("read", "read", false); + const cService = h("input", { type: "checkbox" }); + const newCredential = card( + h("h3", {}, "New credential"), + h( + "p", + { class: "meta" }, + "Mint a credential directly, for an agent that is already enrolled or for a service. The value is shown once, when it is minted; keep it in the vault under the agent's token name.", + ), + cName, + h("datalist", { id: "agent-names" }, roster.filter((a) => a.surface === "fleet").map((a) => h("option", { value: a.name }))), + h("div", { class: "row" }, cInbox.label, cSend.label, cRead.label, h("label", { class: "row check meta" }, cService, "Service (service:)")), + h( + "div", + { class: "row end" }, + h( + "button", + { + onclick: async (e) => { + const agent = cName.value.trim(); + if (!agent) return toast("Name the agent first", true); + const scopes = [cInbox, cSend, cRead].filter((s) => s.box.checked).map((s) => s.box.value); + if (!scopes.length) return toast("Pick at least one scope", true); + const result = await act( + "agent.mint-credential", + { agent, scopes, addr: cService.checked ? `service:${agent}` : undefined }, + `Credential minted for ${agent}`, + e.target, + ); + if (result && typeof result.credential === "string") { + showOnce( + `Credential for ${result.agent}`, + "Shown once: the bridge keeps only its hash, and it can never be shown again. Store it in the vault now, under the agent's token name.", + result.credential, + null, + ); + } + }, + }, + "Mint credential", + ), + ), + ); + const tokenRow = (t) => { + const closed = + t.state === "used" + ? `used ${ago(t.used_at)} — the exchange burned it` + : t.state === "revoked" + ? `revoked ${ago(t.revoked_at)} — taken back by the owner` + : t.state === "expired" + ? `expired ${ago(t.expires_at)} — its time ran out` + : `minted ${ago(t.created)} · works until ${t.expires_at}`; + return card( + h( + "div", + { class: "row" }, + h("h3", {}, t.agent), + chip(t.state, t.state === "pending" ? "warn" : t.state === "used" ? "good" : ""), + ), + h( + "p", + { class: "meta" }, + `${t.kind}${t.groups?.length ? ` · groups ${t.groups.join(", ")}` : ""}${t.notes_identity ? ` · notes ${t.notes_identity}` : ""} · ${closed}`, + ), + t.state === "pending" + ? h( + "div", + { class: "row end" }, + h( + "button", + { + class: "small ghost", + onclick: async (e) => { + const yes = await ask({ + title: `Take back ${t.agent}'s unused enroll tokens?`, + text: "Every still-pending token minted for this agent is revoked. One already used is not touched — its credentials are revoked from the roster above.", + okLabel: "Take back", + danger: true, + }); + if (yes !== null) act("agent.revoke-enroll", { agent: t.agent }, `Took back ${t.agent}'s enroll tokens`, e.target); + }, + }, + "Take back", + ), + ) + : null, + ); + }; return [ ...notices(docs.ops, ["agents"]), compose, h("h2", {}, `Agents (${roster.length})`), directory === null ? empty("The unified directory could not be read just now; the fleet roster is shown, without credential state.") : null, ...roster.map(agentCard), + h("h2", {}, "Provisioning"), + newAgent, + newCredential, + enroll === null ? empty("The enroll tokens could not be read just now.") : null, + ...(enroll ?? []).map(tokenRow), h("h2", {}, "Recent messages"), ...(recent.length ? recent.map((m) => card(h("p", { class: "meta" }, `${ago(m.ts)} · ${m.direction} · ${m.agent} · ${m.kind}`), h("p", {}, String(m.body ?? "").slice(0, 600)))) diff --git a/pm-stack/console/public/outbox.js b/pm-stack/console/public/outbox.js index 1b0db82ecc..c9bec8cdf4 100644 --- a/pm-stack/console/public/outbox.js +++ b/pm-stack/console/public/outbox.js @@ -29,6 +29,11 @@ "message.send", // A revocation done late is still the right act (#14374). "agent.revoke", + // Taking back unused enroll tokens, the same (#14376). The + // provisioning mints are NOT here: their answer is a secret shown + // once, so they are "now" — done with a connection or not at all, + // never kept on this device to be done late. + "agent.revoke-enroll", "intake.send", ]); /** Actions on something that may have changed by the time they are @@ -90,6 +95,8 @@ const name = typeof a.name === "string" ? a.name : ""; return surface === "" || name === "" ? null : `agent:${surface}:${name}`; } + case "agent.revoke-enroll": + return of("enroll", a.agent); default: return null; } @@ -149,6 +156,12 @@ return `Message to ${Array.isArray(a.to) ? a.to.join(", ") : a.to}${quoted(a.text)}`; case "agent.revoke": return `Revoke ${a.name ?? "an agent"}'s ${a.surface === "notes" ? "notes tokens" : "bridge credentials"}`; + case "agent.revoke-enroll": + return `Take back ${a.agent ?? "an agent"}'s unused enroll tokens`; + case "agent.mint-enroll": + return `Mint an enroll token for ${a.agent ?? "a new agent"}`; + case "agent.mint-credential": + return `Mint a credential for ${a.agent ?? "an agent"}`; case "unit.act": return `${a.action} ${a.unit}`; // The platform's own second half of something it filed itself: diff --git a/pm-stack/console/src/actions.ts b/pm-stack/console/src/actions.ts index d0ce024f63..3e5149395b 100644 --- a/pm-stack/console/src/actions.ts +++ b/pm-stack/console/src/actions.ts @@ -222,6 +222,37 @@ export function actions( touch: [], audit: ids("surface", "name"), }, + // Provisioning (#14376, design §4.9). The two mints are never + // held anywhere to be done late (edge-proto.ts): a mint's answer + // IS the secret, shown once on the screen that asked — a mint + // done late would hand its value to nobody, and lose it. Like + // sso.google, their audit records nothing of the value: the mint + // keeps only the binding it was made under. The enroll revoke is + // the opposite shape — no value in it at all, and done late it is + // still the right act — so it is held for a machine like + // agent.revoke. + "agent.mint-enroll": { + run: (a) => + ops.mintEnrollToken({ + agent: a.agent, + kind: a.kind, + groups: a.groups, + notesIdentity: a.notesIdentity, + ttlSeconds: a.ttlSeconds, + }), + touch: [], + audit: ids("agent", "kind", "groups", "notesIdentity", "ttlSeconds"), + }, + "agent.mint-credential": { + run: (a) => ops.mintCredential({ agent: a.agent, scopes: a.scopes, addr: a.addr }), + touch: [], + audit: ids("agent", "scopes", "addr"), + }, + "agent.revoke-enroll": { + run: (a) => ops.revokeEnrollTokens(a.agent), + touch: [], + audit: ids("agent"), + }, }; } diff --git a/pm-stack/console/src/edge-proto.ts b/pm-stack/console/src/edge-proto.ts index e47cd81520..d697bb5410 100644 --- a/pm-stack/console/src/edge-proto.ts +++ b/pm-stack/console/src/edge-proto.ts @@ -290,6 +290,13 @@ export const HOLDABLE = new Set([ // rather than refused while the laptop is away. The edge itself // never revokes: its bridge credential holds the read scope only. "agent.revoke", + // Taking back an agent's unused enroll tokens (#14376) is the same + // shape: no value travels in it, and done late it is still the right + // act. The mints are deliberately NOT here: a mint's answer is the + // secret itself, shown once on the screen that asked — held and + // done late, the value would reach nobody and be lost, so a mint + // asked at the edge while no machine answers is refused, never held. + "agent.revoke-enroll", "prompt.enqueue", // What the owner says is never lost for want of a machine: it is // kept and filed when one is back (or filed here, when the edge can). @@ -335,6 +342,11 @@ export function subjectOf(kind: string, args: Record | null | u const name = typeof a.name === "string" ? a.name : ""; return surface === "" || name === "" ? null : `agent:${surface}:${name}`; } + case "agent.revoke-enroll": + // One agent's enroll tokens: a later mint for the same agent + // does not queue behind this (a mint is never held), but two + // take-backs of one agent keep the owner's order. + return of("enroll", a.agent); case "unit.act": return of("unit", a.unit); default: diff --git a/pm-stack/console/src/ops.ts b/pm-stack/console/src/ops.ts index 31d3c0e350..218506513c 100644 --- a/pm-stack/console/src/ops.ts +++ b/pm-stack/console/src/ops.ts @@ -657,6 +657,160 @@ export class Ops { return { surface: s, name: n, revoked: typeof out.revoked === "number" ? out.revoked : 0 }; } + /** The minted bootstrap tokens' state for the Agents screen + * (#14376): pending, used, expired or revoked, each with the times + * that closed it. State only — the bridge stores hashes and returns + * neither a hash nor a value here; a token's value existed once, in + * its mint answer. */ + async enrollTokens() { + const rows = ( + JSON.parse(await this.must([this.cfg.fleetBin, "bridge", "enroll-tokens"])) as { + enroll_tokens?: unknown; + } | null + )?.enroll_tokens; + return Array.isArray(rows) ? (rows as Record[]) : []; + } + + /** + * Mint a bootstrap enroll token from the Agents screen (#14376, + * design §4.9), bound at mint to the new agent's name, kind, groups + * and class notes identity, for the TTL the owner picked. The + * bridge's answer carries the token value, and it passes straight + * through to the caller — the one screen that shows it, once. + * Nothing keeps it: this class holds no state but the queue token, + * the action's audit record names only the binding (actions.ts), + * and the value never travels as an argument — the CLI builds the + * mint from these flags, and the value comes back on stdout alone. + * The binding is checked here first, in the console's own terms, + * before anything runs. + */ + async mintEnrollToken(input: { + agent?: unknown; + kind?: unknown; + groups?: unknown; + notesIdentity?: unknown; + ttlSeconds?: unknown; + }) { + const name = (value: unknown, what: string, max = 128) => { + const n = text(value, what, max); + if (!/^[A-Za-z0-9][A-Za-z0-9@._/-]{0,127}$/.test(n)) { + throw new OpError(400, `${what}: not a name: ${JSON.stringify(n).slice(0, 80)}`); + } + return n; + }; + const agent = name(input.agent, "agent"); + const argv = [this.cfg.fleetBin, "bridge", "mint-enroll", "--agent", agent]; + if (input.kind !== undefined && input.kind !== null && input.kind !== "") { + argv.push("--kind", name(input.kind, "kind", 64)); + } + if (input.groups !== undefined && input.groups !== null && input.groups !== "") { + const groups = (Array.isArray(input.groups) ? input.groups : String(input.groups).split(",")) + .map((g) => (typeof g === "string" ? g.trim() : g)) + .filter((g) => g !== ""); + if (groups.length > 16) throw new OpError(400, "groups: at most sixteen"); + for (const g of groups) { + if (typeof g !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(g)) { + throw new OpError(400, `groups: not a group name: ${JSON.stringify(g).slice(0, 80)}`); + } + } + if (groups.length > 0) argv.push("--groups", groups.join(",")); + } + if (input.notesIdentity !== undefined && input.notesIdentity !== null && input.notesIdentity !== "") { + argv.push("--notes-identity", name(input.notesIdentity, "notes identity")); + } + if (input.ttlSeconds !== undefined && input.ttlSeconds !== null && input.ttlSeconds !== "") { + const ttl = id(input.ttlSeconds, "ttl"); + if (ttl < 60 || ttl > 604_800) throw new OpError(400, "ttl: between a minute and a week, in seconds"); + argv.push("--ttl", String(ttl)); + } + const out = JSON.parse(await this.must(argv)) as { + agent?: unknown; + kind?: unknown; + groups?: unknown; + notes_identity?: unknown; + expires_at?: unknown; + bootstrap_token?: unknown; + } | null; + if (typeof out?.bootstrap_token !== "string" || out.bootstrap_token === "") { + throw new OpError(502, "the bridge's mint answer carried no token"); + } + return { + agent: typeof out.agent === "string" ? out.agent : agent, + kind: typeof out.kind === "string" ? out.kind : "agent", + groups: Array.isArray(out.groups) ? out.groups.filter((g) => typeof g === "string") : [], + notes_identity: typeof out.notes_identity === "string" ? out.notes_identity : null, + expires_at: typeof out.expires_at === "string" ? out.expires_at : null, + bootstrap_token: out.bootstrap_token, + }; + } + + /** + * Take back an agent's unused bootstrap tokens from the Agents + * screen (#14376): every still-pending token minted for the agent. + * By name, never by value — the list shows no hash, and a token + * value has no business travelling to undo its own minting. Used + * tokens are not this revoke's (they became credentials; revoke + * those above), and expired ones are already dead. + */ + async revokeEnrollTokens(agent: unknown) { + const n = text(agent, "agent", 200); + if (!/^[A-Za-z0-9][A-Za-z0-9@._/-]{0,127}$/.test(n)) { + throw new OpError(400, `agent: not an agent name: ${JSON.stringify(n).slice(0, 80)}`); + } + const out = JSON.parse( + await this.must([this.cfg.fleetBin, "bridge", "revoke-enroll", "--agent", n]), + ) as { revoked?: unknown }; + return { agent: n, revoked: typeof out.revoked === "number" ? out.revoked : 0 }; + } + + /** + * Mint a per-agent credential directly from the Agents screen + * (#14376): for an agent that is already enrolled, or a service + * credential with --addr. Like the enroll mint, the value passes + * straight through to the one screen that shows it, once, and is + * kept nowhere. A service address must name the agent itself — the + * bridge binds a service credential to its own name, and the check + * is made here first as everywhere else. + */ + async mintCredential(input: { agent?: unknown; scopes?: unknown; addr?: unknown }) { + const agent = text(input.agent, "agent", 200); + if (!/^[A-Za-z0-9][A-Za-z0-9@._/-]{0,127}$/.test(agent)) { + throw new OpError(400, `agent: not an agent name: ${JSON.stringify(agent).slice(0, 80)}`); + } + const argv = [this.cfg.fleetBin, "bridge", "mint-credential", "--agent", agent]; + if (input.scopes !== undefined && input.scopes !== null && input.scopes !== "") { + const scopes = (Array.isArray(input.scopes) ? input.scopes : String(input.scopes).split(",")) + .map((s) => (typeof s === "string" ? s.trim() : s)) + .filter((s) => s !== ""); + if (scopes.length === 0 || scopes.some((s) => s !== "inbox" && s !== "send" && s !== "read")) { + throw new OpError(400, "scopes: only inbox, send and read exist"); + } + argv.push("--scopes", scopes.join(",")); + } + if (input.addr !== undefined && input.addr !== null && input.addr !== "") { + const addr = text(input.addr, "addr", 200); + if (addr !== `service:${agent}`) { + throw new OpError(400, "addr: a service credential is bound to its own name (service:)"); + } + argv.push("--addr", addr); + } + const out = JSON.parse(await this.must(argv)) as { + agent?: unknown; + scopes?: unknown; + addr?: unknown; + credential?: unknown; + } | null; + if (typeof out?.credential !== "string" || out.credential === "") { + throw new OpError(502, "the bridge's mint answer carried no credential"); + } + return { + agent: typeof out.agent === "string" ? out.agent : agent, + scopes: Array.isArray(out.scopes) ? out.scopes.filter((s) => typeof s === "string") : [], + addr: typeof out.addr === "string" ? out.addr : null, + credential: out.credential, + }; + } + /** Send a message or a command to agents, groups, or everyone. */ async send(to: unknown, body: unknown, command: unknown) { if (!Array.isArray(to) || to.length === 0 || to.length > 50) throw new OpError(400, "to: one to fifty targets"); diff --git a/pm-stack/console/src/reads.ts b/pm-stack/console/src/reads.ts index d2d9f8adc9..ba073fde54 100644 --- a/pm-stack/console/src/reads.ts +++ b/pm-stack/console/src/reads.ts @@ -61,6 +61,11 @@ export async function platformRead( return ops.pipelineFeed(query); case "directory": return ops.directory(); + // The minted enroll tokens' state (#14376): the provisioning + // half of the Agents screen. Same story again — state only, + // never a hash or a value. + case "enroll-tokens": + return ops.enrollTokens(); case "trends": return trends ? trends.read(query.get("days"), fresh, query.get("end")) : undefined; } diff --git a/pm-stack/console/test/console.test.ts b/pm-stack/console/test/console.test.ts index d4bacaeb2b..bbe452a548 100644 --- a/pm-stack/console/test/console.test.ts +++ b/pm-stack/console/test/console.test.ts @@ -27,7 +27,7 @@ import { verifyJwt, } from "../src/auth.ts"; import { type Config, ConfigError, type Issuer, readConfig } from "../src/config.ts"; -import { HOLDABLE } from "../src/edge-proto.ts"; +import { HOLDABLE, subjectOf } from "../src/edge-proto.ts"; import { manageable, OpError, Ops, parseUnitFiles, parseUnits, type Run, triagePacket } from "../src/ops.ts"; import { assetLinks, type Deps, handle, releaseSaid } from "../src/server.ts"; @@ -828,6 +828,111 @@ describe("operations", () => { expect(r.calls.length).toBe(calls); }); + test("provisioning: a mint's value reaches the caller once and is kept nowhere", async () => { + // The bridge's answers, as fixtures: the values below are made up + // for this test, as everywhere in this suite. + const ENROLL_VALUE = "enroll-token-value-fixture"; + const CRED_VALUE = "credential-value-fixture"; + const r = recorder((argv) => { + if (argv[2] === "mint-enroll") { + return JSON.stringify({ + agent: "new-1", + kind: "muse", + groups: ["muse"], + notes_identity: "muse/new-1", + expires_at: "2026-11-25T00:00:00Z", + bootstrap_token: ENROLL_VALUE, + }); + } + if (argv[2] === "enroll-tokens") { + return JSON.stringify({ + enroll_tokens: [ + { agent: "new-1", kind: "muse", groups: ["muse"], notes_identity: "muse/new-1", created: "2026-11-24T00:00:00Z", expires_at: "2026-11-25T00:00:00Z", used_at: null, revoked_at: null, state: "pending" }, + ], + }); + } + if (argv[2] === "revoke-enroll") return JSON.stringify({ agent: "new-1", revoked: 1 }); + if (argv[2] === "mint-credential") { + return JSON.stringify({ agent: "pm-stack", scopes: ["send", "read"], addr: "service:pm-stack", credential: CRED_VALUE }); + } + return ""; + }); + const ops = new Ops(CFG, r.run); + const table = actions(ops, {} as never); + + // The enroll mint: the binding travels as flags, and the value + // comes back to the caller — the one screen that shows it. + const mint = (await table["agent.mint-enroll"].run({ + agent: "new-1", + kind: "muse", + groups: ["muse"], + notesIdentity: "muse/new-1", + ttlSeconds: 3600, + })) as { bootstrap_token: string; expires_at: string }; + expect(mint.bootstrap_token).toBe(ENROLL_VALUE); + expect(mint.expires_at).toBe("2026-11-25T00:00:00Z"); + expect(r.calls[0].argv).toEqual([ + "fleet", "bridge", "mint-enroll", "--agent", "new-1", "--kind", "muse", + "--groups", "muse", "--notes-identity", "muse/new-1", "--ttl", "3600", + ]); + // The audit record keeps the binding and nothing of the value, + // even when the value is handed to it in the args. + expect( + table["agent.mint-enroll"].audit({ + agent: "new-1", + kind: "muse", + groups: ["muse"], + notesIdentity: "muse/new-1", + ttlSeconds: 3600, + bootstrap_token: ENROLL_VALUE, + }), + ).toEqual({ agent: "new-1", kind: "muse", groups: ["muse"], notesIdentity: "muse/new-1", ttlSeconds: 3600 }); + // A mint is never held to be done late: its answer is the secret. + expect(HOLDABLE.has("agent.mint-enroll")).toBe(false); + expect(HOLDABLE.has("agent.mint-credential")).toBe(false); + + // After the mint, nothing the console can read holds the value: + // the state list is state only, and no call ever carried it. + const listed = await ops.enrollTokens(); + expect(JSON.stringify(listed)).not.toContain(ENROLL_VALUE); + for (const call of r.calls) { + expect(JSON.stringify(call.argv)).not.toContain(ENROLL_VALUE); + expect(call.stdin ?? "").not.toContain(ENROLL_VALUE); + } + + // The credential mint: same shape, scopes and the service binding + // checked here first. + const cred = (await table["agent.mint-credential"].run({ + agent: "pm-stack", + scopes: ["send", "read"], + addr: "service:pm-stack", + })) as { credential: string }; + expect(cred.credential).toBe(CRED_VALUE); + expect(r.calls.at(-1)?.argv).toEqual([ + "fleet", "bridge", "mint-credential", "--agent", "pm-stack", "--scopes", "send,read", "--addr", "service:pm-stack", + ]); + expect(table["agent.mint-credential"].audit({ agent: "pm-stack", scopes: ["send", "read"], addr: "service:pm-stack", credential: CRED_VALUE })).toEqual({ + agent: "pm-stack", + scopes: ["send", "read"], + addr: "service:pm-stack", + }); + const calls = r.calls.length; + await expect(table["agent.mint-credential"].run({ agent: "pm-stack", addr: "service:other" })).rejects.toThrow(OpError); + await expect(table["agent.mint-credential"].run({ agent: "pm-stack", scopes: ["root"] })).rejects.toThrow(OpError); + await expect(table["agent.mint-enroll"].run({ agent: "a b" })).rejects.toThrow(OpError); + await expect(table["agent.mint-enroll"].run({ agent: "new-1", ttlSeconds: 30 })).rejects.toThrow(OpError); + expect(r.calls.length).toBe(calls); + + // Taking tokens back is by agent name, carries no value, and — + // done late it is still the right act — is held for a machine. + const back = (await table["agent.revoke-enroll"].run({ agent: "new-1" })) as { revoked: number }; + expect(back.revoked).toBe(1); + expect(r.calls.at(-1)?.argv).toEqual(["fleet", "bridge", "revoke-enroll", "--agent", "new-1"]); + expect(table["agent.revoke-enroll"].audit({ agent: "new-1", bootstrap_token: ENROLL_VALUE })).toEqual({ agent: "new-1" }); + expect(HOLDABLE.has("agent.revoke-enroll")).toBe(true); + expect(subjectOf("agent.revoke-enroll", { agent: "new-1" })).toBe("enroll:new-1"); + }); + test("ranking an issue adds the new rank before it removes the others", async () => { const r = recorder((argv) => argv.includes("repos/developing-today/code/issues/12279") diff --git a/pm-stack/console/test/direct.test.ts b/pm-stack/console/test/direct.test.ts index bc085c3c53..663267fbb2 100644 --- a/pm-stack/console/test/direct.test.ts +++ b/pm-stack/console/test/direct.test.ts @@ -306,6 +306,17 @@ describe("the edge's run: the bridge through its binding", () => { await expect(h.run(["fleet", "bridge", "revoke", "--agent", "felix-1"])).rejects.toThrow(/needs a machine/); await expect(h.run(["fleet", "bridge", "revoke", "--identity", "muse/felix-1"])).rejects.toThrow(/needs a machine/); expect(h.calls).toHaveLength(3); + // The provisioning state list is a read of the same binding + // (#14376); the mints and the enroll revoke are machines' verbs, + // refused here like the revoke above. + h.answer.body = { enroll_tokens: [{ agent: "new-1", state: "pending" }] }; + const listed = await h.run(["fleet", "bridge", "enroll-tokens"]); + expect(h.calls[3].url).toBe("https://bridge.internal/fleet/pm-cred-test/enroll-tokens"); + expect(JSON.parse(listed.stdout)).toEqual({ enroll_tokens: [{ agent: "new-1", state: "pending" }] }); + await expect(h.run(["fleet", "bridge", "mint-enroll", "--agent", "new-1"])).rejects.toThrow(/needs a machine/); + await expect(h.run(["fleet", "bridge", "mint-credential", "--agent", "felix-1"])).rejects.toThrow(/needs a machine/); + await expect(h.run(["fleet", "bridge", "revoke-enroll", "--agent", "new-1"])).rejects.toThrow(/needs a machine/); + expect(h.calls).toHaveLength(4); }); test("the classes read the pipeline and the merged directory through the bridge, and cannot revoke there", async () => { @@ -335,6 +346,13 @@ describe("the edge's run: the bridge through its binding", () => { ], }; } + if (url.endsWith("/enroll-tokens")) { + return { + enroll_tokens: [ + { agent: "new-1", kind: "muse", groups: ["muse"], notes_identity: null, created: "2026-11-24T00:00:00Z", expires_at: "2026-11-25T00:00:00Z", used_at: null, revoked_at: null, state: "pending" }, + ], + }; + } throw new Error(`unexpected bridge fetch ${url}`); }; const bridgeFetch = (async (url: string) => ({ ok: true, status: 200, json: async () => byPath(String(url)) })) as unknown as Fetch; @@ -364,6 +382,14 @@ describe("the edge's run: the bridge through its binding", () => { expect(scout?.credential?.state).toBe("revoked"); // And a revoke asked of the edge's classes is a machine's. await expect(ops.revokeCredential("fleet", "felix-1")).rejects.toThrow(/needs a machine/); + // The enroll tokens' state is read through the bridge the same + // way (#14376), and taking tokens back is a machine's too. + const enrollTokens = (await ops.enrollTokens()) as { agent: string; state: string }[]; + expect(enrollTokens).toEqual([ + { agent: "new-1", kind: "muse", groups: ["muse"], notes_identity: null, created: "2026-11-24T00:00:00Z", expires_at: "2026-11-25T00:00:00Z", used_at: null, revoked_at: null, state: "pending" }, + ]); + await expect(ops.revokeEnrollTokens("new-1")).rejects.toThrow(/needs a machine/); + await expect(ops.mintEnrollToken({ agent: "new-2" })).rejects.toThrow(/needs a machine/); }); test("the agents section is read by the class that reads it on the laptop", async () => { diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index 1bfec2cd39..a67a57693b 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -692,6 +692,9 @@ async function setup(options: { direct?: boolean; kinds?: readonly string[]; bri const bridgeCredentials = [ { agent: "lane-1", state: "active", scopes: ["inbox", "send"], addr: null, credentials: 1, live: 1, created: "2026-11-24T00:00:00Z", revoked_at: null }, ]; + const bridgeEnrollTokens = [ + { agent: "new-1", kind: "muse", groups: ["muse"], notes_identity: null, created: "2026-11-24T00:00:00Z", expires_at: "2026-11-25T00:00:00Z", used_at: null, revoked_at: null, state: "pending" }, + ]; const bridgeRefuses = { on: false }; const bridgeFetch = (async ( url: string, @@ -719,6 +722,9 @@ async function setup(options: { direct?: boolean; kinds?: readonly string[]; bri if (method === "GET" && u.endsWith("/credentials")) { return { ok: true, status: 200, json: async () => ({ credentials: bridgeCredentials }) }; } + if (method === "GET" && u.endsWith("/enroll-tokens")) { + return { ok: true, status: 200, json: async () => ({ enroll_tokens: bridgeEnrollTokens }) }; + } throw new Error(`unexpected bridge fetch ${method} ${u}`); }) as never; /** The direct source, made to fail by a test that turns it on. */ @@ -3909,6 +3915,15 @@ describe("the edge does the core itself", () => { ]); expect(w.hostSaw).not.toContain("GET /console/api/pipeline?kind=command&sender=lane-1"); expect(w.hostSaw).not.toContain("GET /console/api/directory"); + // The provisioning read (#14376): the minted enroll tokens' + // state, read the same way — state only, no hash, no value. + const enrollTokens = (await (await w.browse("/console/api/enroll-tokens")).json()) as { agent: string; state: string }[]; + expect(enrollTokens).toEqual([ + { agent: "new-1", kind: "muse", groups: ["muse"], notes_identity: null, created: "2026-11-24T00:00:00Z", expires_at: "2026-11-25T00:00:00Z", used_at: null, revoked_at: null, state: "pending" }, + ]); + expect(w.bridgeCalls.at(-1)?.method).toBe("GET"); + expect(w.bridgeCalls.at(-1)?.url).toBe("https://bridge.internal/fleet/pm-cred-test/enroll-tokens"); + expect(w.hostSaw).not.toContain("GET /console/api/enroll-tokens"); // A revoke asked here is held for a machine — the edge's // credential holds the read scope only — and the bridge is not // asked for one. @@ -3916,8 +3931,18 @@ describe("the edge does the core itself", () => { const held = await w.act("agent.revoke", { surface: "fleet", name: "lane-1" }); expect(await held.json()).toEqual({ ok: true, held: true, result: null, waits: "machine" }); expect(w.bridgeCalls).toHaveLength(callsBefore); + // Taking back unused enroll tokens is held the same way (#14376). + const heldEnroll = await w.act("agent.revoke-enroll", { agent: "new-1" }); + expect(await heldEnroll.json()).toEqual({ ok: true, held: true, result: null, waits: "machine" }); + expect(w.bridgeCalls).toHaveLength(callsBefore); + // A mint is never held: its answer is the secret itself, shown + // once on the screen that asked — with no machine answering, it + // is refused, and the bridge is not asked for one either. + const mint = await w.act("agent.mint-enroll", { agent: "new-2", kind: "muse" }); + expect(((await mint.json()) as { held?: unknown }).held).not.toBe(true); + expect(w.bridgeCalls).toHaveLength(callsBefore); const machines = (await (await w.browse("/console/api/machines")).json()) as MachinesAnswer; - expect(machines.held.map((entry) => entry.kind)).toEqual(["agent.revoke"]); + expect(machines.held.map((entry) => entry.kind)).toEqual(["agent.revoke", "agent.revoke-enroll"]); }); test("a bridge credential the bridge no longer knows stops the send here, with the reason said", async () => { From 0bc58a967d6b0bd00d39838c4f1a71c1f8a94f25 Mon Sep 17 00:00:00 2001 From: felix Date: Tue, 24 Nov 2026 17:09:15 +0000 Subject: [PATCH 2/3] bridge S10 (#14376): fix enrollTokenListSql groups parse + align the credential-address mint refusal with the console views' 405 --- pkgs/message-bridge/worker/src/fleet.js | 2 +- pkgs/message-bridge/worker/test/provisioning.test.mjs | 7 +++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/pkgs/message-bridge/worker/src/fleet.js b/pkgs/message-bridge/worker/src/fleet.js index 9a37818f78..b0286fe55e 100644 --- a/pkgs/message-bridge/worker/src/fleet.js +++ b/pkgs/message-bridge/worker/src/fleet.js @@ -1277,7 +1277,7 @@ export function enrollTokenListSql(sql) { .map((r) => ({ agent: r.agent, kind: r.kind, - groups: parseJson(r.groups, []), + groups: JSON.parse(r.groups), notes_identity: r.notes_identity, created: r.created, expires_at: r.expires_at, diff --git a/pkgs/message-bridge/worker/test/provisioning.test.mjs b/pkgs/message-bridge/worker/test/provisioning.test.mjs index 11527c8bc2..37bad02e82 100644 --- a/pkgs/message-bridge/worker/test/provisioning.test.mjs +++ b/pkgs/message-bridge/worker/test/provisioning.test.mjs @@ -205,9 +205,12 @@ test("the read scope sees the same state list; plainer doors stay shut, and revo assert.equal((await h.call(`/fleet/${h.ft}/enroll-tokens`)).status, 404); assert.equal((await h.call(`/fleet/${"x".repeat(43)}/enroll-tokens`)).status, 404); - // Minting and revoking never open at the credential address. + // Minting and revoking never open at the credential address: the + // revoke path is no route there at all (404), and a mint POST meets + // the read view's method refusal — 405, as on every console view + // since #14374, whose method check precedes the credential check. assert.equal((await h.as(pm).revokeEnroll({ token_hash: "0".repeat(64) })).status, 404); - assert.equal((await h.post(`/fleet/${pm}/enroll-tokens`, { agent: "x-1" })).status, 404); + assert.equal((await h.post(`/fleet/${pm}/enroll-tokens`, { agent: "x-1" })).status, 405); }); test("the Durable Object's SQL folds the same states, hash-free (store parity)", async () => { From 5053555627b280a2f08b03654ced05901892b44b Mon Sep 17 00:00:00 2001 From: felix Date: Tue, 24 Nov 2026 17:20:16 +0000 Subject: [PATCH 3/3] bridge S10 (#14376): borrow the flag values split_list takes in mint-enroll/mint-credential --- pkgs/fleet/crates/fleet-bridge/src/lib.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkgs/fleet/crates/fleet-bridge/src/lib.rs b/pkgs/fleet/crates/fleet-bridge/src/lib.rs index 433f75eb9e..c98ae2b3ae 100644 --- a/pkgs/fleet/crates/fleet-bridge/src/lib.rs +++ b/pkgs/fleet/crates/fleet-bridge/src/lib.rs @@ -916,7 +916,7 @@ pub fn execute(ctx: &mut Ctx, args: &[String]) -> R { payload["kind"] = json!(kind); } if let Some(groups) = a.last("--groups") { - payload["groups"] = json!(split_list(groups)); + payload["groups"] = json!(split_list(&groups)); } if let Some(identity) = a.last("--notes-identity") { payload["notes_identity"] = json!(identity); @@ -968,7 +968,7 @@ pub fn execute(ctx: &mut Ctx, args: &[String]) -> R { .ok_or_else(|| usage("mint-credential needs --agent NAME"))?; let mut payload = json!({ "agent": agent }); if let Some(scopes) = a.last("--scopes") { - payload["scopes"] = json!(split_list(scopes)); + payload["scopes"] = json!(split_list(&scopes)); } if let Some(addr) = a.last("--addr") { payload["addr"] = json!(addr);