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.

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

Duarte Santosaccc3c1038b5
diff --git a/.env.example b/.env.example
index 831635f24..ac3773c49 100644
--- a/.env.example
+++ b/.env.example
@@ -34,6 +34,16 @@ RP_NAME=openGym
#
# INVITE_ONLY=1
+# ── Session length (optional) ──────────────────────────────────────────────
+# How long a sign-in lasts, in days. Default 90 — long enough that people who
+# train regularly never see a login screen, short enough that a stolen cookie
+# doesn't stay good forever. Lower it for an instance on the open internet,
+# raise it for a private one. Only affects new sign-ins; cookies already handed
+# out keep the lifetime they were issued with. Users can end every session on
+# every device themselves with "Sign out everywhere" in Settings.
+#
+# SESSION_DAYS=90
+
# ── Notifications (optional) ───────────────────────────────────────────────
# Push works out of the box — nothing to set. VAPID keys are generated on first
# run and saved to ./data/vapid.json. Each user's browser reports its own
diff --git a/SECURITY.md b/SECURITY.md
index 8a7b1927b..76290cb9f 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -80,17 +80,22 @@ Read this before hosting openGym for anyone other than yourself.
- **Passkeys only.** No passwords, no email addresses, no reset flow. Registration and login are
verified server-side by `@simplewebauthn/server` against `expectedOrigin: ORIGIN` and
`expectedRPID: RP_ID`, and the authenticator's signature counter is stored and updated on every
- login (`api/server.js:277-303`, `api/server.js:323-343`).
-- **Sessions are a signed cookie.** `gymsid` carries `<uid>:<expiry>` plus an HMAC-SHA256 tag
- over it, compared in constant time (`api/server.js:144-157`). The key is 32 random bytes
- generated on first run and written to `./data/secret` with mode `0600` (`api/server.js:30-32`).
- The cookie is `HttpOnly` and `SameSite=Lax`, and gets `Secure` **only when `ORIGIN` starts with
- `https:`** (`api/server.js:25`, `api/server.js:183-186`).
+ login (`api/server.js:292-318`, `api/server.js:338-358`).
+- **Sessions are a signed cookie.** `gymsid` carries `<uid>:<expiry>:<version>` plus an
+ HMAC-SHA256 tag over it, compared in constant time (`api/server.js:148-161`). The key is 32
+ random bytes generated on first run and written to `./data/secret` with mode `0600`
+ (`api/server.js:34-36`). The cookie is `HttpOnly` and `SameSite=Lax`, and gets `Secure` **only
+ when `ORIGIN` starts with `https:`** (`api/server.js:29`, `api/server.js:198-201`).
+- **Any user can end every session they have.** `POST /api/logout/all` increments that account's
+ session version, and every authenticated request checks the version in the cookie against the
+ one on the user record (`api/server.js:167`, `api/server.js:187-188`), so every cookie ever
+ issued for the account — on every device, including a copy someone walked off with — stops
+ verifying at once. Passkeys are untouched; signing back in works immediately.
- **Data is isolated per user by the session's uid.** `GET`/`PUT /api/data` only ever touch
- `state-<uid>.json` for the caller (`api/server.js:348-365`); no route lets a normal user name
+ `state-<uid>.json` for the caller (`api/server.js:375-392`); no route lets a normal user name
another user.
- **Disabling an account takes effect immediately.** Every authenticated request and every login
- is rejected for a disabled user (`api/server.js:173`, `api/server.js:342`).
+ is rejected for a disabled user (`api/server.js:184`, `api/server.js:357`).
### What it does not do
@@ -102,19 +107,22 @@ Read this before hosting openGym for anyone other than yourself.
people, they are trusting you exactly as much as they'd trust any server operator.**
- **Admins can read everything.** A user listed in `ADMIN_UIDS` (or flagged `admin: true` in
`db.json`) gets every user's full history and body weight, can disable accounts, and can create
- or revoke invite codes (`api/server.js:433-510`). Off by default — a fresh instance has no admin.
-- **Sessions can't be revoked individually.** They're stateless and last **365 days**
- (`api/server.js:22`); `POST /api/logout` just clears the cookie in that one browser
- (`api/server.js:346`). A copied cookie stays valid until it expires. To invalidate every
- session on the instance, delete `./data/secret` and restart — everyone signs in again, passkeys
- are unaffected. Disabling the account works too, for one user.
+ or revoke invite codes (`api/server.js:460-540`). Off by default — a fresh instance has no admin.
+- **Sessions can't be revoked one device at a time.** Revocation is per *account*, not per
+ session: `POST /api/logout/all` kills all of them at once and there is no device list to pick
+ from. `POST /api/logout` on its own only clears the cookie in that one browser
+ (`api/server.js:361`) — a copy taken beforehand keeps working. Sessions last **90 days** by
+ default, settable with `SESSION_DAYS` (`api/server.js:26`); each cookie carries the lifetime it
+ was issued with, so changing the setting doesn't reach cookies that are already out. Deleting
+ `./data/secret` and restarting still works as the instance-wide reset, and disabling an account
+ still locks out one user completely.
- **CSRF protection is `SameSite=Lax` and nothing else.** There are no CSRF tokens.
- **User verification is preferred, not required.** Both handshakes pass
- `requireUserVerification: false` (`api/server.js:282`, `api/server.js:328`), so a passkey
+ `requireUserVerification: false` (`api/server.js:297`, `api/server.js:343`), so a passkey
released without a biometric or PIN is still accepted. In practice: unlocked device ≈ account
access.
- **One passkey per profile, and no recovery.** Every successful registration creates a *new*
- profile (`api/server.js:294-304`); there is no route to attach a second passkey to an existing
+ profile (`api/server.js:309-319`); there is no route to attach a second passkey to an existing
one, and no email or reset path. Lose the passkey and that profile is unreachable — only direct
surgery on `./data` gets it back.
- **Disabling someone isn't a ban.** They can still register a fresh profile with a new passkey
@@ -123,11 +131,14 @@ Read this before hosting openGym for anyone other than yourself.
nginx listens on `:80` (`web/nginx.conf`); TLS is your reverse proxy's job. Without it,
browsers won't do passkeys at all (except on `http://localhost`) and the session cookie is sent
in the clear.
-- **No rate limiting anywhere.** Nothing throttles logins, registrations or writes. Invite codes
- are 8 hex characters — 32 bits (`api/server.js:494`) — and `POST /api/register/options` answers
- whether a code is valid (`api/server.js:257`), so an invite-only instance on the open internet
- should have a rate limit in front of it. The only hard limit in the app is a 5 MB request body
- (`api/server.js:23`).
+- **No rate limiting anywhere.** Nothing throttles logins, registrations or writes, and
+ `POST /api/register/options` still answers whether an invite code is valid
+ (`api/server.js:272`), so an invite-only instance on the open internet should have a rate limit
+ in front of it. New invite codes are 16 hex characters — 64 bits (`api/server.js:525`) — which
+ makes guessing one impractical even unthrottled; codes generated by earlier versions are 8
+ characters / 32 bits and still work, so revoke and reissue any that are still unused. The only
+ hard limit
+ in the app is a 5 MB request body (`api/server.js:27`).
- **A few endpoints answer without a session:** `/api/health` (which includes the total user
count), `/api/config` (whether invite-only is on), `/api/push/public-key`, and the
register/login handshakes.
diff --git a/api/server.js b/api/server.js
index 7a0186234..e2dce6620 100644
--- a/api/server.js
+++ b/api/server.js
@@ -19,7 +19,11 @@ const RP_NAME = process.env.RP_NAME || 'openGym';
// code the admin generates. Both default off so a fresh self-hosted instance stays open.
const ADMIN_UIDS = (process.env.ADMIN_UIDS || '').split(',').map(s => s.trim()).filter(Boolean);
const INVITE_ONLY = /^(1|true|yes|on)$/i.test(process.env.INVITE_ONLY || '');
-const SESSION_DAYS = 365;
+// 90 days keeps someone who trains a few times a week permanently signed in without a stolen
+// cookie staying good for a year. Overridable because a family instance and one on the open
+// internet don't want the same number. Only affects cookies minted from now on — the expiry is
+// baked into each cookie when it's issued, so lowering this never cuts an existing session short.
+const SESSION_DAYS = Math.max(1, +(process.env.SESSION_DAYS || 90) || 90);
const MAX_BODY = 5 * 1024 * 1024;
// Secure cookies require HTTPS; over plain http://localhost the flag would drop the cookie
const SECURE = /^https:/i.test(ORIGIN) ? ' Secure;' : '';
@@ -155,9 +159,15 @@ function verifySig(token) {
} catch { return null; }
return payload;
}
-function makeSession(uid) {
+// Session payload is `<uid>:<expiry>:<version>`, where the version is the user's `sv` counter.
+// Bumping `sv` (POST /api/logout/all) makes every cookie ever handed out for that account stop
+// verifying, which is the only revocation there was before short of deleting ./data/secret and
+// signing out the whole instance. Cookies minted before `sv` existed have no third field and are
+// read as version 0, matching a user who has never bumped — they stay valid until they expire.
+const sessionVersion = user => user.sv || 0;
+function makeSession(user) {
const exp = Date.now() + SESSION_DAYS * 86400000;
- return sign(uid + ':' + exp);
+ return sign(user.id + ':' + exp + ':' + sessionVersion(user));
}
function readSession(req) {
const cookies = Object.fromEntries((req.headers.cookie || '').split(';').map(c => {
@@ -167,10 +177,15 @@ function readSession(req) {
if (!tok) return null;
const payload = verifySig(tok);
if (!payload) return null;
- const [uid, exp] = payload.split(':');
+ const [uid, exp, ver] = payload.split(':');
if (!uid || +exp < Date.now()) return null;
const user = db.users.find(u => u.id === uid) || null;
- if (user && user.disabled) return null; // disabled accounts are locked out everywhere
+ if (!user) return null;
+ if (user.disabled) return null; // disabled accounts are locked out everywhere
+ // Missing third field = pre-versioning cookie = version 0. Anything non-numeric is a malformed
+ // payload (it still had to pass the HMAC, so this is belt-and-braces) and is refused outright.
+ const claimed = ver === undefined ? 0 : Number(ver);
+ if (!Number.isInteger(claimed) || claimed !== sessionVersion(user)) return null;
return user;
}
// Guard for /api/admin/* — resolves the caller and 401/403s if they aren't an admin.
@@ -180,8 +195,8 @@ function requireAdmin(req, res) {
if (!isAdmin(user)) { json(res, 403, { error: 'forbidden' }); return null; }
return user;
}
-function sessionCookie(uid) {
- return `gymsid=${makeSession(uid)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
+function sessionCookie(user) {
+ return `gymsid=${makeSession(user)}; Path=/; Max-Age=${SESSION_DAYS * 86400}; HttpOnly;${SECURE} SameSite=Lax`;
}
const clearCookie = `gymsid=; Path=/; Max-Age=0; HttpOnly;${SECURE} SameSite=Lax`;
@@ -301,7 +316,7 @@ const routes = {
transports: body.credential?.response?.transports || []
});
saveDb();
- json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user.id) });
+ json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user) });
},
'POST /api/login/options': async (req, res) => {
@@ -340,11 +355,23 @@ const routes = {
const user = db.users.find(u => u.id === cred.userId);
if (!user) return json(res, 500, { error: 'user missing' });
if (user.disabled) return json(res, 403, { error: 'this account has been disabled' });
- json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user.id) });
+ json(res, 200, { user: { id: user.id, name: user.name, admin: isAdmin(user) } }, { 'Set-Cookie': sessionCookie(user) });
},
'POST /api/logout': async (req, res) => json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie }),
+ // "Sign out everywhere" — bumps this user's session version, which invalidates every cookie
+ // ever issued for the account, on every device, including a copy someone else walked off with.
+ // The caller's own cookie is cleared here too, so the browser doing it doesn't sit on a token
+ // it no longer accepts. Passkeys are untouched: signing back in works immediately.
+ 'POST /api/logout/all': async (req, res) => {
+ const user = readSession(req);
+ if (!user) return json(res, 401, { error: 'not signed in' });
+ user.sv = sessionVersion(user) + 1;
+ saveDb();
+ json(res, 200, { ok: true }, { 'Set-Cookie': clearCookie });
+ },
+
'GET /api/data': async (req, res) => {
const user = readSession(req);
if (!user) return json(res, 401, { error: 'not signed in' });
@@ -491,7 +518,11 @@ const routes = {
const admin = requireAdmin(req, res); if (!admin) return;
const body = await readBody(req);
let code;
- do { code = crypto.randomBytes(4).toString('hex').toUpperCase(); } while (db.invites.some(i => i.code === code));
+ // 16 hex chars = 64 bits, up from 8 chars / 32 bits. The app has no rate limiting by design
+ // (that's the reverse proxy's job) and /api/register/options tells a caller whether a code is
+ // good, so the code itself has to be the thing that isn't worth guessing. Codes already in
+ // db.json keep working — validation is an exact string compare, never a length or format check.
+ do { code = crypto.randomBytes(8).toString('hex').toUpperCase(); } while (db.invites.some(i => i.code === code));
const invite = { code, note: String(body.note || '').slice(0, 60), createdBy: admin.id, created: new Date().toISOString() };
db.invites.push(invite);
saveDb();
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 998591843..853c67cee 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -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.',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 2c2cc3140..3c83ce693 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -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.',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 5faf1f264..3d0a03d5b 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -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.',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 744a4e02d..08e3bdfd7 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -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.': 'इस ब्राउज़र में पासकी समर्थित नहीं।',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 1a282c935..e4ef22bf6 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -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.',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 0b6f695bb..e5c485c95 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -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.': '이 브라우저는 패스키를 지원하지 않습니다.',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 5ea873aff..a4704ba62 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -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.',
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index d6996f18b..64ad262a0 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -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.',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 053171e18..94b061b21 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -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.': 'Ключи доступа не поддерживаются в этом браузере.',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index de694c229..7e773d1c3 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -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.',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index e9045cec3..051fcf05d 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -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.': '此浏览器不支持通行密钥。',
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index 641961dfb..2b4163378 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -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").
diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsx
index 7e30f6fe8..078db6563 100644
--- a/frontend/src/views/Settings.jsx
+++ b/frontend/src/views/Settings.jsx
@@ -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} />