@agent-custody/receipts 0.16.4 → 0.16.5
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/a2a.js +1 -1
- package/dist/deny-report.js +6 -2
- package/dist/log-admin.d.ts +2 -0
- package/dist/log-admin.js +13 -3
- package/dist/log-store.js +2 -0
- package/dist/portal.js +28 -4
- package/docs/github-action.md +2 -2
- package/docs/usage.md +1 -1
- package/package.json +1 -1
package/dist/a2a.js
CHANGED
|
@@ -371,7 +371,7 @@ export async function serveA2a(host, cfg, opts) {
|
|
|
371
371
|
handler(req, res).catch((e) => {
|
|
372
372
|
log(`agent-custody gateway (a2a): ${e instanceof Error ? e.message : String(e)}`);
|
|
373
373
|
if (!res.headersSent)
|
|
374
|
-
sendBody(res, 500, "application/json", JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message:
|
|
374
|
+
sendBody(res, 500, "application/json", JSON.stringify({ jsonrpc: "2.0", id: null, error: { code: -32603, message: "internal error" } }));
|
|
375
375
|
else
|
|
376
376
|
res.end();
|
|
377
377
|
});
|
package/dist/deny-report.js
CHANGED
|
@@ -31,12 +31,14 @@ export function denyReport(configFile) {
|
|
|
31
31
|
const reasons = policyText === null ? [] : policyReasons(policyText);
|
|
32
32
|
const currentDigest = policyText === null ? null : policyDigest(policyText);
|
|
33
33
|
const report = { configFile, receiptsDir: cfg.receiptsDir, observe: cfg.mode === "observe", verified: 0, wouldDeny: [], denied: [], unverified: [] };
|
|
34
|
+
const leafOf = new Map();
|
|
34
35
|
const files = existsSync(cfg.receiptsDir)
|
|
35
36
|
? readdirSync(cfg.receiptsDir, { withFileTypes: true }).filter((e) => (e.isFile() || e.isSymbolicLink()) && e.name.endsWith(".json") && !e.name.endsWith(".authorization.json")).map((e) => e.name).sort()
|
|
36
37
|
: [];
|
|
37
38
|
for (const file of files) {
|
|
38
39
|
try {
|
|
39
|
-
const
|
|
40
|
+
const bundle = JSON.parse(readFileSync(join(cfg.receiptsDir, file), "utf8"));
|
|
41
|
+
const result = verifyBundle(bundle, opts);
|
|
40
42
|
if (!result.ok || !result.statement) {
|
|
41
43
|
const failed = result.checks.filter((c) => !c.ok).map((c) => c.name);
|
|
42
44
|
throw new Error(`failed: ${failed.join("; ")}`);
|
|
@@ -58,13 +60,15 @@ export function denyReport(configFile) {
|
|
|
58
60
|
reasons: known ? policyIds.map((id) => reasons[Number(id.replace(/^policy/, ""))]).filter((r) => typeof r === "string") : [],
|
|
59
61
|
rules: known ? policyIds.map((id) => rules[Number(id.replace(/^policy/, ""))]).filter((r) => typeof r === "string").map((r) => r.replace(/\s+/g, " ").replace(/;$/, "").replace(ANNOTATIONS, "").trim()) : [],
|
|
60
62
|
};
|
|
63
|
+
leafOf.set(call, bundle.inclusion.leafIndex);
|
|
61
64
|
(p.policy.enforced === false ? report.wouldDeny : report.denied).push(call);
|
|
62
65
|
}
|
|
63
66
|
catch (e) {
|
|
64
67
|
report.unverified.push({ file, reason: e instanceof Error ? e.message : String(e) });
|
|
65
68
|
}
|
|
66
69
|
}
|
|
67
|
-
|
|
70
|
+
// Calls in the same millisecond share a timestamp, so the log's leaf index, the order they were recorded, breaks the tie.
|
|
71
|
+
const byTime = (a, b) => (a.timestamp < b.timestamp ? -1 : a.timestamp > b.timestamp ? 1 : leafOf.get(a) - leafOf.get(b));
|
|
68
72
|
report.wouldDeny.sort(byTime);
|
|
69
73
|
report.denied.sort(byTime);
|
|
70
74
|
return report;
|
package/dist/log-admin.d.ts
CHANGED
|
@@ -51,6 +51,8 @@ export declare function registrations(tenancy: PostgresTenancy, portal: PortalSt
|
|
|
51
51
|
totalLeaves: number;
|
|
52
52
|
};
|
|
53
53
|
}>;
|
|
54
|
+
/** One CSV cell: RFC 4180 quoting, and a text cell a spreadsheet would read as a formula gets a leading `'`. */
|
|
55
|
+
export declare function csvCell(v: unknown): string;
|
|
54
56
|
export interface RegistrationRow {
|
|
55
57
|
tenant: string;
|
|
56
58
|
logId: string;
|
package/dist/log-admin.js
CHANGED
|
@@ -74,6 +74,15 @@ export async function registrations(tenancy, portal, month) {
|
|
|
74
74
|
});
|
|
75
75
|
return { month: usage.month, rows, totals: { tenants: rows.length, registered: rows.filter((r) => r.email).length, appends: rows.reduce((n, r) => n + r.appends, 0), totalLeaves: rows.reduce((n, r) => n + r.totalLeaves, 0) } };
|
|
76
76
|
}
|
|
77
|
+
/** One CSV cell: RFC 4180 quoting, and a text cell a spreadsheet would read as a formula gets a leading `'`. */
|
|
78
|
+
export function csvCell(v) {
|
|
79
|
+
if (v === null || v === undefined)
|
|
80
|
+
return "";
|
|
81
|
+
let t = String(v);
|
|
82
|
+
if (typeof v === "string" && /^[=+\-@\t\r]/.test(t))
|
|
83
|
+
t = `'${t}`;
|
|
84
|
+
return /[",\r\n]/.test(t) ? `"${t.replace(/"/g, '""')}"` : t;
|
|
85
|
+
}
|
|
77
86
|
export function adminRoutes(opts) {
|
|
78
87
|
// Five wrong tokens from one address, then one more a minute: enough to stop guessing, not enough to lock out a typo.
|
|
79
88
|
const failures = new RateLimiter({ perSecond: 1 / 60, burst: 5 });
|
|
@@ -130,7 +139,7 @@ export function adminRoutes(opts) {
|
|
|
130
139
|
}
|
|
131
140
|
else if (req.method === "GET" && parts.length === 2 && parts[1] === "usage.csv") {
|
|
132
141
|
const u = await t.usage(month);
|
|
133
|
-
const csv = ["month,tenant,log_id,plan,quota,appends,total_leaves,live_tokens,disabled", ...u.tenants.map((x) => [u.month, x.id, x.logId, x.plan, x.quota ?? "", x.appends, x.totalLeaves, x.liveTokens, x.disabled].join(","))].join("\n") + "\n";
|
|
142
|
+
const csv = ["month,tenant,log_id,plan,quota,appends,total_leaves,live_tokens,disabled", ...u.tenants.map((x) => [u.month, x.id, x.logId, x.plan, x.quota ?? "", x.appends, x.totalLeaves, x.liveTokens, x.disabled].map(csvCell).join(","))].join("\n") + "\n";
|
|
134
143
|
res.writeHead(200, { "content-type": "text/csv; charset=utf-8", "content-disposition": `attachment; filename="agent-custody-usage-${u.month}.csv"`, "cache-control": "no-store" });
|
|
135
144
|
res.end(csv);
|
|
136
145
|
}
|
|
@@ -139,8 +148,7 @@ export function adminRoutes(opts) {
|
|
|
139
148
|
}
|
|
140
149
|
else if (req.method === "GET" && parts.length === 2 && parts[1] === "registrations.csv") {
|
|
141
150
|
const r = await registrations(t, opts.portal, month);
|
|
142
|
-
const
|
|
143
|
-
const csv = ["month,tenant,log_id,plan,email,name,company,role,phone,telegram,registered_at,billing,appends,quota,total_leaves,live_tokens,disabled", ...r.rows.map((x) => [r.month, x.tenant, x.logId, x.plan, x.email, x.name, x.company, x.role, x.phone, x.telegram, x.registeredAt, x.billing, x.appends, x.quota, x.totalLeaves, x.liveTokens, x.disabled].map(cell).join(","))].join("\n") + "\n";
|
|
151
|
+
const csv = ["month,tenant,log_id,plan,email,name,company,role,phone,telegram,registered_at,billing,appends,quota,total_leaves,live_tokens,disabled", ...r.rows.map((x) => [r.month, x.tenant, x.logId, x.plan, x.email, x.name, x.company, x.role, x.phone, x.telegram, x.registeredAt, x.billing, x.appends, x.quota, x.totalLeaves, x.liveTokens, x.disabled].map(csvCell).join(","))].join("\n") + "\n";
|
|
144
152
|
res.writeHead(200, { "content-type": "text/csv; charset=utf-8", "content-disposition": `attachment; filename="agent-custody-registrations-${r.month}.csv"`, "cache-control": "no-store" });
|
|
145
153
|
res.end(csv);
|
|
146
154
|
}
|
|
@@ -162,6 +170,8 @@ export function adminRoutes(opts) {
|
|
|
162
170
|
const b = await body();
|
|
163
171
|
if (typeof b.id !== "string" || !/^[A-Za-z0-9_.-]+$/.test(b.id))
|
|
164
172
|
return json(400, { error: "id must be a plain identifier" }), true;
|
|
173
|
+
if (b.logId !== undefined && b.logId !== "" && (typeof b.logId !== "string" || !/^[A-Za-z0-9_.-]+$/.test(b.logId)))
|
|
174
|
+
return json(400, { error: "logId must be a plain identifier" }), true;
|
|
165
175
|
json(200, await t.addTenant(b.id, typeof b.logId === "string" && b.logId ? b.logId : b.id, actor));
|
|
166
176
|
}
|
|
167
177
|
else if (req.method === "POST" && parts.length === 4 && parts[1] === "tenants" && parts[3] === "plan") {
|
package/dist/log-store.js
CHANGED
|
@@ -261,6 +261,8 @@ export class PostgresTenancy {
|
|
|
261
261
|
async addTenant(id, logId = id, by) {
|
|
262
262
|
if (!/^[A-Za-z0-9_.-]+$/.test(id))
|
|
263
263
|
throw new Error(`tenant id must be a plain identifier; got "${id}"`);
|
|
264
|
+
if (!/^[A-Za-z0-9_.-]+$/.test(logId))
|
|
265
|
+
throw new Error(`log id must be a plain identifier; got "${logId}"`);
|
|
264
266
|
await this.init();
|
|
265
267
|
const rows = (await this.client.query(`INSERT INTO ${this.prefix}tenants (id, log_id) VALUES ($1, $2) ON CONFLICT (id) DO UPDATE SET log_id = EXCLUDED.log_id RETURNING id, log_id, plan, created_at, disabled_at`, [id, logId])).rows;
|
|
266
268
|
this.tenantCache.delete(id);
|
package/dist/portal.js
CHANGED
|
@@ -26,6 +26,14 @@ export class UnverifiedAccountError extends Error {
|
|
|
26
26
|
/** A single sign-on identity that the tenant's rules refuse: another domain, or an account in another tenant. */
|
|
27
27
|
export class SsoRefusedError extends Error {
|
|
28
28
|
}
|
|
29
|
+
/** A request the client got wrong: answered with its status and message. Any other error is answered with a plain 500. */
|
|
30
|
+
class ClientError extends Error {
|
|
31
|
+
status;
|
|
32
|
+
constructor(status, message) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.status = status;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
29
37
|
const ident = (s) => {
|
|
30
38
|
if (!/^[a-z_][a-z0-9_]*$/.test(s))
|
|
31
39
|
throw new Error(`prefix must be a plain identifier; got "${s}"`);
|
|
@@ -601,15 +609,22 @@ export function portalHandler(o) {
|
|
|
601
609
|
for await (const chunk of req) {
|
|
602
610
|
text += chunk;
|
|
603
611
|
if (text.length > 65_536)
|
|
604
|
-
throw new
|
|
612
|
+
throw new ClientError(413, "body too large");
|
|
605
613
|
}
|
|
606
614
|
return text;
|
|
607
615
|
};
|
|
608
616
|
const jsonBody = async () => {
|
|
609
617
|
if (!(req.headers["content-type"] ?? "").startsWith("application/json"))
|
|
610
|
-
throw new
|
|
618
|
+
throw new ClientError(400, "expected a JSON body");
|
|
611
619
|
const t = await rawBody();
|
|
612
|
-
|
|
620
|
+
if (!t)
|
|
621
|
+
return {};
|
|
622
|
+
try {
|
|
623
|
+
return JSON.parse(t);
|
|
624
|
+
}
|
|
625
|
+
catch {
|
|
626
|
+
throw new ClientError(400, "the body is not valid JSON");
|
|
627
|
+
}
|
|
613
628
|
};
|
|
614
629
|
try {
|
|
615
630
|
if (req.method === "GET" && url.pathname === "/health")
|
|
@@ -1200,8 +1215,17 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
|
|
|
1200
1215
|
return json(404, { error: "not found" });
|
|
1201
1216
|
}
|
|
1202
1217
|
catch (e) {
|
|
1218
|
+
if (e instanceof ClientError) {
|
|
1219
|
+
if (!res.headersSent)
|
|
1220
|
+
json(e.status, { error: e.message });
|
|
1221
|
+
return;
|
|
1222
|
+
}
|
|
1223
|
+
// the detail can name a table, a query, or another service: it goes to the operator, not to the browser
|
|
1224
|
+
log(`agent-custody portal: ${req.method} ${url.pathname} failed: ${e instanceof Error ? (e.stack ?? e.message) : String(e)}`);
|
|
1203
1225
|
if (!res.headersSent)
|
|
1204
|
-
json(500, { error:
|
|
1226
|
+
json(500, { error: "internal error" });
|
|
1227
|
+
else
|
|
1228
|
+
res.end();
|
|
1205
1229
|
}
|
|
1206
1230
|
};
|
|
1207
1231
|
}
|
package/docs/github-action.md
CHANGED
|
@@ -20,7 +20,7 @@ jobs:
|
|
|
20
20
|
runs-on: ubuntu-latest
|
|
21
21
|
steps:
|
|
22
22
|
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7
|
|
23
|
-
- uses: svayatta/agent-custody@<commit sha of the release> # 0.16.
|
|
23
|
+
- uses: svayatta/agent-custody@<commit sha of the release> # 0.16.5
|
|
24
24
|
with:
|
|
25
25
|
path: .custody/receipts
|
|
26
26
|
issuer-key: .custody/keys/agent.pub
|
|
@@ -37,7 +37,7 @@ Pin the action to the commit of a release, as you pin every other action. A movi
|
|
|
37
37
|
| `principal-key` | the public key files of the principals whose grants a gateway receipt carries, one path on each line; SDK and Claude Code hook receipts need none | |
|
|
38
38
|
| `log-url` | the URL of the log; the action fetches the log key from it (`verify --log-url`) | |
|
|
39
39
|
| `log-id` | the id that every tree head must name (`verify --log-id`) | |
|
|
40
|
-
| `version` | the `@agent-custody/receipts` version that `npx` runs | `0.16.
|
|
40
|
+
| `version` | the `@agent-custody/receipts` version that `npx` runs | `0.16.5` |
|
|
41
41
|
| `github-token` | a token that can write pull request comments; an empty value writes the job summary only | `github.token` |
|
|
42
42
|
| `comment-author` | the login of the account that `github-token` posts as; the action edits only a comment from this account | `github-actions[bot]` |
|
|
43
43
|
|
package/docs/usage.md
CHANGED
|
@@ -123,7 +123,7 @@ At startup the gateway fetches the agent's card from `<url>/.well-known/agent-ca
|
|
|
123
123
|
"log": { "url": "https://log.example.com/", "tokenEnv": "AGENT_CUSTODY_LOG_TOKEN" }
|
|
124
124
|
```
|
|
125
125
|
|
|
126
|
-
Exactly one of the two. The bearer token comes from the named environment variable, never from the file, and a missing variable fails at startup. Add `"hashOnly": true` for any log run by someone else: the gateway then sends only the leaf hash, sha256 of the receipt envelope with the RFC 6962 prefix, so the log commits to the receipt without ever holding it, and the receipts with their arguments and results stay in `receiptsDir`. The verifier does not change; it hashes the envelope itself. A log that serves several tenants is reached at `<url>/t/<tenant>/`, and each of its tree heads names its log, which a verifier checks with `--log-id`. With a remote log the tree head in each receipt is signed by the log's key, and a verifier must be given that key with `--log-key`. The gateway does not take the log's answer on trust either: the tree head in every append's answer must verify against the log's keys, name the expected log, match the proof's size, and the inclusion proof must place that very leaf under the signed root, all before a pre-committed call is forwarded and before any receipt is handed out; an answer that fails any of it is a refusal. `"keys": ["keys/log.pub"]` pins the log's public keys, `"logId"` the id its heads must carry; without `keys` the log's key document at `/.well-known/agent-custody-log.json` is fetched from the log itself once, on the first append, and pinned. That catches a log that turns dishonest later, not one that is dishonest from the start, so a gateway config with `precommit` and a remote log must list `keys`. When the log rotates its key, add the new public key to `keys`; a gateway that fetched the keys needs a restart. An append that gets no answer within `timeoutMs` (default 10000) counts as unreachable and is retried like a server error, so a log that accepts connections and never answers cannot hold a call forever. If the log does not take a receipt, the gateway keeps the signed receipt in `receipts/outbox/<receiptId>.json` and returns the real outcome of the call to the agent, with the receipt id and `_meta["agent-custody/log-pending"]: true`. The gateway appends the outbox at startup and every 30 seconds, and writes `receipts/<receiptId>.json` when the log takes the receipt. Until then no bundle exists, so no receipt that was never logged is handed out. The table [below](#when-the-log-fails) gives each case. For a tool named in `precommit` the order is reversed, below, and the action never happens. A fact lookup is different: it runs before the policy decides, because the policy decides on it, and only once the intercepted tool is in the grant's scope, so a fact tool must be a read. Naming a fact tool in `precommit` is refused at startup; `"*"` covers the tools the agent calls, not the gateway's own lookups. Every lookup is on the receipt with its arguments. The reference log server is `node src/cli.ts log --file log.jsonl --key keys/log.key --port 8787 --token-env AGENT_CUSTODY_LOG_TOKEN [--log-id <id>] [--tenants tenants.json]`. It serves `POST /append` with `{leaf}` or `{leafHash}` (token required when one is configured), `GET /root?size=N`, `GET /consistency?old=M&new=N`, and `GET /head`; [verification.md](verification.md) says what each proves. `--log-id` writes that id into every tree head. `--tenants` names a JSON file, `{ "acme": { "file": "acme.jsonl", "tokenEnv": "ACME_TOKEN", "logId": "acme-eu" } }`, and each tenant is its own log at `/t/acme/…` with its own token and id; the default log stays at the root paths. With `--hash-only` the server refuses `{leaf}` at append and accepts only `{leafHash}`, so a log run for other people never receives a receipt regardless of the client's configuration; the hosted deployment sets it. With `--db-env DATABASE_URL` the server keeps its logs in Postgres instead of files, and needs the `pg` package beside it: leaves as hashes in one table keyed by tenant, one writer per tenant enforced with an advisory lock so a second instance is safe, tenants and their tokens in tables of their own with tokens stored only as hashes, and rate limits per token (50 appends a second, burst 100, a 64 KB body cap; a refused append answers 429 with `retry-after`, and the gateway's sink retries a few times). Tenants are managed with `log-admin --db-env DATABASE_URL`: `tenant add <id> [--log-id <id>]`, `token add <tenant> --label <text>` (the token is printed once), `token revoke <tenant> <hash-prefix>`, `tenant disable <id>`, `tenant plan <id> <free|team|enterprise>`, and `import --file log.jsonl [--tenant default]` to bring an existing file log in as hashes. Every tenant is on a plan, `free` unless moved: free allows ten thousand appends a calendar month, team a million, enterprise has no allowance. An append past the allowance is refused with 429, the numbers, and a `retry-after` that reaches the start of next month; the gateway behind it then withholds pre-committed calls and financial operations, so a tenant out of quota never acts on those without evidence. Any other call is forwarded, and its receipt waits in the outbox ([below](#when-the-log-fails)). The tenant's own `GET /t/<name>/usage` reports the plan and quota beside the month's appends. The tenant portal, `agent-custody portal --db-env DATABASE_URL --secret-env PORTAL_SECRET --public-url <log url> [--checkpoints-url <url>] [--portal-url <url>] [--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]`, is the self-serve front of the same tables: a team registers with an email, a password (scrypt), and a tenant id and gets the tenant and its first key shown once with the welcome sheet; the dashboard shows appends against the plan, the tree size and root, the latest checkpoint, the log's URLs, keys, and the audit rows; keys are minted and revoked there, recorded as `portal:<email>`; the export command is on the page; and with the three Stripe variables the team plan is bought through Stripe Checkout, the signed webhook moving the plan (`stripe:<event>` in the audit trail) and the customer portal handling cancellation. Sessions are a signed cookie, `SameSite=Strict`, and every write needs a JSON body. Each member has a role (`owner`, `admin`, `reviewer`, `readonly`), an account can turn on TOTP MFA, and the operator can set up single sign-on through the tenant's own OIDC or SAML identity provider with `log-admin sso set`; the [hosted log reference](https://docs.agent-custody.dev/reference/hosted) lists the routes. SAML needs `@node-saml/node-saml` beside the CLI. The compose file runs it as the `portal` service at `PORTAL_HOST`. The root paths serve the tenant `default`, created on first start with `--log-id`, and `--token-env` still works for it. The key that signs tree heads can live in its own process: `agent-custody signer --key keys/log.key --port 8790 --token-env SIGNER_TOKEN` holds it and answers `POST /sign` with the shared secret and `GET /keys` to anyone; the log server then runs with `--signer-url http://signer:8790/ --signer-token-env SIGNER_TOKEN` instead of `--key`, and the process that faces the internet never holds the key. Either way the log serves its keys at `/.well-known/agent-custody-log.json`, current key first and retired keys (`--retired-key old.pub`) after it, so verifiers fetch and pin them with `verify --log-url` and `audit --log-url` rather than receiving a key file from the operator. With `--checkpoint-dir <dir>` the server publishes a signed checkpoint, every `--checkpoint-every` seconds (default 300), for each log whose tree has grown, and every `--checkpoint-heartbeat` seconds (default 21600, six hours) for a log that has not, so a quiet log's latest checkpoint is never more than six hours old and the monitor can tell quiet from stalled, as `<dir>/<tenant>/<treeSize>.json` and `latest.json`, and with a database also as rows; `GET /checkpoints?since=<size>` and `GET /t/<tenant>/checkpoints` list them. Serve the directory read-only from a second host, so the record of what the log signed does not depend on the log's API being up; a verifier who kept an earlier head audits against a later checkpoint with `audit --older <bundle> --newer <checkpoint> --log-url <url>`. With `--admin-token-env ADMIN_TOKEN` (Postgres only) the server also serves the operator's page at `/admin` and its API under `/admin/`: list and create tenants, mint a token that is shown once beside the tenant's welcome sheet, revoke tokens, disable tenants. Everything under `/admin`, the page included, needs the admin token: the browser asks for it (any user name, the token as the password) and an API client sends it as a bearer; a handful of wrong attempts from one address are throttled for a minute. Every change made there or with `log-admin` is recorded: who (the name entered at the browser prompt and the address, `bearer` for an API client, or the user and host for the command line), what (`tenant.add`, `tenant.disable`, `token.add`, `token.revoke`), which tenant, and the detail, never the token itself; the page shows it under Activity, `GET /admin/audit?tenant=&limit=` and `log-admin audit` list it, and a tenant reads their own rows at `GET /t/<name>/audit` with their token. Nothing else is stored by the page. Behind a reverse proxy, start the server with `--trust-proxy` so those per-address limits key on `X-Forwarded-For` instead of on the proxy's own address, and only there, since the header is otherwise the client's to forge. `--public-url` and `--checkpoints-url` fill the sheet in. The witness closes the last gap: `agent-custody witness --key witness.key --log-url <url> --checkpoints-url <url> --out <dir> [--tenant <name>]...` runs on a machine the log's operator does not control, fetches each watched log's latest checkpoint, verifies it against the log's published keys, proves with the log's consistency proof that it extends the last head the witness signed, and countersigns it into `<dir>/<tenant>/<size>.json` and `latest.json`; a checkpoint that does not extend, or a second history at the same size, gets `ALARM.json` instead. Its key document is `<dir>/.well-known/agent-custody-witness.json`. Serve `<dir>` from the witness's own host; verifiers add `--witness-url` (or `--witness-key`) to `audit`, and the newer head must then carry the witness's signature. Two more things an operator needs. `agent-custody log-check --log-url <url> --checkpoints-url <url> [--witness-url <url>] [--tenant <name>]... [--max-lag <seconds>]` is the outside monitor: it verifies the head against the published keys, that the latest checkpoint verifies and keeps up with the head, that the head extends the checkpoint, and, with a witness, that the witness has countersigned, keeps up, and has raised no alarm; it exits 1 on any failure, so cron or a scheduled workflow on a machine that is not the log's turns it into an alert. `GET /health` on the server is the liveness check for a load balancer. And `GET /admin/usage?month=YYYY-MM`, on the admin page and as `/admin/usage.csv`, is the metering: appends per tenant for the month, leaves in total, live tokens, the numbers any invoice rests on. A tenant needs none of that to leave with their evidence: `agent-custody log-export --log-url <url> --tenant <name> --token-env AGENT_CUSTODY_LOG_TOKEN --out <dir>` fetches, with their own token, every leaf hash (`GET /t/<name>/leaves?since=&limit=`, pages of up to ten thousand), the signed head, the published keys, the signed checkpoints, their own usage (`GET /t/<name>/usage?month=`), and the administrative actions on their tenant (`GET /t/<name>/audit`, into `audit.json`), checks that the head and every checkpoint verify against the keys and that the leaves fetched hash to their roots, and writes `log.jsonl` in the format `verify --log` and `audit --log` read, so the export verifies receipts with no server at all. It exits 1 and says what did not add up if anything does not. Both routes answer only to that tenant's token. [deploy/](../../deploy/README.md) runs the server, the signer, Postgres, and the checkpoints host as containers, and [deploy/witness/](../../deploy/witness/) the witness.
|
|
126
|
+
Exactly one of the two. The bearer token comes from the named environment variable, never from the file, and a missing variable fails at startup. Add `"hashOnly": true` for any log run by someone else: the gateway then sends only the leaf hash, sha256 of the receipt envelope with the RFC 6962 prefix, so the log commits to the receipt without ever holding it, and the receipts with their arguments and results stay in `receiptsDir`. The verifier does not change; it hashes the envelope itself. A log that serves several tenants is reached at `<url>/t/<tenant>/`, and each of its tree heads names its log, which a verifier checks with `--log-id`. With a remote log the tree head in each receipt is signed by the log's key, and a verifier must be given that key with `--log-key`. The gateway does not take the log's answer on trust either: the tree head in every append's answer must verify against the log's keys, name the expected log, match the proof's size, and the inclusion proof must place that very leaf under the signed root, all before a pre-committed call is forwarded and before any receipt is handed out; an answer that fails any of it is a refusal. `"keys": ["keys/log.pub"]` pins the log's public keys, `"logId"` the id its heads must carry; without `keys` the log's key document at `/.well-known/agent-custody-log.json` is fetched from the log itself once, on the first append, and pinned. That catches a log that turns dishonest later, not one that is dishonest from the start, so a gateway config with `precommit` and a remote log must list `keys`. When the log rotates its key, add the new public key to `keys`; a gateway that fetched the keys needs a restart. An append that gets no answer within `timeoutMs` (default 10000) counts as unreachable and is retried like a server error, so a log that accepts connections and never answers cannot hold a call forever. If the log does not take a receipt, the gateway keeps the signed receipt in `receipts/outbox/<receiptId>.json` and returns the real outcome of the call to the agent, with the receipt id and `_meta["agent-custody/log-pending"]: true`. The gateway appends the outbox at startup and every 30 seconds, and writes `receipts/<receiptId>.json` when the log takes the receipt. Until then no bundle exists, so no receipt that was never logged is handed out. The table [below](#when-the-log-fails) gives each case. For a tool named in `precommit` the order is reversed, below, and the action never happens. A fact lookup is different: it runs before the policy decides, because the policy decides on it, and only once the intercepted tool is in the grant's scope, so a fact tool must be a read. Naming a fact tool in `precommit` is refused at startup; `"*"` covers the tools the agent calls, not the gateway's own lookups. Every lookup is on the receipt with its arguments. The reference log server is `node src/cli.ts log --file log.jsonl --key keys/log.key --port 8787 --token-env AGENT_CUSTODY_LOG_TOKEN [--log-id <id>] [--tenants tenants.json]`. It serves `POST /append` with `{leaf}` or `{leafHash}` (token required when one is configured), `GET /root?size=N`, `GET /consistency?old=M&new=N`, and `GET /head`; [verification.md](verification.md) says what each proves. `--log-id` writes that id into every tree head. `--tenants` names a JSON file, `{ "acme": { "file": "acme.jsonl", "tokenEnv": "ACME_TOKEN", "logId": "acme-eu" } }`, and each tenant is its own log at `/t/acme/…` with its own token and id; the default log stays at the root paths. With `--hash-only` the server refuses `{leaf}` at append and accepts only `{leafHash}`, so a log run for other people never receives a receipt regardless of the client's configuration; the hosted deployment sets it. With `--db-env DATABASE_URL` the server keeps its logs in Postgres instead of files, and needs the `pg` package beside it: leaves as hashes in one table keyed by tenant, one writer per tenant enforced with an advisory lock so a second instance is safe, tenants and their tokens in tables of their own with tokens stored only as hashes, and rate limits per token (50 appends a second, burst 100, a 64 KB body cap; a refused append answers 429 with `retry-after`, and the gateway's sink retries a few times). Tenants are managed with `log-admin --db-env DATABASE_URL`: `tenant add <id> [--log-id <id>]` (both plain identifiers: letters, digits, `.`, `_`, `-`), `token add <tenant> --label <text>` (the token is printed once), `token revoke <tenant> <hash-prefix>`, `tenant disable <id>`, `tenant plan <id> <free|team|enterprise>`, and `import --file log.jsonl [--tenant default]` to bring an existing file log in as hashes. Every tenant is on a plan, `free` unless moved: free allows ten thousand appends a calendar month, team a million, enterprise has no allowance. An append past the allowance is refused with 429, the numbers, and a `retry-after` that reaches the start of next month; the gateway behind it then withholds pre-committed calls and financial operations, so a tenant out of quota never acts on those without evidence. Any other call is forwarded, and its receipt waits in the outbox ([below](#when-the-log-fails)). The tenant's own `GET /t/<name>/usage` reports the plan and quota beside the month's appends. The tenant portal, `agent-custody portal --db-env DATABASE_URL --secret-env PORTAL_SECRET --public-url <log url> [--checkpoints-url <url>] [--portal-url <url>] [--stripe-key-env NAME --stripe-webhook-env NAME --stripe-price-team <price id>] [--trust-proxy]`, is the self-serve front of the same tables: a team registers with an email, a password (scrypt), and a tenant id and gets the tenant and its first key shown once with the welcome sheet; the dashboard shows appends against the plan, the tree size and root, the latest checkpoint, the log's URLs, keys, and the audit rows; keys are minted and revoked there, recorded as `portal:<email>`; the export command is on the page; and with the three Stripe variables the team plan is bought through Stripe Checkout, the signed webhook moving the plan (`stripe:<event>` in the audit trail) and the customer portal handling cancellation. Sessions are a signed cookie, `SameSite=Strict`, and every write needs a JSON body: one over 64 KB is answered 413, one that is not JSON 400, and any other failure a plain 500 with the detail in the portal's log, never in the answer. Each member has a role (`owner`, `admin`, `reviewer`, `readonly`), an account can turn on TOTP MFA, and the operator can set up single sign-on through the tenant's own OIDC or SAML identity provider with `log-admin sso set`; the [hosted log reference](https://docs.agent-custody.dev/reference/hosted) lists the routes. SAML needs `@node-saml/node-saml` beside the CLI. The compose file runs it as the `portal` service at `PORTAL_HOST`. The root paths serve the tenant `default`, created on first start with `--log-id`, and `--token-env` still works for it. The key that signs tree heads can live in its own process: `agent-custody signer --key keys/log.key --port 8790 --token-env SIGNER_TOKEN` holds it and answers `POST /sign` with the shared secret and `GET /keys` to anyone; the log server then runs with `--signer-url http://signer:8790/ --signer-token-env SIGNER_TOKEN` instead of `--key`, and the process that faces the internet never holds the key. Either way the log serves its keys at `/.well-known/agent-custody-log.json`, current key first and retired keys (`--retired-key old.pub`) after it, so verifiers fetch and pin them with `verify --log-url` and `audit --log-url` rather than receiving a key file from the operator. With `--checkpoint-dir <dir>` the server publishes a signed checkpoint, every `--checkpoint-every` seconds (default 300), for each log whose tree has grown, and every `--checkpoint-heartbeat` seconds (default 21600, six hours) for a log that has not, so a quiet log's latest checkpoint is never more than six hours old and the monitor can tell quiet from stalled, as `<dir>/<tenant>/<treeSize>.json` and `latest.json`, and with a database also as rows; `GET /checkpoints?since=<size>` and `GET /t/<tenant>/checkpoints` list them. Serve the directory read-only from a second host, so the record of what the log signed does not depend on the log's API being up; a verifier who kept an earlier head audits against a later checkpoint with `audit --older <bundle> --newer <checkpoint> --log-url <url>`. With `--admin-token-env ADMIN_TOKEN` (Postgres only) the server also serves the operator's page at `/admin` and its API under `/admin/`: list and create tenants, mint a token that is shown once beside the tenant's welcome sheet, revoke tokens, disable tenants. Everything under `/admin`, the page included, needs the admin token: the browser asks for it (any user name, the token as the password) and an API client sends it as a bearer; a handful of wrong attempts from one address are throttled for a minute. Every change made there or with `log-admin` is recorded: who (the name entered at the browser prompt and the address, `bearer` for an API client, or the user and host for the command line), what (`tenant.add`, `tenant.disable`, `token.add`, `token.revoke`), which tenant, and the detail, never the token itself; the page shows it under Activity, `GET /admin/audit?tenant=&limit=` and `log-admin audit` list it, and a tenant reads their own rows at `GET /t/<name>/audit` with their token. Nothing else is stored by the page. Behind a reverse proxy, start the server with `--trust-proxy` so those per-address limits key on `X-Forwarded-For` instead of on the proxy's own address, and only there, since the header is otherwise the client's to forge. `--public-url` and `--checkpoints-url` fill the sheet in. The witness closes the last gap: `agent-custody witness --key witness.key --log-url <url> --checkpoints-url <url> --out <dir> [--tenant <name>]...` runs on a machine the log's operator does not control, fetches each watched log's latest checkpoint, verifies it against the log's published keys, proves with the log's consistency proof that it extends the last head the witness signed, and countersigns it into `<dir>/<tenant>/<size>.json` and `latest.json`; a checkpoint that does not extend, or a second history at the same size, gets `ALARM.json` instead. Its key document is `<dir>/.well-known/agent-custody-witness.json`. Serve `<dir>` from the witness's own host; verifiers add `--witness-url` (or `--witness-key`) to `audit`, and the newer head must then carry the witness's signature. Two more things an operator needs. `agent-custody log-check --log-url <url> --checkpoints-url <url> [--witness-url <url>] [--tenant <name>]... [--max-lag <seconds>]` is the outside monitor: it verifies the head against the published keys, that the latest checkpoint verifies and keeps up with the head, that the head extends the checkpoint, and, with a witness, that the witness has countersigned, keeps up, and has raised no alarm; it exits 1 on any failure, so cron or a scheduled workflow on a machine that is not the log's turns it into an alert. `GET /health` on the server is the liveness check for a load balancer. And `GET /admin/usage?month=YYYY-MM`, on the admin page and as `/admin/usage.csv`, is the metering: appends per tenant for the month, leaves in total, live tokens, the numbers any invoice rests on. A tenant needs none of that to leave with their evidence: `agent-custody log-export --log-url <url> --tenant <name> --token-env AGENT_CUSTODY_LOG_TOKEN --out <dir>` fetches, with their own token, every leaf hash (`GET /t/<name>/leaves?since=&limit=`, pages of up to ten thousand), the signed head, the published keys, the signed checkpoints, their own usage (`GET /t/<name>/usage?month=`), and the administrative actions on their tenant (`GET /t/<name>/audit`, into `audit.json`), checks that the head and every checkpoint verify against the keys and that the leaves fetched hash to their roots, and writes `log.jsonl` in the format `verify --log` and `audit --log` read, so the export verifies receipts with no server at all. It exits 1 and says what did not add up if anything does not. Both routes answer only to that tenant's token. [deploy/](../../deploy/README.md) runs the server, the signer, Postgres, and the checkpoints host as containers, and [deploy/witness/](../../deploy/witness/) the witness.
|
|
127
127
|
|
|
128
128
|
`otel`, optional in both the gateway and SDK configs, sends every receipt to the collector you already run as one span over OTLP/HTTP, after the receipt is issued: `"otel": { "url": "http://localhost:4318", "headersEnv": { "x-api-key": "OTEL_KEY" }, "serviceName": "support-agents" }`. The span's trace id is the receipt id, its attributes carry the tool, agent, principal, execution status, policy decision, and log position, and its status is an error only when the upstream failed or errored, since a denial is the policy working. A door receipt records an inbound request, so its span kind is `SERVER`; every other issuer's span is `CLIENT`. Export is best effort: a collector that is down or refuses costs a line on stderr, never a receipt. Tutorial 18 shows it against a stand-in collector.
|
|
129
129
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent-custody/receipts",
|
|
3
|
-
"version": "0.16.
|
|
3
|
+
"version": "0.16.5",
|
|
4
4
|
"mcpName": "io.github.svayatta/agent-custody",
|
|
5
5
|
"description": "Proof of what your AI agents did. Give your agents real power, without losing control of them: signed, verifiable receipts for tool calls, an MCP gateway with Cedar or Rego policy, and a Merkle transparency log.",
|
|
6
6
|
"license": "Apache-2.0",
|