@agent-custody/receipts 0.6.12 → 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.
@@ -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; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agent-custody/receipts",
3
- "version": "0.6.12",
3
+ "version": "0.6.13",
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",