@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.
package/README.md CHANGED
@@ -4,16 +4,18 @@ Chain of custody for AI agents: a signed receipt for every tool call, checkable
4
4
 
5
5
  Two producers, one receipt format, one verifier.
6
6
 
7
- - **The gateway** is an MCP proxy between an agent and the systems it can affect: MCP servers, REST APIs described as tools, and other agents it delegates to over A2A. For every tool call, allowed or denied, it checks a delegation grant signed by the human principal, gathers the facts the policy needs by calling upstream itself, evaluates a Cedar policy that fails closed, forwards the call only on allow, and emits a signed receipt appended to a Merkle transparency log.
7
+ - **The gateway** is an MCP proxy between an agent and the systems it can affect: MCP servers, REST APIs described as tools, and other agents it delegates to over A2A. For every tool call, allowed or denied, it checks a delegation grant signed by the human principal and any required human approval of the exact arguments, gathers the facts the policy needs by calling upstream itself, evaluates a Cedar policy that fails closed, forwards the call only on allow, and emits a signed receipt appended to a Merkle transparency log.
8
8
  - **The SDK** is an interceptor inside the agent's own process, hooked into the framework's tool-call callbacks: Claude Code, the Claude Agent SDK, the OpenAI Agents SDK, the Vercel AI SDK, OpenClaw, DeepSeek Harness, Hermes, Google ADK, LangChain, or any function you wrap. It reaches everything the gateway cannot see and issues the same receipts, labelled as self-reported.
9
9
 
10
10
  Anyone holding the public keys can verify a receipt offline. The agent is not trusted. The layer around it is, and the receipt says exactly how far that trust extends, starting with who issued it. What the receipt file carries of a call is a choice per tool: a field can be withheld as a commitment or encrypted under your key, and the verifier recomputes the digests when it is shown the values.
11
11
 
