@agent-custody/receipts 0.8.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 CHANGED
@@ -10,9 +10,12 @@ Two producers, one receipt format, one verifier.
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): thirty runnable examples, one per aspect of the code, all executed by the test suite
13
+ - [Tutorials](docs/tutorials.md): thirty-one runnable examples, one per aspect of the code, all executed by the test suite
14
14
  - [Financial operations](docs/financial-operations.md): durable operation ids, provider idempotency keys, atomic daily budget reservations, and reconciliation receipts for uncertain outcomes
15
- - [Usage guide](docs/usage.md): gateway setup, wiring into Claude Desktop, Claude Code, or your own agent loop, and the gateway as an A2A agent between agents that delegate to each other, and private evidence: what the receipt file carries of each call
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
16
19
  - [Human approvals](docs/approvals.md): short-lived signatures over the exact action, two-person thresholds, single-use enforcement, and offline verification
17
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
18
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`
@@ -53,6 +56,8 @@ Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the
53
56
 
54
57
  ## How it fits together
55
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
+
56
61
  ```mermaid
57
62
  flowchart LR
58
63
  P["Principal<br/>(human or org, holds a signing key)"]
@@ -104,6 +109,7 @@ Every receipt names its issuer, and the verifier prints what that issuer kind is
104
109
  | host or framework | producer | enforce + record | record only | tested against |
105
110
  | --- | --- | --- | --- | --- |
106
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) |
107
113
  | Claude Code | SDK | `hook` command, PreToolUse deny | PostToolUse | the documented hook contract, via stdin |
108
114
  | Claude Agent SDK | SDK | `claudeAgentHooks` | same | the same handler |
109
115
  | OpenAI Agents SDK (JS) | SDK | `wrapTools` | `observeRunner` | a real `Runner` with a scripted model |
@@ -120,7 +126,7 @@ Every receipt names its issuer, and the verifier prints what that issuer kind is
120
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) |
121
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) |
122
128
 
123
- 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.
124
130
 
125
131
  ## One tool call, end to end
126
132
 
@@ -183,7 +189,7 @@ Every field carries a provenance label. This is the design decision that matters
183
189
  bun install # from the repository root, once for the workspace
184
190
  cd packages/receipts
185
191
  node scripts/demo.ts # gateway: keys, grant, policy, four tool calls, verification, a tampering attempt; then the SDK wrapping the same tool
186
- node examples/01-keys-and-signing.ts # first of thirty step-by-step examples, see docs/tutorials.md
192
+ node examples/01-keys-and-signing.ts # first of thirty-one step-by-step examples, see docs/tutorials.md
187
193
  bun run test # this package; `bun run test` at the root runs every package
188
194
  ```
189
195
 
@@ -236,7 +242,8 @@ src/config.ts gateway and SDK config schemas, path resolution
236
242
  src/crypto.ts canonical JSON, sha256, Ed25519 keys, DSSE sign/verify
237
243
  src/log.ts Merkle log: append, root, inclusion and consistency proofs, verify, JSONL persistence
238
244
  src/log-check.ts the outside monitor: verifies the head, checkpoints, and witness of a running log
239
- 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)
240
247
  src/log-export.ts a tenant's export of their own log, self-checked, as a log file the verifier reads
241
248
  src/witness.ts the witness: countersigns the log's checkpoints from another operator's machine, or refuses with an alarm
242
249
  src/signer.ts the signer: the log's key in its own process, the key document verifiers fetch
@@ -269,10 +276,10 @@ src/retention.ts pruning the log: leaves become their hashes, bundles are remo
269
276
  src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
270
277
  tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
271
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
272
- examples/ thirty runnable tutorials, plus examples/languages/: Python, Go, Java, and Rust clients of the sidecar, run by the test suite, one per aspect; each is run by the test suite
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
273
280
  test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
274
281
  adapter tests against the real packages, and a test that runs every policy in docs/policies.md
275
- docs/ tutorials, usage (gateway), approvals, sdk, policies, verification
282
+ docs/ tutorials, usage (gateway), codex-recovery (live demo), approvals, sdk, policies, verification
276
283
  ```
277
284
 
278
285
  ## Plan
@@ -281,6 +288,7 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
281
288
 
282
289
  **Done**
283
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.
284
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.
285
293
  - Gateway: MCP proxy, signed delegation, gateway-fetched facts, Cedar policy, denial receipts, Merkle log, offline verifier.
286
294
  - Receipt schema carries the issuer kind, so a verifier reads gateway versus SDK before anything else.
@@ -319,6 +327,8 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
319
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).
320
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.
321
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.
322
332
 
323
333
  **Next, in the order it pays off**
324
334
 
