@agent-custody/receipts 0.13.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +46 -28
  2. package/dist/check.d.ts +10 -0
  3. package/dist/check.js +179 -3
  4. package/dist/claude-init.d.ts +46 -0
  5. package/dist/claude-init.js +208 -0
  6. package/dist/cli.js +126 -11
  7. package/dist/config.d.ts +128 -1
  8. package/dist/config.js +92 -3
  9. package/dist/console.js +16 -7
  10. package/dist/deny-report.d.ts +30 -0
  11. package/dist/deny-report.js +106 -0
  12. package/dist/door.d.ts +203 -0
  13. package/dist/door.js +712 -0
  14. package/dist/export.d.ts +39 -0
  15. package/dist/export.js +95 -0
  16. package/dist/gateway.js +53 -21
  17. package/dist/index.d.ts +8 -0
  18. package/dist/index.js +7 -0
  19. package/dist/issue.js +5 -65
  20. package/dist/lock.d.ts +12 -0
  21. package/dist/lock.js +124 -0
  22. package/dist/log-admin.js +3 -3
  23. package/dist/log.d.ts +20 -3
  24. package/dist/log.js +117 -24
  25. package/dist/opa-server.d.ts +34 -0
  26. package/dist/opa-server.js +93 -0
  27. package/dist/policy-rego.d.ts +30 -0
  28. package/dist/policy-rego.js +114 -0
  29. package/dist/policy.d.ts +6 -0
  30. package/dist/policy.js +17 -0
  31. package/dist/pr-summary.d.ts +25 -0
  32. package/dist/pr-summary.js +87 -0
  33. package/dist/receipt.d.ts +3 -1
  34. package/dist/retention.d.ts +1 -1
  35. package/dist/retention.js +14 -4
  36. package/dist/sdk/claude.js +18 -2
  37. package/dist/sdk/index.d.ts +2 -0
  38. package/dist/sdk/index.js +11 -2
  39. package/dist/simulate.d.ts +3 -1
  40. package/dist/simulate.js +15 -7
  41. package/dist/verify.js +6 -3
  42. package/dist/witness.js +3 -3
  43. package/docs/compliance.md +117 -7
  44. package/docs/configuration.md +3 -3
  45. package/docs/door-signals.md +66 -0
  46. package/docs/door.md +168 -0
  47. package/docs/github-action.md +164 -0
  48. package/docs/policies.md +124 -1
  49. package/docs/sdk.md +99 -1
  50. package/docs/tutorials.md +5 -0
  51. package/docs/usage.md +3 -3
  52. package/docs/verification.md +9 -2
  53. package/package.json +16 -14
  54. package/templates/claude-code.cedar +373 -0
  55. package/vectors/audit.json +27 -27
  56. package/vectors/canonical.json +5 -5
  57. package/vectors/merkle.json +123 -0
  58. package/vectors/receipts.json +1258 -1005
