passcontrol 0.8.0 → 0.9.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.
@@ -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) =>
package/cli/selftest.mjs CHANGED
@@ -16,16 +16,52 @@ import { ok, step, warn } from "./config.mjs";
16
16
  import { createVisaClient } from "./visa-client.mjs";
17
17
  import { verifyReceipt } from "./verify.mjs";
18
18
 
19
- async function control(origin, apiKey, method, path, fetchImpl) {
20
- const res = await fetchImpl(`${origin}/api/control/v1${path}`, {
21
- method,
22
- headers: { authorization: `Bearer ${apiKey}` },
23
- });
24
- const parsed = await res.json().catch(() => null);
25
- if (!res.ok) throw new Error(`Control plane refused ${method} ${path} (${res.status}).`);
26
- // `{ data: ... }` — see lib/control/respond.ts. Unwrapped here so callers read
27
- // the payload, never the envelope.
28
- return parsed && typeof parsed === "object" && "data" in parsed ? parsed.data : parsed;
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
+ }
29
65
  }
30
66
 
31
67
  /**
@@ -55,10 +91,24 @@ async function control(origin, apiKey, method, path, fetchImpl) {
55
91
  * a quieter message and returns, and it wraps ITSELF rather than trusting each
56
92
  * caller to remember.
57
93
  */
58
- export async function proveItWorks({ origin, passportId, passportSecret, apiKey, fetchImpl }) {
94
+ export async function proveItWorks({
95
+ origin,
96
+ passportId,
97
+ passportSecret,
98
+ keyStorage = null,
99
+ apiKey,
100
+ fetchImpl,
101
+ wait = sleep,
102
+ }) {
59
103
  const proof = { visa: false, call: false, receipt: null };
60
104
  try {
61
- const visas = createVisaClient({ gateway: origin, passportId, passportSecret, fetch: fetchImpl });
105
+ const visas = createVisaClient({
106
+ gateway: origin,
107
+ passportId,
108
+ passportSecret,
109
+ keyStorage,
110
+ fetch: fetchImpl,
111
+ });
62
112
  const visa = await visas.getVisa();
63
113
  proof.visa = true;
64
114
  ok("minted a visa with the passport this machine just created");
@@ -102,7 +152,7 @@ export async function proveItWorks({ origin, passportId, passportSecret, apiKey,
102
152
  }
103
153
  proof.receiptId = receiptId;
104
154
 
105
- const row = await control(origin, apiKey, "GET", `/receipts/${receiptId}`, fetchImpl);
155
+ const row = await fetchReceiptRow(origin, apiKey, receiptId, fetchImpl, wait);
106
156
  const jws = row?.receipt;
107
157
  if (!jws) {
108
158
  // The route says why itself: no INSTANCE_SIGNING_KEY is a configuration
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
  }