passcontrol 0.7.2 → 0.9.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.
@@ -0,0 +1,413 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { createHash, timingSafeEqual } from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ export const PASSPORT_KEY_STORAGE_OS = "os";
8
+
9
+ const SERVICE = "eu.vertias.passcontrol.passport";
10
+ const COMMAND_TIMEOUT_MS = 10_000;
11
+
12
+ /**
13
+ * The one prompt string this module ever matches stderr against, reduced
14
+ * immediately to a boolean. See `sawPasswordPrompt` below.
15
+ */
16
+ const MACOS_PASSWORD_PROMPT = /password data for new item/iu;
17
+
18
+ /**
19
+ * Exported for tests/passport-key-store-os.test.ts, which drives a real stalling
20
+ * subprocess through it. The seam tests can only assert the *shape* returned
21
+ * here; something has to check a real process still produces it. `timeoutMs`
22
+ * exists for the same reason — so that check costs under a second instead of the
23
+ * full helper timeout.
24
+ */
25
+ export function runProcess(command, args, { input = "", env = {}, timeoutMs = COMMAND_TIMEOUT_MS } = {}) {
26
+ const result = spawnSync(command, args, {
27
+ input,
28
+ encoding: "utf8",
29
+ windowsHide: true,
30
+ timeout: timeoutMs,
31
+ maxBuffer: 64 * 1024,
32
+ env: { ...process.env, ...env },
33
+ stdio: ["pipe", "pipe", "pipe"],
34
+ });
35
+ // Deliberately omit stderr and the native Error object. Helpers sometimes
36
+ // repeat their input in diagnostics, and no caller may log that raw text.
37
+ //
38
+ // Two derived bits leave, and only two. A timeout is not the same failure as a
39
+ // helper that is not installed, though `error` is set for both — and when a
40
+ // helper stalls, whether it had already printed its password prompt is the
41
+ // difference between "it never took the key on stdin" and "it never got that
42
+ // far, so the store is probably locked". Both are booleans computed from a
43
+ // fixed literal; neither can carry a byte of the helper's output outward.
44
+ const stderr = typeof result.stderr === "string" ? result.stderr : "";
45
+ const timedOut = result.error?.code === "ETIMEDOUT";
46
+ return {
47
+ status: result.status,
48
+ stdout: typeof result.stdout === "string" ? result.stdout : "",
49
+ failedToStart: Boolean(result.error) && !timedOut,
50
+ timedOut,
51
+ sawPasswordPrompt: MACOS_PASSWORD_PROMPT.test(stderr),
52
+ };
53
+ }
54
+
55
+ function passed(result) {
56
+ return result && result.status === 0 && !result.failedToStart;
57
+ }
58
+
59
+ function invoke(run, command, args, options) {
60
+ try {
61
+ return run(command, args, options);
62
+ } catch {
63
+ // A thrown helper error is no safer to surface than stderr: an adapter or
64
+ // platform runtime may attach stdin to it. Collapse it to fixed state.
65
+ return { status: null, stdout: "", failedToStart: true, timedOut: false, sawPasswordPrompt: false };
66
+ }
67
+ }
68
+
69
+ function fixedFailure(reason) {
70
+ return { ok: false, reason };
71
+ }
72
+
73
+ /**
74
+ * A helper that stalls and a helper that refuses are different problems for the
75
+ * operator, and only one of them is fixed by unlocking something. Every adapter
76
+ * routes its failures through here so a hang is never reported as "unavailable"
77
+ * or "did not confirm the removal" — the sentences that made a ten-second stall
78
+ * read as a missing item.
79
+ */
80
+ function helperTimeout(name) {
81
+ return `${name} did not respond within ${Math.round(COMMAND_TIMEOUT_MS / 1000)}s`;
82
+ }
83
+
84
+ function helperFailure(name, result, reason) {
85
+ return fixedFailure(result?.timedOut ? helperTimeout(name) : reason);
86
+ }
87
+
88
+ /** security(1) exit code for errSecItemNotFound — nothing to delete. */
89
+ const MACOS_ITEM_NOT_FOUND = 44;
90
+
91
+ /**
92
+ * A removal is confirmed by POSITIVE evidence from the helper, never by a
93
+ * failed read.
94
+ *
95
+ * `read()` deliberately collapses every failure into one fixed shape to keep
96
+ * stderr away from callers, so "the item is gone", "the keychain is locked" and
97
+ * "the helper is not installed" are indistinguishable from here. Concluding
98
+ * success from an unreadable item would make a locked keychain print
99
+ * "removed the passport key" over a key that is still sitting in it — the one
100
+ * sentence `logout` must never get wrong.
101
+ *
102
+ * So `deleted` carries the helper's own verdict, and the read is only a
103
+ * secondary check: a still-readable item disproves the removal, an unreadable
104
+ * one proves nothing either way.
105
+ */
106
+ function confirmGone(store, passportId, name, deleted) {
107
+ if (!deleted) return fixedFailure(`${name} did not confirm the removal`);
108
+ return store.read(passportId).ok
109
+ ? fixedFailure(`${name} still holds the passport key`)
110
+ : { ok: true };
111
+ }
112
+
113
+ function windowsStateRoot(env) {
114
+ return env.APPDATA || path.join(os.homedir(), "AppData", "Roaming");
115
+ }
116
+
117
+ function windowsBlobPath(passportId, env) {
118
+ const id = createHash("sha256").update(passportId).digest("hex");
119
+ return path.join(windowsStateRoot(env), "PassControl", "passport-keys", `${id}.dpapi`);
120
+ }
121
+
122
+ const WINDOWS_WRITE = [
123
+ "$plain = [Console]::In.ReadToEnd()",
124
+ "$secure = ConvertTo-SecureString $plain -AsPlainText -Force",
125
+ "$cipher = ConvertFrom-SecureString $secure",
126
+ "[IO.File]::WriteAllText($env:PASSCONTROL_DPAPI_BLOB, $cipher)",
127
+ ].join("; ");
128
+
129
+ const WINDOWS_READ = [
130
+ "$cipher = [IO.File]::ReadAllText($env:PASSCONTROL_DPAPI_BLOB)",
131
+ "$secure = ConvertTo-SecureString $cipher",
132
+ "$pointer = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($secure)",
133
+ "try { [Console]::Out.Write([Runtime.InteropServices.Marshal]::PtrToStringBSTR($pointer)) } finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($pointer) }",
134
+ ].join("; ");
135
+
136
+ /**
137
+ * OS credential storage with an injectable subprocess seam for CI.
138
+ * Private key material is supplied only through stdin, never argv.
139
+ */
140
+ export function createPassportCredentialStore({
141
+ platform = process.platform,
142
+ env = process.env,
143
+ run = runProcess,
144
+ ensureDirectory = (directory) => fs.mkdirSync(directory, { recursive: true, mode: 0o700 }),
145
+ removeFile = (file) => fs.rmSync(file, { force: true }),
146
+ } = {}) {
147
+ if (platform === "darwin") {
148
+ return {
149
+ name: "macOS Keychain",
150
+ write(passportId, secret) {
151
+ // `-w` with no argv value does NOT read stdin as a value. It runs an
152
+ // interactive double prompt — "password data for new item:" then
153
+ // "retype password for new item:" — so the secret has to be answered
154
+ // TWICE. Sending it once lets the retype hit EOF, at which point
155
+ // security(1) stores an EMPTY password and still exits 0. That is why
156
+ // the value cannot simply move to argv instead: argv is world-readable
157
+ // in `ps`, and this is a private key. Verified against security(1) on
158
+ // macOS 15; tests/passport-key-store-os.test.ts is what holds it.
159
+ if (/[\r\n]/u.test(secret)) {
160
+ return fixedFailure("macOS Keychain cannot store a key containing a newline");
161
+ }
162
+ const result = invoke(run,
163
+ "security",
164
+ ["add-generic-password", "-U", "-a", passportId, "-s", SERVICE, "-w"],
165
+ { input: `${secret}\n${secret}\n` }
166
+ );
167
+ if (result.timedOut) {
168
+ // The one place the prompt bit earns its keep: `security` stalling
169
+ // after its prompt means stdin never landed, stalling before it means
170
+ // it never reached the Keychain at all.
171
+ return fixedFailure(result.sawPasswordPrompt
172
+ ? `${helperTimeout(this.name)} after asking for the password — the key was never accepted on stdin`
173
+ : `${helperTimeout(this.name)} and never reached its password prompt — the Keychain is probably locked`);
174
+ }
175
+ return passed(result) ? { ok: true } : fixedFailure("macOS Keychain write failed");
176
+ },
177
+ read(passportId) {
178
+ const result = invoke(run,
179
+ "security",
180
+ ["find-generic-password", "-a", passportId, "-s", SERVICE, "-w"]
181
+ );
182
+ return passed(result)
183
+ ? { ok: true, secret: String(result.stdout).replace(/\r?\n$/u, "") }
184
+ : helperFailure(this.name, result, "macOS Keychain item unavailable");
185
+ },
186
+ delete(passportId) {
187
+ const result = invoke(run, "security", ["delete-generic-password", "-a", passportId, "-s", SERVICE]);
188
+ if (result.timedOut) return fixedFailure(helperTimeout(this.name));
189
+ // Already absent is a successful logout, not a failure — the operator
190
+ // asked for the key to be gone, and it is.
191
+ const deleted = passed(result) ||
192
+ (!result.failedToStart && result.status === MACOS_ITEM_NOT_FOUND);
193
+ return confirmGone(this, passportId, "macOS Keychain", deleted);
194
+ },
195
+ };
196
+ }
197
+
198
+ if (platform === "linux") {
199
+ return {
200
+ name: "Linux Secret Service",
201
+ write(passportId, secret) {
202
+ const result = invoke(run,
203
+ "secret-tool",
204
+ ["store", "--label=PassControl passport key", "service", SERVICE, "passport-id", passportId],
205
+ { input: secret }
206
+ );
207
+ return passed(result) ? { ok: true } : helperFailure(this.name, result, "Linux Secret Service unavailable");
208
+ },
209
+ read(passportId) {
210
+ const result = invoke(run,
211
+ "secret-tool",
212
+ ["lookup", "service", SERVICE, "passport-id", passportId]
213
+ );
214
+ return passed(result)
215
+ ? { ok: true, secret: String(result.stdout).replace(/\r?\n$/u, "") }
216
+ : helperFailure(this.name, result, "Linux Secret Service item unavailable");
217
+ },
218
+ delete(passportId) {
219
+ // `secret-tool clear` exits 0 whether or not it matched anything.
220
+ const result = invoke(run, "secret-tool", ["clear", "service", SERVICE, "passport-id", passportId]);
221
+ if (result.timedOut) return fixedFailure(helperTimeout(this.name));
222
+ return confirmGone(this, passportId, "Linux Secret Service", passed(result));
223
+ },
224
+ };
225
+ }
226
+
227
+ if (platform === "win32") {
228
+ const powershell = "powershell.exe";
229
+ const args = (script) => ["-NoLogo", "-NoProfile", "-NonInteractive", "-Command", script];
230
+ return {
231
+ name: "Windows DPAPI",
232
+ write(passportId, secret) {
233
+ const blob = windowsBlobPath(passportId, env);
234
+ try {
235
+ ensureDirectory(path.dirname(blob));
236
+ } catch {
237
+ return fixedFailure("Windows DPAPI storage unavailable");
238
+ }
239
+ const result = invoke(run, powershell, args(WINDOWS_WRITE), {
240
+ input: secret,
241
+ env: { PASSCONTROL_DPAPI_BLOB: blob },
242
+ });
243
+ return passed(result) ? { ok: true } : helperFailure(this.name, result, "Windows DPAPI write failed");
244
+ },
245
+ read(passportId) {
246
+ const blob = windowsBlobPath(passportId, env);
247
+ const result = invoke(run, powershell, args(WINDOWS_READ), {
248
+ env: { PASSCONTROL_DPAPI_BLOB: blob },
249
+ });
250
+ return passed(result)
251
+ ? { ok: true, secret: String(result.stdout) }
252
+ : helperFailure(this.name, result, "Windows DPAPI item unavailable");
253
+ },
254
+ delete(passportId) {
255
+ try {
256
+ // force:true, so a missing blob is a no-op rather than a throw.
257
+ removeFile(windowsBlobPath(passportId, env));
258
+ } catch {
259
+ return fixedFailure("Windows DPAPI item could not be removed");
260
+ }
261
+ return confirmGone(this, passportId, "Windows DPAPI", true);
262
+ },
263
+ };
264
+ }
265
+
266
+ return {
267
+ name: "OS credential store",
268
+ write: () => fixedFailure("OS credential store unsupported"),
269
+ read: () => fixedFailure("OS credential store unsupported"),
270
+ delete: () => fixedFailure("OS credential store unsupported"),
271
+ };
272
+ }
273
+
274
+ /**
275
+ * What this machine may honestly declare to the gateway about its own key
276
+ * storage, derived from the SAME resolution that produced the key — so the CLI
277
+ * cannot declare a tier it did not actually read from.
278
+ *
279
+ * The gateway can never check any of this (research/passport-key-protection.md
280
+ * §4), so the wire shape stays minimal and the dashboard labels it as declared.
281
+ * `fallback` is the state worth carrying: the operator configured tier 1, the
282
+ * store could not be read, and the file key answered instead. Reported as the
283
+ * tier 0 it really is, with the disappointment attached.
284
+ *
285
+ * No key resolved means no claim. Silence is a state the panel renders on its
286
+ * own terms; it must never be sent as "file".
287
+ */
288
+ export function keyStorageDeclaration(storage) {
289
+ if (!storage || storage.available === false) return null;
290
+ if (storage.tier === 1) return { store: "os" };
291
+ if (storage.tier === 0) return storage.fallback ? { store: "file", fallback: true } : { store: "file" };
292
+ return null;
293
+ }
294
+
295
+ export function resolvePassportKey({
296
+ passportId,
297
+ fileSecret = "",
298
+ fileLabel = "configuration file",
299
+ preferFileSecret = false,
300
+ storageMarker = "",
301
+ store = createPassportCredentialStore(),
302
+ }) {
303
+ if (preferFileSecret && fileSecret) {
304
+ return {
305
+ secret: fileSecret,
306
+ storage: {
307
+ tier: 0,
308
+ source: fileLabel,
309
+ available: true,
310
+ fallback: false,
311
+ message: `tier 0 — ${fileLabel}`,
312
+ },
313
+ };
314
+ }
315
+
316
+ if (storageMarker === PASSPORT_KEY_STORAGE_OS && passportId) {
317
+ const stored = store.read(passportId);
318
+ if (stored.ok && stored.secret) {
319
+ return {
320
+ secret: stored.secret,
321
+ storage: {
322
+ tier: 1,
323
+ source: store.name,
324
+ available: true,
325
+ fallback: false,
326
+ message: `tier 1 — ${store.name}`,
327
+ },
328
+ };
329
+ }
330
+ if (fileSecret) {
331
+ return {
332
+ secret: fileSecret,
333
+ storage: {
334
+ tier: 0,
335
+ source: fileLabel,
336
+ available: true,
337
+ fallback: true,
338
+ message: `tier 0 — file fallback (${fileLabel}); ${store.name} was unavailable`,
339
+ },
340
+ };
341
+ }
342
+ return {
343
+ secret: "",
344
+ storage: {
345
+ tier: 1,
346
+ source: store.name,
347
+ available: false,
348
+ fallback: false,
349
+ message: `tier 1 configured, but ${store.name} is unavailable and no tier 0 file key exists`,
350
+ },
351
+ };
352
+ }
353
+
354
+ return {
355
+ secret: fileSecret,
356
+ storage: {
357
+ tier: 0,
358
+ source: fileSecret ? fileLabel : "none",
359
+ available: Boolean(fileSecret),
360
+ fallback: false,
361
+ message: fileSecret ? `tier 0 — file (${fileLabel})` : "tier 0 — no passport key configured",
362
+ },
363
+ };
364
+ }
365
+
366
+ function sameSecret(left, right) {
367
+ const a = Buffer.from(left, "utf8");
368
+ const b = Buffer.from(right, "utf8");
369
+ return a.length === b.length && timingSafeEqual(a, b);
370
+ }
371
+
372
+ export function migratePassportKey({ passportId, secret, store, removeFileSecret }) {
373
+ if (!passportId || !secret) {
374
+ return { ok: false, tier: 0, message: "A tier 0 passport file is required for migration." };
375
+ }
376
+
377
+ const written = store.write(passportId, secret);
378
+ if (!written.ok) {
379
+ return {
380
+ ok: false,
381
+ tier: 0,
382
+ // The store's reason is its own fixed text, never the helper's output, and
383
+ // it is the only thing that tells the operator whether to unlock a
384
+ // Keychain, install a helper, or read a stack trace.
385
+ message: `Credential-store write failed${written.reason ? ` (${written.reason})` : ""}; the tier 0 file was left untouched.`,
386
+ };
387
+ }
388
+
389
+ const readback = store.read(passportId);
390
+ if (!readback.ok || !sameSecret(secret, readback.secret)) {
391
+ return {
392
+ ok: false,
393
+ tier: 0,
394
+ message: "Credential-store readback failed or did not match; the tier 0 file was left untouched.",
395
+ };
396
+ }
397
+
398
+ try {
399
+ removeFileSecret();
400
+ } catch {
401
+ return {
402
+ ok: false,
403
+ tier: 0,
404
+ message: "Credential-store verification succeeded, but the tier 0 file could not be updated and remains authoritative.",
405
+ };
406
+ }
407
+
408
+ return {
409
+ ok: true,
410
+ tier: 1,
411
+ message: `Migrated to tier 1 — ${store.name}; verified readback before removing the file key.`,
412
+ };
413
+ }
@@ -8,6 +8,9 @@ export const GATEWAY_API_PROTOCOL: ProtocolRange;
8
8
  export const RECEIPT_PROTOCOL: ProtocolRange;