@@ -0,0 +1,208 @@
1
+ // `agent-custody init claude-code`: the key, the config, the starter policy, and the three hooks for the user's own
2
+ // Claude Code sessions, in one command. It is safe to run two times.
3
+ import { spawnSync } from "node:child_process";
4
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { homedir, userInfo } from "node:os";
6
+ import { dirname, isAbsolute, join, resolve } from "node:path";
7
+ import { SdkConfigSchema, loadSdkConfig } from "./config.js";
8
+ import { generateKeyPair, publicKeyFromPem, writeKeyPair } from "./crypto.js";
9
+ export const HOOK_EVENTS = ["PreToolUse", "PostToolUse", "PostToolUseFailure"];
10
+ export const HOOK_MATCHER = "Bash|Write|Edit|MultiEdit|NotebookEdit|mcp__.*";
11
+ const KEY_NAME = "claude-code";
12
+ const DEFAULT_TOKEN_ENV = "AGENT_CUSTODY_LOG_TOKEN";
13
+ /** A shell word for a path: bare when it is plain, in single quotes otherwise. */
14
+ export function shellQuote(s) {
15
+ return /^[A-Za-z0-9_\/.:@%+=,-]+$/.test(s) ? s : `'${s.replaceAll("'", `'\\''`)}'`;
16
+ }
17
+ const isObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
18
+ /** Parses a settings file. Throws, and so changes nothing, when the text is not a JSON object with usable `hooks`. */
19
+ export function parseSettings(text, file) {
20
+ let settings;
21
+ try {
22
+ settings = JSON.parse(text);
23
+ }
24
+ catch (e) {
25
+ throw new Error(`${file} is not valid JSON (${e instanceof Error ? e.message : String(e)}). Fix the file and run the command again. The command changed nothing.`);
26
+ }
27
+ if (!isObject(settings))
28
+ throw new Error(`${file} does not hold a JSON object. The command changed nothing.`);
29
+ const hooks = settings.hooks;
30
+ if (hooks !== undefined && !isObject(hooks))
31
+ throw new Error(`"hooks" in ${file} is not an object. The command changed nothing.`);
32
+ for (const event of HOOK_EVENTS) {
33
+ if (hooks?.[event] !== undefined && !Array.isArray(hooks[event]))
34
+ throw new Error(`"hooks.${event}" in ${file} is not an array. The command changed nothing.`);
35
+ }
36
+ return settings;
37
+ }
38
+ /**
39
+ * Registers the hook command for the three events and keeps every other key and hook. A hook of ours is a command
40
+ * that ends with `hook --config <this config>`. It is updated in place when its command differs, and never added twice.
41
+ */
42
+ export function mergeHooks(settings, command, configFile) {
43
+ const ours = ` hook --config ${shellQuote(configFile)}`;
44
+ const hooks = { ...(isObject(settings.hooks) ? settings.hooks : {}) };
45
+ const changes = {};
46
+ for (const event of HOOK_EVENTS) {
47
+ const entries = (hooks[event] ?? []).map((entry) => (isObject(entry) ? { ...entry } : entry));
48
+ let change;
49
+ for (const entry of entries) {
50
+ if (!isObject(entry) || !Array.isArray(entry.hooks))
51
+ continue;
52
+ entry.hooks = entry.hooks.map((hook) => {
53
+ if (!isObject(hook) || typeof hook.command !== "string" || !hook.command.endsWith(ours))
54
+ return hook;
55
+ if (hook.command === command) {
56
+ change ??= "kept";
57
+ return hook;
58
+ }
59
+ change = "updated";
60
+ return { ...hook, command };
61
+ });
62
+ }
63
+ if (!change) {
64
+ entries.push({ matcher: HOOK_MATCHER, hooks: [{ type: "command", command }] });
65
+ change = "added";
66
+ }
67
+ hooks[event] = entries;
68
+ changes[event] = change;
69
+ }
70
+ return { settings: { ...settings, hooks }, changes };
71
+ }
72
+ function buildConfig(o, user) {
73
+ const config = {
74
+ agentId: "claude-code",
75
+ principalId: user,
76
+ framework: "claude-code",
77
+ identity: { keyFile: `keys/${KEY_NAME}.key` },
78
+ policyFile: "policy.cedar",
79
+ ...(o.enforce ? {} : { mode: "observe" }),
80
+ receiptsDir: "receipts",
81
+ };
82
+ if (o.logUrl) {
83
+ config.log = {
84
+ url: o.logUrl,
85
+ tokenEnv: o.logTokenEnv ?? DEFAULT_TOKEN_ENV,
86
+ hashOnly: true,
87
+ keys: ["log.pub"],
88
+ ...(o.logId ? { logId: o.logId } : {}),
89
+ timeoutMs: 3000,
90
+ };
91
+ }
92
+ else {
93
+ config.logFile = "log.jsonl";
94
+ }
95
+ return config;
96
+ }
97
+ /** Throws unless the file holds a PUBLIC key in PEM form. A private key is refused too, so that `log.pub` never holds one. */
98
+ function checkLogKey(file) {
99
+ const text = readFileSync(file, "utf8");
100
+ try {
101
+ if (!text.includes("-----BEGIN PUBLIC KEY-----"))
102
+ throw new Error("no PEM public key");
103
+ publicKeyFromPem(text);
104
+ }
105
+ catch {
106
+ throw new Error(`init: the log key file ${file} does not hold a public key in PEM form. Give the .pub file of the log.`);
107
+ }
108
+ }
109
+ /** True when the path is in a git work tree and git does not ignore it. False when git cannot tell. */
110
+ function notIgnoredByGit(file) {
111
+ return spawnSync("git", ["check-ignore", "-q", file], { cwd: dirname(file), stdio: "ignore", timeout: 5000 }).status === 1;
112
+ }
113
+ function userName() {
114
+ try {
115
+ return userInfo().username;
116
+ }
117
+ catch {
118
+ return "user";
119
+ }
120
+ }
121
+ export function initClaudeCode(o) {
122
+ const print = o.print ?? ((line) => console.log(line));
123
+ const home = o.home ?? homedir();
124
+ const dir = resolve(o.dir ?? join(home, ".config", "agent-custody"));
125
+ const settingsFile = o.user ? join(home, ".claude", "settings.json") : join(resolve(o.cwd ?? process.cwd()), ".claude", "settings.local.json");
126
+ const configFile = join(dir, "sdk.json");
127
+ if (!isAbsolute(o.cliPath))
128
+ throw new Error("init: the CLI path must be absolute");
129
+ if ((o.logId || o.logTokenEnv || o.logKey) && !o.logUrl)
130
+ throw new Error("init: --log-id, --log-token-env, and --log-key need --log-url");
131
+ if (o.logTokenEnv && !/^[A-Z_][A-Z0-9_]*$/.test(o.logTokenEnv))
132
+ throw new Error("init: --log-token-env takes the NAME of an environment variable, such as AGENT_CUSTODY_LOG_TOKEN. Never give the token itself.");
133
+ if (o.logUrl && !o.logKey)
134
+ throw new Error("init: --log-url needs --log-key <pub>, the public key of the log. Without it, `report` cannot check the tree head of any receipt, and every receipt fails.");
135
+ if (o.logKey && !existsSync(o.logKey))
136
+ throw new Error(`init: the log key file ${o.logKey} does not exist`);
137
+ if (o.logKey)
138
+ checkLogKey(o.logKey);
139
+ const config = buildConfig(o, userName());
140
+ const checked = SdkConfigSchema.safeParse(config);
141
+ if (!checked.success)
142
+ throw new Error(`init: the config is not valid: ${checked.error.issues.map((i) => `${i.path.join(".") || "(config)"}: ${i.message}`).join("; ")}`);
143
+ // Read the settings before any write, so that a settings file we cannot merge leaves the machine as it was.
144
+ const settingsText = existsSync(settingsFile) ? readFileSync(settingsFile, "utf8") : undefined;
145
+ const settings = settingsText === undefined ? {} : parseSettings(settingsText, settingsFile);
146
+ print("agent-custody init claude-code");
147
+ const keyFile = join(dir, "keys", `${KEY_NAME}.key`);
148
+ mkdirSync(join(dir, "keys"), { recursive: true, mode: 0o700 });
149
+ if (existsSync(keyFile)) {
150
+ print(`1. Key: kept the existing key ${keyFile}`);
151
+ }
152
+ else {
153
+ const kp = generateKeyPair();
154
+ writeKeyPair(kp, join(dir, "keys"), KEY_NAME);
155
+ print(`1. Key: made ${keyFile} (key id ${kp.keyid.slice(0, 16)}). The file is readable by you only.`);
156
+ }
157
+ const policyFile = join(dir, "policy.cedar");
158
+ if (existsSync(policyFile)) {
159
+ print(`2. Policy: kept the existing ${policyFile}`);
160
+ }
161
+ else {
162
+ copyFileSync(new URL("../templates/claude-code.cedar", import.meta.url), policyFile);
163
+ print(`2. Policy: wrote the starter deny set to ${policyFile}. It forbids force push (not --force-with-lease), rm -rf on /, ~, and $HOME, terraform destroy and apply -destroy, and drop database.`);
164
+ }
165
+ mkdirSync(join(dir, "receipts"), { recursive: true, mode: 0o700 });
166
+ if (existsSync(configFile)) {
167
+ print(`3. Config: kept the existing ${configFile}. The command does not change it.`);
168
+ const ignored = [["--enforce", o.enforce], ["--log-url", o.logUrl], ["--log-id", o.logId], ["--log-token-env", o.logTokenEnv], ["--log-key", o.logKey]].filter(([, given]) => given).map(([flag]) => flag);
169
+ if (ignored.length)
170
+ print(` Warning: ${ignored.join(", ")} not applied, because the config exists. The pinned log key stays as it is. Edit ${configFile}, or remove the file and run this command again.`);
171
+ }
172
+ else {
173
+ if (o.logKey)
174
+ copyFileSync(o.logKey, join(dir, "log.pub"));
175
+ writeFileSync(configFile, `${JSON.stringify(config, null, 2)}\n`);
176
+ print(`3. Config: wrote ${configFile}, ${o.enforce ? "in enforce mode: a denied call is blocked" : 'with "mode": "observe": the policy records a denied call and blocks nothing'}.`);
177
+ print(o.logUrl ? ` Receipts go to ${o.logUrl} as hashes. The token comes from the environment variable ${o.logTokenEnv ?? DEFAULT_TOKEN_ENV}.` : ` Receipts stay on this machine in ${join(dir, "receipts")}. No log is configured.`);
178
+ }
179
+ loadSdkConfig(configFile);
180
+ const nodePath = o.nodePath ?? process.execPath;
181
+ const hookCommand = `${shellQuote(nodePath)} ${shellQuote(o.cliPath)} hook --config ${shellQuote(configFile)}`;
182
+ const merged = mergeHooks(settings, hookCommand, configFile);
183
+ mkdirSync(dirname(settingsFile), { recursive: true });
184
+ writeFileSync(settingsFile, `${JSON.stringify(merged.settings, null, 2)}\n`);
185
+ const by = (c) => HOOK_EVENTS.filter((e) => merged.changes[e] === c);
186
+ const parts = [["registered", "added"], ["updated", "updated"], ["found already registered", "kept"]].filter(([, c]) => by(c).length).map(([word, c]) => `${word} ${by(c).join(", ")}`);
187
+ print(`4. Hooks: ${parts.join("; ")} in ${settingsFile}. The command keeps every other key and hook in that file.`);
188
+ if (!o.user && notIgnoredByGit(settingsFile)) {
189
+ print("");
190
+ print(`Warning: ${settingsFile} is in a git repository, and git does not ignore it. The file holds absolute paths of your home directory.`);
191
+ print("Add this line to .gitignore: .claude/settings.local.json");
192
+ }
193
+ if (/[\\/]_npx[\\/]/.test(o.cliPath)) {
194
+ print("");
195
+ print("Warning: this command runs from the npx cache, and npm can clear that cache. The hooks then stop working.");
196
+ print("Install the package globally with `npm install -g @agent-custody/receipts`, and run this command again. The second run updates the hook paths.");
197
+ }
198
+ if (o.logUrl && !process.env[o.logTokenEnv ?? DEFAULT_TOKEN_ENV]) {
199
+ print("");
200
+ print(`Note: ${o.logTokenEnv ?? DEFAULT_TOKEN_ENV} is not set in this shell. Set it in the environment that starts Claude Code.`);
201
+ }
202
+ print("");
203
+ print("Next:");
204
+ print(` 1. Start a Claude Code session ${o.user ? "in any directory" : "in this directory"} and work as usual. Nothing is blocked${o.enforce ? " except a call that the policy denies" : ""}.`);
205
+ print(` 2. Run: ${shellQuote(nodePath)} ${shellQuote(o.cliPath)} report --config ${shellQuote(configFile)}`);
206
+ print(" The report lists each call that the policy would have denied.");
207
+ return { dir, configFile, settingsFile, hookCommand };
208
+ }
package/dist/cli.js CHANGED
@@ -5,7 +5,7 @@ import { saltsFileFor } from "./retention.js";
5
5
  import { parseArgs } from "node:util";
6
6
  import { closeSync, constants as fsConstants, existsSync, fchmodSync, openSync, readFileSync, readdirSync, writeFileSync, writeSync } from "node:fs";
7
7
  import { dirname, join, resolve } from "node:path";
8
- import { loadConfig, loadSdkConfig } from "./config.js";
8
+ import { loadConfig, loadDoorConfig, loadSdkConfig } from "./config.js";
9
9
  import { dsseVerify, generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
10
10
  import { createDelegation, decodeDelegation, delegateFrom, grantDigest } from "./delegation.js";
11
11
  import { createGateway, createGatewayHost, serveStdio, writeRevokedGrants } from "./gateway.js";
@@ -19,6 +19,7 @@ import { Anchor, ANCHOR_CHAINS, resolveAnchorChain } from "./anchor.js";
19
19
  import { checkCompleteness, formatCompleteness, stripeSource } from "./completeness.js";
20
20
  import { evmChain } from "./anchor-evm.js";
21
21
  import { serveHttp } from "./gateway-http.js";
22
+ import { createDoorHost, serveDoor } from "./door.js";
22
23
  import { serveA2a } from "./a2a.js";
23
24
  import { PortalStore, sendFollowUps, servePortal } from "./portal.js";
24
25
  import { exportLog, formatExport } from "./log-export.js";
@@ -26,14 +27,20 @@ import { CheckpointPublisher, fileResolver } from "./log-sink.js";
26
27
  import { createRequire } from "node:module";
27
28
  import { pruneLog } from "./retention.js";
28
29
  import { serveSidecar } from "./sidecar.js";
29
- import { checkConfig, formatFindings } from "./check.js";
30
+ import { checkConfig, checkDoorConfig, formatFindings, isDoorConfig } from "./check.js";
30
31
  import { serveConsole } from "./console.js";
31
32
  import { TREEHEAD_TYPE } from "./receipt.js";
32
33
  import { MerkleLog } from "./log.js";
33
34
  import { createSdkIssuer } from "./sdk/index.js";
35
+ import { initClaudeCode } from "./claude-init.js";
36
+ import { denyReport, formatDenyReport } from "./deny-report.js";
37
+ import { fileURLToPath } from "node:url";
34
38
  import { handleHookEvent } from "./sdk/claude.js";
35
39
  import { auditExtends, formatReport, verifyBundle } from "./verify.js";
40
+ import { CLEAR_WARNING, exportReceipts, formatReceiptExport as formatExportLines } from "./export.js";
41
+ import { formatSummaryMarkdown, receiptFiles, summarizeReceipts } from "./pr-summary.js";
36
42
  import { formatSimulation, simulatePolicy, verifyOrphanAuthorization } from "./simulate.js";
43
+ import { isRegoFile } from "./policy-rego.js";
37
44
  /**
38
45
  * Resolves on SIGINT or SIGTERM: a container runtime and systemd stop a service with SIGTERM, which PID 1 ignores unless
39
46
  * it is handled. The handlers are installed once, before a service starts, so a signal that arrives while it starts up
@@ -47,7 +54,7 @@ function untilStopped() {
47
54
  });
48
55
  return stopped;
49
56
  }
50
- const SERVICES = new Set(["serve", "witness", "signer", "portal", "log", "console"]);
57
+ const SERVICES = new Set(["serve", "witness", "signer", "portal", "log", "console", "door"]);
51
58
  /** a command that waits for untilStopped(); a stdio gateway runs until its input closes and keeps the default signal behaviour */
52
59
  const runsUntilStopped = (cmd, args) => !!cmd && (SERVICES.has(cmd) || (cmd === "gateway" && (args.includes("--http") || args.includes("--a2a"))));
53
60
  /** 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. */
@@ -87,13 +94,26 @@ const USAGE = `agent-custody <command>
87
94
  gateway --config <gateway.json> [--http [--port 8790] [--host 127.0.0.1] [--idle-minutes 30]]
88
95
  stdio: one gateway for the grant the config names. --http: one shared gateway, MCP over
89
96
  Streamable HTTP at /mcp, each connection presenting its own grant as Authorization: Bearer
97
+ door --config <door.json> [--port 8780] [--host 127.0.0.1]
98
+ a reverse proxy in front of your own site or API: every arrival classified (verified by a
99
+ trusted grant, claimed, or unknown), decided by the Cedar policy for its route, relayed to the
100
+ origin or refused with 403, and receipted either way; GET /.well-known/agent-custody-door
101
+ init claude-code [--dir <dir>] [--user] [--enforce] [--log-url <url> [--log-id <id>] [--log-token-env NAME] [--log-key <pub>]]
102
+ one command for your own Claude Code sessions: an agent key, sdk.json in observe mode, a starter deny
103
+ policy, and the three hooks in .claude/settings.local.json (--user: ~/.claude/settings.json). Safe to run twice
104
+ report --config <sdk.json> the calls that the policy would have denied, from the receipts: tool, command or path, rule, receipt id;
105
+ a receipt that does not verify is counted apart. Exits 1 when any receipt does not verify
90
106
  hook [--config <sdk.json>] Claude Code hook command; reads the event on stdin (or AGENT_CUSTODY_CONFIG)
91
107
  serve --config <sdk.json> [--port 8788] [--host 127.0.0.1] the SDK as a local HTTP API for agents in other languages
92
108
  prune --log <log.jsonl> --before <ISO instant> [--receipts <dir>]
93
109
  retention on the receipt log: replaces older leaves with their hashes, so proofs still verify and the content is gone
94
110
  log --file <log.jsonl> --key <log.key> [--port 8787] [--host 127.0.0.1] [--token-env <NAME>] reference log server
95
111
  verify <bundle.json> --issuer-key <pub> [--principal-key <pub>] [--approval-key <pub>] [--log-key <pub> | --log-url <url>] [--log-id <id>] [--require-strict] [--upstream-key <pub>] [--stripe-secret-env NAME] [--github-secret-env NAME] [--log <log.jsonl>] [--disclose <file>] [--capture-key-env NAME] [--json]
96
- policy simulate --policy <proposed.cedar> --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--approval-key <pub>]... [--log-key <pub>]... [--json] [--out <file>]
112
+ verify --markdown <dir|bundle.json>... --issuer-key <pub> one Markdown table for a directory of bundles; exit 1 when one does not verify or none exists
113
+ export --receipts <dir> --out <dir> --issuer-key <pub>... [--principal-key <pub>]... [--approval-key <pub>]... [--since <ISO time>] [--allow-clear]
114
+ copies the verified receipt bundles that keep their values private into a directory for a pull request, byte for byte.
115
+ Reads only <id>.json at the top level; never salts/, outbox/, or *.authorization.json. Exits 1 when it refuses a receipt, and when it copies none
116
+ policy simulate --policy <proposed.cedar|.rego> --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--approval-key <pub>]... [--log-key <pub>]... [--json] [--out <file>]
97
117
  completeness --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--log-key <pub>]... [--log <log.jsonl>] [--log-id <id>]
