@agent-custody/receipts 0.6.19 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +20 -11
  2. package/dist/a2a.js +19 -7
  3. package/dist/approval.d.ts +74 -0
  4. package/dist/approval.js +196 -0
  5. package/dist/capture.d.ts +153 -0
  6. package/dist/capture.js +607 -0
  7. package/dist/cli.js +221 -6
  8. package/dist/config.d.ts +144 -0
  9. package/dist/config.js +92 -3
  10. package/dist/crypto.d.ts +2 -2
  11. package/dist/crypto.js +7 -4
  12. package/dist/delegation.d.ts +7 -0
  13. package/dist/delegation.js +15 -1
  14. package/dist/gateway-http.js +13 -1
  15. package/dist/gateway.d.ts +15 -0
  16. package/dist/gateway.js +414 -27
  17. package/dist/index.d.ts +4 -0
  18. package/dist/index.js +4 -0
  19. package/dist/issue.d.ts +20 -5
  20. package/dist/issue.js +76 -8
  21. package/dist/log-sink.d.ts +11 -1
  22. package/dist/log-sink.js +24 -5
  23. package/dist/operations.d.ts +101 -0
  24. package/dist/operations.js +239 -0
  25. package/dist/otel.js +16 -8
  26. package/dist/portal.d.ts +23 -2
  27. package/dist/portal.js +181 -36
  28. package/dist/receipt.d.ts +54 -8
  29. package/dist/rest.js +14 -1
  30. package/dist/retention.d.ts +8 -1
  31. package/dist/retention.js +21 -2
  32. package/dist/sdk/index.js +10 -1
  33. package/dist/simulate.d.ts +58 -0
  34. package/dist/simulate.js +204 -0
  35. package/dist/splunk.js +17 -8
  36. package/dist/upstream.d.ts +9 -7
  37. package/dist/upstream.js +16 -8
  38. package/dist/verify.d.ts +18 -0
  39. package/dist/verify.js +405 -15
  40. package/docs/approvals.md +107 -0
  41. package/docs/compliance.md +1 -1
  42. package/docs/financial-operations.md +99 -0
  43. package/docs/policies.md +22 -0
  44. package/docs/tutorials.md +7 -0
  45. package/docs/usage.md +71 -5
  46. package/docs/verification.md +35 -10
  47. package/package.json +1 -1
  48. package/vectors/audit.json +27 -27
  49. package/vectors/canonical.json +5 -5
  50. package/vectors/receipts.json +3612 -292
package/dist/rest.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { OPERATION_META_KEY } from "./operations.js";
1
2
  const encode = (v) => encodeURIComponent(typeof v === "string" ? v : JSON.stringify(v));
2
3
  /** Builds the request for one tool call: path parameters substituted, the rest of the arguments as query or body. */
