@agent-custody/receipts 0.8.0 → 0.10.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,7 @@ 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
+ import { oidcAuthorizeUrl, oidcExchange, pkce, samlAuthorizeUrl, samlValidate } from "./sso.js";
17
18
  /** A provider sign-in whose verified email belongs to a password account that never verified its address: refused, never linked (issue #103). */
18
19
  export class UnverifiedAccountError extends Error {
19
20
  email;
@@ -22,12 +23,41 @@ export class UnverifiedAccountError extends Error {
22
23
  this.email = email;
23
24
  }
24
25
  }
26
+ /** A single sign-on identity that the tenant's rules refuse: another domain, or an account in another tenant. */
27
+ export class SsoRefusedError extends Error {
28
+ }
25
29
  const ident = (s) => {
26
30
  if (!/^[a-z_][a-z0-9_]*$/.test(s))
27
31
  throw new Error(`prefix must be a plain identifier; got "${s}"`);
28
32
  return s;
29
33
  };
30
34
  const PROFILE_COLUMNS = ["name", "company", "role", "phone", "telegram"];
35
+ /** Lowest first. */
36
+ export const ROLES = ["readonly", "reviewer", "admin", "owner"];
37
+ // ---- TOTP (RFC 6238) ----
38
+ const B32 = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
39
+ export const base32 = (b) => {
40
+ const bits = [...b].map((x) => x.toString(2).padStart(8, "0")).join("");
41
+ return (bits.match(/.{1,5}/g) ?? []).map((c) => B32[parseInt(c.padEnd(5, "0"), 2)]).join("");
42
+ };
43
+ export function totp(key, step) {
44
+ const counter = Buffer.alloc(8);
45
+ counter.writeBigUInt64BE(BigInt(step));
46
+ const mac = createHmac("sha1", key).update(counter).digest();
47
+ const at = mac[19] & 15;
48
+ return String((mac.readUInt32BE(at) & 0x7fffffff) % 1_000_000).padStart(6, "0");
49
+ }
50
+ /** The time step the code matches, one step either side of now allowed; null when none. */
51
+ export function totpStep(key, code, now = Date.now()) {
52
+ const here = Math.floor(now / 30_000);
53
+ for (const step of [here - 1, here, here + 1]) {
54
+ const want = Buffer.from(totp(key, step));
55
+ const got = Buffer.from(code);
56
+ if (got.length === want.length && timingSafeEqual(got, want))
57
+ return step;
58
+ }
59
+ return null;
60
+ }
31
61
  export class PortalStore {
32
62
  client;
33
63
  p;
@@ -57,6 +87,15 @@ export class PortalStore {
57
87
  await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS email_verified_at TIMESTAMPTZ`);
58
88
  // a provider identity linked to an account: GitHub or Google's stable subject, and the verified email it gave
59
89
  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))`);
90
+ await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS mfa_secret TEXT`);
91
+ await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS mfa_enabled_at TIMESTAMPTZ`);
92
+ await this.client.query(`ALTER TABLE ${p}users ADD COLUMN IF NOT EXISTS mfa_last_step BIGINT`);
93
+ await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}invites (tenant_id TEXT NOT NULL, email TEXT NOT NULL, role TEXT NOT NULL, invited_by TEXT NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT now(), PRIMARY KEY (tenant_id, email))`);
94
+ // who an admin removed from a tenant: single sign-on does not let them back in on its own
95
+ await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}removed (tenant_id TEXT NOT NULL, user_id TEXT NOT NULL, PRIMARY KEY (tenant_id, user_id))`);
96
+ // the address too, so the removal holds after the account is made again under a new id
97
+ await this.client.query(`ALTER TABLE ${p}removed ADD COLUMN IF NOT EXISTS email TEXT`);
98
+ await this.client.query(`CREATE TABLE IF NOT EXISTS ${p}sso (tenant_id TEXT PRIMARY KEY, protocol TEXT NOT NULL, config TEXT NOT NULL, domains TEXT[] NOT NULL, default_role TEXT NOT NULL, enforced BOOLEAN NOT NULL DEFAULT false, updated_at TIMESTAMPTZ NOT NULL DEFAULT now())`);
60
99
  })();
61
100
  }
62
101
  return this.ready;
@@ -164,9 +203,158 @@ export class PortalStore {
164
203
  const rows = (await this.client.query(`SELECT id, email, created_at, email_verified_at FROM ${this.p}users WHERE id = $1`, [id])).rows;
165
204
  return rows[0] ? PortalStore.asUser(rows[0]) : null;
166
205
  }
