@agent-custody/receipts 0.6.19 → 0.8.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.
Files changed (50) hide show
  1. package/README.md +20 -11
  2. package/dist/a2a.js +19 -7
  3. package/dist/approval.d.ts +74 -0
  4. package/dist/approval.js +196 -0
  5. package/dist/capture.d.ts +153 -0
  6. package/dist/capture.js +607 -0
  7. package/dist/cli.js +221 -6
  8. package/dist/config.d.ts +144 -0
  9. package/dist/config.js +92 -3
  10. package/dist/crypto.d.ts +2 -2
  11. package/dist/crypto.js +7 -4
  12. package/dist/delegation.d.ts +7 -0
  13. package/dist/delegation.js +15 -1
  14. package/dist/gateway-http.js +13 -1
  15. package/dist/gateway.d.ts +15 -0
  16. package/dist/gateway.js +414 -27
  17. package/dist/index.d.ts +4 -0
  18. package/dist/index.js +4 -0
  19. package/dist/issue.d.ts +20 -5
  20. package/dist/issue.js +76 -8
  21. package/dist/log-sink.d.ts +11 -1
  22. package/dist/log-sink.js +24 -5
  23. package/dist/operations.d.ts +101 -0
  24. package/dist/operations.js +239 -0
  25. package/dist/otel.js +16 -8
  26. package/dist/portal.d.ts +23 -2
  27. package/dist/portal.js +181 -36
  28. package/dist/receipt.d.ts +54 -8
  29. package/dist/rest.js +14 -1
  30. package/dist/retention.d.ts +8 -1
  31. package/dist/retention.js +21 -2
  32. package/dist/sdk/index.js +10 -1
  33. package/dist/simulate.d.ts +58 -0
  34. package/dist/simulate.js +204 -0
  35. package/dist/splunk.js +17 -8
  36. package/dist/upstream.d.ts +9 -7
  37. package/dist/upstream.js +16 -8
  38. package/dist/verify.d.ts +18 -0
  39. package/dist/verify.js +405 -15
  40. package/docs/approvals.md +107 -0
  41. package/docs/compliance.md +1 -1
  42. package/docs/financial-operations.md +99 -0
  43. package/docs/policies.md +22 -0
  44. package/docs/tutorials.md +7 -0
  45. package/docs/usage.md +71 -5
  46. package/docs/verification.md +35 -10
  47. package/package.json +1 -1
  48. package/vectors/audit.json +27 -27
  49. package/vectors/canonical.json +5 -5
  50. package/vectors/receipts.json +3612 -292
