@agent-custody/receipts 0.6.19 → 0.8.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.
Files changed (50) hide show
  1. package/README.md +20 -11
  2. package/dist/a2a.js +19 -7
  3. package/dist/approval.d.ts +74 -0
  4. package/dist/approval.js +196 -0
  5. package/dist/capture.d.ts +153 -0
  6. package/dist/capture.js +607 -0
  7. package/dist/cli.js +221 -6
  8. package/dist/config.d.ts +144 -0
  9. package/dist/config.js +92 -3
  10. package/dist/crypto.d.ts +2 -2
  11. package/dist/crypto.js +7 -4
  12. package/dist/delegation.d.ts +7 -0
  13. package/dist/delegation.js +15 -1
  14. package/dist/gateway-http.js +13 -1
  15. package/dist/gateway.d.ts +15 -0
  16. package/dist/gateway.js +414 -27
  17. package/dist/index.d.ts +4 -0
  18. package/dist/index.js +4 -0
  19. package/dist/issue.d.ts +20 -5
  20. package/dist/issue.js +76 -8
  21. package/dist/log-sink.d.ts +11 -1
  22. package/dist/log-sink.js +24 -5
  23. package/dist/operations.d.ts +101 -0
  24. package/dist/operations.js +239 -0
  25. package/dist/otel.js +16 -8
  26. package/dist/portal.d.ts +23 -2
  27. package/dist/portal.js +181 -36
  28. package/dist/receipt.d.ts +54 -8
  29. package/dist/rest.js +14 -1
  30. package/dist/retention.d.ts +8 -1
  31. package/dist/retention.js +21 -2
  32. package/dist/sdk/index.js +10 -1
  33. package/dist/simulate.d.ts +58 -0
  34. package/dist/simulate.js +204 -0
  35. package/dist/splunk.js +17 -8
  36. package/dist/upstream.d.ts +9 -7
  37. package/dist/upstream.js +16 -8
  38. package/dist/verify.d.ts +18 -0
  39. package/dist/verify.js +405 -15
  40. package/docs/approvals.md +107 -0
  41. package/docs/compliance.md +1 -1
  42. package/docs/financial-operations.md +99 -0
  43. package/docs/policies.md +22 -0
  44. package/docs/tutorials.md +7 -0
  45. package/docs/usage.md +71 -5
  46. package/docs/verification.md +35 -10
  47. package/package.json +1 -1
  48. package/vectors/audit.json +27 -27
  49. package/vectors/canonical.json +5 -5
  50. package/vectors/receipts.json +3612 -292
package/dist/verify.js CHANGED
@@ -1,10 +1,167 @@
1
1
  // Independent verification of a receipt bundle. Needs only public keys, and optionally a copy of the log.
2
2
  import { canonicalize, digestOf, dsseVerifiers, dsseVerify } from "./crypto.js";
3
+ import { isApprovalTime, verifyApproval, verifyApprovalStatement } from "./approval.js";
4
+ import { digestSaltFor, getAt, isCommitment, pathKey, pathText, restorePaths, under } from "./capture.js";
3
5
  import { delegationHasParent, delegationValidAt, describeChain, verifyDelegation } from "./delegation.js";
4
6
  import { leafHash, MerkleLog, verifyConsistency, verifyInclusion } from "./log.js";
5
7
  import { checkProvider, checkUpstream, contentDigest, isProviderAttestation } from "./upstream.js";
6
8
  import { AUTHORIZATION_PREDICATE_TYPE, RECEIPT_PREDICATE_TYPE, RECEIPT_TYPE, TREEHEAD_TYPE } from "./receipt.js";
7
9
  const short = (s) => s.slice(0, 12);