@@ -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;
package/dist/check.js ADDED
@@ -0,0 +1,288 @@
1
+ // `agent-custody check`: what a gateway config would fail on at startup, found before it starts. Static checks read the
2
+ // config, the keys, the policy, the grant, the environment, and the paths; --connect also starts the upstreams, which
3
+ // is where tool-name collisions and unreachable servers show up, and compares every tool name the config mentions with
4
+ // the tools the upstreams actually offer.
5
+ import * as cedar from "@cedar-policy/cedar-wasm/nodejs";
6
+ import { accessSync, constants, existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
7
+ import { tmpdir } from "node:os";
8
+ import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
9
+ import { GatewayConfigSchema, loadConfig } from "./config.js";
10
+ import { generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
11
+ import { delegationValidAt, verifyDelegation } from "./delegation.js";
12
+ import { hasPermitRule } from "./policy.js";
13
+ import { createGatewayHost } from "./gateway.js";
14
+ const distance = (a, b) => {
15
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
16
+ for (let i = 1; i <= a.length; i++) {
17
+ let prev = row[0];
18
+ row[0] = i;
19
+ for (let j = 1; j <= b.length; j++) {
20
+ const keep = row[j];
21
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
22
+ prev = keep;
23
+ }
24
+ }
25
+ return row[b.length];
26
+ };
27
+ /** the nearest existing directory above a path, to ask whether something can be created there */
28
+ function writableAncestor(path) {
29
+ let dir = resolve(path);
30
+ while (!existsSync(dir)) {
31
+ const up = dirname(dir);
32
+ if (up === dir)
33
+ return null;
34
+ dir = up;
35
+ }
36
+ try {
37
+ accessSync(dir, constants.W_OK);
38
+ return dir;
39
+ }
40
+ catch {
41
+ return null;
42
+ }
43
+ }
44
+ function onPath(command) {
45
+ if (isAbsolute(command) || command.includes("/"))
46
+ return existsSync(command);
47
+ return (process.env.PATH ?? "").split(delimiter).some((d) => d && existsSync(join(d, command)));
48
+ }
49
+ export async function checkConfig(configPath, options = {}) {
50
+ const out = [];
51
+ const add = (level, check, message) => out.push({ level, check, message });
52
+ let raw;
53
+ try {
54
+ raw = JSON.parse(readFileSync(configPath, "utf8"));
55
+ }
56
+ catch (e) {
57
+ add("error", "config", `${configPath} is not readable JSON: ${e instanceof Error ? e.message : String(e)}`);
58
+ return out;
59
+ }
60
+ const known = Object.keys(GatewayConfigSchema.shape);
61
+ if (raw && typeof raw === "object" && !Array.isArray(raw)) {
62
+ for (const key of Object.keys(raw)) {
63
+ if (known.includes(key))
64
+ continue;
65
+ const near = known.find((k) => distance(k.toLowerCase(), key.toLowerCase()) <= 2);
66
+ add("error", "config", `unknown key "${key}" is ignored by the gateway${near ? `; did you mean "${near}"?` : ""} A mistyped key leaves the setting it was meant for at its default`);
67
+ }
68
+ }
69
+ const parsed = GatewayConfigSchema.safeParse(raw);
70
+ if (!parsed.success) {
71
+ for (const issue of parsed.error.issues)
72
+ add("error", "config", `${issue.path.join(".") || "(root)"}: ${issue.message}`);
73
+ return out;
74
+ }
75
+ add("ok", "config", "the config parses");
76
+ const cfg = loadConfig(configPath);
77
+ // the gateway's key
78
+ if (!existsSync(cfg.identity.keyFile)) {
79
+ add("warn", "key", `${cfg.identity.keyFile} does not exist yet; \`agent-custody keygen\` creates it, and the container creates it on first start`);
80
+ }
81
+ else {
82
+ try {
83
+ loadPrivateKey(cfg.identity.keyFile);
84
+ add("ok", "key", `the gateway key at ${cfg.identity.keyFile} loads`);
85
+ if (process.platform !== "win32" && (statSync(cfg.identity.keyFile).mode & 0o077) !== 0)
86
+ add("warn", "key", `${cfg.identity.keyFile} is readable by other users; make it mode 0600`);
87
+ }
88
+ catch (e) {
89
+ add("error", "key", `${cfg.identity.keyFile}: ${e instanceof Error ? e.message : String(e)}`);
90
+ }
91
+ }
92
+ // the principals whose grants are trusted
93
+ const principals = [];
94
+ for (const f of cfg.trustedPrincipalKeys) {
95
+ try {
96
+ principals.push(loadPublicKey(f));
97
+ }
98
+ catch (e) {
99
+ add("error", "principal keys", `${f}: ${e instanceof Error ? e.message : String(e)}`);
100
+ }
101
+ }
102
+ if (principals.length === cfg.trustedPrincipalKeys.length)
103
+ add("ok", "principal keys", `${principals.length} trusted principal key${principals.length === 1 ? "" : "s"} load`);
104
+ // the policy
105
+ if (!existsSync(cfg.policyFile)) {
106
+ add("error", "policy", `${cfg.policyFile} does not exist`);
107
+ }
108
+ else {
109
+ const text = readFileSync(cfg.policyFile, "utf8");
110
+ const r = cedar.checkParsePolicySet({ staticPolicies: text });
111
+ if (r.type !== "success")
112
+ for (const e of r.errors)
113
+ add("error", "policy", `${cfg.policyFile}: ${e.message}`);
114
+ else if (!hasPermitRule(text))
115
+ add("warn", "policy", `${cfg.policyFile} has no permit rule, so every call is denied`);
116
+ else
117
+ add("ok", "policy", "the policy parses");
118
+ }
119
+ if (cfg.mode === "observe")
120
+ add("warn", "mode", "observe mode forwards every call the grant allows and records what the policy would have decided; nothing is denied by policy");
121
+ // credentials: a variable the config names must be set where the gateway runs
122
+ const envNames = [];
123
+ for (const u of cfg.upstreams ?? (cfg.upstream ? [{ name: "upstream", ...cfg.upstream }] : [])) {
124
+ const name = "name" in u ? u.name : "upstream";
125
+ if ("tokenEnv" in u && u.tokenEnv)
126
+ envNames.push([`upstream ${name}`, u.tokenEnv]);
127
+ if ("rest" in u)
128
+ for (const v of Object.values(u.rest.headerEnv ?? {}))
129
+ envNames.push([`upstream ${name}`, v]);
130
+ if ("a2a" in u)
131
+ for (const v of Object.values(u.a2a.headerEnv ?? {}))
132
+ envNames.push([`upstream ${name}`, v]);
133
+ }
134
+ if (cfg.log?.tokenEnv)
135
+ envNames.push(["log", cfg.log.tokenEnv]);
136
+ if (cfg.splunk?.tokenEnv)
137
+ envNames.push(["splunk", cfg.splunk.tokenEnv]);
138
+ for (const v of Object.values(cfg.otel?.headersEnv ?? {}))
139
+ envNames.push(["otel", v]);
140
+ if (cfg.captureKeyEnv)
141
+ envNames.push(["capture", cfg.captureKeyEnv]);
142
+ const skipEnvironment = options.environment === "skip";
143
+ const missing = skipEnvironment ? [] : envNames.filter(([, v]) => !process.env[v]);
144
+ for (const [who, v] of missing)
145
+ add("error", "environment", `${who}: the variable ${v} is not set here, and a gateway does not start without it`);
146
+ if (envNames.length && skipEnvironment)
147
+ add("ok", "environment", `not checked here: this process does not hold the gateway's credentials (${[...new Set(envNames.map(([, v]) => v))].join(", ")}); run agent-custody check where the gateway runs`);
148
+ else if (envNames.length && !missing.length)
149
+ add("ok", "environment", `${envNames.length} credential variable${envNames.length === 1 ? " is" : "s are"} set`);
150
+ // stdio upstreams: the command must exist where the gateway runs
151
+ for (const u of cfg.upstreams ?? (cfg.upstream ? [{ name: "upstream", ...cfg.upstream }] : [])) {
152
+ if ("command" in u && !onPath(u.command))
153
+ add("error", "upstream", `${"name" in u ? u.name : "upstream"}: the command "${u.command}" is not on the PATH or at that path; in a container it must be inside the image`);
154
+ }
155
+ // a script or file a stdio upstream is started with has to be where the gateway runs, which in a container is inside the image
156
+ for (const u of cfg.upstreams ?? (cfg.upstream ? [{ name: "upstream", ...cfg.upstream }] : [])) {
157
+ if (!("command" in u))
158
+ continue;
159
+ for (const a of u.args)
160
+ if ((a.startsWith("/") || a.startsWith("./")) && !existsSync(a))
161
+ add("warn", "upstream", `${"name" in u ? u.name : "upstream"}: the argument ${a} does not exist here; if it is a file the upstream needs, it must be inside the image`);
162
+ }
163
+ // a REST tool with an idempotency header is a financial operation: every call to it fails unless `operations` configures it
164
+ const operationTools = new Set((cfg.operations?.tools ?? []).map((t) => t.tool));
165
+ for (const u of cfg.upstreams ?? (cfg.upstream ? [{ name: "upstream", ...cfg.upstream }] : [])) {
166
+ if (!("rest" in u))
167
+ continue;
168
+ for (const t of u.rest.tools) {
169
+ if (t.idempotencyHeader && !operationTools.has(t.name))
170
+ add("error", "upstream", `${"name" in u ? u.name : "upstream"}: the tool ${t.name} sets idempotencyHeader, which makes it a financial operation, and every call to it fails unless it is also listed under "operations"; remove idempotencyHeader, or configure it under operations (financial-operations.md)`);
171
+ }
172
+ }
173
+ // where the gateway writes
174
+ const writes = [["receiptsDir", cfg.receiptsDir]];
175
+ if (cfg.operations)
176
+ writes.push(["operations.database", cfg.operations.database]);
177
+ if (cfg.approvals)
178
+ writes.push(["approvals.usedDir", cfg.approvals.usedDir]);
179
+ if (cfg.logFile)
180
+ writes.push(["logFile", cfg.logFile]);
181
+ if (cfg.revokedGrants)
182
+ writes.push(["revokedGrants", cfg.revokedGrants]);
183
+ let writable = true;
184
+ for (const [key, path] of writes) {
185
+ if (!writableAncestor(path)) {
186
+ writable = false;
187
+ add("error", "paths", `${key} ${path} cannot be created or written; in a container, use an absolute path under /data (/config is read-only)`);
188
+ }
189
+ }
190
+ if (writable)
191
+ add("ok", "paths", "every path the gateway writes can be written");
192
+ if (cfg.revokedGrants && existsSync(cfg.revokedGrants)) {
193
+ try {
194
+ if (!Array.isArray(JSON.parse(readFileSync(cfg.revokedGrants, "utf8"))))
195
+ throw new Error("expected a JSON array of grant digests");
196
+ }
197
+ catch (e) {
198
+ add("error", "revokedGrants", `${cfg.revokedGrants}: ${e instanceof Error ? e.message : String(e)}; a revocation file that cannot be read denies every call`);
199
+ }
200
+ }
201
+ // the grant a single-grant gateway serves
202
+ let scopes = [];
203
+ if (cfg.grantFile) {
204
+ try {
205
+ const env = JSON.parse(readFileSync(cfg.grantFile, "utf8"));
206
+ const v = verifyDelegation(env, principals);
207
+ if (!v.ok)
208
+ add("error", "grant", `${cfg.grantFile}: ${v.error}`);
209
+ else {
210
+ scopes = v.delegation.scopes;
211
+ const now = new Date().toISOString();
212
+ if (!delegationValidAt(v.delegation, now))
213
+ add("error", "grant", `${cfg.grantFile} for ${v.delegation.agent} is outside its validity window (${v.delegation.issuedAt} to ${v.delegation.expiresAt})`);
214
+ else if (Date.parse(v.delegation.expiresAt) - Date.now() < 24 * 3600_000)
215
+ add("warn", "grant", `${cfg.grantFile} for ${v.delegation.agent} expires at ${v.delegation.expiresAt}`);
216
+ else
217
+ add("ok", "grant", `the grant for ${v.delegation.agent} verifies; scopes: ${scopes.join(", ")}`);
218
+ }
219
+ }
220
+ catch (e) {
221
+ add("error", "grant", `${cfg.grantFile}: ${e instanceof Error ? e.message : String(e)}`);
222
+ }
223
+ }
224
+ else {
225
+ add("ok", "grant", "no grantFile: each connection over HTTP presents its own grant");
226
+ }
227
+ // what a log outage costs
228
+ if (cfg.log && !cfg.precommit.length)
229
+ add("warn", "precommit", "a remote log is set and precommit is empty: every call is forwarded before its receipt is logged, so a log outage after a call leaves its side effect without evidence. Name the consequential tools in precommit, or [\"*\"]");
230
+ // tool names the config mentions, against the tools the upstreams offer
231
+ const mentioned = () => [
232
+ ...cfg.precommit.filter((t) => t !== "*").map((t) => ["precommit", t]),
233
+ ...cfg.facts.flatMap((f) => [["facts", f.tool], ...f.forTools.map((t) => ["facts.forTools", t])]),
234
+ ...(cfg.approvals?.tools ?? []).map((t) => ["approvals", t.tool]),
235
+ ...(cfg.operations?.tools ?? []).flatMap((t) => [["operations", t.tool], ["operations.reconcile", t.reconcile.tool]]),
236
+ ...scopes.map((t) => ["grant scope", t]),
237
+ ];
238
+ if (!options.connect) {
239
+ add("warn", "upstreams", "not started: run with --connect to start the upstreams, catch tool-name collisions and unreachable servers, and compare the tool names above with the tools offered");
240
+ return out;
241
+ }
242
+ // a gateway key that does not exist yet (the container creates it on first start) must not stop the upstreams being tried
243
+ if (skipEnvironment && envNames.length) {
244
+ add("warn", "upstreams", "not started: the upstreams need credentials that this process does not hold, by design. Run `agent-custody check --connect` where the gateway runs, for example `docker compose exec gateway agent-custody check --config /config/gateway.json --connect`");
245
+ return out;
246
+ }
247
+ let connectCfg = cfg;
248
+ let scratch;
249
+ if (!existsSync(cfg.identity.keyFile)) {
250
+ scratch = mkdtempSync(join(tmpdir(), "agent-custody-check-"));
251
+ connectCfg = { ...cfg, identity: { keyFile: writeKeyPair(generateKeyPair(), scratch, "check").keyFile } };
252
+ }
253
+ let tools;
254
+ try {
255
+ const host = await createGatewayHost(connectCfg, options.signal ? { signal: options.signal } : {});
256
+ try {
257
+ tools = host.tools();
258
+ }
259
+ finally {
260
+ await host.close();
261
+ }
262
+ add("ok", "upstreams", `the upstreams start and offer ${tools.length} tool${tools.length === 1 ? "" : "s"}: ${tools.join(", ")}`);
263
+ }
264
+ catch (e) {
265
+ add("error", "upstreams", `the gateway would not start: ${e instanceof Error ? e.message : String(e)}`);
266
+ }
267
+ finally {
268
+ if (scratch)
269
+ rmSync(scratch, { recursive: true, force: true });
270
+ }
271
+ if (tools) {
272
+ const unknown = mentioned().filter(([, t]) => !tools.includes(t));
273
+ // a scope that names nothing is harmless; a precommit name that matches nothing leaves that tool forwarded with no authorization committed first
274
+ for (const [where, t] of unknown)
275
+ add(where === "grant scope" ? "warn" : "error", "tool names", `${where} names "${t}", which no upstream offers${where === "precommit" ? "; the tool you meant is forwarded before it is logged" : ""}`);
276
+ if (!unknown.length)
277
+ add("ok", "tool names", "every tool the config and the grant name is offered by an upstream");
278
+ }
279
+ return out;
280
+ }
281
+ export function formatFindings(findings) {
282
+ const mark = { ok: "ok ", warn: "warn ", error: "ERROR" };
283
+ const lines = findings.map((f) => `${mark[f.level]} ${f.check}: ${f.message}`);
284
+ const errors = findings.filter((f) => f.level === "error").length;
285
+ const warns = findings.filter((f) => f.level === "warn").length;
286
+ lines.push("", errors ? `${errors} error${errors === 1 ? "" : "s"}, ${warns} warning${warns === 1 ? "" : "s"}: the gateway would not start cleanly` : `no errors, ${warns} warning${warns === 1 ? "" : "s"}`);
287
+ return lines.join("\n");
288
+ }
package/dist/cli.js CHANGED
@@ -23,12 +23,37 @@ import { CheckpointPublisher, fileResolver } from "./log-sink.js";
23
23
  import { createRequire } from "node:module";
24
24
  import { pruneLog } from "./retention.js";
25
25
  import { serveSidecar } from "./sidecar.js";
26
+ import { checkConfig, formatFindings } from "./check.js";
27
+ import { serveConsole } from "./console.js";
26
28
  import { TREEHEAD_TYPE } from "./receipt.js";
27
29
  import { MerkleLog } from "./log.js";
28
30
  import { createSdkIssuer } from "./sdk/index.js";
29
31
  import { handleHookEvent } from "./sdk/claude.js";
30
32
  import { auditExtends, formatReport, verifyBundle } from "./verify.js";
31
33
  import { formatSimulation, simulatePolicy, verifyOrphanAuthorization } from "./simulate.js";
34
+ /**
35
+ * Resolves on SIGINT or SIGTERM: a container runtime and systemd stop a service with SIGTERM, which PID 1 ignores unless
36
+ * it is handled. The handlers are installed once, before a service starts, so a signal that arrives while it starts up
37
+ * is kept and the service closes as soon as it is running.
38
+ */
39
+ let stopped;
40
+ function untilStopped() {
41
+ stopped ??= new Promise((resolve) => {
42
+ process.once("SIGINT", resolve);
43
+ process.once("SIGTERM", resolve);
44
+ });
45
+ return stopped;
46
+ }
47
+ const SERVICES = new Set(["serve", "witness", "signer", "portal", "log", "console"]);
48
+ /** a command that waits for untilStopped(); a stdio gateway runs until its input closes and keeps the default signal behaviour */
49
+ const runsUntilStopped = (cmd, args) => !!cmd && (SERVICES.has(cmd) || (cmd === "gateway" && (args.includes("--http") || args.includes("--a2a"))));
50
+ /** A secret kept in a file that only this process can read, such as a container secret mounted at /run/secrets. The file's path is not a secret; its contents are. */
51
+ function tokenFromFile(path) {
52
+ const v = readFileSync(path, "utf8").trim();
53
+ if (!v)
54
+ throw new Error(`${path} is empty`);
55
+ return v;
56
+ }
32
57
  /** A shared secret from an environment variable; never from the command line, where it would land in shell history. */
33
58
  function secretFrom(envName) {
34
59
  const v = process.env[envName];
@@ -48,6 +73,14 @@ const USAGE = `agent-custody <command>
48
73
  revoke --config <gateway.json> --grant <grant.json> revokes a grant: its digest goes into the config's revokedGrants file, every
49
74
  session under it or under a grant delegated from it refuses its next call, and no new session opens for them
50
75
  reconcile --config <gateway.json> --operation <uuid> operator-only provider lookup; commits a receipt before closing an unknown/pending financial operation
76
+ console --config <gateway.json> [--port 8795] [--host 127.0.0.1] [--token-env CONSOLE_TOKEN | --token-file <path>] [--gateway-url <url>] [--state-dir <dir>]
77
+ the admin console for a gateway: its config and tools, a config check, receipts with a verdict each, a policy editor that
78
+ validates and replays recorded calls before it saves, grant inspection and revocation, and an audit trail of its own changes.
79
+ A separate service from the gateway, behind a token read from the environment; it holds no principal key and never signs
80
+ check --config <gateway.json> [--connect] [--json]
81
+ what the gateway would fail on at startup, found before it starts: the config and its unknown keys, the keys,
82
+ the Cedar policy, the grant, credential variables, stdio commands, and writable paths. --connect also starts the
83
+ upstreams (tool-name collisions, unreachable servers) and checks every tool name the config and grant mention. Exits 1 on an error
51
84
  gateway --config <gateway.json> [--http [--port 8790] [--host 127.0.0.1] [--idle-minutes 30]]
52
85
  stdio: one gateway for the grant the config names. --http: one shared gateway, MCP over
53
86
  Streamable HTTP at /mcp, each connection presenting its own grant as Authorization: Bearer
@@ -87,6 +120,10 @@ const USAGE = `agent-custody <command>
87
120
  log-admin --db-env NAME tenant add <id> [--log-id <id>] | tenant list | tenant disable <id> | tenant plan <id> <free|team|enterprise>
88
121
  log-admin --db-env NAME token add <tenant> --label <text> | token list <tenant> | token revoke <tenant> <hash-prefix>
89
122
  log-admin --db-env NAME audit [--tenant <id>] who did what to tenants and tokens, newest first
123
+ log-admin --db-env NAME sso set <tenant> --domains a.com,b.com [--default-role readonly] [--enforce]
124
+ (--oidc-issuer <url> --oidc-client-id <id> --oidc-secret-env NAME | --saml-entry-point <url> --saml-cert <pem file> [--saml-idp-issuer <id>])
125
+ log-admin --db-env NAME sso show <tenant> | sso remove <tenant> enterprise sign-in through the tenant's own identity provider
126
+ log-admin --db-env NAME user mfa-reset <email> turns MFA off for a portal account that lost its authenticator
90
127
  portal --db-env NAME --secret-env NAME --public-url <log url> [--checkpoints-url <url>] [--portal-url <url>] [--port 8792] [--host 127.0.0.1]
91
128
  [--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]
92
129
  the tenant portal: register, first key, usage against plan, keys, billing, export
@@ -132,6 +169,8 @@ function loadTenants(path) {
132
169
  }
133
170
  async function main(argv) {
134
171
  const [cmd, ...rest] = argv;
172
+ if (runsUntilStopped(cmd, rest))
173
+ void untilStopped();
135
174
  switch (cmd) {
136
175
  case "reconcile": {
137
176
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, operation: { type: "string" } } });
@@ -203,6 +242,24 @@ async function main(argv) {
203
242
  console.log(`delegated to ${chain.agent}: scopes [${chain.scopes.join(", ")}] until ${chain.expiresAt}, under ${decodeDelegation(parent).agent}'s grant from ${chain.principal}`);
204
243
  return 0;
205
244
  }
245
+ case "console": {
246
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, port: { type: "string", default: "8795" }, host: { type: "string", default: "127.0.0.1" }, "token-env": { type: "string", default: "CONSOLE_TOKEN" }, "token-file": { type: "string" }, "gateway-url": { type: "string" }, "state-dir": { type: "string" } } });
247
+ if (!values.config)
248
+ throw new Error("console needs --config");
249
+ const running = await serveConsole({ configFile: values.config, token: values["token-file"] ? tokenFromFile(values["token-file"]) : secretFrom(values["token-env"]), port: Number(values.port), host: values.host, ...(values["gateway-url"] ? { gatewayUrl: values["gateway-url"] } : {}), ...(values["state-dir"] ? { stateDir: values["state-dir"] } : {}) });
250
+ console.error(`agent-custody console: ${running.url} config=${values.config}${values.host === "0.0.0.0" || (values.host !== "127.0.0.1" && values.host !== "localhost") ? " (reachable beyond this host: put TLS in front and limit who can reach it)" : ""}`);
251
+ await untilStopped();
252
+ await running.close();
253
+ return 0;
254
+ }
255
+ case "check": {
256
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, connect: { type: "boolean", default: false }, json: { type: "boolean", default: false } } });
257
+ if (!values.config)
258
+ throw new Error("check needs --config");
259
+ const findings = await checkConfig(values.config, { connect: values.connect });
260
+ console.log(values.json ? JSON.stringify(findings, null, 2) : formatFindings(findings));
261
+ return findings.some((f) => f.level === "error") ? 1 : 0;
262
+ }
206
263
  case "revoke": {
207
264
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, grant: { type: "string" } } });
208
265
  if (!values.config || !values.grant)
