@agent-custody/receipts 0.6.18 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/portal.js CHANGED
@@ -14,6 +14,14 @@ import { postgresCheckpoints } from "./checkpoints.js";
14
14
  import { welcomeSheet } from "./log-admin.js";
15
15
  import { clientAddress } from "./log-sink.js";
16
16
  import { RateLimiter } from "./log-store.js";
17
+ /** A provider sign-in whose verified email belongs to a password account that never verified its address: refused, never linked (issue #103). */
18
+ export class UnverifiedAccountError extends Error {
19
+ email;
20
+ constructor(email) {
21
+ super(`an account with the address ${email} exists but has not verified it; sign in with its password, then link the provider from the account page`);
22
+ this.email = email;
23
+ }
24
+ }
17
25
  const ident = (s) => {
18
26
  if (!/^[a-z_][a-z0-9_]*$/.test(s))
19
27
  throw new Error(`prefix must be a plain identifier; got "${s}"`);
@@ -36,11 +44,17 @@ export class PortalStore {
36
44
  await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}users (id TEXT PRIMARY KEY, email TEXT NOT NULL UNIQUE, password_hash TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now())`);
37
45
  await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}members (user_id TEXT NOT NULL REFERENCES ${p}users(id), tenant_id TEXT NOT NULL, role TEXT NOT NULL DEFAULT 'owner', created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (user_id, tenant_id))`);
38
46
  await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}billing (tenant_id TEXT PRIMARY KEY, customer_id TEXT, subscription_id TEXT, status TEXT NOT NULL, updated_at TIMESTAMPTZ NOT NULL DEFAULT now())`);
47
+ // the Stripe `created` time (unix seconds) of the event that set the billing state; an older event does not move it back
48
+ await this.client.query(`ALTER TABLE ${p}billing ADD COLUMN IF NOT EXISTS event_created BIGINT`);
49
+ // the Stripe event ids already applied; a redelivery of one is ignored
50
+ await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}stripe_events (id TEXT PRIMARY KEY, received_at TIMESTAMPTZ NOT NULL DEFAULT now())`);
39
51
  // who the account belongs to: added after the first tenants registered, so the columns are optional
40
52
  for (const c of PROFILE_COLUMNS)
41
53
  await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS ${c} TEXT`);
42
54
  // when the founder's note went out, so it goes once
43
55
  await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS followed_up_at TIMESTAMPTZ`);
56
+ // when the address was confirmed; a provider sign-in links to a password account only once this is set
57
+ await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS email_verified_at TIMESTAMPTZ`);
44
58
  // a provider identity linked to an account: GitHub or Google's stable subject, and the verified email it gave
45
59
  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))`);
46
60
  })();
@@ -69,9 +83,25 @@ export class PortalStore {
69
83
  }
70
84
  async userByEmail(email) {
71
85
  await this.init();
72
- const rows = (await this.client.query(`SELECT id, email, created_at FROM ${this.p}users WHERE email = $1`, [email])).rows;
73
- const r = rows[0];
74
- return r ? { id: String(r.id), email: String(r.email), createdAt: new Date(r.created_at).toISOString() } : null;
86
+ const rows = (await this.client.query(`SELECT id, email, created_at, email_verified_at FROM ${this.p}users WHERE email = $1`, [email])).rows;
87
+ return rows[0] ? PortalStore.asUser(rows[0]) : null;
88
+ }
89
+ static asUser(r) {
90
+ return { id: String(r.id), email: String(r.email), createdAt: new Date(r.created_at).toISOString(), emailVerifiedAt: r.email_verified_at ? new Date(r.email_verified_at).toISOString() : null };
91
+ }
92
+ async markEmailVerified(userId, at = new Date()) {
93
+ await this.init();
94
+ await this.client.query(`UPDATE ${this.p}users SET email_verified_at = COALESCE(email_verified_at, $2) WHERE id = $1`, [userId, at.toISOString()]);
95
+ }
96
+ /** Links a provider identity to a signed-in account: the account proved itself with its session, so the provider's email need not match. */
97
+ async linkIdentity(provider, subject, email, userId) {
98
+ await this.init();
99
+ 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, userId, email]);
100
+ }
101
+ async identities(userId) {
102
+ await this.init();
103
+ const rows = (await this.client.query(`SELECT DISTINCT provider FROM ${this.p}identities WHERE user_id = $1 ORDER BY provider`, [userId])).rows;
104
+ return rows.map((r) => r.provider);
75
105
  }
76
106
  /** the account's profile, for the onboarding screen and the operator's note */
77
107
  async profile(userId) {
@@ -97,8 +127,11 @@ export class PortalStore {
97
127
  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]);
98
128
  }
99
129
  /**
100
- * The account behind a provider sign-in: the linked one, else the account with that verified email (linked from
101
- * now on), else a new account with a random password nobody knows. The provider's email must be verified.
130
+ * The account behind a provider sign-in: the linked one; else the account with that email, linked from now on, but
131
+ * only if that account has verified its address (otherwise anyone could register a victim's address with a
132
+ * password, wait for the victim to sign in with Google, and keep password access to the merged account: issue
133
+ * #103; the refusal is UnverifiedAccountError); else a new account with a random password nobody knows, its address
134
+ * counted as verified because the provider vouched for it. The provider's email must be verified.
102
135
  */