10
+ const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
11
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12
+ const hex64 = (v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v);
13
+ function operationProblem(o) {
14
+ if (!isObject(o) || (o.id !== undefined && (typeof o.id !== "string" || !UUID.test(o.id))) || typeof o.originalReceiptId !== "string" || !UUID.test(o.originalReceiptId))
15
+ return "operation ids are not UUIDs";
16
+ if (!hex64(o.idempotencyKey) || !hex64(o.lookupDigest))
17
+ return "operation idempotencyKey or lookupDigest is not a sha256";
18
+ if (!["submitted", "pending", "confirmed", "failed", "unknown"].includes(String(o.status)) || o.provenance !== "observed")
19
+ return "operation status or provenance is invalid";
20
+ if (!isObject(o.budget) || typeof o.budget.id !== "string" || !o.budget.id.length || o.budget.id.length > 128 || typeof o.budget.currency !== "string" || !/^[A-Z]{3}$/.test(o.budget.currency) || typeof o.budget.period !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(o.budget.period))
21
+ return "operation budget is invalid";
22
+ return null;
23
+ }
24
+ /** Provider records are JSON in the first text result, just as the gateway's ordinary fact extraction reads them. */
25
+ function providerValue(result, path) {
26
+ let record;
27
+ if (isObject(result) && Array.isArray(result.content)) {
28
+ const text = result.content.find((c) => isObject(c) && c.type === "text");
29
+ if (isObject(text) && typeof text.text === "string") {
30
+ try {
31
+ record = JSON.parse(text.text);
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ }
37
+ }
38
+ return path.split(".").reduce((v, k) => isObject(v) && Object.hasOwn(v, k) ? v[k] : undefined, record);
39
+ }
40
+ /** Verify a pre-forward authorization on its own when a crash prevented an outcome receipt being written. */
41
+ function verifyOriginalAuthorization(bundle, opts) {
42
+ const checks = [];
43
+ const add = (name, ok, detail) => checks.push({ name, ok, ...(detail === undefined ? {} : { detail }) });
44
+ const sig = dsseVerify(bundle.envelope, opts.issuerKeys);
45
+ const st = sig.ok ? sig.payload : null;
46
+ const typed = !!st && bundle.envelope.payloadType === RECEIPT_TYPE && st.predicateType === AUTHORIZATION_PREDICATE_TYPE;
47
+ add("authorization signature (issuer key)", sig.ok && typed);
48
+ if (!sig.ok || !st || !typed)
49
+ return { ok: false, predicate: null, checks };
50
+ const p = st.predicate;
51
+ // Authorizations have no session, model, or execution; validate the parts they share with ordinary receipts.
52
+ const problem = structuralProblem({ ...p, session: { id: null, toolUseId: null, provenance: "claimed" }, model: { id: null, provenance: "claimed" }, execution: { status: "withheld", provenance: "observed" } });
53
+ add("structural parts in clear", !problem, problem ?? undefined);
54
+ if (problem)
55
+ return { ok: false, predicate: null, checks };
56
+ add("authorization issued by the gateway", p.issuer.kind === "gateway" && p.issuer.keyid === sig.keyid);
57
+ add("authorization operation is submitted", p.operation?.status === "submitted");
58
+ add("authorization permits the original call", p.policy?.decision === "allow" ? Array.isArray(p.policy.errors) && p.policy.errors.length === 0 : p.policy?.decision === "deny" && p.policy.enforced === false);
59
+ const del = p.delegation && verifyDelegation(p.delegation.envelope, opts.principalKeys);
60
+ add("delegation signature (principal key)", !!del?.ok);
61
+ if (del?.ok) {
62
+ const d = del.delegation;
63
+ add("delegation binds principal and agent", d.principal === p.principal.id && d.agent === p.agent.id && p.principal.provenance === "attested" && p.principal.keyid === del.keyid);
64
+ add("delegation valid at receipt time", delegationValidAt(d, p.timestamp));
65
+ add("executed tool within delegated scope", d.scopes.includes(p.tool.name));
66
+ }
67
+ const back = restorePaths(p, p.capture, undefined, opts.captureKey);
68
+ add("captured commitments are well formed", back.problems.length === 0, back.problems[0]?.error);
69
+ const missingArgs = back.missing.some((w) => under(w, ["request", "args"]));
70
+ add("request args digest", st.subject[0]?.digest.sha256 === p.request.argsDigest && (missingArgs || digestOf(back.predicate.request.args, digestSaltFor(back, p.capture, ["request", "args"])) === p.request.argsDigest));
71
+ const th = dsseVerify(bundle.treeHead, [...(opts.logKeys ?? []), ...opts.issuerKeys]);
72
+ add("tree head signature", th.ok && bundle.treeHead.payloadType === TREEHEAD_TYPE);
73
+ if (th.ok) {
74
+ const head = th.payload;
75
+ if (opts.logId !== undefined)
76
+ add("tree head names the expected log", head.log === opts.logId);
77
+ add("log inclusion proof", head.treeSize === bundle.inclusion.treeSize && verifyInclusion(leafHash(canonicalize(bundle.envelope)), bundle.inclusion, head.rootHash));
78
+ if (opts.logFile) {
79
+ try {
80
+ add("log file root matches tree head", MerkleLog.rootFromFile(opts.logFile, head.treeSize) === head.rootHash);
81
+ }
82
+ catch {
83
+ add("log file root matches tree head", false);
84
+ }
85
+ }
86
+ }
87
+ return { ok: checks.every((c) => c.ok), predicate: p, checks };
88
+ }
89
+ /** The parts of a statement a capture note may never name: what a verifier reads to run its checks. A note naming one, or a commitment sitting there, is not a private receipt but a broken one. */
90
+ const STRUCTURAL_TOP = new Set(["receiptId", "timestamp", "issuer", "principal", "agent", "delegation", "tool", "authorization", "capture"]);
91
+ // The approval record's envelope and reason are withheld under a private rule; its status, times, and signer ids are not.
92
+ const STRUCTURAL_IN = { approval: new Set(["status", "requiredApprovers", "checkedAt", "consumedAt", "approverKeyids", "fields", "provenance"]), request: new Set(["argsDigest", "provenance"]), execution: new Set(["status", "provenance"]), policy: new Set(["decision", "reasons", "policyDigest", "enforced", "provenance"]), consumed: new Set(["provenance"]), session: new Set(["provenance"]), model: new Set(["provenance"]), operation: new Set(["idempotencyKey", "lookupDigest", "status", "budget", "originalReceiptId", "provenance"]), reconciliation: new Set(["original", "lookup"]) };
93
+ /**
94
+ * Why a statement cannot be verified at all, or null: the capture note is malformed, names a structural part, or a
95
+ * structural part is not what every check assumes it to be. Checked once, before anything reads the statement, so that
96
+ * a crafted note cannot hide the status, the tool, the decision, or the digests behind a commitment and still verify.
97
+ */
98
+ export function structuralProblem(p) {
99
+ if (!isObject(p))
100
+ return "the predicate is not an object";
101
+ const note = p.capture;
102
+ if (note !== undefined) {
103
+ if (!isObject(note) || (note.mode !== "digest" && note.mode !== "encrypted") || !Array.isArray(note.withheld))
104
+ return "the capture note is malformed";
105
+ if (new Set(note.withheld.map((w) => JSON.stringify(w))).size !== note.withheld.length)
106
+ return "the capture note names a path twice";
107
+ for (const w of note.withheld) {
108
+ if (!Array.isArray(w) || w.length === 0 || !w.every((s) => typeof s === "string"))
109
+ return "the capture note names a malformed path";
110
+ const path = w;
111
+ const head = path[0];
112
+ const named = STRUCTURAL_TOP.has(head) || (path.length === 1 && Object.hasOwn(STRUCTURAL_IN, head)) || (path.length === 2 && Object.hasOwn(STRUCTURAL_IN, head) && STRUCTURAL_IN[head].has(path[1])) || head === "facts" && (path.length <= 2 || path[2] === "tool" || path[2] === "provenance") || (head === "execution" && path.length === 2 && path[1] === "upstream") || (head === "execution" && path.length === 3 && path[1] === "upstream" && path[2] === "provider") || (head === "execution" && path.length === 3 && path[1] === "result" && path[2] === "isError");
113
+ if (named)
114
+ return `the capture note names a structural part: ${pathText(path)}`;
115
+ }
116
+ }
117
+ if (typeof p.receiptId !== "string" || typeof p.timestamp !== "string")
118
+ return "receiptId or timestamp is not a string";
119
+ if (!isObject(p.issuer) || !isObject(p.principal) || !isObject(p.agent) || !isObject(p.session) || !isObject(p.model))
120
+ return "issuer, principal, agent, session, or model is not an object";
121
+ if (!isObject(p.tool) || typeof p.tool.name !== "string")
122
+ return "tool.name is not a string";
123
+ if (!isObject(p.request) || typeof p.request.argsDigest !== "string" || !isObject(p.request.args))
124
+ return "request.args or request.argsDigest is not what it should be";
125
+ if (!isObject(p.execution) || typeof p.execution.status !== "string" || !["executed", "failed", "denied", "error", "withheld"].includes(p.execution.status))
126
+ return "execution.status is not a status";
127
+ if (p.policy !== null && (!isObject(p.policy) || (p.policy.decision !== "allow" && p.policy.decision !== "deny") || !Array.isArray(p.policy.reasons)))
128
+ return "policy is neither null nor a decision";
129
+ if (!isObject(p.facts) || Object.values(p.facts).some((f) => !isObject(f) || typeof f.tool !== "string"))
130
+ return "facts is not a map of facts";
131
+ if (p.consumed !== undefined && !isObject(p.consumed))
132
+ return "consumed is not an object";
133
+ if (p.delegation !== undefined && (!isObject(p.delegation) || !isObject(p.delegation.envelope)))
134
+ return "delegation is not a signed envelope";
135
+ if (p.authorization !== undefined && (!isObject(p.authorization) || !isObject(p.authorization.envelope)))
136
+ return "authorization is not a bundle";
137
+ if (p.approval !== undefined) {
138
+ const a = p.approval;
139
+ if (!isObject(a) || typeof a.status !== "string" || !["approved", "denied"].includes(a.status) || (a.requiredApprovers !== 1 && a.requiredApprovers !== 2) || !isApprovalTime(a.checkedAt) || !Array.isArray(a.approverKeyids) || !a.approverKeyids.every((k) => typeof k === "string") || a.provenance !== "observed")
140
+ return "approval is not an approval record";
141
+ if (a.consumedAt !== undefined && !isApprovalTime(a.consumedAt))
142
+ return "approval consumption time is not a timestamp";
143
+ if (a.fields !== undefined && (!isObject(a.fields) || Object.entries(a.fields).some(([k, v]) => !["amount", "currency", "beneficiary"].includes(k) || typeof v !== "string" || !v.length)))
144
+ return "approval field mapping is malformed";
145
+ }
146
+ if (p.operation !== undefined) {
147
+ const problem = operationProblem(p.operation);
148
+ if (problem)
149
+ return problem;
150
+ }
151
+ if (p.reconciliation !== undefined) {
152
+ const r = p.reconciliation;
153
+ if (!isObject(r) || !isObject(r.original) || !isObject(r.original.envelope) || !isObject(r.original.treeHead) || !isObject(r.original.inclusion) || !isObject(r.lookup))
154
+ return "reconciliation is not a lookup and an original bundle";
155
+ const l = r.lookup;
156
+ const statuses = (v) => Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === "string" && s.length > 0 && s.length <= 128);
157
+ const path = (v) => typeof v === "string" && v.length > 0 && v.length <= 512 && v.split(".").every((s) => s.length > 0);
158
+ if (typeof l.tool !== "string" || !l.tool.length || !isObject(l.args) || !path(l.statusPath) || !path(l.identityPath) || !statuses(l.confirmed) || !statuses(l.failed) || l.confirmed.some((s) => l.failed.includes(s)))
159
+ return "reconciliation lookup is malformed or its terminal statuses overlap";
160
+ }
161
+ if (isObject(p.execution.upstream) && typeof p.execution.upstream.provider !== "undefined" && typeof p.execution.upstream.provider !== "string")
162
+ return "execution.upstream.provider is not a string";
163
+ return null;
164
+ }
8
165
  export function verifyBundle(bundle, opts) {
9
166
  const checks = [];
10
167
  const add = (name, ok, detail) => {
@@ -21,9 +178,23 @@ export function verifyBundle(bundle, opts) {
21
178
  const st = sig.payload;
22
179
  if (!add("receipt payload type", bundle.envelope.payloadType === RECEIPT_TYPE && st.predicateType === RECEIPT_PREDICATE_TYPE))
23
180
  return done(null);
181
+ const broken = structuralProblem(st.predicate);
182
+ if (!add("structural parts in clear", !broken, broken ?? undefined))
183
+ return done(null);
24
184
  const p = st.predicate;
25
185
  add("issuer kind is known", p.issuer.kind === "gateway" || p.issuer.kind === "sdk", `${p.issuer.kind}${p.issuer.framework ? ` / ${p.issuer.framework}` : ""}`);
26
186
  add("issuer keyid matches signer", p.issuer.keyid === sig.keyid);
187
+ if (p.operation) {
188
+ add("operation observed by gateway", p.issuer.kind === "gateway" && p.operation.provenance === "observed");
189
+ if (!p.reconciliation) {
190
+ // A retry of an existing operation has a receipt of its own. It is withheld (never forwarded again) and names the original.
191
+ const retry = p.operation.originalReceiptId !== p.receiptId;
192
+ add("operation names this original receipt", !retry || p.execution.status === "withheld");
193
+ const refused = p.execution.status === "withheld" || p.execution.status === "denied";
194
+ add("operation awaits provider reconciliation", retry || ["submitted", "pending", "unknown"].includes(p.operation.status) || refused && p.operation.status === "failed");
195
+ add("operation carries committed authorization", refused || !!p.authorization);
196
+ }
197
+ }
27
198
  if (p.issuer.kind === "gateway") {
28
199
  add("gateway receipt carries a delegation", p.delegation !== undefined);
29
200
  add("gateway receipt carries a policy decision", p.policy !== null);
@@ -40,34 +211,223 @@ export function verifyBundle(bundle, opts) {
40
211
  const d = del.delegation;
41
212
  const principalKeyid = p.principal.provenance === "attested" ? p.principal.keyid : null;
42
213
  add("delegation binds principal and agent", d.principal === p.principal.id && d.agent === p.agent.id && del.keyid === principalKeyid);
43
- add("delegation valid at receipt time", delegationValidAt(d, p.timestamp), `${d.issuedAt} .. ${d.expiresAt}`);
44
214
  const inScope = d.scopes.includes(p.tool.name);
45
215
  const executed = p.execution.status === "executed" || p.execution.status === "failed";
216
+ // a call the gateway refused after the grant ran out is still a true record; only an executed call has to sit inside the window
217
+ const valid = delegationValidAt(d, p.timestamp);
218
+ add("delegation valid at receipt time", valid || !executed || !!p.reconciliation, valid ? `${d.issuedAt} .. ${d.expiresAt}` : p.reconciliation ? "operator reconciliation; the original authorization's grant window is checked separately" : `${d.issuedAt} .. ${d.expiresAt}; the call was ${p.execution.status}, so the grant need not have been in force`);
46
219
  add("executed tool within delegated scope", !executed || inScope, inScope ? p.tool.name : `${p.tool.name} not in [${d.scopes.join(", ")}]`);
47
220
  }
48
221
  }
49
222
  else {
50
223
  add("principal is claimed, not attested", p.principal.provenance === "claimed", "no signed delegation in this receipt");
51
224
  }
52
- add("request args digest", digestOf(p.request.args) === p.request.argsDigest && st.subject[0]?.digest.sha256 === p.request.argsDigest);
53
- if ((p.execution.status === "executed" || p.execution.status === "failed") && p.execution.upstream) {
54
- const result = p.execution.result;
55
- if (isProviderAttestation(p.execution.upstream)) {
225
+ // Private evidence: the signed capture note names every path whose value is withheld behind a commitment. Each path
226
+ // is put back when the receipt carries the value, when it is disclosed, or when the capture key reveals it; a digest
227
+ // over values that are all back is recomputed (with the salt the statement carries), and otherwise the check passes
228
+ // as a commitment and says so. The note decides, never the shape of the data: a path it names must hold a
229
+ // commitment, and commitment-shaped data it does not name is ordinary data, inside the digest.
230
+ const subjectOk = st.subject[0]?.digest.sha256 === p.request.argsDigest;
231
+ const note = p.capture;
232
+ if (opts.disclosed && typeof opts.disclosed === "object" && "receiptId" in opts.disclosed && opts.disclosed.receiptId !== undefined) {
233
+ add("disclosure names this receipt", opts.disclosed.receiptId === p.receiptId, opts.disclosed.receiptId === p.receiptId ? undefined : `the disclosure is for receipt ${String(opts.disclosed.receiptId)}`);
234
+ }
235
+ const back = restorePaths(p, note, opts.disclosed, opts.captureKey);
236
+ const full = back.predicate;
237
+ const committedNote = (paths) => {
238
+ const encrypted = paths.filter((w) => getAt(p, w)?.$custody === "encrypted").length;
239
+ return `committed, not recomputed: ${paths.length} value(s) withheld${encrypted ? ` (${encrypted} encrypted)` : ""}; ${encrypted ? "give the capture key or " : ""}disclose them to recompute`;
240
+ };
241
+ const claimed = new Set();
242
+ /** the state of the withheld paths under a prefix, and the paths it claims for its check line */
243
+ const region = (prefix) => {
244
+ const paths = (note?.withheld ?? []).filter((w) => under(w, prefix));
245
+ for (const w of paths)
246
+ claimed.add(pathKey(w));
247
+ const problem = back.problems.find((x) => under(x.path, prefix))?.error ?? null;
248
+ const missing = back.missing.filter((w) => under(w, prefix));
249
+ const hows = [...new Set(paths.map((w) => back.restored.get(pathKey(w))).filter((h) => !!h))];
250
+ const how = hows.length === 2 ? "disclosed and decrypted" : hows[0];
251
+ return { paths, problem, missing, how };
252
+ };
253
+ const args = region(["request", "args"]);
254
+ if (args.problem)
255
+ add("request args digest", false, args.problem);
256
+ else if (args.missing.length)
257
+ add("request args digest", subjectOk, committedNote(args.missing));
258
+ else
259
+ add("request args digest", digestOf(full.request.args, digestSaltFor(back, note, ["request", "args"])) === p.request.argsDigest && subjectOk, args.how ? `recomputed from ${args.how} values` : undefined);
260
+ // An upstream error can follow a side effect too; every attempted forward must have consumed a valid approval.
261
+ const forwarded = ["executed", "failed", "error"].includes(p.execution.status);
262
+ if (p.approval) {
263
+ const a = p.approval;
264
+ const consumed = a.consumedAt !== undefined && Date.parse(a.consumedAt) >= Date.parse(a.checkedAt) && Date.parse(a.checkedAt) >= Date.parse(p.timestamp);
265
+ add("approval consistent with execution", !forwarded || (a.status === "approved" && consumed), a.status === "denied" ? `approval refused: ${typeof a.reason === "string" ? a.reason : "not approved"}` : "single use is enforced by the gateway's persistent store; one receipt cannot prove absence of reuse elsewhere");
266
+ // Only a forwarded call must rest on a valid approval. A refusal is an authentic record whatever its approval was:
267
+ // missing, expired, forged, already used, or valid for a call that the policy or the grant then refused.
268
+ if (forwarded && a.status === "approved") {
269
+ // The envelope is withheld under a private rule: it carries the action fields and a digest of the arguments.
270
+ const sealed = region(["approval", "envelope"]);
271
+ if (sealed.problem)
272
+ add("approval signatures (human keys)", false, sealed.problem);
273
+ // The issuer withholds the envelope only when it withholds the arguments. With the arguments in clear, a withheld
274
+ // envelope would let an issuer skip the binding check, so it fails rather than passes as committed.
275
+ else if (sealed.missing.length && !args.paths.length)
276
+ add("approval signatures (human keys)", false, "the approval envelope is withheld but the arguments are in clear; the binding cannot be checked");
277
+ else if (sealed.missing.length)
278
+ add("approval signatures (human keys)", true, committedNote(sealed.missing));
279
+ else {
280
+ const envelope = full.approval.envelope;
281
+ const signed = verifyApprovalStatement(envelope, opts.approvalKeys ?? [], a.requiredApprovers);
282
+ const reported = signed.ok && new Set(a.approverKeyids).size >= a.requiredApprovers && a.approverKeyids.every((id) => signed.approverKeyids.includes(id));
283
+ add("approval signatures (human keys)", signed.ok && reported, signed.ok ? `${signed.approverKeyids.length} distinct trusted signature(s)` : signed.error);
284
+ if (signed.ok) {
285
+ const at = a.consumedAt ?? a.checkedAt;
286
+ const valid = [a.checkedAt, at].every((time) => Date.parse(time) >= Date.parse(signed.approval.issuedAt) && Date.parse(time) < Date.parse(signed.approval.expiresAt));
287
+ add("approval valid at forward time", valid, `${signed.approval.issuedAt} .. ${signed.approval.expiresAt}; checked at ${at}`);
288
+ if (args.problem)
289
+ add("approval payload binding", false, args.problem);
290
+ else if (args.missing.length)
291
+ add("approval payload binding", true, committedNote(args.missing));
292
+ else {
293
+ const binding = verifyApproval(envelope, opts.approvalKeys ?? [], { principal: p.principal.id ?? "", agent: p.agent.id, tool: p.tool.name, args: full.request.args, ...(a.fields ? { fields: a.fields } : {}) }, { at, minApprovers: a.requiredApprovers });
294
+ add("approval payload binding", binding.ok, binding.ok ? "principal, agent, tool, full arguments, amount, currency, and beneficiary match" : binding.error);
295
+ }
296
+ }
297
+ }
298
+ }
299
+ }
300
+ // a captured fact: its commitments are checked against a disclosure or the key; the policy decided on the real value
301
+ for (const name of Object.keys(p.facts)) {
302
+ for (const part of ["value", "args"]) {
303
+ const r = region(["facts", name, part]);
304
+ if (!r.paths.length)
305
+ continue;
306
+ if (r.problem)
307
+ add(`fact ${name} ${part}`, false, r.problem);
308
+ else
309
+ add(`fact ${name} ${part}`, true, r.missing.length ? committedNote(r.missing) : `commitments hold against the ${r.how} value`);
310
+ }
311
+ }
312
+ const executedOrFailed = p.execution.status === "executed" || p.execution.status === "failed";
313
+ let result = null;
314
+ if (executedOrFailed) {
315
+ const r = region(["execution", "result"]);
316
+ const ex = full.execution;
317
+ if (r.problem)
318
+ add("execution result digest", false, r.problem);
319
+ else if (r.missing.length) {
320
+ add("execution result digest", true, committedNote(r.missing));
321
+ // the upstream checks read the content, isError, and structuredContent, never _meta, which carries what the
322
+ // upstream wrote and is withheld beside a result the rule leaves in clear: with only _meta withheld they still run
323
+ if (r.missing.every((w) => pathKey(w) === pathKey(["execution", "result", "_meta"])))
324
+ result = ex.result;
325
+ }
326
+ else {
327
+ add("execution result digest", digestOf(ex.result, digestSaltFor(back, note, ["execution", "result"])) === ex.resultDigest, r.how ? `recomputed from ${r.how} values` : undefined);
328
+ result = ex.result;
329
+ }
330
+ }
331
+ // every other withheld path gets its own line: a message, a denial reason, a provider's delivery body, a part added later
332
+ for (const w of note?.withheld ?? []) {
333
+ if (claimed.has(pathKey(w)))
334
+ continue;
335
+ const problem = back.problems.find((x) => pathKey(x.path) === pathKey(w))?.error;
336
+ const how = back.restored.get(pathKey(w));
337
+ add(`withheld ${pathText(w)}`, !problem, problem ?? (how ? `holds against the ${how} value` : committedNote([w])));
338
+ }
339
+ const evidence = executedOrFailed && "upstream" in p.execution ? p.execution.upstream : undefined;
340
+ if (executedOrFailed && evidence) {
341
+ // The evidence as restored: the delivery body or the signed envelope may have been withheld with the result. A
342
+ // check is skipped only for a part the signed note declares withheld and the verifier could not restore; a body
343
+ // or an envelope that is simply not there, or commitment-shaped without the note saying so, fails the check.
344
+ const restoredEvidence = full.execution.upstream;
345
+ const withheldStill = (path) => (note?.withheld ?? []).some((w) => pathKey(w) === pathKey(path)) && back.missing.some((w) => pathKey(w) === pathKey(path));
346
+ if (isProviderAttestation(evidence)) {
56
347
  if (opts.providerSecrets) {
57
- const u = checkProvider(p.execution.upstream, opts.providerSecrets, { timestamp: p.timestamp, result });
58
- add("upstream signature (provider secret)", u.ok, u.ok ? u.keyid : u.error);
348
+ const re = restoredEvidence;
349
+ const parts = ["rawBody", "signature", "bind"];
350
+ if (!result || parts.some((f) => withheldStill(["execution", "upstream", f])))
351
+ add("upstream signature not checked", true, "the result, the delivery body, its signature, or its bind is withheld; disclose them or give the capture key to check the provider's delivery");
352
+ else if (parts.some((f) => typeof re?.[f] !== "string"))
353
+ add("upstream signature (provider secret)", false, "the receipt carries no delivery body, signature, or bind to check, and the capture note does not say they are withheld");
354
+ else {
355
+ const u = checkProvider({ ...evidence, rawBody: re.rawBody, signature: re.signature, bind: re.bind }, opts.providerSecrets, { timestamp: p.timestamp, result });
356
+ add("upstream signature (provider secret)", u.ok, u.ok ? u.keyid : u.error);
357
+ }
59
358
  }
60
359
  }
61
360
  else if ((opts.upstreamKeys?.length ?? 0) > 0) {
62
- const u = checkUpstream(p.execution.upstream.envelope, opts.upstreamKeys, { receiptId: p.receiptId, tool: p.tool.name, contentDigest: contentDigest(result) });
63
- add("upstream signature (upstream key)", u.ok, u.ok ? `keyid ${short(u.keyid)}` : u.error);
361
+ const env = restoredEvidence?.envelope;
362
+ const wellFormed = !!env && typeof env === "object" && typeof env.payload === "string" && Array.isArray(env.signatures);
363
+ if (!result)
364
+ add("upstream signature not checked", true, "the result is withheld; disclose it or give the capture key to check the upstream's signature against it");
365
+ // the issuer withholds the envelope beside a result it leaves in clear only when the envelope is anything but the plain attestation for this call (a field, a claim, or an encoding the upstream added); a verifier given the upstream's key is then told, not waved past
366
+ else if (withheldStill(["execution", "upstream", "envelope"]))
367
+ add("upstream signature (upstream key)", false, "the result is in clear but the upstream's signature is withheld; disclose it or give the capture key to check it");
368
+ else if (!wellFormed)
369
+ add("upstream signature (upstream key)", false, "the receipt carries no upstream envelope to check, and the capture note does not say it is withheld");
370
+ else {
371
+ const u = checkUpstream(env, opts.upstreamKeys, { receiptId: p.receiptId, tool: p.tool.name, contentDigest: contentDigest(result) });
372
+ add("upstream signature (upstream key)", u.ok, u.ok ? `keyid ${short(u.keyid)}` : u.error);
373
+ }
64
374
  }
65
375
  }
66
376
  if (p.policy) {
67
377
  // a deny that was not enforced (observe mode, enforced: false on the receipt) may sit beside an executed call; an enforced one never does
68
378
  const consistent = p.policy.decision === "allow" ? p.execution.status !== "denied" : p.policy.enforced === false ? p.execution.status !== "denied" : p.execution.status === "denied";
69
379
  add("policy decision consistent with execution", consistent, `${p.policy.decision}${p.policy.enforced === false ? " (observe mode, not enforced)" : ""} -> ${p.execution.status}`);
70
- add("no policy errors on an allow", !(p.policy.decision === "allow" && p.policy.errors.length > 0));
380
+ // a withheld error list is a non-empty one: the issuer leaves an empty list in clear
381
+ const errors = isCommitment(p.policy.errors) || (Array.isArray(p.policy.errors) && p.policy.errors.length > 0);
382
+ add("no policy errors on an allow", !(p.policy.decision === "allow" && errors));
383
+ }
384
+ if (p.reconciliation) {
385
+ const r = p.reconciliation;
386
+ // Refuse nesting before the recursive verifier is called; the original must be the first operation attempt.
387
+ const osig = dsseVerify(r.original.envelope, opts.issuerKeys);
388
+ const ost = osig.ok ? osig.payload : null;
389
+ const original = ost?.predicate;
390
+ const eligible = isObject(original) && !("reconciliation" in original);
391
+ let originalOk = false;
392
+ if (eligible && ost) {
393
+ try {
394
+ const nested = ost.predicateType === RECEIPT_PREDICATE_TYPE
395
+ ? verifyBundle(r.original, { ...opts, disclosed: undefined })
396
+ : verifyOriginalAuthorization(r.original, opts);
397
+ originalOk = nested.ok;
398
+ for (const c of nested.checks)
399
+ add(`reconciliation original ${c.name}`, c.ok, c.detail);
400
+ }
401
+ catch {
402
+ add("reconciliation original bundle is well formed", false);
403
+ }
404
+ }
405
+ add("reconciliation original evidence verifies", eligible && originalOk);
406
+ const o = original?.operation;
407
+ const op = p.operation;
408
+ const linked = !!o && !!op && !operationProblem(o) && ["submitted", "pending", "unknown"].includes(o.status) && o.originalReceiptId === original.receiptId && op.originalReceiptId === original.receiptId && p.receiptId !== original.receiptId && (op.id === undefined || o.id === undefined || op.id === o.id) && op.idempotencyKey === o.idempotencyKey && op.lookupDigest === o.lookupDigest && canonicalize(op.budget) === canonicalize(o.budget) && canonicalize(p.principal) === canonicalize(original.principal) && canonicalize(p.agent) === canonicalize(original.agent) && canonicalize(p.tool) === canonicalize(original.tool) && canonicalize(p.delegation) === canonicalize(original.delegation) && p.issuer.keyid === original.issuer.keyid && Date.parse(p.timestamp) >= Date.parse(original.timestamp);
409
+ add("reconciliation links the original operation", linked);
410
+ add("reconciliation lookup matches authorization", !!o && digestOf(r.lookup) === o.lookupDigest);
411
+ const lookupArgs = region(["request", "args"]);
412
+ add("reconciliation lookup args match request", !lookupArgs.problem && (lookupArgs.missing.length > 0 || canonicalize(full.request.args) === canonicalize(r.lookup.args)), lookupArgs.missing.length > 0 ? "request arguments committed under the capture rule" : undefined);
413
+ const before = r.original.inclusion.leafIndex < bundle.inclusion.leafIndex && r.original.inclusion.treeSize <= bundle.inclusion.treeSize;
414
+ const oth = dsseVerify(r.original.treeHead, [...(opts.logKeys ?? []), ...opts.issuerKeys]);
415
+ const cth = dsseVerify(bundle.treeHead, [...(opts.logKeys ?? []), ...opts.issuerKeys]);
416
+ add("reconciliation logged after original", before && oth.ok && cth.ok && isObject(oth.payload) && isObject(cth.payload) && oth.payload.log === cth.payload.log);
417
+ const terminal = op?.status === "confirmed" || op?.status === "failed";
418
+ add("reconciliation records a terminal provider outcome", terminal && p.execution.status === "executed" && p.execution.provenance === "observed");
419
+ const rr = region(["execution", "result"]);
420
+ if (rr.problem)
421
+ add("reconciliation provider status", false, rr.problem);
422
+ else if (rr.missing.some((w) => pathKey(w) !== pathKey(["execution", "result", "_meta"])))
423
+ add("reconciliation provider status", true, "provider result withheld; disclose it or give the capture key to recompute the gateway-observed status");
424
+ else {
425
+ const ex = full.execution;
426
+ const status = providerValue(ex.result, r.lookup.statusPath);
427
+ const mapped = typeof status === "string" ? r.lookup.confirmed.includes(status) ? "confirmed" : r.lookup.failed.includes(status) ? "failed" : null : null;
428
+ const identity = providerValue(ex.result, r.lookup.identityPath);
429
+ add("reconciliation provider status", terminal && mapped === op?.status && identity === op?.idempotencyKey && !(isObject(ex.result) && ex.result.isError === true), "provider read observed by the gateway and bound to its idempotency key; no independent provider signature is implied");
430
+ }
71
431
  }
72
432
  const logKeys = opts.logKeys ?? [];
73
433
  if (p.authorization) {
@@ -80,8 +440,32 @@ export function verifyBundle(bundle, opts) {
80
440
  add("authorization signature (issuer key)", asig.ok && typed && asig.keyid === sig.keyid, asig.ok ? (typed ? `keyid ${short(asig.keyid)}` : "not an authorization statement") : asig.error);
81
441
  if (ast && typed) {
82
442
  const ap = ast.predicate;
83
- const same = ap.receiptId === p.receiptId && ap.tool.name === p.tool.name && ap.request.argsDigest === p.request.argsDigest && ap.agent.id === p.agent.id && ap.principal.id === p.principal.id && ap.policy?.decision === "allow";
443
+ const same = ap.receiptId === p.receiptId && ap.tool.name === p.tool.name && ap.request.argsDigest === p.request.argsDigest && ap.agent.id === p.agent.id && ap.principal.id === p.principal.id && (ap.policy?.decision === "allow" || ap.policy?.decision === "deny" && ap.policy.enforced === false);
84
444
  add("authorization names this call", same, same ? `${ap.tool.name} for receipt ${short(ap.receiptId)}` : "committed for a different receipt, tool, arguments, agent, or decision");
445
+ if (ap.approval || p.approval) {
446
+ const stable = (approval) => approval ? { envelope: approval.envelope, requiredApprovers: approval.requiredApprovers, fields: approval.fields } : null;
447
+ const carries = canonicalize(stable(ap.approval)) === canonicalize(stable(p.approval));
448
+ add("authorization carries this approval", carries, "approval envelope, signer requirement, and argument mapping must match the precommit");
449
+ // A refusal needs no human keys, so the precommit's approval is checked for a forwarded call only.
450
+ if (forwarded) {
451
+ const ac = ap.approval;
452
+ // Under a private rule the precommit carries the receipt's commitment to the envelope: it is checked once restored.
453
+ const envelope = ac && isCommitment(ac.envelope) && carries ? full.approval?.envelope : ac?.envelope;
454
+ // an envelope withheld beside arguments in clear is not a private receipt: see "approval signatures (human keys)"
455
+ const sealed = isCommitment(envelope) && args.paths.length > 0;
456
+ const signed = ac && !sealed ? verifyApprovalStatement(envelope, opts.approvalKeys ?? [], ac.requiredApprovers) : null;
457
+ const valid = !!ac && ac.status === "approved" && ac.provenance === "observed" && isApprovalTime(ac.checkedAt) && (sealed || !!signed?.ok) &&
458
+ (!signed?.ok || (Date.parse(ac.checkedAt) >= Date.parse(signed.approval.issuedAt) && Date.parse(ac.checkedAt) < Date.parse(signed.approval.expiresAt))) &&
459
+ Date.parse(ac.checkedAt) >= Date.parse(p.timestamp) && Date.parse(ac.checkedAt) <= Date.parse(p.approval?.checkedAt ?? "") &&
460
+ Array.isArray(ac.approverKeyids) && new Set(ac.approverKeyids).size >= ac.requiredApprovers && (!signed?.ok || ac.approverKeyids.every((id) => signed.approverKeyids.includes(id)));
461
+ add("authorization approval was valid", valid, sealed ? "the envelope is withheld, so only the recorded status, times, and signer count are checked; disclose it or give the capture key to check the signatures" : "the precommit must record an approved statement with trusted signer observations and a check inside its validity window");
462
+ }
463
+ }
464
+ if (p.operation || ap.operation) {
465
+ const o = p.operation;
466
+ const aop = ap.operation;
467
+ add("authorization names this operation", !!o && !!aop && !operationProblem(aop) && aop.status === "submitted" && (aop.id === undefined || o.id === undefined || aop.id === o.id) && aop.idempotencyKey === o.idempotencyKey && aop.lookupDigest === o.lookupDigest && aop.originalReceiptId === o.originalReceiptId && canonicalize(aop.budget) === canonicalize(o.budget));
468
+ }
85
469
  const ath = dsseVerify(a.treeHead, [...logKeys, ...opts.issuerKeys]);
86
470
  add("authorization tree head signature", ath.ok && a.treeHead.payloadType === TREEHEAD_TYPE, ath.ok ? `keyid ${short(ath.keyid)}` : ath.error);
87
471
  if (ath.ok) {
@@ -167,9 +551,10 @@ export function formatReport(r) {
167
551
  const row = (f, prov, v) => lines.push(`${f.padEnd(15)} ${prov.padEnd(11)} ${typeof v === "string" ? v : JSON.stringify(v)}`);
168
552
  row("principal", p.principal.provenance, p.principal.id ?? "(none)");
169
553
  row("agent", p.agent.provenance, p.agent.id);
554
+ const idText = (v) => (typeof v === "string" ? v : v === null || v === undefined ? "-" : "(withheld under the capture rule)");
170
555
  if (p.session.id || p.session.toolUseId)
171
- row("session", p.session.provenance, `${p.session.id ?? "-"} / ${p.session.toolUseId ?? "-"}`);
172
- row("model", p.model.provenance, p.model.id ?? "(none supplied)");
556
+ row("session", p.session.provenance, `${idText(p.session.id)} / ${idText(p.session.toolUseId)}`);
557
+ row("model", p.model.provenance, p.model.id === null ? "(none supplied)" : idText(p.model.id));
173
558
  row("tool", p.tool.provenance, p.tool.name);
174
559
  row("args", p.request.provenance, p.request.args);
175
560
  for (const [k, f] of Object.entries(p.facts))
@@ -179,18 +564,23 @@ export function formatReport(r) {
179
564
  else
180
565
  row("policy", "-", "(none evaluated)");
181
566
  if (p.consumed)
182
- row("consumed", p.consumed.provenance, p.consumed.factIds.length === 0 ? "(no facts shown before this call)" : p.consumed.factIds);
567
+ row("consumed", p.consumed.provenance, !Array.isArray(p.consumed.factIds) ? "(withheld under the capture rule)" : p.consumed.factIds.length === 0 ? "(no facts shown before this call)" : p.consumed.factIds);
183
568
  if (p.authorization) {
184
569
  const committed = r.checks.filter((c) => c.name.startsWith("authorization ")).every((c) => c.ok);
185
570
  row("authorization", "observed", committed ? `committed to the log as leaf ${p.authorization.inclusion.leafIndex}, before the call was forwarded` : "carried, but its checks FAILED");
186
571
  }
187
572
  else if (p.execution.status === "withheld")
188
573
  row("authorization", "observed", "the log would not commit it; the call was not forwarded");
574
+ if (p.approval)
575
+ row("approval", p.approval.provenance, `${p.approval.status}; ${p.approval.requiredApprovers} approver(s) required${p.approval.consumedAt ? `; consumed ${p.approval.consumedAt}` : ""}${typeof p.approval.reason === "string" ? `; ${p.approval.reason}` : ""}`);
189
576
  const upstreamCheck = r.checks.find((c) => c.name === "upstream signature (upstream key)" || c.name === "upstream signature (provider secret)");
190
577
  const hasUpstream = (p.execution.status === "executed" || p.execution.status === "failed") && !!p.execution.upstream;
191
578
  const byProvider = hasUpstream && isProviderAttestation(p.execution.upstream);
192
579
  const attestedAs = upstreamCheck?.ok ? (byProvider ? "attested (shared secret)" : "attested") : p.execution.provenance;
193
580
  const note = !hasUpstream ? "" : upstreamCheck ? (upstreamCheck.ok ? ` (${byProvider ? upstreamCheck.detail : `signed by upstream ${upstreamCheck.detail}`})` : " (upstream signature FAILED)") : byProvider ? " (carries a provider delivery; pass the provider secret to check it)" : " (carries an upstream signature; pass --upstream-key to check it)";
194
- row("execution", attestedAs, `${p.execution.status}${note}`);
581
+ // a refusal says why, as the receipt records it; under a capture rule the reason is a commitment, and the report says so rather than printing it
582
+ const reason = "reason" in p.execution ? p.execution.reason : undefined;
583
+ const why = reason === undefined ? "" : typeof reason === "string" ? `: ${reason}` : ": (reason withheld under the capture rule)";
584
+ row("execution", attestedAs, `${p.execution.status}${why}${note}`);
195
585
  return lines.join("\n");
196
586
  }
@@ -0,0 +1,107 @@
1
+ # Payload-bound human approvals
2
+
3
+ A delegation lets an agent use a tool. A human approval authorizes one exact call: this principal, this agent, this tool, and every argument, until a short expiry. The gateway requires the signed approval before forwarding a protected call. A flag such as `approved: true` in the arguments has no authority.
4
+
5
+ The approval is a DSSE envelope signed with an approver's Ed25519 key. Its payload carries `approvalId`, `principal`, `agent`, `tool`, a SHA-256 digest of the complete arguments, `issuedAt`, `expiresAt`, and the action's `amount`, `currency`, and `beneficiary` when those fields exist. Money is an integer in minor units: `2500` means £25.00 for `GBP`, never `25.00`. Extra arguments are covered by the digest too; changing a note or adding a field invalidates the approval.
6
+
7
+ ## Configure the gateway
8
+
9
+ Generate approver keys with `agent-custody keygen --dir keys --name approver`, keep their private halves with the people approving actions, and add their public halves to the gateway:
10
+
11
+ ```json
12
+ {
13
+ "approvals": {
14
+ "trustedKeys": ["keys/approver.pub", "keys/second-approver.pub"],
15
+ "usedDir": "approvals-used",
16
+ "maxLifetimeSeconds": 900,
17
+ "tools": [
18
+ { "tool": "stripe.refund", "minApprovers": 2 }
19
+ ]
20
+ }
21
+ }
22
+ ```
23
+
24
+ This is an addition to the [gateway config](usage.md#setup-step-by-step), with paths relative to that file. `maxLifetimeSeconds` caps the approval lifetime, `expiresAt` minus `issuedAt`. The default is `3600`. The signer chooses the expiry, so the gateway refuses an approval with a longer lifetime, in every mode. This keeps an unused approval, which the agent holds, from staying usable for years. `minApprovers` is `1` by default, or `2` for two distinct trusted signing keys. A repeated signature or the same key listed twice counts once. The operator must assign those keys to distinct people; signatures establish possession of keys, not independent human identities.
25
+
26
+ `tool: "*"` protects every agent call, with an exact tool rule taking precedence. Wildcard rules do not require approvals for the gateway's internal fact lookups. A named fact-lookup tool cannot also have an exact approval rule: startup rejects that configuration. The gateway does not start with an empty trust list, an empty tools list, or duplicate tool rules.
27
+
28
+ The default action argument names are `amount`, `currency`, and `beneficiary`. For a refund whose recipient is `customer_id`, map it explicitly:
29
+
30
+ ```json
31
+ { "tool": "stripe.refund", "minApprovers": 1, "fields": { "beneficiary": "customer_id" } }
32
+ ```
33
+
34
+ Pass the same `fields` when creating the approval. These are top-level argument names, not dot paths. Each present amount must be a safe integer; a present currency or beneficiary must be a nonempty string. An omitted action field is still covered by the complete argument digest, but the approval cannot establish a business meaning for a differently named field unless it is mapped.
35
+
36
+ ## Sign the exact action and send it
37
+
38
+ Use the TypeScript API from the process where the human reviews the action. Show the complete arguments before signing, including any fields beyond the displayed amount and recipient.
39
+
40
+ ```ts
41
+ import {
42
+ APPROVAL_META_KEY, createApproval, dsseCountersign, loadPrivateKey,
43
+ } from "@agent-custody/receipts";
44
+
45
+ const args = { customer_id: "cust_123", amount: 2500, currency: "GBP" };
46
+ const fields = { beneficiary: "customer_id" };
47
+ const first = createApproval(loadPrivateKey("keys/approver.key"), {
48
+ principal: "user_456",
49
+ agent: "support-agent",
50
+ tool: "stripe.refund",
51
+ args,
52
+ fields,
53
+ expiresAt: new Date(Date.now() + 5 * 60_000).toISOString(),
54
+ });
55
+ // For a two-person rule, the second person reviews and signs the same payload.
56
+ const approved = dsseCountersign(first, loadPrivateKey("keys/second-approver.key"));
57
+ const result = await agent.callTool({
58
+ name: "stripe.refund",
59
+ arguments: args,
60
+ _meta: { [APPROVAL_META_KEY]: approved },
61
+ });
62
+ ```
63
+
64
+ `createApproval` supplies a UUID `approvalId` and the current `issuedAt` unless given explicitly. `expiresAt` is required and must follow `issuedAt`. The window is half open: the approval is valid at issuance and invalid at expiry. `dsseCountersign` preserves the payload and adds a signature; it does not issue a different approval.
65
+
66
+ The gateway reads `agent-custody/approval` from the call's `_meta` and removes that key before forwarding. It checks the trusted signatures, threshold, lifetime cap, validity window, principal, agent, tool, complete argument digest, and action fields before fact lookups and Cedar evaluation. Missing, malformed, expired, or mismatched approval denies the call even in observe mode. A valid approval still needs a valid grant and an allowing policy.
67
+
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
+
70
+ ## Consumption and failure recovery
71
+
72
+ `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.
73
+
74
+ Consumption is conservative: the id is burned before forwarding. A crash, a log error, or an unknown upstream outcome after consumption does not release it. Obtain a fresh approval after checking the upstream's actual state; retry and exactly-once outcome handling are separate work. Do not delete consumption records while their approvals can still be valid. There is no automatic pruning.
75
+
76
+ An offline receipt verifier checks the signed action and the gateway's recorded consumption time. It cannot prove that another gateway never used that approval: single use depends on this shared persistent store and the gateway enforcing it.
77
+
78
+ ## Verify the evidence
79
+
80
+ The receipt's optional `approval` record embeds the envelope, the required threshold, checked time, status, observed signer keyids, configured field mapping when any, and consumption time when consumed. A missing, malformed, or untrusted approval envelope on a refused call is omitted. Only signature entries that verify against trusted approval keys are retained in an embedded envelope. Under a private capture rule the envelope and the reason are withheld as commitments; see [Privacy](#privacy-limits). Its provenance is `observed`: the gateway records what it checked; the embedded envelope supplies the independent approver signatures.
81
+
82
+ ```bash
83
+ agent-custody verify receipts/<id>.json \
84
+ --issuer-key keys/gateway.pub --principal-key keys/principal.pub \
85
+ --approval-key keys/approver.pub --approval-key keys/second-approver.pub
86
+ ```
87
+
88
+ In code, give `verifyBundle` an `approvalKeys` array of `PublicKeyRef`s, separate from `issuerKeys` and `principalKeys`. Those other keys never implicitly authorize an approval. For a forwarded call carrying an approval record, verification requires trusted approval signatures, the exact action binding, validity at the recorded check and consumption times, and an approved, consumed record. A call that the gateway did not forward needs none of these, and so needs no approval key. This covers a call that Cedar denied, a call outside the grant, and a call withheld after consumption, even when the approval was valid. The record of such a call is an authentic refusal. Verification does not turn its approval into an authorization.
89
+
90
+ `verifyApproval(envelope, trustedKeys, binding, { at?, minApprovers?, maxLifetimeSeconds? })` checks an envelope directly and returns either `{ ok: true, approval, approverKeyids }` or `{ ok: false, error }`. It does not consume it. `consumeApproval(usedDir, approvalId, receiptId, at)` creates the exclusive consumption marker and throws if the id has already been used. The gateway combines these steps; callers building another enforcement boundary must preserve their order.
91
+
92
+ ## Privacy limits
93
+
94
+ The approval envelope arrives in the agent's `_meta`. It carries the amount, currency, beneficiary, and an **unsalted digest of the full arguments**. Under a private capture rule the receipt withholds the whole envelope as one commitment at `approval.envelope`. It is salted, and encrypted in mode `encrypted`. The precommit authorization carries the same commitment. A refusal `reason` can quote the statement, so it is withheld too. Without this, the receipt would publish the action fields, and the digest would confirm a guess of the arguments (issue #126).
95
+
96
+ The record keeps the gateway's own observations in clear: the status, the required threshold, the check and consumption times, the signer key ids, and the configured field mapping. A reviewer sees that an approval was checked and when. To check the signatures and the binding, the reviewer restores the envelope and the arguments with the capture key or a disclosure (`approval.envelope` and `request.args.$rest` in the disclosure file). Without them, the verifier passes the approval checks as committed, as it does for `request args digest`, and says so. A tool with a private rule and an approval therefore proves the approval only to a reviewer who holds the key or a disclosure. The browser verifier cannot restore them.
97
+
98
+ When the issuer withholds nothing under `request.args`, an approved envelope stays in clear. This happens when `args` is in mode `clear` with a private `result`. It also happens when a private `args` rule lists every argument of the call in `clear`, or the call has no arguments. The envelope payload then equals the public call, and the gateway checked that. A denied envelope is still withheld, because it can carry another call's fields. So is the envelope of a call whose tool name is masked. The verifiers use the same test: a forwarded, approved call whose note withholds the envelope, but withholds nothing under `request.args`, fails `approval signatures (human keys)`. Otherwise an issuer could skip the binding check whenever the arguments are public.
99
+
100
+ ### What the receipt can prove about the approval
101
+
102
+ - The receipt proves the signatures, the binding, and the window only to a reviewer who has the envelope. Under a private rule that is the capture key (mode `encrypted`) or a disclosure of `approval.envelope`.
103
+ - In mode `digest` the gateway keeps no copy of the envelope. The salts file holds only salts. A disclosure can then come only from whoever kept the approval: the agent or the approver. If nobody kept it, the human approval cannot be proven afterwards. Use mode `encrypted` when you must prove it later.
104
+ - The receipt does not record `maxLifetimeSeconds`. The offline verifier cannot check the lifetime cap. Only the gateway enforces it, when it admits the approval.
105
+ - Single use is also not provable offline. See above.
106
+
107
+ [Tutorial 30](../examples/30-payload-bound-approvals.ts) runs a real gateway with two approvers, refuses changed arguments, an expired approval and an insufficient threshold, forwards the exact approved call, refuses its replay, and verifies every receipt.