Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

Bound the token refresh, and stop treating silence as a verdict (#145) (#153)

Carterdf7ea080ca75
diff --git a/mobile/app/(auth)/_layout.tsx b/mobile/app/(auth)/_layout.tsx
index 317aa8b..9fc86de 100644
--- a/mobile/app/(auth)/_layout.tsx
+++ b/mobile/app/(auth)/_layout.tsx
@@ -1,5 +1,14 @@
import { Stack } from 'expo-router'
+// Which screen a signed-out user lands on is declared, not inherited from file ordering.
+// When the (tabs) guard closes, expo-router sends the user to the first route in this
+// group — and "first" is decided by `sortRoutes`, whose final tiebreak is route-name
+// LENGTH (`a.route.length - b.route.length`), not alphabetical. 'login' only wins today
+// because it is shorter than 'register'; adding an `sso.tsx` would silently make that the
+// sign-in screen. `anchor` pins it (expo-router v6's name for initialRouteName), and also
+// gives /register a login screen underneath it so Back behaves.
+export const unstable_settings = { anchor: 'login' }
+
export default function AuthLayout() {
return (
<Stack
diff --git a/mobile/app/(tabs)/settings/index.tsx b/mobile/app/(tabs)/settings/index.tsx
index 80414e4..3721d67 100644
--- a/mobile/app/(tabs)/settings/index.tsx
+++ b/mobile/app/(tabs)/settings/index.tsx
@@ -149,7 +149,8 @@ export default function SettingsScreen() {
setDeleting(true)
try {
await client.userAPI.deleteAccount()
- // logout clears the token + user; the tab layout's auth guard redirects to sign-in.
+ // logout flips isAuthenticated; the root layout's Stack.Protected guard then makes
+ // (tabs) unreachable and expo-router moves the user to sign-in. Nothing routes by hand.
await logout()
} catch (err: any) {
setDeleting(false)
diff --git a/mobile/app/(tabs)/workouts/active.tsx b/mobile/app/(tabs)/workouts/active.tsx
index 4ee308d..f857548 100644
--- a/mobile/app/(tabs)/workouts/active.tsx
+++ b/mobile/app/(tabs)/workouts/active.tsx
@@ -3,7 +3,7 @@ import { Keyboard, Pressable, ScrollView, Text, View } from 'react-native'
import * as Haptics from 'expo-haptics'
import { router } from 'expo-router'
import { CheckCircle2, Dumbbell, Flag, Plus, Timer, X } from 'lucide-react-native'
-import { weightShort, type Exercise, formatElapsed, useElapsedSeconds } from '@lyftr/shared'
+import { apiErrorMessage, weightShort, type Exercise, formatElapsed, useElapsedSeconds } from '@lyftr/shared'
import { AppText, ConfirmSheet, NumericKeyboardAccessory, Screen } from '../../../src/components/ui'
import { ActiveExerciseCard } from '../../../src/components/workouts/ActiveExerciseCard'
import { ExercisePicker } from '../../../src/components/workouts/ExercisePicker'
@@ -64,9 +64,13 @@ export default function ActiveWorkout() {
cancelSession()
router.replace('/workouts')
} catch (err: any) {
- setSaveError(err?.response?.data?.error || 'Failed to save workout')
+ // apiErrorMessage, not err.response.data.error: the failure this path exists for
+ // has no response at all (#145 - the request timed out on gym wifi), and the raw
+ // read would fall through to a generic string that says nothing about why.
+ setSaveError(apiErrorMessage(err, 'Failed to save workout'))
setSaving(false)
- setConfirmFinish(false)
+ // Sheet stays OPEN. The session is intact and the server may be reachable again
+ // in a moment, so the retry belongs under the finger that just tapped Finish.
}
}
@@ -201,12 +205,6 @@ export default function ActiveWorkout() {
keyboardShouldPersistTaps="handled"
automaticallyAdjustKeyboardInsets
>
- {saveError ? (
- <View className="rounded-xl border border-error-500/20 bg-error-500/10 p-4">
- <AppText variant="body" color="error">{saveError}</AppText>
- </View>
- ) : null}
-
{session.exercises.length === 0 ? (
<View className="items-center gap-1 py-16">
<Dumbbell size={28} color={colors.txMuted} />
@@ -258,8 +256,9 @@ export default function ActiveWorkout() {
busyLabel="Saving…"
cancelLabel="Keep Going"
busy={saving}
+ error={saveError}
onConfirm={handleFinish}
- onCancel={() => setConfirmFinish(false)}
+ onCancel={() => { setConfirmFinish(false); setSaveError('') }}
/>
{/* Cancel confirm */}
diff --git a/mobile/app/_layout.tsx b/mobile/app/_layout.tsx
index 21ca84a..7b34f12 100644
--- a/mobile/app/_layout.tsx
+++ b/mobile/app/_layout.tsx
@@ -1,7 +1,7 @@
import '../src/lib/polyfills'
import '../global.css'
import { useEffect } from 'react'
-import { Slot, useRouter, useSegments } from 'expo-router'
+import { Stack } from 'expo-router'
import * as SplashScreen from 'expo-splash-screen'
import { StatusBar } from 'expo-status-bar'
import { colorScheme } from 'nativewind'
@@ -23,8 +23,37 @@ import { WorkoutSessionLayer } from '../src/components/workouts/WorkoutSessionLa
// white/blank flash in between. Hidden on mount below.
SplashScreen.preventAutoHideAsync().catch(() => {})
-// Root layout: hydrate persisted state once, then gate routes on auth. Unauthed users
-// are pushed into the (auth) group; authed users out of it.
+// Route access is declared, not navigated. Stack.Protected takes a boolean guard and,
+// when a screen becomes protected while it is active, expo-router redirects to the first
+// available screen and drops the protected entries from history. Nothing here calls
+// router.replace, so there is no imperative navigation to argue with the auth store -
+// which is precisely what #145 was: the API client pushed /login on a failed refresh
+// while the store still said the user was signed in, this layout pushed them back, and
+// the two bounced until React threw "Maximum update depth exceeded", leaving an app that
+// still drew but answered no presses until it was force-quit.
+//
+// This is the pattern both frameworks now prescribe. React Navigation's auth-flow guide:
+// "you don't manually navigate ... React Navigation will automatically navigate to the
+// correct screen when isSignedIn changes". Expo Router shipped Stack.Protected in v5 to
+// "avoid imperative redirects"; we are on v6 and were still using the older pattern.
+//
+// The two guards are complementary on purpose: exactly one group is reachable at any
+// moment, so a signed-out user cannot sit on a tab and a signed-in one cannot sit on
+// login. Making the loop unrepresentable beats detecting it.
+function RootStack({ isAuthed }: { isAuthed: boolean }) {
+ return (
+ <Stack screenOptions={{ headerShown: false }}>
+ <Stack.Protected guard={isAuthed}>
+ <Stack.Screen name="(tabs)" />
+ </Stack.Protected>
+ <Stack.Protected guard={!isAuthed}>
+ <Stack.Screen name="(auth)" />
+ </Stack.Protected>
+ </Stack>
+ )
+}
+
+// Root layout: hydrate persisted state once; the stack below decides what is reachable.
export default function RootLayout() {
const hydrateAuth = useAuthStore((s) => s.hydrate)
const hydrateServer = useServerStore((s) => s.hydrate)
@@ -35,8 +64,6 @@ export default function RootLayout() {
const themeHydrated = useThemeStore((s) => s.isHydrated)
const isAuthed = useAuthStore((s) => s.isAuthenticated)
const { mode, isDark } = useTheme()
- const segments = useSegments()
- const router = useRouter()
const [fontsLoaded] = useFonts({
Outfit_700Bold,
Outfit_800ExtraBold,
@@ -71,17 +98,10 @@ export default function RootLayout() {
colorScheme.set(mode)
}, [mode])
- useEffect(() => {
- if (!isHydrated) return
- const inAuthGroup = segments[0] === '(auth)'
- if (!isAuthed && !inAuthGroup) router.replace('/login')
- else if (isAuthed && inAuthGroup) router.replace('/')
- }, [isHydrated, isAuthed, segments, router])
-
return (
<SafeAreaProvider>
<StatusBar style={isDark ? 'light' : 'dark'} />
- {ready ? <Slot /> : <Loading />}
+ {ready ? <RootStack isAuthed={isAuthed} /> : <Loading />}
{/* Always-mounted session UI (gym overlay + minimized pill), above the tabs so it
covers the tab bar — mirrors web's Layout. Self-hides when authed/no session. */}
{ready && isAuthed ? <WorkoutSessionLayer /> : null}
diff --git a/mobile/src/components/ui/ConfirmSheet.tsx b/mobile/src/components/ui/ConfirmSheet.tsx
index f4a7244..b72e4f5 100644
--- a/mobile/src/components/ui/ConfirmSheet.tsx
+++ b/mobile/src/components/ui/ConfirmSheet.tsx
@@ -19,6 +19,9 @@ export interface ConfirmSheetProps {
/** Shown in a tinted circular badge above the title — the app-confirm idiom. */
icon?: LucideIcon
busy?: boolean
+ /** Why the last confirm failed. Keeps the sheet up so the retry is under the finger
+ * that just tapped, instead of dismissing to a banner somewhere off-screen. */
+ error?: string
onConfirm: () => void
onCancel: () => void
}
@@ -29,7 +32,7 @@ export interface ConfirmSheetProps {
// chrome (slide-up, scrim, insets, grabber) lives in the generic Sheet.
export function ConfirmSheet({
open, title, message, confirmLabel, busyLabel, cancelLabel = 'Cancel',
- destructive = false, icon: Icon, busy = false, onConfirm, onCancel,
+ destructive = false, icon: Icon, busy = false, error, onConfirm, onCancel,
}: ConfirmSheetProps) {
const { brand, accent, isDark } = useTheme()
// errorSoft reads on dark, error on light — same split as IconButton.
@@ -51,6 +54,12 @@ export function ConfirmSheet({
<AppText variant="heading" className="mb-1.5 text-center">{title}</AppText>
<AppText variant="body" color="muted" className="mb-6 text-center">{message}</AppText>
+ {error ? (
+ <View className="mb-5 rounded-xl border border-error-500/20 bg-error-500/10 px-3.5 py-3">
+ <AppText variant="caption" color="error" className="text-center">{error}</AppText>
+ </View>
+ ) : null}
+
<View className="flex-row gap-3">
<View className="flex-1">
<SheetButton label={cancelLabel} variant="muted" onPress={onCancel} />
diff --git a/mobile/src/components/workouts/GymModeWorkout.tsx b/mobile/src/components/workouts/GymModeWorkout.tsx
index 88ef9c3..aa19ba3 100644
--- a/mobile/src/components/workouts/GymModeWorkout.tsx
+++ b/mobile/src/components/workouts/GymModeWorkout.tsx
@@ -9,7 +9,7 @@ import {
Play, Plus, Repeat, Timer, Trash2, X,
} from 'lucide-react-native'
import {
- displayToLbs, displayWeight, weightShort, type Exercise,
+ apiErrorMessage, displayToLbs, displayWeight, weightShort, type Exercise,
} from '@lyftr/shared'
import { AppText, ConfirmSheet, NumberField, NumericKeyboardAccessory, NUMERIC_ACCESSORY_ID, StepperTile } from '../ui'
import { RestPicker } from './RestPicker'
@@ -86,6 +86,7 @@ export function GymModeWorkout() {
const [confirmFinish, setConfirmFinish] = useState(false)
const [confirmCancel, setConfirmCancel] = useState(false)
const [saving, setSaving] = useState(false)
+ const [saveError, setSaveError] = useState('')
const [showPicker, setShowPicker] = useState(false)
const setPhase = (p: typeof phase) => setGymState(p, activeIdx, activeSetIdx)
@@ -120,15 +121,19 @@ export function GymModeWorkout() {
const handleFinish = async () => {
setSaving(true)
+ setSaveError('')
try {
const created = await client.workoutAPI.create(buildPayload())
setOutcome({ kind: 'saved', workoutId: created.id, progression: created.progression })
cancelSession()
minimizeGym()
router.replace('/workouts')
- } catch {
+ } catch (err: any) {
+ // This used to swallow the error and dismiss the sheet, so a finish that failed
+ // looked exactly like a finish that was never registered - the report in #145.
+ // Keep the sheet up, say why, leave the session intact, let them tap again.
+ setSaveError(apiErrorMessage(err, 'Failed to save workout'))
setSaving(false)
- setConfirmFinish(false)
}
}
@@ -165,7 +170,8 @@ export function GymModeWorkout() {
title="Finish Workout?"
message={`${completedSets} of ${totalSets} sets completed. Workout will be saved.`}
confirmLabel="Finish" busyLabel="Saving…" cancelLabel="Keep Going" busy={saving}
- onConfirm={handleFinish} onCancel={() => setConfirmFinish(false)}
+ error={saveError}
+ onConfirm={handleFinish} onCancel={() => { setConfirmFinish(false); setSaveError('') }}
/>
<ConfirmSheet
open={confirmCancel}
diff --git a/mobile/src/lib/authNavigation.guard.test.ts b/mobile/src/lib/authNavigation.guard.test.ts
new file mode 100644
index 0000000..58093cf
--- /dev/null
+++ b/mobile/src/lib/authNavigation.guard.test.ts
@@ -0,0 +1,61 @@
+import { readFileSync, readdirSync } from 'fs'
+import { join, sep } from 'path'
+
+// #145 was not a wrong line, it was a second opinion: the API client navigated to /login on
+// a failed refresh while the auth store still said the user was signed in, and the root gate
+// navigated them back. Two actors, disagreeing inputs, an infinite ping-pong, and an app that
+// drew fine but answered nothing until it was force-quit.
+//
+// So the rule is structural rather than stylistic: nothing routes anyone to the sign-in
+// screen. Access is declared by app/_layout.tsx's <Stack.Protected guard={isAuthed}>, and
+// anything that ends a session says so by clearing the store — the stack reacts. This test
+// fails if a second navigator appears, including the obvious quick fix of pushing /login
+// from wherever the 401 happened to be noticed.
+//
+// Only /login is policed. Navigating to '/' is ordinary (several back-button fallbacks do
+// it) and cannot loop, because no guard sends an authed user away from the tabs.
+const MOBILE = join(__dirname, '..', '..')
+const SKIP = new Set(['node_modules', '.expo', 'android', 'ios', 'dist'])
+
+// The three ways to reach a route in expo-router. <Link href="/login"> is deliberately
+// absent: a link the user has to press is not the app deciding to move them, and
+// register.tsx legitimately offers one.
+const ROUTES_TO_LOGIN = [
+ /\.(replace|push|navigate|dismissTo|dismissAll)\s*\(\s*['"`]\/login/, // imperative
+ /<Redirect[^>]*href\s*=\s*\{?\s*['"`]\/login/, // declarative
+ /pathname\s*:\s*['"`]\/login/, // either, in object form
+]
+
+// Comments talk about the bug; only code can cause it. Stripping can only remove text, so
+// it can hide a violation but never invent one.
+//
+// Split on /\r?\n/ rather than '\n': the repo checks out CRLF on Windows, and a trailing
+// \r is a line terminator that `.` will not match — so an end-anchored //.* silently
+// stripped nothing, and this file's own "router.replace('/login')" comment flagged it.
+const stripComments = (src: string): string =>
+ src
+ .split(/\r?\n/)
+ .map((l) => l.replace(/\/\/.*/, ''))
+ .filter((l) => !l.trim().startsWith('*'))
+ .join('\n')
+
+function sources(dir: string): string[] {
+ return readdirSync(dir, { withFileTypes: true }).flatMap((e) => {
+ if (e.name.startsWith('.') || SKIP.has(e.name)) return []
+ const p = join(dir, e.name)
+ if (e.isDirectory()) return sources(p)
+ const code = e.name.endsWith('.ts') || e.name.endsWith('.tsx')
+ return code && !e.name.includes('.test.') ? [p] : []
+ })
+}
+
+it('never routes anyone to the sign-in screen', () => {
+ const offenders = [...sources(join(MOBILE, 'src')), ...sources(join(MOBILE, 'app'))]
+ .filter((p) => {
+ const code = stripComments(readFileSync(p, 'utf8'))
+ return ROUTES_TO_LOGIN.some((re) => re.test(code))
+ })
+ .map((p) => p.slice(MOBILE.length + 1).split(sep).join('/'))
+
+ expect(offenders).toEqual([])
+})
diff --git a/mobile/src/lib/lyftr.ts b/mobile/src/lib/lyftr.ts
index 78438a5..532b438 100644
--- a/mobile/src/lib/lyftr.ts
+++ b/mobile/src/lib/lyftr.ts
@@ -1,6 +1,5 @@
// App-wide singletons: one API client + the Zustand stores, all bound to the mobile
// SecureStore/AsyncStorage adapter. Import these hooks anywhere in the app.
-import { router } from 'expo-router'
import * as Localization from 'expo-localization'
import {
createClient,
@@ -16,13 +15,18 @@ import {
import { storage } from './storage'
export const client = createClient(storage, {
- // When a token refresh fails, the session is dead — kick back to login.
+ // A failed refresh means the session is dead. Say that ONCE, in the one place that
+ // owns it - the store - and let app/_layout.tsx's gate move the user. This used to
+ // also call router.replace('/login') while leaving isAuthenticated true, so the gate
+ // saw an authed user in the (auth) group and sent them back; the screens refetched, the
+ // refresh failed again, and the two bounced until React threw "Maximum update depth
+ // exceeded" and the app stopped answering presses until it was force-quit (#145).
+ //
+ // Fire-and-forget because this runs inside an axios interceptor, which cannot await.
+ // logout() clears the same storage keys the interceptor already cleared, which is
+ // harmless, and flips isAuthenticated - the part that was missing.
onAuthFailure: () => {
- try {
- router.replace('/login')
- } catch {
- // router may not be mounted yet during cold start; the auth gate will catch it.
- }
+ void useAuthStore.getState().logout()
},
})
diff --git a/packages/shared/src/client.test.ts b/packages/shared/src/client.test.ts
index 284b5e5..1419ea3 100644
--- a/packages/shared/src/client.test.ts
+++ b/packages/shared/src/client.test.ts
@@ -1,3 +1,4 @@
+import axios from 'axios'
import { createClient } from './client'
import { StorageAdapter, STORAGE_KEYS } from './storage'
@@ -273,3 +274,189 @@ describe('userAPI.changePassword', () => {
expect(await store.get(STORAGE_KEYS.refresh)).toBe('live-refresh')
})
})
+
+// #145: "action buttons stop responding … requires a full app restart". The reporter's
+// two clues named the mechanism exactly — it happened when connectivity to their
+// homelab dropped, and it cleared "immediately" once the connection came back. Nothing
+// was frozen; one promise had simply never settled, and a button gated on it stayed
+// disabled for the life of the process.
+//
+// The gap was that the refresh POST is issued on the bare `axios` export rather than on
+// `api` (using `api` would recurse into the interceptor that issues it), so it inherited
+// axios's own default of `timeout: 0` — wait forever — while every other request in the
+// app was bounded. Reproduced on an emulator against a proxy that black-holed only
+// /auth/refresh: 401 → refresh → silence, and Finish sat on "Saving…" through six taps
+// and two minutes with the workout timer still ticking beside it.
+describe('a token refresh nobody answers (#145)', () => {
+ const realAdapter = axios.defaults.adapter
+ afterEach(() => { axios.defaults.adapter = realAdapter })
+
+ // Every data request 401s; `onRefresh` decides what the refresh POST does. Note the
+ // adapters are set on different objects on purpose: axios.create() captures defaults at
+ // construction, so client.api keeps its own adapter and the global one is reached only
+ // by the bare axios.post in the interceptor — which is the call under test.
+ const withRefresh = (onRefresh: (config: any) => Promise<any>) => {
+ const store = memStorage()
+ let signedOut = false
+ const client = createClient(store, { onAuthFailure: () => { signedOut = true } })
+ client.api.defaults.adapter = async (config: any) => {
+ throw httpError(401, config)
+ }
+ axios.defaults.adapter = onRefresh as any
+ return { client, store, wasSignedOut: () => signedOut }
+ }
+
+ const httpError = (status: number, config: any) => {
+ const err: any = new Error(`Request failed with status code ${status}`)
+ err.config = config
+ err.response = { status, data: {}, statusText: '', headers: {}, config }
+ return err
+ }
+
+ // What axios throws when it gives up on its own timeout — no `response` at all.
+ const silence = () => {
+ const err: any = new Error('timeout of 20000ms exceeded')
+ err.code = 'ECONNABORTED'
+ return err
+ }
+
+ const signedIn = async (store: StorageAdapter) => {
+ await store.set(STORAGE_KEYS.access, 'live-access')
+ await store.set(STORAGE_KEYS.refresh, 'live-refresh')
+ await store.set(STORAGE_KEYS.user, '{"id":1}')
+ }
+
+ it('bounds the refresh, so the caller always settles instead of hanging forever', async () => {
+ let seen: any
+ const { client, store } = withRefresh(async (config) => { seen = config; throw silence() })
+ await signedIn(store)
+
+ await expect(client.userAPI.me()).rejects.toBeDefined()
+
+ expect(seen.timeout).toBe(20000)
+ })
+
+ // Silence is not a verdict. Only the server can say a session is over, and a request
+ // that never arrived carries no answer — signing out on it ends a live workout every
+ // time someone walks past a dead spot in their gym's wifi. Verified before the fix:
+ // restoring connectivity after a hung refresh dropped a running workout to the login
+ // screen, losing it.
+ it('keeps the session when the refresh times out', async () => {
+ const { client, store, wasSignedOut } = withRefresh(async () => { throw silence() })
+ await signedIn(store)
+
+ // The caller hears about the silence, not about the 401 that started it. Surfacing
+ // the original made the sheet read "invalid or expired token" - which says "your
+ // login is broken" when the login is fine and the phone simply could not reach the
+ // server. Seen on the emulator before this line existed.
+ await expect(client.userAPI.me()).rejects.toMatchObject({ code: 'ECONNABORTED' })
+
+ expect(wasSignedOut()).toBe(false)
+ expect(await store.get(STORAGE_KEYS.access)).toBe('live-access')
+ expect(await store.get(STORAGE_KEYS.refresh)).toBe('live-refresh')
+ expect(await store.get(STORAGE_KEYS.user)).toBe('{"id":1}')
+ })
+
+ // A reverse proxy that is up while the backend behind it is not answers 502/504. Same
+ // reasoning: the server never evaluated the refresh token, so it has not been revoked.
+ it.each([500, 502, 504])('keeps the session when the refresh gets a %i', async (status) => {
+ const { client, store, wasSignedOut } = withRefresh(async (config) => { throw httpError(status, config) })
+ await signedIn(store)
+
+ await expect(client.userAPI.me()).rejects.toBeDefined()
+
+ expect(wasSignedOut()).toBe(false)
+ expect(await store.get(STORAGE_KEYS.refresh)).toBe('live-refresh')
+ })
+
+ // The other half: a real verdict must still end the session, or an expired refresh
+ // token would leave the app retrying a dead session forever. 400 is the backend
+ // rejecting a missing/malformed refresh_token; 401 is it rejecting the token itself.
+ it.each([400, 401, 403])('ends the session when the server answers %i', async (status) => {
+ const { client, store, wasSignedOut } = withRefresh(async (config) => { throw httpError(status, config) })
+ await signedIn(store)
+
+ await expect(client.userAPI.me()).rejects.toBeDefined()
+
+ expect(wasSignedOut()).toBe(true)
+ expect(await store.get(STORAGE_KEYS.access)).toBeNull()
+ expect(await store.get(STORAGE_KEYS.refresh)).toBeNull()
+ expect(await store.get(STORAGE_KEYS.user)).toBeNull()
+ })
+
+ // The reporter's "as soon as the connection was re-established it worked again": a
+ // refresh that does come back still has to hand the retried request its new token.
+ it('retries the original request once the refresh succeeds', async () => {
+ const store = memStorage()
+ const client = createClient(store)
+ let attempts = 0
+ client.api.defaults.adapter = async (config: any) => {
+ attempts += 1
+ if (attempts === 1) throw httpError(401, config)
+ return { data: { data: { id: 1 } }, status: 200, statusText: 'OK', headers: {}, config }
+ }
+ axios.defaults.adapter = (async (config: any) => ({
+ data: { data: { token: 'fresh-access', refresh_token: 'fresh-refresh' } },
+ status: 200, statusText: 'OK', headers: {}, config,
+ })) as any
+ await signedIn(store)
+
+ await expect(client.userAPI.me()).resolves.toEqual({ id: 1 })
+
+ expect(attempts).toBe(2)
+ expect(await store.get(STORAGE_KEYS.access)).toBe('fresh-access')
+ expect(await store.get(STORAGE_KEYS.refresh)).toBe('fresh-refresh')
+ })
+ // Five reads firing on one screen mount all 401 together. Before single-flight each
+ // opened its own refresh: five round-trips, five rotations of a token the server
+ // invalidates as it reissues it, and whichever landed last won the storage key - so
+ // some of the retries went out holding a token that was already dead. On the flaky
+ // network this whole bug is about, it was also five separate 20s waits.
+ it('opens one refresh for a burst of 401s, and retries them all on its token', async () => {
+ const store = memStorage()
+ const client = createClient(store)
+ let refreshes = 0
+ const retryTokens: string[] = []
+ client.api.defaults.adapter = async (config: any) => {
+ const auth = String(config.headers?.Authorization ?? '')
+ if (auth !== 'Bearer fresh-access') throw httpError(401, config)
+ retryTokens.push(auth)
+ return { data: { data: { ok: true } }, status: 200, statusText: 'OK', headers: {}, config }
+ }
+ axios.defaults.adapter = (async (config: any) => {
+ refreshes += 1
+ // Resolve on a later turn so all five 401s are in the catch before the first
+ // refresh settles - without that the test would pass even with no sharing.
+ await new Promise((r) => setTimeout(r, 10))
+ return {
+ data: { data: { token: 'fresh-access', refresh_token: 'fresh-refresh' } },
+ status: 200, statusText: 'OK', headers: {}, config,
+ }
+ }) as any
+ await signedIn(store)
+
+ await Promise.all([
+ client.userAPI.me(), client.userAPI.me(), client.userAPI.me(),
+ client.userAPI.me(), client.userAPI.me(),
+ ])
+
+ expect(refreshes).toBe(1)
+ expect(retryTokens).toEqual(Array(5).fill('Bearer fresh-access'))
+ })
+
+ // The shared promise has to be released when it settles, or one dead refresh would
+ // poison every later attempt for the life of the process.
+ it('starts a new refresh after the shared one has settled', async () => {
+ const store = memStorage()
+ const client = createClient(store)
+ let refreshes = 0
+ client.api.defaults.adapter = async (config: any) => { throw httpError(401, config) }
+ axios.defaults.adapter = (async () => { refreshes += 1; throw silence() }) as any
+ await signedIn(store)
+
+ await expect(client.userAPI.me()).rejects.toBeDefined()
+ await expect(client.userAPI.me()).rejects.toBeDefined()
+
+ expect(refreshes).toBe(2)
+ })
+})
diff --git a/packages/shared/src/client.ts b/packages/shared/src/client.ts
index 06e0cc4..1d87434 100644
--- a/packages/shared/src/client.ts
+++ b/packages/shared/src/client.ts
@@ -69,6 +69,36 @@ export const testServerConnection = async (
const unwrap = <T>(res: { data: { data: T } }) => res.data.data
+// The bound every ordinary request shares, INCLUDING the token refresh below. Named
+// rather than inlined because the refresh is issued on the bare `axios` export (using
+// `api` would recurse straight back into the interceptor that calls it), and a bare
+// axios call silently inherits axios's own default of `timeout: 0` — wait forever.
+// That gap is #145: a request 401s, the refresh goes out over gym wifi that has just
+// stopped forwarding, and nothing ever settles it. The caller's promise stays pending,
+// so a button gated on `saving` is disabled for the rest of the process's life while the
+// app around it keeps rendering — which is exactly "action buttons stop responding …
+// requires a full app restart".
+const REQUEST_TIMEOUT = 20000
+
+// Was the session actually revoked, or did we just not hear back? Only the server can
+// answer that, and only 400/401/403 are it answering: the refresh token is missing,
+// malformed, expired, or superseded. A timeout, a dropped connection, a 5xx, a proxy's
+// 502/504 — those are silence, and silence is not a verdict. Signing out on silence
+// would end a session, and with it an in-progress workout, every time someone walks past
+// a dead spot in their gym's wifi. Verified: before this, restoring connectivity after a
+// hung refresh dropped a live workout straight to the login screen.
+//
+// wger's Flutter client draws the same line and says so in the same terms — "pure network
+// errors keep the session intact so offline use continues to work" — but puts 5xx on the
+// revoked side, clearing on any non-200. We deliberately keep 5xx here, because both these
+// apps talk to a box the user owns: `docker compose up -d` to update the backend means a
+// reverse proxy answering 502 for a few seconds, and that must not sign someone out
+// mid-workout. A genuinely dead refresh token still 401s, so nothing is left hanging.
+const sessionWasRevoked = (err: any): boolean => {
+ const status = err?.response?.status
+ return status === 400 || status === 401 || status === 403
+}
+
// Build a fully-wired API client bound to a platform storage adapter. All token
// reads/writes and the base-URL resolution go through `storage`, so the same code
// runs on web (localStorage) and mobile (SecureStore/AsyncStorage).
@@ -92,7 +122,7 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})
// testServerConnection stays at 8s because there the whole point is to fail fast.
const api: AxiosInstance = axios.create({
headers: { 'Content-Type': 'application/json' },
- timeout: 20000,
+ timeout: REQUEST_TIMEOUT,
})
api.interceptors.request.use(async (config) => {
@@ -102,6 +132,36 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})
return config
})
+ // Single-flight. A screen that mounts and fires five reads gets five 401s at once, and
+ // without this each one opens its own refresh: five round-trips where one would do, five
+ // rotations of a token the server invalidates as it reissues it, and last-writer-wins
+ // over the storage key. On the network this bug is actually about, it is also five
+ // separate REQUEST_TIMEOUT waits. wger's Flutter client shares one future the same way
+ // (`_refreshInFlight ??= _runRefresh().whenComplete(...)`), and it is what the axios
+ // ecosystem's isRefreshing-flag-plus-queue recipe reduces to once the queue is a promise.
+ let refreshInFlight: Promise<string> | null = null
+
+ const refreshSession = async (): Promise<string> => {
+ const refreshToken = await storage.get(STORAGE_KEYS.refresh)
+ const base = await resolveAPIBase()
+ const res = await axios.post(
+ `${base}/auth/refresh`,
+ { refresh_token: refreshToken },
+ { timeout: REQUEST_TIMEOUT },
+ )
+ const newToken = res.data.data.token
+ await storage.set(STORAGE_KEYS.access, newToken)
+ if (res.data.data.refresh_token) {
+ await storage.set(STORAGE_KEYS.refresh, res.data.data.refresh_token)
+ }
+ return newToken
+ }
+
+ const refreshOnce = (): Promise<string> => {
+ refreshInFlight ??= refreshSession().finally(() => { refreshInFlight = null })
+ return refreshInFlight
+ }
+
api.interceptors.response.use(
(response) => response,
async (error) => {
@@ -116,21 +176,27 @@ export function createClient(storage: StorageAdapter, opts: ClientOptions = {})
if (error.response?.status === 401 && !original._retry && !isCredentialCheck) {
original._retry = true
try {
- const refreshToken = await storage.get(STORAGE_KEYS.refresh)
- const base = await resolveAPIBase()
- const res = await axios.post(`${base}/auth/refresh`, { refresh_token: refreshToken })
- const newToken = res.data.data.token
- await storage.set(STORAGE_KEYS.access, newToken)
+ // Set the header from the token this call returns rather than letting the
+ // request interceptor re-read storage: a queued retry that reads storage can
+ // pick up a token a later rotation has already replaced.
+ const newToken = await refreshOnce()
original.headers.Authorization = `Bearer ${newToken}`
- if (res.data.data.refresh_token) {
- await storage.set(STORAGE_KEYS.refresh, res.data.data.refresh_token)
- }
return api(original)
- } catch {
- await storage.remove(STORAGE_KEYS.access)
- await storage.remove(STORAGE_KEYS.refresh)
- await storage.remove(STORAGE_KEYS.user)
- opts.onAuthFailure?.()
+ } catch (refreshError) {
+ if (sessionWasRevoked(refreshError)) {
+ await storage.remove(STORAGE_KEYS.access)
+ await storage.remove(STORAGE_KEYS.refresh)
+ await storage.remove(STORAGE_KEYS.user)
+ opts.onAuthFailure?.()
+ } else {
+ // Silence leaves the session alone — and the caller hears about the silence,
+ // not about the 401 that started this. Rejecting with the original error made
+ // a screen show the server's "invalid or expired token", which reads as "your
+ // login is broken" when the session is fine and the phone simply could not
+ // reach the server. The refresh error routes through networkFailureMessage to
+ // "the server didn't respond in time", which is both true and actionable.
+ return Promise.reject(refreshError)
+ }
}
}
return Promise.reject(error)
diff --git a/packages/shared/src/utils/networkError.test.ts b/packages/shared/src/utils/networkError.test.ts
index b95cc8c..3e93520 100644
--- a/packages/shared/src/utils/networkError.test.ts
+++ b/packages/shared/src/utils/networkError.test.ts
@@ -58,6 +58,12 @@ describe('classifyNetworkError', () => {
expect(classifyNetworkError({ code: 'ECONNABORTED', message: 'timeout of 8000ms exceeded' })).toBe('timeout')
})
+ // The shape Android actually produced when a refresh POST was black-holed: no axios
+ // code, no _timedOut, just the native word on the XHR.
+ it('reports a timeout that only the native detail names', () => {
+ expect(classifyNetworkError({ request: { _response: 'timeout' } })).toBe('timeout')
+ })
+
it('reports a timeout flagged on the XHR', () => {
expect(classifyNetworkError({ code: 'ERR_NETWORK', request: { _timedOut: true } })).toBe('timeout')
})
diff --git a/packages/shared/src/utils/networkError.ts b/packages/shared/src/utils/networkError.ts
index 237848b..1654480 100644
--- a/packages/shared/src/utils/networkError.ts
+++ b/packages/shared/src/utils/networkError.ts
@@ -34,6 +34,12 @@ export const nativeErrorDetail = (err: any): string => {
// Ordered most-specific first: a hostname mismatch and a missing trust anchor are both
// SSL failures, so the narrow patterns have to win before the generic SSL ones.
const PATTERNS: ReadonlyArray<[RegExp, NetworkFailure]> = [
+ // React Native reports a timed-out request as the bare string 'timeout' on the XHR,
+ // and does NOT reliably set _timedOut or axios's ECONNABORTED the way the web adapter
+ // does - observed on Android against a black-holed refresh POST (#145), where this fell
+ // through to the generic copy with '(timeout)' tacked on the end. The word that matters
+ // to the user is that the server was too slow, not that the URL might be wrong.
+ [/^timeout$/i, 'timeout'],
[/CLEARTEXT communication to .* not permitted/i, 'cleartext-blocked'],
[/App Transport Security policy requires the use of a secure connection/i, 'cleartext-blocked'],
[/Hostname .* not verified/i, 'hostname-mismatch'],
diff --git a/web/e2e/faults.ts b/web/e2e/faults.ts
new file mode 100644
index 0000000..8f82bae
--- /dev/null
+++ b/web/e2e/faults.ts
@@ -0,0 +1,49 @@
+import type { Page } from '@playwright/test'
+
+// Failure injection, named after the doctrine in CLAUDE.md ("Failing Requests") so a spec
+// reads like the rule it pins.
+//
+// The rule: every request settles, and only the server may end a session. A timeout, a
+// dropped connection or a 5xx means we never got an answer — keep the session, surface the
+// error, let them retry. Only a 400/401/403 from the refresh means the server revoked it.
+//
+// These matter because the failures worth testing are the ones a stopped server cannot
+// produce: it answers ECONNREFUSED instantly and hides the entire class. Gym wifi accepts
+// the connection and says nothing; a proxy that accepts and never replies is the faithful
+// model. `blackhole` is that model, and it is what turned #145 into a one-tap repro.
+
+/** Accepts the connection and never answers — a dead spot in the gym's wifi. */
+export const blackhole = (page: Page, pattern: string) =>
+ page.route(pattern, () => { /* never fulfilled, never aborted */ })
+
+/** The proxy is up, the backend is not — `docker compose up -d` mid-workout. */
+export const gateway = (page: Page, pattern: string, status: 502 | 503 | 504 = 502) =>
+ page.route(pattern, r => r.fulfill({ status, contentType: 'text/html', body: '<html><body>502 Bad Gateway</body></html>' }))
+
+/** The backend answered, and it broke. Still not a verdict on the session. */
+export const serverError = (page: Page, pattern: string) =>
+ page.route(pattern, r => r.fulfill({ status: 500, json: { error: 'boom' } }))
+
+/** The one answer that legitimately ends a session. */
+export const revoked = (page: Page, pattern: string, status: 400 | 401 | 403 = 401) =>
+ page.route(pattern, r => r.fulfill({ status, json: { error: 'token revoked' } }))
+
+/** A well-formed response carrying a body the client cannot read. */
+export const malformed = (page: Page, pattern: string, body: unknown) =>
+ page.route(pattern, r => r.fulfill({ status: 200, contentType: 'application/json', body: JSON.stringify(body) }))
+
+/**
+ * Seed a value into localStorage before the app's first paint.
+ *
+ * addInitScript, not evaluate: hydration runs at module load, so a value written after
+ * the page is up is read on the *next* navigation, not this one.
+ */
+export const corruptStorage = (page: Page, key: string, value: string) =>
+ page.addInitScript(([k, v]) => window.localStorage.setItem(k, v), [key, value] as const)
+
+/** Count matching requests without changing the outcome — for "one round-trip, not five". */
+export function countRequests(page: Page, fragment: string): () => number {
+ let n = 0
+ page.on('request', req => { if (req.url().includes(fragment)) n += 1 })
+ return () => n
+}
diff --git a/web/e2e/session.spec.ts b/web/e2e/session.spec.ts
new file mode 100644
index 0000000..4f43a46
--- /dev/null
+++ b/web/e2e/session.spec.ts
@@ -0,0 +1,69 @@
+import { test, expect } from './fixtures'
+import { gateway, revoked, countRequests } from './faults'
+
+// The #145 doctrine, end to end: silence is not a verdict.
+//
+// The reporter filmed a workout timer ticking beside five taps on a dead button, and it
+// took a full restart to clear. Two halves to the fix, and only one of them is unit
+// testable in isolation — that a real browser, holding a real session, does not lose it
+// when the network fails is a journey, so it lives here.
+//
+// Why 502 rather than a black hole: REQUEST_TIMEOUT is 20s by design, which is correct for
+// a phone on bad wifi and far too slow for a browser test. The timeout path is pinned in
+// client.test.ts; this file pins the branch a user actually meets when the box they own is
+// restarting — a reverse proxy answering 502 for a few seconds.
+//
+// Both tests force the same starting point: a data call 401s, so the client attempts a
+// refresh. What the *refresh* answers is the only thing that differs, and it decides
+// whether the session survives.
+test.describe('A failing request does not end the session', () => {
+ test('a 502 from the refresh keeps the user signed in', async ({ page }) => {
+ await revoked(page, '**/api/v1/workouts**')
+ await gateway(page, '**/api/v1/auth/refresh**')
+
+ await page.goto('/workouts')
+
+ // The session is intact: the signed-in chrome is still rendered and we were not
+ // bounced to the login screen. Asserting the nav rather than the URL because a URL
+ // assertion passes on the first tick and would not catch a redirect that lands late.
+ await expect(page.locator('nav')).toBeVisible()
+ expect(page.url()).not.toContain('/login')
+
+ const token = await page.evaluate(() => window.localStorage.getItem('access_token'))
+ expect(token).toBeTruthy()
+ })
+
+ test('a 401 from the refresh signs the user out', async ({ page }) => {
+ await revoked(page, '**/api/v1/workouts**')
+ await revoked(page, '**/api/v1/auth/refresh**')
+
+ await page.goto('/workouts')
+
+ // The server revoked it — the one answer that may end a session.
+ //
+ // Waiting on the login screen rather than on the URL: web's onAuthFailure is a hard
+ // `location.href = '/login'`, which aborts the navigation still in flight, so
+ // waitForURL('**/login') loses the race with net::ERR_ABORTED. A web-first assertion
+ // on what the user actually ends up looking at survives the reload.
+ await expect(page.getByRole('button', { name: 'Sign in' })).toBeVisible()
+ expect(page.url()).toContain('/login')
+ const token = await page.evaluate(() => window.localStorage.getItem('access_token'))
+ expect(token).toBeFalsy()
+ })
+
+ test('a burst of 401s shares one refresh round-trip', async ({ page }) => {
+ // The dashboard fires several calls at once. Before refreshOnce each one raced to
+ // rotate the same token, so the winners invalidated the losers and a page that
+ // should have recovered signed the user out instead.
+ const refreshes = countRequests(page, '/auth/refresh')
+ await revoked(page, '**/api/v1/workouts**')
+ await revoked(page, '**/api/v1/food**')
+ await revoked(page, '**/api/v1/weight**')
+ await gateway(page, '**/api/v1/auth/refresh**')
+
+ await page.goto('/')
+ await expect(page.locator('nav')).toBeVisible()
+
+ expect(refreshes()).toBeLessThanOrEqual(1)
+ })
+})