@agent-custody/receipts 0.10.0 → 0.11.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/dist/anchor.js ADDED
@@ -0,0 +1,367 @@
1
+ // The anchor: a public chain as a witness nobody can collude with. It watches a log's published checkpoints the way
2
+ // the witness does, and after proving that each new one extends the last one it anchored, it commits a Merkle root
3
+ // over the new checkpoints of every watched log in one transaction from a published address. Each log gets a
4
+ // record with its checkpoint and its inclusion proof, so it can be checked without seeing the other logs. A rewritten
5
+ // tree is then caught from the chain alone, without trusting the log's operator, its checkpoints host, or the anchor's
6
+ // own host. What a chain proves is that a checkpoint existed by a block's time; it says nothing about whether the
7
+ // receipts under it are true.
8
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
9
+ import { join } from "node:path";
10
+ import { canonicalize, dsseVerify } from "./crypto.js";
11
+ import { inclusionProof, leafHash, rootOf, verifyConsistency, verifyInclusion } from "./log.js";
12
+ import { TREEHEAD_TYPE } from "./receipt.js";
13
+ import { fetchLogKeys } from "./signer.js";
14
+ /**
15
+ * EVM chains known by name, with the chain id and a default fee cap in gwei per gas, sized to what one anchor costs
16
+ * there. Any other EVM chain is named by its chain id and needs an explicit cap.
17
+ */
18
+ export const ANCHOR_CHAINS = {
19
+ ethereum: { chainId: 1, maxFeeGwei: 20 },
20
+ base: { chainId: 8453, maxFeeGwei: 1 },
21
+ arbitrum: { chainId: 42161, maxFeeGwei: 1 },
22
+ optimism: { chainId: 10, maxFeeGwei: 1 },
23
+ polygon: { chainId: 137, maxFeeGwei: 1000 },
24
+ };
25
+ /** A chain name from `ANCHOR_CHAINS`, or a decimal chain id; `maxFeeGwei` is undefined for an id with no known default. */
26
+ export function resolveAnchorChain(chain) {
27
+ const known = Object.hasOwn(ANCHOR_CHAINS, chain) ? ANCHOR_CHAINS[chain] : undefined;
28
+ if (known)
29
+ return { name: chain, ...known };
30
+ if (!/^[1-9][0-9]{0,15}$/.test(chain))
31
+ throw new Error(`unknown chain "${chain}": use ${Object.keys(ANCHOR_CHAINS).join(", ")}, or a chain id`);
32
+ const chainId = Number(chain);
33
+ const named = Object.entries(ANCHOR_CHAINS).find(([, c]) => c.chainId === chainId);
34
+ return named ? { name: named[0], ...named[1] } : { name: undefined, chainId, maxFeeGwei: undefined };
35
+ }
36
+ const safe = (s) => s.replace(/[^A-Za-z0-9_.-]/g, "_");
37
+ const slash = (u) => (u.endsWith("/") ? u : `${u}/`);
38
+ const TAG = Buffer.from("agent-custody/anchor/1:").toString("hex");
39
+ /** The calldata of the anchor transaction for a Merkle root: a fixed tag, then the 32-byte root. */
40
+ export function anchorCalldata(rootHex) {
41
+ if (!/^[0-9a-f]{64}$/.test(rootHex))
42
+ throw new Error("an anchor root is 32 bytes of lowercase hex");
43
+ return `0x${TAG}${rootHex}`;
44
+ }
45
+ /** The leaf of a checkpoint in the anchor's tree: the canonical bytes of the log's signed envelope. */
46
+ export const anchorLeaf = (checkpoint) => leafHash(canonicalize(checkpoint));
47
+ export class Anchor {
48
+ o;
49
+ f;
50
+ warn;
51
+ timers = [];
52
+ running = null;
53
+ constructor(opts) {
54
+ this.o = opts;
55
+ this.f = opts.fetch ?? fetch;
56
+ this.warn = opts.warn ?? ((m) => console.error(m));
57
+ mkdirSync(join(opts.outDir, ".well-known"), { recursive: true });
58
+ // for discovery only: a verifier pins the address it was given, never this file's
59
+ writeFileSync(join(opts.outDir, ".well-known", "agent-custody-anchor.json"), JSON.stringify({ chainId: opts.chain.chainId, address: opts.chain.address }, null, 2));
60
+ }
61
+ get address() {
62
+ return this.o.chain.address;
63
+ }
64
+ load() {
65
+ try {
66
+ return JSON.parse(readFileSync(join(this.o.outDir, "state.json"), "utf8"));
67
+ }
68
+ catch {
69
+ return { anchored: {} };
70
+ }
71
+ }
72
+ save(s) {
73
+ const file = join(this.o.outDir, "state.json");
74
+ writeFileSync(`${file}.tmp`, JSON.stringify(s, null, 2));
75
+ renameSync(`${file}.tmp`, file);
76
+ }
77
+ async get(url) {
78
+ return this.f(url, { signal: AbortSignal.timeout(10_000) });
79
+ }
80
+ async latest(tenant) {
81
+ const res = await this.get(new URL(`${safe(tenant)}/latest.json`, slash(this.o.checkpointsUrl)));
82
+ if (res.status === 404)
83
+ return null;
84
+ if (!res.ok)
85
+ throw new Error(`checkpoint for ${tenant}: ${res.status}`);
86
+ return (await res.json());
87
+ }
88
+ async proof(tenant, oldSize, newSize) {
89
+ const path = tenant === "default" ? `consistency?old=${oldSize}&new=${newSize}` : `t/${tenant}/consistency?old=${oldSize}&new=${newSize}`;
90
+ const res = await this.get(new URL(path, slash(this.o.logUrl)));
91
+ if (!res.ok)
92
+ throw new Error(`consistency proof for ${tenant}: ${res.status}`);
93
+ return (await res.json()).hashes;
94
+ }
95
+ /** True while a transaction is sent and not yet finalized. */
96
+ get pending() {
97
+ return this.load().pending !== undefined;
98
+ }
99
+ /** One pass. Never throws; runs that overlap share one pass, so two transactions are never in flight at once. */
100
+ runOnce() {
101
+ this.running ??= this.pass().finally(() => {
102
+ this.running = null;
103
+ });
104
+ return this.running;
105
+ }
106
+ async pass() {
107
+ const state = this.load();
108
+ // a transaction in flight holds the address's nonce: nothing new is sent until it is finalized, or fails and the next run resends
109
+ if (state.pending)
110
+ return { tenants: [], tx: await this.settle(state) };
111
+ let keys;
112
+ try {
113
+ keys = (await fetchLogKeys(slash(this.o.logUrl), this.f)).keys;
114
+ }
115
+ catch (e) {
116
+ const reason = e instanceof Error ? e.message : String(e);
117
+ this.warn(`agent-custody anchor: ${reason}`);
118
+ return { tenants: this.o.tenants.map((tenant) => ({ tenant, outcome: "unavailable", reason })), tx: { outcome: "none" } };
119
+ }
120
+ const tenants = [];
121
+ const entries = [];
122
+ for (const tenant of this.o.tenants) {
123
+ let r;
124
+ try {
125
+ r = await this.check(tenant, keys, state);
126
+ }
127
+ catch (e) {
128
+ const reason = e instanceof Error ? e.message : String(e);
129
+ this.warn(`agent-custody anchor: ${tenant}: ${reason}`);
130
+ r = { outcome: { tenant, outcome: "unavailable", reason } };
131
+ }
132
+ tenants.push(r.outcome);
133
+ // Every transaction covers every log anchored before, at its new checkpoint or its last good one. A verifier
134
+ // then requires a record from the address's newest transaction, so an older record cannot be passed off as current.
135
+ const entry = r.entry ?? state.anchored[tenant];
136
+ if (entry)
137
+ entries.push(entry);
138
+ }
139
+ if (!tenants.some((t) => t.outcome === "moved"))
140
+ return { tenants, tx: { outcome: "none" } };
141
+ const root = rootOf(entries.map((e) => anchorLeaf(e.checkpoint)));
142
+ let txHash;
143
+ try {
144
+ txHash = await this.o.chain.send(anchorCalldata(root));
145
+ }
146
+ catch (e) {
147
+ const reason = e instanceof Error ? e.message : String(e);
148
+ this.warn(`agent-custody anchor: not sent: ${reason}`);
149
+ return { tenants, tx: { outcome: "failed", reason } };
150
+ }
151
+ state.pending = { txHash, root, sentAt: new Date().toISOString(), entries };
152
+ this.save(state);
153
+ const deadline = Date.now() + (this.o.waitMs ?? 600_000);
154
+ for (;;) {
155
+ const tx = await this.settle(state);
156
+ if ((tx.outcome !== "pending" && tx.outcome !== "included") || Date.now() >= deadline)
157
+ return { tenants, tx };
158
+ await new Promise((r) => setTimeout(r, this.o.pollMs ?? 12_000));
159
+ }
160
+ }
161
+ async check(tenant, keys, state) {
162
+ const cp = await this.latest(tenant);
163
+ if (!cp)
164
+ return { outcome: { tenant, outcome: "unavailable", reason: "no checkpoint published yet" } };
165
+ const v = dsseVerify(cp.envelope, keys);
166
+ if (!v.ok || cp.envelope.payloadType !== TREEHEAD_TYPE)
167
+ return { outcome: this.refuse(tenant, `checkpoint does not verify against the log's published keys: ${v.ok ? "not a tree head" : v.error}`, cp.envelope) };
168
+ const head = v.payload;
169
+ const prev = state.anchored[tenant];
170
+ if (prev) {
171
+ if (prev.logId !== head.log)
172
+ return { outcome: this.refuse(tenant, `checkpoint names log ${head.log ?? "none"}, the last one anchored named ${prev.logId ?? "none"}`, cp.envelope) };
173
+ if (head.treeSize < prev.treeSize)
174
+ return { outcome: this.refuse(tenant, `checkpoint at size ${head.treeSize} is smaller than the last one anchored at ${prev.treeSize}`, cp.envelope) };
175
+ if (head.treeSize === prev.treeSize) {
176
+ if (head.rootHash !== prev.rootHash)
177
+ return { outcome: this.refuse(tenant, `a different root at the same size ${head.treeSize}: the log shows two histories`, cp.envelope) };
178
+ return { outcome: { tenant, outcome: "unchanged", treeSize: head.treeSize } };
179
+ }
180
+ const proof = await this.proof(tenant, prev.treeSize, head.treeSize);
181
+ if (!verifyConsistency(prev.treeSize, prev.rootHash, head.treeSize, head.rootHash, proof))
182
+ return { outcome: this.refuse(tenant, `the log at ${head.treeSize} does not extend the head anchored at ${prev.treeSize}: history was rewritten`, cp.envelope) };
183
+ }
184
+ return { outcome: { tenant, outcome: "moved", treeSize: head.treeSize }, entry: { tenant, logId: head.log, treeSize: head.treeSize, rootHash: head.rootHash, checkpoint: cp.envelope } };
185
+ }
186
+ /**
187
+ * Looks the pending transaction up once. Records are written as soon as it is in a block, and written again if a
188
+ * reorg moves it to another one; only a finalized block makes its checkpoints the ones later checkpoints must extend.
189
+ */
190
+ async settle(state) {
191
+ const p = state.pending;
192
+ let inc;
193
+ try {
194
+ inc = await this.o.chain.included(p.txHash);
195
+ }
196
+ catch (e) {
197
+ this.warn(`agent-custody anchor: looking up ${p.txHash}: ${e instanceof Error ? e.message : String(e)}`);
198
+ return { outcome: "pending", txHash: p.txHash, sentAt: p.sentAt };
199
+ }
200
+ if (inc === null) {
201
+ if (p.blockNumber !== undefined) {
202
+ this.warn(`agent-custody anchor: transaction ${p.txHash} left block ${p.blockNumber} in a reorg; waiting for it to land again`);
203
+ delete p.blockNumber;
204
+ p.lostAt = new Date().toISOString();
205
+ this.save(state);
206
+ }
207
+ else if (p.lostAt && Date.now() - Date.parse(p.lostAt) >= (this.o.resendAfterMs ?? 1_800_000)) {
208
+ try {
209
+ p.txHash = await this.o.chain.send(anchorCalldata(p.root));
210
+ p.sentAt = new Date().toISOString();
211
+ delete p.lostAt;
212
+ this.save(state);
213
+ this.warn(`agent-custody anchor: the reorged transaction did not land again; sent the same root as ${p.txHash}`);
214
+ }
215
+ catch (e) {
216
+ this.warn(`agent-custody anchor: resending after a reorg: ${e instanceof Error ? e.message : String(e)}`);
217
+ }
218
+ }
219
+ return { outcome: "pending", txHash: p.txHash, sentAt: p.sentAt };
220
+ }
221
+ if (!inc.ok) {
222
+ delete state.pending;
223
+ this.save(state);
224
+ const reason = `transaction ${p.txHash} failed in block ${inc.blockNumber}`;
225
+ this.warn(`agent-custody anchor: ${reason}; the checkpoints go in the next run`);
226
+ return { outcome: "failed", reason };
227
+ }
228
+ if (p.blockNumber !== inc.blockNumber) {
229
+ this.write(p, inc.blockNumber);
230
+ p.blockNumber = inc.blockNumber;
231
+ delete p.lostAt;
232
+ this.save(state);
233
+ }
234
+ if (!inc.finalized)
235
+ return { outcome: "included", txHash: p.txHash, blockNumber: inc.blockNumber };
236
+ for (const e of p.entries)
237
+ state.anchored[e.tenant] = e;
238
+ delete state.pending;
239
+ this.save(state);
240
+ return { outcome: "anchored", txHash: p.txHash, blockNumber: inc.blockNumber, tenants: p.entries.map((e) => e.tenant) };
241
+ }
242
+ write(p, blockNumber) {
243
+ const leaves = p.entries.map((e) => anchorLeaf(e.checkpoint));
244
+ p.entries.forEach((e, i) => {
245
+ const record = { tenant: e.tenant, logId: e.logId, treeSize: e.treeSize, rootHash: e.rootHash, checkpoint: e.checkpoint, anchor: { chainId: this.o.chain.chainId, address: this.o.chain.address, txHash: p.txHash, blockNumber, root: p.root, proof: inclusionProof(leaves, i), sentAt: p.sentAt } };
246
+ const dir = join(this.o.outDir, safe(e.tenant));
247
+ mkdirSync(dir, { recursive: true });
248
+ const text = JSON.stringify(record, null, 2);
249
+ writeFileSync(join(dir, `${e.treeSize}.json`), text);
250
+ writeFileSync(join(dir, "latest.json"), text);
251
+ });
252
+ }
253
+ /** An alarm is written where the records would have gone, so whoever reads the anchor's host sees it. */
254
+ refuse(tenant, reason, envelope) {
255
+ const dir = join(this.o.outDir, safe(tenant));
256
+ mkdirSync(dir, { recursive: true });
257
+ const at = new Date().toISOString();
258
+ const stamp = at.replace(/[:.]/g, "-");
259
+ let file = join(dir, `ALARM-${stamp}.json`);
260
+ for (let n = 2; existsSync(file); n++)
261
+ file = join(dir, `ALARM-${stamp}-${n}.json`);
262
+ writeFileSync(file, JSON.stringify({ tenant, at, reason, checkpoint: envelope }, null, 2));
263
+ writeFileSync(join(dir, "ALARM.json"), JSON.stringify({ tenant, at, reason }, null, 2));
264
+ this.warn(`agent-custody anchor: REFUSED ${tenant}: ${reason}`);
265
+ return { tenant, outcome: "refused", reason };
266
+ }
267
+ /** Runs every `everyMs`, and every `settleMs` while a transaction is pending, so a record is published soon after it lands. */
268
+ start(everyMs = 21_600_000, settleMs = 60_000) {
269
+ if (this.timers.length)
270
+ return;
271
+ this.timers.push(setInterval(() => void this.runOnce(), everyMs));
272
+ this.timers.push(setInterval(() => {
273
+ if (this.pending)
274
+ void this.runOnce();
275
+ }, settleMs));
276
+ for (const t of this.timers)
277
+ t.unref?.();
278
+ void this.runOnce();
279
+ }
280
+ async stop() {
281
+ for (const t of this.timers)
282
+ clearInterval(t);
283
+ this.timers = [];
284
+ await this.running;
285
+ }
286
+ }
287
+ async function rpc(f, url, method, params) {
288
+ // the URL can carry a provider's key, so errors name the host only
289
+ const host = new URL(url).host;
290
+ const res = await f(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), signal: AbortSignal.timeout(10_000) });
291
+ if (!res.ok)
292
+ throw new Error(`${host} ${method}: HTTP ${res.status}`);
293
+ const body = (await res.json());
294
+ if (body.error)
295
+ throw new Error(`${host} ${method}: ${body.error.message ?? "error"}`);
296
+ return body.result;
297
+ }
298
+ const lower = (s) => (typeof s === "string" ? s.toLowerCase() : undefined);
299
+ /**
300
+ * Checks an anchor record against the chain: the checkpoint is the log's, it is a leaf under the anchored root, and a
301
+ * successful transaction from the pinned address to itself carries exactly that root. Needs no Ethereum library.
302
+ */
303
+ export async function checkAnchorRecord(record, o) {
304
+ const f = o.fetch ?? fetch;
305
+ const address = o.address.toLowerCase();
306
+ const a = record.anchor;
307
+ if (!a || typeof a.txHash !== "string" || typeof a.root !== "string" || !a.proof)
308
+ return { ok: false, error: "not an anchor record" };
309
+ if (a.chainId !== o.chainId)
310
+ return { ok: false, error: `anchored on chain ${a.chainId}, expected ${o.chainId}` };
311
+ if (lower(a.address) !== address)
312
+ return { ok: false, error: `anchored from ${a.address}, the pinned anchor is ${o.address}` };
313
+ const v = dsseVerify(record.checkpoint, o.logKeys);
314
+ if (!v.ok || record.checkpoint.payloadType !== TREEHEAD_TYPE)
315
+ return { ok: false, error: `checkpoint does not verify against the log's keys: ${v.ok ? "not a tree head" : v.error}` };
316
+ const head = v.payload;
317
+ if (head.treeSize !== record.treeSize || head.rootHash !== record.rootHash || head.log !== record.logId)
318
+ return { ok: false, error: "the record's size, root, or log id is not the checkpoint's" };
319
+ if (!verifyInclusion(anchorLeaf(record.checkpoint), a.proof, a.root))
320
+ return { ok: false, error: "the checkpoint is not under the anchored root" };
321
+ let data;
322
+ try {
323
+ data = anchorCalldata(a.root);
324
+ }
325
+ catch (e) {
326
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
327
+ }
328
+ if (o.rpcUrls.length === 0)
329
+ return { ok: false, error: "no JSON-RPC endpoint to check the chain with" };
330
+ let seen;
331
+ let newer = 0;
332
+ for (const url of o.rpcUrls) {
333
+ try {
334
+ const chainId = Number(await rpc(f, url, "eth_chainId", []));
335
+ if (chainId !== o.chainId)
336
+ return { ok: false, error: `${new URL(url).host} is chain ${chainId}, expected ${o.chainId}` };
337
+ const tx = (await rpc(f, url, "eth_getTransactionByHash", [a.txHash]));
338
+ if (!tx)
339
+ return { ok: false, error: `${new URL(url).host} has no transaction ${a.txHash}` };
340
+ if (lower(tx.from) !== address || lower(tx.to) !== address)
341
+ return { ok: false, error: `transaction ${a.txHash} is not from the anchor to itself` };
342
+ if (lower(tx.input) !== data)
343
+ return { ok: false, error: `transaction ${a.txHash} does not carry the anchored root` };
344
+ if (tx.blockNumber == null || Number(tx.blockNumber) !== a.blockNumber)
345
+ return { ok: false, error: `transaction ${a.txHash} is not in block ${a.blockNumber}` };
346
+ // the address's count of mined transactions says, from the chain, whether a later anchor exists
347
+ const sent = Number(await rpc(f, url, "eth_getTransactionCount", [address, "latest"]));
348
+ newer = Math.max(newer, sent - 1 - Number(tx.nonce));
349
+ const receipt = (await rpc(f, url, "eth_getTransactionReceipt", [a.txHash]));
350
+ if (!receipt || receipt.status !== "0x1")
351
+ return { ok: false, error: `transaction ${a.txHash} did not succeed` };
352
+ const block = (await rpc(f, url, "eth_getBlockByNumber", [`0x${a.blockNumber.toString(16)}`, false]));
353
+ if (!block || lower(block.hash) !== lower(receipt.blockHash))
354
+ return { ok: false, error: `block ${a.blockNumber} is not the one the transaction is in` };
355
+ const fin = (await rpc(f, url, "eth_getBlockByNumber", ["finalized", false]));
356
+ const here = { blockHash: String(lower(block.hash)), blockNumber: a.blockNumber, blockTime: new Date(Number(block.timestamp) * 1000).toISOString(), finalized: fin !== null && Number(fin.number) >= a.blockNumber };
357
+ if (seen && seen.blockHash !== here.blockHash)
358
+ return { ok: false, error: `the endpoints disagree on block ${a.blockNumber}` };
359
+ // finality is only as good as the least-finalized endpoint says
360
+ seen = seen ? { ...here, finalized: seen.finalized && here.finalized } : here;
361
+ }
362
+ catch (e) {
363
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
364
+ }
365
+ }
366
+ return { ok: true, blockNumber: seen.blockNumber, blockTime: seen.blockTime, finalized: seen.finalized, newer };
367
+ }
package/dist/check.js CHANGED
@@ -6,7 +6,7 @@ import * as cedar from "@cedar-policy/cedar-wasm/nodejs";
6
6
  import { accessSync, constants, existsSync, mkdtempSync, readFileSync, rmSync, statSync } from "node:fs";
