@agent-custody/receipts 0.8.0 → 0.9.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,157 @@ 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
+ async removeMember(tenantId, userId) {
226
+ await this.init();
227
+ 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;
228
+ if (gone)
229
+ 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]);
230
+ return gone;
231
+ }
232
+ async invite(tenantId, email, role, by) {
233
+ await this.init();
234
+ 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]);
235
+ }
236
+ async invitesOf(tenantId) {
237
+ await this.init();
238
+ 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;
239
+ return rows.map((r) => ({ email: String(r.email), role: r.role, invitedBy: String(r.invited_by), createdAt: new Date(r.created_at).toISOString() }));
240
+ }
241
+ async invitesFor(email) {
242
+ await this.init();
243
+ 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;
244
+ return rows.map((r) => ({ tenant: r.tenant_id, role: r.role }));
245
+ }
246
+ async removeInvite(tenantId, email) {
247
+ await this.init();
248
+ return (await this.client.query(`DELETE FROM ${this.p}invites WHERE tenant_id = $1 AND email = $2 RETURNING email`, [tenantId, email])).rows.length > 0;
249
+ }
250
+ async takeInvite(tenantId, email) {
251
+ await this.init();
252
+ 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;
253
+ return rows[0]?.role ?? null;
254
+ }
255
+ async mfa(userId) {
168
256
  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]);
257
+ const rows = (await this.client.query(`SELECT mfa_secret, mfa_enabled_at FROM ${this.p}users WHERE id = $1`, [userId])).rows;
258
+ return { secret: rows[0]?.mfa_secret ? String(rows[0].mfa_secret) : null, enabled: !!rows[0]?.mfa_enabled_at };
259
+ }
260
+ async setMfaSecret(userId, secretHex) {
261
+ await this.init();
262
+ 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;
263
+ }
264
+ /** False when this step or a later one was used already. */
265
+ async takeMfaStep(userId, step) {
266
+ await this.init();
267
+ 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;
268
+ }
269
+ async enableMfa(userId) {
270
+ await this.init();
271
+ await this.client.query(`UPDATE ${this.p}users SET mfa_enabled_at = now() WHERE id = $1`, [userId]);
272
+ }
273
+ async resetMfa(email) {
274
+ await this.init();
275
+ 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;
276
+ }
277
+ /** Replaces the tenant's setting. A domain belongs to one tenant, so a domain that another tenant holds is refused. */
278
+ async setSso(s) {
279
+ await this.init();
280
+ const domains = [...new Set(s.domains.map((d) => d.trim().toLowerCase()))];
281
+ if (!domains.length || domains.some((d) => !/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?\.[a-z]{2,}$/.test(d)))
282
+ throw new Error("SSO needs one or more email domains, such as acme.example");
283
+ if (!ROLES.includes(s.defaultRole) || s.defaultRole === "owner")
284
+ throw new Error("the default role of an SSO member is readonly, reviewer, or admin");
285
+ 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;
286
+ if (held[0])
287
+ throw new Error(`the domain ${domains.find((d) => held[0].domains.includes(d))} belongs to tenant ${held[0].tenant_id} already`);
288
+ 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())
289
+ 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]);
290
+ }
291
+ async ssoWhere(where, param) {
292
+ await this.init();
293
+ const r = (await this.client.query(`SELECT tenant_id, protocol, config, domains, default_role, enforced FROM ${this.p}sso WHERE ${where}`, [param])).rows[0];
294
+ 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;
295
+ }
296
+ ssoOf(tenant) {
297
+ return this.ssoWhere("tenant_id = $1", tenant);
298
+ }
299
+ ssoByDomain(domain) {
300
+ return this.ssoWhere("$1 = ANY(domains)", domain.toLowerCase());
301
+ }
302
+ async removeSso(tenant) {
303
+ await this.init();
304
+ return (await this.client.query(`DELETE FROM ${this.p}sso WHERE tenant_id = $1 RETURNING tenant_id`, [tenant])).rows.length > 0;
305
+ }
306
+ /**
307
+ * The account behind an identity that the tenant's IdP vouched for: the linked one; else the account with that
308
+ * email, linked from now on, if it verified its address; else a new verified account with a random password.
309
+ * The IdP proves the address, so an account that never verified it loses the address: the account goes, with its
310
+ * password, its sessions, and its links. A tenant that it owned stays for the operator. There are two exceptions: an
311
+ * unverified member of this same tenant, who verifies by password first (UnverifiedAccountError), and an
312
+ * unverified member of another tenant that has other members, who is refused. An account with
313
+ * no tenant joins with the default role. A member that an admin removed joins again only through a new invite,
314
+ * with the invited role.
315
+ */
316
+ async findOrCreateSsoUser(s, id) {
317
+ await this.init();
318
+ const provider = `sso:${s.tenant}`;
319
+ const parts = id.email.split("@");
320
+ if (parts.length !== 2 || !s.domains.includes(parts[1]))
321
+ throw new SsoRefusedError(`the address ${id.email} is not in a domain that signs in to ${s.tenant} through single sign-on`);
322
+ const linked = (await this.client.query(`SELECT user_id FROM ${this.p}identities WHERE provider = $1 AND subject = $2`, [provider, id.subject])).rows;
323
+ let user = linked[0] ? await this.user(linked[0].user_id) : null;
324
+ const known = !!user;
325
+ user ??= await this.userByEmail(id.email);
326
+ const unverified = !!user && !known && !user.emailVerifiedAt;
327
+ let home = user ? await this.tenantOf(user.id) : null;
328
+ if (unverified && home === s.tenant)
329
+ throw new UnverifiedAccountError(id.email);
330
+ // deleting an unverified account would strand the other members of the tenant that it belongs to
331
+ 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))
332
+ throw new SsoRefusedError(`the account ${id.email} belongs to another tenant`);
333
+ let role = s.defaultRole;
334
+ // 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
335
+ 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) {
336
+ const invited = await this.takeInvite(s.tenant, id.email);
337
+ if (!invited)
338
+ throw new SsoRefusedError(`${id.email} was removed from ${s.tenant}; an admin must invite the address again`);
339
+ role = invited;
340
+ }
341
+ if (unverified) {
342
+ for (const t of ["members", "identities"])
343
+ await this.client.query(`DELETE FROM ${this.p}${t} WHERE user_id = $1`, [user.id]);
344
+ await this.client.query(`DELETE FROM ${this.p}users WHERE id = $1`, [user.id]);
345
+ user = null;
346
+ home = null;
347
+ }
348
+ if (!user) {
349
+ user = await this.createUser(id.email, randomBytes(32).toString("hex"));
350
+ await this.markEmailVerified(user.id);
351
+ }
352
+ if (!known)
353
+ await this.linkIdentity(provider, id.subject, id.email, user.id);
354
+ if (!home)
355
+ await this.addMember(user.id, s.tenant, role);
356
+ return user;
170
357
  }