@@ -237,7 +294,7 @@ async function main(argv) {
237
294
  const grant = cfg.grantFile ? JSON.parse(readFileSync(cfg.grantFile, "utf8")) : undefined;
238
295
  const running = await serveA2a(host, a2a, { port: Number(values.port), host: values.host, ...(grant ? { grant } : {}) });
239
296
  console.error(`agent-custody gateway (a2a): ${running.url} keyid=${host.keyid} fronting ${a2a.url} as ${a2a.prefix}.send; card at ${running.url}/.well-known/agent-card.json`);
240
- await new Promise((resolve) => process.once("SIGINT", resolve));
297
+ await untilStopped();
241
298
  await running.close();
242
299
  await host.close();
243
300
  return 0;
@@ -246,7 +303,7 @@ async function main(argv) {
246
303
  const host = await createGatewayHost(loadConfig(values.config));
247
304
  const running = await serveHttp(host, { port: Number(values.port), host: values.host, idleMs: Number(values["idle-minutes"]) * 60_000 });
248
305
  console.error(`agent-custody gateway: ${running.url} keyid=${host.keyid} one session per grant; GET /health`);
249
- await new Promise((resolve) => process.once("SIGINT", resolve));
306
+ await untilStopped();
250
307
  await running.close();
251
308
  await host.close();
252
309
  return 0;
@@ -274,7 +331,7 @@ async function main(argv) {
274
331
  const issuer = createSdkIssuer(loadSdkConfig(values.config));
275
332
  const running = await serveSidecar(issuer, { port: Number(values.port), host: values.host });
276
333
  console.error(`agent-custody serve: ${running.url} agent=${issuer.agentId} keyid=${issuer.keyid} log=${issuer.log.kind}:${issuer.log.where}`);
277
- await new Promise((resolve) => process.once("SIGINT", resolve));
334
+ await untilStopped();
278
335
  await running.close();
279
336
  return 0;
280
337
  }
@@ -313,7 +370,7 @@ async function main(argv) {
313
370
  }
314
371
  console.error(`agent-custody witness: keyid=${w.keyid} watching ${values["log-url"]} via ${values["checkpoints-url"]} every ${values.every}s, writing to ${values.out}`);
315
372
  w.start(everyMs);
316
- await new Promise((resolve) => process.once("SIGINT", resolve));
373
+ await untilStopped();
317
374
  w.stop();
318
375
  return 0;
319
376
  }
@@ -327,7 +384,7 @@ async function main(argv) {
327
384
  const kp = loadPrivateKey(values.key);
328
385
  const running = await serveSigner(kp, { port: Number(values.port), host: values.host, ...(token ? { token } : {}), retired: (values["retired-key"] ?? []).map(retiredKey) });
329
386
  console.error(`agent-custody signer: ${running.url} keyid=${kp.keyid} ${token ? "token required" : "open: bind this to a private network"}${values["retired-key"]?.length ? ` retired=${values["retired-key"].length}` : ""}`);
330
- await new Promise((resolve) => process.once("SIGINT", resolve));
387
+ await untilStopped();
331
388
  await running.close();
332
389
  return 0;
333
390
  }
@@ -395,12 +452,12 @@ async function main(argv) {
395
452
  }
396
453
  const running = await servePortal({ tenancy, client, secret, publicUrl: values["public-url"], ...(values["checkpoints-url"] ? { checkpointsUrl: values["checkpoints-url"] } : {}), ...(values["portal-url"] ? { portalUrl: values["portal-url"] } : {}), ...(keyid ? { keyid } : {}), ...(stripe ? { stripe } : {}), ...(mail ? { mail } : {}), ...(oauth ? { oauth } : {}), trustProxy: values["trust-proxy"] }, { port: Number(values.port), host: values.host });
397
454
  console.error(`agent-custody portal: ${running.url} log=${values["public-url"]} billing=${stripe ? "stripe" : "off"}${values["trust-proxy"] ? " trust-proxy" : ""}`);
398
- await new Promise((resolve) => process.once("SIGINT", resolve));
455
+ await untilStopped();
399
456
  await running.close();
400
457
  return 0;
401
458
  }
