File size: 25,552 Bytes
42128a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
// Authentication: registration and login with OPAQUE (RFC 9807, configuration
// taper-opaque-v1; the server never sees the password), access tokens and
// the devices they sign in, security keys (WebAuthn/FIDO2) as a second
// factor and for step-up, and account suspension. Owns `state.users`,
// `state.tokens`, OPAQUE flows, login attempt counters, security-key records
// and the reserved names of deleted accounts.
// Trust boundary: everything before `identify` arrives here (the methods
// marked `public`); requireStrong() is the step-up check for sensitive
// actions: a fresh password proof and, when the account has keys, a touch.

import { randomBytes, createHash } from 'node:crypto';
import * as opaque from '@serenity-kit/opaque';
import { verifyRegistration, verifyAssertion, WebAuthnError } from './webauthn.js';
import { fail, requireString } from './events.js';
import { b64url, now, dropWhere, isLoopback } from './util.js';

await opaque.ready;

const OPAQUE_FLOW_MS = 60_000;
// Exact sizes for ristretto255-SHA512 (section 9.3: reject malformed input
// before it reaches the library).
const OPAQUE_SIZES = { registration_request: 32, registration_record: 192, ke1: 96, ke3: 64 };
const LOGIN_FREE_ATTEMPTS = 5;
const LOGIN_WINDOW_MS = 3_600_000;
const MAX_OPAQUE_FLOWS = 2048;
const MAX_AUTHED_FLOWS_PER_USER = 16;
const MAX_CONN_FREE_LOGINS = LOGIN_FREE_ATTEMPTS;
const MAX_DEVICES_PER_USER = 32;
const MAX_SECURITY_KEYS = 8;
const WEBAUTHN_TIMEOUT_MS = 60_000;

// Tokens are stored only as SHA-256 hashes, so a leak of server memory or a
// future database doesn't hand out working tokens. They expire.
export const tokenKey = (token) => createHash('sha256').update(token).digest('base64url');

function opaqueMessage(body, key) {
  const v = requireString(body, key, { max: 512 });
  const bytes = Buffer.from(v, 'base64url');
  if (bytes.length !== OPAQUE_SIZES[key] || bytes.toString('base64url') !== v) fail('T_INVALID_PARAM', `'${key}' is malformed`);
  return v;
}

const credDescriptor = (c) => ({ type: 'public-key', id: c.id });
function keyFailure(e) {
  if (e instanceof WebAuthnError) fail('T_FORBIDDEN', `Security key refused: ${e.message}`);
  throw e;
}

