aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/auth-page.js
blob: 9ded87b5b3b7521792fdf6c012a1e1e8ababf8f6 (plain) (blame)
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
import {
  html, useState, useEffect, useRef, useCallback,
} from './vendor/htm-preact.js';
import { t } from './i18n.js';
import {
  hubFetch, navigate, session, HUB, loadAuth, _storeRecoveryKey,
} from './hub-client.js';
import * as platform from './platform.js';
import { Icon } from './icon.js';

const PASSWORD_MIN_BITS = 60;
const PASSWORD_MIN_LEN = 12;

// ── reCAPTCHA v2 helper ──────────────────────────────────────────────────────

let _captchaSiteKey = null;
let _captchaKeyFetched = false;

async function fetchCaptchaSiteKey() {
  if (_captchaKeyFetched) return _captchaSiteKey;
  try {
    const info = await hubFetch('/v1/hub/info');
    _captchaSiteKey = info.captcha_site_key || null;
  } catch { _captchaSiteKey = null; }
  _captchaKeyFetched = true;
  return _captchaSiteKey;
}

function loadRecaptchaScript() {
  if (document.getElementById('recaptcha-script')) return;
  const s = document.createElement('script');
  s.id = 'recaptcha-script';
  s.src = 'https://www.google.com/recaptcha/api.js?render=explicit';
  s.async = true;
  s.defer = true;
  document.head.appendChild(s);
}

function useCaptcha() {
  const [siteKey, setSiteKey] = useState(_captchaSiteKey);
  const [token, setToken] = useState(null);
  const containerRef = useRef(null);
  const widgetId = useRef(null);

  useEffect(() => {
    fetchCaptchaSiteKey().then(k => {
      if (k) { setSiteKey(k); loadRecaptchaScript(); }
    });
  }, []);

  useEffect(() => {
    if (!siteKey || !containerRef.current) return;
    const poll = setInterval(() => {
      if (window.grecaptcha && window.grecaptcha.render && widgetId.current === null) {
        clearInterval(poll);
        widgetId.current = window.grecaptcha.render(containerRef.current, {
          sitekey: siteKey,
          callback: (tk) => setToken(tk),
          'expired-callback': () => setToken(null),
          theme: document.documentElement.getAttribute('data-theme') === 'dark'
            ? 'dark' : 'light',
        });
      }
    }, 100);
    return () => clearInterval(poll);
  }, [siteKey]);

  const reset = useCallback(() => {
    if (widgetId.current !== null && window.grecaptcha) {
      window.grecaptcha.reset(widgetId.current);
      setToken(null);
    }
  }, []);

  const widget = siteKey
    ? html`<div ref=${containerRef}
                style="display:flex;justify-content:center;margin:12px 0"></div>`
    : null;

  return { token, widget, reset, enabled: !!siteKey };
}

function passwordBits(pw) {
  if (!pw) return 0;
  let pool = 0;
  if (/[a-z]/.test(pw)) pool += 26;
  if (/[A-Z]/.test(pw)) pool += 26;
  if (/[0-9]/.test(pw)) pool += 10;
  if (/[^A-Za-z0-9]/.test(pw)) pool += 32;
  let bits = pw.length * Math.log2(pool || 1);

  const unique = new Set(pw).size;
  if (unique < pw.length / 2) bits *= 0.6;
  if (/^[0-9]+$/.test(pw)) bits *= 0.5;
  if (/(password|motdepasse|azerty|qwerty|123456|meshbay)/i.test(pw)) bits *= 0.3;
  return Math.round(bits);
}

export function FirstRunPage({ onSet }) {
  const [url, setUrl] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    setBusy(true);
    try {
      await window.meshbay.setHubBase(url.trim());
      onSet();
    } catch (err) {
      setError(platform.bridgeMessage(err));
      setBusy(false);
    }
  };

  return html`
    <div class="page-center">
      <div class="card login-card">
        <h2>${t('firstrun.title')}</h2>
        <p class="settings-hint" style="margin-bottom:16px">${t('firstrun.hint')}</p>
        <form onSubmit=${submit}>
          <input type="text" placeholder="https://meshbay.org" required
            autofocus value=${url}
            onInput=${e => setUrl(e.target.value)} />
          <button type="submit" disabled=${busy}>
            ${busy ? t('firstrun.checking') : t('firstrun.btn')}
          </button>
        </form>
        ${error && html`<div class="error-msg">${error}</div>`}
        <p class="settings-hint" style="margin-top:16px">${t('firstrun.note')}</p>
      </div>
    </div>
  `;
}

