passcontrol 0.4.0 โ†’ 0.5.1

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.
package/README.md CHANGED
@@ -38,10 +38,15 @@ PassControl removes the key from the agent entirely and puts a governed gateway
38
38
  - โ›” Layered, per-tenant kill switch + per-agent suspend
39
39
  - ๐Ÿ“’ Per-agent / per-passport audit trail (append-only; direct `UPDATE` / `DELETE` /
40
40
  `TRUNCATE` rejected by the database)
41
+ - ๐Ÿงพ Signed call receipts โ€” a governed call, allowed *or* blocked, is recorded in an
42
+ Ed25519-signed artifact anyone can check with `passcontrol verify receipt` (no account,
43
+ no access to your database), or by pasting it into `/verify/receipt` on your deployment
41
44
  - ๐Ÿงฐ Drop-in: point your existing OpenAI/Anthropic/OpenAI-compatible SDK at the gateway
42
45
  (OpenAI, Anthropic, Groq, Mistral, Together, DeepSeek)
43
46
  - ๐Ÿ”Œ MCP server: expose governed `chat` / `list_models` tools to Claude Desktop, Cursor &
44
47
  Claude Code โ€” same scope, budget, and kill switch (`passcontrol mcp`)
48
+ - ๐Ÿชช Agent passport page โ€” per-agent identity document: key-derived sigil, allowed scopes,
49
+ providers actually reached, budget state, exportable (redacted) PNG
45
50
  - ๐Ÿ–ฅ๏ธ Control Tower dashboard + a developer control-plane API + TOTP MFA
46
51
 
47
52
  ## Quickstart (self-host)
@@ -199,11 +204,20 @@ refused. Run `passcontrol env claude-desktop` to preview the config without writ
199
204
  - Instant revocation assumes Redis is configured for persistence/no-eviction behavior. If
200
205
  Redis evicts suspend/kill keys, enforcement falls back to short visa TTLs and durable agent
201
206
  status checks at the next mint.
207
+ - Receipts are best-effort: a signing failure never aborts a call, so the **absence** of a
208
+ receipt is not evidence a call did not happen. A receipt covers the request and the
209
+ gateway's decision โ€” not the provider's reply. Verifying one proves the named issuer signed
210
+ it, not that the issuer is honest; anyone can run PassControl.
211
+ - Receipts have **no expiry** and are checked against the keys a deployment publishes now, so
212
+ replacing `INSTANCE_SIGNING_KEY` invalidates every receipt ever signed. Move the old seed to
213
+ `INSTANCE_SIGNING_KEY_PREV` first โ€” it is never signed with; its public half stays published.
202
214
 
203
215
  ## Security
204
216
  Security is the point of this project, so please report issues privately rather than opening
205
- a public issue: **security@vertias.eu**. We'll acknowledge and work with you on a fix +
206
- disclosure timeline. Notes:
217
+ a public issue โ€” use GitHub's
218
+ **[private vulnerability reporting](https://github.com/Vertias3u/PassControl/security/advisories/new)**
219
+ (Security tab โ†’ "Report a vulnerability"). You'll get an acknowledgement and a fix +
220
+ disclosure timeline worked out with you. Notes:
207
221
  - It's **BYOK** โ€” your provider key lives encrypted in your own Supabase Vault; it's
208
222
  decrypted only in-flight and cached briefly (encrypted) in your own Redis.
209
223
  - It is **not yet independently audited.** If you find a hole, you're doing us a favor.
@@ -37,7 +37,20 @@ import {
37
37
  mcpServersDocument,
38
38
  writeMcpClientConfig,
39
39
  } from "../cli/mcp/integration.mjs";
40
+ import {
41
+ GUI_PRESET_LABELS,
42
+ integrationChoices,
43
+ isGuiPreset,
44
+ isIntegration,
45
+ supportsWrite,
46
+ } from "../cli/presets.mjs";
40
47
  import { startSidecar } from "../cli/sidecar.mjs";
48
+ import {
49
+ checkIssuerPublishesKey,
50
+ generateInstanceKey,
51
+ instanceKidFromSeed,
52
+ } from "../cli/instance-key.mjs";
53
+ import { FAILURE_REASONS, verifyAgentToken, verifyReceipt } from "../cli/verify.mjs";
41
54
 
42
55
  const b64url = (bytes) =>
43
56
  Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
@@ -118,7 +131,7 @@ ${heading("Usage:")}
118
131
  ${cmd} show cockpit status
119
132
  ${cmd} init [--global] create a config profile
120
133
  ${cmd} status [--no-network] show active config
121
- ${cmd} start start the configured local dashboard
134
+ ${cmd} start [--dashboard-only] start the whole local stack (dashboard + Supabase + Redis)
122
135
  ${cmd} stop [--dashboard-only] stop the whole local stack (dashboard + Supabase + Redis)
123
136
  ${cmd} restart restart the CLI-managed local dashboard
124
137
  ${cmd} local-logs [--follow] show local dashboard logs
@@ -133,11 +146,12 @@ ${heading("Usage:")}
133
146
  ${cmd} call "hi" mint a visa and call a model
134
147
  ${cmd} sidecar [--port 8788] start the local agent bridge
135
148
  ${cmd} mcp start the local stdio MCP server
136
- ${cmd} env [openhands] print sidecar settings for agents
137
- ${cmd} env claude-desktop|cursor|claude-code
138
- print secret-free MCP client settings
139
149
  ${cmd} configure <integration> [--write] [--force]
140
- preview or create a supported integration config
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()}
141
155
  ${cmd} agent list list agents
