@agent-custody/receipts 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -13
- package/dist/approval.d.ts +74 -0
- package/dist/approval.js +196 -0
- package/dist/capture.js +49 -1
- package/dist/check.d.ts +19 -0
- package/dist/check.js +288 -0
- package/dist/cli.js +238 -11
- package/dist/config.d.ts +85 -0
- package/dist/config.js +72 -2
- package/dist/console-page.d.ts +4 -0
- package/dist/console-page.js +342 -0
- package/dist/console.d.ts +20 -0
- package/dist/console.js +521 -0
- package/dist/gateway.d.ts +9 -0
- package/dist/gateway.js +335 -45
- package/dist/index.d.ts +9 -2
- package/dist/index.js +7 -1
- package/dist/issue.d.ts +8 -3
- package/dist/issue.js +13 -4
- package/dist/log-store.d.ts +3 -2
- package/dist/log-store.js +2 -0
- package/dist/operations.d.ts +101 -0
- package/dist/operations.js +239 -0
- package/dist/otel.js +12 -5
- package/dist/policy.d.ts +2 -0
- package/dist/policy.js +10 -0
- package/dist/portal.d.ts +78 -4
- package/dist/portal.js +516 -26
- package/dist/receipt.d.ts +36 -1
- package/dist/rest.js +14 -1
- package/dist/simulate.d.ts +58 -0
- package/dist/simulate.js +204 -0
- package/dist/splunk.js +11 -4
- package/dist/sso.d.ts +47 -0
- package/dist/sso.js +161 -0
- package/dist/verify.d.ts +2 -0
- package/dist/verify.js +241 -7
- package/docs/approvals.md +107 -0
- package/docs/codex-recovery.md +132 -0
- package/docs/configuration.md +224 -0
- package/docs/console.md +79 -0
- package/docs/financial-operations.md +99 -0
- package/docs/policies.md +23 -0
- package/docs/threat-model.md +13 -0
- package/docs/tutorials.md +9 -0
- package/docs/usage.md +49 -4
- package/docs/verification.md +26 -8
- package/package.json +8 -2
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/receipts.json +2866 -464
package/README.md
CHANGED
|
@@ -4,16 +4,21 @@ 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):
|
|
14
|
-
- [
|
|
13
|
+
- [Tutorials](docs/tutorials.md): thirty-one 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
|
+
- [The gateway console](docs/console.md): an admin service for the person who runs a gateway: config, tools, receipts with a verdict each, a policy editor that replays recorded calls before it saves, grant revocation, and an audit trail
|
|
16
|
+
- [Configuring the gateway](docs/configuration.md): who may use which tools and where the tools live, a worked example with two agents, the Docker image, and `agent-custody check` to validate a config before it starts
|
|
17
|
+
- [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, private evidence: what the receipt file carries of each call, and searching receipts and exporting offline cases with the state package's review console
|
|
18
|
+
- [Live Codex recovery demo](docs/codex-recovery.md): a real support agent, incorrect CRM memory, operator-reviewed compensation, and verified receipts; an opt-in live run with offline regression coverage
|
|
19
|
+
- [Human approvals](docs/approvals.md): short-lived signatures over the exact action, two-person thresholds, single-use enforcement, and offline verification
|
|
15
20
|
- [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
|
|
21
|
+
- [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
22
|
- [Verifying a receipt](docs/verification.md): what each check means and what a verified receipt does and does not prove
|
|
18
23
|
- [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
24
|
- [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
|
|
@@ -51,6 +56,8 @@ Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the
|
|
|
51
56
|
|
|
52
57
|
## How it fits together
|
|
53
58
|
|
|
59
|
+
The [architecture guide](../../site/guide/architecture.md) adds the customer-side and hosted split, the data model, and sequence diagrams for onboarding, revocation, and verification.
|
|
60
|
+
|
|
54
61
|
```mermaid
|
|
55
62
|
flowchart LR
|
|
56
63
|
P["Principal<br/>(human or org, holds a signing key)"]
|
|
@@ -102,6 +109,7 @@ Every receipt names its issuer, and the verifier prints what that issuer kind is
|
|
|
102
109
|
| host or framework | producer | enforce + record | record only | tested against |
|
|
103
110
|
| --- | --- | --- | --- | --- |
|
|
104
111
|
| any MCP host: Claude Desktop, Claude Code, Cursor, custom | gateway | yes | | a real MCP client and upstream over stdio |
|
|
112
|
+
| Codex CLI (headless) | gateway | yes | | a manual `codex exec` run and offline MCP recovery checks; [guide](docs/codex-recovery.md) |
|
|
105
113
|
| Claude Code | SDK | `hook` command, PreToolUse deny | PostToolUse | the documented hook contract, via stdin |
|
|
106
114
|
| Claude Agent SDK | SDK | `claudeAgentHooks` | same | the same handler |
|
|
107
115
|
| OpenAI Agents SDK (JS) | SDK | `wrapTools` | `observeRunner` | a real `Runner` with a scripted model |
|
|
@@ -118,7 +126,7 @@ Every receipt names its issuer, and the verifier prints what that issuer kind is
|
|
|
118
126
|
| any REST API, as tools the agent reaches through the gateway | gateway, `rest` upstream | yes | | a stand-in HTTP API; [usage.md](docs/usage.md#setup-step-by-step) |
|
|
119
127
|
| any agent reached over A2A (Google ADK `RemoteA2aAgent`, or any A2A client) | gateway, `a2a` upstream and `gateway --a2a` | yes | | stand-in A2A agents in both wire formats; ADK's own `to_a2a` and `RemoteA2aAgent` in the Python suite; [usage.md](docs/usage.md#the-gateway-as-an-a2a-agent) |
|
|
120
128
|
|
|
121
|
-
The framework packages are optional peer dependencies. Each adapter imports only from its own package.
|
|
129
|
+
The framework packages, `pg`, and `@node-saml/node-saml` (for SAML sign-in to the portal) are optional peer dependencies. Each adapter imports only from its own package.
|
|
122
130
|
|
|
123
131
|
## One tool call, end to end
|
|
124
132
|
|
|
@@ -181,7 +189,7 @@ Every field carries a provenance label. This is the design decision that matters
|
|
|
181
189
|
bun install # from the repository root, once for the workspace
|
|
182
190
|
cd packages/receipts
|
|
183
191
|
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
|
|
192
|
+
node examples/01-keys-and-signing.ts # first of thirty-one step-by-step examples, see docs/tutorials.md
|
|
185
193
|
bun run test # this package; `bun run test` at the root runs every package
|
|
186
194
|
```
|
|
187
195
|
|
|
@@ -234,7 +242,8 @@ src/config.ts gateway and SDK config schemas, path resolution
|
|
|
234
242
|
src/crypto.ts canonical JSON, sha256, Ed25519 keys, DSSE sign/verify
|
|
235
243
|
src/log.ts Merkle log: append, root, inclusion and consistency proofs, verify, JSONL persistence
|
|
236
244
|
src/log-check.ts the outside monitor: verifies the head, checkpoints, and witness of a running log
|
|
237
|
-
src/portal.ts the tenant portal: register, first key, usage against plan, keys, Stripe billing, export, on the log's Postgres
|
|
245
|
+
src/portal.ts the tenant portal: register, first key, usage against plan, keys, Stripe billing, export, member roles, TOTP MFA, single sign-on, on the log's Postgres
|
|
246
|
+
src/sso.ts enterprise sign-in for the portal: OIDC (code and PKCE, id_token checked against the IdP's key set) and SAML 2.0 (signed assertions only, through @node-saml/node-saml)
|
|
238
247
|
src/log-export.ts a tenant's export of their own log, self-checked, as a log file the verifier reads
|
|
239
248
|
src/witness.ts the witness: countersigns the log's checkpoints from another operator's machine, or refuses with an alarm
|
|
240
249
|
src/signer.ts the signer: the log's key in its own process, the key document verifiers fetch
|
|
@@ -242,10 +251,13 @@ src/checkpoints.ts signed heads published on a schedule, to files and to Postgre
|
|
|
242
251
|
src/log-store.ts the log server's backends: the file, and Postgres with tenants, hashed tokens, one writer per tenant, rate limits
|
|
243
252
|
src/log-sink.ts where leaves go: the local file, or a remote log over HTTP; plus the reference log server
|
|
244
253
|
src/policy.ts Cedar evaluation wrapper, fail-closed
|
|
254
|
+
src/simulate.ts replay recorded policy decisions against a proposed Cedar policy, grouped changes and run digest
|
|
245
255
|
src/delegation.ts signed delegation grants
|
|
256
|
+
src/approval.ts exact-action human approvals, distinct trusted signatures, persistent single-use consumption
|
|
246
257
|
src/receipt.ts receipt and authorization statement types and provenance labels
|
|
247
258
|
src/issue.ts sign, log, and write a receipt, or commit an authorization first; shared by both producers
|
|
248
259
|
src/gateway.ts the MCP proxy: a host (key, policy, upstreams, log) and a session per grant; scope check, facts, policy, forward, receipt
|
|
260
|
+
src/operations.ts SQLite operation claims and daily budget reservations, retained across retries and process crashes
|
|
249
261
|
src/gateway-http.ts the gateway over Streamable HTTP: one process, a session per connection, each under the grant it presents
|
|
250
262
|
src/sdk/index.ts the interceptor: policy decision, record, wrap(tool fn)
|
|
251
263
|
src/sdk/claude.ts Claude Code command hook and Claude Agent SDK in-process hooks
|
|
@@ -259,15 +271,15 @@ src/upstream.ts attested execution: an upstream signs its result for the rece
|
|
|
259
271
|
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
272
|
vectors/ conformance vectors: receipts, keys, logs, proofs, and expected verdicts; `bun run vectors` regenerates them
|
|
261
273
|
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
|
|
274
|
+
src/cli.ts keygen, grant, gateway, hook, serve, log, prune, verify, reveal, audit, policy simulate
|
|
263
275
|
src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
|
|
264
276
|
src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
|
|
265
277
|
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/
|
|
278
|
+
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
|
|
279
|
+
examples/ thirty-one 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
280
|
test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
|
|
269
281
|
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
|
|
282
|
+
docs/ tutorials, usage (gateway), codex-recovery (live demo), approvals, sdk, policies, verification
|
|
271
283
|
```
|
|
272
284
|
|
|
273
285
|
## Plan
|
|
@@ -276,6 +288,8 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
|
|
|
276
288
|
|
|
277
289
|
**Done**
|
|
278
290
|
|
|
291
|
+
- Live Codex support recovery demo: model-selected MCP calls, incorrect CRM memory, a reviewed recovery plan, simulated credit compensation, and verified evidence; [guide](docs/codex-recovery.md), with offline regression coverage.
|
|
292
|
+
- 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
293
|
- Gateway: MCP proxy, signed delegation, gateway-fetched facts, Cedar policy, denial receipts, Merkle log, offline verifier.
|
|
280
294
|
- Receipt schema carries the issuer kind, so a verifier reads gateway versus SDK before anything else.
|
|
281
295
|
- SDK core: policy decision, record, and a generic `wrap(tool, fn)` for any framework whose tools are functions.
|
|
@@ -304,7 +318,7 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
|
|
|
304
318
|
- 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
319
|
- 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
320
|
- 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.
|
|
321
|
+
- 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
322
|
- 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
323
|
- 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
324
|
- 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 +326,9 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
|
|
|
312
326
|
- 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
327
|
- 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
328
|
- 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;
|
|
329
|
+
- 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.
|
|
330
|
+
- Enterprise identity for the hosted portal: member roles (`owner`, `admin`, `reviewer`, `readonly`) with invites, TOTP MFA with single-use codes and an operator reset (`log-admin user mfa-reset`), and single sign-on per tenant through the tenant's own IdP, OIDC or SAML 2.0, set by the operator (`log-admin sso set`), with an enforce mode that closes the password, GitHub, and Google paths to members. Revoking an agent's authority mid-session already shipped (`agent-custody revoke`, example 27); example 31 shows the enterprise sign-in and the roles.
|
|
331
|
+
- The [state review console](../state/README.md#explain-one-action): search receipts by transaction, customer, agent or time, read the ten answers, and hand over a portable HTML/JSON case whose signatures, authorizations and inclusion proofs can be verified offline.
|
|
316
332
|
|
|
317
333
|
**Next, in the order it pays off**
|
|
318
334
|
|
|
@@ -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;
|
package/dist/approval.js
ADDED
|
@@ -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
|
-
|
|
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/check.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export interface CheckFinding {
|
|
2
|
+
level: "ok" | "warn" | "error";
|
|
3
|
+
check: string;
|
|
4
|
+
message: string;
|
|
5
|
+
}
|
|
6
|
+
export interface CheckOptions {
|
|
7
|
+
/** start the upstreams and compare tool names with what they offer */
|
|
8
|
+
connect?: boolean;
|
|
9
|
+
/**
|
|
10
|
+
* "check" (the default) requires every credential variable the config names to be set in this process. "skip" is for a
|
|
11
|
+
* process that is not the gateway and deliberately does not hold its credentials, such as the console: they are not
|
|
12
|
+
* checked, and an upstream that needs one is not started.
|
|
13
|
+
*/
|
|
14
|
+
environment?: "check" | "skip";
|
|
15
|
+
/** cancels --connect while it is starting the upstreams; whatever was started is closed */
|
|
16
|
+
signal?: AbortSignal;
|
|
17
|
+
}
|
|
18
|
+
export declare function checkConfig(configPath: string, options?: CheckOptions): Promise<CheckFinding[]>;
|
|
19
|
+
export declare function formatFindings(findings: CheckFinding[]): string;
|