@agent-custody/receipts 0.16.10 → 0.16.12

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.
Files changed (78) hide show
  1. package/README.md +32 -12
  2. package/dist/approval-requests.d.ts +114 -0
  3. package/dist/approval-requests.js +198 -0
  4. package/dist/approval.d.ts +8 -0
  5. package/dist/approval.js +10 -3
  6. package/dist/check.js +14 -0
  7. package/dist/cli.js +184 -5
  8. package/dist/completeness.d.ts +11 -2
  9. package/dist/completeness.js +45 -9
  10. package/dist/config.d.ts +6 -0
  11. package/dist/config.js +19 -1
  12. package/dist/console-page.js +87 -2
  13. package/dist/console.js +72 -0
  14. package/dist/crypto.d.ts +2 -0
  15. package/dist/crypto.js +2 -1
  16. package/dist/delegation.d.ts +1 -1
  17. package/dist/delegation.js +19 -2
  18. package/dist/did-key.d.ts +2 -0
  19. package/dist/did-key.js +21 -1
  20. package/dist/door-app.js +1 -1
  21. package/dist/door-core.d.ts +385 -0
  22. package/dist/door-core.js +757 -0
  23. package/dist/door-error-rates.d.ts +102 -0
  24. package/dist/door-error-rates.js +178 -0
  25. package/dist/door-form.d.ts +7 -2
  26. package/dist/door-form.js +52 -4
  27. package/dist/door-measure.d.ts +153 -0
  28. package/dist/door-measure.js +325 -0
  29. package/dist/door-signals.d.ts +414 -0
  30. package/dist/door-signals.js +555 -0
  31. package/dist/door-test-set.d.ts +43 -0
  32. package/dist/door-test-set.js +117 -0
  33. package/dist/door-worker.d.ts +148 -0
  34. package/dist/door-worker.js +283 -0
  35. package/dist/door.d.ts +11 -293
  36. package/dist/door.js +45 -755
  37. package/dist/gateway-http.d.ts +1 -6
  38. package/dist/gateway-http.js +2 -19
  39. package/dist/gateway.js +24 -3
  40. package/dist/grant-header.d.ts +8 -0
  41. package/dist/grant-header.js +19 -0
  42. package/dist/index.d.ts +11 -2
  43. package/dist/index.js +6 -1
  44. package/dist/issue.d.ts +2 -16
  45. package/dist/issue.js +2 -12
  46. package/dist/lock.d.ts +5 -0
  47. package/dist/lock.js +1 -1
  48. package/dist/log-http.d.ts +37 -0
  49. package/dist/log-http.js +74 -0
  50. package/dist/log-sink.d.ts +3 -37
  51. package/dist/log-sink.js +5 -71
  52. package/dist/log.d.ts +2 -27
  53. package/dist/log.js +2 -173
  54. package/dist/merkle.d.ts +27 -0
  55. package/dist/merkle.js +175 -0
  56. package/dist/object-issuer.d.ts +29 -0
  57. package/dist/object-issuer.js +172 -0
  58. package/dist/receipt-pending.d.ts +16 -0
  59. package/dist/receipt-pending.js +14 -0
  60. package/dist/web-bot-auth.d.ts +26 -6
  61. package/dist/web-bot-auth.js +116 -56
  62. package/docs/approvals.md +33 -0
  63. package/docs/completeness.md +44 -5
  64. package/docs/console.md +11 -4
  65. package/docs/door-error-rates.md +490 -0
  66. package/docs/door-languages.md +3 -1
  67. package/docs/door-middleware.md +6 -1
  68. package/docs/door-quickstart.md +53 -17
  69. package/docs/door-signals.md +117 -7
  70. package/docs/door-worker.md +94 -0
  71. package/docs/door.md +41 -12
  72. package/docs/github-action.md +2 -2
  73. package/docs/tutorials.md +6 -0
  74. package/docs/verification.md +1 -1
  75. package/package.json +4 -1
  76. package/vectors/audit.json +27 -27
  77. package/vectors/canonical.json +5 -5
  78. package/vectors/receipts.json +1645 -1549
@@ -70,7 +70,8 @@ export interface WebBotAuthOptions {
70
70
  }
71
71
  /**
72
72
  * What the door made of a request's signature. `verified`: a signature tagged `web-bot-auth` checked against a key
73
- * that `agent`'s directory publishes. `invalid`: the signature, its parameters, its agent, or the directory was wrong.
73
+ * that `agent`'s directory publishes, or against the key that its did:key `keyid` names (`agent` is then that did:key).
74
+ * `invalid`: the signature, its parameters, its agent, or the directory was wrong.
74
75
  * `unavailable`: the directory could not be fetched, or the door could not record the nonce. `unchecked`: a signature
75
76
  * arrived and the door has no `webBotAuth` config. `absent`: no `Signature-Input`.
76
77
  */
@@ -88,10 +89,27 @@ export type SignatureCheck = {
88
89
  outcome: "unchecked" | "absent";
89
90
  };
90
91
  export interface WebBotAuthVerifier {
91
- verify(req: SignedRequest): Promise<SignatureCheck>;
92
- /** nonces held now */
93
- nonces(): number;
92
+ /** `grantAgent`: the agent of the request's grant, when a trusted principal signed it; a did:key signature keeps its nonce only for that agent */
93
+ verify(req: SignedRequest, grantAgent?: string): Promise<SignatureCheck>;
94
+ /** nonces held now, or undefined when the nonce store does not count them */
95
+ nonces(): number | undefined;
94
96
  }