98
118
  --provider stripe --object refunds|payouts|transfers --key-env NAME --tool <name>... --since <ISO> --until <ISO>
99
119
  [--id-path id] [--amount-field amount] [--currency-field currency] [--beneficiary <arg>=<field>]... [--json]
@@ -273,7 +293,7 @@ async function main(argv) {
273
293
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, connect: { type: "boolean", default: false }, json: { type: "boolean", default: false } } });
274
294
  if (!values.config)
275
295
  throw new Error("check needs --config");
276
- const findings = await checkConfig(values.config, { connect: values.connect });
296
+ const findings = isDoorConfig(values.config) ? checkDoorConfig(values.config) : await checkConfig(values.config, { connect: values.connect });
277
297
  console.log(values.json ? JSON.stringify(findings, null, 2) : formatFindings(findings));
278
298
  return findings.some((f) => f.level === "error") ? 1 : 0;
279
299
  }
@@ -331,6 +351,55 @@ async function main(argv) {
331
351
  await gw.close();
332
352
  return 0;
333
353
  }
354
+ case "door": {
355
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" }, port: { type: "string", default: "8780" }, host: { type: "string", default: "127.0.0.1" } } });
356
+ if (!values.config)
357
+ throw new Error("door needs --config");
358
+ const cfg = loadDoorConfig(values.config);
359
+ const host = await createDoorHost(cfg, { autoFlush: true });
360
+ const running = await serveDoor(host, { port: Number(values.port), host: values.host });
361
+ console.error(`agent-custody door: ${running.url} keyid=${host.keyid} in front of ${cfg.origin.url}; ${cfg.routes.length} route(s), unmatched arrivals are "${cfg.unmatchedRoute}"`);
362
+ await untilStopped();
363
+ await running.close();
364
+ await host.close();
365
+ return 0;
366
+ }
367
+ case "init": {
368
+ const [target, ...args] = rest;
369
+ if (target !== "claude-code")
370
+ throw new Error("init needs a target: init claude-code");
371
+ const { values } = parseArgs({
372
+ args,
373
+ options: {
374
+ dir: { type: "string" },
375
+ user: { type: "boolean", default: false },
376
+ enforce: { type: "boolean", default: false },
377
+ "log-url": { type: "string" },
378
+ "log-id": { type: "string" },
379
+ "log-token-env": { type: "string" },
380
+ "log-key": { type: "string" },
381
+ },
382
+ });
383
+ initClaudeCode({
384
+ cliPath: fileURLToPath(import.meta.url),
385
+ ...(values.dir ? { dir: values.dir } : {}),
386
+ user: values.user,
387
+ enforce: values.enforce,
388
+ ...(values["log-url"] ? { logUrl: values["log-url"] } : {}),
389
+ ...(values["log-id"] ? { logId: values["log-id"] } : {}),
390
+ ...(values["log-token-env"] ? { logTokenEnv: values["log-token-env"] } : {}),
391
+ ...(values["log-key"] ? { logKey: values["log-key"] } : {}),
392
+ });
393
+ return 0;
394
+ }
395
+ case "report": {
396
+ const { values } = parseArgs({ args: rest, options: { config: { type: "string" } } });
397
+ if (!values.config)
398
+ throw new Error("report needs --config <sdk.json>");
399
+ const report = denyReport(resolve(values.config));
400
+ console.log(formatDenyReport(report));
401
+ return report.unverified.length ? 1 : 0;
402
+ }
334
403
  case "hook": {
335
404
  const { values } = parseArgs({ args: rest, options: { config: { type: "string" } } });
336
405
  const configPath = values.config ?? process.env.AGENT_CUSTODY_CONFIG;
@@ -726,18 +795,20 @@ async function main(argv) {
726
795
  disclose: { type: "string" },
727
796
  "capture-key-env": { type: "string" },
728
797
  json: { type: "boolean", default: false },
798
+ markdown: { type: "boolean", default: false },
729
799
  },
730
800
  });