export function LoginPage({ onLogin }) {
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const [loading, setLoading] = useState(false);

  const [pendingVerif, setPendingVerif] = useState(false);

  const onSubmit = async (e) => {
    e.preventDefault();
    const name = username.trim();
    if (!name || !password) return;
    setError('');
    setPendingVerif(false);
    setLoading(true);
    try {
      // Trimmed to match the hub's stored username and every client-side key
      // derivation (auth_key, bundle_key, recovery_key all fold the username in).
      await onLogin(name, password);
      navigate('/');
    } catch (err) {
      if (err.message === 'email_verification_required') {
        setPendingVerif(true);
      } else {
        setError(err.message);
      }
    } finally {
      setLoading(false);
    }
  };

  return html`
    <div class="page-center">
      <div class="welcome">
      <div class="card login-card">
        <h2>${t('login.title')}</h2>
        <form onSubmit=${onSubmit}>
          <input type="text" placeholder="${t('login.username')}" value=${username}
                 onInput=${e => setUsername(e.target.value)}
                 autocomplete="username" required autofocus />
          <input type="password" placeholder="${t('login.password')}" value=${password}
                 onInput=${e => setPassword(e.target.value)}
                 autocomplete="current-password" required />
          ${error && html`<div class="error-msg">${error}</div>`}
          ${pendingVerif && html`
            <div class="error-msg" style="background:var(--bg-secondary);border-left:3px solid var(--yellow, #f59e0b)">
              <p>${t('login.pending_verification')}</p>
            </div>
          `}
          <button type="submit" disabled=${loading}>
            ${loading ? t('login.loading') : t('login.submit')}
          </button>
        </form>
        <div class="login-footer">
          ${t('login.no_account')} <a href="#/register">${t('login.register_link')}</a>
        </div>
        <div class="login-footer">
          <a href="#/reset">${t('login.forgot')}</a>
        </div>
      </div>
      ${!platform.isNative && html`<${WelcomePitch} />`}
      </div>
    </div>
  `;
}

// What MeshBay is, beside the sign-in form. Browser only: inside the desktop
// application the reader has already downloaded it, and the links point at the
// project's own site rather than at whichever hub the application is set to.
//
// Every sentence here is held to MESHBAY_DESIGN.md §2.3. "Data never transits
// the hub" is a claim the design makes; "the hub cannot read anything" is one it
// forbids (T3), which is why the list below says what never *reaches* the hub
// and stops there. "End-to-end" means device to node, as §2.3 defines it.
const WELCOME_APPS = [
  ['chat', 'welcome.app_chat'], ['image', 'welcome.app_photos'],
  ['video', 'welcome.app_media'], ['play', 'welcome.app_video'],
  ['music', 'welcome.app_music'],
];
const WELCOME_USES = [
  ['chat', 'welcome.use_chat'], ['image', 'welcome.use_photos'],
  ['cast', 'welcome.use_media'], ['pencil', 'welcome.use_apps'],
];
const WELCOME_NEVER = ['welcome.never_transit', 'welcome.never_stored', 'welcome.never_e2e'];

function WelcomePitch() {
  return html`
    <section class="welcome-pitch" aria-labelledby="welcome-title">
      <h1 id="welcome-title" class="welcome-title">${t('welcome.title')}</h1>
      <p class="welcome-lead">${t('welcome.lead')}</p>
      <ul class="welcome-apps">
        ${WELCOME_APPS.map(([icon, key]) => html`
          <li key=${key}><${Icon} name=${icon} />${t(key)}</li>`)}
      </ul>
      <p>${t('welcome.groups')}</p>
      <p class="welcome-e2e"><${Icon} name="lock" /><span>${t('welcome.e2e')}</span></p>

      <h2 class="welcome-h">${t('welcome.uses_title')}</h2>
      <ul class="welcome-uses">
        ${WELCOME_USES.map(([icon, key]) => html`
          <li key=${key}><span class="welcome-use-icon"><${Icon} name=${icon} /></span>
            <span>${t(key)}</span></li>`)}
      </ul>

      <div class="welcome-hub">
        <h2 class="welcome-h">${t('welcome.hub_title')}</h2>
        <p>${t('welcome.hub_body')}</p>
        <p class="welcome-hub-never">${t('welcome.hub_never')}</p>
        <ul class="welcome-never">
          ${WELCOME_NEVER.map(key => html`
            <li key=${key}><${Icon} name="check" /><span>${t(key)}</span></li>`)}
        </ul>
        <p class="welcome-hub-free">${t('welcome.hub_free')}</p>
      </div>

      <div class="welcome-links">
        <a class="welcome-cta" href="https://meshbay.org/downloads/">
          <${Icon} name="download" />${t('welcome.download')}</a>
        <a class="welcome-legal" href="https://meshbay.org/legal/">${t('welcome.legal')}</a>
      </div>
    </section>
  `;
}