export function create(app) {
  const { cfg, disk } = app;
  const { users, tokens } = app.state;
  const { SERVER_NAME, TOKEN_TTL_MS, TOKEN_MAX_MS, WEBAUTHN_ORIGINS, WEBAUTHN_ROOTS } = cfg;
  const LIMITS = cfg.limits;
  // The OPRF seed and AKE key pair: global, long-lived, kept with the other
  // keys (not with the data).
  const OPAQUE_SETUP = disk.secret('opaque', () => opaque.server.createSetup());
  const opaqueFlows = new Map(); // flow id -> { kind, user_id, state?, expires_ts }: before sign-in
  const authedFlows = new Map(); // the same, started by a signed-in session (kept apart, capped per account)
  const loginAttempts = new Map(); // user_id -> { count, since }: logins that never finished
  // user_id -> { credentials: [{id, public_key, alg, sign_count, nickname, level, created_ts, rp_id}],
  //              show_indicator, login_requires_key }
  const webauthn = new Map();
  const credentialOwner = new Map(); // credential id -> user_id
  const suspended = new Set(); // user_id
  // Deleted accounts' names stay reserved, so nobody can register one later
  // and pass for the old owner.
  const deletedUsers = new Set();

  const opaqueIds = (user_id) => ({ client: user_id, server: SERVER_NAME });

  function registrationResponse(user_id, registrationRequest) {
    try {
      return opaque.server.createRegistrationResponse({ serverSetup: OPAQUE_SETUP, userIdentifier: user_id, registrationRequest }).registrationResponse;
    } catch {
      return fail('T_INVALID_PARAM', "'registration_request' is malformed");
    }
  }

  function userIdFor(body) {
    const username = requireString(body, 'username', { max: 255 }).toLowerCase();
    return username.startsWith('@') ? username : `@${username}:${SERVER_NAME}`;
  }

  // A flow started by a signed-in session (`authed`) can only push out that
  // account's own older flows, never anyone's sign-in.
  function startFlow(entry, { authed = false } = {}) {
    const t = now();
    const flows = authed ? authedFlows : opaqueFlows;
    // Map preserves insertion order and all flows share OPAQUE_FLOW_MS TTL,
    // so expiring from the front is O(1) amortized.
    for (const [id, f] of flows) {
      if (f.expires_ts > t) break;
      flows.delete(id);
    }
    const mine = authed ? [...flows].filter(([, f]) => f.user_id === entry.user_id) : [];
    while (mine.length >= MAX_AUTHED_FLOWS_PER_USER) flows.delete(mine.shift()[0]);
    while (flows.size >= MAX_OPAQUE_FLOWS) flows.delete(flows.keys().next().value);
    const id = b64url(randomBytes(16));
    flows.set(id, { ...entry, expires_ts: t + OPAQUE_FLOW_MS });
    return id;
  }

  // Forget every flow in progress for an account (after a password change,
  // suspension, unlock or deletion): nothing started before may finish after.
  function dropFlows(user_id) {
    for (const flows of [opaqueFlows, authedFlows]) for (const [id, f] of flows) if (f.user_id === user_id) flows.delete(id);
  }

  function takeFlow(body, key, kind) {
    const id = requireString(body, key, { max: 64 });
    const flow = opaqueFlows.get(id) ?? authedFlows.get(id);
    opaqueFlows.delete(id); // single use
    authedFlows.delete(id);
    if (!flow || flow.kind !== kind || flow.expires_ts <= now()) fail('T_FORBIDDEN', 'Unknown or expired flow');
    return flow;
  }

  // Count every login start as a failure until it finishes (section 9.2: the
  // client learns the outcome from KE2 and need never send KE3). Also gate
  // per-connection login attempts so rotating usernames cannot bypass PoW.
  function countLoginAttempt(user_id, frame, binding, conn = null) {
    const t = now();
    let a = loginAttempts.get(user_id);
    if (!a || t - a.since > LOGIN_WINDOW_MS) a = { count: 0, since: t };
    while (loginAttempts.size >= 100_000) loginAttempts.delete(loginAttempts.keys().next().value);
    const connLimited = conn && !conn.session && conn.loginStarts >= MAX_CONN_FREE_LOGINS;
    if (a.count >= LOGIN_FREE_ATTEMPTS || connLimited) app.quota.requireChallenge(frame, binding, 16, 'Too many login attempts');
    a.count++;
    loginAttempts.set(user_id, a);
    if (conn && !conn.session) conn.loginStarts++;
  }

  function loginStart(body, frame, binding, conn = null) {
    const user_id = userIdFor(body);
    // A signed-in session proves only its own password (step-up), never probes others.
    if (conn?.session && user_id !== conn.session.user_id) fail('T_FORBIDDEN', 'A signed-in session cannot start a proof for another account');
    const ke1 = opaqueMessage(body, 'ke1');
    countLoginAttempt(user_id, frame, binding, conn);
    // Unknown users get a response built from a fake record, indistinguishable
    // from a real one (section 6.3.2.2). Both paths do the same work.
    const record = users.get(user_id)?.opaque_record ?? null;
    let res;
    try {
      res = opaque.server.startLogin({
        serverSetup: OPAQUE_SETUP, registrationRecord: record, startLoginRequest: ke1,
        userIdentifier: user_id, identifiers: opaqueIds(user_id),
      });
    } catch {
      fail('T_INVALID_PARAM', "'ke1' is malformed");
    }
    // The flow remembers which record it was started against: a proof begun
    // before a password change must not finish after it.
    return { ke2: res.loginResponse, login_id: startFlow({ kind: 'login', user_id, state: res.serverLoginState, record }, { authed: Boolean(conn?.session) }) };
  }

  // Verify KE3. Throws unless the client proved it knows the password; never
  // returns the session key (section 6.4).
  function loginFinish(body) {
    const flow = takeFlow(body, 'login_id', 'login');
    const ke3 = opaqueMessage(body, 'ke3');
    try {
      opaque.server.finishLogin({ serverLoginState: flow.state, finishLoginRequest: ke3, identifiers: opaqueIds(flow.user_id) });
    } catch {
      fail('T_FORBIDDEN', 'Invalid username or password');
    }
    // A fake record can't produce a valid KE3, but never trust that alone.
    if (!users.get(flow.user_id)?.opaque_record || users.get(flow.user_id).opaque_record !== flow.record) fail('T_FORBIDDEN', 'Invalid username or password');
    if (suspended.has(flow.user_id)) fail('T_USER_SUSPENDED', 'This account is suspended on this server');
    loginAttempts.delete(flow.user_id);
    return flow.user_id;
  }

  function issueToken(user_id) {
    // Signing in again and again must not grow an account's devices without
    // bound: the oldest sign-in makes way.
    const mine = [...tokens].filter(([, a]) => a.user_id === user_id).sort((x, y) => (x[1].issued_ts ?? 0) - (y[1].issued_ts ?? 0));
    for (const [k] of mine.slice(0, Math.max(0, mine.length - MAX_DEVICES_PER_USER + 1))) expireToken(k, 'Too many devices');
    const access_token = 'tp_' + b64url(randomBytes(32));
    const device_id = b64url(randomBytes(6)).toUpperCase();
    const auth = { user_id, device_id, issued_ts: now(), expires_ts: now() + TOKEN_TTL_MS };
    tokens.set(tokenKey(access_token), auth);
    disk.put('tokens', tokenKey(access_token), auth);
    return { user_id, access_token, device_id, expires_in_ms: TOKEN_TTL_MS };
  }

  const hasToken = (user_id, device_id) => [...tokens.values()].some((t) => t.user_id === user_id && t.device_id === device_id);

  // A token is gone: every socket bound to it closes, and its device's keys go
  // once no other token uses that device.
  function expireToken(k, reason = 'Access token expired') {
    const auth = tokens.get(k);
    if (!auth) return;
    tokens.delete(k);
    disk.del('tokens', k);
    app.sessions.closeSessions(auth.user_id, (s) => s.tokenHash === k, reason);
    if (!hasToken(auth.user_id, auth.device_id)) app.keys.forgetDevice(auth.user_id, auth.device_id);
  }

  // Sign devices of an account out: those matching `pred`, or all of them.
  function revokeDevices(user_id, reason, pred = () => true) {
    for (const [k, auth] of tokens) if (auth.user_id === user_id && pred(auth.device_id)) expireToken(k, reason);
    for (const device_id of app.keys.devicesOf(user_id)) if (pred(device_id)) app.keys.forgetDevice(user_id, device_id);
    app.sessions.closeSessions(user_id, (s) => pred(s.device_id), reason);
  }

  function lookupToken(token) {
    if (typeof token !== 'string') return null;
    const key = tokenKey(token);
    const auth = tokens.get(key);
    if (!auth) return null;
    if (auth.expires_ts <= now()) { expireToken(key); return null; }
    // A token in use doesn't lapse (a device that stays signed in would lose its keys otherwise),
    // up to an absolute limit from when it was issued.
    const renewed = Math.min(now() + TOKEN_TTL_MS, (auth.issued_ts ?? now()) + TOKEN_MAX_MS);
    if (renewed - auth.expires_ts > TOKEN_TTL_MS / 4) {
      auth.expires_ts = renewed;
      disk.put('tokens', key, auth);
    }
    return auth;
  }

  // --- Security keys ---------------------------------------------------------

  function saveWebauthn(user_id) {
    const rec = webauthn.get(user_id);
    if (rec) disk.put('webauthn', user_id, rec); else disk.del('webauthn', user_id);
  }

  function dropSecurityKeys(user_id) {
    for (const c of webauthn.get(user_id)?.credentials ?? []) credentialOwner.delete(c.id);
    webauthn.delete(user_id);
    disk.del('webauthn', user_id);
  }

  function webauthnRecord(user_id) {
    let rec = webauthn.get(user_id);
    if (!rec) { rec = { credentials: [], show_indicator: false, login_requires_key: false }; webauthn.set(user_id, rec); }
    return rec;
  }

  // The page's origin comes from the WebSocket handshake. A key only answers
  // for the site it was registered on, so a page elsewhere can't use it.
  function webauthnSite(origin) {
    let u;
    try { u = new URL(origin); } catch { return fail('T_FORBIDDEN', 'Security keys need a web page: this connection has no origin'); }
    const local = isLoopback(u.hostname) || u.hostname.endsWith('.onion');
    if (u.origin !== origin || (u.protocol !== 'https:' && !(u.protocol === 'http:' && local))) {
      fail('T_FORBIDDEN', 'Security keys need an https page (or http on localhost or an onion address)');
    }
    if (WEBAUTHN_ORIGINS && !WEBAUTHN_ORIGINS.has(origin)) fail('T_FORBIDDEN', 'This server does not accept security keys from this site');
    return { origin, rp_id: u.hostname };
  }

  const requestOptions = (site, creds, challenge) => ({
    challenge, rpId: site.rp_id, timeout: WEBAUTHN_TIMEOUT_MS, userVerification: 'preferred',
    allowCredentials: creds.filter((c) => c.rp_id === site.rp_id).map(credDescriptor),
  });

  function checkAssertion(user_id, flow, credential) {
    const cred = webauthn.get(user_id)?.credentials.find((c) => c.id === credential?.id);
    if (!cred || cred.rp_id !== flow.rp_id) fail('T_FORBIDDEN', 'Unknown security key');
    try {
      cred.sign_count = verifyAssertion(credential, { challenge: flow.challenge, origin: flow.origin, rpId: flow.rp_id, stored: cred });
    } catch (e) { keyFailure(e); }
    saveWebauthn(user_id);
  }

  /** A touch of one of the account's keys, if it has any. `keyAuth` is {challenge_id, credential}. */
  function requireKey(ctx, keyAuth) {
    if (!webauthn.get(ctx.user_id)?.credentials.length) return;
    if (typeof keyAuth?.challenge_id !== 'string') fail('T_FORBIDDEN', 'This needs your security key', { needs: 'security_key' });
    const flow = takeFlow(keyAuth, 'challenge_id', 'wa-assert');
    if (flow.user_id !== ctx.user_id) fail('T_FORBIDDEN', 'That challenge is for another account');
    checkAssertion(ctx.user_id, flow, keyAuth.credential);
  }

  /** The password (fresh OPAQUE proof) and, if there are keys, a touch. */
  function requireStrong(ctx, body, what) {
    const auth = body?.auth;
    if (auth?.type !== 't.login.opaque') fail('T_FORBIDDEN', `${what} requires your password`, { needs: 'password' });
    if (loginFinish(auth) !== ctx.user_id) fail('T_FORBIDDEN', 'That proof is for another account');
    requireKey(ctx, body.key_auth ?? auth.key_auth);
  }

  // A new challenge for `creds` on `site`, remembered as a flow of `kind`.
  function keyChallenge(kind, user_id, site, creds, authed) {
    const challenge = b64url(randomBytes(32));
    return { id: startFlow({ kind, user_id, challenge, ...site }, { authed }), options: requestOptions(site, creds, challenge) };
  }

  // Methods callable before `identify`.
  const publicMethods = {
    't.opaque.register.start': { public: true, run(_p, { frame, binding }, body) {
      if (!LIMITS.registration_open) fail('T_REGISTRATION_CLOSED', 'Registration is closed on this server');
      const inviteHash = LIMITS.invite_only ? app.quota.checkInvite(requireString(body, 'invite_token', { max: 128 })) : null;
      if (LIMITS.register_pow_bits > 0) app.quota.requireChallenge(frame, binding, LIMITS.register_pow_bits, 'Registration needs a proof-of-work challenge');
      const username = requireString(body, 'username', { max: 64 }).toLowerCase();
      if (!/^[a-z0-9._=\-/]+$/.test(username)) fail('T_INVALID_USERNAME', 'Usernames may only contain a-z, 0-9, . _ = - /');
      const user_id = `@${username}:${SERVER_NAME}`;
      // Registration can't hide whether a name exists (section 10.9); the
      // challenge above rate-limits it.
      if (users.has(user_id) || deletedUsers.has(user_id)) fail('T_USER_IN_USE', 'Username taken');
      const registration_response = registrationResponse(user_id, opaqueMessage(body, 'registration_request'));
      if (inviteHash) app.quota.reserveInvite(inviteHash, now() + OPAQUE_FLOW_MS);
      return { registration_response, registration_id: startFlow({ kind: 'register', user_id, inviteHash }) };
    } },

    't.opaque.register.finish': { public: true, run(_p, _ctx, body) {
      const flow = takeFlow(body, 'registration_id', 'register');
      const registration_record = opaqueMessage(body, 'registration_record');
      if (flow.inviteHash) app.quota.releaseInvite(flow.inviteHash);
      if (users.has(flow.user_id) || deletedUsers.has(flow.user_id)) fail('T_USER_IN_USE', 'Username taken');
      if (flow.inviteHash) app.quota.useInvite(flow.inviteHash);
      const record = { user_id: flow.user_id, opaque_record: registration_record, created_ts: now() };
      users.set(flow.user_id, record);
      disk.put('users', flow.user_id, record);
      return issueToken(flow.user_id);
    } },

    't.opaque.login.start': { public: true, run: (_p, { frame, binding, conn }, body) => loginStart(body, frame, binding, conn) },

    't.opaque.login.finish': { public: true, run(_p, { origin }, body) {
      const user_id = loginFinish(body);
      const rec = webauthn.get(user_id);
      if (rec?.login_requires_key && rec.credentials.length) {
        // The password was right. This account also wants a touch of a key.
        const site = webauthnSite(origin);
        const creds = rec.credentials.filter((c) => c.rp_id === site.rp_id);
        if (!creds.length) fail('T_FORBIDDEN', 'This account needs a security key that was registered for this site');
        const { id: ticket, options } = keyChallenge('wa-login', user_id, site, creds, false);
        return { second_factor: { type: 't.webauthn', ticket, options } };
      }
      return issueToken(user_id);
    } },

    // Second step of a login on an account that requires a security key.
    't.webauthn.login': { public: true, run(_p, _ctx, body) {
      const flow = takeFlow(body, 'ticket', 'wa-login');
      if (suspended.has(flow.user_id)) fail('T_USER_SUSPENDED', 'This account is suspended on this server');
      checkAssertion(flow.user_id, flow, body.credential);
      return issueToken(flow.user_id);
    } },
  };

  const methods = {
    't.webauthn.list': { run(_p, ctx) {
      const rec = webauthn.get(ctx.user_id);
      return {
        keys: (rec?.credentials ?? []).map((c) => ({ id: c.id, nickname: c.nickname, level: c.level, created_ts: c.created_ts })),
        show_indicator: rec?.show_indicator ?? false,
        login_requires_key: rec?.login_requires_key ?? false,
      };
    } },

    // A challenge for a sensitive action: touch a key, then pass the result as `key_auth`.
    't.webauthn.challenge': { run(_p, ctx) {
      const site = webauthnSite(ctx.origin);
      const creds = (webauthn.get(ctx.user_id)?.credentials ?? []).filter((c) => c.rp_id === site.rp_id);
      if (!creds.length) fail('T_NOT_FOUND', 'No security key is registered for this site');
      const { id: challenge_id, options } = keyChallenge('wa-assert', ctx.user_id, site, creds, true);
      return { challenge_id, options };
    } },

    't.webauthn.register.start': { run(_p, ctx, body) {
      const site = webauthnSite(ctx.origin);
      requireStrong(ctx, body, 'Adding a security key');
      const rec = webauthnRecord(ctx.user_id);
      if (rec.credentials.length >= MAX_SECURITY_KEYS) fail('T_LIMIT_EXCEEDED', `At most ${MAX_SECURITY_KEYS} security keys`);
      const challenge = b64url(randomBytes(32));
      const challenge_id = startFlow({ kind: 'wa-register', user_id: ctx.user_id, challenge, ...site }, { authed: true });
      const roaming = body.attachment !== 'any';
      return {
        challenge_id,
        options: {
          challenge, timeout: WEBAUTHN_TIMEOUT_MS, attestation: 'direct',
          rp: { id: site.rp_id, name: 'Taper' },
          user: { id: b64url(createHash('sha256').update(`taper-webauthn-user|${ctx.user_id}`).digest()), name: ctx.user_id, displayName: ctx.user_id },
          pubKeyCredParams: [-7, -8, -257].map((alg) => ({ type: 'public-key', alg })),
          excludeCredentials: rec.credentials.filter((c) => c.rp_id === site.rp_id).map(credDescriptor),
          authenticatorSelection: {
            ...(roaming ? { authenticatorAttachment: 'cross-platform' } : {}),
            residentKey: 'discouraged', requireResidentKey: false, userVerification: 'preferred',
          },
        },
      };
    } },

    't.webauthn.register.finish': { run(_p, ctx, body) {
      const flow = takeFlow(body, 'challenge_id', 'wa-register');
      if (flow.user_id !== ctx.user_id) fail('T_FORBIDDEN', 'That challenge is for another account');
      const site = webauthnSite(ctx.origin);
      if (site.origin !== flow.origin) fail('T_FORBIDDEN', 'The page changed during registration');
      let r;
      try {
        r = verifyRegistration(body.credential, { challenge: flow.challenge, origin: flow.origin, rpId: flow.rp_id, roots: WEBAUTHN_ROOTS, now: now() });
      } catch (e) { keyFailure(e); }
      if (credentialOwner.has(r.credentialId)) fail('T_FORBIDDEN', 'That security key is already registered');
      const rec = webauthnRecord(ctx.user_id);
      if (rec.credentials.length >= MAX_SECURITY_KEYS) fail('T_LIMIT_EXCEEDED', `At most ${MAX_SECURITY_KEYS} security keys`);
      const nickname = requireString(body, 'nickname', { optional: true, max: 40 })?.trim() || 'Security key';
      // Kept: what's needed to check a touch later, and the level. Nothing about the device's make or model.
      rec.credentials.push({
        id: r.credentialId, public_key: r.publicKey, alg: r.alg, sign_count: r.signCount,
        nickname, level: r.level, created_ts: now(), rp_id: flow.rp_id,
      });
      credentialOwner.set(r.credentialId, ctx.user_id);
      saveWebauthn(ctx.user_id);
      return { id: r.credentialId, level: r.level };
    } },

    't.webauthn.remove': { params: { id: { max: 1400 } }, run({ id }, ctx, body) {
      const rec = webauthn.get(ctx.user_id);
      if (!rec?.credentials.some((c) => c.id === id)) fail('T_NOT_FOUND', 'No such security key');
      requireStrong(ctx, body, 'Removing a security key');
      rec.credentials = rec.credentials.filter((c) => c.id !== id);
      credentialOwner.delete(id);
      if (!rec.credentials.length) { rec.login_requires_key = false; rec.show_indicator = false; }
      saveWebauthn(ctx.user_id);
      return {};
    } },

    't.webauthn.settings': { run(_p, ctx, body) {
      const rec = webauthnRecord(ctx.user_id);
      const wantsIndicator = body.show_indicator;
      const wantsLogin = body.login_requires_key;
      for (const v of [wantsIndicator, wantsLogin]) if (v !== undefined && typeof v !== 'boolean') fail('T_INVALID_PARAM', 'Settings are true or false');
      if ((wantsIndicator || wantsLogin) && !rec.credentials.length) fail('T_FORBIDDEN', 'Register a security key first');
      const loginChanges = wantsLogin !== undefined && wantsLogin !== rec.login_requires_key;
      const indicatorChanges = wantsIndicator !== undefined && wantsIndicator !== rec.show_indicator;
      // Changing the login rule, or showing the badge (it publishes something),
      // takes the password and a touch, checked once before anything changes.
      // Hiding the badge needs only the session.
      if (loginChanges || (indicatorChanges && wantsIndicator)) requireStrong(ctx, body, loginChanges ? 'Changing login rules' : 'Showing the key badge');
      if (loginChanges) rec.login_requires_key = wantsLogin;
      if (indicatorChanges) {
        rec.show_indicator = wantsIndicator;
        app.keys.notifyDeviceListChange(ctx.user_id); // peers re-read the indicator with the keys
      }
      saveWebauthn(ctx.user_id);
      return { show_indicator: rec.show_indicator, login_requires_key: rec.login_requires_key };
    } },
  };

  return {
    methods: { ...publicMethods, ...methods },
    opaqueMessage, registrationResponse, startFlow, takeFlow, dropFlows, requireStrong,
    issueToken, lookupToken, revokeDevices, hasToken, dropSecurityKeys,
    resetLoginAttempts: (user_id) => loginAttempts.delete(user_id),
    securityKeyCount: (user_id) => webauthn.get(user_id)?.credentials.length ?? 0,
    /** The best level among the user's keys, or null if they hold none or don't show it. */
    hardwareKeyLevel(user_id) {
      const rec = webauthn.get(user_id);
      if (!rec?.show_indicator || !rec.credentials.length) return null;
      return rec.credentials.some((c) => c.level === 'attested') ? 'attested' : 'unattested';
    },
    isSuspended: (user_id) => suspended.has(user_id),
    suspendedCount: () => suspended.size,
    setSuspended(user_id, on) {
      if (on) { suspended.add(user_id); disk.put('suspended', user_id, { ts: now() }); } else { suspended.delete(user_id); disk.del('suspended', user_id); }
    },
    markDeleted(user_id) { deletedUsers.add(user_id); disk.put('deleted_users', user_id, { ts: now() }); },
    // Returns whether anything left the plaintext store (so it needs a checkpoint).
    purge(t) {
      let n = 0;
      for (const [k, auth] of tokens) if (auth.expires_ts <= t) { expireToken(k); n++; }
      dropWhere(loginAttempts, (a) => t - a.since > LOGIN_WINDOW_MS);
      return n > 0;
    },
    restore() {
      for (const [user_id, u] of disk.all('users')) if (u.opaque_record) users.set(user_id, u);
      for (const [k, auth] of disk.all('tokens')) {
        if (auth.expires_ts > now()) tokens.set(k, auth);
        else disk.del('tokens', k); // expired while the server was stopped
      }
      for (const [user_id, rec] of disk.all('webauthn')) {
        webauthn.set(user_id, rec);
        for (const c of rec.credentials) credentialOwner.set(c.id, user_id);
      }
      for (const [user_id] of disk.all('deleted_users')) deletedUsers.add(user_id);
      for (const [user_id] of disk.all('suspended')) suspended.add(user_id);
    },
  };
}