103
136
  async findOrCreateOAuthUser(provider, subject, email) {
104
137
  await this.init();
@@ -109,9 +142,13 @@ export class PortalStore {
109
142
  return u;
110
143
  }
111
144
  let user = await this.userByEmail(email);
112
- if (!user)
145
+ if (user && !user.emailVerifiedAt)
146
+ throw new UnverifiedAccountError(email);
147
+ if (!user) {
113
148
  user = await this.createUser(email, randomBytes(32).toString("hex"));
114
- 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]);
149
+ await this.markEmailVerified(user.id);
150
+ }
151
+ await this.linkIdentity(provider, subject, email, user.id);
115
152
  return user;
116
153
  }
117
154
  async authenticate(email, password) {
@@ -124,9 +161,8 @@ export class PortalStore {
124
161
  }
125
162
  async user(id) {
126
163
  await this.init();
127
- const rows = (await this.client.query(`SELECT id, email, created_at FROM ${this.p}users WHERE id = $1`, [id])).rows;
128
- const r = rows[0];
129
- return r ? { id: String(r.id), email: String(r.email), createdAt: new Date(r.created_at).toISOString() } : null;
164
+ const rows = (await this.client.query(`SELECT id, email, created_at, email_verified_at FROM ${this.p}users WHERE id = $1`, [id])).rows;
165
+ return rows[0] ? PortalStore.asUser(rows[0]) : null;
130
166
  }
131
167
  async addMember(userId, tenantId) {
132
168
  await this.init();
@@ -140,14 +176,24 @@ export class PortalStore {
140
176
  }
141
177
  async setBilling(tenantId, b) {
142
178
  await this.init();
143
- await this.client.query(`INSERT INTO ${this.p}billing (tenant_id, customer_id, subscription_id, status, updated_at) VALUES ($1, $2, $3, $4, now())
144
- ON CONFLICT (tenant_id) DO UPDATE SET customer_id = COALESCE(EXCLUDED.customer_id, ${this.p}billing.customer_id), subscription_id = COALESCE(EXCLUDED.subscription_id, ${this.p}billing.subscription_id), status = EXCLUDED.status, updated_at = now()`, [tenantId, b.customerId ?? null, b.subscriptionId ?? null, b.status]);
179
+ await this.client.query(`INSERT INTO ${this.p}billing (tenant_id, customer_id, subscription_id, status, event_created, updated_at) VALUES ($1, $2, $3, $4, $5, now())
180
+ ON CONFLICT (tenant_id) DO UPDATE SET customer_id = COALESCE(EXCLUDED.customer_id, ${this.p}billing.customer_id), subscription_id = COALESCE(EXCLUDED.subscription_id, ${this.p}billing.subscription_id), status = EXCLUDED.status, event_created = COALESCE(EXCLUDED.event_created, ${this.p}billing.event_created), updated_at = now()`, [tenantId, b.customerId ?? null, b.subscriptionId ?? null, b.status, b.eventCreated ?? null]);
145
181
  }
146
182
  async billing(tenantId) {
147
183
  await this.init();
148
- const rows = (await this.client.query(`SELECT customer_id, subscription_id, status FROM ${this.p}billing WHERE tenant_id = $1`, [tenantId])).rows;
184
+ const rows = (await this.client.query(`SELECT customer_id, subscription_id, status, event_created FROM ${this.p}billing WHERE tenant_id = $1`, [tenantId])).rows;
149
185
  const r = rows[0];
150
- return r ? { customerId: r.customer_id ? String(r.customer_id) : null, subscriptionId: r.subscription_id ? String(r.subscription_id) : null, status: String(r.status) } : null;
186
+ return r ? { customerId: r.customer_id ? String(r.customer_id) : null, subscriptionId: r.subscription_id ? String(r.subscription_id) : null, status: String(r.status), eventCreated: r.event_created == null ? null : Number(r.event_created) } : null;
187
+ }
188
+ /** Has this Stripe event id been applied already? */
189
+ async stripeEventSeen(id) {
190
+ await this.init();
191
+ return (await this.client.query(`SELECT 1 FROM ${this.p}stripe_events WHERE id = $1`, [id])).rows.length > 0;
192
+ }
193
+ /** Records a Stripe event id as applied, after it was applied, so a failure before this point lets Stripe's retry through. */
194
+ async noteStripeEvent(id) {
195
+ await this.init();
196
+ await this.client.query(`INSERT INTO ${this.p}stripe_events (id) VALUES ($1) ON CONFLICT (id) DO NOTHING`, [id]);
151
197
  }
152
198
  /** Every portal registration with its tenant and billing state, oldest first: what the operator's admin page lists. */
153
199
  async registrations() {
@@ -296,6 +342,12 @@ export function portalHandler(o) {
296
342
  // Mail is best effort and off the request path: a provider outage is logged, never a failed registration.
297
343
  const send = async (m) => { if (o.mail)
298
344
  await deliverMail(o.mail, m, log); };
345
+ /** The verification link: a signed, single-purpose token good for a day. Until it is used, a provider sign-in for this address will not link to the account. */
346
+ const verificationMail = (u) => ({
347
+ to: u.email,
348
+ subject: "Verify your email address for agent-custody",
349
+ text: ["Hello,", "", "Please confirm this address for your agent-custody account by opening the link below. It is good for 24 hours.", "", `${portalBase}verify-email?token=${signSession(o.secret, `verify:${u.id}`, 86_400_000)}`, "", "If you did not create an account, ignore this mail; nothing was created in your name that works without it.", "", "agent-custody"].join("\n"),
350
+ });
299
351
  const welcomeMail = (to, name, tenant, logId) => send({ to, subject: `Your agent-custody log "${tenant}" is ready`, text: [
300
352
  `Hello ${name},`, "",
301
353
  `Your tenant "${tenant}" is live on the hosted log. Your API key was shown once when you registered and is not in this email; if it is gone, mint another under API keys at ${portalBase}.`, "",
@@ -328,6 +380,11 @@ export function portalHandler(o) {
328
380
  res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store", ...headers });
329
381
  res.end(JSON.stringify(body));
330
382
  };
383
+ const page = (status, title, body, headers = {}) => {
384
+ res.writeHead(status, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'", ...headers });
385
+ res.end(`<!doctype html><meta charset="utf-8"><title>${title}</title><p style="font:15px system-ui;padding:2rem">${body}</p>`);
386
+ };
387
+ const esc = (v) => v.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
331
388
  const setCookie = (value) => `${cookieName}=${value ?? ""}; Path=/; HttpOnly; SameSite=Strict${o.trustProxy ? "; Secure" : ""}; Max-Age=${value ? 14 * 86_400 : 0}`;
332
389
  const cookies = Object.fromEntries((req.headers.cookie ?? "").split(";").map((c) => c.trim().split("=")).filter(([k]) => k));
333
390
  const userId = readSession(o.secret, cookies[cookieName]);
@@ -366,26 +423,35 @@ export function portalHandler(o) {
366
423
  if (!verifyStripeSignature(req.headers["stripe-signature"], raw, o.stripe.webhookSecret))
367
424
  return json(400, { error: "bad signature" });
368
425
  const event = JSON.parse(raw);
426
+ if (typeof event.id !== "string" || !event.id || typeof event.created !== "number")
427
+ return json(400, { error: "an event needs an id and a created time" });
428
+ // Stripe delivers at least once and in no set order: a repeat is ignored by its id, and an event older than the
429
+ // one that set the stored state is ignored by its created time, so neither moves the plan back (issue #105)
430
+ if (await store.stripeEventSeen(event.id))
431
+ return json(200, { received: true, duplicate: true });
369
432
  const obj = event.data.object;
370
- if (event.type === "checkout.session.completed") {
371
- const tenant = String(obj.client_reference_id ?? "");
372
- if (tenant && (await o.tenancy.tenant(tenant))) {
373
- await store.setBilling(tenant, { customerId: obj.customer ? String(obj.customer) : null, subscriptionId: obj.subscription ? String(obj.subscription) : null, status: "active" });
374
- await o.tenancy.setPlan(tenant, "team", "stripe:checkout");
375
- log(`agent-custody portal: tenant ${tenant} moved to team by checkout ${String(obj.id ?? "")}`);
376
- }
433
+ const checkout = event.type === "checkout.session.completed";
434
+ const subscription = event.type === "customer.subscription.deleted" || event.type === "customer.subscription.updated";
435
+ const ref = String(obj.client_reference_id ?? "");
436
+ const tenant = checkout ? (ref && (await o.tenancy.tenant(ref)) ? ref : null) : subscription ? await store.tenantBySubscription(String(obj.id ?? "")) : null;
437
+ const stored = tenant ? (await store.billing(tenant))?.eventCreated : null;
438
+ if (tenant && stored != null && event.created < stored) {
439
+ log(`agent-custody portal: ignored ${event.type} ${event.id} for tenant ${tenant}: older than the stored billing state`);
377
440
  }
378
- else if (event.type === "customer.subscription.deleted" || event.type === "customer.subscription.updated") {
379
- const tenant = await store.tenantBySubscription(String(obj.id ?? ""));
380
- if (tenant) {
381
- const status = event.type === "customer.subscription.deleted" ? "canceled" : String(obj.status ?? "unknown");
382
- await store.setBilling(tenant, { status });
383
- const plan = status === "active" || status === "trialing" || status === "past_due" ? "team" : "free";
384
- const current = (await o.tenancy.tenant(tenant))?.plan;
385
- if (current !== "enterprise" && current !== plan)
386
- await o.tenancy.setPlan(tenant, plan, `stripe:${event.type}`);
387
- }
441
+ else if (tenant && checkout) {
442
+ await store.setBilling(tenant, { customerId: obj.customer ? String(obj.customer) : null, subscriptionId: obj.subscription ? String(obj.subscription) : null, status: "active", eventCreated: event.created });
443
+ await o.tenancy.setPlan(tenant, "team", "stripe:checkout");
444
+ log(`agent-custody portal: tenant ${tenant} moved to team by checkout ${String(obj.id ?? "")}`);
388
445
  }
446
+ else if (tenant) {
447
+ const status = event.type === "customer.subscription.deleted" ? "canceled" : String(obj.status ?? "unknown");
448
+ await store.setBilling(tenant, { status, eventCreated: event.created });
449
+ const plan = status === "active" || status === "trialing" || status === "past_due" ? "team" : "free";
450
+ const current = (await o.tenancy.tenant(tenant))?.plan;
451
+ if (current !== "enterprise" && current !== plan)
452
+ await o.tenancy.setPlan(tenant, plan, `stripe:${event.type}`);
453
+ }
454
+ await store.noteStripeEvent(event.id);
389
455
  return json(200, { received: true });
390
456
  }
391
457
  // What the tenant setup needs, checked before anything is created: a mistyped form leaves nothing behind.
@@ -449,11 +515,33 @@ export function portalHandler(o) {
449
515
  const cookie = { "set-cookie": setCookie(signSession(o.secret, user.id)) };
450
516
  if (!parsed) {
451
517
  log(`agent-custody portal: ${email} created an account`);
452
- return json(200, { email, tenant: null }, cookie);
518
+ void send(verificationMail(user));
519
+ return json(200, { email, tenant: null, emailVerified: false }, cookie);
453
520
  }
454
521
  const r = await onboard(user, parsed);
522
+ void send(verificationMail(user));
455
523
  return json(r.status, r.body, cookie);
456
524
  }
525
+ if (req.method === "GET" && url.pathname === "/verify-email") {
526
+ const who = readSession(o.secret, url.searchParams.get("token") ?? undefined);
527
+ if (!who?.startsWith("verify:"))
528
+ return page(400, "Link not valid", "This verification link is not valid or has expired. Sign in and ask for a new one from the account page.");
529
+ const u = await store.user(who.slice("verify:".length));
530
+ if (!u)
531
+ return page(400, "Link not valid", "This verification link belongs to no account.");
532
+ // Opening the link proves nothing: an attacker may have registered the address, and its owner may click the link. Only the account's own session confirms it, through POST /api/verify-email.
533
+ const token = url.searchParams.get("token");
534
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline'; connect-src 'self'" });
535
+ return void res.end(`<!doctype html><meta charset="utf-8"><title>Confirm your address</title><p style="font:15px system-ui;padding:2rem" id="m">Confirming ${esc(u.email)}...</p><script>
536
+ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ token: ${JSON.stringify(token).replace(/</g, "\\u003c")} }) }).then(async (r) => {
537
+ const b = await r.json().catch(() => ({}));
538
+ const m = document.getElementById("m");
539
+ if (r.ok) m.innerHTML = "Your address is confirmed. <a href='/'>Continue to your account</a>.";
540
+ else if (r.status === 401) m.innerHTML = "Sign in to this account with its password first, then open the link again. <a href='/'>Sign in</a>.";
541
+ else m.textContent = b.error || "The address was not confirmed.";
542
+ });
543
+ </script>`);
544
+ }
457
545
  // ---- sign in through a provider: the OAuth web flow, state in a short-lived signed cookie ----
458
546
  const provider = /^\/auth\/(github|google)(\/callback)?$/.exec(url.pathname);
459
547
  if (req.method === "GET" && provider && o.oauth?.[provider[1]]) {
@@ -462,7 +550,11 @@ export function portalHandler(o) {
462
550
  const redirectUri = `${portalBase}auth/${name}/callback`;
463
551
  const stateCookie = (value) => `custody_oauth=${value ?? ""}; Path=/auth; HttpOnly; SameSite=Lax${o.trustProxy ? "; Secure" : ""}; Max-Age=${value ? 600 : 0}`;
464
552
  if (!provider[2]) {
465
- const state = signSession(o.secret, `oauth:${name}:${randomBytes(16).toString("hex")}`, 600_000);
553
+ // ?link=1 from a signed-in session links the provider to that account instead of signing in; the state says so
554
+ const linking = url.searchParams.get("link") === "1";
555
+ if (linking && !userId)
556
+ return json(401, { error: "sign in first, then link a provider from the account page" });
557
+ const state = signSession(o.secret, `oauth:${name}:${linking ? `link:${userId}:` : ""}${randomBytes(16).toString("hex")}`, 600_000);
466
558
  const authorize = name === "github"
467
559
  ? `https://github.com/login/oauth/authorize?${new URLSearchParams({ client_id: conf.clientId, redirect_uri: redirectUri, scope: "user:email", state })}`
468
560
  : `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" })}`;
@@ -508,7 +600,28 @@ export function portalHandler(o) {
508
600
  log(`agent-custody portal: ${name} sign-in failed: ${e instanceof Error ? e.message : String(e)}`);
509
601
  return json(502, { error: `${name === "github" ? "GitHub" : "Google"} sign-in failed: ${e instanceof Error ? e.message : String(e)}` }, { "set-cookie": stateCookie(null) });
510
602
  }
511
- const user = await store.findOrCreateOAuthUser(name, subject, email);
603
+ const linkTo = /^oauth:[a-z]+:link:([^:]+):/.exec(stateUser)?.[1];
604
+ let user;
605
+ if (linkTo) {
606
+ // linking: the signed state records the session that started it (the Strict cookie does not come back from the provider), so the provider's email need not match; when it does, it also confirms the address
607
+ const owner = await store.user(linkTo);
608
+ if (!owner)
609
+ return json(401, { error: "the account that started the link no longer exists" }, { "set-cookie": stateCookie(null) });
610
+ await store.linkIdentity(name, subject, email, owner.id);
611
+ if (email === owner.email)
612
+ await store.markEmailVerified(owner.id);
613
+ log(`agent-custody portal: ${owner.email} linked ${name}`);
614
+ return page(200, "Linked", `${name === "github" ? "GitHub" : "Google"} is linked to ${esc(owner.email)}. <a href="/">Continue</a>.`, { "set-cookie": stateCookie(null) });
615
+ }
616
+ try {
617
+ user = await store.findOrCreateOAuthUser(name, subject, email);
618
+ }
619
+ catch (e) {
620
+ if (!(e instanceof UnverifiedAccountError))
621
+ throw e;
622
+ log(`agent-custody portal: ${name} sign-in for ${email} refused: the password account has not verified its address`);
623
+ return page(409, "Sign in with your password", `An account with the address ${esc(email)} already exists. <a href="/">Sign in with its password</a>, then link ${name === "github" ? "GitHub" : "Google"} from the account page.`, { "set-cookie": stateCookie(null) });
624
+ }
512
625
  log(`agent-custody portal: ${email} signed in with ${name}`);
513
626
  // A page, not a redirect: the session cookie is SameSite=Strict, and a redirect that started at the provider
514
627
  // would not carry it. The page's own navigation to / does.
@@ -535,8 +648,27 @@ export function portalHandler(o) {
535
648
  if (req.method !== "GET" && !(req.headers["content-type"] ?? "").startsWith("application/json"))
536
649
  return json(415, { error: "expected a JSON body" });
537
650
  const tenantId = await store.tenantOf(user.id);
651
+ const account = async () => ({ emailVerified: !!user.emailVerifiedAt, identities: await store.identities(user.id), providers: ["github", "google"].filter((p) => !!o.oauth?.[p]), mail: !!o.mail });
652
+ if (req.method === "POST" && url.pathname === "/api/verify-email") {
653
+ const who = readSession(o.secret, String((await jsonBody()).token ?? ""));
654
+ if (!who?.startsWith("verify:"))
655
+ return json(400, { error: "this verification link is not valid or has expired" });
656
+ if (who.slice("verify:".length) !== user.id)
657
+ return json(403, { error: "this link belongs to another account; sign in to the account it was sent for" });
658
+ await store.markEmailVerified(user.id);
659
+ log(`agent-custody portal: ${user.email} verified their address`);
660
+ return json(200, { ok: true, emailVerified: true });
661
+ }
662
+ if (req.method === "POST" && url.pathname === "/api/verify-email/resend") {
663
+ if (user.emailVerifiedAt)
664
+ return json(200, { ok: true, emailVerified: true });
665
+ if (!o.mail)
666
+ return json(503, { error: "mail is not configured on this portal" });
667
+ void send(verificationMail(user));
668
+ return json(200, { ok: true, emailVerified: false });
669
+ }
538
670
  if (req.method === "GET" && url.pathname === "/api/me" && !tenantId)
539
- return json(200, { email: user.email, tenant: null, profile: await store.profile(user.id), billing: !!o.stripe });
671
+ return json(200, { email: user.email, tenant: null, profile: await store.profile(user.id), billing: !!o.stripe, ...(await account()) });
540
672
  if (req.method === "POST" && url.pathname === "/api/onboard") {
541
673
  const p = await parseOnboarding(await jsonBody());
542
674
  if ("status" in p)
@@ -551,7 +683,7 @@ export function portalHandler(o) {
551
683
  return json(409, { error: "the tenant no longer exists" });
552
684
  if (req.method === "GET" && url.pathname === "/api/me") {
553
685
  const q = await o.tenancy.quota(tenantId);
554
- 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 });
686
+ 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, ...(await account()) });
555
687
  }
556
688
  if (req.method === "GET" && url.pathname === "/api/overview") {
557
689
  const q = await o.tenancy.quota(tenantId);
@@ -679,6 +811,7 @@ const PORTAL_PAGE = `<!doctype html>
679
811
  .top .who { color: var(--ink2); font-size: .9rem; margin-left: .5rem; }
680
812
  button.theme { background: transparent; color: var(--ink2); border: 1px solid var(--line); padding: .25rem .6rem; font-size: .8rem; border-radius: 4px; } button.theme:hover { color: var(--ink); }
681
813
  .pill { display: inline-block; padding: .05rem .5rem; border-radius: 999px; font: 600 .72rem/1.6 var(--mono); letter-spacing: .06em; text-transform: uppercase; background: var(--accent-bg); color: var(--accent); }
814
+ .notice { margin: 0 auto; max-width: 72rem; padding: .6rem 1.5rem; font-size: .9rem; color: var(--ink); background: var(--accent-bg); border-bottom: 1px solid var(--line); } .notice a, .notice button { margin-left: .6rem; } .notice button { font: inherit; background: none; border: 1px solid var(--line); border-radius: 4px; padding: .1rem .5rem; color: var(--ink); cursor: pointer; }
682
815
  .layout { display: grid; grid-template-columns: 15rem 1fr; min-height: calc(100vh - 3.3rem); }
683
816
  nav { border-right: 1px solid var(--line); background: var(--panel); padding: 1rem 0; }
684
817
  nav .group { font: 600 .68rem/1.4 var(--mono); letter-spacing: .12em; text-transform: uppercase; color: var(--accent); padding: 1rem 1.25rem .35rem; }
@@ -728,6 +861,7 @@ const PORTAL_PAGE = `<!doctype html>
728
861
  @media (max-width: 48rem) { .layout { grid-template-columns: 1fr; } nav { display: flex; flex-wrap: wrap; padding: .3rem; border-right: 0; border-bottom: 1px solid var(--line); } nav .group { display: none; } nav a { border-left: 0; border-bottom: 3px solid transparent; } nav a.on { border-bottom-color: var(--accent); } }
729
862
  </style>
730
863
  <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>
864
+ <div id="notice" class="notice" hidden></div>
731
865
  <section id="auth" class="auth" hidden>
732
866
  <h1 id="authTitle">Sign in</h1>
733
867
  <div id="providers" class="providers" hidden></div>
@@ -925,11 +1059,22 @@ const PORTAL_PAGE = `<!doctype html>
925
1059
  const enter = async () => {
926
1060
  try {
927
1061
  const me = await api("GET", "/api/me");
1062
+ accountNotice(me);
928
1063
  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; }
929
1064
  $("who").textContent = me.email; show("app"); await load(); view((location.hash || "#overview").slice(1) || "overview");
930
1065
  }
931
1066
  catch (err) { if (err.status === 401) { show("auth"); if (location.hash === "#register" && !registering) $("authSwap").click(); } else { show("app"); $("who").textContent = err.message; } }
932
1067
  };
1068
+ const accountNotice = (me) => {
1069
+ const parts = [];
1070
+ if (me.emailVerified === false && me.mail) parts.push("Verify your email address: we sent a link to " + me.email + ". <button type=button id=resendVerify>Send it again</button>");
1071
+ const unlinked = (me.providers || []).filter((p) => !(me.identities || []).includes(p));
1072
+ if (unlinked.length) parts.push("Sign in faster next time:" + unlinked.map((p) => "<a href='/auth/" + p + "?link=1'>Link " + (p === "github" ? "GitHub" : "Google") + "</a>").join(""));
1073
+ $("notice").innerHTML = parts.join(" &middot; ");
1074
+ $("notice").hidden = parts.length === 0;
1075
+ const b = document.getElementById("resendVerify");
1076
+ if (b) b.onclick = async () => { b.disabled = true; try { await api("POST", "/api/verify-email/resend", {}); b.textContent = "Sent"; } catch (e) { b.textContent = e.message; } };
1077
+ };
933
1078
  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("");
934
1079
  const loadPolicies = async () => {
935
1080
  const r = await api("GET", "/api/policies");
package/dist/receipt.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { Envelope } from "./crypto.ts";
2
+ import type { CaptureNote, Commitment } from "./capture.ts";
2
3
  import type { InclusionProof } from "./log.ts";
3
4
  import type { PolicyDecision } from "./policy.ts";
4
5
  import type { UpstreamEvidence } from "./upstream.ts";
@@ -23,8 +24,10 @@ export type IssuerKind = "gateway" | "sdk";
23
24
  export interface FactRecord {
24
25
  tool: string;
25
26
  args: Record<string, unknown>;
27
+ /** the value as recorded; under a capture rule, commitments where fields were withheld (the receipt's `capture` note names them) */
26
28
  value: unknown;
27
- resultDigest: string;
29
+ /** the digest of the lookup's full result; under a capture rule a commitment to that result (the receipt shows only the selected value, the rest is private), named in the `capture` note */
30
+ resultDigest: string | Commitment;
28
31
  provenance: "observed";
29
32
  }
30
33
  export interface ReceiptPredicate {
@@ -69,6 +72,7 @@ export interface ReceiptPredicate {
69
72
  provenance: Provenance;
70
73
  upstream?: string;
71
74
  };
75
+ /** `args` as the receipt carries them; `argsDigest` is over the whole call's arguments, salted from the field salts when any are withheld. Withheld fields hold commitments. */
72
76
  request: {
73
77
  args: Record<string, unknown>;
74
78
  argsDigest: string;
@@ -81,11 +85,12 @@ export interface ReceiptPredicate {
81
85
  * saw those results itself. Absent on SDK receipts. This is what the agent relied on, as an upper bound.
82
86
  */
83
87
  consumed?: {
84
- factIds: string[];
88
+ factIds: string[] | Commitment;
85
89
  provenance: "observed";
86
90
  };
87
- /** null when the issuer evaluated no policy. */
88
- policy: (PolicyDecision & {
91
+ /** null when the issuer evaluated no policy. Under a capture rule a non-empty `errors` is a commitment: the evaluator's messages can repeat a withheld value. */
92
+ policy: (Omit<PolicyDecision, "errors"> & {
93
+ errors: string[] | Commitment;
89
94
  provenance: Provenance;
90
95
  }) | null;
91
96
  /**
@@ -97,6 +102,7 @@ export interface ReceiptPredicate {
97
102
  authorization?: AuthorizationBundle;
98
103
  execution: {
99
104
  status: "executed" | "failed";
105
+ /** the result as the receipt carries it; `resultDigest` is over the whole result, salted from the field salts when any are withheld */
100
106
  result: unknown;
101
107
  resultDigest: string;
102
108
  provenance: Provenance;
@@ -104,22 +110,27 @@ export interface ReceiptPredicate {
104
110
  upstream?: UpstreamEvidence;
105
111
  } | {
106
112
  status: "denied";
107
- reason: string;
113
+ reason: string | Commitment;
108
114
  provenance: Provenance;
109
115
  } | {
110
116
  status: "error";
111
- error: string;
117
+ error: string | Commitment;
112
118
  provenance: Provenance;
113
119
  }
114
120
  /** the policy allowed the call but the gateway did not forward it, because the log would not commit the authorization first */
115
121
  | {
116
122
  status: "withheld";
117
- reason: string;
123
+ reason: string | Commitment;
118
124
  provenance: Provenance;
119
125
  };
126
+ /**
127
+ * Private evidence: present when a capture rule withheld anything. Names every path in this predicate that holds a
128
+ * commitment in place of its value, and the mode. A verifier trusts this note, not the shape of the data.
129
+ */
130
+ capture?: CaptureNote;
120
131
  }
121
132
  /** What the gateway commits before a consequential call goes out: everything the receipt will say, except the outcome. */
122
- export type AuthorizationPredicate = Pick<ReceiptPredicate, "receiptId" | "timestamp" | "issuer" | "principal" | "agent" | "delegation" | "tool" | "request" | "facts" | "consumed" | "policy">;
133
+ export type AuthorizationPredicate = Pick<ReceiptPredicate, "receiptId" | "timestamp" | "issuer" | "principal" | "agent" | "delegation" | "tool" | "request" | "facts" | "consumed" | "policy" | "capture">;
123
134
  export interface AuthorizationStatement {
124
135
  _type: "https://in-toto.io/Statement/v1";
125
136
  subject: {
@@ -1,3 +1,9 @@
1
+ /** where the issuer keeps the salts behind a receipt's commitments, under the receipts directory; private, pruned with the receipt */
2
+ export declare const SALTS_DIR = "salts";
3
+ /** a receipt id as the issuer mints it; anything else never becomes part of a path */
4
+ export declare const RECEIPT_ID: RegExp;
5
+ /** the salts file of a receipt, or a throw when the id (which may come from a bundle or a log line) is not one */
6
+ export declare function saltsFileFor(receiptsDir: string, receiptId: string): string;
1
7
  export interface PruneResult {
2
8
  pruned: {
3
9
  leafIndex: number;
@@ -9,6 +15,7 @@ export interface PruneResult {
9
15
  }
10
16
  /**
11
17
  * Prunes every leaf whose receipt timestamp is before the cutoff. Leaves already pruned, and leaves that are not
12
- * receipts, are left as they are. Rewrites the log file in place and deletes the pruned receipts' bundle files.
18
+ * receipts, are left as they are. Rewrites the log file in place and deletes the pruned receipts' bundle files, and
19
+ * the salts the issuer kept for them.
13
20
  */
14
21
  export declare function pruneLog(logFile: string, before: string, receiptsDir?: string): PruneResult;
package/dist/retention.js CHANGED
@@ -6,6 +6,16 @@
6
6
  import { existsSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
7
7
  import { join } from "node:path";
8
8
  import { leafHash } from "./log.js";
9
+ /** where the issuer keeps the salts behind a receipt's commitments, under the receipts directory; private, pruned with the receipt */
10
+ export const SALTS_DIR = "salts";
11
+ /** a receipt id as the issuer mints it; anything else never becomes part of a path */
12
+ export const RECEIPT_ID = /^[A-Za-z0-9-]{1,64}$/;
13
+ /** the salts file of a receipt, or a throw when the id (which may come from a bundle or a log line) is not one */
14
+ export function saltsFileFor(receiptsDir, receiptId) {
15
+ if (!RECEIPT_ID.test(receiptId))
16
+ throw new Error(`receipt id ${JSON.stringify(receiptId)} is not a valid id`);
17
+ return join(receiptsDir, SALTS_DIR, `${receiptId}.json`);
18
+ }
9
19
  function receiptOf(leaf) {
10
20
  try {
11
21
  const env = JSON.parse(leaf);
@@ -18,7 +28,8 @@ function receiptOf(leaf) {
18
28
  }
19
29
  /**
20
30
  * Prunes every leaf whose receipt timestamp is before the cutoff. Leaves already pruned, and leaves that are not
21
- * receipts, are left as they are. Rewrites the log file in place and deletes the pruned receipts' bundle files.
31
+ * receipts, are left as they are. Rewrites the log file in place and deletes the pruned receipts' bundle files, and
32
+ * the salts the issuer kept for them.
22
33
  */
23
34
  export function pruneLog(logFile, before, receiptsDir) {
24
35
  const lines = readFileSync(logFile, "utf8").split("\n").filter((l) => l.trim());
@@ -34,12 +45,20 @@ export function pruneLog(logFile, before, receiptsDir) {
34
45
  if (timestamp !== null && timestamp < before) {
35
46
  out.push(JSON.stringify({ pruned: leafHash(parsed).toString("hex") }));
36
47
  result.pruned.push({ leafIndex: i, receiptId, timestamp });
37
- if (receiptsDir && receiptId) {
48
+ // the id comes from a log line: it never becomes part of a path unless it is one the issuer could have minted
49
+ if (receiptsDir && receiptId && RECEIPT_ID.test(receiptId)) {
38
50
  const bundle = join(receiptsDir, `${receiptId}.json`);
39
51
  if (existsSync(bundle)) {
40
52
  unlinkSync(bundle);
41
53
  result.bundlesRemoved++;
42
54
  }
55
+ const salts = saltsFileFor(receiptsDir, receiptId);
56
+ if (existsSync(salts))
57
+ unlinkSync(salts);
58
+ // the authorization committed before the call carries the same call: it goes too
59
+ const authorization = join(receiptsDir, `${receiptId}.authorization.json`);
60
+ if (existsSync(authorization))
61
+ unlinkSync(authorization);
43
62
  }
44
63
  }
45
64
  else {
package/dist/sdk/index.js CHANGED
@@ -1,6 +1,7 @@
1
1
  // The interceptor SDK: issues receipts from inside the agent's own process.
2
2
  // Everything it records is "claimed", because the issuer shares a process with the agent. The receipt says so.
3
3
  import { randomUUID } from "node:crypto";
4
+ import { captureKeyFrom } from "../capture.js";
4
5
  import { readFileSync } from "node:fs";
5
6
  import { digestOf, loadPrivateKey } from "../crypto.js";
6
7
  import { createIssuer } from "../issue.js";
@@ -26,7 +27,14 @@ export class PolicyDeniedError extends Error {
26
27
  }
27
28
  export function createSdkIssuer(cfg) {
28
29
  const key = loadPrivateKey(cfg.identity.keyFile);
29
- const issuer = createIssuer(key, cfg.receiptsDir, openLog(cfg, key), { exporter: openExporter(cfg) });
30
+ const captureKey = cfg.captureKeyEnv ? captureKeyFrom(process.env[cfg.captureKeyEnv] ?? (() => { throw new Error(`capture key: environment variable ${cfg.captureKeyEnv} is not set`); })()) : undefined;
31
+ for (const [tool, rule] of Object.entries(cfg.capture ?? {})) {
32
+ for (const side of [rule.args, rule.result, rule.facts])
33
+ if (side?.mode === "encrypted" && !captureKey)
34
+ throw new Error(`capture for ${tool} uses mode encrypted, which needs captureKeyEnv`);
35
+ }
36
+ // the capture rules are applied by the issuer to every statement it signs, so every adapter's receipt gets them
37
+ const issuer = createIssuer(key, cfg.receiptsDir, openLog(cfg, key), { exporter: openExporter(cfg), capture: { rules: cfg.capture, key: captureKey } });
30
38
  const policyText = cfg.policyFile ? readFileSync(cfg.policyFile, "utf8") : null;
31
39
  const decide = (ev) => {
32
40
  if (policyText === null)
@@ -35,6 +43,7 @@ export function createSdkIssuer(cfg) {
35
43
  return cfg.mode === "observe" ? { ...d, enforced: false } : d;
36
44
  };
37
45
  function record(ev, outcome, policy = null) {
46
+ // the call in full; the issuer withholds what the tool's capture rule says, the thrown message included
38
47
  const execution = outcome.status === "denied"
39
48
  ? { status: "denied", reason: outcome.reason, provenance: "claimed" }
40
49
  : outcome.status === "error"
package/dist/splunk.js CHANGED
@@ -2,6 +2,8 @@
2
2
  export function hecEvent(p, bundle, cfg) {
3
3
  const auth = p.authorization;
4
4
  const exec = p.execution;
5
+ // under a capture rule a message is a commitment; the event says so rather than carrying it
6
+ const text = (v) => (typeof v === "string" ? v : v && typeof v === "object" ? "(withheld under the capture rule)" : undefined);
5
7
  return {
6
8
  time: Date.parse(p.timestamp) / 1000,
7
9
  source: cfg.source ?? "agent-custody",
@@ -18,7 +20,7 @@ export function hecEvent(p, bundle, cfg) {
18
20
  agent_provenance: p.agent.provenance,
19
21
  principal: p.principal.id,
20
22
  status: exec.status,
21
- reason: exec.reason ?? exec.error ?? null,
23
+ reason: text(exec.reason) ?? text(exec.error) ?? null,
22
24
  policy_decision: p.policy?.decision ?? null,
23
25
  policy_digest: p.policy?.policyDigest ?? null,
24
26
  policy_reasons: p.policy?.reasons ?? [],
@@ -26,9 +28,9 @@ export function hecEvent(p, bundle, cfg) {
26
28
  log_leaf_index: bundle.inclusion.leafIndex,
27
29
  log_tree_size: bundle.inclusion.treeSize,
28
30
  authorization_leaf_index: auth ? auth.inclusion.leafIndex : null,
29
- consumed_count: p.consumed?.factIds.length ?? 0,
30
- model: p.model.id,
31
- session: p.session.id,
31
+ consumed_count: (Array.isArray(p.consumed?.factIds) ? p.consumed.factIds.length : 0) ?? 0,
32
+ model: text(p.model.id) ?? null,
33
+ session: text(p.session.id) ?? null,
32
34
  },
33
35
  };
34
36
  }
@@ -1,5 +1,6 @@
1
1
  import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js";
2
2
  import { type Envelope, type KeyPair, type PublicKeyRef } from "./crypto.ts";
3
+ import { type Commitment } from "./capture.ts";
3
4
  export declare const UPSTREAM_SIG_META_KEY = "agent-custody/upstream-signature";
4
5
  export declare const UPSTREAM_TYPE = "application/vnd.agent-custody.upstream+json";
5
6
  export interface UpstreamAttestation {
@@ -27,17 +28,18 @@ export type UpstreamCheck = {
27
28
  export declare function checkUpstream(envelope: Envelope, keys: PublicKeyRef[], expected: UpstreamAttestation): UpstreamCheck;
28
29
  export interface ProviderAttestation {
29
30
  provider: "stripe-webhook" | "github-delivery";
30
- /** the delivery body exactly as received; the HMAC is over these bytes */
31
- rawBody: string;
32
- /** Stripe: the Stripe-Signature header; GitHub: the X-Hub-Signature-256 header */
33
- signature: string;
34
- /** dot path into the parsed body whose value must appear in the receipt's result, e.g. data.object.id */
35
- bind: string;
31
+ /** the delivery body exactly as received; the HMAC is over these bytes. Under a private capture rule the receipt carries a commitment here instead, and the body is disclosed or revealed to check the delivery (capture.ts) */
32
+ rawBody: string | Commitment;
33
+ /** Stripe: the Stripe-Signature header; GitHub: the X-Hub-Signature-256 header. A MAC over the body: withheld with it under a private rule */
34
+ signature: string | Commitment;
35
+ /** dot path into the parsed body whose value must appear in the receipt's result, e.g. data.object.id; upstream-chosen, withheld with the body under a private rule */
36
+ bind: string | Commitment;
36
37
  /** GitHub: the X-GitHub-Delivery id, for the record */
37
38
  deliveryId?: string;
38
39
  }
40
+ /** under a private result rule the envelope, or the delivery body, is a commitment in the receipt, restored by the verifier with the result */
39
41
  export type UpstreamEvidence = {
40
- envelope: Envelope;
42
+ envelope: Envelope | Commitment;
41
43
  } | ProviderAttestation;
42
44
  export declare function isProviderAttestation(v: unknown): v is ProviderAttestation;
43
45
  /** For upstreams wrapping a provider: attaches the provider's own delivery for this call. */