167
- async addMember(userId, tenantId) {
206
+ async addMember(userId, tenantId, role = "owner") {
207
+ await this.init();
208
+ await this.client.query(`INSERT INTO ${this.p}members (user_id, tenant_id, role) VALUES ($1, $2, $3) ON CONFLICT DO NOTHING`, [userId, tenantId, role]);
209
+ }
210
+ async roleOf(userId, tenantId) {
211
+ await this.init();
212
+ const rows = (await this.client.query(`SELECT role FROM ${this.p}members WHERE user_id = $1 AND tenant_id = $2`, [userId, tenantId])).rows;
213
+ return rows[0]?.role ?? null;
214
+ }
215
+ async members(tenantId) {
216
+ await this.init();
217
+ const rows = (await this.client.query(`SELECT u.id, u.email, m.role, m.created_at, u.mfa_enabled_at FROM ${this.p}members m JOIN ${this.p}users u ON u.id = m.user_id WHERE m.tenant_id = $1 ORDER BY m.created_at, u.email`, [tenantId])).rows;
218
+ return rows.map((r) => ({ id: String(r.id), email: String(r.email), role: r.role, joinedAt: new Date(r.created_at).toISOString(), mfa: !!r.mfa_enabled_at }));
219
+ }
220
+ // Both statements skip the row of the last owner, and return false then.
221
+ async setRole(tenantId, userId, role) {
222
+ await this.init();
223
+ return (await this.client.query(`UPDATE ${this.p}members SET role = $3 WHERE user_id = $1 AND tenant_id = $2 AND ($3 = 'owner' OR role <> 'owner' OR EXISTS (SELECT 1 FROM ${this.p}members o WHERE o.tenant_id = $2 AND o.role = 'owner' AND o.user_id <> $1)) RETURNING user_id`, [userId, tenantId, role])).rows.length > 0;
224
+ }
225
+ // The removal record stays after a rejoin by invite. It has no effect while the user is a member: only findOrCreateSsoUser reads it, and only when the home tenant differs.
226
+ async removeMember(tenantId, userId) {
227
+ await this.init();
228
+ const gone = (await this.client.query(`DELETE FROM ${this.p}members WHERE user_id = $1 AND tenant_id = $2 AND (role <> 'owner' OR EXISTS (SELECT 1 FROM ${this.p}members o WHERE o.tenant_id = $2 AND o.role = 'owner' AND o.user_id <> $1)) RETURNING user_id`, [userId, tenantId])).rows.length > 0;
229
+ if (gone)
230
+ await this.client.query(`INSERT INTO ${this.p}removed (tenant_id, user_id, email) SELECT $1, id, email FROM ${this.p}users WHERE id = $2 ON CONFLICT DO NOTHING`, [tenantId, userId]);
231
+ return gone;
232
+ }
233
+ async invite(tenantId, email, role, by) {
234
+ await this.init();
235
+ await this.client.query(`INSERT INTO ${this.p}invites (tenant_id, email, role, invited_by) VALUES ($1, $2, $3, $4) ON CONFLICT (tenant_id, email) DO UPDATE SET role = EXCLUDED.role, invited_by = EXCLUDED.invited_by, created_at = now()`, [tenantId, email, role, by]);
236
+ }
237
+ async invitesOf(tenantId) {
238
+ await this.init();
239
+ const rows = (await this.client.query(`SELECT email, role, invited_by, created_at FROM ${this.p}invites WHERE tenant_id = $1 ORDER BY created_at`, [tenantId])).rows;
240
+ return rows.map((r) => ({ email: String(r.email), role: r.role, invitedBy: String(r.invited_by), createdAt: new Date(r.created_at).toISOString() }));
241
+ }
242
+ async invitesFor(email) {
243
+ await this.init();
244
+ const rows = (await this.client.query(`SELECT tenant_id, role FROM ${this.p}invites WHERE email = $1 AND created_at > now() - interval '7 days' ORDER BY created_at`, [email])).rows;
245
+ return rows.map((r) => ({ tenant: r.tenant_id, role: r.role }));
246
+ }
247
+ async removeInvite(tenantId, email) {
248
+ await this.init();
249
+ return (await this.client.query(`DELETE FROM ${this.p}invites WHERE tenant_id = $1 AND email = $2 RETURNING email`, [tenantId, email])).rows.length > 0;
250
+ }
251
+ async takeInvite(tenantId, email) {
252
+ await this.init();
253
+ const rows = (await this.client.query(`DELETE FROM ${this.p}invites WHERE tenant_id = $1 AND email = $2 AND created_at > now() - interval '7 days' RETURNING role`, [tenantId, email])).rows;
254
+ return rows[0]?.role ?? null;
255
+ }
256
+ async mfa(userId) {
168
257
  await this.init();
169
- await this.client.query(`INSERT INTO ${this.p}members (user_id, tenant_id) VALUES ($1, $2) ON CONFLICT DO NOTHING`, [userId, tenantId]);
258
+ const rows = (await this.client.query(`SELECT mfa_secret, mfa_enabled_at FROM ${this.p}users WHERE id = $1`, [userId])).rows;
259
+ return { secret: rows[0]?.mfa_secret ? String(rows[0].mfa_secret) : null, enabled: !!rows[0]?.mfa_enabled_at };
260
+ }
261
+ async setMfaSecret(userId, secretHex) {
262
+ await this.init();
263
+ return (await this.client.query(`UPDATE ${this.p}users SET mfa_secret = $2, mfa_last_step = NULL WHERE id = $1 AND mfa_enabled_at IS NULL RETURNING id`, [userId, secretHex])).rows.length > 0;
264
+ }
265
+ /** False when this step or a later one was used already. */
266
+ async takeMfaStep(userId, step) {
267
+ await this.init();
268
+ return (await this.client.query(`UPDATE ${this.p}users SET mfa_last_step = $2 WHERE id = $1 AND (mfa_last_step IS NULL OR mfa_last_step < $2) RETURNING id`, [userId, step])).rows.length > 0;
269
+ }
270
+ async enableMfa(userId) {
271
+ await this.init();
272
+ await this.client.query(`UPDATE ${this.p}users SET mfa_enabled_at = now() WHERE id = $1`, [userId]);
273
+ }
274
+ async resetMfa(email) {
275
+ await this.init();
276
+ return (await this.client.query(`UPDATE ${this.p}users SET mfa_secret = NULL, mfa_enabled_at = NULL, mfa_last_step = NULL WHERE email = $1 RETURNING id`, [email])).rows.length > 0;
277
+ }
278
+ /** Replaces the tenant's setting. A domain belongs to one tenant, so a domain that another tenant holds is refused. */
279
+ async setSso(s) {
280
+ await this.init();
281
+ const domains = [...new Set(s.domains.map((d) => d.trim().toLowerCase()))];
282
+ if (!domains.length || domains.some((d) => !/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$/.test(d)))
283
+ throw new Error("SSO needs one or more email domains, such as acme.example");
284
+ if (!ROLES.includes(s.defaultRole) || s.defaultRole === "owner")
285
+ throw new Error("the default role of an SSO member is readonly, reviewer, or admin");
286
+ const held = (await this.client.query(`SELECT tenant_id, domains FROM ${this.p}sso WHERE tenant_id <> $1 AND domains && $2::text[]`, [s.tenant, domains])).rows;
287
+ if (held[0])
288
+ throw new Error(`the domain ${domains.find((d) => held[0].domains.includes(d))} belongs to tenant ${held[0].tenant_id} already`);
289
+ await this.client.query(`INSERT INTO ${this.p}sso (tenant_id, protocol, config, domains, default_role, enforced, updated_at) VALUES ($1, $2, $3, $4::text[], $5, $6, now())
290
+ ON CONFLICT (tenant_id) DO UPDATE SET protocol = EXCLUDED.protocol, config = EXCLUDED.config, domains = EXCLUDED.domains, default_role = EXCLUDED.default_role, enforced = EXCLUDED.enforced, updated_at = now()`, [s.tenant, s.protocol, JSON.stringify(s.config), domains, s.defaultRole, s.enforced]);
291
+ }
292
+ async ssoWhere(where, param) {
293
+ await this.init();
294
+ const r = (await this.client.query(`SELECT tenant_id, protocol, config, domains, default_role, enforced FROM ${this.p}sso WHERE ${where}`, [param])).rows[0];
295
+ return r ? { tenant: String(r.tenant_id), protocol: r.protocol, config: JSON.parse(String(r.config)), domains: r.domains, defaultRole: r.default_role, enforced: !!r.enforced } : null;
296
+ }
297
+ ssoOf(tenant) {
298
+ return this.ssoWhere("tenant_id = $1", tenant);
299
+ }
300
+ ssoByDomain(domain) {
301
+ return this.ssoWhere("$1 = ANY(domains)", domain.toLowerCase());
302
+ }
303
+ async removeSso(tenant) {
304
+ await this.init();
305
+ return (await this.client.query(`DELETE FROM ${this.p}sso WHERE tenant_id = $1 RETURNING tenant_id`, [tenant])).rows.length > 0;
306
+ }
307
+ /**
308
+ * The account behind an identity that the tenant's IdP vouched for: the linked one; else the account with that
309
+ * email, linked from now on, if it verified its address; else a new verified account with a random password.
310
+ * The IdP proves the address, so an account that never verified it loses the address: the account goes, with its
311
+ * password, its sessions, and its links. A tenant that it owned stays for the operator. There are two exceptions: an
312
+ * unverified member of this same tenant, who verifies by password first (UnverifiedAccountError), and an
313
+ * unverified member of another tenant that has other members, who is refused. An account with
314
+ * no tenant joins with the default role. A member that an admin removed joins again only through a new invite,
315
+ * with the invited role.
316
+ */
317
+ async findOrCreateSsoUser(s, id) {
318
+ await this.init();
319
+ const provider = `sso:${s.tenant}`;
320
+ const parts = id.email.split("@");
321
+ if (parts.length !== 2 || !s.domains.includes(parts[1]))
322
+ throw new SsoRefusedError(`the address ${id.email} is not in a domain that signs in to ${s.tenant} through single sign-on`);
323
+ const linked = (await this.client.query(`SELECT user_id FROM ${this.p}identities WHERE provider = $1 AND subject = $2`, [provider, id.subject])).rows;
324
+ let user = linked[0] ? await this.user(linked[0].user_id) : null;
325
+ const known = !!user;
326
+ user ??= await this.userByEmail(id.email);
327
+ const unverified = !!user && !known && !user.emailVerifiedAt;
328
+ let home = user ? await this.tenantOf(user.id) : null;
329
+ if (unverified && home === s.tenant)
330
+ throw new UnverifiedAccountError(id.email);
331
+ // deleting an unverified account would strand the other members of the tenant that it belongs to
332
+ if (home && home !== s.tenant && (!unverified || (await this.client.query(`SELECT 1 FROM ${this.p}members WHERE tenant_id = $1 AND user_id <> $2 LIMIT 1`, [home, user.id])).rows.length))
333
+ throw new SsoRefusedError(`the account ${id.email} belongs to another tenant`);
334
+ let role = s.defaultRole;
335
+ // the removal is looked up before an unverified account goes, or the person would rejoin as a new account; an account of another tenant is no way around it
336
+ if (home !== s.tenant && (await this.client.query(`SELECT 1 FROM ${this.p}removed WHERE tenant_id = $1 AND (email = $3 OR user_id = $2)`, [s.tenant, user?.id ?? "", id.email])).rows.length) {
337
+ const invited = await this.takeInvite(s.tenant, id.email);
338
+ if (!invited)
339
+ throw new SsoRefusedError(`${id.email} was removed from ${s.tenant}; an admin must invite the address again`);
340
+ role = invited;
341
+ }
342
+ if (unverified) {
343
+ for (const t of ["members", "identities"])
344
+ await this.client.query(`DELETE FROM ${this.p}${t} WHERE user_id = $1`, [user.id]);
345
+ await this.client.query(`DELETE FROM ${this.p}users WHERE id = $1`, [user.id]);
346
+ user = null;
347
+ home = null;
348
+ }
349
+ if (!user) {
350
+ user = await this.createUser(id.email, randomBytes(32).toString("hex"));
351
+ await this.markEmailVerified(user.id);
352
+ }
353
+ if (!known)
354
+ await this.linkIdentity(provider, id.subject, id.email, user.id);
355
+ if (!home)
356
+ await this.addMember(user.id, s.tenant, role);
357
+ return user;
170
358
  }
171
359
  /** the user's tenant; one per account today */
172
360
  async tenantOf(userId) {
@@ -195,10 +383,10 @@ export class PortalStore {
195
383
  await this.init();
196
384
  await this.client.query(`INSERT INTO ${this.p}stripe_events (id) VALUES ($1) ON CONFLICT (id) DO NOTHING`, [id]);
197
385
  }
198
- /** Every portal registration with its tenant and billing state, oldest first: what the operator's admin page lists. */
386
+ /** Every portal registration with its tenant and billing state, oldest first: what the operator's admin page lists. Owners only. */
199
387
  async registrations() {
200
388
  await this.init();
201
- const rows = (await this.client.query(`SELECT m.tenant_id, u.email, u.created_at, u.name, u.company, u.role, u.phone, u.telegram, b.status FROM ${this.p}members m JOIN ${this.p}users u ON u.id = m.user_id LEFT JOIN ${this.p}billing b ON b.tenant_id = m.tenant_id ORDER BY u.created_at, m.tenant_id`)).rows;
389
+ const rows = (await this.client.query(`SELECT m.tenant_id, u.email, u.created_at, u.name, u.company, u.role, u.phone, u.telegram, b.status FROM ${this.p}members m JOIN ${this.p}users u ON u.id = m.user_id LEFT JOIN ${this.p}billing b ON b.tenant_id = m.tenant_id WHERE m.role = 'owner' ORDER BY u.created_at, m.tenant_id`)).rows;
202
390
  const str = (v) => (v == null ? null : String(v));
203
391
  return rows.map((r) => ({ tenantId: String(r.tenant_id), email: String(r.email), registeredAt: new Date(r.created_at).toISOString(), billing: str(r.status), name: str(r.name), company: str(r.company), role: str(r.role), phone: str(r.phone), telegram: str(r.telegram) }));
204
392
  }
@@ -210,11 +398,12 @@ export class PortalStore {
210
398
  }
211
399
  // ---- sessions ----
212
400
  const b64u = (b) => b.toString("base64url");
213
- export function signSession(secret, userId, ttlMs = 14 * 86_400_000) {
214
- const body = b64u(Buffer.from(JSON.stringify({ u: userId, e: Date.now() + ttlMs })));
401
+ /** `via` records how the user signed in, for example `sso:acme`. */
402
+ export function signSession(secret, userId, ttlMs = 14 * 86_400_000, via) {
403
+ const body = b64u(Buffer.from(JSON.stringify({ u: userId, e: Date.now() + ttlMs, ...(via ? { a: via } : {}) })));
215
404
  return `${body}.${createHmac("sha256", secret).update(body).digest("base64url")}`;
216
405
  }
217
- export function readSession(secret, cookie) {
406
+ function readClaims(secret, cookie) {
218
407
  if (!cookie)
219
408
  return null;
220
409
  const [body, mac] = cookie.split(".");
@@ -224,13 +413,16 @@ export function readSession(secret, cookie) {
224
413
  if (expected.length !== mac.length || !timingSafeEqual(Buffer.from(expected), Buffer.from(mac)))
225
414
  return null;
226
415
  try {
227
- const { u, e } = JSON.parse(Buffer.from(body, "base64url").toString());
228
- return typeof u === "string" && typeof e === "number" && e > Date.now() ? u : null;
416
+ const { u, e, a } = JSON.parse(Buffer.from(body, "base64url").toString());
417
+ return typeof u === "string" && typeof e === "number" && e > Date.now() ? { u, ...(typeof a === "string" ? { a } : {}) } : null;
229
418
  }
230
419
  catch {
231
420
  return null;
232
421
  }
233
422
  }
423
+ export const readSession = (secret, cookie) => readClaims(secret, cookie)?.u ?? null;
424
+ /** The `via` of a valid session, or null. */
425
+ export const readSessionVia = (secret, cookie) => readClaims(secret, cookie)?.a ?? null;
234
426
  // ---- Stripe, over its REST API; no SDK ----
235
427
  const form = (o) => new URLSearchParams(o).toString();
236
428
  export async function stripeRequest(s, path, body) {
@@ -260,6 +452,7 @@ export function verifyStripeSignature(header, rawBody, secret, now = Date.now(),
260
452
  }
261
453
  const TENANT_ID = /^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/;
262
454
  const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
455
+ const ENFORCED = "Your organisation signs in through its identity provider. Use Sign in with single sign-on";
263
456
  const RESERVED = new Set(["default", "admin", "api", "www", "log", "checkpoints", "app", "portal", "stripe", "health", "t"]);
264
457
  /** One message through the provider. Best effort: a refusal or a failure is reported through `log`, never thrown. Returns whether it was accepted. */
265
458
  export async function deliverMail(mail, m, log = console.error) {
@@ -335,6 +528,8 @@ export function portalHandler(o) {
335
528
  const log = o.log ?? ((m) => console.error(m));
336
529
  const loginFailures = new RateLimiter({ perSecond: 1 / 30, burst: 8 });
337
530
  const registrations = new RateLimiter({ perSecond: 1 / 600, burst: 5 });
531
+ // per account, whatever the address
532
+ const mfaFailures = new RateLimiter({ perSecond: 1 / 120, burst: 5 });
338
533
  const base = o.publicUrl.endsWith("/") ? o.publicUrl : `${o.publicUrl}/`;
339
534
  const cookieName = "custody_session";
340
535
  const sheet = (tenant, logId) => welcomeSheet({ tenant, logId, publicUrl: base, ...(o.checkpointsUrl ? { checkpointsUrl: o.checkpointsUrl } : {}), ...(o.keyid ? { keyid: o.keyid } : {}) });
@@ -386,8 +581,21 @@ export function portalHandler(o) {
386
581
  };
387
582
  const esc = (v) => v.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
388
583
  const setCookie = (value) => `${cookieName}=${value ?? ""}; Path=/; HttpOnly; SameSite=Strict${o.trustProxy ? "; Secure" : ""}; Max-Age=${value ? 14 * 86_400 : 0}`;
584
+ // the state between the first step and the code; never a session
585
+ const mfaCookie = (id) => `custody_mfa=${id ? signSession(o.secret, `mfa:${id}`, 300_000) : ""}; Path=/api/login; HttpOnly; SameSite=Strict${o.trustProxy ? "; Secure" : ""}; Max-Age=${id ? 300 : 0}`;
389
586
  const cookies = Object.fromEntries((req.headers.cookie ?? "").split(";").map((c) => c.trim().split("=")).filter(([k]) => k));
390
587
  const userId = readSession(o.secret, cookies[cookieName]);
588
+ const via = readSessionVia(o.secret, cookies[cookieName]);
589
+ // A page, not a redirect: the session cookie is SameSite=Strict, and a redirect that started at the provider
590
+ // would not carry it. The page's own navigation to / does.
591
+ const signedInPage = (who, next, setCookies, lead) => {
592
+ res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "set-cookie": setCookies, "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'" });
593
+ res.end(`<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=${next}"><title>Signed in</title><p style="font:15px system-ui;padding:2rem">${lead} ${esc(who)}. <a href="${next}">Continue</a>.</p>`);
594
+ };
595
+ const enforcedFor = async (id) => {
596
+ const t = await store.tenantOf(id);
597
+ return t && (await store.ssoOf(t))?.enforced;
598
+ };
391
599
  const rawBody = async () => {
392
600
  let text = "";
393
601
  for await (const chunk of req) {
@@ -486,6 +694,20 @@ export function portalHandler(o) {
486
694
  void notifyMail({ ...profile, email: user.email, tenant: t.id });
487
695
  return { status: 200, body: { tenant: t.id, logId: t.logId, plan: t.plan, token: minted.token, tokenHash: minted.tokenHash.slice(0, 12), welcome: sheet(t.id, t.logId), setup: setupFor(t.id, t.logId), exportCommand: exportCommand(t.id) } };
488
696
  };
697
+ // `on` is the state the account must be in: true to sign in or turn MFA off, false to turn it on.
698
+ const checkCode = async (id, code, on) => {
699
+ if (!mfaFailures.take(id))
700
+ return { status: 429, body: { error: "too many codes tried for this account; wait a few minutes" } };
701
+ const m = await store.mfa(id);
702
+ if (!m.secret || m.enabled !== on)
703
+ return { status: 409, body: { error: on ? "MFA is not on for this account" : "start the MFA setup first" } };
704
+ const step = totpStep(Buffer.from(m.secret, "hex"), String(code ?? ""));
705
+ if (step === null || !(await store.takeMfaStep(id, step)))
706
+ return { status: 401, body: { error: "that code is not valid, or was used already" } };
707
+ if (!on)
708
+ await store.enableMfa(id);
709
+ return null;
710
+ };
489
711
  if (req.method === "POST" && url.pathname === "/api/register") {
490
712
  const b = await jsonBody();
491
713
  const email = String(b.email ?? "").trim().toLowerCase();
@@ -542,6 +764,95 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
542
764
  });
543
765
  </script>`);
544
766
  }
767
+ // ---- enterprise sign-in through the tenant's own identity provider, which only the operator sets ----
768
+ const sso = /^\/auth\/sso(?:\/([a-z0-9-]+)(\/callback|\/saml|\/saml\/acs)?)?$/.exec(url.pathname);
769
+ if (sso && req.method === (sso[2] === "/saml/acs" ? "POST" : "GET")) {
770
+ const [, t, tail] = sso;
771
+ if (!t) {
772
+ const domain = (url.searchParams.get("email") ?? "").split("@")[1]?.trim().toLowerCase() ?? "";
773
+ const found = domain ? await store.ssoByDomain(domain) : null;
774
+ if (!found)
775
+ return page(404, "No single sign-on", `No single sign-on is set up for ${esc(domain || "that address")}. <a href="/">Sign in another way</a>.`);
776
+ res.writeHead(302, { location: `/auth/sso/${found.tenant}`, "cache-control": "no-store" });
777
+ return void res.end();
778
+ }
779
+ const conf = await store.ssoOf(t);
780
+ const oidcCookie = (v) => `custody_sso=${v ?? ""}; Path=/auth; HttpOnly; SameSite=Lax${o.trustProxy ? "; Secure" : ""}; Max-Age=${v ? 600 : 0}`;
781
+ // the IdP posts to the ACS from another site, and only SameSite=None comes back with that post
782
+ const samlCookie = (v) => `custody_saml=${v ?? ""}; Path=/auth/sso; HttpOnly; SameSite=None; Secure; Max-Age=${v ? 600 : 0}`;
783
+ const flowCookie = conf?.protocol === "saml" ? samlCookie : oidcCookie;
784
+ const refuse = (status, text) => page(status, "Single sign-on", esc(text), { "set-cookie": flowCookie(null) });
785
+ if (!conf)
786
+ return refuse(404, "No single sign-on is set up for that organisation.");
787
+ const at = `${portalBase}auth/sso/${t}`;
788
+ const sp = { spEntityId: `${at}/saml`, acsUrl: `${at}/saml/acs` };
789
+ const sayFailed = (what, e) => {
790
+ log(`agent-custody portal: ${what} for ${t} failed: ${e instanceof Error ? e.message : String(e)}`);
791
+ return `${what} failed. Ask your administrator to check the identity provider settings.`;
792
+ };
793
+ if (tail === "/saml") {
794
+ if (conf.protocol !== "saml")
795
+ return refuse(404, "This organisation does not use SAML.");
796
+ res.writeHead(200, { "content-type": "application/samlmetadata+xml", "cache-control": "no-store" });
797
+ return void res.end(`<?xml version="1.0"?><EntityDescriptor xmlns="urn:oasis:names:tc:SAML:2.0:metadata" entityID="${esc(sp.spEntityId)}"><SPSSODescriptor protocolSupportEnumeration="urn:oasis:names:tc:SAML:2.0:protocol" WantAssertionsSigned="true"><NameIDFormat>urn:oasis:names:tc:SAML:1.1:nameid-format:emailAddress</NameIDFormat><AssertionConsumerService Binding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" Location="${esc(sp.acsUrl)}" index="0"/></SPSSODescriptor></EntityDescriptor>`);
798
+ }
799
+ const ssoFetch = o.ssoFetch ? { fetch: o.ssoFetch } : {};
800
+ if (!tail) {
801
+ try {
802
+ if (conf.protocol === "oidc") {
803
+ const { verifier, challenge } = pkce();
804
+ const state = randomBytes(16).toString("hex");
805
+ const nonce = randomBytes(16).toString("hex");
806
+ const to = await oidcAuthorizeUrl(conf.config, { redirectUri: `${at}/callback`, state, nonce, codeChallenge: challenge, ...ssoFetch });
807
+ res.writeHead(302, { location: to, "set-cookie": oidcCookie(signSession(o.secret, `oidc:${t}:${state}:${verifier}:${nonce}`, 600_000)), "cache-control": "no-store" });
808
+ }
809
+ else {
810
+ const { url: to, requestId } = await samlAuthorizeUrl(conf.config, sp);
811
+ res.writeHead(302, { location: to, "set-cookie": samlCookie(signSession(o.secret, `saml:${t}:${requestId}`, 600_000)), "cache-control": "no-store" });
812
+ }
813
+ return void res.end();
814
+ }
815
+ catch (e) {
816
+ return refuse(502, sayFailed("Single sign-on start", e));
817
+ }
818
+ }
819
+ let id;
820
+ try {
821
+ if (tail === "/callback" && conf.protocol === "oidc") {
822
+ const [kind, flowTenant, state, verifier, nonce] = (readSession(o.secret, cookies.custody_sso) ?? "").split(":");
823
+ const code = url.searchParams.get("code") ?? "";
824
+ if (kind !== "oidc" || flowTenant !== t || !code || !state || state !== url.searchParams.get("state"))
825
+ return refuse(400, "The sign-in did not start here, or took too long. Go back and try again.");
826
+ id = await oidcExchange(conf.config, { code, redirectUri: `${at}/callback`, codeVerifier: verifier, nonce: nonce, ...ssoFetch });
827
+ }
828
+ else if (tail === "/saml/acs" && conf.protocol === "saml") {
829
+ const [kind, flowTenant, requestId] = (readSession(o.secret, cookies.custody_saml) ?? "").split(":");
830
+ const samlResponse = new URLSearchParams(await rawBody()).get("SAMLResponse") ?? "";
831
+ if (kind !== "saml" || flowTenant !== t || !samlResponse)
832
+ return refuse(400, "The sign-in did not start here, or took too long. Go back and try again.");
833
+ id = await samlValidate(conf.config, { ...sp, samlResponse, requestId: requestId });
834
+ }
835
+ else {
836
+ return refuse(404, "Not found.");
837
+ }
838
+ }
839
+ catch (e) {
840
+ return refuse(401, sayFailed("Single sign-on", e));
841
+ }
842
+ let user;
843
+ try {
844
+ user = await store.findOrCreateSsoUser(conf, id);
845
+ }
846
+ catch (e) {
847
+ if (e instanceof UnverifiedAccountError)
848
+ return refuse(409, e.message);
849
+ if (e instanceof SsoRefusedError)
850
+ return refuse(403, e.message);
851
+ throw e;
852
+ }
853
+ log(`agent-custody portal: ${id.email} signed in through single sign-on for ${t}`);
854
+ return signedInPage(id.email, "/", [setCookie(signSession(o.secret, user.id, undefined, `sso:${t}`)), flowCookie(null)], "Signed in as");
855
+ }
545
856
  // ---- sign in through a provider: the OAuth web flow, state in a short-lived signed cookie ----
546
857
  const provider = /^\/auth\/(github|google)(\/callback)?$/.exec(url.pathname);
547
858
  if (req.method === "GET" && provider && o.oauth?.[provider[1]]) {
@@ -622,11 +933,11 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
622
933
  log(`agent-custody portal: ${name} sign-in for ${email} refused: the password account has not verified its address`);
623
934
  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
935
  }
625
- log(`agent-custody portal: ${email} signed in with ${name}`);
626
- // A page, not a redirect: the session cookie is SameSite=Strict, and a redirect that started at the provider
627
- // would not carry it. The page's own navigation to / does.
628
- res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-store", "set-cookie": [setCookie(signSession(o.secret, user.id)), stateCookie(null)], "content-security-policy": "default-src 'none'; style-src 'unsafe-inline'" });
629
- return void res.end(`<!doctype html><meta charset="utf-8"><meta http-equiv="refresh" content="0;url=/"><title>Signed in</title><p style="font:15px system-ui;padding:2rem">Signed in as ${email.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c])}. <a href="/">Continue</a>.</p>`);
936
+ if (await enforcedFor(user.id))
937
+ return page(403, "Single sign-on required", `${esc(ENFORCED)}.`, { "set-cookie": stateCookie(null) });
938
+ const mfa = (await store.mfa(user.id)).enabled;
939
+ log(`agent-custody portal: ${email} signed in with ${name}${mfa ? ", MFA code needed" : ""}`);
940
+ return signedInPage(email, mfa ? "/?mfa=1" : "/", [mfa ? mfaCookie(user.id) : setCookie(signSession(o.secret, user.id)), stateCookie(null)], mfa ? "One more step for" : "Signed in as");
630
941
  }
631
942
  if (req.method === "POST" && url.pathname === "/api/login") {
632
943
  if (!loginFailures.take(`login:${addr}`))
@@ -635,8 +946,25 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
635
946
  const user = await store.authenticate(String(b.email ?? "").trim().toLowerCase(), String(b.password ?? ""));
636
947
  if (!user)
637
948
  return json(401, { error: "email or password not recognised" });
949
+ if (await enforcedFor(user.id))
950
+ return json(403, { error: ENFORCED });
951
+ if ((await store.mfa(user.id)).enabled)
952
+ return json(200, { mfa: true }, { "set-cookie": mfaCookie(user.id) });
638
953
  return json(200, { email: user.email }, { "set-cookie": setCookie(signSession(o.secret, user.id)) });
639
954
  }
955
+ if (req.method === "POST" && url.pathname === "/api/login/mfa") {
956
+ if (!loginFailures.take(`login:${addr}`))
957
+ return json(429, { error: "too many attempts; wait a minute" });
958
+ const b = await jsonBody();
959
+ const who = readSession(o.secret, cookies.custody_mfa);
960
+ const half = who?.startsWith("mfa:") ? await store.user(who.slice(4)) : null;
961
+ if (!half)
962
+ return json(401, { error: "the password step expired; sign in again" });
963
+ const refused = await checkCode(half.id, b.code, true);
964
+ if (refused)
965
+ return json(refused.status, refused.body);
966
+ return json(200, { email: half.email }, { "set-cookie": [setCookie(signSession(o.secret, half.id)), mfaCookie(null)] });
967
+ }
640
968
  if (req.method === "POST" && url.pathname === "/api/logout")
641
969
  return json(200, { ok: true }, { "set-cookie": setCookie(null) });
642
970
  // ---- everything below needs a session ----
@@ -648,7 +976,10 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
648
976
  if (req.method !== "GET" && !(req.headers["content-type"] ?? "").startsWith("application/json"))
649
977
  return json(415, { error: "expected a JSON body" });
650
978
  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 });
979
+ const ssoConf = tenantId ? await store.ssoOf(tenantId) : null;
980
+ if (ssoConf?.enforced && via !== `sso:${tenantId}`)
981
+ return json(401, { error: ENFORCED });
982
+ const account = async () => ({ emailVerified: !!user.emailVerifiedAt, identities: await store.identities(user.id), providers: ["github", "google"].filter((p) => !!o.oauth?.[p]), mail: !!o.mail, mfa: (await store.mfa(user.id)).enabled });
652
983
  if (req.method === "POST" && url.pathname === "/api/verify-email") {
653
984
  const who = readSession(o.secret, String((await jsonBody()).token ?? ""));
654
985
  if (!who?.startsWith("verify:"))
@@ -668,7 +999,41 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
668
999
  return json(200, { ok: true, emailVerified: false });
669
1000
  }
670
1001
  if (req.method === "GET" && url.pathname === "/api/me" && !tenantId)
671
- return json(200, { email: user.email, tenant: null, profile: await store.profile(user.id), billing: !!o.stripe, ...(await account()) });
1002
+ return json(200, { email: user.email, tenant: null, profile: await store.profile(user.id), invites: await store.invitesFor(user.email), billing: !!o.stripe, ...(await account()) });
1003
+ if (req.method === "POST" && url.pathname === "/api/mfa/setup") {
1004
+ await jsonBody();
1005
+ const secret = randomBytes(20);
1006
+ if (!(await store.setMfaSecret(user.id, secret.toString("hex"))))
1007
+ return json(409, { error: "MFA is on already; turn it off first" });
1008
+ const b32 = base32(secret);
1009
+ return json(200, { secret: b32, uri: `otpauth://totp/agent-custody:${encodeURIComponent(user.email)}?secret=${b32}&issuer=agent-custody` });
1010
+ }
1011
+ if (req.method === "POST" && (url.pathname === "/api/mfa/enable" || url.pathname === "/api/mfa/disable")) {
1012
+ const on = url.pathname.endsWith("/disable");
1013
+ const refused = await checkCode(user.id, (await jsonBody()).code, on);
1014
+ if (refused)
1015
+ return json(refused.status, refused.body);
1016
+ if (on)
1017
+ await store.resetMfa(user.email);
1018
+ log(`agent-custody portal: ${user.email} turned MFA ${on ? "off" : "on"}`);
1019
+ return json(200, { mfa: !on });
1020
+ }
1021
+ // The address must be verified: otherwise anyone who registers the invited address with a password gets in.
1022
+ if (req.method === "POST" && url.pathname === "/api/invites/accept") {
1023
+ const tenant = String((await jsonBody()).tenant ?? "");
1024
+ if (tenantId)
1025
+ return json(409, { error: "this account has a tenant already; one tenant per account" });
1026
+ if (!user.emailVerifiedAt)
1027
+ return json(403, { error: "verify your email address first, then accept the invite" });
1028
+ if ((await store.ssoOf(tenant))?.enforced)
1029
+ return json(409, { error: "members of this tenant join through its identity provider" });
1030
+ const role = await store.takeInvite(tenant, user.email);
1031
+ if (!role)
1032
+ return json(404, { error: "no invite to this address for that tenant, or it is older than seven days" });
1033
+ await store.addMember(user.id, tenant, role);
1034
+ log(`agent-custody portal: ${user.email} joined tenant ${tenant} as ${role}`);
1035
+ return json(200, { tenant, role });
1036
+ }
672
1037
  if (req.method === "POST" && url.pathname === "/api/onboard") {
673
1038
  const p = await parseOnboarding(await jsonBody());
674
1039
  if ("status" in p)
@@ -681,9 +1046,15 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
681
1046
  const tenant = await o.tenancy.tenant(tenantId);
682
1047
  if (!tenant)
683
1048
  return json(409, { error: "the tenant no longer exists" });
1049
+ // The lowest role a route needs; an unlisted write needs admin.
1050
+ const myRole = (await store.roleOf(user.id, tenantId));
1051
+ const needs = [[/^\/api\/(checkout|billing-portal)$/, "owner"], [/^\/api\/policies(\/|$)/, "reviewer"]];
1052
+ const least = req.method === "GET" ? "readonly" : needs.find(([re]) => re.test(url.pathname))?.[1] ?? "admin";
1053
+ if (ROLES.indexOf(myRole) < ROLES.indexOf(least))
1054
+ return json(403, { error: `this needs the ${least} role or higher; you are ${myRole}` });
684
1055
  if (req.method === "GET" && url.pathname === "/api/me") {
685
1056
  const q = await o.tenancy.quota(tenantId);
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()) });
1057
+ return json(200, { email: user.email, tenant: tenantId, role: myRole, logId: tenant.logId, plan: q.plan, used: q.used, quota: q.quota, disabled: !!tenant.disabledAt, billing: !!o.stripe, sso: ssoConf && { protocol: ssoConf.protocol, enforced: ssoConf.enforced }, ...(await account()) });
687
1058
  }
