@agent-custody/receipts 0.6.12 → 0.6.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -267,9 +267,24 @@ async function main(argv) {
267
267
  return 0;
268
268
  }
269
269
  case "portal": {
270
- const { values } = parseArgs({ args: rest, options: { "db-env": { type: "string" }, "secret-env": { type: "string" }, "public-url": { type: "string" }, "checkpoints-url": { type: "string" }, "portal-url": { type: "string" }, port: { type: "string", default: "8792" }, host: { type: "string", default: "127.0.0.1" }, "stripe-key-env": { type: "string" }, "stripe-webhook-env": { type: "string" }, "stripe-price-team": { type: "string" }, "mail-key-env": { type: "string" }, "mail-from": { type: "string" }, "mail-notify": { type: "string" }, "trust-proxy": { type: "boolean", default: false } } });
270
+ const { values } = parseArgs({ args: rest, options: { "db-env": { type: "string" }, "secret-env": { type: "string" }, "public-url": { type: "string" }, "checkpoints-url": { type: "string" }, "portal-url": { type: "string" }, port: { type: "string", default: "8792" }, host: { type: "string", default: "127.0.0.1" }, "stripe-key-env": { type: "string" }, "stripe-webhook-env": { type: "string" }, "stripe-price-team": { type: "string" }, "mail-key-env": { type: "string" }, "mail-from": { type: "string" }, "mail-notify": { type: "string" }, "github-client-id": { type: "string" }, "github-secret-env": { type: "string" }, "google-client-id": { type: "string" }, "google-secret-env": { type: "string" }, "trust-proxy": { type: "boolean", default: false } } });
271
271
  if (!values["db-env"] || !values["secret-env"] || !values["public-url"])
272
272
  throw new Error("portal needs --db-env, --secret-env, and --public-url");
273
+ let oauth;
274
+ for (const p of ["github", "google"]) {
275
+ const id = values[`${p}-client-id`];
276
+ const env = values[`${p}-secret-env`];
277
+ if (!id && !env)
278
+ continue;
279
+ if (!id || !env)
280
+ throw new Error(`${p} sign-in needs both --${p}-client-id and --${p}-secret-env`);
281
+ const clientSecret = process.env[env];
282
+ if (!clientSecret)
283
+ throw new Error(`portal: environment variable ${env} is not set`);
284
+ if (!values["portal-url"])
285
+ throw new Error("provider sign-in needs --portal-url, the callback is built from it");
286
+ oauth = { ...(oauth ?? {}), [p]: { clientId: id, clientSecret } };
287
+ }
273
288
  let mail;
274
289
  if (values["mail-key-env"] || values["mail-from"]) {
275
290
  if (!values["mail-key-env"] || !values["mail-from"])
@@ -301,7 +316,7 @@ async function main(argv) {
301
316
  catch {
302
317
  // the log may not be reachable from here at start; the sheet then omits the keyid
303
318
  }
304
- const running = await servePortal({ tenancy, client, secret, publicUrl: values["public-url"], ...(values["checkpoints-url"] ? { checkpointsUrl: values["checkpoints-url"] } : {}), ...(values["portal-url"] ? { portalUrl: values["portal-url"] } : {}), ...(keyid ? { keyid } : {}), ...(stripe ? { stripe } : {}), ...(mail ? { mail } : {}), trustProxy: values["trust-proxy"] }, { port: Number(values.port), host: values.host });
319
+ const running = await servePortal({ tenancy, client, secret, publicUrl: values["public-url"], ...(values["checkpoints-url"] ? { checkpointsUrl: values["checkpoints-url"] } : {}), ...(values["portal-url"] ? { portalUrl: values["portal-url"] } : {}), ...(keyid ? { keyid } : {}), ...(stripe ? { stripe } : {}), ...(mail ? { mail } : {}), ...(oauth ? { oauth } : {}), trustProxy: values["trust-proxy"] }, { port: Number(values.port), host: values.host });
305
320
  console.error(`agent-custody portal: ${running.url} log=${values["public-url"]} billing=${stripe ? "stripe" : "off"}${values["trust-proxy"] ? " trust-proxy" : ""}`);
306
321
  await new Promise((resolve) => process.once("SIGINT", resolve));
307
322
  await running.close();
package/dist/index.d.ts CHANGED
@@ -6,7 +6,7 @@ export { openExporter, otlpExporter, spanFor } from "./otel.ts";
6
6
  export { hecEvent, splunkExporter } from "./splunk.ts";
7
7
  export { GRANT_HEADER, grantHeader, parseGrantHeader, serveHttp } from "./gateway-http.ts";
8
8
  export { PortalStore, portalHandler, readSession, servePortal, signSession, stripeRequest, verifyStripeSignature } from "./portal.ts";
9
- export type { MailOptions, PortalOptions, PortalUser, Profile, RunningPortal, StripeOptions } from "./portal.ts";
9
+ export type { MailOptions, OAuthOptions, PortalOptions, PortalUser, Profile, RunningPortal, StripeOptions } from "./portal.ts";
10
10
  export type { HttpGatewayOptions, RunningHttpGateway } from "./gateway-http.ts";
11
11
  export { exportLog, formatExport } from "./log-export.ts";
12
12
  export type { ExportOptions, ExportResult } from "./log-export.ts";
@@ -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.d.ts CHANGED
@@ -18,6 +18,18 @@ export interface MailOptions {
18
18
  url?: string;
19
19
  fetch?: typeof fetch;
20
20
  }
21
+ /** Sign in through GitHub or Google: the OAuth web flow over fetch, no library. The callback is `<portalUrl>auth/<provider>/callback`. */
22
+ export interface OAuthOptions {
23
+ github?: {
24
+ clientId: string;
25
+ clientSecret: string;
26
+ };
27
+ google?: {
28
+ clientId: string;
29
+ clientSecret: string;
30
+ };
31
+ fetch?: typeof fetch;
32
+ }
21
33
  export interface PortalOptions {
22
34
  tenancy: PostgresTenancy;
23
35
  /** the Postgres client the tenancy uses; the portal's own tables live beside the log's */
@@ -33,6 +45,7 @@ export interface PortalOptions {
33
45
  portalUrl?: string;
34
46
  stripe?: StripeOptions;
35
47
  mail?: MailOptions;
48
+ oauth?: OAuthOptions;
36
49
  /** key throttles by X-Forwarded-For; only behind a proxy you run. Also marks cookies Secure. */
37
50
  trustProxy?: boolean;
38
51
  /** table prefix; default portal_ */
@@ -62,6 +75,15 @@ export declare class PortalStore {
62
75
  static hashPassword(password: string): string;
63
76
  static checkPassword(password: string, stored: string): boolean;
64
77
  createUser(email: string, password: string, profile?: Profile): Promise<PortalUser>;
78
+ userByEmail(email: string): Promise<PortalUser | null>;
79
+ /** the account's profile, for the onboarding screen and the operator's note */
80
+ profile(userId: string): Promise<Profile>;
81
+ updateProfile(userId: string, profile: Profile): Promise<void>;
82
+ /**
83
+ * The account behind a provider sign-in: the linked one, else the account with that verified email (linked from
84
+ * now on), else a new account with a random password nobody knows. The provider's email must be verified.
85
+ */
86
+ findOrCreateOAuthUser(provider: string, subject: string, email: string): Promise<PortalUser>;
65
87
  authenticate(email: string, password: string): Promise<PortalUser | null>;
66
88
  user(id: string): Promise<PortalUser | null>;
67
89
  addMember(userId: string, tenantId: string): Promise<void>;
package/dist/portal.js CHANGED
@@ -39,6 +39,8 @@ export class PortalStore {
39
39
  // who the account belongs to: added after the first tenants registered, so the columns are optional
40
40
  for (const c of PROFILE_COLUMNS)
41
41
  await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS ${c} TEXT`);
42
+ // a provider identity linked to an account: GitHub or Google's stable subject, and the verified email it gave
43
+ await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}identities (provider TEXT NOT NULL, subject TEXT NOT NULL, user_id TEXT NOT NULL REFERENCES ${p}users(id), email TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (provider, subject))`);
42
44
  })();
43
45
  }
44
46
  return this.ready;
@@ -63,6 +65,42 @@ export class PortalStore {
63
65
  throw new Error("an account with this email already exists");
64
66
  return { id, email, createdAt: new Date(rows[0].created_at).toISOString() };
65
67
  }
68
+ async userByEmail(email) {
69
+ await this.init();
70
+ const rows = (await this.client.query(`SELECT id, email, created_at FROM ${this.p}users WHERE email = $1`, [email])).rows;
71
+ const r = rows[0];
72
+ return r ? { id: String(r.id), email: String(r.email), createdAt: new Date(r.created_at).toISOString() } : null;
73
+ }
74
+ /** the account's profile, for the onboarding screen and the operator's note */
75
+ async profile(userId) {
76
+ await this.init();
77
+ const rows = (await this.client.query(`SELECT name, company, role, phone, telegram FROM ${this.p}users WHERE id = $1`, [userId])).rows;
78
+ const r = rows[0] ?? {};
79
+ const str = (v) => (v == null ? null : String(v));
80
+ return { name: str(r.name), company: str(r.company), role: str(r.role), phone: str(r.phone), telegram: str(r.telegram) };
81
+ }
82
+ async updateProfile(userId, profile) {
83
+ await this.init();
84
+ await this.client.query(`UPDATE ${this.p}users SET name = $2, company = $3, role = $4, phone = $5, telegram = $6 WHERE id = $1`, [userId, profile.name ?? null, profile.company ?? null, profile.role ?? null, profile.phone ?? null, profile.telegram ?? null]);
85
+ }
86
+ /**
87
+ * The account behind a provider sign-in: the linked one, else the account with that verified email (linked from
88
+ * now on), else a new account with a random password nobody knows. The provider's email must be verified.
89
+ */
90
+ async findOrCreateOAuthUser(provider, subject, email) {
91
+ await this.init();
92
+ const linked = (await this.client.query(`SELECT user_id FROM ${this.p}identities WHERE provider = $1 AND subject = $2`, [provider, subject])).rows;
93
+ if (linked[0]) {
94
+ const u = await this.user(linked[0].user_id);
95
+ if (u)
96
+ return u;
97
+ }
98
+ let user = await this.userByEmail(email);
99
+ if (!user)
100
+ user = await this.createUser(email, randomBytes(32).toString("hex"));
101
+ await this.client.query(`INSERT INTO ${this.p}identities (provider, subject, user_id, email) VALUES ($1, $2, $3, $4) ON CONFLICT (provider, subject) DO UPDATE SET user_id = EXCLUDED.user_id, email = EXCLUDED.email`, [provider, subject, user.id, email]);
102
+ return user;
103
+ }
66
104
  async authenticate(email, password) {
67
105
  await this.init();
68
106
  const rows = (await this.client.query(`SELECT id, email, password_hash, created_at FROM ${this.p}users WHERE email = $1`, [email])).rows;
@@ -247,7 +285,8 @@ export function portalHandler(o) {
247
285
  }
248
286
  if (req.method === "GET" && url.pathname === "/") {
249
287
  res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "x-frame-options": "DENY", "content-security-policy": "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src 'self'; connect-src 'self'; form-action 'self'; base-uri 'none'" });
250
- return void res.end(PORTAL_PAGE.replace("__LOG_BASE__", base.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c])));
288
+ const providers = JSON.stringify(["github", "google"].filter((p) => !!o.oauth?.[p]));
289
+ return void res.end(PORTAL_PAGE.replace("__LOG_BASE__", base.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c])).replace("__PROVIDERS__", providers));
251
290
  }
