@agent-custody/receipts 0.6.11 → 0.6.13

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 CHANGED
@@ -47,7 +47,7 @@ const bundle = JSON.parse(readFileSync("receipts/<id>.json", "utf8"));
47
47
  verifyBundle(bundle, { issuerKeys: [loadPublicKey("keys/app.pub")], logFile: "log.jsonl" }).ok; // true
48
48
  ```
49
49
 
50
- Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the Vercel AI SDK and LangChain, are in [docs/sdk.md](docs/sdk.md). To enforce rather than record, put the gateway between the agent and its tools: `npx agent-custody gateway --config gateway.json`, set up in [docs/usage.md](docs/usage.md).
50
+ Framework hooks and adapters, including Claude Code, the OpenAI Agents SDK, the Vercel AI SDK and LangChain, are in [docs/sdk.md](docs/sdk.md). To enforce rather than record, put the gateway between the agent and its tools: `npx agent-custody gateway --config gateway.json`, set up in [docs/usage.md](docs/usage.md). The gateway is listed in the [MCP Registry](https://registry.modelcontextprotocol.io/) as `io.github.svayatta/agent-custody`; its entry is [server.json](server.json), published with `mcp-publisher publish` after each npm release.
51
51
 
52
52
  ## How it fits together
53
53
 
@@ -293,10 +293,10 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
293
293
  - An audit trail of administrative actions: every tenant created or disabled and every token minted or revoked is recorded with who did it, from the admin page or the command line, shown on the page and carried in the tenant's export.
294
294
  - A tenant's export: `log-export` takes, with the tenant's own token, every leaf hash, the signed head, the published keys, the checkpoints, and their usage, checks that they add up, and writes a log copy the verifier reads offline; the evidence never depends on the operator staying in business.
295
295
  - Monitoring and metering: `log-check`, the outside probe that verifies the head, the checkpoints, and the witness and exits 1 on trouble, run every ten minutes by the `monitor` workflow; `GET /health`; and usage per tenant per month on the admin page and as CSV.
296
- - The witness: a second signer on a machine the log's operator does not control countersigns each checkpoint after proving it extends the last one it signed, refuses a rewritten or forked history with an alarm, and publishes its key; `audit --witness-url` requires it. Phase 6 of [issue #6](https://github.com/ch4r10t33r/agent-custody/issues/6).
297
- - The signer, keys, and checkpoints: the key in its own process (`signer`, `--signer-url`), the key document at `/.well-known/agent-custody-log.json` fetched and pinned by `verify --log-url` and `audit --log-url`, and signed checkpoints per log published to a directory and a table for a verifier who was not watching. Phase 3 of [issue #6](https://github.com/ch4r10t33r/agent-custody/issues/6).
298
- - The log over Postgres: `log --db-env`, leaves as hashes in one table keyed by tenant, one writer per tenant by advisory lock, tenants and hashed tokens in tables managed by `log-admin`, rate limits and a body cap, retries in the sink, and `import` for an existing file log. Phase 2 of [issue #6](https://github.com/ch4r10t33r/agent-custody/issues/6).
299
- - A log for someone else: `hashOnly` sends leaf hashes so the log never holds a receipt; the reference server runs several tenant logs at `/t/<tenant>/` with their own tokens and ids; tree heads name their log and the verifier checks it with `--log-id`. Phase 1 of the hosted log, [issue #6](https://github.com/ch4r10t33r/agent-custody/issues/6).
296
+ - The witness: a second signer on a machine the log's operator does not control countersigns each checkpoint after proving it extends the last one it signed, refuses a rewritten or forked history with an alarm, and publishes its key; `audit --witness-url` requires it. Phase 6 of [issue #6](https://github.com/svayatta/agent-custody/issues/6).
297
+ - The signer, keys, and checkpoints: the key in its own process (`signer`, `--signer-url`), the key document at `/.well-known/agent-custody-log.json` fetched and pinned by `verify --log-url` and `audit --log-url`, and signed checkpoints per log published to a directory and a table for a verifier who was not watching. Phase 3 of [issue #6](https://github.com/svayatta/agent-custody/issues/6).
298
+ - The log over Postgres: `log --db-env`, leaves as hashes in one table keyed by tenant, one writer per tenant by advisory lock, tenants and hashed tokens in tables managed by `log-admin`, rate limits and a body cap, retries in the sink, and `import` for an existing file log. Phase 2 of [issue #6](https://github.com/svayatta/agent-custody/issues/6).
299
+ - A log for someone else: `hashOnly` sends leaf hashes so the log never holds a receipt; the reference server runs several tenant logs at `/t/<tenant>/` with their own tokens and ids; tree heads name their log and the verifier checks it with `--log-id`. Phase 1 of the hosted log, [issue #6](https://github.com/svayatta/agent-custody/issues/6).
300
300
  - OpenTelemetry export: with `otel` in either config, every receipt is also one span at the collector the team already runs, trace id equal to the receipt id, attributes for tool, agent, principal, status, decision, and log position; after the receipt, best effort, never on the evidence path.
301
301
  - Delegation chains for sub-agents: a grant that names the agent's key lets it delegate a narrower grant, with the parent embedded, up to three deep; the verifier and the gateway walk the chain to the principal, refusing any link that escalates scope, widens the window, changes the principal, or is signed by the wrong key; the receipt names the sub-agent and the principal and carries the chain. Pinned by the `gateway-chain-*` vectors and mirrored in the browser verifier.
302
302
  - One gateway for many agents: `gateway --http` serves the gateway over Streamable HTTP, one session per connection under the grant that connection presents, sessions sharing the upstreams and the policy and nothing else; a platform team runs one gateway in front of the tools instead of one process per agent.
@@ -306,8 +306,8 @@ The design is two producers feeding one verifier. The SDK is the top of the funn
306
306
 
307
307
  **Next, in the order it pays off**
308
308
 
309
- 1. Run the witness for log.agent-custody.dev on a machine and under an account that is not ours, and require it in the welcome sheet. The code is done; what it needs is a second operator. [Issue #6](https://github.com/ch4r10t33r/agent-custody/issues/6).
310
- 2. Post-quantum signatures: ML-DSA beside Ed25519 in the same DSSE envelope, hybrid by default when a PQ key is present, in every signed artefact and in the browser verifier. [Issue #11](https://github.com/ch4r10t33r/agent-custody/issues/11).
309
+ 1. Run the witness for log.agent-custody.dev on a machine and under an account that is not ours, and require it in the welcome sheet. The code is done; what it needs is a second operator. [Issue #6](https://github.com/svayatta/agent-custody/issues/6).
310
+ 2. Post-quantum signatures: ML-DSA beside Ed25519 in the same DSSE envelope, hybrid by default when a PQ key is present, in every signed artefact and in the browser verifier. [Issue #11](https://github.com/svayatta/agent-custody/issues/11).
311
311
  3. Receiver-attested receipts for agent-to-agent calls.
312
312
  4. A TEE-hosted signer, then SD-JWT redaction, then ZK proofs of policy compliance. Not before.
313
313
 
@@ -17,6 +17,8 @@ export interface ExportResult {
17
17
  checkpoints: number;
18
18
  /** administrative actions on this tenant: tokens minted and revoked, the tenant created or disabled, by whom */
19
19
  audit: number;
20
+ /** policy versions the tenant published, each with its text and the digest receipts carry */
21
+ policies: number;
20
22
  usage: {
21
23
  month: string;
22
24
  appends: number;
@@ -68,6 +68,13 @@ export async function exportLog(o) {
68
68
  catch (e) {
69
69
  problems.push(`audit trail: ${e instanceof Error ? e.message : String(e)}`);
70
70
  }
71
+ let policies = [];
72
+ try {
73
+ policies = (await get(path("policies"), true)).policies;
74
+ }
75
+ catch (e) {
76
+ problems.push(`policies: ${e instanceof Error ? e.message : String(e)}`);
77
+ }
71
78
  mkdirSync(o.outDir, { recursive: true });
72
79
  writeFileSync(join(o.outDir, "log.jsonl"), leaves.map((h) => JSON.stringify({ hash: h })).join("\n") + (leaves.length ? "\n" : ""));
73
80
  writeFileSync(join(o.outDir, "head.json"), JSON.stringify({ treeHead, ...head }, null, 2));
@@ -75,14 +82,15 @@ export async function exportLog(o) {
75
82
  writeFileSync(join(o.outDir, "checkpoints.json"), JSON.stringify(cps.checkpoints, null, 2));
76
83
  writeFileSync(join(o.outDir, "usage.json"), JSON.stringify(usage, null, 2));
77
84
  writeFileSync(join(o.outDir, "audit.json"), JSON.stringify(audit, null, 2));
78
- const result = { outDir: o.outDir, logId: head.log ?? null, treeSize: head.treeSize, rootHash: head.rootHash, keyid: v.keyid, checkpoints: cps.checkpoints.length, audit: audit.length, usage, problems };
85
+ writeFileSync(join(o.outDir, "policies.json"), JSON.stringify(policies, null, 2));
86
+ const result = { outDir: o.outDir, logId: head.log ?? null, treeSize: head.treeSize, rootHash: head.rootHash, keyid: v.keyid, checkpoints: cps.checkpoints.length, audit: audit.length, policies: policies.length, usage, problems };
79
87
  writeFileSync(join(o.outDir, "export.json"), JSON.stringify({ exportedAt: new Date().toISOString(), logUrl: base, tenant: o.tenant ?? null, ...result }, null, 2));
80
88
  return result;
81
89
  }
82
90
  export function formatExport(r) {
83
91
  const lines = [
84
92
  `exported ${r.treeSize} leaf hash(es) of log ${r.logId ?? "(unnamed)"} to ${r.outDir}`,
85
- `head root ${r.rootHash.slice(0, 16)}, signed by ${r.keyid.slice(0, 12)}, ${r.checkpoints} checkpoint(s), ${r.audit} administrative action(s) on this tenant`,
93
+ `head root ${r.rootHash.slice(0, 16)}, signed by ${r.keyid.slice(0, 12)}, ${r.checkpoints} checkpoint(s), ${r.audit} administrative action(s) on this tenant, ${r.policies} published policy version(s)`,
86
94
  ...r.usage.map((u) => `usage ${u.month}: ${u.appends} append(s), ${u.totalLeaves} leaves in total, ${u.liveTokens} live token(s)`),
87
95
  "",
88
96
  "log.jsonl is a log copy the verifier reads: agent-custody verify <receipt> --log <outDir>/log.jsonl --issuer-key ...",
@@ -1,7 +1,7 @@
1
1
  import { type IncomingMessage, type ServerResponse } from "node:http";
2
2
  import { type Envelope, type KeyPair } from "./crypto.ts";
3
3
  import { type InclusionProof } from "./log.ts";
4
- import { type AuditEntry, type QuotaState, type LogBackend, type PostgresTenancy, type RateLimitOptions } from "./log-store.ts";
4
+ import { type AuditEntry, type QuotaState, type LogBackend, type PostgresTenancy, type RateLimitOptions, type PolicyRecord } from "./log-store.ts";
5
5
  import { type Signer } from "./signer.ts";
6
6
  import type { Checkpoint, CheckpointStore } from "./checkpoints.ts";
7
7
  import { type AdminOptions } from "./log-admin.ts";
@@ -102,6 +102,10 @@ export interface ResolvedLog {
102
102
  quota?(): Promise<QuotaState>;
103
103
  /** told after an append lands, so a cached quota count stays honest */
104
104
  appended?(): void;
105
+ /** the policy versions the tenant published, with their text, for the export */
106
+ policies?: () => Promise<PolicyRecord[] & {
107
+ text?: string;
108
+ }[]>;
105
109
  }
106
110
  /** Turns the tenant in a path, or null for the root paths, into a log. */
107
111
  export interface LogResolver {
package/dist/log-sink.js CHANGED
@@ -160,6 +160,7 @@ export function postgresResolver(tenancy, opts = {}) {
160
160
  return { month, appends: row?.appends ?? 0, totalLeaves: row?.totalLeaves ?? 0, liveTokens: row?.liveTokens ?? 0 };
161
161
  },
162
162
  audit: (limit) => tenancy.audit({ tenant: id, limit }),
163
+ policies: async () => Promise.all((await tenancy.listPolicies(id)).map(async (p) => ({ ...p, text: (await tenancy.policy(id, p.id))?.text }))),
163
164
  quota: () => tenancy.quota(id),
164
165
  appended: () => tenancy.noteAppend(id),
165
166
  };
@@ -280,7 +281,7 @@ export function logHandler(source, keyOrSigner, opts = {}) {
280
281
  }
281
282
  }
282
283
  // /t/<tenant>/<op> reaches that tenant's log; anything else is the default log.
283
- const m = /^\/t\/([A-Za-z0-9_.-]+)\/(append|root|consistency|head|checkpoints|leaves|usage|audit)$/.exec(url.pathname);
284
+ const m = /^\/t\/([A-Za-z0-9_.-]+)\/(append|root|consistency|head|checkpoints|leaves|usage|audit|policies)$/.exec(url.pathname);
284
285
  let which;
285
286
  try {
286
287
  which = await resolver.resolve(m ? m[1] : null);
@@ -340,9 +341,14 @@ export function logHandler(source, keyOrSigner, opts = {}) {
340
341
  const current = await log.size();
341
342
  // A tenant's own data, with their token: every leaf hash, in pages, and their metering. The export command
342
343
  // pages through these and rebuilds a log file the verifier reads directly.
343
- if (req.method === "GET" && (url.pathname.endsWith("/leaves") || url.pathname.endsWith("/usage") || url.pathname.endsWith("/audit"))) {
344
+ if (req.method === "GET" && (url.pathname.endsWith("/leaves") || url.pathname.endsWith("/usage") || url.pathname.endsWith("/audit") || url.pathname.endsWith("/policies"))) {
344
345
  if (!(await which.authorize(bearer(req))))
345
346
  return json(401, { error: "unauthorized" });
347
+ if (url.pathname.endsWith("/policies")) {
348
+ if (!which.policies)
349
+ return json(404, { error: "this log keeps no policies" });
350
+ return json(200, { policies: await which.policies() }, { "cache-control": "no-store" });
351
+ }
346
352
  if (url.pathname.endsWith("/audit")) {
347
353
  if (!which.audit)
348
354
  return json(404, { error: "this log keeps no audit trail" });
@@ -88,10 +88,20 @@ export interface AuditEntry {
88
88
  id: number;
89
89
  at: string;
90
90
  actor: string;
91
- action: "tenant.add" | "tenant.disable" | "tenant.plan" | "token.add" | "token.revoke";
91
+ action: "tenant.add" | "tenant.disable" | "tenant.plan" | "token.add" | "token.revoke" | "policy.add" | "policy.remove";
92
92
  tenantId: string | null;
93
93
  detail: Record<string, unknown>;
94
94
  }
95
+ /** A policy version a tenant published: a name for the digest that receipts carry. Never read by the gateway. */
96
+ export interface PolicyRecord {
97
+ id: string;
98
+ tenantId: string;
99
+ name: string;
100
+ digest: string;
101
+ bytes: number;
102
+ createdAt: string;
103
+ createdBy: string;
104
+ }
95
105
  /** Tenants and their tokens, in Postgres. Tokens are stored hashed; a lookup hashes what the caller presented. */
96
106
  export declare class PostgresTenancy {
97
107
  private readonly client;
@@ -153,6 +163,21 @@ export declare class PostgresTenancy {
153
163
  disabled: boolean;
154
164
  }[];
155
165
  }>;
166
+ /**
167
+ * Publish a policy version under a name. The digest is the same sha256 of the text the gateway writes into every
168
+ * receipt as policyDigest, so the text must be byte-for-byte the file the gateway loads. The same text twice is
169
+ * refused, naming the version it already is.
170
+ */
171
+ addPolicy(tenantId: string, name: string, text: string, by?: string): Promise<PolicyRecord>;
172
+ listPolicies(tenantId: string): Promise<PolicyRecord[]>;
173
+ /** one version with its text */
174
+ policy(tenantId: string, id: string): Promise<(PolicyRecord & {
175
+ text: string;
176
+ }) | null>;
177
+ /** the version a receipt's policyDigest names, if the tenant published it */
178
+ policyByDigest(tenantId: string, digest: string): Promise<PolicyRecord | null>;
179
+ removePolicy(tenantId: string, id: string, by?: string): Promise<boolean>;
180
+ private policyRow;
156
181
  listTokens(tenantId: string): Promise<TokenRecord[]>;
157
182
  }
158
183
  /**
package/dist/log-store.js CHANGED
@@ -3,6 +3,7 @@
3
3
  // writer per tenant enforced by an advisory lock so a second instance is safe, tenants and their tokens in tables of
4
4
  // their own, and rate limits per token. The subtree cache stays in memory on every instance and resyncs from the
5
5
  // table whenever the table has moved on without it.
6
+ import { sha256Hex } from "./crypto.js";
6
7
  import { createHash, randomBytes } from "node:crypto";
7
8
  import { readFileSync } from "node:fs";
8
9
  import { leafHash, MerkleLog, SubtreeCache } from "./log.js";
@@ -197,6 +198,8 @@ export class PostgresTenancy {
197
198
  await this.client.query(`ALTER TABLE ${p}tenants ADD COLUMN IF NOT EXISTS plan TEXT NOT NULL DEFAULT 'free'`);
198
199
  await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}tokens (token_hash TEXT PRIMARY KEY, tenant_id TEXT NOT NULL REFERENCES ${p}tenants(id), label TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), revoked_at TIMESTAMPTZ)`);