688
1059
  if (req.method === "GET" && url.pathname === "/api/overview") {
689
1060
  const q = await o.tenancy.quota(tenantId);
@@ -702,6 +1073,59 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
702
1073
  const billing = await store.billing(tenantId);
703
1074
  return json(200, { tenant: tenantId, logId: tenant.logId, plan: q.plan, used: q.used, quota: q.quota, treeSize: size, rootHash: size ? await backend.root(size) : null, latestCheckpoint: latest ? { treeSize: latest.treeSize, signedAt: latest.signedAt } : null, months, keys, audit, billing: billing ? { status: billing.status } : null, urls: { log: `${base}t/${tenantId}/`, keys: `${base}.well-known/agent-custody-log.json`, checkpoints: o.checkpointsUrl ? `${o.checkpointsUrl.replace(/\/?$/, "/")}${tenantId}/latest.json` : null }, exportCommand: exportCommand(tenantId), welcome: sheet(tenantId, tenant.logId), setup: setupFor(tenantId, tenant.logId), stripe: !!o.stripe });
704
1075
  }
1076
+ if (req.method === "GET" && url.pathname === "/api/members")
1077
+ return json(200, { members: await store.members(tenantId), invites: await store.invitesOf(tenantId) });
1078
+ const ownerOnly = (...roles) => myRole !== "owner" && roles.includes("owner");
1079
+ const OWNER_ONLY = { error: "this needs the owner role: only an owner changes an owner or grants owner" };
1080
+ if (req.method === "POST" && url.pathname === "/api/members") {
1081
+ if (ssoConf?.enforced)
1082
+ return json(409, { error: "this tenant signs in through its identity provider: members join through it, not by invite" });
1083
+ const b = await jsonBody();
1084
+ const email = String(b.email ?? "").trim().toLowerCase();
1085
+ const role = String(b.role ?? "");
1086
+ if (!EMAIL.test(email))
1087
+ return json(400, { error: "a valid email address is needed" });
1088
+ if (!ROLES.includes(role))
1089
+ return json(400, { error: `role must be one of ${ROLES.join(", ")}` });
1090
+ if (ownerOnly(role, ...(await store.invitesOf(tenantId)).filter((i) => i.email === email).map((i) => i.role)))
1091
+ return json(403, OWNER_ONLY);
1092
+ await store.invite(tenantId, email, role, user.email);
1093
+ log(`agent-custody portal: ${user.email} invited ${email} to tenant ${tenantId} as ${role}`);
1094
+ void send({ to: email, subject: `You are invited to ${tenantId} on agent-custody`, text: [`${user.email} invited you to the agent-custody tenant "${tenantId}" as ${role}.`, "", `Create an account or sign in with this address at ${portalBase}, verify the address, and accept the invite. The invite is good for seven days.`, "", "agent-custody"].join("\n") });
1095
+ return json(200, { invited: email, role });
1096
+ }
1097
+ if (req.method === "POST" && url.pathname === "/api/invites/remove") {
1098
+ const email = String((await jsonBody()).email ?? "").trim().toLowerCase();
1099
+ const invited = (await store.invitesOf(tenantId)).find((i) => i.email === email);
1100
+ if (invited && ownerOnly(invited.role))
1101
+ return json(403, OWNER_ONLY);
1102
+ log(`agent-custody portal: ${user.email} cancelled the invite of ${email} to tenant ${tenantId}`);
1103
+ return json(200, { removed: await store.removeInvite(tenantId, email) });
1104
+ }
1105
+ const member = /^\/api\/members\/([0-9a-f-]{36})\/(role|remove)$/.exec(url.pathname);
1106
+ if (req.method === "POST" && member) {
1107
+ const b = await jsonBody();
1108
+ const target = await store.roleOf(member[1], tenantId);
1109
+ if (!target)
1110
+ return json(404, { error: "no such member" });
1111
+ if (member[2] === "role") {
1112
+ const role = String(b.role ?? "");
1113
+ if (!ROLES.includes(role))
1114
+ return json(400, { error: `role must be one of ${ROLES.join(", ")}` });
1115
+ if (ownerOnly(target, role))
1116
+ return json(403, OWNER_ONLY);
1117
+ if (!(await store.setRole(tenantId, member[1], role)))
1118
+ return json(409, { error: "the last owner cannot be demoted; make another member an owner first" });
1119
+ log(`agent-custody portal: ${user.email} made ${member[1]} ${role} in tenant ${tenantId}`);
1120
+ return json(200, { role });
1121
+ }
1122
+ if (ownerOnly(target))
1123
+ return json(403, OWNER_ONLY);
1124
+ if (!(await store.removeMember(tenantId, member[1])))
1125
+ return json(409, { error: "the last owner cannot be removed; make another member an owner first" });
1126
+ log(`agent-custody portal: ${user.email} removed ${member[1]} from tenant ${tenantId}`);
1127
+ return json(200, { removed: true });
1128
+ }
705
1129
  if (req.method === "GET" && url.pathname === "/api/keys") {
706
1130
  return json(200, { keys: (await o.tenancy.listTokens(tenantId)).map((k) => ({ label: k.label, hash: k.tokenHash.slice(0, 12), createdAt: k.createdAt, revokedAt: k.revokedAt })) });
707
1131
  }