export function RegisterPage() {
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [error, setError] = useState('');
  const [phase, setPhase] = useState('form'); // form | recovery | verify | done
  const [loading, setLoading] = useState(false);
  const [code, setCode] = useState('');
  const [verifying, setVerifying] = useState(false);
  const [resent, setResent] = useState(false);
  const [recoveryMnemonic, setRecoveryMnemonic] = useState('');
  const [recoverySaved, setRecoverySaved] = useState(false);
  const [recoveryCopied, setRecoveryCopied] = useState(false);
  const [emailRecovery, setEmailRecovery] = useState(true);
  const captcha = useCaptcha();

  const onSubmit = async (e) => {
    e.preventDefault();
    const name = username.trim();
    if (password !== confirm) { setError(t('register.err_mismatch')); return; }
    if (password.length < PASSWORD_MIN_LEN) {
      setError(t('register.err_min_len', { n: PASSWORD_MIN_LEN })); return;
    }
    if (passwordBits(password) < PASSWORD_MIN_BITS) {
      setError(t('register.err_too_weak')); return;
    }
    setError('');
    setLoading(true);
    try {
      if (window.MeshBayKeys) {
        // The account recovery key (docs/auth-confirm.md §4.3/§4.4): generated
        // here, shown once on the next screen. When the user leaves "e-mail it"
        // checked, the mnemonic goes in the register body so the hub appends it
        // to the verification e-mail (and stores it nowhere); otherwise it is
        // screen-only. The derived key is kept in `session.recoveryKey` and
        // persisted, so groups joined later — this session or a future one —
        // still leave a recovery-wrapped copy on their node.
        const rk = window.MeshBayKeys.generateRecoveryKey();
        // `name` (trimmed), not the raw field: the hub stores the trimmed
        // username and every key derivation must fold in the same string.
        // `captcha.token` rides along — the submit button is already disabled
        // until it is set when a captcha is configured (see the form below).
        await window.MeshBayKeys.registerUser(
          name, email, password, emailRecovery ? rk.mnemonic : null,
          captcha.token);
        setRecoveryMnemonic(rk.mnemonic);
        session.recoveryKey =
          await window.MeshBayKeys.deriveRecoveryKey(rk.mnemonic, name);
        await _storeRecoveryKey(session.recoveryKey);
        setPhase('recovery');
      } else {
        await hubFetch('/v1/users/register', {
          method: 'POST',
          body: {
            username: name, email, password,
            pk_user_ed25519: '', pk_user_x25519: '',
            captcha_token: captcha.token,
          },
        });
        setPhase('verify');
      }
    } catch (err) {
      setError(err.message);
      // A reCAPTCHA token is single-use: after a failed attempt (name taken,
      // e-mail in use…) it is spent, so clear it and make the user solve a
      // fresh one before the next try. No-op when no captcha is configured.
      captcha.reset();
    } finally {
      setLoading(false);
    }
  };

  const onVerify = async (e) => {
    e.preventDefault();
    if (!code.trim()) return;
    setError('');
    setVerifying(true);
    try {
      await hubFetch('/v1/users/verify-email', {
        method: 'POST',
        body: { email, code: code.trim() },
      });
      setPhase('done');
    } catch (err) {
      setError(err.message);
    } finally {
      setVerifying(false);
    }
  };

  const onResend = async () => {
    setError('');
    setResent(false);
    try {
      await hubFetch('/v1/users/register', {
        method: 'POST',
        body: {
          username: username.trim(), email, password,
          pk_user_ed25519: '', pk_user_x25519: '',
        },
      });
      setResent(true);
    } catch (err) {
      setError(err.message);
    }
  };

  if (phase === 'done') {
    return html`
      <div class="page-center">
        <div class="card login-card">
          <h2>${t('register.verified_title')}</h2>
          <p style="text-align:center; margin-bottom:16px; color:var(--text-secondary)">
            ${t('register.verified_msg')}
          </p>
          <a href="#/login" style="display:block; text-align:center">${t('register.go_login')}</a>
        </div>
      </div>
    `;
  }

  if (phase === 'recovery') {
    const copyRecovery = async () => {
      try {
        await navigator.clipboard.writeText(recoveryMnemonic);
        setRecoveryCopied(true);
        setTimeout(() => setRecoveryCopied(false), 2000);
      } catch { /* clipboard blocked — the text is on screen to copy by hand */ }
    };
    return html`
      <div class="page-center">
        <div class="card login-card">
          <h2>${t('register.recovery_title')}</h2>
          <p style="margin-bottom:12px; color:var(--text-secondary)">
            ${t('register.recovery_intro')}
          </p>
          <code style="display:block; padding:12px; border:1px solid var(--border);
                       border-radius:6px; font-size:1.05em; letter-spacing:0.12em;
                       line-height:1.9; word-spacing:0.3em; text-align:center;
                       user-select:all; background:var(--bg-secondary, transparent)">
            ${recoveryMnemonic}
          </code>
          <button class="btn-secondary" style="margin-top:8px" onClick=${copyRecovery}>
            ${recoveryCopied ? t('register.recovery_copied') : t('register.recovery_copy')}
          </button>
          <p style="margin-top:12px; color:var(--text-secondary)">
            ${emailRecovery ? t('register.recovery_emailed') : t('register.recovery_not_emailed')}
          </p>
          <p class="error-msg" style="margin-top:8px">${t('register.recovery_warning')}</p>
          <label style="display:flex; gap:8px; align-items:flex-start; margin-top:12px">
            <input type="checkbox" checked=${recoverySaved}
                   onChange=${e => setRecoverySaved(e.target.checked)} />
            <span>${t('register.recovery_saved')}</span>
          </label>
          <button style="margin-top:12px" disabled=${!recoverySaved}
                  onClick=${() => setPhase('verify')}>
            ${t('register.recovery_continue')}
          </button>
        </div>
      </div>
    `;
  }

  if (phase === 'verify') {
    return html`
      <div class="page-center">
        <div class="card login-card">
          <h2>${t('register.success_title')}</h2>
          <p style="text-align:center; margin-bottom:16px; color:var(--text-secondary)">
            ${t('register.success_msg')}
          </p>
          <form onSubmit=${onVerify}>
            <input type="text" placeholder="${t('register.code_placeholder')}"
                   value=${code} onInput=${e => setCode(e.target.value)}
                   autocomplete="one-time-code" inputmode="numeric"
                   maxlength="6" required autofocus
                   style="text-align:center;font-size:1.4em;letter-spacing:0.3em" />
            ${error && html`<div class="error-msg">${error}</div>`}
            <button type="submit" disabled=${verifying}>
              ${verifying ? t('register.verifying') : t('register.verify_btn')}
            </button>
          </form>
          <div class="login-footer">
            <button class="link-btn" onClick=${onResend}>${t('register.resend')}</button>
            ${resent && html`<span style="color:var(--success);margin-left:8px">
              ${t('register.resend_sent')}</span>`}
          </div>
        </div>
      </div>
    `;
  }

  return html`
    <div class="page-center">
      <div class="card login-card">
        <h2>${t('register.title')}</h2>
        <form onSubmit=${onSubmit}>
          <input type="text" placeholder="${t('register.username')}" value=${username}
                 onInput=${e => setUsername(e.target.value)}
                 autocomplete="username" required />
          <input type="email" placeholder="${t('register.email')}" value=${email}
                 onInput=${e => setEmail(e.target.value)}
                 autocomplete="email" required />
          <input type="password" placeholder="${t('register.password')}" value=${password}
                 onInput=${e => setPassword(e.target.value)}
                 autocomplete="new-password" required minlength="8" />
          <div style=${`margin:-4px 0 10px;${password ? '' : 'visibility:hidden;height:0;margin:0;overflow:hidden'}`}>
            <div style="height:4px;background:var(--border);border-radius:2px;overflow:hidden">
              <div style=${`height:100%;width:${Math.min(100, passwordBits(password) / 100 * 100)}%;
                   background:${passwordBits(password) < PASSWORD_MIN_BITS ? 'var(--error)'
                     : passwordBits(password) < 80 ? 'var(--yellow, #f59e0b)' : 'var(--success)'}`}></div>
            </div>
            <p style="font-size:0.8em;color:var(--text-dim);margin-top:4px">
              ${t('register.strength', { bits: passwordBits(password) })}
            </p>
          </div>
          <input type="password" placeholder="${t('register.confirm')}" value=${confirm}
                 onInput=${e => setConfirm(e.target.value)}
                 autocomplete="new-password" required />
          <label style="display:flex; gap:8px; align-items:flex-start; margin:4px 0 2px;
                        font-size:0.88em; color:var(--text-secondary)">
            <input type="checkbox" checked=${emailRecovery}
                   onChange=${e => setEmailRecovery(e.target.checked)} />
            <span>${t('register.recovery_email_opt')}</span>
          </label>
          ${captcha.widget}
          ${error && html`<div class="error-msg">${error}</div>`}
          <button type="submit" disabled=${loading || (captcha.enabled && !captcha.token)}>
            ${loading ? t('register.loading') : t('register.submit')}
          </button>
        </form>
        <div class="login-footer">
          ${t('register.has_account')} <a href="#/login">${t('register.login_link')}</a>
        </div>
      </div>
    </div>
  `;
}