142
156
  ${cmd} agent create <name> create an agent passport
143
157
  ${cmd} agent suspend <id> suspend an agent
@@ -147,6 +161,11 @@ ${heading("Usage:")}
147
161
  ${cmd} audit [--limit 20] show admin audit trail
148
162
  ${cmd} logs [--limit 20] show gateway call logs
149
163
  ${cmd} kill on|off toggle tenant kill switch
164
+ ${cmd} keygen instance generate the deployment's receipt-signing key
165
+ ${cmd} verify receipt <jws> --issuer <origin>
166
+ check a signed call receipt (no account needed)
167
+ ${cmd} verify token <jwt> --audience <aud> --issuer <origin>
168
+ check an agent-to-agent token
150
169
  ${cmd} open start (if needed) and open the dashboard
151
170
 
152
171
  ${heading("Config:")}
@@ -459,11 +478,93 @@ async function ensureAppRoot({ clone = false, appDir, yes = false } = {}) {
459
478
  return appRoot;
460
479
  }
461
480
 
462
- function localComposeProjectName() {
481
+ // The Supabase project id setup baked into supabase/config.toml. Read it back
482
+ // rather than re-deriving it from the directory name and a --port-offset: the
483
+ // offset is a setup-time flag nobody passes again on `start`, and config.toml is
484
+ // what the Supabase CLI itself will use.
485
+ function localSupabaseProjectId() {
463
486
  const configPath = path.join(appRoot, "supabase", "config.toml");
464
487
  const configText = fs.existsSync(configPath) ? fs.readFileSync(configPath, "utf8") : "";
465
- const projectId = configText.match(/^project_id\s*=\s*"([^"]+)"\s*$/m)?.[1] ?? path.basename(appRoot);
466
- return `passcontrol_${projectId.replace(/[^A-Za-z0-9]/g, "_").toLowerCase()}`;
488
+ return configText.match(/^project_id\s*=\s*"([^"]+)"\s*$/m)?.[1] ?? path.basename(appRoot);
489
+ }
490
+
491
+ function localComposeProjectName() {
492
+ return `passcontrol_${localSupabaseProjectId().replace(/[^A-Za-z0-9]/g, "_").toLowerCase()}`;
493
+ }
494
+
495
+ // Same container filter scripts/dev-stack.sh uses to find the DB to migrate.
496
+ function localSupabaseIsRunning() {
497
+ try {
498
+ return Boolean(
499
+ execFileSync(
500
+ "docker",
501
+ ["ps", "-q", "--filter", `label=com.supabase.cli.project=${localSupabaseProjectId()}`, "--filter", "name=supabase_db"],
502
+ { encoding: "utf8" }
503
+ ).trim()
504
+ );
505
+ } catch {
506
+ return false;
507
+ }
508
+ }
509
+
510
+ // The port the dashboard will actually reach Redis on, read from the env file
511
+ // rather than assumed. `setup --port-offset N` moves SRH, and bringing compose
512
+ // up on the compose default while the app reads the offset port gives you a
513
+ // Redis that is up and unreachable โ€” every nonce, budget reservation and
514
+ // kill-switch read failing against a container that looks healthy in `docker ps`.
515
+ function localRedisPort() {
516
+ const compose = fs.readFileSync(path.join(appRoot, "docker", "compose.yml"), "utf8");
517
+ const fallback = Number(compose.match(/PASSCONTROL_SRH_PORT:-(\d+)/)?.[1] ?? 8079);
518
+ try {
519
+ const envText = fs.readFileSync(path.join(appRoot, ".env.docker"), "utf8");
520
+ const port = Number(new URL(envText.match(/^UPSTASH_REDIS_REST_URL=(.*)$/m)?.[1]?.trim()).port);
521
+ if (Number.isInteger(port) && port > 0 && port < 65536) return port;
522
+ } catch {
523
+ // An unreadable or malformed env file is reported by the caller's own
524
+ // configuration check; fall back rather than failing here.
525
+ }
526
+ return fallback;
527
+ }
528
+
529
+ // The other half of `passcontrol start`. `stop` takes the dashboard, Supabase and
530
+ // Redis down together; a start that raised only the dashboard left that pair
531
+ // asymmetric, and the result is worse than a plain failure โ€” the Control Tower
532
+ // comes back up and every page on it errors, because the Postgres it reads and
533
+ // the Redis holding the kill switch are both still stopped. Nothing on screen
534
+ // names the cause.
535
+ //
536
+ // Deliberately NOT `npm run dev:stack`. That script also rewrites .env.docker,
537
+ // applies every migration and seeds a dev user: first-run work that belongs to
538
+ // `setup`, and that would turn a routine restart into a schema event. `start`
539
+ // raises exactly what `stop` lowered, and nothing else.
540
+ async function startLocalServices() {
541
+ for (const check of [checkDockerInstalled(), checkDockerDaemon(), checkSupabaseInstalled()]) {
542
+ if (!check.ok) throw new Error(check.message);
543
+ }
544
+
545
+ if (localSupabaseIsRunning()) {
546
+ ok("Supabase already running");
547
+ } else {
548
+ step("Starting Supabase (Postgres, Vault, Auth)โ€ฆ");
549
+ // -x studio mirrors scripts/dev-stack.sh: Studio's image is flaky enough
550
+ // here to fail its health check and roll the whole stack back, and nothing
551
+ // depends on it โ€” PassControl ships its own dashboard.
552
+ await runLocalCommand("supabase", ["start", "-x", "studio"]);
553
+ ok("Supabase running");
554
+ }
555
+
556
+ const redisPort = localRedisPort();
557
+ if (await portIsListening(redisPort)) {
558
+ ok(`Redis already running on port ${redisPort}`);
559
+ } else {
560
+ step("Starting Redisโ€ฆ");
561
+ await runLocalCommand("docker", ["compose", "-f", "docker/compose.yml", "up", "-d"], {
562
+ ...process.env,
563
+ COMPOSE_PROJECT_NAME: localComposeProjectName(),
564
+ PASSCONTROL_SRH_PORT: String(redisPort),
565
+ });
566
+ ok(`Redis running on port ${redisPort}`);
567
+ }
467
568
  }