731
801
  const file = positionals[0];
732
802
  const issuerKeyFiles = [...(values["issuer-key"] ?? []), ...(values["gateway-key"] ?? [])];
733
803
  if (!file || issuerKeyFiles.length === 0)
734
804
  throw new Error("verify needs <bundle> --issuer-key (alias --gateway-key)");
735
- const bundle = JSON.parse(readFileSync(file, "utf8"));
805
+ if (values.markdown && (values.json || values.disclose))
806
+ throw new Error("verify --markdown does not combine with --json or --disclose");
736
807
  const captureKey = values["capture-key-env"] ? captureKeyFrom(secretFrom(values["capture-key-env"])) : undefined;
737
808
  const disclosed = values.disclose ? JSON.parse(readFileSync(values.disclose, "utf8")) : undefined;
738
809
  const fetchedLogKeys = values["log-url"] ? (await fetchLogKeys(values["log-url"])).keys : [];
739
810
  const logKeys = [...(values["log-key"] ?? []).map(loadPublicKey), ...fetchedLogKeys];
740
- const result = verifyBundle(bundle, {
811
+ const verifyOptions = {
741
812
  issuerKeys: issuerKeyFiles.map(loadPublicKey),
742
813
  principalKeys: (values["principal-key"] ?? []).map(loadPublicKey),
743
814
  ...(values["approval-key"] ? { approvalKeys: values["approval-key"].map(loadPublicKey) } : {}),
@@ -749,10 +820,54 @@ async function main(argv) {
749
820
  ...(values.log ? { logFile: values.log } : {}),
750
821
  ...(captureKey ? { captureKey } : {}),
751
822
  ...(disclosed ? { disclosed } : {}),
752
- });
823
+ };
824
+ if (values.markdown) {
825
+ const summary = summarizeReceipts(positionals.flatMap(receiptFiles), verifyOptions);
826
+ console.log(formatSummaryMarkdown(summary));
827
+ return summary.ok ? 0 : 1;
828
+ }
829
+ const result = verifyBundle(JSON.parse(readFileSync(file, "utf8")), verifyOptions);
753
830
  console.log(values.json ? JSON.stringify(result, null, 2) : formatReport(result));
754
831
  return result.ok ? 0 : 1;
755
832
  }