171
358
  /** the user's tenant; one per account today */
172
359
  async tenantOf(userId) {
@@ -195,10 +382,10 @@ export class PortalStore {
195
382
  await this.init();
196
383
  await this.client.query(`INSERT INTO ${this.p}stripe_events (id) VALUES ($1) ON CONFLICT (id) DO NOTHING`, [id]);
197
384
  }
198
- /** Every portal registration with its tenant and billing state, oldest first: what the operator's admin page lists. */
385
+ /** Every portal registration with its tenant and billing state, oldest first: what the operator's admin page lists. Owners only. */
199
386
  async registrations() {
200
387
  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;
388
+ 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
389
  const str = (v) => (v == null ? null : String(v));
203
390
  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
391
  }
@@ -210,11 +397,12 @@ export class PortalStore {
210
397
  }
211
398
  // ---- sessions ----
212
399
  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 })));
400
+ /** `via` records how the user signed in, for example `sso:acme`. */
401
+ export function signSession(secret, userId, ttlMs = 14 * 86_400_000, via) {
402
+ const body = b64u(Buffer.from(JSON.stringify({ u: userId, e: Date.now() + ttlMs, ...(via ? { a: via } : {}) })));
215
403
  return `${body}.${createHmac("sha256", secret).update(body).digest("base64url")}`;
216
404
  }
