Sessions you can actually end, and invite codes worth guessing at

SECURITY.md documented three weaknesses two hours ago. Documented is better than
hidden; fixed is better than documented.

Sessions were a signed cookie the server trusted for a year, and /api/logout
only cleared it in the browser you clicked it in — a copy left on a shared
machine stayed good until it expired, and the only way to end it was deleting
./data/secret and signing out the entire instance. The cookie payload now
carries the user's session version, and POST /api/logout/all bumps it, which
kills every cookie that account ever had. Settings grows a "Sign out
everywhere" row for it.

Cookies already in the wild have no version field. They read as version 0 and
match a user who has never bumped, so nobody is signed out by this deploy and
db.json needs no migration — sv appears lazily on the first bump. Verified
against a server running the new code with a db.json shaped like the live one.

Session default drops from 365 days to 90, overridable with SESSION_DAYS. The
expiry is baked into each cookie when issued, so lowering it never cuts an
existing session short.

Invite codes go from 32 to 64 bits. The app has no rate limiting by design and
/api/register/options answers whether a code is valid, so the code itself has to
be the part not worth guessing. Existing codes still work — validation is an
exact string compare. Unused old ones are worth revoking and reissuing.

What did not change: no rate limiting, still the reverse proxy's job, still the
first caveat in SECURITY.md. requireUserVerification stays false — raising it
could refuse passkeys that already exist, which is a lockout, not a fix.
This commit is contained in:
Duarte Santos committed 2026-07-31 19:32:57 +02:00
1 parent 1574811af0
commit accc3c1038
16 files changed
+184 -37

No files matched your search

