@agent-custody/receipts 0.7.0 → 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.
@@ -0,0 +1,204 @@
1
+ // Offline policy replay. The recorded inputs stay fixed; no tool or fact provider is called.
2
+ import { randomUUID } from "node:crypto";
3
+ import * as cedar from "@cedar-policy/cedar-wasm/nodejs";
4
+ import { isCommitment, pathText, restorePaths, under } from "./capture.js";
5
+ import { canonicalize, dsseVerify } from "./crypto.js";
6
+ import { decodeDelegation, DELEGATION_TYPE, delegationValidAt } from "./delegation.js";
7
+ import { leafHash, verifyInclusion } from "./log.js";
8
+ import { evaluate, policyDigest } from "./policy.js";
9
+ import { AUTHORIZATION_PREDICATE_TYPE, RECEIPT_TYPE, TREEHEAD_TYPE } from "./receipt.js";
10
+ import { structuralProblem } from "./verify.js";
11
+ const strings = (v) => Array.isArray(v) && v.every((x) => typeof x === "string");
12
+ const order = (a, b) => a < b ? -1 : a > b ? 1 : 0;
13
+ /** A gateway can deny before Cedar runs. Such a denial cannot be changed by replacing Cedar text. */
14
+ function gateProblem(p) {
15
+ if (p.issuer.kind !== "gateway")
16
+ return null;
17
+ // The approval gate runs before Cedar and records its refusal as a deny. The approval record, which stays in clear
18
+ // under a private rule, says so. A later approval refusal beside an allow, or beside an unenforced deny, means that
19
+ // Cedar did run.
20
+ if (p.policy?.decision === "deny" && p.policy.enforced !== false && p.approval?.status === "denied")
21
+ return "non-policy gate: the approval was refused before Cedar ran";
22
+ // A failed gatherFacts never assigns its partial result to the receipt. With private errors, no facts, and no
23
+ // determining policy ids, an evaluation error and missing lookup inputs are indistinguishable. Observe mode may
24
+ // even have executed this call, so execution status cannot establish whether Cedar ran.
25
+ if (p.policy?.decision === "deny" && isCommitment(p.policy.errors) && Object.keys(p.facts).length === 0 && p.policy.reasons.length === 0) {
26
+ return "original failure details are withheld; cannot establish complete Cedar inputs";
27
+ }
28
+ // The decision is the baseline. A grant revoked after Cedar ran can withhold execution, but does not invalidate
29
+ // the recorded policy inputs or turn that allow into an early gate denial.
30
+ const messages = Array.isArray(p.policy?.errors) ? p.policy.errors : [];
31
+ const gate = messages.find((s) => /^delegation grant /s.test(s)
32
+ || /^tool ".*" is not in the delegation scopes$/s.test(s)
33
+ || /^fact argument ".*" needs call argument ".*", which is missing$/s.test(s)
34
+ || /^fact ".*" lookup via .* failed:/s.test(s));
35
+ return gate ? `non-policy gate: ${gate}` : null;
36
+ }
37
+ /**
38
+ * Check an authorization bundle that has no receipt, as the verifier does for an embedded one: the issuer signed it, it
39
+ * is an authorization statement, and its leaf is in the log under a signed tree head. Throws when a check fails.
40
+ * Returns the statement's predicate.
41
+ */
42
+ export function verifyOrphanAuthorization(bundle, issuerKeys, logKeys) {
43
+ const signed = dsseVerify(bundle.envelope, issuerKeys);
44
+ if (!signed.ok)
45
+ throw new Error(`authorization signature (issuer key) (${signed.error})`);
46
+ const statement = signed.payload;
47
+ if (bundle.envelope.payloadType !== RECEIPT_TYPE || statement.predicateType !== AUTHORIZATION_PREDICATE_TYPE)
48
+ throw new Error("authorization payload type");
49
+ const head = dsseVerify(bundle.treeHead, [...logKeys, ...issuerKeys]);
50
+ if (!head.ok || bundle.treeHead.payloadType !== TREEHEAD_TYPE)
51
+ throw new Error(`authorization tree head signature${head.ok ? "" : ` (${head.error})`}`);
52
+ const tree = head.payload;
53
+ if (tree.treeSize !== bundle.inclusion.treeSize || !verifyInclusion(leafHash(canonicalize(bundle.envelope)), bundle.inclusion, tree.rootHash))
54
+ throw new Error("authorization log inclusion proof");
55
+ return statement.predicate;
56
+ }
57
+ /**
58
+ * Compare a proposed Cedar policy with recorded policy decisions, using each receipt's original arguments, fact
59
+ * values, agent, and (for gateways) grant context. Observe-mode decisions are the baseline even when the call ran.
60
+ * Receipts are not signature-verified here; verify their bundles separately when their authenticity matters.
61
+ * Missing inputs and non-Cedar gate failures are reported as skipped, never guessed or fetched again.
62
+ * The receipts are read once, one at a time, so a caller can verify and parse a large history lazily.
63
+ */
64
+ export function simulatePolicy(policyText, receipts, options = {}) {
65
+ const parsed = cedar.checkParsePolicySet({ staticPolicies: policyText });
66
+ if (parsed.type === "failure")
67
+ throw new Error(`invalid Cedar policy: ${parsed.errors.map((e) => e.message).join("; ")}`);
68
+ const unreplayable = options.unreplayable ?? [];
69
+ const report = {
70
+ runId: randomUUID(),
71
+ timestamp: new Date().toISOString(),
72
+ policyDigest: policyDigest(policyText),
73
+ previousPolicyDigests: [],
74
+ total: unreplayable.length,
75
+ evaluated: 0,
76
+ unchanged: 0,
77
+ complete: true,
78
+ changes: [],
79
+ skipped: [...unreplayable],
80
+ groups: [],
81
+ };
82
+ const digests = new Set();
83
+ for (const original of receipts) {
84
+ report.total++;
85
+ const receiptId = typeof original?.receiptId === "string" ? original.receiptId : "(unknown receipt)";
86
+ const tool = typeof original?.tool?.name === "string" ? original.tool.name : "(unknown tool)";
87
+ const skip = (reason) => { report.skipped.push({ receiptId, tool, reason }); };
88
+ const broken = structuralProblem(original);
89
+ if (broken) {
90
+ skip(`malformed receipt: ${broken}`);
91
+ continue;
92
+ }
93
+ if (original.policy === null) {
94
+ skip("no recorded policy decision (record-only receipt)");
95
+ continue;
96
+ }
97
+ const previous = original.policy;
98
+ if (typeof previous.policyDigest !== "string" || !previous.policyDigest || !strings(previous.reasons)
99
+ || (!strings(previous.errors) && !(isCommitment(previous.errors) && original.capture?.withheld.some((p) => p.length === 2 && p[0] === "policy" && p[1] === "errors")))
100
+ || (previous.enforced !== undefined && typeof previous.enforced !== "boolean")) {
101
+ skip("malformed receipt: recorded policy metadata is invalid");
102
+ continue;
103
+ }
104
+ digests.add(previous.policyDigest);
105
+ if (!receiptId || !tool || typeof original.agent.id !== "string" || !original.agent.id
106
+ || !Number.isFinite(Date.parse(original.timestamp)) || !["sdk", "gateway"].includes(original.issuer.kind)) {
107
+ skip("malformed receipt: receipt id, tool, agent, timestamp, or issuer is invalid");
108
+ continue;
109
+ }
110
+ const restored = restorePaths(original, original.capture, options.disclosures?.get(receiptId), options.captureKey);
111
+ if (restored.problems.length) {
112
+ skip(`malformed capture: ${restored.problems.map((p) => p.error).join("; ")}`);
113
+ continue;
114
+ }
115
+ const missing = restored.missing.filter((p) => under(p, ["request", "args"]) || (p[0] === "facts" && p[2] === "value"));
116
+ if (missing.length) {
117
+ skip(`required policy inputs are withheld: ${missing.map(pathText).join(", ")}`);
118
+ continue;
119
+ }
120
+ const p = restored.predicate;
121
+ if (tool === "(unknown tool)" && p.issuer.kind === "gateway" && p.capture) {
122
+ skip("the original tool name is unavailable under the capture rule");
123
+ continue;
124
+ }
125
+ if (Object.values(p.facts).some((f) => !Object.hasOwn(f, "value") || f.value === undefined)) {
126
+ skip("malformed receipt: a recorded fact has no value");
127
+ continue;
128
+ }
129
+ const gate = gateProblem(p);
130
+ if (gate) {
131
+ skip(gate);
132
+ continue;
133
+ }
134
+ const context = {
135
+ args: p.request.args,
136
+ facts: Object.fromEntries(Object.entries(p.facts).map(([name, fact]) => [name, fact.value])),
137
+ };
138
+ if (p.issuer.kind === "gateway") {
139
+ const envelope = p.delegation?.envelope;
140
+ const grant = envelope?.payloadType === DELEGATION_TYPE ? decodeDelegation(envelope) : null;
141
+ if (!grant || grant.agent !== p.agent.id || grant.principal !== p.principal.id) {
142
+ skip("the recorded delegation context is missing, malformed, or does not name this agent and principal");
143
+ continue;
144
+ }
145
+ if (!grant.scopes.includes(tool)) {
146
+ skip("the tool is outside the recorded delegation scopes");
147
+ continue;
148
+ }
149
+ if (!delegationValidAt(grant, p.timestamp)) {
150
+ skip("the recorded delegation was outside its validity window at receipt time");
151
+ continue;
152
+ }
153
+ context.grant = { principal: grant.principal, scopes: grant.scopes };
154
+ }
155
+ let proposed;
156
+ try {
157
+ proposed = evaluate(policyText, { agentId: p.agent.id, tool, context });
158
+ }
159
+ catch (e) {
160
+ // An evaluator exception is a deny, just as at the gateway; it must never become an allow in a replay.
161
+ proposed = { decision: "deny", reasons: [], errors: [e instanceof Error ? e.message : String(e)], policyDigest: report.policyDigest };
162
+ }
163
+ report.evaluated++;
164
+ if (proposed.decision === previous.decision)
165
+ report.unchanged++;
166
+ else
167
+ report.changes.push({ receiptId, tool, previous, proposed });
168
+ }
169
+ report.previousPolicyDigests = [...digests].sort(order);
170
+ report.complete = report.skipped.length === 0;
171
+ const groups = new Map();
172
+ for (const change of report.changes) {
173
+ const reason = [...new Set([...change.proposed.reasons, ...change.proposed.errors])].sort(order).join("; ") || "no permit policy matched";
174
+ const key = JSON.stringify([change.tool, reason]);
175
+ const group = groups.get(key) ?? { tool: change.tool, reason, receiptIds: [] };
176
+ group.receiptIds.push(change.receiptId);
177
+ groups.set(key, group);
178
+ }
179
+ report.groups = [...groups.values()].sort((a, b) => order(a.tool, b.tool) || order(a.reason, b.reason));
180
+ for (const group of report.groups)
181
+ group.receiptIds.sort(order);
182
+ return report;
183
+ }
184
+ export function formatSimulation(report) {
185
+ const changes = new Map(report.changes.map((c) => [JSON.stringify([c.tool, c.receiptId]), c]));
186
+ const lines = [
187
+ `Policy simulation ${report.runId}`,
188
+ `Timestamp: ${report.timestamp}`,
189
+ `Proposed policy: ${report.policyDigest}`,
190
+ `Previous policies: ${report.previousPolicyDigests.join(", ") || "none"}`,
191
+ `Receipts: ${report.total}; evaluated: ${report.evaluated}; unchanged: ${report.unchanged}; changed: ${report.changes.length}; skipped: ${report.skipped.length}`,
192
+ ];
193
+ for (const group of report.groups) {
194
+ lines.push("", `${group.tool}: ${group.reason}`);
195
+ for (const receiptId of group.receiptIds) {
196
+ const change = changes.get(JSON.stringify([group.tool, receiptId]));
197
+ lines.push(` ${receiptId}: ${change.previous.decision} -> ${change.proposed.decision}`);
198
+ }
199
+ }
200
+ for (const skipped of report.skipped)
201
+ lines.push(`SKIPPED ${skipped.receiptId} (${skipped.tool}): ${skipped.reason}`);
202
+ lines.push("", report.complete ? "RESULT: COMPLETE" : "RESULT: INCOMPLETE");
203
+ return lines.join("\n");
204
+ }
package/dist/splunk.js CHANGED
@@ -4,6 +4,9 @@ export function hecEvent(p, bundle, cfg) {
4
4
  const exec = p.execution;
5
5
  // under a capture rule a message is a commitment; the event says so rather than carrying it
6
6
  const text = (v) => (typeof v === "string" ? v : v && typeof v === "object" ? "(withheld under the capture rule)" : undefined);
7
+ // A reconciliation receipt records a provider read. No policy ran and the payment tool did not run again, so the
8
+ // event carries no decision and its status is "reconciled", never "executed" with "allow".
9
+ const reconciliation = p.reconciliation !== undefined;
7
10
  return {
8
11
  time: Date.parse(p.timestamp) / 1000,
9
12
  source: cfg.source ?? "agent-custody",
@@ -19,11 +22,15 @@ export function hecEvent(p, bundle, cfg) {
19
22
  agent: p.agent.id,
20
23
  agent_provenance: p.agent.provenance,
21
24
  principal: p.principal.id,
22
- status: exec.status,
25
+ status: reconciliation ? "reconciled" : exec.status,
23
26
  reason: text(exec.reason) ?? text(exec.error) ?? null,
24
- policy_decision: p.policy?.decision ?? null,
25
- policy_digest: p.policy?.policyDigest ?? null,
26
- policy_reasons: p.policy?.reasons ?? [],
27
+ policy_decision: reconciliation ? null : p.policy?.decision ?? null,
28
+ policy_digest: reconciliation ? null : p.policy?.policyDigest ?? null,
29
+ policy_reasons: reconciliation ? [] : p.policy?.reasons ?? [],
30
+ reconciliation,
31
+ reconciliation_lookup_tool: reconciliation ? p.reconciliation.lookup?.tool ?? null : null,
32
+ operation_status: p.operation?.status ?? null,
33
+ operation_original_receipt_id: p.operation?.originalReceiptId ?? null,
27
34
  args_digest: p.request.argsDigest,
28
35
  log_leaf_index: bundle.inclusion.leafIndex,
29
36
  log_tree_size: bundle.inclusion.treeSize,
package/dist/verify.d.ts CHANGED
@@ -10,6 +10,8 @@ export interface VerifyOptions {
10
10
  /** keys trusted to have issued receipts: gateway keys, SDK application keys */
11
11
  issuerKeys: PublicKeyRef[];
12
12
  principalKeys: PublicKeyRef[];
13
+ /** Human approval keys, trusted independently of receipt issuers and delegation principals. Required for an approved action. */
14
+ approvalKeys?: PublicKeyRef[];
13
15
  /** keys of logs run by someone other than the issuer; tree heads are checked against these and the issuer keys */
14
16
  logKeys?: PublicKeyRef[];
15
17
  /** keys of upstreams that sign their results; with one given, an execution carrying an upstream signature is checked and becomes attested */
package/dist/verify.js CHANGED
@@ -1,5 +1,6 @@
1
1
  // Independent verification of a receipt bundle. Needs only public keys, and optionally a copy of the log.
2
2
  import { canonicalize, digestOf, dsseVerifiers, dsseVerify } from "./crypto.js";
3
+ import { isApprovalTime, verifyApproval, verifyApprovalStatement } from "./approval.js";
3
4
  import { digestSaltFor, getAt, isCommitment, pathKey, pathText, restorePaths, under } from "./capture.js";
4
5
  import { delegationHasParent, delegationValidAt, describeChain, verifyDelegation } from "./delegation.js";
5
6
  import { leafHash, MerkleLog, verifyConsistency, verifyInclusion } from "./log.js";
@@ -7,9 +8,88 @@ import { checkProvider, checkUpstream, contentDigest, isProviderAttestation } fr
7
8
  import { AUTHORIZATION_PREDICATE_TYPE, RECEIPT_PREDICATE_TYPE, RECEIPT_TYPE, TREEHEAD_TYPE } from "./receipt.js";
8
9
  const short = (s) => s.slice(0, 12);
9
10
  const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
11
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12
+ const hex64 = (v) => typeof v === "string" && /^[0-9a-f]{64}$/.test(v);
13
+ function operationProblem(o) {
14
+ if (!isObject(o) || (o.id !== undefined && (typeof o.id !== "string" || !UUID.test(o.id))) || typeof o.originalReceiptId !== "string" || !UUID.test(o.originalReceiptId))
15
+ return "operation ids are not UUIDs";
16
+ if (!hex64(o.idempotencyKey) || !hex64(o.lookupDigest))
17
+ return "operation idempotencyKey or lookupDigest is not a sha256";
18
+ if (!["submitted", "pending", "confirmed", "failed", "unknown"].includes(String(o.status)) || o.provenance !== "observed")
19
+ return "operation status or provenance is invalid";
20
+ if (!isObject(o.budget) || typeof o.budget.id !== "string" || !o.budget.id.length || o.budget.id.length > 128 || typeof o.budget.currency !== "string" || !/^[A-Z]{3}$/.test(o.budget.currency) || typeof o.budget.period !== "string" || !/^\d{4}-\d{2}-\d{2}$/.test(o.budget.period))
21
+ return "operation budget is invalid";
22
+ return null;
23
+ }
24
+ /** Provider records are JSON in the first text result, just as the gateway's ordinary fact extraction reads them. */
25
+ function providerValue(result, path) {
26
+ let record;
27
+ if (isObject(result) && Array.isArray(result.content)) {
28
+ const text = result.content.find((c) => isObject(c) && c.type === "text");
29
+ if (isObject(text) && typeof text.text === "string") {
30
+ try {
31
+ record = JSON.parse(text.text);
32
+ }
33
+ catch {
34
+ return undefined;
35
+ }
36
+ }
37
+ }
38
+ return path.split(".").reduce((v, k) => isObject(v) && Object.hasOwn(v, k) ? v[k] : undefined, record);
39
+ }
40
+ /** Verify a pre-forward authorization on its own when a crash prevented an outcome receipt being written. */
41
+ function verifyOriginalAuthorization(bundle, opts) {
42
+ const checks = [];
43
+ const add = (name, ok, detail) => checks.push({ name, ok, ...(detail === undefined ? {} : { detail }) });
44
+ const sig = dsseVerify(bundle.envelope, opts.issuerKeys);
45
+ const st = sig.ok ? sig.payload : null;
46
+ const typed = !!st && bundle.envelope.payloadType === RECEIPT_TYPE && st.predicateType === AUTHORIZATION_PREDICATE_TYPE;
47
+ add("authorization signature (issuer key)", sig.ok && typed);
48
+ if (!sig.ok || !st || !typed)
49
+ return { ok: false, predicate: null, checks };
50
+ const p = st.predicate;
51
+ // Authorizations have no session, model, or execution; validate the parts they share with ordinary receipts.
52
+ const problem = structuralProblem({ ...p, session: { id: null, toolUseId: null, provenance: "claimed" }, model: { id: null, provenance: "claimed" }, execution: { status: "withheld", provenance: "observed" } });
53
+ add("structural parts in clear", !problem, problem ?? undefined);
54
+ if (problem)
55
+ return { ok: false, predicate: null, checks };
56
+ add("authorization issued by the gateway", p.issuer.kind === "gateway" && p.issuer.keyid === sig.keyid);
57
+ add("authorization operation is submitted", p.operation?.status === "submitted");
58
+ add("authorization permits the original call", p.policy?.decision === "allow" ? Array.isArray(p.policy.errors) && p.policy.errors.length === 0 : p.policy?.decision === "deny" && p.policy.enforced === false);
59
+ const del = p.delegation && verifyDelegation(p.delegation.envelope, opts.principalKeys);
60
+ add("delegation signature (principal key)", !!del?.ok);
61
+ if (del?.ok) {
62
+ const d = del.delegation;
63
+ add("delegation binds principal and agent", d.principal === p.principal.id && d.agent === p.agent.id && p.principal.provenance === "attested" && p.principal.keyid === del.keyid);
64
+ add("delegation valid at receipt time", delegationValidAt(d, p.timestamp));
65
+ add("executed tool within delegated scope", d.scopes.includes(p.tool.name));
66
+ }
67
+ const back = restorePaths(p, p.capture, undefined, opts.captureKey);
68
+ add("captured commitments are well formed", back.problems.length === 0, back.problems[0]?.error);
69
+ const missingArgs = back.missing.some((w) => under(w, ["request", "args"]));
70
+ add("request args digest", st.subject[0]?.digest.sha256 === p.request.argsDigest && (missingArgs || digestOf(back.predicate.request.args, digestSaltFor(back, p.capture, ["request", "args"])) === p.request.argsDigest));
71
+ const th = dsseVerify(bundle.treeHead, [...(opts.logKeys ?? []), ...opts.issuerKeys]);
72
+ add("tree head signature", th.ok && bundle.treeHead.payloadType === TREEHEAD_TYPE);
73
+ if (th.ok) {
74
+ const head = th.payload;
75
+ if (opts.logId !== undefined)
76
+ add("tree head names the expected log", head.log === opts.logId);
77
+ add("log inclusion proof", head.treeSize === bundle.inclusion.treeSize && verifyInclusion(leafHash(canonicalize(bundle.envelope)), bundle.inclusion, head.rootHash));
78
+ if (opts.logFile) {
79
+ try {
80
+ add("log file root matches tree head", MerkleLog.rootFromFile(opts.logFile, head.treeSize) === head.rootHash);
81
+ }
82
+ catch {
83
+ add("log file root matches tree head", false);
84
+ }
85
+ }
86
+ }
87
+ return { ok: checks.every((c) => c.ok), predicate: p, checks };
88
+ }
10
89
  /** The parts of a statement a capture note may never name: what a verifier reads to run its checks. A note naming one, or a commitment sitting there, is not a private receipt but a broken one. */
11
90
  const STRUCTURAL_TOP = new Set(["receiptId", "timestamp", "issuer", "principal", "agent", "delegation", "tool", "authorization", "capture"]);
12
- const STRUCTURAL_IN = { 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"]) };
91
+ // The approval record's envelope and reason are withheld under a private rule; its status, times, and signer ids are not.
92
+ const STRUCTURAL_IN = { approval: new Set(["status", "requiredApprovers", "checkedAt", "consumedAt", "approverKeyids", "fields", "provenance"]), request: new Set(["argsDigest", "provenance"]), execution: new Set(["status", "provenance"]), policy: new Set(["decision", "reasons", "policyDigest", "enforced", "provenance"]), consumed: new Set(["provenance"]), session: new Set(["provenance"]), model: new Set(["provenance"]), operation: new Set(["idempotencyKey", "lookupDigest", "status", "budget", "originalReceiptId", "provenance"]), reconciliation: new Set(["original", "lookup"]) };
13
93
  /**
14
94
  * Why a statement cannot be verified at all, or null: the capture note is malformed, names a structural part, or a
15
95
  * structural part is not what every check assumes it to be. Checked once, before anything reads the statement, so that
@@ -42,7 +122,7 @@ export function structuralProblem(p) {
42
122
  return "tool.name is not a string";
43
123
  if (!isObject(p.request) || typeof p.request.argsDigest !== "string" || !isObject(p.request.args))
44
124
  return "request.args or request.argsDigest is not what it should be";
45
- if (!isObject(p.execution) || !["executed", "failed", "denied", "error", "withheld"].includes(String(p.execution.status)))
125
+ if (!isObject(p.execution) || typeof p.execution.status !== "string" || !["executed", "failed", "denied", "error", "withheld"].includes(p.execution.status))
46
126
  return "execution.status is not a status";
47
127
  if (p.policy !== null && (!isObject(p.policy) || (p.policy.decision !== "allow" && p.policy.decision !== "deny") || !Array.isArray(p.policy.reasons)))
48
128
  return "policy is neither null nor a decision";
@@ -54,6 +134,30 @@ export function structuralProblem(p) {
54
134
  return "delegation is not a signed envelope";
55
135
  if (p.authorization !== undefined && (!isObject(p.authorization) || !isObject(p.authorization.envelope)))
56
136
  return "authorization is not a bundle";
137
+ if (p.approval !== undefined) {
138
+ const a = p.approval;
139
+ if (!isObject(a) || typeof a.status !== "string" || !["approved", "denied"].includes(a.status) || (a.requiredApprovers !== 1 && a.requiredApprovers !== 2) || !isApprovalTime(a.checkedAt) || !Array.isArray(a.approverKeyids) || !a.approverKeyids.every((k) => typeof k === "string") || a.provenance !== "observed")
140
+ return "approval is not an approval record";
141
+ if (a.consumedAt !== undefined && !isApprovalTime(a.consumedAt))
142
+ return "approval consumption time is not a timestamp";
143
+ if (a.fields !== undefined && (!isObject(a.fields) || Object.entries(a.fields).some(([k, v]) => !["amount", "currency", "beneficiary"].includes(k) || typeof v !== "string" || !v.length)))
144
+ return "approval field mapping is malformed";
145
+ }
146
+ if (p.operation !== undefined) {
147
+ const problem = operationProblem(p.operation);
148
+ if (problem)
149
+ return problem;
150
+ }
151
+ if (p.reconciliation !== undefined) {
152
+ const r = p.reconciliation;
153
+ if (!isObject(r) || !isObject(r.original) || !isObject(r.original.envelope) || !isObject(r.original.treeHead) || !isObject(r.original.inclusion) || !isObject(r.lookup))
154
+ return "reconciliation is not a lookup and an original bundle";
155
+ const l = r.lookup;
156
+ const statuses = (v) => Array.isArray(v) && v.length > 0 && v.every((s) => typeof s === "string" && s.length > 0 && s.length <= 128);
157
+ const path = (v) => typeof v === "string" && v.length > 0 && v.length <= 512 && v.split(".").every((s) => s.length > 0);
158
+ if (typeof l.tool !== "string" || !l.tool.length || !isObject(l.args) || !path(l.statusPath) || !path(l.identityPath) || !statuses(l.confirmed) || !statuses(l.failed) || l.confirmed.some((s) => l.failed.includes(s)))
159
+ return "reconciliation lookup is malformed or its terminal statuses overlap";
160
+ }
57
161
  if (isObject(p.execution.upstream) && typeof p.execution.upstream.provider !== "undefined" && typeof p.execution.upstream.provider !== "string")
58
162
  return "execution.upstream.provider is not a string";
59
163
  return null;
@@ -80,6 +184,17 @@ export function verifyBundle(bundle, opts) {
80
184
  const p = st.predicate;
81
185
  add("issuer kind is known", p.issuer.kind === "gateway" || p.issuer.kind === "sdk", `${p.issuer.kind}${p.issuer.framework ? ` / ${p.issuer.framework}` : ""}`);
82
186
  add("issuer keyid matches signer", p.issuer.keyid === sig.keyid);
187
+ if (p.operation) {
188
+ add("operation observed by gateway", p.issuer.kind === "gateway" && p.operation.provenance === "observed");
189
+ if (!p.reconciliation) {
190
+ // A retry of an existing operation has a receipt of its own. It is withheld (never forwarded again) and names the original.
191
+ const retry = p.operation.originalReceiptId !== p.receiptId;
192
+ add("operation names this original receipt", !retry || p.execution.status === "withheld");
193
+ const refused = p.execution.status === "withheld" || p.execution.status === "denied";
194
+ add("operation awaits provider reconciliation", retry || ["submitted", "pending", "unknown"].includes(p.operation.status) || refused && p.operation.status === "failed");
195
+ add("operation carries committed authorization", refused || !!p.authorization);
196
+ }
197
+ }
83
198
  if (p.issuer.kind === "gateway") {
84
199
  add("gateway receipt carries a delegation", p.delegation !== undefined);
85
200
  add("gateway receipt carries a policy decision", p.policy !== null);
@@ -100,7 +215,7 @@ export function verifyBundle(bundle, opts) {
100
215
  const executed = p.execution.status === "executed" || p.execution.status === "failed";
101
216
  // a call the gateway refused after the grant ran out is still a true record; only an executed call has to sit inside the window
102
217
  const valid = delegationValidAt(d, p.timestamp);
103
- add("delegation valid at receipt time", valid || !executed, valid ? `${d.issuedAt} .. ${d.expiresAt}` : `${d.issuedAt} .. ${d.expiresAt}; the call was ${p.execution.status}, so the grant need not have been in force`);
218
+ add("delegation valid at receipt time", valid || !executed || !!p.reconciliation, valid ? `${d.issuedAt} .. ${d.expiresAt}` : p.reconciliation ? "operator reconciliation; the original authorization's grant window is checked separately" : `${d.issuedAt} .. ${d.expiresAt}; the call was ${p.execution.status}, so the grant need not have been in force`);
104
219
  add("executed tool within delegated scope", !executed || inScope, inScope ? p.tool.name : `${p.tool.name} not in [${d.scopes.join(", ")}]`);
105
220
  }
106
221
  }
@@ -142,6 +257,46 @@ export function verifyBundle(bundle, opts) {
142
257
  add("request args digest", subjectOk, committedNote(args.missing));
143
258
  else
144
259
  add("request args digest", digestOf(full.request.args, digestSaltFor(back, note, ["request", "args"])) === p.request.argsDigest && subjectOk, args.how ? `recomputed from ${args.how} values` : undefined);
260
+ // An upstream error can follow a side effect too; every attempted forward must have consumed a valid approval.
261
+ const forwarded = ["executed", "failed", "error"].includes(p.execution.status);
262
+ if (p.approval) {
263
+ const a = p.approval;
264
+ const consumed = a.consumedAt !== undefined && Date.parse(a.consumedAt) >= Date.parse(a.checkedAt) && Date.parse(a.checkedAt) >= Date.parse(p.timestamp);
265
+ add("approval consistent with execution", !forwarded || (a.status === "approved" && consumed), a.status === "denied" ? `approval refused: ${typeof a.reason === "string" ? a.reason : "not approved"}` : "single use is enforced by the gateway's persistent store; one receipt cannot prove absence of reuse elsewhere");
266
+ // Only a forwarded call must rest on a valid approval. A refusal is an authentic record whatever its approval was:
267
+ // missing, expired, forged, already used, or valid for a call that the policy or the grant then refused.
268
+ if (forwarded && a.status === "approved") {
269
+ // The envelope is withheld under a private rule: it carries the action fields and a digest of the arguments.
270
+ const sealed = region(["approval", "envelope"]);
271
+ if (sealed.problem)
272
+ add("approval signatures (human keys)", false, sealed.problem);
273
+ // The issuer withholds the envelope only when it withholds the arguments. With the arguments in clear, a withheld
274
+ // envelope would let an issuer skip the binding check, so it fails rather than passes as committed.
275
+ else if (sealed.missing.length && !args.paths.length)
276
+ add("approval signatures (human keys)", false, "the approval envelope is withheld but the arguments are in clear; the binding cannot be checked");
277
+ else if (sealed.missing.length)
278
+ add("approval signatures (human keys)", true, committedNote(sealed.missing));
279
+ else {
280
+ const envelope = full.approval.envelope;
281
+ const signed = verifyApprovalStatement(envelope, opts.approvalKeys ?? [], a.requiredApprovers);
282
+ const reported = signed.ok && new Set(a.approverKeyids).size >= a.requiredApprovers && a.approverKeyids.every((id) => signed.approverKeyids.includes(id));
283
+ add("approval signatures (human keys)", signed.ok && reported, signed.ok ? `${signed.approverKeyids.length} distinct trusted signature(s)` : signed.error);
284
+ if (signed.ok) {
285
+ const at = a.consumedAt ?? a.checkedAt;
286
+ const valid = [a.checkedAt, at].every((time) => Date.parse(time) >= Date.parse(signed.approval.issuedAt) && Date.parse(time) < Date.parse(signed.approval.expiresAt));
287
+ add("approval valid at forward time", valid, `${signed.approval.issuedAt} .. ${signed.approval.expiresAt}; checked at ${at}`);
288
+ if (args.problem)
289
+ add("approval payload binding", false, args.problem);
290
+ else if (args.missing.length)
291
+ add("approval payload binding", true, committedNote(args.missing));
292
+ else {
293
+ const binding = verifyApproval(envelope, opts.approvalKeys ?? [], { principal: p.principal.id ?? "", agent: p.agent.id, tool: p.tool.name, args: full.request.args, ...(a.fields ? { fields: a.fields } : {}) }, { at, minApprovers: a.requiredApprovers });
294
+ add("approval payload binding", binding.ok, binding.ok ? "principal, agent, tool, full arguments, amount, currency, and beneficiary match" : binding.error);
295
+ }
296
+ }
297
+ }
298
+ }
299
+ }
145
300
  // a captured fact: its commitments are checked against a disclosure or the key; the policy decided on the real value
146
301
  for (const name of Object.keys(p.facts)) {
147
302
  for (const part of ["value", "args"]) {
@@ -226,6 +381,54 @@ export function verifyBundle(bundle, opts) {
226
381
  const errors = isCommitment(p.policy.errors) || (Array.isArray(p.policy.errors) && p.policy.errors.length > 0);
227
382
  add("no policy errors on an allow", !(p.policy.decision === "allow" && errors));
228
383
  }
384
+ if (p.reconciliation) {
385
+ const r = p.reconciliation;
386
+ // Refuse nesting before the recursive verifier is called; the original must be the first operation attempt.
387
+ const osig = dsseVerify(r.original.envelope, opts.issuerKeys);
388
+ const ost = osig.ok ? osig.payload : null;
389
+ const original = ost?.predicate;
390
+ const eligible = isObject(original) && !("reconciliation" in original);
391
+ let originalOk = false;
392
+ if (eligible && ost) {
393
+ try {
394
+ const nested = ost.predicateType === RECEIPT_PREDICATE_TYPE
395
+ ? verifyBundle(r.original, { ...opts, disclosed: undefined })
396
+ : verifyOriginalAuthorization(r.original, opts);
397
+ originalOk = nested.ok;
398
+ for (const c of nested.checks)
399
+ add(`reconciliation original ${c.name}`, c.ok, c.detail);
400
+ }
401
+ catch {
402
+ add("reconciliation original bundle is well formed", false);
403
+ }
404
+ }
405
+ add("reconciliation original evidence verifies", eligible && originalOk);
406
+ const o = original?.operation;
407
+ const op = p.operation;
408
+ const linked = !!o && !!op && !operationProblem(o) && ["submitted", "pending", "unknown"].includes(o.status) && o.originalReceiptId === original.receiptId && op.originalReceiptId === original.receiptId && p.receiptId !== original.receiptId && (op.id === undefined || o.id === undefined || op.id === o.id) && op.idempotencyKey === o.idempotencyKey && op.lookupDigest === o.lookupDigest && canonicalize(op.budget) === canonicalize(o.budget) && canonicalize(p.principal) === canonicalize(original.principal) && canonicalize(p.agent) === canonicalize(original.agent) && canonicalize(p.tool) === canonicalize(original.tool) && canonicalize(p.delegation) === canonicalize(original.delegation) && p.issuer.keyid === original.issuer.keyid && Date.parse(p.timestamp) >= Date.parse(original.timestamp);
409
+ add("reconciliation links the original operation", linked);
410
+ add("reconciliation lookup matches authorization", !!o && digestOf(r.lookup) === o.lookupDigest);
411
+ const lookupArgs = region(["request", "args"]);
412
+ add("reconciliation lookup args match request", !lookupArgs.problem && (lookupArgs.missing.length > 0 || canonicalize(full.request.args) === canonicalize(r.lookup.args)), lookupArgs.missing.length > 0 ? "request arguments committed under the capture rule" : undefined);
413
+ const before = r.original.inclusion.leafIndex < bundle.inclusion.leafIndex && r.original.inclusion.treeSize <= bundle.inclusion.treeSize;
414
+ const oth = dsseVerify(r.original.treeHead, [...(opts.logKeys ?? []), ...opts.issuerKeys]);
415
+ const cth = dsseVerify(bundle.treeHead, [...(opts.logKeys ?? []), ...opts.issuerKeys]);
416
+ add("reconciliation logged after original", before && oth.ok && cth.ok && isObject(oth.payload) && isObject(cth.payload) && oth.payload.log === cth.payload.log);
417
+ const terminal = op?.status === "confirmed" || op?.status === "failed";
418
+ add("reconciliation records a terminal provider outcome", terminal && p.execution.status === "executed" && p.execution.provenance === "observed");
419
+ const rr = region(["execution", "result"]);
420
+ if (rr.problem)
421
+ add("reconciliation provider status", false, rr.problem);
422
+ else if (rr.missing.some((w) => pathKey(w) !== pathKey(["execution", "result", "_meta"])))
423
+ add("reconciliation provider status", true, "provider result withheld; disclose it or give the capture key to recompute the gateway-observed status");
424
+ else {
425
+ const ex = full.execution;
426
+ const status = providerValue(ex.result, r.lookup.statusPath);
427
+ const mapped = typeof status === "string" ? r.lookup.confirmed.includes(status) ? "confirmed" : r.lookup.failed.includes(status) ? "failed" : null : null;
428
+ const identity = providerValue(ex.result, r.lookup.identityPath);
429
+ add("reconciliation provider status", terminal && mapped === op?.status && identity === op?.idempotencyKey && !(isObject(ex.result) && ex.result.isError === true), "provider read observed by the gateway and bound to its idempotency key; no independent provider signature is implied");
430
+ }
431
+ }
229
432
  const logKeys = opts.logKeys ?? [];
230
433
  if (p.authorization) {
231
434
  // The gateway says it committed this call to the log before forwarding it. Check that the committed statement is
@@ -237,8 +440,32 @@ export function verifyBundle(bundle, opts) {
237
440
  add("authorization signature (issuer key)", asig.ok && typed && asig.keyid === sig.keyid, asig.ok ? (typed ? `keyid ${short(asig.keyid)}` : "not an authorization statement") : asig.error);
238
441
  if (ast && typed) {
239
442
  const ap = ast.predicate;
240
- const same = ap.receiptId === p.receiptId && ap.tool.name === p.tool.name && ap.request.argsDigest === p.request.argsDigest && ap.agent.id === p.agent.id && ap.principal.id === p.principal.id && ap.policy?.decision === "allow";
443
+ const same = ap.receiptId === p.receiptId && ap.tool.name === p.tool.name && ap.request.argsDigest === p.request.argsDigest && ap.agent.id === p.agent.id && ap.principal.id === p.principal.id && (ap.policy?.decision === "allow" || ap.policy?.decision === "deny" && ap.policy.enforced === false);
241
444
  add("authorization names this call", same, same ? `${ap.tool.name} for receipt ${short(ap.receiptId)}` : "committed for a different receipt, tool, arguments, agent, or decision");
445
+ if (ap.approval || p.approval) {
446
+ const stable = (approval) => approval ? { envelope: approval.envelope, requiredApprovers: approval.requiredApprovers, fields: approval.fields } : null;
447
+ const carries = canonicalize(stable(ap.approval)) === canonicalize(stable(p.approval));
448
+ add("authorization carries this approval", carries, "approval envelope, signer requirement, and argument mapping must match the precommit");
449
+ // A refusal needs no human keys, so the precommit's approval is checked for a forwarded call only.
450
+ if (forwarded) {
451
+ const ac = ap.approval;
452
+ // Under a private rule the precommit carries the receipt's commitment to the envelope: it is checked once restored.
453
+ const envelope = ac && isCommitment(ac.envelope) && carries ? full.approval?.envelope : ac?.envelope;
454
+ // an envelope withheld beside arguments in clear is not a private receipt: see "approval signatures (human keys)"
455
+ const sealed = isCommitment(envelope) && args.paths.length > 0;
456
+ const signed = ac && !sealed ? verifyApprovalStatement(envelope, opts.approvalKeys ?? [], ac.requiredApprovers) : null;
457
+ const valid = !!ac && ac.status === "approved" && ac.provenance === "observed" && isApprovalTime(ac.checkedAt) && (sealed || !!signed?.ok) &&
458
+ (!signed?.ok || (Date.parse(ac.checkedAt) >= Date.parse(signed.approval.issuedAt) && Date.parse(ac.checkedAt) < Date.parse(signed.approval.expiresAt))) &&
459
+ Date.parse(ac.checkedAt) >= Date.parse(p.timestamp) && Date.parse(ac.checkedAt) <= Date.parse(p.approval?.checkedAt ?? "") &&
460
+ Array.isArray(ac.approverKeyids) && new Set(ac.approverKeyids).size >= ac.requiredApprovers && (!signed?.ok || ac.approverKeyids.every((id) => signed.approverKeyids.includes(id)));
461
+ add("authorization approval was valid", valid, sealed ? "the envelope is withheld, so only the recorded status, times, and signer count are checked; disclose it or give the capture key to check the signatures" : "the precommit must record an approved statement with trusted signer observations and a check inside its validity window");
462
+ }
463
+ }
464
+ if (p.operation || ap.operation) {
465
+ const o = p.operation;
466
+ const aop = ap.operation;
467
+ add("authorization names this operation", !!o && !!aop && !operationProblem(aop) && aop.status === "submitted" && (aop.id === undefined || o.id === undefined || aop.id === o.id) && aop.idempotencyKey === o.idempotencyKey && aop.lookupDigest === o.lookupDigest && aop.originalReceiptId === o.originalReceiptId && canonicalize(aop.budget) === canonicalize(o.budget));
468
+ }
242
469
  const ath = dsseVerify(a.treeHead, [...logKeys, ...opts.issuerKeys]);
243
470
  add("authorization tree head signature", ath.ok && a.treeHead.payloadType === TREEHEAD_TYPE, ath.ok ? `keyid ${short(ath.keyid)}` : ath.error);
244
471
  if (ath.ok) {
@@ -344,11 +571,16 @@ export function formatReport(r) {
344
571
  }
345
572
  else if (p.execution.status === "withheld")
346
573
  row("authorization", "observed", "the log would not commit it; the call was not forwarded");
574
+ if (p.approval)
575
+ row("approval", p.approval.provenance, `${p.approval.status}; ${p.approval.requiredApprovers} approver(s) required${p.approval.consumedAt ? `; consumed ${p.approval.consumedAt}` : ""}${typeof p.approval.reason === "string" ? `; ${p.approval.reason}` : ""}`);
347
576
  const upstreamCheck = r.checks.find((c) => c.name === "upstream signature (upstream key)" || c.name === "upstream signature (provider secret)");
348
577
  const hasUpstream = (p.execution.status === "executed" || p.execution.status === "failed") && !!p.execution.upstream;
349
578
  const byProvider = hasUpstream && isProviderAttestation(p.execution.upstream);
350
579
  const attestedAs = upstreamCheck?.ok ? (byProvider ? "attested (shared secret)" : "attested") : p.execution.provenance;
351
580
  const note = !hasUpstream ? "" : upstreamCheck ? (upstreamCheck.ok ? ` (${byProvider ? upstreamCheck.detail : `signed by upstream ${upstreamCheck.detail}`})` : " (upstream signature FAILED)") : byProvider ? " (carries a provider delivery; pass the provider secret to check it)" : " (carries an upstream signature; pass --upstream-key to check it)";
352
- row("execution", attestedAs, `${p.execution.status}${note}`);
581
+ // a refusal says why, as the receipt records it; under a capture rule the reason is a commitment, and the report says so rather than printing it
582
+ const reason = "reason" in p.execution ? p.execution.reason : undefined;
583
+ const why = reason === undefined ? "" : typeof reason === "string" ? `: ${reason}` : ": (reason withheld under the capture rule)";
584
+ row("execution", attestedAs, `${p.execution.status}${why}${note}`);
353
585
  return lines.join("\n");
354
586
  }