12
12
  - [Reference](https://docs.agent-custody.dev/reference/): every function, endpoint, MCP tool, and command with its request and response
13
- - [Tutorials](docs/tutorials.md): twenty-seven runnable examples, one per aspect of the code, all executed by the test suite
13
+ - [Tutorials](docs/tutorials.md): thirty runnable examples, one per aspect of the code, all executed by the test suite
14
+ - [Financial operations](docs/financial-operations.md): durable operation ids, provider idempotency keys, atomic daily budget reservations, and reconciliation receipts for uncertain outcomes
14
15
  - [Usage guide](docs/usage.md): gateway setup, wiring into Claude Desktop, Claude Code, or your own agent loop, and the gateway as an A2A agent between agents that delegate to each other, and private evidence: what the receipt file carries of each call
16
+ - [Human approvals](docs/approvals.md): short-lived signatures over the exact action, two-person thresholds, single-use enforcement, and offline verification
15
17
  - [The interceptor SDK](docs/sdk.md): Claude Code hooks, the Claude Agent SDK, adapters for the OpenAI Agents SDK, Vercel AI SDK, LangChain, OpenClaw and DeepSeek Harness, a Hermes Agent plugin and Google ADK callbacks through the Python package, and wrapping tool functions in anything else
16
- - [Writing policies](docs/policies.md): how a tool call becomes a Cedar request, with tested examples
18
+ - [Writing policies](docs/policies.md): how a tool call becomes a Cedar request, with tested examples, and replaying history against a proposed policy with `policy simulate`
17
19
  - [Verifying a receipt](docs/verification.md): what each check means and what a verified receipt does and does not prove
18
20
  - [What the evidence satisfies](docs/compliance.md): the receipts, packs, and certificates mapped to SOC 2, ISO 27001, the EU AI Act, and UK GDPR, with what none of them claims
19
21
  - [Threat model](docs/threat-model.md): every party who could make a receipt false, the move, what stops it, and whether that is a property of the evidence or of the deployment; and what is not defended
@@ -181,7 +183,7 @@ Every field carries a provenance label. This is the design decision that matters
181
183
  bun install # from the repository root, once for the workspace
182
184
  cd packages/receipts
183
185
  node scripts/demo.ts # gateway: keys, grant, policy, four tool calls, verification, a tampering attempt; then the SDK wrapping the same tool
184
- node examples/01-keys-and-signing.ts # first of twenty-seven step-by-step examples, see docs/tutorials.md
186
+ node examples/01-keys-and-signing.ts # first of thirty step-by-step examples, see docs/tutorials.md
185
187
  bun run test # this package; `bun run test` at the root runs every package
186
188
  ```
187
189
 
@@ -242,10 +244,13 @@ src/checkpoints.ts signed heads published on a schedule, to files and to Postgre
242
244
  src/log-store.ts the log server's backends: the file, and Postgres with tenants, hashed tokens, one writer per tenant, rate limits
243
245
  src/log-sink.ts where leaves go: the local file, or a remote log over HTTP; plus the reference log server
244
246
  src/policy.ts Cedar evaluation wrapper, fail-closed
247
+ src/simulate.ts replay recorded policy decisions against a proposed Cedar policy, grouped changes and run digest
245
248
  src/delegation.ts signed delegation grants
249
+ src/approval.ts exact-action human approvals, distinct trusted signatures, persistent single-use consumption
246
250
  src/receipt.ts receipt and authorization statement types and provenance labels
247
251
  src/issue.ts sign, log, and write a receipt, or commit an authorization first; shared by both producers
248
252
  src/gateway.ts the MCP proxy: a host (key, policy, upstreams, log) and a session per grant; scope check, facts, policy, forward, receipt
253
+ src/operations.ts SQLite operation claims and daily budget reservations, retained across retries and process crashes
249
254
  src/gateway-http.ts the gateway over Streamable HTTP: one process, a session per connection, each under the grant it presents
250
255
  src/sdk/index.ts the interceptor: policy decision, record, wrap(tool fn)
251
256
  src/sdk/claude.ts Claude Code command hook and Claude Agent SDK in-process hooks
@@ -259,15 +264,15 @@ src/upstream.ts attested execution: an upstream signs its result for the rece
259
264
  src/capture.ts private evidence: per-tool capture rules applied by the issuer to the whole statement, withheld values as salted commitments or encrypted under the customer's key, restore and reveal
260
265
  vectors/ conformance vectors: receipts, keys, logs, proofs, and expected verdicts; `bun run vectors` regenerates them
261
266
  src/verify.ts offline verification, the human-readable report, and the audit that a later log extends an earlier one
262
- src/cli.ts keygen, grant, gateway, hook, serve, log, prune, verify, reveal, audit
267
+ src/cli.ts keygen, grant, gateway, hook, serve, log, prune, verify, reveal, audit, policy simulate
263
268
  src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
264
269
  src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
265
270
  tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
266
- scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, fixture builders for gateway and SDK, demo
267
- examples/ twenty-seven runnable tutorials, plus examples/languages/: Python, Go, Java, and Rust clients of the sidecar, run by the test suite, one per aspect; each is run by the test suite
271
+ scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, fixture builders for gateway and SDK, the replay builder (`replay.ts`: example 27 and state example 07 as a folder of receipts and public keys anyone can verify with the published packages), demo
272
+ examples/ thirty runnable tutorials, plus examples/languages/: Python, Go, Java, and Rust clients of the sidecar, run by the test suite, one per aspect; each is run by the test suite
268
273
  test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
269
274
  adapter tests against the real packages, and a test that runs every policy in docs/policies.md
270
- docs/ tutorials, usage (gateway), sdk, policies, verification
275
+ docs/ tutorials, usage (gateway), approvals, sdk, policies, verification
271
276
  ```
272
277
 
273
278
  ## Plan
@@ -276,6 +281,7 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
276
281
 
277
282
  **Done**
278
283
 
284
+ - Payload-bound human approvals: short-lived signatures over the principal, agent, tool, full arguments, amount, currency, and beneficiary; configurable one- or two-key thresholds, enforced even in observe mode, a configurable lifetime cap, persistent atomic single-use consumption before forwarding, and independent approval-key verification. [Guide](docs/approvals.md), tutorial 30.
279
285
  - Gateway: MCP proxy, signed delegation, gateway-fetched facts, Cedar policy, denial receipts, Merkle log, offline verifier.
280
286
  - Receipt schema carries the issuer kind, so a verifier reads gateway versus SDK before anything else.
281
287
  - SDK core: policy decision, record, and a generic `wrap(tool, fn)` for any framework whose tools are functions.
@@ -304,7 +310,7 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
304
310
  - The signer, keys, and checkpoints: the key in its own process (`signer`, `--signer-url`), the key document at `/.well-known/agent-custody-log.json` fetched and pinned by `verify --log-url` and `audit --log-url`, and signed checkpoints per log published to a directory and a table for a verifier who was not watching. Phase 3 of [issue #6](https://github.com/svayatta/agent-custody/issues/6).
305
311
  - The log over Postgres: `log --db-env`, leaves as hashes in one table keyed by tenant, one writer per tenant by advisory lock, tenants and hashed tokens in tables managed by `log-admin`, rate limits and a body cap, retries in the sink, and `import` for an existing file log. Phase 2 of [issue #6](https://github.com/svayatta/agent-custody/issues/6).
306
312
  - A log for someone else: `hashOnly` sends leaf hashes so the log never holds a receipt; the reference server runs several tenant logs at `/t/<tenant>/` with their own tokens and ids; tree heads name their log and the verifier checks it with `--log-id`. Phase 1 of the hosted log, [issue #6](https://github.com/svayatta/agent-custody/issues/6).
307
- - OpenTelemetry export: with `otel` in either config, every receipt is also one span at the collector the team already runs, trace id equal to the receipt id, attributes for tool, agent, principal, status, decision, and log position; after the receipt, best effort, never on the evidence path.
313
+ - OpenTelemetry export: with `otel` in either config, every receipt is also one span at the collector the team already runs, trace id equal to the receipt id, attributes for tool, agent, principal, status, decision, and log position; after the receipt, best effort, never on the evidence path. A reconciliation receipt is marked and carries no policy decision, so a dashboard never counts it as a second allowed call.
308
314
  - Delegation chains for sub-agents: a grant that names the agent's key lets it delegate a narrower grant, with the parent embedded, up to three deep; the verifier and the gateway walk the chain to the principal, refusing any link that escalates scope, widens the window, changes the principal, or is signed by the wrong key; the receipt names the sub-agent and the principal and carries the chain. Pinned by the `gateway-chain-*` vectors and mirrored in the browser verifier.
309
315
  - One gateway for many agents: `gateway --http` serves the gateway over Streamable HTTP, one session per connection under the grant that connection presents, sessions sharing the upstreams and the policy and nothing else; a platform team runs one gateway in front of the tools instead of one process per agent.
310
316
  - Splunk export: with `splunk` in either config, every receipt is also one event at the HTTP Event Collector, with the receipt id, tool, agent, principal, status, decision, and log position as searchable fields and the token from the environment; the same best-effort rule.
@@ -312,7 +318,7 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
312
318
  - Pre-commit authorization for consequential tools: named in `precommit`, a call is signed and logged before it is forwarded, withheld if the log will not take it, and its receipt carries the committed authorization with proof that it precedes the execution.
313
319
  - The grant on every call (issue #97): expiry and revocation are checked on every call and again before the forward, in every mode, on the MCP, HTTP, and A2A fronts; `agent-custody revoke` revokes a grant and every grant delegated from it. The remote log's answer is verified against pinned keys before a pre-committed call goes upstream (issue #99). The portal verifies an address only from the account's own session before a provider sign-in can link to it (issue #103). The verifier recomputes the execution result digest (issue #104). The Stripe webhook ignores a repeated or out-of-order event (issue #105).
314
320
  - Agent-to-agent delegation under custody: the A2A upstream and the gateway's A2A front; receipts per delegation with the delegate's card as a fact. A Google ADK `RemoteA2aAgent`, or any A2A client, is pointed at the gateway and a refused delegation comes back as a rejected task the delegate never saw. The delegate does not yet countersign its answer; the receipt attests what the gateway sent and observed, not what the delegate did with it.
315
- - Private evidence: per-tool capture rules, applied by the issuer to the whole statement so nothing outside a fixed structural list is in clear under a private rule; withheld values as salted commitments whose salts never enter the receipt, encrypted under the customer's key, revealed and recomputed by the verifier; nothing in the receipt confirms a guess of a withheld value.
321
+ - Private evidence: per-tool capture rules, applied by the issuer to the whole statement so nothing outside a fixed structural list is in clear under a private rule; withheld values as salted commitments whose salts never enter the receipt, encrypted under the customer's key, revealed and recomputed by the verifier; the commitments do not confirm a guess of a withheld value. A human approval envelope carries the action fields and an unsalted argument digest, so a private rule withholds it as a commitment; the [privacy limits](docs/approvals.md#privacy-limits) apply.
316
322
 
317
323
  **Next, in the order it pays off**
318
324
 
@@ -0,0 +1,74 @@
1
+ import { z } from "zod";
2
+ import { type Envelope, type KeyPair, type PublicKeyRef } from "./crypto.ts";
3
+ export declare const APPROVAL_TYPE = "application/vnd.agent-custody.approval+json";
4
+ export declare const APPROVAL_META_KEY = "agent-custody/approval";
5
+ /** The longest approval lifetime that the gateway accepts when `approvals.maxLifetimeSeconds` is not set. */
6
+ export declare const DEFAULT_APPROVAL_LIFETIME_SECONDS = 3600;
7
+ /** An ISO time with an offset: the only form that the approval and the receipt's approval record accept. Both verifiers use this rule. */
8
+ export declare const isApprovalTime: (value: unknown) => value is string;
9
+ export declare const ApprovalSchema: z.ZodObject<{
10
+ version: z.ZodLiteral<"0.1">;
11
+ approvalId: z.ZodUUID;
12
+ principal: z.ZodString;
13
+ agent: z.ZodString;
14
+ tool: z.ZodString;
15
+ argsDigest: z.ZodString;
16
+ amount: z.ZodOptional<z.ZodNumber>;
17
+ currency: z.ZodOptional<z.ZodString>;
18
+ beneficiary: z.ZodOptional<z.ZodString>;
19
+ issuedAt: z.ZodISODateTime;
20
+ expiresAt: z.ZodISODateTime;
21
+ }, z.core.$strict>;
22
+ export type Approval = z.infer<typeof ApprovalSchema>;
23
+ export interface ApprovalBinding {
24
+ principal: string;
25
+ agent: string;
26
+ tool: string;
27
+ args: Record<string, unknown>;
28
+ /** Argument names for the action fields; each defaults to its own name. */
29
+ fields?: {
30
+ amount?: string;
31
+ currency?: string;
32
+ beneficiary?: string;
33
+ };
34
+ }
35
+ /** The gateway's observation of its approval check, embedded in the authorization and the receipt. */
36
+ export interface ApprovalRecord {
37
+ envelope?: Envelope;
38
+ /** Effective argument names used for the action fields. */
39
+ fields?: ApprovalBinding["fields"];
40
+ requiredApprovers: 1 | 2;
41
+ checkedAt: string;
42
+ status: "approved" | "denied";
43
+ reason?: string;
44
+ approverKeyids: string[];
45
+ consumedAt?: string;
46
+ provenance: "observed";
47
+ }
48
+ /** Sign the exact arguments and their explicit action fields. A second approver uses dsseCountersign. */
49
+ export declare function createApproval(key: KeyPair, input: ApprovalBinding & {
50
+ approvalId?: string;
51
+ issuedAt?: string;
52
+ expiresAt: string;
53
+ }): Envelope;
54
+ export type ApprovalVerifyResult = {
55
+ ok: true;
56
+ approval: Approval;
57
+ approverKeyids: string[];
58
+ } | {
59
+ ok: false;
60
+ error: string;
61
+ };
62
+ /** Check the signed approval schema and trusted, distinct signatures; the caller must also check its action and validity window. */
63
+ export declare function verifyApprovalStatement(envelope: unknown, trusted: PublicKeyRef[], minApprovers?: 1 | 2): ApprovalVerifyResult;
64
+ /** Check trusted, distinct signatures, the whole action binding, and the half-open validity window. Never throws for untrusted input. */
65
+ export declare function verifyApproval(envelope: unknown, trusted: PublicKeyRef[], binding: ApprovalBinding, options?: {
66
+ at?: string;
67
+ minApprovers?: 1 | 2;
68
+ maxLifetimeSeconds?: number;
69
+ }): ApprovalVerifyResult;
70
+ /**
71
+ * Burn an approval before any side effect. Exclusive creation shares replay protection across processes and restarts.
72
+ * A subsequent write, log, or upstream failure deliberately leaves the marker in place: retry needs a new approval.
73
+ */
74
+ export declare function consumeApproval(usedDir: string, approvalId: string, receiptId: string, at: string): void;
@@ -0,0 +1,196 @@
1
+ // A short-lived human approval signs the exact action, independently of the agent's delegation grant.
2
+ import { randomUUID } from "node:crypto";
3
+ import { closeSync, fsyncSync, mkdirSync, openSync, realpathSync, writeFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { z } from "zod";
6
+ import { digestOf, dsseSign, dsseVerifiers, sha256Hex } from "./crypto.js";
7
+ export const APPROVAL_TYPE = "application/vnd.agent-custody.approval+json";
8
+ export const APPROVAL_META_KEY = "agent-custody/approval";
9
+ /** The longest approval lifetime that the gateway accepts when `approvals.maxLifetimeSeconds` is not set. */
10
+ export const DEFAULT_APPROVAL_LIFETIME_SECONDS = 3600;
11
+ const Nonempty = z.string().min(1);
12
+ const Timestamp = z.iso.datetime({ offset: true });
13
+ /** An ISO time with an offset: the only form that the approval and the receipt's approval record accept. Both verifiers use this rule. */
14
+ export const isApprovalTime = (value) => Timestamp.safeParse(value).success;
15
+ const ApprovalId = z.uuid();
16
+ export const ApprovalSchema = z.strictObject({
17
+ version: z.literal("0.1"),
18
+ approvalId: ApprovalId,
19
+ principal: Nonempty,
20
+ agent: Nonempty,
21
+ tool: Nonempty,
22
+ argsDigest: z.string().regex(/^[0-9a-f]{64}$/),
23
+ /** Money is expressed in integer minor units, never a float. */
24
+ amount: z.number().int().min(Number.MIN_SAFE_INTEGER).max(Number.MAX_SAFE_INTEGER).optional(),
25
+ currency: Nonempty.optional(),
26
+ beneficiary: Nonempty.optional(),
27
+ issuedAt: Timestamp,
28
+ expiresAt: Timestamp,
29
+ }).refine((a) => Date.parse(a.expiresAt) > Date.parse(a.issuedAt), {
30
+ message: "approval expiry must be after issuance", path: ["expiresAt"],
31
+ });
32
+ const BindingSchema = z.strictObject({
33
+ principal: Nonempty,
34
+ agent: Nonempty,
35
+ tool: Nonempty,
36
+ args: z.record(z.string(), z.unknown()),
37
+ fields: z.strictObject({ amount: Nonempty.optional(), currency: Nonempty.optional(), beneficiary: Nonempty.optional() }).optional(),
38
+ });
39
+ // Reject values JSON would silently omit or change. Otherwise two different actions could have the same digest.
40
+ function assertJson(value, ancestors = new Set()) {
41
+ if (value === null || typeof value === "string" || typeof value === "boolean")
42
+ return;
43
+ if (typeof value === "number" && Number.isFinite(value))
44
+ return;
45
+ if (typeof value !== "object" || ancestors.has(value))
46
+ throw new Error("approval arguments must be JSON data");
47
+ if (!Array.isArray(value) && Object.getPrototypeOf(value) !== Object.prototype && Object.getPrototypeOf(value) !== null) {
48
+ throw new Error("approval arguments must be JSON data");
49
+ }
50
+ ancestors.add(value);
51
+ if (Array.isArray(value)) {
52
+ for (let i = 0; i < value.length; i++)
53
+ assertJson(value[i], ancestors);
54
+ }
55
+ else {
56
+ for (const key of Object.keys(value))
57
+ assertJson(value[key], ancestors);
58
+ }
59
+ ancestors.delete(value);
60
+ }
61
+ function actionFor(input) {
62
+ // Validate without replacing args: z.record would copy an own __proto__ property on some runtimes.
63
+ BindingSchema.parse(input);
64
+ assertJson(input.args);
65
+ const action = {
66
+ principal: input.principal, agent: input.agent, tool: input.tool, argsDigest: digestOf(input.args),
67
+ };
68
+ for (const field of ["amount", "currency", "beneficiary"]) {
69
+ const name = input.fields?.[field] ?? field;
70
+ if (!Object.hasOwn(input.args, name))
71
+ continue;
72
+ const value = input.args[name];
73
+ if (field === "amount") {
74
+ if (typeof value !== "number" || !Number.isSafeInteger(value))
75
+ throw new Error("approval amount must be a safe integer in minor units");
76
+ action.amount = value;
77
+ }
78
+ else {
79
+ if (typeof value !== "string" || !value.length)
80
+ throw new Error(`approval ${field} must be a nonempty string`);
81
+ action[field] = value;
82
+ }
83
+ }
84
+ return action;
85
+ }
86
+ /** Sign the exact arguments and their explicit action fields. A second approver uses dsseCountersign. */
87
+ export function createApproval(key, input) {
88
+ const { approvalId = randomUUID(), issuedAt = new Date().toISOString(), expiresAt, ...binding } = input;
89
+ const approval = ApprovalSchema.parse({ version: "0.1", approvalId, ...actionFor(binding), issuedAt, expiresAt });
90
+ return dsseSign(APPROVAL_TYPE, approval, key);
91
+ }
92
+ function isBase64(value) {
93
+ return value.length > 0 && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value) && Buffer.from(value, "base64").toString("base64") === value;
94
+ }
95
+ const EnvelopeSchema = z.strictObject({
96
+ payloadType: z.literal(APPROVAL_TYPE),
97
+ payload: z.string().refine(isBase64, "approval payload must be base64"),
98
+ signatures: z.array(z.strictObject({
99
+ keyid: Nonempty,
100
+ sig: z.string().refine((s) => isBase64(s) && Buffer.from(s, "base64").length === 64, "approval signature must be an Ed25519 signature"),
101
+ })).min(1),
102
+ });
103
+ /** Check the signed approval schema and trusted, distinct signatures; the caller must also check its action and validity window. */
104
+ export function verifyApprovalStatement(envelope, trusted, minApprovers = 1) {
105
+ try {
106
+ const parsedEnvelope = EnvelopeSchema.safeParse(envelope);
107
+ if (!parsedEnvelope.success)
108
+ return { ok: false, error: "malformed approval envelope" };
109
+ const env = parsedEnvelope.data;
110
+ if (minApprovers !== 1 && minApprovers !== 2)
111
+ return { ok: false, error: "approval requires one or two approvers" };
112
+ const approverKeyids = [...new Set(dsseVerifiers(env, trusted))];
113
+ if (approverKeyids.length < minApprovers)
114
+ return { ok: false, error: `approval requires ${minApprovers} distinct trusted signature${minApprovers === 1 ? "" : "s"}` };
115
+ const parsed = ApprovalSchema.safeParse(JSON.parse(Buffer.from(env.payload, "base64").toString("utf8")));
116
+ if (!parsed.success)
117
+ return { ok: false, error: `invalid approval: ${parsed.error.message}` };
118
+ return { ok: true, approval: parsed.data, approverKeyids };
119
+ }
120
+ catch (error) {
121
+ return { ok: false, error: `invalid approval: ${error instanceof Error ? error.message : "could not verify"}` };
122
+ }
123
+ }
124
+ /** Check trusted, distinct signatures, the whole action binding, and the half-open validity window. Never throws for untrusted input. */
125
+ export function verifyApproval(envelope, trusted, binding, options = {}) {
126
+ try {
127
+ const signed = verifyApprovalStatement(envelope, trusted, options.minApprovers ?? 1);
128
+ if (!signed.ok)
129
+ return signed;
130
+ const { approval, approverKeyids } = signed;
131
+ const action = actionFor(binding);
132
+ // Fields must match in both directions: a signed field missing from the call is a mismatch too.
133
+ for (const field of ["principal", "agent", "tool", "argsDigest", "amount", "currency", "beneficiary"]) {
134
+ if (approval[field] !== action[field])
135
+ return { ok: false, error: `approval ${field} does not match this call` };
136
+ }
137
+ // The signer chooses the expiry, so the caller can cap it. An unused approval then cannot stay usable for years.
138
+ if (options.maxLifetimeSeconds !== undefined && Date.parse(approval.expiresAt) - Date.parse(approval.issuedAt) > options.maxLifetimeSeconds * 1000) {
139
+ return { ok: false, error: `approval lifetime exceeds the maximum of ${options.maxLifetimeSeconds} seconds` };
140
+ }
141
+ const at = options.at ?? new Date().toISOString();
142
+ if (!Timestamp.safeParse(at).success)
143
+ return { ok: false, error: "invalid approval check time" };
144
+ if (Date.parse(at) < Date.parse(approval.issuedAt))
145
+ return { ok: false, error: "approval is not yet valid" };
146
+ if (Date.parse(at) >= Date.parse(approval.expiresAt))
147
+ return { ok: false, error: "approval has expired" };
148
+ return { ok: true, approval, approverKeyids };
149
+ }
150
+ catch (error) {
151
+ return { ok: false, error: `invalid approval: ${error instanceof Error ? error.message : "could not verify"}` };
152
+ }
153
+ }
154
+ /**
155
+ * Burn an approval before any side effect. Exclusive creation shares replay protection across processes and restarts.
156
+ * A subsequent write, log, or upstream failure deliberately leaves the marker in place: retry needs a new approval.
157
+ */
158
+ export function consumeApproval(usedDir, approvalId, receiptId, at) {
159
+ ApprovalId.parse(approvalId);
160
+ Nonempty.parse(receiptId);
161
+ Timestamp.parse(at);
162
+ mkdirSync(usedDir, { recursive: true, mode: 0o700 });
163
+ const directory = realpathSync(usedDir);
164
+ // UUID spelling is case-insensitive; using its canonical spelling prevents two markers for one logical id.
165
+ const id = approvalId.toLowerCase();
166
+ let fd;
167
+ try {
168
+ fd = openSync(join(directory, `${sha256Hex(id)}.json`), "wx", 0o600);
169
+ }
170
+ catch (error) {
171
+ if (error.code === "EEXIST")
172
+ throw new Error(`approval ${approvalId} has already been used`);
173
+ throw error;
174
+ }
175
+ try {
176
+ writeFileSync(fd, JSON.stringify({ approvalId, receiptId, consumedAt: at }) + "\n");
177
+ fsyncSync(fd);
178
+ }
179
+ finally {
180
+ closeSync(fd);
181
+ }
182
+ // fsync(file) does not persist the new directory entry. Flush the directory and its ancestry, deepest first, so
183
+ // newly created parents survive a machine crash too. Flush existing parents as well: another process may just
184
+ // have created them and not yet synced them. Any failure leaves the id burned and must prevent forwarding.
185
+ for (let path = directory;; path = dirname(path)) {
186
+ const dirFd = openSync(path, "r");
187
+ try {
188
+ fsyncSync(dirFd);
189
+ }
190
+ finally {
191
+ closeSync(dirFd);
192
+ }
193
+ if (dirname(path) === path)
194
+ break;
195
+ }
196
+ }
package/dist/capture.js CHANGED
@@ -255,6 +255,12 @@ const CLEAR_IN = {
255
255
  execution: new Set(["status", "resultDigest", "provenance"]),
256
256
  upstream: new Set(["provider"]),
257
257
  consumed: new Set(["provenance"]),
258
+ /**
259
+ * The gateway's own observations of its approval check: the status, the times, the signers' key ids, and the config's
260
+ * argument mapping. The envelope is not here: the agent supplied it, and it carries the action fields and an unsalted
261
+ * digest of the arguments. The reason is not here either: it can quote the statement.
262
+ */
263
+ approval: new Set(["status", "requiredApprovers", "checkedAt", "consumedAt", "approverKeyids", "fields", "provenance"]),
258
264
  /** the host's correlation ids are supplied by the agent's process or its call: values, withheld; the provenance stays */
259
265
  session: new Set(["provenance"]),
260
266
  model: new Set(["provenance"]),
@@ -266,6 +272,7 @@ const RESULT_NEVER_CLEAR = new Set(["_meta"]);
266
272
  export const REST = "$rest";
267
273
  /** The parts an authorization and its receipt share; the receipt's view takes them from the authorization's, commitments and salts alike. */
268
274
  const SHARED_WITH_AUTHORIZATION = ["request", "facts", "policy", "consumed"];
275
+ const APPROVAL_ENVELOPE = ["approval", "envelope"];
269
276
  /**
270
277
  * The statement a receipt carries under a tool's rule: the predicate with every non-structural value withheld as the
271
278
  * rule says, the three digests salted from the field salts, and the note of what is withheld at `capture`. Under a
@@ -293,6 +300,10 @@ export function privateView(predicate, rule, key, ctx = {}, prior) {
293
300
  if (own(prior.predicate, part))
294
301
  out[part] = prior.predicate[part];
295
302
  for (const w of prior.predicate.capture?.withheld ?? []) {
303
+ // a part the receipt does not share (the operation, whose status changes) is withheld again below, once; the
304
+ // approval envelope is shared, though the rest of the approval record changes
305
+ if (!SHARED_WITH_AUTHORIZATION.includes(w[0]) && pathKey(w) !== pathKey(APPROVAL_ENVELOPE))
306
+ continue;
296
307
  withheld.push(w);
297
308
  const s = ownOf(prior.salts, pathKey(w));
298
309
  if (s)
@@ -350,7 +361,8 @@ export function privateView(predicate, rule, key, ctx = {}, prior) {
350
361
  const resultSide = sideOf(rule, "result", key);
351
362
  const factsSide = sideOf(rule, "facts", key);
352
363
  for (const [key_, value] of Object.entries(predicate)) {
353
- if (CLEAR_TOP.has(key_))
364
+ // the approval record is handled after the loop: whether its envelope may stay depends on what the arguments withheld
365
+ if (CLEAR_TOP.has(key_) || key_ === "approval")
354
366
  continue;
355
367
  if (prior && SHARED_WITH_AUTHORIZATION.includes(key_))
356
368
  continue;
@@ -465,9 +477,45 @@ export function privateView(predicate, rule, key, ctx = {}, prior) {
465
477
  hide(["consumed", f], v, k);
466
478
  }
467
479
  }
480
+ else if (key_ === "operation" && isObject(value)) {
481
+ // Only gateway-derived identities and operator configuration are public. The id is not: the agent chose it
482
+ // (a caller may use an order or customer UUID), so it is withheld. The idempotencyKey links the receipts. The
483
+ // amount is never duplicated here: it belongs to the captured request. New fields start private, together at $rest.
484
+ object(["operation"], value, { clear: new Set(["idempotencyKey", "lookupDigest", "status", "budget", "originalReceiptId", "provenance"]), key: k });
485
+ if (isObject(value.budget))
486
+ object(["operation", "budget"], value.budget, { clear: new Set(["id", "currency", "period"]), key: k });
487
+ }
488
+ else if (key_ === "reconciliation" && isObject(value)) {
489
+ // original is the immutable, already captured bundle written by this issuer. The lookup consists solely of
490
+ // operator configuration and the gateway-derived idempotency key; the provider response lives in execution.result.
491
+ object(["reconciliation"], value, { clear: new Set(["original", "lookup"]), key: k });
492
+ if (isObject(value.lookup))
493
+ object(["reconciliation", "lookup"], value.lookup, { clear: new Set(["tool", "args", "statusPath", "identityPath", "confirmed", "failed"]), key: k });
494
+ }
468
495
  else
469
496
  hide([key_], value, k);
470
497
  }
498
+ const approval = predicate.approval;
499
+ if (isObject(approval)) {
500
+ // Beside arguments of which nothing is withheld, an approved envelope adds nothing: its payload equals the public
501
+ // call, and the gateway checked that. It stays, so a verifier can run the binding check on it (the analogue of
502
+ // isPlainAttestation). A denied envelope may carry another call's fields, so it is withheld, unless the
503
+ // authorization already showed it. A masked tool name is never kept beside its envelope.
504
+ const argsPublic = !withheld.some((w) => under(w, ["request", "args"])) && !ctx.unknownTool;
505
+ for (const [f, v] of Object.entries(approval)) {
506
+ if (CLEAR_IN.approval.has(f))
507
+ continue;
508
+ const path = ["approval", f];
509
+ // the authorization and the receipt carry the same envelope, so they carry the same commitment to it
510
+ const earlier = f === "envelope" && prior ? getAt(prior.predicate, path) : undefined;
511
+ if (f === "envelope" && argsPublic && (approval.status === "approved" || (earlier !== undefined && !isCommitment(earlier))))
512
+ continue;
513
+ if (isCommitment(earlier))
514
+ out = setAt(out, path, earlier);
515
+ else
516
+ hide(path, v, f === "envelope" && argsSide ? argsSide.key : k);
517
+ }
518
+ }
471
519
  if (withheld.length)
472
520
  out.capture = { mode, withheld };
473
521
  return { predicate: out, salts };
package/dist/cli.js CHANGED
@@ -3,8 +3,8 @@ import { hostname, userInfo } from "node:os";
3
3
  import { captureKeyFrom, getAt, pathText, restorePaths, setAt } from "./capture.js";
4
4
  import { saltsFileFor } from "./retention.js";
5
5
  import { parseArgs } from "node:util";
6
- import { closeSync, constants as fsConstants, existsSync, fchmodSync, openSync, readFileSync, writeFileSync, writeSync } from "node:fs";
7
- import { dirname, resolve } from "node:path";
6
+ import { closeSync, constants as fsConstants, existsSync, fchmodSync, openSync, readFileSync, readdirSync, writeFileSync, writeSync } from "node:fs";
7
+ import { dirname, join, resolve } from "node:path";
8
8
  import { loadConfig, loadSdkConfig } from "./config.js";
9
9
  import { dsseVerify, generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
10
10
  import { createDelegation, decodeDelegation, delegateFrom, grantDigest } from "./delegation.js";
@@ -28,6 +28,7 @@ import { MerkleLog } from "./log.js";
28
28
  import { createSdkIssuer } from "./sdk/index.js";
29
29
  import { handleHookEvent } from "./sdk/claude.js";
30
30
  import { auditExtends, formatReport, verifyBundle } from "./verify.js";
31
+ import { formatSimulation, simulatePolicy, verifyOrphanAuthorization } from "./simulate.js";
31
32
  /** A shared secret from an environment variable; never from the command line, where it would land in shell history. */
32
33
  function secretFrom(envName) {
33
34
  const v = process.env[envName];
@@ -46,6 +47,7 @@ const USAGE = `agent-custody <command>
46
47
  for verify --disclose; needs the customer's capture key
47
48
  revoke --config <gateway.json> --grant <grant.json> revokes a grant: its digest goes into the config's revokedGrants file, every
48
49
  session under it or under a grant delegated from it refuses its next call, and no new session opens for them
50
+ reconcile --config <gateway.json> --operation <uuid> operator-only provider lookup; commits a receipt before closing an unknown/pending financial operation
49
51
  gateway --config <gateway.json> [--http [--port 8790] [--host 127.0.0.1] [--idle-minutes 30]]
50
52
  stdio: one gateway for the grant the config names. --http: one shared gateway, MCP over
51
53
  Streamable HTTP at /mcp, each connection presenting its own grant as Authorization: Bearer
@@ -54,7 +56,10 @@ const USAGE = `agent-custody <command>
54
56
  prune --log <log.jsonl> --before <ISO instant> [--receipts <dir>]
55
57
  retention on the receipt log: replaces older leaves with their hashes, so proofs still verify and the content is gone
56
58
  log --file <log.jsonl> --key <log.key> [--port 8787] [--host 127.0.0.1] [--token-env <NAME>] reference log server
57
- verify <bundle.json> --issuer-key <pub> [--principal-key <pub>] [--log-key <pub> | --log-url <url>] [--log-id <id>] [--upstream-key <pub>] [--stripe-secret-env NAME] [--github-secret-env NAME] [--log <log.jsonl>] [--json]
59
+ verify <bundle.json> --issuer-key <pub> [--principal-key <pub>] [--approval-key <pub>] [--log-key <pub> | --log-url <url>] [--log-id <id>] [--upstream-key <pub>] [--stripe-secret-env NAME] [--github-secret-env NAME] [--log <log.jsonl>] [--disclose <file>] [--capture-key-env NAME] [--json]
60
+ policy simulate --policy <proposed.cedar> --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--approval-key <pub>]... [--log-key <pub>]... [--json] [--out <file>]
61
+ replay verified local receipts against a proposed policy using their recorded inputs;
62
+ --out saves the full JSON report. Exits 1 when any call could not be evaluated.
58
63
  log ... --db-env NAME the same server over Postgres: tenants and tokens from the database, one writer per tenant,
59
64
  root paths serve the tenant "default" (created with --log-id). Needs the pg package.
60
65
  log ... (--key <log.key> [--retired-key <pub>]... | --signer-url <url> [--signer-token-env NAME]) [--checkpoint-dir <dir>] [--checkpoint-every <seconds>] [--checkpoint-heartbeat <seconds>]
@@ -128,6 +133,22 @@ function loadTenants(path) {
128
133
  async function main(argv) {
129
134
  const [cmd, ...rest] = argv;
130
135
  switch (cmd) {
136
+ case "reconcile": {
137
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, operation: { type: "string" } } });
138
+ if (!values.config || !values.operation)
139
+ throw new Error("reconcile needs --config and --operation");
140
+ const cfg = loadConfig(values.config);
141
+ const host = await createGatewayHost(cfg);
142
+ try {
143
+ const bundle = await host.reconcile(values.operation);
144
+ const p = JSON.parse(Buffer.from(bundle.envelope.payload, "base64").toString("utf8")).predicate;
145
+ console.log(JSON.stringify({ operation: values.operation, status: p.operation.status, receipt: join(cfg.receiptsDir, `${p.receiptId}.json`) }));
146
+ return 0;
147
+ }
148
+ finally {
149
+ await host.close();
150
+ }
151
+ }
131
152
  case "keygen": {
132
153
  const { values } = parseArgs({ args: rest, options: { dir: { type: "string" }, name: { type: "string" } } });
133
154
  if (!values.dir || !values.name)
@@ -518,6 +539,7 @@ async function main(argv) {
518
539
  "issuer-key": { type: "string", multiple: true },
519
540
  "gateway-key": { type: "string", multiple: true },
520
541
  "principal-key": { type: "string", multiple: true },
542
+ "approval-key": { type: "string", multiple: true },
521
543
  "log-key": { type: "string", multiple: true },
522
544
  "log-url": { type: "string" },
523
545
  "log-id": { type: "string" },
@@ -542,6 +564,7 @@ async function main(argv) {
542
564
  const result = verifyBundle(bundle, {
543
565
  issuerKeys: issuerKeyFiles.map(loadPublicKey),
544
566
  principalKeys: (values["principal-key"] ?? []).map(loadPublicKey),
567
+ ...(values["approval-key"] ? { approvalKeys: values["approval-key"].map(loadPublicKey) } : {}),
545
568
  ...(logKeys.length ? { logKeys } : {}),
546
569
  ...(values["log-id"] ? { logId: values["log-id"] } : {}),
547
570
  ...(values["upstream-key"] ? { upstreamKeys: values["upstream-key"].map(loadPublicKey) } : {}),
@@ -553,6 +576,104 @@ async function main(argv) {
553
576
  console.log(values.json ? JSON.stringify(result, null, 2) : formatReport(result));
554
577
  return result.ok ? 0 : 1;
555
578
  }
579
+ case "policy": {
580
+ const [subcommand, ...args] = rest;
581
+ if (subcommand !== "simulate")
582
+ throw new Error("policy needs the simulate subcommand: policy simulate --policy <proposed.cedar> --receipts <dir> --issuer-key <pub>");
583
+ const { values } = parseArgs({
584
+ args,
585
+ options: {
586
+ policy: { type: "string" },
587
+ receipts: { type: "string" },
588
+ "issuer-key": { type: "string", multiple: true },
589
+ "principal-key": { type: "string", multiple: true },
590
+ "approval-key": { type: "string", multiple: true },
591
+ "log-key": { type: "string", multiple: true },
592
+ "capture-key-env": { type: "string" },
593
+ disclose: { type: "string", multiple: true },
594
+ json: { type: "boolean", default: false },
595
+ out: { type: "string" },
596
+ },
597
+ });
598
+ if (!values.policy || !values.receipts || !values["issuer-key"]?.length)
599
+ throw new Error("policy simulate needs --policy <proposed.cedar> --receipts <dir> --issuer-key <pub>");
600
+ const policy = readFileSync(values.policy, "utf8");
601
+ const keys = {
602
+ issuerKeys: values["issuer-key"].map(loadPublicKey),
603
+ principalKeys: (values["principal-key"] ?? []).map(loadPublicKey),
604
+ approvalKeys: (values["approval-key"] ?? []).map(loadPublicKey),
605
+ logKeys: (values["log-key"] ?? []).map(loadPublicKey),
606
+ };
607
+ const names = readdirSync(values.receipts, { withFileTypes: true })
608
+ .filter((entry) => (entry.isFile() || entry.isSymbolicLink()) && entry.name.endsWith(".json"))
609
+ .map((entry) => entry.name);
610
+ const AUTHORIZATION = ".authorization.json";
611
+ const files = names.filter((name) => !name.endsWith(AUTHORIZATION)).sort();
612
+ const have = new Set(files);
613
+ const fail = (file, error) => { throw new Error(`policy simulate: ${file}: ${error instanceof Error ? error.message : String(error)}`); };
614
+ // A gateway that dies after it forwards a precommit call leaves <id>.authorization.json and no <id>.json. That
615
+ // call went upstream, so it counts as skipped and the report is incomplete.
616
+ const unreplayable = names.filter((name) => name.endsWith(AUTHORIZATION) && !have.has(`${name.slice(0, -AUTHORIZATION.length)}.json`)).sort().map((name) => {
617
+ const file = join(values.receipts, name);
618
+ try {
619
+ const p = verifyOrphanAuthorization(JSON.parse(readFileSync(file, "utf8")), keys.issuerKeys, keys.logKeys);
620
+ if (`${p.receiptId}${AUTHORIZATION}` !== name)
621
+ throw new Error("the file name does not match the receipt id in the authorization");
622
+ return { receiptId: p.receiptId, tool: p.tool.name, reason: "only the authorization survives; the receipt is missing, so the outcome and the call cannot be replayed" };
623
+ }
624
+ catch (error) {
625
+ return fail(file, error);
626
+ }
627
+ });
628
+ if (!files.length && !unreplayable.length)
629
+ throw new Error(`policy simulate: no receipt bundles found in ${values.receipts}`);
630
+ const captureKey = values["capture-key-env"] ? captureKeyFrom(secretFrom(values["capture-key-env"])) : undefined;
631
+ const disclosures = new Map();
632
+ for (const file of values.disclose ?? []) {
633
+ try {
634
+ const disclosure = JSON.parse(readFileSync(file, "utf8"));
635
+ if (typeof disclosure?.receiptId !== "string")
636
+ throw new Error("the disclosure names no receiptId");
637
+ disclosures.set(disclosure.receiptId, disclosure);
638
+ }
639
+ catch (error) {
640
+ fail(file, error);
641
+ }
642
+ }
643
+ // One bundle at a time: the replay needs the predicate of the receipt it is on, not the results of the others.
644
+ function* verified() {
645
+ for (const name of files) {
646
+ const file = join(values.receipts, name);
647
+ try {
648
+ const bundle = JSON.parse(readFileSync(file, "utf8"));
649
+ const result = verifyBundle(bundle, keys);
650
+ if (!result.ok || !result.statement) {
651
+ const failures = result.checks.filter((check) => !check.ok).map((check) => `${check.name}${check.detail ? ` (${check.detail})` : ""}`);
652
+ throw new Error(`receipt verification failed: ${failures.join("; ")}`);
653
+ }
654
+ yield result.statement.predicate;
655
+ }
656
+ catch (error) {
657
+ fail(file, error);
658
+ }
659
+ }
660
+ }
661
+ const report = simulatePolicy(policy, verified(), { unreplayable, ...(captureKey ? { captureKey } : {}), disclosures });
662
+ const json = JSON.stringify(report, null, 2);
663
+ if (values.out) {
664
+ // Reports name calls and decisions: keep them owner-only, including when replacing an existing file.
665
+ const fd = openSync(values.out, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_TRUNC | fsConstants.O_NOFOLLOW, 0o600);
666
+ try {
667
+ fchmodSync(fd, 0o600);
668
+ writeSync(fd, json);
669
+ }
670
+ finally {
671
+ closeSync(fd);
672
+ }
673
+ }
674
+ console.log(values.json ? json : formatSimulation(report));
675
+ return report.complete ? 0 : 1;
676
+ }
556
677
  case "reveal": {
557
678
  // The values a receipt withheld, under the customer's key, as a disclosure file: hand it to a reviewer with the
558
679
  // receipt, and `verify --disclose` recomputes every digest from it.