// ── Passphrase reset — Flow B (docs/auth-confirm.md §4) ─────────────────────
//
// An e-mail code restores hub login. A recovery key, if the user still has one,
// restores the per-node identities in the same step: the fan-out reads each
// node's recovery-wrapped bundle and re-wraps it under the new passphrase.
// Without a recovery key, sign-in comes back and the groups do not.
export function ResetPasswordPage({ onLogin }) {
  const [username, setUsername] = useState('');
  const [email, setEmail] = useState('');
  const [phase, setPhase] = useState('request'); // request | form | working | done | norecovery
  const [code, setCode] = useState('');
  const [recovery, setRecovery] = useState('');
  const [password, setPassword] = useState('');
  const [confirm, setConfirm] = useState('');
  const [error, setError] = useState('');
  const [busy, setBusy] = useState(false);
  const [progress, setProgress] = useState(null);
  const [result, setResult] = useState(null);
  const captcha = useCaptcha();

  const requestCode = async (e) => {
    e.preventDefault();
    if (!username.trim() || !email.trim()) return;
    setError('');
    setBusy(true);
    try {
      await hubFetch('/v1/users/password/reset-request', {
        method: 'POST',
        body: {
          username: username.trim(), email: email.trim(),
          captcha_token: captcha.token,
        },
      });
      setPhase('form');
    } catch (err) {
      setError(err.message);
    } finally {
      setBusy(false);
    }
  };

  const doReset = async (e) => {
    e.preventDefault();
    if (!window.MeshBayKeys) { setError(t('reset.err_unsupported')); return; }
    if (password.length < PASSWORD_MIN_LEN) {
      setError(t('register.err_min_len', { n: PASSWORD_MIN_LEN })); return;
    }
    if (passwordBits(password) < PASSWORD_MIN_BITS) {
      setError(t('register.err_too_weak')); return;
    }
    if (password !== confirm) { setError(t('register.err_mismatch')); return; }
    setError('');
    setBusy(true);
    let signedIn = false;
    try {
      const name = username.trim();
      const newAuthKey = await window.MeshBayKeys.deriveAuthKey(password, name);
      // Before this point a failure means the code or passphrase is wrong and
      // the account is untouched — go back to the form.
      await hubFetch('/v1/users/password/reset', {
        method: 'POST',
        body: { username: name, code: code.trim(), new_auth_key: newAuthKey },
      });
      await onLogin(name, password);   // sets session.bundleKey
      signedIn = true;

      const mnemonic = recovery.trim();
      if (!mnemonic) { setPhase('norecovery'); return; }

      session.recoveryKey =
        await window.MeshBayKeys.deriveRecoveryKey(mnemonic, name);
      await _storeRecoveryKey(session.recoveryKey);
      setPhase('working');
      const auth = loadAuth() || {};
      const r = await window.MeshBayTransport.rewrapAllNodes({
        hubUrl: HUB, token: auth.token, username: name, userId: auth.userId,
        newPassphrase: password, recoveryKey: mnemonic,
        onProgress: setProgress,
      });
      setResult(r);
      setPhase('done');
    } catch (err) {
      setError(err.message);
      // After sign-in the reset already happened and the code is spent — do not
      // send the user back to re-enter it. Land on the done screen with the
      // error shown; their groups may need the operator fallback.
      setPhase(signedIn ? 'done' : 'form');
    } finally {
      setBusy(false);
    }
  };

  if (phase === 'working') {
    return html`
      <div class="page-center"><div class="card login-card">
        <h2>${t('reset.title')}</h2>
        <p class="settings-hint">
          ${t('reset.working')}
          ${progress && progress.total ? ` (${progress.done}/${progress.total})` : ''}
        </p>
      </div></div>
    `;
  }

  if (phase === 'done' || phase === 'norecovery') {
    const stragglers = phase === 'done' && result
      ? result.unreachable.concat(result.failed) : [];
    return html`
      <div class="page-center"><div class="card login-card">
        <h2>${t('reset.title')}</h2>
        <p style="color:var(--success)">${t('reset.signin_restored')}</p>
        ${error && html`<div class="error-msg" style="margin-top:8px">${error}</div>`}
        ${phase === 'norecovery' && html`
          <p class="settings-hint" style="margin-top:8px">${t('reset.no_recovery')}</p>`}
        ${phase === 'done' && !error && stragglers.length === 0 && html`
          <p class="settings-hint" style="margin-top:8px">${t('reset.groups_restored')}</p>`}
        ${stragglers.length > 0 && html`
          <p class="settings-hint" style="margin-top:8px">${t('reset.needs_operator')}</p>
          <ul style="margin:0 0 8px 18px">
            ${stragglers.map(g => html`<li>${g.name}${g.reason ? ` — ${g.reason}` : ''}</li>`)}
          </ul>`}
        <button style="margin-top:12px" onClick=${() => navigate('/')}>
          ${t('reset.go_app')}
        </button>
      </div></div>
    `;
  }

  return html`
    <div class="page-center"><div class="card login-card">
      <h2>${t('reset.title')}</h2>
      ${phase === 'request' && html`
        <p style="margin-bottom:12px; color:var(--text-secondary)">${t('reset.request_intro')}</p>
        <form onSubmit=${requestCode}>
          <input type="text" placeholder="${t('login.username')}" value=${username}
                 onInput=${e => setUsername(e.target.value)}
                 autocomplete="username" required autofocus />
          <input type="email" placeholder="${t('register.email')}" value=${email}
                 onInput=${e => setEmail(e.target.value)}
                 autocomplete="email" required />
          ${captcha.widget}
          ${error && html`<div class="error-msg">${error}</div>`}
          <button type="submit" disabled=${busy || (captcha.enabled && !captcha.token)}>
            ${t('reset.send_code')}</button>
        </form>`}

      ${phase === 'form' && html`
        <p style="margin-bottom:12px; color:var(--text-secondary)">${t('reset.form_intro')}</p>
        <form onSubmit=${doReset}>
          <input type="text" placeholder="${t('reset.code')}" value=${code}
                 onInput=${e => setCode(e.target.value)}
                 inputmode="numeric" maxlength="6" required autofocus
                 style="text-align:center;font-size:1.3em;letter-spacing:0.3em" />
          <textarea placeholder="${t('reset.recovery_key')}" value=${recovery}
                    onInput=${e => setRecovery(e.target.value)} rows="2"
                    style="width:100%;font-family:monospace;font-size:0.9em;
                           letter-spacing:0.08em;resize:vertical"></textarea>
          <p style="font-size:0.8em;color:var(--text-dim);margin:-4px 0 8px">
            ${t('reset.recovery_key_hint')}
          </p>
          <input type="password" placeholder="${t('reset.new_pass')}" value=${password}
                 onInput=${e => setPassword(e.target.value)}
                 autocomplete="new-password" required />
          <input type="password" placeholder="${t('reset.new_pass_repeat')}" value=${confirm}
                 onInput=${e => setConfirm(e.target.value)}
                 autocomplete="new-password" required />
          ${error && html`<div class="error-msg">${error}</div>`}
          <button type="submit" disabled=${busy}>${t('reset.submit')}</button>
        </form>`}

      <div class="login-footer">
        <a href="#/login">${t('reset.back_to_login')}</a>
      </div>
    </div></div>
  `;
}