@@ -871,13 +1295,24 @@ const PORTAL_PAGE = `<!doctype html>
871
1295
  <button id="authGo" type="submit">Sign in</button>
872
1296
  <p class="msg" id="authMsg"></p>
873
1297
  </form>
1298
+ <form id="mfaForm" hidden>
1299
+ <p class="muted">Your account has two-step sign-in. Enter the six-digit code from your authenticator app.</p>
1300
+ <label>Code<input id="mfaCode" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required></label>
1301
+ <button type="submit">Verify</button>
1302
+ <p class="msg" id="mfaMsg"></p>
1303
+ </form>
874
1304
  <p class="muted" id="authNote" hidden>Next you name your organisation and get your tenant and its first key. Two minutes.</p>
1305
+ <form id="ssoForm" action="/auth/sso" method="get">
1306
+ <label>Work email for single sign-on<input name="email" type="email" autocomplete="email" required></label>
1307
+ <button class="quiet" type="submit">Sign in with single sign-on</button>
1308
+ </form>
875
1309
  <p class="muted"><button class="link" id="authSwap" type="button">Create an account instead</button></p>
876
1310
  <p class="muted">The free plan is ten thousand appends a month, no card. Your gateway sends only hashes; nothing you log here can be read by us.</p>
877
1311
  </section>
878
1312
  <section id="onboard" class="auth" hidden>
879
1313
  <h1>Set up your tenant</h1>
880
1314
  <p class="muted">Signed in as <b id="onboardWho"></b>. A tenant is your own log on this service, with its own keys and its own path.</p>
1315
+ <div id="invites" class="panel" hidden><p><b>You are invited to join a tenant.</b> Your email address must be verified first.</p><div id="inviteList"></div></div>
881
1316
  <form id="onboardForm">
882
1317
  <label>Your name<input id="name" autocomplete="name" maxlength="120" required></label>
883
1318
  <label>Company or organisation<input id="company" autocomplete="organization" maxlength="160" required></label>
@@ -906,9 +1341,11 @@ const PORTAL_PAGE = `<!doctype html>
906
1341
  <a href="#setup" data-view="setup">Setup</a>