+6
View File
@@ -245,6 +245,12 @@ export default {
'Sign out?': 'Abmelden?',
'Your data is synced to your profile first, then cleared from this device.': 'Deine Daten werden erst mit dem Profil synchronisiert, dann von diesem Gerät entfernt.',
'Sign out': 'Abmelden',
'Sign out everywhere?': 'Überall abmelden?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Meldet dieses Profil auf allen Geräten ab, auch auf diesem. Deine Passkeys bleiben gültig — du kannst dich damit jederzeit wieder anmelden.',
'Sign out everywhere': 'Überall abmelden',
'Ends this profile’s sessions on all your devices.': 'Beendet die Sitzungen dieses Profils auf all deinen Geräten.',
'Signed out on all devices': 'Auf allen Geräten abgemeldet',
'Could not sign out everywhere — you are still signed in.': 'Abmelden auf allen Geräten fehlgeschlagen — du bist weiterhin angemeldet.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Gastmodus — Daten liegen nur in diesem Browser. Erstelle ein Passkey-Profil, um sie zu sichern und pro Person zu trennen.',
'Create passkey profile': 'Passkey-Profil erstellen',
'Passkeys not supported in this browser.': 'Passkeys werden in diesem Browser nicht unterstützt.',
+6
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': '¿Cerrar sesión?',
'Your data is synced to your profile first, then cleared from this device.': 'Tus datos se sincronizan primero con tu perfil y luego se borran de este dispositivo.',
'Sign out': 'Cerrar sesión',
'Sign out everywhere?': '¿Cerrar sesión en todos los dispositivos?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Cierra la sesión de este perfil en todos los dispositivos, incluido este. Tus passkeys siguen funcionando — puedes volver a iniciar sesión con ellas cuando quieras.',
'Sign out everywhere': 'Cerrar sesión en todos los dispositivos',
'Ends this profile’s sessions on all your devices.': 'Termina las sesiones de este perfil en todos tus dispositivos.',
'Signed out on all devices': 'Sesión cerrada en todos los dispositivos',
'Could not sign out everywhere — you are still signed in.': 'No se pudo cerrar la sesión en todos los dispositivos — sigues con la sesión iniciada.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Modo invitado — los datos viven solo en este navegador. Crea un perfil con passkey para protegerlos y separarlos por persona.',
'Create passkey profile': 'Crear perfil con passkey',
'Passkeys not supported in this browser.': 'Passkeys no compatibles con este navegador.',
+6
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Se déconnecter ?',
'Your data is synced to your profile first, then cleared from this device.': 'Tes données sont d’abord synchronisées avec ton profil, puis effacées de cet appareil.',
'Sign out': 'Se déconnecter',
'Sign out everywhere?': 'Se déconnecter partout ?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Déconnecte ce profil sur tous les appareils, y compris celui-ci. Tes passkeys restent valides — tu peux te reconnecter avec elles à tout moment.',
'Sign out everywhere': 'Se déconnecter partout',
'Ends this profile’s sessions on all your devices.': 'Met fin aux sessions de ce profil sur tous tes appareils.',
'Signed out on all devices': 'Déconnecté sur tous les appareils',
'Could not sign out everywhere — you are still signed in.': 'Impossible de se déconnecter partout — tu es toujours connecté.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Mode invité — les données ne vivent que dans ce navigateur. Crée un profil passkey pour les protéger et les séparer par personne.',
'Create passkey profile': 'Créer un profil passkey',
'Passkeys not supported in this browser.': 'Passkeys non prises en charge par ce navigateur.',
+6
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'साइन आउट करें?',
'Your data is synced to your profile first, then cleared from this device.': 'डेटा पहले प्रोफ़ाइल से सिंक होता है, फिर इस डिवाइस से हटता है।',
'Sign out': 'साइन आउट',
'Sign out everywhere?': 'हर जगह साइन आउट करें?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'इस डिवाइस सहित सभी डिवाइस पर इस प्रोफ़ाइल को साइन आउट करता है। आपकी पासकी काम करती रहेंगी — उनसे कभी भी दोबारा साइन इन करें।',
'Sign out everywhere': 'हर जगह साइन आउट करें',
'Ends this profile’s sessions on all your devices.': 'आपके सभी डिवाइस पर इस प्रोफ़ाइल के सेशन खत्म करता है।',
'Signed out on all devices': 'सभी डिवाइस पर साइन आउट हो गया',
'Could not sign out everywhere — you are still signed in.': 'हर जगह साइन आउट नहीं हो सका — आप अभी भी साइन इन हैं।',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'गेस्ट मोड — डेटा केवल इस ब्राउज़र में रहता है। सुरक्षित रखने और हर व्यक्ति के लिए अलग रखने हेतु पासकी प्रोफ़ाइल बनाएँ।',
'Create passkey profile': 'पासकी प्रोफ़ाइल बनाएँ',
'Passkeys not supported in this browser.': 'इस ब्राउज़र में पासकी समर्थित नहीं।',
+6
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Uscire?',
'Your data is synced to your profile first, then cleared from this device.': 'I dati vengono prima sincronizzati col profilo, poi rimossi da questo dispositivo.',
'Sign out': 'Esci',
'Sign out everywhere?': 'Uscire ovunque?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Esce da questo profilo su tutti i dispositivi, incluso questo. Le tue passkey restano valide — puoi rientrare con loro quando vuoi.',
'Sign out everywhere': 'Esci ovunque',
'Ends this profile’s sessions on all your devices.': 'Chiude le sessioni di questo profilo su tutti i tuoi dispositivi.',
'Signed out on all devices': 'Uscito da tutti i dispositivi',
'Could not sign out everywhere — you are still signed in.': 'Impossibile uscire ovunque — sei ancora connesso.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Modalità ospite — i dati vivono solo in questo browser. Crea un profilo passkey per proteggerli e separarli per persona.',
'Create passkey profile': 'Crea profilo passkey',
'Passkeys not supported in this browser.': 'Passkey non supportate in questo browser.',
+6
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': '로그아웃할까요?',
'Your data is synced to your profile first, then cleared from this device.': '데이터를 먼저 프로필에 동기화한 뒤 이 기기에서 지웁니다.',
'Sign out': '로그아웃',
'Sign out everywhere?': '모든 기기에서 로그아웃할까요?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': '이 기기를 포함해 모든 기기에서 이 프로필을 로그아웃합니다. 패스키는 그대로 사용할 수 있어 언제든 다시 로그인할 수 있습니다.',
'Sign out everywhere': '모든 기기에서 로그아웃',
'Ends this profile’s sessions on all your devices.': '모든 기기에서 이 프로필의 세션을 종료합니다.',
'Signed out on all devices': '모든 기기에서 로그아웃했습니다',
'Could not sign out everywhere — you are still signed in.': '모든 기기에서 로그아웃하지 못했습니다 — 아직 로그인 상태입니다.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': '게스트 모드 — 데이터가 이 브라우저에만 저장됩니다. 패스키 프로필을 만들어 안전하게 보관하고 사람별로 분리하세요.',
'Create passkey profile': '패스키 프로필 만들기',
'Passkeys not supported in this browser.': '이 브라우저는 패스키를 지원하지 않습니다.',
+6
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Wylogować?',
'Your data is synced to your profile first, then cleared from this device.': 'Dane najpierw synchronizują się z profilem, potem są usuwane z urządzenia.',
'Sign out': 'Wyloguj',
'Sign out everywhere?': 'Wylogować wszędzie?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Wylogowuje ten profil na wszystkich urządzeniach, także na tym. Twoje passkey nadal działają — możesz się nimi zalogować w każdej chwili.',
'Sign out everywhere': 'Wyloguj wszędzie',
'Ends this profile’s sessions on all your devices.': 'Kończy sesje tego profilu na wszystkich Twoich urządzeniach.',
'Signed out on all devices': 'Wylogowano na wszystkich urządzeniach',
'Could not sign out everywhere — you are still signed in.': 'Nie udało się wylogować wszędzie — nadal jesteś zalogowany.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Tryb gościa — dane żyją tylko w tej przeglądarce. Utwórz profil passkey, aby je zabezpieczyć i rozdzielić na osoby.',
'Create passkey profile': 'Utwórz profil passkey',
'Passkeys not supported in this browser.': 'Passkey nieobsługiwane w tej przeglądarce.',
+6
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Terminar sessão?',
'Your data is synced to your profile first, then cleared from this device.': 'Os teus dados são primeiro sincronizados com o perfil e depois apagados deste dispositivo.',
'Sign out': 'Terminar sessão',
'Sign out everywhere?': 'Terminar sessão em todos os dispositivos?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Termina a sessão deste perfil em todos os dispositivos, incluindo este. As tuas passkeys continuam a funcionar — podes voltar a entrar com elas quando quiseres.',
'Sign out everywhere': 'Terminar sessão em todos os dispositivos',
'Ends this profile’s sessions on all your devices.': 'Termina as sessões deste perfil em todos os teus dispositivos.',
'Signed out on all devices': 'Sessão terminada em todos os dispositivos',
'Could not sign out everywhere — you are still signed in.': 'Não foi possível terminar a sessão em todos os dispositivos — continuas com sessão iniciada.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Modo convidado — os dados vivem só neste navegador. Cria um perfil com passkey para os proteger e separar por pessoa.',
'Create passkey profile': 'Criar perfil com passkey',
'Passkeys not supported in this browser.': 'Passkeys não suportadas neste navegador.',
+6
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Выйти?',
'Your data is synced to your profile first, then cleared from this device.': 'Данные сначала синхронизируются с профилем, затем удаляются с устройства.',
'Sign out': 'Выйти',
'Sign out everywhere?': 'Выйти на всех устройствах?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Завершает сеансы этого профиля на всех устройствах, включая это. Ключи доступа продолжают работать — по ним можно войти снова в любой момент.',
'Sign out everywhere': 'Выйти на всех устройствах',
'Ends this profile’s sessions on all your devices.': 'Завершает сеансы этого профиля на всех твоих устройствах.',
'Signed out on all devices': 'Выход выполнен на всех устройствах',
'Could not sign out everywhere — you are still signed in.': 'Не удалось выйти на всех устройствах — ты всё ещё в системе.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Гостевой режим — данные живут только в этом браузере. Создай профиль с ключом доступа, чтобы защитить их и разделить по людям.',
'Create passkey profile': 'Создать профиль с ключом доступа',
'Passkeys not supported in this browser.': 'Ключи доступа не поддерживаются в этом браузере.',
+6
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': 'Çıkış yapılsın mı?',
'Your data is synced to your profile first, then cleared from this device.': 'Verilerin önce profiline eşitlenir, sonra bu cihazdan silinir.',
'Sign out': 'Çıkış yap',
'Sign out everywhere?': 'Her yerden çıkış yapılsın mı?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': 'Bu profili, bu cihaz dahil tüm cihazlarda oturumdan çıkarır. Geçiş anahtarların çalışmaya devam eder — istediğin zaman onlarla tekrar giriş yapabilirsin.',
'Sign out everywhere': 'Her yerden çıkış yap',
'Ends this profile’s sessions on all your devices.': 'Bu profilin tüm cihazlarındaki oturumlarını sonlandırır.',
'Signed out on all devices': 'Tüm cihazlarda çıkış yapıldı',
'Could not sign out everywhere — you are still signed in.': 'Her yerden çıkış yapılamadı — hâlâ giriş yapmış durumdasın.',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': 'Misafir modu — veriler sadece bu tarayıcıda yaşar. Güvende tutmak ve kişi başına ayırmak için geçiş anahtarlı profil oluştur.',
'Create passkey profile': 'Geçiş anahtarlı profil oluştur',
'Passkeys not supported in this browser.': 'Bu tarayıcıda geçiş anahtarları desteklenmiyor.',
+6
View File
@@ -231,6 +231,12 @@ export default {
'Sign out?': '退出登录?',
'Your data is synced to your profile first, then cleared from this device.': '数据会先同步到档案,然后从本设备清除。',
'Sign out': '退出登录',
'Sign out everywhere?': '在所有设备上退出登录?',
'Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.': '让此档案在所有设备上退出登录,包括这台。通行密钥不受影响——随时可以用它们重新登录。',
'Sign out everywhere': '在所有设备上退出登录',
'Ends this profile’s sessions on all your devices.': '结束此档案在你所有设备上的会话。',
'Signed out on all devices': '已在所有设备上退出登录',
'Could not sign out everywhere — you are still signed in.': '无法在所有设备上退出登录——你仍处于登录状态。',
'Guest mode — data lives only in this browser. Create a passkey profile to keep it safe and separate per person.': '访客模式——数据只保存在此浏览器。创建通行密钥档案以保护数据并按人区分。',
'Create passkey profile': '创建通行密钥档案',
'Passkeys not supported in this browser.': '此浏览器不支持通行密钥。',
+21 -5
View File
@@ -70,6 +70,15 @@ export const useStore = create((set, get) => {
}
})
// Everything a sign-out leaves behind on this device, whichever way it was triggered.
const clearLocalSession = () => {
get().setUser(null)
localStorage.removeItem('gym_guest')
localStorage.removeItem('gym_dirty')
localStorage.removeItem(KEY)
persist(clone(DEF), false)
}
return {
S: (() => { const s = loadState(); registerCustom(s.customEx); return s })(),
user: (() => { try { return JSON.parse(localStorage.getItem('gym_user')) || null } catch { return null } })(),
@@ -114,11 +123,18 @@ export const useStore = create((set, get) => {
async signOut() {
try { await get().pushState(); await api('/api/logout', { method: 'POST', body: '{}' }) } catch (e) { /* */ }
get().setUser(null)
localStorage.removeItem('gym_guest')
localStorage.removeItem('gym_dirty')
localStorage.removeItem(KEY)
persist(clone(DEF), false)
clearLocalSession()
},
// "Sign out everywhere": the server bumps this profile's session version, which kills every
// session it has on any device — this browser included, so the app has to end up exactly
// where a normal signOut leaves it. Unlike signOut the request is NOT swallowed: if it fails
// the sessions elsewhere are all still valid, and wiping this device's copy of the data
// would sign the user out of the one place the bump didn't reach. Caller reports the error.
async signOutAll() {
await get().pushState() // never throws — stores gym_dirty and moves on when offline
await api('/api/logout/all', { method: 'POST', body: '{}' })
clearLocalSession()
},
// Demo build only: drop the seeded example profile back in (Settings → "Reset demo data").
+14 -1
View File
@@ -18,7 +18,7 @@ export default function Settings() {
const nav = useNavigate()
const S = useStore(s => s.S)
const user = useStore(s => s.user)
const { update, replaceState, setUser, pullState, pushState, signOut, resetDemo } = useStore()
const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo } = useStore()
const toast = useUI(s => s.toast)
const fileRef = useRef(null)
const importRef = useRef(null)
@@ -53,6 +53,18 @@ export default function Settings() {
catch (e) { if (e.name !== 'NotAllowedError' && e.name !== 'AbortError') toast(e.message || t('Sign-in failed')) }
}
const registerHere = () => useUI.getState().openSheet(close => <RegisterInline close={close} setUser={setUser} pushState={pushState} pullState={pullState} toast={toast} />)
// Ends the profile's sessions on every device — this one included, so on success it lands in
// the same place as the plain sign-out above (home, local data cleared). On failure nothing
// local is touched: still signed in here, and say so rather than leaving a half-signed-out app.
const signOutEverywhere = () => confirmSheet({
title: t('Sign out everywhere?'),
message: t('Signs this profile out on every device, including this one. Your passkeys keep working — sign in with them again anytime.'),
confirmText: t('Sign out everywhere'), danger: true,
onConfirm: async () => {
try { await signOutAll(); nav('/home'); toast(t('Signed out on all devices')) }
catch (e) { toast(t('Could not sign out everywhere — you are still signed in.')) }
},
})
return <div className="narrow">
<div className="hdr">
@@ -76,6 +88,7 @@ export default function Settings() {
<Row icon="personCircle" iconTint="var(--grey)" title={user.name} subtitle={t('Signed in with passkey — data syncs to this profile.')} />
{user.admin && <Row icon="wrench" iconTint="var(--indigo)" title={t('Admin dashboard')} accessory="chevron" onClick={() => nav('/admin')} />}
<Row icon="signOut" iconTint="var(--red)" title={t('Sign out')} danger onClick={() => confirmSheet({ title: t('Sign out?'), message: t('Your data is synced to your profile first, then cleared from this device.'), confirmText: t('Sign out'), danger: true, onConfirm: () => { signOut(); nav('/home') } })} />
<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={signInHere} />