@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/README.md +20 -10
- package/dist/anchor-evm.d.ts +19 -0
- package/dist/anchor-evm.js +49 -0
- package/dist/anchor.d.ts +167 -0
- package/dist/anchor.js +367 -0
- package/dist/check.js +8 -2
- package/dist/cli.js +68 -4
- package/dist/config.d.ts +9 -0
- package/dist/config.js +23 -1
- package/dist/gateway.d.ts +1 -1
- package/dist/gateway.js +23 -11
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/log-check.d.ts +15 -0
- package/dist/log-check.js +52 -0
- package/dist/receipt.d.ts +2 -0
- package/dist/verify.d.ts +2 -0
- package/dist/verify.js +7 -1
- package/docs/anchoring.md +115 -0
- package/docs/configuration.md +5 -1
- package/docs/threat-model.md +16 -2
- package/docs/tutorials.md +3 -0
- package/docs/usage.md +19 -1
- package/docs/verification.md +4 -2
- package/package.json +7 -2
- package/vectors/audit.json +27 -27
- package/vectors/canonical.json +5 -5
- package/vectors/receipts.json +1176 -967
package/dist/gateway.js
CHANGED
|
@@ -9,6 +9,7 @@ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/
|
|
|
9
9
|
import { Server } from "@modelcontextprotocol/sdk/server/index.js";
|
|
10
10
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
|
11
11
|
import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprotocol/sdk/types.js";
|
|
12
|
+
import { strictRefusals } from "./config.js";
|
|
12
13
|
import { digestOf, dsseVerifiers, dsseVerify, loadPrivateKey, loadPublicKey } from "./crypto.js";
|
|
13
14
|
import { delegationValidAt, grantChainDigests, verifyDelegation } from "./delegation.js";
|
|
14
15
|
import { APPROVAL_META_KEY, DEFAULT_APPROVAL_LIFETIME_SECONDS, consumeApproval, verifyApproval, verifyApprovalStatement } from "./approval.js";
|
|
@@ -192,10 +193,19 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
192
193
|
throw new Error(`capture for ${tool} uses mode encrypted, which needs captureKeyEnv`);
|
|
193
194
|
}
|
|
194
195
|
// The rules are applied by the issuer to every statement it signs, the authorization included: the gateway hands it the call in full.
|
|
195
|
-
|
|
196
|
+
if (cfg.strict) {
|
|
197
|
+
const refused = strictRefusals(cfg);
|
|
198
|
+
if (refused.length)
|
|
199
|
+
throw new Error(`agent-custody gateway: ${refused.join("; ")}`);
|
|
200
|
+
}
|
|
201
|
+
const sink = options.log ?? openLog(cfg, gatewayKey);
|
|
202
|
+
if (cfg.strict && sink.kind !== "http")
|
|
203
|
+
throw new Error(`agent-custody gateway: strict mode needs a remote log, and ${sink.where} is a file`);
|
|
204
|
+
const issuer = createIssuer(gatewayKey, cfg.receiptsDir, sink, { exporter: options.exporter ?? openExporter(cfg), capture: { rules: cfg.capture, key: captureKey } });
|
|
205
|
+
const issuedBy = { kind: "gateway", keyid: issuer.keyid, version: GATEWAY_VERSION, ...(cfg.strict ? { strict: true } : {}) };
|
|
196
206
|
const precommit = new Set(cfg.precommit);
|
|
197
207
|
const operationRule = (tool) => cfg.operations?.tools.find((rule) => rule.tool === tool);
|
|
198
|
-
const consequential = (tool) => !!operationRule(tool) || precommit.has("*") || precommit.has(tool);
|
|
208
|
+
const consequential = (tool) => !!cfg.strict || !!operationRule(tool) || precommit.has("*") || precommit.has(tool);
|
|
199
209
|
// A fact lookup runs before the policy can decide, because the policy decides on it. It is therefore a read the
|
|
200
210
|
// gateway makes on the agent's request, never a consequential call: a fact tool named in precommit is a config error.
|
|
201
211
|
// "*" covers the tools the agent calls; a lookup is the gateway's own read, so only an explicit name makes it consequential.
|
|
@@ -508,7 +518,7 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
508
518
|
const head = {
|
|
509
519
|
receiptId,
|
|
510
520
|
timestamp,
|
|
511
|
-
issuer:
|
|
521
|
+
issuer: issuedBy,
|
|
512
522
|
principal: { id: delegation.principal, keyid: principalKeyid, provenance: "attested" },
|
|
513
523
|
agent: { id: delegation.agent, provenance: "attested" },
|
|
514
524
|
delegation: { envelope: grantEnvelope, provenance: "attested" },
|
|
@@ -551,15 +561,15 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
551
561
|
cached = { ...(result ?? { isError: true, content: [{ type: "text", text: head.operation.status === "failed" ? "Operation failed and the call was not sent; use a new operation id to try again" : `Operation outcome is ${head.operation.status}; reconcile with the provider before taking further action` }] }), _meta: { ...result?._meta, [RECEIPT_META_KEY]: receipt, ...(operation.original && !existsSync(`${cfg.receiptsDir}/${operation.originalReceiptId}.json`) ? { "agent-custody/authorization": operation.original } : {}) } };
|
|
552
562
|
execution = { status: "withheld", reason: `existing operation: not forwarded again; the stored outcome is ${head.operation.status}`, provenance: "observed" };
|
|
553
563
|
}
|
|
554
|
-
if (!execution && (policy.decision === "allow" || financial && forward) && consequential(tool)) {
|
|
564
|
+
if (!execution && (policy.decision === "allow" || (financial || cfg.strict) && forward) && consequential(tool)) {
|
|
555
565
|
// A consequential call is committed to the log before it goes out, so that evidence of the side effect exists
|
|
556
566
|
// before the side effect does. If the log will not take the authorization, the call is not forwarded; in
|
|
557
|
-
// observe mode nothing is withheld, and the missing authorization is printed instead.
|
|
567
|
+
// observe mode nothing is withheld, and the missing authorization is printed instead, unless the mode is strict.
|
|
558
568
|
try {
|
|
559
569
|
authorization = await issuer.authorize({ ...head, policy: { ...policy, provenance: "observed" } }, captureCtx);
|
|
560
570
|
}
|
|
561
571
|
catch (e) {
|
|
562
|
-
if (cfg.mode === "observe" && !financial)
|
|
572
|
+
if (cfg.mode === "observe" && !financial && !cfg.strict)
|
|
563
573
|
console.error(`agent-custody gateway (observe mode): the log did not commit the authorization for ${tool}, receipt ${receiptId}; the call was forwarded without it: ${String(e instanceof Error ? e.message : e)}`);
|
|
564
574
|
else
|
|
565
575
|
execution = { status: "withheld", reason: `the log did not commit the authorization, so the call was not forwarded: ${String(e instanceof Error ? e.message : e)}`, provenance: "observed" };
|
|
@@ -659,7 +669,8 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
659
669
|
if (operation)
|
|
660
670
|
head.operation = operationEvidence(operation, operation.status === "submitted" && !createdOperation ? "unknown" : operation.status);
|
|
661
671
|
// The call is done, so a log outage now must not tell the agent it failed: the receipt waits in the outbox. An
|
|
662
|
-
// operation keeps the old order, because its record holds the bundle and its retry is idempotent.
|
|
672
|
+
// operation keeps the old order, because its record holds the bundle and its retry is idempotent. Strict mode
|
|
673
|
+
// keeps no outbox: the authorization is in the log, and a receipt the log refuses leaves the call incomplete.
|
|
663
674
|
let issued;
|
|
664
675
|
let logPending = false;
|
|
665
676
|
try {
|
|
@@ -671,7 +682,7 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
671
682
|
policy: { ...policy, provenance: "observed" },
|
|
672
683
|
...(authorization ? { authorization } : {}),
|
|
673
684
|
execution,
|
|
674
|
-
}, captureCtx, undefined, { deferLog: !operation });
|
|
685
|
+
}, captureCtx, undefined, { deferLog: !operation && !cfg.strict });
|
|
675
686
|
}
|
|
676
687
|
catch (e) {
|
|
677
688
|
if (!(e instanceof ReceiptPending))
|
|
@@ -713,7 +724,7 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
713
724
|
},
|
|
714
725
|
};
|
|
715
726
|
}
|
|
716
|
-
if (cfg.log && !cfg.precommit.length)
|
|
727
|
+
if (cfg.log && !cfg.precommit.length && !cfg.strict)
|
|
717
728
|
console.error("agent-custody gateway: a remote log is set and precommit is empty: every call is forwarded before its receipt is logged. Name the consequential tools in precommit, or [\"*\"]; requirePrecommit makes this an error");
|
|
718
729
|
let flushing;
|
|
719
730
|
const flushOutbox = () => flushing ??= (async () => {
|
|
@@ -727,7 +738,8 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
727
738
|
return r;
|
|
728
739
|
})().finally(() => { flushing = undefined; });
|
|
729
740
|
const autoFlush = () => void flushOutbox().catch((e) => console.error(`agent-custody gateway: the outbox flush failed: ${e instanceof Error ? e.message : String(e)}`));
|
|
730
|
-
|
|
741
|
+
// strict mode never adds to the outbox; receipts left there from before it was turned on are appended once, at start
|
|
742
|
+
const outboxTimer = options.autoFlush && !cfg.strict ? setInterval(autoFlush, 30_000).unref() : undefined;
|
|
731
743
|
if (options.autoFlush)
|
|
732
744
|
autoFlush();
|
|
733
745
|
return {
|
|
@@ -792,7 +804,7 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
792
804
|
throw new Error("provider outcome remains pending or unknown; the reservation is retained");
|
|
793
805
|
const predicate = {
|
|
794
806
|
receiptId: randomUUID(), timestamp: new Date().toISOString(),
|
|
795
|
-
issuer:
|
|
807
|
+
issuer: issuedBy,
|
|
796
808
|
principal: initial.principal, agent: initial.agent, delegation: initial.delegation,
|
|
797
809
|
session: { id: null, toolUseId: null, provenance: "claimed" }, model: { id: null, provenance: "claimed" },
|
|
798
810
|
tool: initial.tool, request: { args: lookup.args, argsDigest: digestOf(lookup.args), provenance: "claimed" },
|
package/dist/index.d.ts
CHANGED
|
@@ -25,6 +25,10 @@ export type { KeyDocument, RemoteSignerOptions, RetiredKey, RunningSigner, Signe
|
|
|
25
25
|
export { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoints.ts";
|
|
26
26
|
export { adminRoutes, welcomeSheet } from "./log-admin.ts";
|
|
27
27
|
export { fetchWitnessKeys, Witness } from "./witness.ts";
|
|
28
|
+
export { Anchor, ANCHOR_CHAINS, anchorCalldata, anchorLeaf, checkAnchorRecord, resolveAnchorChain } from "./anchor.ts";
|
|
29
|
+
export type { AnchorChain, AnchorCheck, AnchorCheckOptions, AnchorOptions, AnchorRecord, AnchorRun, AnchorTenantOutcome, AnchorTxOutcome } from "./anchor.ts";
|
|
30
|
+
export { evmChain } from "./anchor-evm.ts";
|
|
31
|
+
export type { EvmChainOptions } from "./anchor-evm.ts";
|
|
28
32
|
export { checkLog, formatLogCheck } from "./log-check.ts";
|
|
29
33
|
export type { LogCheck, LogCheckOptions, LogCheckResult } from "./log-check.ts";
|
|
30
34
|
export type { WitnessOptions, WitnessOutcome, WitnessedCheckpoint } from "./witness.ts";
|
package/dist/index.js
CHANGED
|
@@ -17,6 +17,8 @@ export { connectSigner, fetchLogKeys, localSigner, serveSigner, signerHandler }
|
|
|
17
17
|
export { bothCheckpoints, dirCheckpoints, postgresCheckpoints } from "./checkpoints.js";
|
|
18
18
|
export { adminRoutes, welcomeSheet } from "./log-admin.js";
|
|
19
19
|
export { fetchWitnessKeys, Witness } from "./witness.js";
|
|
20
|
+
export { Anchor, ANCHOR_CHAINS, anchorCalldata, anchorLeaf, checkAnchorRecord, resolveAnchorChain } from "./anchor.js";
|
|
21
|
+
export { evmChain } from "./anchor-evm.js";
|
|
20
22
|
export { checkLog, formatLogCheck } from "./log-check.js";
|
|
21
23
|
export * from "./config.js";
|
|
22
24
|
export * from "./operations.js";
|
package/dist/log-check.d.ts
CHANGED
|
@@ -8,6 +8,21 @@ export interface LogCheckOptions {
|
|
|
8
8
|
maxLagMs?: number;
|
|
9
9
|
/** how old a checkpoint may be while the head has not moved; default a day, since an idle log is not a broken one */
|
|
10
10
|
maxIdleMs?: number;
|
|
11
|
+
/** where the anchor publishes its records; with it, `anchorAddress` and `anchorRpcUrls` are required */
|
|
12
|
+
anchorUrl?: string;
|
|
13
|
+
/** the anchor's address, pinned from a source other than the anchor's host */
|
|
14
|
+
anchorAddress?: string;
|
|
15
|
+
/** JSON-RPC endpoints of the anchor's chain; with more than one, they must agree */
|
|
16
|
+
anchorRpcUrls?: string[];
|
|
17
|
+
/** the anchor's chain id; default 1, Ethereum mainnet (`resolveAnchorChain` maps a name to its id) */
|
|
18
|
+
anchorChainId?: number;
|
|
19
|
+
/**
|
|
20
|
+
* each anchored log's id, pinned by the verifier: tenant logs share the log's keys and the anchor's address, so only
|
|
21
|
+
* the id tells one log's anchored checkpoint from another's
|
|
22
|
+
*/
|
|
23
|
+
anchorLogIds?: Record<string, string>;
|
|
24
|
+
/** how long the log may stay ahead of its newest anchor, counted from that anchor's block time; default thirteen hours */
|
|
25
|
+
maxAnchorLagMs?: number;
|
|
11
26
|
fetch?: typeof fetch;
|
|
12
27
|
now?: () => number;
|
|
13
28
|
}
|
package/dist/log-check.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// log is down, its head does not verify, its checkpoints have fallen behind its head, or its witness has stopped
|
|
4
4
|
// countersigning. Run it from cron on a machine that is not the log's, or from a scheduled workflow; the exit code
|
|
5
5
|
// is the alert.
|
|
6
|
+
import { checkAnchorRecord } from "./anchor.js";
|
|
6
7
|
import { dsseVerify, dsseVerifiers } from "./crypto.js";
|
|
7
8
|
import { verifyConsistency } from "./log.js";
|
|
8
9
|
import { TREEHEAD_TYPE } from "./receipt.js";
|
|
@@ -26,6 +27,55 @@ export async function checkLog(o) {
|
|
|
26
27
|
throw new Error(`${res.status} from ${url.pathname}`);
|
|
27
28
|
return res.json();
|
|
28
29
|
};
|
|
30
|
+
const anchorChecks = async (tenant, head) => {
|
|
31
|
+
if (!o.anchorAddress || !o.anchorRpcUrls?.length) {
|
|
32
|
+
add(tenant, "anchor verifies on chain", false, "an anchor URL needs the pinned anchor address and at least one JSON-RPC endpoint");
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const logId = o.anchorLogIds && Object.hasOwn(o.anchorLogIds, tenant) ? o.anchorLogIds[tenant] : undefined;
|
|
36
|
+
if (logId === undefined) {
|
|
37
|
+
add(tenant, "anchor verifies on chain", false, `checking an anchor needs the log id of ${tenant} pinned (--anchor-log-id ${tenant}=<id>)`);
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
const aBase = o.anchorUrl.endsWith("/") ? o.anchorUrl : `${o.anchorUrl}/`;
|
|
41
|
+
let record;
|
|
42
|
+
try {
|
|
43
|
+
record = (await get(new URL(`${tenant}/latest.json`, aBase)));
|
|
44
|
+
}
|
|
45
|
+
catch (e) {
|
|
46
|
+
add(tenant, "anchor verifies on chain", false, e instanceof Error ? e.message : String(e));
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
const r = await checkAnchorRecord(record, { rpcUrls: o.anchorRpcUrls, address: o.anchorAddress, chainId: o.anchorChainId ?? 1, logKeys: keys, fetch: f });
|
|
50
|
+
if (!add(tenant, "anchor verifies on chain", r.ok, r.ok ? `size ${record.treeSize} in block ${r.blockNumber} at ${r.blockTime}${r.finalized ? ", finalized" : ", not yet finalized"}` : r.error))
|
|
51
|
+
return;
|
|
52
|
+
if (!r.ok)
|
|
53
|
+
return;
|
|
54
|
+
// the record's id is its signed checkpoint's (checked above); both it and the head must be the pinned log's
|
|
55
|
+
if (!add(tenant, "anchor and head name the pinned log", record.logId === logId && head.log === logId, `pinned ${logId}, anchored ${record.logId ?? "none"}, head ${head.log ?? "none"}`))
|
|
56
|
+
return;
|
|
57
|
+
add(tenant, "anchor is the newest from its address", r.newer === 0, r.newer === 0 ? undefined : `the address has sent ${r.newer} transaction(s) since this one: the record is not the current anchor`);
|
|
58
|
+
if (record.treeSize > head.treeSize) {
|
|
59
|
+
add(tenant, "head extends the anchored checkpoint", false, `the head at ${head.treeSize} is behind the anchored size ${record.treeSize}: the log was rolled back`);
|
|
60
|
+
}
|
|
61
|
+
else if (record.treeSize === head.treeSize) {
|
|
62
|
+
add(tenant, "head extends the anchored checkpoint", record.rootHash === head.rootHash, record.rootHash === head.rootHash ? `at the anchored size ${head.treeSize}` : `a different root at the anchored size ${head.treeSize}: history was rewritten`);
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
try {
|
|
66
|
+
const proof = (await get(new URL(tenant === "default" ? `consistency?old=${record.treeSize}&new=${head.treeSize}` : `t/${tenant}/consistency?old=${record.treeSize}&new=${head.treeSize}`, base)));
|
|
67
|
+
const ok = verifyConsistency(record.treeSize, record.rootHash, head.treeSize, head.rootHash, proof.hashes);
|
|
68
|
+
add(tenant, "head extends the anchored checkpoint", ok, ok ? `${record.treeSize} -> ${head.treeSize}` : `the head at ${head.treeSize} does not extend the anchored ${record.treeSize}: history was rewritten`);
|
|
69
|
+
}
|
|
70
|
+
catch (e) {
|
|
71
|
+
add(tenant, "head extends the anchored checkpoint", false, e instanceof Error ? e.message : String(e));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
// the block's time is the chain's, so a host that stopped anchoring cannot make a log look covered
|
|
75
|
+
const age = now() - Date.parse(r.blockTime);
|
|
76
|
+
const ahead = head.treeSize > record.treeSize;
|
|
77
|
+
add(tenant, "anchor keeps up with the log", !ahead || age <= (o.maxAnchorLagMs ?? 13 * 3_600_000), ahead ? `the head at ${head.treeSize} is ahead of an anchor ${Math.round(age / 60_000)} min old` : `the anchor covers the head; anchored ${Math.round(age / 60_000)} min ago`);
|
|
78
|
+
};
|
|
29
79
|
let keys = [];
|
|
30
80
|
try {
|
|
31
81
|
keys = (await fetchLogKeys(base, f)).keys;
|
|
@@ -60,6 +110,8 @@ export async function checkLog(o) {
|
|
|
60
110
|
}
|
|
61
111
|
if (!head)
|
|
62
112
|
continue;
|
|
113
|
+
if (o.anchorUrl)
|
|
114
|
+
await anchorChecks(tenant, head);
|
|
63
115
|
if (!o.checkpointsUrl)
|
|
64
116
|
continue;
|
|
65
117
|
const cpBase = o.checkpointsUrl.endsWith("/") ? o.checkpointsUrl : `${o.checkpointsUrl}/`;
|
package/dist/receipt.d.ts
CHANGED
|
@@ -63,11 +63,13 @@ export interface ReconciliationEvidence {
|
|
|
63
63
|
export interface ReceiptPredicate {
|
|
64
64
|
receiptId: string;
|
|
65
65
|
timestamp: string;
|
|
66
|
+
/** `strict` is the gateway's own statement that it ran in strict mode: every call precommitted to a remote, hash-only log, and no outbox */
|
|
66
67
|
issuer: {
|
|
67
68
|
kind: IssuerKind;
|
|
68
69
|
keyid: string;
|
|
69
70
|
version: string;
|
|
70
71
|
framework?: string;
|
|
72
|
+
strict?: boolean;
|
|
71
73
|
};
|
|
72
74
|
principal: {
|
|
73
75
|
id: string;
|
package/dist/verify.d.ts
CHANGED
|
@@ -22,6 +22,8 @@ export interface VerifyOptions {
|
|
|
22
22
|
logFile?: string;
|
|
23
23
|
/** If given, every tree head in the bundle must name this log, so a head from another tenant's log cannot be presented as this one's. */
|
|
24
24
|
logId?: string;
|
|
25
|
+
/** Require a strict gateway receipt: one whose issuer says it ran in strict mode, and whose call, if forwarded, carries the authorization committed before it. */
|
|
26
|
+
requireStrict?: boolean;
|
|
25
27
|
/**
|
|
26
28
|
* The withheld values, as `agent-custody reveal` writes them or the party that holds them hands them over: a partial
|
|
27
29
|
* predicate with `{ $custody: "disclosed", salt, value }` at each withheld path (`{ receiptId, request: { args: { reason: {...} } }, execution: { result: { content: {...} }, error, upstream: { rawBody } }, policy: { errors }, facts: { <name>: { value, args } } }`).
|
package/dist/verify.js
CHANGED
|
@@ -186,6 +186,12 @@ export function verifyBundle(bundle, opts) {
|
|
|
186
186
|
const p = st.predicate;
|
|
187
187
|
add("issuer kind is known", p.issuer.kind === "gateway" || p.issuer.kind === "sdk", `${p.issuer.kind}${p.issuer.framework ? ` / ${p.issuer.framework}` : ""}`);
|
|
188
188
|
add("issuer keyid matches signer", p.issuer.keyid === sig.keyid);
|
|
189
|
+
if (opts.requireStrict) {
|
|
190
|
+
add("strict mode in force", p.issuer.kind === "gateway" && p.issuer.strict === true, p.issuer.strict === true ? undefined : "the issuer does not say it ran in strict mode");
|
|
191
|
+
// under strict mode every call is precommitted; a provider read the operator ran is a lookup, not a call
|
|
192
|
+
const forwarded = p.execution.status === "executed" || p.execution.status === "failed" || p.execution.status === "error";
|
|
193
|
+
add("strict: call precommitted before forwarding", !forwarded || !!p.reconciliation || !!p.authorization, forwarded && !p.reconciliation && !p.authorization ? `the call was ${p.execution.status} with no authorization committed first` : undefined);
|
|
194
|
+
}
|
|
189
195
|
if (p.operation) {
|
|
190
196
|
add("operation observed by gateway", p.issuer.kind === "gateway" && p.operation.provenance === "observed");
|
|
191
197
|
if (!p.reconciliation) {
|
|
@@ -547,7 +553,7 @@ export function formatReport(r) {
|
|
|
547
553
|
return lines.join("\n");
|
|
548
554
|
const p = r.statement.predicate;
|
|
549
555
|
lines.push("");
|
|
550
|
-
lines.push(`ISSUER: ${p.issuer.kind}${p.issuer.framework ? ` (${p.issuer.framework})` : ""}, ${ISSUER_NOTE[p.issuer.kind] ?? "unknown issuer kind"}`);
|
|
556
|
+
lines.push(`ISSUER: ${p.issuer.kind}${p.issuer.framework ? ` (${p.issuer.framework})` : ""}${p.issuer.strict ? ", strict mode" : ""}, ${ISSUER_NOTE[p.issuer.kind] ?? "unknown issuer kind"}`);
|
|
551
557
|
lines.push("");
|
|
552
558
|
lines.push("field provenance value");
|
|
553
559
|
const row = (f, prov, v) => lines.push(`${f.padEnd(15)} ${prov.padEnd(11)} ${typeof v === "string" ? v : JSON.stringify(v)}`);
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
# Anchoring the log on a chain
|
|
2
|
+
|
|
3
|
+
The log's operator holds the key that signs the log's tree heads. A signed checkpoint therefore shows what the log said at one moment, but it cannot show that the operator never rewrote a tenant's tree later. Anyone who saved an earlier checkpoint can check that, and so can a witness on a machine the operator does not control. The anchor removes the need for either: it commits each new checkpoint to a public chain that nobody in the chain of custody controls: Ethereum mainnet by default, or another EVM chain the installation chooses. A monitor then checks the log against the chain alone.
|
|
4
|
+
|
|
5
|
+
## What it proves, and what it does not
|
|
6
|
+
|
|
7
|
+
| claim | who can check it | holds against |
|
|
8
|
+
| --- | --- | --- |
|
|
9
|
+
| this signed checkpoint existed no later than this block's time | anyone with a JSON-RPC endpoint, the pinned anchor address, and the log's pinned id | the log's operator, the checkpoints host, the anchor's own host |
|
|
10
|
+
| this is the newest anchor, so no later one says something else | the same: the address's transaction count is on the chain | the anchor's own host |
|
|
11
|
+
| the log today extends what was anchored, so nothing before it was removed or changed | the same, plus the log's consistency proof | the log's operator |
|
|
12
|
+
| the receipts under the checkpoint are true | nobody, from the chain | nothing: a chain commits to existence, not truth |
|
|
13
|
+
|
|
14
|
+
What an anchor rests on depends on the chain; see [choosing the chain](#choosing-the-chain).
|
|
15
|
+
|
|
16
|
+
A rewritten tree is caught between anchors as well as at them: once a checkpoint is anchored, every later head must extend it. What the anchor does not catch is a rewrite inside the window before the first anchor that covers it. That window is at most the anchor's interval, six hours by default, plus the time to finality.
|
|
17
|
+
|
|
18
|
+
The anchor host is not trusted. A record it publishes is checked against the chain:
|
|
19
|
+
- the checkpoint must verify against the log's published keys;
|
|
20
|
+
- it must name the log the verifier pinned;
|
|
21
|
+
- its leaf must be under the anchored Merkle root;
|
|
22
|
+
- a successful transaction from the pinned address to itself must carry exactly that root;
|
|
23
|
+
- that transaction must be the newest the address has sent.
|
|
24
|
+
|
|
25
|
+
The last point is why every anchor transaction covers every watched log. A log that did not move goes in again at its last checkpoint, so the newest transaction always holds each log's current anchor, and a host that serves an older, genuine record is caught by the address's transaction count. The address must therefore send nothing but anchors.
|
|
26
|
+
|
|
27
|
+
Pin the address, the chain, and each log's id from a source other than the anchor's host, such as the welcome sheet, the security page, or the log id in your own receipts' tree heads. Tenant logs share the log's keys and the anchor's address, so only the id tells one tenant's checkpoint from another's. The anchor's `/.well-known/agent-custody-anchor.json` is for discovery only.
|
|
28
|
+
|
|
29
|
+
JSON-RPC endpoints are trusted to report the chain. With several `--anchor-rpc-env` endpoints from different providers, each one must agree on the transaction and its block. A block counts as finalized only when every endpoint says so.
|
|
30
|
+
|
|
31
|
+
## How it works
|
|
32
|
+
|
|
33
|
+
Each run, for each watched log, the anchor:
|
|
34
|
+
|
|
35
|
+
1. fetches `latest.json` from the checkpoints host and verifies it against the log's published keys;
|
|
36
|
+
2. proves, with the log's `GET /consistency`, that it extends the last checkpoint this anchor committed;
|
|
37
|
+
3. refuses, and writes `<dir>/<tenant>/ALARM.json` and `ALARM-<time>.json`, when it does not, when a second root appears at the same size, or when an unpublished key signed it.
|
|
38
|
+
|
|
39
|
+
When any log has moved, every watched log's checkpoint becomes a leaf of one Merkle tree: the new one for a log that moved, the last one anchored for the rest. Each leaf is the RFC 9162 leaf hash of the checkpoint's canonical envelope. The anchor sends one zero-value transaction from its address to itself, with calldata `0x` + hex(`agent-custody/anchor/1:`) + the 32-byte root. Once the transaction is in a block, each log gets `<dir>/<tenant>/<treeSize>.json` and `latest.json`: its own checkpoint, the transaction, the block, the root, and its inclusion proof. A log's record names no other log.
|
|
40
|
+
|
|
41
|
+
Nothing is sent when no checkpoint has moved, so an idle log costs nothing.
|
|
42
|
+
|
|
43
|
+
A transaction in flight holds the address's nonce, and no new one is sent until its block is finalized:
|
|
44
|
+
- **In a block:** the records are published at once, and the run reports `included`.
|
|
45
|
+
- **Moved by a reorg:** if the transaction lands in another block, the records are written again with that block.
|
|
46
|
+
- **Dropped by a reorg:** if it stays out of every block for 30 minutes (`resendAfterMs`), the same root is sent again.
|
|
47
|
+
- **Finalized:** only now do its checkpoints become the ones that later checkpoints must extend.
|
|
48
|
+
- **Failed:** it is reported, and the next run sends the same checkpoints again.
|
|
49
|
+
|
|
50
|
+
While a transaction is pending, the service checks it every minute, so a record is published soon after it lands.
|
|
51
|
+
|
|
52
|
+
## Running it
|
|
53
|
+
|
|
54
|
+
```bash
|
|
55
|
+
export ANCHOR_RPC_URL=https://... # a mainnet JSON-RPC endpoint; a provider URL often carries its key
|
|
56
|
+
export ANCHOR_KEY=0x... # the anchor's private key, for this purpose only
|
|
57
|
+
npm install viem # optional dependency, needed by the anchor only
|
|
58
|
+
agent-custody anchor --log-url https://log.example.com/ --checkpoints-url https://checkpoints.example.com/ \
|
|
59
|
+
--out /srv/anchors --rpc-url-env ANCHOR_RPC_URL --key-env ANCHOR_KEY --tenant acme --tenant default
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
| flag | default | meaning |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| `--rpc-url-env NAME` | | the environment variable holding the JSON-RPC URL |
|
|
65
|
+
| `--key-env NAME` | | the environment variable holding the private key, 0x-prefixed hex |
|
|
66
|
+
| `--chain` | `ethereum` | `ethereum`, `base`, `arbitrum`, `optimism`, `polygon`, or any EVM chain id; the endpoint must report the same chain |
|
|
67
|
+
| `--max-fee-gwei` | per chain, below | a run whose fee per gas would exceed this is skipped, not sent; required for a chain given by id alone |
|
|
68
|
+
| `--every` | `21600` | seconds between runs |
|
|
69
|
+
| `--once` | | one run; exit 1 when a log was refused |
|
|
70
|
+
|
|
71
|
+
Serve `<dir>` read-only from a host of its own, or under the checkpoints host.
|
|
72
|
+
|
|
73
|
+
**The key.** Generate it for this purpose and hold only what it needs to pay for anchors. Its address is the anchor's identity: publish it where tenants already read the log's key ids. A key that leaks lets someone else post transactions from that address. A transaction that carries a root nobody computed proves nothing, so the harm is spent funds, not a false anchor. To rotate, publish the new address beside the old one with its date and keep the old one listed, so earlier records still check.
|
|
74
|
+
|
|
75
|
+
**Cost.** One transaction uses about 23,200 gas on Ethereum: 21,000 for the transaction and the calldata floor of EIP-7623 for its 55 bytes. At 2 gwei per gas that is about 0.000046 ETH, and at the default cap of 20 gwei about 0.00046 ETH. An L2 also charges for posting the transaction's data to Ethereum, which the fee cap does not bound, though for 55 bytes it is small. The anchor sends at most one transaction per run, and only when a log grew, so the default interval means at most four a day.
|
|
76
|
+
|
|
77
|
+
## Choosing the chain
|
|
78
|
+
|
|
79
|
+
The default is Ethereum mainnet. An installation can anchor on any other EVM chain with `--chain`; a verifier then names the same chain with `--anchor-chain`, and a record from another chain fails. The record carries its chain id, and an endpoint that reports another chain fails the check.
|
|
80
|
+
|
|
81
|
+
| `--chain` | chain id | default `--max-fee-gwei` | what an anchor there rests on |
|
|
82
|
+
| --- | --- | --- | --- |
|
|
83
|
+
| `ethereum` | 1 | 20 | Ethereum's consensus; a block is finalized after about two epochs, some 13 minutes |
|
|
84
|
+
| `base` | 8453 | 1 | an OP Stack rollup: one sequencer orders transactions and can delay or refuse one; a block is finalized once its batch is in a finalized Ethereum block |
|
|
85
|
+
| `optimism` | 10 | 1 | the same as Base |
|
|
86
|
+
| `arbitrum` | 42161 | 1 | an Arbitrum rollup: the same shape, with its own sequencer, finalized once its batch is in a finalized Ethereum block |
|
|
87
|
+
| `polygon` | 137 | 1000 | Polygon PoS: its own validator set, which checkpoints to Ethereum; finality is Polygon's, not Ethereum's |
|
|
88
|
+
| a chain id | that id | none: give one | whatever that chain's consensus is; say so to whoever relies on the anchor |
|
|
89
|
+
|
|
90
|
+
What a chain's sequencer or validators can do is delay an anchor or refuse it, which `log-check` shows as an anchor that does not keep up. Rewriting a block that a verifier saw finalized would mean breaking that chain's own guarantees, which differ by chain. Choose the chain the people who rely on the log already trust. A verifier checks finality through `eth_getBlockByNumber("finalized")`, and every named chain's endpoints answer it.
|
|
91
|
+
|
|
92
|
+
The fee caps are in gwei per gas of the chain's own gas token: ETH on Ethereum and the L2s, POL on Polygon.
|
|
93
|
+
|
|
94
|
+
## Checking it
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
export ETH_RPC_A=https://... ETH_RPC_B=https://...
|
|
98
|
+
agent-custody log-check --log-url https://log.example.com/ --tenant acme \
|
|
99
|
+
--anchor-url https://anchors.example.com/ --anchor-address 0x... --anchor-rpc-env ETH_RPC_A --anchor-rpc-env ETH_RPC_B \
|
|
100
|
+
--anchor-chain ethereum --anchor-log-id acme=acme
|
|
101
|
+
```
|
|
102
|
+
|
|
103
|
+
Each log being checked needs its id pinned with `--anchor-log-id <tenant>=<log id>` (repeatable). Five checks are added per log:
|
|
104
|
+
|
|
105
|
+
- **`anchor verifies on chain`**: the record checks out against the chain as described above. The detail says whether the block is finalized yet.
|
|
106
|
+
- **`anchor and head name the pinned log`**: the anchored checkpoint and the log's current head both carry the pinned id, so another tenant's record cannot stand in for this log's.
|
|
107
|
+
- **`anchor is the newest from its address`**: the chain's count of transactions from the address shows that none came after this record's.
|
|
108
|
+
- **`head extends the anchored checkpoint`**: the log's head is at or beyond the anchored size, and the log's consistency proof shows that it extends the anchored root. A head below the anchored size is a rolled-back log. A head that does not extend the anchored root is a rewritten one.
|
|
109
|
+
- **`anchor keeps up with the log`**: a head ahead of its newest anchor fails once that anchor's block is older than `--max-anchor-lag` (default 46800 s, thirteen hours). The block's time is the chain's, so an anchor that stopped cannot be hidden by its host.
|
|
110
|
+
|
|
111
|
+
Anchors are sent only when a log grows. A log that has been quiet for longer than the lag therefore shows this failure after it grows, until the anchor's next run covers it. Keep the anchor's interval well under the lag.
|
|
112
|
+
|
|
113
|
+
An `--anchor-url` without `--anchor-address`, at least one `--anchor-rpc-env`, and a pinned log id for each log is a failure, never a skipped check.
|
|
114
|
+
|
|
115
|
+
In code, `checkAnchorRecord(record, { rpcUrls, address, chainId, logKeys })` checks one record and needs no Ethereum library. Its `newer` is the number of transactions the address has sent since the record's, so 0 means this is the current anchor. `new Anchor({ logUrl, checkpointsUrl, tenants, chain, outDir })` runs the anchor with any `AnchorChain`, and `evmChain({ rpcUrl, privateKey, chainId, maxFeeGwei })` is the EVM one. `resolveAnchorChain("base")` gives a named chain's id and default cap, and `ANCHOR_CHAINS` lists them. Example 33 runs the whole loop against an in-memory chain; the tests drive real signed transactions.
|
package/docs/configuration.md
CHANGED
|
@@ -202,7 +202,8 @@ docker run --rm -v "$PWD/config:/config:ro" -v gateway-data:/data --env-file .en
|
|
|
202
202
|
| a stdio `command` exists, and a script argument exists | error, and a warning |
|
|
203
203
|
| the receipts, log, revocation, operations database, and approvals paths can be written, and the revocation file is a JSON array | error |
|
|
204
204
|
| the grant the config names verifies, and is inside its window | error, and a warning near expiry |
|
|
205
|
-
| a remote log with an empty `precommit` | warning: a log outage after a call puts its receipt in the outbox, so the side effect is in the log only after the outbox is appended |
|
|
205
|
+
| a remote log with an empty `precommit` | warning: a log outage after a call puts its receipt in the outbox, so the side effect is in the log only after the outbox is appended. Not reported under `strict`, which precommits every tool |
|
|
206
|
+
| what [strict mode](usage.md#strict-mode) would refuse: a local log, a remote log that is not `hashOnly`, one without `keys` | with `"strict": true`, **error**: the gateway does not start; without it, listed under `strict` as what turning it on would refuse |
|
|
206
207
|
|
|
207
208
|
With **`--connect`** it also starts the upstreams, which is where an unreachable server or **two upstreams offering the same tool** shows up, prints the tools they offer, and compares every tool name in `precommit`, `facts`, `approvals`, `operations`, and the grant's scopes with that list. A name in `precommit`, `facts`, `approvals`, or `operations` that no upstream offers is an **error** (for `precommit` it means the tool you meant is forwarded before it is logged); a grant scope that names nothing is a warning. `--connect` starts your stdio upstreams and may create the receipts directory. It exits 1 on any error, so it can gate a deploy.
|
|
208
209
|
|
|
@@ -218,6 +219,9 @@ With **`--connect`** it also starts the upstreams, which is where an unreachable
|
|
|
218
219
|
| `exactly one of logFile or log is required` | both, or neither | a local file, or a remote log |
|
|
219
220
|
| `precommit with a remote log needs log.keys` | a remote log gating consequential calls without a pinned key | add the log's public key file to `log.keys` |
|
|
220
221
|
| `requirePrecommit is set and precommit is empty` | a remote log with no consequential tools named | name them in `precommit`, or `["*"]` |
|
|
222
|
+
| `strict mode needs a remote log` | `"strict": true` with `logFile`, a log the operator can rewrite | set `log.url` to a log someone else runs |
|
|
223
|
+
| `strict mode needs log.hashOnly` | `"strict": true` with a log that would receive whole receipts | add `"hashOnly": true` to `log` |
|
|
224
|
+
| `strict mode needs log.keys` | `"strict": true` with the log's key not pinned | add the log's public key file to `log.keys` |
|
|
221
225
|
| `fact "f" uses tool t, which precommit names as consequential` | a fact lookup must be a read | use a read tool for the fact |
|
|
222
226
|
| `ENOENT … gateway.key` | the key file does not exist | `agent-custody keygen`, or let the container create it |
|
|
223
227
|
| `EROFS` or a permission error on `receipts` | a writable path points into the read-only `/config` | use an absolute path under `/data` |
|
package/docs/threat-model.md
CHANGED
|
@@ -51,7 +51,7 @@ Each row names the attacker, the move, the defence, and whether the defence is a
|
|
|
51
51
|
| attack | defence | kind |
|
|
52
52
|
| --- | --- | --- |
|
|
53
53
|
| Rewrite a receipt after the fact | The receipt's envelope is signed by the gateway key, which the operator holds, so the signature alone does not stop this. What stops it is the log: the leaf hash of the original envelope is in a tree whose head the log signed, and a rewritten receipt has a different hash with no inclusion proof. | evidence, with a remote log; deployment, with a local log the operator can rewrite |
|
|
54
|
-
| Drop a receipt | The log's tree only grows, and consistency proofs between any two heads show nothing was removed. A receipt the operator never logged never existed as evidence, which is the point of `precommit` for consequential calls: the authorization leaf goes in before the action. | evidence for logged receipts; withheld calls for pre-committed tools |
|
|
54
|
+
| Drop a receipt | The log's tree only grows, and consistency proofs between any two heads show nothing was removed. A receipt the operator never logged never existed as evidence, which is the point of `precommit` for consequential calls: the authorization leaf goes in before the action. [Strict mode](usage.md#strict-mode) does that for every call, with a remote hash-only log and no outbox, and its receipts say so, so a verifier can require it; a modified gateway can still claim strict mode. | evidence for logged receipts; withheld calls for pre-committed tools, and for every call under strict mode |
|
|
55
55
|
| Forge a receipt for an action that never happened | Nothing in the log stops the operator logging a fabricated receipt; the log commits to existence, not truth. What limits it: the upstream's signature over the result when the upstream signs, provider attestations where the provider delivers them, and the principal's signature on the grant. A forged receipt for a signing upstream fails its `upstream` checks. | evidence, where the upstream signs; otherwise the operator's word |
|
|
56
56
|
| Replace the policy and claim a different one decided | The receipt carries the sha256 of the policy text; a verifier with the policy file can check it, and a policy change is a different digest in every later receipt. | evidence |
|
|
57
57
|
| Produce a second, cleaner history | With a remote log, both histories would need heads signed by the log's key at the same size with different roots; the checkpoints host and the witness make that detectable. With a local log, a copy taken earlier by someone else is the only defence. | evidence with a witnessed remote log |
|
|
@@ -76,7 +76,7 @@ Each row names the attacker, the move, the defence, and whether the defence is a
|
|
|
76
76
|
| attack | defence | kind |
|
|
77
77
|
| --- | --- | --- |
|
|
78
78
|
| Read receipt contents | The hosted log runs with `--hash-only` and refuses a full leaf at append, so no receipt reaches the log process even from a misconfigured gateway or a stolen token; the tenant's `hashOnly` setting keeps the receipt from ever leaving their machine. A log an operator runs for themselves may accept full leaves. | evidence: the server refuses; deployment on the tenant's side |
|
|
79
|
-
| Rewrite a tenant's tree | Every head is signed and published as a checkpoint on a second host; a rewrite means two signed heads at one size with different roots, or a later head that does not extend an earlier one. Anyone holding an earlier head detects it with `audit`; the monitor does it every ten minutes; the witness countersigns only heads that extend the last it signed. | evidence, given a witness or an earlier head held elsewhere |
|
|
79
|
+
| Rewrite a tenant's tree | Every head is signed and published as a checkpoint on a second host; a rewrite means two signed heads at one size with different roots, or a later head that does not extend an earlier one. Anyone holding an earlier head detects it with `audit`; the monitor does it every ten minutes; the witness countersigns only heads that extend the last it signed; the anchor commits each checkpoint to Ethereum, and `log-check --anchor-url` fails a head that does not extend the anchored one. | evidence, given a witness or an earlier head held elsewhere |
|
|
80
80
|
| Show different histories to different verifiers | Same: checkpoints are public and the witness sees one history. Without a witness, two verifiers who compare heads detect it, and nobody else does. | evidence with a witness; otherwise detection needs comparison |
|
|
81
81
|
| Mint a token for a tenant and append noise | Appends are hashes with no content; the tenant's export and usage show leaves and live tokens they did not make, and the audit trail, which the tenant's export carries, records who minted what and from where. | deployment |
|
|
82
82
|
| Sign with a key not in the key document | Verifiers pin by keyid from the published document; a head signed by an unpublished key fails. Retired keys stay published so old heads keep verifying, and a rotation is announced with its date. | evidence |
|
|
@@ -90,6 +90,20 @@ Each row names the attacker, the move, the defence, and whether the defence is a
|
|
|
90
90
|
| Refuse a true history | An alarm with no consistency failure behind it is a false alarm; the log's consistency proof settles it in public. Verifiers who require a witness signature see a gap, which is the correct outcome for a disputed period. | evidence |
|
|
91
91
|
| Collude with the log operator | Two independent operators are the assumption. A witness on the log operator's machine proves nothing, and the deployment guide says so. | assumption |
|
|
92
92
|
|
|
93
|
+
### By the anchor
|
|
94
|
+
|
|
95
|
+
| attack | defence | kind |
|
|
96
|
+
| --- | --- | --- |
|
|
97
|
+
| Publish a record for a checkpoint it never anchored | The record is checked against the chain: the transaction must come from the pinned address to itself, succeed, and carry exactly the root the record's inclusion proof leads to, from a checkpoint the log's keys signed. | evidence |
|
|
98
|
+
| Anchor a rewritten history | The anchor proves each checkpoint extends the last one it anchored, and refuses with an alarm otherwise. An anchor that skipped the proof would still leave two anchored roots that cannot both extend the earlier one, in public. | evidence |
|
|
99
|
+
| Serve an older, genuine record as the current one | Every anchor transaction covers every watched log, and the verifier requires the record's transaction to be the newest from the address, by the address's transaction count on the chain. | evidence |
|
|
100
|
+
| Serve another tenant's record for this log | Tenant logs share the log's keys and the anchor's address, so the verifier pins each log's id; the anchored checkpoint and the current head must both name it. | evidence, given the pinned id |
|
|
101
|
+
| Stop anchoring | A head ahead of its newest anchor fails once that anchor's block, timed by the chain, is older than `--max-anchor-lag`. Between anchors, a rewrite is caught only once a later anchor or another holder of a head disagrees. | detection |
|
|
102
|
+
| Count an anchor a reorg removed | The anchor holds a transaction until its block is finalized, writes its records again if a reorg moves it, and sends the same root again if a reorg drops it. A verifier reports whether the record's block is finalized. | evidence once finalized |
|
|
103
|
+
| Leak its key | Someone else can spend the funds and post transactions from the address. A root that no checkpoint leads to proves nothing, so a leaked key cannot make a false record check out. | evidence |
|
|
104
|
+
| Anchor on a chain a few parties control | The installation chooses the chain, and the record names it. On an L2 a sequencer can delay or refuse an anchor, which shows as an anchor that does not keep up. A finalized block is as hard to rewrite as that chain makes it, which differs by chain (`docs/anchoring.md` lists what each rests on). | assumption: the chain's own guarantees |
|
|
105
|
+
| Lie through a JSON-RPC endpoint | Give `log-check` several endpoints from different providers: they must agree on the transaction and its block, and a block counts as finalized only when every endpoint says so. | assumption: not every endpoint lies the same way |
|
|
106
|
+
|
|
93
107
|
### On the network
|
|
94
108
|
|
|
95
109
|
| attack | defence | kind |
|
package/docs/tutorials.md
CHANGED
|
@@ -42,6 +42,8 @@ Suggested reading order is the numbering. Output lands in `examples-out/`, which
|
|
|
42
42
|
| 30 | payload-bound human approvals | [30-payload-bound-approvals.ts](../examples/30-payload-bound-approvals.ts) | two people sign the exact refund; missing approval, one signer, changed amount or beneficiary, extra arguments, and expiry are refused; the approved call executes once, its replay is refused, and every receipt verifies with separately trusted approval keys | `src/approval.ts`, `src/gateway.ts`, `src/verify.ts` |
|
|
43
43
|
| 31 | enterprise sign-in and roles | [31-enterprise-sign-in.ts](../examples/31-enterprise-sign-in.ts) | an enterprise tenant signs in through its own identity provider, a stand-in OIDC IdP: the operator sets single sign-on, a member joins as readonly and is refused a policy write, an owner promotes them to reviewer, and enforcement turns password sign-in off | `src/sso.ts`, `src/portal.ts` |
|
|
44
44
|
| 32 | the gateway console | [32-console.ts](../examples/32-console.ts) | a gateway that has made two receipts, and its operator's console: a token on every route, the receipts with a verdict each, a stricter policy replayed against the recorded calls before it is saved, the save recorded with the old version kept and a stale edit refused, and a grant inspected, revoked, and then refused by the gateway | `src/console.ts`, `src/console-page.ts` |
|
|
45
|
+
| 33 | anchoring the log on a chain | [33-chain-anchor.ts](../examples/33-chain-anchor.ts) | a log publishes a checkpoint, the anchor commits it to a stand-in chain in one transaction, and `log-check` passes against the chain; the operator swaps in a rewritten log under the same key and log id, and `log-check` fails it from the chain alone |
|
|
46
|
+
| 34 | strict mode | [34-strict-mode.ts](../examples/34-strict-mode.ts) | `check` lists what strict mode would refuse; a local log and a log that is not hash-only are refused at startup; behind a hash-only log with a pinned key, a read is precommitted and its receipt says `issuer.strict`; `requireStrict` accepts it and refuses an ordinary receipt; with the log down the call is not forwarded and the outbox stays empty | `src/config.ts`, `src/gateway.ts`, `src/check.ts`, `src/verify.ts` |
|
|
45
47
|
|
|
46
48
|
## How policies are defined, in one paragraph
|
|
47
49
|
|
|
@@ -53,6 +55,7 @@ A policy is a Cedar file. The gateway turns each tool call into a Cedar request:
|
|
|
53
55
|
- [codex-recovery.md](codex-recovery.md): the opt-in live Codex support incident, operator-reviewed recovery, and its offline state example
|
|
54
56
|
- [approvals.md](approvals.md): exact-action signatures, two-person thresholds, consumption, and privacy limits
|
|
55
57
|
- [console.md](console.md): the admin console: run it, what each tab does, how it is protected, and its limits
|
|
58
|
+
- [anchoring.md](anchoring.md): the log's checkpoints on Ethereum: what an anchor proves, running it, and checking a log against the chain
|
|
56
59
|
- [financial-operations.md](financial-operations.md): payment retries, budget reservations, provider contract, and operator reconciliation
|
|
57
60
|
- [sdk.md](sdk.md): the interceptor and every adapter
|
|
58
61
|
- [policies.md](policies.md): the Cedar mapping, evaluation rules, tested examples, gotchas
|
package/docs/usage.md
CHANGED
|
@@ -135,7 +135,7 @@ Exactly one of the two. The bearer token comes from the named environment variab
|
|
|
135
135
|
|
|
136
136
|
To test a different policy against the history already collected, run `agent-custody policy simulate --policy proposed.cedar --receipts receipts --issuer-key keys/gateway.pub --principal-key keys/principal.pub --out simulation.json`. It replays recorded arguments and fact values without calling upstreams, lists changed decisions by tool and reason with the receipt ids, and records the proposed policy digest. Missing replay inputs make the report incomplete. See [the policy simulation guide](policies.md#simulating-a-policy-against-recorded-history).
|
|
137
137
|
|
|
138
|
-
The grant is checked on every call, not only when the session opens: a call after `expiresAt` is denied with a receipt that says so, the check is repeated just before the forward (a grant that ran out while the facts were gathered leaves the call `withheld`), and over HTTP a session whose grant has expired or been revoked is closed on its next request with `403`. `"revokedGrants": "revoked.json"` names a file of grant digests the gateway re-reads whenever it changes. The digest is sha256 over the grant's signed payload, so extra signatures or fields on the envelope do not change it, and revoking a grant also revokes every grant delegated from it. A file that cannot be read denies every call until it can be read; `agent-custody revoke --config gateway.json --grant grant.json` appends a grant's digest to it, after which every session under that grant refuses its next call and no new session opens for it, with no key rotation. The Cedar policy is re-read the same way: when `policyFile` changes (device, inode, mtime, ctime, or size; a file written in the last two seconds is re-read on each call until it settles), the next call is evaluated under the new policy, with no restart and no dropped session, and a call already evaluating finishes under the policy it started with, whose digest its receipt carries. A changed file that does not parse, or that cannot be read, is refused: the policy in force stays, never an allow, and the gateway prints `POLICY NOT RELOADED` on stderr. Every change and every refusal is appended to `receipts/policy-reloads.jsonl` as `{ at, file, event: "reloaded" | "refused", from, to, errors?, warnings? }`, with the digest in force and the digest of the new file (`null` when the file was removed or cannot be read), so the change between two receipts' `policyDigest`s has a time. A reloaded policy with no permit rule is applied, since it denies every call, but is printed and recorded with the warning `no permit rule: every call is denied`. Write the file by rename, as `agent-custody console` does. A file written in place can be read half-written: a prefix that parses, missing a trailing `forbid`, decides calls until the write finishes and the settled file is read. `precommit` names the consequential tools, or `["*"]` for all of them. For every other tool the gateway forwards the call and then records it, so if the log is unreachable at that moment the side effect exists before its evidence is in the log: the receipt waits in the outbox. With a remote log and an empty `precommit`, the gateway prints a warning at startup and `agent-custody check` reports it; `"requirePrecommit": true` makes it a startup error. For a tool in `precommit` the gateway first signs an authorization statement, everything the receipt will say except the outcome, and appends it to the log. Only if the log took it does the call go upstream. The receipt then embeds that authorization with its own inclusion proof, and a verifier checks that it names this call and sits in the log before the receipt does. If the log will not take it, or answers with a head or proof that does not verify, the call is not forwarded, the agent is told `Not executed`, and the receipt records `execution.status: "withheld"` with the policy's `allow` beside it. The authorization is also written on its own as `receipts/<receiptId>.authorization.json`, which is the evidence that survives if the gateway dies between forwarding and the receipt. Use it for money, for anything irreversible, and for anything a counterparty could later dispute; the cost is one extra log append per call.
|
|
138
|
+
The grant is checked on every call, not only when the session opens: a call after `expiresAt` is denied with a receipt that says so, the check is repeated just before the forward (a grant that ran out while the facts were gathered leaves the call `withheld`), and over HTTP a session whose grant has expired or been revoked is closed on its next request with `403`. `"revokedGrants": "revoked.json"` names a file of grant digests the gateway re-reads whenever it changes. The digest is sha256 over the grant's signed payload, so extra signatures or fields on the envelope do not change it, and revoking a grant also revokes every grant delegated from it. A file that cannot be read denies every call until it can be read; `agent-custody revoke --config gateway.json --grant grant.json` appends a grant's digest to it, after which every session under that grant refuses its next call and no new session opens for it, with no key rotation. The Cedar policy is re-read the same way: when `policyFile` changes (device, inode, mtime, ctime, or size; a file written in the last two seconds is re-read on each call until it settles), the next call is evaluated under the new policy, with no restart and no dropped session, and a call already evaluating finishes under the policy it started with, whose digest its receipt carries. A changed file that does not parse, or that cannot be read, is refused: the policy in force stays, never an allow, and the gateway prints `POLICY NOT RELOADED` on stderr. Every change and every refusal is appended to `receipts/policy-reloads.jsonl` as `{ at, file, event: "reloaded" | "refused", from, to, errors?, warnings? }`, with the digest in force and the digest of the new file (`null` when the file was removed or cannot be read), so the change between two receipts' `policyDigest`s has a time. A reloaded policy with no permit rule is applied, since it denies every call, but is printed and recorded with the warning `no permit rule: every call is denied`. Write the file by rename, as `agent-custody console` does. A file written in place can be read half-written: a prefix that parses, missing a trailing `forbid`, decides calls until the write finishes and the settled file is read. `precommit` names the consequential tools, or `["*"]` for all of them. For every other tool the gateway forwards the call and then records it, so if the log is unreachable at that moment the side effect exists before its evidence is in the log: the receipt waits in the outbox. With a remote log and an empty `precommit`, the gateway prints a warning at startup and `agent-custody check` reports it; `"requirePrecommit": true` makes it a startup error, and [strict mode](#strict-mode) precommits every tool. For a tool in `precommit` the gateway first signs an authorization statement, everything the receipt will say except the outcome, and appends it to the log. Only if the log took it does the call go upstream. The receipt then embeds that authorization with its own inclusion proof, and a verifier checks that it names this call and sits in the log before the receipt does. If the log will not take it, or answers with a head or proof that does not verify, the call is not forwarded, the agent is told `Not executed`, and the receipt records `execution.status: "withheld"` with the policy's `allow` beside it. The authorization is also written on its own as `receipts/<receiptId>.authorization.json`, which is the evidence that survives if the gateway dies between forwarding and the receipt. Use it for money, for anything irreversible, and for anything a counterparty could later dispute; the cost is one extra log append per call.
|
|
139
139
|
|
|
140
140
|
#### When the log fails
|
|
141
141
|
|
|
@@ -152,6 +152,24 @@ Several gateways, or a gateway and a command, can share one `receipts/` director
|
|
|
152
152
|
|
|
153
153
|
When the log takes a receipt, the gateway records the log's answer in the outbox entry before it writes the bundle. If the bundle write then fails (a full disk, a permission error), the gateway prints the error on stderr, and the next flush writes the bundle from the recorded answer and does not append the leaf again. A process that dies between the append and that record appends the leaf again on the next flush; the log then holds it twice, and either copy proves the receipt. A gateway that dies after the forward and before the outbox write leaves no receipt; `precommit` is the guard for the calls where that matters. Before the gateway appends an outbox entry, it checks the entry. It renames an entry to `<name>.bad`, does not append it, and prints a warning, when the file is damaged, when the entry carries this gateway's key id but the signature does not verify, or when the receipt id in the statement is not the id in the file name. An entry that another key signed (a rotated gateway key, or a restored backup) is not appended, is not called forged, and stays in the outbox; the gateway prints a warning on each flush. Restore the key that signed it, or move the entry away. Until the log takes a pending receipt, `receipts/<id>.json` does not exist, so `verify`, `explain`, `blast`, the review console, and `prune` do not see the call yet.
|
|
154
154
|
|
|
155
|
+
#### Strict mode
|
|
156
|
+
|
|
157
|
+
The outbox keeps the receipt of a call through a log outage, but the operator runs the gateway: killing it between the forward and the outbox write, or deleting the outbox entry, leaves a call with no receipt, and a local log can be rewritten outright. `"strict": true` closes that for the calls the agent makes:
|
|
158
|
+
|
|
159
|
+
```json
|
|
160
|
+
{
|
|
161
|
+
"strict": true,
|
|
162
|
+
"log": { "url": "https://log.example.com/t/acme/", "tokenEnv": "AGENT_CUSTODY_LOG_TOKEN", "hashOnly": true, "keys": ["keys/log.pub"] }
|
|
163
|
+
}
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
- The gateway does not start with `logFile`, with a `log` that is not `hashOnly`, or with a `log` without `keys`. Each is a startup error that names the setting, and `agent-custody check` reports it. On a config without `strict`, `check` lists what strict mode would refuse.
|
|
167
|
+
- Every tool is precommitted, as with `precommit: ["*"]`: the authorization is in the log before the call is forwarded, and a call whose authorization the log will not take is `withheld`. In observe mode too, where a call the policy would deny is still forwarded and is precommitted like any other.
|
|
168
|
+
- No receipt goes to the outbox. A receipt that the log refuses after the forward is not kept, the call returns an error to the agent, and the authorization in the log stands. A gateway killed at any point leaves either no call or an authorization with no outcome, which a verifier reports as incomplete. Receipts left in the outbox from before strict mode was turned on are appended once, at start; there is no 30-second retry.
|
|
169
|
+
- Every receipt and authorization carries `issuer.strict: true`, and `verify --require-strict` refuses a receipt without it, or a forwarded call without its authorization ([verification.md](verification.md)).
|
|
170
|
+
|
|
171
|
+
The cost is one extra log append per call, and a log outage stops every call. What strict mode does not cover: a fact lookup and a `reconcile` read are reads the gateway makes itself, before the policy decides or on the operator's command, and go out before any log entry; each is on the receipt that follows. The flag is the gateway's own statement, signed with its key: it binds an honest gateway's operator to a mode a verifier can hold them to, and a modified gateway can still claim it. Only a gateway the operator cannot change ([the plan](../README.md#plan)) closes that.
|
|
172
|
+
|
|
155
173
|
**5. Run the gateway.** It speaks MCP on stdin/stdout and logs to stderr only.
|
|
156
174
|
|
|
157
175
|
```bash
|
package/docs/verification.md
CHANGED
|
@@ -24,7 +24,7 @@ node src/cli.ts verify receipts/<id>.json \
|
|
|
24
24
|
--log log.jsonl
|
|
25
25
|
```
|
|
26
26
|
|
|
27
|
-
`--approval-key` is needed for forwarded calls carrying human approvals (not for a refusal), `--log-key` for a remote log, and `--upstream-key` when checking a signed upstream result. `--log` is optional.
|
|
27
|
+
`--approval-key` is needed for forwarded calls carrying human approvals (not for a refusal), `--log-key` for a remote log, and `--upstream-key` when checking a signed upstream result. `--log` is optional. `--require-strict` refuses a receipt that a gateway in [strict mode](usage.md#strict-mode) did not issue, and a forwarded call without its precommitted authorization.
|
|
28
28
|
|
|
29
29
|
Exit code 0 when every check passes, 1 otherwise. Add `--json` for machine-readable output. `--issuer-key`, `--principal-key`, and `--approval-key` can be repeated to accept rotated keys; signatures are matched by keyid. `--gateway-key` is an alias for `--issuer-key`. `--principal-key` may be omitted for SDK receipts, which carry no delegation.
|
|
30
30
|
|
|
@@ -103,12 +103,14 @@ A refused call's `execution` row carries the reason the receipt records, for exa
|
|
|
103
103
|
| authorization log inclusion proof | the authorization statement is a leaf of that tree | an authorization that was never logged |
|
|
104
104
|
| authorization logged before execution | the authorization's leaf precedes the receipt's leaf, at a tree size no larger than the receipt's | evidence written after the side effect, dressed up as before |
|
|
105
105
|
| tree head signature | the tree head was signed by a trusted issuer key | forged log position |
|
|
106
|
+
| strict mode in force | with `--require-strict`: a gateway receipt whose issuer says `strict: true`. It is the gateway's own statement, signed with its key, so it binds the operator to a mode it can be held to; it does not prove the gateway's code | an ordinary receipt presented where strict ones are required |
|
|
107
|
+
| strict: call precommitted before forwarding | with `--require-strict`: a call that was executed, failed, or errored carries its authorization, which the `authorization …` checks then place in the log before the receipt. A reconciliation receipt is a provider read and needs none | a strict claim on a call that went out before any log entry |
|
|
106
108
|
| tree head names the expected log | with `--log-id`: the tree head carries that log id, so a head from another tenant's log on the same server cannot be presented as this one's | a receipt logged to a different log than claimed |
|
|
107
109
|
| tree head matches inclusion proof size | the proof and the tree head describe the same tree | mismatched bundle parts |
|
|
108
110
|
| log inclusion proof | this exact envelope is a leaf of the tree with that root | receipt never logged, or logged then changed |
|
|
109
111
|
| log file root matches tree head | recomputing the root from your copy of the log at that size gives the same value | your log copy and the issuer's history diverge: deletion, reordering, or edit |
|
|
110
112
|
|
|
111
|
-
Approval-bearing forwarded calls add four approval checks. A refused call runs only `approval consistent with execution`, so it verifies without approval keys, with a valid approval or with the invalid approval that caused its refusal. Gateway receipts otherwise run seventeen checks, eighteen with a log file, one more (`execution result digest`) when the call was executed or failed, and five more when the tool was committed before it ran (`precommit` in the gateway config). SDK receipts run fewer, because there is no delegation to check, and the report says so on the `principal is claimed` line. A receipt issued to a sub-agent under a delegation chain runs one more, `delegation chain to the principal`.
|
|
113
|
+
Approval-bearing forwarded calls add four approval checks. A refused call runs only `approval consistent with execution`, so it verifies without approval keys, with a valid approval or with the invalid approval that caused its refusal. Gateway receipts otherwise run seventeen checks, eighteen with a log file, one more (`execution result digest`) when the call was executed or failed, and five more when the tool was committed before it ran (`precommit` in the gateway config). `--require-strict` adds two. SDK receipts run fewer, because there is no delegation to check, and the report says so on the `principal is claimed` line. A receipt issued to a sub-agent under a delegation chain runs one more, `delegation chain to the principal`.
|
|
112
114
|
|
|
113
115
|
Financial receipts add `operation …` checks and `authorization names this operation` for the durable id (absent under a private capture rule; the provider key then links the receipts), provider key, precommitted lookup, and budget. Reconciliation receipts embed their original receipt or authorization and run its checks under `reconciliation original …`, reject nested reconciliation evidence, preserve identity at `reconciliation links the original operation`, and check the configured mapping and provider record at `reconciliation lookup matches authorization`, `reconciliation lookup args match request`, and `reconciliation provider status`. The provider's terminal state must agree with the financial outcome and its record must echo the idempotency key. `reconciliation logged after original` checks ordering. These observations do not independently prove settlement without trusting the gateway and provider; private provider results verify as committed until disclosed or decrypted. See [financial operations](financial-operations.md).
|
|
114
116
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent-custody/receipts",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.0",
|
|
4
4
|
"mcpName": "io.github.svayatta/agent-custody",
|
|
5
5
|
"description": "Chain of custody for AI agents: signed, independently verifiable receipts for tool calls. MCP gateway + Cedar policy + Merkle transparency log",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -84,6 +84,7 @@
|
|
|
84
84
|
"langchain": "1.5.15",
|
|
85
85
|
"tsx": "^4.23.13",
|
|
86
86
|
"typescript": "^7.0.2",
|
|
87
|
+
"viem": "2.57.4",
|
|
87
88
|
"vitest": "^5.0.0",
|
|
88
89
|
"xml-crypto": "^6.1.2"
|
|
89
90
|
},
|
|
@@ -92,7 +93,8 @@
|
|
|
92
93
|
"@node-saml/node-saml": ">=5.1.0",
|
|
93
94
|
"@openai/agents": ">=0.1.0",
|
|
94
95
|
"ai": ">=5.0.0",
|
|
95
|
-
"pg": ">=8"
|
|
96
|
+
"pg": ">=8",
|
|
97
|
+
"viem": ">=2.30.0"
|
|
96
98
|
},
|
|
97
99
|
"peerDependenciesMeta": {
|
|
98
100
|
"@langchain/core": {
|
|
@@ -109,6 +111,9 @@
|
|
|
109
111
|
},
|
|
110
112
|
"pg": {
|
|
111
113
|
"optional": true
|
|
114
|
+
},
|
|
115
|
+
"viem": {
|
|
116
|
+
"optional": true
|
|
112
117
|
}
|
|
113
118
|
}
|
|
114
119
|
}
|