907
1342
  <a href="#keys" data-view="keys">API keys <span class="n" id="nKeys"></span></a>
908
1343
  <a href="#policies" data-view="policies">Policies <span class="n" id="nPolicies"></span></a>
1344
+ <a href="#members" data-view="members">Members <span class="n" id="nMembers"></span></a>
909
1345
  <a href="#billing" data-view="billing">Billing</a>
910
1346
  <a href="#export" data-view="export">Export</a>
911
1347
  <div class="group">Account</div>
1348
+ <a href="#account" data-view="account">Two-step sign-in</a>
912
1349
  <a href="#" id="signout">Sign out</a>
913
1350
  </nav>
914
1351
  <main>
@@ -948,6 +1385,29 @@ const PORTAL_PAGE = `<!doctype html>
948
1385
  <div class="panel" id="policyView" hidden><h2 id="policyViewName"></h2><pre id="policyViewText"></pre></div>
949
1386
  <p class="msg" id="policiesMsg"></p>
950
1387
  </div>
1388
+ <div data-pane="members" hidden>
1389
+ <h1>Members</h1>
1390
+ <p class="muted">An owner manages everything, billing and owners included. An admin manages keys and members below owner. A reviewer publishes policy versions. A read-only member only looks. An invited person creates an account with the invited address, verifies it, and accepts on the first screen. An invite is good for seven days.</p>
1391
+ <div class="panel" id="inviteBox" hidden><form id="inviteForm" style="display:flex;gap:.6rem;align-items:end;flex-wrap:wrap"><label style="margin:0">Email<input id="inviteEmail" type="email" required></label><label style="margin:0">Role<select id="inviteRole"></select></label><button type="submit">Invite</button></form></div>
1392
+ <div class="panel"><table><thead><tr><th>member</th><th>role</th><th>joined</th><th>two-step</th><th></th></tr></thead><tbody id="members"></tbody></table></div>
1393
+ <h2>Pending invites</h2>
1394
+ <div class="panel"><table><thead><tr><th>email</th><th>role</th><th>invited by</th><th>sent</th><th></th></tr></thead><tbody id="inviteRows"></tbody></table></div>
1395
+ <p class="msg" id="membersMsg"></p>
1396
+ </div>
1397
+ <div data-pane="account" hidden>
1398
+ <h1>Two-step sign-in</h1>
1399
+ <p class="muted">Two-step sign-in is <b id="mfaState">off</b>. With it on, a password or a GitHub or Google sign-in is followed by a six-digit code from an authenticator app (TOTP).</p>
1400
+ <div class="panel">
1401
+ <button id="mfaStart" type="button">Set up</button>
1402
+ <div id="mfaSetupBox" hidden>
1403
+ <p>Add this secret to your authenticator app (enter it by hand, or paste the address), then type a code from the app.</p>
1404
+ <p class="tok" id="mfaSecret"></p><p class="tok" id="mfaUri"></p>
1405
+ <form id="mfaOnForm"><label>Code<input id="mfaOnCode" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required></label><button type="submit">Turn on</button></form>
1406
+ </div>
1407
+ <form id="mfaOffForm" hidden><label>Current code<input id="mfaOffCode" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required></label><button type="submit" class="quiet">Turn off</button></form>
1408
+ </div>
1409
+ <p class="msg" id="accountMsg"></p>
1410
+ </div>
951
1411
  <div data-pane="billing" hidden>
952
1412
  <h1>Billing</h1>
953
1413
  <div class="panel" id="billingPanel"></div>
@@ -978,6 +1438,10 @@ const PORTAL_PAGE = `<!doctype html>
978
1438
  const fmt = (n) => Number(n).toLocaleString();
