passcontrol 0.3.0 โ†’ 0.5.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.
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)
@@ -49,10 +54,21 @@ Stack: **Next.js** (App Router, edge routes) ยท **Supabase** (Postgres + Vault +
49
54
  **Upstash Redis**. Deploy on Vercel or any Node host (`next start`). No Vercel-proprietary
50
55
  services are required โ€” the kill switch is Redis-backed.
51
56
 
52
- ### Try it in 60 seconds (no key, no signup)
53
- The lowest-friction way to see what PassControl does โ€” a **governed AI call and a live
54
- kill switch, with no provider key and no account**. Enable demo mode when you bring the
55
- local stack up:
57
+ ### See it work in 60 seconds โ€” nothing to install
58
+
59
+ **[passcontrol.vertias.eu](https://passcontrol.vertias.eu)** โ€” no signup, no provider key,
60
+ no clone. Run a governed AI call, arm the kill switch, run the same call again, and watch
61
+ it get blocked at the gateway.
62
+
63
+ That demo runs the **real** pipeline โ€” passport โ†’ work-visa โ†’ scope + budget checks โ†’ kill
64
+ switch. Only the model response is synthesized, by a keyless `demo` provider that never
65
+ touches the Vault.
66
+
67
+ ### Prove it on your own machine (`passcontrol try`)
68
+
69
+ Same story, your hardware, still no provider key and no account. This one is a real local
70
+ install โ€” **prereqs: Docker Desktop and the Supabase CLI**, and the first stack boot takes
71
+ a few minutes:
56
72
 
57
73
  ```bash
58
74
  git clone https://github.com/<you>/passcontrol && cd passcontrol
@@ -62,35 +78,34 @@ PASSCONTROL_DEMO=1 npm run dev:docker & # run the gateway with demo mode on
62
78
  npx passcontrol try # governed call โ†’ arm kill switch โ†’ blocked โ†’ disarm
63
79
  ```
64
80
 
65
- `passcontrol try` runs the **real** pipeline (passport โ†’ work-visa โ†’ scope + budget
66
- checks), returns a synthesized `[demo]` response instead of calling a provider, then arms
67
- the kill switch and shows the same call get blocked โ€” the whole PassControl story in one
68
- command. Demo mode is **off by default and must never be enabled in production**: the
69
- keyless `demo` provider is env-gated and never touches the Vault. Ready to use it for
70
- real? Continue with the full quickstart below.
81
+ `passcontrol try` runs the real pipeline end-to-end and shows the same call blocked after
82
+ the kill switch fires โ€” the whole PassControl story in one command, verified on your own
83
+ stack. Demo mode is **off by default and must never be enabled in production**: the keyless
84
+ `demo` provider is env-gated and never touches the Vault. Ready to use it for real?
85
+ Continue with the full quickstart below.
71
86
 
72
87
  ### Local (Docker) quickstart
73
88
  For the fastest local run, use the bundled Docker stack. It starts Supabase locally
74
89
  (Postgres + Vault + Auth), Redis-over-REST, applies migrations inside the DB container, and
75
- seeds a confirmed dev user. Prereqs: Docker Desktop and the Supabase CLI. No host `psql`
76
- is required.
90
+ prompts you to create your Control Tower account. Prereqs: Docker Desktop and the Supabase
91
+ CLI. No host `psql` is required.
77
92
 
78
93
  ```bash
79
94
  git clone https://github.com/<you>/passcontrol && cd passcontrol
80
95
  npm install
81
- npm run dev:stack # starts Supabase + Redis locally, migrates, seeds a dev user
96
+ npm run dev:stack # starts Supabase + Redis locally, migrates, creates your account
82
97
  npm run dev:docker # runs the app against the local stack (loads .env.docker)
83
98
  ```
84
99
 
85
100
  > Use **`npm run dev:docker`**, not `npm run dev`, for the local stack โ€” plain `npm run
86
101
  > dev` loads `.env.local` (your hosted Supabase), not the Docker stack's `.env.docker`.
87
102
 
88
- Open `http://localhost:3000` and log in with:
103
+ During `dev:stack` you're asked to choose an account email and password โ€” that account
104
+ guards the provider keys in your local Vault, so pick a real password. Open
105
+ `http://localhost:3000` and log in with it.
89
106
 
90
- ```text
91
- dev@passcontrol.local
92
- passcontrol-dev
93
- ```
107
+ > No shared default credentials ship. If the stack was brought up without a terminal
108
+ > attached (CI, piped output), a password is generated and printed once by the seed step.
94
109
 
95
110
  Then add a provider key in the Control Tower, issue a passport, and run:
96
111
 
@@ -102,6 +117,12 @@ node examples/chat-agent.mjs "Say hello in 3 words"
102
117
  The final agent call uses your real Anthropic/OpenAI key from the local Vault, so start
103
118
  with a non-critical key.
104
119
 
120
+ > **Installed globally?** The stack lives in a checkout of this repo, not in the npm
121
+ > package, and the CLI remembers which one in `~/.config/passcontrol/app.json`. That file
122
+ > outlives `npm uninstall -g`, so a fresh install can keep pointing at an old directory.
123
+ > `passcontrol status` shows where the current path came from; `passcontrol unlink` forgets
124
+ > it, and `passcontrol setup --app-dir <path>` repoints.
125
+
105
126
  ### Manual self-host quickstart
106
127
 
107
128
  > **Supabase specifically** (not vanilla Postgres): the credential vault uses the
@@ -183,11 +204,20 @@ refused. Run `passcontrol env claude-desktop` to preview the config without writ
183
204
  - Instant revocation assumes Redis is configured for persistence/no-eviction behavior. If
184
205
  Redis evicts suspend/kill keys, enforcement falls back to short visa TTLs and durable agent
185
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.
186
214
 
187
215
  ## Security
188
216
  Security is the point of this project, so please report issues privately rather than opening
189
- a public issue: **security@vertias.eu**. We'll acknowledge and work with you on a fix +
190
- 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:
191
221
  - It's **BYOK** โ€” your provider key lives encrypted in your own Supabase Vault; it's
192
222
  decrypted only in-flight and cached briefly (encrypted) in your own Redis.
193
223
  - It is **not yet independently audited.** If you find a hole, you're doing us a favor.
@@ -26,6 +26,7 @@ import {
26
26
  requireControlApiKey,
27
27
  requirePassport,
28
28
  step,
29
+ warn,
29
30
  writeConfigFile,
30
31
  } from "../cli/config.mjs";
31
32
  import {
@@ -36,7 +37,20 @@ import {
36
37
  mcpServersDocument,
37
38
  writeMcpClientConfig,
38
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";
39
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";
40
54
 
41
55
  const b64url = (bytes) =>
42
56
  Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
@@ -118,7 +132,7 @@ ${heading("Usage:")}
118
132
  ${cmd} init [--global] create a config profile
119
133
  ${cmd} status [--no-network] show active config
120
134
  ${cmd} start start the configured local dashboard
121
- ${cmd} stop stop the CLI-managed local dashboard
135
+ ${cmd} stop [--dashboard-only] stop the whole local stack (dashboard + Supabase + Redis)
122
136
  ${cmd} restart restart the CLI-managed local dashboard
123
137
  ${cmd} local-logs [--follow] show local dashboard logs
124
138
  ${cmd} doctor [--deep] [--fix] check local setup and repair a stopped dashboard
@@ -126,15 +140,18 @@ ${heading("Usage:")}
126
140
  destroy and recreate the local stack
127
141
  ${cmd} setup [--no-open] [--port-offset N] [--app-dir DIR]
128
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
129
145
  ${cmd} try 60-second demo: governed keyless call + kill switch (no key)
130
146
  ${cmd} call "hi" mint a visa and call a model
131
147
  ${cmd} sidecar [--port 8788] start the local agent bridge
132
148
  ${cmd} mcp start the local stdio MCP server
133
- ${cmd} env [openhands] print sidecar settings for agents
134
- ${cmd} env claude-desktop|cursor|claude-code
135
- print secret-free MCP client settings
136
149
  ${cmd} configure <integration> [--write] [--force]
137
- 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()}
138
155
  ${cmd} agent list list agents
139
156
  ${cmd} agent create <name> create an agent passport
140
157
  ${cmd} agent suspend <id> suspend an agent
@@ -144,12 +161,20 @@ ${heading("Usage:")}
144
161
  ${cmd} audit [--limit 20] show admin audit trail
145
162
  ${cmd} logs [--limit 20] show gateway call logs
146
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
147
169
  ${cmd} open start (if needed) and open the dashboard
148
170
 
149
171
  ${heading("Config:")}
150
172
  Env vars win, then nearest .passcontrol, then ~/.config/passcontrol/config.
151
173
  Installed globally, the local-stack commands (setup/start/reset) use a cloned
152
- app checkout; override its location with PASSCONTROL_APP_ROOT.
174
+ app checkout, resolved in this order:
175
+ --app-dir DIR โ†’ PASSCONTROL_APP_ROOT โ†’ surrounding checkout โ†’ remembered
176
+ checkout in ~/.config/passcontrol/app.json (survives npm uninstall; clear
177
+ it with \`${cmd} unlink\`).
153
178
  `;
154
179
  }
155
180
 
@@ -259,31 +284,50 @@ function saveAppRoot(dir) {
259
284
  fs.writeFileSync(statePath, `${JSON.stringify({ path: dir, savedAt: new Date().toISOString() })}\n`, { mode: 0o600 });
260
285
  }
261
286
 
287
+ function forgetAppRoot() {
288
+ const saved = readSavedAppRoot();
289
+ fs.rmSync(appRootStatePath(), { force: true });
290
+ return saved;
291
+ }
292
+
262
293
  // Precedence: explicit env override โ†’ the surrounding checkout (npm run cli --) โ†’
263
- // a previously cloned/saved checkout. Returns null when the CLI is installed
264
- // globally and no stack has been set up yet.
265
- function resolveAppRoot() {
294
+ // a previously cloned/saved checkout. (An explicit --app-dir outranks all three;
295
+ // ensureAppRoot applies it before consulting this.) Returns null when the CLI is
296
+ // installed globally and no stack has been set up yet. `source` exists so status
297
+ // can say where the path came from โ€” a saved root that outlives the checkout it
298
+ // points at is invisible otherwise, which reads as the CLI ignoring the user.
299
+ function resolveAppRootSource() {
266
300
  const envRoot = process.env.PASSCONTROL_APP_ROOT?.trim();
267
301
  if (envRoot) {
268
302
  const abs = path.resolve(envRoot);
269
303
  if (!isRepoCheckout(abs)) {
270
304
  throw new Error(`PASSCONTROL_APP_ROOT=${envRoot} is not a PassControl checkout (missing scripts/dev-stack.sh).`);
271
305
  }
272
- return abs;
306
+ return { path: abs, source: "PASSCONTROL_APP_ROOT" };
307
+ }
308
+ if (process.env.PASSCONTROL_FORCE_INSTALLED !== "1" && isRepoCheckout(PACKAGE_ROOT)) {
309
+ return { path: PACKAGE_ROOT, source: "surrounding checkout" };
273
310
  }
274
- if (process.env.PASSCONTROL_FORCE_INSTALLED !== "1" && isRepoCheckout(PACKAGE_ROOT)) return PACKAGE_ROOT;
275
311
  const saved = readSavedAppRoot();
276
- if (saved && isRepoCheckout(saved)) return path.resolve(saved);
312
+ if (saved && isRepoCheckout(saved)) {
313
+ return { path: path.resolve(saved), source: `saved โ€” \`${cliCommand("unlink")}\` to clear` };
314
+ }
277
315
  return null;
278
316
  }
279
317
 
318
+ function resolveAppRoot() {
319
+ return resolveAppRootSource()?.path ?? null;
320
+ }
321
+
280
322
  function defaultAppDir() {
281
323
  return path.join(os.homedir(), "passcontrol");
282
324
  }
283
325
 
284
326
  function appRootLabel() {
285
327
  try {
286
- return resolveAppRoot() ?? `not set up (run \`${cliCommand("setup")}\`)`;
328
+ const resolved = resolveAppRootSource();
329
+ if (!resolved) return `not set up (run \`${cliCommand("setup")}\`)`;
330
+ return `${resolved.path} (${resolved.source})`;
287
331
  } catch (error) {
288
332
  return error.message;
289
333
  }
@@ -364,15 +408,35 @@ async function confirmYes(question) {
364
408
  // installed globally. `clone: false` never clones โ€” it errors with a pointer to
365
409
  // `passcontrol setup` (used by reset/doctor, where there's nothing yet to act on).
366
410
  async function ensureAppRoot({ clone = false, appDir, yes = false } = {}) {
367
- if (appRoot) return appRoot;
368
- const resolved = resolveAppRoot();
369
- if (resolved) {
370
- appRoot = resolved;
411
+ // An explicit --app-dir is the strongest signal there is and must outrank a
412
+ // saved checkout. It used to lose: resolveAppRoot() ran first, so a stale
413
+ // ~/.config/passcontrol/app.json (which survives `npm uninstall -g`) meant
414
+ // `setup --app-dir NEW` silently kept using the old directory, with no error
415
+ // and no way to repoint short of deleting an undocumented state file.
416
+ // parseArgv yields `true` for a valueless --app-dir; path.resolve(true) would
417
+ // throw a raw TypeError that reads as a crash rather than a usage mistake.
418
+ if (appDir !== undefined && typeof appDir !== "string") {
419
+ throw new Error(`--app-dir needs a directory path, e.g. \`${cliCommand("setup --app-dir ~/passcontrol")}\`.`);
420
+ }
421
+ const explicit = appDir ? path.resolve(appDir) : null;
422
+ if (explicit && isRepoCheckout(explicit)) {
423
+ saveAppRoot(explicit);
424
+ appRoot = explicit;
371
425
  return appRoot;
372
426
  }
427
+ if (appRoot) return appRoot;
428
+ if (!explicit) {
429
+ const resolved = resolveAppRoot();
430
+ if (resolved) {
431
+ appRoot = resolved;
432
+ return appRoot;
433
+ }
434
+ }
373
435
  if (!clone) {
374
436
  throw new Error(
375
- `No PassControl app checkout found. Run \`${cliCommand("setup")}\` to clone and start it, or set PASSCONTROL_APP_ROOT to an existing checkout.`
437
+ explicit
438
+ ? `--app-dir ${appDir} is not a PassControl checkout (missing scripts/dev-stack.sh).`
439
+ : `No PassControl app checkout found. Run \`${cliCommand("setup")}\` to clone and start it, or set PASSCONTROL_APP_ROOT to an existing checkout.`
376
440
  );
377
441
  }
378
442
 
@@ -383,7 +447,9 @@ async function ensureAppRoot({ clone = false, appDir, yes = false } = {}) {
383
447
  );
384
448
  }
385
449
 
386
- const target = path.resolve(appDir || (interactive ? await promptLine(`Where should the PassControl app be cloned? [${defaultAppDir()}] `, defaultAppDir()) : defaultAppDir()));
450
+ const target =
451
+ explicit ??
452
+ path.resolve(interactive ? await promptLine(`Where should the PassControl app be cloned? [${defaultAppDir()}] `, defaultAppDir()) : defaultAppDir());
387
453
  if (fs.existsSync(target) && fs.readdirSync(target).length) {
388
454
  if (isRepoCheckout(target)) {
389
455
  saveAppRoot(target);
@@ -652,6 +718,68 @@ async function stopDashboard() {
652
718
  ok(`stopped CLI-managed dashboard (PID ${state.pid})`);
653
719
  }
654
720
 
721
+ // `passcontrol stop` โ€” one command for "stop PassControl". Previously this halted
722
+ // only the CLI-managed dashboard, so a developer still had to remember
723
+ // `supabase stop` and a `docker compose` invocation in the right directory to
724
+ // actually free the ports and the RAM.
725
+ //
726
+ // Deliberately NON-DESTRUCTIVE: it stops containers but never removes volumes, so
727
+ // the Vault, passports, and audit log survive. Wiping local data stays with
728
+ // `passcontrol reset --local --confirm RESET`, which asks before it deletes.
729
+ async function stopCommand(opts = {}) {
730
+ await stopDashboard();
731
+
732
+ if (opts.dashboardOnly) {
733
+ step("Left Supabase and Redis running (--dashboard-only).");
734
+ return;
735
+ }
736
+
737
+ let root;
738
+ try {
739
+ root = resolveAppRoot();
740
+ } catch (error) {
741
+ // A bad PASSCONTROL_APP_ROOT shouldn't turn "stop" into a failure โ€” the
742
+ // dashboard is already down, which is most of what was asked for.
743
+ step(error.message);
744
+ return;
745
+ }
746
+ if (!root) {
747
+ step(`No local stack checkout found โ€” nothing else to stop (\`${cliCommand("setup")}\` creates one).`);
748
+ return;
749
+ }
750
+ // Helpers below (localComposeProjectName) read the module-level appRoot, which
751
+ // is only populated by ensureAppRoot() on the setup path. Stop never clones, so
752
+ // publish the resolved checkout here.
753
+ appRoot = root;
754
+
755
+ // Each service is stopped independently and tolerantly: a stack that is already
756
+ // down, or half down, must still end with everything down and exit 0.
757
+ await stopLocalService("Supabase", "supabase", ["stop"], root);
758
+ await stopLocalService(
759
+ "Redis",
760
+ "docker",
761
+ ["compose", "-f", "docker/compose.yml", "down"],
762
+ root,
763
+ { ...process.env, COMPOSE_PROJECT_NAME: localComposeProjectName() }
764
+ );
765
+
766
+ ok("PassControl stopped. Local data kept โ€” `passcontrol reset --local` wipes it.");
767
+ }
768
+
769
+ /** Stop one local service, reporting rather than throwing when it is already down. */
770
+ async function stopLocalService(label, command, args, cwd, env = process.env) {
771
+ if (!commandExists(command)) {
772
+ step(`${label}: \`${command}\` not found โ€” skipping.`);
773
+ return;
774
+ }
775
+ try {
776
+ await runCommand(command, args, { cwd, env });
777
+ ok(`${label} stopped`);
778
+ } catch {
779
+ step(`${label}: already stopped (or not running).`);
780
+ }
781
+ }
782
+
655
783
  async function restartDashboard(opts = {}) {
656
784
  localDashboard();
657
785
  const managed = runningManagedDashboard();
@@ -696,6 +824,37 @@ async function runLocalCommand(command, args, env = process.env) {
696
824
  await runCommand(command, args, { cwd: appRoot, env });
697
825
  }
698
826
 
827
+ // The saved app root lives outside the npm package, so `npm uninstall -g` leaves
828
+ // it behind and a reinstall silently keeps pointing at the old checkout. `unlink`
829
+ // is the supported way to forget it โ€” without this, deleting an undocumented
830
+ // state file by hand is the only reset.
831
+ function unlinkCommand() {
832
+ const statePath = appRootStatePath();
833
+ // Branch on the file, not on readSavedAppRoot(): that returns null for corrupt
834
+ // JSON exactly as it does for a missing file, so keying off it would report
835
+ // "does not exist" about a file that does โ€” and leave the blockage in place.
836
+ if (!fs.existsSync(statePath)) {
837
+ ok(`No saved app checkout to forget (${statePath} does not exist).`);
838
+ return;
839
+ }
840
+ const saved = readSavedAppRoot();
841
+
842
+ // Forgetting the path while the stack is up strands it: `stop` resolves the
843
+ // checkout to bring Supabase and Redis down, and can't once the path is gone.
844
+ const running = runningManagedDashboard();
845
+ if (running) {
846
+ warn(`A CLI-managed dashboard (PID ${running.pid}) is still running from ${saved ?? "the saved checkout"}.`);
847
+ warn(`Run \`${cliCommand("stop")}\` first, or stop it from that checkout by hand.`);
848
+ }
849
+
850
+ forgetAppRoot();
851
+ ok(saved ? `Forgot the saved app checkout ${saved} (removed ${statePath}).` : `Removed an unreadable app checkout state file (${statePath}).`);
852
+ // `setup --app-dir` runs the Docker/Supabase prerequisite gate before it
853
+ // repoints, so it is not the zero-dependency answer; name the env override too.
854
+ step(`Link another with \`${cliCommand("setup --app-dir <path>")}\` (also starts the local stack),`);
855
+ step("or set PASSCONTROL_APP_ROOT=<path> for a one-off override.");
856
+ }
857
+
699
858
  async function resetLocalStack(opts = {}) {
700
859
  if (opts.local !== true) {
701
860
  throw new Error("Usage: passcontrol reset --local --confirm RESET");
@@ -734,7 +893,7 @@ async function setupLocal(opts = {}) {
734
893
  await startDashboard(opts);
735
894
  if (!opts.noOpen) await openDashboard(opts);
736
895
  console.log(`\n${formatLabel("Local dashboard", dashboard.url, 19)}`);
737
- console.log(formatLabel("Local-only login", "dev@passcontrol.local / passcontrol-dev", 19));
896
+ console.log(formatLabel("Login", "the account you created during setup", 19));
738
897
  step("Add a non-critical provider key, issue a passport, then run `passcontrol doctor --deep`.");
739
898
  }
740
899
 
@@ -1231,6 +1390,18 @@ function printAgentPreset(name = "generic", opts = {}) {
1231
1390
  const sidecarStart = opts.port ? cliCommand(`sidecar --port ${opts.port}`) : cliCommand("sidecar");
1232
1391
 
1233
1392
  console.log(`# Start the bridge first: ${sidecarStart}`);
1393
+
1394
+ // Desktop / GUI clients: there is nothing to export, you type these into a
1395
+ // settings form. The API-key field is required by the UI but ignored by the
1396
+ // sidecar โ€” that is the point. It is where your real provider key used to go.
1397
+ if (isGuiPreset(preset)) {
1398
+ console.log(`# ${GUI_PRESET_LABELS[preset]} settings:`);
1399
+ console.log(`Base URL: ${baseUrl}`);
1400
+ console.log(`API key: ${apiKey}`);
1401
+ console.log(`Model: ${modelWithProvider}`);
1402
+ return;
1403
+ }
1404
+
1234
1405
  switch (preset) {
1235
1406
  case "openhands":
1236
1407
  console.log("# OpenHands / LiteLLM-compatible starting point:");
@@ -1256,13 +1427,6 @@ function printAgentPreset(name = "generic", opts = {}) {
1256
1427
  ["AIDER_MODEL", modelWithProvider],
1257
1428
  ]);
1258
1429
  break;
1259
- case "cline":
1260
- case "continue":
1261
- console.log(`# ${preset} UI settings:`);
1262
- console.log(`Base URL: ${baseUrl}`);
1263
- console.log(`API key: ${apiKey}`);
1264
- console.log(`Model: ${modelWithProvider}`);
1265
- break;
1266
1430
  case "generic":
1267
1431
  console.log("# Generic sidecar settings:");
1268
1432
  printExports([
@@ -1272,9 +1436,7 @@ function printAgentPreset(name = "generic", opts = {}) {
1272
1436
  ]);
1273
1437
  break;
1274
1438
  default:
1275
- throw new Error(
1276
- "Usage: passcontrol env [generic|openhands|litellm|aider|cline|continue|claude-desktop|cursor|claude-code]"
1277
- );
1439
+ throw new Error(`Usage: passcontrol env <${integrationChoices()}>`);
1278
1440
  }
1279
1441
  }
1280
1442
 
@@ -1293,6 +1455,14 @@ function aiderConfig(opts = {}) {
1293
1455
  function configureMcpClient(integration, opts = {}) {
1294
1456
  requireGlobalMcpPassport();
1295
1457
  if (integration === "claude-code") {
1458
+ // Claude Code owns its MCP registry through its own CLI, so there is no
1459
+ // config file for us to merge into. `--write` used to be accepted here and
1460
+ // silently do nothing โ€” refuse it and hand back the command that works.
1461
+ if (opts.write) {
1462
+ throw new Error(
1463
+ `Claude Code manages MCP servers through its own CLI, so there is no file to write. Run:\n ${CLAUDE_CODE_ADD_COMMAND}`
1464
+ );
1465
+ }
1296
1466
  console.log("Claude Code manages MCP servers through its CLI. Run:");
1297
1467
  console.log(CLAUDE_CODE_ADD_COMMAND);
1298
1468
  return;
@@ -1320,14 +1490,19 @@ async function configureCommand(rest, opts = {}) {
1320
1490
  const integration = String(rest[0] ?? "").toLowerCase();
1321
1491
  if (!integration) {
1322
1492
  throw new Error(
1323
- "Usage: passcontrol configure <aider|cline|continue|openhands|claude-desktop|cursor|claude-code> [--write] [--force]"
1493
+ `Usage: passcontrol configure <${integrationChoices()}> [--write] [--force]`
1494
+ );
1495
+ }
1496
+ if (!isIntegration(integration)) {
1497
+ throw new Error(
1498
+ `Unknown integration "${integration}". Use one of: ${integrationChoices()}.`
1324
1499
  );
1325
1500
  }
1326
1501
  if (isMcpIntegration(integration)) {
1327
1502
  configureMcpClient(integration, opts);
1328
1503
  return;
1329
1504
  }
1330
- if (integration !== "aider") {
1505
+ if (!supportsWrite(integration)) {
1331
1506
  if (opts.write) throw new Error(`${integration} configuration is UI- or project-schema-specific; no file was written. Use the preview below.`);
1332
1507
  printAgentPreset(integration, opts);
1333
1508
  step("This integration is configured manually from the settings shown above. Aider is the current file-writing integration.");
@@ -1405,6 +1580,114 @@ async function doctorCommand(opts = {}) {
1405
1580
  } else {
1406
1581
  step("Skipping control API check: no PASSCONTROL_API_KEY configured.");
1407
1582
  }
1583
+
1584
+ await checkInstanceSigningKey();
1585
+ }
1586
+
1587
+ // Receipts and agent tokens are signed by a key the DEPLOYMENT owns. A missing
1588
+ // key is loud (nothing is signed), but a PASSCONTROL_ISSUER pointing somewhere
1589
+ // that does not serve this deployment's JWKS fails silently: every receipt then
1590
+ // carries an `iss` whose key set cannot verify it. Check it explicitly.
1591
+ async function checkInstanceSigningKey() {
1592
+ const seed = process.env.INSTANCE_SIGNING_KEY;
1593
+ const issuer = process.env.PASSCONTROL_ISSUER;
1594
+
1595
+ if (!seed) {
1596
+ step(
1597
+ "Instance signing key not set in this shell โ€” receipts and agent tokens are disabled " +
1598
+ `(run \`${cliCommand("keygen instance")}\` to create one).`
1599
+ );
1600
+ return;
1601
+ }
1602
+
1603
+ let kid;
1604
+ try {
1605
+ kid = instanceKidFromSeed(seed);
1606
+ } catch {
1607
+ fail("INSTANCE_SIGNING_KEY is set but is not a valid 32-byte base64url seed.");
1608
+ return;
1609
+ }
1610
+ ok(`Instance signing key configured (kid ${kid})`);
1611
+
1612
+ if (!issuer) {
1613
+ fail("PASSCONTROL_ISSUER is not set โ€” receipts would be signed with no verifiable issuer.");
1614
+ return;
1615
+ }
1616
+
1617
+ const result = await checkIssuerPublishesKey({ issuer, kid });
1618
+ (result.ok ? ok : fail)(`Issuer check: ${result.reason}`);
1619
+ }
1620
+
1621
+ // `passcontrol verify` needs no config, no passport, and no API key โ€” it is the
1622
+ // one command a stranger runs against someone else's deployment.
1623
+ async function verifyCommand(rest, opts) {
1624
+ const what = rest[0];
1625
+ const artifact = rest[1];
1626
+ const issuer = String(opts.issuer || process.env.PASSCONTROL_ISSUER || "");
1627
+
1628
+ if ((what !== "token" && what !== "receipt") || !artifact) {
1629
+ throw new Error(
1630
+ "Usage: passcontrol verify token <jwt> --audience <aud> --issuer <origin>\n" +
1631
+ " passcontrol verify receipt <jws> --issuer <origin>"
1632
+ );
1633
+ }
1634
+ if (!issuer) {
1635
+ throw new Error(
1636
+ "Set --issuer <https origin> (or PASSCONTROL_ISSUER). A verifier that trusts " +
1637
+ "whatever issuer the artifact names is not verifying anything."
1638
+ );
1639
+ }
1640
+
1641
+ const result =
1642
+ what === "token"
1643
+ ? await verifyAgentToken(artifact, { issuer, audience: String(opts.audience || "") })
1644
+ : await verifyReceipt(artifact, { issuer });
1645
+
1646
+ if (!result.ok) {
1647
+ fail(`Not valid: ${FAILURE_REASONS[result.reason] ?? result.reason}`);
1648
+ process.exitCode = 1;
1649
+ return;
1650
+ }
1651
+
1652
+ const c = result.claims;
1653
+ ok(what === "token" ? "Token is valid." : "Receipt is valid.");
1654
+ step(`Issuer: ${c.iss}`);
1655
+ step(`Passport: ${c.sub}`);
1656
+ if (what === "token") {
1657
+ step(`Audience: ${c.aud}`);
1658
+ step(`Expires: ${new Date(c.exp * 1000).toISOString()}`);
1659
+ } else {
1660
+ step(`Call: ${c.mth} ${c.path} โ†’ ${c.prov}${c.mdl ? `/${c.mdl}` : ""}`);
1661
+ step(`Verdict: ${c.res?.status} (HTTP ${c.res?.http})`);
1662
+ step(`Usage: ${c.use?.in ?? 0} in / ${c.use?.out ?? 0} out ยท ${c.cost ?? 0} ยตยข`);
1663
+ if (c.req) step(`Request: ${c.req.alg} ${c.req.dig} (${c.req.len} bytes)`);
1664
+ }
1665
+ if (c.own) {
1666
+ step(
1667
+ `Owner: ${c.own.sub} (${c.own.tier === "unverified" ? "self-declared, unverified" : c.own.tier})`
1668
+ );
1669
+ }
1670
+ }
1671
+
1672
+ async function keygenCommand(rest) {
1673
+ const target = rest[0];
1674
+ if (target !== "instance") {
1675
+ throw new Error(`Usage: ${cliCommand("keygen instance")}`);
1676
+ }
1677
+
1678
+ const { seed, kid } = generateInstanceKey();
1679
+ ok("Generated an Ed25519 instance signing key.");
1680
+ step("This key signs call receipts and agent-to-agent tokens. Store the seed like a password:");
1681
+ console.log(` INSTANCE_SIGNING_KEY=${seed}`);
1682
+ console.log("");
1683
+ step(`Its public half publishes at /.well-known/jwks.json as kid ${kid}.`);
1684
+ step("Also set PASSCONTROL_ISSUER to this deployment's https origin โ€” it becomes the");
1685
+ step("`iss` claim, and the origin other deployments use to find this one's JWKS.");
1686
+ step("");
1687
+ step("Rotating? Move the current value to INSTANCE_SIGNING_KEY_PREV and keep it there.");
1688
+ step("Unlike VISA_SECRET_PREV we never sign with it โ€” its public key stays published so");
1689
+ step("receipts signed before the rotation still verify. Publish the new key, wait one");
1690
+ step("JWKS max-age window, then start signing with it.");
1408
1691
  }
1409
1692
 
1410
1693
  async function openDashboard(opts = {}) {
@@ -1455,7 +1738,7 @@ async function main() {
1455
1738
  await startDashboard(opts);
1456
1739
  break;
1457
1740
  case "stop":
1458
- await stopDashboard();
1741
+ await stopCommand(opts);
1459
1742
  break;
1460
1743
  case "restart":
1461
1744
  await restartDashboard(opts);
@@ -1469,6 +1752,9 @@ async function main() {
1469
1752
  case "setup":
1470
1753
  await setupLocal(opts);
1471
1754
  break;
1755
+ case "unlink":
1756
+ unlinkCommand();
1757
+ break;
1472
1758
  case "call":
1473
1759
  await callCommand(commandRest, opts);
1474
1760
  break;
@@ -1506,6 +1792,12 @@ async function main() {
1506
1792
  case "open":
1507
1793
  await openDashboard(opts);
1508
1794
  break;
1795
+ case "keygen":
1796
+ await keygenCommand(commandRest);
1797
+ break;
1798
+ case "verify":
1799
+ await verifyCommand(commandRest, opts);
1800
+ break;
1509
1801
  default:
1510
1802
  throw new Error(`Unknown command "${command}". Run \`passcontrol help\`.`);
1511
1803
  }
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
 
@@ -23,6 +36,7 @@ const ANSI = {
23
36
  green: "\x1b[32m",
24
37
  cyan: "\x1b[36m",
25
38
  red: "\x1b[31m",
39
+ yellow: "\x1b[33m",
26
40
  heading: "\x1b[1;32m",
27
41
  };
28
42
 
@@ -208,6 +222,12 @@ export function fail(message = "") {
208
222
  console.error(`${paint(ANSI.red, "โœ—")} ${message}`);
209
223
  }
210
224
 
225
+ // Goes to stdout, not stderr: a warning accompanies work that still succeeded,
226
+ // so it must not make a passing command look failed to a caller reading stderr.
227
+ export function warn(message = "") {
228
+ console.log(`${paint(ANSI.yellow, "!")} ${message}`);
229
+ }
230
+
211
231
  export function die(message) {
212
232
  fail(message);
213
233
  process.exit(1);
@@ -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.3.0",
3
+ "version": "0.5.0",
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
  }