3
4
  export function buildRequest(base, tool, args) {
@@ -42,7 +43,19 @@ export function restUpstream(name, cfg, opts = {}) {
42
43
  if (!tool)
43
44
  throw new Error(`upstream ${name} has no tool "${params.name}"`);
44
45
  const { url, method, body } = buildRequest(cfg.baseUrl, tool, params.arguments ?? {});
45
- const res = await f(url, { method, headers: { accept: "application/json", ...(body !== null ? { "content-type": "application/json" } : {}), ...headers }, ...(body !== null ? { body } : {}), signal: AbortSignal.timeout(cfg.timeoutMs) });
46
+ const requestHeaders = new Headers({ accept: "application/json", ...(body !== null ? { "content-type": "application/json" } : {}), ...headers });
47
+ if (tool.idempotencyHeader) {
48
+ const operation = params._meta?.[OPERATION_META_KEY];
49
+ if (!operation || typeof operation !== "object" || !Object.hasOwn(operation, "id") || !Object.hasOwn(operation, "idempotencyKey"))
50
+ throw new Error(`tool ${tool.name}: durable operation metadata is required`);
51
+ const { id, idempotencyKey } = operation;
52
+ if (typeof id !== "string" || !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id) || typeof idempotencyKey !== "string" || !/^[0-9a-f]{64}$/.test(idempotencyKey))
53
+ throw new Error(`tool ${tool.name}: malformed durable operation metadata`);
54
+ // Set after static/environment headers, case-insensitively, so a configured header cannot replace
55
+ // the durable key. The metadata itself never enters the provider's body or query arguments.
56
+ requestHeaders.set(tool.idempotencyHeader, idempotencyKey);
57
+ }
58
+ const res = await f(url, { method, headers: requestHeaders, ...(body !== null ? { body } : {}), signal: AbortSignal.timeout(cfg.timeoutMs) });
46
59
  const text = await res.text();
47
60
  // The result is what the API returned, as text. JSON stays JSON so policy facts and consumers can read it.
48
61
  return { content: [{ type: "text", text: text.length ? text : JSON.stringify({ status: res.status }) }], ...(res.ok ? {} : { isError: true }) };
@@ -1,3 +1,9 @@
1
+ /** where the issuer keeps the salts behind a receipt's commitments, under the receipts directory; private, pruned with the receipt */
2
+ export declare const SALTS_DIR = "salts";
3
+ /** a receipt id as the issuer mints it; anything else never becomes part of a path */
4
+ export declare const RECEIPT_ID: RegExp;
5
+ /** the salts file of a receipt, or a throw when the id (which may come from a bundle or a log line) is not one */
6
+ export declare function saltsFileFor(receiptsDir: string, receiptId: string): string;
1
7
  export interface PruneResult {
2
8
  pruned: {
3
9
  leafIndex: number;
@@ -9,6 +15,7 @@ export interface PruneResult {
9
15
  }
10
16
  /**
11
17
  * Prunes every leaf whose receipt timestamp is before the cutoff. Leaves already pruned, and leaves that are not
12
- * receipts, are left as they are. Rewrites the log file in place and deletes the pruned receipts' bundle files.
18
+ * receipts, are left as they are. Rewrites the log file in place and deletes the pruned receipts' bundle files, and
19
+ * the salts the issuer kept for them.
13
20
  */
14
21
  export declare function pruneLog(logFile: string, before: string, receiptsDir?: string): PruneResult;
package/dist/retention.js CHANGED
@@ -6,6 +6,16 @@
6
6
  import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
8
  import { leafHash } from "./log.js";
9
+ /** where the issuer keeps the salts behind a receipt's commitments, under the receipts directory; private, pruned with the receipt */
10
+ export const SALTS_DIR = "salts";
11
+ /** a receipt id as the issuer mints it; anything else never becomes part of a path */
12
+ export const RECEIPT_ID = /^[A-Za-z0-9-]{1,64}$/;
13
+ /** the salts file of a receipt, or a throw when the id (which may come from a bundle or a log line) is not one */
14
+ export function saltsFileFor(receiptsDir, receiptId) {
15
+ if (!RECEIPT_ID.test(receiptId))
16
+ throw new Error(`receipt id ${JSON.stringify(receiptId)} is not a valid id`);
17
+ return join(receiptsDir, SALTS_DIR, `${receiptId}.json`);
18
+ }
9
19
  function receiptOf(leaf) {
10
20
  try {
11
21
  const env = JSON.parse(leaf);
@@ -18,7 +28,8 @@ function receiptOf(leaf) {
18
28
  }
19
29
  /**
20
30
  * Prunes every leaf whose receipt timestamp is before the cutoff. Leaves already pruned, and leaves that are not
21
- * receipts, are left as they are. Rewrites the log file in place and deletes the pruned receipts' bundle files.
31
+ * receipts, are left as they are. Rewrites the log file in place and deletes the pruned receipts' bundle files, and
32
+ * the salts the issuer kept for them.
22
33
  */
23
34
  export function pruneLog(logFile, before, receiptsDir) {
24
35
  const lines = readFileSync(logFile, "utf8").split("\n").filter((l) => l.trim());
@@ -34,12 +45,20 @@ export function pruneLog(logFile, before, receiptsDir) {
34
45
  if (timestamp !== null && timestamp < before) {
35
46
  out.push(JSON.stringify({ pruned: leafHash(parsed).toString("hex") }));
36
47
  result.pruned.push({ leafIndex: i, receiptId, timestamp });
37
- if (receiptsDir && receiptId) {
48
+ // the id comes from a log line: it never becomes part of a path unless it is one the issuer could have minted
49
+ if (receiptsDir && receiptId && RECEIPT_ID.test(receiptId)) {
38
50
  const bundle = join(receiptsDir, `${receiptId}.json`);
39
51
  if (existsSync(bundle)) {
40
52
  unlinkSync(bundle);
41
53
  result.bundlesRemoved++;
42
54
  }
55
+ const salts = saltsFileFor(receiptsDir, receiptId);
56
+ if (existsSync(salts))
57
+ unlinkSync(salts);
58
+ // the authorization committed before the call carries the same call: it goes too
59
+ const authorization = join(receiptsDir, `${receiptId}.authorization.json`);
60
+ if (existsSync(authorization))
61
+ unlinkSync(authorization);
43
62
  }
44
63
  }
45
64
  else {
package/dist/sdk/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // The interceptor SDK: issues receipts from inside the agent's own process.
2
2
  // Everything it records is "claimed", because the issuer shares a process with the agent. The receipt says so.
3
3
  import { randomUUID } from "node:crypto";
4
+ import { captureKeyFrom } from "../capture.js";
4
5
  import { readFileSync } from "node:fs";
5
6
  import { digestOf, loadPrivateKey } from "../crypto.js";
6
7
  import { createIssuer } from "../issue.js";
@@ -26,7 +27,14 @@ export class PolicyDeniedError extends Error {
26
27
  }
27
28
  export function createSdkIssuer(cfg) {
28
29
  const key = loadPrivateKey(cfg.identity.keyFile);
29
- const issuer = createIssuer(key, cfg.receiptsDir, openLog(cfg, key), { exporter: openExporter(cfg) });
30
+ const captureKey = cfg.captureKeyEnv ? captureKeyFrom(process.env[cfg.captureKeyEnv] ?? (() => { throw new Error(`capture key: environment variable ${cfg.captureKeyEnv} is not set`); })()) : undefined;
31
+ for (const [tool, rule] of Object.entries(cfg.capture ?? {})) {
32
+ for (const side of [rule.args, rule.result, rule.facts])
33
+ if (side?.mode === "encrypted" && !captureKey)
34
+ throw new Error(`capture for ${tool} uses mode encrypted, which needs captureKeyEnv`);
35
+ }
36
+ // the capture rules are applied by the issuer to every statement it signs, so every adapter's receipt gets them
37
+ const issuer = createIssuer(key, cfg.receiptsDir, openLog(cfg, key), { exporter: openExporter(cfg), capture: { rules: cfg.capture, key: captureKey } });
30
38
  const policyText = cfg.policyFile ? readFileSync(cfg.policyFile, "utf8") : null;
31
39
  const decide = (ev) => {
32
40
  if (policyText === null)
@@ -35,6 +43,7 @@ export function createSdkIssuer(cfg) {
35
43
  return cfg.mode === "observe" ? { ...d, enforced: false } : d;
36
44
  };
37
45
  function record(ev, outcome, policy = null) {
46
+ // the call in full; the issuer withholds what the tool's capture rule says, the thrown message included
38
47
  const execution = outcome.status === "denied"
39
48
  ? { status: "denied", reason: outcome.reason, provenance: "claimed" }
40
49
  : outcome.status === "error"
@@ -0,0 +1,58 @@
1
+ import { type PublicKeyRef } from "./crypto.ts";
2
+ import { type PolicyDecision } from "./policy.ts";
3
+ import { type AuthorizationBundle, type AuthorizationStatement, type ReceiptPredicate } from "./receipt.ts";
4
+ export interface SimulationChange {
5
+ receiptId: string;
6
+ tool: string;
7
+ /** The recorded Cedar decision, including observe-mode and provenance information. */
8
+ previous: NonNullable<ReceiptPredicate["policy"]>;
9
+ proposed: PolicyDecision;
10
+ }
11
+ export interface SimulationSkip {
12
+ receiptId: string;
13
+ tool: string;
14
+ reason: string;
15
+ }
16
+ export interface SimulationGroup {
17
+ tool: string;
18
+ /** The proposed policy's determining policy ids and evaluation errors. */
19
+ reason: string;
20
+ receiptIds: string[];
21
+ }
22
+ export interface SimulationReport {
23
+ runId: string;
24
+ timestamp: string;
25
+ policyDigest: string;
26
+ previousPolicyDigests: string[];
27
+ total: number;
28
+ evaluated: number;
29
+ unchanged: number;
30
+ complete: boolean;
31
+ changes: SimulationChange[];
32
+ skipped: SimulationSkip[];
33
+ /** Changed decisions, grouped by tool and the proposed reason. */
34
+ groups: SimulationGroup[];
35
+ }
36
+ export interface SimulationOptions {
37
+ /** The customer's capture key. It decrypts the withheld values that were encrypted under it. */
38
+ captureKey?: Buffer;
39
+ /** Disclosure files by receipt id, as `agent-custody reveal` writes them. A disclosure applies only to its own receipt. */
40
+ disclosures?: ReadonlyMap<string, unknown>;
41
+ /** Calls that have no receipt to replay. Each counts in `total` and is reported as skipped. */
42
+ unreplayable?: SimulationSkip[];
43
+ }
44
+ /**
45
+ * Check an authorization bundle that has no receipt, as the verifier does for an embedded one: the issuer signed it, it
46
+ * is an authorization statement, and its leaf is in the log under a signed tree head. Throws when a check fails.
47
+ * Returns the statement's predicate.
48
+ */
49
+ export declare function verifyOrphanAuthorization(bundle: AuthorizationBundle, issuerKeys: PublicKeyRef[], logKeys: PublicKeyRef[]): AuthorizationStatement["predicate"];
50
+ /**
51
+ * Compare a proposed Cedar policy with recorded policy decisions, using each receipt's original arguments, fact
52
+ * values, agent, and (for gateways) grant context. Observe-mode decisions are the baseline even when the call ran.
53
+ * Receipts are not signature-verified here; verify their bundles separately when their authenticity matters.
54
+ * Missing inputs and non-Cedar gate failures are reported as skipped, never guessed or fetched again.
55
+ * The receipts are read once, one at a time, so a caller can verify and parse a large history lazily.
56
+ */
57
+ export declare function simulatePolicy(policyText: string, receipts: Iterable<ReceiptPredicate>, options?: SimulationOptions): SimulationReport;
58
+ export declare function formatSimulation(report: SimulationReport): string;
@@ -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
@@ -2,6 +2,11 @@
2
2
  export function hecEvent(p, bundle, cfg) {
3
3
  const auth = p.authorization;
4
4
  const exec = p.execution;
5
+ // under a capture rule a message is a commitment; the event says so rather than carrying it
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;
5
10
  return {
6
11
  time: Date.parse(p.timestamp) / 1000,
7
12
  source: cfg.source ?? "agent-custody",
@@ -17,18 +22,22 @@ export function hecEvent(p, bundle, cfg) {
17
22
  agent: p.agent.id,
18
23
  agent_provenance: p.agent.provenance,
19
24
  principal: p.principal.id,
20
- status: exec.status,
21
- reason: exec.reason ?? exec.error ?? null,
22
- policy_decision: p.policy?.decision ?? null,
23
- policy_digest: p.policy?.policyDigest ?? null,
24
- policy_reasons: p.policy?.reasons ?? [],
25
+ status: reconciliation ? "reconciled" : exec.status,
26
+ reason: text(exec.reason) ?? text(exec.error) ?? null,
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,
25
34
  args_digest: p.request.argsDigest,
26
35
  log_leaf_index: bundle.inclusion.leafIndex,
27
36
  log_tree_size: bundle.inclusion.treeSize,
28
37
  authorization_leaf_index: auth ? auth.inclusion.leafIndex : null,
29
- consumed_count: p.consumed?.factIds.length ?? 0,
30
- model: p.model.id,
31
- session: p.session.id,
38
+ consumed_count: (Array.isArray(p.consumed?.factIds) ? p.consumed.factIds.length : 0) ?? 0,
39
+ model: text(p.model.id) ?? null,
40
+ session: text(p.session.id) ?? null,
32
41
  },
33
42
  };
34
43
  }
@@ -1,5 +1,6 @@
1
1
  import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
2
2
  import { type Envelope, type KeyPair, type PublicKeyRef } from "./crypto.ts";
3
+ import { type Commitment } from "./capture.ts";
3
4
  export declare const UPSTREAM_SIG_META_KEY = "agent-custody/upstream-signature";
4
5
  export declare const UPSTREAM_TYPE = "application/vnd.agent-custody.upstream+json";
5
6
  export interface UpstreamAttestation {
@@ -27,17 +28,18 @@ export type UpstreamCheck = {
27
28
  export declare function checkUpstream(envelope: Envelope, keys: PublicKeyRef[], expected: UpstreamAttestation): UpstreamCheck;
28
29
  export interface ProviderAttestation {
29
30
  provider: "stripe-webhook" | "github-delivery";
30
- /** the delivery body exactly as received; the HMAC is over these bytes */
31
- rawBody: string;
32
- /** Stripe: the Stripe-Signature header; GitHub: the X-Hub-Signature-256 header */
33
- signature: string;
34
- /** dot path into the parsed body whose value must appear in the receipt's result, e.g. data.object.id */
35
- bind: string;
31
+ /** the delivery body exactly as received; the HMAC is over these bytes. Under a private capture rule the receipt carries a commitment here instead, and the body is disclosed or revealed to check the delivery (capture.ts) */
32
+ rawBody: string | Commitment;
33
+ /** Stripe: the Stripe-Signature header; GitHub: the X-Hub-Signature-256 header. A MAC over the body: withheld with it under a private rule */
34
+ signature: string | Commitment;
35
+ /** dot path into the parsed body whose value must appear in the receipt's result, e.g. data.object.id; upstream-chosen, withheld with the body under a private rule */
36
+ bind: string | Commitment;
36
37
  /** GitHub: the X-GitHub-Delivery id, for the record */
37
38
  deliveryId?: string;
38
39
  }
40
+ /** under a private result rule the envelope, or the delivery body, is a commitment in the receipt, restored by the verifier with the result */
39
41
  export type UpstreamEvidence = {
40
- envelope: Envelope;
42
+ envelope: Envelope | Commitment;
41
43
  } | ProviderAttestation;
42
44
  export declare function isProviderAttestation(v: unknown): v is ProviderAttestation;
43
45
  /** For upstreams wrapping a provider: attaches the provider's own delivery for this call. */
package/dist/upstream.js CHANGED
@@ -4,6 +4,7 @@
4
4
  // upstream's key checks it. Provider-native formats, such as Stripe's webhook signatures, are adapters on top of this.
5
5
  import { createHmac, timingSafeEqual } from "node:crypto";
6
6
  import { digestOf, dsseSign, dsseVerify } from "./crypto.js";
7
+ import { isCommitment } from "./capture.js";
7
8
  export const UPSTREAM_SIG_META_KEY = "agent-custody/upstream-signature";
8
9
  export const UPSTREAM_TYPE = "application/vnd.agent-custody.upstream+json";
9
10
  export function contentDigest(result) {
@@ -37,7 +38,8 @@ export function checkUpstream(envelope, keys, expected) {
37
38
  }
38
39
  export function isProviderAttestation(v) {
39
40
  const p = v;
40
- return !!p && (p.provider === "stripe-webhook" || p.provider === "github-delivery") && typeof p.rawBody === "string" && typeof p.signature === "string" && typeof p.bind === "string";
41
+ const stringOrCommitment = (v) => typeof v === "string" || isCommitment(v);
42
+ return !!p && (p.provider === "stripe-webhook" || p.provider === "github-delivery") && stringOrCommitment(p.rawBody) && stringOrCommitment(p.signature) && stringOrCommitment(p.bind);
41
43
  }
42
44
  /** For upstreams wrapping a provider: attaches the provider's own delivery for this call. */
43
45
  export function attachProviderAttestation(result, attestation) {
@@ -54,13 +56,17 @@ export function upstreamEvidenceOf(result) {
54
56
  const pathValue = (body, path) => path.split(".").reduce((v, k) => (v && typeof v === "object" ? v[k] : undefined), body);
55
57
  /** Stripe: header `t=<unix>,v1=<hex>`, HMAC-SHA256 over `<t>.<rawBody>`; GitHub: header `sha256=<hex>` over rawBody. */
56
58
  export function checkProvider(att, secrets, ctx) {
59
+ if (typeof att.rawBody !== "string" || typeof att.signature !== "string" || typeof att.bind !== "string")
60
+ return { ok: false, error: "the delivery body, signature, or bind is withheld; disclose them or give the capture key" };
61
+ const signature = att.signature;
62
+ const bind = att.bind;
57
63
  const secret = att.provider === "stripe-webhook" ? secrets.stripe : secrets.github;
58
64
  if (!secret)
59
65
  return { ok: false, error: `no ${att.provider === "stripe-webhook" ? "Stripe" : "GitHub"} secret given` };
60
66
  const hmac = (data) => createHmac("sha256", secret).update(data).digest("hex");
61
67
  const equal = (a, b) => a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
62
68
  if (att.provider === "stripe-webhook") {
63
- const parts = Object.fromEntries(att.signature.split(",").map((kv) => kv.split("=")));
69
+ const parts = Object.fromEntries(signature.split(",").map((kv) => kv.split("=")));
64
70
  const t = parts.t;
65
71
  const v1 = parts.v1;
66
72
  if (!t || !v1)
@@ -72,7 +78,7 @@ export function checkProvider(att, secrets, ctx) {
72
78
  return { ok: false, error: `Stripe timestamp is ${Math.round(skew)}s from the receipt, beyond tolerance` };
73
79
  }
74
80
  else {
75
- const hex = att.signature.startsWith("sha256=") ? att.signature.slice(7) : "";
81
+ const hex = signature.startsWith("sha256=") ? signature.slice(7) : "";
76
82
  if (!hex || !equal(hmac(att.rawBody), hex))
77
83
  return { ok: false, error: "GitHub signature does not verify with this secret" };
78
84
  }
@@ -83,12 +89,14 @@ export function checkProvider(att, secrets, ctx) {
83
89
  catch {
84
90
  return { ok: false, error: "delivery body is not JSON" };
85
91
  }
86
- const bound = pathValue(body, att.bind);
92
+ const bound = pathValue(body, bind);
87
93
  if (bound === undefined || bound === null || bound === "")
88
- return { ok: false, error: `delivery has no value at ${att.bind}` };
89
- if (!JSON.stringify(ctx.result).includes(JSON.stringify(bound).replace(/^"|"$/g, "")))
90
- return { ok: false, error: `delivery's ${att.bind} (${String(bound)}) does not appear in the receipt's result` };
91
- return { ok: true, keyid: `shared secret (${att.provider}, bound on ${att.bind})` };
94
+ return { ok: false, error: `delivery has no value at ${bind}` };
95
+ // what the agent received: the content and the flag, never _meta, which carries the delivery itself and so always contains the bound value
96
+ const received = ctx.result;
97
+ if (!JSON.stringify({ content: received.content, isError: received.isError, structuredContent: received.structuredContent }).includes(JSON.stringify(bound).replace(/^"|"$/g, "")))
98
+ return { ok: false, error: `delivery's ${bind} (${String(bound)}) does not appear in the receipt's result` };
99
+ return { ok: true, keyid: `shared secret (${att.provider}, bound on ${bind})` };
92
100
  }
93
101
  /** For fake providers and tests: a Stripe-Signature header for a body at a time. */
94
102
  export function stripeSignature(rawBody, secret, unixSeconds) {
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 */
@@ -20,12 +22,28 @@ export interface VerifyOptions {
20
22
  logFile?: string;
21
23
  /** If given, every tree head in the bundle must name this log, so a head from another tenant's log cannot be presented as this one's. */
22
24
  logId?: string;
25
+ /**
26
+ * The withheld values, as `agent-custody reveal` writes them or the party that holds them hands them over: a partial
27
+ * predicate with `{ $custody: "disclosed", salt, value }` at each withheld path (`{ receiptId, request: { args: { reason: {...} } }, execution: { result: { content: {...} }, error, upstream: { rawBody } }, policy: { errors }, facts: { <name>: { value, args } } }`).
28
+ * The digests are then recomputed and every disclosed value checked against its commitment under its salt.
29
+ */
30
+ disclosed?: Record<string, unknown> & {
31
+ receiptId?: string;
32
+ };
33
+ /** the customer's capture key: encrypted fields are revealed and the digests recomputed */
34
+ captureKey?: Buffer;
23
35
  }
24
36
  export interface VerifyResult {
25
37
  ok: boolean;
26
38
  checks: Check[];
27
39
  statement: ReceiptStatement | null;
28
40
  }
41
+ /**
42
+ * Why a statement cannot be verified at all, or null: the capture note is malformed, names a structural part, or a
43
+ * structural part is not what every check assumes it to be. Checked once, before anything reads the statement, so that
44
+ * a crafted note cannot hide the status, the tool, the decision, or the digests behind a commitment and still verify.
45
+ */
46
+ export declare function structuralProblem(p: unknown): string | null;
29
47
  export declare function verifyBundle(bundle: ReceiptBundle, opts: VerifyOptions): VerifyResult;
30
48
  export interface AuditResult {
31
49
  ok: boolean;