7
7
  import { tmpdir } from "node:os";
8
8
  import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
9
- import { GatewayConfigSchema, loadConfig } from "./config.js";
9
+ import { GatewayConfigSchema, loadConfig, strictRefusals } from "./config.js";
10
10
  import { generateKeyPair, loadPrivateKey, loadPublicKey, writeKeyPair } from "./crypto.js";
11
11
  import { delegationValidAt, verifyDelegation } from "./delegation.js";
12
12
  import { hasPermitRule } from "./policy.js";
@@ -225,7 +225,13 @@ export async function checkConfig(configPath, options = {}) {
225
225
  add("ok", "grant", "no grantFile: each connection over HTTP presents its own grant");
226
226
  }
227
227
  // what a log outage costs
228
- if (cfg.log && !cfg.precommit.length)
228
+ if (cfg.strict)
229
+ add("ok", "strict", "strict mode: every call is precommitted to a remote, hash-only log with pinned keys, and no receipt goes to the outbox");
230
+ else {
231
+ const refused = strictRefusals(cfg);
232
+ add("ok", "strict", refused.length ? `strict mode is off; turned on, it would refuse: ${refused.join("; ")}` : "strict mode is off; this config would also run strict");
233
+ }
234
+ if (cfg.log && !cfg.precommit.length && !cfg.strict)
229
235
  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 puts its receipt in the outbox and the side effect is in the log only later. Name the consequential tools in precommit, or [\"*\"]; requirePrecommit makes this an error");
