summaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/src/meshbay_hub/static/profile-page.js
blob: 7e355e754a9cd1eac6500523310681276881b4b3 (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
import {
  html, useState, useEffect, useCallback,
} from './vendor/htm-preact.js';
import { t } from './i18n.js';
import { Icon } from './icon.js';
import {
  hubFetch, HUB, session, setAuth,
  _storeBundleKey, _loadBundleKey, _storeRecoveryKey,
} from './hub-client.js';

// A sign-in lockout also refuses the two actions here that re-check the
// passphrase (the hub counts them on the same row).
function lockedText(seconds) {
  return t('login.locked', { minutes: Math.max(1, Math.ceil(seconds / 60)) });
}

async function lockedMessage(token) {
  try {
    const me = await hubFetch('/v1/users/me', { token });
    return lockedText(me.passphrase_locked_for || 60);
  } catch {
    return lockedText(60);
  }
}

export function ProfilePage({ user, onLogout }) {
  const [nodeKey, setNodeKey] = useState('');
  const [currentNodeKey, setCurrentNodeKey] = useState(null);
  const [nodeKeyStatus, setNodeKeyStatus] = useState('');
  const [nodeKeyLoading, setNodeKeyLoading] = useState(false);
  const [email, setEmail] = useState('');
  const [emailDraft, setEmailDraft] = useState('');
  const [emailEditing, setEmailEditing] = useState(false);
  const [emailSaving, setEmailSaving] = useState(false);
  const [emailStatus, setEmailStatus] = useState('');
  const [emailVerifyPending, setEmailVerifyPending] = useState(false);
  const [emailCode, setEmailCode] = useState('');
  const [emailVerifying, setEmailVerifying] = useState(false);
  const [pinCount, setPinCount] = useState(
    () => (window.MeshBayTransport?.pinnedNodeCount?.() ?? 0));
  const [delOpen, setDelOpen] = useState(false);
  const [delPass, setDelPass] = useState('');
  const [delError, setDelError] = useState('');
  const [deleting, setDeleting] = useState(false);

  const deleteAccount = useCallback(async (e) => {
    e.preventDefault();
    setDeleting(true);
    setDelError('');
    try {
      const authKey = await window.MeshBayKeys.deriveAuthKey(delPass, user.username);
      await hubFetch('/v1/users/me', {
        method: 'DELETE', token: user.token, body: { auth_key: authKey },
      });
      onLogout();
    } catch (err) {
      setDelError(err.message === 'account_locked'
        ? await lockedMessage(user.token) : err.message);
    } finally {
      setDeleting(false);
    }
  }, [delPass, user]);

  const clearPins = useCallback(() => {
    window.MeshBayTransport?.clearNodePin?.();
    setPinCount(window.MeshBayTransport?.pinnedNodeCount?.() ?? 0);
  }, []);

  // ── Passphrase change (docs/auth-confirm.md §3) ─────────────────────────
  const [cpOpen, setCpOpen] = useState(false);
  const [cpOld, setCpOld] = useState('');
  const [cpNew, setCpNew] = useState('');
  const [cpNew2, setCpNew2] = useState('');
  const [cpPhase, setCpPhase] = useState('form');   // form | confirm | working | done
  const [cpEstimate, setCpEstimate] = useState(null);
  const [cpProgress, setCpProgress] = useState(null);
  const [cpResult, setCpResult] = useState(null);
  const [cpError, setCpError] = useState('');

  const cpReset = useCallback(() => {
    setCpOpen(false); setCpPhase('form');
    setCpOld(''); setCpNew(''); setCpNew2('');
    setCpEstimate(null); setCpProgress(null); setCpResult(null); setCpError('');
  }, []);

  const _label = (g) => (g.owner_username ? `${g.name}@${g.owner_username}` : g.name);

  const cpBeginConfirm = useCallback(async (e) => {
    e.preventDefault();
    setCpError('');
    if (cpNew.length < 12) { setCpError(t('settings.pw_too_short')); return; }
    if (cpNew !== cpNew2) { setCpError(t('settings.pw_mismatch')); return; }
    if (cpNew === cpOld) { setCpError(t('settings.pw_same')); return; }
    try {
      // The next step re-wraps every node's bundle before the hub is asked to
      // accept the new passphrase. Started during a lockout, the nodes would
      // take the new one and the hub would refuse it — so ask first.
      const me = await hubFetch('/v1/users/me', { token: user.token });
      if (me.passphrase_locked_for > 0) {
        setCpError(lockedText(me.passphrase_locked_for));
        return;
      }
      const mine = await hubFetch('/v1/groups/mine', { token: user.token });
      const groups = mine.groups || [];
      setCpEstimate({
        reachable: groups.filter((g) => g.node_online).map(_label),
        unreachable: groups.filter((g) => !g.node_online).map(_label),
      });
      setCpPhase('confirm');
    } catch (err) {
      setCpError(err.message);
    }
  }, [cpOld, cpNew, cpNew2, user.token]);

  const cpConfirm = useCallback(async () => {
    setCpPhase('working');
    setCpError('');
    setCpProgress({ done: 0, total: 0 });
    try {
      // Re-wrap every reachable node's identity bundle first — if this cannot
      // run at all the account is left untouched.
      const result = await window.MeshBayTransport.rewrapAllNodes({
        hubUrl: HUB, token: user.token,
        username: user.username, userId: user.userId,
        oldPassphrase: cpOld, newPassphrase: cpNew,
        onProgress: setCpProgress,
      });

      const oldAuthKey = await window.MeshBayKeys.deriveAuthKey(cpOld, user.username);
      const newAuthKey = await window.MeshBayKeys.deriveAuthKey(cpNew, user.username);
      const resp = await hubFetch('/v1/users/password', {
        method: 'POST', token: user.token,
        body: { old_auth_key: oldAuthKey, new_auth_key: newAuthKey },
      });

      // Keep this tab signed in with the fresh pair, and move the session's
      // bundle key forward so the next node connection opens the new bundles.
      setAuth({ ...user, token: resp.access_token, refreshToken: resp.refresh_token });
      session.bundleKey = result.newBundleKey;
      _storeBundleKey(result.newBundleKey);

      setCpResult(result);
      setCpPhase('done');
    } catch (err) {
      const msg = err.message === 'account_locked'
        ? await lockedMessage(user.token)
        : /403|does not match/i.test(err.message)
          ? t('settings.pw_wrong_current') : err.message;
      setCpError(msg);
      setCpPhase('confirm');
    }
  }, [cpOld, cpNew, user]);

  // ── Recovery key backfill (docs/auth-confirm.md §4.3) ───────────────────
  // Enter the recovery key once per browser to add a recovery-wrapped copy of
  // your identity to every group — covers groups joined before the key was
  // loaded here.
  const [rkOpen, setRkOpen] = useState(false);
  const [rkInput, setRkInput] = useState('');
  const [rkPhase, setRkPhase] = useState('form');   // form | working | done
  const [rkProgress, setRkProgress] = useState(null);
  const [rkResult, setRkResult] = useState(null);
  const [rkError, setRkError] = useState('');
  const rkLoaded = !!session.recoveryKey;

  const rkReset = useCallback(() => {
    setRkOpen(false); setRkPhase('form'); setRkInput('');
    setRkProgress(null); setRkResult(null); setRkError('');
  }, []);

  const rkBackfill = useCallback(async (e) => {
    e.preventDefault();
    const mnemonic = rkInput.trim();
    if (!mnemonic || !window.MeshBayKeys) return;
    setRkError('');
    if (!session.bundleKey) session.bundleKey = await _loadBundleKey();
    if (!session.bundleKey) { setRkError(t('settings.recovery_need_relogin')); return; }
    setRkPhase('working');
    setRkProgress(null);
    try {
      // Derives the key (and validates the mnemonic — a bad one throws here).
      const key = await window.MeshBayKeys.deriveRecoveryKey(mnemonic, user.username);
      session.recoveryKey = key;
      await _storeRecoveryKey(key);
      const r = await window.MeshBayTransport.rewrapAllNodes({
        hubUrl: HUB, token: user.token,
        username: user.username, userId: user.userId,
        bundleKey: session.bundleKey,   // keep the current passphrase key
        recoveryKey: mnemonic,
        onProgress: setRkProgress,
      });
      setRkResult(r);
      setRkPhase('done');
      setRkInput('');
    } catch (err) {
      setRkError(err.message);
      setRkPhase('form');
    }
  }, [rkInput, user]);

  useEffect(() => {
    hubFetch('/v1/users/me', { token: user.token })
      .then(data => {
        if (data.email) { setEmail(data.email); setEmailDraft(data.email); }
      })
      .catch(() => {});
    hubFetch(`/v1/users/${user.username}/pubkeys`, { token: user.token })
      .then(data => {
        if (data.pk_node_ed25519) setCurrentNodeKey(data.pk_node_ed25519);
      })
      .catch(() => {});
  }, [user.username, user.token]);

  const saveEmail = useCallback(async () => {
    const val = emailDraft.trim();
    if (!val || val === email) { setEmailEditing(false); return; }
    setEmailSaving(true);
    setEmailStatus('');
    try {
      const resp = await hubFetch('/v1/users/me', {
        method: 'PATCH', token: user.token, body: { email: val },
      });
      if (resp.email_verification_required) {
        setEmailVerifyPending(true);
        setEmailStatus(t('settings.email_code_sent'));
      } else {
        setEmail(val);
        setEmailEditing(false);
        setEmailStatus(t('settings.email_saved'));
        setTimeout(() => setEmailStatus(''), 3000);
      }
    } catch (e) {
      setEmailStatus(e.message);
    } finally {
      setEmailSaving(false);
    }
  }, [emailDraft, email, user.token]);

  const verifyEmailChange = useCallback(async () => {
    if (!emailCode.trim()) return;
    setEmailVerifying(true);
    setEmailStatus('');
    try {
      const resp = await hubFetch('/v1/users/verify-email-change', {
        method: 'POST', token: user.token, body: { code: emailCode.trim() },
      });
      setEmail(resp.email || emailDraft.trim());
      setEmailEditing(false);
      setEmailVerifyPending(false);
      setEmailCode('');
      setEmailStatus(t('settings.email_verified'));
      setTimeout(() => setEmailStatus(''), 3000);
    } catch (e) {
      setEmailStatus(e.message);
    } finally {
      setEmailVerifying(false);
    }
  }, [emailCode, emailDraft, user.token]);

  const submitNodeKey = useCallback(async () => {
    const key = nodeKey.trim();
    if (!key) return;
    setNodeKeyLoading(true);
    setNodeKeyStatus('');
    try {
      await hubFetch('/v1/users/me/node_key', {
        method: 'PUT', token: user.token,
        body: { pk_node_ed25519: key },
      });
      setCurrentNodeKey(key);
      setNodeKey('');
      setNodeKeyStatus(t('settings.node_key_success'));
    } catch (e) {
      setNodeKeyStatus(e.message);
    } finally {
      setNodeKeyLoading(false);
    }
  }, [nodeKey, user.token]);

  return html`
    <div>
      <h2>${t('profile.title')}</h2>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.profile')}</h3>
        <div class="settings-row">
          <span class="settings-label">${t('settings.username')}</span>
          <span class="settings-value">${user.username}</span>
        </div>
        <div class="settings-row">
          <span class="settings-label">${t('settings.email')}</span>
          ${emailEditing
            ? html`<span style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
                <input type="email" value=${emailDraft}
                  onInput=${e => setEmailDraft(e.target.value)}
                  onKeyDown=${e => e.key === 'Enter' && saveEmail()}
                  disabled=${emailVerifyPending}
                  style="font-size:0.9em;padding:4px 8px;border:1px solid var(--border);border-radius:4px" />
                ${!emailVerifyPending && html`
                  <button class="admin-btn" onClick=${saveEmail}
                    disabled=${emailSaving}>${t('settings.email_save')}</button>
                  <button class="btn-secondary" onClick=${() => {
                    setEmailEditing(false); setEmailDraft(email);
                  }}>${t('settings.cancel')}</button>
                `}
              </span>`
            : html`<span style="display:flex;gap:8px;align-items:center">
                <span class="settings-value">${email || '—'}</span>
                <button class="link-btn" onClick=${() => setEmailEditing(true)}>
                  <${Icon} name="pencil" /></button>
              </span>`
          }
        </div>
        ${emailVerifyPending && html`
          <div style="display:flex;gap:8px;align-items:center;margin-top:8px">
            <input type="text" placeholder="${t('settings.email_code_placeholder')}"
              value=${emailCode} onInput=${e => setEmailCode(e.target.value)}
              onKeyDown=${e => e.key === 'Enter' && verifyEmailChange()}
              inputmode="numeric" maxlength="6"
              style="width:120px;text-align:center;font-size:1.1em;letter-spacing:0.2em" />
            <button class="admin-btn" onClick=${verifyEmailChange}
              disabled=${emailVerifying}>
              ${emailVerifying ? t('settings.email_verifying') : t('settings.email_verify_btn')}
            </button>
            <button class="btn-secondary" onClick=${() => {
              setEmailVerifyPending(false); setEmailEditing(false);
              setEmailDraft(email); setEmailCode(''); setEmailStatus('');
            }}>${t('settings.cancel')}</button>
          </div>
        `}
        ${emailStatus && html`<p class="settings-hint" style="margin-top:4px">${emailStatus}</p>`}
      </div>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.node_key')}</h3>
        <p style="font-size:0.85em;color:var(--text-dim);margin-bottom:8px">${t('settings.node_key_desc')}</p>
        ${currentNodeKey && html`
          <div class="settings-row" style="margin-top:8px">
            <span class="settings-label">${t('settings.node_key_current')}</span>
            <code class="settings-value" style="font-size:0.8em;word-break:break-all">${currentNodeKey}</code>
          </div>
        `}
        <div style="display:flex;gap:8px;margin-top:10px;align-items:center">
          <input type="text" class="admin-search" style="flex:1;font-family:monospace;font-size:0.85em"
            placeholder=${t('settings.node_key_placeholder')}
            value=${nodeKey} onInput=${e => setNodeKey(e.target.value)}
            onKeyDown=${e => e.key === 'Enter' && submitNodeKey()} />
          <button class="admin-btn" onClick=${submitNodeKey}
            disabled=${nodeKeyLoading || !nodeKey.trim()}>
            ${t('settings.node_key_submit')}
          </button>
        </div>
        ${nodeKeyStatus && html`
          <p style="margin-top:6px;font-size:0.85em;color:${nodeKeyStatus === t('settings.node_key_success') ? 'var(--success)' : 'var(--error)'}">
            ${nodeKeyStatus}
          </p>
        `}
      </div>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.node_pins')}</h3>
        <p class="settings-hint">${t('settings.node_pins_hint')}</p>
        <div class="settings-row">
          <span class="settings-label">${t('settings.node_pins_count', { n: pinCount })}</span>
          <button class="btn-secondary" onClick=${clearPins} disabled=${pinCount === 0}>
            ${t('settings.node_pins_clear')}
          </button>
        </div>
      </div>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.passphrase')}</h3>
        <p class="settings-hint">${t('settings.passphrase_hint')}</p>
        ${!cpOpen && html`
          <button class="admin-btn" onClick=${() => setCpOpen(true)}>
            ${t('settings.passphrase_change')}
          </button>`}

        ${cpOpen && cpPhase === 'form' && html`
          <form onSubmit=${cpBeginConfirm} style="display:flex;flex-direction:column;gap:8px;max-width:340px">
            <input type="password" autocomplete="current-password"
              placeholder=${t('settings.passphrase_current')}
              value=${cpOld} onInput=${e => setCpOld(e.target.value)} required />
            <input type="password" autocomplete="new-password"
              placeholder=${t('settings.passphrase_new')}
              value=${cpNew} onInput=${e => setCpNew(e.target.value)} required />
            <input type="password" autocomplete="new-password"
              placeholder=${t('settings.passphrase_new_repeat')}
              value=${cpNew2} onInput=${e => setCpNew2(e.target.value)} required />
            ${cpError && html`<p class="error-msg">${cpError}</p>`}
            <div style="display:flex;gap:8px">
              <button class="admin-btn" type="submit">${t('settings.continue')}</button>
              <button class="btn-secondary" type="button" onClick=${cpReset}>
                ${t('settings.cancel')}
              </button>
            </div>
          </form>`}

        ${cpOpen && cpPhase === 'confirm' && cpEstimate && html`
          <div style="max-width:420px">
            <p class="settings-hint">${t('settings.passphrase_confirm_intro')}</p>
            ${cpEstimate.reachable.length > 0 && html`
              <p style="margin:8px 0 2px"><strong>${t('settings.passphrase_reachable')}</strong></p>
              <ul style="margin:0 0 8px 18px">
                ${cpEstimate.reachable.map(n => html`<li>${n}</li>`)}
              </ul>`}
            ${cpEstimate.unreachable.length > 0 && html`
              <p style="margin:8px 0 2px"><strong>${t('settings.passphrase_unreachable')}</strong></p>
              <ul style="margin:0 0 8px 18px">
                ${cpEstimate.unreachable.map(n => html`<li>${n}</li>`)}
              </ul>`}
            <p class="settings-hint">${t('settings.passphrase_fallback_note')}</p>
            ${cpError && html`<p class="error-msg">${cpError}</p>`}
            <div style="display:flex;gap:8px;margin-top:8px">
              <button class="btn-danger" onClick=${cpConfirm}>
                ${t('settings.passphrase_confirm_btn')}
              </button>
              <button class="btn-secondary" onClick=${cpReset}>${t('settings.cancel')}</button>
            </div>
          </div>`}

        ${cpOpen && cpPhase === 'working' && html`
          <p class="settings-hint">
            ${t('settings.passphrase_working')}
            ${cpProgress && cpProgress.total ? ` (${cpProgress.done}/${cpProgress.total})` : ''}
          </p>`}

        ${cpOpen && cpPhase === 'done' && cpResult && html`
          <div style="max-width:420px">
            <p style="color:var(--success)">${t('settings.passphrase_done')}</p>
            ${(cpResult.unreachable.length > 0 || cpResult.failed.length > 0) && html`
              <p class="settings-hint" style="margin-top:8px">
                ${t('settings.passphrase_needs_operator')}
              </p>
              <ul style="margin:0 0 8px 18px">
                ${cpResult.unreachable.concat(cpResult.failed).map(g =>
                  html`<li>${g.name}${g.reason ? ` — ${g.reason}` : ''}</li>`)}
              </ul>`}
            <button class="admin-btn" onClick=${cpReset}>${t('settings.done')}</button>
          </div>`}
      </div>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.recovery')}</h3>
        <p class="settings-hint">${t('settings.recovery_hint')}</p>
        ${rkLoaded && rkPhase !== 'done' && html`
          <p class="settings-hint" style="color:var(--success)">${t('settings.recovery_loaded')}</p>`}

        ${!rkOpen && html`
          <button class="admin-btn" onClick=${() => setRkOpen(true)}>
            ${t('settings.recovery_open')}
          </button>`}

        ${rkOpen && rkPhase === 'form' && html`
          <form onSubmit=${rkBackfill} style="display:flex;flex-direction:column;gap:8px;max-width:360px">
            <textarea placeholder=${t('settings.recovery_input_ph')}
              value=${rkInput} onInput=${e => setRkInput(e.target.value)} rows="2"
              style="font-family:monospace;font-size:0.9em;letter-spacing:0.08em;resize:vertical"></textarea>
            ${rkError && html`<p class="error-msg">${rkError}</p>`}
            <div style="display:flex;gap:8px">
              <button class="admin-btn" type="submit">${t('settings.recovery_submit')}</button>
              <button class="btn-secondary" type="button" onClick=${rkReset}>
                ${t('settings.cancel')}
              </button>
            </div>
          </form>`}

        ${rkOpen && rkPhase === 'working' && html`
          <p class="settings-hint">
            ${t('settings.recovery_working')}
            ${rkProgress && rkProgress.total ? ` (${rkProgress.done}/${rkProgress.total})` : ''}
          </p>`}

        ${rkOpen && rkPhase === 'done' && rkResult && html`
          <div style="max-width:420px">
            <p style="color:var(--success)">${t('settings.recovery_done')}</p>
            ${(rkResult.unreachable.length > 0 || rkResult.failed.length > 0) && html`
              <p class="settings-hint" style="margin-top:8px">${t('settings.recovery_partial')}</p>
              <ul style="margin:0 0 8px 18px">
                ${rkResult.unreachable.concat(rkResult.failed).map(g =>
                  html`<li>${g.name}${g.reason ? ` — ${g.reason}` : ''}</li>`)}
              </ul>`}
            <button class="admin-btn" onClick=${rkReset}>${t('settings.done')}</button>
          </div>`}
      </div>

      <div class="settings-section">
        <h3 class="settings-heading">${t('settings.danger')}</h3>
        <p class="settings-hint">${t('settings.delete_hint')}</p>
        ${delError && html`<p class="error-msg">${delError}</p>`}
        ${!delOpen
          ? html`<button class="btn-danger" onClick=${() => setDelOpen(true)}>
              ${t('settings.delete_account')}
            </button>`
          : html`
            <form onSubmit=${deleteAccount}>
              <p class="settings-hint">${t('settings.delete_confirm')}</p>
              <div style="display:flex;gap:8px;margin-top:8px">
                <input type="password" placeholder=${t('login.password')}
                  autocomplete="current-password"
                  value=${delPass} onInput=${e => setDelPass(e.target.value)} required />
                <button class="btn-danger" type="submit" disabled=${deleting}>
                  ${deleting ? '…' : t('settings.delete_confirm_btn')}
                </button>
                <button class="btn-secondary" type="button"
                  onClick=${() => { setDelOpen(false); setDelPass(''); setDelError(''); }}>
                  ${t('settings.cancel')}
                </button>
              </div>
            </form>
          `}
      </div>

    </div>
  `;
}