252
291
  // ---- Stripe's webhook: the only caller that is not a browser with a session ----
253
292
  if (req.method === "POST" && url.pathname === "/stripe/webhook") {
@@ -279,47 +318,132 @@ export function portalHandler(o) {
279
318
  }
280
319
  return json(200, { received: true });
281
320
  }
282
- // ---- registration and login ----
283
- if (req.method === "POST" && url.pathname === "/api/register") {
284
- const b = await jsonBody();
285
- const email = String(b.email ?? "").trim().toLowerCase();
286
- const password = String(b.password ?? "");
321
+ // What the tenant setup needs, checked before anything is created: a mistyped form leaves nothing behind.
322
+ const parseOnboarding = async (b) => {
287
323
  const tenant = String(b.tenant ?? "").trim().toLowerCase();
288
- if (!EMAIL.test(email))
289
- return json(400, { error: "a valid email address is needed" });
290
- if (password.length < 10)
291
- return json(400, { error: "the password needs at least ten characters" });
292
324
  if (!TENANT_ID.test(tenant) || RESERVED.has(tenant))
293
- return json(400, { error: "the tenant id is the name in your log's URL: three to forty lowercase letters, digits, or hyphens, and not a reserved word" });
325
+ return { status: 400, body: { error: "the tenant id is the name in your log's URL: three to forty lowercase letters, digits, or hyphens, and not a reserved word" } };
294
326
  const text = (k, max) => String(b[k] ?? "").trim().slice(0, max);
295
327
  const profile = { name: text("name", 120), company: text("company", 160), role: text("role", 120) || null, phone: text("phone", 40) || null, telegram: text("telegram", 40).replace(/^@/, "") || null };
296
328
  if (!profile.name)
297
- return json(400, { error: "your name is needed, so we know who to write to" });
329
+ return { status: 400, body: { error: "your name is needed, so we know who to write to" } };
298
330
  if (!profile.company)
299
- return json(400, { error: "the company or organisation the tenant is for is needed" });
331
+ return { status: 400, body: { error: "the company or organisation the tenant is for is needed" } };
300
332
  if (profile.telegram && !/^[A-Za-z0-9_]{5,32}$/.test(profile.telegram))
301
- return json(400, { error: "a Telegram username is five to thirty-two letters, digits, or underscores, with or without the @" });
333
+ return { status: 400, body: { error: "a Telegram username is five to thirty-two letters, digits, or underscores, with or without the @" } };
302
334
  if (profile.phone && !/^[+0-9 ()./-]{6,40}$/.test(profile.phone))
303
- return json(400, { error: "a phone number is digits, with an optional + and spaces" });
335
+ return { status: 400, body: { error: "a phone number is digits, with an optional + and spaces" } };
304
336
  if (await o.tenancy.tenant(tenant))
305
- return json(409, { error: "that tenant id is taken" });
337
+ return { status: 409, body: { error: "that tenant id is taken" } };
338
+ return { tenant, profile };
339
+ };
340
+ const onboard = async (user, parsed) => {
341
+ const { tenant, profile } = parsed;
342
+ if (await store.tenantOf(user.id))
343
+ return { status: 409, body: { error: "this account already has a tenant" } };
344
+ await store.updateProfile(user.id, profile);
345
+ const t = await o.tenancy.addTenant(tenant, tenant, `portal:${user.email}`);
346
+ await store.addMember(user.id, tenant);
347
+ const minted = await o.tenancy.addToken(tenant, "first key", `portal:${user.email}`);
348
+ log(`agent-custody portal: ${user.email} registered tenant ${tenant}`);
349
+ void welcomeMail(user.email, profile.name, t.id, t.logId);
350
+ void notifyMail({ ...profile, email: user.email, tenant: t.id });
351
+ return { status: 200, body: { tenant: t.id, logId: t.logId, plan: t.plan, token: minted.token, tokenHash: minted.tokenHash.slice(0, 12), welcome: sheet(t.id, t.logId), setup: setupFor(t.id, t.logId), exportCommand: exportCommand(t.id) } };
352
+ };
353
+ if (req.method === "POST" && url.pathname === "/api/register") {
354
+ const b = await jsonBody();
355
+ const email = String(b.email ?? "").trim().toLowerCase();
356
+ const password = String(b.password ?? "");
357
+ if (!EMAIL.test(email))
358
+ return json(400, { error: "a valid email address is needed" });
359
+ if (password.length < 10)
360
+ return json(400, { error: "the password needs at least ten characters" });
361
+ const oneStep = "tenant" in b || "company" in b || "name" in b;
362
+ let parsed = null;
363
+ if (oneStep) {
364
+ const p = await parseOnboarding(b);
365
+ if ("status" in p)
366
+ return json(p.status, p.body);
367
+ parsed = p;
368
+ }
306
369
  // throttled once the request is well formed: a mistyped form costs nothing, five real registrations from one address, then one every ten minutes
307
370
  if (!registrations.take(`reg:${addr}`))
308
371
  return json(429, { error: "too many registrations from this address; try again later" });
309
372
  let user;
310
373
  try {
311
- user = await store.createUser(email, password, profile);
374
+ user = await store.createUser(email, password);
312
375
  }
313
376
  catch (e) {
314
377
  return json(409, { error: e instanceof Error ? e.message : String(e) });
315
378
  }
316
- const t = await o.tenancy.addTenant(tenant, tenant, `portal:${email}`);
317
- await store.addMember(user.id, tenant);
318
- const minted = await o.tenancy.addToken(tenant, "first key", `portal:${email}`);
319
- log(`agent-custody portal: ${email} registered tenant ${tenant}`);
320
- void welcomeMail(email, profile.name, t.id, t.logId);
321
- void notifyMail({ ...profile, email, tenant: t.id });
322
- return json(200, { tenant: t.id, logId: t.logId, plan: t.plan, token: minted.token, tokenHash: minted.tokenHash.slice(0, 12), welcome: sheet(t.id, t.logId), setup: setupFor(t.id, t.logId), exportCommand: exportCommand(t.id) }, { "set-cookie": setCookie(signSession(o.secret, user.id)) });
379
+ const cookie = { "set-cookie": setCookie(signSession(o.secret, user.id)) };
380
+ if (!parsed) {
381
+ log(`agent-custody portal: ${email} created an account`);
382
+ return json(200, { email, tenant: null }, cookie);
383
+ }
384
+ const r = await onboard(user, parsed);
385
+ return json(r.status, r.body, cookie);
386
+ }
387
+ // ---- sign in through a provider: the OAuth web flow, state in a short-lived signed cookie ----
388
+ const provider = /^\/auth\/(github|google)(\/callback)?$/.exec(url.pathname);
389
+ if (req.method === "GET" && provider && o.oauth?.[provider[1]]) {
390
+ const name = provider[1];
391
+ const conf = o.oauth[name];
392
+ const redirectUri = `${portalBase}auth/${name}/callback`;
393
+ const stateCookie = (value) => `custody_oauth=${value ?? ""}; Path=/auth; HttpOnly; SameSite=Lax${o.trustProxy ? "; Secure" : ""}; Max-Age=${value ? 600 : 0}`;
394
+ if (!provider[2]) {
395
+ const state = signSession(o.secret, `oauth:${name}:${randomBytes(16).toString("hex")}`, 600_000);
396
+ const authorize = name === "github"
397
+ ? `https://github.com/login/oauth/authorize?${new URLSearchParams({ client_id: conf.clientId, redirect_uri: redirectUri, scope: "user:email", state })}`
398
+ : `https://accounts.google.com/o/oauth2/v2/auth?${new URLSearchParams({ client_id: conf.clientId, redirect_uri: redirectUri, response_type: "code", scope: "openid email", state, prompt: "select_account" })}`;
399
+ res.writeHead(302, { location: authorize, "set-cookie": stateCookie(state), "cache-control": "no-store" });
400
+ return void res.end();
401
+ }
402
+ const state = url.searchParams.get("state") ?? "";
403
+ const code = url.searchParams.get("code") ?? "";
404
+ const expected = cookies.custody_oauth;
405
+ const stateUser = readSession(o.secret, state);
406
+ if (!code || !state || state !== expected || !stateUser?.startsWith(`oauth:${name}:`))
407
+ return json(400, { error: "the sign-in did not start here, or took too long; go back and try again" }, { "set-cookie": stateCookie(null) });
408
+ const f = o.oauth.fetch ?? fetch;
409
+ let subject = "";
410
+ let email = "";
411
+ try {
412
+ if (name === "github") {
413
+ const tok = (await (await f("https://github.com/login/oauth/access_token", { method: "POST", headers: { accept: "application/json", "content-type": "application/json" }, body: JSON.stringify({ client_id: conf.clientId, client_secret: conf.clientSecret, code, redirect_uri: redirectUri }), signal: AbortSignal.timeout(10_000) })).json());
414
+ if (!tok.access_token)
415
+ throw new Error(tok.error ?? "no access token");
416
+ const gh = { authorization: `Bearer ${tok.access_token}`, accept: "application/vnd.github+json", "user-agent": "agent-custody-portal" };
417
+ const me = (await (await f("https://api.github.com/user", { headers: gh, signal: AbortSignal.timeout(10_000) })).json());
418
+ const emails = (await (await f("https://api.github.com/user/emails", { headers: gh, signal: AbortSignal.timeout(10_000) })).json());
419
+ const primary = emails.find((e) => e.primary && e.verified) ?? emails.find((e) => e.verified);
420
+ if (me.id === undefined || !primary)
421
+ throw new Error("GitHub gave no verified email; add one to your GitHub account or use email and password");
422
+ subject = String(me.id);
423
+ email = primary.email.toLowerCase();
424
+ }
425
+ else {
426
+ const tok = (await (await f("https://oauth2.googleapis.com/token", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams({ client_id: conf.clientId, client_secret: conf.clientSecret, code, redirect_uri: redirectUri, grant_type: "authorization_code" }), signal: AbortSignal.timeout(10_000) })).json());
427
+ if (!tok.id_token)
428
+ throw new Error(tok.error ?? "no id token");
429
+ // the id token came straight from Google's token endpoint over TLS in this exchange, so its claims are read without a second signature check
430
+ const claims = JSON.parse(Buffer.from(tok.id_token.split(".")[1] ?? "", "base64url").toString());
431
+ if (!claims.sub || !claims.email || claims.email_verified !== true)
432
+ throw new Error("Google gave no verified email");
433
+ subject = claims.sub;
434
+ email = claims.email.toLowerCase();
435
+ }
436
+ }
437
+ catch (e) {
438
+ log(`agent-custody portal: ${name} sign-in failed: ${e instanceof Error ? e.message : String(e)}`);
439
+ return json(502, { error: `${name === "github" ? "GitHub" : "Google"} sign-in failed: ${e instanceof Error ? e.message : String(e)}` }, { "set-cookie": stateCookie(null) });
440
+ }
441
+ const user = await store.findOrCreateOAuthUser(name, subject, email);
442
+ log(`agent-custody portal: ${email} signed in with ${name}`);
443
+ // A page, not a redirect: the session cookie is SameSite=Strict, and a redirect that started at the provider
444
+ // would not carry it. The page's own navigation to / does.
445
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "set-cookie": [setCookie(signSession(o.secret, user.id)), stateCookie(null)], "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'" });
446
+ return void res.end(`<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=/"><title>Signed in</title><p style="font:15px system-ui;padding:2rem">Signed in as ${email.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c])}. <a href="/">Continue</a>.</p>`);
323
447
  }
