@agent-custody/receipts 0.13.0 → 0.14.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 +16 -11
- package/dist/claude-init.d.ts +46 -0
- package/dist/claude-init.js +208 -0
- package/dist/cli.js +44 -0
- package/dist/deny-report.d.ts +30 -0
- package/dist/deny-report.js +106 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/log-admin.js +3 -3
- package/dist/log.d.ts +13 -2
- package/dist/log.js +97 -17
- package/dist/policy.d.ts +6 -0
- package/dist/policy.js +17 -0
- package/dist/sdk/claude.js +18 -2
- package/dist/sdk/index.d.ts +2 -0
- package/dist/sdk/index.js +3 -1
- package/dist/witness.js +3 -3
- package/docs/compliance.md +117 -7
- package/docs/policies.md +12 -0
- package/docs/sdk.md +83 -1
- package/docs/tutorials.md +2 -0
- package/docs/usage.md +1 -1
- package/package.json +3 -2
- package/templates/claude-code.cedar +96 -0
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ 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):
|
|
13
|
+
- [Tutorials](docs/tutorials.md): 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
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
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
|
|
@@ -20,7 +20,7 @@ Anyone holding the public keys can verify a receipt offline. The agent is not tr
|
|
|
20
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
|
|
21
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`
|
|
22
22
|
- [Verifying a receipt](docs/verification.md): what each check means and what a verified receipt does and does not prove
|
|
23
|
-
- [What the evidence satisfies](docs/compliance.md): the receipts, packs, and certificates mapped to SOC 2, ISO 27001, the EU AI Act, and
|
|
23
|
+
- [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
|
|
24
24
|
- [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
|
|
25
25
|
- [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
|
|
26
26
|
- [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
|
|
@@ -38,7 +38,7 @@ Published on npm as [`@agent-custody/receipts`](https://www.npmjs.com/package/@a
|
|
|
38
38
|
Record receipts from inside your own agent, no gateway needed. Generate a signing key, point a config at it, wrap the functions the agent calls:
|
|
39
39
|
|
|
40
40
|
```bash
|
|
41
|
-
npx agent-custody keygen --dir keys --name app
|
|
41
|
+
npx @agent-custody/receipts keygen --dir keys --name app
|
|
42
42
|
```
|
|
43
43
|
|
|
44
44
|
```json
|
|
@@ -56,7 +56,9 @@ const bundle = JSON.parse(readFileSync("receipts/<id>.json", "utf8"));
|
|
|
56
56
|
verifyBundle(bundle, { issuerKeys: [loadPublicKey("keys/app.pub")], logFile: "log.jsonl" }).ok; // true
|
|
57
57
|
```
|
|
58
58
|
|
|
59
|
-
|
|
59
|
+
For your own Claude Code sessions, one command does the whole setup (key, config in observe mode, starter deny policy, hooks), and `agent-custody report` lists the calls the policy would have denied: `npx @agent-custody/receipts init claude-code`, then see [docs/sdk.md](docs/sdk.md#claude-code).
|
|
60
|
+
|
|
61
|
+
Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the Vercel AI SDK, LangChain, OpenClaw, DeepSeek Harness, Hermes and Google ADK, are in [docs/sdk.md](docs/sdk.md). To enforce rather than record, put the gateway between the agent and its tools: `npx @agent-custody/receipts gateway --config gateway.json`, set up in [docs/usage.md](docs/usage.md); between an agent and the agents it delegates to over A2A, `--a2a` serves the gateway as an A2A agent itself. The gateway is listed in the [MCP Registry](https://registry.modelcontextprotocol.io/) as `io.github.svayatta/agent-custody`; its entry is [server.json](server.json), published after each npm release by running the `mcp-registry` workflow from the Actions tab (GitHub OIDC, no token).
|
|
60
62
|
|
|
61
63
|
## How it fits together
|
|
62
64
|
|
|
@@ -114,7 +116,7 @@ Every receipt names its issuer, and the verifier prints what that issuer kind is
|
|
|
114
116
|
| --- | --- | --- | --- | --- |
|
|
115
117
|
| any MCP host: Claude Desktop, Claude Code, Cursor, custom | gateway | yes | | a real MCP client and upstream over stdio |
|
|
116
118
|
| Codex CLI (headless) | gateway | yes | | a manual `codex exec` run and offline MCP recovery checks; [guide](docs/codex-recovery.md) |
|
|
117
|
-
| Claude Code | SDK | `hook` command, PreToolUse deny | PostToolUse | the documented hook contract, via stdin |
|
|
119
|
+
| Claude Code | SDK | `hook` command, PreToolUse deny; `init claude-code` sets it up | PostToolUse | the documented hook contract, via stdin; `init` and `report` against a temporary home |
|
|
118
120
|
| Claude Agent SDK | SDK | `claudeAgentHooks` | same | the same handler |
|
|
119
121
|
| OpenAI Agents SDK (JS) | SDK | `wrapTools` | `observeRunner` | a real `Runner` with a scripted model |
|
|
120
122
|
| Vercel AI SDK | SDK | `wrapTools` | | a real `generateText` loop over the SDK's mock model |
|
|
@@ -193,7 +195,7 @@ Every field carries a provenance label. This is the design decision that matters
|
|
|
193
195
|
bun install # from the repository root, once for the workspace
|
|
194
196
|
cd packages/receipts
|
|
195
197
|
node scripts/demo.ts # gateway: keys, grant, policy, four tool calls, verification, a tampering attempt; then the SDK wrapping the same tool
|
|
196
|
-
node examples/01-keys-and-signing.ts # first of
|
|
198
|
+
node examples/01-keys-and-signing.ts # first of the step-by-step examples, see docs/tutorials.md
|
|
197
199
|
bun run test # this package; `bun run test` at the root runs every package
|
|
198
200
|
```
|
|
199
201
|
|
|
@@ -244,7 +246,7 @@ If a vendor tells you their receipts prove more than the first five rows, ask th
|
|
|
244
246
|
```
|
|
245
247
|
src/config.ts gateway and SDK config schemas, path resolution
|
|
246
248
|
src/crypto.ts canonical JSON, sha256, Ed25519 keys, DSSE sign/verify
|
|
247
|
-
src/log.ts Merkle log: append, root, inclusion and consistency proofs, verify, JSONL persistence
|
|
249
|
+
src/log.ts Merkle log: append, root, inclusion and consistency proofs, verify, JSONL persistence; an O_EXCL lock file makes an append safe when several processes share one log file
|
|
248
250
|
src/log-check.ts the outside monitor: verifies the head, checkpoints, witness, and anchor of a running log
|
|
249
251
|
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
|
|
250
252
|
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)
|
|
@@ -278,12 +280,15 @@ src/upstream.ts attested execution: an upstream signs its result for the rece
|
|
|
278
280
|
src/capture.ts private evidence: per-tool capture rules applied by the issuer to the whole statement, withheld values as salted commitments or encrypted under the customer's key, restore and reveal
|
|
279
281
|
vectors/ conformance vectors: receipts, keys, logs, proofs, and expected verdicts; `bun run vectors` regenerates them
|
|
280
282
|
src/verify.ts offline verification, the human-readable report, and the audit that a later log extends an earlier one
|
|
281
|
-
src/
|
|
283
|
+
src/claude-init.ts `init claude-code`: the agent key, the observe-mode config, the starter policy, and the three hooks merged into the settings file with absolute paths
|
|
284
|
+
src/deny-report.ts `report`: verifies the receipts of an SDK config and lists the calls the policy would have denied
|
|
285
|
+
templates/ the starter Cedar policy that `init claude-code` copies (shipped in the package)
|
|
286
|
+
src/cli.ts keygen, grant, gateway, init, report, hook, serve, log, prune, verify, reveal, audit, policy simulate
|
|
282
287
|
src/retention.ts pruning the log: leaves become their hashes, bundles are removed, proofs survive
|
|
283
288
|
src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
|
|
284
289
|
tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
|
|
285
290
|
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
|
|
286
|
-
examples/
|
|
291
|
+
examples/ 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
|
|
287
292
|
test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
|
|
288
293
|
adapter tests against the real packages, and a test that runs every policy in docs/policies.md
|
|
289
294
|
docs/ tutorials, usage (gateway), codex-recovery (live demo), approvals, sdk, policies, verification
|
|
@@ -295,6 +300,8 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
|
|
|
295
300
|
|
|
296
301
|
**Done**
|
|
297
302
|
|
|
303
|
+
- An incident replay: `node examples/38-incident-replay.ts` plays a Claude Code session against the starter deny set in enforce mode. `terraform destroy` and `rm -rf ~` are denied before they run, and the denial receipts verify offline with the public key only. The site page [An incident replay](../../site/guide/incident-replay.md) shows the output and the limit: a credential in the agent's environment goes around the hook (tutorial 38).
|
|
304
|
+
- One command for Claude Code (issue #204): `agent-custody init claude-code` makes the agent key, writes `sdk.json` in observe mode with no log, writes a starter deny policy, and merges the three hooks into `.claude/settings.local.json` or `~/.claude/settings.json` with absolute paths, safe to run two times. `agent-custody report` verifies the receipts and prints the calls the policy would have denied, with the reason, the rule, and the receipt id; removing the `mode` line enforces. The default local log takes a lock for each append, so hooks that run at the same time keep one log; `--log-url` needs `--log-key`; a second run keeps the pinned log key and warns about log flags it does not apply; `init` warns when git does not ignore the project settings file ([sdk.md](docs/sdk.md#claude-code), tutorial 36).
|
|
298
305
|
- 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).
|
|
299
306
|
- 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)).
|
|
300
307
|
- 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.
|
|
@@ -353,5 +360,3 @@ The first three close the gap between a log the operator cannot rewrite and a re
|
|
|
353
360
|
5. Post-quantum signatures: ML-DSA beside Ed25519 in the same DSSE envelope, hybrid by default when a PQ key is present, in every signed artefact and in the browser verifier. [Issue #11](https://github.com/svayatta/agent-custody/issues/11).
|
|
354
361
|
6. Receiver attestation for agent-to-agent calls: the delegate signs its answer for the receipt, as a signing upstream does today.
|
|
355
362
|
7. SD-JWT redaction, then ZK proofs of policy compliance. Not before.
|
|
356
|
-
|
|
357
|
-
A Python SDK follows the same shape once the TypeScript adapters have settled.
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export declare const HOOK_EVENTS: readonly ["PreToolUse", "PostToolUse", "PostToolUseFailure"];
|
|
2
|
+
export declare const HOOK_MATCHER = "Bash|Write|Edit|MultiEdit|NotebookEdit|mcp__.*";
|
|
3
|
+
export interface ClaudeInitOptions {
|
|
4
|
+
/** The absolute path of the CLI script that runs now. The hook runs this script. */
|
|
5
|
+
cliPath: string;
|
|
6
|
+
/** The Node binary that the hook runs. Default: the binary that runs now. */
|
|
7
|
+
nodePath?: string;
|
|
8
|
+
/** Default: `~/.config/agent-custody` */
|
|
9
|
+
dir?: string;
|
|
10
|
+
/** Write the hooks to `~/.claude/settings.json`. Default: `.claude/settings.local.json` in `cwd`. */
|
|
11
|
+
user?: boolean;
|
|
12
|
+
/** Leave out `"mode": "observe"`, so the policy blocks a denied call. */
|
|
13
|
+
enforce?: boolean;
|
|
14
|
+
logUrl?: string;
|
|
15
|
+
logId?: string;
|
|
16
|
+
/** The NAME of the environment variable that holds the log token. Never the token. */
|
|
17
|
+
logTokenEnv?: string;
|
|
18
|
+
/** The log's public key file. A log URL needs it. The command copies it into the directory when it writes a new config. */
|
|
19
|
+
logKey?: string;
|
|
20
|
+
home?: string;
|
|
21
|
+
cwd?: string;
|
|
22
|
+
/** One line of progress. Default: stdout. */
|
|
23
|
+
print?: (line: string) => void;
|
|
24
|
+
}
|
|
25
|
+
export interface ClaudeInitResult {
|
|
26
|
+
dir: string;
|
|
27
|
+
configFile: string;
|
|
28
|
+
settingsFile: string;
|
|
29
|
+
hookCommand: string;
|
|
30
|
+
}
|
|
31
|
+
/** A shell word for a path: bare when it is plain, in single quotes otherwise. */
|
|
32
|
+
export declare function shellQuote(s: string): string;
|
|
33
|
+
type Json = Record<string, unknown>;
|
|
34
|
+
/** Parses a settings file. Throws, and so changes nothing, when the text is not a JSON object with usable `hooks`. */
|
|
35
|
+
export declare function parseSettings(text: string, file: string): Json;
|
|
36
|
+
export type HookChange = "added" | "updated" | "kept";
|
|
37
|
+
/**
|
|
38
|
+
* Registers the hook command for the three events and keeps every other key and hook. A hook of ours is a command
|
|
39
|
+
* that ends with `hook --config <this config>`. It is updated in place when its command differs, and never added twice.
|
|
40
|
+
*/
|
|
41
|
+
export declare function mergeHooks(settings: Json, command: string, configFile: string): {
|
|
42
|
+
settings: Json;
|
|
43
|
+
changes: Record<string, HookChange>;
|
|
44
|
+
};
|
|
45
|
+
export declare function initClaudeCode(o: ClaudeInitOptions): ClaudeInitResult;
|
|
46
|
+
export {};
|
|
@@ -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
|
@@ -31,6 +31,9 @@ import { serveConsole } from "./console.js";
|
|
|
31
31
|
import { TREEHEAD_TYPE } from "./receipt.js";
|
|
32
32
|
import { MerkleLog } from "./log.js";
|
|
33
33
|
import { createSdkIssuer } from "./sdk/index.js";
|
|
34
|
+
import { initClaudeCode } from "./claude-init.js";
|
|
35
|
+
import { denyReport, formatDenyReport } from "./deny-report.js";
|
|
36
|
+
import { fileURLToPath } from "node:url";
|
|
34
37
|
import { handleHookEvent } from "./sdk/claude.js";
|
|
35
38
|
import { auditExtends, formatReport, verifyBundle } from "./verify.js";
|
|
36
39
|
import { formatSimulation, simulatePolicy, verifyOrphanAuthorization } from "./simulate.js";
|
|
@@ -87,6 +90,11 @@ const USAGE = `agent-custody <command>
|
|
|
87
90
|
gateway --config <gateway.json> [--http [--port 8790] [--host 127.0.0.1] [--idle-minutes 30]]
|
|
88
91
|
stdio: one gateway for the grant the config names. --http: one shared gateway, MCP over
|
|
89
92
|
Streamable HTTP at /mcp, each connection presenting its own grant as Authorization: Bearer
|
|
93
|
+
init claude-code [--dir <dir>] [--user] [--enforce] [--log-url <url> [--log-id <id>] [--log-token-env NAME] [--log-key <pub>]]
|
|
94
|
+
one command for your own Claude Code sessions: an agent key, sdk.json in observe mode, a starter deny
|
|
95
|
+
policy, and the three hooks in .claude/settings.local.json (--user: ~/.claude/settings.json). Safe to run twice
|
|
96
|
+
report --config <sdk.json> the calls that the policy would have denied, from the receipts: tool, command or path, rule, receipt id;
|
|
97
|
+
a receipt that does not verify is counted apart. Exits 1 when any receipt does not verify
|
|
90
98
|
hook [--config <sdk.json>] Claude Code hook command; reads the event on stdin (or AGENT_CUSTODY_CONFIG)
|
|
91
99
|
serve --config <sdk.json> [--port 8788] [--host 127.0.0.1] the SDK as a local HTTP API for agents in other languages
|
|
92
100
|
prune --log <log.jsonl> --before <ISO instant> [--receipts <dir>]
|
|
@@ -331,6 +339,42 @@ async function main(argv) {
|
|
|
331
339
|
await gw.close();
|
|
332
340
|
return 0;
|
|
333
341
|
}
|
|
342
|
+
case "init": {
|
|
343
|
+
const [target, ...args] = rest;
|
|
344
|
+
if (target !== "claude-code")
|
|
345
|
+
throw new Error("init needs a target: init claude-code");
|
|
346
|
+
const { values } = parseArgs({
|
|
347
|
+
args,
|
|
348
|
+
options: {
|
|
349
|
+
dir: { type: "string" },
|
|
350
|
+
user: { type: "boolean", default: false },
|
|
351
|
+
enforce: { type: "boolean", default: false },
|
|
352
|
+
"log-url": { type: "string" },
|
|
353
|
+
"log-id": { type: "string" },
|
|
354
|
+
"log-token-env": { type: "string" },
|
|
355
|
+
"log-key": { type: "string" },
|
|
356
|
+
},
|
|
357
|
+
});
|
|
358
|
+
initClaudeCode({
|
|
359
|
+
cliPath: fileURLToPath(import.meta.url),
|
|
360
|
+
...(values.dir ? { dir: values.dir } : {}),
|
|
361
|
+
user: values.user,
|
|
362
|
+
enforce: values.enforce,
|
|
363
|
+
...(values["log-url"] ? { logUrl: values["log-url"] } : {}),
|
|
364
|
+
...(values["log-id"] ? { logId: values["log-id"] } : {}),
|
|
365
|
+
...(values["log-token-env"] ? { logTokenEnv: values["log-token-env"] } : {}),
|
|
366
|
+
...(values["log-key"] ? { logKey: values["log-key"] } : {}),
|
|
367
|
+
});
|
|
368
|
+
return 0;
|
|
369
|
+
}
|
|
370
|
+
case "report": {
|
|
371
|
+
const { values } = parseArgs({ args: rest, options: { config: { type: "string" } } });
|
|
372
|
+
if (!values.config)
|
|
373
|
+
throw new Error("report needs --config <sdk.json>");
|
|
374
|
+
const report = denyReport(resolve(values.config));
|
|
375
|
+
console.log(formatDenyReport(report));
|
|
376
|
+
return report.unverified.length ? 1 : 0;
|
|
377
|
+
}
|
|
334
378
|
case "hook": {
|
|
335
379
|
const { values } = parseArgs({ args: rest, options: { config: { type: "string" } } });
|
|
336
380
|
const configPath = values.config ?? process.env.AGENT_CUSTODY_CONFIG;
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export interface DeniedCall {
|
|
2
|
+
receiptId: string;
|
|
3
|
+
timestamp: string;
|
|
4
|
+
tool: string;
|
|
5
|
+
/** The command, the file path, or the URL of the call. */
|
|
6
|
+
target: string;
|
|
7
|
+
/** The Cedar policy ids that decided, such as `policy3`. */
|
|
8
|
+
policyIds: string[];
|
|
9
|
+
/** The `@reason` of each rule that has one. */
|
|
10
|
+
reasons: string[];
|
|
11
|
+
/** The text of each rule, when the policy file still has the digest that the receipt names. */
|
|
12
|
+
rules: string[];
|
|
13
|
+
}
|
|
14
|
+
export interface DenyReport {
|
|
15
|
+
configFile: string;
|
|
16
|
+
receiptsDir: string;
|
|
17
|
+
observe: boolean;
|
|
18
|
+
/** Receipts that verified. */
|
|
19
|
+
verified: number;
|
|
20
|
+
/** Denials recorded with `enforced: false`: the call ran. */
|
|
21
|
+
wouldDeny: DeniedCall[];
|
|
22
|
+
/** Denials that the policy enforced: the call was blocked. */
|
|
23
|
+
denied: DeniedCall[];
|
|
24
|
+
unverified: {
|
|
25
|
+
file: string;
|
|
26
|
+
reason: string;
|
|
27
|
+
}[];
|
|
28
|
+
}
|
|
29
|
+
export declare function denyReport(configFile: string): DenyReport;
|
|
30
|
+
export declare function formatDenyReport(r: DenyReport): string;
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
// `agent-custody report`: the calls that the policy would have denied, read from the receipts of an SDK config.
|
|
2
|
+
// Each receipt is verified with the agent's key first. A receipt that does not verify is counted apart and never listed as a denial.
|
|
3
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { loadSdkConfig } from "./config.js";
|
|
6
|
+
import { loadPrivateKey, loadPublicKey } from "./crypto.js";
|
|
7
|
+
import { policyDigest, policyReasons, policyRules } from "./policy.js";
|
|
8
|
+
import { verifyBundle } from "./verify.js";
|
|
9
|
+
const ANNOTATIONS = /^(?:\s*@\w+\s*\("(?:[^"\\]|\\.)*"\))+\s*/;
|
|
10
|
+
const TARGET_ARGS = ["command", "file_path", "notebook_path", "path", "url"];
|
|
11
|
+
function targetOf(args) {
|
|
12
|
+
if (!args || typeof args !== "object")
|
|
13
|
+
return "(withheld)";
|
|
14
|
+
const a = args;
|
|
15
|
+
const name = TARGET_ARGS.find((k) => typeof a[k] === "string");
|
|
16
|
+
const text = name ? a[name] : JSON.stringify(a);
|
|
17
|
+
return text.replace(/\s+/g, " ").trim();
|
|
18
|
+
}
|
|
19
|
+
export function denyReport(configFile) {
|
|
20
|
+
const cfg = loadSdkConfig(configFile);
|
|
21
|
+
const issuer = loadPrivateKey(cfg.identity.keyFile);
|
|
22
|
+
const opts = {
|
|
23
|
+
issuerKeys: [{ publicKey: issuer.publicKey, keyid: issuer.keyid }],
|
|
24
|
+
principalKeys: [],
|
|
25
|
+
logKeys: (cfg.log?.keys ?? []).map(loadPublicKey),
|
|
26
|
+
...(cfg.logFile ? { logFile: cfg.logFile } : {}),
|
|
27
|
+
...(cfg.log?.logId ? { logId: cfg.log.logId } : {}),
|
|
28
|
+
};
|
|
29
|
+
const policyText = cfg.policyFile && existsSync(cfg.policyFile) ? readFileSync(cfg.policyFile, "utf8") : null;
|
|
30
|
+
const rules = policyText === null ? [] : policyRules(policyText);
|
|
31
|
+
const reasons = policyText === null ? [] : policyReasons(policyText);
|
|
32
|
+
const currentDigest = policyText === null ? null : policyDigest(policyText);
|
|
33
|
+
const report = { configFile, receiptsDir: cfg.receiptsDir, observe: cfg.mode === "observe", verified: 0, wouldDeny: [], denied: [], unverified: [] };
|
|
34
|
+
const files = existsSync(cfg.receiptsDir)
|
|
35
|
+
? readdirSync(cfg.receiptsDir, { withFileTypes: true }).filter((e) => (e.isFile() || e.isSymbolicLink()) && e.name.endsWith(".json") && !e.name.endsWith(".authorization.json")).map((e) => e.name).sort()
|
|
36
|
+
: [];
|
|
37
|
+
for (const file of files) {
|
|
38
|
+
try {
|
|
39
|
+
const result = verifyBundle(JSON.parse(readFileSync(join(cfg.receiptsDir, file), "utf8")), opts);
|
|
40
|
+
if (!result.ok || !result.statement) {
|
|
41
|
+
const failed = result.checks.filter((c) => !c.ok).map((c) => c.name);
|
|
42
|
+
throw new Error(`failed: ${failed.join("; ")}`);
|
|
43
|
+
}
|
|
44
|
+
const p = result.statement.predicate;
|
|
45
|
+
if (`${p.receiptId}.json` !== file)
|
|
46
|
+
throw new Error("the file name does not match the receipt id");
|
|
47
|
+
report.verified++;
|
|
48
|
+
if (p.policy?.decision !== "deny")
|
|
49
|
+
continue;
|
|
50
|
+
const policyIds = p.policy.reasons;
|
|
51
|
+
const known = p.policy.policyDigest === currentDigest;
|
|
52
|
+
const call = {
|
|
53
|
+
receiptId: p.receiptId,
|
|
54
|
+
timestamp: p.timestamp,
|
|
55
|
+
tool: p.tool.name,
|
|
56
|
+
target: targetOf(p.request.args),
|
|
57
|
+
policyIds,
|
|
58
|
+
reasons: known ? policyIds.map((id) => reasons[Number(id.replace(/^policy/, ""))]).filter((r) => typeof r === "string") : [],
|
|
59
|
+
rules: known ? policyIds.map((id) => rules[Number(id.replace(/^policy/, ""))]).filter((r) => typeof r === "string").map((r) => r.replace(/\s+/g, " ").replace(/;$/, "").replace(ANNOTATIONS, "").trim()) : [],
|
|
60
|
+
};
|
|
61
|
+
(p.policy.enforced === false ? report.wouldDeny : report.denied).push(call);
|
|
62
|
+
}
|
|
63
|
+
catch (e) {
|
|
64
|
+
report.unverified.push({ file, reason: e instanceof Error ? e.message : String(e) });
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
const byTime = (a, b) => (a.timestamp < b.timestamp ? -1 : a.timestamp > b.timestamp ? 1 : 0);
|
|
68
|
+
report.wouldDeny.sort(byTime);
|
|
69
|
+
report.denied.sort(byTime);
|
|
70
|
+
return report;
|
|
71
|
+
}
|
|
72
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
73
|
+
const clip = (s) => (s.length > 160 ? `${s.slice(0, 157)}...` : s);
|
|
74
|
+
export function formatDenyReport(r) {
|
|
75
|
+
const lines = [];
|
|
76
|
+
const list = (calls) => {
|
|
77
|
+
for (const c of calls) {
|
|
78
|
+
lines.push("", ` ${c.tool}: ${clip(c.target)}`);
|
|
79
|
+
if (c.reasons.length)
|
|
80
|
+
lines.push(` reason: ${c.reasons.join("; ")}`);
|
|
81
|
+
lines.push(` rule: ${c.rules.length ? c.rules.join(" | ") : c.policyIds.join(", ") || "(none)"}${c.rules.length ? ` [${c.policyIds.join(", ")}]` : ""}`);
|
|
82
|
+
lines.push(` receipt: ${c.receiptId} (${c.timestamp})`);
|
|
83
|
+
}
|
|
84
|
+
};
|
|
85
|
+
if (!r.verified && !r.unverified.length) {
|
|
86
|
+
lines.push(`No receipts in ${r.receiptsDir} yet.`, "Start a Claude Code session with the hooks registered, then run this report again.");
|
|
87
|
+
return lines.join("\n");
|
|
88
|
+
}
|
|
89
|
+
lines.push(`would have denied ${plural(r.wouldDeny.length, "call")}${r.wouldDeny.length ? " (the policy recorded each one and blocked nothing)" : ""}`);
|
|
90
|
+
list(r.wouldDeny);
|
|
91
|
+
lines.push("", `Checked ${plural(r.verified + r.unverified.length, "receipt")}: ${r.verified} verified, ${r.unverified.length} did not verify.`);
|
|
92
|
+
if (r.denied.length) {
|
|
93
|
+
lines.push("", `denied ${plural(r.denied.length, "call")} (the policy enforced these, and the call did not run)`);
|
|
94
|
+
list(r.denied);
|
|
95
|
+
}
|
|
96
|
+
if (r.unverified.length) {
|
|
97
|
+
lines.push("", `${plural(r.unverified.length, "receipt")} did not verify. The report does not count them.`);
|
|
98
|
+
for (const u of r.unverified)
|
|
99
|
+
lines.push(` ${u.file}: ${u.reason}`);
|
|
100
|
+
}
|
|
101
|
+
lines.push("");
|
|
102
|
+
lines.push(r.observe
|
|
103
|
+
? `To enforce this policy, remove the "mode": "observe" line from ${r.configFile}. A denied call is then blocked before it runs.`
|
|
104
|
+
: `The config ${r.configFile} has no "mode": "observe" line, so the policy already blocks a denied call.`);
|
|
105
|
+
return lines.join("\n");
|
|
106
|
+
}
|
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
package/dist/log-admin.js
CHANGED
|
@@ -31,12 +31,12 @@ export function welcomeSheet(o) {
|
|
|
31
31
|
"hashOnly means this log never receives your receipts, only their hashes.",
|
|
32
32
|
"",
|
|
33
33
|
"For whoever verifies your receipts:",
|
|
34
|
-
` npx agent-custody verify receipts/<id>.json --issuer-key <your gateway.pub> --principal-key <your principal.pub> --log-url ${url} --log-id ${o.logId}`,
|
|
35
|
-
` npx agent-custody audit --older receipts/<earlier>.json --newer receipts/<later>.json --log-url ${url} --log-id ${o.logId}`,
|
|
34
|
+
` npx @agent-custody/receipts verify receipts/<id>.json --issuer-key <your gateway.pub> --principal-key <your principal.pub> --log-url ${url} --log-id ${o.logId}`,
|
|
35
|
+
` npx @agent-custody/receipts audit --older receipts/<earlier>.json --newer receipts/<later>.json --log-url ${url} --log-id ${o.logId}`,
|
|
36
36
|
"--log-url fetches this log's published keys and pins them; --log-id makes sure the tree heads are this log's.",
|
|
37
37
|
"",
|
|
38
38
|
"Your log is yours to take, any time, with your token:",
|
|
39
|
-
` npx agent-custody log-export --log-url ${url} --tenant ${o.tenant} --token-env AGENT_CUSTODY_LOG_TOKEN --out custody-export/`,
|
|
39
|
+
` npx @agent-custody/receipts log-export --log-url ${url} --tenant ${o.tenant} --token-env AGENT_CUSTODY_LOG_TOKEN --out custody-export/`,
|
|
40
40
|
"It fetches every leaf hash, the signed head, the keys, the checkpoints, and your usage, checks they add up, and writes",
|
|
41
41
|
"a log copy that verify --log and audit --log read with no server.",
|
|
42
42
|
"",
|
package/dist/log.d.ts
CHANGED
|
@@ -26,10 +26,21 @@ export declare function inclusionProof(leafHashes: Buffer[], leafIndex: number,
|
|
|
26
26
|
/** RFC 9162 section 2.1.3.2 verification. Pure function: needs only the leaf hash, proof and claimed root. */
|
|
27
27
|
export declare function verifyInclusion(leaf: Buffer, proof: InclusionProof, rootHex: string): boolean;
|
|
28
28
|
export declare class MerkleLog {
|
|
29
|
-
private hashes;
|
|
30
|
-
private
|
|
29
|
+
private readonly hashes;
|
|
30
|
+
private tree;
|
|
31
31
|
private readonly file;
|
|
32
|
+
private bytes;
|
|
33
|
+
private inode;
|
|
32
34
|
constructor(file: string);
|
|
35
|
+
/** Reads the leaves that another handle or process appended since the last read. A file that was replaced or cut short is read again from the start. */
|
|
36
|
+
private catchUp;
|
|
37
|
+
/**
|
|
38
|
+
* Runs `fn` while this process holds `<file>.lock`, made with O_EXCL. Each hook of a coding agent is its own
|
|
39
|
+
* process, so appends overlap. A lock older than ten seconds belongs to a process that died: the next writer removes it.
|
|
40
|
+
*/
|
|
41
|
+
private locked;
|
|
42
|
+
/** Under the lock: reads what other writers appended, then writes this line, so each leaf gets the next index. */
|
|
43
|
+
private appendLine;
|
|
33
44
|
get size(): number;
|
|
34
45
|
/** Leaf hashes `from` (inclusive) to `to` (exclusive), as hex: what an export carries and what a copy is rebuilt from. */
|
|
35
46
|
leafHashes(from: number, to?: number): string[];
|