Skip to content

fix(auth): avoid reusing a stale refresh token in recoverSession - #1391

Merged
spydon merged 3 commits into
mainfrom
fix/recover-session-stale-refresh-token
Jun 10, 2026
Merged

spydon merged 3 commits into
mainfrom
fix/recover-session-stale-refresh-token

Conversation

@spydon

@spydon spydon commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

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 tried to "proactively refresh on resume". As pointed out in review, 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.

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.

On cold start both `recoverSession` and the auto-refresh tick (fired when
the app resumes) can refresh the same persisted, expired session. If one
refreshes first, the refresh token serialized in the session string passed
to `recoverSession` becomes stale. Reusing it made the server respond with
`refresh_token_already_used`, which removed the session and signed the user
out.

`recoverSession` now returns the already valid in-memory session instead of
refreshing the stale token again. The check runs synchronously before
`_callRefreshToken`, so combined with the existing in-flight refresh guard it
closes the race entirely.

Fixes #1158
@spydon
spydon requested a review from a team as a code owner June 10, 2026 11:59
@github-actions github-actions Bot added the auth This issue or pull request is related to authentication label Jun 10, 2026
spydon added 2 commits June 10, 2026 14:05
The short-circuit added in recoverSession was too broad: it returned any
valid in-memory session, which broke the "Sign out on wrong refresh token"
test where a valid session exists but a different, bad session is recovered.

Restrict the short-circuit to when the current valid session belongs to the
same user as the one being recovered, which is exactly the cold-start race
this guards against. Also remove the explanatory comment.
Adds a reactive guard in _callRefreshToken: when a refresh fails with
`refresh_token_already_used` but the current session is still valid, another
refresh (a concurrent tick or another process sharing storage) already
rotated the token, so return the valid session instead of removing it and
emitting signedOut.

This complements the recoverSession fix: recoverSession avoids sending a
stale token preemptively, while this handles the case where the token is
consumed elsewhere between reading it and refreshing.

A genuinely unknown refresh token still returns a different error code
(refresh_token_not_found) and signs out as before.

Adds refresh_token_race_test.dart covering the cold-start race, concurrent
recovery, and graceful already-used handling.
@spydon
spydon force-pushed the fix/recover-session-stale-refresh-token branch from 49d9e58 to 10b9d94 Compare June 10, 2026 12:19
@spydon

spydon commented Jun 10, 2026

Copy link
Copy Markdown
Contributor Author

I would love to get your thoughts on this @Vinzent03 (if you have time of course) since you were involved in reviewing the previous PR :)

@spydon
spydon merged commit de2adf9 into main Jun 10, 2026
18 checks passed
@spydon
spydon deleted the fix/recover-session-stale-refresh-token branch June 10, 2026 15:24
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

auth This issue or pull request is related to authentication

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Auto Refresh is not working Supabase.initialize don't refresh token after 1h on app open again onAuthStateChange not triggered when JWT expired

2 participants