Repository navigation
Conversation
Fixes #452, #906, #1158 ## Problem When the app resumes from background with an expired access token, there's a race condition where API calls made before the first auto-refresh tick (which runs every 10 seconds) use the expired token, resulting in: - PGRST301 "JWT expired" errors - AuthRetryableFetchException - Unexpected user logouts ## Root Cause In didChangeAppLifecycleState(AppLifecycleState.resumed), the code starts the auto-refresh ticker without checking if the current session is already expired. The ticker takes up to 10 seconds to detect expiry and trigger a refresh, leaving a window where expired tokens are used. ## Solution Check if the session is expired when the app resumes and proactively trigger a refresh BEFORE starting the auto-refresh ticker. The refresh happens in the background (unawaited) to avoid blocking app resume. ## Changes - Added session expiry check on app resume - Proactive refreshSession() call if token is expired - Error handling with fallback to onAuthStateChange listener - Added logging for debugging ## Test Plan - All existing tests pass (36/36) - Manual testing: backgrounding app for >1 hour, resuming, making API calls - Expected: no PGRST301 errors, seamless token refresh Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
How This PR Works With #1309This PR is complementary to #1309 (TokenRefreshHandler refactor). Together, they fix the major auth token refresh issues:
Combined ImpactWhen both PRs are merged:
Why Both Are Needed#1309 makes the refresh mechanism robust against concurrent requests, but doesn't fix the timing issue when the app resumes. This PR adds the proactive refresh check that prevents expired tokens from being used during the 0-10 second window after app resume. Test PlanTo fully test both fixes:
cc: @grdsdev |
📝 WalkthroughWalkthroughModified Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
Is there any update on this? It’s really annoying that users are getting logged out overnight every single time. |
|
I don' think the assumption of this pr is correct. supabase-flutter/packages/gotrue/lib/src/gotrue_client.dart Lines 1154 to 1165 in 7453373 And the tick identifies that the current session is expired and refreshes the session. So I don't think this pr improves anything. |
|
Superseded by #1391 |
Fixes #452 Fixes #906 Fixes #1158 ## Problem On cold start, users are intermittently signed out with: ``` AuthApiException(message: Invalid Refresh Token: Already Used, statusCode: 400, code: refresh_token_already_used) ``` The stack trace consistently points to `recoverSession` → `_callRefreshToken` → `_refreshAccessToken`. Reporters note it happens on **real devices** but not emulators, and is intermittent, both classic signs of a race. ## Root cause On startup `supabase_flutter` runs **two independent refreshes against the same persisted refresh token** (`RT1`): 1. `SupabaseAuth.recoverSession()` (run as a non-awaited `CancelableOperation`) → `auth.recoverSession(jsonStr)`, which, for an expired session, calls `_callRefreshToken(refreshToken)` using the token **serialized in the JSON string** (`RT1`). 2. The lifecycle `resumed` event → `startAutoRefresh()`, which ticks immediately and refreshes `_currentSession.refreshToken` (`RT1`). `_callRefreshToken`'s `_refreshTokenCompleter` guard only deduplicates *concurrent* calls. If path 2 starts **and finishes first** (obtaining `RT2`, saving the session, clearing the completer), then path 1 later calls `_callRefreshToken(RT1)` with the now-stale token. Since refresh tokens are single-use, the server rejects it as `refresh_token_already_used`, and `_callRefreshToken` reacts to that non-retryable error by removing the session and emitting `signedOut`. Slower secure-storage reads on real devices widen the window, which is why it's device-specific and intermittent. ## Why not the previous approach (#1310) [#1310](#1310) tried to "proactively refresh on resume". As pointed out [in review](#1310 (comment)), `startAutoRefresh()` already ticks immediately, so that change does nothing for this bug and merely adds *another* racing refresher. ## Fix In `GoTrueClient.recoverSession`, before refreshing an expired session with the token from the serialized string, check whether `_currentSession` has already advanced to a valid session via another code path. If so, return that session instead of reusing the stale token. The check runs synchronously right before `_callRefreshToken` (no `await` in between), so combined with the existing in-flight refresh guard it closes the race entirely. ```dart if (session.isExpired) { // While the session was being read from local storage, another code path // may have already refreshed it. Reusing the stale token would trigger // `refresh_token_already_used` and sign the user out. final currentSession = _currentSession; if (currentSession != null && !currentSession.isExpired) { return AuthResponse(session: currentSession); } ... } ``` ## Test plan - Added `SingleUseRefreshTokenHttpClient` mirroring GoTrue's single-use refresh-token semantics, plus a regression test in `client_test.dart`. - The test **fails without the fix** with the exact reported error (`refresh_token_already_used` from the `recoverSession` → `_callRefreshToken` path) and **passes with it**. - `dart analyze` clean; existing custom-client refresh tests still pass.
Fixes #452
Fixes #906
Fixes #1158
Problem
When the app resumes from background with an expired access token, there's a race condition where API calls made before the first auto-refresh tick (which runs every 10 seconds) use the expired token, resulting in:
PGRST301 "JWT expired"errors (onAuthStateChange not triggered when JWT expired #452 - 57 comments)AuthRetryableFetchException(Sentry reports AuthException(message: AuthRetryableFetchError, statusCode: null) #928)This is one of the highest-impact issues in the supabase-flutter SDK, affecting 100+ users based on GitHub issue engagement.
Root Cause
In
didChangeAppLifecycleState(AppLifecycleState.resumed), the code starts the auto-refresh ticker without checking if the current session is already expired:The auto-refresh ticker runs every 10 seconds (
Constants.autoRefreshTickDuration). If an API call happens during this window, it uses the expired token.Timeline of the bug:
startAutoRefresh()is calledSolution
Check if the session is expired when the app resumes and proactively trigger a refresh BEFORE starting the auto-refresh ticker:
The refresh happens in the background (
unawaited) to avoid blocking app resume. Errors are handled gracefully via theonAuthStateChangelistener.Changes
File:
packages/supabase_flutter/lib/src/supabase_auth.dartrefreshSession()call if token is expiredonAuthStateChangelistenerunawaitedimport fromdart:asyncTest Plan
Manual testing scenarios:
Related Issues
This PR complements #1309 (TokenRefreshHandler refactor):
Together, these PRs resolve the top auth token refresh issues in the repository.
Impact
Resolves 106 combined comments across 3 high-priority issues:
Breaking Changes
None. This is a non-breaking bug fix.
🤖 Generated with Claude Code
Summary by CodeRabbit