@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/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
- 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.
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-five runnable examples, one per aspect of the code, all executed by the test suite
14
- - [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
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
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-five 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
@@ -256,17 +261,18 @@ src/splunk.ts Splunk export: one HTTP Event Collector event per receipt, to
256
261
  src/rest.ts the REST connector: an HTTP API described as tools, standing where an MCP upstream stands
257
262
  src/a2a.ts agents delegating to agents: a remote A2A agent as an upstream, and the gateway serving A2A itself in front of it
258
263
  src/upstream.ts attested execution: an upstream signs its result for the receipt; the verifier checks it with the upstream key
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
259
265
  vectors/ conformance vectors: receipts, keys, logs, proofs, and expected verdicts; `bun run vectors` regenerates them
260
266
  src/verify.ts offline verification, the human-readable report, and the audit that a later log extends an earlier one
261
- src/cli.ts keygen, grant, gateway, hook, serve, log, prune, verify, audit
267
+ src/cli.ts keygen, grant, gateway, hook, serve, log, prune, verify, reveal, audit, policy simulate
262
268
  src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
263
269
  src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
264
270
  tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
265
- scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, fixture builders for gateway and SDK, demo
266
- examples/ twenty-five 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
267
273
  test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
268
274
  adapter tests against the real packages, and a test that runs every policy in docs/policies.md
269
- docs/ tutorials, usage (gateway), sdk, policies, verification
275
+ docs/ tutorials, usage (gateway), approvals, sdk, policies, verification
270
276
  ```
271
277
 
272
278
  ## Plan
@@ -275,6 +281,7 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
275
281
 
276
282
  **Done**
277
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.
278
285
  - Gateway: MCP proxy, signed delegation, gateway-fetched facts, Cedar policy, denial receipts, Merkle log, offline verifier.
279
286
  - Receipt schema carries the issuer kind, so a verifier reads gateway versus SDK before anything else.
280
287
  - SDK core: policy decision, record, and a generic `wrap(tool, fn)` for any framework whose tools are functions.
@@ -303,13 +310,15 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
303
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).
304
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).
305
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).
306
- - 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.
307
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.
308
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.
309
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.
310
317
  - The REST connector: a plain HTTP API described as tools in the gateway config, credentials from the environment, so an agent's direct API calls become receipted, policy-checked tool calls through the gateway.
311
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.
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).
312
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.
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.
313
322
 
314
323
  **Next, in the order it pays off**
315
324
 
package/dist/a2a.js CHANGED
@@ -136,20 +136,20 @@ export function a2aUpstream(name, cfg, opts = {}) {
136
136
  const tools = [
137
137
  {
138
138
  name: sendTool,
139
- description: `Delegate a task to the agent "${c.name}"${c.description ? `: ${c.description}` : ""}${skills ? `. Skills: ${skills}` : ""}`,
139
+ description: `Delegate a task to the agent "${c.name}"${c.description ? `: ${c.description}` : ""}${skills ? `. Skills: ${skills}` : ""}. Send text for a plain task, or message for a full A2A message; one of the two is needed. Returns the agent's task or message as JSON text. A JSON-RPC error from the agent comes back as an error result.`,
140
140
  inputSchema: {
141
141
  type: "object",
142
142
  properties: {
143
143
  text: { type: "string", description: "the task, as text" },
144
144
  message: { type: "object", description: "a full A2A message, forwarded as is; text is derived from it" },
145
- taskId: { type: "string" },
146
- contextId: { type: "string" },
147
- configuration: { type: "object" },
148
- metadata: { type: "object" },
145
+ taskId: { type: "string", description: "the id of an earlier task to continue; used with text only, because a full message carries its own" },
146
+ contextId: { type: "string", description: "the id of the conversation context to continue; used with text only" },
147
+ configuration: { type: "object", description: "the A2A send configuration, forwarded as is" },
148
+ metadata: { type: "object", description: "A2A metadata for the request, forwarded as is" },
149
149
  },
150
150
  },
151
151
  },