97
+ /** `free`: not held, and there is room to record it. `replayed`: held, unexpired. `full`: no room to record another. */
98
+ export type NonceState = "free" | "replayed" | "full";
99
+ /**
100
+ * Where the door remembers the nonces of the signatures it verified, keyed `<agent> <keyid> <nonce>`. `claim` records a
101
+ * key until `until` (milliseconds since the epoch) unless it is held already, and does both as one step: two arrivals
102
+ * with one nonce get one `claimed`. `check` is asked before the directory is fetched, so a replay or a full store costs
103
+ * no fetch; `claim` decides. A store that throws or rejects makes the signature `unavailable`, never `verified`.
104
+ */
105
+ export interface NonceStore {
106
+ check?(key: string): NonceState | Promise<NonceState>;
107
+ claim(key: string, until: number): "claimed" | "replayed" | "full" | Promise<"claimed" | "replayed" | "full">;
108
+ /** keys held now, where the store can count them */
109
+ size?(): number;
110
+ }
111
+ /** The default nonce store: one process's (or one isolate's) memory, at most `maxNonces` keys, an expired key dropped when room is needed. */
112
+ export declare function createMemoryNonceStore(maxNonces: number, now?: () => number): NonceStore;
95
113
  /** A response body up to `max` bytes; null when it passes that, and the rest is not read. */
96
114
  export declare function readCapped(res: Response, max: number): Promise<Buffer | null>;
97
115
  /** An https origin with nothing after it, as the config holds it; throws on anything else. */
@@ -100,6 +118,8 @@ export declare function agentOrigin(uri: string): string;
100
118
  * Checks Web Bot Auth signatures. The directory of each configured agent is fetched from
101
119
  * `<origin>/.well-known/http-message-signatures-directory` over https, never following a redirect, within `timeoutMs`
102
120
  * and `maxDirectoryBytes`, and kept for `cacheSeconds` (a failure for 30 seconds). A nonce is remembered until the
103
- * signature it came with could no longer be accepted, so a signature serves one request. `now` is for tests.
121
+ * signature it came with could no longer be accepted, so a signature serves one request. Nonces are kept in `nonceStore`,
122
+ * by default this process's memory (`maxNonces` of them); a door that runs as many processes or isolates needs a store
123
+ * they share, or a signature refused by one is accepted once by another. `now` is for tests.
104
124
  */
105
- export declare function createWebBotAuthVerifier(opts: WebBotAuthOptions, f: typeof fetch, now?: () => number): WebBotAuthVerifier;
125
+ export declare function createWebBotAuthVerifier(opts: WebBotAuthOptions, f: typeof fetch, now?: () => number, nonceStore?: NonceStore): WebBotAuthVerifier;
@@ -3,7 +3,12 @@
3
3
  // draft-meunier-http-message-signatures-directory-05). A signature that checks proves the request was signed by a key
4
4
  // published at the `Signature-Agent` origin, for this door's authority, inside a short window. It proves nothing about
5
5
  // the body, the path, or the method unless the signature covers them.
6
+ //
7
+ // A signature whose `keyid` is a did:key is checked against the key that the did:key names, with no directory. It
8
+ // proves that the signer holds that key, and nothing else. Anyone can make such a key, so the door (`classifyArrival`)
9
+ // accepts it only with a grant for that did:key.
6
10
  import { createHash, createPublicKey, verify as cryptoVerify } from "node:crypto";
11
+ import { DID_KEY_PREFIX, publicKeyFromDidKey } from "./did-key.js";
7
12
  export const DIRECTORY_PATH = "/.well-known/http-message-signatures-directory";
8
13
  export const DIRECTORY_MEDIA_TYPE = "application/http-message-signatures-directory+json";
9
14
  export const WEB_BOT_AUTH_TAG = "web-bot-auth";