979
1439
  const ago = (iso) => { const m = Math.round((Date.now() - Date.parse(iso)) / 60000); return m < 60 ? m + " min ago" : m < 1440 ? Math.round(m / 60) + " h ago" : Math.round(m / 1440) + " d ago"; };
980
1440
  let registering = false;
1441
+ let myRole = "readonly";
1442
+ const ROLES = ["readonly", "reviewer", "admin", "owner"];
1443
+ const can = (least) => ROLES.indexOf(myRole) >= ROLES.indexOf(least);
1444
+ const note = (id, text, ok) => { $(id).className = "msg " + (ok ? "ok" : "err"); $(id).textContent = text; };
981
1445
  const show = (id) => { for (const s of ["auth", "onboard", "welcome", "app"]) $(s).hidden = s !== id; };
982
1446
  const PROVIDERS = __PROVIDERS__;
983
1447
  if (PROVIDERS.length) { $("providers").innerHTML = PROVIDERS.map((p) => "<a href='/auth/" + p + "'>Continue with " + (p === "github" ? "GitHub" : "Google") + "</a>").join("") + "<p class=or>or with email</p>"; $("providers").hidden = false; }
@@ -996,10 +1460,17 @@ const PORTAL_PAGE = `<!doctype html>
996
1460
  $("authForm").onsubmit = async (e) => {
997
1461
  e.preventDefault(); $("authMsg").className = "msg"; $("authMsg").textContent = "";
998
1462
  try {
999
- await api("POST", registering ? "/api/register" : "/api/login", { email: $("email").value, password: $("password").value });
1463
+ const r = await api("POST", registering ? "/api/register" : "/api/login", { email: $("email").value, password: $("password").value });
1464
+ if (r.mfa) { askCode(); return; }
1000
1465
  await enter();
1001
1466
  } catch (err) { $("authMsg").className = "msg err"; $("authMsg").textContent = err.message; }
1002
1467
  };
1468
+ const askCode = () => { $("authForm").hidden = true; $("ssoForm").hidden = true; $("providers").hidden = true; $("authSwap").parentElement.hidden = true; $("authTitle").textContent = "Enter your code"; $("mfaForm").hidden = false; $("mfaCode").focus(); };
1469
+ $("mfaForm").onsubmit = async (e) => {
1470
+ e.preventDefault();
1471
+ try { await api("POST", "/api/login/mfa", { code: $("mfaCode").value }); location.href = "/"; }
1472
+ catch (err) { note("mfaMsg", err.message, false); }
1473
+ };
1003
1474
  $("onboardForm").onsubmit = async (e) => {
1004
1475
  e.preventDefault(); $("onboardMsg").className = "msg"; $("onboardMsg").textContent = "";
1005
1476
  try {
@@ -1047,23 +1518,43 @@ const PORTAL_PAGE = `<!doctype html>
1047
1518
  const max = Math.max(1, ...o.months.map((m) => m.appends));
