@agent-custody/receipts 0.16.10 → 0.16.11

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 (62) hide show
  1. package/README.md +20 -9
  2. package/dist/approval-requests.d.ts +114 -0
  3. package/dist/approval-requests.js +198 -0
  4. package/dist/approval.d.ts +8 -0
  5. package/dist/approval.js +10 -3
  6. package/dist/check.js +2 -0
  7. package/dist/cli.js +68 -2
  8. package/dist/completeness.d.ts +11 -2
  9. package/dist/completeness.js +45 -9
  10. package/dist/config.d.ts +3 -0
  11. package/dist/config.js +6 -1
  12. package/dist/console-page.js +87 -2
  13. package/dist/console.js +72 -0
  14. package/dist/crypto.d.ts +2 -0
  15. package/dist/crypto.js +2 -1
  16. package/dist/delegation.d.ts +1 -1
  17. package/dist/delegation.js +19 -2
  18. package/dist/did-key.d.ts +2 -0
  19. package/dist/did-key.js +21 -1
  20. package/dist/door-core.d.ts +373 -0
  21. package/dist/door-core.js +743 -0
  22. package/dist/door-worker.d.ts +133 -0
  23. package/dist/door-worker.js +259 -0
  24. package/dist/door.d.ts +11 -293
  25. package/dist/door.js +43 -753
  26. package/dist/gateway-http.d.ts +1 -6
  27. package/dist/gateway-http.js +2 -19
  28. package/dist/gateway.js +24 -3
  29. package/dist/grant-header.d.ts +8 -0
  30. package/dist/grant-header.js +19 -0
  31. package/dist/index.d.ts +3 -2
  32. package/dist/index.js +2 -1
  33. package/dist/issue.d.ts +2 -16
  34. package/dist/issue.js +2 -12
  35. package/dist/log-http.d.ts +37 -0
  36. package/dist/log-http.js +74 -0
  37. package/dist/log-sink.d.ts +3 -37
  38. package/dist/log-sink.js +5 -71
  39. package/dist/log.d.ts +2 -27
  40. package/dist/log.js +2 -173
  41. package/dist/merkle.d.ts +27 -0
  42. package/dist/merkle.js +175 -0
  43. package/dist/object-issuer.d.ts +29 -0
  44. package/dist/object-issuer.js +172 -0
  45. package/dist/receipt-pending.d.ts +16 -0
  46. package/dist/receipt-pending.js +14 -0
  47. package/dist/web-bot-auth.d.ts +26 -6
  48. package/dist/web-bot-auth.js +116 -56
  49. package/docs/approvals.md +33 -0
  50. package/docs/completeness.md +44 -5
  51. package/docs/console.md +11 -4
  52. package/docs/door-quickstart.md +53 -17
  53. package/docs/door-signals.md +5 -5
  54. package/docs/door-worker.md +81 -0
  55. package/docs/door.md +10 -8
  56. package/docs/github-action.md +2 -2
  57. package/docs/tutorials.md +2 -0
  58. package/docs/verification.md +1 -1
  59. package/package.json +3 -1
  60. package/vectors/audit.json +27 -27
  61. package/vectors/canonical.json +5 -5
  62. package/vectors/receipts.json +1645 -1549
package/README.md CHANGED
@@ -7,7 +7,7 @@ Chain of custody for AI agents: a signed receipt for every tool call, checkable
7
7
  Five producers, one receipt format, one verifier.
8
8
 
9
9
  - **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 or Rego policy that fails closed (Rego from a file or from your own OPA server), forwards the call only on allow, and emits a signed receipt appended to a Merkle transparency log.