9
9
  export const AGENT_TOKEN_PROTOCOL: ProtocolRange;
10
10
  export const WORKSPACE_EXPORT_PROTOCOL: ProtocolRange;
11
+ // Signed spend statements. Its own version line, and part of CLIENT_PROTOCOLS
12
+ // since the format was published — see the note in protocols.mjs.
13
+ export const STATEMENT_PROTOCOL: ProtocolRange;
11
14
  export const CLIENT_PROTOCOLS: Readonly<Record<string, ProtocolRange>>;
12
15
  export function compareProtocolRanges(client: ProtocolRange, server: unknown): "compatible" | "partial" | "update-required" | "unavailable";
13
16
  export function compareProtocolSets(serverProtocols: unknown): {
package/cli/protocols.mjs CHANGED
@@ -7,12 +7,35 @@ export const RECEIPT_PROTOCOL = { minimum: 1, maximum: 2 };
7
7
  export const AGENT_TOKEN_PROTOCOL = { minimum: 1, maximum: 1 };
8
8
  export const WORKSPACE_EXPORT_PROTOCOL = { minimum: 1, maximum: 1 };
9
9
 
10
+ /**
11
+ * Signed spend statements. Its OWN version line, deliberately separate from the
12
+ * receipt's: a statement carries `v` where a receipt carries `ver`, and gating
13
+ * one on the other's maximum would let a statement claiming the receipt's
14
+ * current version (2) through a verifier that only understands statement v1.
15
+ *
16
+ * IN CLIENT_PROTOCOLS below, as of the scope split. It was deliberately absent
17
+ * while nothing negotiated it, but the statement format is now a published
18
+ * contract — docs/statement-format.md is written for someone implementing a
19
+ * verifier from scratch — and a published contract that the compatibility
20
+ * handshake does not report is a version number nobody can act on.
21
+ *
22
+ * KNOWN CONSEQUENCE, ACCEPTED. `compareProtocolSets` walks every key here, and
23
+ * a server that does not declare `statement` scores "unavailable", which makes
24
+ * the overall verdict unavailable. So this CLI reports incompatibility against
25
+ * any gateway predating the declaration. That is the honest answer rather than
26
+ * a regression — `passcontrol statements` genuinely does not work there — but
27
+ * it means a self-hoster who upgrades the CLI before their gateway will see it,
28
+ * and the release note has to say so.
29
+ */
30
+ export const STATEMENT_PROTOCOL = { minimum: 1, maximum: 1 };
31
+
10
32
  export const CLIENT_PROTOCOLS = Object.freeze({
11
33
  control_api: CONTROL_API_PROTOCOL,
12
34
  gateway_api: GATEWAY_API_PROTOCOL,
13
35
  receipt: RECEIPT_PROTOCOL,
14
36
  agent_token: AGENT_TOKEN_PROTOCOL,
15
37
  workspace_export: WORKSPACE_EXPORT_PROTOCOL,
38
+ statement: STATEMENT_PROTOCOL,
16
39
  });
17
40
 
18
41
  const validRange = (value) =>
@@ -0,0 +1,191 @@
1
+ // The end-to-end proof: does this passport actually govern a call, and can a
2
+ // stranger check that it did?
3
+ //
4
+ // Extracted from `passcontrol login` so `doctor --deep` runs the SAME chain
5
+ // rather than a second one that drifts. Before this, doctor stopped at "visa
6
+ // mint works" — which proves the passport authenticates and nothing about
7
+ // scope, budget, the proxy, or receipts. The most useful diagnostic in the tool
8
+ // was the one thing login already did better.
9
+ //
10
+ // Every leg is existing surface:
11
+ // challenge -> visa cli/visa-client.mjs (the same signer the sidecar uses)
12
+ // demo call app/api/v1/[provider]/[...path]/route.ts, keyless
13
+ // receipt row GET /api/control/v1/receipts/{id}
14
+ // verification cli/verify.mjs, the same code `passcontrol verify` runs
15
+ import { ok, step, warn } from "./config.mjs";
16
+ import { createVisaClient } from "./visa-client.mjs";
17
+ import { verifyReceipt } from "./verify.mjs";
18
+
19
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
20
+
21
+ /**
22
+ * The proxy answers BEFORE its receipt row exists.
23
+ *
24
+ * Signing and storing the audit row happen after the response, deliberately, so
25
+ * a governed call is never slowed by its own paperwork. The receipt id in the
26
+ * response header is therefore a promise that the row WILL exist, not a claim
27
+ * that it does — and a single immediate read loses that race. Codex reproduced
28
+ * it deterministically by holding the background write until the first read
29
+ * finished.
30
+ *
31
+ * What made it worth fixing rather than tolerating is how it fails: that 404 is
32
+ * the same answer a gateway gives when it stores no receipts at all, so the
33
+ * operator is told the deployment signs nothing, on the one screen they read as
34
+ * proof that it does.
35
+ *
36
+ * Bounded to five attempts inside ~1.75s, and ONLY on 404. A 401 is the wrong
37
+ * key, a 429 is a limiter that retrying would only anger, and a 5xx is not
38
+ * something a login should sit through. Exhausting the attempts falls through
39
+ * to the caller's existing "no receipt was stored" branch, which by then is a
40
+ * fair description.
41
+ *
42
+ * Exported because the policy IS the contract: the number of attempts, and the
43
+ * fact that only a 404 earns one, are what separate a row still being written
44
+ * from a wrong key or a limiter that retrying would only anger.
45
+ */
46
+ const RECEIPT_RETRY_DELAYS_MS = [120, 240, 480, 900];
47
+
48
+ export async function fetchReceiptRow(origin, apiKey, receiptId, fetchImpl, wait) {
49
+ const url = `${origin}/api/control/v1/receipts/${encodeURIComponent(receiptId)}`;
50
+ for (let attempt = 0; ; attempt += 1) {
51
+ const res = await fetchImpl(url, {
52
+ method: "GET",
53
+ headers: { authorization: `Bearer ${apiKey}` },
54
+ });
55
+ if (res.ok) {
56
+ const parsed = await res.json().catch(() => null);
57
+ return parsed && typeof parsed === "object" && "data" in parsed ? parsed.data : parsed;
58
+ }
59
+ if (res.status !== 404) {
60
+ throw new Error(`Control plane refused GET /receipts/${receiptId} (${res.status}).`);
61
+ }
62
+ if (attempt >= RECEIPT_RETRY_DELAYS_MS.length) return null;
63
+ await wait(RECEIPT_RETRY_DELAYS_MS[attempt]);
64
+ }
65
+ }
66
+
67
+ /**
68
+ * End the command with the product working, not with homework.
69
+ *
70
+ * `login` used to sign off with homework — go and make a call yourself. This
71
+ * runs it for them, and then does the part nothing else on the market does:
72
+ * fetches the SIGNED RECEIPT for that call and verifies the signature locally,
73
+ * against the gateway's published JWKS.
74
+ *
75
+ * Nothing here is new server surface. Every leg already existed:
76
+ * challenge → visa cli/visa-client.mjs (the same signer the sidecar uses)
77
+ * demo call app/api/v1/[provider]/[...path]/route.ts
78
+ * receipt row GET /api/control/v1/receipts/{id}
79
+ * verification cli/verify.mjs, the same code `passcontrol verify` runs
80
+ *
81
+ * `createVisaClient` rather than a local ed25519.sign: it re-validates the
82
+ * origin at the point of signature, which is the guard its own header explains
83
+ * is easy to leave behind when a new caller copies the signing lines instead.
84
+ *
85
+ * ── This function must never throw ──────────────────────────────────────────
86
+ *
87
+ * In login, the agent, the key and the config all already exist by the time
88
+ * this runs — the command has SUCCEEDED. A proof that could turn that into a
89
+ * non-zero exit would be a demo that costs people their setup. In doctor, a
90
+ * throwing diagnostic is simply a bad diagnostic. So every branch degrades to
91
+ * a quieter message and returns, and it wraps ITSELF rather than trusting each
92
+ * caller to remember.
93
+ */
94
+ export async function proveItWorks({
95
+ origin,
96
+ passportId,
97
+ passportSecret,
98
+ keyStorage = null,
99
+ apiKey,
100
+ fetchImpl,
101
+ wait = sleep,
102
+ }) {
103
+ const proof = { visa: false, call: false, receipt: null };
104
+ try {
105
+ const visas = createVisaClient({
106
+ gateway: origin,
107
+ passportId,
108
+ passportSecret,
109
+ keyStorage,
110
+ fetch: fetchImpl,
111
+ });
112
+ const visa = await visas.getVisa();
113
+ proof.visa = true;
114
+ ok("minted a visa with the passport this machine just created");
115
+
116
+ const res = await fetchImpl(`${origin}/api/v1/demo/chat/completions`, {
117
+ method: "POST",
118
+ headers: { "content-type": "application/json", authorization: `Bearer ${visa}` },
119
+ body: JSON.stringify({
120
+ model: "demo-1",
121
+ max_tokens: 32,
122
+ messages: [{ role: "user", content: "Say hello in three words." }],
123
+ }),
124
+ });
125
+
126
+ if (!res.ok) {
127
+ // 404 is the ordinary answer from a self-hosted gateway that has not set
128
+ // PASSCONTROL_DEMO=1 — a correctly configured gateway, not a fault. Say so
129
+ // in those words, because "404" here would read as something being broken.
130
+ proof.reason = res.status === 404 ? "demo_unavailable" : `call_${res.status}`;
131
+ step(
132
+ res.status === 404
133
+ ? "This gateway has no keyless demo provider, so there was nothing free to call."
134
+ : `The demo call answered ${res.status}; your passport is still fine.`
135
+ );
136
+ step('Add a provider key in the Control Tower, then: passcontrol call "hi"');
137
+ return proof;
138
+ }
139
+ proof.call = true;
140
+ const body = await res.json().catch(() => null);
141
+ const tokens = body?.usage?.total_tokens;
142
+ ok(`governed call ok — demo/${body?.model ?? "demo-1"}${tokens ? `, ${tokens} tokens` : ""}`);
143
+
144
+ // Absent only when the deployment predates receipts; the id is the handle
145
+ // for the audit row either way.
146
+ const receiptId = res.headers.get("x-passcontrol-receipt-id");
147
+ // No control key (doctor can run without one): the call is still proven,
148
+ // the receipt just cannot be fetched to check.
149
+ if (!receiptId || !apiKey) {
150
+ proof.receipt = "unavailable";
151
+ return proof;
152
+ }
153
+ proof.receiptId = receiptId;
154
+
155
+ const row = await fetchReceiptRow(origin, apiKey, receiptId, fetchImpl, wait);
156
+ const jws = row?.receipt;
157
+ if (!jws) {
158
+ // The route says why itself: no INSTANCE_SIGNING_KEY is a configuration
159
+ // answer, not missing data.
160
+ proof.receipt = "unavailable";
161
+ step(
162
+ row?.reason === "receipts_not_enabled"
163
+ ? "This deployment signs no receipts yet (no instance signing key)."
164
+ : "No receipt was stored for that call."
165
+ );
166
+ return proof;
167
+ }
168
+
169
+ // Verified HERE, on this machine, against the issuer's published key — the
170
+ // same code path `passcontrol verify receipt` runs for a stranger. If this
171
+ // said "verified" without checking, the feature would be a slogan.
172
+ const verified = await verifyReceipt(jws, { issuer: origin, fetch: fetchImpl });
173
+ proof.receipt = verified.ok ? "verified" : "unverified";
174
+ if (verified.ok) {
175
+ ok(`receipt verified against ${origin}/.well-known/jwks.json`);
176
+ step("");
177
+ step("Your agent is live. Anyone can check that call for themselves:");
178
+ step(` passcontrol verify receipt ${jws} --issuer ${origin}`);
179
+ } else {
180
+ warn(`A receipt came back but did not verify (${verified.reason}).`);
181
+ }
182
+ return proof;
183
+ } catch (error) {
184
+ // Deliberately quiet. The login worked; this did not, and saying so loudly
185
+ // would teach the operator to distrust a config that is perfectly good.
186
+ proof.reason = error?.message ?? "unknown";
187
+ step("Could not run the first call just now — your config is written and valid.");
188
+ step('Try it yourself: passcontrol call "hi"');
189
+ return proof;
190
+ }
191
+ }
package/cli/sidecar.mjs CHANGED
@@ -11,6 +11,7 @@ import { createVisaClient } from "./visa-client.mjs";
11
11
  // have no meaning upstream.
12
12
  const STRIP_REQ = new Set([
13
13
  "authorization",
14
+ "x-passcontrol-proof",
14
15
  "x-api-key",
15
16
  "host",
16
17
  "content-length",
@@ -100,6 +101,7 @@ export function createSidecar({
100
101
  gateway,
101
102
  passportId,
102
103
  passportSecret,
104
+ keyStorage = null,
103
105
  port = 8788,
104
106
  host = "127.0.0.1",
105
107
  refreshSkewSeconds = 30,
@@ -114,6 +116,7 @@ export function createSidecar({
114
116
  gateway: origin,
115
117
  passportId,
116
118
  passportSecret,
119
+ keyStorage,
117
120
  refreshSkewSeconds,
118
121
  missingVisaMessage: "challenge returned no visa",
119
122
  });
@@ -140,6 +143,7 @@ export function createSidecar({
140
143
  if (!isStripped(k) && typeof v === "string") headers[k] = v;
141
144
  }
142
145
  headers["authorization"] = `Bearer ${visa}`;
146
+ headers["x-passcontrol-proof"] = visas.createProof(visa, req.method, new URL(path, origin));
143
147
  headers["accept-encoding"] = "identity";
144
148
  return fetch(`${origin}${path}`, { method: req.method, headers, body: body ?? undefined });
145
149
  }