199
200
  await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}audit (id BIGSERIAL PRIMARY KEY, at TIMESTAMPTZ NOT NULL DEFAULT now(), actor TEXT NOT NULL, action TEXT NOT NULL, tenant_id TEXT, detail JSONB NOT NULL DEFAULT '{}')`);
201
+ // named policy versions a tenant chose to publish, so a receipt's policy digest can be read as a name; enforcement never reads this table
202
+ await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}policies (id TEXT PRIMARY KEY, tenant_id TEXT NOT NULL REFERENCES ${p}tenants(id), name TEXT NOT NULL, digest TEXT NOT NULL, text TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), created_by TEXT NOT NULL, UNIQUE (tenant_id, digest))`);
200
203
  })();
201
204
  }
202
205
  return this.ready;
@@ -350,6 +353,51 @@ export class PostgresTenancy {
350
353
  FROM ${p}tenants t ORDER BY t.created_at`, [start, end])).rows;
351
354
  return { month, tenants: rows.map((r) => { const plan = PLANS.includes(String(r.plan)) ? String(r.plan) : "free"; return { id: String(r.id), logId: String(r.log_id), plan, quota: this.quotas[plan], appends: Number(r.appends), totalLeaves: Number(r.total), liveTokens: Number(r.live), disabled: !!r.disabled_at }; }) };
352
355
  }
356
+ /**
357
+ * Publish a policy version under a name. The digest is the same sha256 of the text the gateway writes into every
358
+ * receipt as policyDigest, so the text must be byte-for-byte the file the gateway loads. The same text twice is
359
+ * refused, naming the version it already is.
360
+ */
361
+ async addPolicy(tenantId, name, text, by) {
362
+ await this.init();
363
+ if (!(await this.tenant(tenantId)))
364
+ throw new Error(`unknown tenant ${tenantId}`);
365
+ const digest = sha256Hex(text);
366
+ const dup = await this.policyByDigest(tenantId, digest);
367
+ if (dup)
368
+ throw new Error(`this exact policy text is already published as "${dup.name}" (${dup.digest.slice(0, 12)})`);
369
+ const id = `pol_${sha256Hex(`${tenantId}\n${digest}\n${Date.now()}`).slice(0, 16)}`;
370
+ const rows = (await this.client.query(`INSERT INTO ${this.prefix}policies (id, tenant_id, name, digest, text, created_by) VALUES ($1, $2, $3, $4, $5, $6) RETURNING id, tenant_id, name, digest, length(text) AS bytes, created_at, created_by`, [id, tenantId, name, digest, text, by ?? "unattributed"])).rows;
371
+ await this.record(by, "policy.add", tenantId, { policy: id, name, digest });
372
+ return this.policyRow(rows[0]);
373
+ }
374
+ async listPolicies(tenantId) {
375
+ await this.init();
376
+ return (await this.client.query(`SELECT id, tenant_id, name, digest, octet_length(text) AS bytes, created_at, created_by FROM ${this.prefix}policies WHERE tenant_id = $1 ORDER BY created_at DESC`, [tenantId])).rows.map((r) => this.policyRow(r));
377
+ }
378
+ /** one version with its text */
379
+ async policy(tenantId, id) {
380
+ await this.init();
381
+ const rows = (await this.client.query(`SELECT id, tenant_id, name, digest, octet_length(text) AS bytes, created_at, created_by, text FROM ${this.prefix}policies WHERE tenant_id = $1 AND id = $2`, [tenantId, id])).rows;
382
+ return rows[0] ? { ...this.policyRow(rows[0]), text: String(rows[0].text) } : null;
383
+ }
384
+ /** the version a receipt's policyDigest names, if the tenant published it */
385
+ async policyByDigest(tenantId, digest) {
386
+ await this.init();
387
+ const rows = (await this.client.query(`SELECT id, tenant_id, name, digest, octet_length(text) AS bytes, created_at, created_by FROM ${this.prefix}policies WHERE tenant_id = $1 AND digest = $2`, [tenantId, digest.toLowerCase()])).rows;
388
+ return rows[0] ? this.policyRow(rows[0]) : null;
389
+ }
390
+ async removePolicy(tenantId, id, by) {
391
+ await this.init();
392
+ const rows = (await this.client.query(`DELETE FROM ${this.prefix}policies WHERE tenant_id = $1 AND id = $2 RETURNING name, digest`, [tenantId, id])).rows;
393
+ if (!rows[0])
394
+ return false;
395
+ await this.record(by, "policy.remove", tenantId, { policy: id, name: rows[0].name, digest: rows[0].digest });
396
+ return true;
397
+ }
398
+ policyRow(r) {
399
+ return { id: String(r.id), tenantId: String(r.tenant_id), name: String(r.name), digest: String(r.digest), bytes: Number(r.bytes), createdAt: new Date(r.created_at).toISOString(), createdBy: String(r.created_by) };
400
+ }
353
401
  async listTokens(tenantId) {
354
402
  await this.init();
355
403
  return (await this.client.query(`SELECT tenant_id, label, token_hash, created_at, revoked_at FROM ${this.prefix}tokens WHERE tenant_id = $1 ORDER BY created_at`, [tenantId])).rows.map((r) => ({ tenantId: String(r.tenant_id), label: String(r.label), tokenHash: String(r.token_hash), createdAt: new Date(r.created_at).toISOString(), revokedAt: r.revoked_at ? new Date(r.revoked_at).toISOString() : null }));
package/dist/portal.js CHANGED
@@ -381,6 +381,43 @@ export function portalHandler(o) {
381
381
  await jsonBody();
382
382
  return json(200, { revoked: await o.tenancy.revokeToken(tenantId, revoke[1], `portal:${user.email}`) });
383
383
  }
384
+ // Policies: named versions the tenant publishes so a receipt's policyDigest reads as a name. The gateway never
385
+ // reads these; enforcement stays on the tenant's machines.
386
+ if (req.method === "GET" && url.pathname === "/api/policies") {
387
+ const digest = url.searchParams.get("digest");
388
+ if (digest !== null) {
389
+ if (!/^[0-9a-f]{64}$/i.test(digest))
390
+ return json(400, { error: "a policy digest is 64 hexadecimal characters, the policyDigest a receipt carries" });
391
+ return json(200, { match: await o.tenancy.policyByDigest(tenantId, digest) });
392
+ }
393
+ return json(200, { policies: await o.tenancy.listPolicies(tenantId) });
394
+ }
395
+ if (req.method === "POST" && url.pathname === "/api/policies") {
396
+ const b = await jsonBody();
397
+ const name = String(b.name ?? "").trim().slice(0, 80);
398
+ const text = typeof b.text === "string" ? b.text : "";
399
+ if (!name)
400
+ return json(400, { error: "a name for this version is needed, for example refunds-v3 or 2026-10-01" });
401
+ if (!text.trim())
402
+ return json(400, { error: "the policy text is empty" });
403
+ if (text.length > 256_000)
404
+ return json(400, { error: "a policy is at most 256 KB" });
405
+ try {
406
+ return json(200, { policy: await o.tenancy.addPolicy(tenantId, name, text, `portal:${user.email}`) });
407
+ }
408
+ catch (e) {
409
+ return json(409, { error: e instanceof Error ? e.message : String(e) });
410
+ }
411
+ }
412
+ const pol = /^\/api\/policies\/(pol_[0-9a-f]{16})(\/remove)?$/.exec(url.pathname);
413
+ if (req.method === "GET" && pol && !pol[2]) {
414
+ const p = await o.tenancy.policy(tenantId, pol[1]);
415
+ return p ? json(200, { policy: p }) : json(404, { error: "no such policy version" });
416
+ }
417
+ if (req.method === "POST" && pol && pol[2]) {
418
+ await jsonBody();
419
+ return json(200, { removed: await o.tenancy.removePolicy(tenantId, pol[1], `portal:${user.email}`) });
420
+ }
384
421
  if (req.method === "POST" && url.pathname === "/api/checkout") {
385
422
  if (!o.stripe)
386
423
  return json(503, { error: "billing is not configured on this portal yet; email us and we move the plan by hand" });
@@ -465,6 +502,7 @@ const PORTAL_PAGE = `<!doctype html>
465
502
  .bar b { font-family: var(--mono); font-weight: 400; margin-top: .3rem; }
466
503
  label { display: grid; gap: .25rem; font-size: .85rem; color: var(--ink2); margin: 0 0 .8rem; }
467
504
  label .opt { font-size: .72rem; text-transform: uppercase; letter-spacing: .06em; margin-left: .3rem; } label .hint { font-size: .8rem; line-height: 1.45; } label .hint code { font-family: var(--mono); font-size: .9em; }
505
+ textarea { font: .86rem/1.5 var(--mono); padding: .5rem .6rem; border: 1px solid var(--line); border-radius: 4px; background: var(--bg); color: var(--ink); width: 100%; box-sizing: border-box; }
468
506
  input, select { font: inherit; padding: .5rem .6rem; border: 1px solid var(--line); border-radius: 4px; background: var(--bg); color: var(--ink); }
469
507
  button { font: inherit; padding: .5rem .9rem; border-radius: 4px; border: 1px solid var(--accent); background: var(--accent); color: #fff; cursor: pointer; }
470
508
  button.quiet { background: transparent; color: var(--accent); }
@@ -521,6 +559,7 @@ const PORTAL_PAGE = `<!doctype html>
521
559
  <div class="group">Configure</div>
522
560
  <a href="#setup" data-view="setup">Setup</a>
523
561
  <a href="#keys" data-view="keys">API keys <span class="n" id="nKeys"></span></a>
562
+ <a href="#policies" data-view="policies">Policies <span class="n" id="nPolicies"></span></a>
524
563
  <a href="#billing" data-view="billing">Billing</a>
525
564
  <a href="#export" data-view="export">Export</a>
526
565
  <div class="group">Account</div>
@@ -554,6 +593,15 @@ const PORTAL_PAGE = `<!doctype html>
554
593
  <table style="margin-top:1rem"><thead><tr><th>label</th><th>hash</th><th>created</th><th>state</th><th></th></tr></thead><tbody id="keys"></tbody></table></div>
555
594
  <p class="msg" id="keysMsg"></p>
556
595
  </div>
596
+ <div data-pane="policies" hidden>
597
+ <h1>Policies</h1>
598
+ <p class="muted">Enforcement stays on your machines: the gateway reads its Cedar file locally and writes the file's SHA-256 into every receipt as <code>policyDigest</code>. This page gives those digests names. Publish each version you deploy, byte for byte as the gateway loads it, and a receipt's digest reads as "refunds-v3" instead of a hash, here and in your export. We never evaluate a policy and nothing here is read by the gateway.</p>
599
+ <div class="panel"><form id="policyForm"><label>Name for this version<input id="policyName" placeholder="refunds-v3" maxlength="80" required></label><label>Policy text, exactly as the gateway's file<textarea id="policyText" rows="8" spellcheck="false" placeholder="permit(principal, action == Action::&quot;stripe.refund&quot;, resource) when { context.args.amount <= 100000 };" required></textarea></label><button type="submit">Publish version</button> <span class="muted" id="policyDigestPreview"></span></form></div>
600
+ <div class="panel"><h2>Match a receipt</h2><p class="muted">Paste a receipt file, or just its <code>policyDigest</code>, to see which published version decided it.</p><form id="matchForm"><label>Receipt JSON or digest<textarea id="matchIn" rows="3" spellcheck="false"></textarea></label><button type="submit" class="quiet">Match</button></form><p class="msg" id="matchOut"></p></div>
601
+ <div class="panel"><table><thead><tr><th>name</th><th>digest</th><th>bytes</th><th>published</th><th>by</th><th></th></tr></thead><tbody id="policies"></tbody></table></div>
602
+ <div class="panel" id="policyView" hidden><h2 id="policyViewName"></h2><pre id="policyViewText"></pre></div>
603
+ <p class="msg" id="policiesMsg"></p>
604
+ </div>
557
605
  <div data-pane="billing" hidden>
558
606
  <h1>Billing</h1>
559
607
  <div class="panel" id="billingPanel"></div>
@@ -653,11 +701,36 @@ const PORTAL_PAGE = `<!doctype html>
653
701
  const up = $("upgrade"); if (up) up.onclick = async () => { try { const r = await api("POST", "/api/checkout", {}); location.href = r.url; } catch (err) { $("billingMsg").className = "msg err"; $("billingMsg").textContent = err.message; } };
654
702
  const mg = $("manage"); if (mg) mg.onclick = async () => { try { const r = await api("POST", "/api/billing-portal", {}); location.href = r.url; } catch (err) { $("billingMsg").className = "msg err"; $("billingMsg").textContent = err.message; } };
655
703
  };
656
- const load = async () => render(await api("GET", "/api/overview"));
704
+ const load = async () => { render(await api("GET", "/api/overview")); await loadPolicies(); };
657
705
  const enter = async () => {
658
706
  try { const me = await api("GET", "/api/me"); $("who").textContent = me.email; show("app"); await load(); view((location.hash || "#overview").slice(1) || "overview"); }
659
707
  catch (err) { if (err.status === 401) { show("auth"); if (location.hash === "#register" && !registering) $("authSwap").click(); } else { show("app"); $("who").textContent = err.message; } }
660
708
  };
709
+ const sha256hex = async (text) => [...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))].map((b) => b.toString(16).padStart(2, "0")).join("");
710
+ const loadPolicies = async () => {
711
+ const r = await api("GET", "/api/policies");
712
+ $("nPolicies").textContent = r.policies.length || "";
713
+ $("policies").innerHTML = r.policies.map((p) => "<tr><td>" + esc(p.name) + "</td><td class=mono>" + esc(p.digest.slice(0, 16)) + "…</td><td>" + p.bytes + "</td><td>" + esc(p.createdAt.slice(0, 10)) + "</td><td class=mono>" + esc(p.createdBy.replace(/^portal:/, "")) + "</td><td><button class=link data-viewpol=\\"" + esc(p.id) + "\\">View</button> <button class=link data-rmpol=\\"" + esc(p.id) + "\\">Remove</button></td></tr>").join("") || "<tr><td colspan=6 class=muted>No versions published yet. Receipts keep their digests either way; a name is for the people reading them.</td></tr>";
714
+ };
715
+ $("policyText").oninput = async () => { const t = $("policyText").value; $("policyDigestPreview").textContent = t ? "sha256 " + (await sha256hex(t)).slice(0, 16) + "…" : ""; };
716
+ $("policyForm").onsubmit = async (e) => {
717
+ e.preventDefault(); $("policiesMsg").className = "msg";
718
+ try { const r = await api("POST", "/api/policies", { name: $("policyName").value, text: $("policyText").value }); $("policiesMsg").className = "msg ok"; $("policiesMsg").textContent = "Published " + r.policy.name + " as " + r.policy.digest.slice(0, 16) + "…"; $("policyName").value = ""; $("policyText").value = ""; $("policyDigestPreview").textContent = ""; await loadPolicies(); }
719
+ catch (err) { $("policiesMsg").className = "msg err"; $("policiesMsg").textContent = err.message; }
720
+ };
721
+ $("matchForm").onsubmit = async (e) => {
722
+ e.preventDefault(); $("matchOut").className = "msg";
723
+ try {
724
+ const raw = $("matchIn").value.trim(); let digest = raw;
725
+ if (!/^[0-9a-f]{64}$/i.test(raw)) { const b = JSON.parse(raw); const payload = b.envelope ? b.envelope.payload : b.payload; const st = JSON.parse(atob(payload)); digest = st.predicate && st.predicate.policy ? st.predicate.policy.policyDigest : ""; if (!digest) throw new Error("this receipt carries no policy decision"); }
726
+ const r = await api("GET", "/api/policies?digest=" + encodeURIComponent(digest));
727
+ $("matchOut").className = r.match ? "msg ok" : "msg"; $("matchOut").textContent = r.match ? "Decided by \\"" + r.match.name + "\\", published " + r.match.createdAt.slice(0, 10) + " (" + digest.slice(0, 16) + "…)" : "No published version has digest " + digest.slice(0, 16) + "…; publish the file the gateway loaded to name it.";
728
+ } catch (err) { $("matchOut").className = "msg err"; $("matchOut").textContent = err.message; }
729
+ };
730
+ document.addEventListener("click", async (e) => {
731
+ const v = e.target.closest("button[data-viewpol]"); if (v) { try { const r = await api("GET", "/api/policies/" + v.dataset.viewpol); $("policyViewName").textContent = r.policy.name + " · " + r.policy.digest; $("policyViewText").textContent = r.policy.text; $("policyView").hidden = false; } catch (err) { $("policiesMsg").className = "msg err"; $("policiesMsg").textContent = err.message; } return; }
732
+ const rm = e.target.closest("button[data-rmpol]"); if (rm && confirm("Remove this published version? Receipts keep their digests; only the name goes.")) { try { await api("POST", "/api/policies/" + rm.dataset.rmpol + "/remove", {}); $("policyView").hidden = true; await loadPolicies(); } catch (err) { $("policiesMsg").className = "msg err"; $("policiesMsg").textContent = err.message; } }
733
+ });
661
734
  $("mintForm").onsubmit = async (e) => { e.preventDefault(); try { const r = await api("POST", "/api/keys", { label: $("label").value }); $("mintedTok").textContent = r.token; $("minted").hidden = false; $("keysMsg").className = "msg ok"; $("keysMsg").textContent = "minted " + r.label + ", stored as hash " + r.tokenHash; await load(); } catch (err) { $("keysMsg").className = "msg err"; $("keysMsg").textContent = err.message; } };
662
735
  $("copyMinted").onclick = () => navigator.clipboard.writeText($("mintedTok").textContent);
663
736
  document.addEventListener("click", async (e) => { const b = e.target.closest("button[data-revoke]"); if (!b) return; if (!confirm("Revoke key " + b.dataset.revoke + "? A gateway using it stops appending at once.")) return; try { await api("POST", "/api/keys/" + b.dataset.revoke + "/revoke", {}); $("keysMsg").className = "msg ok"; $("keysMsg").textContent = "revoked"; await load(); } catch (err) { $("keysMsg").className = "msg err"; $("keysMsg").textContent = err.message; } });
@@ -23,7 +23,7 @@ Everything below asks who could make that claim false, and what stops them.
23
23
 
24
24
  ## What the design assumes
25
25
 
26
- - Ed25519 signatures and SHA-256 are sound. Post-quantum signatures are [issue #11](https://github.com/ch4r10t33r/agent-custody/issues/11), not present.
26
+ - Ed25519 signatures and SHA-256 are sound. Post-quantum signatures are [issue #11](https://github.com/svayatta/agent-custody/issues/11), not present.
27
27
  - Private keys stay private to their holder. Key custody is the holder's problem; the packages read keys from files or a signer process and never transmit them.
28
28
  - The gateway runs where the agent cannot read its key or its receipts directory. A gateway in the agent's own container, with the key readable by the agent, is an SDK with extra steps and the receipts it produces are worth exactly that.
29
29
  - Clocks are roughly right. Timestamps in receipts are the producer's; the log's checkpoint times and the witness's countersignature times are the only times a verifier can hold anyone to.
package/package.json CHANGED
@@ -1,11 +1,12 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.6.11",
3
+ "version": "0.6.13",
4
+ "mcpName": "io.github.svayatta/agent-custody",
4
5
  "description": "Chain of custody for AI agents: signed, independently verifiable receipts for tool calls. MCP gateway + Cedar policy + Merkle transparency log",
5
6
  "license": "Apache-2.0",
6
7
  "repository": {
7
8
  "type": "git",
8
- "url": "git+https://github.com/ch4r10t33r/agent-custody.git",
9
+ "url": "git+https://github.com/svayatta/agent-custody.git",
9
10
  "directory": "packages/receipts"
10
11
  },
11
12
  "publishConfig": {