@agent-custody/receipts 0.9.0 → 0.10.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 +5 -3
- package/dist/check.js +1 -1
- package/dist/cli.js +5 -3
- package/dist/config.d.ts +1 -0
- package/dist/config.js +3 -0
- package/dist/console-page.js +3 -3
- package/dist/console.js +2 -1
- package/dist/gateway-http.js +1 -1
- package/dist/gateway.d.ts +14 -0
- package/dist/gateway.js +142 -16
- package/dist/issue.d.ts +31 -1
- package/dist/issue.js +261 -10
- package/dist/policy.d.ts +2 -0
- package/dist/policy.js +5 -0
- package/dist/portal.js +1 -0
- package/dist/simulate.d.ts +7 -1
- package/dist/simulate.js +27 -2
- package/dist/verify.js +4 -2
- package/docs/codex-recovery.md +1 -1
- package/docs/configuration.md +3 -1
- package/docs/console.md +2 -3
- package/docs/policies.md +3 -1
- package/docs/usage.md +18 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -10,7 +10,7 @@ Two producers, one receipt format, one verifier.
|
|
|
10
10
|
Anyone holding the public keys can verify a receipt offline. The agent is not trusted. The layer around it is, and the receipt says exactly how far that trust extends, starting with who issued it. What the receipt file carries of a call is a choice per tool: a field can be withheld as a commitment or encrypted under your key, and the verifier recomputes the digests when it is shown the values.
|
|
11
11
|
|
|
12
12
|
- [Reference](https://docs.agent-custody.dev/reference/): every function, endpoint, MCP tool, and command with its request and response
|
|
13
|
-
- [Tutorials](docs/tutorials.md): thirty-
|
|
13
|
+
- [Tutorials](docs/tutorials.md): thirty-two runnable examples, one per aspect of the code, all executed by the test suite
|
|
14
14
|
- [Financial operations](docs/financial-operations.md): durable operation ids, provider idempotency keys, atomic daily budget reservations, and reconciliation receipts for uncertain outcomes
|
|
15
15
|
- [The gateway console](docs/console.md): an admin service for the person who runs a gateway: config, tools, receipts with a verdict each, a policy editor that replays recorded calls before it saves, grant revocation, and an audit trail
|
|
16
16
|
- [Configuring the gateway](docs/configuration.md): who may use which tools and where the tools live, a worked example with two agents, the Docker image, and `agent-custody check` to validate a config before it starts
|
|
@@ -189,7 +189,7 @@ Every field carries a provenance label. This is the design decision that matters
|
|
|
189
189
|
bun install # from the repository root, once for the workspace
|
|
190
190
|
cd packages/receipts
|
|
191
191
|
node scripts/demo.ts # gateway: keys, grant, policy, four tool calls, verification, a tampering attempt; then the SDK wrapping the same tool
|
|
192
|
-
node examples/01-keys-and-signing.ts # first of thirty-
|
|
192
|
+
node examples/01-keys-and-signing.ts # first of thirty-two step-by-step examples, see docs/tutorials.md
|
|
193
193
|
bun run test # this package; `bun run test` at the root runs every package
|
|
194
194
|
```
|
|
195
195
|
|
|
@@ -276,7 +276,7 @@ src/retention.ts pruning the log: leaves become their hashes, bundles are remo
|
|
|
276
276
|
src/index.ts the package's public surface; adapters are exported on ./sdk/<framework> subpaths
|
|
277
277
|
tsconfig.build.json emits dist/ (JavaScript plus declarations) for consumers; the repo itself runs the .ts directly
|
|
278
278
|
scripts/ fake Stripe upstream (signs its results with --key), a second fake upstream, fixture builders for gateway and SDK, the replay builder (`replay.ts`: example 27 and state example 07 as a folder of receipts and public keys anyone can verify with the published packages), demo
|
|
279
|
-
examples/ thirty-
|
|
279
|
+
examples/ thirty-two runnable tutorials, plus examples/languages/: Python, Go, Java, and Rust clients of the sidecar, run by the test suite, one per aspect; each is run by the test suite
|
|
280
280
|
test/ unit tests per module, end-to-end gateway test, SDK and hook tests,
|
|
281
281
|
adapter tests against the real packages, and a test that runs every policy in docs/policies.md
|
|
282
282
|
docs/ tutorials, usage (gateway), codex-recovery (live demo), approvals, sdk, policies, verification
|
|
@@ -288,6 +288,7 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
|
|
|
288
288
|
|
|
289
289
|
**Done**
|
|
290
290
|
|
|
291
|
+
- Policy reload: the gateway re-reads `policy.cedar` whenever it changes and applies it from the next call, with no restart and no dropped session; a policy that does not parse is refused and the one in force stays, and every change or refusal is recorded in `receipts/policy-reloads.jsonl` ([usage](docs/usage.md)).
|
|
291
292
|
- Live Codex support recovery demo: model-selected MCP calls, incorrect CRM memory, a reviewed recovery plan, simulated credit compensation, and verified evidence; [guide](docs/codex-recovery.md), with offline regression coverage.
|
|
292
293
|
- Payload-bound human approvals: short-lived signatures over the principal, agent, tool, full arguments, amount, currency, and beneficiary; configurable one- or two-key thresholds, enforced even in observe mode, a configurable lifetime cap, persistent atomic single-use consumption before forwarding, and independent approval-key verification. [Guide](docs/approvals.md), tutorial 30.
|
|
293
294
|
- Gateway: MCP proxy, signed delegation, gateway-fetched facts, Cedar policy, denial receipts, Merkle log, offline verifier.
|
|
@@ -329,6 +330,7 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
|
|
|
329
330
|
- Private evidence: per-tool capture rules, applied by the issuer to the whole statement so nothing outside a fixed structural list is in clear under a private rule; withheld values as salted commitments whose salts never enter the receipt, encrypted under the customer's key, revealed and recomputed by the verifier; the commitments do not confirm a guess of a withheld value. A human approval envelope carries the action fields and an unsalted argument digest, so a private rule withholds it as a commitment; the [privacy limits](docs/approvals.md#privacy-limits) apply.
|
|
330
331
|
- Enterprise identity for the hosted portal: member roles (`owner`, `admin`, `reviewer`, `readonly`) with invites, TOTP MFA with single-use codes and an operator reset (`log-admin user mfa-reset`), and single sign-on per tenant through the tenant's own IdP, OIDC or SAML 2.0, set by the operator (`log-admin sso set`), with an enforce mode that closes the password, GitHub, and Google paths to members. Revoking an agent's authority mid-session already shipped (`agent-custody revoke`, example 27); example 31 shows the enterprise sign-in and the roles.
|
|
331
332
|
- The [state review console](../state/README.md#explain-one-action): search receipts by transaction, customer, agent or time, read the ten answers, and hand over a portable HTML/JSON case whose signatures, authorizations and inclusion proofs can be verified offline.
|
|
333
|
+
- A log outage after an ordinary call (issue #149): the signed receipt waits in `receipts/outbox/` and the gateway appends it when the log is back, the agent gets the real outcome marked `log-pending`, `GET /health` counts the pending receipts, and `requirePrecommit` refuses a remote log with an empty `precommit`. The [failure table](docs/usage.md#when-the-log-fails) gives each case.
|
|
332
334
|
|
|
333
335
|
**Next, in the order it pays off**
|
|
334
336
|
|
package/dist/check.js
CHANGED
|
@@ -226,7 +226,7 @@ export async function checkConfig(configPath, options = {}) {
|
|
|
226
226
|
}
|
|
227
227
|
// what a log outage costs
|
|
228
228
|
if (cfg.log && !cfg.precommit.length)
|
|
229
|
-
add("warn", "precommit", "a remote log is set and precommit is empty: every call is forwarded before its receipt is logged, so a log outage after a call
|
|
229
|
+
add("warn", "precommit", "a remote log is set and precommit is empty: every call is forwarded before its receipt is logged, so a log outage after a call puts its receipt in the outbox and the side effect is in the log only later. Name the consequential tools in precommit, or [\"*\"]; requirePrecommit makes this an error");
|
|
230
230
|
// tool names the config mentions, against the tools the upstreams offer
|
|
231
231
|
const mentioned = () => [
|
|
232
232
|
...cfg.precommit.filter((t) => t !== "*").map((t) => ["precommit", t]),
|
package/dist/cli.js
CHANGED
|
@@ -290,7 +290,7 @@ async function main(argv) {
|
|
|
290
290
|
if (candidates.length !== 1)
|
|
291
291
|
throw new Error("gateway --a2a needs exactly one { a2a: ... } upstream in the config");
|
|
292
292
|
const a2a = candidates[0].a2a;
|
|
293
|
-
const host = await createGatewayHost(cfg);
|
|
293
|
+
const host = await createGatewayHost(cfg, { autoFlush: true });
|
|
294
294
|
const grant = cfg.grantFile ? JSON.parse(readFileSync(cfg.grantFile, "utf8")) : undefined;
|
|
295
295
|
const running = await serveA2a(host, a2a, { port: Number(values.port), host: values.host, ...(grant ? { grant } : {}) });
|
|
296
296
|
console.error(`agent-custody gateway (a2a): ${running.url} keyid=${host.keyid} fronting ${a2a.url} as ${a2a.prefix}.send; card at ${running.url}/.well-known/agent-card.json`);
|
|
@@ -300,7 +300,7 @@ async function main(argv) {
|
|
|
300
300
|
return 0;
|
|
301
301
|
}
|
|
302
302
|
if (values.http) {
|
|
303
|
-
const host = await createGatewayHost(loadConfig(values.config));
|
|
303
|
+
const host = await createGatewayHost(loadConfig(values.config), { autoFlush: true });
|
|
304
304
|
const running = await serveHttp(host, { port: Number(values.port), host: values.host, idleMs: Number(values["idle-minutes"]) * 60_000 });
|
|
305
305
|
console.error(`agent-custody gateway: ${running.url} keyid=${host.keyid} one session per grant; GET /health`);
|
|
306
306
|
await untilStopped();
|
|
@@ -308,7 +308,7 @@ async function main(argv) {
|
|
|
308
308
|
await host.close();
|
|
309
309
|
return 0;
|
|
310
310
|
}
|
|
311
|
-
const gw = await createGateway(loadConfig(values.config));
|
|
311
|
+
const gw = await createGateway(loadConfig(values.config), { autoFlush: true });
|
|
312
312
|
console.error(`agent-custody gateway: agent=${gw.agentId} principal=${gw.delegation.principal} scopes=[${gw.delegation.scopes.join(", ")}]`);
|
|
313
313
|
await serveStdio(gw);
|
|
314
314
|
await gw.close();
|
|
@@ -757,6 +757,8 @@ async function main(argv) {
|
|
|
757
757
|
const failures = result.checks.filter((check) => !check.ok).map((check) => `${check.name}${check.detail ? ` (${check.detail})` : ""}`);
|
|
758
758
|
throw new Error(`receipt verification failed: ${failures.join("; ")}`);
|
|
759
759
|
}
|
|
760
|
+
if (`${result.statement.predicate.receiptId}.json` !== name)
|
|
761
|
+
throw new Error("the file name does not match the receipt id");
|
|
760
762
|
yield result.statement.predicate;
|
|
761
763
|
}
|
|
762
764
|
catch (error) {
|
package/dist/config.d.ts
CHANGED
|
@@ -249,6 +249,7 @@ export declare const GatewayConfigSchema: z.ZodObject<{
|
|
|
249
249
|
optional: z.ZodDefault<z.ZodBoolean>;
|
|
250
250
|
}, z.core.$strip>>>;
|
|
251
251
|
precommit: z.ZodDefault<z.ZodArray<z.ZodString>>;
|
|
252
|
+
requirePrecommit: z.ZodOptional<z.ZodBoolean>;
|
|
252
253
|
approvals: z.ZodOptional<z.ZodObject<{
|
|
253
254
|
trustedKeys: z.ZodArray<z.ZodString>;
|
|
254
255
|
usedDir: z.ZodString;
|
package/dist/config.js
CHANGED
|
@@ -143,6 +143,8 @@ export const GatewayConfigSchema = z.object({
|
|
|
143
143
|
* authorization to the log and refuses the call if the log will not take it. Evidence then precedes the side effect.
|
|
144
144
|
*/
|
|
145
145
|
precommit: z.array(z.string().min(1)).default([]),
|
|
146
|
+
/** with a remote log, refuse to start when precommit is empty; without it the gateway only warns */
|
|
147
|
+
requirePrecommit: z.boolean().optional(),
|
|
146
148
|
/** Tools that require a signed, unexpired, single-use approval, in every mode; "*" covers all agent calls. */
|
|
147
149
|
approvals: ApprovalsSchema.optional(),
|
|
148
150
|
/** Durable idempotency, daily budget reservations, and provider reconciliation for financial operations. */
|
|
@@ -169,6 +171,7 @@ export const GatewayConfigSchema = z.object({
|
|
|
169
171
|
// a key fetched from the log itself proves nothing about a log that is dishonest from the start, so a remote log that
|
|
170
172
|
// gates consequential calls must have its keys pinned in the config (issue #99)
|
|
171
173
|
.refine((c) => !c.log || (!c.precommit.length && !c.operations) || !!c.log.keys?.length, { message: "precommit with a remote log needs log.keys: the log's public key files, pinned, to check its answer before a consequential call is forwarded" })
|
|
174
|
+
.refine((c) => !c.requirePrecommit || !c.log || c.precommit.length > 0, { message: "requirePrecommit is set and precommit is empty: name the consequential tools in precommit, or [\"*\"]" })
|
|
172
175
|
.refine((c) => !c.operations || !c.facts.some((fact) => c.operations.tools.some((tool) => tool.tool === fact.tool)), { message: "a fact lookup cannot invoke a financial operation tool" });
|
|
173
176
|
/** Loads a config file and resolves every path relative to the file's directory. */
|
|
174
177
|
export function loadConfig(path) {
|
package/dist/console-page.js
CHANGED
|
@@ -172,7 +172,7 @@ const SCRIPT = String.raw `
|
|
|
172
172
|
var r = s.report;
|
|
173
173
|
out.appendChild(h('div', { class: 'card' }, h('h3', { text: 'Replay of recorded calls' }),
|
|
174
174
|
h('p', { class: 'muted', text: 'A replay re-decides calls that already happened. A limit that no recorded call reached, and an argument value that was never sent, are not covered, so a change that widens what is allowed can show no change here.' }),
|
|
175
|
-
h('p', { text: s.replayed + ' verified receipts replayed (' + s.unverified + ' skipped because they did not verify). ' + r.evaluated + ' evaluated, ' + r.unchanged + ' unchanged, ' + r.changeCount + ' would change.' + (r.complete ? '' : ' The replay is incomplete: ' + r.skipped.length + ' calls could not be replayed.') }),
|
|
175
|
+
h('p', { text: s.replayed + ' verified receipts replayed (' + s.unverified + ' skipped because they did not verify). ' + r.evaluated + ' evaluated, ' + r.unchanged + ' unchanged, ' + r.reconciliations + ' reconciliations (provider reads with no policy decision), ' + r.changeCount + ' would change.' + (r.complete ? '' : ' The replay is incomplete: ' + r.skipped.length + ' calls could not be replayed.') }),
|
|
176
176
|
r.changes.length ? (function () {
|
|
177
177
|
var t = h('table', null, h('tr', null, h('th', { text: 'receipt' }), h('th', { text: 'tool' }), h('th', { text: 'was' }), h('th', { text: 'would be' })));
|
|
178
178
|
r.changes.forEach(function (c) { t.appendChild(h('tr', null, h('td', { text: short(c.receiptId) }), h('td', { text: c.tool }), h('td', { text: c.from }), h('td', { class: c.to === 'deny' ? 'bad' : 'warn', text: c.to }))); });
|
|
@@ -184,7 +184,7 @@ const SCRIPT = String.raw `
|
|
|
184
184
|
function save() {
|
|
185
185
|
return validate().then(function (v) {
|
|
186
186
|
if (!v.ok) return;
|
|
187
|
-
var ask = 'Save this policy?\n\
|
|
187
|
+
var ask = 'Save this policy?\n\nA running gateway applies it from its next call.';
|
|
188
188
|
if (v.issues.length) ask = 'Confirm before saving:\n\n' + v.issues.join('\n\n') + '\n\nSave this policy anyway?';
|
|
189
189
|
if (!window.confirm(ask)) return;
|
|
190
190
|
return api('PUT', '/api/policy', { text: area.value, expectDigest: policyDigest, confirm: v.issues.length > 0 }).then(function (r) {
|
|
@@ -194,7 +194,7 @@ const SCRIPT = String.raw `
|
|
|
194
194
|
});
|
|
195
195
|
}
|
|
196
196
|
return h('div', null, h('h2', { text: 'Policy' }),
|
|
197
|
-
h('div', { class: 'banner' }, '
|
|
197
|
+
h('div', { class: 'banner' }, 'A running gateway applies a saved change from its next call; every save is recorded in the audit trail, and the previous version is kept.'),
|
|
198
198
|
h('p', { class: 'muted' }, p.path + ' · ' + short(p.digest)),
|
|
199
199
|
area, h('div', { class: 'row' },
|
|
200
200
|
h('button', { class: 'secondary', onclick: function () { validate().catch(fail); } }, 'Validate'),
|
package/dist/console.js
CHANGED
|
@@ -326,6 +326,7 @@ export async function serveConsole(options) {
|
|
|
326
326
|
total: report.total,
|
|
327
327
|
evaluated: report.evaluated,
|
|
328
328
|
unchanged: report.unchanged,
|
|
329
|
+
reconciliations: report.reconciliations,
|
|
329
330
|
complete: report.complete,
|
|
330
331
|
changes: report.changes.slice(0, 200).map((c) => ({ receiptId: c.receiptId, tool: c.tool, from: c.previous.decision, to: c.proposed.decision })),
|
|
331
332
|
changeCount: report.changes.length,
|
|
@@ -357,7 +358,7 @@ export async function serveConsole(options) {
|
|
|
357
358
|
throw new HttpError(500, `the policy file cannot be written (${e instanceof Error ? e.message : String(e)}); mount the config directory read-write for the console`);
|
|
358
359
|
}
|
|
359
360
|
audit("policy.save", { file: cfg.policyFile, from: policyDigest(current), to: policyDigest(text), bytes: text.length, confirmed: issues }, by);
|
|
360
|
-
return { digest: policyDigest(text), note: "saved;
|
|
361
|
+
return { digest: policyDigest(text), note: "saved; a running gateway applies it from its next call" };
|
|
361
362
|
});
|
|
362
363
|
},
|
|
363
364
|
"POST /api/grants/inspect": async (req) => {
|
package/dist/gateway-http.js
CHANGED
|
@@ -89,7 +89,7 @@ export async function serveHttp(host, opts) {
|
|
|
89
89
|
const handler = async (req, res) => {
|
|
90
90
|
const url = new URL(req.url ?? "/", "http://localhost");
|
|
91
91
|
if (req.method === "GET" && url.pathname === "/health")
|
|
92
|
-
return json(res, 200, { ok: true, sessions: sessions.size, keyid: host.keyid });
|
|
92
|
+
return json(res, 200, { ok: true, sessions: sessions.size, keyid: host.keyid, pendingReceipts: host.pendingReceipts() });
|
|
93
93
|
if (url.pathname !== path)
|
|
94
94
|
return json(res, 404, { error: "not found" });
|
|
95
95
|
try {
|
package/dist/gateway.d.ts
CHANGED
|
@@ -2,12 +2,15 @@ import { type CallToolResult, type Tool } from "@modelcontextprotocol/sdk/types.
|
|
|
2
2
|
import type { GatewayConfig } from "./config.ts";
|
|
3
3
|
import { type Envelope } from "./crypto.ts";
|
|
4
4
|
import { type Delegation } from "./delegation.ts";
|
|
5
|
+
import { type FlushResult } from "./issue.ts";
|
|
5
6
|
import { type LogSink } from "./log-sink.ts";
|
|
6
7
|
import { type ReceiptExporter } from "./otel.ts";
|
|
7
8
|
import type { ReceiptBundle } from "./receipt.ts";
|
|
8
9
|
export declare const GATEWAY_VERSION = "0.1.0";
|
|
9
10
|
export declare const RECEIPT_META_KEY = "agent-custody/receipt";
|
|
10
11
|
export declare const MODEL_META_KEY = "agent-custody/model";
|
|
12
|
+
/** true on a result whose receipt is signed and kept in the outbox, and not yet in the log */
|
|
13
|
+
export declare const LOG_PENDING_META_KEY = "agent-custody/log-pending";
|
|
11
14
|
/** Set by the gateway on the answer to a retry of a financial operation: the receipt of the retry itself. `agent-custody/receipt` stays the receipt that holds the operation's outcome. */
|
|
12
15
|
export declare const RETRY_RECEIPT_META_KEY = "agent-custody/retry-receipt";
|
|
13
16
|
/** Set by the gateway on the call it forwards upstream: the receipt id, and the agent and principal from the attested grant. */
|
|
@@ -46,6 +49,11 @@ export interface GatewayOptions {
|
|
|
46
49
|
exporter?: ReceiptExporter;
|
|
47
50
|
/** cancels the start while it is connecting to the upstreams: every upstream already started is closed and the call rejects */
|
|
48
51
|
signal?: AbortSignal;
|
|
52
|
+
/**
|
|
53
|
+
* Appends the outbox at start and every 30 seconds. Only a gateway that serves sets it: `check` and `reconcile` open
|
|
54
|
+
* a host too, and must not append to the log or touch the outbox of a gateway that runs.
|
|
55
|
+
*/
|
|
56
|
+
autoFlush?: boolean;
|
|
49
57
|
}
|
|
50
58
|
/**
|
|
51
59
|
* The shared part of a gateway: the key, the policy, the issuer, the log, the upstreams, and the fact lookups. One host
|
|
@@ -59,10 +67,16 @@ export interface GatewayHost {
|
|
|
59
67
|
revoke(grantDigest: string): void;
|
|
60
68
|
/** the digests revoked so far */
|
|
61
69
|
revoked(): string[];
|
|
70
|
+
/** sha256 of the policy in force: the one the next call is evaluated under */
|
|
71
|
+
policyDigest(): string;
|
|
62
72
|
/** the names of every tool the upstreams offer, before any grant narrows them */
|
|
63
73
|
tools(): string[];
|
|
64
74
|
/** Operator-only provider lookup. Never exposed as an agent tool. Unknown/pending reservations remain held until a terminal reconciliation receipt is committed. */
|
|
65
75
|
reconcile(operationId: string): Promise<ReceiptBundle>;
|
|
76
|
+
/** Appends the receipts in the outbox, whose log append failed. A host opened with `autoFlush` also runs it at start and every 30 seconds; `close()` waits for a flush that runs. */
|
|
77
|
+
flushOutbox(): Promise<FlushResult>;
|
|
78
|
+
/** the receipts in the outbox */
|
|
79
|
+
pendingReceipts(): number;
|
|
66
80
|
/** closes the upstreams; every session opened from this host is finished with */
|
|
67
81
|
close(): Promise<void>;
|
|
68
82
|
}
|
package/dist/gateway.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
// The MCP gateway: sits between an agent and its upstreams, MCP servers or REST APIs, enforces scope + Cedar policy,
|
|
2
2
|
// and emits a signed, logged receipt for every tool call, allowed or denied.
|
|
3
3
|
import { randomUUID } from "node:crypto";
|
|
4
|
-
import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { appendFileSync, closeSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { join } from "node:path";
|
|
5
6
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
6
7
|
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
7
8
|
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
@@ -11,18 +12,20 @@ import { CallToolRequestSchema, ListToolsRequestSchema } from "@modelcontextprot
|
|
|
11
12
|
import { digestOf, dsseVerifiers, dsseVerify, loadPrivateKey, loadPublicKey } from "./crypto.js";
|
|
12
13
|
import { delegationValidAt, grantChainDigests, verifyDelegation } from "./delegation.js";
|
|
13
14
|
import { APPROVAL_META_KEY, DEFAULT_APPROVAL_LIFETIME_SECONDS, consumeApproval, verifyApproval, verifyApprovalStatement } from "./approval.js";
|
|
14
|
-
import { createIssuer } from "./issue.js";
|
|
15
|
+
import { createIssuer, ReceiptPending } from "./issue.js";
|
|
15
16
|
import { openLog } from "./log-sink.js";
|
|
16
17
|
import { openExporter } from "./otel.js";
|
|
17
18
|
import { upstreamEvidenceOf } from "./upstream.js";
|
|
18
19
|
import { restUpstream } from "./rest.js";
|
|
19
20
|
import { a2aUpstream } from "./a2a.js";
|
|
20
21
|
import { captureKeyFrom, effectiveRule } from "./capture.js";
|
|
21
|
-
import { evaluate, policyDigest } from "./policy.js";
|
|
22
|
+
import { evaluate, hasPermitRule, policyDigest, policyParseErrors } from "./policy.js";
|
|
22
23
|
import { OPERATION_META_KEY, OperationStore, ownerAlive } from "./operations.js";
|
|
23
24
|
export const GATEWAY_VERSION = "0.1.0";
|
|
24
25
|
export const RECEIPT_META_KEY = "agent-custody/receipt";
|
|
25
26
|
export const MODEL_META_KEY = "agent-custody/model";
|
|
27
|
+
/** true on a result whose receipt is signed and kept in the outbox, and not yet in the log */
|
|
28
|
+
export const LOG_PENDING_META_KEY = "agent-custody/log-pending";
|
|
26
29
|
/** Set by the gateway on the answer to a retry of a financial operation: the receipt of the retry itself. `agent-custody/receipt` stays the receipt that holds the operation's outcome. */
|
|
27
30
|
export const RETRY_RECEIPT_META_KEY = "agent-custody/retry-receipt";
|
|
28
31
|
/** Set by the gateway on the call it forwards upstream: the receipt id, and the agent and principal from the attested grant. */
|
|
@@ -92,8 +95,95 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
92
95
|
const trusted = cfg.trustedPrincipalKeys.map(loadPublicKey);
|
|
93
96
|
const approvalKeys = cfg.approvals?.trustedKeys.map(loadPublicKey) ?? [];
|
|
94
97
|
const approvalRule = (tool) => cfg.approvals?.tools.find((rule) => rule.tool === tool) ?? cfg.approvals?.tools.find((rule) => rule.tool === "*");
|
|
95
|
-
|
|
96
|
-
|
|
98
|
+
// The Cedar policy, re-read whenever the file changes, like the revocation list. A call is evaluated under the policy
|
|
99
|
+
// in force when it starts, and its receipt names that policy's digest. A changed file that cannot be read or does not
|
|
100
|
+
// parse is refused and the policy in force stays: never an allow, and never a fall back to no policy. Every change
|
|
101
|
+
// and every refusal is printed and appended to receiptsDir/policy-reloads.jsonl with both digests and the time.
|
|
102
|
+
// The bytes and the metadata come from one open file, so a rename between reading and stat'ing cannot pair them wrongly.
|
|
103
|
+
// ctime is in the key because a program can set mtime back but not ctime, and every write moves it. A file written in
|
|
104
|
+
// the last two seconds may still be being written within one timestamp tick, so its key is not kept: it is re-read on
|
|
105
|
+
// each call until it settles, and a half-written file read meanwhile is replaced by the finished one.
|
|
106
|
+
const keyOf = (st) => `${st.dev}:${st.ino}:${st.mtimeMs}:${st.ctimeMs}:${st.size}`;
|
|
107
|
+
const settled = (st) => Date.now() - Math.max(st.mtimeMs, st.ctimeMs) >= 2000;
|
|
108
|
+
const readPolicy = () => {
|
|
109
|
+
const fd = openSync(cfg.policyFile, "r");
|
|
110
|
+
try {
|
|
111
|
+
const st = fstatSync(fd);
|
|
112
|
+
const text = readFileSync(fd, "utf8");
|
|
113
|
+
return { text, seen: settled(st) ? keyOf(st) : "" };
|
|
114
|
+
}
|
|
115
|
+
finally {
|
|
116
|
+
closeSync(fd);
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
const policyStat = () => keyOf(statSync(cfg.policyFile));
|
|
120
|
+
const initialPolicy = readPolicy();
|
|
121
|
+
let policyNow = { text: initialPolicy.text, digest: policyDigest(initialPolicy.text) };
|
|
122
|
+
let policySeen = initialPolicy.seen;
|
|
123
|
+
// A file that cannot be read is retried on every call, since restoring access changes none of its metadata; this
|
|
124
|
+
// keeps the refusal from being printed and recorded on each of those calls.
|
|
125
|
+
let unreadableSeen = "";
|
|
126
|
+
// A file still settling is re-read on each call; a refusal is recorded once for the same bytes.
|
|
127
|
+
let refusedDigest = "";
|
|
128
|
+
const policyReloads = join(cfg.receiptsDir, "policy-reloads.jsonl");
|
|
129
|
+
const recordReload = (entry) => {
|
|
130
|
+
try {
|
|
131
|
+
mkdirSync(cfg.receiptsDir, { recursive: true });
|
|
132
|
+
appendFileSync(policyReloads, JSON.stringify({ at: new Date().toISOString(), file: cfg.policyFile, ...entry }) + "\n");
|
|
133
|
+
}
|
|
134
|
+
catch (e) {
|
|
135
|
+
console.error(`agent-custody gateway: cannot record the policy change in ${policyReloads}: ${e instanceof Error ? e.message : String(e)}`);
|
|
136
|
+
}
|
|
137
|
+
};
|
|
138
|
+
const refuseReload = (to, errors) => {
|
|
139
|
+
console.error(`agent-custody gateway: POLICY NOT RELOADED: ${cfg.policyFile} ${errors.join("; ")}; policy ${policyNow.digest} stays in force`);
|
|
140
|
+
recordReload({ event: "refused", from: policyNow.digest, to, errors });
|
|
141
|
+
};
|
|
142
|
+
const currentPolicy = () => {
|
|
143
|
+
const unreadable = (seen, e) => {
|
|
144
|
+
if (unreadableSeen !== seen)
|
|
145
|
+
refuseReload(null, [`cannot be read (${e instanceof Error ? e.message : String(e)})`]);
|
|
146
|
+
unreadableSeen = seen;
|
|
147
|
+
return policyNow;
|
|
148
|
+
};
|
|
149
|
+
let seen;
|
|
150
|
+
try {
|
|
151
|
+
seen = policyStat();
|
|
152
|
+
}
|
|
153
|
+
catch (e) {
|
|
154
|
+
return unreadable("missing", e);
|
|
155
|
+
}
|
|
156
|
+
if (seen === policySeen)
|
|
157
|
+
return policyNow;
|
|
158
|
+
let read;
|
|
159
|
+
try {
|
|
160
|
+
read = readPolicy();
|
|
161
|
+
}
|
|
162
|
+
catch (e) {
|
|
163
|
+
return unreadable(seen, e);
|
|
164
|
+
}
|
|
165
|
+
unreadableSeen = "";
|
|
166
|
+
policySeen = read.seen;
|
|
167
|
+
const text = read.text;
|
|
168
|
+
const digest = policyDigest(text);
|
|
169
|
+
if (digest === policyNow.digest)
|
|
170
|
+
return policyNow;
|
|
171
|
+
if (digest === refusedDigest)
|
|
172
|
+
return policyNow;
|
|
173
|
+
const errors = policyParseErrors(text);
|
|
174
|
+
if (errors.length > 0) {
|
|
175
|
+
refusedDigest = digest;
|
|
176
|
+
refuseReload(digest, [`does not parse: ${errors.join("; ")}`]);
|
|
177
|
+
return policyNow;
|
|
178
|
+
}
|
|
179
|
+
refusedDigest = "";
|
|
180
|
+
// a policy with no permit rule parses and denies every call: fail-closed, but never a reload to pass over quietly
|
|
181
|
+
const warnings = hasPermitRule(text) ? [] : ["no permit rule: every call is denied"];
|
|
182
|
+
console.error(`agent-custody gateway: policy reloaded from ${cfg.policyFile}: ${policyNow.digest} -> ${digest}${warnings.length ? `; WARNING: ${warnings.join("; ")}` : ""}`);
|
|
183
|
+
recordReload({ event: "reloaded", from: policyNow.digest, to: digest, ...(warnings.length ? { warnings } : {}) });
|
|
184
|
+
policyNow = { text, digest };
|
|
185
|
+
return policyNow;
|
|
186
|
+
};
|
|
97
187
|
// Private evidence: the key that encrypts withheld fields, read once; a rule in mode encrypted without it is a config error.
|
|
98
188
|
const captureKey = cfg.captureKeyEnv ? captureKeyFrom(process.env[cfg.captureKeyEnv] ?? (() => { throw new Error(`capture key: environment variable ${cfg.captureKeyEnv} is not set`); })()) : undefined;
|
|
99
189
|
for (const [tool, rule] of Object.entries(cfg.capture ?? {})) {
|
|
@@ -320,6 +410,7 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
320
410
|
};
|
|
321
411
|
async function handleCall(params) {
|
|
322
412
|
const tool = params.name;
|
|
413
|
+
const { text: policyText, digest: pDigest } = currentPolicy();
|
|
323
414
|
// An embedding caller can mutate its objects while a lookup or log append is awaited. Snapshot the call and
|
|
324
415
|
// approval before the first await, so the approved bytes are the bytes evaluated, logged, and forwarded. A caller
|
|
325
416
|
// also cannot change the payment after its reservation was bound.
|
|
@@ -567,18 +658,30 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
567
658
|
operation = operations.update(operation.id, { status: "failed", unsent: undefined });
|
|
568
659
|
if (operation)
|
|
569
660
|
head.operation = operationEvidence(operation, operation.status === "submitted" && !createdOperation ? "unknown" : operation.status);
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
661
|
+
// 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.
|
|
663
|
+
let issued;
|
|
664
|
+
let logPending = false;
|
|
665
|
+
try {
|
|
666
|
+
issued = await issuer.issue({
|
|
667
|
+
...head,
|
|
668
|
+
...(approval ? { approval } : {}),
|
|
669
|
+
session: { id: null, toolUseId: null, provenance: "claimed" },
|
|
670
|
+
model: { id: typeof modelClaim === "string" ? modelClaim : null, provenance: "claimed" },
|
|
671
|
+
policy: { ...policy, provenance: "observed" },
|
|
672
|
+
...(authorization ? { authorization } : {}),
|
|
673
|
+
execution,
|
|
674
|
+
}, captureCtx, undefined, { deferLog: !operation });
|
|
675
|
+
}
|
|
676
|
+
catch (e) {
|
|
677
|
+
if (!(e instanceof ReceiptPending))
|
|
678
|
+
throw e;
|
|
679
|
+
console.error(`agent-custody gateway: ${e.message}`);
|
|
680
|
+
logPending = true;
|
|
681
|
+
}
|
|
579
682
|
if (operation && createdOperation && attemptedOperation)
|
|
580
683
|
operations.update(operation.id, { original: issued });
|
|
581
|
-
const meta = { [RECEIPT_META_KEY]: receiptId, ...(head.operation ? { [OPERATION_META_KEY]: head.operation } : {}) };
|
|
684
|
+
const meta = { [RECEIPT_META_KEY]: receiptId, ...(head.operation ? { [OPERATION_META_KEY]: head.operation } : {}), ...(logPending ? { [LOG_PENDING_META_KEY]: true } : {}) };
|
|
582
685
|
const refuse = (text) => ({ isError: true, content: [{ type: "text", text: `${text} (receipt ${receiptId})` }], _meta: meta });
|
|
583
686
|
switch (execution.status) {
|
|
584
687
|
// the agent gets the real result, the real reason, and the real error: what is withheld is withheld from the receipt
|
|
@@ -610,10 +713,28 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
610
713
|
},
|
|
611
714
|
};
|
|
612
715
|
}
|
|
716
|
+
if (cfg.log && !cfg.precommit.length)
|
|
717
|
+
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
|
+
let flushing;
|
|
719
|
+
const flushOutbox = () => flushing ??= (async () => {
|
|
720
|
+
const r = await issuer.flushOutbox();
|
|
721
|
+
if (r.setAside)
|
|
722
|
+
console.error(`agent-custody gateway: ${r.setAside} outbox entr${r.setAside === 1 ? "y is" : "ies are"} damaged, or not signed under its file name; renamed to .bad and not appended`);
|
|
723
|
+
if (r.foreign)
|
|
724
|
+
console.error(`agent-custody gateway: ${r.foreign} outbox entr${r.foreign === 1 ? "y is" : "ies are"} signed by a key other than ${issuer.keyid.slice(0, 12)}; left in the outbox and not appended. Restore the key that signed them, or move them away`);
|
|
725
|
+
if (r.error)
|
|
726
|
+
console.error(`agent-custody gateway: ${r.pending} receipt(s) wait in the outbox: ${r.error}`);
|
|
727
|
+
return r;
|
|
728
|
+
})().finally(() => { flushing = undefined; });
|
|
729
|
+
const autoFlush = () => void flushOutbox().catch((e) => console.error(`agent-custody gateway: the outbox flush failed: ${e instanceof Error ? e.message : String(e)}`));
|
|
730
|
+
const outboxTimer = options.autoFlush ? setInterval(autoFlush, 30_000).unref() : undefined;
|
|
731
|
+
if (options.autoFlush)
|
|
732
|
+
autoFlush();
|
|
613
733
|
return {
|
|
614
734
|
keyid: issuer.keyid,
|
|
615
735
|
open,
|
|
616
736
|
revoke,
|
|
737
|
+
policyDigest: () => currentPolicy().digest,
|
|
617
738
|
tools: () => advertised.map((t) => t.name),
|
|
618
739
|
revoked: () => {
|
|
619
740
|
reloadRevoked();
|
|
@@ -675,7 +796,7 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
675
796
|
principal: initial.principal, agent: initial.agent, delegation: initial.delegation,
|
|
676
797
|
session: { id: null, toolUseId: null, provenance: "claimed" }, model: { id: null, provenance: "claimed" },
|
|
677
798
|
tool: initial.tool, request: { args: lookup.args, argsDigest: digestOf(lookup.args), provenance: "claimed" },
|
|
678
|
-
facts: {}, policy: { decision: "allow", reasons: ["reconciliation: the gateway read the provider record and evaluated no policy"], errors: [], policyDigest:
|
|
799
|
+
facts: {}, policy: { decision: "allow", reasons: ["reconciliation: the gateway read the provider record and evaluated no policy"], errors: [], policyDigest: currentPolicy().digest, provenance: "observed" },
|
|
679
800
|
operation: operationEvidence(op, status), reconciliation: { original, lookup },
|
|
680
801
|
execution: { status: "executed", result, resultDigest: digestOf(result), provenance: "observed" },
|
|
681
802
|
};
|
|
@@ -690,7 +811,12 @@ export async function createGatewayHost(cfg, options = {}) {
|
|
|
690
811
|
operations.update(op.id, { status: intent.predicate.operation.status, reconciliation: { ...retained, bundle }, result: intent.predicate.execution.result, unsent: undefined });
|
|
691
812
|
return bundle;
|
|
692
813
|
},
|
|
814
|
+
flushOutbox,
|
|
815
|
+
pendingReceipts: () => issuer.pending(),
|
|
693
816
|
async close() {
|
|
817
|
+
if (outboxTimer)
|
|
818
|
+
clearInterval(outboxTimer);
|
|
819
|
+
await flushing?.catch(() => { });
|
|
694
820
|
for (const c of upstreams.values())
|
|
695
821
|
await c.close();
|
|
696
822
|
operations?.close();
|
package/dist/issue.d.ts
CHANGED
|
@@ -8,6 +8,24 @@ export interface PreparedReceipt {
|
|
|
8
8
|
envelope: Envelope;
|
|
9
9
|
view: PrivateView<ReceiptPredicate>;
|
|
10
10
|
}
|
|
11
|
+
/** The receipts whose log append failed wait here, signed, until `flushOutbox` appends them. */
|
|
12
|
+
export declare const OUTBOX_DIR = "outbox";
|
|
13
|
+
/** What one `flushOutbox` did. `foreign` entries are signed by another key and stay in the outbox. */
|
|
14
|
+
export interface FlushResult {
|
|
15
|
+
sent: number;
|
|
16
|
+
pending: number;
|
|
17
|
+
setAside: number;
|
|
18
|
+
foreign: number;
|
|
19
|
+
error?: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Thrown by `issue` with `deferLog` when the log did not take the receipt. The signed receipt is kept in the outbox and
|
|
23
|
+
* no bundle is written yet: `flushOutbox` appends it later and then writes the bundle.
|
|
24
|
+
*/
|
|
25
|
+
export declare class ReceiptPending extends Error {
|
|
26
|
+
readonly receiptId: string;
|
|
27
|
+
constructor(receiptId: string, cause: unknown);
|
|
28
|
+
}
|
|
11
29
|
export interface Issuer {
|
|
12
30
|
keyid: string;
|
|
13
31
|
log: LogSink;
|
|
@@ -16,9 +34,21 @@ export interface Issuer {
|
|
|
16
34
|
* bundle. Rejects if the log refuses the leaf; no bundle is written then. The predicate is the call in full; what
|
|
17
35
|
* is signed, written, and exported is the view.
|
|
18
36
|
*/
|
|
19
|
-
issue(predicate: ReceiptPredicate, ctx?: CaptureContext, retainPrepared?: (prepared: PreparedReceipt) => PreparedReceipt
|
|
37
|
+
issue(predicate: ReceiptPredicate, ctx?: CaptureContext, retainPrepared?: (prepared: PreparedReceipt) => PreparedReceipt, opts?: {
|
|
38
|
+
deferLog?: boolean;
|
|
39
|
+
}): Promise<ReceiptBundle>;
|
|
20
40
|
/** The same for an authorization, signed and committed before a consequential call is forwarded. Rejects if the log refuses; the caller must then not forward. */
|
|
21
41
|
authorize(predicate: AuthorizationPredicate, ctx?: CaptureContext): Promise<AuthorizationBundle>;
|
|
42
|
+
/**
|
|
43
|
+
* Appends each receipt in the outbox, oldest statement first, and writes its bundle. A log refusal stops the flush;
|
|
44
|
+
* another failure is reported in `error` and the flush goes on. One flush runs at a time in a process, and a lock
|
|
45
|
+
* file in the outbox keeps other processes out: when another process holds it, nothing is done. An entry that is
|
|
46
|
+
* damaged, or that this issuer's key signed under another receipt id, is renamed to `<name>.bad` and counted in
|
|
47
|
+
* `setAside`. An entry signed by another key stays in the outbox and is counted in `foreign`.
|
|
48
|
+
*/
|
|
49
|
+
flushOutbox(): Promise<FlushResult>;
|
|
50
|
+
/** the receipts in the outbox */
|
|
51
|
+
pending(): number;
|
|
22
52
|
}
|
|
23
53
|
export interface IssuerOptions {
|
|
24
54
|
/** told about every receipt after it is written; an exporter's failure never reaches the caller */
|
package/dist/issue.js
CHANGED
|
@@ -1,11 +1,28 @@
|
|
|
1
1
|
// Signing, logging and writing a receipt. Shared by every producer: the gateway and the SDK.
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
2
|
+
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { chmodSync, closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, utimesSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { hostname } from "node:os";
|
|
5
|
+
import { RECEIPT_ID, SALTS_DIR, saltsFileFor } from "./retention.js";
|
|
6
|
+
import { dirname, join } from "node:path";
|
|
5
7
|
import { effectiveRule, getAt, privateView } from "./capture.js";
|
|
6
8
|
import { canonicalize, dsseSign, dsseVerify } from "./crypto.js";
|
|
7
9
|
import { fileLog } from "./log-sink.js";
|
|
10
|
+
import { ownerAlive, processStamp } from "./operations.js";
|
|
8
11
|
import { buildAuthorizationStatement, buildStatement, RECEIPT_TYPE } from "./receipt.js";
|
|
12
|
+
/** The receipts whose log append failed wait here, signed, until `flushOutbox` appends them. */
|
|
13
|
+
export const OUTBOX_DIR = "outbox";
|
|
14
|
+
/**
|
|
15
|
+
* Thrown by `issue` with `deferLog` when the log did not take the receipt. The signed receipt is kept in the outbox and
|
|
16
|
+
* no bundle is written yet: `flushOutbox` appends it later and then writes the bundle.
|
|
17
|
+
*/
|
|
18
|
+
export class ReceiptPending extends Error {
|
|
19
|
+
receiptId;
|
|
20
|
+
constructor(receiptId, cause) {
|
|
21
|
+
super(`receipt ${receiptId} is kept in the outbox; its log append is pending: ${cause instanceof Error ? cause.message : String(cause)}`, { cause });
|
|
22
|
+
this.name = "ReceiptPending";
|
|
23
|
+
this.receiptId = receiptId;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
9
26
|
/** `log` is a sink, or a file path for the local log with tree heads signed by the issuer's key. */
|
|
10
27
|
export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
11
28
|
const sink = typeof log === "string" ? fileLog(log, key) : log;
|
|
@@ -32,6 +49,116 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
|
32
49
|
/** an authorization whose receipt has not followed within this long is a call that died; its view is let go */
|
|
33
50
|
const COMMITTED_FOR_MS = 60 * 60 * 1000;
|
|
34
51
|
const COMMITTED_AT_MOST = 100_000;
|
|
52
|
+
/** a lock that its owner has not touched for this long is broken, whatever machine the owner is on */
|
|
53
|
+
const LOCK_STALE_MS = 15 * 60 * 1000;
|
|
54
|
+
const outboxDir = join(receiptsDir, OUTBOX_DIR);
|
|
55
|
+
const outboxed = () => existsSync(outboxDir) ? readdirSync(outboxDir).filter((f) => f.endsWith(".json") && RECEIPT_ID.test(f.slice(0, -".json".length))) : [];
|
|
56
|
+
/** the outbox in the order of the signed statements' timestamps; an entry that cannot be read sorts first and is dealt with when its turn comes */
|
|
57
|
+
const outboxOrdered = () => outboxed().map((f) => {
|
|
58
|
+
let at = 0;
|
|
59
|
+
try {
|
|
60
|
+
const env = JSON.parse(readFileSync(join(outboxDir, f), "utf8")).envelope;
|
|
61
|
+
at = Date.parse(JSON.parse(Buffer.from(env.payload, "base64").toString("utf8")).predicate.timestamp) || 0;
|
|
62
|
+
}
|
|
63
|
+
catch { /* unreadable: at stays 0 */ }
|
|
64
|
+
return { f, at };
|
|
65
|
+
}).sort((a, b) => a.at - b.at || (a.f < b.f ? -1 : 1)).map((e) => e.f);
|
|
66
|
+
/** the file is whole or absent, and on disk before the caller goes on: it can be the only copy of the evidence */
|
|
67
|
+
const writeDurable = (file, text) => {
|
|
68
|
+
const fd = openSync(`${file}.tmp`, "w");
|
|
69
|
+
try {
|
|
70
|
+
writeFileSync(fd, text);
|
|
71
|
+
fsyncSync(fd);
|
|
72
|
+
}
|
|
73
|
+
finally {
|
|
74
|
+
closeSync(fd);
|
|
75
|
+
}
|
|
76
|
+
renameSync(`${file}.tmp`, file);
|
|
77
|
+
syncDir(dirname(file));
|
|
78
|
+
};
|
|
79
|
+
const syncDir = (dir) => {
|
|
80
|
+
const fd = openSync(dir, "r");
|
|
81
|
+
try {
|
|
82
|
+
fsyncSync(fd);
|
|
83
|
+
}
|
|
84
|
+
finally {
|
|
85
|
+
closeSync(fd);
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
const lockFile = join(outboxDir, ".lock");
|
|
89
|
+
/** Takes the outbox lock with an exclusive create. A lock whose owner is gone, or that no one has touched for a long time, is broken. Returns its release, or undefined when another flusher holds it. */
|
|
90
|
+
const takeLock = () => {
|
|
91
|
+
const token = randomUUID();
|
|
92
|
+
const body = JSON.stringify({ token, pid: process.pid, start: processStamp(process.pid), host: hostname() });
|
|
93
|
+
for (let attempt = 0; attempt < 3; attempt++) {
|
|
94
|
+
try {
|
|
95
|
+
const fd = openSync(lockFile, "wx", 0o600);
|
|
96
|
+
try {
|
|
97
|
+
writeFileSync(fd, body);
|
|
98
|
+
}
|
|
99
|
+
finally {
|
|
100
|
+
closeSync(fd);
|
|
101
|
+
}
|
|
102
|
+
return () => {
|
|
103
|
+
try {
|
|
104
|
+
if (JSON.parse(readFileSync(lockFile, "utf8")).token === token)
|
|
105
|
+
rmSync(lockFile, { force: true });
|
|
106
|
+
}
|
|
107
|
+
catch { /* already broken by another flusher */ }
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
catch (e) {
|
|
111
|
+
if (e.code !== "EEXIST")
|
|
112
|
+
throw e;
|
|
113
|
+
}
|
|
114
|
+
if (!lockIsStale())
|
|
115
|
+
return undefined;
|
|
116
|
+
// two flushers may both judge it stale; the rename lets one of them move it, the other gets ENOENT and tries again
|
|
117
|
+
try {
|
|
118
|
+
const gone = `${lockFile}.stale-${randomUUID()}`;
|
|
119
|
+
renameSync(lockFile, gone);
|
|
120
|
+
rmSync(gone, { force: true });
|
|
121
|
+
}
|
|
122
|
+
catch (e) {
|
|
123
|
+
if (e.code !== "ENOENT")
|
|
124
|
+
throw e;
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
return undefined;
|
|
128
|
+
};
|
|
129
|
+
const lockIsStale = () => {
|
|
130
|
+
try {
|
|
131
|
+
const age = Date.now() - statSync(lockFile).mtimeMs;
|
|
132
|
+
let owner;
|
|
133
|
+
try {
|
|
134
|
+
owner = JSON.parse(readFileSync(lockFile, "utf8"));
|
|
135
|
+
}
|
|
136
|
+
catch { /* a lock being written */ }
|
|
137
|
+
if (!owner)
|
|
138
|
+
return age > 60_000;
|
|
139
|
+
if (owner.host === hostname() && !ownerAlive({ ownerPid: owner.pid, ...(owner.start ? { ownerStart: owner.start } : {}) }))
|
|
140
|
+
return true;
|
|
141
|
+
return age > LOCK_STALE_MS;
|
|
142
|
+
}
|
|
143
|
+
catch (e) {
|
|
144
|
+
if (e.code === "ENOENT")
|
|
145
|
+
return true;
|
|
146
|
+
throw e;
|
|
147
|
+
}
|
|
148
|
+
};
|
|
149
|
+
const writeBundle = async (receiptId, v, bundle) => {
|
|
150
|
+
const file = join(receiptsDir, `${receiptId}.json`);
|
|
151
|
+
// whole or absent: a flush takes a bundle that is there as proof that the outbox entry is done
|
|
152
|
+
writeFileSync(`${file}.tmp`, JSON.stringify(bundle, null, 2));
|
|
153
|
+
renameSync(`${file}.tmp`, file);
|
|
154
|
+
// After the evidence, not before, and awaited so a process that exits right after issuing still exports. The
|
|
155
|
+
// exporter sees the view, never the full call.
|
|
156
|
+
if (opts.exporter)
|
|
157
|
+
await opts.exporter.exported(v, bundle).catch(() => { });
|
|
158
|
+
};
|
|
159
|
+
let flushing;
|
|
160
|
+
/** the log's answer for a receipt whose bundle could not be written yet: a retry in this process writes the bundle and does not append again */
|
|
161
|
+
const appended = new Map();
|
|
35
162
|
/**
|
|
36
163
|
* The salts behind a statement's digest-only commitments, kept beside the receipts and never in them:
|
|
37
164
|
* `receipts/salts/<id>.json`, the owner's alone. They are what makes a disclosure possible for a value withheld
|
|
@@ -47,7 +174,7 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
|
47
174
|
return {
|
|
48
175
|
keyid: key.keyid,
|
|
49
176
|
log: sink,
|
|
50
|
-
async issue(predicate, ctx, retainPrepared) {
|
|
177
|
+
async issue(predicate, ctx, retainPrepared, issueOpts) {
|
|
51
178
|
ensureSaltsDir();
|
|
52
179
|
// the authorization's view stays until the log has taken the receipt: a producer that retries after a refusal gets the same commitments and salts
|
|
53
180
|
const prior = committed.get(predicate.receiptId)?.view;
|
|
@@ -63,16 +190,32 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
|
63
190
|
if (!checked.ok || envelope.payloadType !== RECEIPT_TYPE || v.receiptId !== predicate.receiptId || canonicalize(checked.payload) !== canonicalize(buildStatement(v)))
|
|
64
191
|
throw new Error("prepared receipt does not match this issuer, predicate, or receipt id");
|
|
65
192
|
}
|
|
66
|
-
|
|
193
|
+
let entry;
|
|
194
|
+
try {
|
|
195
|
+
entry = await sink.append(canonicalize(envelope));
|
|
196
|
+
}
|
|
197
|
+
catch (e) {
|
|
198
|
+
if (!issueOpts?.deferLog)
|
|
199
|
+
throw e;
|
|
200
|
+
// The call has happened, so its receipt is kept: signed, with its salts, and appended later. The salts go
|
|
201
|
+
// first, so an outbox entry never lacks them; the rename makes the entry whole or absent.
|
|
202
|
+
try {
|
|
203
|
+
keepSalts(pv);
|
|
204
|
+
mkdirSync(outboxDir, { recursive: true });
|
|
205
|
+
writeDurable(join(outboxDir, `${predicate.receiptId}.json`), JSON.stringify({ envelope }));
|
|
206
|
+
syncDir(receiptsDir);
|
|
207
|
+
}
|
|
208
|
+
catch (w) {
|
|
209
|
+
throw new Error(`${e instanceof Error ? e.message : String(e)}; the receipt could not be kept in the outbox either: ${w instanceof Error ? w.message : String(w)}`, { cause: e });
|
|
210
|
+
}
|
|
211
|
+
committed.delete(predicate.receiptId);
|
|
212
|
+
throw new ReceiptPending(predicate.receiptId, e);
|
|
213
|
+
}
|
|
67
214
|
committed.delete(predicate.receiptId);
|
|
68
215
|
// the salts once the log has taken the leaf: a receipt the log refused leaves nothing behind
|
|
69
216
|
keepSalts(pv);
|
|
70
217
|
const bundle = { envelope, treeHead: entry.treeHead, inclusion: entry.inclusion };
|
|
71
|
-
|
|
72
|
-
// After the evidence, not before, and awaited so a process that exits right after issuing still exports. The
|
|
73
|
-
// exporter sees the view, never the full call.
|
|
74
|
-
if (opts.exporter)
|
|
75
|
-
await opts.exporter.exported(v, bundle).catch(() => { });
|
|
218
|
+
await writeBundle(predicate.receiptId, v, bundle);
|
|
76
219
|
return bundle;
|
|
77
220
|
},
|
|
78
221
|
async authorize(predicate, ctx) {
|
|
@@ -97,5 +240,113 @@ export function createIssuer(key, receiptsDir, log, opts = {}) {
|
|
|
97
240
|
writeFileSync(join(receiptsDir, `${predicate.receiptId}.authorization.json`), JSON.stringify(bundle, null, 2));
|
|
98
241
|
return bundle;
|
|
99
242
|
},
|
|
243
|
+
pending: () => outboxed().length,
|
|
244
|
+
flushOutbox() {
|
|
245
|
+
flushing ??= (async () => {
|
|
246
|
+
const idle = () => ({ sent: 0, pending: outboxed().length, setAside: 0, foreign: 0 });
|
|
247
|
+
if (!outboxed().length)
|
|
248
|
+
return idle();
|
|
249
|
+
const release = takeLock();
|
|
250
|
+
if (!release)
|
|
251
|
+
return idle();
|
|
252
|
+
try {
|
|
253
|
+
let sent = 0;
|
|
254
|
+
let setAside = 0;
|
|
255
|
+
let foreign = 0;
|
|
256
|
+
const errors = [];
|
|
257
|
+
const done = () => ({ sent, pending: outboxed().length, setAside, foreign, ...(errors.length ? { error: errors.length === 1 ? errors[0] : `${errors[0]} (and ${errors.length - 1} more)` } : {}) });
|
|
258
|
+
const setAsideFile = (file) => {
|
|
259
|
+
try {
|
|
260
|
+
renameSync(file, `${file}.bad`);
|
|
261
|
+
setAside++;
|
|
262
|
+
}
|
|
263
|
+
catch (e) {
|
|
264
|
+
if (e.code !== "ENOENT")
|
|
265
|
+
throw e;
|
|
266
|
+
}
|
|
267
|
+
};
|
|
268
|
+
for (const f of outboxOrdered()) {
|
|
269
|
+
const receiptId = f.slice(0, -".json".length);
|
|
270
|
+
const file = join(outboxDir, f);
|
|
271
|
+
try {
|
|
272
|
+
// a bundle already there means the append and the write happened and only the removal did not
|
|
273
|
+
if (existsSync(join(receiptsDir, f))) {
|
|
274
|
+
rmSync(file, { force: true });
|
|
275
|
+
appended.delete(receiptId);
|
|
276
|
+
sent++;
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
let record;
|
|
280
|
+
try {
|
|
281
|
+
record = JSON.parse(readFileSync(file, "utf8"));
|
|
282
|
+
}
|
|
283
|
+
catch (e) {
|
|
284
|
+
// gone: another flusher took it; anything else that is not readable JSON is damaged
|
|
285
|
+
if (e.code === "ENOENT")
|
|
286
|
+
continue;
|
|
287
|
+
if (!(e instanceof SyntaxError))
|
|
288
|
+
throw e;
|
|
289
|
+
setAsideFile(file);
|
|
290
|
+
continue;
|
|
291
|
+
}
|
|
292
|
+
const envelope = record?.envelope;
|
|
293
|
+
if (typeof envelope?.payload !== "string" || !Array.isArray(envelope.signatures) || envelope.signatures.length === 0) {
|
|
294
|
+
setAsideFile(file);
|
|
295
|
+
continue;
|
|
296
|
+
}
|
|
297
|
+
// a signature by another key proves nothing about this entry (a rotated key, a restored backup): it stays, and is reported
|
|
298
|
+
if (!envelope.signatures.some((sig) => sig?.keyid === key.keyid)) {
|
|
299
|
+
foreign++;
|
|
300
|
+
continue;
|
|
301
|
+
}
|
|
302
|
+
// only this issuer's own receipt, under its own id, goes to the log; anything else is set aside, not retried
|
|
303
|
+
const checked = dsseVerify(envelope, [key]);
|
|
304
|
+
const statement = (checked.ok ? checked.payload : undefined);
|
|
305
|
+
if (!statement || envelope.payloadType !== RECEIPT_TYPE || statement.predicate?.receiptId !== receiptId) {
|
|
306
|
+
setAsideFile(file);
|
|
307
|
+
continue;
|
|
308
|
+
}
|
|
309
|
+
let entry = record.appended ?? appended.get(receiptId);
|
|
310
|
+
if (!entry) {
|
|
311
|
+
try {
|
|
312
|
+
entry = await sink.append(canonicalize(envelope));
|
|
313
|
+
}
|
|
314
|
+
catch (e) {
|
|
315
|
+
errors.push(e instanceof Error ? e.message : String(e));
|
|
316
|
+
return done();
|
|
317
|
+
}
|
|
318
|
+
// Until the bundle is written, the answer is the only proof that the log has the leaf. It is kept in
|
|
319
|
+
// memory and in the entry, so that a failure now does not make the next flush append the leaf again.
|
|
320
|
+
appended.set(receiptId, entry);
|
|
321
|
+
try {
|
|
322
|
+
writeDurable(file, JSON.stringify({ envelope, appended: entry }));
|
|
323
|
+
}
|
|
324
|
+
catch (e) {
|
|
325
|
+
errors.push(`receipt ${receiptId} is in the log, but its outbox entry could not record that: ${e instanceof Error ? e.message : String(e)}`);
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
await writeBundle(receiptId, statement.predicate, { envelope, treeHead: entry.treeHead, inclusion: entry.inclusion });
|
|
329
|
+
rmSync(file, { force: true });
|
|
330
|
+
appended.delete(receiptId);
|
|
331
|
+
sent++;
|
|
332
|
+
try {
|
|
333
|
+
utimesSync(lockFile, new Date(), new Date());
|
|
334
|
+
}
|
|
335
|
+
catch { /* the lock is only a hint */ }
|
|
336
|
+
}
|
|
337
|
+
catch (e) {
|
|
338
|
+
if (e.code === "ENOENT" && !existsSync(file))
|
|
339
|
+
continue;
|
|
340
|
+
errors.push(`outbox entry ${f}: ${e instanceof Error ? e.message : String(e)}`);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return done();
|
|
344
|
+
}
|
|
345
|
+
finally {
|
|
346
|
+
release();
|
|
347
|
+
}
|
|
348
|
+
})().finally(() => { flushing = undefined; });
|
|
349
|
+
return flushing;
|
|
350
|
+
},
|
|
100
351
|
};
|
|
101
352
|
}
|
package/dist/policy.d.ts
CHANGED
|
@@ -16,6 +16,8 @@ export interface PolicyRequest {
|
|
|
16
16
|
}
|
|
17
17
|
/** True when the policy set contains a permit rule. Cedar answers, so a `permit(` in a comment does not count. */
|
|
18
18
|
export declare function hasPermitRule(policyText: string): boolean;
|
|
19
|
+
/** Why Cedar cannot parse the policy set, or an empty list when it can. */
|
|
20
|
+
export declare function policyParseErrors(policyText: string): string[];
|
|
19
21
|
export declare function policyDigest(policyText: string): string;
|
|
20
22
|
/**
|
|
21
23
|
* Cedar's JSON context reads `{ "__entity": … }` and `{ "__extn": … }` as typed values. Arguments come from the agent,
|
package/dist/policy.js
CHANGED
|
@@ -11,6 +11,11 @@ export function hasPermitRule(policyText) {
|
|
|
11
11
|
return j.type === "success" && j.json.effect === "permit";
|
|
12
12
|
});
|
|
13
13
|
}
|
|
14
|
+
/** Why Cedar cannot parse the policy set, or an empty list when it can. */
|
|
15
|
+
export function policyParseErrors(policyText) {
|
|
16
|
+
const parsed = cedar.checkParsePolicySet({ staticPolicies: policyText });
|
|
17
|
+
return parsed.type === "success" ? [] : parsed.errors.map((e) => e.message);
|
|
18
|
+
}
|
|
14
19
|
export function policyDigest(policyText) {
|
|
15
20
|
return sha256Hex(policyText);
|
|
16
21
|
}
|
package/dist/portal.js
CHANGED
|
@@ -222,6 +222,7 @@ export class PortalStore {
|
|
|
222
222
|
await this.init();
|
|
223
223
|
return (await this.client.query(`UPDATE ${this.p}members SET role = $3 WHERE user_id = $1 AND tenant_id = $2 AND ($3 = 'owner' OR role <> 'owner' OR EXISTS (SELECT 1 FROM ${this.p}members o WHERE o.tenant_id = $2 AND o.role = 'owner' AND o.user_id <> $1)) RETURNING user_id`, [userId, tenantId, role])).rows.length > 0;
|
|
224
224
|
}
|
|
225
|
+
// The removal record stays after a rejoin by invite. It has no effect while the user is a member: only findOrCreateSsoUser reads it, and only when the home tenant differs.
|
|
225
226
|
async removeMember(tenantId, userId) {
|
|
226
227
|
await this.init();
|
|
227
228
|
const gone = (await this.client.query(`DELETE FROM ${this.p}members WHERE user_id = $1 AND tenant_id = $2 AND (role <> 'owner' OR EXISTS (SELECT 1 FROM ${this.p}members o WHERE o.tenant_id = $2 AND o.role = 'owner' AND o.user_id <> $1)) RETURNING user_id`, [userId, tenantId])).rows.length > 0;
|
package/dist/simulate.d.ts
CHANGED
|
@@ -27,6 +27,8 @@ export interface SimulationReport {
|
|
|
27
27
|
total: number;
|
|
28
28
|
evaluated: number;
|
|
29
29
|
unchanged: number;
|
|
30
|
+
/** Reconciliation receipts. Each is a provider read with no policy decision, so a replay counts it here and not in `evaluated` or `skipped`. */
|
|
31
|
+
reconciliations: number;
|
|
30
32
|
complete: boolean;
|
|
31
33
|
changes: SimulationChange[];
|
|
32
34
|
skipped: SimulationSkip[];
|
|
@@ -50,7 +52,11 @@ export declare function verifyOrphanAuthorization(bundle: AuthorizationBundle, i
|
|
|
50
52
|
/**
|
|
51
53
|
* Compare a proposed Cedar policy with recorded policy decisions, using each receipt's original arguments, fact
|
|
52
54
|
* values, agent, and (for gateways) grant context. Observe-mode decisions are the baseline even when the call ran.
|
|
53
|
-
* Receipts are not signature-verified here; verify their bundles separately when their authenticity matters.
|
|
55
|
+
* Receipts are not signature-verified here; verify their bundles separately when their authenticity matters. A
|
|
56
|
+
* reconciliation receipt is trusted as a provider read only after `verifyBundle` accepts it: the library checks no more
|
|
57
|
+
* than its shape and its link to an original receipt id.
|
|
58
|
+
* A reconciliation whose original receipt is not among the supplied receipts or `unreplayable` is reported as skipped,
|
|
59
|
+
* because the call it settles cannot be replayed.
|
|
54
60
|
* Missing inputs and non-Cedar gate failures are reported as skipped, never guessed or fetched again.
|
|
55
61
|
* The receipts are read once, one at a time, so a caller can verify and parse a large history lazily.
|
|
56
62
|
*/
|
package/dist/simulate.js
CHANGED
|
@@ -57,7 +57,11 @@ export function verifyOrphanAuthorization(bundle, issuerKeys, logKeys) {
|
|
|
57
57
|
/**
|
|
58
58
|
* Compare a proposed Cedar policy with recorded policy decisions, using each receipt's original arguments, fact
|
|
59
59
|
* values, agent, and (for gateways) grant context. Observe-mode decisions are the baseline even when the call ran.
|
|
60
|
-
* Receipts are not signature-verified here; verify their bundles separately when their authenticity matters.
|
|
60
|
+
* Receipts are not signature-verified here; verify their bundles separately when their authenticity matters. A
|
|
61
|
+
* reconciliation receipt is trusted as a provider read only after `verifyBundle` accepts it: the library checks no more
|
|
62
|
+
* than its shape and its link to an original receipt id.
|
|
63
|
+
* A reconciliation whose original receipt is not among the supplied receipts or `unreplayable` is reported as skipped,
|
|
64
|
+
* because the call it settles cannot be replayed.
|
|
61
65
|
* Missing inputs and non-Cedar gate failures are reported as skipped, never guessed or fetched again.
|
|
62
66
|
* The receipts are read once, one at a time, so a caller can verify and parse a large history lazily.
|
|
63
67
|
*/
|
|
@@ -74,22 +78,37 @@ export function simulatePolicy(policyText, receipts, options = {}) {
|
|
|
74
78
|
total: unreplayable.length,
|
|
75
79
|
evaluated: 0,
|
|
76
80
|
unchanged: 0,
|
|
81
|
+
reconciliations: 0,
|
|
77
82
|
complete: true,
|
|
78
83
|
changes: [],
|
|
79
84
|
skipped: [...unreplayable],
|
|
80
85
|
groups: [],
|
|
81
86
|
};
|
|
82
87
|
const digests = new Set();
|
|
88
|
+
const seen = new Set(unreplayable.map((u) => u.receiptId));
|
|
89
|
+
const reconciled = [];
|
|
83
90
|
for (const original of receipts) {
|
|
84
91
|
report.total++;
|
|
85
92
|
const receiptId = typeof original?.receiptId === "string" ? original.receiptId : "(unknown receipt)";
|
|
86
93
|
const tool = typeof original?.tool?.name === "string" ? original.tool.name : "(unknown tool)";
|
|
87
94
|
const skip = (reason) => { report.skipped.push({ receiptId, tool, reason }); };
|
|
95
|
+
if (original?.reconciliation === undefined)
|
|
96
|
+
seen.add(receiptId);
|
|
88
97
|
const broken = structuralProblem(original);
|
|
89
98
|
if (broken) {
|
|
90
99
|
skip(`malformed receipt: ${broken}`);
|
|
91
100
|
continue;
|
|
92
101
|
}
|
|
102
|
+
if (original.reconciliation !== undefined) {
|
|
103
|
+
const link = original.operation?.originalReceiptId;
|
|
104
|
+
if (original.issuer.kind !== "gateway" || typeof link !== "string" || link === receiptId) {
|
|
105
|
+
skip("malformed receipt: a reconciliation needs a gateway issuer and an operation that names another receipt");
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
report.reconciliations++;
|
|
109
|
+
reconciled.push({ receiptId: link, tool, reason: `only the reconciliation ${receiptId} survives; the original receipt is missing, so the call cannot be replayed` });
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
93
112
|
if (original.policy === null) {
|
|
94
113
|
skip("no recorded policy decision (record-only receipt)");
|
|
95
114
|
continue;
|
|
@@ -166,6 +185,12 @@ export function simulatePolicy(policyText, receipts, options = {}) {
|
|
|
166
185
|
else
|
|
167
186
|
report.changes.push({ receiptId, tool, previous, proposed });
|
|
168
187
|
}
|
|
188
|
+
for (const lost of reconciled) {
|
|
189
|
+
if (seen.has(lost.receiptId))
|
|
190
|
+
continue;
|
|
191
|
+
report.reconciliations--;
|
|
192
|
+
report.skipped.push(lost);
|
|
193
|
+
}
|
|
169
194
|
report.previousPolicyDigests = [...digests].sort(order);
|
|
170
195
|
report.complete = report.skipped.length === 0;
|
|
171
196
|
const groups = new Map();
|
|
@@ -188,7 +213,7 @@ export function formatSimulation(report) {
|
|
|
188
213
|
`Timestamp: ${report.timestamp}`,
|
|
189
214
|
`Proposed policy: ${report.policyDigest}`,
|
|
190
215
|
`Previous policies: ${report.previousPolicyDigests.join(", ") || "none"}`,
|
|
191
|
-
`Receipts: ${report.total}; evaluated: ${report.evaluated}; unchanged: ${report.unchanged}; changed: ${report.changes.length}; skipped: ${report.skipped.length}`,
|
|
216
|
+
`Receipts: ${report.total}; evaluated: ${report.evaluated}; unchanged: ${report.unchanged}; reconciliations: ${report.reconciliations}; changed: ${report.changes.length}; skipped: ${report.skipped.length}`,
|
|
192
217
|
];
|
|
193
218
|
for (const group of report.groups) {
|
|
194
219
|
lines.push("", `${group.tool}: ${group.reason}`);
|
package/dist/verify.js
CHANGED
|
@@ -561,7 +561,9 @@ export function formatReport(r) {
|
|
|
561
561
|
row("args", p.request.provenance, p.request.args);
|
|
562
562
|
for (const [k, f] of Object.entries(p.facts))
|
|
563
563
|
row(`fact.${k}`, f.provenance, f.value);
|
|
564
|
-
if (p.
|
|
564
|
+
if (p.reconciliation)
|
|
565
|
+
row("policy", "-", "(none evaluated: a provider read, not a call)");
|
|
566
|
+
else if (p.policy)
|
|
565
567
|
row("policy", p.policy.provenance, `${p.policy.decision}${p.policy.enforced === false ? " (observe mode, not enforced)" : ""} [${p.policy.reasons.join(",")}] policy ${short(p.policy.policyDigest)}`);
|
|
566
568
|
else
|
|
567
569
|
row("policy", "-", "(none evaluated)");
|
|
@@ -583,6 +585,6 @@ export function formatReport(r) {
|
|
|
583
585
|
// a refusal says why, as the receipt records it; under a capture rule the reason is a commitment, and the report says so rather than printing it
|
|
584
586
|
const reason = "reason" in p.execution ? p.execution.reason : undefined;
|
|
585
587
|
const why = reason === undefined ? "" : typeof reason === "string" ? `: ${reason}` : ": (reason withheld under the capture rule)";
|
|
586
|
-
row("execution", attestedAs, `${p.execution.status}${why}${note}`);
|
|
588
|
+
row("execution", attestedAs, `${p.reconciliation ? "provider read, " : ""}${p.execution.status}${why}${note}`);
|
|
587
589
|
return lines.join("\n");
|
|
588
590
|
}
|
package/docs/codex-recovery.md
CHANGED
|
@@ -127,6 +127,6 @@ node examples/10-support-recovery.ts
|
|
|
127
127
|
bun run test test/codex-recovery.test.ts test/examples.test.ts
|
|
128
128
|
```
|
|
129
129
|
|
|
130
|
-
The checks cover approval, stale plans, revoked support authority, duplicate-credit prevention, receipt tampering, store/evidence consistency, missing observed dependencies, and runs without agent activity.
|
|
130
|
+
The checks cover approval, stale plans, revoked support authority, duplicate-credit prevention, receipt tampering, store/evidence consistency, missing observed dependencies (a credit or a benefit that no memory read supports), the refresh after a partial recovery, and runs without agent activity.
|
|
131
131
|
|
|
132
132
|
Codex integration references: [non-interactive mode](https://learn.chatgpt.com/docs/non-interactive-mode), [MCP configuration](https://learn.chatgpt.com/docs/extend/mcp?surface=cli).
|
package/docs/configuration.md
CHANGED
|
@@ -119,6 +119,7 @@ What each part does:
|
|
|
119
119
|
| `trustedPrincipalKeys` | the public keys whose grants this gateway accepts. Only public keys go here. |
|
|
120
120
|
| `facts` | before a refund, the gateway calls `customer.lookup` itself with the customer id from the call, and the policy reads the answer as `context.facts.customer`. |
|
|
121
121
|
| `precommit` | the consequential tools: the gateway commits the authorization to the log before it forwards, and withholds the call if the log will not take it. |
|
|
122
|
+
| `requirePrecommit` | with a remote log, the gateway does not start when `precommit` is empty. Without it, the gateway prints a warning. |
|
|
122
123
|
| `revokedGrants` | the file `agent-custody revoke` appends to; the gateway re-reads it on every call. |
|
|
123
124
|
| `receiptsDir`, `log` | full receipts stay on the gateway's disk. The hosted log receives only their hashes (`hashOnly`), and its public key is pinned (`keys`), which `precommit` with a remote log requires. |
|
|
124
125
|
|
|
@@ -201,7 +202,7 @@ docker run --rm -v "$PWD/config:/config:ro" -v gateway-data:/data --env-file .en
|
|
|
201
202
|
| a stdio `command` exists, and a script argument exists | error, and a warning |
|
|
202
203
|
| the receipts, log, revocation, operations database, and approvals paths can be written, and the revocation file is a JSON array | error |
|
|
203
204
|
| the grant the config names verifies, and is inside its window | error, and a warning near expiry |
|
|
204
|
-
| a remote log with an empty `precommit` | warning: a log outage after a call
|
|
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
206
|
|
|
206
207
|
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.
|
|
207
208
|
|
|
@@ -216,6 +217,7 @@ With **`--connect`** it also starts the upstreams, which is where an unreachable
|
|
|
216
217
|
| `exactly one of upstream or upstreams is required` | both, or neither | use `upstream` for one source and `upstreams` for several |
|
|
217
218
|
| `exactly one of logFile or log is required` | both, or neither | a local file, or a remote log |
|
|
218
219
|
| `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
|
+
| `requirePrecommit is set and precommit is empty` | a remote log with no consequential tools named | name them in `precommit`, or `["*"]` |
|
|
219
221
|
| `fact "f" uses tool t, which precommit names as consequential` | a fact lookup must be a read | use a read tool for the fact |
|
|
220
222
|
| `ENOENT … gateway.key` | the key file does not exist | `agent-custody keygen`, or let the container create it |
|
|
221
223
|
| `EROFS` or a permission error on `receipts` | a writable path points into the read-only `/config` | use an absolute path under `/data` |
|
package/docs/console.md
CHANGED
|
@@ -37,7 +37,7 @@ It listens on `127.0.0.1:8795` and prints the URL. Open it and sign in with the
|
|
|
37
37
|
|
|
38
38
|
## What a saved policy does
|
|
39
39
|
|
|
40
|
-
|
|
40
|
+
A running gateway re-reads `policy.cedar` when it changes, so **a saved policy applies from the gateway's next call**, with no restart, and the gateway records the change in `receipts/policy-reloads.jsonl`. The save is guarded: Cedar must parse the text; and the operator must confirm a policy that has no `permit` rule (a `permit(` in a comment does not count), because every call would be denied, or a `permit` rule with **no action and no condition**, which allows every tool in a grant's scopes and which a replay cannot show. A save made from a copy that is no longer the file on disk is refused with `409`. The digest check, the history copy, and the write happen under one lock, in this process and, through a lock file in the state directory, across consoles that share it, so two administrators cannot overwrite each other. The previous version is kept under `console/policy-history/` and the change goes in the audit trail.
|
|
41
41
|
|
|
42
42
|
## How it is protected
|
|
43
43
|
|
|
@@ -52,7 +52,6 @@ The gateway reads `policy.cedar` when it starts, so **a saved policy applies aft
|
|
|
52
52
|
|
|
53
53
|
- It does not issue grants. A grant is signed by a principal's key, which belongs where grants are issued ([configuration.md](configuration.md#the-principals-key)).
|
|
54
54
|
- It does not edit `gateway.json`: upstreams, facts, and `precommit` are changed in the file, and the gateway restarted. The Overview and Check tabs show them.
|
|
55
|
-
- A policy change needs a gateway restart.
|
|
56
55
|
- The credential variables are not checked in the console, and an upstream that needs one is not started there.
|
|
57
56
|
- One token, no per-user accounts, and the audit records the address and not a person.
|
|
58
57
|
- It reads the local receipts directory. With a remote log it verifies receipts against the keys but not the log's inclusion proofs.
|
|
@@ -68,7 +67,7 @@ Every route except `GET /` (the page) and `GET /healthz` needs `Authorization: B
|
|
|
68
67
|
| `POST /api/check` `{ connect? }` | the check; `connect` starts the upstreams |
|
|
69
68
|
| `GET /api/policy` | the policy text, its digest, and the earlier versions kept |
|
|
70
69
|
| `POST /api/policy/validate` `{ text }` | does Cedar parse it, and which things need confirming (`issues`) |
|
|
71
|
-
| `POST /api/policy/simulate` `{ text }` | replay up to 1,000 verified receipts against it |
|
|
70
|
+
| `POST /api/policy/simulate` `{ text }` | replay up to 1,000 verified receipts against it; the report counts reconciliation receipts (provider reads, no policy decision) in `reconciliations`, apart from `evaluated` |
|
|
72
71
|
| `PUT /api/policy` `{ text, expectDigest, confirm? }` | save it; `400` unless `confirm` is true when the policy has an issue the validate route reported; `409` if the file changed |
|
|
73
72
|
| `POST /api/grants/inspect` `{ grant }` | status, agent, scopes, window, digest |
|
|
74
73
|
| `POST /api/grants/revoke` `{ grant }` | add its digest to the revocation file |
|
package/docs/policies.md
CHANGED
|
@@ -215,10 +215,12 @@ For SDK receipts, use the application's public key as `--issuer-key`; no princip
|
|
|
215
215
|
|
|
216
216
|
A gateway that dies after it forwards a `precommit` call leaves `<id>.authorization.json` and no `<id>.json`. The command verifies each such file as an authorization statement (the issuer key, the tree head, and the inclusion proof) and lists the call under `skipped`, so the report is `INCOMPLETE`. An authorization that does not verify fails the command. An authorization that sits beside its receipt is not read twice.
|
|
217
217
|
|
|
218
|
+
The command also checks that each `<id>.json` holds receipt `<id>`. A receipt under another file name fails the command, so a copy over the name of another receipt cannot hide that call.
|
|
219
|
+
|
|
218
220
|
A receipt under a capture rule needs its withheld arguments and fact values to replay. Give `--capture-key-env NAME` to decrypt the values that mode `encrypted` withheld, as `verify` does. Give `--disclose <file>`, which you can repeat, for the values that mode `digest` withheld. Each file is a disclosure as `reveal` writes it, and it applies only to the receipt that its `receiptId` names. A key or a disclosure that does not match a commitment skips that receipt as malformed. The key comes from the environment, never from a flag value.
|
|
219
221
|
|
|
220
222
|
The report lists every call whose `allow` or `deny` decision changes, grouped by tool and the proposed decision's policy ids or evaluation errors, with the receipt ids and both decisions. A call executed in observe mode may already have a recorded deny: replay compares that recorded decision, not whether the tool ran. Calls with the same decision stay unchanged even when different policy ids match. Cedar evaluation errors remain denials.
|
|
221
223
|
|
|
222
|
-
Every run records a `runId`, `timestamp`, the proposed text's sha256 as `policyDigest`, and the original digests as `previousPolicyDigests`. `--out` saves the full JSON report, and `--json` prints it to stdout. Changes alone exit 0. A report that cannot replay every call says `INCOMPLETE` and exits 1: `skipped` names each receipt and why. This includes record-only receipts with no policy baseline, withheld arguments or fact values, calls whose receipt is missing, and calls stopped before Cedar could evaluate. Grant failures cannot become permits through a policy change, and neither can an approval refusal: the gateway checks the approval before Cedar runs, so the call is skipped as a non-policy gate. The approval record says so even under a private rule. Withheld results alone do not prevent replay.
|
|
224
|
+
Every run records a `runId`, `timestamp`, the proposed text's sha256 as `policyDigest`, and the original digests as `previousPolicyDigests`. `--out` saves the full JSON report, and `--json` prints it to stdout. Changes alone exit 0. A report that cannot replay every call says `INCOMPLETE` and exits 1: `skipped` names each receipt and why. This includes record-only receipts with no policy baseline, withheld arguments or fact values, calls whose receipt is missing, and calls stopped before Cedar could evaluate. Grant failures cannot become permits through a policy change, and neither can an approval refusal: the gateway checks the approval before Cedar runs, so the call is skipped as a non-policy gate. The approval record says so even under a private rule. Withheld results alone do not prevent replay. A reconciliation receipt is a provider read, so no policy decision exists to replay. The report counts it in `reconciliations`, not in `evaluated` or `skipped`, and it does not make the report incomplete. A reconciliation whose original receipt is missing is the exception: the call that it settles cannot be replayed, so the report skips that call and says `INCOMPLETE`. The library trusts a reconciliation receipt only after `verifyBundle` accepts it; the CLI and the console verify first.
|
|
223
225
|
|
|
224
226
|
The report is an analysis of the supplied receipt directory; it does not prove that the directory contains the whole history. Keep the report beside the proposed policy and review the changed receipt ids before switching from observe mode to enforcement. [Tutorial 28](../examples/28-policy-simulation.ts) records three refunds, stops the gateway, and replays them against a lower limit.
|
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 refuses a leaf, the receipt is not issued and the call returns an error to the agent. For an ordinary call the upstream action has already happened by then, and the error says so; a receipt that was never logged must not be handed out. 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, so a tenant out of quota never acts without evidence. 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>]`, `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, so a tenant out of quota never acts without evidence. 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.
|
|
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. 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
|
|
|
@@ -135,7 +135,22 @@ 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. `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
|
|
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.
|
|
139
|
+
|
|
140
|
+
#### When the log fails
|
|
141
|
+
|
|
142
|
+
"Down" is a log that does not answer or answers 5xx. "Slow" is an append that takes longer than `log.timeoutMs` (default 10000 ms), which counts as down. "Refusing" is a 4xx answer other than 429, or an answer whose tree head or proof does not verify. "Quota" is 429, after the sink's retries. The sink makes three attempts before the gateway treats the append as failed.
|
|
143
|
+
|
|
144
|
+
| log state | ordinary tool | tool in `precommit` | financial operation |
|
|
145
|
+
| --- | --- | --- | --- |
|
|
146
|
+
| down, slow, or quota (429) | forwarded; the agent gets the real result and `log-pending`; the receipt waits in the outbox and is appended when the log answers again | not forwarded; the agent gets `Not executed` and `log-pending`; the `withheld` receipt waits in the outbox | the call returns an error and nothing is forwarded, because the authorization is not in the log; if only the receipt append fails after the forward, the call also returns an error, and `reconcile` finishes the operation |
|
|
147
|
+
| refusing | as above, but the outbox does not empty until the operator fixes the cause (a token, a quota, the pinned keys); the gateway prints the reason on each attempt | as above | as above |
|
|
148
|
+
|
|
149
|
+
The outbox is appended in the order of the signed statements' timestamps, oldest first. A log refusal stops the flush, so one receipt that the log refuses holds the receipts after it. `GET /health` on the HTTP gateway reports `pendingReceipts`. Only a gateway that serves (stdio, `--http`, `--a2a`) runs the flush, at start and every 30 seconds; `check`, `reconcile`, and the other commands never append the outbox. A gateway that stops waits for a flush that runs. A gateway that stops before the log takes the receipt keeps the outbox on disk and appends it on the next start. The gateway writes the outbox entry to disk, and syncs the file and its directory, before the agent gets the result.
|
|
150
|
+
|
|
151
|
+
Several gateways, or a gateway and a command, can share one `receipts/` directory. A flush takes the lock file `receipts/outbox/.lock` with an exclusive create. When another process holds the lock, the flush does nothing and reports the entries as `pending`. The gateway breaks a lock whose owner process no longer runs on this host, and a lock that nobody has touched for 15 minutes.
|
|
152
|
+
|
|
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.
|
|
139
154
|
|
|
140
155
|
**5. Run the gateway.** It speaks MCP on stdin/stdout and logs to stderr only.
|
|
141
156
|
|
|
@@ -347,6 +362,6 @@ The upstream can answer in kind. A result whose `_meta` carries `agent-custody/f
|
|
|
347
362
|
- **Money is integer minor units.** Cedar has no floating point. A float in `args` that a policy touches is an evaluation error, which is a deny.
|
|
348
363
|
- **The gateway key is the trust root for receipts.** Keep it out of the agent's reach. The upstream credentials in `upstream.env` are likewise never exposed to the agent.
|
|
349
364
|
- **Rotate keys by adding, not replacing.** The verifier accepts a list of gateway keys and principal keys and matches by keyid, so old receipts stay verifiable.
|
|
350
|
-
- **Evidence before the side effect, for the calls that matter.** Without `precommit`, a call is forwarded and then logged, and a log outage at that moment leaves an executed action
|
|
365
|
+
- **Evidence before the side effect, for the calls that matter.** Without `precommit`, a call is forwarded and then logged, and a log outage at that moment leaves an executed action whose receipt waits in the outbox until the log takes it (the agent gets the real result, marked `log-pending`). With `precommit`, the authorization is logged first and the call is withheld if that fails. The receipt of a withheld call shows `allow` next to `withheld`, so an auditor can tell a log outage from a denial.
|
|
351
366
|
- **The log is append-only by convention, not enforcement.** Copy it somewhere the operator cannot rewrite, on a schedule. The receipts' tree heads let an auditor check that the copy matches.
|
|
352
367
|
- **stdout is the MCP channel.** Anything the gateway prints goes to stderr. Do not add `console.log` to gateway code paths.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@agent-custody/receipts",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.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",
|