402
459
  case "log-admin": {
403
- const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { "db-env": { type: "string" }, "log-id": { type: "string" }, label: { type: "string" }, file: { type: "string" }, tenant: { type: "string", default: "default" } } });
460
+ const { values, positionals } = parseArgs({ args: rest, allowPositionals: true, options: { "db-env": { type: "string" }, "log-id": { type: "string" }, label: { type: "string" }, file: { type: "string" }, tenant: { type: "string", default: "default" }, domains: { type: "string" }, "default-role": { type: "string", default: "readonly" }, enforce: { type: "boolean", default: false }, "oidc-issuer": { type: "string" }, "oidc-client-id": { type: "string" }, "oidc-secret-env": { type: "string" }, "saml-entry-point": { type: "string" }, "saml-cert": { type: "string" }, "saml-idp-issuer": { type: "string" } } });
404
461
  if (!values["db-env"])
405
462
  throw new Error("log-admin needs --db-env NAME");
406
463
  const tenancy = new PostgresTenancy(openPostgres(values["db-env"]));
@@ -436,6 +493,55 @@ async function main(argv) {
436
493
  else if (what === "token" && verb === "revoke" && args[0] && args[1]) {
437
494
  console.log(`revoked ${await tenancy.revokeToken(args[0], args[1], actor)} token(s)`);
438
495
  }
496
+ else if (what === "sso" && verb === "set" && args[0]) {
497
+ if (!(await tenancy.tenant(args[0])))
498
+ throw new Error(`unknown tenant ${args[0]}; add it first`);
499
+ if (!values.domains)
500
+ throw new Error("sso set needs --domains");
501
+ let config;
502
+ if (values["oidc-issuer"]) {
503
+ if (!values["oidc-client-id"] || !values["oidc-secret-env"])
504
+ throw new Error("OIDC needs --oidc-issuer, --oidc-client-id, and --oidc-secret-env");
505
+ const clientSecret = process.env[values["oidc-secret-env"]];
506
+ if (!clientSecret)
507
+ throw new Error(`environment variable ${values["oidc-secret-env"]} is not set`);
508
+ config = { issuer: values["oidc-issuer"], clientId: values["oidc-client-id"], clientSecret };
509
+ }
510
+ else if (values["saml-entry-point"] && values["saml-cert"]) {
511
+ config = { entryPoint: values["saml-entry-point"], idpCert: readFileSync(values["saml-cert"], "utf8"), ...(values["saml-idp-issuer"] ? { idpIssuer: values["saml-idp-issuer"] } : {}) };
512
+ }
513
+ else {
514
+ throw new Error("sso set needs the OIDC flags or --saml-entry-point with --saml-cert");
515
+ }
516
+ const domains = values.domains.split(",");
517
+ const protocol = "issuer" in config ? "oidc" : "saml";
518
+ await new PortalStore(openPostgres(values["db-env"])).setSso({ tenant: args[0], protocol, config, domains, defaultRole: values["default-role"], enforced: values.enforce });
519
+ await tenancy.record(actor, "sso.set", args[0], { protocol, ...("issuer" in config ? { issuer: config.issuer } : { entryPoint: config.entryPoint }), domains, defaultRole: values["default-role"], enforced: values.enforce });
520
+ console.log(`single sign-on set for ${args[0]}: ${domains.join(", ")}${values.enforce ? " (enforced)" : ""}`);
521
+ }
522
+ else if (what === "sso" && verb === "show" && args[0]) {
523
+ const s = await new PortalStore(openPostgres(values["db-env"])).ssoOf(args[0]);
524
+ if (!s)
525
+ throw new Error(`no single sign-on for ${args[0]}`);
526
+ const c = s.config;
527
+ console.log([`protocol ${s.protocol}`, ...(c.issuer ? [`issuer ${c.issuer}`, `client id ${c.clientId}`, "client secret set"] : [`entry point ${c.entryPoint}`, `idp issuer ${c.idpIssuer ?? "(not pinned)"}`, "idp cert set"]), `domains ${s.domains.join(", ")}`, `default role ${s.defaultRole}`, `enforced ${s.enforced}`].join("\n"));
528
+ }
529
+ else if (what === "sso" && verb === "remove" && args[0]) {
530
+ const removed = await new PortalStore(openPostgres(values["db-env"])).removeSso(args[0]);
531
+ if (removed)
532
+ await tenancy.record(actor, "sso.remove", args[0], {});
533
+ console.log(`${removed ? "removed" : "there was no"} single sign-on for ${args[0]}`);
534
+ }
535
+ else if (what === "user" && verb === "mfa-reset" && args[0]) {
536
+ const portal = new PortalStore(openPostgres(values["db-env"]));
537
+ const email = args[0].trim().toLowerCase();
538
+ const member = await portal.userByEmail(email);
539
+ if (!member)
540
+ throw new Error(`no portal account with the address ${args[0]}`);
541
+ await portal.resetMfa(email);
542
+ await tenancy.record(actor, "user.mfa-reset", await portal.tenantOf(member.id), { email });
543
+ console.log(`MFA reset for ${args[0]}`);
544
+ }
439
545
  else if (what === "audit") {
440
546
  for (const e of await tenancy.audit({ ...(values.tenant !== "default" ? { tenant: values.tenant } : {}), limit: 100 }))
441
547
  console.log(`${e.at} ${e.actor.padEnd(40)} ${e.action.padEnd(14)} ${(e.tenantId ?? "").padEnd(20)} ${Object.entries(e.detail).map(([k, v]) => `${k}=${v}`).join(" ")}`);
@@ -526,7 +632,7 @@ async function main(argv) {
526
632
  const publisher = checkpoints ? new CheckpointPublisher(resolver, signer, checkpoints, everyMs, undefined, heartbeatMs) : null;
527
633
  publisher?.start();
528
634
  console.error(`agent-custody log: ${running.url} keyid=${signer.keyid} ${values["signer-url"] ? `signer=${values["signer-url"]} ` : ""}${where}${checkpoints ? ` checkpoints every ${values["checkpoint-every"]}s${values["checkpoint-dir"] ? ` to ${values["checkpoint-dir"]}` : ""}` : ""}${admin ? " admin page at /admin" : ""}`);
529
- await new Promise((resolve) => process.once("SIGINT", resolve));
635
+ await untilStopped();
530
636
  publisher?.stop();
531
637
  await running.close();
532
638
  return 0;
@@ -0,0 +1,4 @@
1
+ declare const SCRIPT: string;
2
+ export declare const CONSOLE_CSP: string;
3
+ export declare const CONSOLE_HTML: string;
4
+ export { SCRIPT as CONSOLE_SCRIPT };