217
- export function readSession(secret, cookie) {
405
+ function readClaims(secret, cookie) {
218
406
  if (!cookie)
219
407
  return null;
220
408
  const [body, mac] = cookie.split(".");
@@ -224,13 +412,16 @@ export function readSession(secret, cookie) {
224
412
  if (expected.length !== mac.length || !timingSafeEqual(Buffer.from(expected), Buffer.from(mac)))
225
413
  return null;
226
414
  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;
415
+ const { u, e, a } = JSON.parse(Buffer.from(body, "base64url").toString());
416
+ return typeof u === "string" && typeof e === "number" && e > Date.now() ? { u, ...(typeof a === "string" ? { a } : {}) } : null;
229
417
  }
230
418
  catch {
231
419
  return null;
232
420
  }
233
421
  }
422
+ export const readSession = (secret, cookie) => readClaims(secret, cookie)?.u ?? null;
423
+ /** The `via` of a valid session, or null. */
424
+ export const readSessionVia = (secret, cookie) => readClaims(secret, cookie)?.a ?? null;
234
425
  // ---- Stripe, over its REST API; no SDK ----
235
426
  const form = (o) => new URLSearchParams(o).toString();
236
427
  export async function stripeRequest(s, path, body) {
@@ -260,6 +451,7 @@ export function verifyStripeSignature(header, rawBody, secret, now = Date.now(),
260
451
  }
261
452
  const TENANT_ID = /^[a-z0-9][a-z0-9-]{1,38}[a-z0-9]$/;
262
453
  const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
454
+ const ENFORCED = "Your organisation signs in through its identity provider. Use Sign in with single sign-on";
263
455
  const RESERVED = new Set(["default", "admin", "api", "www", "log", "checkpoints", "app", "portal", "stripe", "health", "t"]);
264
456
  /** One message through the provider. Best effort: a refusal or a failure is reported through `log`, never thrown. Returns whether it was accepted. */
265
457
  export async function deliverMail(mail, m, log = console.error) {
@@ -335,6 +527,8 @@ export function portalHandler(o) {
335
527
  const log = o.log ?? ((m) => console.error(m));
336
528
  const loginFailures = new RateLimiter({ perSecond: 1 / 30, burst: 8 });
337
529
  const registrations = new RateLimiter({ perSecond: 1 / 600, burst: 5 });
530
+ // per account, whatever the address
531
+ const mfaFailures = new RateLimiter({ perSecond: 1 / 120, burst: 5 });
338
532
  const base = o.publicUrl.endsWith("/") ? o.publicUrl : `${o.publicUrl}/`;
339
533
  const cookieName = "custody_session";
340
534
  const sheet = (tenant, logId) => welcomeSheet({ tenant, logId, publicUrl: base, ...(o.checkpointsUrl ? { checkpointsUrl: o.checkpointsUrl } : {}), ...(o.keyid ? { keyid: o.keyid } : {}) });
@@ -386,8 +580,21 @@ export function portalHandler(o) {
386
580
  };
387
581
  const esc = (v) => v.replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
388
582
  const setCookie = (value) => `${cookieName}=${value ?? ""}; Path=/; HttpOnly; SameSite=Strict${o.trustProxy ? "; Secure" : ""}; Max-Age=${value ? 14 * 86_400 : 0}`;
583
+ // the state between the first step and the code; never a session
584
+ 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
585
  const cookies = Object.fromEntries((req.headers.cookie ?? "").split(";").map((c) => c.trim().split("=")).filter(([k]) => k));
390
586
  const userId = readSession(o.secret, cookies[cookieName]);
587
+ const via = readSessionVia(o.secret, cookies[cookieName]);
588
+ // A page, not a redirect: the session cookie is SameSite=Strict, and a redirect that started at the provider
589
+ // would not carry it. The page's own navigation to / does.
590
+ const signedInPage = (who, next, setCookies, lead) => {
591
+ 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'" });
592
+ 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>`);
593
+ };
594
+ const enforcedFor = async (id) => {
595
+ const t = await store.tenantOf(id);
596
+ return t && (await store.ssoOf(t))?.enforced;
597
+ };
391
598
  const rawBody = async () => {
392
599
  let text = "";
393
600
  for await (const chunk of req) {
@@ -486,6 +693,20 @@ export function portalHandler(o) {
486
693
  void notifyMail({ ...profile, email: user.email, tenant: t.id });
487
694
  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
695
  };
696
+ // `on` is the state the account must be in: true to sign in or turn MFA off, false to turn it on.
697
+ const checkCode = async (id, code, on) => {
698
+ if (!mfaFailures.take(id))
699
+ return { status: 429, body: { error: "too many codes tried for this account; wait a few minutes" } };
700
+ const m = await store.mfa(id);
701
+ if (!m.secret || m.enabled !== on)
702
+ return { status: 409, body: { error: on ? "MFA is not on for this account" : "start the MFA setup first" } };
703
+ const step = totpStep(Buffer.from(m.secret, "hex"), String(code ?? ""));
704
+ if (step === null || !(await store.takeMfaStep(id, step)))
705
+ return { status: 401, body: { error: "that code is not valid, or was used already" } };
706
+ if (!on)
707
+ await store.enableMfa(id);
708
+ return null;
709
+ };
489
710
  if (req.method === "POST" && url.pathname === "/api/register") {
490
711
  const b = await jsonBody();
491
712
  const email = String(b.email ?? "").trim().toLowerCase();
@@ -542,6 +763,95 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
542
763
  });
543
764
  </script>`);
544
765
  }
766
+ // ---- enterprise sign-in through the tenant's own identity provider, which only the operator sets ----
767
+ const sso = /^\/auth\/sso(?:\/([a-z0-9-]+)(\/callback|\/saml|\/saml\/acs)?)?$/.exec(url.pathname);
768
+ if (sso && req.method === (sso[2] === "/saml/acs" ? "POST" : "GET")) {
769
+ const [, t, tail] = sso;
770
+ if (!t) {
771
+ const domain = (url.searchParams.get("email") ?? "").split("@")[1]?.trim().toLowerCase() ?? "";
772
+ const found = domain ? await store.ssoByDomain(domain) : null;
773
+ if (!found)
774
+ 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>.`);
775
+ res.writeHead(302, { location: `/auth/sso/${found.tenant}`, "cache-control": "no-store" });
776
+ return void res.end();
777
+ }
778
+ const conf = await store.ssoOf(t);
779
+ const oidcCookie = (v) => `custody_sso=${v ?? ""}; Path=/auth; HttpOnly; SameSite=Lax${o.trustProxy ? "; Secure" : ""}; Max-Age=${v ? 600 : 0}`;
780
+ // the IdP posts to the ACS from another site, and only SameSite=None comes back with that post
781
+ const samlCookie = (v) => `custody_saml=${v ?? ""}; Path=/auth/sso; HttpOnly; SameSite=None; Secure; Max-Age=${v ? 600 : 0}`;
782
+ const flowCookie = conf?.protocol === "saml" ? samlCookie : oidcCookie;
783
+ const refuse = (status, text) => page(status, "Single sign-on", esc(text), { "set-cookie": flowCookie(null) });
784
+ if (!conf)
785
+ return refuse(404, "No single sign-on is set up for that organisation.");
786
+ const at = `${portalBase}auth/sso/${t}`;
787
+ const sp = { spEntityId: `${at}/saml`, acsUrl: `${at}/saml/acs` };
788
+ const sayFailed = (what, e) => {
789
+ log(`agent-custody portal: ${what} for ${t} failed: ${e instanceof Error ? e.message : String(e)}`);
790
+ return `${what} failed. Ask your administrator to check the identity provider settings.`;
791
+ };
792
+ if (tail === "/saml") {
793
+ if (conf.protocol !== "saml")
794
+ return refuse(404, "This organisation does not use SAML.");
795
+ res.writeHead(200, { "content-type": "application/samlmetadata+xml", "cache-control": "no-store" });
796
+ 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>`);
797
+ }
798
+ const ssoFetch = o.ssoFetch ? { fetch: o.ssoFetch } : {};
799
+ if (!tail) {
800
+ try {
801
+ if (conf.protocol === "oidc") {
802
+ const { verifier, challenge } = pkce();
803
+ const state = randomBytes(16).toString("hex");
804
+ const nonce = randomBytes(16).toString("hex");
805
+ const to = await oidcAuthorizeUrl(conf.config, { redirectUri: `${at}/callback`, state, nonce, codeChallenge: challenge, ...ssoFetch });
806
+ res.writeHead(302, { location: to, "set-cookie": oidcCookie(signSession(o.secret, `oidc:${t}:${state}:${verifier}:${nonce}`, 600_000)), "cache-control": "no-store" });
807
+ }
808
+ else {
809
+ const { url: to, requestId } = await samlAuthorizeUrl(conf.config, sp);
810
+ res.writeHead(302, { location: to, "set-cookie": samlCookie(signSession(o.secret, `saml:${t}:${requestId}`, 600_000)), "cache-control": "no-store" });
811
+ }
812
+ return void res.end();
813
+ }
814
+ catch (e) {
815
+ return refuse(502, sayFailed("Single sign-on start", e));
816
+ }
817
+ }
818
+ let id;
819
+ try {
820
+ if (tail === "/callback" && conf.protocol === "oidc") {
821
+ const [kind, flowTenant, state, verifier, nonce] = (readSession(o.secret, cookies.custody_sso) ?? "").split(":");
822
+ const code = url.searchParams.get("code") ?? "";
823
+ if (kind !== "oidc" || flowTenant !== t || !code || !state || state !== url.searchParams.get("state"))
824
+ return refuse(400, "The sign-in did not start here, or took too long. Go back and try again.");
825
+ id = await oidcExchange(conf.config, { code, redirectUri: `${at}/callback`, codeVerifier: verifier, nonce: nonce, ...ssoFetch });
826
+ }
827
+ else if (tail === "/saml/acs" && conf.protocol === "saml") {
828
+ const [kind, flowTenant, requestId] = (readSession(o.secret, cookies.custody_saml) ?? "").split(":");
829
+ const samlResponse = new URLSearchParams(await rawBody()).get("SAMLResponse") ?? "";
830
+ if (kind !== "saml" || flowTenant !== t || !samlResponse)
831
+ return refuse(400, "The sign-in did not start here, or took too long. Go back and try again.");
832
+ id = await samlValidate(conf.config, { ...sp, samlResponse, requestId: requestId });
833
+ }
834
+ else {
835
+ return refuse(404, "Not found.");
836
+ }
837
+ }
838
+ catch (e) {
839
+ return refuse(401, sayFailed("Single sign-on", e));
840
+ }
841
+ let user;
842
+ try {
843
+ user = await store.findOrCreateSsoUser(conf, id);
844
+ }
845
+ catch (e) {
846
+ if (e instanceof UnverifiedAccountError)
847
+ return refuse(409, e.message);
848
+ if (e instanceof SsoRefusedError)
849
+ return refuse(403, e.message);
850
+ throw e;
851
+ }
852
+ log(`agent-custody portal: ${id.email} signed in through single sign-on for ${t}`);
853
+ return signedInPage(id.email, "/", [setCookie(signSession(o.secret, user.id, undefined, `sso:${t}`)), flowCookie(null)], "Signed in as");
854
+ }
545
855
  // ---- sign in through a provider: the OAuth web flow, state in a short-lived signed cookie ----
546
856
  const provider = /^\/auth\/(github|google)(\/callback)?$/.exec(url.pathname);
547
857
  if (req.method === "GET" && provider && o.oauth?.[provider[1]]) {
@@ -622,11 +932,11 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
622
932
  log(`agent-custody portal: ${name} sign-in for ${email} refused: the password account has not verified its address`);
623
933
  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
934
  }
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>`);
935
+ if (await enforcedFor(user.id))
936
+ return page(403, "Single sign-on required", `${esc(ENFORCED)}.`, { "set-cookie": stateCookie(null) });
937
+ const mfa = (await store.mfa(user.id)).enabled;
938
+ log(`agent-custody portal: ${email} signed in with ${name}${mfa ? ", MFA code needed" : ""}`);
939
+ 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
940
  }
631
941
  if (req.method === "POST" && url.pathname === "/api/login") {
632
942
  if (!loginFailures.take(`login:${addr}`))
@@ -635,8 +945,25 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
635
945
  const user = await store.authenticate(String(b.email ?? "").trim().toLowerCase(), String(b.password ?? ""));
636
946
  if (!user)
637
947
  return json(401, { error: "email or password not recognised" });
948
+ if (await enforcedFor(user.id))
949
+ return json(403, { error: ENFORCED });
950
+ if ((await store.mfa(user.id)).enabled)
951
+ return json(200, { mfa: true }, { "set-cookie": mfaCookie(user.id) });
638
952
  return json(200, { email: user.email }, { "set-cookie": setCookie(signSession(o.secret, user.id)) });
639
953
  }
954
+ if (req.method === "POST" && url.pathname === "/api/login/mfa") {
955
+ if (!loginFailures.take(`login:${addr}`))
956
+ return json(429, { error: "too many attempts; wait a minute" });
957
+ const b = await jsonBody();
958
+ const who = readSession(o.secret, cookies.custody_mfa);
959
+ const half = who?.startsWith("mfa:") ? await store.user(who.slice(4)) : null;
960
+ if (!half)
961
+ return json(401, { error: "the password step expired; sign in again" });
962
+ const refused = await checkCode(half.id, b.code, true);
963
+ if (refused)
964
+ return json(refused.status, refused.body);
965
+ return json(200, { email: half.email }, { "set-cookie": [setCookie(signSession(o.secret, half.id)), mfaCookie(null)] });
966
+ }
640
967
  if (req.method === "POST" && url.pathname === "/api/logout")
641
968
  return json(200, { ok: true }, { "set-cookie": setCookie(null) });
642
969
  // ---- everything below needs a session ----
@@ -648,7 +975,10 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
648
975
  if (req.method !== "GET" && !(req.headers["content-type"] ?? "").startsWith("application/json"))
649
976
  return json(415, { error: "expected a JSON body" });
650
977
  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 });
978
+ const ssoConf = tenantId ? await store.ssoOf(tenantId) : null;
979
+ if (ssoConf?.enforced && via !== `sso:${tenantId}`)
980
+ return json(401, { error: ENFORCED });
981
+ 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
982
  if (req.method === "POST" && url.pathname === "/api/verify-email") {
653
983
  const who = readSession(o.secret, String((await jsonBody()).token ?? ""));
654
984
  if (!who?.startsWith("verify:"))
@@ -668,7 +998,41 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
668
998
  return json(200, { ok: true, emailVerified: false });
669
999
  }
670
1000
  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()) });
1001
+ 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()) });
1002
+ if (req.method === "POST" && url.pathname === "/api/mfa/setup") {
1003
+ await jsonBody();
1004
+ const secret = randomBytes(20);
1005
+ if (!(await store.setMfaSecret(user.id, secret.toString("hex"))))
1006
+ return json(409, { error: "MFA is on already; turn it off first" });
1007
+ const b32 = base32(secret);
1008
+ return json(200, { secret: b32, uri: `otpauth://totp/agent-custody:${encodeURIComponent(user.email)}?secret=${b32}&issuer=agent-custody` });
1009
+ }
1010
+ if (req.method === "POST" && (url.pathname === "/api/mfa/enable" || url.pathname === "/api/mfa/disable")) {
1011
+ const on = url.pathname.endsWith("/disable");
1012
+ const refused = await checkCode(user.id, (await jsonBody()).code, on);
1013
+ if (refused)
1014
+ return json(refused.status, refused.body);
1015
+ if (on)
1016
+ await store.resetMfa(user.email);
1017
+ log(`agent-custody portal: ${user.email} turned MFA ${on ? "off" : "on"}`);
1018
+ return json(200, { mfa: !on });
1019
+ }
1020
+ // The address must be verified: otherwise anyone who registers the invited address with a password gets in.
1021
+ if (req.method === "POST" && url.pathname === "/api/invites/accept") {
1022
+ const tenant = String((await jsonBody()).tenant ?? "");
1023
+ if (tenantId)
1024
+ return json(409, { error: "this account has a tenant already; one tenant per account" });
1025
+ if (!user.emailVerifiedAt)
1026
+ return json(403, { error: "verify your email address first, then accept the invite" });
1027
+ if ((await store.ssoOf(tenant))?.enforced)
1028
+ return json(409, { error: "members of this tenant join through its identity provider" });
1029
+ const role = await store.takeInvite(tenant, user.email);
1030
+ if (!role)
1031
+ return json(404, { error: "no invite to this address for that tenant, or it is older than seven days" });
1032
+ await store.addMember(user.id, tenant, role);
1033
+ log(`agent-custody portal: ${user.email} joined tenant ${tenant} as ${role}`);
1034
+ return json(200, { tenant, role });
1035
+ }
672
1036
  if (req.method === "POST" && url.pathname === "/api/onboard") {
673
1037
  const p = await parseOnboarding(await jsonBody());
674
1038
  if ("status" in p)
@@ -681,9 +1045,15 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
681
1045
  const tenant = await o.tenancy.tenant(tenantId);
682
1046
  if (!tenant)
683
1047
  return json(409, { error: "the tenant no longer exists" });
1048
+ // The lowest role a route needs; an unlisted write needs admin.
1049
+ const myRole = (await store.roleOf(user.id, tenantId));
1050
+ const needs = [[/^\/api\/(checkout|billing-portal)$/, "owner"], [/^\/api\/policies(\/|$)/, "reviewer"]];
1051
+ const least = req.method === "GET" ? "readonly" : needs.find(([re]) => re.test(url.pathname))?.[1] ?? "admin";
1052
+ if (ROLES.indexOf(myRole) < ROLES.indexOf(least))
1053
+ return json(403, { error: `this needs the ${least} role or higher; you are ${myRole}` });
684
1054
  if (req.method === "GET" && url.pathname === "/api/me") {
685
1055
  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()) });
