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
|
import {
html, useState,
} 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';
const PASSWORD_MIN_BITS = 60;
const PASSWORD_MIN_LEN = 12;
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="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>
</div>
`;
}
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 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.
await window.MeshBayKeys.registerUser(
name, email, password, emailRecovery ? rk.mnemonic : null);
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: '' },
});
setPhase('verify');
}
} catch (err) {
setError(err.message);
} 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" />
${password && html`
<div style="margin:-4px 0 10px">
<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>
${error && html`<div class="error-msg">${error}</div>`}
<button type="submit" disabled=${loading}>
${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 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() },
});
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 />
${error && html`<div class="error-msg">${error}</div>`}
<button type="submit" disabled=${busy}>${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>
`;
}
|