833
+ case "export": {
834
+ const { values } = parseArgs({
835
+ args: rest,
836
+ options: {
837
+ receipts: { type: "string" },
838
+ out: { type: "string" },
839
+ "issuer-key": { type: "string", multiple: true },
840
+ "principal-key": { type: "string", multiple: true },
841
+ "approval-key": { type: "string", multiple: true },
842
+ since: { type: "string" },
843
+ "allow-clear": { type: "boolean", default: false },
844
+ },
845
+ });
846
+ if (!values.receipts || !values.out || !values["issuer-key"]?.length)
847
+ throw new Error("export needs --receipts <dir>, --out <dir> and --issuer-key <pub>");
848
+ // Date.parse reads "1" as the year 2001, so the text must start with a date
849
+ const since = values.since === undefined ? undefined : /^\d{4}-\d{2}-\d{2}/.test(values.since) ? Date.parse(values.since) : NaN;
850
+ if (since !== undefined && !Number.isFinite(since))
851
+ throw new Error(`--since must be an ISO time; got "${values.since}"`);
852
+ const result = exportReceipts({
853
+ receiptsDir: values.receipts,
854
+ outDir: values.out,
855
+ verify: {
856
+ issuerKeys: values["issuer-key"].map(loadPublicKey),
857
+ principalKeys: (values["principal-key"] ?? []).map(loadPublicKey),
858
+ ...(values["approval-key"] ? { approvalKeys: values["approval-key"].map(loadPublicKey) } : {}),
859
+ },
860
+ ...(since !== undefined ? { since } : {}),
861
+ allowClear: values["allow-clear"],
862
+ });
863
+ for (const line of formatExportLines(result))
864
+ console.log(line);
865
+ if (result.lines.some((l) => l.outcome === "copied" && l.clear.length))
866
+ console.error(CLEAR_WARNING);
867
+ if (result.problem)
868
+ console.error(`agent-custody export: ${result.problem}`);
869
+ return result.refused > 0 || result.copied === 0 ? 1 : 0;
870
+ }
756
871
  case "completeness": {
757
872
  const { values } = parseArgs({
758
873
  args: rest,
@@ -820,7 +935,7 @@ async function main(argv) {
820
935
  case "policy": {
821
936
  const [subcommand, ...args] = rest;
822
937
  if (subcommand !== "simulate")
823
- throw new Error("policy needs the simulate subcommand: policy simulate --policy <proposed.cedar> --receipts <dir> --issuer-key <pub>");
938
+ throw new Error("policy needs the simulate subcommand: policy simulate --policy <proposed.cedar|.rego> --receipts <dir> --issuer-key <pub>");
824
939
  const { values } = parseArgs({
825
940
  args,
826
941
  options: {
@@ -837,7 +952,7 @@ async function main(argv) {
837
952
  },
838
953
  });
839
954
  if (!values.policy || !values.receipts || !values["issuer-key"]?.length)
840
- throw new Error("policy simulate needs --policy <proposed.cedar> --receipts <dir> --issuer-key <pub>");
955
+ throw new Error("policy simulate needs --policy <proposed.cedar|.rego> --receipts <dir> --issuer-key <pub>");
841
956
  const policy = readFileSync(values.policy, "utf8");
842
957
  const keys = {
843
958
  issuerKeys: values["issuer-key"].map(loadPublicKey),
@@ -901,7 +1016,7 @@ async function main(argv) {
901
1016
  }
902
1017
  }
903
1018
  }
904
- const report = simulatePolicy(policy, verified(), { unreplayable, ...(captureKey ? { captureKey } : {}), disclosures });
1019
+ const report = simulatePolicy(policy, verified(), { unreplayable, ...(captureKey ? { captureKey } : {}), disclosures, language: isRegoFile(values.policy) ? "rego" : "cedar" });
905
1020
  const json = JSON.stringify(report, null, 2);
906
1021
  if (values.out) {
907
1022
  // Reports name calls and decisions: keep them owner-only, including when replacing an existing file.
package/dist/config.d.ts CHANGED
@@ -248,7 +248,13 @@ export declare const GatewayConfigSchema: z.ZodObject<{
248
248
  }, z.core.$strip>>>>;
249
249
  grantFile: z.ZodOptional<z.ZodString>;
250
250
  trustedPrincipalKeys: z.ZodArray<z.ZodString>;
251
- policyFile: z.ZodString;
251
+ policyFile: z.ZodOptional<z.ZodString>;
252
+ opa: z.ZodOptional<z.ZodObject<{
253
+ url: z.ZodString;
254
+ decision: z.ZodOptional<z.ZodString>;
255
+ tokenEnv: z.ZodOptional<z.ZodString>;
256
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
257
+ }, z.core.$strip>>;
252
258
  facts: z.ZodDefault<z.ZodArray<z.ZodObject<{
253
259
  name: z.ZodString;
254
260
  tool: z.ZodString;
@@ -357,6 +363,127 @@ export type GatewayConfig = z.infer<typeof GatewayConfigSchema>;
357
363
  export type FactConfig = z.infer<typeof FactSchema>;
358
364
  /** Loads a config file and resolves every path relative to the file's directory. */
359
365
  export declare function loadConfig(path: string): GatewayConfig;
366
+ /** One route of the door: a name the policy sees as the action, and what arrives there. `path` is exact, a prefix when it ends in `/*`, or `*` for anything. The first route that matches wins. */
367
+ declare const DoorRouteSchema: z.ZodObject<{
368
+ name: z.ZodString;
369
+ methods: z.ZodOptional<z.ZodArray<z.ZodEnum<{
370
+ DELETE: "DELETE";
371
+ GET: "GET";
372
+ HEAD: "HEAD";
373
+ OPTIONS: "OPTIONS";
374
+ PATCH: "PATCH";
375
+ POST: "POST";
376
+ PUT: "PUT";
377
+ }>>>;
378
+ path: z.ZodString;
379
+ }, z.core.$strip>;
380
+ export type DoorRouteConfig = z.infer<typeof DoorRouteSchema>;
381
+ /**
382
+ * The door: a reverse proxy in front of a business's own website, API, or forms. Every arrival is classified (verified,
383
+ * claimed, or unknown), decided by the Cedar policy per route, forwarded to the origin or refused, and receipted either
384
+ * way. The origin's credentials, if any, come from the environment through headerEnv, never from the file or the caller.
385
+ */
386
+ export declare const DoorConfigSchema: z.ZodObject<{
387
+ identity: z.ZodObject<{
388
+ keyFile: z.ZodString;
389
+ }, z.core.$strip>;
390
+ origin: z.ZodObject<{
391
+ url: z.ZodString;
392
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
393
+ headerEnv: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
394
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
395
+ }, z.core.$strip>;
396
+ routes: z.ZodDefault<z.ZodArray<z.ZodObject<{
397
+ name: z.ZodString;
398
+ methods: z.ZodOptional<z.ZodArray<z.ZodEnum<{
399
+ DELETE: "DELETE";
400
+ GET: "GET";
401
+ HEAD: "HEAD";
402
+ OPTIONS: "OPTIONS";
403
+ PATCH: "PATCH";
404
+ POST: "POST";
405
+ PUT: "PUT";
406
+ }>>>;
407
+ path: z.ZodString;
408
+ }, z.core.$strip>>>;
409
+ unmatchedRoute: z.ZodDefault<z.ZodString>;
410
+ trustedPrincipalKeys: z.ZodDefault<z.ZodArray<z.ZodString>>;
411
+ policyFile: z.ZodString;
412
+ mode: z.ZodOptional<z.ZodEnum<{
413
+ enforce: "enforce";
414
+ observe: "observe";
415
+ }>>;
416
+ trustProxy: z.ZodOptional<z.ZodBoolean>;
417
+ maxBodyBytes: z.ZodDefault<z.ZodNumber>;
418
+ maxResponseBytes: z.ZodDefault<z.ZodNumber>;
419
+ maxInFlight: z.ZodDefault<z.ZodNumber>;
420
+ precommit: z.ZodDefault<z.ZodArray<z.ZodString>>;
421
+ challenge: z.ZodOptional<z.ZodObject<{
422
+ provider: z.ZodEnum<{
423
+ hcaptcha: "hcaptcha";
424
+ turnstile: "turnstile";
425
+ }>;
426
+ siteKey: z.ZodString;
427
+ secretEnv: z.ZodString;
428
+ header: z.ZodDefault<z.ZodString>;
429
+ timeoutMs: z.ZodDefault<z.ZodNumber>;
430
+ hostnames: z.ZodArray<z.ZodPipe<z.ZodString, z.ZodTransform<string, string>>>;
431
+ action: z.ZodOptional<z.ZodString>;
432
+ maxInFlight: z.ZodDefault<z.ZodNumber>;
433
+ }, z.core.$strip>>;
434
+ receiptsDir: z.ZodString;
435
+ logFile: z.ZodOptional<z.ZodString>;
436
+ log: z.ZodOptional<z.ZodObject<{
437
+ url: z.ZodString;
438
+ tokenEnv: z.ZodOptional<z.ZodString>;
439
+ hashOnly: z.ZodOptional<z.ZodBoolean>;
440
+ timeoutMs: z.ZodOptional<z.ZodNumber>;
441
+ keys: z.ZodOptional<z.ZodArray<z.ZodString>>;
442
+ logId: z.ZodOptional<z.ZodString>;
443
+ }, z.core.$strip>>;
444
+ otel: z.ZodOptional<z.ZodObject<{
445
+ url: z.ZodString;
446
+ headersEnv: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
447
+ serviceName: z.ZodOptional<z.ZodString>;
448
+ }, z.core.$strip>>;
449
+ splunk: z.ZodOptional<z.ZodObject<{
450
+ url: z.ZodString;
451
+ tokenEnv: z.ZodString;
452
+ index: z.ZodOptional<z.ZodString>;
453
+ source: z.ZodOptional<z.ZodString>;
454
+ sourcetype: z.ZodOptional<z.ZodString>;
455
+ host: z.ZodOptional<z.ZodString>;
456
+ }, z.core.$strip>>;
457
+ capture: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodObject<{
458
+ args: z.ZodOptional<z.ZodObject<{
459
+ mode: z.ZodEnum<{
460
+ clear: "clear";
461
+ digest: "digest";
462
+ encrypted: "encrypted";
463
+ }>;
464
+ clear: z.ZodOptional<z.ZodArray<z.ZodString>>;
465
+ }, z.core.$strip>>;
466
+ result: z.ZodOptional<z.ZodObject<{
467
+ mode: z.ZodEnum<{
468
+ clear: "clear";
469
+ digest: "digest";
470
+ encrypted: "encrypted";
471
+ }>;
472
+ clear: z.ZodOptional<z.ZodArray<z.ZodString>>;
473
+ }, z.core.$strip>>;
474
+ facts: z.ZodOptional<z.ZodObject<{
475
+ mode: z.ZodEnum<{
476
+ clear: "clear";
477
+ digest: "digest";
478
+ encrypted: "encrypted";
479
+ }>;
480
+ clear: z.ZodOptional<z.ZodArray<z.ZodString>>;
481
+ }, z.core.$strip>>;
482
+ }, z.core.$strip>>>;
483
+ captureKeyEnv: z.ZodOptional<z.ZodString>;
484
+ }, z.core.$strip>;
485
+ export type DoorConfig = z.infer<typeof DoorConfigSchema>;
486
+ export declare function loadDoorConfig(path: string): DoorConfig;
360
487
  export declare const SdkConfigSchema: z.ZodObject<{
361
488
  agentId: z.ZodString;
362
489
  principalId: z.ZodOptional<z.ZodString>;