Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Sign-in: a name and password next to passkeys where the instance offers it, with admin reset codes (#118)

Duarte Santos046c3de79869
diff --git a/frontend/src/components/PasswordAuth.jsx b/frontend/src/components/PasswordAuth.jsx
new file mode 100644
index 000000000..7f736cdbc
--- /dev/null
+++ b/frontend/src/components/PasswordAuth.jsx
@@ -0,0 +1,276 @@
+// Name-and-password sign-in next to passkeys (#118), on an instance that offers it
+// (GET /api/config → `password_login`). Everything a password needs on screen lives here:
+// signing in, redeeming the one-time code an admin hands out, creating a profile with a
+// password, and the Settings row that sets, changes or removes one. Passkeys stay the default
+// wherever this appears; the rules themselves are the server's (api/password.js and the
+// password block in api/server.js), this only words them.
+import { useEffect, useRef, useState } from 'react'
+import { useStore, hasData } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
+import { t } from '../lib/i18n.js'
+import { dateLocale } from '../lib/i18n-core.js'
+import { api, webauthnOK, passkeyAssertion, passwordLogin, passwordRegister, passwordResetRedeem } from '../lib/api.js'
+import { askAddDeviceData, confirmSheet } from '../sheets.jsx'
+import { Row, Button } from './ui.jsx'
+
+// The server's floor (api/password.js MIN_LENGTH), checked here first so the common mistake is
+// answered without a round trip. The server still decides.
+export const MIN_PASSWORD = 10
+export const passwordOn = config => !!config?.password_login
+
+const ui = () => useUI.getState()
+const toast = m => ui().toast(m)
+const length = s => [...String(s || '')].length
+const errStyle = { color: 'var(--red)', marginTop: 10 }
+
+// "in 5 minutes" in the UI language, for how long a pause (429, Retry-After) still lasts.
+function fmtIn(sec) {
+ const [n, unit] = sec < 60 ? [Math.max(1, Math.round(sec)), 'second'] : sec < 3600 ? [Math.ceil(sec / 60), 'minute'] : [Math.ceil(sec / 3600), 'hour']
+ try { return new Intl.RelativeTimeFormat(dateLocale(), { numeric: 'always' }).format(n, unit) }
+ catch { return n + ' ' + unit }
+}
+
+// The server's answer in the UI language. Every password route sends a stable `code` beside its
+// English message (api/openapi.yaml, Error.code); an answer without one is shown as it came.
+export function passwordError(e) {
+ const code = e?.data?.code
+ if (e?.status === 429 || code === 'locked') return t('Too many attempts — try again {0}.', fmtIn(e?.data?.retryAfter || 60))
+ switch (code) {
+ case 'bad-credentials': return t('Wrong name or password.')
+ case 'too-short': return t('Use at least {0} characters.', MIN_PASSWORD)
+ case 'too-long': return t('That password is too long.')
+ case 'too-common': return t('That password is too easy to guess — try a longer one, or a few unrelated words.')
+ case 'name-taken': return t('Another profile already signs in with this name.')
+ case 'invite': return t('That invite code is not valid.')
+ case 'current-required': case 'current-wrong': return t('Your current password is not right.')
+ case 'passkey': case 'passkey-required': return t('Your passkey could not be confirmed.')
+ case 'last-way-in': return t('This password is the only way into your profile, so it cannot be removed.')
+ case 'reset-invalid': return t('That reset code is wrong or has expired — ask your admin for a new one.')
+ case 'disabled': return t('This account has been disabled.')
+ case 'busy': return t('The server is busy — try again in a moment.')
+ }
+ return e?.message || t('Sign-in failed')
+}
+// A passkey prompt the person closed is their answer, not an error worth a line in red.
+const dismissed = e => e?.name === 'NotAllowedError' || e?.name === 'AbortError'
+
+// Signed in: the same steps as a passkey sign-in (Login.jsx) — and the same account coming back
+// merges what this device kept for it (adoptProfile).
+async function signedIn(u, close) {
+ const st = useStore.getState()
+ st.setUser(u)
+ close()
+ await st.adoptProfile(askAddDeviceData)
+ toast(t('Welcome back, {0}', u.name))
+}
+
+const field = { autoCapitalize: 'none', autoCorrect: 'off', spellCheck: false }
+const codeStyle = { letterSpacing: '.14em', fontWeight: 600, textAlign: 'center' }
+
+/* Sign in with name and password, or — one tap away — redeem a reset code from the admin, which
+ sets a new password and signs in. `onPasskey`, when given, offers the passkey instead. The
+ inputs carry the autocomplete names password managers look for, inside a real form. */
+export function PasswordSignInSheet({ close, onPasskey }) {
+ const [mode, setMode] = useState('signin') // 'signin' | 'reset'
+ const [name, setName] = useState('')
+ const [pw, setPw] = useState('')
+ const [code, setCode] = useState('')
+ const [next, setNext] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [err, setErr] = useState(null)
+ const nameRef = useRef(null)
+ useEffect(() => { setTimeout(() => nameRef.current?.focus(), 250) }, [])
+ const reset = mode === 'reset'
+ const submit = async ev => {
+ ev.preventDefault()
+ if (busy) return
+ const n = name.trim()
+ const bad = !n ? t('Enter a name')
+ : !reset && !pw ? t('Enter your password.')
+ : reset && !code.trim() ? t('Enter the reset code.')
+ : reset && length(next) < MIN_PASSWORD ? t('Use at least {0} characters.', MIN_PASSWORD)
+ : null
+ if (bad) { setErr(bad); return }
+ setBusy(true); setErr(null)
+ try { await signedIn(reset ? await passwordResetRedeem(n, code.trim(), next) : await passwordLogin(n, pw), close) }
+ catch (e) { setErr(passwordError(e)) }
+ finally { setBusy(false) }
+ }
+ return <>
+ <h3>{reset ? t('Reset your password') : t('Sign in with password')}</h3>
+ <div className="muted small" style={{ marginBottom: 14 }}>{reset
+ ? t('Enter the code your admin gave you and choose a new password. It signs you out everywhere else.')
+ : t('Use your profile name and the password you set for it.')}</div>
+ <form onSubmit={submit} noValidate>
+ <input ref={nameRef} className="input" name="username" autoComplete="username" placeholder={t('Your name')} maxLength={40}
+ value={name} onChange={e => setName(e.target.value)} {...field} />
+ <div style={{ height: 10 }} />
+ {reset ? <>
+ <input className="input" name="reset-code" autoComplete="one-time-code" placeholder={t('Reset code')} maxLength={20}
+ value={code} onChange={e => setCode(e.target.value.toUpperCase())} {...field} style={codeStyle} />
+ <div style={{ height: 10 }} />
+ <input className="input" type="password" name="new-password" autoComplete="new-password" placeholder={t('New password')}
+ value={next} onChange={e => setNext(e.target.value)} />
+ <div className="dim small" style={{ marginTop: 6 }}>{t('At least {0} characters. A few unrelated words make a good one.', MIN_PASSWORD)}</div>
+ </> : <input className="input" type="password" name="password" autoComplete="current-password" placeholder={t('Password')}
+ value={pw} onChange={e => setPw(e.target.value)} />}
+ {err && <div className="small" role="alert" style={errStyle}>{err}</div>}
+ <div style={{ height: 12 }} />
+ <Button type="submit" variant="primary" disabled={busy}>{reset ? t('Set password & sign in') : t('Sign in')}</Button>
+ </form>
+ <div style={{ height: 8 }} />
+ <Button type="button" variant="ghost" className="dim" onClick={() => { setErr(null); setMode(reset ? 'signin' : 'reset') }}>
+ {reset ? t('Sign in with password') : t('Have a reset code from your admin?')}</Button>
+ {onPasskey && !reset && webauthnOK() && <>
+ <div style={{ height: 8 }} />
+ <Button type="button" icon="person" onClick={() => { close(); onPasskey() }}>{t('Sign in with passkey')}</Button>
+ </>}
+ </>
+}
+export const openPasswordSignIn = onPasskey => ui().openSheet(close => <PasswordSignInSheet close={close} onPasskey={onPasskey} />)
+
+/* The password half of creating a profile. Name and invite code are the caller's state, so
+ switching between passkey and password on the sign-up sheet keeps what was typed. */
+export function PasswordRegisterForm({ close, inviteOnly, name, setName, code, setCode }) {
+ const [pw, setPw] = useState('')
+ const [again, setAgain] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [err, setErr] = useState(null)
+ const submit = async ev => {
+ ev.preventDefault()
+ if (busy) return
+ const n = name.trim()
+ const bad = !n ? t('Enter a name')
+ : inviteOnly && !code.trim() ? t('An invite code is required')
+ : length(pw) < MIN_PASSWORD ? t('Use at least {0} characters.', MIN_PASSWORD)
+ : pw !== again ? t('The two passwords are not the same.')
+ : null
+ if (bad) { setErr(bad); return }
+ setBusy(true); setErr(null)
+ try {
+ const u = await passwordRegister(n, pw, code.trim())
+ const st = useStore.getState()
+ st.setUser(u); close()
+ if (hasData(useStore.getState().S)) { await st.pushState(); toast(t('Profile created — data from this device moved into it')) }
+ else { await st.pullState(); toast(t('Welcome, {0}', u.name)) }
+ } catch (e) { setErr(passwordError(e)) }
+ finally { setBusy(false) }
+ }
+ return <form onSubmit={submit} noValidate>
+ <input className="input" name="username" autoComplete="username" placeholder={t('Your name')} maxLength={40}
+ value={name} onChange={e => setName(e.target.value)} {...field} />
+ {inviteOnly && <>
+ <div style={{ height: 10 }} />
+ <input className="input" placeholder={t('Invite code')} maxLength={40} value={code}
+ onChange={e => setCode(e.target.value.toUpperCase())} style={codeStyle} />
+ <div className="dim small" style={{ marginTop: 6 }}>{t('This app is invite-only — enter the code you were given.')}</div>
+ </>}
+ <div style={{ height: 10 }} />
+ <input className="input" type="password" name="new-password" autoComplete="new-password" placeholder={t('Password')}
+ value={pw} onChange={e => setPw(e.target.value)} />
+ <div style={{ height: 10 }} />
+ <input className="input" type="password" name="new-password-again" autoComplete="new-password" placeholder={t('Repeat the password')}
+ value={again} onChange={e => setAgain(e.target.value)} />
+ <div className="dim small" style={{ marginTop: 6 }}>{t('At least {0} characters. A few unrelated words make a good one.', MIN_PASSWORD)}</div>
+ {err && <div className="small" role="alert" style={errStyle}>{err}</div>}
+ <div style={{ height: 12 }} />
+ <Button type="submit" variant="primary" disabled={busy}>{t('Create profile')}</Button>
+ </form>
+}
+
+// The same form on its own sheet — Settings, in a browser that cannot make a passkey.
+function PasswordRegisterSheet({ close }) {
+ const config = useStore(s => s.config)
+ const [name, setName] = useState('')
+ const [code, setCode] = useState('')
+ return <>
+ <h3>{t('Create your profile')}</h3>
+ <div className="muted small" style={{ marginBottom: 14 }}>{t('Pick a name and a password. You sign in with both.')}</div>
+ <PasswordRegisterForm close={close} inviteOnly={!!config?.invite_only} name={name} setName={setName} code={code} setCode={setCode} />
+ </>
+}
+export const openPasswordRegister = () => ui().openSheet(close => <PasswordRegisterSheet close={close} />)
+
+/* ------------------------------------------------------------------- Settings -------------
+ Settings → Account → Password, for a signed-in browser. A first password needs a passkey
+ ceremony right now (a session on its own could be a copied cookie); a change needs the
+ current password, or the passkey when it was forgotten. Saving signs every other device out,
+ which the sheet says before anyone taps. */
+export function PasswordRow() {
+ const [st, setSt] = useState(null) // GET /api/account/password
+ const load = () => api('/api/account/password').then(setSt).catch(() => {})
+ useEffect(() => { load() }, [])
+ if (!st) return null
+ // Nothing here could set a first password without a passkey ceremony.
+ if (!st.set && !webauthnOK()) return null
+ const blocked = !st.set && st.nameTaken
+ const subtitle = blocked ? t('Another profile already signs in with this name.')
+ : st.set ? t('Set · sign in as “{0}”', st.name)
+ : t('Not set — lets you sign in where passkeys do not work.')
+ return <Row icon="key" iconTint="var(--orange)" title={t('Password')} subtitle={subtitle} accessory={blocked ? 'none' : 'chevron'}
+ onClick={blocked ? undefined : () => ui().openSheet(close => <PasswordSheet status={st} close={close} done={load} />)} />
+}
+
+export function PasswordSheet({ status, close, done }) {
+ const [current, setCurrent] = useState('')
+ const [next, setNext] = useState('')
+ const [again, setAgain] = useState('')
+ const [busy, setBusy] = useState(false)
+ const [err, setErr] = useState(null)
+ const save = async withPasskey => {
+ if (busy) return
+ const bad = !withPasskey && !current ? t('Enter your password.')
+ : length(next) < MIN_PASSWORD ? t('Use at least {0} characters.', MIN_PASSWORD)
+ : next !== again ? t('The two passwords are not the same.')
+ : null
+ if (bad) { setErr(bad); return }
+ setBusy(true); setErr(null)
+ try {
+ const proof = withPasskey ? await passkeyAssertion() : { current }
+ await api('/api/account/password', { method: 'POST', body: JSON.stringify({ next, ...proof }) })
+ close(); done()
+ toast(t('Password saved — you are signed out everywhere else.'))
+ } catch (e) { if (!dismissed(e)) setErr(passwordError(e)) }
+ finally { setBusy(false) }
+ }
+ const remove = () => confirmSheet({
+ title: t('Remove your password?'),
+ message: t('Only your passkeys sign in to this profile afterwards.'),
+ confirmText: t('Remove'), danger: true,
+ onConfirm: () => api('/api/account/password', { method: 'DELETE' })
+ .then(() => { close(); done(); toast(t('Password removed')) })
+ .catch(e => toast(passwordError(e))),
+ })
+ return <>
+ <h3>{status.set ? t('Change password') : t('Set a password')}</h3>
+ <div className="muted small" style={{ marginBottom: 14 }}>
+ {t('Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.', status.name)}
+ </div>
+ <form onSubmit={ev => { ev.preventDefault(); save(!status.set) }} noValidate>
+ {/* Tells a password manager which account the new password belongs to. */}
+ <input type="text" name="username" autoComplete="username" value={status.name} readOnly hidden />
+ {status.set && <>
+ <input className="input" type="password" name="current-password" autoComplete="current-password" placeholder={t('Current password')}
+ value={current} onChange={e => setCurrent(e.target.value)} />
+ <div style={{ height: 10 }} />
+ </>}
+ <input className="input" type="password" name="new-password" autoComplete="new-password" placeholder={t('New password')}
+ value={next} onChange={e => setNext(e.target.value)} />
+ <div style={{ height: 10 }} />
+ <input className="input" type="password" name="new-password-again" autoComplete="new-password" placeholder={t('Repeat the password')}
+ value={again} onChange={e => setAgain(e.target.value)} />
+ <div className="dim small" style={{ marginTop: 6 }}>{t('At least {0} characters. A few unrelated words make a good one.', MIN_PASSWORD)}</div>
+ {err && <div className="small" role="alert" style={errStyle}>{err}</div>}
+ <div style={{ height: 12 }} />
+ <Button type="submit" variant="primary" disabled={busy}>{status.set ? t('Save') : t('Confirm with passkey & save')}</Button>
+ </form>
+ {status.set && webauthnOK() && <>
+ <div style={{ height: 8 }} />
+ <Button type="button" variant="ghost" className="dim" disabled={busy} onClick={() => save(true)}>{t('Forgot it? Confirm with your passkey instead')}</Button>
+ </>}
+ {status.set && status.passkeys > 0 && <>
+ <div style={{ height: 8 }} />
+ <button type="button" className="btn danger" disabled={busy} onClick={remove}>{t('Remove password')}</button>
+ </>}
+ </>
+}
diff --git a/frontend/src/components/PasswordAuth.test.jsx b/frontend/src/components/PasswordAuth.test.jsx
new file mode 100644
index 000000000..7d587ef24
--- /dev/null
+++ b/frontend/src/components/PasswordAuth.test.jsx
@@ -0,0 +1,263 @@
+// @vitest-environment happy-dom
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { passwordError, PasswordSignInSheet, PasswordRegisterForm, PasswordRow, PasswordSheet } from './PasswordAuth.jsx'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+/* Password sign-in on screen (#118): the sign-in sheet and its reset-code half, creating a profile
+ with a password, and the Settings row that sets, changes or removes one. The API is a
+ stand-in; what each form sends, and what it says back in the UI language, is the point. */
+const mocks = vi.hoisted(() => {
+ const state = { webauthn: true, hasData: false, sheets: [], answers: {}, calls: [] }
+ state.toast = vi.fn()
+ state.setUser = vi.fn()
+ state.adoptProfile = vi.fn(async () => ({}))
+ state.pushState = vi.fn(async () => {})
+ state.pullState = vi.fn(async () => {})
+ state.passwordLogin = vi.fn()
+ state.passwordRegister = vi.fn()
+ state.passwordResetRedeem = vi.fn()
+ state.passkeyAssertion = vi.fn(async () => ({ cid: 'c1', credential: { id: 'k1' } }))
+ state.confirmSheet = vi.fn()
+ state.api = vi.fn(async (path, init) => {
+ state.calls.push({ path, method: init?.method || 'GET', body: init?.body ? JSON.parse(init.body) : null })
+ const a = state.answers[(init?.method || 'GET') + ' ' + path]
+ if (a instanceof Error) throw a
+ return a ?? {}
+ })
+ state.snapshot = () => ({
+ S: {}, config: { password_login: true },
+ setUser: state.setUser, adoptProfile: state.adoptProfile, pushState: state.pushState, pullState: state.pullState,
+ })
+ return state
+})
+vi.mock('../store/useStore.js', () => {
+ const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
+ useStore.getState = mocks.snapshot
+ return { useStore, hasData: () => mocks.hasData }
+})
+vi.mock('../store/useUI.js', () => {
+ const snap = () => ({ toast: (...a) => mocks.toast(...a), openSheet: (render, opts) => { mocks.sheets.push({ render, opts }); return {} } })
+ const useUI = selector => selector ? selector(snap()) : snap()
+ useUI.getState = snap
+ return { useUI }
+})
+vi.mock('../lib/api.js', () => ({
+ api: (...a) => mocks.api(...a),
+ webauthnOK: () => mocks.webauthn,
+ passkeyAssertion: (...a) => mocks.passkeyAssertion(...a),
+ passwordLogin: (...a) => mocks.passwordLogin(...a),
+ passwordRegister: (...a) => mocks.passwordRegister(...a),
+ passwordResetRedeem: (...a) => mocks.passwordResetRedeem(...a),
+}))
+vi.mock('../sheets.jsx', () => ({ askAddDeviceData: vi.fn(), confirmSheet: (...a) => mocks.confirmSheet(...a) }))
+
+const fail = (status, data) => Object.assign(new Error(data?.error || 'HTTP ' + status), { status, data })
+
+const mounted = []
+function mount(el) {
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push({ root, host })
+ act(() => root.render(el))
+ return host
+}
+const settle = () => act(() => new Promise(r => setTimeout(r, 0)))
+function type(el, value) {
+ act(() => {
+ Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
+ el.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+}
+const byPlaceholder = (host, p) => host.querySelector(`input[placeholder="${p}"]`)
+const button = (host, text) => [...host.querySelectorAll('button')].find(b => b.textContent === text)
+const submit = async host => { act(() => { host.querySelector('form').dispatchEvent(new Event('submit', { bubbles: true, cancelable: true })) }); await settle() }
+const alertText = host => host.querySelector('[role="alert"]')?.textContent || null
+
+beforeEach(() => {
+ mocks.webauthn = true
+ mocks.hasData = false
+ mocks.sheets.length = 0
+ mocks.answers = {}
+ mocks.calls.length = 0
+ for (const f of [mocks.toast, mocks.setUser, mocks.adoptProfile, mocks.pushState, mocks.pullState, mocks.passwordLogin,
+ mocks.passwordRegister, mocks.passwordResetRedeem, mocks.passkeyAssertion, mocks.confirmSheet]) f.mockClear()
+})
+afterEach(() => { act(() => { mounted.splice(0).forEach(({ root, host }) => { root.unmount(); host.remove() }) }) })
+
+describe('passwordError', () => {
+ it('words each server code in the UI language, and a pause with how long it lasts', () => {
+ expect(passwordError(fail(401, { code: 'bad-credentials' }))).toBe('Wrong name or password.')
+ expect(passwordError(fail(400, { code: 'too-common' }))).toMatch(/too easy to guess/)
+ expect(passwordError(fail(400, { code: 'too-short' }))).toBe('Use at least 10 characters.')
+ expect(passwordError(fail(409, { code: 'last-way-in' }))).toMatch(/only way into your profile/)
+ expect(passwordError(fail(429, { code: 'locked', retryAfter: 120 }))).toBe('Too many attempts — try again in 2 minutes.')
+ expect(passwordError(fail(429, { code: 'locked', retryAfter: 30 }))).toBe('Too many attempts — try again in 30 seconds.')
+ // No code: what the server said, as it said it.
+ expect(passwordError(fail(500, { error: 'server error' }))).toBe('server error')
+ })
+})
+
+describe('PasswordSignInSheet', () => {
+ it('signs in with the name and password, then carries on like a passkey sign-in', async () => {
+ mocks.passwordLogin.mockResolvedValue({ id: 'u1', name: 'Ana' })
+ const close = vi.fn()
+ const host = mount(<PasswordSignInSheet close={close} />)
+ const name = byPlaceholder(host, 'Your name')
+ const pw = byPlaceholder(host, 'Password')
+ // What password managers look for.
+ expect(name.getAttribute('autocomplete')).toBe('username')
+ expect(pw.getAttribute('autocomplete')).toBe('current-password')
+ expect(pw.type).toBe('password')
+ type(name, ' Ana '); type(pw, 'correct horse battery')
+ await submit(host)
+ expect(mocks.passwordLogin).toHaveBeenCalledWith('Ana', 'correct horse battery')
+ expect(mocks.setUser).toHaveBeenCalledWith({ id: 'u1', name: 'Ana' })
+ expect(close).toHaveBeenCalled()
+ expect(mocks.adoptProfile).toHaveBeenCalled()
+ expect(mocks.toast).toHaveBeenCalledWith('Welcome back, Ana')
+ })
+
+ it('a wrong password stays on the sheet and says so, without signing anyone in', async () => {
+ mocks.passwordLogin.mockRejectedValue(fail(401, { error: 'wrong name or password', code: 'bad-credentials' }))
+ const close = vi.fn()
+ const host = mount(<PasswordSignInSheet close={close} />)
+ type(byPlaceholder(host, 'Your name'), 'Ana'); type(byPlaceholder(host, 'Password'), 'nope nope nope')
+ await submit(host)
+ expect(alertText(host)).toBe('Wrong name or password.')
+ expect(mocks.setUser).not.toHaveBeenCalled()
+ expect(close).not.toHaveBeenCalled()
+ })
+
+ it('redeems a reset code with a new password; a too-short one is caught before any request', async () => {
+ mocks.passwordResetRedeem.mockResolvedValue({ id: 'u1', name: 'Ana' })
+ const host = mount(<PasswordSignInSheet close={() => {}} />)
+ act(() => button(host, 'Have a reset code from your admin?').click())
+ expect(host.querySelector('h3').textContent).toBe('Reset your password')
+ type(byPlaceholder(host, 'Your name'), 'Ana')
+ type(byPlaceholder(host, 'Reset code'), 'k7wq-2mzp-4hxa')
+ type(byPlaceholder(host, 'New password'), 'short')
+ await submit(host)
+ expect(alertText(host)).toBe('Use at least 10 characters.')
+ expect(mocks.passwordResetRedeem).not.toHaveBeenCalled()
+ type(byPlaceholder(host, 'New password'), 'a brand new passphrase')
+ await submit(host)
+ expect(mocks.passwordResetRedeem).toHaveBeenCalledWith('Ana', 'K7WQ-2MZP-4HXA', 'a brand new passphrase')
+ expect(mocks.setUser).toHaveBeenCalled()
+ })
+
+ it('offers the passkey only when the caller hands one over and this browser can make one', () => {
+ const onPasskey = vi.fn()
+ const host = mount(<PasswordSignInSheet close={() => {}} onPasskey={onPasskey} />)
+ act(() => button(host, 'Sign in with passkey').click())
+ expect(onPasskey).toHaveBeenCalled()
+ mocks.webauthn = false
+ expect(button(mount(<PasswordSignInSheet close={() => {}} onPasskey={onPasskey} />), 'Sign in with passkey')).toBeUndefined()
+ mocks.webauthn = true
+ expect(button(mount(<PasswordSignInSheet close={() => {}} />), 'Sign in with passkey')).toBeUndefined()
+ })
+})
+
+describe('PasswordRegisterForm', () => {
+ function Harness({ inviteOnly }) {
+ const [name, setName] = React.useState('')
+ const [code, setCode] = React.useState('')
+ return <PasswordRegisterForm close={() => {}} inviteOnly={inviteOnly} name={name} setName={setName} code={code} setCode={setCode} />
+ }
+ it('checks the invite and the repeated password here, then creates the profile', async () => {
+ mocks.passwordRegister.mockResolvedValue({ id: 'u9', name: 'Cleo' })
+ const host = mount(<Harness inviteOnly />)
+ type(byPlaceholder(host, 'Your name'), 'Cleo')
+ type(byPlaceholder(host, 'Password'), 'correct horse battery')
+ type(byPlaceholder(host, 'Repeat the password'), 'correct horse battery')
+ await submit(host)
+ expect(alertText(host)).toBe('An invite code is required')
+ type(byPlaceholder(host, 'Invite code'), 'abc123')
+ type(byPlaceholder(host, 'Repeat the password'), 'correct horse batterY')
+ await submit(host)
+ expect(alertText(host)).toBe('The two passwords are not the same.')
+ expect(mocks.passwordRegister).not.toHaveBeenCalled()
+ type(byPlaceholder(host, 'Repeat the password'), 'correct horse battery')
+ await submit(host)
+ expect(mocks.passwordRegister).toHaveBeenCalledWith('Cleo', 'correct horse battery', 'ABC123')
+ expect(mocks.setUser).toHaveBeenCalledWith({ id: 'u9', name: 'Cleo' })
+ expect(mocks.pullState).toHaveBeenCalled()
+ expect(mocks.toast).toHaveBeenCalledWith('Welcome, Cleo')
+ })
+
+ it('a name already taken by a password profile is said in words', async () => {
+ mocks.passwordRegister.mockRejectedValue(fail(409, { code: 'name-taken' }))
+ const host = mount(<Harness />)
+ type(byPlaceholder(host, 'Your name'), 'Ana')
+ type(byPlaceholder(host, 'Password'), 'correct horse battery')
+ type(byPlaceholder(host, 'Repeat the password'), 'correct horse battery')
+ await submit(host)
+ expect(alertText(host)).toBe('Another profile already signs in with this name.')
+ })
+})
+
+describe('Settings → Password', () => {
+ const rowTitle = host => host.querySelector('.lrow-t')?.textContent
+ const rowSub = host => host.querySelector('.lrow-s')?.textContent
+
+ it('shows whether a password is set, and nothing when a first one could not be confirmed here', async () => {
+ mocks.answers['GET /api/account/password'] = { set: true, setAt: null, passkeys: 1, name: 'Ana', nameTaken: false }
+ const host = mount(<PasswordRow />)
+ await settle()
+ expect(rowTitle(host)).toBe('Password')
+ expect(rowSub(host)).toBe('Set · sign in as “Ana”')
+
+ mocks.answers['GET /api/account/password'] = { set: false, setAt: null, passkeys: 1, name: 'Ana', nameTaken: false }
+ mocks.webauthn = false
+ const none = mount(<PasswordRow />)
+ await settle()
+ expect(none.textContent).toBe('')
+ })
+
+ it('a first password is confirmed with the passkey and sent with its assertion', async () => {
+ const done = vi.fn(), close = vi.fn()
+ const host = mount(<PasswordSheet status={{ set: false, passkeys: 1, name: 'Ana' }} close={close} done={done} />)
+ expect(byPlaceholder(host, 'Current password')).toBeNull()
+ type(byPlaceholder(host, 'New password'), 'correct horse battery')
+ type(byPlaceholder(host, 'Repeat the password'), 'correct horse battery')
+ await submit(host)
+ expect(mocks.passkeyAssertion).toHaveBeenCalled()
+ expect(mocks.calls.at(-1)).toEqual({ path: '/api/account/password', method: 'POST', body: { next: 'correct horse battery', cid: 'c1', credential: { id: 'k1' } } })
+ expect(close).toHaveBeenCalled()
+ expect(done).toHaveBeenCalled()
+ expect(mocks.toast).toHaveBeenCalledWith('Password saved — you are signed out everywhere else.')
+ })
+
+ it('a change sends the current password; a wrong one is said on the sheet', async () => {
+ mocks.answers['POST /api/account/password'] = fail(403, { code: 'current-wrong' })
+ const close = vi.fn()
+ const host = mount(<PasswordSheet status={{ set: true, passkeys: 0, name: 'Ana' }} close={close} done={() => {}} />)
+ type(byPlaceholder(host, 'Current password'), 'old passphrase here')
+ type(byPlaceholder(host, 'New password'), 'a brand new passphrase')
+ type(byPlaceholder(host, 'Repeat the password'), 'a brand new passphrase')
+ await submit(host)
+ expect(mocks.calls.at(-1).body).toEqual({ next: 'a brand new passphrase', current: 'old passphrase here' })
+ expect(mocks.passkeyAssertion).not.toHaveBeenCalled()
+ expect(alertText(host)).toBe('Your current password is not right.')
+ expect(close).not.toHaveBeenCalled()
+ // No passkey on this profile: the password is its only way in, so there is no "Remove".
+ expect(button(host, 'Remove password')).toBeUndefined()
+ })
+
+ it('removing asks first and then deletes; only offered while a passkey remains', async () => {
+ const done = vi.fn()
+ const host = mount(<PasswordSheet status={{ set: true, passkeys: 2, name: 'Ana' }} close={() => {}} done={done} />)
+ act(() => button(host, 'Remove password').click())
+ expect(mocks.confirmSheet).toHaveBeenCalledTimes(1)
+ const opts = mocks.confirmSheet.mock.calls[0][0]
+ expect(opts.title).toBe('Remove your password?')
+ await act(async () => { opts.onConfirm() })
+ await settle()
+ expect(mocks.calls.at(-1)).toEqual({ path: '/api/account/password', method: 'DELETE', body: null })
+ expect(done).toHaveBeenCalled()
+ expect(mocks.toast).toHaveBeenCalledWith('Password removed')
+ })
+})
diff --git a/frontend/src/components/ServerSync.jsx b/frontend/src/components/ServerSync.jsx
index d3a37c467..179cf2453 100644
--- a/frontend/src/components/ServerSync.jsx
+++ b/frontend/src/components/ServerSync.jsx
@@ -12,10 +12,15 @@ import { MOBILE } from '../lib/mobile.js'
import { DEMO } from '../lib/demo.js'
import { askAddDeviceData } from '../sheets.jsx'
import { ConnectSheet } from '../views/MobileOnboarding.jsx'
+import { passwordOn, openPasswordSignIn } from './PasswordAuth.jsx'
import { Section, Row, Button } from './ui.jsx'
const ui = () => useUI.getState()
const toast = m => ui().toast(m)
+// Whether this browser has a way to sign in at all: a passkey, or a password on an instance that
+// offers one (#118) — which is also what a browser without passkey support has left.
+const pwOn = () => passwordOn(useStore.getState?.()?.config)
+const canSignIn = () => webauthnOK() || pwOn()
// "gym.example.com" out of the base URL the store keeps (a subpath stays: it is part of which
// server this is). Anything unparseable is shown as it is.
@@ -58,7 +63,7 @@ export function connectionView(sync, { mobile = MOBILE } = {}) {
default: // 'local': no server at all — chosen, so it is said quietly, but it is said
return mobile
? { tone: 'quiet', icon: 'lock', action: 'connect', line: t('On this phone only — not connected to a server'), banner: t('On this phone only — not connected to a server') }
- : { tone: 'quiet', icon: 'lock', action: webauthnOK() ? 'signin' : null, line: t('Guest mode — data lives only in this browser.'), banner: t('Guest mode — data lives only in this browser.') }
+ : { tone: 'quiet', icon: 'lock', action: canSignIn() ? 'signin' : null, line: t('Guest mode — data lives only in this browser.'), banner: t('Guest mode — data lives only in this browser.') }
}
}
@@ -85,8 +90,14 @@ export function connectServer() {
}
// A browser whose session ended, or a guest: the passkey sign-in, and the same account merges
-// what this browser kept (adoptProfile).
-export async function signInAgain() {
+// what this browser kept (adoptProfile). On an instance with passwords the sign-in sheet comes
+// first, with the passkey one tap away on it: which of the two this account has is not
+// something this browser can know.
+export function signInAgain() {
+ if (pwOn()) { openPasswordSignIn(webauthnOK() ? passkeySignIn : undefined); return }
+ return passkeySignIn()
+}
+export async function passkeySignIn() {
const st = useStore.getState()
try {
const u = await passkeyLogin()
@@ -161,7 +172,7 @@ export function OwedSheet({ kind, count: count0, exportBackup, done, close }) {
{t('Try again, or export a backup first. Going ahead anyway keeps a copy of these changes on this device until it connects to this server as this account again — then they are added back.')}
</div>
{refused && MOBILE && <><button className="btn primary" disabled={busy} onClick={() => { close(); pairAgain() }}>{t('Pair again')}</button><div style={{ height: 8 }} /></>}
- {refused && !MOBILE && webauthnOK() && <><button className="btn primary" disabled={busy} onClick={() => { close(); signInAgain() }}>{t('Sign in with passkey')}</button><div style={{ height: 8 }} /></>}
+ {refused && !MOBILE && canSignIn() && <><button className="btn primary" disabled={busy} onClick={() => { close(); signInAgain() }}>{pwOn() ? t('Sign in') : t('Sign in with passkey')}</button><div style={{ height: 8 }} /></>}
{!refused && <><button className="btn primary" disabled={busy} onClick={retry}>{busy ? t('Syncing…') : t('Try again')}</button><div style={{ height: 8 }} /></>}
<Button icon="download" disabled={busy} onClick={exportBackup}>{t('Export backup (JSON)')}</Button>
<div style={{ height: 8 }} />
@@ -181,6 +192,7 @@ export function ServerSyncSection({ children }) {
const user = useStore(s => s.user)
const sync = useStore(s => s.sync)
useStore(s => s.S) // the count of waiting changes follows every edit
+ useStore(s => s.config) // whether "Sign in" may offer a password
const unsynced = useStore(s => s.unsyncedChanges)
const [busy, setBusy] = useState(false)
// "Last synced: 3 minutes ago" goes stale on an open screen; a re-render now and then keeps it true.
@@ -207,7 +219,7 @@ export function ServerSyncSection({ children }) {
<Row icon="reset" iconTint="var(--acc)" title={busy ? t('Syncing…') : t('Sync now')} onClick={now} />
{sync.status === 'auth' && (MOBILE
? <Row icon="link" iconTint="var(--indigo)" title={t('Pair again')} subtitle={t('Your changes are kept here, and merged into your account once it is paired again.')} accessory="chevron" onClick={pairAgain} />
- : webauthnOK() && <Row icon="person" iconTint="var(--blue)" title={t('Sign in with passkey')} subtitle={t('Your changes are kept here, and merged into your account once you are signed in again.')} accessory="chevron" onClick={signInAgain} />)}
+ : canSignIn() && <Row icon="person" iconTint="var(--blue)" title={pwOn() ? t('Sign in') : t('Sign in with passkey')} subtitle={t('Your changes are kept here, and merged into your account once you are signed in again.')} accessory="chevron" onClick={signInAgain} />)}
{/* another account's, kept when this one signed in over a copy that still owed them */}
<KeptChangesRows />
{children}
diff --git a/frontend/src/lib/api.js b/frontend/src/lib/api.js
index eea1944f7..4c41e381c 100644
--- a/frontend/src/lib/api.js
+++ b/frontend/src/lib/api.js
@@ -132,9 +132,28 @@ export async function passkeyRegister(name, code) {
const res = await api('/api/register/verify', { method: 'POST', body: JSON.stringify({ cid, credential: credToJSON(cred) }) })
return res.user
}
-export async function passkeyLogin() {
+// One passkey ceremony, not yet sent anywhere: /api/login/verify turns it into a sign-in, and
+// POST /api/account/password takes it as proof before a first password is set (#118).
+export async function passkeyAssertion() {
const { cid, options } = await api('/api/login/options', { method: 'POST', body: '{}' })
const cred = await navigator.credentials.get({ publicKey: toRequestOptions(options) })
- const res = await api('/api/login/verify', { method: 'POST', body: JSON.stringify({ cid, credential: credToJSON(cred) }) })
+ return { cid, credential: credToJSON(cred) }
+}
+export async function passkeyLogin() {
+ const res = await api('/api/login/verify', { method: 'POST', body: JSON.stringify(await passkeyAssertion()) })
return res.user
}
+
+// Name-and-password sign-in, on an instance that offers it (config.password_login). Each of
+// these answers with the same session cookie a passkey sign-in sets, so callers treat the user
+// they return exactly alike.
+const post = (path, body) => api(path, { method: 'POST', body: JSON.stringify(body) })
+export async function passwordLogin(name, password) {
+ return (await post('/api/login/password', { name, password })).user
+}
+export async function passwordRegister(name, password, code) {
+ return (await post('/api/register/password', { name, password, code: code || '' })).user
+}
+export async function passwordResetRedeem(name, code, next) {
+ return (await post('/api/login/password-reset', { name, code, next })).user
+}
diff --git a/frontend/src/lib/audit.js b/frontend/src/lib/audit.js
index a2c73f86a..ff30e3989 100644
--- a/frontend/src/lib/audit.js
+++ b/frontend/src/lib/audit.js
@@ -26,9 +26,20 @@ const LABELS = {
'auth.pair.create': 'Created a pairing code',
'auth.pair.ok': 'Paired a phone',
'auth.pair.fail': 'Pairing failed',
+ // Password sign-in (#118), where the instance offers it.
+ 'auth.password.ok': 'Signed in with a password',
+ 'auth.password.fail': 'Password sign-in failed',
+ 'auth.password.locked': 'Password sign-in paused after repeated failures',
+ 'auth.password.set': 'Set a password',
+ 'auth.password.change': 'Changed their password',
+ 'auth.password.remove': 'Removed their password',
+ 'auth.password.reset': 'Used a reset code',
+ // The sign-in throttle paused an address; `msg` says for what (password, signup, pair).
+ 'auth.throttled': 'Too many failed attempts from one address',
'admin.user.disable': 'Disabled an account',
'admin.user.enable': 'Re-enabled an account',
'admin.user.delete': 'Deleted an account',
+ 'admin.password.reset': 'Issued a password reset code',
'admin.invite.create': 'Created an invite code',
'admin.invite.revoke': 'Revoked an invite code',
'admin.audit.clear': 'Cleared the activity log',
@@ -49,7 +60,13 @@ const REASONS = {
'invite-invalid': 'the invite code was used or revoked in the meantime',
'invite-rejected': 'wrong or already-used invite code',
'code-invalid': 'wrong or expired pairing code',
- 'user-unavailable': 'the profile behind the pairing code is disabled or gone'
+ 'user-unavailable': 'the profile behind the pairing code is disabled or gone',
+ 'bad-password': 'wrong password',
+ 'bad-current': 'wrong current password while changing it',
+ 'unknown-name': 'no profile with a password has that name',
+ 'step-up-failed': 'the passkey confirming a new password was rejected',
+ 'reset-invalid': 'wrong or expired reset code',
+ 'reset': 'too many wrong reset codes for one name'
}
export const auditReason = msg => REASONS[msg] || (msg ? String(msg) : '')
diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js
index 680046ae9..929fed922 100644
--- a/frontend/src/lib/pt-br-locale.test.js
+++ b/frontend/src/lib/pt-br-locale.test.js
@@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(679)
- expect(inherited).toHaveLength(674)
+ expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(721)
+ expect(inherited).toHaveLength(677)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('f81cca4b7e73e229526217b8a3825069ee65fb6a5586c143b324038f99499f75')
+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('4d451f4281754e48e4e5d41bf9a4327d8931ef91b7b2a9905b6d5422d3d9951c')
})
test('does not leak European Portuguese UI terms', () => {
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index d736fc60a..6e46ad5df 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -304,6 +304,52 @@ export default {
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Dieser Browser unterstützt keine Passkeys, und dieser Server verlangt ein Konto. Probier einen Browser oder ein Gerät mit Passkey-Unterstützung.',
'Continue without account': 'Ohne Konto fortfahren',
'Passkeys use {0} — no passwords.': 'Passkeys nutzen {0} — keine Passwörter.',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': 'Mit Passwort anmelden',
+ 'Password': 'Passwort',
+ 'Passkey': 'Passkey',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': 'Passkeys nutzen {0}. Wo sie nicht funktionieren, geht auch ein Passwort.',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": 'Dieser Browser unterstützt keine Passkeys — melde dich stattdessen mit Name und Passwort an.',
+ 'Use your profile name and the password you set for it.': 'Mit deinem Profilnamen und dem Passwort, das du dafür festgelegt hast.',
+ 'Have a reset code from your admin?': 'Einen Reset-Code von deinem Admin bekommen?',
+ 'Reset your password': 'Passwort zurücksetzen',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': 'Gib den Code von deinem Admin ein und wähle ein neues Passwort. Überall sonst wirst du damit abgemeldet.',
+ 'Reset code': 'Reset-Code',
+ 'New password': 'Neues Passwort',
+ 'Repeat the password': 'Passwort wiederholen',
+ 'Current password': 'Aktuelles Passwort',
+ 'At least {0} characters. A few unrelated words make a good one.': 'Mindestens {0} Zeichen. Ein paar Wörter, die nichts miteinander zu tun haben, sind ein gutes Passwort.',
+ 'Set password & sign in': 'Passwort festlegen & anmelden',
+ 'Create profile': 'Profil erstellen',
+ 'Pick a name and a password. You sign in with both.': 'Wähle einen Namen und ein Passwort. Mit beidem meldest du dich an.',
+ 'Enter your password.': 'Gib dein Passwort ein.',
+ 'Enter the reset code.': 'Gib den Reset-Code ein.',
+ 'The two passwords are not the same.': 'Die beiden Passwörter stimmen nicht überein.',
+ 'Set · sign in as “{0}”': 'Festgelegt · Anmeldung als „{0}“',
+ 'Not set — lets you sign in where passkeys do not work.': 'Nicht festgelegt — damit meldest du dich an, wo Passkeys nicht funktionieren.',
+ 'Set a password': 'Passwort festlegen',
+ 'Change password': 'Passwort ändern',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': 'Damit meldest du dich als „{0}“ auf Geräten an, auf denen Passkeys nicht funktionieren. Beim Speichern wirst du überall sonst abgemeldet, und gekoppelte Handys müssen neu gekoppelt werden.',
+ 'Confirm with passkey & save': 'Mit Passkey bestätigen & speichern',
+ 'Forgot it? Confirm with your passkey instead': 'Vergessen? Stattdessen mit deinem Passkey bestätigen',
+ 'Password saved — you are signed out everywhere else.': 'Passwort gespeichert — überall sonst bist du jetzt abgemeldet.',
+ 'Remove password': 'Passwort entfernen',
+ 'Remove your password?': 'Passwort entfernen?',
+ 'Only your passkeys sign in to this profile afterwards.': 'Danach melden nur noch deine Passkeys dich bei diesem Profil an.',
+ 'Password removed': 'Passwort entfernt',
+ 'Wrong name or password.': 'Name oder Passwort falsch.',
+ 'Too many attempts — try again {0}.': 'Zu viele Versuche — versuch es {0} noch einmal.',
+ 'Use at least {0} characters.': 'Nimm mindestens {0} Zeichen.',
+ 'That password is too long.': 'Dieses Passwort ist zu lang.',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': 'Dieses Passwort ist zu leicht zu erraten — nimm ein längeres oder ein paar Wörter, die nichts miteinander zu tun haben.',
+ 'Another profile already signs in with this name.': 'Ein anderes Profil meldet sich schon mit diesem Namen an.',
+ 'That invite code is not valid.': 'Dieser Einladungscode ist nicht gültig.',
+ 'Your current password is not right.': 'Dein aktuelles Passwort stimmt nicht.',
+ 'Your passkey could not be confirmed.': 'Dein Passkey konnte nicht bestätigt werden.',
+ 'This password is the only way into your profile, so it cannot be removed.': 'Dieses Passwort ist der einzige Weg in dein Profil und kann deshalb nicht entfernt werden.',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': 'Dieser Reset-Code ist falsch oder abgelaufen — bitte deinen Admin um einen neuen.',
+ 'This account has been disabled.': 'Dieses Konto wurde deaktiviert.',
+ 'The server is busy — try again in a moment.': 'Der Server ist ausgelastet — versuch es gleich noch einmal.',
'Each profile keeps its own plan, workouts & body weight.': 'Jedes Profil hat seinen eigenen Plan, Trainings & Körpergewicht.',
// --- settings ---
'Account': 'Konto',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 5764277a7..c6bf5522c 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -290,6 +290,52 @@ export default {
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Este navegador no admite passkeys y este servidor requiere una cuenta. Prueba con un navegador o dispositivo compatible con passkeys.',
'Continue without account': 'Continuar sin cuenta',
'Passkeys use {0} — no passwords.': 'Las passkeys usan {0} — sin contraseñas.',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': 'Iniciar sesión con contraseña',
+ 'Password': 'Contraseña',
+ 'Passkey': 'Passkey',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': 'Las passkeys usan {0}. Donde no funcionan, también sirve una contraseña.',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": 'Este navegador no admite passkeys — inicia sesión con tu nombre y tu contraseña.',
+ 'Use your profile name and the password you set for it.': 'Usa el nombre de tu perfil y la contraseña que le pusiste.',
+ 'Have a reset code from your admin?': '¿Tienes un código de restablecimiento de tu administrador?',
+ 'Reset your password': 'Restablecer tu contraseña',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': 'Introduce el código que te dio tu administrador y elige una contraseña nueva. Se cierra tu sesión en todos los demás sitios.',
+ 'Reset code': 'Código de restablecimiento',
+ 'New password': 'Contraseña nueva',
+ 'Repeat the password': 'Repite la contraseña',
+ 'Current password': 'Contraseña actual',
+ 'At least {0} characters. A few unrelated words make a good one.': 'Al menos {0} caracteres. Unas cuantas palabras sin relación entre sí son una buena contraseña.',
+ 'Set password & sign in': 'Guardar contraseña e iniciar sesión',
+ 'Create profile': 'Crear perfil',
+ 'Pick a name and a password. You sign in with both.': 'Elige un nombre y una contraseña. Inicias sesión con ambos.',
+ 'Enter your password.': 'Introduce tu contraseña.',
+ 'Enter the reset code.': 'Introduce el código de restablecimiento.',
+ 'The two passwords are not the same.': 'Las dos contraseñas no coinciden.',
+ 'Set · sign in as “{0}”': 'Configurada · inicia sesión como «{0}»',
+ 'Not set — lets you sign in where passkeys do not work.': 'Sin configurar — te permite iniciar sesión donde las passkeys no funcionan.',
+ 'Set a password': 'Poner una contraseña',
+ 'Change password': 'Cambiar contraseña',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': 'Con ella inicias sesión como «{0}» en dispositivos donde las passkeys no funcionan. Al guardar se cierra tu sesión en todos los demás sitios, y los teléfonos emparejados tendrán que emparejarse de nuevo.',
+ 'Confirm with passkey & save': 'Confirmar con passkey y guardar',
+ 'Forgot it? Confirm with your passkey instead': '¿La olvidaste? Confirma con tu passkey',
+ 'Password saved — you are signed out everywhere else.': 'Contraseña guardada — se ha cerrado tu sesión en todos los demás sitios.',
+ 'Remove password': 'Quitar contraseña',
+ 'Remove your password?': '¿Quitar tu contraseña?',
+ 'Only your passkeys sign in to this profile afterwards.': 'Después, solo tus passkeys inician sesión en este perfil.',
+ 'Password removed': 'Contraseña quitada',
+ 'Wrong name or password.': 'Nombre o contraseña incorrectos.',
+ 'Too many attempts — try again {0}.': 'Demasiados intentos — vuelve a intentarlo {0}.',
+ 'Use at least {0} characters.': 'Usa al menos {0} caracteres.',
+ 'That password is too long.': 'Esa contraseña es demasiado larga.',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': 'Esa contraseña es demasiado fácil de adivinar — prueba con una más larga o con unas cuantas palabras sin relación entre sí.',
+ 'Another profile already signs in with this name.': 'Otro perfil ya inicia sesión con este nombre.',
+ 'That invite code is not valid.': 'Ese código de invitación no es válido.',
+ 'Your current password is not right.': 'Tu contraseña actual no es correcta.',
+ 'Your passkey could not be confirmed.': 'No se pudo confirmar tu passkey.',
+ 'This password is the only way into your profile, so it cannot be removed.': 'Esta contraseña es la única forma de entrar en tu perfil, así que no se puede quitar.',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': 'Ese código de restablecimiento es incorrecto o ha caducado — pide uno nuevo a tu administrador.',
+ 'This account has been disabled.': 'Esta cuenta ha sido desactivada.',
+ 'The server is busy — try again in a moment.': 'El servidor está ocupado — inténtalo de nuevo en un momento.',
'Each profile keeps its own plan, workouts & body weight.': 'Cada perfil guarda su propio plan, entrenamientos y peso corporal.',
'Account': 'Cuenta',
'Sign out?': '¿Cerrar sesión?',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 277c4dbc0..bc416ffe2 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -290,6 +290,52 @@ export default {
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Ce navigateur ne prend pas en charge les passkeys, et ce serveur exige un compte. Essaie un navigateur ou un appareil compatible avec les passkeys.',
'Continue without account': 'Continuer sans compte',
'Passkeys use {0} — no passwords.': 'Les passkeys utilisent {0} — pas de mots de passe.',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': 'Se connecter avec un mot de passe',
+ 'Password': 'Mot de passe',
+ 'Passkey': 'Passkey',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': 'Les passkeys utilisent {0}. Là où elles ne fonctionnent pas, un mot de passe marche aussi.',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": 'Ce navigateur ne prend pas en charge les passkeys — connecte-toi plutôt avec ton nom et ton mot de passe.',
+ 'Use your profile name and the password you set for it.': 'Utilise le nom de ton profil et le mot de passe que tu lui as donné.',
+ 'Have a reset code from your admin?': 'Tu as un code de réinitialisation de ton administrateur ?',
+ 'Reset your password': 'Réinitialiser ton mot de passe',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': 'Entre le code que ton administrateur t’a donné et choisis un nouveau mot de passe. Tu seras déconnecté partout ailleurs.',
+ 'Reset code': 'Code de réinitialisation',
+ 'New password': 'Nouveau mot de passe',
+ 'Repeat the password': 'Répète le mot de passe',
+ 'Current password': 'Mot de passe actuel',
+ 'At least {0} characters. A few unrelated words make a good one.': 'Au moins {0} caractères. Quelques mots sans rapport entre eux font un bon mot de passe.',
+ 'Set password & sign in': 'Définir le mot de passe et se connecter',
+ 'Create profile': 'Créer le profil',
+ 'Pick a name and a password. You sign in with both.': 'Choisis un nom et un mot de passe. Tu te connectes avec les deux.',
+ 'Enter your password.': 'Entre ton mot de passe.',
+ 'Enter the reset code.': 'Entre le code de réinitialisation.',
+ 'The two passwords are not the same.': 'Les deux mots de passe ne sont pas identiques.',
+ 'Set · sign in as “{0}”': 'Défini · connexion en tant que « {0} »',
+ 'Not set — lets you sign in where passkeys do not work.': 'Non défini — permet de te connecter là où les passkeys ne fonctionnent pas.',
+ 'Set a password': 'Définir un mot de passe',
+ 'Change password': 'Changer le mot de passe',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': 'Il te permet de te connecter en tant que « {0} » sur les appareils où les passkeys ne fonctionnent pas. En l’enregistrant, tu es déconnecté partout ailleurs, et les téléphones associés devront être associés à nouveau.',
+ 'Confirm with passkey & save': 'Confirmer avec la passkey et enregistrer',
+ 'Forgot it? Confirm with your passkey instead': 'Oublié ? Confirme plutôt avec ta passkey',
+ 'Password saved — you are signed out everywhere else.': 'Mot de passe enregistré — tu es déconnecté partout ailleurs.',
+ 'Remove password': 'Retirer le mot de passe',
+ 'Remove your password?': 'Retirer ton mot de passe ?',
+ 'Only your passkeys sign in to this profile afterwards.': 'Ensuite, seules tes passkeys permettent de te connecter à ce profil.',
+ 'Password removed': 'Mot de passe retiré',
+ 'Wrong name or password.': 'Nom ou mot de passe incorrect.',
+ 'Too many attempts — try again {0}.': 'Trop de tentatives — réessaie {0}.',
+ 'Use at least {0} characters.': 'Utilise au moins {0} caractères.',
+ 'That password is too long.': 'Ce mot de passe est trop long.',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': 'Ce mot de passe est trop facile à deviner — essaie-en un plus long, ou quelques mots sans rapport entre eux.',
+ 'Another profile already signs in with this name.': 'Un autre profil se connecte déjà avec ce nom.',
+ 'That invite code is not valid.': 'Ce code d’invitation n’est pas valide.',
+ 'Your current password is not right.': 'Ton mot de passe actuel n’est pas le bon.',
+ 'Your passkey could not be confirmed.': 'Ta passkey n’a pas pu être confirmée.',
+ 'This password is the only way into your profile, so it cannot be removed.': 'Ce mot de passe est le seul moyen d’accéder à ton profil, il ne peut donc pas être retiré.',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': 'Ce code de réinitialisation est faux ou a expiré — demande-en un nouveau à ton administrateur.',
+ 'This account has been disabled.': 'Ce compte a été désactivé.',
+ 'The server is busy — try again in a moment.': 'Le serveur est occupé — réessaie dans un instant.',
'Each profile keeps its own plan, workouts & body weight.': 'Chaque profil garde son plan, ses séances et son poids corporel.',
'Account': 'Compte',
'Sign out?': 'Se déconnecter ?',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 303289210..09d9d159c 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -290,6 +290,52 @@ export default {
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'यह ब्राउज़र पासकी सपोर्ट नहीं करता, और इस सर्वर के लिए खाता ज़रूरी है। पासकी सपोर्ट वाला ब्राउज़र या डिवाइस आज़माएँ।',
'Continue without account': 'बिना खाते के जारी रखें',
'Passkeys use {0} — no passwords.': 'पासकी {0} का उपयोग करती हैं — कोई पासवर्ड नहीं।',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': 'पासवर्ड से साइन इन करें',
+ 'Password': 'पासवर्ड',
+ 'Passkey': 'पासकी',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': 'पासकी {0} का उपयोग करती हैं। जहाँ वे काम नहीं करतीं, वहाँ पासवर्ड भी चलता है।',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": 'यह ब्राउज़र पासकी का समर्थन नहीं करता — इसकी जगह अपने नाम और पासवर्ड से साइन इन करें।',
+ 'Use your profile name and the password you set for it.': 'अपनी प्रोफ़ाइल का नाम और उसके लिए सेट किया गया पासवर्ड इस्तेमाल करें।',
+ 'Have a reset code from your admin?': 'क्या आपके पास एडमिन से मिला रीसेट कोड है?',
+ 'Reset your password': 'अपना पासवर्ड रीसेट करें',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': 'अपने एडमिन से मिला कोड दर्ज करें और नया पासवर्ड चुनें। इससे आप बाकी हर जगह से साइन आउट हो जाएँगे।',
+ 'Reset code': 'रीसेट कोड',
+ 'New password': 'नया पासवर्ड',
+ 'Repeat the password': 'पासवर्ड दोबारा लिखें',
+ 'Current password': 'मौजूदा पासवर्ड',
+ 'At least {0} characters. A few unrelated words make a good one.': 'कम से कम {0} अक्षर। कुछ आपस में असंबंधित शब्द मिलकर अच्छा पासवर्ड बनाते हैं।',
+ 'Set password & sign in': 'पासवर्ड सेट करें और साइन इन करें',
+ 'Create profile': 'प्रोफ़ाइल बनाएँ',
+ 'Pick a name and a password. You sign in with both.': 'एक नाम और एक पासवर्ड चुनें। आप दोनों से साइन इन करेंगे।',
+ 'Enter your password.': 'अपना पासवर्ड दर्ज करें।',
+ 'Enter the reset code.': 'रीसेट कोड दर्ज करें।',
+ 'The two passwords are not the same.': 'दोनों पासवर्ड एक जैसे नहीं हैं।',
+ 'Set · sign in as “{0}”': 'सेट है · "{0}" के रूप में साइन इन',
+ 'Not set — lets you sign in where passkeys do not work.': 'सेट नहीं — जहाँ पासकी काम नहीं करती, वहाँ साइन इन करने देता है।',
+ 'Set a password': 'पासवर्ड सेट करें',
+ 'Change password': 'पासवर्ड बदलें',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': 'जिन डिवाइस पर पासकी काम नहीं करती, वहाँ इससे "{0}" के रूप में साइन इन करें। सहेजने पर आप बाकी हर जगह से साइन आउट हो जाएँगे, और पेयर किए गए फ़ोन दोबारा पेयर करने होंगे।',
+ 'Confirm with passkey & save': 'पासकी से पुष्टि करें और सहेजें',
+ 'Forgot it? Confirm with your passkey instead': 'भूल गए? इसकी जगह अपनी पासकी से पुष्टि करें',
+ 'Password saved — you are signed out everywhere else.': 'पासवर्ड सहेजा गया — आप बाकी हर जगह से साइन आउट हो गए हैं।',
+ 'Remove password': 'पासवर्ड हटाएँ',
+ 'Remove your password?': 'अपना पासवर्ड हटाएँ?',
+ 'Only your passkeys sign in to this profile afterwards.': 'इसके बाद केवल आपकी पासकी से ही इस प्रोफ़ाइल में साइन इन होगा।',
+ 'Password removed': 'पासवर्ड हटाया गया',
+ 'Wrong name or password.': 'नाम या पासवर्ड गलत है।',
+ 'Too many attempts — try again {0}.': 'बहुत ज़्यादा प्रयास — {0} फिर से कोशिश करें।',
+ 'Use at least {0} characters.': 'कम से कम {0} अक्षर इस्तेमाल करें।',
+ 'That password is too long.': 'यह पासवर्ड बहुत लंबा है।',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': 'इस पासवर्ड का अनुमान लगाना बहुत आसान है — कोई लंबा पासवर्ड या कुछ आपस में असंबंधित शब्द आज़माएँ।',
+ 'Another profile already signs in with this name.': 'कोई दूसरी प्रोफ़ाइल पहले से इस नाम से साइन इन करती है।',
+ 'That invite code is not valid.': 'यह इनवाइट कोड मान्य नहीं है।',
+ 'Your current password is not right.': 'आपका मौजूदा पासवर्ड सही नहीं है।',
+ 'Your passkey could not be confirmed.': 'आपकी पासकी की पुष्टि नहीं हो सकी।',
+ 'This password is the only way into your profile, so it cannot be removed.': 'यह पासवर्ड आपकी प्रोफ़ाइल में जाने का एकमात्र तरीका है, इसलिए इसे हटाया नहीं जा सकता।',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': 'यह रीसेट कोड गलत है या इसकी अवधि समाप्त हो गई है — अपने एडमिन से नया कोड माँगें।',
+ 'This account has been disabled.': 'यह खाता निष्क्रिय कर दिया गया है।',
+ 'The server is busy — try again in a moment.': 'सर्वर व्यस्त है — थोड़ी देर में फिर से कोशिश करें।',
'Each profile keeps its own plan, workouts & body weight.': 'हर प्रोफ़ाइल की अपनी योजना, वर्कआउट और वज़न होते हैं।',
'Account': 'खाता',
'Sign out?': 'साइन आउट करें?',
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 28c1a24a8..2351e4dde 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -296,6 +296,52 @@ export default {
'This browser doesn\'t support passkeys, and this instance requires an account. Try a browser or device with passkey support.': 'Ez a böngésző nem támogatja a jelszókulcsokat, ez a szerver pedig fiókot igényel. Próbálj egy jelszókulcsot támogató böngészőt vagy eszközt.',
'Continue without account': 'Folytatás fiók nélkül',
'Passkeys use {0} — no passwords.': 'A jelszókulcs ezt használja: {0} — jelszó nélkül.',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': 'Bejelentkezés jelszóval',
+ 'Password': 'Jelszó',
+ 'Passkey': 'Jelszókulcs',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': 'A jelszókulcs ezt használja: {0}. Ahol nem működik, jelszóval is megy.',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": 'Ez a böngésző nem támogatja a jelszókulcsokat — jelentkezz be inkább a neveddel és a jelszavaddal.',
+ 'Use your profile name and the password you set for it.': 'Használd a profilod nevét és a hozzá beállított jelszót.',
+ 'Have a reset code from your admin?': 'Kaptál visszaállító kódot az adminisztrátortól?',
+ 'Reset your password': 'Jelszó visszaállítása',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': 'Add meg az adminisztrátortól kapott kódot, és válassz új jelszót. Ezzel minden más helyen kijelentkezel.',
+ 'Reset code': 'Visszaállító kód',
+ 'New password': 'Új jelszó',
+ 'Repeat the password': 'Jelszó még egyszer',
+ 'Current password': 'Jelenlegi jelszó',
+ 'At least {0} characters. A few unrelated words make a good one.': 'Legalább {0} karakter. Néhány egymáshoz nem kapcsolódó szó jó jelszót ad.',
+ 'Set password & sign in': 'Jelszó beállítása és bejelentkezés',
+ 'Create profile': 'Profil létrehozása',
+ 'Pick a name and a password. You sign in with both.': 'Válassz egy nevet és egy jelszót. Mindkettővel jelentkezel be.',
+ 'Enter your password.': 'Add meg a jelszavad.',
+ 'Enter the reset code.': 'Add meg a visszaállító kódot.',
+ 'The two passwords are not the same.': 'A két jelszó nem egyezik.',
+ 'Set · sign in as “{0}”': 'Beállítva · bejelentkezés mint „{0}”',
+ 'Not set — lets you sign in where passkeys do not work.': 'Nincs beállítva — ott jelentkezhetsz be vele, ahol a jelszókulcsok nem működnek.',
+ 'Set a password': 'Jelszó beállítása',
+ 'Change password': 'Jelszó módosítása',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': 'Ezzel „{0}” néven jelentkezhetsz be olyan eszközökön, ahol a jelszókulcsok nem működnek. Mentéskor minden más helyen kijelentkezel, a párosított telefonokat pedig újra kell párosítani.',
+ 'Confirm with passkey & save': 'Megerősítés jelszókulccsal és mentés',
+ 'Forgot it? Confirm with your passkey instead': 'Elfelejtetted? Erősítsd meg inkább a jelszókulcsoddal',
+ 'Password saved — you are signed out everywhere else.': 'Jelszó mentve — minden más helyen kijelentkeztél.',
+ 'Remove password': 'Jelszó eltávolítása',
+ 'Remove your password?': 'Eltávolítod a jelszavad?',
+ 'Only your passkeys sign in to this profile afterwards.': 'Ezután csak a jelszókulcsaiddal lehet belépni ebbe a profilba.',
+ 'Password removed': 'Jelszó eltávolítva',
+ 'Wrong name or password.': 'Hibás név vagy jelszó.',
+ 'Too many attempts — try again {0}.': 'Túl sok próbálkozás — próbáld újra {0}.',
+ 'Use at least {0} characters.': 'Legalább {0} karaktert használj.',
+ 'That password is too long.': 'Ez a jelszó túl hosszú.',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': 'Ezt a jelszót túl könnyű kitalálni — próbálj egy hosszabbat, vagy néhány egymáshoz nem kapcsolódó szót.',
+ 'Another profile already signs in with this name.': 'Egy másik profil már ezzel a névvel jelentkezik be.',
+ 'That invite code is not valid.': 'Ez a meghívókód nem érvényes.',
+ 'Your current password is not right.': 'A jelenlegi jelszavad nem stimmel.',
+ 'Your passkey could not be confirmed.': 'A jelszókulcsodat nem sikerült megerősíteni.',
+ 'This password is the only way into your profile, so it cannot be removed.': 'Ez a jelszó az egyetlen módja, hogy belépj a profilodba, ezért nem távolítható el.',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': 'Ez a visszaállító kód hibás vagy lejárt — kérj újat az adminisztrátortól.',
+ 'This account has been disabled.': 'Ezt a fiókot letiltották.',
+ 'The server is busy — try again in a moment.': 'A szerver foglalt — próbáld újra egy pillanat múlva.',
'Each profile keeps its own plan, workouts & body weight.': 'Minden profil megőrzi a saját tervét, edzéseit és testsúlyát.',
// --- settings ---
'Account': 'Fiók',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 65fbe048b..c4bb4743f 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -290,6 +290,52 @@ export default {
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Questo browser non supporta le passkey e questo server richiede un account. Prova un browser o un dispositivo che supporti le passkey.',
'Continue without account': 'Continua senza account',
'Passkeys use {0} — no passwords.': 'Le passkey usano {0} — niente password.',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': 'Accedi con password',
+ 'Password': 'Password',
+ 'Passkey': 'Passkey',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': 'Le passkey usano {0}. Dove non funzionano, va bene anche una password.',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": 'Questo browser non supporta le passkey — accedi invece con nome e password.',
+ 'Use your profile name and the password you set for it.': 'Usa il nome del tuo profilo e la password che gli hai impostato.',
+ 'Have a reset code from your admin?': 'Hai un codice di reimpostazione dal tuo amministratore?',
+ 'Reset your password': 'Reimposta la password',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': 'Inserisci il codice che ti ha dato il tuo amministratore e scegli una nuova password. Verrai disconnesso ovunque altrove.',
+ 'Reset code': 'Codice di reimpostazione',
+ 'New password': 'Nuova password',
+ 'Repeat the password': 'Ripeti la password',
+ 'Current password': 'Password attuale',
+ 'At least {0} characters. A few unrelated words make a good one.': 'Almeno {0} caratteri. Qualche parola senza legame tra loro è una buona password.',
+ 'Set password & sign in': 'Imposta la password e accedi',
+ 'Create profile': 'Crea profilo',
+ 'Pick a name and a password. You sign in with both.': 'Scegli un nome e una password. Accedi con entrambi.',
+ 'Enter your password.': 'Inserisci la tua password.',
+ 'Enter the reset code.': 'Inserisci il codice di reimpostazione.',
+ 'The two passwords are not the same.': 'Le due password non coincidono.',
+ 'Set · sign in as “{0}”': 'Impostata · accedi come «{0}»',
+ 'Not set — lets you sign in where passkeys do not work.': 'Non impostata — ti permette di accedere dove le passkey non funzionano.',
+ 'Set a password': 'Imposta una password',
+ 'Change password': 'Cambia password',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': 'Con questa accedi come «{0}» sui dispositivi dove le passkey non funzionano. Salvando vieni disconnesso ovunque altrove, e i telefoni abbinati andranno abbinati di nuovo.',
+ 'Confirm with passkey & save': 'Conferma con passkey e salva',
+ 'Forgot it? Confirm with your passkey instead': 'L’hai dimenticata? Conferma invece con la tua passkey',
+ 'Password saved — you are signed out everywhere else.': 'Password salvata — sei stato disconnesso ovunque altrove.',
+ 'Remove password': 'Rimuovi password',
+ 'Remove your password?': 'Rimuovere la password?',
+ 'Only your passkeys sign in to this profile afterwards.': 'Dopo, si accede a questo profilo solo con le tue passkey.',
+ 'Password removed': 'Password rimossa',
+ 'Wrong name or password.': 'Nome o password errati.',
+ 'Too many attempts — try again {0}.': 'Troppi tentativi — riprova {0}.',
+ 'Use at least {0} characters.': 'Usa almeno {0} caratteri.',
+ 'That password is too long.': 'Questa password è troppo lunga.',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': 'Questa password è troppo facile da indovinare — provane una più lunga, o qualche parola senza legame tra loro.',
+ 'Another profile already signs in with this name.': 'Un altro profilo accede già con questo nome.',
+ 'That invite code is not valid.': 'Questo codice di invito non è valido.',
+ 'Your current password is not right.': 'La tua password attuale non è corretta.',
+ 'Your passkey could not be confirmed.': 'Non è stato possibile confermare la tua passkey.',
+ 'This password is the only way into your profile, so it cannot be removed.': 'Questa password è l’unico modo per entrare nel tuo profilo, quindi non si può rimuovere.',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': 'Questo codice di reimpostazione è sbagliato o scaduto — chiedine uno nuovo al tuo amministratore.',
+ 'This account has been disabled.': 'Questo account è stato disattivato.',
+ 'The server is busy — try again in a moment.': 'Il server è occupato — riprova tra un momento.',
'Each profile keeps its own plan, workouts & body weight.': 'Ogni profilo ha il proprio piano, allenamenti e peso corporeo.',
'Account': 'Account',
'Sign out?': 'Uscire?',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 9018a95d3..a996e3572 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -290,6 +290,52 @@ export default {
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": '이 브라우저는 패스키를 지원하지 않고, 이 서버는 계정이 필요합니다. 패스키를 지원하는 브라우저나 기기를 사용해 보세요.',
'Continue without account': '계정 없이 계속',
'Passkeys use {0} — no passwords.': '패스키는 {0}을(를) 사용합니다 — 비밀번호 없음.',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': '비밀번호로 로그인',
+ 'Password': '비밀번호',
+ 'Passkey': '패스키',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': '패스키는 {0}을(를) 사용합니다. 패스키가 작동하지 않는 곳에서는 비밀번호도 됩니다.',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": '이 브라우저는 패스키를 지원하지 않습니다 — 대신 이름과 비밀번호로 로그인하세요.',
+ 'Use your profile name and the password you set for it.': '프로필 이름과 그 프로필에 설정한 비밀번호를 사용하세요.',
+ 'Have a reset code from your admin?': '관리자에게 받은 재설정 코드가 있나요?',
+ 'Reset your password': '비밀번호 재설정',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': '관리자에게 받은 코드를 입력하고 새 비밀번호를 정하세요. 다른 모든 곳에서는 로그아웃됩니다.',
+ 'Reset code': '재설정 코드',
+ 'New password': '새 비밀번호',
+ 'Repeat the password': '비밀번호 다시 입력',
+ 'Current password': '현재 비밀번호',
+ 'At least {0} characters. A few unrelated words make a good one.': '최소 {0}자. 서로 관련 없는 단어 몇 개면 좋은 비밀번호가 됩니다.',
+ 'Set password & sign in': '비밀번호 설정 후 로그인',
+ 'Create profile': '프로필 생성',
+ 'Pick a name and a password. You sign in with both.': '이름과 비밀번호를 정하세요. 둘 다 있어야 로그인할 수 있습니다.',
+ 'Enter your password.': '비밀번호를 입력하세요.',
+ 'Enter the reset code.': '재설정 코드를 입력하세요.',
+ 'The two passwords are not the same.': '두 비밀번호가 같지 않습니다.',
+ 'Set · sign in as “{0}”': '설정됨 · "{0}"(으)로 로그인',
+ 'Not set — lets you sign in where passkeys do not work.': '설정 안 됨 — 패스키가 작동하지 않는 곳에서 로그인할 수 있습니다.',
+ 'Set a password': '비밀번호 설정',
+ 'Change password': '비밀번호 변경',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': '패스키가 작동하지 않는 기기에서 이 비밀번호로 "{0}"(으)로 로그인합니다. 저장하면 다른 모든 곳에서 로그아웃되며, 페어링된 휴대폰은 다시 페어링해야 합니다.',
+ 'Confirm with passkey & save': '패스키로 확인하고 저장',
+ 'Forgot it? Confirm with your passkey instead': '잊으셨나요? 대신 패스키로 확인하세요',
+ 'Password saved — you are signed out everywhere else.': '비밀번호 저장됨 — 다른 모든 곳에서 로그아웃되었습니다.',
+ 'Remove password': '비밀번호 제거',
+ 'Remove your password?': '비밀번호를 제거할까요?',
+ 'Only your passkeys sign in to this profile afterwards.': '이후에는 패스키로만 이 프로필에 로그인할 수 있습니다.',
+ 'Password removed': '비밀번호 제거됨',
+ 'Wrong name or password.': '이름 또는 비밀번호가 올바르지 않습니다.',
+ 'Too many attempts — try again {0}.': '시도 횟수가 너무 많습니다 — {0} 다시 시도하세요.',
+ 'Use at least {0} characters.': '최소 {0}자 이상 사용하세요.',
+ 'That password is too long.': '비밀번호가 너무 깁니다.',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': '추측하기 너무 쉬운 비밀번호입니다 — 더 긴 비밀번호나 서로 관련 없는 단어 몇 개를 사용해 보세요.',
+ 'Another profile already signs in with this name.': '다른 프로필이 이미 이 이름으로 로그인합니다.',
+ 'That invite code is not valid.': '유효하지 않은 초대 코드입니다.',
+ 'Your current password is not right.': '현재 비밀번호가 올바르지 않습니다.',
+ 'Your passkey could not be confirmed.': '패스키를 확인할 수 없습니다.',
+ 'This password is the only way into your profile, so it cannot be removed.': '이 비밀번호는 프로필에 들어갈 수 있는 유일한 방법이므로 제거할 수 없습니다.',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': '재설정 코드가 틀렸거나 만료되었습니다 — 관리자에게 새 코드를 요청하세요.',
+ 'This account has been disabled.': '이 계정은 비활성화되었습니다.',
+ 'The server is busy — try again in a moment.': '서버가 바쁩니다 — 잠시 후 다시 시도하세요.',
'Each profile keeps its own plan, workouts & body weight.': '프로필마다 자신의 계획, 운동, 체중을 보관합니다.',
'Account': '계정',
'Sign out?': '로그아웃할까요?',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 668ec24b2..1c66fccb8 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -290,6 +290,52 @@ export default {
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Ta przeglądarka nie obsługuje passkey, a ten serwer wymaga konta. Spróbuj przeglądarki lub urządzenia z obsługą passkey.',
'Continue without account': 'Kontynuuj bez konta',
'Passkeys use {0} — no passwords.': 'Passkey używa: {0} — bez haseł.',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': 'Zaloguj się hasłem',
+ 'Password': 'Hasło',
+ 'Passkey': 'Passkey',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': 'Passkey używa: {0}. Tam, gdzie nie działa, wystarczy też hasło.',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": 'Ta przeglądarka nie obsługuje passkey — zaloguj się zamiast tego nazwą i hasłem.',
+ 'Use your profile name and the password you set for it.': 'Użyj nazwy swojego profilu i hasła, które dla niego ustawiłeś.',
+ 'Have a reset code from your admin?': 'Masz kod resetu od administratora?',
+ 'Reset your password': 'Zresetuj hasło',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': 'Wpisz kod od administratora i wybierz nowe hasło. Wszędzie indziej zostaniesz wylogowany.',
+ 'Reset code': 'Kod resetu',
+ 'New password': 'Nowe hasło',
+ 'Repeat the password': 'Powtórz hasło',
+ 'Current password': 'Obecne hasło',
+ 'At least {0} characters. A few unrelated words make a good one.': 'Co najmniej {0} znaków. Kilka niezwiązanych ze sobą słów to dobre hasło.',
+ 'Set password & sign in': 'Ustaw hasło i zaloguj się',
+ 'Create profile': 'Utwórz profil',
+ 'Pick a name and a password. You sign in with both.': 'Wybierz nazwę i hasło. Logujesz się jednym i drugim.',
+ 'Enter your password.': 'Wpisz swoje hasło.',
+ 'Enter the reset code.': 'Wpisz kod resetu.',
+ 'The two passwords are not the same.': 'Hasła nie są takie same.',
+ 'Set · sign in as “{0}”': 'Ustawione · logowanie jako „{0}”',
+ 'Not set — lets you sign in where passkeys do not work.': 'Nieustawione — pozwala zalogować się tam, gdzie passkey nie działa.',
+ 'Set a password': 'Ustaw hasło',
+ 'Change password': 'Zmień hasło',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': 'Dzięki niemu zalogujesz się jako „{0}” na urządzeniach, na których passkey nie działa. Zapisanie wyloguje cię wszędzie indziej, a sparowane telefony trzeba będzie sparować ponownie.',
+ 'Confirm with passkey & save': 'Potwierdź passkey i zapisz',
+ 'Forgot it? Confirm with your passkey instead': 'Nie pamiętasz? Potwierdź zamiast tego passkey',
+ 'Password saved — you are signed out everywhere else.': 'Hasło zapisane — wszędzie indziej zostałeś wylogowany.',
+ 'Remove password': 'Usuń hasło',
+ 'Remove your password?': 'Usunąć hasło?',
+ 'Only your passkeys sign in to this profile afterwards.': 'Potem do tego profilu zalogujesz się już tylko passkey.',
+ 'Password removed': 'Hasło usunięte',
+ 'Wrong name or password.': 'Błędna nazwa lub hasło.',
+ 'Too many attempts — try again {0}.': 'Za dużo prób — spróbuj ponownie {0}.',
+ 'Use at least {0} characters.': 'Użyj co najmniej {0} znaków.',
+ 'That password is too long.': 'To hasło jest za długie.',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': 'To hasło jest zbyt łatwe do odgadnięcia — spróbuj dłuższego albo kilku niezwiązanych ze sobą słów.',
+ 'Another profile already signs in with this name.': 'Inny profil loguje się już tą nazwą.',
+ 'That invite code is not valid.': 'Ten kod zaproszenia jest nieprawidłowy.',
+ 'Your current password is not right.': 'Twoje obecne hasło jest nieprawidłowe.',
+ 'Your passkey could not be confirmed.': 'Nie udało się potwierdzić passkey.',
+ 'This password is the only way into your profile, so it cannot be removed.': 'To hasło jest jedynym sposobem wejścia do twojego profilu, więc nie można go usunąć.',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': 'Ten kod resetu jest błędny lub wygasł — poproś administratora o nowy.',
+ 'This account has been disabled.': 'To konto zostało wyłączone.',
+ 'The server is busy — try again in a moment.': 'Serwer jest zajęty — spróbuj ponownie za chwilę.',
'Each profile keeps its own plan, workouts & body weight.': 'Każdy profil ma własny plan, treningi i masę ciała.',
'Account': 'Konto',
'Sign out?': 'Wylogować?',
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 54b70d992..9374e5d94 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -299,6 +299,49 @@ export const PT_BR_OVERRIDES = {
'Superset with exercise above': 'Superset com o exercício acima',
'Guest mode — data lives only in this browser.': 'Modo visitante — os dados ficam somente neste navegador.',
'Sign in with passkey': 'Entrar com chave de acesso',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': 'Entrar com senha',
+ 'Password': 'Senha',
+ 'Passkey': 'Chave de acesso',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': 'As chaves de acesso usam {0}. Onde elas não funcionam, uma senha também serve.',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": 'Este navegador não é compatível com chaves de acesso — entre com seu nome e sua senha.',
+ 'Use your profile name and the password you set for it.': 'Use o nome do seu perfil e a senha que você definiu para ele.',
+ 'Have a reset code from your admin?': 'Tem um código de redefinição do seu administrador?',
+ 'Reset your password': 'Redefinir sua senha',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': 'Digite o código que seu administrador deu e escolha uma nova senha. Você sai de todos os outros lugares.',
+ 'Reset code': 'Código de redefinição',
+ 'New password': 'Nova senha',
+ 'Repeat the password': 'Repita a senha',
+ 'Current password': 'Senha atual',
+ 'At least {0} characters. A few unrelated words make a good one.': 'Pelo menos {0} caracteres. Algumas palavras sem relação entre si formam uma boa senha.',
+ 'Set password & sign in': 'Definir senha e entrar',
+ 'Pick a name and a password. You sign in with both.': 'Escolha um nome e uma senha. Você entra com os dois.',
+ 'Enter your password.': 'Digite sua senha.',
+ 'Enter the reset code.': 'Digite o código de redefinição.',
+ 'The two passwords are not the same.': 'As duas senhas não são iguais.',
+ 'Set · sign in as “{0}”': 'Definida · entrar como “{0}”',
+ 'Not set — lets you sign in where passkeys do not work.': 'Não definida — permite entrar onde as chaves de acesso não funcionam.',
+ 'Set a password': 'Definir uma senha',
+ 'Change password': 'Alterar senha',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': 'Com ela você entra como “{0}” em dispositivos onde as chaves de acesso não funcionam. Ao salvar, você sai de todos os outros lugares, e os celulares pareados precisam ser pareados de novo.',
+ 'Confirm with passkey & save': 'Confirmar com chave de acesso e salvar',
+ 'Forgot it? Confirm with your passkey instead': 'Esqueceu? Confirme com sua chave de acesso',
+ 'Password saved — you are signed out everywhere else.': 'Senha salva — você saiu de todos os outros lugares.',
+ 'Remove password': 'Remover senha',
+ 'Remove your password?': 'Remover sua senha?',
+ 'Only your passkeys sign in to this profile afterwards.': 'Depois disso, só suas chaves de acesso entram neste perfil.',
+ 'Password removed': 'Senha removida',
+ 'Wrong name or password.': 'Nome ou senha incorretos.',
+ 'Too many attempts — try again {0}.': 'Muitas tentativas — tente novamente {0}.',
+ 'Use at least {0} characters.': 'Use pelo menos {0} caracteres.',
+ 'That password is too long.': 'Essa senha é longa demais.',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': 'Essa senha é fácil demais de adivinhar — tente uma mais longa ou algumas palavras sem relação entre si.',
+ 'Another profile already signs in with this name.': 'Outro perfil já entra com este nome.',
+ 'Your current password is not right.': 'Sua senha atual não está correta.',
+ 'Your passkey could not be confirmed.': 'Não foi possível confirmar sua chave de acesso.',
+ 'This password is the only way into your profile, so it cannot be removed.': 'Esta senha é a única forma de entrar no seu perfil, por isso não pode ser removida.',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': 'Esse código de redefinição está errado ou expirou — peça um novo ao seu administrador.',
+ 'The server is busy — try again in a moment.': 'O servidor está ocupado — tente novamente daqui a pouco.',
'Passkeys not supported in this browser.': 'Chaves de acesso não são compatíveis com este navegador.',
'Su': 'D',
'Mo': 'S',
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index fb5d3ef38..1b29f7e1d 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -290,6 +290,52 @@ export default {
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Este navegador não suporta passkeys e este servidor exige uma conta. Experimenta um navegador ou dispositivo com suporte a passkeys.',
'Continue without account': 'Continuar sem conta',
'Passkeys use {0} — no passwords.': 'As passkeys usam {0} — sem palavras-passe.',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': 'Iniciar sessão com palavra-passe',
+ 'Password': 'Palavra-passe',
+ 'Passkey': 'Passkey',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': 'As passkeys usam {0}. Onde não funcionam, uma palavra-passe também serve.',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": 'Este navegador não suporta passkeys — inicia sessão com o teu nome e a tua palavra-passe.',
+ 'Use your profile name and the password you set for it.': 'Usa o nome do teu perfil e a palavra-passe que definiste para ele.',
+ 'Have a reset code from your admin?': 'Tens um código de reposição do teu administrador?',
+ 'Reset your password': 'Repor a palavra-passe',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': 'Introduz o código que o teu administrador te deu e escolhe uma nova palavra-passe. Terminas a sessão em todos os outros sítios.',
+ 'Reset code': 'Código de reposição',
+ 'New password': 'Nova palavra-passe',
+ 'Repeat the password': 'Repete a palavra-passe',
+ 'Current password': 'Palavra-passe atual',
+ 'At least {0} characters. A few unrelated words make a good one.': 'Pelo menos {0} caracteres. Algumas palavras sem relação entre si dão uma boa palavra-passe.',
+ 'Set password & sign in': 'Definir palavra-passe e iniciar sessão',
+ 'Create profile': 'Criar perfil',
+ 'Pick a name and a password. You sign in with both.': 'Escolhe um nome e uma palavra-passe. Inicias sessão com os dois.',
+ 'Enter your password.': 'Introduz a tua palavra-passe.',
+ 'Enter the reset code.': 'Introduz o código de reposição.',
+ 'The two passwords are not the same.': 'As duas palavras-passe não são iguais.',
+ 'Set · sign in as “{0}”': 'Definida · iniciar sessão como «{0}»',
+ 'Not set — lets you sign in where passkeys do not work.': 'Não definida — permite iniciar sessão onde as passkeys não funcionam.',
+ 'Set a password': 'Definir uma palavra-passe',
+ 'Change password': 'Alterar palavra-passe',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': 'Com ela inicias sessão como «{0}» em dispositivos onde as passkeys não funcionam. Ao guardar, terminas a sessão em todos os outros sítios, e os telemóveis emparelhados têm de ser emparelhados de novo.',
+ 'Confirm with passkey & save': 'Confirmar com passkey e guardar',
+ 'Forgot it? Confirm with your passkey instead': 'Esqueceste-te? Confirma antes com a tua passkey',
+ 'Password saved — you are signed out everywhere else.': 'Palavra-passe guardada — terminaste a sessão em todos os outros sítios.',
+ 'Remove password': 'Remover palavra-passe',
+ 'Remove your password?': 'Remover a tua palavra-passe?',
+ 'Only your passkeys sign in to this profile afterwards.': 'Depois disso, só as tuas passkeys iniciam sessão neste perfil.',
+ 'Password removed': 'Palavra-passe removida',
+ 'Wrong name or password.': 'Nome ou palavra-passe errados.',
+ 'Too many attempts — try again {0}.': 'Demasiadas tentativas — tenta novamente {0}.',
+ 'Use at least {0} characters.': 'Usa pelo menos {0} caracteres.',
+ 'That password is too long.': 'Essa palavra-passe é demasiado longa.',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': 'Essa palavra-passe é demasiado fácil de adivinhar — experimenta uma mais longa ou algumas palavras sem relação entre si.',
+ 'Another profile already signs in with this name.': 'Outro perfil já inicia sessão com este nome.',
+ 'That invite code is not valid.': 'Esse código de convite não é válido.',
+ 'Your current password is not right.': 'A tua palavra-passe atual não está certa.',
+ 'Your passkey could not be confirmed.': 'Não foi possível confirmar a tua passkey.',
+ 'This password is the only way into your profile, so it cannot be removed.': 'Esta palavra-passe é a única forma de entrar no teu perfil, por isso não pode ser removida.',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': 'Esse código de reposição está errado ou expirou — pede um novo ao teu administrador.',
+ 'This account has been disabled.': 'Esta conta foi desativada.',
+ 'The server is busy — try again in a moment.': 'O servidor está ocupado — tenta novamente daqui a pouco.',
'Each profile keeps its own plan, workouts & body weight.': 'Cada perfil guarda o seu plano, treinos e peso corporal.',
'Account': 'Conta',
'Sign out?': 'Terminar sessão?',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 9bfac9658..34fc7561f 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -290,6 +290,52 @@ export default {
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Этот браузер не поддерживает ключи доступа, а на этом сервере нужен аккаунт. Попробуйте браузер или устройство с поддержкой ключей доступа.',
'Continue without account': 'Продолжить без аккаунта',
'Passkeys use {0} — no passwords.': 'Ключи доступа используют {0} — без паролей.',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': 'Войти по паролю',
+ 'Password': 'Пароль',
+ 'Passkey': 'Ключ доступа',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': 'Ключи доступа используют {0}. Где они не работают, подойдёт и пароль.',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": 'Этот браузер не поддерживает ключи доступа — войди по имени и паролю.',
+ 'Use your profile name and the password you set for it.': 'Используй имя профиля и пароль, который ты для него задал.',
+ 'Have a reset code from your admin?': 'Есть код сброса от администратора?',
+ 'Reset your password': 'Сброс пароля',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': 'Введи код от администратора и выбери новый пароль. Во всех остальных местах ты выйдешь из аккаунта.',
+ 'Reset code': 'Код сброса',
+ 'New password': 'Новый пароль',
+ 'Repeat the password': 'Повтори пароль',
+ 'Current password': 'Текущий пароль',
+ 'At least {0} characters. A few unrelated words make a good one.': 'Не меньше {0} символов. Несколько не связанных между собой слов — хороший пароль.',
+ 'Set password & sign in': 'Задать пароль и войти',
+ 'Create profile': 'Создать профиль',
+ 'Pick a name and a password. You sign in with both.': 'Выбери имя и пароль. Входить будешь с ними обоими.',
+ 'Enter your password.': 'Введи пароль.',
+ 'Enter the reset code.': 'Введи код сброса.',
+ 'The two passwords are not the same.': 'Пароли не совпадают.',
+ 'Set · sign in as “{0}”': 'Задан · вход как «{0}»',
+ 'Not set — lets you sign in where passkeys do not work.': 'Не задан — позволяет входить там, где ключи доступа не работают.',
+ 'Set a password': 'Задать пароль',
+ 'Change password': 'Сменить пароль',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': 'С ним ты входишь как «{0}» на устройствах, где ключи доступа не работают. При сохранении ты выйдешь из аккаунта во всех остальных местах, а сопряжённые телефоны придётся сопрячь заново.',
+ 'Confirm with passkey & save': 'Подтвердить ключом доступа и сохранить',
+ 'Forgot it? Confirm with your passkey instead': 'Забыл? Подтверди ключом доступа',
+ 'Password saved — you are signed out everywhere else.': 'Пароль сохранён — во всех остальных местах ты вышел из аккаунта.',
+ 'Remove password': 'Удалить пароль',
+ 'Remove your password?': 'Удалить пароль?',
+ 'Only your passkeys sign in to this profile afterwards.': 'После этого войти в этот профиль можно будет только по ключам доступа.',
+ 'Password removed': 'Пароль удалён',
+ 'Wrong name or password.': 'Неверное имя или пароль.',
+ 'Too many attempts — try again {0}.': 'Слишком много попыток — попробуй снова {0}.',
+ 'Use at least {0} characters.': 'Используй не меньше {0} символов.',
+ 'That password is too long.': 'Этот пароль слишком длинный.',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': 'Этот пароль слишком легко угадать — попробуй подлиннее или несколько не связанных между собой слов.',
+ 'Another profile already signs in with this name.': 'Другой профиль уже входит под этим именем.',
+ 'That invite code is not valid.': 'Этот код приглашения недействителен.',
+ 'Your current password is not right.': 'Текущий пароль неверный.',
+ 'Your passkey could not be confirmed.': 'Не удалось подтвердить ключ доступа.',
+ 'This password is the only way into your profile, so it cannot be removed.': 'Этот пароль — единственный способ войти в твой профиль, поэтому его нельзя удалить.',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': 'Этот код сброса неверный или истёк — попроси у администратора новый.',
+ 'This account has been disabled.': 'Эта учётная запись отключена.',
+ 'The server is busy — try again in a moment.': 'Сервер занят — попробуй ещё раз чуть позже.',
'Each profile keeps its own plan, workouts & body weight.': 'У каждого профиля свой план, тренировки и вес тела.',
'Account': 'Аккаунт',
'Sign out?': 'Выйти?',
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index 952e70287..3ab986bcc 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -296,6 +296,52 @@ export default {
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'เบราว์เซอร์นี้ไม่รองรับพาสคีย์ และเซิร์ฟเวอร์นี้ต้องมีบัญชีผู้ใช้ ลองใช้เบราว์เซอร์หรืออุปกรณ์ที่รองรับพาสคีย์',
'Continue without account': 'ใช้งานต่อโดยไม่มีบัญชี',
'Passkeys use {0} — no passwords.': 'พาสคีย์ใช้ {0} — ไม่ต้องใช้รหัสผ่าน',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': 'เข้าสู่ระบบด้วยรหัสผ่าน',
+ 'Password': 'รหัสผ่าน',
+ 'Passkey': 'พาสคีย์',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': 'พาสคีย์ใช้ {0} ในที่ที่พาสคีย์ใช้ไม่ได้ ใช้รหัสผ่านก็ได้',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": 'เบราว์เซอร์นี้ไม่รองรับพาสคีย์ — เข้าสู่ระบบด้วยชื่อและรหัสผ่านแทน',
+ 'Use your profile name and the password you set for it.': 'ใช้ชื่อโปรไฟล์และรหัสผ่านที่คุณตั้งไว้สำหรับโปรไฟล์นั้น',
+ 'Have a reset code from your admin?': 'มีรหัสรีเซ็ตจากผู้ดูแลระบบใช่ไหม?',
+ 'Reset your password': 'รีเซ็ตรหัสผ่านของคุณ',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': 'กรอกรหัสที่ได้จากผู้ดูแลระบบ แล้วตั้งรหัสผ่านใหม่ คุณจะออกจากระบบในที่อื่นทั้งหมด',
+ 'Reset code': 'รหัสรีเซ็ต',
+ 'New password': 'รหัสผ่านใหม่',
+ 'Repeat the password': 'กรอกรหัสผ่านอีกครั้ง',
+ 'Current password': 'รหัสผ่านปัจจุบัน',
+ 'At least {0} characters. A few unrelated words make a good one.': 'อย่างน้อย {0} ตัวอักษร คำที่ไม่เกี่ยวข้องกันสักสองสามคำเป็นรหัสผ่านที่ดี',
+ 'Set password & sign in': 'ตั้งรหัสผ่านและเข้าสู่ระบบ',
+ 'Create profile': 'สร้างโปรไฟล์',
+ 'Pick a name and a password. You sign in with both.': 'เลือกชื่อและรหัสผ่าน คุณจะเข้าสู่ระบบด้วยทั้งสองอย่าง',
+ 'Enter your password.': 'กรอกรหัสผ่านของคุณ',
+ 'Enter the reset code.': 'กรอกรหัสรีเซ็ต',
+ 'The two passwords are not the same.': 'รหัสผ่านทั้งสองไม่ตรงกัน',
+ 'Set · sign in as “{0}”': 'ตั้งแล้ว · เข้าสู่ระบบในชื่อ “{0}”',
+ 'Not set — lets you sign in where passkeys do not work.': 'ยังไม่ได้ตั้ง — ใช้เข้าสู่ระบบในที่ที่พาสคีย์ใช้ไม่ได้',
+ 'Set a password': 'ตั้งรหัสผ่าน',
+ 'Change password': 'เปลี่ยนรหัสผ่าน',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': 'ใช้รหัสผ่านนี้เข้าสู่ระบบในชื่อ “{0}” บนอุปกรณ์ที่พาสคีย์ใช้ไม่ได้ เมื่อบันทึก คุณจะออกจากระบบในที่อื่นทั้งหมด และต้องจับคู่โทรศัพท์ที่จับคู่ไว้ใหม่อีกครั้ง',
+ 'Confirm with passkey & save': 'ยืนยันด้วยพาสคีย์และบันทึก',
+ 'Forgot it? Confirm with your passkey instead': 'ลืมใช่ไหม? ยืนยันด้วยพาสคีย์แทน',
+ 'Password saved — you are signed out everywhere else.': 'บันทึกรหัสผ่านแล้ว — คุณออกจากระบบในที่อื่นทั้งหมดแล้ว',
+ 'Remove password': 'ลบรหัสผ่าน',
+ 'Remove your password?': 'ลบรหัสผ่านของคุณ?',
+ 'Only your passkeys sign in to this profile afterwards.': 'หลังจากนี้ จะเข้าสู่โปรไฟล์นี้ได้ด้วยพาสคีย์เท่านั้น',
+ 'Password removed': 'ลบรหัสผ่านแล้ว',
+ 'Wrong name or password.': 'ชื่อหรือรหัสผ่านไม่ถูกต้อง',
+ 'Too many attempts — try again {0}.': 'ลองหลายครั้งเกินไป — ลองใหม่อีกครั้ง{0}',
+ 'Use at least {0} characters.': 'ใช้อย่างน้อย {0} ตัวอักษร',
+ 'That password is too long.': 'รหัสผ่านนี้ยาวเกินไป',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': 'รหัสผ่านนี้เดาง่ายเกินไป — ลองใช้รหัสที่ยาวขึ้น หรือคำที่ไม่เกี่ยวข้องกันสักสองสามคำ',
+ 'Another profile already signs in with this name.': 'มีโปรไฟล์อื่นใช้ชื่อนี้เข้าสู่ระบบอยู่แล้ว',
+ 'That invite code is not valid.': 'รหัสเชิญนี้ไม่ถูกต้อง',
+ 'Your current password is not right.': 'รหัสผ่านปัจจุบันไม่ถูกต้อง',
+ 'Your passkey could not be confirmed.': 'ไม่สามารถยืนยันพาสคีย์ของคุณได้',
+ 'This password is the only way into your profile, so it cannot be removed.': 'รหัสผ่านนี้เป็นทางเดียวที่จะเข้าสู่โปรไฟล์ของคุณ จึงลบไม่ได้',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': 'รหัสรีเซ็ตนี้ไม่ถูกต้องหรือหมดอายุแล้ว — ขอรหัสใหม่จากผู้ดูแลระบบของคุณ',
+ 'This account has been disabled.': 'บัญชีนี้ถูกปิดใช้งานแล้ว',
+ 'The server is busy — try again in a moment.': 'เซิร์ฟเวอร์ไม่ว่าง — ลองใหม่อีกครั้งในอีกสักครู่',
'Each profile keeps its own plan, workouts & body weight.': 'แต่ละโปรไฟล์เก็บแผน, การออกกำลังกาย และน้ำหนักตัวของตัวเองแยกกัน',
// --- settings ---
'Account': 'บัญชี',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 6f0a9eca2..7b70c0c96 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -290,6 +290,52 @@ export default {
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": 'Bu tarayıcı geçiş anahtarlarını desteklemiyor ve bu sunucu bir hesap gerektiriyor. Geçiş anahtarı destekleyen bir tarayıcı veya cihaz dene.',
'Continue without account': 'Hesapsız devam et',
'Passkeys use {0} — no passwords.': 'Geçiş anahtarları {0} kullanır — şifre yok.',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': 'Şifreyle giriş yap',
+ 'Password': 'Şifre',
+ 'Passkey': 'Geçiş anahtarı',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': 'Geçiş anahtarları {0} kullanır. Çalışmadıkları yerde şifre de olur.',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": 'Bu tarayıcı geçiş anahtarlarını desteklemiyor — bunun yerine isim ve şifreyle giriş yap.',
+ 'Use your profile name and the password you set for it.': 'Profil adını ve onun için belirlediğin şifreyi kullan.',
+ 'Have a reset code from your admin?': 'Yöneticinden aldığın bir sıfırlama kodu mu var?',
+ 'Reset your password': 'Şifreni sıfırla',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': 'Yöneticinin verdiği kodu gir ve yeni bir şifre seç. Diğer her yerde oturumun kapanır.',
+ 'Reset code': 'Sıfırlama kodu',
+ 'New password': 'Yeni şifre',
+ 'Repeat the password': 'Şifreyi tekrarla',
+ 'Current password': 'Mevcut şifre',
+ 'At least {0} characters. A few unrelated words make a good one.': 'En az {0} karakter. Birbiriyle ilgisiz birkaç kelime iyi bir şifre olur.',
+ 'Set password & sign in': 'Şifreyi belirle ve giriş yap',
+ 'Create profile': 'Profil oluştur',
+ 'Pick a name and a password. You sign in with both.': 'Bir isim ve bir şifre seç. İkisiyle birlikte giriş yaparsın.',
+ 'Enter your password.': 'Şifreni gir.',
+ 'Enter the reset code.': 'Sıfırlama kodunu gir.',
+ 'The two passwords are not the same.': 'İki şifre aynı değil.',
+ 'Set · sign in as “{0}”': 'Belirlendi · “{0}” olarak giriş',
+ 'Not set — lets you sign in where passkeys do not work.': 'Belirlenmedi — geçiş anahtarlarının çalışmadığı yerlerde giriş yapmanı sağlar.',
+ 'Set a password': 'Şifre belirle',
+ 'Change password': 'Şifreyi değiştir',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': 'Geçiş anahtarlarının çalışmadığı cihazlarda bununla “{0}” olarak giriş yaparsın. Kaydedince diğer her yerde oturumun kapanır ve eşleştirilmiş telefonların yeniden eşleştirilmesi gerekir.',
+ 'Confirm with passkey & save': 'Geçiş anahtarıyla onayla ve kaydet',
+ 'Forgot it? Confirm with your passkey instead': 'Unuttun mu? Bunun yerine geçiş anahtarınla onayla',
+ 'Password saved — you are signed out everywhere else.': 'Şifre kaydedildi — diğer her yerde oturumun kapatıldı.',
+ 'Remove password': 'Şifreyi kaldır',
+ 'Remove your password?': 'Şifren kaldırılsın mı?',
+ 'Only your passkeys sign in to this profile afterwards.': 'Bundan sonra bu profile yalnızca geçiş anahtarlarınla giriş yapılabilir.',
+ 'Password removed': 'Şifre kaldırıldı',
+ 'Wrong name or password.': 'İsim veya şifre yanlış.',
+ 'Too many attempts — try again {0}.': 'Çok fazla deneme — {0} tekrar dene.',
+ 'Use at least {0} characters.': 'En az {0} karakter kullan.',
+ 'That password is too long.': 'Bu şifre çok uzun.',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': 'Bu şifreyi tahmin etmek çok kolay — daha uzun bir şifre ya da birbiriyle ilgisiz birkaç kelime dene.',
+ 'Another profile already signs in with this name.': 'Başka bir profil zaten bu isimle giriş yapıyor.',
+ 'That invite code is not valid.': 'Bu davet kodu geçerli değil.',
+ 'Your current password is not right.': 'Mevcut şifren doğru değil.',
+ 'Your passkey could not be confirmed.': 'Geçiş anahtarın doğrulanamadı.',
+ 'This password is the only way into your profile, so it cannot be removed.': 'Bu şifre profiline girmenin tek yolu, bu yüzden kaldırılamaz.',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': 'Bu sıfırlama kodu yanlış ya da süresi dolmuş — yöneticinden yeni bir tane iste.',
+ 'This account has been disabled.': 'Bu hesap devre dışı bırakıldı.',
+ 'The server is busy — try again in a moment.': 'Sunucu meşgul — birazdan tekrar dene.',
'Each profile keeps its own plan, workouts & body weight.': 'Her profilin kendi planı, antrenmanları ve vücut ağırlığı vardır.',
'Account': 'Hesap',
'Sign out?': 'Çıkış yapılsın mı?',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 5ad7f7998..ff4c0388a 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -290,6 +290,52 @@ export default {
"This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.": '此浏览器不支持通行密钥,且此服务器需要账户。请换用支持通行密钥的浏览器或设备。',
'Continue without account': '不用账号继续',
'Passkeys use {0} — no passwords.': '通行密钥使用{0}——没有密码。',
+ // --- password sign-in (#118) ---
+ 'Sign in with password': '用密码登录',
+ 'Password': '密码',
+ 'Passkey': '通行密钥',
+ 'Passkeys use {0}. A password works too, where passkeys do not.': '通行密钥使用{0}。在通行密钥无法使用的地方,也可以用密码。',
+ "This browser doesn't support passkeys — sign in with your name and password instead.": '此浏览器不支持通行密钥 — 请改用名字和密码登录。',
+ 'Use your profile name and the password you set for it.': '使用你的档案名字和你为它设置的密码。',
+ 'Have a reset code from your admin?': '有管理员给的重置码?',
+ 'Reset your password': '重置你的密码',
+ 'Enter the code your admin gave you and choose a new password. It signs you out everywhere else.': '输入管理员给你的代码,并设置新密码。你在其他所有地方都会被退出登录。',
+ 'Reset code': '重置码',
+ 'New password': '新密码',
+ 'Repeat the password': '再次输入密码',
+ 'Current password': '当前密码',
+ 'At least {0} characters. A few unrelated words make a good one.': '至少 {0} 个字符。几个互不相关的词就是一个好密码。',
+ 'Set password & sign in': '设置密码并登录',
+ 'Create profile': '创建档案',
+ 'Pick a name and a password. You sign in with both.': '选择一个名字和一个密码。你用两者一起登录。',
+ 'Enter your password.': '请输入你的密码。',
+ 'Enter the reset code.': '请输入重置码。',
+ 'The two passwords are not the same.': '两次输入的密码不一致。',
+ 'Set · sign in as “{0}”': '已设置 · 以“{0}”登录',
+ 'Not set — lets you sign in where passkeys do not work.': '未设置 — 可在通行密钥无法使用的地方登录。',
+ 'Set a password': '设置密码',
+ 'Change password': '更改密码',
+ 'Sign in as “{0}” with it on devices where passkeys do not work. Saving signs you out everywhere else, and paired phones have to be paired again.': '在通行密钥无法使用的设备上,用它以“{0}”登录。保存后你将在其他所有地方退出登录,已配对的手机需要重新配对。',
+ 'Confirm with passkey & save': '用通行密钥确认并保存',
+ 'Forgot it? Confirm with your passkey instead': '忘记了?改用你的通行密钥确认',
+ 'Password saved — you are signed out everywhere else.': '密码已保存 — 你已在其他所有地方退出登录。',
+ 'Remove password': '移除密码',
+ 'Remove your password?': '移除你的密码?',
+ 'Only your passkeys sign in to this profile afterwards.': '之后只能用你的通行密钥登录此档案。',
+ 'Password removed': '密码已移除',
+ 'Wrong name or password.': '名字或密码错误。',
+ 'Too many attempts — try again {0}.': '尝试次数过多 — 请{0}再试。',
+ 'Use at least {0} characters.': '至少使用 {0} 个字符。',
+ 'That password is too long.': '这个密码太长了。',
+ 'That password is too easy to guess — try a longer one, or a few unrelated words.': '这个密码太容易被猜到 — 试试更长的密码,或几个互不相关的词。',
+ 'Another profile already signs in with this name.': '已有另一个档案用这个名字登录。',
+ 'That invite code is not valid.': '这个邀请码无效。',
+ 'Your current password is not right.': '你当前的密码不对。',
+ 'Your passkey could not be confirmed.': '无法确认你的通行密钥。',
+ 'This password is the only way into your profile, so it cannot be removed.': '这个密码是进入你档案的唯一方式,因此不能移除。',
+ 'That reset code is wrong or has expired — ask your admin for a new one.': '这个重置码错误或已过期 — 请向管理员要一个新的。',
+ 'This account has been disabled.': '此账户已被停用。',
+ 'The server is busy — try again in a moment.': '服务器繁忙 — 请稍后再试。',
'Each profile keeps its own plan, workouts & body weight.': '每个档案有自己的计划、训练和体重。',
'Account': '账号',
'Sign out?': '退出登录?',
diff --git a/frontend/src/views/Admin.jsx b/frontend/src/views/Admin.jsx
index 7af4e69f8..792036dfb 100644
--- a/frontend/src/views/Admin.jsx
+++ b/frontend/src/views/Admin.jsx
@@ -30,9 +30,24 @@ const rel = ts => {
}
const dur = ms => { const m = Math.max(0, Math.floor(ms / 60000)); return m < 60 ? m + ' min' : Math.floor(m / 60) + ' h ' + (m % 60) + ' min' }
+// The one time the reset code is visible. Locked, so a tap beside the sheet cannot lose it
+// before it has been copied or written down.
+function ResetCodeSheet({ name, code, expires, close }) {
+ const toast = useUI(s => s.toast)
+ const copy = () => { navigator.clipboard?.writeText(code).catch(() => {}); toast('Copied') }
+ return <>
+ <h3>Reset code for {name}</h3>
+ <div className="adm-lead">Give them this code. They choose “Sign in with password” → “Have a reset code from your admin?”, enter their name <b>{name}</b>, the code and a new password. It works once, until {new Date(expires).toLocaleString()}, and will not be shown again.</div>
+ <button className="adm-code" style={{ fontSize: 22, width: '100%', padding: '14px 0' }} onClick={copy} aria-label="copy code">{code}</button>
+ <div style={{ height: 12 }} />
+ <Button variant="primary" onClick={close}>Done</Button>
+ </>
+}
+
function UserDetail({ id, onChanged, close }) {
const [d, setD] = useState(null)
const toast = useUI(s => s.toast)
+ const openSheet = useUI(s => s.openSheet)
useEffect(() => { api('/api/admin/user?id=' + encodeURIComponent(id)).then(setD).catch(e => toast(e.message)) }, [id])
if (!d) return <div className="muted small">Loading…</div>
const u = d.user
@@ -61,12 +76,26 @@ function UserDetail({ id, onChanged, close }) {
.then(() => { toast(disabled ? 'User disabled' : 'User enabled'); onChanged(); close() })
.catch(e => toast(e.message))
}
+ // Password sign-in (#118): the server only sends `password` when the instance offers it. The
+ // code comes back once, is shown once, and is never stored anywhere but as a hash.
+ const pwInstance = typeof u.password === 'boolean'
+ const resetPassword = () => confirmSheet({
+ title: 'Reset ' + u.name + '’s password?',
+ message: 'You get a one-time code to hand them. Their current password stops working now and they are signed out everywhere; their passkeys keep working. They set a new password with the code under “Sign in with password”. It is shown once and is valid for 24 hours.',
+ confirmText: 'Create reset code',
+ danger: true,
+ onConfirm: () => api('/api/admin/user/password-reset', { method: 'POST', body: JSON.stringify({ id: u.id }) })
+ .then(r => { onChanged(); close(); openSheet(done => <ResetCodeSheet name={r.name} code={r.code} expires={r.expires} close={done} />, { locked: true }) })
+ .catch(e => toast(e.message)),
+ })
return <>
<h3 className="capitalize">{u.name}</h3>
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '8px 0 12px' }}>
{u.admin && <span className="adm-pill acc">admin</span>}
{u.disabled && <span className="adm-pill bad">disabled</span>}
{u.invitedBy && <span className="adm-pill">invite {u.invitedBy}</span>}
+ {u.password && <span className="adm-pill">password</span>}
+ {u.resetUntil && <span className="adm-pill acc">reset code until {new Date(u.resetUntil).toLocaleString()}</span>}
<span className="adm-pill">joined {u.created ? fmtDate(u.created.slice(0, 10)) : '—'}</span>
</div>
<div className="tiles" style={{ textAlign: 'left' }}>
@@ -100,6 +129,12 @@ function UserDetail({ id, onChanged, close }) {
})}>Delete account</button>
<button className="btn" style={{ marginBottom: 4 }} onClick={exportUser}>Download their data</button>
<div className="adm-hint">Deleting removes the account and every trace of its training history from this server.</div>
+ {pwInstance && <>
+ <button className="btn" style={{ margin: '14px 0 4px' }} onClick={resetPassword}>Reset password</button>
+ <div className="adm-hint">{u.password
+ ? 'For a forgotten password: a one-time code lets them choose a new one. Their current password stops working at once.'
+ : 'No password yet. A one-time code lets them set one — the way back in after losing their only passkey.'}</div>
+ </>}
</>}
<h4 className="sec">Workout history</h4>
{workouts.length ? <div className="list" style={{ gap: 0 }}>
diff --git a/frontend/src/views/Admin.password.test.jsx b/frontend/src/views/Admin.password.test.jsx
new file mode 100644
index 000000000..8a88f0d14
--- /dev/null
+++ b/frontend/src/views/Admin.password.test.jsx
@@ -0,0 +1,114 @@
+// @vitest-environment happy-dom
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import Admin from './Admin.jsx'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+/* The admin's half of password sign-in (#118): "Reset password" in a user's drill-down, which
+ asks first and then shows the one-time code exactly once, on a sheet that a stray tap cannot
+ close. Only an instance with password sign-in sends `password` on the user, and only then is
+ any of this there. */
+const mocks = vi.hoisted(() => ({ answers: {}, sheets: [], posts: [], confirm: vi.fn() }))
+vi.mock('../lib/api.js', () => ({
+ api: (path, init) => {
+ if (init?.method === 'POST') mocks.posts.push({ path, body: JSON.parse(init.body) })
+ const key = path.split('?')[0]
+ return key in mocks.answers ? Promise.resolve(mocks.answers[key]) : Promise.reject(new Error('not found'))
+ }
+}))
+vi.mock('../store/useStore.js', () => {
+ const snap = () => ({ user: { id: 'adm', name: 'Admin', admin: true }, S: {} })
+ const useStore = selector => selector ? selector(snap()) : snap()
+ useStore.getState = snap
+ return { useStore }
+})
+vi.mock('../store/useUI.js', () => {
+ const snap = () => ({ toast: () => {}, openSheet: (render, opts) => mocks.sheets.push({ render, opts }) })
+ const useUI = selector => selector ? selector(snap()) : snap()
+ useUI.getState = snap
+ return { useUI }
+})
+vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
+vi.mock('../sheets.jsx', () => ({ confirmSheet: (...a) => mocks.confirm(...a) }))
+vi.mock('./AdminCoach.jsx', () => ({ default: () => null }))
+
+const mounted = []
+function render(el) {
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push(root)
+ act(() => root.render(el))
+ return host
+}
+const settle = () => act(() => new Promise(r => setTimeout(r, 0)))
+const button = (host, text) => [...host.querySelectorAll('button')].find(b => b.textContent === text)
+
+const detail = extra => ({
+ user: { id: 'u1', name: 'Mallory', created: '2026-09-01T00:00:00Z', disabled: false, admin: false, ...extra },
+ unit: 'kg', lastSync: null, routines: [], bodyweight: [], workouts: []
+})
+async function openMallory() {
+ const page = render(<Admin />)
+ await settle()
+ act(() => [...page.querySelectorAll('.item')].find(el => el.textContent.includes('Mallory')).click())
+ const sheet = render(mocks.sheets.at(-1).render(() => {}))
+ await settle()
+ return sheet
+}
+
+beforeEach(() => {
+ document.body.innerHTML = ''
+ mocks.sheets.length = 0
+ mocks.posts.length = 0
+ mocks.confirm.mockClear()
+ mocks.answers = {
+ '/api/admin/users': { users: [{ id: 'u1', name: 'Mallory', workouts: 0, lastSync: null, disabled: false }], invite_only: false },
+ '/api/admin/invites': { invites: [] },
+ '/api/admin/audit': { events: [], total: 0, enabled: true, retention: { days: 90 }, ip_mode: 'off' },
+ '/api/admin/user/password-reset': { ok: true, name: 'Mallory', code: 'K7WQ-2MZP-4HXA', expires: Date.now() + 86400000 },
+ }
+})
+afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) })
+
+describe('Admin → Reset password', () => {
+ it('is not there on an instance without password sign-in', async () => {
+ mocks.answers['/api/admin/user'] = detail()
+ const sheet = await openMallory()
+ expect(button(sheet, 'Disable account')).toBeTruthy()
+ expect(button(sheet, 'Reset password')).toBeUndefined()
+ })
+
+ it('asks first, then shows the one-time code once, on a sheet that stays until "Done"', async () => {
+ mocks.answers['/api/admin/user'] = detail({ password: true, resetUntil: null })
+ const sheet = await openMallory()
+ expect([...sheet.querySelectorAll('.adm-pill')].map(p => p.textContent)).toContain('password')
+ act(() => button(sheet, 'Reset password').click())
+ expect(mocks.confirm).toHaveBeenCalledTimes(1)
+ const opts = mocks.confirm.mock.calls[0][0]
+ expect(opts.confirmText).toBe('Create reset code')
+ expect(opts.message).toMatch(/current password stops working/)
+ expect(mocks.posts).toEqual([]) // nothing happens before the confirm
+
+ const before = mocks.sheets.length
+ await act(async () => { await opts.onConfirm() })
+ await settle()
+ expect(mocks.posts).toEqual([{ path: '/api/admin/user/password-reset', body: { id: 'u1' } }])
+ const shown = mocks.sheets.slice(before).find(s => s.opts?.locked)
+ expect(shown).toBeTruthy()
+ const code = render(shown.render(() => {}))
+ expect(code.textContent).toContain('K7WQ-2MZP-4HXA')
+ expect(code.textContent).toContain('Mallory')
+ expect(button(code, 'Done')).toBeTruthy()
+ })
+
+ it('offers it to a profile with no password too — the way back after a lost passkey', async () => {
+ mocks.answers['/api/admin/user'] = detail({ password: false, resetUntil: Date.now() + 3600000 })
+ const sheet = await openMallory()
+ expect(button(sheet, 'Reset password')).toBeTruthy()
+ expect(sheet.textContent).toMatch(/lets them set one/)
+ expect(sheet.textContent).toMatch(/reset code until/)
+ })
+})
diff --git a/frontend/src/views/Login.jsx b/frontend/src/views/Login.jsx
index f373ff762..0a7c71b85 100644
--- a/frontend/src/views/Login.jsx
+++ b/frontend/src/views/Login.jsx
@@ -7,8 +7,9 @@ import { DEMO, REPO } from '../lib/demo.js'
import { guestAllowed } from '../lib/guest.js'
import { useState, useRef, useEffect } from 'react'
import Icon from '../components/Icon.jsx'
-import { Button } from '../components/ui.jsx'
+import { Button, Segmented } from '../components/ui.jsx'
import { askAddDeviceData } from '../sheets.jsx'
+import { passwordOn, PasswordRegisterForm, openPasswordSignIn } from '../components/PasswordAuth.jsx'
function RegisterSheet({ close }) {
const { setUser, pushState, pullState, loadConfig } = useStore()
@@ -16,6 +17,10 @@ function RegisterSheet({ close }) {
const [name, setName] = useState('')
const [code, setCode] = useState('')
const inviteOnly = !!config?.invite_only
+ // A password is offered only where the instance allows it (#118), and is the only choice in a
+ // browser that cannot make a passkey. Where both work, the passkey stays the first one.
+ const pwOn = passwordOn(config)
+ const [how, setHow] = useState(webauthnOK() ? 'passkey' : 'password')
const ref = useRef(null)
useEffect(() => { setTimeout(() => ref.current?.focus(), 250) }, [])
// Boot already fetched this; retry here only if that attempt failed, so the invite field still
@@ -32,8 +37,20 @@ function RegisterSheet({ close }) {
else { await pullState(); useUI.getState().toast(t('Welcome, {0}', u.name)) }
} catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') useUI.getState().toast(e.message || t('Registration failed')) }
}
+ const choose = pwOn && webauthnOK() && <>
+ <Segmented options={[{ value: 'passkey', label: t('Passkey'), icon: 'person' }, { value: 'password', label: t('Password'), icon: 'key' }]}
+ value={how} onChange={setHow} />
+ <div style={{ height: 12 }} />
+ </>
+ if (pwOn && how === 'password') return <>
+ <h3>{t('Create your profile')}</h3>
+ {choose}
+ <div className="muted small" style={{ marginBottom: 14 }}>{t('Pick a name and a password. You sign in with both.')}</div>
+ <PasswordRegisterForm close={close} inviteOnly={inviteOnly} name={name} setName={setName} code={code} setCode={setCode} />
+ </>
return <>
<h3>{t('Create your profile')}</h3>
+ {choose}
<div className="muted small" style={{ marginBottom: 14 }}>{t('Pick a name, then confirm with {0}. The passkey is saved in your device — no password needed.', BIO)}</div>
<input ref={ref} className="input" placeholder={t('Your name')} maxLength={40} value={name} onChange={e => setName(e.target.value)} />
{inviteOnly && <>
@@ -51,6 +68,8 @@ export default function Login() {
const { setUser, adoptProfile, setGuest } = useStore()
const config = useStore(s => s.config)
const canGuest = guestAllowed(config)
+ const pwOn = passwordOn(config)
+ const register = () => useUI.getState().openSheet(close => <RegisterSheet close={close} />)
const signIn = async () => {
try { const u = await passkeyLogin(); setUser(u); await adoptProfile(askAddDeviceData); useUI.getState().toast(t('Welcome back, {0}', u.name)) }
catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') useUI.getState().toast(e.message || t('Sign-in failed')) }
@@ -83,7 +102,16 @@ export default function Login() {
{webauthnOK() ? <>
<Button variant="primary" icon="person" onClick={signIn}>{t('Sign in with passkey')}</Button>
<div style={{ height: 10 }} />
- <Button icon="sparkles" onClick={() => useUI.getState().openSheet(close => <RegisterSheet close={close} />)}>{t('Create new profile')}</Button>
+ {pwOn && <><Button icon="key" onClick={() => openPasswordSignIn()}>{t('Sign in with password')}</Button><div style={{ height: 10 }} /></>}
+ <Button icon="sparkles" onClick={register}>{t('Create new profile')}</Button>
+ {canGuest && <div style={{ height: 10 }} />}
+ </> : pwOn ? <>
+ {/* Plain http on a LAN address, or a browser without passkey support: the password is
+ the way in, and the only way to create a profile from here. */}
+ <div className="card small muted" style={{ textAlign: 'left', marginBottom: 14 }}>{t("This browser doesn't support passkeys — sign in with your name and password instead.")}</div>
+ <Button variant="primary" icon="key" onClick={() => openPasswordSignIn()}>{t('Sign in with password')}</Button>
+ <div style={{ height: 10 }} />
+ <Button icon="sparkles" onClick={register}>{t('Create new profile')}</Button>
{canGuest && <div style={{ height: 10 }} />}
</> : <div className="card small muted" style={{ textAlign: 'left' }}>{canGuest
? t("This browser doesn't support passkeys — you can still use openGym locally on this device.")
@@ -91,7 +119,7 @@ export default function Login() {
// so say that plainly instead of offering a local profile that cannot be created.
: t("This browser doesn't support passkeys, and this instance requires an account. Try a browser or device with passkey support.")}</div>}
{canGuest && <Button variant="ghost" className="dim" onClick={() => setGuest(true)}>{t('Continue without account')}</Button>}
- <div className="dim small" style={{ marginTop: 26, lineHeight: 1.5 }}>{t('Passkeys use {0} — no passwords.', BIO)}<br />{t('Each profile keeps its own plan, workouts & body weight.')}</div>
+ <div className="dim small" style={{ marginTop: 26, lineHeight: 1.5 }}>{pwOn ? t('Passkeys use {0}. A password works too, where passkeys do not.', BIO) : t('Passkeys use {0} — no passwords.', BIO)}<br />{t('Each profile keeps its own plan, workouts & body weight.')}</div>
</div>
)
}
diff --git a/frontend/src/views/Login.password.test.jsx b/frontend/src/views/Login.password.test.jsx
new file mode 100644
index 000000000..2e6ca0b08
--- /dev/null
+++ b/frontend/src/views/Login.password.test.jsx
@@ -0,0 +1,102 @@
+// @vitest-environment happy-dom
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import Login from './Login.jsx'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+/* The sign-in screen with password sign-in (#118). Only an instance that advertises
+ `password_login` shows any of it; there, a browser without passkey support finally has a way
+ in instead of being told to stay local, and creating a profile can use a password. */
+const mocks = vi.hoisted(() => {
+ const state = { webauthn: true, config: null, sheets: [] }
+ state.snapshot = () => ({
+ config: state.config, S: {},
+ setUser: vi.fn(), adoptProfile: vi.fn(), setGuest: vi.fn(), loadConfig: vi.fn(async () => state.config),
+ pushState: vi.fn(), pullState: vi.fn(),
+ })
+ return state
+})
+vi.mock('../store/useStore.js', () => {
+ const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
+ useStore.getState = mocks.snapshot
+ return { useStore, hasData: () => false }
+})
+vi.mock('../store/useUI.js', () => {
+ const snap = () => ({ toast: vi.fn(), openSheet: render => { mocks.sheets.push(render); return {} } })
+ const useUI = selector => selector ? selector(snap()) : snap()
+ useUI.getState = snap
+ return { useUI }
+})
+vi.mock('../lib/api.js', () => ({
+ webauthnOK: () => mocks.webauthn, passkeyLogin: vi.fn(), passkeyRegister: vi.fn(), BIO: 'your fingerprint',
+ api: vi.fn(), passkeyAssertion: vi.fn(), passwordLogin: vi.fn(), passwordRegister: vi.fn(), passwordResetRedeem: vi.fn(),
+}))
+vi.mock('../lib/demo.js', () => ({ DEMO: false, REPO: 'https://example.invalid' }))
+vi.mock('../sheets.jsx', () => ({ askAddDeviceData: vi.fn(), confirmSheet: vi.fn() }))
+
+const mounted = []
+function mount(el) {
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push({ root, host })
+ act(() => root.render(el))
+ return host
+}
+const buttons = host => [...host.querySelectorAll('button')].map(b => b.textContent)
+const button = (host, text) => [...host.querySelectorAll('button')].find(b => b.textContent === text)
+
+beforeEach(() => { mocks.webauthn = true; mocks.config = null; mocks.sheets.length = 0 })
+afterEach(() => { act(() => { mounted.splice(0).forEach(({ root, host }) => { root.unmount(); host.remove() }) }) })
+
+describe('Login with password sign-in', () => {
+ it('an instance without it looks exactly as before', () => {
+ const page = mount(<Login />)
+ expect(buttons(page)).not.toContain('Sign in with password')
+ expect(page.textContent).toContain('Passkeys use your fingerprint — no passwords.')
+ mocks.webauthn = false
+ const noPasskeys = mount(<Login />)
+ expect(noPasskeys.textContent).toContain("This browser doesn't support passkeys — you can still use openGym locally on this device.")
+ expect(buttons(noPasskeys)).not.toContain('Sign in with password')
+ })
+
+ it('next to passkeys it is a second button, and the footer no longer says "no passwords"', () => {
+ mocks.config = { password_login: true, allow_guest: true }
+ const page = mount(<Login />)
+ expect(buttons(page).slice(0, 3)).toEqual(['Sign in with passkey', 'Sign in with password', 'Create new profile'])
+ expect(page.textContent).toContain('Passkeys use your fingerprint. A password works too, where passkeys do not.')
+ act(() => button(page, 'Sign in with password').click())
+ const sheet = mount(mocks.sheets[0](() => {}))
+ expect(sheet.querySelector('h3').textContent).toBe('Sign in with password')
+ expect(sheet.querySelector('input[autocomplete="current-password"]')).toBeTruthy()
+ })
+
+ it('a browser without passkeys gets a way in instead of "stay local"', () => {
+ mocks.webauthn = false
+ mocks.config = { password_login: true, allow_guest: false }
+ const page = mount(<Login />)
+ expect(page.textContent).toContain("This browser doesn't support passkeys — sign in with your name and password instead.")
+ expect(page.textContent).not.toContain('Try a browser or device with passkey support.')
+ expect(buttons(page)).toEqual(['Sign in with password', 'Create new profile'])
+ // Creating a profile here can only mean a password: no passkey/password choice to make.
+ act(() => button(page, 'Create new profile').click())
+ const sheet = mount(mocks.sheets[0](() => {}))
+ expect(sheet.querySelector('.seg')).toBeNull()
+ expect(sheet.querySelector('input[placeholder="Repeat the password"]')).toBeTruthy()
+ expect(buttons(sheet)).toContain('Create profile')
+ })
+
+ it('where both work, creating a profile starts on the passkey and switches to a password', () => {
+ mocks.config = { password_login: true, invite_only: true }
+ const page = mount(<Login />)
+ act(() => button(page, 'Create new profile').click())
+ const sheet = mount(mocks.sheets[0](() => {}))
+ expect(buttons(sheet)).toContain('Create passkey')
+ act(() => button(sheet, 'Password').click())
+ expect(buttons(sheet)).toContain('Create profile')
+ expect(sheet.querySelector('input[placeholder="Invite code"]')).toBeTruthy()
+ expect(sheet.querySelector('input[autocomplete="new-password"]')).toBeTruthy()
+ })
+})
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index a82efcf33..96c027abe 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -17,7 +17,8 @@ import { checkForUpdate, downloadAndInstall } from '../lib/update.js'
import { forgetCoach } from '../lib/coach-api.js'
import { starterPlanSheet, confirmSheet, importFromApp, importFromHevy, equipmentProfileSheet, menuSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
-import { ServerSyncSection, KeptChangesRows, leaveServer, connectServer, signInAgain } from '../components/ServerSync.jsx'
+import { ServerSyncSection, KeptChangesRows, leaveServer, connectServer, passkeySignIn } from '../components/ServerSync.jsx'
+import { passwordOn, PasswordRow, openPasswordSignIn, openPasswordRegister } from '../components/PasswordAuth.jsx'
import { Section, Row, SelectRow, Switch, Segmented, Button, TextField } from '../components/ui.jsx'
export default function Settings() {
@@ -25,6 +26,8 @@ export default function Settings() {
const S = useStore(s => s.S)
const user = useStore(s => s.user)
const coachLocal = useStore(s => s.coachLocal)
+ // Name-and-password sign-in, where the instance offers it (#118).
+ const pwOn = passwordOn(useStore(s => s.config))
const { update, replaceState, setUser, pullState, pushState, resetDemo } = useStore()
const toast = useUI(s => s.toast)
const fileRef = useRef(null)
@@ -226,11 +229,18 @@ export default function Settings() {
{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}
<Row icon="link" iconTint="var(--blue)" title={t('Pair the mobile app')} subtitle={t('Connect the openGym app on your phone to this account.')} accessory="chevron"
onClick={() => useUI.getState().openSheet(close => <PairSheet close={close} />)} />
+ {pwOn && <PasswordRow />}
<Row icon="signOut" iconTint="var(--red)" title={t('Sign out')} danger onClick={signOutHere} />
<Row icon="shield" iconTint="var(--red)" title={t('Sign out everywhere')} subtitle={t('Ends this profile’s sessions on all your devices.')} danger onClick={signOutEverywhere} />
</> : webauthnOK() ? <>
<Row icon="sparkles" iconTint="var(--acc)" title={t('Create passkey profile')} subtitle={t('Keeps your data safe and separate per person.')} accessory="chevron" onClick={registerHere} />
- <Row icon="person" iconTint="var(--blue)" title={t('Sign in with passkey')} accessory="chevron" onClick={signInAgain} />
+ <Row icon="person" iconTint="var(--blue)" title={t('Sign in with passkey')} accessory="chevron" onClick={passkeySignIn} />
+ {pwOn && <Row icon="key" iconTint="var(--orange)" title={t('Sign in with password')} accessory="chevron" onClick={() => openPasswordSignIn()} />}
+ <KeptChangesRows />
+ </> : pwOn ? <>
+ {/* No passkeys in this browser (plain http on a LAN address, say): a password is the way in. */}
+ <Row icon="sparkles" iconTint="var(--acc)" title={t('Create new profile')} subtitle={t('Keeps your data safe and separate per person.')} accessory="chevron" onClick={openPasswordRegister} />
+ <Row icon="key" iconTint="var(--orange)" title={t('Sign in with password')} accessory="chevron" onClick={() => openPasswordSignIn()} />
<KeptChangesRows />
</> : <>
<Row icon="lock" iconTint="var(--grey)" title={t('Passkeys not supported in this browser.')} />
diff --git a/frontend/src/views/Settings.password.test.jsx b/frontend/src/views/Settings.password.test.jsx
new file mode 100644
index 000000000..402d5d082
--- /dev/null
+++ b/frontend/src/views/Settings.password.test.jsx
@@ -0,0 +1,122 @@
+// @vitest-environment happy-dom
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import Settings from './Settings.jsx'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+/* Settings with password sign-in (#118): the Password row in a signed-in browser's account
+ section, the ways in for a guest — including one in a browser that cannot make a passkey —
+ and "Sign in" after the server ended a session, which now asks which way before prompting
+ for a passkey the account may not have. None of it appears unless the instance says
+ `password_login`. */
+const mocks = vi.hoisted(() => {
+ // `kept` is one array for good: KeptChangesRows re-asks whenever the function changes, and a
+ // fresh [] per answer would re-render it forever.
+ const state = { S: null, user: null, sync: null, config: null, webauthn: true, sheets: [], kept: [] }
+ state.passkeyLogin = vi.fn(async () => ({ id: 'u1', name: 'andi' }))
+ state.api = vi.fn(async path => (path === '/api/account/password' ? { set: false, setAt: null, passkeys: 1, name: 'andi', nameTaken: false } : {}))
+ state.snapshot = () => ({
+ S: state.S, user: state.user, sync: state.sync, config: state.config, coachLocal: null,
+ update: vi.fn(), replaceState: vi.fn(), setUser: vi.fn(), pullState: vi.fn(), pushState: vi.fn(), resetDemo: vi.fn(),
+ syncNow: vi.fn(), unsyncedChanges: () => ({ owed: false, count: 0 }), keptChanges: async () => state.kept,
+ disconnectServer: vi.fn(), signOut: vi.fn(), signOutAll: vi.fn(), adoptProfile: vi.fn(),
+ })
+ return state
+})
+vi.mock('../store/useStore.js', () => {
+ const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
+ useStore.getState = mocks.snapshot
+ return { useStore, DEF: { reminder: { time: '17:30' } }, hasData: () => false }
+})
+vi.mock('../store/useUI.js', () => {
+ const snap = () => ({ toast: vi.fn(), openSheet: (render, opts) => { mocks.sheets.push({ render, opts }); return {} } })
+ const useUI = selector => selector ? selector(snap()) : snap()
+ useUI.getState = snap
+ return { useUI }
+})
+vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
+vi.mock('../lib/api.js', () => ({
+ api: (...a) => mocks.api(...a), webauthnOK: () => mocks.webauthn, passkeyLogin: (...a) => mocks.passkeyLogin(...a), passkeyRegister: vi.fn(), IS_ANDROID: false,
+ passkeyAssertion: vi.fn(), passwordLogin: vi.fn(), passwordRegister: vi.fn(), passwordResetRedeem: vi.fn(),
+}))
+vi.mock('../lib/push.js', () => ({ pushSupported: () => false, enablePush: vi.fn(), disablePush: vi.fn(), sendTestPush: vi.fn() }))
+vi.mock('../lib/wakelock.js', () => ({ wakeLockSupported: () => false }))
+vi.mock('../lib/mobile.js', () => ({ MOBILE: false, isAndroid: () => Promise.resolve(false), shareExport: vi.fn(), syncReminder: vi.fn() }))
+vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))
+vi.mock('../sheets.jsx', () => ({
+ starterPlanSheet: vi.fn(), confirmSheet: vi.fn(), importFromApp: vi.fn(),
+ importFromHevy: vi.fn(), equipmentProfileSheet: vi.fn(), menuSheet: vi.fn(), askAddDeviceData: vi.fn(),
+}))
+
+globalThis.__APP_VERSION__ ??= 'test'
+
+const mounted = []
+function mount(el) {
+ const host = document.createElement('div')
+ document.body.appendChild(host)
+ const root = createRoot(host)
+ mounted.push({ root, host })
+ act(() => root.render(el))
+ return host
+}
+const settle = () => act(() => new Promise(r => setTimeout(r, 0)))
+const section = (page, title) => [...page.querySelectorAll('.sect')].find(s => s.querySelector('.sect-t')?.textContent === title)
+const titles = el => [...el.querySelectorAll('.lrow-t')].map(t => t.textContent)
+const rowByTitle = (el, title) => [...el.querySelectorAll('.lrow')].find(r => r.querySelector('.lrow-t')?.textContent === title)
+
+beforeEach(() => {
+ mocks.S = { unit: 'kg', restSec: 90, restPauseSec: 15, sound: false, effort: 'none', gifSize: 'full', workouts: [], routines: [], exWeights: {} }
+ mocks.user = { id: 'u1', name: 'andi' }
+ mocks.sync = { status: 'ok', offline: false, pending: false, auth: false, lastError: null, lastSynced: Date.now(), server: null }
+ mocks.config = { password_login: true }
+ mocks.webauthn = true
+ mocks.sheets.length = 0
+ mocks.passkeyLogin.mockClear()
+})
+afterEach(() => { act(() => { mounted.splice(0).forEach(({ root, host }) => { root.unmount(); host.remove() }) }) })
+
+describe('Settings with password sign-in', () => {
+ it('a signed-in browser gets a Password row in Account — and none on an instance without it', async () => {
+ const page = mount(<Settings />)
+ await settle()
+ const account = section(page, 'Account')
+ expect(titles(account)).toContain('Password')
+ expect(rowByTitle(account, 'Password').textContent).toContain('Not set — lets you sign in where passkeys do not work.')
+
+ mocks.config = null
+ const off = mount(<Settings />)
+ await settle()
+ expect(titles(section(off, 'Account'))).not.toContain('Password')
+ })
+
+ it('a guest in a browser without passkeys can create a profile and sign in with a password', () => {
+ mocks.user = null
+ mocks.sync = null
+ mocks.webauthn = false
+ const page = mount(<Settings />)
+ const account = section(page, 'Account')
+ expect(titles(account)).toEqual(['Create new profile', 'Sign in with password'])
+ act(() => rowByTitle(account, 'Sign in with password').click())
+ const sheet = mount(mocks.sheets.at(-1).render(() => {}))
+ expect(sheet.querySelector('h3').textContent).toBe('Sign in with password')
+
+ mocks.config = null
+ const off = mount(<Settings />)
+ expect(titles(section(off, 'Account'))).toEqual(['Passkeys not supported in this browser.'])
+ })
+
+ it('"Sign in" after the server ended the session asks which way; the passkey is one tap on it', async () => {
+ mocks.sync = { status: 'auth', offline: false, pending: true, auth: true, lastError: { status: 401 }, lastSynced: 0, server: null }
+ const page = mount(<Settings />)
+ const row = rowByTitle(section(page, 'Server & sync'), 'Sign in')
+ expect(row).toBeTruthy()
+ act(() => row.click())
+ expect(mocks.passkeyLogin).not.toHaveBeenCalled()
+ const sheet = mount(mocks.sheets.at(-1).render(() => {}))
+ const passkey = [...sheet.querySelectorAll('button')].find(b => b.textContent === 'Sign in with passkey')
+ await act(async () => { passkey.click() })
+ expect(mocks.passkeyLogin).toHaveBeenCalledTimes(1)
+ })
+})