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
Signing out while the server cannot be reached no longer leaves the session behind: the next start sends the sign-out again instead of signing the browser back in without a passkey or password
Duarte Santosc1c5ad7dad88
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex 3a47e6ca3..bee13a7a6 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -33,6 +33,19 @@ const SYNCED_FP_KEY = 'gym_synced_fp' // a fingerprint of that copy (lib/sync-c// reaches that server as that account again. On a phone also a file beside the state mirror.const STASH_KEY = 'gym_stash'const STASH_FILE = 'opengym-stash.json'+// A browser sign-out whose request never reached the server. The session cookie is HttpOnly, so+// only the server's answer to /api/logout takes it out of the browser; until that answer comes,+// boot sends the logout again instead of asking /api/me, which would sign the browser straight+// back in with no passkey or password. Any sign-in replaces the cookie and clears the mark.+const LOGOUT_OWED_KEY = 'gym_logout_owed'+// Reads the mark with no argument, sets or clears it with one. Storage that cannot be read owes nothing.+function logoutOwed(on) {+ try {+ if (on === undefined) return localStorage.getItem(LOGOUT_OWED_KEY) === '1'+ if (on) localStorage.setItem(LOGOUT_OWED_KEY, '1'); else localStorage.removeItem(LOGOUT_OWED_KEY)+ } catch { /* private mode with storage blocked */ }+ return false+}// Mobile build: whose copy the file mirror (lib/mobile.js, opengym-state.json) holds, and which// one — { owner, ts }, written after it (saveMirror). A device fact, so never inside S.const MIRROR_OWNER_FILE = 'opengym-state-owner.json'@@ -789,6 +802,7 @@ export const useStore = create((set, get) => {localStorage.setItem('gym_owner_name', u.name || '')localStorage.setItem('gym_owner', u.id)localStorage.setItem('gym_user', JSON.stringify(u)); localStorage.removeItem('gym_guest')+ logoutOwed(false) // this sign-in's cookie replaced the one a failed sign-out left behind// The file follows at once, as the new account's: until then it holds the previous one's.if (other && MOBILE) nativePersist(true)// The server answers /api/config with a `coach` key only to a session — the block, or@@ -988,7 +1002,9 @@ export const useStore = create((set, get) => {const left = get().unsyncedChanges()if (left.owed && !force) return { owed: true, count: left.count }if (left.owed && !(await stashOwed())) return { owed: true, count: left.count, stashed: false }- try { await api('/api/logout', { method: 'POST', body: '{}' }) } catch (e) { /* the session ends here either way */ }+ // The device is signed out either way. A request that did not get through leaves the cookie+ // behind, still valid, so the logout is owed until the server answers it (see boot).+ try { await api('/api/logout', { method: 'POST', body: '{}' }) } catch (e) { if (!MOBILE) logoutOwed(true) }await clearLocalSession()return left.owed ? { owed: true, count: left.count, stashed: true } : { owed: false }},@@ -1140,6 +1156,12 @@ export const useStore = create((set, get) => {// an unreachable server must not be allowed to lock anyone out (#42).const cfg = await get().loadConfig()if (!guestAllowed(cfg)) get().setGuest(false)+ // A sign-out that could not reach the server: finish it first. Still unanswered, the+ // browser stays signed out rather than adopt the session it left behind.+ if (logoutOwed()) {+ try { await api('/api/logout', { method: 'POST', body: '{}' }); logoutOwed(false) } catch { /* owed until it is answered */ }+ if (logoutOwed()) { finishBoot(); return }+ }try {const me = await api('/api/me')if (!me.user?.id) throw Object.assign(new Error('no user'), { status: 200, code: 'bad-response' })diff --git a/frontend/src/store/useStore.sync-status.test.jsx b/frontend/src/store/useStore.sync-status.test.jsxindex 6024a2059..15005d761 100644--- a/frontend/src/store/useStore.sync-status.test.jsx+++ b/frontend/src/store/useStore.sync-status.test.jsx@@ -259,6 +259,68 @@ describe('signing out never loses a change silently', () => {})})+describe('a sign-out the server did not answer', () => {+ // A copy in step with the server: nothing owed, so the sign-out goes ahead at once.+ const inStep = async () => {+ signedIn({ ...clone(DEF), _ts: 100, workouts: [workout('w1')] })+ localStorage.setItem('gym_sync', JSON.stringify({ rev: 1, ts: 100 }))+ api.mockResolvedValueOnce({ rev: 1 })+ window.dispatchEvent(new Event('online'))+ await new Promise(r => setTimeout(r, 10))+ api.mockReset()+ }++ // The session cookie is HttpOnly: only the server's answer to /api/logout takes it out of the+ // browser. A sign-out that could not reach the server left it there, still valid, and the next+ // boot's /api/me signed the browser back in with no passkey — on a shared computer, into the+ // account the last person signed out of.+ it('a sign-out the server never heard is finished on the next boot, and until then nothing signs the browser back in', async () => {+ await inStep()+ api.mockRejectedValue(netError())+ expect(await useStore.getState().signOut()).toEqual({ owed: false })+ expect(useStore.getState().user).toBeNull()+ expect(localStorage.getItem('gym_logout_owed')).toBe('1')++ // Still unreachable: the old session is not even asked about.+ api.mockReset()+ api.mockImplementation(async (path, o) => {+ if (path === '/api/config') return { allow_guest: true }+ if (path === '/api/logout') throw httpError(502)+ if (path === '/api/me') return { user: USER }+ throw new Error('unexpected ' + path)+ })+ useStore.setState({ ready: false, config: null })+ await useStore.getState().boot()+ expect(paths()).toEqual(['GET /api/config', 'POST /api/logout'])+ expect(useStore.getState().user).toBeNull()+ expect(useStore.getState().ready).toBe(true)+ expect(localStorage.getItem('gym_logout_owed')).toBe('1')++ // The server answers again: the logout goes first, and /api/me finds nobody.+ api.mockReset()+ api.mockImplementation(async path => {+ if (path === '/api/config') return { allow_guest: true }+ if (path === '/api/logout') return { ok: true }+ if (path === '/api/me') throw httpError(401)+ throw new Error('unexpected ' + path)+ })+ useStore.setState({ ready: false, config: null })+ await useStore.getState().boot()+ expect(paths()).toEqual(['GET /api/config', 'POST /api/logout', 'GET /api/me'])+ expect(useStore.getState().user).toBeNull()+ expect(localStorage.getItem('gym_logout_owed')).toBeNull()+ })++ it('signing in again replaces the cookie a failed sign-out left behind, so the next boot asks /api/me as usual', async () => {+ await inStep()+ api.mockRejectedValue(netError())+ await useStore.getState().signOut()+ expect(localStorage.getItem('gym_logout_owed')).toBe('1')+ useStore.getState().setUser(USER) // a passkey or password sign-in+ expect(localStorage.getItem('gym_logout_owed')).toBeNull()+ })+})+describe('signing in again to the account this copy belongs to', () => {// A browser whose session ended mid-week: the copy is still here with its owner and owes the// server a workout, a routine edit and a setting.