package/dist/otel.js CHANGED
@@ -7,26 +7,33 @@ export function spanFor(p, bundle, serviceName) {
7
7
  const traceId = hex.length === 32 ? hex : hex.padEnd(32, "0").slice(0, 32);
8
8
  const start = BigInt(Date.parse(p.timestamp)) * 1000000n;
9
9
  const end = BigInt(Date.now()) * 1000000n;
10
- const status = p.execution.status;
10
+ // A reconciliation receipt records a provider read that the gateway made. The gateway evaluated no policy, and it did
11
+ // not execute the payment tool again. The span says so: a dashboard must not count it as a second allowed call.
12
+ const reconciliation = p.reconciliation !== undefined;
13
+ const status = reconciliation ? "reconciled" : p.execution.status;
14
+ const operationFailed = reconciliation && p.operation?.status === "failed";
11
15
  const auth = p.authorization;
12
16
  const attributes = [
13
17
  ...str("agent_custody.receipt_id", p.receiptId),
14
18
  ...str("agent_custody.issuer.kind", p.issuer.kind),
15
19
  ...str("agent_custody.issuer.keyid", p.issuer.keyid),
16
20
  ...str("agent_custody.tool", p.tool.name),
21
+ ...(reconciliation ? [{ key: "agent_custody.reconciliation", value: { boolValue: true } }, ...str("agent_custody.reconciliation.lookup_tool", p.reconciliation.lookup?.tool)] : []),
22
+ ...str("agent_custody.operation.status", p.operation?.status),
23
+ ...str("agent_custody.operation.original_receipt_id", p.operation?.originalReceiptId),
17
24
  ...str("agent_custody.upstream", p.tool.upstream),
18
25
  ...str("agent_custody.agent", p.agent.id),
19
26
  ...str("agent_custody.agent.provenance", p.agent.provenance),
20
27
  ...str("agent_custody.principal", p.principal.id),
21
28
  ...str("agent_custody.execution.status", status),
22
- ...str("agent_custody.policy.decision", p.policy?.decision),
23
- ...str("agent_custody.policy.digest", p.policy?.policyDigest),
29
+ ...(reconciliation ? [] : str("agent_custody.policy.decision", p.policy?.decision)),
30
+ ...(reconciliation ? [] : str("agent_custody.policy.digest", p.policy?.policyDigest)),
24
31
  ...int("agent_custody.log.leaf_index", bundle.inclusion.leafIndex),
25
32
  ...int("agent_custody.log.tree_size", bundle.inclusion.treeSize),
26
33
  ...(auth ? int("agent_custody.authorization.leaf_index", auth.inclusion.leafIndex) : []),
27
- ...int("agent_custody.consumed.count", p.consumed?.factIds.length ?? 0),
28
- ...str("agent_custody.model", p.model.id),
29
- ...str("agent_custody.session", p.session.id),
34
+ ...int("agent_custody.consumed.count", Array.isArray(p.consumed?.factIds) ? p.consumed.factIds.length : 0),
35
+ ...str("agent_custody.model", typeof p.model.id === "string" ? p.model.id : undefined),
36
+ ...str("agent_custody.session", typeof p.session.id === "string" ? p.session.id : undefined),
30
37
  ];
31
38
  return {
32
39
  resourceSpans: [
@@ -39,12 +46,13 @@ export function spanFor(p, bundle, serviceName) {
39
46
  {
40
47
  traceId,
41
48
  spanId: traceId.slice(0, 16),
42
- name: `${p.tool.name}`,
49
+ name: reconciliation ? `${p.tool.name} reconciliation` : `${p.tool.name}`,
43
50
  kind: 3, // CLIENT: the agent calling out
44
51
  startTimeUnixNano: start.toString(),
45
52
  endTimeUnixNano: (end > start ? end : start).toString(),
46
53
  attributes,
47
- status: status === "executed" || status === "denied" || status === "withheld" ? { code: 1 } : { code: 2, message: status === "failed" ? "the upstream reported failure" : p.execution.error ?? status },
54
+ // Status.message is a string in OTLP; under a capture rule the error is a commitment, and the span says so
55
+ status: operationFailed ? { code: 2, message: "the provider reports that the operation failed" } : status === "executed" || status === "reconciled" || status === "denied" || status === "withheld" ? { code: 1 } : { code: 2, message: status === "failed" ? "the upstream reported failure" : typeof p.execution.error === "string" ? (p.execution.error) : p.execution.error ? "the upstream reported an error (withheld under the capture rule)" : status },
48
56
  },
49
57
  ],
50
58
  },
package/dist/portal.d.ts CHANGED
@@ -56,6 +56,13 @@ export interface PortalUser {
56
56
  id: string;
57
57
  email: string;
58
58
  createdAt: string;
59
+ /** when the address was confirmed: by a verification link, or by a provider that vouched for it; null until then */
60
+ emailVerifiedAt?: string | null;
61
+ }
62
+ /** A provider sign-in whose verified email belongs to a password account that never verified its address: refused, never linked (issue #103). */
63
+ export declare class UnverifiedAccountError extends Error {
64
+ email: string;
65
+ constructor(email: string);
59
66
  }
60
67
  /** Users, memberships, and billing records, beside the log's tables. */
61
68
  /** What a registration says about the person and the organisation; every field optional in the store, the route decides what it requires. */
@@ -76,6 +83,11 @@ export declare class PortalStore {
76
83
  static checkPassword(password: string, stored: string): boolean;
77
84
  createUser(email: string, password: string, profile?: Profile): Promise<PortalUser>;
78
85
  userByEmail(email: string): Promise<PortalUser | null>;
86
+ private static asUser;
87
+ markEmailVerified(userId: string, at?: Date): Promise<void>;
88
+ /** Links a provider identity to a signed-in account: the account proved itself with its session, so the provider's email need not match. */
89
+ linkIdentity(provider: string, subject: string, email: string, userId: string): Promise<void>;
90
+ identities(userId: string): Promise<string[]>;
79
91
  /** the account's profile, for the onboarding screen and the operator's note */
80
92
  profile(userId: string): Promise<Profile>;
81
93
  /** Accounts with a tenant, a name, and no founder's note yet, registered inside the window: the hourly job's work list. */
@@ -94,8 +106,11 @@ export declare class PortalStore {
94
106
  markFollowedUp(userId: string, at?: Date): Promise<void>;
95
107
  updateProfile(userId: string, profile: Profile): Promise<void>;
96
108
  /**
97
- * The account behind a provider sign-in: the linked one, else the account with that verified email (linked from
98
- * now on), else a new account with a random password nobody knows. The provider's email must be verified.
109
+ * The account behind a provider sign-in: the linked one; else the account with that email, linked from now on, but
110
+ * only if that account has verified its address (otherwise anyone could register a victim's address with a
111
+ * password, wait for the victim to sign in with Google, and keep password access to the merged account: issue
112
+ * #103; the refusal is UnverifiedAccountError); else a new account with a random password nobody knows, its address
113
+ * counted as verified because the provider vouched for it. The provider's email must be verified.
99
114
  */
100
115
  findOrCreateOAuthUser(provider: string, subject: string, email: string): Promise<PortalUser>;
101
116
  authenticate(email: string, password: string): Promise<PortalUser | null>;
@@ -107,12 +122,18 @@ export declare class PortalStore {
107
122
  customerId?: string | null;
108
123
  subscriptionId?: string | null;
109
124
  status: string;
125
+ eventCreated?: number;
110
126
  }): Promise<void>;
111
127
  billing(tenantId: string): Promise<{
112
128
  customerId: string | null;
113
129
  subscriptionId: string | null;
114
130
  status: string;
131
+ eventCreated: number | null;
115
132
  } | null>;
133
+ /** Has this Stripe event id been applied already? */
134
+ stripeEventSeen(id: string): Promise<boolean>;
135
+ /** Records a Stripe event id as applied, after it was applied, so a failure before this point lets Stripe's retry through. */
136
+ noteStripeEvent(id: string): Promise<void>;
116
137
  /** Every portal registration with its tenant and billing state, oldest first: what the operator's admin page lists. */
117
138
  registrations(): Promise<({
118
139
  tenantId: string;
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,7 +1,10 @@
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";
6
+ import type { ApprovalRecord } from "./approval.ts";
7
+ export type { ApprovalRecord } from "./approval.ts";
5
8
  export declare const RECEIPT_TYPE = "application/vnd.in-toto+json";
6
9
  export declare const RECEIPT_PREDICATE_TYPE = "https://agent-custody.dev/receipt/v0.2";
7
10
  /** The statement a gateway commits to the log before forwarding a consequential call; the receipt for that call embeds it. */
@@ -23,10 +26,40 @@ export type IssuerKind = "gateway" | "sdk";
23
26
  export interface FactRecord {
24
27
  tool: string;
25
28
  args: Record<string, unknown>;
29
+ /** the value as recorded; under a capture rule, commitments where fields were withheld (the receipt's `capture` note names them) */
26
30
  value: unknown;
27
- resultDigest: string;
31
+ /** 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 */
32
+ resultDigest: string | Commitment;
28
33
  provenance: "observed";
29
34
  }
35
+ /** A gateway's durable financial operation identity; execution still describes only the tool/API call. */
36
+ export interface OperationEvidence {
37
+ id: string;
38
+ idempotencyKey: string;
39
+ /** Commits the configured provider read and status mapping before the financial call is forwarded. */
40
+ lookupDigest: string;
41
+ status: "submitted" | "pending" | "confirmed" | "failed" | "unknown";
42
+ /** Amounts stay in the original request, under its capture rule, rather than being copied into public metadata. */
43
+ budget: {
44
+ id: string;
45
+ currency: string;
46
+ period: string;
47
+ };
48
+ originalReceiptId: string;
49
+ provenance: "observed";
50
+ }
51
+ /** A later provider read, observed by the gateway, linked to the original signed, logged operation. */
52
+ export interface ReconciliationEvidence {
53
+ original: ReceiptBundle | AuthorizationBundle;
54
+ lookup: {
55
+ tool: string;
56
+ args: Record<string, unknown>;
57
+ statusPath: string;
58
+ identityPath: string;
59
+ confirmed: string[];
60
+ failed: string[];
61
+ };
62
+ }
30
63
  export interface ReceiptPredicate {
31
64
  receiptId: string;
32
65
  timestamp: string;
@@ -53,6 +86,8 @@ export interface ReceiptPredicate {
53
86
  envelope: Envelope;
54
87
  provenance: "attested";
55
88
  };
89
+ /** The gateway's payload-bound human approval check, when this tool requires approval. */
90
+ approval?: ApprovalRecord;
56
91
  /** Correlation ids from the host, when it supplied any. Never checked, always claimed. */
57
92
  session: {
58
93
  id: string | null;
@@ -69,6 +104,7 @@ export interface ReceiptPredicate {
69
104
  provenance: Provenance;
70
105
  upstream?: string;
71
106
  };
107
+ /** `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
108
  request: {
73
109
  args: Record<string, unknown>;
74
110
  argsDigest: string;
@@ -81,11 +117,12 @@ export interface ReceiptPredicate {
81
117
  * saw those results itself. Absent on SDK receipts. This is what the agent relied on, as an upper bound.
82
118
  */
83
119
  consumed?: {
84
- factIds: string[];
120
+ factIds: string[] | Commitment;
85
121
  provenance: "observed";
86
122
  };
87
- /** null when the issuer evaluated no policy. */
88
- policy: (PolicyDecision & {
123
+ /** 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. */
124
+ policy: (Omit<PolicyDecision, "errors"> & {
125
+ errors: string[] | Commitment;
89
126
  provenance: Provenance;
90
127
  }) | null;
91
128
  /**
@@ -95,8 +132,12 @@ export interface ReceiptPredicate {
95
132
  * side effect exists only after the side effect.
96
133
  */
97
134
  authorization?: AuthorizationBundle;
135
+ operation?: OperationEvidence;
136
+ /** The provider read's full result is execution.result and follows the ordinary result capture rule. */
137
+ reconciliation?: ReconciliationEvidence;
98
138
  execution: {
99
139
  status: "executed" | "failed";
140
+ /** the result as the receipt carries it; `resultDigest` is over the whole result, salted from the field salts when any are withheld */
100
141
  result: unknown;
101
142
  resultDigest: string;
102
143
  provenance: Provenance;
@@ -104,22 +145,27 @@ export interface ReceiptPredicate {
104
145
  upstream?: UpstreamEvidence;
105
146
  } | {
106
147
  status: "denied";
107
- reason: string;
148
+ reason: string | Commitment;
108
149
  provenance: Provenance;
109
150
  } | {
110
151
  status: "error";
111
- error: string;
152
+ error: string | Commitment;
112
153
  provenance: Provenance;
113
154
  }
114
155
  /** the policy allowed the call but the gateway did not forward it, because the log would not commit the authorization first */
115
156
  | {
116
157
  status: "withheld";
117
- reason: string;
158
+ reason: string | Commitment;
118
159
  provenance: Provenance;
119
160
  };
161
+ /**
162
+ * Private evidence: present when a capture rule withheld anything. Names every path in this predicate that holds a
163
+ * commitment in place of its value, and the mode. A verifier trusts this note, not the shape of the data.
164
+ */
165
+ capture?: CaptureNote;
120
166
  }
121
167
  /** 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">;
168
+ export type AuthorizationPredicate = Pick<ReceiptPredicate, "receiptId" | "timestamp" | "issuer" | "principal" | "agent" | "delegation" | "approval" | "tool" | "request" | "facts" | "consumed" | "policy" | "capture" | "operation">;
123
169
  export interface AuthorizationStatement {
124
170
  _type: "https://in-toto.io/Statement/v1";
125
171
  subject: {