152
- { name: cardTool, description: `The agent card of "${c.name}", fetched by the gateway`, inputSchema: { type: "object", properties: {} } },
152
+ { name: cardTool, description: `The agent card of "${c.name}", fetched afresh from the agent by the gateway: its name, description, skills, and the interfaces it serves. Call it to see what the agent can do before you delegate with ${sendTool}. A gateway config can also name it as a fact, so that a policy can read the card.`, inputSchema: { type: "object", properties: {} } },
153
153
  ];
154
154
  return { tools };
155
155
  },
@@ -316,8 +316,20 @@ export async function serveA2a(host, cfg, opts) {
316
316
  const method = restSend ?? (typeof parsed.method === "string" ? parsed.method : "");
317
317
  const id = restSend ? null : parsed.id ?? null;
318
318
  const params = (restSend ? parsed : parsed.params) ?? {};
319
- if (!SEND_METHODS.has(method) && !STREAM_METHODS.has(method))
319
+ if (!SEND_METHODS.has(method) && !STREAM_METHODS.has(method)) {
320
+ // reads and cancels carry no receipt, but they still need a grant in force (issue #97)
321
+ let problem;
322
+ try {
323
+ const p = session(req).grantProblem();
324
+ problem = p && `the grant ${p}`;
325
+ }
326
+ catch (e) {
327
+ problem = e instanceof Error ? e.message : String(e);
328
+ }
329
+ if (problem)
330
+ return sendBody(res, 403, "application/json", JSON.stringify(restSend ? { error: problem } : { jsonrpc: "2.0", id, error: { code: -32000, message: problem } }));
320
331
  return forward(req, res, body);
332
+ }
321
333
  const legacy = LEGACY_METHODS.has(method);
322
334
  const stream = STREAM_METHODS.has(method);
323
335
  const message = (params.message ?? {});
@@ -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
+ }
@@ -0,0 +1,153 @@
1
+ import type { AuthorizationPredicate } from "./receipt.ts";
2
+ export type CaptureMode = "clear" | "digest" | "encrypted";
3
+ /** One side of a call: the arguments, the result, or the facts. */
4
+ export interface CaptureSide {
5
+ /** clear: the side in the receipt as it was; digest: withheld fields leave a commitment; encrypted: withheld fields leave a commitment and the value under the customer's key */
6
+ mode: CaptureMode;
7
+ /** top-level fields kept in clear in digest or encrypted mode, e.g. the amount and the customer id of a refund */
8
+ clear?: string[];
9
+ }
10
+ /**
11
+ * A tool's rule. Once any side is private, the rule is private: a side it does not set is withheld whole, field by
12
+ * field, and so is every other value in the receipt that is not structural (policy errors, an error message, a denial
13
+ * reason, the result's metadata, a provider's delivery body). A side set to mode clear stays in clear.
14
+ */
15
+ export interface CaptureRule {
16
+ args?: CaptureSide;
17
+ result?: CaptureSide;
18
+ facts?: CaptureSide;
19
+ }
20
+ /** by tool name, or "*" for every tool without a rule of its own */
21
+ export type CaptureConfig = Record<string, CaptureRule>;
22
+ /** A path into the predicate, one segment per key: `["request", "args", "reason"]`. Segments are keys, so a field named "." or "*" is just a field. */
23
+ export type Path = string[];
24
+ /**
25
+ * On the receipt, inside the signed statement: how the call was captured and which paths are withheld. The verifier
26
+ * trusts the note, not the shape of the data: a path the note names must hold a commitment, and commitment-shaped data
27
+ * at a path the note does not name is ordinary data, in the digest like anything else.
28
+ */
29
+ export interface CaptureNote {
30
+ mode: "digest" | "encrypted";
31
+ withheld: Path[];
32
+ }
33
+ export interface Withheld {
34
+ $custody: "withheld";
35
+ /** sha256 over salt || canonical JSON of the value; the salt is not in the receipt */
36
+ sha256: string;
37
+ }
38
+ export interface Encrypted {
39
+ $custody: "encrypted";
40
+ alg: "A256GCM";
41
+ /** sha256 of the key, so a reviewer knows which key reveals it */
42
+ keyid: string;
43
+ iv: string;
44
+ /** AES-256-GCM over the canonical JSON of `{ salt, value }` */
45
+ ciphertext: string;
46
+ tag: string;
47
+ sha256: string;
48
+ }
49
+ export type Commitment = Withheld | Encrypted;
50
+ /** What a disclosure carries at a withheld path: the value and the salt the commitment was made with. Without `value` it is unfinished (`reveal --include-salts` writes it so for the holder to fill in) and fails verification. */
51
+ export interface Disclosed {
52
+ $custody: "disclosed";
53
+ salt: string;
54
+ value?: unknown;
55
+ }
56
+ /** A 32-byte key from hex (64 chars) or base64 (44 chars), as an environment variable holds it. */
57
+ export declare function captureKeyFrom(text: string): Buffer;
58
+ export declare function captureKeyId(key: Buffer): string;
59
+ /** A well-formed commitment: the sha256 a verifier checks, and for an encrypted one the fields the key needs. A `$custody` tag alone is not one. */
60
+ export declare function isCommitment(v: unknown): v is Commitment;
61
+ /** What an encrypted commitment is bound to: the receipt and the path, so a ciphertext moved to another receipt or path does not decrypt. */
62
+ export declare function aadFor(receiptId: unknown, path: Path): string;
63
+ /** A disclosed value as a disclosure carries it: the salt, and the value when the holder has filled it in. */
64
+ export declare function isDisclosed(v: unknown): v is Disclosed;
65
+ /** Replaces a value with its commitment, carrying the value and the salt encrypted when a key is given (bound to `aad`, see `aadFor`); the salt is returned to the caller, never written into the receipt. */
66
+ export declare function withhold(value: unknown, key?: Buffer, aad?: string): {
67
+ commitment: Commitment;
68
+ salt: string;
69
+ };
70
+ /** True when `value` under `salt` is what the commitment was made over. */
71
+ export declare function checkCommitment(c: Commitment, value: unknown, salt: string): boolean;
72
+ /** The value and the salt behind an encrypted commitment, under the key that made it; checked against the commitment too. */
73
+ export declare function reveal(c: Commitment, key: Buffer, aad?: string): {
74
+ value: unknown;
75
+ salt: string;
76
+ };
77
+ /**
78
+ * The salt of a digest over a part that holds withheld values: derived from the salts of those values, in note order,
79
+ * so whoever can restore the values can recompute the digest and nobody else can confirm a guess against it. No salt
80
+ * when nothing under the part is withheld: the values are public, and so may the digest be.
81
+ */
82
+ export declare function digestSalt(salts: string[]): string | undefined;
83
+ /** The tool's rule, else the "*" rule: by own property, so a tool named `constructor` or `toString` does not find an inherited member and fall through to clear. */
84
+ export declare function ruleFor(capture: CaptureConfig | undefined, tool: string): CaptureRule | undefined;
85
+ /**
86
+ * The rule for a call: the tool's own, else the wildcard. For a name no upstream offers, which is text the agent
87
+ * chose, both together, side by side: the more private mode, and only the fields both keep in clear, so that a rule
88
+ * left for a retired name can never be selected by an agent to widen what is in clear. A mode does not order which
89
+ * fields are public, so the clear lists are intersected, not taken from the more private rule. The gateway and the
90
+ * issuer both call this, so the fact arguments kept in clear and the view agree.
91
+ */
92
+ export declare function effectiveRule(capture: CaptureConfig | undefined, tool: string, unknownTool?: boolean): CaptureRule | undefined;
93
+ /** The one mode a rule withholds in: encrypted when any side is, else digest; clear when no side is private. */
94
+ export declare function ruleMode(rule: CaptureRule | undefined): CaptureMode;
95
+ export declare const pathKey: (p: Path) => string;
96
+ export declare const pathText: (p: Path) => string;
97
+ export declare const under: (p: Path, prefix: Path) => boolean;
98
+ /** The value at a path, by own properties only; undefined when the path leaves the data. */
99
+ export declare function getAt(root: unknown, path: Path): unknown;
100
+ /** A copy of `root` with `value` at `path`, every object on the way copied (null-prototype), the rest shared. Creates objects for missing segments. */
101
+ export declare function setAt<T>(root: T, path: Path, value: unknown): T;
102
+ /** the slot in a captured side's view that holds the commitment over every field not kept in clear */
103
+ export declare const REST = "$rest";
104
+ /** What the producer knows about this call that the view needs: which fact arguments copy a call argument that is in clear, and the full lookup results behind the fact digests. */
105
+ export interface CaptureContext {
106
+ /** per fact name: the lookup arguments that may stay in clear under a private args rule (constants, or copies of call arguments the rule keeps in clear) */
107
+ clearFactArgs?: Record<string, string[]>;
108
+ /** per fact name: the lookup's full result, which the receipt's `resultDigest` then commits to; without it the digest the producer computed is withheld */
109
+ factResults?: Record<string, unknown>;
110
+ /** the tool name is not one any upstream offers, so it is text the agent chose: under a private rule the view shows "(unknown tool)" in its place, the rule having been selected by the real name */
111
+ unknownTool?: boolean;
112
+ }
113
+ /** The view the issuer signs, and the salts behind its commitments by `pathKey`, which the issuer keeps and never signs. */
114
+ export interface PrivateView<P> {
115
+ predicate: P;
116
+ salts: Record<string, string>;
117
+ }
118
+ /**
119
+ * The statement a receipt carries under a tool's rule: the predicate with every non-structural value withheld as the
120
+ * rule says, the three digests salted from the field salts, and the note of what is withheld at `capture`. Under a
121
+ * clear rule, the predicate itself and no salts. Applied by the issuer to every statement it signs, the authorization
122
+ * included; given the authorization's view as `prior`, the receipt's view carries the same request, facts, and policy,
123
+ * so that the receipt still names the authorization and nothing is withheld twice.
124
+ */
125
+ export declare function privateView<P extends AuthorizationPredicate>(predicate: P, rule: CaptureRule | undefined, key?: Buffer, ctx?: CaptureContext, prior?: PrivateView<AuthorizationPredicate>): PrivateView<P>;
126
+ export type How = "disclosed" | "decrypted";
127
+ export interface Restoration<P> {
128
+ /** the predicate with every restorable path put back */
129
+ predicate: P;
130
+ /** how each restored path came back, by `pathKey` */
131
+ restored: Map<string, How>;
132
+ /** the salt of each restored path, by `pathKey`: what the digests over them are salted from */
133
+ salts: Map<string, string>;
134
+ /** the value of each restored path as it was committed, by `pathKey`; a `$rest` is folded into its parent in `predicate`, so this is where it stays whole */
135
+ values: Map<string, unknown>;
136
+ /** the withheld paths whose value could not be had */
137
+ missing: Path[];
138
+ /** paths where the note, the data, a disclosure, or the key contradict each other; each a reason a check must fail */
139
+ problems: {
140
+ path: Path;
141
+ error: string;
142
+ }[];
143
+ }
144
+ /**
145
+ * The full statement behind a view, under its note: a path the note names must hold a commitment; the disclosure, when
146
+ * it carries that path as `{ $custody: "disclosed", salt, value }`, must match the commitment; else the key reveals
147
+ * what was encrypted under it; else the path stays withheld. A disclosure is a partial predicate with those at the
148
+ * withheld paths, as `agent-custody reveal` writes it. Nothing here throws: the problems are reported, so a verifier
149
+ * fails the right check.
150
+ */
151
+ export declare function restorePaths<P>(predicate: P, note: CaptureNote | undefined, disclosed?: unknown, key?: Buffer): Restoration<P>;
152
+ /** The salt a digest over `prefix` was made with, once every withheld path under it is restored: see `digestSalt`. */
153
+ export declare function digestSaltFor<P>(r: Restoration<P>, note: CaptureNote | undefined, prefix: Path): string | undefined;