passcontrol 0.5.3 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,6 +24,8 @@ import {
24
24
  ok,
25
25
  redact,
26
26
  requireControlApiKey,
27
+ requireControlGateway,
28
+ requirePassportGateway,
27
29
  requirePassport,
28
30
  step,
29
31
  warn,
@@ -125,48 +127,64 @@ function cliCommand(args = "") {
125
127
 
126
128
  function usage() {
127
129
  const cmd = cliPrefix();
128
- return `${heading("PassControl")}
130
+ return `${heading(`PassControl ${CLI_VERSION}`)}
131
+ Governed identity and credentials for AI agents.
129
132
 
130
133
  ${heading("Usage:")}
131
134
  ${cmd} show cockpit status
132
- ${cmd} init [--global] create a config profile
133
- ${cmd} status [--no-network] show active config
135
+ ${cmd} <command> [options]
136
+
137
+ ${heading("Quick start")}
138
+ ${cmd} init [--global] configure this project
134
139
  ${cmd} start [--dashboard-only] start the whole local stack (dashboard + Supabase + Redis)
135
- ${cmd} stop [--dashboard-only] stop the whole local stack (dashboard + Supabase + Redis)
136
- ${cmd} restart restart the CLI-managed local dashboard
137
- ${cmd} local-logs [--follow] show local dashboard logs
138
- ${cmd} doctor [--deep] [--fix] check local setup and repair a stopped dashboard
139
- ${cmd} reset --local --confirm RESET
140
- destroy and recreate the local stack
141
- ${cmd} setup [--no-open] [--port-offset N] [--app-dir DIR]
142
- clone the app (if needed), start local services, open the dashboard
143
- --app-dir repoints the CLI and is remembered
144
- ${cmd} unlink forget the remembered app checkout
145
- ${cmd} try 60-second demo: governed keyless call + kill switch (no key)
146
- ${cmd} call "hi" mint a visa and call a model
140
+ ${cmd} open start if needed and open the Control Tower
141
+ ${cmd} try run the 60-second keyless guided demo
142
+
143
+ ${heading("Operate")}
144
+ ${cmd} status [--no-network] [--json]
145
+ show active config and instance state
146
+ ${cmd} doctor [--deep] [--fix] diagnose setup and repair a stopped dashboard
147
+ ${cmd} call "hi" mint a visa and make a governed model call
147
148
  ${cmd} sidecar [--port 8788] start the local agent bridge
148
- ${cmd} mcp start the local stdio MCP server
149
- ${cmd} configure <integration> [--write] [--force]
150
- set up an integration: previews the config, and
151
- --write creates it for aider|claude-desktop|cursor
152
- ${cmd} env [integration] print the same settings without writing anything
153
- (defaults to generic)
154
- <integration>: ${integrationChoices()}
155
- ${cmd} agent list list agents
149
+
150
+ ${heading("Manage")}
151
+ ${cmd} agent list [--json] list agents
156
152
  ${cmd} agent create <name> create an agent passport
153
+ ${cmd} agent rotate <id> [--grace <seconds>]
154
+ rotate locally and reveal the new secret once
157
155
  ${cmd} agent suspend <id> suspend an agent
158
156
  ${cmd} agent resume <id> resume an agent
159
- ${cmd} agent revoke <id> revoke an agent
160
- ${cmd} spend show fleet + per-agent spend
161
- ${cmd} audit [--limit 20] show admin audit trail
162
- ${cmd} logs [--limit 20] show gateway call logs
163
- ${cmd} kill on|off toggle tenant kill switch
164
- ${cmd} keygen instance generate the deployment's receipt-signing key
157
+ ${cmd} agent revoke <id> permanently revoke an agent
158
+ ${cmd} spend [--json] show fleet and per-agent spend
159
+ ${cmd} audit [--limit 20] [--json]
160
+ show operator audit history
161
+ ${cmd} logs [--limit 20] [--json]
162
+ show governed call logs
163
+ ${cmd} kill on|off toggle the tenant kill switch
164
+
165
+ ${heading("Integrate")}
166
+ ${cmd} env [integration] print settings without writing anything
167
+ ${cmd} configure <integration> [--write] [--force]
168
+ preview or write integration config
169
+ ${cmd} mcp start the stdio MCP server
170
+ integrations: ${integrationChoices()}
171
+
172
+ ${heading("Trust")}
173
+ ${cmd} keygen instance create the receipt-signing key
165
174
  ${cmd} verify receipt <jws> --issuer <origin>
166
- check a signed call receipt (no account needed)
175
+ verify a signed call receipt
167
176
  ${cmd} verify token <jwt> --audience <aud> --issuer <origin>
168
- check an agent-to-agent token
169
- ${cmd} open start (if needed) and open the dashboard
177
+ verify an agent-to-agent token
178
+
179
+ ${heading("Local stack")}
180
+ ${cmd} setup [--no-open] [--port-offset N] [--app-dir DIR]
181
+ clone if needed, start services, open dashboard
182
+ ${cmd} stop [--dashboard-only] stop the whole local stack (dashboard + Supabase + Redis)
183
+ ${cmd} restart restart the CLI-managed local dashboard
184
+ ${cmd} local-logs [--follow] show local dashboard logs
185
+ ${cmd} reset --local --confirm RESET
186
+ destroy and recreate the local stack
187
+ ${cmd} unlink forget the remembered app checkout
170
188
 
171
189
  ${heading("Config:")}
172
190
  Env vars win, then nearest .passcontrol, then ~/.config/passcontrol/config.
@@ -178,6 +196,30 @@ ${heading("Config:")}
178
196
  `;
179
197
  }
180
198
 
199
+ function agentUsage() {
200
+ const cmd = cliPrefix();
201
+ return `${heading("Manage agent passports")}
202
+
203
+ ${heading("Usage:")}
204
+ ${cmd} agent list
205
+ ${cmd} agent create <name> [--provider <provider>] [--scope <model-pattern>]
206
+ ${cmd} agent rotate <id> [--grace <seconds>]
207
+ ${cmd} agent suspend <id>
208
+ ${cmd} agent resume <id>
209
+ ${cmd} agent revoke <id>
210
+
211
+ ${heading("Examples")}
212
+ ${cmd} agent create prod-summarizer --provider anthropic --scope 'claude-*'
213
+ ${cmd} agent rotate <id> --grace 3600
214
+ ${cmd} agent suspend <id>
215
+
216
+ Create and rotate generate the Ed25519 private key on this machine. Only the
217
+ public key crosses the control API. The private key is shown once; store it
218
+ before leaving the command. During rotation grace, both old and new keys work.
219
+ Revocation is permanent; suspension is reversible.
220
+ `;
221
+ }
222
+
181
223
  function assertProvider(provider) {
182
224
  if (!PROVIDERS.includes(provider)) {
183
225
  throw new Error(`Unknown provider "${provider}". Use one of: ${PROVIDERS.join(", ")}.`);
@@ -211,34 +253,61 @@ async function gatewayStatus(noNetwork = false) {
211
253
  }
212
254
  }
213
255
 
214
- async function printCockpit({ noNetwork = false } = {}) {
256
+ async function printCockpit({ noNetwork = false, json = false } = {}) {
215
257
  const gateway = await gatewayStatus(noNetwork);
216
258
  const passportConfigured = Boolean(config.passportId && config.passportSecret);
217
259
  const adminConfigured = Boolean(config.apiKey);
260
+ const dashboard = dashboardStatusLabel(gateway, noNetwork);
261
+ const app = appRootLabel();
262
+ const configFile = configPathLabel(config.sources);
263
+
264
+ if (json) {
265
+ console.log(JSON.stringify({
266
+ version: CLI_VERSION,
267
+ gateway: { url: config.gateway, state: gateway.label, healthy: gateway.ok },
268
+ dashboard: { state: dashboard },
269
+ app: { state: app },
270
+ config: {
271
+ source: configFile,
272
+ provider: config.provider,
273
+ model: config.model,
274
+ passport_configured: passportConfigured,
275
+ control_api_key_configured: adminConfigured,
276
+ },
277
+ }, null, 2));
278
+ return;
279
+ }
218
280
 
219
281
  console.log(`${heading("PassControl")}\n`);
220
282
  console.log(formatLabel("Gateway", `${gateway.label} ${config.gateway}`));
221
- console.log(formatLabel("Dashboard", dashboardStatusLabel(gateway, noNetwork)));
222
- console.log(formatLabel("App", appRootLabel()));
223
- console.log(formatLabel("Config", configPathLabel(config.sources)));
283
+ console.log(formatLabel("Dashboard", dashboard));
284
+ console.log(formatLabel("App", app));
285
+ console.log(formatLabel("Config", configFile));
224
286
  console.log(formatLabel("Provider", config.provider));
225
287
  console.log(formatLabel("Model", config.model));
226
288
  console.log(formatLabel("Passport", passportConfigured ? redact(config.passportId) : "missing"));
227
289
  console.log(formatLabel("Admin key", adminConfigured ? redact(config.apiKey, 6) : "missing"));
228
290
  console.log(`${formatLabel("Sidecar", `foreground command (\`${cliCommand("sidecar")}\`)`)}\n`);
229
- console.log(heading("Next commands:"));
230
- console.log(` ${cliCommand("start")} start the local dashboard`);
231
- console.log(` ${cliCommand("stop")} stop the local dashboard`);
232
- console.log(` ${cliCommand("restart")} restart the local dashboard`);
233
- console.log(` ${cliCommand("local-logs --follow")} follow local dashboard logs`);
234
- console.log(` ${cliCommand("init")} configure this project`);
235
- console.log(` ${cliCommand('call "hi"')} test a governed model call`);
236
- console.log(` ${cliCommand("sidecar")} start the local agent bridge`);
237
- console.log(` ${cliCommand("agent list")} list agents`);
238
- console.log(` ${cliCommand("spend")} show fleet spend`);
239
- console.log(` ${cliCommand("env openhands")} print agent settings`);
240
- console.log(` ${cliCommand("doctor")} check setup`);
241
- console.log(` ${cliCommand("open")} open dashboard`);
291
+ const next = [];
292
+ if (config.sources.length === 0) {
293
+ next.push(["init", "configure this project"]);
294
+ }
295
+ if (gateway.ok === false) {
296
+ next.push(["start", "start the local control plane"]);
297
+ next.push(["doctor", "diagnose why the gateway is unavailable"]);
298
+ } else if (!passportConfigured) {
299
+ next.push(["agent create <name>", "issue a governed agent passport"]);
300
+ next.push(["open", "finish setup in the Control Tower"]);
301
+ } else {
302
+ next.push(['call "hi"', "test a governed model call"]);
303
+ next.push(["agent list", "inspect the configured fleet"]);
304
+ next.push(["open", "open the Control Tower"]);
305
+ }
306
+
307
+ console.log(heading("Next:"));
308
+ for (const [command, description] of next.slice(0, 3)) {
309
+ console.log(` ${cliCommand(command).padEnd(34)} ${description}`);
310
+ }
242
311
  }
243
312
 
244
313
  function appConfigDir(env = process.env) {
@@ -359,7 +428,10 @@ function checkDockerDaemon() {
359
428
  };
360
429
  }
361
430
  try {
362
- execFileSync("docker", ["info"], { stdio: "ignore" });
431
+ // Docker Desktop can leave its CLI socket present while the engine is
432
+ // wedged. A diagnostic command must report that state, not hang every
433
+ // onboarding/release check indefinitely.
434
+ execFileSync("docker", ["info"], { stdio: "ignore", timeout: 2_000 });
363
435
  return { ok: true, message: "Docker daemon: running." };
364
436
  } catch {
365
437
  return {
@@ -1039,12 +1111,17 @@ async function initCommand(opts) {
1039
1111
  }
1040
1112
  }
1041
1113
 
1114
+ // Destination first, passport second. The signature this produces is the
1115
+ // passport proving itself and carries no audience, so handing it to the wrong
1116
+ // host is the whole compromise — see `requirePassportGateway`. Validating here
1117
+ // covers every minting caller, `doctor --deep` and `try` included.
1042
1118
  async function mintVisa(current = config) {
1119
+ const origin = requirePassportGateway(current);
1043
1120
  const { passportId, passportSecret } = requirePassport(current);
1044
1121
  const payloadObj = { passport_id: passportId, ts: Date.now(), nonce: crypto.randomUUID() };
1045
1122
  const payload = b64url(new TextEncoder().encode(JSON.stringify(payloadObj)));
1046
1123
  const signature = b64url(ed25519.sign(fromB64url(payload), fromB64url(passportSecret)));
1047
- const res = await fetch(`${current.gateway}/api/auth/challenge`, {
1124
+ const res = await fetch(`${origin}/api/auth/challenge`, {
1048
1125
  method: "POST",
1049
1126
  headers: { "content-type": "application/json" },
1050
1127
  body: JSON.stringify({ payload, signature }),
@@ -1109,15 +1186,19 @@ async function callCommand(rest, opts) {
1109
1186
  assertProvider(provider);
1110
1187
  const model = activeModel(provider, opts);
1111
1188
  const prompt = rest.join(" ") || process.env.PROMPT || "Say hello in exactly 3 words.";
1189
+ // Before `requirePassport`, and before the banner: this line used to print
1190
+ // `config.gateway` verbatim, so `https://admin:hunter2@host` put the password
1191
+ // on the terminal and into any log scraping it.
1192
+ const origin = requirePassportGateway(config);
1112
1193
  requirePassport(config);
1113
- step(`${provider}/${model} via ${config.gateway}`);
1194
+ step(`${provider}/${model} via ${origin}`);
1114
1195
  step(`prompt: ${prompt}\n`);
1115
1196
 
1116
1197
  const { visa, expires_in } = await mintVisa(config);
1117
1198
  ok(`minted visa (expires in ${expires_in ?? 300}s)`);
1118
1199
 
1119
1200
  const { path: proxyPath, body } = requestFor(provider, model, prompt);
1120
- const res = await fetch(`${config.gateway}/api/v1/${provider}/${proxyPath}`, {
1201
+ const res = await fetch(`${origin}/api/v1/${provider}/${proxyPath}`, {
1121
1202
  method: "POST",
1122
1203
  headers: { "content-type": "application/json", authorization: `Bearer ${visa}` },
1123
1204
  body: JSON.stringify(body),
@@ -1132,7 +1213,9 @@ async function callCommand(rest, opts) {
1132
1213
  // keyless `demo` provider, then arms the kill switch to show the same call
1133
1214
  // blocked. Everything is real (visa, scope, budget, kill) except the model.
1134
1215
  async function tryCommand() {
1135
- const gateway = config.gateway;
1216
+ // Covers the demo proxy call AND the kill-switch PUT below, which builds its
1217
+ // own control-plane URL rather than going through the guarded `api()`.
1218
+ const gateway = requirePassportGateway(config);
1136
1219
  const demo = { gateway, passportId: DEMO_PASSPORT_ID, passportSecret: DEMO_PASSPORT_SECRET };
1137
1220
 
1138
1221
  const demoCall = async () => {
@@ -1204,7 +1287,7 @@ async function tryCommand() {
1204
1287
  const json = await res.json().catch(() => ({}));
1205
1288
  const text = json?.choices?.[0]?.message?.content ?? JSON.stringify(json);
1206
1289
  const usage = json?.usage ?? {};
1207
- ok("Governed keyless call succeeded — the passport signed a visa, the gateway enforced scope + budget, and no key was needed:");
1290
+ ok("Governed keyless call succeeded — the passport signed the challenge, the gateway issued a short-lived visa and enforced scope + budget, and no key was needed:");
1208
1291
  console.log(`\n ${text}\n`);
1209
1292
  step(`tokens: ${usage.total_tokens ?? "?"} (prompt ${usage.prompt_tokens ?? "?"} + completion ${usage.completion_tokens ?? "?"})`);
1210
1293
 
@@ -1230,8 +1313,13 @@ async function tryCommand() {
1230
1313
  }
1231
1314
 
1232
1315
  async function api(method, pathPart, body) {
1316
+ // Destination first, key second — same order and same reason as the SDK's
1317
+ // ControlClient. `config.gateway` is whatever PASSCONTROL_GATEWAY said, and
1318
+ // this is the one place a long-lived fleet-wide `pc_` key goes on the wire, so
1319
+ // the URL is built from the validated origin rather than from that string.
1320
+ const origin = requireControlGateway(config);
1233
1321
  const apiKey = requireControlApiKey(config);
1234
- const res = await fetch(`${config.gateway}/api/control/v1${pathPart}`, {
1322
+ const res = await fetch(`${origin}/api/control/v1${pathPart}`, {
1235
1323
  method,
1236
1324
  headers: {
1237
1325
  authorization: `Bearer ${apiKey}`,
@@ -1278,15 +1366,15 @@ async function agentCommand(rest, opts) {
1278
1366
  switch (sub) {
1279
1367
  case "list": {
1280
1368
  const agents = await api("GET", "/agents");
1281
- console.table(
1282
- agents.map((a) => ({
1369
+ const rows = agents.map((a) => ({
1283
1370
  id: a.id,
1284
1371
  name: a.name,
1285
1372
  status: a.status,
1286
1373
  tokens: a.spent_tokens,
1287
1374
  usd: a.spent_microcents === undefined ? undefined : usd(a.spent_microcents),
1288
- }))
1289
- );
1375
+ }));
1376
+ if (opts.json) console.log(JSON.stringify(rows, null, 2));
1377
+ else console.table(rows);
1290
1378
  break;
1291
1379
  }
1292
1380
  case "create": {
@@ -1322,13 +1410,57 @@ async function agentCommand(rest, opts) {
1322
1410
  if (!args[0]) throw new Error("Usage: passcontrol agent revoke <id>");
1323
1411
  console.log(await api("DELETE", `/agents/${encodeURIComponent(args[0])}`));
1324
1412
  break;
1413
+ // Retire this agent's key and install a new one, keeping the agent — its id,
1414
+ // budgets, audit history and receipts all stay put.
1415
+ //
1416
+ // The keypair is generated HERE, on the operator's machine, and only the
1417
+ // PUBLIC half is sent. That is the product: the gateway has never held a
1418
+ // passport private key and this command must not be the first thing to
1419
+ // change that.
1420
+ case "rotate": {
1421
+ if (!args[0]) {
1422
+ throw new Error("Usage: passcontrol agent rotate <id> [--grace <seconds>]");
1423
+ }
1424
+ const grace = opts.grace === undefined ? undefined : Number(opts.grace);
1425
+ if (grace !== undefined && (!Number.isFinite(grace) || grace < 0)) {
1426
+ throw new Error("--grace must be a non-negative number of seconds.");
1427
+ }
1428
+ const priv = ed25519.utils.randomPrivateKey();
1429
+ const passportId = b64url(ed25519.getPublicKey(priv));
1430
+ const result = await api("POST", `/agents/${encodeURIComponent(args[0])}/rotate`, {
1431
+ passportPubkey: passportId,
1432
+ ...(grace === undefined ? {} : { graceSeconds: grace }),
1433
+ });
1434
+
1435
+ ok(`rotated agent ${args[0]}`);
1436
+ // Printed BEFORE the deadline, and never written to a file. A rotation
1437
+ // that silently overwrote .passcontrol would destroy the only copy of the
1438
+ // key that is still working — mid-window, which is the outage the window
1439
+ // exists to prevent. The operator moves it deliberately.
1440
+ step("Store these - the secret is shown once and is the agent's new passport:");
1441
+ console.log(` PASSPORT_ID=${passportId}`);
1442
+ console.log(` PASSPORT_SECRET=${b64url(priv)}`);
1443
+ const until = result?.previous_valid_until;
1444
+ step(
1445
+ until
1446
+ ? `The OLD key keeps working until ${until}. Both keys authenticate until then — deploy the new one before it passes.`
1447
+ : "The old key stops working immediately."
1448
+ );
1449
+ break;
1450
+ }
1325
1451
  default:
1326
- throw new Error("Usage: passcontrol agent list|create <name>|suspend <id>|resume <id>|revoke <id>");
1452
+ throw new Error(
1453
+ "Usage: passcontrol agent list|create <name>|suspend <id>|resume <id>|revoke <id>|rotate <id> [--grace <seconds>]"
1454
+ );
1327
1455
  }
1328
1456
  }
1329
1457
 
1330
- async function spendCommand() {
1458
+ async function spendCommand(opts = {}) {
1331
1459
  const data = await api("GET", "/spend");
1460
+ if (opts.json) {
1461
+ console.log(JSON.stringify(data, null, 2));
1462
+ return;
1463
+ }
1332
1464
  console.log(`fleet: ${data.fleet.spent_tokens} tokens · ${usd(data.fleet.spent_microcents)}`);
1333
1465
  console.table(
1334
1466
  data.agents.map((agent) => ({
@@ -1342,6 +1474,10 @@ async function spendCommand() {
1342
1474
 
1343
1475
  async function auditCommand(opts) {
1344
1476
  const events = await api("GET", controlPath("/audit", { limit: safeLimit(opts.limit) }));
1477
+ if (opts.json) {
1478
+ console.log(JSON.stringify(events, null, 2));
1479
+ return;
1480
+ }
1345
1481
  console.table(
1346
1482
  events.map((event) => ({
1347
1483
  at: event.created_at,
@@ -1361,6 +1497,10 @@ async function logsCommand(opts) {
1361
1497
  status: opts.status,
1362
1498
  })
1363
1499
  );
1500
+ if (opts.json) {
1501
+ console.log(JSON.stringify(rows, null, 2));
1502
+ return;
1503
+ }
1364
1504
  console.table(
1365
1505
  rows.map((row) => {
1366
1506
  const input = typeof row.input_tokens === "number" && Number.isFinite(row.input_tokens)
@@ -1398,12 +1538,16 @@ async function sidecarCommand(rest, opts) {
1398
1538
  return;
1399
1539
  }
1400
1540
 
1541
+ // Validate before the passport is read and before the listener binds: the
1542
+ // sidecar mints on demand for the lifetime of the process, so a bad
1543
+ // destination has to be refused at start, not at the first proxied request.
1544
+ const gateway = requirePassportGateway(config);
1401
1545
  const { passportId, passportSecret } = requirePassport(config);
1402
1546
  startSidecar({
1403
- gateway: config.gateway,
1547
+ gateway,
1404
1548
  passportId,
1405
1549
  passportSecret,
1406
- port: Number(opts.port ?? process.env.SIDECAR_PORT ?? 8788),
1550
+ port: sidecarPort(opts),
1407
1551
  host: String(opts.host ?? process.env.SIDECAR_HOST ?? "127.0.0.1"),
1408
1552
  refreshSkewSeconds: Number(opts.refreshSkewSeconds ?? process.env.REFRESH_SKEW_SECONDS ?? 30),
1409
1553
  });
@@ -1415,21 +1559,31 @@ async function sidecarCommand(rest, opts) {
1415
1559
  }
1416
1560
 
1417
1561
  async function mcpCommand() {
1562
+ const gateway = requirePassportGateway(config);
1418
1563
  const { passportId, passportSecret } = requirePassport(config);
1419
1564
  const { startMcpServer } = await import("../cli/mcp/server.mjs");
1420
- await startMcpServer({ gateway: config.gateway, passportId, passportSecret });
1565
+ await startMcpServer({ gateway, passportId, passportSecret });
1566
+ }
1567
+
1568
+ function sidecarPort(opts = {}) {
1569
+ const port = Number(opts.port ?? process.env.SIDECAR_PORT ?? 8788);
1570
+ if (!Number.isInteger(port) || port < 1 || port > 65535) {
1571
+ throw new Error("--port must be an integer from 1 to 65535.");
1572
+ }
1573
+ return port;
1421
1574
  }
1422
1575
 
1423
1576
  function sidecarBaseUrl(opts = {}) {
1424
1577
  const provider = String(opts.provider || config.provider);
1425
1578
  assertProvider(provider);
1426
1579
  const host = String(opts.host ?? process.env.SIDECAR_HOST ?? "127.0.0.1");
1427
- const port = Number(opts.port ?? process.env.SIDECAR_PORT ?? 8788);
1580
+ const port = sidecarPort(opts);
1428
1581
  return {
1429
1582
  provider,
1430
1583
  model: activeModel(provider, opts),
1431
1584
  apiKey: "passcontrol",
1432
1585
  baseUrl: `http://${host}:${port}/api/v1/${provider}`,
1586
+ port,
1433
1587
  };
1434
1588
  }
1435
1589
 
@@ -1479,9 +1633,11 @@ function printAgentPreset(name = "generic", opts = {}) {
1479
1633
  return;
1480
1634
  }
1481
1635
 
1482
- const { provider, model, apiKey, baseUrl } = sidecarBaseUrl(opts);
1636
+ const { provider, model, apiKey, baseUrl, port } = sidecarBaseUrl(opts);
1483
1637
  const modelWithProvider = `${provider}/${model}`;
1484
- const sidecarStart = opts.port ? cliCommand(`sidecar --port ${opts.port}`) : cliCommand("sidecar");
1638
+ const sidecarStart = opts.port != null || process.env.SIDECAR_PORT != null
1639
+ ? cliCommand(`sidecar --port ${port}`)
1640
+ : cliCommand("sidecar");
1485
1641
 
1486
1642
  console.log(`# Start the bridge first: ${sidecarStart}`);
1487
1643
 
@@ -1497,6 +1653,16 @@ function printAgentPreset(name = "generic", opts = {}) {
1497
1653
  }
1498
1654
 
1499
1655
  switch (preset) {
1656
+ case "hermes":
1657
+ console.log("# Hermes Agent custom provider (verified against Hermes 0.18.2):");
1658
+ console.log("# Merge this model block into ~/.hermes/config.yaml:");
1659
+ console.log("model:");
1660
+ console.log(` default: ${JSON.stringify(model)}`);
1661
+ console.log(" provider: custom");
1662
+ console.log(` base_url: ${JSON.stringify(`${baseUrl}/v1`)}`);
1663
+ console.log(` api_key: ${JSON.stringify(apiKey)}`);
1664
+ console.log("# The placeholder key is stripped by the sidecar. Keep `passcontrol sidecar` running.");
1665
+ break;
1500
1666
  case "openhands":
1501
1667
  console.log("# OpenHands / LiteLLM-compatible starting point:");
1502
1668
  printExports([
@@ -1809,7 +1975,8 @@ async function main() {
1809
1975
  const [command, ...commandRest] = rest;
1810
1976
 
1811
1977
  if (opts.help || command === "help") {
1812
- console.log(usage());
1978
+ const target = command === "help" ? commandRest[0] : command;
1979
+ console.log(target === "agent" || target === "fleet" ? agentUsage() : usage());
1813
1980
  return;
1814
1981
  }
1815
1982
  if (opts.version || command === "version") {
@@ -1820,7 +1987,7 @@ async function main() {
1820
1987
  switch (command) {
1821
1988
  case undefined:
1822
1989
  case "status":
1823
- await printCockpit({ noNetwork: Boolean(opts.noNetwork) });
1990
+ await printCockpit({ noNetwork: Boolean(opts.noNetwork), json: Boolean(opts.json) });
1824
1991
  break;
1825
1992
  case "init":
1826
1993
  await initCommand(opts);
@@ -1872,7 +2039,7 @@ async function main() {
1872
2039
  await agentCommand(commandRest, opts);
1873
2040
  break;
1874
2041
  case "spend":
1875
- await spendCommand();
2042
+ await spendCommand(opts);
1876
2043
  break;
1877
2044
  case "audit":
1878
2045
  await auditCommand(opts);
package/cli/config.mjs CHANGED
@@ -253,6 +253,101 @@ export function requireControlApiKey(current = config) {
253
253
  return current.apiKey;
254
254
  }
255
255
 
256
+ /**
257
+ * The only hosts allowed to speak plain HTTP. Exact matches, never a prefix or
258
+ * suffix: `localhost.`, `localhost.example` and `127.0.0.1.attacker.example` are
259
+ * other people's hostnames. Compared against the parsed `hostname`, which the URL
260
+ * parser has already lowercased and canonicalised (`127.1` → `127.0.0.1`), so
261
+ * shorthand loopback spellings land here instead of slipping past a string test.
262
+ */
263
+ const LOOPBACK_HOSTNAMES = new Set(["localhost", "127.0.0.1", "[::1]"]);
264
+
265
+ /**
266
+ * Validate a gateway value and return the origin to build URLs from.
267
+ *
268
+ * A bare HTTPS origin — scheme, host, optional port — with no path beyond `/`,
269
+ * no query, fragment, username or password. HTTP only on loopback. The value is
270
+ * parsed and the result re-derived from `URL.origin`, so no path material
271
+ * survives into a request URL and `https://trusted.example@attacker.example`
272
+ * cannot pose as the host it imitates.
273
+ *
274
+ * **This is deliberately the same rule as `sdk/gateway.ts`'s
275
+ * `requireGatewayOrigin`, and deliberately a second implementation of it.** The
276
+ * SDK is TypeScript that only becomes JavaScript after `tsc`; `cli/` is plain
277
+ * .mjs run straight from the repository, so importing across that line works in
278
+ * the published package and breaks every CLI invocation in a checkout. The two
279
+ * are held in agreement by `tests/cli-control-gateway.test.ts`, which runs one
280
+ * table through both — if you change one, that test fails until you change both.
281
+ *
282
+ * Throws rather than `die`s: `bin/passcontrol.mjs` has a top-level handler that
283
+ * prints the message and exits 1, and `doctor` catches it to report a failed
284
+ * check instead of vanishing mid-diagnosis. The message never quotes the value,
285
+ * because a rejected gateway can itself carry credentials.
286
+ */
287
+ export function bareGatewayOrigin(gateway, label = "PASSCONTROL_GATEWAY") {
288
+ let url;
289
+ try {
290
+ url = new URL(String(gateway ?? ""));
291
+ } catch {
292
+ throw new Error(
293
+ `${label} must be an absolute URL (for example https://passcontrol.example.com).`
294
+ );
295
+ }
296
+ const loopback = LOOPBACK_HOSTNAMES.has(url.hostname);
297
+ if (
298
+ (url.protocol !== "https:" && !(loopback && url.protocol === "http:")) ||
299
+ url.username ||
300
+ url.password ||
301
+ url.search ||
302
+ url.hash ||
303
+ url.pathname !== "/"
304
+ ) {
305
+ throw new Error(
306
+ `${label} must be a bare HTTPS origin — scheme, host and optional port, with no path, ` +
307
+ "query, fragment or embedded credentials. Plain HTTP is accepted only for localhost, " +
308
+ "127.0.0.1 and [::1]. The configured value is refused and is not printed here, because " +
309
+ "a gateway URL can itself contain a credential."
310
+ );
311
+ }
312
+ return url.origin;
313
+ }
314
+
315
+ /**
316
+ * The gateway guard for the control plane, beside the key guard above.
317
+ *
318
+ * A `pc_` key is long-lived and manages the whole fleet, so where it is sent is
319
+ * part of the credential's security, not configuration taste. Every `api()` call
320
+ * resolves its destination through this, never through the raw config string.
321
+ */
322
+ export function requireControlGateway(current = config) {
323
+ assertConfigLoaded();
324
+ return bareGatewayOrigin(current.gateway);
325
+ }
326
+
327
+ /**
328
+ * The same guard for the passport paths — `call`, `try`, `doctor --deep`,
329
+ * `sidecar`, `mcp`.
330
+ *
331
+ * It exists as its own name because the two credentials fail differently, not
332
+ * because the rule differs: it is `bareGatewayOrigin` in both cases, so the two
333
+ * cannot drift. A `pc_` key is long-lived and manages the fleet; what travels
334
+ * here is an Ed25519 challenge signature and the short-lived visa minted from
335
+ * it. That signature is the passport proving itself, and
336
+ * `app/api/auth/challenge/route.ts` binds it to no audience — so a copy taken
337
+ * off the wire replays against the REAL gateway for as long as its `SKEW_MS`
338
+ * window allows, and mints a genuine visa carrying the agent's scope and budget.
339
+ *
340
+ * Which is why this must be called BEFORE the credentials are read, before the
341
+ * signature is computed, and before the destination is echoed to the terminal.
342
+ * Every caller resolves its URLs from the returned origin, never from
343
+ * `config.gateway`; `tests/cli-passport-gateway.test.ts` pins both the ordering
344
+ * and the absence of raw-string interpolation.
345
+ */
346
+ export function requirePassportGateway(current = config) {
347
+ assertConfigLoaded();
348
+ return bareGatewayOrigin(current.gateway);
349
+ }
350
+
256
351
  export function redact(value, keep = 4) {
257
352
  if (!value) return "missing";
258
353
  const s = String(value);
@@ -1,11 +1,9 @@
1
1
  import { decodeJwt } from "jose";
2
- import { OPENAI_SHAPE_PROVIDERS, formatProxyError } from "../config.mjs";
2
+ import { OPENAI_SHAPE_PROVIDERS, bareGatewayOrigin, formatProxyError } from "../config.mjs";
3
3
  import { createVisaClient } from "../visa-client.mjs";
4
4
 
5
5
  const DEFAULT_ANTHROPIC_MAX_TOKENS = 1024;
6
6
 
7
- const trimSlash = (value) => String(value ?? "").replace(/\/+$/, "");
8
-
9
7
  function requestFor({ provider, model, messages, max_tokens, temperature }) {
10
8
  if (provider === "anthropic") {
11
9
  const system = messages
@@ -110,7 +108,9 @@ export function createGatewayClient({
110
108
  randomUUID = () => globalThis.crypto.randomUUID(),
111
109
  refreshSkewSeconds = 30,
112
110
  }) {
113
- const baseUrl = trimSlash(gateway);
111
+ // `trimSlash` tidied a string; it never judged the destination. Every proxied
112
+ // call below carries a bearer visa, so the base is the validated origin.
113
+ const baseUrl = bareGatewayOrigin(gateway);
114
114
  const visas = createVisaClient({
115
115
  gateway: baseUrl,
116
116
  passportId,
package/cli/presets.mjs CHANGED
@@ -36,6 +36,7 @@ export const SIDECAR_PRESETS = [
36
36
  "openhands",
37
37
  "litellm",
38
38
  "aider",
39
+ "hermes",
39
40
  ...Object.keys(GUI_PRESET_LABELS),
40
41
  ];
41
42