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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Admin dashboard: Recovery code, and the new events in the activity log (#584)
Duarte Santosf26bb5b794ac
diff --git a/frontend/src/lib/audit.js b/frontend/src/lib/audit.jsindex 32cff626e..bbb390232 100644--- a/frontend/src/lib/audit.js+++ b/frontend/src/lib/audit.js@@ -51,6 +51,10 @@ const LABELS = {'auth.link.create': 'Made a one-time code for another device','auth.link.ok': 'Added a device with a one-time code','auth.link.fail': 'Adding a device with a code failed',+ // Recovery codes (#584): made by an admin or by the server's own command, used on a new device.+ 'auth.recovery.ok': 'Got back in with a recovery code',+ 'admin.recovery.create': 'Made a recovery code',+ 'server.recovery.create': 'A recovery code was made on the server',// The owner's proof (current password or a passkey) for one of the changes below was refused.'auth.proof.fail': 'Confirming a change failed',// The password throttle paused an address; `msg` says for what (password, signup).@@ -98,6 +102,8 @@ const REASONS = {'reset-invalid': 'wrong or expired reset code','link-invalid': 'wrong, used or expired device code','passkey-limit': 'the profile already has as many passkeys as it can hold',+ // An `admin.denied` for a recovery code: only the owner makes one for an admin (#584).+ 'recovery': 'a recovery code for an admin, which only the owner can make',// What an `auth.throttled` pause was for.'password': 'wrong passwords or reset codes','signup': 'wrong invite codes on password signup',diff --git a/frontend/src/views/Admin.jsx b/frontend/src/views/Admin.jsxindex 3264534fc..50f9fc572 100644--- a/frontend/src/views/Admin.jsx+++ b/frontend/src/views/Admin.jsx@@ -44,7 +44,21 @@ function ResetCodeSheet({ name, email, code, expires, close }) {</>}+// The one time a recovery code (#584) is visible. Locked like the reset code's sheet.+function RecoveryCodeSheet({ name, code, expires, close }) {+ const toast = useUI(s => s.toast)+ const copy = () => { navigator.clipboard?.writeText(code).catch(() => {}); toast('Copied') }+ return <>+ <h3>Recovery code for {name}</h3>+ <div className="adm-lead">Give them this code. On the sign-in screen they tap “Lost access?” → “I have a code” (or “Use a code from your other device”) and enter it; the device they use gets a new passkey for <b>{name}</b> and is signed in. In the phone app they do this in a browser first, then pair the app again. 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, viewerOwner, onChanged, close }) {+ const me = useStore(s => s.user)const [d, setD] = useState(null)const toast = useUI(s => s.toast)const openSheet = useUI(s => s.openSheet)@@ -100,6 +114,18 @@ function UserDetail({ id, viewerOwner, onChanged, close }) {.then(r => { onChanged(); close(); openSheet(done => <ResetCodeSheet name={r.name} email={u.email} code={r.code} expires={r.expires} close={done} />, { locked: true }) }).catch(e => toast(e.message)),})+ // A recovery code (#584): any admin for a profile that is not an admin, the owner for an admin;+ // the owner's own comes from the server command (recover.js). Not for oneself.+ const canRecover = !u.owner && !u.disabled && u.id !== me?.id && (!u.admin || viewerOwner)+ const makeRecovery = () => confirmSheet({+ title: 'Recovery code for ' + u.name + '?',+ message: 'For someone who lost every way in: their devices and passkey are gone, and they have no password. You get a one-time code to hand them; the device they enter it on gets a new passkey. They are signed out everywhere now. Their passkeys and password stay. It is shown once and is valid for 24 hours.',+ confirmText: 'Create recovery code',+ danger: true,+ onConfirm: () => api('/api/admin/user/recovery', { method: 'POST', body: JSON.stringify({ id: u.id }) })+ .then(r => { onChanged(); close(); openSheet(done => <RecoveryCodeSheet 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' }}>@@ -110,6 +136,7 @@ function UserDetail({ id, viewerOwner, onChanged, close }) {{/* The sign-in e-mail (password instances only): shown to admins and nobody else. */}{u.email && <span className="adm-pill" title="sign-in e-mail">{u.email}</span>}{u.resetUntil && <span className="adm-pill acc">reset code until {new Date(u.resetUntil).toLocaleString()}</span>}+ {u.recoveryUntil && <span className="adm-pill acc">recovery code until {new Date(u.recoveryUntil).toLocaleString()}</span>}<span className="adm-pill">joined {u.created ? fmtDate(u.created.slice(0, 10)) : '–'}</span></div><div className="tiles" style={{ textAlign: 'start' }}>@@ -163,6 +190,11 @@ function UserDetail({ id, viewerOwner, onChanged, close }) {: 'No password yet. A one-time code lets them set one. That’s the way back in after losing their only passkey.'}</div></>}</>}+ {canRecover && <>+ <button className="btn" style={{ margin: '14px 0 4px' }} onClick={makeRecovery}>Recovery code</button>+ <div className="adm-hint">Lost every device and passkey? A one-time code gives a new device a passkey for this profile. Works with or without password sign-in.</div>+ </>}+ {u.owner && u.id !== me?.id && <div className="adm-hint" style={{ marginTop: 14 }}>A locked-out owner gets a recovery code from the server itself: <code>docker compose exec api node recover.js "{u.name}"</code></div>}<h4 className="sec">Workout history</h4>{workouts.length ? <div className="list" style={{ gap: 0 }}>{workouts.slice(0, 60).map(w => <div key={w.id} className="row between" style={{ padding: '9px 2px', borderBottom: '1px solid var(--sep)' }}>diff --git a/frontend/src/views/Admin.recovery.test.jsx b/frontend/src/views/Admin.recovery.test.jsxnew file mode 100644index 000000000..09d11e61a--- /dev/null+++ b/frontend/src/views/Admin.recovery.test.jsx@@ -0,0 +1,120 @@+// @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++/* "Recovery code" in a user's drill-down (#584): on every instance, for a profile that is not an+ admin; for an admin only when the viewer is the owner; never for the owner (whose way back is+ the server command) or oneself. Asks first, then shows the code exactly once, locked. */+const mocks = vi.hoisted(() => ({ answers: {}, sheets: [], posts: [], confirm: vi.fn(), me: { id: 'adm', name: 'Admin', admin: true } }))+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: mocks.me, 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.me = { id: 'adm', name: 'Admin', admin: true }+ 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/recovery': { ok: true, name: 'Mallory', code: 'K7WQ-2MZP-4HXA', expires: Date.now() + 86400000 },+ }+})+afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) })++describe('Admin → Recovery code', () => {+ it('is there for a plain profile on an instance without password sign-in, asks, then shows the code once, locked', async () => {+ mocks.answers['/api/admin/user'] = detail()+ const sheet = await openMallory()+ act(() => button(sheet, 'Recovery code').click())+ expect(mocks.confirm).toHaveBeenCalledTimes(1)+ const ask = mocks.confirm.mock.calls[0][0]+ expect(ask.title).toBe('Recovery code for Mallory?')+ expect(ask.message).not.toMatch(/—/)+ await act(async () => { await ask.onConfirm() })+ expect(mocks.posts).toEqual([{ path: '/api/admin/user/recovery', body: { id: 'u1' } }])+ const shown = mocks.sheets.at(-1)+ expect(shown.opts).toEqual({ locked: true })+ const code = render(shown.render(() => {}))+ expect(code.textContent).toContain('K7WQ-2MZP-4HXA')+ expect(code.textContent).toContain('Lost access?')+ })+ it('shows until when an unused one is good', async () => {+ mocks.answers['/api/admin/user'] = detail({ recoveryUntil: Date.now() + 3600000 })+ const sheet = await openMallory()+ expect(sheet.textContent).toContain('recovery code until')+ })+ it('for an admin only when the viewer is the owner', async () => {+ mocks.answers['/api/admin/user'] = detail({ admin: true })+ expect(button(await openMallory(), 'Recovery code')).toBeUndefined()+ })+ it('the owner may make one for an admin', async () => {+ mocks.answers['/api/admin/users'] = { users: [{ id: 'adm', name: 'Admin', owner: true, admin: true, workouts: 0 }, { id: 'u1', name: 'Mallory', workouts: 0, lastSync: null, disabled: false }], invite_only: false }+ mocks.answers['/api/admin/user'] = detail({ admin: true })+ expect(button(await openMallory(), 'Recovery code')).toBeTruthy()+ })+ it('never for the owner, who gets the server command instead, nor for a disabled profile', async () => {+ mocks.answers['/api/admin/user'] = detail({ admin: true, owner: true })+ const owner = await openMallory()+ expect(button(owner, 'Recovery code')).toBeUndefined()+ expect(owner.textContent).toContain('node recover.js')+ mocks.answers['/api/admin/user'] = detail({ disabled: true })+ expect(button(await openMallory(), 'Recovery code')).toBeUndefined()+ })+ it('never for oneself', async () => {+ mocks.me = { id: 'u1', name: 'Mallory', admin: true }+ mocks.answers['/api/admin/user'] = detail()+ expect(button(await openMallory(), 'Recovery code')).toBeUndefined()+ })+})