1048
1519
  $("bars").innerHTML = o.months.map((m) => "<div class=bar><span class=mono>" + fmt(m.appends) + "</span><i style=\\"height:" + Math.max(2, Math.round(100 * m.appends / max)) + "%\\"></i><b>" + esc(m.month.slice(2)) + "</b></div>").join("");
1049
1520
  $("usageNote").textContent = "Appends per calendar month, UTC. Your plan allows " + (o.quota === null ? "any number" : fmt(o.quota)) + " a month; the count resets on the first.";
1050
- $("keys").innerHTML = o.keys.map((k) => "<tr><td>" + esc(k.label) + "</td><td class=mono>" + esc(k.hash) + "</td><td>" + esc(k.createdAt.slice(0, 10)) + "</td><td>" + (k.revokedAt ? "revoked " + esc(k.revokedAt.slice(0, 10)) : "live") + "</td><td>" + (k.revokedAt ? "" : "<button class=quiet data-revoke=\\"" + esc(k.hash) + "\\">Revoke</button>") + "</td></tr>").join("");
1521
+ $("keys").innerHTML = o.keys.map((k) => "<tr><td>" + esc(k.label) + "</td><td class=mono>" + esc(k.hash) + "</td><td>" + esc(k.createdAt.slice(0, 10)) + "</td><td>" + (k.revokedAt ? "revoked " + esc(k.revokedAt.slice(0, 10)) : "live") + "</td><td>" + (k.revokedAt || !can("admin") ? "" : "<button class=quiet data-revoke=\\"" + esc(k.hash) + "\\">Revoke</button>") + "</td></tr>").join("");
1051
1522
  $("billingPanel").innerHTML = o.plan === "free"
1052
- ? "<p>You are on the <b>free</b> plan: ten thousand appends a month, no card.</p><p>The <b>team</b> plan is <b>$50 a month</b>: a million appends, email support within two working days, the same export and audit trail. No availability commitment yet, and the design fails closed: when the log is unreachable your gateway withholds pre-committed calls.</p>" + (o.stripe ? "<button id=upgrade>Upgrade to team, $50/month</button>" : "<p class=muted>Card payments are not switched on for this portal yet; email us and we move the plan by hand.</p>")
1053
- : "<p>You are on the <b>" + esc(o.plan) + "</b> plan" + (o.billing ? " (subscription " + esc(o.billing.status) + ")" : "") + ".</p>" + (o.stripe && o.billing ? "<button class=quiet id=manage>Manage billing</button>" : "");
1523
+ ? "<p>You are on the <b>free</b> plan: ten thousand appends a month, no card.</p><p>The <b>team</b> plan is <b>$50 a month</b>: a million appends, email support within two working days, the same export and audit trail. No availability commitment yet, and the design fails closed: when the log is unreachable your gateway withholds pre-committed calls.</p>" + (o.stripe ? (can("owner") ? "<button id=upgrade>Upgrade to team, $50/month</button>" : "<p class=muted>An owner upgrades the plan.</p>") : "<p class=muted>Card payments are not switched on for this portal yet; email us and we move the plan by hand.</p>")
1524
+ : "<p>You are on the <b>" + esc(o.plan) + "</b> plan" + (o.billing ? " (subscription " + esc(o.billing.status) + ")" : "") + ".</p>" + (o.stripe && o.billing && can("owner") ? "<button class=quiet id=manage>Manage billing</button>" : "");
1054
1525
  $("exportCmd").textContent = o.exportCommand; renderSetup($("setupPane"), o.setup, false);
1055
1526
  const up = $("upgrade"); if (up) up.onclick = async () => { try { const r = await api("POST", "/api/checkout", {}); location.href = r.url; } catch (err) { $("billingMsg").className = "msg err"; $("billingMsg").textContent = err.message; } };