10
- - **The door** is the gateway turned around: a reverse proxy in front of your own website, API, or forms. Every arrival, a browser, an API client, a crawler, or an agent, is classified by what it presented (a grant signed by a principal you trust, or a Web Bot Auth signature checked against the signer's key directory, makes it `verified`; an assertion the door cannot check is `claimed`; nothing is `unknown`), decided by a Cedar policy for its route, relayed or refused, and receipted either way with the same receipt. A Node site can run the same loop in its own process: `app.use(door("door.json"))` in Express, or a wrapper around a Next.js route handler ([the door in your Node app](docs/door-middleware.md)). A site in Go, Rails, Django, or Spring asks a door in authz mode from a middleware ([the door in Go, Rails, Django, and Spring](docs/door-languages.md)). A partner detection engine (Cloudflare Bot Management, HUMAN, DataDome, behind an adapter that holds a key) can sign its verdict for each arrival, and the policy reads it and the receipt carries it, attested. It is the first piece of an agent front door; it does not yet detect agents in web traffic itself, and says so ([the door](docs/door.md)).
10
+ - **The door** is the gateway turned around: a reverse proxy in front of your own website, API, or forms. Every arrival, a browser, an API client, a crawler, or an agent, is classified by what it presented (a grant signed by a principal you trust, or a Web Bot Auth signature checked against the signer's key directory, makes it `verified`; an assertion the door cannot check is `claimed`; nothing is `unknown`), decided by a Cedar policy for its route, relayed or refused, and receipted either way with the same receipt. A Node site can run the same loop in its own process: `app.use(door("door.json"))` in Express, or a wrapper around a Next.js route handler ([the door in your Node app](docs/door-middleware.md)). A site in Go, Rails, Django, or Spring asks a door in authz mode from a middleware ([the door in Go, Rails, Django, and Spring](docs/door-languages.md)). A site already on Cloudflare runs the same decision at the edge, as a Worker that receipts to an R2 bucket and the hosted log ([the door as a Cloudflare Worker](docs/door-worker.md)). A partner detection engine (Cloudflare Bot Management, HUMAN, DataDome, behind an adapter that holds a key) can sign its verdict for each arrival, and the policy reads it and the receipt carries it, attested. It is the first piece of an agent front door; it does not yet detect agents in web traffic itself, and says so ([the door](docs/door.md)).
11
11
  - **The egress witness** covers the calls that go around the gateway. Under egress lockdown, a locked-down agent's network reaches only the gateway and the witness. The witness is a forward proxy: it identifies the agent by the proxy credential it checked, lets a Cedar or Rego policy decide per destination, relays or refuses the connection, and receipts it either way (issuer kind `egress`). It records the destination, the times, and the byte counts. It never records a payload, because there is no TLS interception. It sees nothing when lockdown is off, and it relays no protocol other than HTTP. A receipt is an observed bypass, not a record of what was done.
12
12
  - **The ACS Guardian**, a spike, answers an agent that asks before it acts over the OWASP Agent Control Standard: it decides `steps/toolCallRequest` and `steps/toolCallResult` by a Cedar policy and receipts each decision (issuer kind `guardian`). It carries out nothing, and the agent chooses to ask and to obey, so a receipt proves the decision, not that the call ran or did not ([the ACS Guardian](docs/acs.md)).
13
13
  - **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.
@@ -29,14 +29,14 @@ Anyone holding the public keys can verify a receipt offline. The agent is not tr
29
29
  - [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
30
30
  - [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
31
31
  - [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
32
- - [Human approvals](docs/approvals.md): short-lived signatures over the exact action, two-person thresholds, single-use enforcement, and offline verification
32
+ - [Human approvals](docs/approvals.md): short-lived signatures over the exact action, two-person thresholds, single-use enforcement, offline verification, and approval requests that the gateway leaves for a person to sign from the command line
33
33
  - [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
34
34
  - [Writing policies](docs/policies.md): how a tool call becomes a Cedar request or Rego input, with tested examples, a Rego file against an OPA server, and replaying history against a proposed policy with `policy simulate`
35
35
  - [Verifying a receipt](docs/verification.md): what each check means and what a verified receipt does and does not prove
36
36
  - [What the evidence satisfies](docs/compliance.md): the receipts, packs, and certificates mapped to SOC 2, ISO 27001, UK GDPR, the EU AI Act, FINRA, MAS, Colorado, DORA, the CSA AI Controls Matrix, the OWASP agentic guidance, and ISO/IEC 42001. Each regulation has a primary source, an "as of" date, and a list of what a receipt does not supply
37
37
  - [Anchoring the log on a chain](docs/anchoring.md): the log's checkpoints committed to Ethereum mainnet, or another EVM chain the installation picks, from a published address, what that proves and what it does not, running the anchor, and `log-check` against the chain
38
38
  - [Receipts on a pull request](docs/github-action.md): the GitHub Action that verifies a directory of receipt bundles and posts one table on the pull request, the workflow file to copy, the `export` command that copies the receipts into the branch, and why a committed receipt publishes the call unless a capture rule withholds it
39
- - [Completeness](docs/completeness.md): an auditor's read-only key lists the provider's objects and matches each to a verified receipt, so an action taken outside the gateway shows up, for Stripe and for GitHub
39
+ - [Completeness](docs/completeness.md): an auditor's read-only key lists the provider's objects and matches each to a verified receipt, so an action taken outside the gateway shows up, for Stripe and for GitHub. A Stripe object that a site behind the door made is matched to its door receipt
40
40
  - [Payment mandates and agent identity](docs/mandates.md): the design for fitting grants and receipts to Google's AP2 mandates, Visa's Trusted Agent Protocol and Mastercard Agent Pay; not yet built
41
41
  - [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
42
42
  - [What a receipt costs](docs/performance.md): each step of the issuer's hot path in microseconds, measured with `bun run bench`, what is and is not fsynced, and where the time goes
@@ -151,6 +151,7 @@ Every receipt names its issuer, and the verifier prints what that issuer kind is
151
151
  | 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) |
152
152
  | a site any agent arrives at, built on Express or Connect | door, in-process | `app.use(door("door.json"))` | | Express 5.2.1 with `express.json()`, `express.urlencoded()`, and a raw stream read after the door; [guide](docs/door-middleware.md) |
153
153
  | a site any agent arrives at, built on Go `net/http`, Rails (Rack), Django (or WSGI), or Spring | door, authz mode, asked by a middleware | `Door(url, timeout)(handler)`, `AgentCustody::Door`, `DoorMiddleware` / `DoorWSGI`, `CustodyDoor` with a filter | | each example against a live door: Go through `ServeHTTP`, Rack with a Rack env, WSGI under `wsgiref`, Django with a stand-in request and `HttpResponse`, the JDK `HttpServer` filter; the Spring filter is a doc snippet, not compiled; [guide](docs/door-languages.md) |
154
+ | a site any agent arrives at, served through Cloudflare | door, as a Worker at the edge | `deploy/door/cloudflare-worker`, `wrangler deploy` | | the Worker bundle `wrangler deploy` builds, run in workerd (Miniflare) with stand-ins for the origin, the log, and a key directory; `wrangler deploy --dry-run` by hand; not yet a deployment to Cloudflare itself; [guide](docs/door-worker.md) |
154
155
  | a site any agent arrives at, built on Next.js (App Router) | door, in-process | `guard.route(handler)` on each route handler | | fetch `Request` and `Response` objects in the tests; by hand, a fresh `create-next-app` (Next.js 16.4.6) under `next dev` and `next start`; [guide](docs/door-middleware.md) |
155
156
 
156
157
  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.
@@ -267,6 +268,7 @@ If a vendor tells you their receipts prove more than the first five rows, ask th
267
268
  ```
268
269
  src/config.ts gateway and SDK config schemas, path resolution
269
270
  src/crypto.ts canonical JSON, sha256, Ed25519 keys, DSSE sign/verify
271
+ src/merkle.ts RFC 6962 / RFC 9162 Merkle hashing, inclusion and consistency proofs and their checks: pure functions, re-exported by log.ts
270
272
  src/log.ts Merkle log: append, root, inclusion and consistency proofs, verify, JSONL persistence; a lock file makes an append safe when several processes share one log file, and a partial last line from a killed writer is moved to `<file>.torn`
271
273
  src/lock.ts the one lock file design (owner token, liveness check, rename to break a stale lock) that the local log, prune, and the gateway outbox share
272
274
  src/log-check.ts the outside monitor: verifies the head, checkpoints, witness, and anchor of a running log
@@ -283,7 +285,8 @@ src/export.ts `export`: verified receipt bundles that keep their values pri
283
285
  src/signer.ts the signer: the log's key in its own process, the key document verifiers fetch
284
286
  src/checkpoints.ts signed heads published on a schedule, to files and to Postgres
285
287
  src/log-store.ts the log server's backends: the file, and Postgres with tenants, hashed tokens, one writer per tenant, rate limits
286
- src/log-sink.ts where leaves go: the local file, or a remote log over HTTP; plus the reference log server
288
+ src/log-http.ts the sink interface and a remote log over HTTP, every answer checked before it is taken; apart from the file log so a Worker can append
289
+ src/log-sink.ts where leaves go: the local file, or a remote log over HTTP (log-http.ts); plus the reference log server
287
290
  src/policy.ts Cedar evaluation wrapper, fail-closed
288
291
  src/policy-rego.ts Rego: compiled with opa build, evaluated in-process with the OPA WebAssembly SDK, fail-closed
289
292
  src/opa-server.ts an OPA server's Data API as the policy, with bundle revisions as the digest
@@ -292,15 +295,21 @@ src/delegation.ts signed delegation grants
292
295
  src/did-key.ts did:key identifiers for Ed25519 keys (base58btc, multicodec 0xed01): an agent named by its key in a grant
293
296
  src/revocation.ts the revoked-grants file the gateway and the door share: re-read when it changes, written by rename
294
297
  src/approval.ts exact-action human approvals, distinct trusted signatures, persistent single-use consumption
298
+ src/approval-requests.ts human in the loop: the requests a gateway leaves for calls with no approval, signed by an approver and picked up on retry
295
299
  src/receipt.ts receipt and authorization statement types and provenance labels
296
300
  src/issue.ts sign, log, and write a receipt, or commit an authorization first; shared by every producer
301
+ src/receipt-pending.ts what an issuer throws when a receipt's log append is pending, and what a flush of the outbox did
297
302
  src/gateway.ts the MCP proxy: a host (key, policy, upstreams, log) and a session per grant; scope check, facts, policy, forward, receipt
298
303
  src/operations.ts SQLite operation claims and daily budget reservations, retained across retries and process crashes
299
304
  src/gateway-http.ts the gateway over Streamable HTTP: one process, a session per connection, each under the grant it presents
300
- src/door.ts the door: a reverse proxy in front of your own HTTP surface, or the authz check behind nginx and Envoy; every arrival classified, decided per route, relayed or refused, receipted as issuer kind door; its decision loop is shared with door-app.ts
305
+ src/grant-header.ts how an agent presents a grant over HTTP (`X-Agent-Custody-Grant` or `Authorization: Bearer`), shared by the HTTP gateway and the door
306
+ src/door-core.ts the door's decision apart from where it runs: classify, decide, relay with fetch, receipt; its key, policy, revocation list, secrets, and issuer come in a `DoorIO`, so the same code runs in Node and at the edge
307
+ src/door.ts the door in Node: a reverse proxy in front of your own HTTP surface, or the authz check behind nginx and Envoy, over door-core.ts with a `DoorIO` read from the config's files; every arrival classified, decided per route, relayed or refused, receipted as issuer kind door; its decision loop is shared with door-app.ts
308
+ src/door-worker.ts the door as a Cloudflare Worker: its DoorIO from the Worker's bindings (key secret, policy and config variables, R2 and the log), the fetch and cron handlers, Cloudflare Bot Management as an observed fact, and the Durable Object (`DoorNonce`) that keeps Web Bot Auth nonces for every isolate
309
+ src/object-issuer.ts the receipt issuer over an object store (R2): bundles, authorizations, salts, and the outbox, by the file issuer's rules
301
310
  src/door-form.ts the form protector: the script the door serves at /.well-known/agent-custody-door/form.js, from its challenge config
302
311
  src/door-app.ts the door in-process (`@agent-custody/receipts/door`): Express or Connect middleware and a fetch route-handler wrapper (Next.js), over the same decision loop
303
- src/web-bot-auth.ts the door's Web Bot Auth check: RFC 9421 signature base, RFC 8941 dictionaries, Ed25519, the signer's key directory fetched and cached, nonces
312
+ src/web-bot-auth.ts the door's Web Bot Auth check: RFC 9421 signature base, RFC 8941 dictionaries, Ed25519, the signer's key directory fetched and cached, nonces in a store (one process's memory unless the door is given another); a did:key keyid checked against its own key
304
313
  src/door-partner.ts the door's partner engine slot: asks a detection engine about an arrival, accepts only a verdict signed for that receipt and route (the upstream attestation format), and `signVerdict` for engines
305
314
  src/egress.ts the egress witness: a forward proxy (CONNECT and plain HTTP, no TLS interception) for calls around the gateway; agent by proxy credential, decided per destination, receipted as issuer kind egress
306
315
  src/egress-draft.ts `egress draft-policy`: a first egress policy from verified observe-mode receipts, one permit per agent and scheme over the destinations it used, for review
@@ -324,7 +333,7 @@ src/cli.ts keygen, grant, gateway, door, egress, egress draft-policy, ac
324
333
  src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
325
334
  src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
326
335
  tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
327
- scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, a fake partner detection engine for the door (`fake-partner.ts`, signs its verdicts), fixture builders for gateway, SDK, door (with a stand-in origin), and the egress witness (with a stand-in destination), 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, the site's numbers (`bench.ts`), and the per-step hot-path benchmark (`hot-path-bench.ts`, `bun run bench`)
336
+ scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, a fake partner detection engine for the door (`fake-partner.ts`, signs its verdicts), the door Worker's build for workerd (`build-door-worker.ts`, also wrangler's build command), fixture builders for gateway, SDK, door (with a stand-in origin), and the egress witness (with a stand-in destination), 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, the site's numbers (`bench.ts`), and the per-step hot-path benchmark (`hot-path-bench.ts`, `bun run bench`)
328
337
  examples/ runnable tutorials, plus examples/languages/: Python, Go, Java, and Rust clients of the sidecar, and in door/ the Go, Rack, Django and WSGI, and JDK middleware clients of the door's authz check, run by the test suite, one per aspect; each is run by the test suite
329
338
  test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
330
339
  adapter tests against the real packages, and tests that run every policy in docs/policies.md and site/guide/egress-policies.md
@@ -337,7 +346,8 @@ The design is several producers feeding one verifier. The SDK is the top of the
337
346
 
338
347
  **Done**
339
348
 
340
- - did:key identity on grants (#255): a grant may name its agent by the did:key of its Ed25519 key (`grant --agent-key agent.pub --did-key`). The door checks that the identifier decodes and agrees with the grant's `agentKey`; a grant that does not is `claimed`, one that does is `verified` with the did:key as the agent ([a did:key agent](docs/door.md#a-did-key-agent), tutorial 55).
349
+ - The door as a Cloudflare Worker (#387): `deploy/door/cloudflare-worker` puts the door's own decision loop at Cloudflare's edge. The key is a Worker secret; the config and the policy are variables; receipts go to an R2 bucket and the hosted log. A request that can change something reaches the origin only once both have its authorization. A safe request's receipt waits in the bucket's outbox when the log is down, and a cron trigger appends it. Web Bot Auth and grants are checked as at any door, with each nonce in a Durable Object that every isolate reaches, so a signature replayed to another isolate is refused; Cloudflare Bot Management enters as an observed fact. The bundle `wrangler deploy` builds is tested in workerd, and its receipts verify with `agent-custody verify` ([the door as a Cloudflare Worker](docs/door-worker.md), tutorial 56). A run against Cloudflare itself is still to be recorded.
350
+ - did:key identity on grants (#255): a grant may name its agent by the did:key of its Ed25519 key (`grant --agent-key agent.pub --did-key`). The door checks that the identifier decodes and agrees with the grant's `agentKey`; a grant that does not is `claimed`, one that does is `verified` with the did:key as the agent ([a did:key agent](docs/door.md#a-did-key-agent), tutorial 55). The gateway and the three verifiers run the same check (#405): the gateway refuses such a grant when the session opens, and a verifier fails `delegation signature (principal key)`. A request signature (RFC 9421) whose `keyid` is the did:key binds the grant to its sender (#406, [a did:key signature](docs/door.md#a-did-key-signature)).
341
351
  - The form protector (svayatta/pm#14): with `challenge` configured, the door serves `/.well-known/agent-custody-door/form.js`, and one script tag on a page puts the Turnstile or hCaptcha widget in its same-origin POST forms. The script sends each form with the token in the door's header and follows the answer as a form post would, so a static site's form reaches its backend with a receipt id, and a direct post with no token is refused ([protecting a form with one line](docs/door.md#protecting-a-form-with-one-line), tutorial 54).
342
352
  - The door for sites that are not Node (svayatta/pm#4): standard-library middleware for Go `net/http`, Rack (Rails), Django and WSGI, and the JDK `HttpServer`, in `examples/languages/door/`, each a client of the door's authz check. It forwards the method, path, query, and headers, runs the app only on the door's 200 with the receipt id and class in the request and the grant removed, returns any refusal as the door gave it, and answers 503 when the door cannot be reached or does not answer in time. A Spring `OncePerRequestFilter` around the same Java client is a doc snippet, not compiled by the tests ([the door in Go, Rails, Django, and Spring](docs/door-languages.md)).
343
353
  - The door's partner engine slot (svayatta/pm#13): with `partner` in the door config, the door asks a detection engine (Cloudflare Bot Management, HUMAN, DataDome, behind an adapter that holds an Ed25519 key) about each arrival on the listed routes, naming the receipt it is writing. The engine signs its verdict for that receipt and route in the upstream attestation format; only a verdict whose signature verifies under the configured key reaches the policy, as `context.facts.partner`, and lands in the receipt as an attested fact, checked again by all three verifiers with `--upstream-key`. A verdict for another arrival is refused, and an engine that is down, slow, or signs wrongly never becomes an allow: the arrival is refused with 503 (`onFailure: "deny"`, the default) or the policy decides without the fact (`"absent"`) ([the door](docs/door.md#a-partner-engines-verdict), tutorial 52).
@@ -357,6 +367,7 @@ The design is several producers feeding one verifier. The SDK is the top of the
357
367
  - Strict mode: `"strict": true` refuses a local log, a log that is not hash-only, and a log without pinned keys; precommits every tool, in observe mode too; and turns the outbox off. No call the agent makes is forwarded before its authorization is in a log the operator does not run, every receipt says `issuer.strict`, and `verify --require-strict` requires it ([usage](docs/usage.md#strict-mode), tutorial 34). [Issue #177](https://github.com/svayatta/agent-custody/issues/177).
358
368
  - Policy reload: the gateway re-reads `policy.cedar` whenever it changes and applies it from the next call, with no restart and no dropped session; a policy that does not parse is refused and the one in force stays, and every change or refusal is recorded in `receipts/policy-reloads.jsonl` ([usage](docs/usage.md)).
359
369
  - 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.
370
+ - Human in the loop (issue #428): a protected call with no approval leaves a request; the console's Approvals tab or `agent-custody approvals` lists it, shows the exact arguments, and signs it with the approver's own key, in their browser or at the command line; the same call sent again is forwarded once, and the receipt carries the approval. The request directory is untrusted: only an envelope that verifies and binds the call is used. [Guide](docs/approvals.md#ask-a-person-approval-requests), tutorial 57.
360
371
  - 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.
361
372
  - Gateway: MCP proxy, signed delegation, gateway-fetched facts, Cedar policy, denial receipts, Merkle log, offline verifier.
362
373
  - Receipt schema carries the issuer kind, so a verifier reads gateway versus SDK before anything else.
@@ -399,7 +410,7 @@ The design is several producers feeding one verifier. The SDK is the top of the
399
410
  - 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.
400
411
  - A log outage after an ordinary call (issue #149): the signed receipt waits in `receipts/outbox/` and the gateway appends it when the log is back, the agent gets the real outcome marked `log-pending`, `GET /health` counts the pending receipts, and `requirePrecommit` refuses a remote log with an empty `precommit`. The [failure table](docs/usage.md#when-the-log-fails) gives each case.
401
412
  - The anchor (issue #176): `agent-custody anchor` proves each new checkpoint extends the last one it anchored, then commits a Merkle root over them in one transaction from its address to itself, on Ethereum by default or on Base, Arbitrum, Optimism, Polygon, or any EVM chain by id (`--chain`), with a fee cap sized per chain. It publishes each log's record and inclusion proof, sends nothing for an idle log, skips a run above a fee cap, and never has two transactions in flight. Every transaction covers every watched log, and a transaction counts only once its block is finalized, following reorgs. `log-check --anchor-url` checks the record against one or more JSON-RPC endpoints, requires the log id the verifier pinned and the address's newest transaction, and checks the log's head against the anchored checkpoint, so a rewritten or rolled-back tree is caught from the chain alone ([anchoring](docs/anchoring.md), example 33).
402
- - Completeness from the provider's side (issue #178): `agent-custody completeness` lists Stripe's refunds, payouts, or transfers over a window with the auditor's own read-only key, and matches each to a verified receipt by the provider's object id. It reports actions with no receipt, receipts the provider does not have, amount, currency, and beneficiary mismatches, calls forwarded without an outcome receipt, and receipts it cannot match ([completeness](docs/completeness.md), example 35). `--provider github` does the same check over one repository's pushes, merged pull requests, or releases, matched by the commit or the release id that the receipt's result carries (example 53).
413
+ - Completeness from the provider's side (issue #178): `agent-custody completeness` lists Stripe's refunds, payouts, or transfers over a window with the auditor's own read-only key, and matches each to a verified receipt by the provider's object id. It reports actions with no receipt, receipts the provider does not have, amount, currency, and beneficiary mismatches, calls forwarded without an outcome receipt, and receipts it cannot match ([completeness](docs/completeness.md), example 35). `--provider github` does the same check over one repository's pushes, merged pull requests, or releases, matched by the commit or the release id that the receipt's result carries (example 53). A Stripe object made through a door-protected site is matched to its door receipt by the receipt id that the origin copies into the object's metadata, and each match names the receipt kind (issue #262).
403
414
 
404
415
  **Next, in the order it pays off**
405
416
  <!-- #region receipts-next -->
@@ -0,0 +1,114 @@
1
+ import { z } from "zod";
2
+ import { type ApprovalBinding } from "./approval.ts";
3
+ import { type Envelope, type KeyPair, type PublicKeyRef } from "./crypto.ts";
4
+ /** Where a refusal names the request it opened: `{ requestId, status }` in the result's `_meta`. */
5
+ export declare const APPROVAL_REQUEST_META_KEY = "agent-custody/approval-request";
6
+ declare const RequestSchema: z.ZodObject<{
7
+ version: z.ZodLiteral<"0.1">;
8
+ requestId: z.ZodString;
9
+ createdAt: z.ZodISODateTime;
10
+ binding: z.ZodObject<{
11
+ principal: z.ZodString;
12
+ agent: z.ZodString;
13
+ tool: z.ZodString;
14
+ args: z.ZodRecord<z.ZodString, z.ZodUnknown>;
15
+ fields: z.ZodOptional<z.ZodObject<{
16
+ amount: z.ZodOptional<z.ZodString>;
17
+ currency: z.ZodOptional<z.ZodString>;
18
+ beneficiary: z.ZodOptional<z.ZodString>;
19
+ }, z.core.$strict>>;
20
+ }, z.core.$strict>;
21
+ argsDigest: z.ZodString;
22
+ requiredApprovers: z.ZodUnion<readonly [z.ZodLiteral<1>, z.ZodLiteral<2>]>;
23
+ receiptId: z.ZodString;
24
+ status: z.ZodEnum<{
25
+ approved: "approved";
26
+ denied: "denied";
27
+ pending: "pending";
28
+ }>;
29
+ envelope: z.ZodOptional<z.ZodObject<{
30
+ payloadType: z.ZodString;
31
+ payload: z.ZodString;
32
+ signatures: z.ZodArray<z.ZodObject<{
33
+ keyid: z.ZodString;
34
+ sig: z.ZodString;
35
+ }, z.core.$strict>>;
36
+ }, z.core.$strict>>;
37
+ decidedAt: z.ZodOptional<z.ZodISODateTime>;
38
+ reason: z.ZodOptional<z.ZodString>;
39
+ }, z.core.$strict>;
40
+ export type ApprovalRequest = z.infer<typeof RequestSchema>;
41
+ /** One request per exact call: the same principal, agent, tool, field mapping, and arguments always name the same request. */
42
+ export declare function approvalRequestId(binding: ApprovalBinding): string;
43
+ /** The request, or undefined when there is none or the file is not a request. */
44
+ export declare function readApprovalRequest(dir: string, requestId: string): ApprovalRequest | undefined;
45
+ /** Every request in the directory, oldest first. Files that are not requests are skipped. */
46
+ export declare function listApprovalRequests(dir: string): ApprovalRequest[];
47
+ export type ApprovalPickup = {
48
+ envelope: Envelope;
49
+ requestId: string;
50
+ } | {
51
+ requestId: string;
52
+ status: "pending" | "denied";
53
+ previous?: string;
54
+ };
55
+ /**
56
+ * The gateway's side, for a protected call that came without an approval. An approved request whose envelope `usable`
57
+ * accepts, and that `usedDir` has not consumed, gives its envelope. A pending or denied request is reported as it is.
58
+ * Anything else (no request, a file that is not one, an approval used or no longer accepted) opens a new pending
59
+ * request; `previous` says why an approved one was not taken.
60
+ */
61
+ export declare function pickupApproval(dir: string, usedDir: string, binding: ApprovalBinding, requiredApprovers: 1 | 2, receiptId: string, at: string, usable: (envelope: Envelope) => {
62
+ ok: true;
63
+ } | {
64
+ ok: false;
65
+ error: string;
66
+ }): ApprovalPickup;
67
+ /**
68
+ * The approver's side: sign the request's exact call with `key`. The first signature sets the expiry (`expiresAt`); a
69
+ * second approver countersigns the same payload, whose expiry was set by the first. The request is approved once it
70
+ * carries `requiredApprovers` distinct keys. The key stays where this runs; only the signed envelope is written, and
71
+ * only after the checks of `signApprovalRequest`.
72
+ */
73
+ export declare function approveApprovalRequest(dir: string, requestId: string, key: KeyPair, opts: {
74
+ expiresAt: string;
75
+ trusted: PublicKeyRef[];
76
+ at?: string;
77
+ maxLifetimeSeconds?: number;
78
+ }): ApprovalRequest;
79
+ /** When the approval a request carries stops being valid, read from its signed payload. */
80
+ export declare function approvalRequestExpiresAt(request: ApprovalRequest): string | undefined;
81
+ /**
82
+ * What an approver signs for a pending request, when the signing happens elsewhere (the console signs in the browser):
83
+ * the payload already signed once under a two-person rule, or a new statement expiring at `expiresAt`, and the DSSE
84
+ * bytes a signature is made over. Nothing is written until `signApprovalRequest` gets a signature that verifies.
85
+ */
86
+ export declare function approvalRequestPayload(dir: string, requestId: string, opts: {
87
+ expiresAt: string;
88
+ at?: string;
89
+ }): {
90
+ payloadType: string;
91
+ payload: string;
92
+ pae: string;
93
+ signedBy: string[];
94
+ };
95
+ /**
96
+ * Add a signature. It is kept only if it verifies with a trusted key and its payload binds this request's exact call,
97
+ * inside the lifetime cap: the same checks the gateway makes. A countersignature is added only to an envelope whose
98
+ * signature already passes them: the directory is untrusted, and a payload planted there must never get a second
99
+ * signature for a call nobody reviewed.
100
+ */
101
+ export declare function signApprovalRequest(dir: string, requestId: string, sig: {
102
+ payload: string;
103
+ keyid: string;
104
+ sig: string;
105
+ }, trusted: PublicKeyRef[], opts?: {
106
+ at?: string;
107
+ maxLifetimeSeconds?: number;
108
+ }): ApprovalRequest;
109
+ /** The approver's side: refuse the request. The gateway keeps refusing that exact call, and says so, until the request is deleted. */
110
+ export declare function denyApprovalRequest(dir: string, requestId: string, opts?: {
111
+ reason?: string;
112
+ at?: string;
113
+ }): ApprovalRequest;
114
+ export {};
@@ -0,0 +1,198 @@
1
+ // Human in the loop for signed approvals. A protected call that arrives without an approval leaves a request
2
+ // here; an approver reviews it and signs it with their own key (`agent-custody approvals approve`); the same call sent
3
+ // again picks the signed envelope up. The directory is untrusted storage: the gateway verifies every envelope it takes
4
+ // from it exactly as it verifies one an agent sends in `_meta`, so a write to it can do no more than an agent can.
5
+ import { randomUUID, sign } from "node:crypto";
6
+ import { mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
7
+ import { join } from "node:path";
8
+ import { z } from "zod";
9
+ import { APPROVAL_TYPE, approvalConsumed, approvalStatement, verifyApproval } from "./approval.js";
10
+ import { canonicalize, digestOf, pae, sha256Hex } from "./crypto.js";
11
+ /** Where a refusal names the request it opened: `{ requestId, status }` in the result's `_meta`. */
12
+ export const APPROVAL_REQUEST_META_KEY = "agent-custody/approval-request";
13
+ const Nonempty = z.string().min(1);
14
+ const Timestamp = z.iso.datetime({ offset: true });
15
+ const RequestId = z.string().regex(/^[0-9a-f]{32}$/);
16
+ const RequestSchema = z.strictObject({
17
+ version: z.literal("0.1"),
18
+ requestId: RequestId,
19
+ createdAt: Timestamp,
20
+ binding: z.strictObject({
21
+ principal: Nonempty,
22
+ agent: Nonempty,
23
+ tool: Nonempty,
24
+ args: z.record(z.string(), z.unknown()),
25
+ fields: z.strictObject({ amount: Nonempty.optional(), currency: Nonempty.optional(), beneficiary: Nonempty.optional() }).optional(),
26
+ }),
27
+ argsDigest: z.string().regex(/^[0-9a-f]{64}$/),
28
+ requiredApprovers: z.union([z.literal(1), z.literal(2)]),
29
+ /** the receipt of the refused call that opened the request */
30
+ receiptId: Nonempty,
31
+ status: z.enum(["pending", "approved", "denied"]),
32
+ /** the approval signed so far: one signature while a two-person rule waits for the second */
33
+ envelope: z.strictObject({ payloadType: Nonempty, payload: Nonempty, signatures: z.array(z.strictObject({ keyid: Nonempty, sig: Nonempty })).min(1) }).optional(),
34
+ decidedAt: Timestamp.optional(),
35
+ /** why an approver denied it */
36
+ reason: z.string().max(1000).optional(),
37
+ });
38
+ /** One request per exact call: the same principal, agent, tool, field mapping, and arguments always name the same request. */
39
+ export function approvalRequestId(binding) {
40
+ const { principal, agent, tool, fields } = binding;
41
+ return sha256Hex(JSON.stringify({ principal, agent, tool, fields: fields ?? null, argsDigest: digestOf(binding.args) })).slice(0, 32);
42
+ }
43
+ const fileOf = (dir, requestId) => join(dir, `${RequestId.parse(requestId)}.json`);
44
+ /** The request, or undefined when there is none or the file is not a request. */
45
+ export function readApprovalRequest(dir, requestId) {
46
+ let text;
47
+ try {
48
+ text = readFileSync(fileOf(dir, requestId), "utf8");
49
+ }
50
+ catch {
51
+ return undefined;
52
+ }
53
+ try {
54
+ const parsed = RequestSchema.safeParse(JSON.parse(text));
55
+ return parsed.success && parsed.data.requestId === requestId ? parsed.data : undefined;
56
+ }
57
+ catch {
58
+ return undefined;
59
+ }
60
+ }
61
+ /** Every request in the directory, oldest first. Files that are not requests are skipped. */
62
+ export function listApprovalRequests(dir) {
63
+ let names;
64
+ try {
65
+ names = readdirSync(dir);
66
+ }
67
+ catch {
68
+ return [];
69
+ }
70
+ return names
71
+ .filter((n) => /^[0-9a-f]{32}\.json$/.test(n))
72
+ .map((n) => readApprovalRequest(dir, n.slice(0, 32)))
73
+ .filter((r) => r !== undefined)
74
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt));
75
+ }
76
+ function write(dir, request) {
77
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
78
+ const file = fileOf(dir, request.requestId);
79
+ const tmp = `${file}.${randomUUID()}.tmp`;
80
+ writeFileSync(tmp, JSON.stringify(request, null, 2) + "\n", { mode: 0o600 });
81
+ renameSync(tmp, file);
82
+ return request;
83
+ }
84
+ /**
85
+ * The gateway's side, for a protected call that came without an approval. An approved request whose envelope `usable`
86
+ * accepts, and that `usedDir` has not consumed, gives its envelope. A pending or denied request is reported as it is.
87
+ * Anything else (no request, a file that is not one, an approval used or no longer accepted) opens a new pending
88
+ * request; `previous` says why an approved one was not taken.
89
+ */
90
+ export function pickupApproval(dir, usedDir, binding, requiredApprovers, receiptId, at, usable) {
91
+ const requestId = approvalRequestId(binding);
92
+ const found = readApprovalRequest(dir, requestId);
93
+ let previous;
94
+ // a denial's reason is the file's free text: the gateway reports that the call was denied, not what the file says
95
+ if (found?.status === "denied")
96
+ return { requestId, status: "denied" };
97
+ if (found?.status === "pending" && found.requiredApprovers === requiredApprovers)
98
+ return { requestId, status: "pending" };
99
+ if (found?.status === "approved" && found.envelope) {
100
+ const env = found.envelope;
101
+ const id = approvalIdOf(env);
102
+ const checked = usable(env);
103
+ if (id && approvalConsumed(usedDir, id))
104
+ previous = "has been used";
105
+ else if (!checked.ok)
106
+ previous = `was not accepted: ${checked.error}`;
107
+ else
108
+ return { envelope: env, requestId };
109
+ }
110
+ write(dir, { version: "0.1", requestId, createdAt: at, binding: structuredClone(binding), argsDigest: digestOf(binding.args), requiredApprovers, receiptId, status: "pending" });
111
+ return { requestId, status: "pending", ...(previous ? { previous } : {}) };
112
+ }
113
+ function approvalIdOf(env) {
114
+ try {
115
+ const id = JSON.parse(Buffer.from(env.payload, "base64").toString("utf8")).approvalId;
116
+ return typeof id === "string" ? id : undefined;
117
+ }
118
+ catch {
119
+ return undefined;
120
+ }
121
+ }
122
+ function pending(dir, requestId) {
123
+ const request = readApprovalRequest(dir, requestId);
124
+ if (!request)
125
+ throw new Error(`no approval request ${requestId} in ${dir}`);
126
+ if (request.status !== "pending")
127
+ throw new Error(`approval request ${requestId} is already ${request.status}`);
128
+ return request;
129
+ }
130
+ /**
131
+ * The approver's side: sign the request's exact call with `key`. The first signature sets the expiry (`expiresAt`); a
132
+ * second approver countersigns the same payload, whose expiry was set by the first. The request is approved once it
133
+ * carries `requiredApprovers` distinct keys. The key stays where this runs; only the signed envelope is written, and
134
+ * only after the checks of `signApprovalRequest`.
135
+ */
136
+ export function approveApprovalRequest(dir, requestId, key, opts) {
137
+ const at = opts.at ?? new Date().toISOString();
138
+ const p = approvalRequestPayload(dir, requestId, { expiresAt: opts.expiresAt, at });
139
+ const sig = sign(null, Buffer.from(p.pae, "base64"), key.privateKey).toString("base64");
140
+ return signApprovalRequest(dir, requestId, { payload: p.payload, keyid: key.keyid, sig }, opts.trusted, { at, ...(opts.maxLifetimeSeconds !== undefined ? { maxLifetimeSeconds: opts.maxLifetimeSeconds } : {}) });
141
+ }
142
+ /** When the approval a request carries stops being valid, read from its signed payload. */
143
+ export function approvalRequestExpiresAt(request) {
144
+ try {
145
+ const expiresAt = JSON.parse(Buffer.from(request.envelope?.payload ?? "", "base64").toString("utf8")).expiresAt;
146
+ return typeof expiresAt === "string" ? expiresAt : undefined;
147
+ }
148
+ catch {
149
+ return undefined;
150
+ }
151
+ }
152
+ function signed(dir, request, envelope, at) {
153
+ const done = new Set(envelope.signatures.map((s) => s.keyid)).size >= request.requiredApprovers;
154
+ return write(dir, { ...request, envelope, ...(done ? { status: "approved", decidedAt: at } : {}) });
155
+ }
156
+ /**
157
+ * What an approver signs for a pending request, when the signing happens elsewhere (the console signs in the browser):
158
+ * the payload already signed once under a two-person rule, or a new statement expiring at `expiresAt`, and the DSSE
159
+ * bytes a signature is made over. Nothing is written until `signApprovalRequest` gets a signature that verifies.
160
+ */
161
+ export function approvalRequestPayload(dir, requestId, opts) {
162
+ const request = pending(dir, requestId);
163
+ const payload = request.envelope?.payload ?? Buffer.from(canonicalize(approvalStatement({ ...request.binding, issuedAt: opts.at ?? new Date().toISOString(), expiresAt: opts.expiresAt }))).toString("base64");
164
+ return { payloadType: APPROVAL_TYPE, payload, pae: pae(APPROVAL_TYPE, Buffer.from(payload, "base64")).toString("base64"), signedBy: request.envelope?.signatures.map((s) => s.keyid) ?? [] };
165
+ }
166
+ /**
167
+ * Add a signature. It is kept only if it verifies with a trusted key and its payload binds this request's exact call,
168
+ * inside the lifetime cap: the same checks the gateway makes. A countersignature is added only to an envelope whose
169
+ * signature already passes them: the directory is untrusted, and a payload planted there must never get a second
170
+ * signature for a call nobody reviewed.
171
+ */
172
+ export function signApprovalRequest(dir, requestId, sig, trusted, opts = {}) {
173
+ const request = pending(dir, requestId);
174
+ const at = opts.at ?? new Date().toISOString();
175
+ const checks = { at, minApprovers: 1, ...(opts.maxLifetimeSeconds !== undefined ? { maxLifetimeSeconds: opts.maxLifetimeSeconds } : {}) };
176
+ if (request.envelope) {
177
+ if (request.requiredApprovers < 2)
178
+ throw new Error(`approval request ${requestId} needs one approver, yet carries a signature; delete it, and the gateway opens it again on the next call`);
179
+ const first = verifyApproval(request.envelope, trusted, request.binding, checks);
180
+ if (!first.ok)
181
+ throw new Error(`approval request ${requestId} carries a signature that does not stand (${first.error}); delete it, and the gateway opens it again on the next call`);
182
+ }
183
+ if (request.envelope && sig.payload !== request.envelope.payload)
184
+ throw new Error(`approval request ${requestId} already carries a signed payload, and this signature is over another one`);
185
+ if (request.envelope?.signatures.some((s) => s.keyid === sig.keyid))
186
+ throw new Error(`approval request ${requestId} is already signed with key ${sig.keyid}; a second approver must use a different key`);
187
+ const one = { payloadType: APPROVAL_TYPE, payload: sig.payload, signatures: [{ keyid: sig.keyid, sig: sig.sig }] };
188
+ const checked = verifyApproval(one, trusted, request.binding, checks);
189
+ if (!checked.ok)
190
+ throw new Error(`the signature was not accepted: ${checked.error}`);
191
+ return signed(dir, request, request.envelope ? { ...request.envelope, signatures: [...request.envelope.signatures, one.signatures[0]] } : one, at);
192
+ }
193
+ /** The approver's side: refuse the request. The gateway keeps refusing that exact call, and says so, until the request is deleted. */
194
+ export function denyApprovalRequest(dir, requestId, opts = {}) {
195
+ const request = pending(dir, requestId);
196
+ const { envelope: _signedSoFar, ...rest } = request;
197
+ return write(dir, { ...rest, status: "denied", decidedAt: opts.at ?? new Date().toISOString(), ...(opts.reason ? { reason: opts.reason.slice(0, 1000) } : {}) });
198
+ }
@@ -51,6 +51,12 @@ export declare function createApproval(key: KeyPair, input: ApprovalBinding & {
51
51
  issuedAt?: string;
52
52
  expiresAt: string;
53
53
  }): Envelope;
54
+ /** The statement `createApproval` signs, for a signer elsewhere (a browser, a hardware key) to sign the same bytes. */
55
+ export declare function approvalStatement(input: ApprovalBinding & {
56
+ approvalId?: string;
57
+ issuedAt?: string;
58
+ expiresAt: string;
59
+ }): Approval;
54
60
  export type ApprovalVerifyResult = {
55
61
  ok: true;
56
62
  approval: Approval;
@@ -67,6 +73,8 @@ export declare function verifyApproval(envelope: unknown, trusted: PublicKeyRef[
67
73
  minApprovers?: 1 | 2;
68
74
  maxLifetimeSeconds?: number;
69
75
  }): ApprovalVerifyResult;
76
+ /** Whether `consumeApproval` has burned this approval id in `usedDir`. */
77
+ export declare function approvalConsumed(usedDir: string, approvalId: string): boolean;
70
78
  /**
71
79
  * Burn an approval before any side effect. Exclusive creation shares replay protection across processes and restarts.
72
80
  * A subsequent write, log, or upstream failure deliberately leaves the marker in place: retry needs a new approval.
package/dist/approval.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // A short-lived human approval signs the exact action, independently of the agent's delegation grant.
2
2
  import { randomUUID } from "node:crypto";
3
- import { closeSync, fsyncSync, mkdirSync, openSync, realpathSync, writeFileSync } from "node:fs";
3
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, realpathSync, writeFileSync } from "node:fs";
4
4
  import { dirname, join } from "node:path";
5
5
  import { z } from "zod";
6
6
  import { digestOf, dsseSign, dsseVerifiers, sha256Hex } from "./crypto.js";
@@ -85,9 +85,12 @@ function actionFor(input) {
85
85
  }
86
86
  /** Sign the exact arguments and their explicit action fields. A second approver uses dsseCountersign. */
87
87
  export function createApproval(key, input) {
88
+ return dsseSign(APPROVAL_TYPE, approvalStatement(input), key);
89
+ }
90
+ /** The statement `createApproval` signs, for a signer elsewhere (a browser, a hardware key) to sign the same bytes. */
91
+ export function approvalStatement(input) {
88
92
  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);
93
+ return ApprovalSchema.parse({ version: "0.1", approvalId, ...actionFor(binding), issuedAt, expiresAt });
91
94
  }
92
95
  function isBase64(value) {
93
96
  return value.length > 0 && value.length % 4 === 0 && /^[A-Za-z0-9+/]+={0,2}$/.test(value) && Buffer.from(value, "base64").toString("base64") === value;
@@ -151,6 +154,10 @@ export function verifyApproval(envelope, trusted, binding, options = {}) {
151
154
  return { ok: false, error: `invalid approval: ${error instanceof Error ? error.message : "could not verify"}` };
152
155
  }
153
156
  }
157
+ /** Whether `consumeApproval` has burned this approval id in `usedDir`. */
158
+ export function approvalConsumed(usedDir, approvalId) {
159
+ return existsSync(join(usedDir, `${sha256Hex(approvalId.toLowerCase())}.json`));
160
+ }
154
161
  /**
155
162
  * Burn an approval before any side effect. Exclusive creation shares replay protection across processes and restarts.
156
163
  * A subsequent write, log, or upstream failure deliberately leaves the marker in place: retry needs a new approval.
package/dist/check.js CHANGED
@@ -488,6 +488,8 @@ export async function checkConfig(configPath, options = {}) {
488
488
  writes.push(["operations.database", cfg.operations.database]);
489
489
  if (cfg.approvals)
490
490
  writes.push(["approvals.usedDir", cfg.approvals.usedDir]);
491
+ if (cfg.approvals?.requests)
492
+ writes.push(["approvals.requests.dir", cfg.approvals.requests.dir]);
491
493
  if (cfg.logFile)
492
494
  writes.push(["logFile", cfg.logFile]);
493
495
  if (cfg.revokedGrants)