1056
+ 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
1057
  }
688
1058
  if (req.method === "GET" && url.pathname === "/api/overview") {
689
1059
  const q = await o.tenancy.quota(tenantId);
@@ -702,6 +1072,59 @@ fetch("/api/verify-email", { method: "POST", headers: { "content-type": "applica
702
1072
  const billing = await store.billing(tenantId);
703
1073
  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
1074
  }
1075
+ if (req.method === "GET" && url.pathname === "/api/members")
1076
+ return json(200, { members: await store.members(tenantId), invites: await store.invitesOf(tenantId) });
1077
+ const ownerOnly = (...roles) => myRole !== "owner" && roles.includes("owner");
1078
+ const OWNER_ONLY = { error: "this needs the owner role: only an owner changes an owner or grants owner" };
1079
+ if (req.method === "POST" && url.pathname === "/api/members") {
1080
+ if (ssoConf?.enforced)
1081
+ return json(409, { error: "this tenant signs in through its identity provider: members join through it, not by invite" });
1082
+ const b = await jsonBody();
1083
+ const email = String(b.email ?? "").trim().toLowerCase();
1084
+ const role = String(b.role ?? "");
1085
+ if (!EMAIL.test(email))
1086
+ return json(400, { error: "a valid email address is needed" });
1087
+ if (!ROLES.includes(role))
1088
+ return json(400, { error: `role must be one of ${ROLES.join(", ")}` });
1089
+ if (ownerOnly(role, ...(await store.invitesOf(tenantId)).filter((i) => i.email === email).map((i) => i.role)))
1090
+ return json(403, OWNER_ONLY);
1091
+ await store.invite(tenantId, email, role, user.email);
1092
+ log(`agent-custody portal: ${user.email} invited ${email} to tenant ${tenantId} as ${role}`);
1093
+ 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") });
1094
+ return json(200, { invited: email, role });
1095
+ }
1096
+ if (req.method === "POST" && url.pathname === "/api/invites/remove") {
1097
+ const email = String((await jsonBody()).email ?? "").trim().toLowerCase();
1098
+ const invited = (await store.invitesOf(tenantId)).find((i) => i.email === email);
1099
+ if (invited && ownerOnly(invited.role))
1100
+ return json(403, OWNER_ONLY);
1101
+ log(`agent-custody portal: ${user.email} cancelled the invite of ${email} to tenant ${tenantId}`);
1102
+ return json(200, { removed: await store.removeInvite(tenantId, email) });
1103
+ }
1104
+ const member = /^\/api\/members\/([0-9a-f-]{36})\/(role|remove)$/.exec(url.pathname);
1105
+ if (req.method === "POST" && member) {
1106
+ const b = await jsonBody();
1107
+ const target = await store.roleOf(member[1], tenantId);
1108
+ if (!target)
1109
+ return json(404, { error: "no such member" });
1110
+ if (member[2] === "role") {
1111
+ const role = String(b.role ?? "");
1112
+ if (!ROLES.includes(role))
1113
+ return json(400, { error: `role must be one of ${ROLES.join(", ")}` });
1114
+ if (ownerOnly(target, role))
1115
+ return json(403, OWNER_ONLY);
1116
+ if (!(await store.setRole(tenantId, member[1], role)))
1117
+ return json(409, { error: "the last owner cannot be demoted; make another member an owner first" });
1118
+ log(`agent-custody portal: ${user.email} made ${member[1]} ${role} in tenant ${tenantId}`);
1119
+ return json(200, { role });
1120
+ }
1121
+ if (ownerOnly(target))
1122
+ return json(403, OWNER_ONLY);
1123
+ if (!(await store.removeMember(tenantId, member[1])))
1124
+ return json(409, { error: "the last owner cannot be removed; make another member an owner first" });
1125
+ log(`agent-custody portal: ${user.email} removed ${member[1]} from tenant ${tenantId}`);
1126
+ return json(200, { removed: true });
1127
+ }
705
1128
  if (req.method === "GET" && url.pathname === "/api/keys") {
706
1129
  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
1130
  }
@@ -871,13 +1294,24 @@ const PORTAL_PAGE = `<!doctype html>
871
1294
  <button id="authGo" type="submit">Sign in</button>
872
1295
  <p class="msg" id="authMsg"></p>
873
1296
  </form>
1297
+ <form id="mfaForm" hidden>
1298
+ <p class="muted">Your account has two-step sign-in. Enter the six-digit code from your authenticator app.</p>
1299
+ <label>Code<input id="mfaCode" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required></label>
1300
+ <button type="submit">Verify</button>
1301
+ <p class="msg" id="mfaMsg"></p>
1302
+ </form>
874
1303
  <p class="muted" id="authNote" hidden>Next you name your organisation and get your tenant and its first key. Two minutes.</p>
1304
+ <form id="ssoForm" action="/auth/sso" method="get">
1305
+ <label>Work email for single sign-on<input name="email" type="email" autocomplete="email" required></label>
1306
+ <button class="quiet" type="submit">Sign in with single sign-on</button>
1307
+ </form>
875
1308
  <p class="muted"><button class="link" id="authSwap" type="button">Create an account instead</button></p>
876
1309
  <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
1310
  </section>
878
1311
  <section id="onboard" class="auth" hidden>
879
1312
  <h1>Set up your tenant</h1>
880
1313
  <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>
1314
+ <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
1315
  <form id="onboardForm">
882
1316
  <label>Your name<input id="name" autocomplete="name" maxlength="120" required></label>
883
1317
  <label>Company or organisation<input id="company" autocomplete="organization" maxlength="160" required></label>
@@ -906,9 +1340,11 @@ const PORTAL_PAGE = `<!doctype html>
906
1340
  <a href="#setup" data-view="setup">Setup</a>
907
1341
  <a href="#keys" data-view="keys">API keys <span class="n" id="nKeys"></span></a>
908
1342
  <a href="#policies" data-view="policies">Policies <span class="n" id="nPolicies"></span></a>
1343
+ <a href="#members" data-view="members">Members <span class="n" id="nMembers"></span></a>
909
1344
  <a href="#billing" data-view="billing">Billing</a>
910
1345
  <a href="#export" data-view="export">Export</a>
911
1346
  <div class="group">Account</div>
1347
+ <a href="#account" data-view="account">Two-step sign-in</a>
912
1348
  <a href="#" id="signout">Sign out</a>
913
1349
  </nav>
914
1350
  <main>
@@ -948,6 +1384,29 @@ const PORTAL_PAGE = `<!doctype html>
948
1384
  <div class="panel" id="policyView" hidden><h2 id="policyViewName"></h2><pre id="policyViewText"></pre></div>
949
1385
  <p class="msg" id="policiesMsg"></p>
950
1386
  </div>
1387
+ <div data-pane="members" hidden>
1388
+ <h1>Members</h1>
1389
+ <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>
1390
+ <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>
1391
+ <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>
1392
+ <h2>Pending invites</h2>
1393
+ <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>
1394
+ <p class="msg" id="membersMsg"></p>
1395
+ </div>
1396
+ <div data-pane="account" hidden>
1397
+ <h1>Two-step sign-in</h1>
1398
+ <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>
1399
+ <div class="panel">
1400
+ <button id="mfaStart" type="button">Set up</button>
1401
+ <div id="mfaSetupBox" hidden>
1402
+ <p>Add this secret to your authenticator app (enter it by hand, or paste the address), then type a code from the app.</p>
1403
+ <p class="tok" id="mfaSecret"></p><p class="tok" id="mfaUri"></p>
1404
+ <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>
1405
+ </div>
1406
+ <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>
1407
+ </div>
1408
+ <p class="msg" id="accountMsg"></p>
1409
+ </div>
951
1410
  <div data-pane="billing" hidden>
952
1411
  <h1>Billing</h1>
953
1412
  <div class="panel" id="billingPanel"></div>
@@ -978,6 +1437,10 @@ const PORTAL_PAGE = `<!doctype html>
978
1437
  const fmt = (n) => Number(n).toLocaleString();
979
1438
  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
1439
  let registering = false;
1440
+ let myRole = "readonly";
1441
+ const ROLES = ["readonly", "reviewer", "admin", "owner"];
1442
+ const can = (least) => ROLES.indexOf(myRole) >= ROLES.indexOf(least);
1443
+ const note = (id, text, ok) => { $(id).className = "msg " + (ok ? "ok" : "err"); $(id).textContent = text; };
981
1444
  const show = (id) => { for (const s of ["auth", "onboard", "welcome", "app"]) $(s).hidden = s !== id; };
982
1445
  const PROVIDERS = __PROVIDERS__;
983
1446
  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 +1459,17 @@ const PORTAL_PAGE = `<!doctype html>
996
1459
  $("authForm").onsubmit = async (e) => {
997
1460
  e.preventDefault(); $("authMsg").className = "msg"; $("authMsg").textContent = "";
998
1461
  try {
999
- await api("POST", registering ? "/api/register" : "/api/login", { email: $("email").value, password: $("password").value });
1462
+ const r = await api("POST", registering ? "/api/register" : "/api/login", { email: $("email").value, password: $("password").value });
1463
+ if (r.mfa) { askCode(); return; }
1000
1464
  await enter();
1001
1465
  } catch (err) { $("authMsg").className = "msg err"; $("authMsg").textContent = err.message; }
1002
1466
  };
1467
+ 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(); };
1468
+ $("mfaForm").onsubmit = async (e) => {
1469
+ e.preventDefault();
1470
+ try { await api("POST", "/api/login/mfa", { code: $("mfaCode").value }); location.href = "/"; }
1471
+ catch (err) { note("mfaMsg", err.message, false); }
1472
+ };
1003
1473
  $("onboardForm").onsubmit = async (e) => {
1004
1474
  e.preventDefault(); $("onboardMsg").className = "msg"; $("onboardMsg").textContent = "";
1005
1475
  try {
@@ -1047,23 +1517,43 @@ const PORTAL_PAGE = `<!doctype html>
1047
1517
  const max = Math.max(1, ...o.months.map((m) => m.appends));
1048
1518
  $("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
1519
  $("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("");
1520
+ $("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
1521
  $("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>" : "");
1522
+ ? "<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>")
1523
+ : "<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
1524
  $("exportCmd").textContent = o.exportCommand; renderSetup($("setupPane"), o.setup, false);
1055
1525
  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
1526
  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
1527
  };
1058
- const load = async () => { render(await api("GET", "/api/overview")); await loadPolicies(); };
1528
+ const load = async () => { render(await api("GET", "/api/overview")); await loadPolicies(); await loadMembers(); };
1529
+ const mfaShow = (on) => { $("mfaState").textContent = on ? "on" : "off"; $("mfaStart").hidden = on; $("mfaOffForm").hidden = !on; $("mfaSetupBox").hidden = true; };
1530
+ $("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); } };
1531
+ $("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); } };
1532
+ $("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); } };
1533
+ const roleOptions = (cur) => ROLES.filter((r) => r !== "owner" || can("owner")).map((r) => "<option" + (r === cur ? " selected" : "") + ">" + r + "</option>").join("");
1534
+ const loadMembers = async () => {
1535
+ const r = await api("GET", "/api/members");
1536
+ $("nMembers").textContent = r.members.length;
1537
+ $("inviteRole").innerHTML = roleOptions("readonly");
1538
+ $("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("");
1539
+ $("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>";
1540
+ };
1541
+ 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(); } };
1542
+ $("inviteForm").onsubmit = (e) => { e.preventDefault(); membersDo("/api/members", { email: $("inviteEmail").value, role: $("inviteRole").value }, "Invite sent to " + $("inviteEmail").value + ".").then(() => { $("inviteEmail").value = ""; }); };
1543
+ 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."); });
1544
+ document.addEventListener("click", async (e) => {
1545
+ 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; }
1546
+ const ri = e.target.closest("button[data-rminvite]"); if (ri) { membersDo("/api/invites/remove", { email: ri.dataset.rminvite }, "Invite cancelled."); return; }
1547
+ 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); } }
1548
+ });
1059
1549
  const enter = async () => {
1060
1550
  try {
1061
1551
  const me = await api("GET", "/api/me");
1062
1552
  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");
1553
+ 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; }
1554
+ $("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
1555
  }
1066
- catch (err) { if (err.status === 401) { show("auth"); if (location.hash === "#register" && !registering) $("authSwap").click(); } else { show("app"); $("who").textContent = err.message; } }
1556
+ 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
1557
  };
1068
1558
  const accountNotice = (me) => {
1069
1559
  const parts = [];
@@ -1079,7 +1569,7 @@ const PORTAL_PAGE = `<!doctype html>
1079
1569
  const loadPolicies = async () => {
1080
1570
  const r = await api("GET", "/api/policies");
1081
1571
  $("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>";
1572
+ $("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
1573
  };
1084
1574
  $("policyText").oninput = async () => { const t = $("policyText").value; $("policyDigestPreview").textContent = t ? "sha256 " + (await sha256hex(t)).slice(0, 16) + "…" : ""; };
1085
1575
  $("policyForm").onsubmit = async (e) => {