1056
1527
  const mg = $("manage"); if (mg) mg.onclick = async () => { try { const r = await api("POST", "/api/billing-portal", {}); location.href = r.url; } catch (err) { $("billingMsg").className = "msg err"; $("billingMsg").textContent = err.message; } };
1057
1528
  };
1058
- const load = async () => { render(await api("GET", "/api/overview")); await loadPolicies(); };
1529
+ const load = async () => { render(await api("GET", "/api/overview")); await loadPolicies(); await loadMembers(); };
1530
+ const mfaShow = (on) => { $("mfaState").textContent = on ? "on" : "off"; $("mfaStart").hidden = on; $("mfaOffForm").hidden = !on; $("mfaSetupBox").hidden = true; };
1531
+ $("mfaStart").onclick = async () => { try { const r = await api("POST", "/api/mfa/setup", {}); $("mfaSecret").textContent = r.secret; $("mfaUri").textContent = r.uri; $("mfaSetupBox").hidden = false; $("accountMsg").textContent = ""; } catch (err) { note("accountMsg", err.message, false); } };
1532
+ $("mfaOnForm").onsubmit = async (e) => { e.preventDefault(); try { await api("POST", "/api/mfa/enable", { code: $("mfaOnCode").value }); $("mfaOnCode").value = ""; mfaShow(true); note("accountMsg", "Two-step sign-in is on.", true); } catch (err) { note("accountMsg", err.message, false); } };
1533
+ $("mfaOffForm").onsubmit = async (e) => { e.preventDefault(); try { await api("POST", "/api/mfa/disable", { code: $("mfaOffCode").value }); $("mfaOffCode").value = ""; mfaShow(false); note("accountMsg", "Two-step sign-in is off.", true); } catch (err) { note("accountMsg", err.message, false); } };
1534
+ const roleOptions = (cur) => ROLES.filter((r) => r !== "owner" || can("owner")).map((r) => "<option" + (r === cur ? " selected" : "") + ">" + r + "</option>").join("");
1535
+ const loadMembers = async () => {
1536
+ const r = await api("GET", "/api/members");
1537
+ $("nMembers").textContent = r.members.length;
1538
+ $("inviteRole").innerHTML = roleOptions("readonly");
1539
+ $("members").innerHTML = r.members.map((m) => "<tr><td>" + esc(m.email) + "</td><td>" + (can("admin") && (m.role !== "owner" || can("owner")) ? "<select data-setrole=" + m.id + ">" + roleOptions(m.role) + "</select>" : esc(m.role)) + "</td><td>" + esc(m.joinedAt.slice(0, 10)) + "</td><td>" + (m.mfa ? "on" : "off") + "</td><td>" + (can("admin") && (m.role !== "owner" || can("owner")) ? "<button class=link data-rmmember=" + m.id + ">Remove</button>" : "") + "</td></tr>").join("");
1540
+ $("inviteRows").innerHTML = r.invites.map((i) => "<tr><td>" + esc(i.email) + "</td><td>" + esc(i.role) + "</td><td class=mono>" + esc(i.invitedBy) + "</td><td>" + esc(i.createdAt.slice(0, 10)) + "</td><td>" + (can("admin") ? "<button class=link data-rminvite=\\"" + esc(i.email) + "\\">Cancel</button>" : "") + "</td></tr>").join("") || "<tr><td colspan=5 class=muted>none</td></tr>";
1541
+ };
1542
+ const membersDo = async (path, body, done) => { try { await api("POST", path, body); note("membersMsg", done, true); await loadMembers(); } catch (err) { note("membersMsg", err.message, false); await loadMembers(); } };
1543
+ $("inviteForm").onsubmit = (e) => { e.preventDefault(); membersDo("/api/members", { email: $("inviteEmail").value, role: $("inviteRole").value }, "Invite sent to " + $("inviteEmail").value + ".").then(() => { $("inviteEmail").value = ""; }); };
1544
+ document.addEventListener("change", (e) => { const s = e.target.closest("select[data-setrole]"); if (s) membersDo("/api/members/" + s.dataset.setrole + "/role", { role: s.value }, "Role changed."); });
1545
+ document.addEventListener("click", async (e) => {
1546
+ const rm = e.target.closest("button[data-rmmember]"); if (rm && confirm("Remove this member? They lose access to the tenant at once.")) { membersDo("/api/members/" + rm.dataset.rmmember + "/remove", {}, "Member removed."); return; }
1547
+ const ri = e.target.closest("button[data-rminvite]"); if (ri) { membersDo("/api/invites/remove", { email: ri.dataset.rminvite }, "Invite cancelled."); return; }
1548
+ const ac = e.target.closest("button[data-accept]"); if (ac) { try { await api("POST", "/api/invites/accept", { tenant: ac.dataset.accept }); await enter(); } catch (err) { note("onboardMsg", err.message, false); } }
1549
+ });
1059
1550
  const enter = async () => {
1060
1551
  try {
1061
1552
  const me = await api("GET", "/api/me");
1062
1553
  accountNotice(me);
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; }
1064
- $("who").textContent = me.email; show("app"); await load(); view((location.hash || "#overview").slice(1) || "overview");
1554
+ if (me.tenant === null) { $("onboardWho").textContent = me.email; $("invites").hidden = !(me.invites || []).length; $("inviteList").innerHTML = (me.invites || []).map((i) => "<p>Join <b>" + esc(i.tenant) + "</b> as " + esc(i.role) + " <button type=button data-accept=\\"" + esc(i.tenant) + "\\">Accept</button></p>").join(""); 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; }
1555
+ $("who").textContent = me.email; myRole = me.role; $("mintForm").hidden = !can("admin"); $("policyForm").hidden = !can("reviewer"); $("inviteBox").hidden = !can("admin") || !!(me.sso && me.sso.enforced); mfaShow(me.mfa); show("app"); await load(); view((location.hash || "#overview").slice(1) || "overview");
1065
1556
  }
1066
- catch (err) { if (err.status === 401) { show("auth"); if (location.hash === "#register" && !registering) $("authSwap").click(); } else { show("app"); $("who").textContent = err.message; } }
1557
+ catch (err) { if (err.status === 401) { show("auth"); if (location.hash === "#register" && !registering) $("authSwap").click(); if (new URLSearchParams(location.search).get("mfa") === "1") askCode(); } else { show("app"); $("who").textContent = err.message; } }
1067
1558
  };
1068
1559
  const accountNotice = (me) => {
1069
1560
  const parts = [];
@@ -1079,7 +1570,7 @@ const PORTAL_PAGE = `<!doctype html>
1079
1570
  const loadPolicies = async () => {
1080
1571
  const r = await api("GET", "/api/policies");
1081
1572
  $("nPolicies").textContent = r.policies.length || "";
1082
- $("policies").innerHTML = r.policies.map((p) => "<tr><td>" + esc(p.name) + "</td><td class=mono>" + esc(p.digest.slice(0, 16)) + "…</td><td>" + p.bytes + "</td><td>" + esc(p.createdAt.slice(0, 10)) + "</td><td class=mono>" + esc(p.createdBy.replace(/^portal:/, "")) + "</td><td><button class=link data-viewpol=\\"" + esc(p.id) + "\\">View</button> <button class=link data-rmpol=\\"" + esc(p.id) + "\\">Remove</button></td></tr>").join("") || "<tr><td colspan=6 class=muted>No versions published yet. Receipts keep their digests either way; a name is for the people reading them.</td></tr>";
1573
+ $("policies").innerHTML = r.policies.map((p) => "<tr><td>" + esc(p.name) + "</td><td class=mono>" + esc(p.digest.slice(0, 16)) + "…</td><td>" + p.bytes + "</td><td>" + esc(p.createdAt.slice(0, 10)) + "</td><td class=mono>" + esc(p.createdBy.replace(/^portal:/, "")) + "</td><td><button class=link data-viewpol=\\"" + esc(p.id) + "\\">View</button>" + (can("reviewer") ? " <button class=link data-rmpol=\\"" + esc(p.id) + "\\">Remove</button>" : "") + "</td></tr>").join("") || "<tr><td colspan=6 class=muted>No versions published yet. Receipts keep their digests either way; a name is for the people reading them.</td></tr>";
1083
1574
  };
1084
1575
  $("policyText").oninput = async () => { const t = $("policyText").value; $("policyDigestPreview").textContent = t ? "sha256 " + (await sha256hex(t)).slice(0, 16) + "…" : ""; };
1085
1576
  $("policyForm").onsubmit = async (e) => {