@@ -276,6 +281,33 @@ export function signatureBase(req, input) {
276
281
  export function jwkThumbprint(x) {
277
282
  return createHash("sha256").update(`{"crv":"Ed25519","kty":"OKP","x":"${x}"}`).digest("base64url");
278
283
  }
284
+ /** The default nonce store: one process's (or one isolate's) memory, at most `maxNonces` keys, an expired key dropped when room is needed. */
285
+ export function createMemoryNonceStore(maxNonces, now = () => Date.now()) {
286
+ const nonces = new Map();
287
+ const held = (key) => {
288
+ const until = nonces.get(key);
289
+ return until !== undefined && until > now();
290
+ };
291
+ const room = () => {
292
+ if (nonces.size < maxNonces)
293
+ return true;
294
+ const t = now();
295
+ for (const [k, until] of nonces)
296
+ if (until <= t)
297
+ nonces.delete(k);
298
+ return nonces.size < maxNonces;
299
+ };
300
+ return {
301
+ check: (key) => (held(key) ? "replayed" : room() ? "free" : "full"),
302
+ claim(key, until) {
303
+ if (held(key))
304
+ return "replayed";
305
+ nonces.set(key, until);
306
+ return "claimed";
307
+ },
308
+ size: () => nonces.size,
309
+ };
310
+ }
279
311
  /** A response body up to `max` bytes; null when it passes that, and the rest is not read. */
280
312
  export async function readCapped(res, max) {
281
313
  if (!res.body)
@@ -322,14 +354,17 @@ export function agentOrigin(uri) {
322
354
  * Checks Web Bot Auth signatures. The directory of each configured agent is fetched from
323
355
  * `<origin>/.well-known/http-message-signatures-directory` over https, never following a redirect, within `timeoutMs`
324
356
  * and `maxDirectoryBytes`, and kept for `cacheSeconds` (a failure for 30 seconds). A nonce is remembered until the
325
- * signature it came with could no longer be accepted, so a signature serves one request. `now` is for tests.
357
+ * signature it came with could no longer be accepted, so a signature serves one request. Nonces are kept in `nonceStore`,
358
+ * by default this process's memory (`maxNonces` of them); a door that runs as many processes or isolates needs a store
359
+ * they share, or a signature refused by one is accepted once by another. `now` is for tests.
326
360
  */
327
- export function createWebBotAuthVerifier(opts, f, now = () => Date.now()) {
361
+ export function createWebBotAuthVerifier(opts, f, now = () => Date.now(), nonceStore) {
328
362
  const agents = new Set(opts.agents.map(agentOrigin));
329
363
  const authorities = new Set(opts.authorities.map(normalizeAuthority));
330
364
  const cache = new Map();
331
365
  const inflight = new Map();
332
- const nonces = new Map();
366
+ const nonces = nonceStore ?? createMemoryNonceStore(opts.maxNonces, now);
367
+ const storeDown = (e) => `the door could not reach its nonce store, so it cannot refuse a replay: ${e instanceof Error ? e.message : String(e)}`;
333
368
  const fetchDirectory = async (origin) => {
334
369
  const url = `${origin}${DIRECTORY_PATH}`;
335
370
  try {
@@ -376,16 +411,7 @@ export function createWebBotAuthVerifier(opts, f, now = () => Date.now()) {
376
411
  inflight.set(origin, p);
377
412
  return p;
378
413
  };
379
- const roomForNonce = () => {
380
- if (nonces.size < opts.maxNonces)
381
- return true;
382
- const t = now();
383
- for (const [k, until] of nonces)
384
- if (until <= t)
385
- nonces.delete(k);
386
- return nonces.size < opts.maxNonces;
387
- };
388
- async function verify(req) {
414
+ async function verify(req, grantAgent) {
389
415
  const inputText = req.header("signature-input");
390
416
  const sigText = req.header("signature");
391
417
  if (!inputText && !sigText)
@@ -425,34 +451,47 @@ export function createWebBotAuthVerifier(opts, f, now = () => Date.now()) {
425
451
  return invalid(`${label} uses alg ${serializeBare(algP)}; this door checks ed25519 only`, { keyid });
426
452
  if (nonceP && nonceP.t !== "string")
427
453
  return invalid(`${label} has a nonce that is not a string`, { keyid });
428
- // the covered components: @authority, and the Signature-Agent member that names the directory
454
+ // the covered components: @authority, and the Signature-Agent member that names the directory (none for a did:key)
429
455
  const covered = input.list;
430
456
  if (!covered.some((c) => c.item.t === "string" && c.item.v === "@authority" && c.params.length === 0))
431
457
  return invalid(`${label} does not cover @authority`, { keyid });
432
- const agentComponent = covered.find((c) => c.item.t === "string" && c.item.v === "signature-agent");
433
- const agentText = req.header("signature-agent");
434
- if (!agentComponent || !agentText)
435
- return invalid(agentText ? `${label} does not cover signature-agent` : "no Signature-Agent field names the signer's directory", { keyid });
436
- let agentUri;
437
- try {
438
- const key = param(agentComponent.params, "key");
439
- const named = key?.t === "string" ? parseDictionary(agentText.join(", ")).get(key.v) : parseItem(agentText.join(", "));
440
- if (!named || "list" in named || named.item.t !== "string")
441
- return invalid(`the Signature-Agent ${key?.t === "string" ? `member ${key.v} ` : ""}is not a string`, { keyid });
442
- agentUri = named.item.v;
443
- }
444
- catch (e) {
445
- return invalid(`the Signature-Agent field does not parse: ${e instanceof Error ? e.message : String(e)}`, { keyid });
446
- }
447
458
  let agent;
448
- try {
449
- agent = agentOrigin(agentUri);
459
+ let didKey;
460
+ if (keyid.startsWith(DID_KEY_PREFIX)) {
461
+ // a did:key keyid carries its key: the signer is the did:key, and no Signature-Agent or directory is necessary
462
+ try {
463
+ didKey = publicKeyFromDidKey(keyid).publicKey;
464
+ }
465
+ catch (e) {
466
+ return invalid(`the keyid of ${label} does not decode: ${e instanceof Error ? e.message : String(e)}`, { keyid });
467
+ }
468
+ agent = keyid;
450
469
  }
451
- catch (e) {
452
- return invalid(e instanceof Error ? e.message : String(e), { keyid });
470
+ else {
471
+ const agentComponent = covered.find((c) => c.item.t === "string" && c.item.v === "signature-agent");
472
+ const agentText = req.header("signature-agent");
473
+ if (!agentComponent || !agentText)
474
+ return invalid(agentText ? `${label} does not cover signature-agent` : "no Signature-Agent field names the signer's directory", { keyid });
475
+ let agentUri;
476
+ try {
477
+ const key = param(agentComponent.params, "key");
478
+ const named = key?.t === "string" ? parseDictionary(agentText.join(", ")).get(key.v) : parseItem(agentText.join(", "));
479
+ if (!named || "list" in named || named.item.t !== "string")
480
+ return invalid(`the Signature-Agent ${key?.t === "string" ? `member ${key.v} ` : ""}is not a string`, { keyid });
481
+ agentUri = named.item.v;
482
+ }
483
+ catch (e) {
484
+ return invalid(`the Signature-Agent field does not parse: ${e instanceof Error ? e.message : String(e)}`, { keyid });
485
+ }
486
+ try {
487
+ agent = agentOrigin(agentUri);
488
+ }
489
+ catch (e) {
490
+ return invalid(e instanceof Error ? e.message : String(e), { keyid });
491
+ }
492
+ if (!agents.has(agent))
493
+ return invalid(`${agent} is not a signature agent this door is configured to check`, { agent, keyid });
453
494
  }
454
- if (!agents.has(agent))
455
- return invalid(`${agent} is not a signature agent this door is configured to check`, { agent, keyid });
456
495
  // the window: created is not in the future, the signature has not expired, and it is no older than maxAgeSeconds
457
496
  const t = now() / 1000;
458
497
  const skew = opts.clockSkewSeconds;
@@ -477,32 +516,53 @@ export function createWebBotAuthVerifier(opts, f, now = () => Date.now()) {
477
516
  }
478
517
  if (opts.requireNonce && !nonceP)
479
518
  return invalid(`${label} has no nonce, and this door requires one`, { agent, keyid });
480
- const nonceKey = nonceP ? `${agent} ${keyid} ${nonceP.v}` : undefined;
481
- if (nonceKey) {
482
- const until = nonces.get(nonceKey);
483
- if (until !== undefined && until > now())
519
+ // Anyone can make a did:key, so a stranger's signatures must not fill the nonce store. A did:key signature that no
520
+ // trusted grant names is never accepted by the door, and its nonce is not kept.
521
+ const nonceKey = nonceP && (!didKey || keyid === grantAgent) ? `${agent} ${keyid} ${nonceP.v}` : undefined;
522
+ const full = { outcome: "unavailable", error: nonceStore ? "the door's nonce store is full and cannot record another" : `the door holds ${opts.maxNonces} nonces and cannot record another`, agent, keyid };
523
+ if (nonceKey && nonces.check) {
524
+ let state;
525
+ try {
526
+ state = await nonces.check(nonceKey);
527
+ }
528
+ catch (e) {
529
+ return { outcome: "unavailable", error: storeDown(e), agent, keyid };
530
+ }
531
+ if (state === "replayed")
484
532
  return invalid(`${label} repeats a nonce already used`, { agent, keyid });
485
- if (!roomForNonce())
486
- return { outcome: "unavailable", error: `the door holds ${opts.maxNonces} nonces and cannot record another`, agent, keyid };
533
+ if (state === "full")
534
+ return full;
487
535
  }
488
- const dir = await directory(agent);
489
- if (!dir.ok)
490
- return { outcome: dir.outcome, error: dir.error, agent, keyid };
491
- const k = dir.keys.get(keyid);
492
- if (!k)
493
- return invalid(`keyid ${keyid} is not an Ed25519 key in ${agent}'s directory`, { agent, keyid });
494
- if ((k.nbf !== undefined && t + skew < k.nbf) || (k.exp !== undefined && t - skew > k.exp))
495
- return invalid(`keyid ${keyid} is outside the validity its directory gives it`, { agent, keyid });
496
- if (!cryptoVerify(null, Buffer.from(base, "utf8"), k.key, sig.item.v))
497
- return invalid(`${label} does not verify with ${agent}'s key ${keyid}`, { agent, keyid });
536
+ let key = didKey;
537
+ if (!key) {
538
+ const dir = await directory(agent);
539
+ if (!dir.ok)
540
+ return { outcome: dir.outcome, error: dir.error, agent, keyid };
541
+ const k = dir.keys.get(keyid);
542
+ if (!k)
543
+ return invalid(`keyid ${keyid} is not an Ed25519 key in ${agent}'s directory`, { agent, keyid });
544
+ if ((k.nbf !== undefined && t + skew < k.nbf) || (k.exp !== undefined && t - skew > k.exp))
545
+ return invalid(`keyid ${keyid} is outside the validity its directory gives it`, { agent, keyid });
546
+ key = k.key;
547
+ }
548
+ if (!cryptoVerify(null, Buffer.from(base, "utf8"), key, sig.item.v))
549
+ return invalid(didKey ? `${label} does not verify with the key that ${keyid} names` : `${label} does not verify with ${agent}'s key ${keyid}`, { agent, keyid });
498
550
  if (nonceKey) {
499
- // checked again: another arrival with this nonce may have verified while the directory was fetched
500
- const until = nonces.get(nonceKey);
501
- if (until !== undefined && until > now())
551
+ // claimed only once the signature verifies, so a forgery cannot spend a nonce; an arrival with this nonce that
552
+ // verified while the directory was fetched has claimed it, and this one is refused
553
+ let claim;
554
+ try {
555
+ claim = await nonces.claim(nonceKey, (Math.min(expires, created + opts.maxAgeSeconds) + skew) * 1000 + 1000);
556
+ }
557
+ catch (e) {
558
+ return { outcome: "unavailable", error: storeDown(e), agent, keyid };
559
+ }
560
+ if (claim === "replayed")
502
561
  return invalid(`${label} repeats a nonce already used`, { agent, keyid });
503
- nonces.set(nonceKey, (Math.min(expires, created + opts.maxAgeSeconds) + skew) * 1000 + 1000);
562
+ if (claim === "full")
563
+ return full;
504
564
  }
505
565
  return { outcome: "verified", agent, keyid, label };
506
566
  }
507
- return { verify, nonces: () => nonces.size };
567
+ return { verify, nonces: () => nonces.size?.() };
508
568
  }
package/docs/approvals.md CHANGED
@@ -67,6 +67,39 @@ The gateway reads `agent-custody/approval` from the call's `_meta` and removes t
67
67
 
68
68
  After facts and any pre-commit authorization have completed, the gateway checks the approval again and atomically consumes its id immediately before forwarding. An approval that expired during those waits, or lost a concurrent race to use the same id, leaves the call `withheld`. Every refusal gets a signed receipt with its reason.
69
69
 
70
+ ## Ask a person: approval requests
71
+
72
+ Signing with `createApproval` in your own review tool works when you already have one. Without one, the gateway can run the loop: it asks, a person signs, and the agent picks the signature up. Add `requests` to `approvals`:
73
+
74
+ ```json
75
+ { "approvals": { "trustedKeys": ["keys/approver.pub"], "usedDir": "approvals-used", "requests": { "dir": "approval-requests" }, "tools": [{ "tool": "stripe.refund" }] } }
76
+ ```
77
+
78
+ A protected call that arrives with no approval in `_meta`, from an agent whose grant covers the tool, is refused as before. The gateway also writes a request to `requests.dir`: the principal, the agent, the tool, the complete arguments, the field mapping, and the number of approvers the rule requires. The agent's refusal names it:
79
+
80
+ ```
81
+ Denied by policy: approval required: request b41a90c4… is waiting for an approver; send the same call again once it is approved
82
+ ```
83
+
84
+ The same id is in the result's `_meta` under `agent-custody/approval-request`, as `{ requestId, status }`. One exact call has one request: the same principal, agent, tool, mapping, and arguments always name the same id, so an agent that retries does not open a second one.
85
+
86
+ The approver works in the [console](console.md)'s **Approvals** tab, which signs in their browser, or from the command line with their own key:
87
+
88
+ ```bash
89
+ agent-custody approvals list --config gateway.json
90
+ agent-custody approvals show <id> --config gateway.json
91
+ agent-custody approvals approve <id> --config gateway.json --key keys/approver.key --expires 10m
92
+ agent-custody approvals deny <id> --config gateway.json --reason "refunded by phone"
93
+ ```
94
+
95
+ `show` prints the complete arguments, not a summary: they are what the approver signs. `approve` signs locally, so the private key never leaves that machine, and writes only the signed envelope, after checking it as the gateway will: a key the gateway does not trust is refused. `--expires` takes `90s`, `10m`, or `1h`, and is refused if it is longer than `maxLifetimeSeconds`. The first signature sets the expiry; a countersignature keeps it, and `approve` prints it. Under a two-person rule, the first `approve` signs and the request stays pending. A second approver's `approve`, with a different key, countersigns it. `list` shows pending requests; `--all` shows decided ones too; `--json` prints them whole.
96
+
97
+ When the agent sends the same call again with no approval in `_meta`, the gateway takes the envelope from the approved request. It checks it exactly as one sent in `_meta`, and consumes it before forwarding. The call after that finds the approval used, opens a new request, and its refusal says so. A call with any argument changed is a different request. A denied request keeps that exact call refused until the request file is deleted. The refusal says that an approver denied it. The reason stays in the request, for `show` and the console: the gateway does not repeat the file's free text to the agent or into the receipt.
98
+
99
+ The request directory is untrusted storage. It carries requests and signed envelopes, and the gateway uses an envelope from it only if it verifies against `trustedKeys` and binds this exact call. A forged file, an envelope signed by another key, or one for other arguments is not used. The refusal says why, and a new request is opened. The same holds for signing: `approve` and the console sign only the call the request names, and add a second signature only to an envelope whose first signature already verifies with a trusted key, binds that call, and is within `maxLifetimeSeconds`. A planted envelope is refused, never countersigned. A single-approver request that carries a signature while pending is refused too. A write to the directory can do no more than an agent can do by sending `_meta`. It can deny, which an operator who can write there could do anyway by not approving.
100
+
101
+ A request holds the complete arguments in clear, because the approver must see what they sign. A capture rule withholds arguments from receipts, not from the request directory. Keep it with the gateway's other private state, mode `0700` as the gateway creates it, and delete requests once they are decided. [Tutorial 57](../examples/57-approval-requests.ts) runs the loop end to end.
102
+
70
103
  ## Consumption and failure recovery
71
104
 
72
105
  `usedDir` is part of the enforcement boundary. Keep it persistent across restarts and share the same directory between all gateway processes that accept the same approvals. The filesystem must support exclusive file creation consistently across those processes, and durable file and directory synchronization. A synchronization failure withholds the call. Separate directories let each gateway consume the same approval once.
@@ -4,12 +4,12 @@ A verified receipt proves what went through the gateway. Nothing on the gateway'
4
4
 
5
5
  ## What it reports
6
6
 
7
- For a window and a set of tools, it lists the provider's objects and matches each to a verified receipt by the provider's object id, which the receipt's result carries.
7
+ For a window and a set of tools, it lists the provider's objects and matches each to a verified receipt. A gateway receipt matches by the provider's object id, which the receipt's result carries. A door receipt matches by its own receipt id, which the provider object carries (see [Door receipts](#door-receipts)). Each match names the kind of the receipt: `gateway`, `sdk`, or `door`.
8
8
 
9
9
  | section | meaning | what to do |
10
10
  | --- | --- | --- |
11
11
  | provider actions with no receipt | an object the provider created in the window that no verified receipt names, or a second object with an id that a receipt already accounts for | the finding this command exists for: an action taken outside the gateway, or by a gateway whose receipts you were not given |
12
- | receipts the provider does not have | an executed receipt in the window whose object the provider has no record of | a receipt for something that did not happen at the provider, or an object in another account or mode |
12
+ | receipts the provider does not have | an executed gateway receipt in the window whose object the provider has no record of; a door receipt is never listed here | a receipt for something that did not happen at the provider, or an object in another account or mode |
13
13
  | mismatches | a matched pair whose amount, currency (ignoring case), or a beneficiary field differs | the receipt and the provider disagree about what happened |
14
14
  | one provider object, several receipts | more than one verified receipt names the same provider object; each is still compared with it | one action recorded twice, or receipts that contradict each other |
15
15
  | forwarded without an outcome receipt | a call committed to the log before it was forwarded (`precommit`) whose outcome receipt is missing | the gateway stopped after forwarding; this explains a provider object that has no receipt, without guessing which one |
@@ -41,15 +41,53 @@ agent-custody completeness --receipts ./receipts --issuer-key gateway.pub --prin
41
41
  | `--object` | `refunds` for Stripe, `pushes` for GitHub | Stripe: `refunds`, `payouts`, or `transfers`. GitHub: `pushes`, `merges`, or `releases` |
42
42
  | `--repo <owner>/<name>` | | GitHub only: the repository to list |
43
43
  | `--key-env NAME` | | the environment variable holding the read-only key or token; never a flag value |
44
- | `--tool <name>` | | each tool whose executed calls create provider objects; repeatable |
44
+ | `--tool <name>` | | each tool whose executed calls create provider objects, or each door route that relays them; repeatable |
45
45
  | `--since`, `--until` | | the window, ISO times; `--until` is exclusive |
46
46
  | `--id-path` | `id` | where the provider's object id sits in the JSON of the result's first text item, a string or an integer; Stripe's own response uses `id` |
47
- | `--amount-field`, `--currency-field` | `amount`, `currency` | the call arguments compared with the provider's amount and currency |
47
+ | `--receipt-id-path` | `metadata.agent_custody_receipt` | where a provider object carries the id of the door receipt that relayed its request |
48
+ | `--amount-field`, `--currency-field` | `amount`, `currency` | the call arguments compared with the provider's amount and currency; for a door receipt, fields of the JSON request body |
48
49
  | `--beneficiary <arg>=<field>` | | a call argument that must equal a provider field, such as `charge=charge` or `customer_id=metadata.customer_id`; repeatable |
49
50
  | `--json` | | the full report as JSON |
50
51
 
51
52
  Use a restricted Stripe key with read-only access to the objects you check. The command only lists objects: it never creates, retries, or reconciles anything. The operator's `reconcile` command is a different thing: it settles one financial operation through the gateway and writes a receipt.
52
53
 
54
+ ## Door receipts
55
+
56
+ A payment can reach Stripe through a site behind the door, and not through the gateway. The door relays the request to the origin, and the origin calls Stripe. The door receipt records the origin's answer only by its size and digest, so it does not hold the Stripe object id. The door sends its receipt id to the origin in the `x-agent-custody-receipt` header. The origin copies that value into the Stripe object:
57
+
58
+ ```js
59
+ await stripe.refunds.create({ charge, amount, metadata: { agent_custody_receipt: req.headers["x-agent-custody-receipt"] } });
60
+ ```
61
+
62
+ Then give the door route as a tool:
63
+
64
+ ```bash
65
+ agent-custody completeness --receipts ./receipts --issuer-key gateway.pub --issuer-key door.pub --principal-key principal.pub \
66
+ --log log.jsonl --provider stripe --object refunds --key-env STRIPE_AUDIT_KEY \
67
+ --tool stripe.refund --tool refund --since 2026-10-01T00:00:00Z --until 2026-11-01T00:00:00Z
68
+ ```
69
+
70
+ A refund made through the gateway matches its gateway receipt. A refund made through the door matches its door receipt. A refund made directly against Stripe's API has no tag, and the report shows it as a provider action with no receipt.
71
+
72
+ A door receipt matches a Stripe object only when both of these are true:
73
+
74
+ - The origin answered with a 2xx status. The door records every answer below 500 as executed, but a 4xx answer made no refund. A refund that carries the id of a refused request is a provider action with no receipt.
75
+ - Stripe created the object within the margin (`marginMs`, default fifteen minutes) of the receipt's time. A refund that carries the id of an older or a later request is a provider action with no receipt.
76
+
77
+ If a capture rule withholds the result, the door receipt shows no status, and it matches no object.
78
+
79
+ What a matched door receipt proves:
80
+
81
+ - The door received a request on that route, the policy decided it, and the door relayed it to the origin. The arrival fact records who the caller was and how the door checked it.
82
+ - The origin answered with a 2xx status, within the margin of the time when Stripe created the object.
83
+ - The Stripe object holds the receipt id. That id is a random UUID that the door made for that one request.
84
+
85
+ What a matched door receipt does not prove:
86
+
87
+ - **That the request caused the refund.** The link between them is the origin's word: the origin copies the tag. An origin can put a valid receipt id on a refund that it made for another reason. The 2xx status and the time limit stop a person who holds the Stripe key from reusing the id of a refused or old request. They do not stop the origin. A second object with an id that is already matched shows as a provider action with no receipt.
88
+ - **The amount, without a capture rule.** By default the door withholds the request body, and the comparison is unmatchable. Keep `body` in clear for the route (`capture: { refund: { args: { mode: "digest", clear: ["method", "path", "body"] } } }`) and the amount, currency, and beneficiary fields are compared with the body. These are the body's field names, not Stripe's.
89
+ - **That a relayed request made a refund.** A door receipt names no Stripe object, so a door receipt with no matching object is not a finding. The report does not list it as a receipt that the provider does not have.
90
+
53
91
  ## GitHub
54
92
 
55
93
  ```bash
@@ -85,6 +123,7 @@ Limits that apply to GitHub only:
85
123
  - **The receipts you were given.** The check proves completeness against those receipts. A second gateway, or a second receipts directory, that issued receipts you were not handed shows up as provider actions with no receipt, which is the correct finding.
86
124
  - **One provider account and mode per run.** Test-mode and live-mode objects are separate lists.
87
125
  - **The id must be readable.** A capture rule that withholds the result content also withholds the object id inside it, and such receipts are reported as unmatchable, never as matched or missing. A rule that keeps `content` in clear (`result: { mode: "digest", clear: ["content"] }`) leaves the id readable. Likewise, keep the amount, currency, and beneficiary arguments in clear, or those comparisons are reported as unmatchable. Reading values from disclosures is still to come.
126
+ - **Door receipts are matched from the provider's side only.** See [Door receipts](#door-receipts).
88
127
  - **Stripe and GitHub.** Other providers, and on-chain transfers from an agent's wallet, are `ProviderSource` implementations still to come.
89
128
 
90
- In code, `checkCompleteness({ receiptsDir, verify, source, tools, sinceMs, untilMs })` returns the report, `stripeSource({ secretKey, object })` lists Stripe objects, `githubSource({ token, repo, object })` lists GitHub objects, and `formatCompleteness(report)` prints it. Example 35 runs the whole check against a stand-in for Stripe's list API, and example 53 runs it against a stand-in for GitHub's activity list.
129
+ In code, `checkCompleteness({ receiptsDir, verify, source, tools, sinceMs, untilMs, receiptIdPath })` returns the report, `stripeSource({ secretKey, object })` lists Stripe objects, `githubSource({ token, repo, object })` lists GitHub objects, and `formatCompleteness(report)` prints it. Example 35 runs the whole check against a stand-in for Stripe's list API, and example 53 runs it against a stand-in for GitHub's activity list.
package/docs/console.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # Gateway console
2
2
 
3
- A small admin service for the person who runs a gateway. It shows what the gateway is configured to do and what it has done, validates and replays a policy change before it is saved, and revokes a grant. It is a separate process from the gateway, behind a token, so the gateway never serves an admin page next to the agents' credentials.
3
+ A small admin service for the person who runs a gateway. It shows what the gateway is configured to do and what it has done, validates and replays a policy change before it is saved, revokes a grant, and puts the gateway's approval requests in front of a person. It is a separate process from the gateway, behind a token, so the gateway never serves an admin page next to the agents' credentials.
4
4
 
5
- It is deliberately limited. It holds **no principal key and signs nothing**, so it cannot issue a grant or widen anyone's authority; everything it shows is read from the gateway's own config, receipts, and revocation file; and the only things it changes are the policy file and the revocation file, both of which the gateway reads. [Example 32](../examples/32-console.ts) runs it end to end.
5
+ It is deliberately limited. It holds **no principal or approver key and signs nothing**, so it cannot issue a grant, approve a call, or widen anyone's authority. Everything it shows is read from the gateway's own config, receipts, revocation file, and approval requests. The only things it changes are the policy file, the revocation file, and the approval requests, all of which the gateway reads. An approval is signed in the approver's browser, not by the console. [Example 32](../examples/32-console.ts) runs it end to end.
6
6
 
7
7
  ## Run it
8
8
 
@@ -32,8 +32,9 @@ It listens on `127.0.0.1:8795` and prints the URL. Open it and sign in with the
32
32
  | **Check** | the same checks as `agent-custody check`, except that the credential variables are **not** checked: the console deliberately does not hold the gateway's credentials, so it cannot tell whether they are set where the gateway runs. "Connect" starts the upstreams and lists their tools only for a config that names no credentials; otherwise it says to run `agent-custody check --connect` where the gateway runs, for example `docker compose exec gateway agent-custody check --config /config/gateway.json --connect`. A connect check that does not finish in 60 seconds is stopped and the upstreams it started are closed ([configuration.md](configuration.md#check-it-before-you-start-it)) |
33
33
  | **Policy** | the policy file in an editor. *Validate* asks Cedar to parse it. *Replay recorded calls* runs it against the verified receipts, using each call's own arguments and facts, and lists the decisions that would change, with their receipts. **A replay only re-decides calls that already happened**: a limit that no recorded call reached, or removing one, can show no change, so it is not a test of what a policy allows. *Save* writes it, keeping the previous version and recording the change |
34
34
  | **Grants** | paste a grant to see whether the gateway would accept it (valid, expired, revoked, signed by a key it does not trust) and what it allows; *Revoke* adds its digest to the revocation file, and the gateway refuses it, and every grant delegated from it, on its next call. Lists the revoked digests |
35
+ | **Approvals** | the requests a gateway with `approvals.requests` left for protected calls that came with no approval: who asked, for which tool, and the exact arguments. *Sign and approve* reads the approver's key file in the browser, signs the call there with WebCrypto, and sends only the signature; the console stores it only if it verifies with one of the gateway's trusted approver keys over this exact call, inside `maxLifetimeSeconds`. Under a two-person rule the second approver's *Countersign* needs a different key, and is refused unless the first signature verifies with a trusted key over this call. *Deny* keeps that call refused until the request is deleted; the reason stays in the request and the audit, and is not repeated to the agent. [Approval requests](approvals.md#ask-a-person-approval-requests) |
35
36
  | **Receipts** | the newest receipts with their agent, tool, decision, and outcome, each verified against the gateway key, the trusted principals, and the local log; a receipt that does not verify says which checks failed; the id in a row opens a summary of the statement, with the full statement behind *Raw JSON* |
36
- | **Audit** | every change made through the console: who, when, and what, with the policy's digest before and after |
37
+ | **Audit** | every change made through the console: who, when, and what, with the policy's digest before and after, and each approval signed (with the key id) or denied |
37
38
 
38
39
  ## Use the page
39
40
 
@@ -42,6 +43,7 @@ It listens on `127.0.0.1:8795` and prints the URL. Open it and sign in with the
42
43
  - **Unsaved policy edits are not lost without a warning.** A tab change with unsaved edits opens a dialog that asks you to discard them or to keep editing. Closing or reloading the page shows the browser's own warning.
43
44
  - **Save and Revoke ask in the page.** The dialog names the policy file or the grant (the agent and the digest). Escape and *Cancel* do nothing. For *Revoke*, the focus starts on *Cancel*.
44
45
  - **A receipt opens from its id.** The id in each row is a button, so the keyboard and a screen reader can open it. The detail shows the tool, the decision, the status, the time, the agent, the principal, whether a grant was presented, the digests, and whether the receipt verifies. The full statement is behind *Raw JSON*. The focus moves to the detail when it opens and returns to the id when you press *Close*.
46
+ - **Signing needs a secure page.** Browsers offer WebCrypto only on `https` or on `localhost`, so the console signs on its default `127.0.0.1` address, or behind TLS. The key file is read by the page and never sent; a browser without Ed25519 in WebCrypto says it cannot sign, and `agent-custody approvals approve` does the same from the command line.
45
47
  - **Times show in your local time.** The UTC value shows when you hold the pointer over a time.
46
48
 
47
49
  ## What a saved policy does
@@ -52,7 +54,7 @@ A running gateway re-reads `policy.cedar` when it changes, so **a saved policy a
52
54
 
53
55
  - **A token on every API route.** It is compared in constant time. Five wrong tokens from one address lock it out for a minute. A request with no token is refused and does not count towards that.
54
56
  - **Loopback by default.** The transport is plain HTTP. Anything beyond one machine needs TLS in front (a proxy or mesh) and a network only administrators can reach. The console has one shared token, not per-user accounts or roles.
55
- - **No keys.** It never reads a principal's private key. It reads the gateway's key file only to take the public half, so that it can verify receipts.
57
+ - **No keys.** It never reads a principal's or an approver's private key. It reads the gateway's key file only to take the public half, so that it can verify receipts. An approver's key is read by the page in their browser to sign, and only the signature reaches the console, which checks it against the gateway's trusted approver keys before storing it. The console token therefore lets someone deny a request, not approve one. It does let them read each request's arguments in clear, including fields that a `capture` rule withholds from receipts, because the Approvals tab shows the approver the exact call.
56
58
  - **The page cannot run what it shows.** Every value is written with `textContent`, never as markup, and the page is served with a content-security-policy that allows exactly its own script and style by hash and nothing else (no inline attributes, no outside requests). The page's own tests check both.
57
59
  - **Bounded input.** A request body over a megabyte is refused, and a receipt id must be a UUID, so a path cannot be read through it.
58
60
  - **Everything it changes is recorded**, in an append-only file in its state directory, and the policy it replaces is kept.
@@ -63,6 +65,7 @@ A running gateway re-reads `policy.cedar` when it changes, so **a saved policy a
63
65
  - It does not edit `gateway.json`: upstreams, facts, and `precommit` are changed in the file, and the gateway restarted. The Overview and Check tabs show them.
64
66
  - The credential variables are not checked in the console, and an upstream that needs one is not started there.
65
67
  - One token, no per-user accounts, and the audit records the address and not a person.
68
+ - An approval in the audit names the key that signed it. Which person holds that key is the operator's to know, as for `agent-custody approvals approve`.
66
69
  - It reads the local receipts directory. With a remote log it verifies receipts against the keys but not the log's inclusion proofs.
67
70
  - A shared gateway has one policy and one key for every agent on it, so the console edits one policy.
68
71
 
@@ -81,6 +84,10 @@ Every route except `GET /` (the page) and `GET /healthz` needs `Authorization: B
81
84
  | `POST /api/grants/inspect` `{ grant }` | status, agent, scopes, window, digest |
82
85
  | `POST /api/grants/revoke` `{ grant }` | add its digest to the revocation file |
83
86
  | `GET /api/revocations` | the revoked digests |
87
+ | `GET /api/approvals` | `{ configured }`, and when requests are on: the pending requests, then up to 50 decided ones, with their exact arguments; `trustedKeyids` and `maxLifetimeSeconds` |
88
+ | `POST /api/approvals/prepare` `{ requestId, expiresInSeconds }` | the payload to sign and its DSSE bytes (`pae`), base64; the payload already signed once under a two-person rule. Nothing is written |
89
+ | `POST /api/approvals/sign` `{ requestId, payload, keyid, sig }` | stores the signature if it verifies with a trusted approver key and binds this request's call inside `maxLifetimeSeconds`; 409 otherwise |
90
+ | `POST /api/approvals/deny` `{ requestId, reason? }` | marks the request denied |
84
91
  | `GET /api/receipts?limit=` | recent receipts with their verdicts; `GET /api/receipts/<id>` is one statement |
85
92
  | `GET /api/audit` | the console's audit trail |
86
93