@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
@@ -0,0 +1,607 @@
1
+ // Private evidence: what a receipt records of a call, decided in one place. The signature and the digests are over
2
+ // the whole call as it happened; what the receipt file carries in clear is a choice, made per tool in the config, and
3
+ // applied by the issuer to the whole statement just before it is signed (`privateView`). A fixed list of structural
4
+ // paths stays in clear: ids, key ids, timestamps, the tool name, the grant, the digests, the decision
5
+ // and the ids of the policies behind it, the status, the provenance fields, and the note itself. Every other value
6
+ // under a private rule leaves a commitment in its place, sha256 over a random salt and the canonical value, so a
7
+ // reviewer who is later shown the value and the salt can check it belongs; an encrypted commitment carries both as
8
+ // well, under a key the customer holds (AES-256-GCM). The salt never appears in the receipt: without it a reviewer
9
+ // cannot confirm a guess of a withheld value against the commitment (issue #126), and the digests over withheld
10
+ // values are salted with material derived from the field salts, so nothing public confirms a guess against them
11
+ // either. A field or path added to the receipt later starts withheld, never in clear. The signed note lists the
12
+ // withheld paths; a verifier trusts the note, not the shape of the data.
13
+ import { createCipheriv, createDecipheriv, randomBytes } from "node:crypto";
14
+ import { canonicalize, digestOf, sha256Hex } from "./crypto.js";
15
+ // used only inside functions, so the cycle with upstream.ts (which takes isCommitment from here) is resolved before either runs
16
+ import { contentDigest, UPSTREAM_TYPE } from "./upstream.js";
17
+ /** A 32-byte key from hex (64 chars) or base64 (44 chars), as an environment variable holds it. */
18
+ export function captureKeyFrom(text) {
19
+ const t = text.trim();
20
+ // strict forms only: a base64 string with stray characters would decode silently to a different key
21
+ if (!/^[0-9a-fA-F]{64}$/.test(t) && !/^[A-Za-z0-9+/]{43}=$/.test(t))
22
+ throw new Error("capture key: expected 32 bytes as 64 hex characters or 44 characters of base64");
23
+ const key = t.length === 64 ? Buffer.from(t, "hex") : Buffer.from(t, "base64");
24
+ if (key.length !== 32)
25
+ throw new Error("capture key: expected 32 bytes as 64 hex characters or base64");
26
+ return key;
27
+ }
28
+ export function captureKeyId(key) {
29
+ return sha256Hex(key);
30
+ }
31
+ const HEX64 = /^[0-9a-f]{64}$/;
32
+ const HEX32 = /^[0-9a-f]{32}$/;
33
+ const B64 = /^[A-Za-z0-9+/]+=*$/;
34
+ /** A well-formed commitment: the sha256 a verifier checks, and for an encrypted one the fields the key needs. A `$custody` tag alone is not one. */
35
+ export function isCommitment(v) {
36
+ if (!v || typeof v !== "object" || Array.isArray(v))
37
+ return false;
38
+ const c = v;
39
+ if (typeof c.sha256 !== "string" || !HEX64.test(c.sha256))
40
+ return false;
41
+ if (c.$custody === "withheld")
42
+ return true;
43
+ if (c.$custody !== "encrypted")
44
+ return false;
45
+ // a 12-byte iv and a 16-byte tag, as AES-256-GCM is used here; a shorter tag would be accepted by the cipher and must not be
46
+ return c.alg === "A256GCM" && typeof c.keyid === "string" && HEX64.test(c.keyid) && [c.iv, c.ciphertext, c.tag].every((f) => typeof f === "string" && f.length > 0 && B64.test(f)) && c.iv.length === 16 && c.tag.length === 24;
47
+ }
48
+ /** What an encrypted commitment is bound to: the receipt and the path, so a ciphertext moved to another receipt or path does not decrypt. */
49
+ export function aadFor(receiptId, path) {
50
+ return canonicalize({ receiptId: typeof receiptId === "string" ? receiptId : null, path });
51
+ }
52
+ /** A disclosed value as a disclosure carries it: the salt, and the value when the holder has filled it in. */
53
+ export function isDisclosed(v) {
54
+ if (!v || typeof v !== "object" || Array.isArray(v))
55
+ return false;
56
+ const d = v;
57
+ return d.$custody === "disclosed" && typeof d.salt === "string" && HEX32.test(d.salt);
58
+ }
59
+ function commit(value, salt) {
60
+ return sha256Hex(Buffer.concat([Buffer.from(salt, "hex"), Buffer.from(canonicalize(value), "utf8")]));
61
+ }
62
+ /** Replaces a value with its commitment, carrying the value and the salt encrypted when a key is given (bound to `aad`, see `aadFor`); the salt is returned to the caller, never written into the receipt. */
63
+ export function withhold(value, key, aad) {
64
+ const salt = randomBytes(16).toString("hex");
65
+ const sha256 = commit(value, salt);
66
+ if (!key)
67
+ return { commitment: { $custody: "withheld", sha256 }, salt };
68
+ const iv = randomBytes(12);
69
+ const cipher = createCipheriv("aes-256-gcm", key, iv);
70
+ if (aad)
71
+ cipher.setAAD(Buffer.from(aad, "utf8"));
72
+ const ciphertext = Buffer.concat([cipher.update(canonicalize({ salt, value }), "utf8"), cipher.final()]);
73
+ return { commitment: { $custody: "encrypted", alg: "A256GCM", keyid: captureKeyId(key), iv: iv.toString("base64"), ciphertext: ciphertext.toString("base64"), tag: cipher.getAuthTag().toString("base64"), sha256 }, salt };
74
+ }
75
+ /** True when `value` under `salt` is what the commitment was made over. */
76
+ export function checkCommitment(c, value, salt) {
77
+ return HEX32.test(salt) && commit(value, salt) === c.sha256;
78
+ }
79
+ /** The value and the salt behind an encrypted commitment, under the key that made it; checked against the commitment too. */
80
+ export function reveal(c, key, aad) {
81
+ if (c.$custody !== "encrypted")
82
+ throw new Error("this value was withheld without its value; only the party that holds it can supply it, with its salt");
83
+ if (c.keyid !== captureKeyId(key))
84
+ throw new Error(`this value was encrypted under key ${c.keyid.slice(0, 12)}…, not the one given`);
85
+ const decipher = createDecipheriv("aes-256-gcm", key, Buffer.from(c.iv, "base64"));
86
+ if (aad)
87
+ decipher.setAAD(Buffer.from(aad, "utf8"));
88
+ decipher.setAuthTag(Buffer.from(c.tag, "base64"));
89
+ const text = Buffer.concat([decipher.update(Buffer.from(c.ciphertext, "base64")), decipher.final()]).toString("utf8");
90
+ const inner = JSON.parse(text);
91
+ if (!inner || typeof inner !== "object" || typeof inner.salt !== "string" || !("value" in inner))
92
+ throw new Error("the decrypted content is not a salt and a value");
93
+ if (!checkCommitment(c, inner.value, inner.salt))
94
+ throw new Error("the decrypted value does not match its commitment");
95
+ return { value: inner.value, salt: inner.salt };
96
+ }
97
+ /**
98
+ * The salt of a digest over a part that holds withheld values: derived from the salts of those values, in note order,
99
+ * so whoever can restore the values can recompute the digest and nobody else can confirm a guess against it. No salt
100
+ * when nothing under the part is withheld: the values are public, and so may the digest be.
101
+ */
102
+ export function digestSalt(salts) {
103
+ return salts.length ? sha256Hex(Buffer.from(salts.join(""), "hex")) : undefined;
104
+ }
105
+ /** The tool's rule, else the "*" rule: by own property, so a tool named `constructor` or `toString` does not find an inherited member and fall through to clear. */
106
+ export function ruleFor(capture, tool) {
107
+ if (!capture)
108
+ return undefined;
109
+ if (Object.hasOwn(capture, tool))
110
+ return capture[tool];
111
+ return Object.hasOwn(capture, "*") ? capture["*"] : undefined;
112
+ }
113
+ const ownOf = (o, k) => (o && Object.hasOwn(o, k) ? o[k] : undefined);
114
+ const PRIVACY = { clear: 0, digest: 1, encrypted: 2 };
115
+ /** A side as the rule captures it: its mode, and the fields it keeps in clear (null for all of them, a side in clear whole). */
116
+ function sideRule(rule, side) {
117
+ const mode = ruleMode(rule);
118
+ const s = rule[side];
119
+ if (mode === "clear" || s?.mode === "clear")
120
+ return { mode: "clear", clear: null };
121
+ return { mode: s?.mode ?? mode, clear: s?.clear ?? [] };
122
+ }
123
+ /**
124
+ * The rule for a call: the tool's own, else the wildcard. For a name no upstream offers, which is text the agent
125
+ * chose, both together, side by side: the more private mode, and only the fields both keep in clear, so that a rule
126
+ * left for a retired name can never be selected by an agent to widen what is in clear. A mode does not order which
127
+ * fields are public, so the clear lists are intersected, not taken from the more private rule. The gateway and the
128
+ * issuer both call this, so the fact arguments kept in clear and the view agree.
129
+ */
130
+ export function effectiveRule(capture, tool, unknownTool = false) {
131
+ const named = ruleFor(capture, tool);
132
+ if (!unknownTool)
133
+ return named;
134
+ const star = ownOf(capture, "*");
135
+ const own_ = ownOf(capture, tool);
136
+ if (!star || !own_)
137
+ return named ?? star;
138
+ const both = {};
139
+ for (const side of ["args", "result", "facts"]) {
140
+ const a = sideRule(own_, side);
141
+ const b = sideRule(star, side);
142
+ const mode = PRIVACY[a.mode] >= PRIVACY[b.mode] ? a.mode : b.mode;
143
+ if (mode === "clear")
144
+ both[side] = { mode };
145
+ else
146
+ both[side] = { mode, clear: a.clear === null ? (b.clear ?? []) : b.clear === null ? a.clear : a.clear.filter((f) => b.clear.includes(f)) };
147
+ }
148
+ return both;
149
+ }
150
+ /**
151
+ * An upstream's attestation envelope exactly as `signResult` writes it for this call: the three envelope fields, the
152
+ * upstream payload type, one signature entry of a key id and a signature, and a payload that is the canonical bytes of
153
+ * this receipt's id, this tool, and the digest of this result, nothing else. Any other field, claim, or encoding is
154
+ * upstream-authored data that may repeat the withheld arguments. The key id and the signature are bytes the upstream
155
+ * chose and the gateway, holding no upstream key, checks for shape only; they carry no more than the clear result the
156
+ * rule publishes from the same upstream.
157
+ */
158
+ function isPlainAttestation(envelope, receiptId, tool, result) {
159
+ if (!isObject(envelope) || !exactKeys(envelope, ["payload", "payloadType", "signatures"]))
160
+ return false;
161
+ if (envelope.payloadType !== UPSTREAM_TYPE || typeof envelope.payload !== "string" || !isObject(result))
162
+ return false;
163
+ const sigs = envelope.signatures;
164
+ if (!Array.isArray(sigs) || sigs.length !== 1)
165
+ return false;
166
+ const sig = sigs[0];
167
+ if (!isObject(sig) || !exactKeys(sig, ["keyid", "sig"]) || typeof sig.keyid !== "string" || !/^[0-9a-f]{64}$/.test(sig.keyid))
168
+ return false;
169
+ if (typeof sig.sig !== "string" || !canonicalBase64(sig.sig, 64))
170
+ return false;
171
+ if (!canonicalBase64(envelope.payload))
172
+ return false;
173
+ try {
174
+ const bytes = Buffer.from(envelope.payload, "base64");
175
+ const p = JSON.parse(bytes.toString("utf8"));
176
+ // compared as bytes: decoding to text would turn an invalid byte into U+FFFD and let it through
177
+ if (!isObject(p) || !exactKeys(p, ["contentDigest", "receiptId", "tool"]) || !bytes.equals(Buffer.from(canonicalize(p), "utf8")))
178
+ return false;
179
+ return p.receiptId === receiptId && p.tool === tool && p.contentDigest === contentDigest(result);
180
+ }
181
+ catch {
182
+ return false;
183
+ }
184
+ }
185
+ /** exactly these own keys: a joined list would let one key named "a,b" stand for two, and an inherited one would not count */
186
+ const exactKeys = (o, keys) => Object.keys(o).length === keys.length && keys.every((k) => Object.hasOwn(o, k));
187
+ /** base64 that decodes and encodes back to itself, so no character rides along unread; of `length` bytes when given */
188
+ function canonicalBase64(s, length) {
189
+ const b = Buffer.from(s, "base64");
190
+ return b.toString("base64") === s && (length === undefined || b.length === length);
191
+ }
192
+ /** The one mode a rule withholds in: encrypted when any side is, else digest; clear when no side is private. */
193
+ export function ruleMode(rule) {
194
+ const modes = [rule?.args, rule?.result, rule?.facts].map((s) => s?.mode ?? "clear");
195
+ if (modes.includes("encrypted"))
196
+ return "encrypted";
197
+ if (modes.includes("digest"))
198
+ return "digest";
199
+ return "clear";
200
+ }
201
+ /**
202
+ * How a side is captured: null when it is in clear whole (set to clear, or every side clear); else the fields kept in
203
+ * clear and whether its commitments carry the value encrypted. A side the rule does not set is withheld whole, field
204
+ * by field, in the rule's mode.
205
+ */
206
+ function sideOf(rule, side, key) {
207
+ const mode = ruleMode(rule);
208
+ if (mode === "clear")
209
+ return null;
210
+ const s = rule?.[side];
211
+ if (s?.mode === "clear")
212
+ return null;
213
+ return { clear: new Set(s?.clear ?? []), key: (s?.mode ?? mode) === "encrypted" ? key : undefined };
214
+ }
215
+ // ---- paths ----
216
+ export const pathKey = (p) => JSON.stringify(p);
217
+ export const pathText = (p) => p.map((s) => (/^[A-Za-z0-9_$-]+$/.test(s) ? s : JSON.stringify(s))).join(".");
218
+ export const under = (p, prefix) => prefix.length <= p.length && prefix.every((s, i) => p[i] === s);
219
+ const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
220
+ const own = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
221
+ /** The value at a path, by own properties only; undefined when the path leaves the data. */
222
+ export function getAt(root, path) {
223
+ let v = root;
224
+ for (const s of path) {
225
+ if (!isObject(v) || !own(v, s))
226
+ return undefined;
227
+ v = v[s];
228
+ }
229
+ return v;
230
+ }
231
+ /** A copy with a null prototype, so a field named __proto__ stays a field. */
232
+ const plain = (o) => {
233
+ const out = Object.create(null);
234
+ for (const [k, v] of Object.entries(o))
235
+ out[k] = v;
236
+ return out;
237
+ };
238
+ /** A copy of `root` with `value` at `path`, every object on the way copied (null-prototype), the rest shared. Creates objects for missing segments. */
239
+ export function setAt(root, path, value) {
240
+ if (path.length === 0)
241
+ return value;
242
+ const [head, ...rest] = path;
243
+ const o = isObject(root) ? plain(root) : Object.create(null);
244
+ o[head] = setAt(own(o, head) ? o[head] : undefined, rest, value);
245
+ return o;
246
+ }
247
+ // ---- the choke point ----
248
+ /** The structural top-level parts of a statement: ids, keys, times, the grant, the names. Never withheld. */
249
+ const CLEAR_TOP = new Set(["receiptId", "timestamp", "issuer", "principal", "agent", "delegation", "tool", "authorization", "capture"]);
250
+ /** Inside the parts that carry values: what stays in clear beside them. */
251
+ const CLEAR_IN = {
252
+ request: new Set(["argsDigest", "provenance"]),
253
+ fact: new Set(["tool", "resultDigest", "provenance"]),
254
+ policy: new Set(["decision", "reasons", "policyDigest", "enforced", "provenance"]),
255
+ execution: new Set(["status", "resultDigest", "provenance"]),
256
+ upstream: new Set(["provider"]),
257
+ consumed: new Set(["provenance"]),
258
+ /**
259
+ * The gateway's own observations of its approval check: the status, the times, the signers' key ids, and the config's
260
+ * argument mapping. The envelope is not here: the agent supplied it, and it carries the action fields and an unsalted
261
+ * digest of the arguments. The reason is not here either: it can quote the statement.
262
+ */
263
+ approval: new Set(["status", "requiredApprovers", "checkedAt", "consumedAt", "approverKeyids", "fields", "provenance"]),
264
+ /** the host's correlation ids are supplied by the agent's process or its call: values, withheld; the provenance stays */
265
+ session: new Set(["provenance"]),
266
+ model: new Set(["provenance"]),
267
+ };
268
+ /** The result's error flag is its status, so it stays in clear when it is the boolean flag and nothing else; its metadata carries whatever an upstream put there, so it never does. */
269
+ const RESULT_ALWAYS_CLEAR = new Set(["isError"]);
270
+ const RESULT_NEVER_CLEAR = new Set(["_meta"]);
271
+ /** the slot in a captured side's view that holds the commitment over every field not kept in clear */
272
+ export const REST = "$rest";
273
+ /** The parts an authorization and its receipt share; the receipt's view takes them from the authorization's, commitments and salts alike. */
274
+ const SHARED_WITH_AUTHORIZATION = ["request", "facts", "policy", "consumed"];
275
+ const APPROVAL_ENVELOPE = ["approval", "envelope"];
276
+ /**
277
+ * The statement a receipt carries under a tool's rule: the predicate with every non-structural value withheld as the
278
+ * rule says, the three digests salted from the field salts, and the note of what is withheld at `capture`. Under a
279
+ * clear rule, the predicate itself and no salts. Applied by the issuer to every statement it signs, the authorization
280
+ * included; given the authorization's view as `prior`, the receipt's view carries the same request, facts, and policy,
281
+ * so that the receipt still names the authorization and nothing is withheld twice.
282
+ */
283
+ export function privateView(predicate, rule, key, ctx = {}, prior) {
284
+ const mode = ruleMode(rule);
285
+ if (mode === "clear")
286
+ return { predicate, salts: {} };
287
+ if (mode === "encrypted" && !key)
288
+ throw new Error("capture mode encrypted needs captureKeyEnv");
289
+ /** every value outside the three sides is withheld in the rule's mode: encrypted when any side is */
290
+ const k = mode === "encrypted" ? key : undefined;
291
+ const withheld = [];
292
+ const salts = {};
293
+ let out = plain(predicate);
294
+ // the note is this view's to write: one that came in with the predicate names nothing here
295
+ delete out.capture;
296
+ if (ctx.unknownTool && isObject(out.tool))
297
+ out.tool = { ...out.tool, name: "(unknown tool)" };
298
+ if (prior) {
299
+ for (const part of SHARED_WITH_AUTHORIZATION)
300
+ if (own(prior.predicate, part))
301
+ out[part] = prior.predicate[part];
302
+ for (const w of prior.predicate.capture?.withheld ?? []) {
303
+ // a part the receipt does not share (the operation, whose status changes) is withheld again below, once; the
304
+ // approval envelope is shared, though the rest of the approval record changes
305
+ if (!SHARED_WITH_AUTHORIZATION.includes(w[0]) && pathKey(w) !== pathKey(APPROVAL_ENVELOPE))
306
+ continue;
307
+ withheld.push(w);
308
+ const s = ownOf(prior.salts, pathKey(w));
309
+ if (s)
310
+ salts[pathKey(w)] = s;
311
+ }
312
+ }
313
+ const receiptId = predicate.receiptId;
314
+ const hide = (path, value, withKey) => {
315
+ // nothing carries nothing; a null does (that a value was null), and is withheld like any other
316
+ if (value === undefined)
317
+ return;
318
+ const w = withhold(value, withKey, aadFor(receiptId, path));
319
+ out = setAt(out, path, w.commitment);
320
+ salts[pathKey(path)] = w.salt;
321
+ withheld.push(path);
322
+ };
323
+ /** the digest of a part, salted from the salts of the withheld values under it */
324
+ const digest = (value, prefix) => digestOf(value, digestSalt(withheld.filter((w) => under(w, prefix)).map((w) => salts[pathKey(w)])));
325
+ /**
326
+ * A side captured under its rule: the listed fields are kept beside one commitment, at `$rest`, over an object of
327
+ * every other field. Field by field would leave the field names in clear, in the view and in the signed note, and
328
+ * names are chosen by the agent or the upstream like the values are. A value that is not a plain object is withheld
329
+ * whole. `always` names a boolean status flag that stays in clear only when it is one; `never` names fields that are
330
+ * withheld even when listed. A field literally named `$rest` is never clear: it is withheld with the rest and comes
331
+ * back with it.
332
+ */
333
+ const object = (path, value, side, always = new Set(), never = new Set()) => {
334
+ if (!isObject(value))
335
+ return hide(path, value, side.key);
336
+ const view = Object.create(null);
337
+ const rest = Object.create(null);
338
+ let any = false;
339
+ for (const [f, v] of Object.entries(value)) {
340
+ if (f !== REST && !never.has(f) && (side.clear.has(f) || (always.has(f) && typeof v === "boolean")))
341
+ view[f] = v;
342
+ else {
343
+ rest[f] = v;
344
+ any = true;
345
+ }
346
+ }
347
+ if (!any)
348
+ return;
349
+ out = setAt(out, path, view);
350
+ hide([...path, REST], rest, side.key);
351
+ };
352
+ /** the lookup arguments of a fact, field by field: the names are the fact config's, not the call's */
353
+ const fields = (path, value, side) => {
354
+ if (!isObject(value))
355
+ return hide(path, value, side.key);
356
+ for (const [f, v] of Object.entries(value))
357
+ if (!side.clear.has(f))
358
+ hide([...path, f], v, side.key);
359
+ };
360
+ const argsSide = sideOf(rule, "args", key);
361
+ const resultSide = sideOf(rule, "result", key);
362
+ const factsSide = sideOf(rule, "facts", key);
363
+ for (const [key_, value] of Object.entries(predicate)) {
364
+ // the approval record is handled after the loop: whether its envelope may stay depends on what the arguments withheld
365
+ if (CLEAR_TOP.has(key_) || key_ === "approval")
366
+ continue;
367
+ if (prior && SHARED_WITH_AUTHORIZATION.includes(key_))
368
+ continue;
369
+ // no policy was evaluated: structural, not a value
370
+ if (key_ === "policy" && value === null)
371
+ continue;
372
+ if (key_ === "request" && isObject(value)) {
373
+ for (const [f, v] of Object.entries(value)) {
374
+ if (f === "args") {
375
+ if (argsSide)
376
+ object(["request", "args"], v, argsSide);
377
+ }
378
+ else if (!CLEAR_IN.request.has(f))
379
+ hide(["request", f], v, k);
380
+ }
381
+ if (own(value, "args"))
382
+ out = setAt(out, ["request", "argsDigest"], digest(value.args, ["request", "args"]));
383
+ }
384
+ else if (key_ === "facts" && isObject(value)) {
385
+ for (const [name, fact] of Object.entries(value)) {
386
+ if (!isObject(fact)) {
387
+ hide(["facts", name], fact, k);
388
+ continue;
389
+ }
390
+ for (const [f, v] of Object.entries(fact)) {
391
+ if (f === "value") {
392
+ if (factsSide)
393
+ object(["facts", name, "value"], v, factsSide);
394
+ }
395
+ else if (f === "args") {
396
+ if (argsSide)
397
+ fields(["facts", name, "args"], v, { clear: new Set(ownOf(ctx.clearFactArgs, name) ?? []), key: argsSide.key });
398
+ }
399
+ else if (!CLEAR_IN.fact.has(f))
400
+ hide(["facts", name, f], v, k);
401
+ }
402
+ // The fact's digest is over the lookup's full result, of which the receipt shows only the selected value: the
403
+ // rest (metadata, other content) is never public under a private rule, whatever the selected fields are. So
404
+ // the digest becomes a commitment to the full result (disclosed or decrypted like any value, and checked at
405
+ // `withheld facts.<name>.resultDigest`), or, when the producer did not give the full result, the digest
406
+ // string itself is withheld: an unsalted digest over private data would confirm a guess.
407
+ const full = ownOf(ctx.factResults, name);
408
+ const digestPath = ["facts", name, "resultDigest"];
409
+ if (full !== undefined) {
410
+ const w = withhold(full, factsSide ? factsSide.key : k, aadFor(receiptId, digestPath));
411
+ out = setAt(out, digestPath, w.commitment);
412
+ salts[pathKey(digestPath)] = w.salt;
413
+ withheld.push(digestPath);
414
+ }
415
+ else
416
+ hide(digestPath, fact.resultDigest, k);
417
+ }
418
+ }
419
+ else if (key_ === "policy" && isObject(value)) {
420
+ for (const [f, v] of Object.entries(value)) {
421
+ // an empty error list is structural (there were none); a non-empty one carries the evaluator's messages
422
+ if (f === "errors" && Array.isArray(v) && v.length === 0)
423
+ continue;
424
+ if (!CLEAR_IN.policy.has(f))
425
+ hide(["policy", f], v, k);
426
+ }
427
+ }
428
+ else if (key_ === "execution" && isObject(value)) {
429
+ for (const [f, v] of Object.entries(value)) {
430
+ if (f === "result") {
431
+ if (resultSide)
432
+ object(["execution", "result"], v, resultSide, RESULT_ALWAYS_CLEAR, RESULT_NEVER_CLEAR);
433
+ // a result left in clear by the rule still carries its metadata, which an upstream wrote and which may repeat the arguments: withheld under any private rule
434
+ else if (isObject(v) && own(v, "_meta"))
435
+ hide(["execution", "result", "_meta"], v._meta, k);
436
+ }
437
+ else if (f === "upstream" && isObject(v)) {
438
+ // Everything an upstream or a provider wrote in the evidence is withheld under any private rule: the delivery
439
+ // body and the signed envelope (a signed payload may carry any claim), and the provider's signature and bind
440
+ // too, since the signature is a MAC over the withheld body (whoever holds the secret would confirm a guess of
441
+ // the body against it) and the bind is a string the upstream chose. Only the provider's name stays. The
442
+ // verifier checks the delivery once the body, the signature, and the bind are back.
443
+ for (const [uf, uv] of Object.entries(v)) {
444
+ // beside a result the rule leaves in clear, an envelope that is exactly the plain attestation for this call
445
+ // (isPlainAttestation: every field, the signature entry, and the payload's bytes) stays, so the signature over
446
+ // that public result can be checked; any other field or claim is upstream-authored data and withholds it, and
447
+ // the verifier then says so rather than skipping the check. A masked tool name is never kept beside its envelope.
448
+ if (uf === "envelope" && !resultSide && !ctx.unknownTool && isPlainAttestation(uv, predicate.receiptId, predicate.tool.name, value.result))
449
+ continue;
450
+ if (uf === "rawBody" || uf === "envelope" || uf === "signature" || uf === "bind")
451
+ hide(["execution", "upstream", uf], uv, resultSide ? resultSide.key : k);
452
+ else if (!CLEAR_IN.upstream.has(uf))
453
+ hide(["execution", "upstream", uf], uv, k);
454
+ }
455
+ }
456
+ else if (!CLEAR_IN.execution.has(f))
457
+ hide(["execution", f], v, k);
458
+ }
459
+ if (own(value, "result"))
460
+ out = setAt(out, ["execution", "resultDigest"], digest(value.result, ["execution", "result"]));
461
+ }
462
+ else if ((key_ === "session" || key_ === "model") && isObject(value)) {
463
+ // correlation ids the host or the agent supplied: a value when there is one; none is structural
464
+ for (const [f, v] of Object.entries(value)) {
465
+ if (v === null)
466
+ continue;
467
+ if (!CLEAR_IN[key_].has(f))
468
+ hide([key_, f], v, k);
469
+ }
470
+ }
471
+ else if (key_ === "consumed" && isObject(value)) {
472
+ // the fact ids an upstream declared it served are upstream-chosen strings: withheld under a private rule, an empty list being structural
473
+ for (const [f, v] of Object.entries(value)) {
474
+ if (f === "factIds" && Array.isArray(v) && v.length === 0)
475
+ continue;
476
+ if (!CLEAR_IN.consumed.has(f))
477
+ hide(["consumed", f], v, k);
478
+ }
479
+ }
480
+ else if (key_ === "operation" && isObject(value)) {
481
+ // Only gateway-derived identities and operator configuration are public. The id is not: the agent chose it
482
+ // (a caller may use an order or customer UUID), so it is withheld. The idempotencyKey links the receipts. The
483
+ // amount is never duplicated here: it belongs to the captured request. New fields start private, together at $rest.
484
+ object(["operation"], value, { clear: new Set(["idempotencyKey", "lookupDigest", "status", "budget", "originalReceiptId", "provenance"]), key: k });
485
+ if (isObject(value.budget))
486
+ object(["operation", "budget"], value.budget, { clear: new Set(["id", "currency", "period"]), key: k });
487
+ }
488
+ else if (key_ === "reconciliation" && isObject(value)) {
489
+ // original is the immutable, already captured bundle written by this issuer. The lookup consists solely of
490
+ // operator configuration and the gateway-derived idempotency key; the provider response lives in execution.result.
491
+ object(["reconciliation"], value, { clear: new Set(["original", "lookup"]), key: k });
492
+ if (isObject(value.lookup))
493
+ object(["reconciliation", "lookup"], value.lookup, { clear: new Set(["tool", "args", "statusPath", "identityPath", "confirmed", "failed"]), key: k });
494
+ }
495
+ else
496
+ hide([key_], value, k);
497
+ }
498
+ const approval = predicate.approval;
499
+ if (isObject(approval)) {
500
+ // Beside arguments of which nothing is withheld, an approved envelope adds nothing: its payload equals the public
501
+ // call, and the gateway checked that. It stays, so a verifier can run the binding check on it (the analogue of
502
+ // isPlainAttestation). A denied envelope may carry another call's fields, so it is withheld, unless the
503
+ // authorization already showed it. A masked tool name is never kept beside its envelope.
504
+ const argsPublic = !withheld.some((w) => under(w, ["request", "args"])) && !ctx.unknownTool;
505
+ for (const [f, v] of Object.entries(approval)) {
506
+ if (CLEAR_IN.approval.has(f))
507
+ continue;
508
+ const path = ["approval", f];
509
+ // the authorization and the receipt carry the same envelope, so they carry the same commitment to it
510
+ const earlier = f === "envelope" && prior ? getAt(prior.predicate, path) : undefined;
511
+ if (f === "envelope" && argsPublic && (approval.status === "approved" || (earlier !== undefined && !isCommitment(earlier))))
512
+ continue;
513
+ if (isCommitment(earlier))
514
+ out = setAt(out, path, earlier);
515
+ else
516
+ hide(path, v, f === "envelope" && argsSide ? argsSide.key : k);
517
+ }
518
+ }
519
+ if (withheld.length)
520
+ out.capture = { mode, withheld };
521
+ return { predicate: out, salts };
522
+ }
523
+ /**
524
+ * The full statement behind a view, under its note: a path the note names must hold a commitment; the disclosure, when
525
+ * it carries that path as `{ $custody: "disclosed", salt, value }`, must match the commitment; else the key reveals
526
+ * what was encrypted under it; else the path stays withheld. A disclosure is a partial predicate with those at the
527
+ * withheld paths, as `agent-custody reveal` writes it. Nothing here throws: the problems are reported, so a verifier
528
+ * fails the right check.
529
+ */
530
+ export function restorePaths(predicate, note, disclosed, key) {
531
+ const r = { predicate, restored: new Map(), salts: new Map(), values: new Map(), missing: [], problems: [] };
532
+ if (!note)
533
+ return r;
534
+ const keyid = key ? captureKeyId(key) : null;
535
+ for (const path of note.withheld) {
536
+ const c = getAt(predicate, path);
537
+ if (!isCommitment(c)) {
538
+ r.problems.push({ path, error: `the capture note says ${pathText(path)} is withheld, but the receipt carries no commitment for it` });
539
+ continue;
540
+ }
541
+ const d = disclosed === undefined ? undefined : getAt(disclosed, path);
542
+ if (d !== undefined) {
543
+ if (!isDisclosed(d)) {
544
+ r.problems.push({ path, error: `the disclosed ${pathText(path)} must be { "$custody": "disclosed", "salt", "value" }, as agent-custody reveal writes it; a value alone cannot be checked` });
545
+ continue;
546
+ }
547
+ // a salt without its value is what reveal --include-salts writes for the holder to complete: handed over as it
548
+ // is, it would let a reviewer confirm guesses, so an unfinished disclosure fails rather than passes as committed
549
+ if (!("value" in d)) {
550
+ r.problems.push({ path, error: `the disclosed ${pathText(path)} carries a salt but no value; fill in the value or remove the entry, since a salt alone lets a reviewer confirm guesses` });
551
+ continue;
552
+ }
553
+ if (!checkCommitment(c, d.value, d.salt)) {
554
+ r.problems.push({ path, error: `the disclosed ${pathText(path)} does not match the receipt's commitment` });
555
+ continue;
556
+ }
557
+ r.predicate = setAt(r.predicate, path, d.value);
558
+ r.restored.set(pathKey(path), "disclosed");
559
+ r.salts.set(pathKey(path), d.salt);
560
+ r.values.set(pathKey(path), d.value);
561
+ }
562
+ else if (key && c.$custody === "encrypted" && c.keyid !== keyid) {
563
+ // a key was given and it is not this value's: said so, rather than passing as committed with a hint to give the key
564
+ r.problems.push({ path, error: `${pathText(path)} is encrypted under key ${c.keyid.slice(0, 12)}…, not the one given` });
565
+ }
566
+ else if (key && c.$custody === "encrypted") {
567
+ try {
568
+ const back = reveal(c, key, aadFor(getAt(predicate, ["receiptId"]), path));
569
+ r.predicate = setAt(r.predicate, path, back.value);
570
+ r.restored.set(pathKey(path), "decrypted");
571
+ r.salts.set(pathKey(path), back.salt);
572
+ r.values.set(pathKey(path), back.value);
573
+ }
574
+ catch (e) {
575
+ r.problems.push({ path, error: `${pathText(path)}: ${e instanceof Error ? e.message : String(e)}` });
576
+ }
577
+ }
578
+ else
579
+ r.missing.push(path);
580
+ }
581
+ // a restored `$rest` is the rest of its parent: folded back in, so the parent is the object the digest was made over.
582
+ // Only where a side is captured as one (the arguments, the result, a fact's value): a fact's lookup arguments are
583
+ // captured field by field, and one of them may be named $rest.
584
+ const aggregate = (parent) => pathKey(parent) === pathKey(["request", "args"]) || pathKey(parent) === pathKey(["execution", "result"]) || (parent.length === 3 && parent[0] === "facts" && parent[2] === "value");
585
+ for (const path of note.withheld) {
586
+ if (path[path.length - 1] !== REST || !r.restored.has(pathKey(path)) || !aggregate(path.slice(0, -1)))
587
+ continue;
588
+ const parentPath = path.slice(0, -1);
589
+ const parent = getAt(r.predicate, parentPath);
590
+ if (!isObject(parent))
591
+ continue;
592
+ const merged = Object.create(null);
593
+ for (const [k, v] of Object.entries(parent))
594
+ if (k !== REST)
595
+ merged[k] = v;
596
+ const rest = parent[REST];
597
+ if (isObject(rest))
598
+ for (const [k, v] of Object.entries(rest))
599
+ merged[k] = v;
600
+ r.predicate = setAt(r.predicate, parentPath, merged);
601
+ }
602
+ return r;
603
+ }
604
+ /** The salt a digest over `prefix` was made with, once every withheld path under it is restored: see `digestSalt`. */
605
+ export function digestSaltFor(r, note, prefix) {
606
+ return digestSalt((note?.withheld ?? []).filter((w) => under(w, prefix)).map((w) => r.salts.get(pathKey(w)) ?? ""));
607
+ }