468
569
 
469
570
  function localDashboard() {
@@ -620,9 +721,23 @@ async function runLocalPrerequisiteChecks({ offset = 0, report = false, enforce
620
721
  return results;
621
722
  }
622
723
 
724
+ // `passcontrol start` โ€” one command for "start PassControl", the mirror of what
725
+ // `stop` already does. The configuration check and the services come BEFORE the
726
+ // gateway health check on purpose: "the dashboard is answering" is not the same
727
+ // claim as "PassControl is up", and returning early on it is how you end up with
728
+ // a Control Tower talking to a stopped database.
623
729
  async function startDashboard(opts = {}) {
624
730
  await ensureAppRoot({ clone: true, appDir: opts.appDir, yes: opts.yes });
625
731
  const dashboard = localDashboard();
732
+
733
+ const envFile = path.join(appRoot, ".env.docker");
734
+ if (!fs.existsSync(envFile)) {
735
+ throw new Error(`Local stack is not configured. Run \`${cliCommand("setup")}\` in ${appRoot} first.`);
736
+ }
737
+
738
+ if (opts.dashboardOnly) step("Leaving Supabase and Redis alone (--dashboard-only).");
739
+ else await startLocalServices();
740
+
626
741
  if ((await gatewayStatus(false)).ok) {
627
742
  ok(`dashboard already online at ${dashboard.url}`);
628
743
  return dashboard;
@@ -638,11 +753,6 @@ async function startDashboard(opts = {}) {
638
753
  throw new Error(`CLI-managed dashboard (PID ${running.pid}) did not become ready. See ${running.logPath}.`);
639
754
  }
640
755
 
641
- const envFile = path.join(appRoot, ".env.docker");
642
- if (!fs.existsSync(envFile)) {
643
- throw new Error(`Local stack is not configured. Run \`${cliCommand("setup")}\` in ${appRoot} first.`);
644
- }
645
-
646
756
  const statePath = dashboardStatePath();
647
757
  const logPath = dashboardLogPath();
648
758
  fs.mkdirSync(path.dirname(statePath), { recursive: true, mode: 0o700 });
@@ -871,7 +981,10 @@ async function setupLocal(opts = {}) {
871
981
  ...process.env,
872
982
  PASSCONTROL_PORT_OFFSET: String(offset),
873
983
  });
874
- await startDashboard(opts);
984
+ // dev:stack has just brought Supabase and Redis up (and would have exited
985
+ // non-zero if it hadn't), so skip start's own service pass rather than print
986
+ // two "already running" lines under a banner that just said the stack is up.
987
+ await startDashboard({ ...opts, dashboardOnly: true });
875
988
  if (!opts.noOpen) await openDashboard(opts);
876
989
  console.log(`\n${formatLabel("Local dashboard", dashboard.url, 19)}`);
877
990
  console.log(formatLabel("Login", "the account you created during setup", 19));
@@ -1371,6 +1484,18 @@ function printAgentPreset(name = "generic", opts = {}) {
1371
1484
  const sidecarStart = opts.port ? cliCommand(`sidecar --port ${opts.port}`) : cliCommand("sidecar");
1372
1485
 
1373
1486
  console.log(`# Start the bridge first: ${sidecarStart}`);
1487
+
1488
+ // Desktop / GUI clients: there is nothing to export, you type these into a
1489
+ // settings form. The API-key field is required by the UI but ignored by the
1490
+ // sidecar โ€” that is the point. It is where your real provider key used to go.
1491
+ if (isGuiPreset(preset)) {
1492
+ console.log(`# ${GUI_PRESET_LABELS[preset]} settings:`);
1493
+ console.log(`Base URL: ${baseUrl}`);
1494
+ console.log(`API key: ${apiKey}`);
1495
+ console.log(`Model: ${modelWithProvider}`);
1496
+ return;
1497
+ }
1498
+
1374
1499
  switch (preset) {
1375
1500
  case "openhands":
1376
1501
  console.log("# OpenHands / LiteLLM-compatible starting point:");
@@ -1396,13 +1521,6 @@ function printAgentPreset(name = "generic", opts = {}) {
1396
1521
  ["AIDER_MODEL", modelWithProvider],
1397
1522
  ]);
1398
1523
  break;
1399
- case "cline":
1400
- case "continue":
1401
- console.log(`# ${preset} UI settings:`);
1402
- console.log(`Base URL: ${baseUrl}`);
1403
- console.log(`API key: ${apiKey}`);
1404
- console.log(`Model: ${modelWithProvider}`);
1405
- break;
1406
1524
  case "generic":
1407
1525
  console.log("# Generic sidecar settings:");
1408
1526
  printExports([
@@ -1412,9 +1530,7 @@ function printAgentPreset(name = "generic", opts = {}) {
1412
1530
  ]);
1413
1531
  break;
1414
1532
  default:
1415
- throw new Error(
1416
- "Usage: passcontrol env [generic|openhands|litellm|aider|cline|continue|claude-desktop|cursor|claude-code]"
1417
- );
1533
+ throw new Error(`Usage: passcontrol env <${integrationChoices()}>`);
1418
1534
  }
1419
1535
  }
1420
1536
 
@@ -1433,6 +1549,14 @@ function aiderConfig(opts = {}) {
1433
1549
  function configureMcpClient(integration, opts = {}) {
1434
1550
  requireGlobalMcpPassport();
1435
1551
  if (integration === "claude-code") {
1552
+ // Claude Code owns its MCP registry through its own CLI, so there is no
1553
+ // config file for us to merge into. `--write` used to be accepted here and
1554
+ // silently do nothing โ€” refuse it and hand back the command that works.
1555
+ if (opts.write) {
1556
+ throw new Error(
1557
+ `Claude Code manages MCP servers through its own CLI, so there is no file to write. Run:\n ${CLAUDE_CODE_ADD_COMMAND}`
1558
+ );
1559
+ }
1436
1560
  console.log("Claude Code manages MCP servers through its CLI. Run:");
1437
1561
  console.log(CLAUDE_CODE_ADD_COMMAND);
1438
1562
  return;
@@ -1460,14 +1584,19 @@ async function configureCommand(rest, opts = {}) {
1460
1584
  const integration = String(rest[0] ?? "").toLowerCase();
1461
1585
  if (!integration) {
1462
1586
  throw new Error(
1463
- "Usage: passcontrol configure <aider|cline|continue|openhands|claude-desktop|cursor|claude-code> [--write] [--force]"
1587
+ `Usage: passcontrol configure <${integrationChoices()}> [--write] [--force]`
1588
+ );
1589
+ }
1590
+ if (!isIntegration(integration)) {
1591
+ throw new Error(
1592
+ `Unknown integration "${integration}". Use one of: ${integrationChoices()}.`
1464
1593
  );
1465
1594
  }
1466
1595
  if (isMcpIntegration(integration)) {
1467
1596
  configureMcpClient(integration, opts);
1468
1597
  return;
1469
1598
  }
1470
- if (integration !== "aider") {
1599
+ if (!supportsWrite(integration)) {
1471
1600
  if (opts.write) throw new Error(`${integration} configuration is UI- or project-schema-specific; no file was written. Use the preview below.`);
1472
1601
  printAgentPreset(integration, opts);
1473
1602
  step("This integration is configured manually from the settings shown above. Aider is the current file-writing integration.");
@@ -1545,6 +1674,114 @@ async function doctorCommand(opts = {}) {
1545
1674
  } else {
1546
1675
  step("Skipping control API check: no PASSCONTROL_API_KEY configured.");
1547
1676
  }
1677
+
1678
+ await checkInstanceSigningKey();
1679
+ }
1680
+
1681
+ // Receipts and agent tokens are signed by a key the DEPLOYMENT owns. A missing
1682
+ // key is loud (nothing is signed), but a PASSCONTROL_ISSUER pointing somewhere
1683
+ // that does not serve this deployment's JWKS fails silently: every receipt then
1684
+ // carries an `iss` whose key set cannot verify it. Check it explicitly.
1685
+ async function checkInstanceSigningKey() {
1686
+ const seed = process.env.INSTANCE_SIGNING_KEY;
1687
+ const issuer = process.env.PASSCONTROL_ISSUER;
1688
+
1689
+ if (!seed) {
1690
+ step(
1691
+ "Instance signing key not set in this shell โ€” receipts and agent tokens are disabled " +
1692
+ `(run \`${cliCommand("keygen instance")}\` to create one).`
1693
+ );
1694
+ return;
1695
+ }
1696
+
1697
+ let kid;
1698
+ try {
1699
+ kid = instanceKidFromSeed(seed);
1700
+ } catch {
1701
+ fail("INSTANCE_SIGNING_KEY is set but is not a valid 32-byte base64url seed.");
1702
+ return;
1703
+ }
1704
+ ok(`Instance signing key configured (kid ${kid})`);
1705
+
1706
+ if (!issuer) {
1707
+ fail("PASSCONTROL_ISSUER is not set โ€” receipts would be signed with no verifiable issuer.");
1708
+ return;
1709
+ }
1710
+
1711
+ const result = await checkIssuerPublishesKey({ issuer, kid });
1712
+ (result.ok ? ok : fail)(`Issuer check: ${result.reason}`);
1713
+ }
1714
+
1715
+ // `passcontrol verify` needs no config, no passport, and no API key โ€” it is the
1716
+ // one command a stranger runs against someone else's deployment.
1717
+ async function verifyCommand(rest, opts) {
1718
+ const what = rest[0];
1719
+ const artifact = rest[1];
1720
+ const issuer = String(opts.issuer || process.env.PASSCONTROL_ISSUER || "");
1721
+
1722
+ if ((what !== "token" && what !== "receipt") || !artifact) {
1723
+ throw new Error(
1724
+ "Usage: passcontrol verify token <jwt> --audience <aud> --issuer <origin>\n" +
1725
+ " passcontrol verify receipt <jws> --issuer <origin>"
1726
+ );
1727
+ }
1728
+ if (!issuer) {
1729
+ throw new Error(
1730
+ "Set --issuer <https origin> (or PASSCONTROL_ISSUER). A verifier that trusts " +
1731
+ "whatever issuer the artifact names is not verifying anything."
1732
+ );
1733
+ }
1734
+
1735
+ const result =
1736
+ what === "token"
1737
+ ? await verifyAgentToken(artifact, { issuer, audience: String(opts.audience || "") })
1738
+ : await verifyReceipt(artifact, { issuer });
1739
+
1740
+ if (!result.ok) {
1741
+ fail(`Not valid: ${FAILURE_REASONS[result.reason] ?? result.reason}`);
1742
+ process.exitCode = 1;
1743
+ return;
1744
+ }
1745
+
1746
+ const c = result.claims;
1747
+ ok(what === "token" ? "Token is valid." : "Receipt is valid.");
1748
+ step(`Issuer: ${c.iss}`);
1749
+ step(`Passport: ${c.sub}`);
1750
+ if (what === "token") {
1751
+ step(`Audience: ${c.aud}`);
1752
+ step(`Expires: ${new Date(c.exp * 1000).toISOString()}`);
1753
+ } else {
1754
+ step(`Call: ${c.mth} ${c.path} โ†’ ${c.prov}${c.mdl ? `/${c.mdl}` : ""}`);
1755
+ step(`Verdict: ${c.res?.status} (HTTP ${c.res?.http})`);
1756
+ step(`Usage: ${c.use?.in ?? 0} in / ${c.use?.out ?? 0} out ยท ${c.cost ?? 0} ยตยข`);
1757
+ if (c.req) step(`Request: ${c.req.alg} ${c.req.dig} (${c.req.len} bytes)`);
1758
+ }
1759
+ if (c.own) {
1760
+ step(
1761
+ `Owner: ${c.own.sub} (${c.own.tier === "unverified" ? "self-declared, unverified" : c.own.tier})`
1762
+ );
1763
+ }
1764
+ }
1765
+
1766
+ async function keygenCommand(rest) {
1767
+ const target = rest[0];
1768
+ if (target !== "instance") {
1769
+ throw new Error(`Usage: ${cliCommand("keygen instance")}`);
1770
+ }
1771
+
1772
+ const { seed, kid } = generateInstanceKey();
1773
+ ok("Generated an Ed25519 instance signing key.");
1774
+ step("This key signs call receipts and agent-to-agent tokens. Store the seed like a password:");
1775
+ console.log(` INSTANCE_SIGNING_KEY=${seed}`);
1776
+ console.log("");
1777
+ step(`Its public half publishes at /.well-known/jwks.json as kid ${kid}.`);
1778
+ step("Also set PASSCONTROL_ISSUER to this deployment's https origin โ€” it becomes the");
1779
+ step("`iss` claim, and the origin other deployments use to find this one's JWKS.");
1780
+ step("");
1781
+ step("Rotating? Move the current value to INSTANCE_SIGNING_KEY_PREV and keep it there.");
1782
+ step("Unlike VISA_SECRET_PREV we never sign with it โ€” its public key stays published so");
1783
+ step("receipts signed before the rotation still verify. Publish the new key, wait one");
1784
+ step("JWKS max-age window, then start signing with it.");
1548
1785
  }
1549
1786
 
1550
1787
  async function openDashboard(opts = {}) {
@@ -1649,6 +1886,12 @@ async function main() {
1649
1886
  case "open":
1650
1887
  await openDashboard(opts);
1651
1888
  break;
1889
+ case "keygen":
1890
+ await keygenCommand(commandRest);
1891
+ break;
1892
+ case "verify":
1893
+ await verifyCommand(commandRest, opts);
1894
+ break;
1652
1895
  default:
1653
1896
  throw new Error(`Unknown command "${command}". Run \`passcontrol help\`.`);
1654
1897
  }
package/cli/config.mjs CHANGED
@@ -1,8 +1,21 @@
1
1
  import fs from "node:fs";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
4
5
 
5
6
  export const CONFIG_FILE = ".passcontrol";
7
+
8
+ // The version the shipped CLI reports. Read from the installed package.json rather
9
+ // than typed anywhere โ€” the MCP server used to carry its own literal and was still
10
+ // announcing 0.2.0 to clients at 0.4.0.
11
+ export const PACKAGE_VERSION = (() => {
12
+ try {
13
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
14
+ return JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")).version ?? "0.0.0";
15
+ } catch {
16
+ return "0.0.0";
17
+ }
18
+ })();
6
19
  export const PROVIDERS = ["openai", "anthropic", "groq", "mistral", "together", "deepseek"];
7
20
  export const OPENAI_SHAPE_PROVIDERS = new Set(["openai", "groq", "mistral", "together", "deepseek"]);
8
21
 
@@ -0,0 +1,60 @@
1
+ // Operator-side helpers for the deployment's Ed25519 signing key.
2
+ //
3
+ // The app half lives in lib/crypto/instanceKey.ts. This is the plain-ESM twin
4
+ // the CLI uses to GENERATE a key and to check that a running deployment
5
+ // actually publishes it. The kid derivation is duplicated rather than imported
6
+ // because the shipped CLI is deliberately transpilation-free โ€” so
7
+ // cli/__tests__/instance-key.test.mjs pins the two derivations to agree.
8
+ import { ed25519 } from "@noble/curves/ed25519";
9
+ import { sha256 } from "@noble/hashes/sha256";
10
+
11
+ const b64url = (bytes) =>
12
+ Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
13
+
14
+ const fromB64url = (value) =>
15
+ new Uint8Array(Buffer.from(String(value).replace(/-/g, "+").replace(/_/g, "/"), "base64"));
16
+
17
+ /** RFC 7638 JWK thumbprint โ€” the same value the app publishes as `kid`. */
18
+ export function instanceKidFromSeed(seed) {
19
+ const publicKey = ed25519.getPublicKey(fromB64url(seed));
20
+ const x = b64url(publicKey);
21
+ return b64url(sha256(new TextEncoder().encode(`{"crv":"Ed25519","kty":"OKP","x":"${x}"}`)));
22
+ }
23
+
24
+ /** Generate a fresh instance signing key. The seed is printed once, never stored. */
25
+ export function generateInstanceKey() {
26
+ const seed = b64url(ed25519.utils.randomPrivateKey());
27
+ return { seed, kid: instanceKidFromSeed(seed) };
28
+ }
29
+
30
+ /**
31
+ * Verify that PASSCONTROL_ISSUER resolves to a deployment publishing OUR key.
32
+ *
33
+ * A missing signing key is loud โ€” nothing gets signed. The quiet failure is an
34
+ * issuer pointing at a host that serves a different key set (or none): every
35
+ * receipt then carries an `iss` whose JWKS cannot verify it, so third-party
36
+ * verification fails universally while the gateway itself looks perfectly
37
+ * healthy. This is the check that makes a self-hosted deployment debuggable
38
+ * without reading someone else's logs.
39
+ */
40
+ export async function checkIssuerPublishesKey({ issuer, kid, fetch: fetchImpl = fetch }) {
41
+ const url = new URL("/.well-known/jwks.json", issuer).toString();
42
+ let payload;
43
+ try {
44
+ const res = await fetchImpl(url);
45
+ if (!res.ok) return { ok: false, reason: `${url} responded ${res.status}` };
46
+ payload = await res.json();
47
+ } catch (error) {
48
+ return { ok: false, reason: `${url} is unreachable (${error.message})` };
49
+ }
50
+
51
+ const keys = Array.isArray(payload?.keys) ? payload.keys : [];
52
+ if (keys.length === 0) return { ok: false, reason: `${url} publishes no keys` };
53
+ if (!keys.some((key) => key?.kid === kid)) {
54
+ return {
55
+ ok: false,
56
+ reason: `${url} does not publish the key this deployment signs with (${kid})`,
57
+ };
58
+ }
59
+ return { ok: true, reason: `${url} publishes ${kid}` };
60
+ }
@@ -1,7 +1,7 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
3
3
  import { z } from "zod/v4";
4
- import { PROVIDERS } from "../config.mjs";
4
+ import { PACKAGE_VERSION, PROVIDERS } from "../config.mjs";
5
5
  import { createGatewayClient } from "./gateway.mjs";
6
6
 
7
7
  const messageSchema = z.object({
@@ -30,7 +30,7 @@ function toolError(error) {
30
30
  export function createMcpServer(options) {
31
31
  const gateway = createGatewayClient(options);
32
32
  const server = new McpServer(
33
- { name: "passcontrol", version: "0.2.0" },
33
+ { name: "passcontrol", version: PACKAGE_VERSION },
34
34
  {
35
35
  instructions:
36
36
  "Use chat for governed model calls through PassControl. Every chat call is subject to the configured passport's scope, budget, and kill switches.",
@@ -0,0 +1,67 @@
1
+ import { MCP_INTEGRATIONS } from "./mcp/integration.mjs";
2
+
3
+ // Single source of truth for the integrations `passcontrol env` and
4
+ // `passcontrol configure` accept. Both commands' usage strings are GENERATED
5
+ // from these lists rather than typed, because they drifted once already: the
6
+ // `configure` usage advertised seven presets while `printAgentPreset` handled
7
+ // nine, so `passcontrol configure litellm` worked but was documented as invalid.
8
+
9
+ /**
10
+ * Clients configured by typing a base URL into a settings form rather than by
11
+ * exporting environment variables. They all take the same three fields, so the
12
+ * value here is the display name โ€” the preset body is identical for every one.
13
+ *
14
+ * These are the desktop chat apps people already keep their raw provider key
15
+ * in. Pointing one at the sidecar means the app holds a passport-minted visa
16
+ * instead, and never sees the key.
17
+ */
18
+ export const GUI_PRESET_LABELS = {
19
+ cline: "Cline",
20
+ continue: "Continue",
21
+ chatbox: "Chatbox",
22
+ jan: "Jan",
23
+ msty: "Msty",
24
+ "cherry-studio": "Cherry Studio",
25
+ "open-webui": "Open WebUI",
26
+ librechat: "LibreChat",
27
+ };
28
+
29
+ export function isGuiPreset(name) {
30
+ return Object.hasOwn(GUI_PRESET_LABELS, String(name ?? "").toLowerCase());
31
+ }
32
+
33
+ /** Presets that print settings pointing an agent at the local sidecar bridge. */
34
+ export const SIDECAR_PRESETS = [
35
+ "generic",
36
+ "openhands",
37
+ "litellm",
38
+ "aider",
39
+ ...Object.keys(GUI_PRESET_LABELS),
40
+ ];
41
+
42
+ /** MCP client targets. Shares the set the MCP config writer dispatches on. */
43
+ export const MCP_PRESETS = [...MCP_INTEGRATIONS];
44
+
45
+ /** Everything both commands accept. */
46
+ export const INTEGRATIONS = [...SIDECAR_PRESETS, ...MCP_PRESETS];
47
+
48
+ /**
49
+ * Integrations where `configure --write` actually writes a file. Everything else
50
+ * is UI- or project-schema-specific (or, for claude-code, owned by that client's
51
+ * own CLI), so `--write` is refused with the real instruction instead of being
52
+ * accepted and silently doing nothing.
53
+ */
54
+ export const WRITABLE_INTEGRATIONS = ["aider", "claude-desktop", "cursor"];
55
+
56
+ export function isIntegration(name) {
57
+ return INTEGRATIONS.includes(String(name ?? "").toLowerCase());
58
+ }
59
+
60
+ export function supportsWrite(name) {
61
+ return WRITABLE_INTEGRATIONS.includes(String(name ?? "").toLowerCase());
62
+ }
63
+
64
+ /** `generic|openhands|โ€ฆ` โ€” for usage strings, so they can never drift again. */
65
+ export function integrationChoices() {
66
+ return INTEGRATIONS.join("|");
67
+ }
package/cli/sidecar.mjs CHANGED
@@ -4,6 +4,21 @@ import { fail, ok, step } from "./config.mjs";
4
4
  import { createVisaClient } from "./visa-client.mjs";
5
5
 
6
6
  const STRIP_REQ = new Set(["authorization", "x-api-key", "host", "content-length", "accept-encoding", "connection"]);
7
+
8
+ // The set above is a denylist over header NAMES, and a denylist over names loses
9
+ // to spelling. A client that was previously configured with a raw provider key
10
+ // sends it as whatever its vendor chose: `x-api-key` (Anthropic), `api-key`
11
+ // (Azure style), `openai-api-key`, `x-goog-api-key`, or `proxy-authorization`.
12
+ // Only the first was named, so the rest reached the gateway verbatim. The
13
+ // gateway builds its upstream headers from scratch and never forwarded them on,
14
+ // so no key ever reached a provider โ€” but it had no business leaving the user's
15
+ // machine at all, since not sending the key IS the sidecar.
16
+ const CREDENTIAL_HEADER = /(^|[-_])(api[-_]?key|authorization|auth|token|secret|credentials?)$/i;
17
+
18
+ function isStripped(name) {
19
+ const key = name.toLowerCase();
20
+ return STRIP_REQ.has(key) || CREDENTIAL_HEADER.test(key);
21
+ }
7
22
  const STRIP_RES = new Set(["content-encoding", "content-length", "transfer-encoding", "connection"]);
8
23
 
9
24
  export function createSidecar({ gateway, passportId, passportSecret, port = 8788, host = "127.0.0.1", refreshSkewSeconds = 30 }) {
@@ -27,7 +42,7 @@ export function createSidecar({ gateway, passportId, passportSecret, port = 8788
27
42
  async function fetchUpstream(req, body, visa) {
28
43
  const headers = {};
29
44
  for (const [k, v] of Object.entries(req.headers)) {
30
- if (!STRIP_REQ.has(k.toLowerCase()) && typeof v === "string") headers[k] = v;
45
+ if (!isStripped(k) && typeof v === "string") headers[k] = v;
31
46
  }
32
47
  headers["authorization"] = `Bearer ${visa}`;
33
48
  headers["accept-encoding"] = "identity";
package/cli/verify.mjs ADDED
@@ -0,0 +1,120 @@
1
+ // Offline verification of what a PassControl deployment signs.
2
+ //
3
+ // The plain-ESM twin of sdk/verify.ts, for `passcontrol verify`. Duplicated
4
+ // rather than imported because the shipped CLI is transpilation-free; the tests
5
+ // pin the two implementations to agree on the cases that matter.
6
+ //
7
+ // Nothing here needs a PassControl account, an API key, or a passport. You need
8
+ // the artifact and the issuer's origin. That is the whole point.
9
+ import { ed25519 } from "@noble/curves/ed25519";
10
+
11
+ export const RECEIPT_TYP = "passcontrol-receipt+jwt";
12
+ export const AGENT_TOKEN_TYP = "passcontrol-agent+jwt";
13
+ export const SUPPORTED_VER = 1;
14
+
15
+ const fromB64url = (value) =>
16
+ new Uint8Array(Buffer.from(String(value).replace(/-/g, "+").replace(/_/g, "/"), "base64"));
17
+
18
+ const decodeJson = (segment) => JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
19
+
20
+ /**
21
+ * Exact match after stripping a trailing slash. Prefix or suffix matching is
22
+ * the classic issuer-confusion bug โ€” `https://good.com.evil.com` and
23
+ * `https://evil.com/?x=https://good.com` must both fail.
24
+ */
25
+ export function matchesIssuer(iss, trusted) {
26
+ const strip = (v) => String(v).replace(/\/+$/, "");
27
+ return trusted.some((candidate) => strip(candidate) === strip(iss));
28
+ }
29
+
30
+ async function loadJwks(issuer, fetchImpl) {
31
+ try {
32
+ const res = await fetchImpl(new URL("/.well-known/jwks.json", issuer).toString());
33
+ if (!res.ok) return null;
34
+ const body = await res.json();
35
+ return Array.isArray(body?.keys) ? body.keys : [];
36
+ } catch {
37
+ return null;
38
+ }
39
+ }
40
+
41
+ async function verifySigned(token, typ, { issuer, fetch: fetchImpl = fetch }) {
42
+ const parts = String(token).split(".");
43
+ if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) {
44
+ return { ok: false, reason: "malformed" };
45
+ }
46
+
47
+ let header;
48
+ let claims;
49
+ try {
50
+ header = decodeJson(parts[0]);
51
+ claims = decodeJson(parts[1]);
52
+ } catch {
53
+ return { ok: false, reason: "malformed" };
54
+ }
55
+
56
+ // EdDSA is pinned, never read from the token. A verifier that dispatches on
57
+ // the token's own `alg` accepts alg:"none" and accepts an HS256 MAC keyed on
58
+ // the public key it just fetched โ€” which is public, so anyone can compute it.
59
+ if (header?.alg !== "EdDSA") return { ok: false, reason: "bad_signature" };
60
+ if (header?.typ !== typ) return { ok: false, reason: "wrong_type" };
61
+ if (!claims?.iss || !matchesIssuer(claims.iss, [issuer])) {
62
+ return { ok: false, reason: "untrusted_issuer" };
63
+ }
64
+ if (Number(claims.ver ?? 0) > SUPPORTED_VER) return { ok: false, reason: "unsupported_version" };
65
+
66
+ const keys = await loadJwks(claims.iss, fetchImpl);
67
+ if (!keys) return { ok: false, reason: "jwks_unreachable" };
68
+
69
+ const candidates = keys.filter(
70
+ (key) =>
71
+ key?.kty === "OKP" &&
72
+ key?.crv === "Ed25519" &&
73
+ typeof key.x === "string" &&
74
+ (!header.kid || !key.kid || key.kid === header.kid)
75
+ );
76
+ if (candidates.length === 0) return { ok: false, reason: "unknown_key" };
77
+
78
+ const signature = fromB64url(parts[2]);
79
+ const signed = new TextEncoder().encode(`${parts[0]}.${parts[1]}`);
80
+ for (const key of candidates) {
81
+ try {
82
+ if (ed25519.verify(signature, signed, fromB64url(key.x))) return { ok: true, claims };
83
+ } catch {
84
+ // A malformed JWK entry must not abort verification against the others.
85
+ }
86
+ }
87
+ return { ok: false, reason: "bad_signature" };
88
+ }
89
+
90
+ export function verifyReceipt(jws, options) {
91
+ return verifySigned(jws, RECEIPT_TYP, options);
92
+ }
93
+
94
+ export async function verifyAgentToken(token, options) {
95
+ const { audience, now = () => Date.now() } = options;
96
+ if (!audience) return { ok: false, reason: "wrong_audience" };
97
+
98
+ const result = await verifySigned(token, AGENT_TOKEN_TYP, options);
99
+ if (!result.ok) return result;
100
+
101
+ if (result.claims.aud !== audience) return { ok: false, reason: "wrong_audience" };
102
+ const seconds = Math.floor(now() / 1000);
103
+ if (typeof result.claims.exp !== "number" || result.claims.exp <= seconds) {
104
+ return { ok: false, reason: "expired" };
105
+ }
106
+ return result;
107
+ }
108
+
109
+ /** Human-readable one-liners. Kept here so the CLI and its tests agree on wording. */
110
+ export const FAILURE_REASONS = {
111
+ malformed: "not a compact JWS",
112
+ bad_signature: "signature does not verify against the issuer's published key",
113
+ wrong_type: "this artifact is a different type than the one you asked to verify",
114
+ untrusted_issuer: "the issuer in the artifact is not the one you named",
115
+ unknown_key: "the issuer does not publish the key this was signed with",
116
+ jwks_unreachable: "could not fetch the issuer's key set",
117
+ unsupported_version: "signed by a newer PassControl than this CLI understands",
118
+ wrong_audience: "minted for a different audience",
119
+ expired: "expired",
120
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "passcontrol",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Secure Agent Control Plane & Passport Vault โ€” identity-aware reverse proxy for AI agent credentials.",
5
5
  "license": "BUSL-1.1",
6
6
  "homepage": "https://github.com/Vertias3u/PassControl#readme",
@@ -58,7 +58,7 @@
58
58
  },
59
59
  "dependencies": {
60
60
  "@base-ui/react": "^1.5.0",
61
- "@modelcontextprotocol/sdk": "^1.29.0",
61
+ "@modelcontextprotocol/sdk": "^1.30.0",
62
62
  "@noble/curves": "^1.6.0",
63
63
  "@noble/hashes": "^1.5.0",
64
64
  "@sentry/nextjs": "^10.64.0",
@@ -83,9 +83,14 @@
83
83
  "@types/node": "^22.5.5",
84
84
  "@types/react": "^18.3.8",
85
85
  "@types/react-dom": "^18.3.0",
86
- "postcss": "^8.5.15",
86
+ "postcss": "^8.5.24",
87
87
  "tailwindcss": "^4.3.1",
88
88
  "typescript": "^5.6.2",
89
89
  "vitest": "^4.1.9"
90
+ },
91
+ "overrides": {
92
+ "postcss": "$postcss",
93
+ "sharp": "^0.35.3",
94
+ "@hono/node-server": "^2.0.5"
90
95
  }
91
96
  }