230
236
  // tool names the config mentions, against the tools the upstreams offer
231
237
  const mentioned = () => [
package/dist/cli.js CHANGED
@@ -15,6 +15,8 @@ import { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoi
15
15
  import { connectSigner, fetchLogKeys, localSigner, serveSigner } from "./signer.js";
16
16
  import { fetchWitnessKeys, Witness } from "./witness.js";
17
17
  import { checkLog, formatLogCheck } from "./log-check.js";
18
+ import { Anchor, ANCHOR_CHAINS, resolveAnchorChain } from "./anchor.js";
19
+ import { evmChain } from "./anchor-evm.js";
18
20
  import { serveHttp } from "./gateway-http.js";
19
21
  import { serveA2a } from "./a2a.js";
20
22
  import { PortalStore, sendFollowUps, servePortal } from "./portal.js";
@@ -89,7 +91,7 @@ const USAGE = `agent-custody <command>
89
91
  prune --log <log.jsonl> --before <ISO instant> [--receipts <dir>]
90
92
  retention on the receipt log: replaces older leaves with their hashes, so proofs still verify and the content is gone
91
93
  log --file <log.jsonl> --key <log.key> [--port 8787] [--host 127.0.0.1] [--token-env <NAME>] reference log server
92
- verify <bundle.json> --issuer-key <pub> [--principal-key <pub>] [--approval-key <pub>] [--log-key <pub> | --log-url <url>] [--log-id <id>] [--upstream-key <pub>] [--stripe-secret-env NAME] [--github-secret-env NAME] [--log <log.jsonl>] [--disclose <file>] [--capture-key-env NAME] [--json]
94
+ 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]
93
95
  policy simulate --policy <proposed.cedar> --receipts <dir> --issuer-key <pub>... [--principal-key <pub>]... [--approval-key <pub>]... [--log-key <pub>]... [--json] [--out <file>]
94
96
  replay verified local receipts against a proposed policy using their recorded inputs;
95
97
  --out saves the full JSON report. Exits 1 when any call could not be evaluated.
@@ -104,7 +106,9 @@ const USAGE = `agent-custody <command>
104
106
  log ... --db-env NAME --admin-token-env NAME [--public-url <https://log.example.com/>] [--checkpoints-url <https://checkpoints.example.com/>]
105
107
  the operator's admin page at /admin and its API, behind the admin token: tenants, tokens shown once,
106
108
  the welcome sheet; the public URLs fill the sheet in
107
- log-check --log-url <url> [--checkpoints-url <url>] [--witness-url <url>] [--tenant <name>]... [--max-lag <seconds>] [--json]
109
+ log-check --log-url <url> [--checkpoints-url <url>] [--witness-url <url>] [--tenant <name>]... [--max-lag <seconds>]
110
+ [--anchor-url <url> --anchor-address <0x...> --anchor-rpc-env NAME... --anchor-log-id <tenant>=<log id>...
111
+ [--anchor-chain ethereum] [--max-anchor-lag <seconds>]] [--json]
108
112
  log-export --log-url <url> [--tenant <name>] --token-env NAME --out <dir> [--month YYYY-MM]... [--json]
109
113
  a tenant's own log, with their token: every leaf hash as a log file the verifier
110
114
  reads, the signed head, the published keys, the checkpoints, and their usage
@@ -115,6 +119,12 @@ const USAGE = `agent-custody <command>
115
119
  a second signer, run by someone who is not the log's operator: fetches the log's latest
116
120
  checkpoint per watched log, proves it extends the last one it signed, and countersigns it
117
121
  into <dir>; refuses and writes an alarm otherwise. Serve <dir> from a host of your own.
122
+ anchor --log-url <url> --checkpoints-url <url> --out <dir> --rpc-url-env NAME --key-env NAME [--tenant <name>]...
123
+ [--chain ethereum|base|arbitrum|optimism|polygon|<chain id>] [--max-fee-gwei <gwei>] [--every <seconds>] [--once]
124
+ anchors the log's checkpoints on an EVM chain, Ethereum by default: proves each new one extends the last one
125
+ anchored, sends one transaction with a Merkle root over them from the key's address,
126
+ and writes each log's record and inclusion proof into <dir>; refuses and writes an alarm
127
+ otherwise. Needs the optional package viem. Serve <dir> read-only.
118
128
  signer --key <log.key> --port 8790 [--host 127.0.0.1] [--token-env NAME] [--retired-key <pub>]...
119
129
  the one process that holds the log's key: POST /sign, GET /keys
120
130
  log-admin --db-env NAME tenant add <id> [--log-id <id>] | tenant list | tenant disable <id> | tenant plan <id> <free|team|enterprise>
@@ -336,10 +346,29 @@ async function main(argv) {
336
346
  return 0;
337
347
  }
338
348
  case "log-check": {
339
- const { values } = parseArgs({ args: rest, options: { "log-url": { type: "string" }, "checkpoints-url": { type: "string" }, "witness-url": { type: "string" }, tenant: { type: "string", multiple: true }, "max-lag": { type: "string", default: "900" }, json: { type: "boolean", default: false } } });
349
+ const { values } = parseArgs({ args: rest, options: { "log-url": { type: "string" }, "checkpoints-url": { type: "string" }, "witness-url": { type: "string" }, tenant: { type: "string", multiple: true }, "max-lag": { type: "string", default: "900" }, "anchor-url": { type: "string" }, "anchor-address": { type: "string" }, "anchor-rpc-env": { type: "string", multiple: true }, "anchor-log-id": { type: "string", multiple: true }, "anchor-chain": { type: "string", default: "ethereum" }, "max-anchor-lag": { type: "string", default: "46800" }, json: { type: "boolean", default: false } } });
340
350
  if (!values["log-url"])
341
351
  throw new Error("log-check needs --log-url");
342
- const r = await checkLog({ logUrl: values["log-url"], ...(values["checkpoints-url"] ? { checkpointsUrl: values["checkpoints-url"] } : {}), ...(values["witness-url"] ? { witnessUrl: values["witness-url"] } : {}), tenants: values.tenant?.length ? values.tenant : ["default"], maxLagMs: Number(values["max-lag"]) * 1000 });
352
+ let anchor = {};
353
+ if (values["anchor-url"]) {
354
+ if (!values["anchor-address"] || !values["anchor-rpc-env"]?.length)
355
+ throw new Error("--anchor-url needs --anchor-address and at least one --anchor-rpc-env");
356
+ const rpcUrls = values["anchor-rpc-env"].map((name) => {
357
+ const url = process.env[name];
358
+ if (!url)
359
+ throw new Error(`environment variable ${name} is not set`);
360
+ return url;
361
+ });
362
+ const anchorLogIds = {};
363
+ for (const pin of values["anchor-log-id"] ?? []) {
364
+ const at = pin.indexOf("=");
365
+ if (at < 1 || at === pin.length - 1)
366
+ throw new Error(`--anchor-log-id takes <tenant>=<log id>, got "${pin}"`);
367
+ anchorLogIds[pin.slice(0, at)] = pin.slice(at + 1);
368
+ }
369
+ anchor = { anchorUrl: values["anchor-url"], anchorAddress: values["anchor-address"], anchorRpcUrls: rpcUrls, anchorLogIds, anchorChainId: resolveAnchorChain(values["anchor-chain"]).chainId, maxAnchorLagMs: Number(values["max-anchor-lag"]) * 1000 };
370
+ }
371
+ const r = await checkLog({ logUrl: values["log-url"], ...(values["checkpoints-url"] ? { checkpointsUrl: values["checkpoints-url"] } : {}), ...(values["witness-url"] ? { witnessUrl: values["witness-url"] } : {}), tenants: values.tenant?.length ? values.tenant : ["default"], maxLagMs: Number(values["max-lag"]) * 1000, ...anchor });
343
372
  console.log(values.json ? JSON.stringify(r, null, 2) : formatLogCheck(r));
344
373
  return r.ok ? 0 : 1;
345
374
  }
@@ -374,6 +403,39 @@ async function main(argv) {
374
403
  w.stop();
375
404
  return 0;
376
405
  }
406
+ case "anchor": {
407
+ const { values } = parseArgs({ args: rest, options: { "log-url": { type: "string" }, "checkpoints-url": { type: "string" }, out: { type: "string" }, tenant: { type: "string", multiple: true }, "rpc-url-env": { type: "string" }, "key-env": { type: "string" }, chain: { type: "string", default: "ethereum" }, "max-fee-gwei": { type: "string" }, every: { type: "string", default: "21600" }, once: { type: "boolean", default: false } } });
408
+ if (!values["log-url"] || !values["checkpoints-url"] || !values.out || !values["rpc-url-env"] || !values["key-env"])
409
+ throw new Error("anchor needs --log-url, --checkpoints-url, --out, --rpc-url-env, and --key-env");
410
+ const rpcUrl = process.env[values["rpc-url-env"]];
411
+ if (!rpcUrl)
412
+ throw new Error(`environment variable ${values["rpc-url-env"]} is not set`);
413
+ const privateKey = process.env[values["key-env"]];
414
+ if (!privateKey)
415
+ throw new Error(`environment variable ${values["key-env"]} is not set`);
416
+ const everyMs = Number(values.every) * 1000;
417
+ if (!(everyMs > 0))
418
+ throw new Error("--every must be a positive number of seconds");
419
+ const target = resolveAnchorChain(values.chain);
420
+ const maxFeeGwei = values["max-fee-gwei"] === undefined ? target.maxFeeGwei : Number(values["max-fee-gwei"]);
421
+ if (maxFeeGwei === undefined)
422
+ throw new Error(`chain ${target.chainId} has no default fee cap; give --max-fee-gwei (the named chains are ${Object.keys(ANCHOR_CHAINS).join(", ")})`);
423
+ const chain = await evmChain({ rpcUrl, privateKey, chainId: target.chainId, maxFeeGwei });
424
+ const a = new Anchor({ logUrl: values["log-url"], checkpointsUrl: values["checkpoints-url"], tenants: values.tenant?.length ? values.tenant : ["default"], chain, outDir: values.out });
425
+ if (values.once) {
426
+ const run = await a.runOnce();
427
+ for (const t of run.tenants)
428
+ console.log(`${t.tenant.padEnd(20)} ${t.outcome}${"treeSize" in t ? ` at ${t.treeSize}` : ""}${"reason" in t ? `: ${t.reason}` : ""}`);
429
+ const tx = run.tx;
430
+ console.log(`transaction: ${tx.outcome}${"txHash" in tx ? ` ${tx.txHash}` : ""}${"blockNumber" in tx ? ` in block ${tx.blockNumber}` : ""}${"reason" in tx ? `: ${tx.reason}` : ""}`);
431
+ return run.tenants.some((t) => t.outcome === "refused") ? 1 : 0;
432
+ }
433
+ console.error(`agent-custody anchor: ${a.address} on ${target.name ?? "chain"} ${chain.chainId}, fee cap ${maxFeeGwei} gwei, watching ${values["log-url"]} via ${values["checkpoints-url"]} every ${values.every}s, writing to ${values.out}`);
434
+ a.start(everyMs);
435
+ await untilStopped();
436
+ await a.stop();
437
+ return 0;
438
+ }
377
439
  case "signer": {
378
440
  const { values } = parseArgs({ args: rest, options: { key: { type: "string" }, port: { type: "string", default: "8790" }, host: { type: "string", default: "127.0.0.1" }, "token-env": { type: "string" }, "retired-key": { type: "string", multiple: true } } });
379
441
  if (!values.key)
@@ -649,6 +711,7 @@ async function main(argv) {
649
711
  "log-key": { type: "string", multiple: true },
650
712
  "log-url": { type: "string" },
651
713
  "log-id": { type: "string" },
714
+ "require-strict": { type: "boolean", default: false },
652
715
  "upstream-key": { type: "string", multiple: true },
653
716
  "stripe-secret-env": { type: "string" },
654
717
  "github-secret-env": { type: "string" },
@@ -673,6 +736,7 @@ async function main(argv) {
673
736
  ...(values["approval-key"] ? { approvalKeys: values["approval-key"].map(loadPublicKey) } : {}),
674
737
  ...(logKeys.length ? { logKeys } : {}),
675
738
  ...(values["log-id"] ? { logId: values["log-id"] } : {}),
739
+ ...(values["require-strict"] ? { requireStrict: true } : {}),
676
740
  ...(values["upstream-key"] ? { upstreamKeys: values["upstream-key"].map(loadPublicKey) } : {}),
677
741
  ...(values["stripe-secret-env"] || values["github-secret-env"] ? { providerSecrets: { ...(values["stripe-secret-env"] ? { stripe: secretFrom(values["stripe-secret-env"]) } : {}), ...(values["github-secret-env"] ? { github: secretFrom(values["github-secret-env"]) } : {}) } } : {}),
678
742
  ...(values.log ? { logFile: values.log } : {}),
package/dist/config.d.ts CHANGED
@@ -148,6 +148,14 @@ declare const OperationsSchema: z.ZodObject<{
148
148
  }, z.core.$strip>;
149
149
  export type OperationsConfig = z.infer<typeof OperationsSchema>;
150
150
  export type OperationToolConfig = z.infer<typeof OperationToolSchema>;
151
+ /** What strict mode refuses in a config, whether or not it is on: an empty list means the config can run strict. */
152
+ export declare function strictRefusals(c: {
153
+ logFile?: string | undefined;
154
+ log?: {
155
+ hashOnly?: boolean | undefined;
156
+ keys?: string[] | undefined;
157
+ } | undefined;
158
+ }): string[];
151
159
  export declare const GatewayConfigSchema: z.ZodObject<{
152
160
  identity: z.ZodObject<{
153
161
  keyFile: z.ZodString;
@@ -250,6 +258,7 @@ export declare const GatewayConfigSchema: z.ZodObject<{
250
258
  }, z.core.$strip>>>;
251
259
  precommit: z.ZodDefault<z.ZodArray<z.ZodString>>;
252
260
  requirePrecommit: z.ZodOptional<z.ZodBoolean>;
261
+ strict: z.ZodOptional<z.ZodBoolean>;
253
262
  approvals: z.ZodOptional<z.ZodObject<{
254
263
  trustedKeys: z.ZodArray<z.ZodString>;
255
264
  usedDir: z.ZodString;
package/dist/config.js CHANGED
@@ -127,6 +127,19 @@ const OperationsSchema = z.object({
127
127
  ctx.addIssue({ code: "custom", path: ["tools", i, "reconcile", "tool"], message: "a reconciliation read cannot be a financial operation tool" });
128
128
  }
129
129
  });
130
+ /** What strict mode refuses in a config, whether or not it is on: an empty list means the config can run strict. */
131
+ export function strictRefusals(c) {
132
+ const out = [];
133
+ if (c.logFile || !c.log)
134
+ out.push("strict mode needs a remote log: logFile is a log the operator can rewrite; set log.url to a log someone else runs");
135
+ else {
136
+ if (!c.log.hashOnly)
137
+ out.push("strict mode needs log.hashOnly: the log is run by someone else, so send it leaf hashes, not receipts");
138
+ if (!c.log.keys?.length)
139
+ out.push("strict mode needs log.keys: the log's public key files, pinned, to check its answer before any call is forwarded");
140
+ }
141
+ return out;
142
+ }
130
143
  export const GatewayConfigSchema = z.object({
131
144
  identity: z.object({ keyFile: z.string() }),
132
145
  /** the upstream: an MCP server to spawn over stdio, an MCP URL to reach over Streamable HTTP with an optional bearer token from the environment, or a REST API described as tools */
@@ -145,6 +158,12 @@ export const GatewayConfigSchema = z.object({
145
158
  precommit: z.array(z.string().min(1)).default([]),
146
159
  /** with a remote log, refuse to start when precommit is empty; without it the gateway only warns */
147
160
  requirePrecommit: z.boolean().optional(),
161
+ /**
162
+ * Strict mode: every tool is precommitted, the log must be remote, hash-only, and pinned, and no receipt goes to the
163
+ * outbox. A call is forwarded only once its authorization is in a log the operator does not run, and every receipt says
164
+ * `issuer.strict`, so a verifier can require it.
165
+ */
166
+ strict: z.boolean().optional(),
148
167
  /** Tools that require a signed, unexpired, single-use approval, in every mode; "*" covers all agent calls. */
149
168
  approvals: ApprovalsSchema.optional(),
150
169
  /** Durable idempotency, daily budget reservations, and provider reconciliation for financial operations. */
@@ -171,7 +190,10 @@ export const GatewayConfigSchema = z.object({
171
190
  // a key fetched from the log itself proves nothing about a log that is dishonest from the start, so a remote log that
172
191
  // gates consequential calls must have its keys pinned in the config (issue #99)
173
192
  .refine((c) => !c.log || (!c.precommit.length && !c.operations) || !!c.log.keys?.length, { message: "precommit with a remote log needs log.keys: the log's public key files, pinned, to check its answer before a consequential call is forwarded" })
174
- .refine((c) => !c.requirePrecommit || !c.log || c.precommit.length > 0, { message: "requirePrecommit is set and precommit is empty: name the consequential tools in precommit, or [\"*\"]" })
193
+ .superRefine((c, ctx) => { if (c.strict)
194
+ for (const message of strictRefusals(c))
195
+ ctx.addIssue({ code: "custom", path: ["strict"], message }); })
196
+ .refine((c) => !c.requirePrecommit || !c.log || c.precommit.length > 0 || !!c.strict, { message: "requirePrecommit is set and precommit is empty: name the consequential tools in precommit, or [\"*\"]" })
175
197
  .refine((c) => !c.operations || !c.facts.some((fact) => c.operations.tools.some((tool) => tool.tool === fact.tool)), { message: "a fact lookup cannot invoke a financial operation tool" });
176
198
  /** Loads a config file and resolves every path relative to the file's directory. */
177
199
  export function loadConfig(path) {
package/dist/gateway.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { type CallToolResult, type Tool } from "@modelcontextprotocol/sdk/types.js";
2
- import type { GatewayConfig } from "./config.ts";
2
+ import { type GatewayConfig } from "./config.ts";
3
3
  import { type Envelope } from "./crypto.ts";
4
4
  import { type Delegation } from "./delegation.ts";
5
5
  import { type FlushResult } from "./issue.ts";