@agent-custody/state 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,856 @@
1
+ const RECEIPT_TYPE = "application/vnd.in-toto+json";
2
+ const PREDICATE_TYPE = "https://agent-custody.dev/receipt/v0.2";
3
+ const TREEHEAD_TYPE = "application/vnd.agent-custody.treehead+json";
4
+ const DELEGATION_TYPE = "application/vnd.agent-custody.delegation+json";
5
+ const UPSTREAM_TYPE = "application/vnd.agent-custody.upstream+json";
6
+ const AUTHORIZATION_TYPE = "https://agent-custody.dev/authorization/v0.1";
7
+ const APPROVAL_TYPE = "application/vnd.agent-custody.approval+json";
8
+ const subtle = () => globalThis.crypto.subtle;
9
+ const enc = new TextEncoder();
10
+ const b64 = { decode: (s) => Uint8Array.from(atob(s), (c) => c.charCodeAt(0)) };
11
+ const hex = (buf) => [...new Uint8Array(buf)].map((b) => b.toString(16).padStart(2, "0")).join("");
12
+ const unhex = (h) => Uint8Array.from(h.match(/.{2}/g) ?? [], (x) => parseInt(x, 16));
13
+ const concat = (...parts) => { const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); let o = 0; for (const p of parts) {
14
+ out.set(p, o);
15
+ o += p.length;
16
+ } return out; };
17
+ const sha256 = async (data) => new Uint8Array(await subtle().digest("SHA-256", data));
18
+ export function canonicalize(value) {
19
+ const sort = (v) => {
20
+ if (Array.isArray(v))
21
+ return v.map(sort);
22
+ // null-prototype, so an own property named __proto__ survives (mirrors src/crypto.ts)
23
+ if (v && typeof v === "object") {
24
+ const o = Object.create(null);
25
+ for (const k of Object.keys(v).sort()) {
26
+ const x = v[k];
27
+ if (x !== undefined)
28
+ o[k] = sort(x);
29
+ }
30
+ return o;
31
+ }
32
+ return v;
33
+ };
34
+ return JSON.stringify(sort(value));
35
+ }
36
+ /** sha256 over the canonical JSON. A digest over withheld values is salted from their salts, which the browser never has, so it recomputes only digests over values in clear. */
37
+ export const digestOf = async (v) => hex(await sha256(enc.encode(canonicalize(v))));
38
+ /** Loads an Ed25519 public key from SPKI PEM. keyid is the sha256 of the DER. */
39
+ export async function publicKeyFromPem(pem) {
40
+ const der = b64.decode(pem.replace(/-----[^-]+-----/g, "").replace(/\s+/g, ""));
41
+ const key = await subtle().importKey("spki", der, { name: "Ed25519" }, true, ["verify"]);
42
+ return { key, keyid: hex(await sha256(der)), pem };
43
+ }
44
+ function pae(payloadType, payload) {
45
+ return concat(enc.encode(`DSSEv1 ${enc.encode(payloadType).length} ${payloadType} ${payload.length} `), payload);
46
+ }
47
+ export async function dsseVerify(env, trusted) {
48
+ if (!env || typeof env.payload !== "string" || !Array.isArray(env.signatures) || env.signatures.length === 0)
49
+ return { ok: false, error: "malformed envelope" };
50
+ const payload = b64.decode(env.payload);
51
+ const data = pae(env.payloadType, payload);
52
+ for (const s of env.signatures) {
53
+ const key = trusted.find((t) => t.keyid === s.keyid);
54
+ if (!key)
55
+ continue;
56
+ const good = await subtle().verify({ name: "Ed25519" }, key.key, b64.decode(s.sig), data);
57
+ if (good) {
58
+ try {
59
+ return { ok: true, payload: JSON.parse(new TextDecoder().decode(payload)), keyid: s.keyid };
60
+ }
61
+ catch {
62
+ return { ok: false, error: "payload is not JSON" };
63
+ }
64
+ }
65
+ return { ok: false, error: `signature by ${s.keyid.slice(0, 12)} did not verify` };
66
+ }
67
+ return { ok: false, error: `no trusted key matches keyids [${env.signatures.map((s) => s.keyid.slice(0, 12)).join(", ")}]` };
68
+ }
69
+ // ---- delegation chains ----
70
+ const delegationShape = (d) => !!d && d.version === "0.1" && typeof d.principal === "string" && typeof d.agent === "string" && Array.isArray(d.scopes) && typeof d.issuedAt === "string" && typeof d.expiresAt === "string";
71
+ function decodeDelegationPayload(env) {
72
+ try {
73
+ const d = JSON.parse(new TextDecoder().decode(b64.decode(env.payload)));
74
+ return delegationShape(d) ? d : null;
75
+ }
76
+ catch {
77
+ return null;
78
+ }
79
+ }
80
+ export function delegationHasParent(env) {
81
+ return decodeDelegationPayload(env)?.parent !== undefined;
82
+ }
83
+ /** Mirrors verifyDelegation in the package: walks a chain to a grant signed by a trusted principal key. */
84
+ export async function verifyDelegationChain(env, trusted, depth = 1) {
85
+ if (env.payloadType !== DELEGATION_TYPE)
86
+ return { ok: false, error: `unexpected payloadType ${env.payloadType}` };
87
+ if (depth > 4)
88
+ return { ok: false, error: "delegation chain deeper than 4" };
89
+ const unverified = decodeDelegationPayload(env);
90
+ if (!unverified)
91
+ return { ok: false, error: "malformed delegation" };
92
+ if (unverified.parent === undefined) {
93
+ const r = await dsseVerify(env, trusted);
94
+ if (!r.ok)
95
+ return r;
96
+ if (!delegationShape(r.payload))
97
+ return { ok: false, error: "malformed delegation" };
98
+ return { ok: true, delegation: r.payload, keyid: r.keyid, chain: [r.payload] };
99
+ }
100
+ const up = await verifyDelegationChain(unverified.parent, trusted, depth + 1);
101
+ if (!up.ok)
102
+ return { ok: false, error: `link ${depth}: ${up.error}` };
103
+ const parent = up.delegation;
104
+ if (typeof parent.agentKey !== "string")
105
+ return { ok: false, error: `link ${depth}: ${parent.agent} holds no agent key and cannot delegate` };
106
+ let parentKey;
107
+ try {
108
+ parentKey = await publicKeyFromPem(parent.agentKey);
109
+ }
110
+ catch {
111
+ return { ok: false, error: `link ${depth}: the agent key named for ${parent.agent} is not a public key` };
112
+ }
113
+ const r = await dsseVerify(env, [parentKey]);
114
+ if (!r.ok)
115
+ return { ok: false, error: `link ${depth}: not signed by ${parent.agent}'s key: ${r.error}` };
116
+ const d = r.payload;
117
+ if (!delegationShape(d))
118
+ return { ok: false, error: "malformed delegation" };
119
+ if (d.principal !== parent.principal)
120
+ return { ok: false, error: `link ${depth}: principal changed from ${parent.principal} to ${d.principal}` };
121
+ const extra = d.scopes.filter((s) => !parent.scopes.includes(s));
122
+ if (extra.length)
123
+ return { ok: false, error: `link ${depth}: ${d.agent} was given scopes ${parent.agent} does not hold: ${extra.join(", ")}` };
124
+ const [ci, ce, pi, pe] = [d.issuedAt, d.expiresAt, parent.issuedAt, parent.expiresAt].map((x) => Date.parse(x));
125
+ if ([ci, ce, pi, pe].some(Number.isNaN))
126
+ return { ok: false, error: `link ${depth}: a window timestamp is not a date` };
127
+ if (ci < pi || ce > pe)
128
+ return { ok: false, error: `link ${depth}: ${d.agent}'s window is not inside ${parent.agent}'s` };
129
+ return { ok: true, delegation: d, keyid: up.keyid, chain: [...up.chain, d] };
130
+ }
131
+ // ---- RFC 6962 / 9162 ----
132
+ const leafHash = (data) => sha256(concat(new Uint8Array([0]), enc.encode(data)));
133
+ const nodeHash = (l, r) => sha256(concat(new Uint8Array([1]), l, r));
134
+ export async function verifyInclusion(leaf, proof, rootHex) {
135
+ let fn = proof.leafIndex, sn = proof.treeSize - 1;
136
+ if (fn < 0 || sn < 0 || fn > sn)
137
+ return false;
138
+ let r = leaf;
139
+ for (const h of proof.hashes) {
140
+ if (sn === 0)
141
+ return false;
142
+ const p = unhex(h);
143
+ if (fn % 2 === 1 || fn === sn) {
144
+ r = await nodeHash(p, r);
145
+ if (fn % 2 === 0) {
146
+ while (fn % 2 === 0 && fn !== 0) {
147
+ fn = Math.floor(fn / 2);
148
+ sn = Math.floor(sn / 2);
149
+ }
150
+ }
151
+ }
152
+ else
153
+ r = await nodeHash(r, p);
154
+ fn = Math.floor(fn / 2);
155
+ sn = Math.floor(sn / 2);
156
+ }
157
+ return sn === 0 && hex(r) === rootHex;
158
+ }
159
+ export async function verifyConsistency(oldSize, oldRoot, newSize, newRoot, proofHex) {
160
+ if (oldSize < 0 || oldSize > newSize)
161
+ return false;
162
+ if (oldSize === newSize)
163
+ return proofHex.length === 0 && oldRoot === newRoot;
164
+ if (oldSize === 0)
165
+ return proofHex.length === 0;
166
+ if (proofHex.length === 0)
167
+ return false;
168
+ const proof = proofHex.map(unhex);
169
+ if ((oldSize & (oldSize - 1)) === 0)
170
+ proof.unshift(unhex(oldRoot));
171
+ let fn = oldSize - 1, sn = newSize - 1;
172
+ while (fn % 2 === 1) {
173
+ fn = Math.floor(fn / 2);
174
+ sn = Math.floor(sn / 2);
175
+ }
176
+ let fr = proof[0], sr = proof[0];
177
+ for (const c of proof.slice(1)) {
178
+ if (sn === 0)
179
+ return false;
180
+ if (fn % 2 === 1 || fn === sn) {
181
+ fr = await nodeHash(c, fr);
182
+ sr = await nodeHash(c, sr);
183
+ while (fn % 2 === 0 && fn !== 0) {
184
+ fn = Math.floor(fn / 2);
185
+ sn = Math.floor(sn / 2);
186
+ }
187
+ }
188
+ else
189
+ sr = await nodeHash(sr, c);
190
+ fn = Math.floor(fn / 2);
191
+ sn = Math.floor(sn / 2);
192
+ }
193
+ return sn === 0 && hex(fr) === oldRoot && hex(sr) === newRoot;
194
+ }
195
+ const ISSUER_NOTE = {
196
+ gateway: "enforced outside the agent's process; the agent could neither skip nor forge this receipt",
197
+ sdk: "self-reported by the agent's own process; tamper-evident after issue, but nothing here was enforced outside the agent",
198
+ };
199
+ const short = (s) => s.slice(0, 12);
200
+ async function hmacHex(secret, data) {
201
+ const key = await subtle().importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
202
+ return hex(await subtle().sign("HMAC", key, enc.encode(data)));
203
+ }
204
+ async function checkProvider(att, secrets, timestamp, result) {
205
+ const secret = att.provider === "stripe-webhook" ? secrets.stripe : secrets.github;
206
+ if (!secret)
207
+ return { ok: false, detail: `no ${att.provider === "stripe-webhook" ? "Stripe" : "GitHub"} secret given` };
208
+ if (att.provider === "stripe-webhook") {
209
+ const parts = Object.fromEntries(String(att.signature).split(",").map((kv) => kv.split("=")));
210
+ if (!parts.t || !parts.v1)
211
+ return { ok: false, detail: "Stripe-Signature header lacks t or v1" };
212
+ if ((await hmacHex(secret, `${parts.t}.${att.rawBody}`)) !== parts.v1)
213
+ return { ok: false, detail: "Stripe signature does not verify with this secret" };
214
+ const skew = Math.abs(Number(parts.t) * 1000 - Date.parse(timestamp)) / 1000;
215
+ if (!(skew <= 300))
216
+ return { ok: false, detail: `Stripe timestamp is ${Math.round(skew)}s from the receipt, beyond tolerance` };
217
+ }
218
+ else {
219
+ const hexSig = String(att.signature).startsWith("sha256=") ? String(att.signature).slice(7) : "";
220
+ if (!hexSig || (await hmacHex(secret, att.rawBody)) !== hexSig)
221
+ return { ok: false, detail: "GitHub signature does not verify with this secret" };
222
+ }
223
+ let body;
224
+ try {
225
+ body = JSON.parse(att.rawBody);
226
+ }
227
+ catch {
228
+ return { ok: false, detail: "delivery body is not JSON" };
229
+ }
230
+ const bound = String(att.bind).split(".").reduce((v, k) => (v && typeof v === "object" ? v[k] : undefined), body);
231
+ if (bound === undefined || bound === null || bound === "")
232
+ return { ok: false, detail: `delivery has no value at ${att.bind}` };
233
+ // what the agent received, never _meta: the delivery copy there always contains the bound value
234
+ const received = result;
235
+ if (!JSON.stringify({ content: received.content, isError: received.isError, structuredContent: received.structuredContent }).includes(JSON.stringify(bound).replace(/^"|"$/g, "")))
236
+ return { ok: false, detail: `delivery's ${att.bind} (${String(bound)}) does not appear in the receipt's result` };
237
+ return { ok: true, detail: `shared secret (${att.provider}, bound on ${att.bind})` };
238
+ }
239
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
240
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
241
+ const hex64 = (v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v);
242
+ function operationProblem(o) {
243
+ if (!isObj(o) || (o.id !== undefined && (typeof o.id !== "string" || !UUID.test(o.id))) || typeof o.originalReceiptId !== "string" || !UUID.test(o.originalReceiptId))
244
+ return "operation ids are not UUIDs";
245
+ if (!hex64(o.idempotencyKey) || !hex64(o.lookupDigest))
246
+ return "operation idempotencyKey or lookupDigest is not a sha256";
247
+ if (!["submitted", "pending", "confirmed", "failed", "unknown"].includes(String(o.status)) || o.provenance !== "observed")
248
+ return "operation status or provenance is invalid";
249
+ if (!isObj(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))
250
+ return "operation budget is invalid";
251
+ return null;
252
+ }
253
+ /** Provider records are JSON in the first text result, just as the gateway's ordinary fact extraction reads them. */
254
+ function providerValue(result, path) {
255
+ let record;
256
+ if (isObj(result) && Array.isArray(result.content)) {
257
+ const text = result.content.find((c) => isObj(c) && c.type === "text");
258
+ if (isObj(text) && typeof text.text === "string") {
259
+ try {
260
+ record = JSON.parse(text.text);
261
+ }
262
+ catch {
263
+ return undefined;
264
+ }
265
+ }
266
+ }
267
+ return path.split(".").reduce((v, k) => isObj(v) && Object.hasOwn(v, k) ? v[k] : undefined, record);
268
+ }
269
+ /** A committed authorization is sufficient original evidence after a process crash before the outcome receipt. */
270
+ async function verifyOriginalAuthorization(bundle, opts) {
271
+ const checks = [];
272
+ const add = (name, ok, detail) => checks.push({ name, ok, ...(detail === undefined ? {} : { detail }) });
273
+ const sig = await dsseVerify(bundle.envelope, opts.issuerKeys);
274
+ const st = sig.ok ? sig.payload : null;
275
+ const typed = !!st && bundle.envelope.payloadType === RECEIPT_TYPE && st.predicateType === AUTHORIZATION_TYPE;
276
+ add("authorization signature (issuer key)", sig.ok && typed);
277
+ if (!sig.ok || !st || !typed)
278
+ return { ok: false, checks };
279
+ const p = st.predicate;
280
+ const problem = structuralProblem({ ...p, session: { id: null, toolUseId: null, provenance: "claimed" }, model: { id: null, provenance: "claimed" }, execution: { status: "withheld", provenance: "observed" } });
281
+ add("structural parts in clear", !problem, problem ?? undefined);
282
+ if (problem)
283
+ return { ok: false, checks };
284
+ add("authorization issued by the gateway", p.issuer.kind === "gateway" && p.issuer.keyid === sig.keyid);
285
+ add("authorization operation is submitted", p.operation?.status === "submitted");
286
+ 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);
287
+ const del = p.delegation && await verifyDelegationChain(p.delegation.envelope, opts.principalKeys);
288
+ add("delegation signature (principal key)", !!del?.ok);
289
+ if (del?.ok) {
290
+ const d = del.delegation;
291
+ 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);
292
+ const at = Date.parse(p.timestamp);
293
+ add("delegation valid at receipt time", !Number.isNaN(at) && Date.parse(d.issuedAt) <= at && at <= Date.parse(d.expiresAt));
294
+ add("executed tool within delegated scope", d.scopes.includes(p.tool.name));
295
+ }
296
+ const getAt = (root, path) => path.reduce((v, k) => isObj(v) && Object.hasOwn(v, k) ? v[k] : undefined, root);
297
+ const isCommitment = (v) => isObj(v) && hex64(v.sha256) && (v.$custody === "withheld" || (v.$custody === "encrypted" && v.alg === "A256GCM" && hex64(v.keyid) && [v.iv, v.ciphertext, v.tag].every((f) => typeof f === "string" && f.length > 0 && /^[A-Za-z0-9+/]+=*$/.test(f)) && v.iv.length === 16 && v.tag.length === 24));
298
+ const paths = p.capture?.withheld ?? [];
299
+ add("captured commitments are well formed", paths.every((w) => isCommitment(getAt(p, w))));
300
+ const missingArgs = paths.some((w) => w[0] === "request" && w[1] === "args");
301
+ add("request args digest", st.subject[0]?.digest.sha256 === p.request.argsDigest && (missingArgs || (await digestOf(p.request.args)) === p.request.argsDigest));
302
+ const th = await dsseVerify(bundle.treeHead, [...(opts.logKeys ?? []), ...opts.issuerKeys]);
303
+ add("tree head signature", th.ok && bundle.treeHead.payloadType === TREEHEAD_TYPE);
304
+ if (th.ok) {
305
+ const head = th.payload;
306
+ if (opts.logId !== undefined)
307
+ add("tree head names the expected log", head.log === opts.logId);
308
+ add("log inclusion proof", head.treeSize === bundle.inclusion.treeSize && await verifyInclusion(await leafHash(canonicalize(bundle.envelope)), bundle.inclusion, head.rootHash));
309
+ if (opts.logLeaves) {
310
+ const hashes = [];
311
+ for (const l of opts.logLeaves)
312
+ hashes.push(typeof l === "string" ? await leafHash(l) : unhex((l.pruned ?? l.hash)));
313
+ add("log file root matches tree head", head.treeSize <= hashes.length && await rootOf(hashes, head.treeSize) === head.rootHash);
314
+ }
315
+ }
316
+ return { ok: checks.every((c) => c.ok), checks };
317
+ }
318
+ /** mirrors isApprovalTime in src/approval.ts: an ISO time with an offset, as the approval and the receipt's approval record write it */
319
+ const iso = (v) => {
320
+ if (typeof v !== "string")
321
+ return false;
322
+ const m = /^(\d{4})-(\d{2})-(\d{2})T([01]\d|2[0-3]):([0-5]\d):([0-5]\d)(?:\.\d+)?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/.exec(v);
323
+ if (!m || !Number.isFinite(Date.parse(v)))
324
+ return false;
325
+ const y = Number(m[1]), month = Number(m[2]), day = Number(m[3]);
326
+ const days = [31, y % 4 === 0 && (y % 100 !== 0 || y % 400 === 0) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
327
+ return month >= 1 && month <= 12 && day >= 1 && day <= days[month - 1];
328
+ };
329
+ const STRUCTURAL_TOP = new Set(["receiptId", "timestamp", "issuer", "principal", "agent", "delegation", "tool", "authorization", "capture"]);
330
+ // The approval record's envelope and reason are withheld under a private rule; its status, times, and signer ids are not.
331
+ 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"]) };
332
+ const pathTextOf = (w) => w.map((s) => (/^[A-Za-z0-9_$-]+$/.test(s) ? s : JSON.stringify(s))).join(".");
333
+ /** mirrors src/verify.ts structuralProblem: a capture note may never name what a verifier reads to run its checks, and those parts must be what every check assumes */
334
+ export function structuralProblem(p) {
335
+ if (!isObj(p))
336
+ return "the predicate is not an object";
337
+ const note = p.capture;
338
+ if (note !== undefined) {
339
+ if (!isObj(note) || (note.mode !== "digest" && note.mode !== "encrypted") || !Array.isArray(note.withheld))
340
+ return "the capture note is malformed";
341
+ if (new Set(note.withheld.map((w) => JSON.stringify(w))).size !== note.withheld.length)
342
+ return "the capture note names a path twice";
343
+ for (const w of note.withheld) {
344
+ if (!Array.isArray(w) || w.length === 0 || !w.every((s) => typeof s === "string"))
345
+ return "the capture note names a malformed path";
346
+ const path = w;
347
+ const head = path[0];
348
+ 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");
349
+ if (named)
350
+ return `the capture note names a structural part: ${pathTextOf(path)}`;
351
+ }
352
+ }
353
+ if (typeof p.receiptId !== "string" || typeof p.timestamp !== "string")
354
+ return "receiptId or timestamp is not a string";
355
+ if (!isObj(p.issuer) || !isObj(p.principal) || !isObj(p.agent) || !isObj(p.session) || !isObj(p.model))
356
+ return "issuer, principal, agent, session, or model is not an object";
357
+ if (p.principal.provenance === "attested" && typeof p.principal.keyid !== "string")
358
+ return "an attested principal has no keyid";
359
+ if (!isObj(p.tool) || typeof p.tool.name !== "string")
360
+ return "tool.name is not a string";
361
+ if (!isObj(p.request) || typeof p.request.argsDigest !== "string" || !isObj(p.request.args))
362
+ return "request.args or request.argsDigest is not what it should be";
363
+ if (!isObj(p.execution) || typeof p.execution.status !== "string" || !["executed", "failed", "denied", "error", "withheld"].includes(p.execution.status))
364
+ return "execution.status is not a status";
365
+ if (p.policy !== null && (!isObj(p.policy) || (p.policy.decision !== "allow" && p.policy.decision !== "deny") || !Array.isArray(p.policy.reasons) || typeof p.policy.policyDigest !== "string"))
366
+ return "policy is neither null nor a decision";
367
+ if (!isObj(p.facts) || Object.values(p.facts).some((f) => !isObj(f) || typeof f.tool !== "string"))
368
+ return "facts is not a map of facts";
369
+ if (p.consumed !== undefined && !isObj(p.consumed))
370
+ return "consumed is not an object";
371
+ if (p.delegation !== undefined && (!isObj(p.delegation) || !isObj(p.delegation.envelope)))
372
+ return "delegation is not a signed envelope";
373
+ if (p.authorization !== undefined && (!isObj(p.authorization) || !isObj(p.authorization.envelope) || !isObj(p.authorization.treeHead) || !isObj(p.authorization.inclusion)))
374
+ return "authorization is not a bundle";
375
+ if (p.approval !== undefined) {
376
+ const a = p.approval;
377
+ if (!isObj(a) || typeof a.status !== "string" || !["approved", "denied"].includes(a.status) || (a.requiredApprovers !== 1 && a.requiredApprovers !== 2) || !iso(a.checkedAt) || !Array.isArray(a.approverKeyids) || !a.approverKeyids.every((k) => typeof k === "string") || a.provenance !== "observed")
378
+ return "approval is not an approval record";
379
+ if (a.consumedAt !== undefined && !iso(a.consumedAt))
380
+ return "approval consumption time is not a timestamp";
381
+ if (a.fields !== undefined && (!isObj(a.fields) || Object.entries(a.fields).some(([k, v]) => !["amount", "currency", "beneficiary"].includes(k) || typeof v !== "string" || !v.length)))
382
+ return "approval field mapping is malformed";
383
+ }
384
+ if (p.operation !== undefined) {
385
+ const problem = operationProblem(p.operation);
386
+ if (problem)
387
+ return problem;
388
+ }
389
+ if (p.reconciliation !== undefined) {
390
+ const r = p.reconciliation;
391
+ if (!isObj(r) || !isObj(r.original) || !isObj(r.original.envelope) || !isObj(r.original.treeHead) || !isObj(r.original.inclusion) || !isObj(r.lookup))
392
+ return "reconciliation is not a lookup and an original bundle";
393
+ const l = r.lookup;
394
+ const statuses = (v) => Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === "string" && s.length > 0 && s.length <= 128);
395
+ const path = (v) => typeof v === "string" && v.length > 0 && v.length <= 512 && v.split(".").every((s) => s.length > 0);
396
+ if (typeof l.tool !== "string" || !l.tool.length || !isObj(l.args) || !path(l.statusPath) || !path(l.identityPath) || !statuses(l.confirmed) || !statuses(l.failed) || l.confirmed.some((s) => l.failed.includes(s)))
397
+ return "reconciliation lookup is malformed or its terminal statuses overlap";
398
+ }
399
+ if (isObj(p.execution.upstream) && typeof p.execution.upstream.provider !== "undefined" && typeof p.execution.upstream.provider !== "string")
400
+ return "execution.upstream.provider is not a string";
401
+ return null;
402
+ }
403
+ /** Strict human-approval envelope and payload checks, mirroring src/approval.ts without a runtime dependency. */
404
+ async function verifyApprovalStatement(env, trusted, minimum) {
405
+ const exact = (v, required, optional = []) => isObj(v) && required.every((k) => Object.hasOwn(v, k)) && Object.keys(v).every((k) => required.includes(k) || optional.includes(k));
406
+ const base64 = (v) => { try {
407
+ return typeof v === "string" && v.length > 0 && v.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(v) && btoa(atob(v)) === v;
408
+ }
409
+ catch {
410
+ return false;
411
+ } };
412
+ const nonempty = (v) => typeof v === "string" && v.length > 0;
413
+ try {
414
+ if (!exact(env, ["payloadType", "payload", "signatures"]) || env.payloadType !== APPROVAL_TYPE || !base64(env.payload) || !Array.isArray(env.signatures) || !env.signatures.length || !env.signatures.every((s) => exact(s, ["keyid", "sig"]) && nonempty(s.keyid) && base64(s.sig) && b64.decode(s.sig).length === 64))
415
+ return { ok: false, error: "malformed approval envelope" };
416
+ const approvers = new Set();
417
+ const data = pae(env.payloadType, b64.decode(env.payload));
418
+ for (const s of env.signatures) {
419
+ const k = trusted.find((key) => key.keyid === s.keyid);
420
+ if (k && await subtle().verify({ name: "Ed25519" }, k.key, b64.decode(s.sig), data))
421
+ approvers.add(k.keyid);
422
+ }
423
+ if (approvers.size < minimum)
424
+ return { ok: false, error: `approval requires ${minimum} distinct trusted signature${minimum === 1 ? "" : "s"}` };
425
+ const a = JSON.parse(new TextDecoder().decode(b64.decode(env.payload)));
426
+ const uuid = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;
427
+ if (!exact(a, ["version", "approvalId", "principal", "agent", "tool", "argsDigest", "issuedAt", "expiresAt"], ["amount", "currency", "beneficiary"]) || a.version !== "0.1" || typeof a.approvalId !== "string" || !uuid.test(a.approvalId) || ![a.principal, a.agent, a.tool].every(nonempty) || typeof a.argsDigest !== "string" || !/^[0-9a-f]{64}$/.test(a.argsDigest) || (Object.hasOwn(a, "amount") && !Number.isSafeInteger(a.amount)) || ["currency", "beneficiary"].some((k) => Object.hasOwn(a, k) && !nonempty(a[k])) || !iso(a.issuedAt) || !iso(a.expiresAt) || Date.parse(a.expiresAt) <= Date.parse(a.issuedAt))
428
+ return { ok: false, error: "invalid approval payload" };
429
+ return { ok: true, approval: a, approverKeyids: [...approvers] };
430
+ }
431
+ catch {
432
+ return { ok: false, error: "invalid approval" };
433
+ }
434
+ }
435
+ /** The same checks, in the same order, with the same names, as the reference verifyBundle. */
436
+ export async function verifyBundle(bundle, opts) {
437
+ const checks = [];
438
+ const add = (name, ok, detail) => { checks.push(detail === undefined ? { name, ok } : { name, ok, detail }); return ok; };
439
+ let treeHeadSigner = null;
440
+ const done = (statement) => ({ ok: checks.every((c) => c.ok), checks, statement, issuerNote: statement ? (ISSUER_NOTE[statement.predicate.issuer.kind] ?? "unknown issuer kind") : null, treeHeadSigner });
441
+ const sig = await dsseVerify(bundle.envelope, opts.issuerKeys);
442
+ if (!sig.ok) {
443
+ add("receipt signature (issuer key)", false, sig.error);
444
+ return done(null);
445
+ }
446
+ add("receipt signature (issuer key)", true, `keyid ${short(sig.keyid)}`);
447
+ const st = sig.payload;
448
+ if (!add("receipt payload type", bundle.envelope.payloadType === RECEIPT_TYPE && st.predicateType === PREDICATE_TYPE))
449
+ return done(null);
450
+ const broken = structuralProblem(st.predicate);
451
+ if (!add("structural parts in clear", !broken, broken ?? undefined))
452
+ return done(null);
453
+ const p = st.predicate;
454
+ add("issuer kind is known", p.issuer.kind === "gateway" || p.issuer.kind === "sdk", `${p.issuer.kind}${p.issuer.framework ? ` / ${p.issuer.framework}` : ""}`);
455
+ add("issuer keyid matches signer", p.issuer.keyid === sig.keyid);
456
+ if (p.operation) {
457
+ add("operation observed by gateway", p.issuer.kind === "gateway" && p.operation.provenance === "observed");
458
+ if (!p.reconciliation) {
459
+ // A retry of an existing operation has a receipt of its own. It is withheld (never forwarded again) and names the original.
460
+ const retry = p.operation.originalReceiptId !== p.receiptId;
461
+ add("operation names this original receipt", !retry || p.execution.status === "withheld");
462
+ const refused = p.execution.status === "withheld" || p.execution.status === "denied";
463
+ add("operation awaits provider reconciliation", retry || ["submitted", "pending", "unknown"].includes(p.operation.status) || refused && p.operation.status === "failed");
464
+ add("operation carries committed authorization", refused || !!p.authorization);
465
+ }
466
+ }
467
+ if (p.issuer.kind === "gateway") {
468
+ add("gateway receipt carries a delegation", p.delegation !== undefined);
469
+ add("gateway receipt carries a policy decision", p.policy !== null);
470
+ }
471
+ if (p.delegation) {
472
+ const del = await verifyDelegationChain(p.delegation.envelope, opts.principalKeys);
473
+ const d = del.ok ? del.delegation : null;
474
+ const shape = !!d;
475
+ add("delegation signature (principal key)", del.ok, del.ok ? `signed by ${short(del.keyid)}` : del.error);
476
+ if (delegationHasParent(p.delegation.envelope))
477
+ add("delegation chain to the principal", del.ok, del.ok ? `${[del.chain[0].principal, ...del.chain.map((c) => c.agent)].join(" → ")} (${del.chain.length - 1} delegation(s))` : del.error);
478
+ if (del.ok && shape) {
479
+ const principalKeyid = p.principal.provenance === "attested" ? p.principal.keyid : null;
480
+ add("delegation binds principal and agent", d.principal === p.principal.id && d.agent === p.agent.id && del.keyid === principalKeyid);
481
+ const at = Date.parse(p.timestamp);
482
+ const inScope = d.scopes.includes(p.tool.name);
483
+ const executed = p.execution.status === "executed" || p.execution.status === "failed";
484
+ // mirrors src/verify.ts: a call refused after the grant ran out is a true record; only an executed call must sit inside the window
485
+ const valid = !Number.isNaN(at) && Date.parse(d.issuedAt) <= at && at <= Date.parse(d.expiresAt);
486
+ 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`);
487
+ add("executed tool within delegated scope", !executed || inScope, inScope ? p.tool.name : `${p.tool.name} not in [${d.scopes.join(", ")}]`);
488
+ }
489
+ }
490
+ else {
491
+ add("principal is claimed, not attested", p.principal.provenance === "claimed", "no signed delegation in this receipt");
492
+ }
493
+ // Private evidence (mirrors src/verify.ts): the signed capture note names every path whose value is withheld behind
494
+ // a commitment. The browser has no key and takes no disclosure, so a digest over withheld values passes as committed
495
+ // and says so; a digest over values the receipt carries in clear is recomputed, with the salt the statement carries.
496
+ // The note decides, never the shape of the data: a path it names must hold a commitment (else the check fails), and
497
+ // commitment-shaped data it does not name is ordinary data, inside the digest.
498
+ // a commitment is one only when it carries what a verifier checks: the sha256 (the salt is never in the receipt), and for an encrypted one the fields the key needs, a 12-byte iv and a 16-byte tag
499
+ // a string check before each pattern: RegExp.test coerces, and an array of one hex string is not a hash
500
+ const hex64 = (v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v);
501
+ const isCommitment = (v) => !!v && typeof v === "object" && !Array.isArray(v) && hex64(v.sha256) && (v.$custody === "withheld" || (v.$custody === "encrypted" && v.alg === "A256GCM" && hex64(v.keyid) && [v.iv, v.ciphertext, v.tag].every((f) => typeof f === "string" && f.length > 0 && /^[A-Za-z0-9+/]+=*$/.test(f)) && v.iv.length === 16 && v.tag.length === 24));
502
+ const note = p.capture;
503
+ const under = (w, prefix) => prefix.length <= w.length && prefix.every((s, i) => w[i] === s);
504
+ const getAt = (root, path) => path.reduce((v, k) => (v && typeof v === "object" && !Array.isArray(v) && Object.prototype.hasOwnProperty.call(v, k) ? v[k] : undefined), root);
505
+ const pathText = (w) => w.map((s) => (/^[A-Za-z0-9_$-]+$/.test(s) ? s : JSON.stringify(s))).join(".");
506
+ const committedNote = (paths) => {
507
+ const encrypted = paths.filter((w) => getAt(p, w)?.$custody === "encrypted").length;
508
+ return `committed, not recomputed: ${paths.length} value(s) withheld${encrypted ? ` (${encrypted} encrypted)` : ""}; ${encrypted ? "give the capture key or " : ""}disclose them with the command-line verifier to recompute`;
509
+ };
510
+ const claimed = new Set();
511
+ /** the withheld paths under a prefix, and the first one the receipt bears no commitment for */
512
+ const region = (prefix) => {
513
+ const paths = (note?.withheld ?? []).filter((w) => under(w, prefix));
514
+ for (const w of paths)
515
+ claimed.add(JSON.stringify(w));
516
+ const bad = paths.find((w) => !isCommitment(getAt(p, w)));
517
+ return { paths, problem: bad ? `the capture note says ${pathText(bad)} is withheld, but the receipt carries no commitment for it` : null };
518
+ };
519
+ const subjectOk = st.subject[0]?.digest.sha256 === p.request.argsDigest;
520
+ const args = region(["request", "args"]);
521
+ if (args.problem)
522
+ add("request args digest", false, args.problem);
523
+ else if (args.paths.length)
524
+ add("request args digest", subjectOk, committedNote(args.paths));
525
+ else
526
+ add("request args digest", (await digestOf(p.request.args)) === p.request.argsDigest && subjectOk);
527
+ const forwarded = ["executed", "failed", "error"].includes(p.execution.status);
528
+ if (p.approval) {
529
+ const a = p.approval;
530
+ const consumed = a.consumedAt !== undefined && Date.parse(a.consumedAt) >= Date.parse(a.checkedAt) && Date.parse(a.checkedAt) >= Date.parse(p.timestamp);
531
+ 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");
532
+ // Only a forwarded call must rest on a valid approval; a refusal is an authentic record whatever its approval was.
533
+ if (forwarded && a.status === "approved") {
534
+ const sealed = region(["approval", "envelope"]);
535
+ if (sealed.problem)
536
+ add("approval signatures (human keys)", false, sealed.problem);
537
+ // The issuer withholds the envelope only when it withholds the arguments. With the arguments in clear, a withheld
538
+ // envelope would let an issuer skip the binding check, so it fails rather than passes as committed.
539
+ else if (sealed.paths.length && !args.paths.length)
540
+ add("approval signatures (human keys)", false, "the approval envelope is withheld but the arguments are in clear; the binding cannot be checked");
541
+ else if (sealed.paths.length)
542
+ add("approval signatures (human keys)", true, committedNote(sealed.paths));
543
+ else {
544
+ const signed = await verifyApprovalStatement(a.envelope, opts.approvalKeys ?? [], a.requiredApprovers);
545
+ const reported = signed.ok && new Set(a.approverKeyids).size >= a.requiredApprovers && a.approverKeyids.every((id) => signed.approverKeyids.includes(id));
546
+ add("approval signatures (human keys)", signed.ok && reported, signed.ok ? `${signed.approverKeyids.length} distinct trusted signature(s)` : signed.error);
547
+ if (signed.ok) {
548
+ const at = a.consumedAt ?? a.checkedAt;
549
+ const atValid = Date.parse(at) >= Date.parse(signed.approval.issuedAt) && Date.parse(at) < Date.parse(signed.approval.expiresAt);
550
+ const valid = [a.checkedAt, at].every((time) => Date.parse(time) >= Date.parse(signed.approval.issuedAt) && Date.parse(time) < Date.parse(signed.approval.expiresAt));
551
+ add("approval valid at forward time", valid, `${signed.approval.issuedAt} .. ${signed.approval.expiresAt}; checked at ${at}`);
552
+ if (args.problem)
553
+ add("approval payload binding", false, args.problem);
554
+ else if (args.paths.length)
555
+ add("approval payload binding", true, committedNote(args.paths));
556
+ else {
557
+ const action = { principal: p.principal.id ?? "", agent: p.agent.id, tool: p.tool.name, argsDigest: await digestOf(p.request.args) };
558
+ for (const field of ["amount", "currency", "beneficiary"]) {
559
+ const name = a.fields?.[field] ?? field;
560
+ if (Object.hasOwn(p.request.args, name))
561
+ action[field] = p.request.args[name];
562
+ }
563
+ const mismatch = ["principal", "agent", "tool", "argsDigest", "amount", "currency", "beneficiary"].find((k) => signed.approval[k] !== action[k]);
564
+ add("approval payload binding", !mismatch && atValid, mismatch ? `approval ${mismatch} does not match this call` : atValid ? "principal, agent, tool, full arguments, amount, currency, and beneficiary match" : "approval has expired or is not yet valid");
565
+ }
566
+ }
567
+ }
568
+ }
569
+ }
570
+ for (const name of Object.keys(p.facts)) {
571
+ for (const part of ["value", "args"]) {
572
+ const r = region(["facts", name, part]);
573
+ if (!r.paths.length)
574
+ continue;
575
+ add(`fact ${name} ${part}`, !r.problem, r.problem ?? committedNote(r.paths));
576
+ }
577
+ }
578
+ const executedOrFailed = p.execution.status === "executed" || p.execution.status === "failed";
579
+ let resultInClear = false;
580
+ if (executedOrFailed) {
581
+ const r = region(["execution", "result"]);
582
+ if (r.problem)
583
+ add("execution result digest", false, r.problem);
584
+ else if (r.paths.length) {
585
+ add("execution result digest", true, committedNote(r.paths));
586
+ // the upstream checks read the content, isError, and structuredContent, never _meta, which carries what the
587
+ // upstream wrote and is withheld beside a result the rule leaves in clear: with only _meta withheld they still run
588
+ if (r.paths.every((w) => JSON.stringify(w) === JSON.stringify(["execution", "result", "_meta"])))
589
+ resultInClear = true;
590
+ }
591
+ else {
592
+ add("execution result digest", (await digestOf(p.execution.result)) === p.execution.resultDigest);
593
+ resultInClear = true;
594
+ }
595
+ }
596
+ // every other withheld path gets its own line: a message, a denial reason, a provider's delivery body, a part added later
597
+ for (const w of note?.withheld ?? []) {
598
+ if (claimed.has(JSON.stringify(w)))
599
+ continue;
600
+ const ok = isCommitment(getAt(p, w));
601
+ add(`withheld ${pathText(w)}`, ok, ok ? committedNote([w]) : `the capture note says ${pathText(w)} is withheld, but the receipt carries no commitment for it`);
602
+ }
603
+ const stringOrCommitment = (v) => typeof v === "string" || isCommitment(v);
604
+ const isProvider = (v) => !!v && (v.provider === "stripe-webhook" || v.provider === "github-delivery") && stringOrCommitment(v.rawBody) && stringOrCommitment(v.signature) && stringOrCommitment(v.bind);
605
+ // a check is skipped only for a part the signed note declares withheld; a part that is simply not there, or commitment-shaped without the note saying so, fails
606
+ const declared = (path) => (note?.withheld ?? []).some((w) => JSON.stringify(w) === JSON.stringify(path));
607
+ if (executedOrFailed && p.execution.upstream && isProvider(p.execution.upstream)) {
608
+ if (opts.providerSecrets) {
609
+ const parts = ["rawBody", "signature", "bind"];
610
+ if (!resultInClear || parts.some((f) => declared(["execution", "upstream", f])))
611
+ add("upstream signature not checked", true, "the result, the delivery body, its signature, or its bind is withheld; disclose them with the command-line verifier to check the provider's delivery");
612
+ else if (parts.some((f) => typeof p.execution.upstream[f] !== "string"))
613
+ 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");
614
+ else {
615
+ const u = await checkProvider(p.execution.upstream, opts.providerSecrets, p.timestamp, p.execution.result);
616
+ add("upstream signature (provider secret)", u.ok, u.detail);
617
+ }
618
+ }
619
+ }
620
+ else if (executedOrFailed && p.execution.upstream && (opts.upstreamKeys?.length ?? 0) > 0) {
621
+ const env = p.execution.upstream.envelope;
622
+ const wellFormed = !!env && typeof env === "object" && typeof env.payload === "string" && Array.isArray(env.signatures);
623
+ if (!resultInClear)
624
+ add("upstream signature not checked", true, "the result is withheld; disclose it with the command-line verifier to check the upstream's signature against it");
625
+ else if (declared(["execution", "upstream", "envelope"]))
626
+ 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");
627
+ else if (!wellFormed)
628
+ add("upstream signature (upstream key)", false, "the receipt carries no upstream envelope to check, and the capture note does not say it is withheld");
629
+ else {
630
+ const u = await dsseVerify(p.execution.upstream.envelope, opts.upstreamKeys);
631
+ let ok = u.ok && p.execution.upstream.envelope.payloadType === UPSTREAM_TYPE;
632
+ let detail = u.ok ? `keyid ${short(u.keyid)}` : u.error;
633
+ if (u.ok) {
634
+ const expectedDigest = await digestOf({ content: p.execution.result.content, isError: !!p.execution.result.isError });
635
+ if (u.payload.receiptId !== p.receiptId) {
636
+ ok = false;
637
+ detail = "signed for a different receipt";
638
+ }
639
+ else if (u.payload.tool !== p.tool.name) {
640
+ ok = false;
641
+ detail = `signed for tool ${u.payload.tool}`;
642
+ }
643
+ else if (u.payload.contentDigest !== expectedDigest) {
644
+ ok = false;
645
+ detail = "signed content differs from the result in the receipt";
646
+ }
647
+ }
648
+ add("upstream signature (upstream key)", ok, detail);
649
+ }
650
+ }
651
+ if (p.policy) {
652
+ // a deny that was not enforced (observe mode, enforced: false on the receipt) may sit beside an executed call; an enforced one never does
653
+ const consistent = p.policy.decision === "allow" ? p.execution.status !== "denied" : p.policy.enforced === false ? p.execution.status !== "denied" : p.execution.status === "denied";
654
+ add("policy decision consistent with execution", consistent, `${p.policy.decision}${p.policy.enforced === false ? " (observe mode, not enforced)" : ""} -> ${p.execution.status}`);
655
+ // a withheld error list is a non-empty one: the issuer leaves an empty list in clear
656
+ const errors = isCommitment(p.policy.errors) || (Array.isArray(p.policy.errors) && p.policy.errors.length > 0);
657
+ add("no policy errors on an allow", !(p.policy.decision === "allow" && errors));
658
+ }
659
+ if (p.reconciliation) {
660
+ const r = p.reconciliation;
661
+ // Refuse nesting before the recursive verifier is called; the original must be the first operation attempt.
662
+ const osig = await dsseVerify(r.original.envelope, opts.issuerKeys);
663
+ const ost = osig.ok ? osig.payload : null;
664
+ const original = ost?.predicate;
665
+ const eligible = isObj(original) && !("reconciliation" in original);
666
+ let originalOk = false;
667
+ if (eligible && ost) {
668
+ try {
669
+ const nested = ost.predicateType === PREDICATE_TYPE
670
+ ? await verifyBundle(r.original, opts)
671
+ : await verifyOriginalAuthorization(r.original, opts);
672
+ originalOk = nested.ok;
673
+ for (const c of nested.checks)
674
+ add(`reconciliation original ${c.name}`, c.ok, c.detail);
675
+ }
676
+ catch {
677
+ add("reconciliation original bundle is well formed", false);
678
+ }
679
+ }
680
+ add("reconciliation original evidence verifies", eligible && originalOk);
681
+ const o = original?.operation;
682
+ const op = p.operation;
683
+ 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);
684
+ add("reconciliation links the original operation", linked);
685
+ add("reconciliation lookup matches authorization", !!o && (await digestOf(r.lookup)) === o.lookupDigest);
686
+ const lookupArgs = region(["request", "args"]);
687
+ add("reconciliation lookup args match request", !lookupArgs.problem && (lookupArgs.paths.length > 0 || canonicalize(p.request.args) === canonicalize(r.lookup.args)), lookupArgs.paths.length > 0 ? "request arguments committed under the capture rule" : undefined);
688
+ const before = r.original.inclusion.leafIndex < bundle.inclusion.leafIndex && r.original.inclusion.treeSize <= bundle.inclusion.treeSize;
689
+ const oth = await dsseVerify(r.original.treeHead, [...(opts.logKeys ?? []), ...opts.issuerKeys]);
690
+ const cth = await dsseVerify(bundle.treeHead, [...(opts.logKeys ?? []), ...opts.issuerKeys]);
691
+ add("reconciliation logged after original", before && oth.ok && cth.ok && isObj(oth.payload) && isObj(cth.payload) && oth.payload.log === cth.payload.log);
692
+ const terminal = op?.status === "confirmed" || op?.status === "failed";
693
+ add("reconciliation records a terminal provider outcome", terminal && p.execution.status === "executed" && p.execution.provenance === "observed");
694
+ const rr = region(["execution", "result"]);
695
+ if (rr.problem)
696
+ add("reconciliation provider status", false, rr.problem);
697
+ else if (rr.paths.some((w) => JSON.stringify(w) !== JSON.stringify(["execution", "result", "_meta"])))
698
+ add("reconciliation provider status", true, "provider result withheld; disclose it or give the capture key to recompute the gateway-observed status");
699
+ else {
700
+ const ex = p.execution;
701
+ const status = providerValue(ex.result, r.lookup.statusPath);
702
+ const mapped = typeof status === "string" ? r.lookup.confirmed.includes(status) ? "confirmed" : r.lookup.failed.includes(status) ? "failed" : null : null;
703
+ const identity = providerValue(ex.result, r.lookup.identityPath);
704
+ add("reconciliation provider status", terminal && mapped === op?.status && identity === op?.idempotencyKey && !(isObj(ex.result) && ex.result.isError === true), "provider read observed by the gateway and bound to its idempotency key; no independent provider signature is implied");
705
+ }
706
+ }
707
+ const logKeys = opts.logKeys ?? [];
708
+ if (p.authorization) {
709
+ const a = p.authorization;
710
+ const asig = await dsseVerify(a.envelope, opts.issuerKeys);
711
+ const ast = asig.ok ? asig.payload : null;
712
+ const typed = !!ast && a.envelope.payloadType === RECEIPT_TYPE && ast.predicateType === AUTHORIZATION_TYPE;
713
+ 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);
714
+ if (ast && typed) {
715
+ const ap = ast.predicate;
716
+ 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);
717
+ 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");
718
+ if (ap.approval || p.approval) {
719
+ const stable = (approval) => approval ? { envelope: approval.envelope, requiredApprovers: approval.requiredApprovers, fields: approval.fields } : null;
720
+ add("authorization carries this approval", canonicalize(stable(ap.approval)) === canonicalize(stable(p.approval)), "approval envelope, signer requirement, and argument mapping must match the precommit");
721
+ // A refusal needs no human keys, so the precommit's approval is checked for a forwarded call only.
722
+ if (forwarded) {
723
+ const ac = ap.approval;
724
+ // Under a private rule the precommit carries a commitment to the envelope, which this verifier cannot open.
725
+ // an envelope withheld beside arguments in clear is not a private receipt: see "approval signatures (human keys)"
726
+ const sealed = isCommitment(ac?.envelope) && args.paths.length > 0;
727
+ const signed = ac && !sealed && (ac.requiredApprovers === 1 || ac.requiredApprovers === 2) ? await verifyApprovalStatement(ac.envelope, opts.approvalKeys ?? [], ac.requiredApprovers) : null;
728
+ const valid = !!ac && ac.status === "approved" && ac.provenance === "observed" && iso(ac.checkedAt) && (sealed || !!signed?.ok) &&
729
+ (!signed?.ok || (Date.parse(ac.checkedAt) >= Date.parse(signed.approval.issuedAt) && Date.parse(ac.checkedAt) < Date.parse(signed.approval.expiresAt))) &&
730
+ Date.parse(ac.checkedAt) >= Date.parse(p.timestamp) && Date.parse(ac.checkedAt) <= Date.parse(p.approval?.checkedAt ?? "") &&
731
+ Array.isArray(ac.approverKeyids) && new Set(ac.approverKeyids).size >= ac.requiredApprovers && (!signed?.ok || ac.approverKeyids.every((id) => typeof id === "string" && signed.approverKeyids.includes(id)));
732
+ 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");
733
+ }
734
+ }
735
+ if (p.operation || ap.operation) {
736
+ const o = p.operation;
737
+ const aop = ap.operation;
738
+ 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));
739
+ }
740
+ const ath = await dsseVerify(a.treeHead, [...logKeys, ...opts.issuerKeys]);
741
+ add("authorization tree head signature", ath.ok && a.treeHead.payloadType === TREEHEAD_TYPE, ath.ok ? `keyid ${short(ath.keyid)}` : ath.error);
742
+ if (ath.ok) {
743
+ const ahead = ath.payload;
744
+ const included = ahead.treeSize === a.inclusion.treeSize && (await verifyInclusion(await leafHash(canonicalize(a.envelope)), a.inclusion, ahead.rootHash));
745
+ add("authorization log inclusion proof", included, `leaf ${a.inclusion.leafIndex} of ${a.inclusion.treeSize}`);
746
+ const before = a.inclusion.leafIndex < bundle.inclusion.leafIndex && a.inclusion.treeSize <= bundle.inclusion.treeSize;
747
+ add("authorization logged before execution", before, `authorization leaf ${a.inclusion.leafIndex}, receipt leaf ${bundle.inclusion.leafIndex}`);
748
+ }
749
+ }
750
+ }
751
+ const th = await dsseVerify(bundle.treeHead, [...logKeys, ...opts.issuerKeys]);
752
+ const byLog = th.ok && logKeys.some((k) => k.keyid === th.keyid);
753
+ treeHeadSigner = th.ok ? (byLog ? "log key" : "issuer key") : null;
754
+ add("tree head signature", th.ok && bundle.treeHead.payloadType === TREEHEAD_TYPE, th.ok ? `${byLog ? "log key" : "issuer key"} ${short(th.keyid)}` : th.error);
755
+ if (th.ok) {
756
+ const head = th.payload;
757
+ if (opts.logId !== undefined)
758
+ add("tree head names the expected log", head.log === opts.logId, head.log ? `log ${head.log}` : "tree head names no log");
759
+ add("tree head matches inclusion proof size", head.treeSize === bundle.inclusion.treeSize);
760
+ const included = await verifyInclusion(await leafHash(canonicalize(bundle.envelope)), bundle.inclusion, head.rootHash);
761
+ add("log inclusion proof", included, `leaf ${bundle.inclusion.leafIndex} of ${bundle.inclusion.treeSize}, root ${short(head.rootHash)}`);
762
+ if (opts.logLeaves) {
763
+ const hashes = [];
764
+ // a log copy holds leaf strings, or {pruned} and {hash} lines that already are the leaf hash
765
+ for (const l of opts.logLeaves)
766
+ hashes.push(typeof l === "string" ? await leafHash(l) : unhex((l.pruned ?? l.hash)));
767
+ if (head.treeSize > hashes.length)
768
+ add("log file root matches tree head", false, `log copy has ${hashes.length} leaves, tree head is at ${head.treeSize}`);
769
+ else {
770
+ const root = await rootOf(hashes, head.treeSize);
771
+ add("log file root matches tree head", root === head.rootHash, `recomputed ${short(root)}`);
772
+ }
773
+ }
774
+ }
775
+ return done(st);
776
+ }
777
+ async function rootOf(hashes, size) {
778
+ const split = (n) => { let k = 1; while (k * 2 < n)
779
+ k *= 2; return k; };
780
+ const mth = async (lo, hi) => {
781
+ const n = hi - lo;
782
+ if (n === 0)
783
+ return sha256(new Uint8Array(0));
784
+ if (n === 1)
785
+ return hashes[lo];
786
+ const k = split(n);
787
+ return nodeHash(await mth(lo, lo + k), await mth(lo + k, hi));
788
+ };
789
+ return hex(await mth(0, size));
790
+ }
791
+ export async function auditExtends(older, newer, proof, keys, logId, opts = {}) {
792
+ const checks = [];
793
+ const add = (name, ok, detail) => { checks.push(detail === undefined ? { name, ok } : { name, ok, detail }); return ok; };
794
+ const decode = async (label, env) => { const v = await dsseVerify(env, keys); add(`${label} tree head signature`, v.ok && env.payloadType === TREEHEAD_TYPE, v.ok ? `keyid ${short(v.keyid)}` : v.error); return v.ok ? v.payload : null; };
795
+ const a = await decode("older", older);
796
+ const b = await decode("newer", newer);
797
+ if (!a || !b)
798
+ return { ok: false, checks };
799
+ if (logId !== undefined)
800
+ add("both tree heads name the expected log", a.log === logId && b.log === logId, `expected ${logId}, got ${a.log ?? "none"} and ${b.log ?? "none"}`);
801
+ else if (a.log !== b.log)
802
+ add("both tree heads name the same log", false, `${a.log ?? "none"} and ${b.log ?? "none"}`);
803
+ if (!add("older is not larger than newer", a.treeSize <= b.treeSize, `${a.treeSize} -> ${b.treeSize}`))
804
+ return { ok: false, checks };
805
+ const consistent = await verifyConsistency(a.treeSize, a.rootHash, b.treeSize, b.rootHash, proof);
806
+ add("newer log extends older log", consistent, consistent ? `${proof.length} proof hashes` : "history was rewritten, or the proof is for other tree heads");
807
+ if (opts.witnessKeys && opts.witnessKeys.length > 0) {
808
+ // every witness key whose signature on the newer head verifies
809
+ const by = [];
810
+ for (const s of newer.signatures) {
811
+ const k = opts.witnessKeys.find((w) => w.keyid === s.keyid);
812
+ if (!k)
813
+ continue;
814
+ const payload = b64.decode(newer.payload);
815
+ if (await subtle().verify({ name: "Ed25519" }, k.key, b64.decode(s.sig), pae(newer.payloadType, payload)))
816
+ by.push(s.keyid);
817
+ }
818
+ add("newer tree head countersigned by a witness", by.length > 0, by.length ? `witness ${short(by[0])}` : "no witness signature on the newer head");
819
+ }
820
+ return { ok: checks.every((c) => c.ok), checks };
821
+ }
822
+ /** The human-readable report, the same shape the CLI prints. */
823
+ export function formatReport(r) {
824
+ const lines = r.checks.map((c) => `${c.ok ? "PASS" : "FAIL"} ${c.name}${c.detail ? ` (${c.detail})` : ""}`);
825
+ lines.push("", r.ok ? "RESULT: VERIFIED" : "RESULT: NOT VERIFIED");
826
+ if (!r.statement)
827
+ return lines.join("\n");
828
+ const p = r.statement.predicate;
829
+ lines.push("", `ISSUER: ${p.issuer.kind}${p.issuer.framework ? ` (${p.issuer.framework})` : ""}, ${r.issuerNote}`, "", "field provenance value");
830
+ const row = (f, prov, v) => lines.push(`${f.padEnd(15)} ${prov.padEnd(11)} ${typeof v === "string" ? v : JSON.stringify(v)}`);
831
+ row("principal", p.principal.provenance, p.principal.id ?? "(none)");
832
+ row("agent", p.agent.provenance, p.agent.id);
833
+ const idText = (v) => (typeof v === "string" ? v : v === null || v === undefined ? "-" : "(withheld under the capture rule)");
834
+ if (p.session.id || p.session.toolUseId)
835
+ row("session", p.session.provenance, `${idText(p.session.id)} / ${idText(p.session.toolUseId)}`);
836
+ row("model", p.model.provenance, p.model.id === null ? "(none supplied)" : idText(p.model.id));
837
+ row("tool", p.tool.provenance, p.tool.name);
838
+ row("args", p.request.provenance, p.request.args);
839
+ for (const [k, f] of Object.entries(p.facts))
840
+ row(`fact.${k}`, f.provenance, f.value);
841
+ if (p.policy)
842
+ row("policy", p.policy.provenance, `${p.policy.decision}${p.policy.enforced === false ? " (observe mode, not enforced)" : ""} [${p.policy.reasons.join(",")}] policy ${short(p.policy.policyDigest)}`);
843
+ else
844
+ row("policy", "-", "(none evaluated)");
845
+ if (p.consumed)
846
+ 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);
847
+ if (p.approval)
848
+ 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}` : ""}`);
849
+ const upstreamCheck = r.checks.find((c) => c.name === "upstream signature (upstream key)" || c.name === "upstream signature (provider secret)");
850
+ const hasUpstream = (p.execution.status === "executed" || p.execution.status === "failed") && !!p.execution.upstream;
851
+ const byProvider = hasUpstream && !!p.execution.upstream.provider;
852
+ const attestedAs = upstreamCheck?.ok ? (byProvider ? "attested (shared secret)" : "attested") : p.execution.provenance;
853
+ const note = !hasUpstream ? "" : upstreamCheck ? (upstreamCheck.ok ? ` (${byProvider ? upstreamCheck.detail : `signed by upstream ${upstreamCheck.detail}`})` : " (upstream signature FAILED)") : byProvider ? " (carries a provider delivery; add the provider secret to check it)" : " (carries an upstream signature; add the upstream key to check it)";
854
+ row("execution", attestedAs, `${p.execution.status}${note}`);
855
+ return lines.join("\n");
856
+ }