324
448
  if (req.method === "POST" && url.pathname === "/api/login") {
325
449
  if (!loginFailures.take(`login:${addr}`))
@@ -338,14 +462,23 @@ export function portalHandler(o) {
338
462
  const user = userId ? await store.user(userId) : null;
339
463
  if (!user)
340
464
  return json(401, { error: "sign in first" });
465
+ if (req.method !== "GET" && !(req.headers["content-type"] ?? "").startsWith("application/json"))
466
+ return json(415, { error: "expected a JSON body" });
341
467
  const tenantId = await store.tenantOf(user.id);
468
+ if (req.method === "GET" && url.pathname === "/api/me" && !tenantId)
469
+ return json(200, { email: user.email, tenant: null, profile: await store.profile(user.id), billing: !!o.stripe });
470
+ if (req.method === "POST" && url.pathname === "/api/onboard") {
471
+ const p = await parseOnboarding(await jsonBody());
472
+ if ("status" in p)
473
+ return json(p.status, p.body);
474
+ const r = await onboard(user, p);
475
+ return json(r.status, r.body);
476
+ }
342
477
  if (!tenantId)
343
- return json(409, { error: "this account has no tenant" });
478
+ return json(409, { error: "this account has no tenant yet; finish setting it up" });
344
479
  const tenant = await o.tenancy.tenant(tenantId);
345
480
  if (!tenant)
346
481
  return json(409, { error: "the tenant no longer exists" });
347
- if (req.method !== "GET" && !(req.headers["content-type"] ?? "").startsWith("application/json"))
348
- return json(415, { error: "expected a JSON body" });
349
482
  if (req.method === "GET" && url.pathname === "/api/me") {
350
483
  const q = await o.tenancy.quota(tenantId);
351
484
  return json(200, { email: user.email, tenant: tenantId, logId: tenant.logId, plan: q.plan, used: q.used, quota: q.quota, disabled: !!tenant.disabledAt, billing: !!o.stripe });
@@ -381,6 +514,43 @@ export function portalHandler(o) {
381
514
  await jsonBody();
382
515
  return json(200, { revoked: await o.tenancy.revokeToken(tenantId, revoke[1], `portal:${user.email}`) });
383
516
  }
517
+ // Policies: named versions the tenant publishes so a receipt's policyDigest reads as a name. The gateway never
518
+ // reads these; enforcement stays on the tenant's machines.
519
+ if (req.method === "GET" && url.pathname === "/api/policies") {
520
+ const digest = url.searchParams.get("digest");
521
+ if (digest !== null) {
522
+ if (!/^[0-9a-f]{64}$/i.test(digest))
523
+ return json(400, { error: "a policy digest is 64 hexadecimal characters, the policyDigest a receipt carries" });
524
+ return json(200, { match: await o.tenancy.policyByDigest(tenantId, digest) });
525
+ }
526
+ return json(200, { policies: await o.tenancy.listPolicies(tenantId) });
527
+ }
528
+ if (req.method === "POST" && url.pathname === "/api/policies") {
529
+ const b = await jsonBody();
530
+ const name = String(b.name ?? "").trim().slice(0, 80);
531
+ const text = typeof b.text === "string" ? b.text : "";
532
+ if (!name)
533
+ return json(400, { error: "a name for this version is needed, for example refunds-v3 or 2026-10-01" });
534
+ if (!text.trim())
535
+ return json(400, { error: "the policy text is empty" });
536
+ if (text.length > 256_000)
537
+ return json(400, { error: "a policy is at most 256 KB" });
538
+ try {
539
+ return json(200, { policy: await o.tenancy.addPolicy(tenantId, name, text, `portal:${user.email}`) });
540
+ }
541
+ catch (e) {
542
+ return json(409, { error: e instanceof Error ? e.message : String(e) });
543
+ }
544
+ }
545
+ const pol = /^\/api\/policies\/(pol_[0-9a-f]{16})(\/remove)?$/.exec(url.pathname);
546
+ if (req.method === "GET" && pol && !pol[2]) {
547
+ const p = await o.tenancy.policy(tenantId, pol[1]);
548
+ return p ? json(200, { policy: p }) : json(404, { error: "no such policy version" });
549
+ }
550
+ if (req.method === "POST" && pol && pol[2]) {
551
+ await jsonBody();
552
+ return json(200, { removed: await o.tenancy.removePolicy(tenantId, pol[1], `portal:${user.email}`) });
553
+ }
384
554
  if (req.method === "POST" && url.pathname === "/api/checkout") {
385
555
  if (!o.stripe)
386
556
  return json(503, { error: "billing is not configured on this portal yet; email us and we move the plan by hand" });
@@ -465,12 +635,15 @@ const PORTAL_PAGE = `<!doctype html>
465
635
  .bar b { font-family: var(--mono); font-weight: 400; margin-top: .3rem; }
466
636
  label { display: grid; gap: .25rem; font-size: .85rem; color: var(--ink2); margin: 0 0 .8rem; }
467
637
  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; }
638
+ 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
639
  input, select { font: inherit; padding: .5rem .6rem; border: 1px solid var(--line); border-radius: 4px; background: var(--bg); color: var(--ink); }
469
640
  button { font: inherit; padding: .5rem .9rem; border-radius: 4px; border: 1px solid var(--accent); background: var(--accent); color: #fff; cursor: pointer; }
470
641
  button.quiet { background: transparent; color: var(--accent); }
471
642
  button.link { background: none; border: 0; padding: 0; color: var(--accent); text-decoration: underline; }
472
643
  .auth { max-width: 26rem; margin: 4rem auto; }
473
644
  .auth.wide { max-width: 44rem; }
645
+ .providers { display: grid; gap: .5rem; margin: 0 0 1rem; } .providers a { display: block; text-align: center; padding: .55rem .9rem; border: 1px solid var(--line); border-radius: 4px; background: var(--panel); color: var(--ink); text-decoration: none; font-weight: 600; }
646
+ .providers a:hover { border-color: var(--accent); } .or { text-align: center; color: var(--ink2); font-size: .82rem; margin: 0 0 .8rem; }
474
647
  .step { display: grid; grid-template-columns: 2rem 1fr; gap: .2rem .8rem; padding: 1rem 0; border-top: 1px solid var(--line); }
475
648
  .step .n { font: 700 .85rem/1.6 var(--mono); color: var(--accent); }
476
649
  .step h3 { margin: 0 0 .3rem; font-size: 1rem; } .step p { margin: 0 0 .5rem; color: var(--ink2); font-size: .92rem; }
@@ -487,25 +660,32 @@ const PORTAL_PAGE = `<!doctype html>
487
660
  <div class="top"><a class="brand" href="https://agent-custody.dev/"><svg viewBox="0 0 64 64" aria-hidden="true"><rect width="64" height="64" rx="14"/><path d="M19 11H45V45L41.75 48 38.5 45 35.25 48 32 45 28.75 48 25.5 45 22.25 48 19 45Z" fill="#fff"/><path d="M25 20h14M25 27h14" stroke="var(--accent)" stroke-width="2.6" stroke-linecap="round"/><path d="M25 37.5l5 4.5 9.5-10" fill="none" stroke="var(--accent)" stroke-width="3.4" stroke-linecap="round" stroke-linejoin="round"/></svg>agent-custody</a><span id="tenantTag" class="pill" hidden></span><span id="planTag" class="pill" hidden></span><span class="links"><a href="https://agent-custody.dev/guide/getting-started">Guide</a><a href="https://docs.agent-custody.dev/reference/">Docs</a><a href="https://agent-custody.dev/verify">Verify a receipt</a></span><span class="who" id="who"></span><button class="theme" id="themeToggle" type="button">Dark mode</button></div>
488
661
  <section id="auth" class="auth" hidden>
489
662
  <h1 id="authTitle">Sign in</h1>
663
+ <div id="providers" class="providers" hidden></div>
490
664
  <form id="authForm">
491
- <div id="regFields" hidden>
492
- <label>Your name<input id="name" autocomplete="name" maxlength="120"></label>
493
- <label>Company or organisation<input id="company" autocomplete="organization" maxlength="160"></label>
494
- <label>Your role <span class="opt">optional</span><input id="role" autocomplete="organization-title" maxlength="120" placeholder="Head of Platform"></label>
495
- </div>
496
665
  <label>Work email<input id="email" type="email" autocomplete="email" required></label>
497
- <div id="regFields2" hidden>
498
- <label>Phone <span class="opt">optional</span><input id="phone" type="tel" autocomplete="tel" maxlength="40" placeholder="+44 20 …"></label>
499
- <label>Telegram username <span class="opt">optional</span><input id="telegram" maxlength="40" placeholder="@yourname"><span class="hint">Your handle in Telegram, under Settings, if you would rather we reach you there than by email.</span></label>
500
- </div>
501
666
  <label>Password<input id="password" type="password" autocomplete="current-password" minlength="10" required></label>
502
- <label id="tenantField" hidden>Tenant id<input id="tenant" placeholder="acme" pattern="[a-z0-9][a-z0-9-]{1,38}[a-z0-9]"><span class="hint">A short name for your organisation, filled in from the company name; change it if you like. It becomes the path of your log, which your gateway config and your auditors will use: <code id="tenantPreview">__LOG_BASE__t/&lt;tenant&gt;/</code></span></label>
503
667
  <button id="authGo" type="submit">Sign in</button>
504
668
  <p class="msg" id="authMsg"></p>
505
669
  </form>
506
- <p class="muted"><button class="link" id="authSwap" type="button">Create an account and a tenant instead</button></p>
670
+ <p class="muted" id="authNote" hidden>Next you name your organisation and get your tenant and its first key. Two minutes.</p>
671
+ <p class="muted"><button class="link" id="authSwap" type="button">Create an account instead</button></p>
507
672
  <p class="muted">The free plan is ten thousand appends a month, no card. Your gateway sends only hashes; nothing you log here can be read by us.</p>
508
673
  </section>
674
+ <section id="onboard" class="auth" hidden>
675
+ <h1>Set up your tenant</h1>
676
+ <p class="muted">Signed in as <b id="onboardWho"></b>. A tenant is your own log on this service, with its own keys and its own path.</p>
677
+ <form id="onboardForm">
678
+ <label>Your name<input id="name" autocomplete="name" maxlength="120" required></label>
679
+ <label>Company or organisation<input id="company" autocomplete="organization" maxlength="160" required></label>
680
+ <label>Tenant id<input id="tenant" placeholder="acme" pattern="[a-z0-9][a-z0-9-]{1,38}[a-z0-9]" required><span class="hint">A short name for your organisation, filled in from the company name; change it if you like. It becomes the path of your log, which your gateway config and your auditors will use: <code id="tenantPreview">__LOG_BASE__t/&lt;tenant&gt;/</code></span></label>
681
+ <label>Your role <span class="opt">optional</span><input id="role" autocomplete="organization-title" maxlength="120" placeholder="Head of Platform"></label>
682
+ <label>Phone <span class="opt">optional</span><input id="phone" type="tel" autocomplete="tel" maxlength="40" placeholder="+44 20 …"></label>
683
+ <label>Telegram username <span class="opt">optional</span><input id="telegram" maxlength="40" placeholder="@yourname"><span class="hint">Your handle in Telegram, under Settings, if you would rather we reach you there than by email.</span></label>
684
+ <button type="submit">Create tenant</button>
685
+ <p class="msg" id="onboardMsg"></p>
686
+ </form>
687
+ <p class="muted"><a href="#" id="signoutOnboard">Sign out</a></p>
688
+ </section>
509
689
  <section id="welcome" class="auth wide" hidden>
510
690
  <h1>Your tenant is ready</h1>
511
691
  <p class="muted">Three steps to your first receipt in this log. Everything here is under <b>Setup</b> in the dashboard whenever you need it again.</p>
@@ -521,6 +701,7 @@ const PORTAL_PAGE = `<!doctype html>
521
701
  <div class="group">Configure</div>
522
702
  <a href="#setup" data-view="setup">Setup</a>
523
703
  <a href="#keys" data-view="keys">API keys <span class="n" id="nKeys"></span></a>
704
+ <a href="#policies" data-view="policies">Policies <span class="n" id="nPolicies"></span></a>
524
705
  <a href="#billing" data-view="billing">Billing</a>
525
706
  <a href="#export" data-view="export">Export</a>
526
707
  <div class="group">Account</div>
@@ -554,6 +735,15 @@ const PORTAL_PAGE = `<!doctype html>
554
735
  <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
736
  <p class="msg" id="keysMsg"></p>
556
737
  </div>
738
+ <div data-pane="policies" hidden>
739
+ <h1>Policies</h1>
740
+ <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>
741
+ <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>
742
+ <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>
743
+ <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>
744
+ <div class="panel" id="policyView" hidden><h2 id="policyViewName"></h2><pre id="policyViewText"></pre></div>
745
+ <p class="msg" id="policiesMsg"></p>
746
+ </div>
557
747
  <div data-pane="billing" hidden>
558
748
  <h1>Billing</h1>
559
749
  <div class="panel" id="billingPanel"></div>
@@ -584,7 +774,9 @@ const PORTAL_PAGE = `<!doctype html>
584
774
  const fmt = (n) => Number(n).toLocaleString();
585
775
  const ago = (iso) => { const m = Math.round((Date.now() - Date.parse(iso)) / 60000); return m < 60 ? m + " min ago" : m < 1440 ? Math.round(m / 60) + " h ago" : Math.round(m / 1440) + " d ago"; };
586
776
  let registering = false;
587
- const show = (id) => { for (const s of ["auth", "welcome", "app"]) $(s).hidden = s !== id; };
777
+ const show = (id) => { for (const s of ["auth", "onboard", "welcome", "app"]) $(s).hidden = s !== id; };
778
+ const PROVIDERS = __PROVIDERS__;
779
+ if (PROVIDERS.length) { $("providers").innerHTML = PROVIDERS.map((p) => "<a href='/auth/" + p + "'>Continue with " + (p === "github" ? "GitHub" : "Google") + "</a>").join("") + "<p class=or>or with email</p>"; $("providers").hidden = false; }
588
780
  const view = (name) => {
589
781
  for (const p of document.querySelectorAll("[data-pane]")) p.hidden = p.dataset.pane !== name;
590
782
  for (const a of document.querySelectorAll("nav a[data-view]")) a.classList.toggle("on", a.dataset.view === name);
@@ -596,16 +788,22 @@ const PORTAL_PAGE = `<!doctype html>
596
788
  const previewTenant = () => { $("tenantPreview").textContent = LOG_BASE + "t/" + ($("tenant").value || "<tenant>") + "/"; };
597
789
  $("company").oninput = () => { if (!tenantEdited) { $("tenant").value = slug($("company").value); previewTenant(); } };
598
790
  $("tenant").oninput = () => { tenantEdited = $("tenant").value !== ""; previewTenant(); };
599
- $("authSwap").onclick = () => { registering = !registering; $("authTitle").textContent = registering ? "Create your tenant" : "Sign in"; $("authGo").textContent = registering ? "Create tenant" : "Sign in"; for (const id of ["regFields", "regFields2", "tenantField"]) $(id).hidden = !registering; for (const id of ["name", "company", "tenant"]) $(id).required = registering; $("password").autocomplete = registering ? "new-password" : "current-password"; $("authSwap").textContent = registering ? "I already have an account" : "Create an account and a tenant instead"; previewTenant(); };
791
+ $("authSwap").onclick = () => { registering = !registering; $("authTitle").textContent = registering ? "Create an account" : "Sign in"; $("authGo").textContent = registering ? "Create account" : "Sign in"; $("authNote").hidden = !registering; $("password").autocomplete = registering ? "new-password" : "current-password"; $("authSwap").textContent = registering ? "I already have an account" : "Create an account instead"; };
600
792
  $("authForm").onsubmit = async (e) => {
601
793
  e.preventDefault(); $("authMsg").className = "msg"; $("authMsg").textContent = "";
602
794
  try {
603
- if (registering) {
604
- const r = await api("POST", "/api/register", { email: $("email").value, password: $("password").value, tenant: $("tenant").value, name: $("name").value, company: $("company").value, role: $("role").value, phone: $("phone").value, telegram: $("telegram").value });
605
- $("firstToken").textContent = r.token; renderSetup($("firstSetup"), r.setup, true); show("welcome");
606
- } else { await api("POST", "/api/login", { email: $("email").value, password: $("password").value }); await enter(); }
795
+ await api("POST", registering ? "/api/register" : "/api/login", { email: $("email").value, password: $("password").value });
796
+ await enter();
607
797
  } catch (err) { $("authMsg").className = "msg err"; $("authMsg").textContent = err.message; }
608
798
  };
799
+ $("onboardForm").onsubmit = async (e) => {
800
+ e.preventDefault(); $("onboardMsg").className = "msg"; $("onboardMsg").textContent = "";
801
+ try {
802
+ const r = await api("POST", "/api/onboard", { tenant: $("tenant").value, name: $("name").value, company: $("company").value, role: $("role").value, phone: $("phone").value, telegram: $("telegram").value });
803
+ $("firstToken").textContent = r.token; renderSetup($("firstSetup"), r.setup, true); show("welcome");
804
+ } catch (err) { $("onboardMsg").className = "msg err"; $("onboardMsg").textContent = err.message; }
805
+ };
806
+ $("signoutOnboard").onclick = async (e) => { e.preventDefault(); await api("POST", "/api/logout", {}); location.hash = ""; show("auth"); };
609
807
  $("copyFirst").onclick = () => navigator.clipboard.writeText($("firstToken").textContent);
610
808
  // Light or dark by choice, kept in this browser; unset, the page follows the system. The button says where it is going.
611
809
  const themeNow = () => document.documentElement.dataset.theme || (matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light");
@@ -653,11 +851,40 @@ const PORTAL_PAGE = `<!doctype html>
653
851
  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
852
  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
853
  };
656
- const load = async () => render(await api("GET", "/api/overview"));
854
+ const load = async () => { render(await api("GET", "/api/overview")); await loadPolicies(); };
657
855
  const enter = async () => {
658
- try { const me = await api("GET", "/api/me"); $("who").textContent = me.email; show("app"); await load(); view((location.hash || "#overview").slice(1) || "overview"); }
856
+ try {
857
+ const me = await api("GET", "/api/me");
858
+ if (me.tenant === null) { $("onboardWho").textContent = me.email; if (me.profile) { for (const k of ["name", "company", "role", "phone", "telegram"]) if (me.profile[k]) $(k).value = me.profile[k]; } previewTenant(); show("onboard"); return; }
859
+ $("who").textContent = me.email; show("app"); await load(); view((location.hash || "#overview").slice(1) || "overview");
860
+ }
659
861
  catch (err) { if (err.status === 401) { show("auth"); if (location.hash === "#register" && !registering) $("authSwap").click(); } else { show("app"); $("who").textContent = err.message; } }
660
862
  };
863
+ 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("");
864
+ const loadPolicies = async () => {
865
+ const r = await api("GET", "/api/policies");
866
+ $("nPolicies").textContent = r.policies.length || "";
867
+ $("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>";
868
+ };
869
+ $("policyText").oninput = async () => { const t = $("policyText").value; $("policyDigestPreview").textContent = t ? "sha256 " + (await sha256hex(t)).slice(0, 16) + "…" : ""; };
870
+ $("policyForm").onsubmit = async (e) => {
871
+ e.preventDefault(); $("policiesMsg").className = "msg";
872
+ 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(); }
873
+ catch (err) { $("policiesMsg").className = "msg err"; $("policiesMsg").textContent = err.message; }
874
+ };
875
+ $("matchForm").onsubmit = async (e) => {
876
+ e.preventDefault(); $("matchOut").className = "msg";
877
+ try {
878
+ const raw = $("matchIn").value.trim(); let digest = raw;
879
+ 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"); }
880
+ const r = await api("GET", "/api/policies?digest=" + encodeURIComponent(digest));
881
+ $("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.";
882
+ } catch (err) { $("matchOut").className = "msg err"; $("matchOut").textContent = err.message; }
883
+ };
884
+ document.addEventListener("click", async (e) => {
885
+ 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; }
886
+ 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; } }
887
+ });
661
888
  $("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
889
  $("copyMinted").onclick = () => navigator.clipboard.writeText($("mintedTok").textContent);
663
890
  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.14",
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",