A cross platform Audiobookshelf client for Android and iOS
Dart
Stop a lost token rotation from silently killing your session
Barnabas562aab5e3607
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dartindex f8e59e24..ec45994c 100644--- a/lib/providers/auth_provider.dart+++ b/lib/providers/auth_provider.dart@@ -283,36 +283,55 @@ class AuthProvider extends ChangeNotifier {_username == username;}- Future<void> _onTokensRefreshed(+ Future<bool> _onTokensRefreshed(String sessionServer,String? sessionUsername,String newAccessToken,String? newRefreshToken,) async {- if (!_isCurrentSession(sessionServer, sessionUsername) ||- _accessToken == null) {- return;+ // These used to return silently, so a rotation that was never stored looked+ // identical in the log to one that was. Say which guard stopped it.+ if (!_isCurrentSession(sessionServer, sessionUsername)) {+ debugPrint(+ '[Auth] Dropping rotated tokens: they belong to '+ '$sessionUsername@$sessionServer, current session is $_username@$_serverUrl',+ );+ return false;+ }+ if (_accessToken == null) {+ debugPrint('[Auth] Dropping rotated tokens: no access token in memory');+ return false;}final refreshUnchanged =newRefreshToken == null || newRefreshToken == _refreshToken;- if (_accessToken == newAccessToken && refreshUnchanged) return;+ if (_accessToken == newAccessToken && refreshUnchanged) return true;_accessToken = newAccessToken;if (newRefreshToken != null) _refreshToken = newRefreshToken;+ var persisted = false;try {- await UserAccountService().persistRefreshedTokens(+ persisted = await UserAccountService().persistRefreshedTokens(_accessToken!,_refreshToken,serverUrl: sessionServer,username: sessionUsername,);- final prefs = await SharedPreferences.getInstance();- await prefs.setInt(- 'token_saved_at', DateTime.now().millisecondsSinceEpoch);- debugPrint(- '[Auth] Rotated tokens persisted: '- 'access=${ApiService.tokenFp(_accessToken)} '- 'refresh=${ApiService.tokenFp(_refreshToken)}',- );+ if (persisted) {+ final prefs = await SharedPreferences.getInstance();+ await prefs.setInt(+ 'token_saved_at', DateTime.now().millisecondsSinceEpoch);+ debugPrint(+ '[Auth] Rotated tokens persisted: '+ 'access=${ApiService.tokenFp(_accessToken)} '+ 'refresh=${ApiService.tokenFp(_refreshToken)}',+ );+ } else {+ debugPrint(+ '[Auth] ROTATION NOT PERSISTED: this session now holds a refresh '+ 'token that only exists in memory - a restart will come back with a '+ 'spent one (access=${ApiService.tokenFp(_accessToken)} '+ 'refresh=${ApiService.tokenFp(_refreshToken)})',+ );+ }} catch (e) {debugPrint('[Auth] Failed to persist refreshed tokens: $e');}@@ -321,6 +340,7 @@ class AuthProvider extends ChangeNotifier {// Keep the paired Wear OS app's cached token in sync._pushSessionToWear();notifyListeners();+ return persisted;}/// Push the current session to the paired Wear OS app (if any). Safe@@ -365,11 +385,16 @@ class AuthProvider extends ChangeNotifier {}void _onAuthExpired(String sessionServer, String? sessionUsername) {- if (!_isCurrentSession(sessionServer, sessionUsername) ||- _accessToken == null ||- _authExpiryInProgress) {+ // Swallowing this is how a dead session turns into fifteen minutes of+ // silent 401s instead of one "please sign in again", so name the guard.+ if (!_isCurrentSession(sessionServer, sessionUsername)) {+ debugPrint(+ '[Auth] Ignoring auth-expired for $sessionUsername@$sessionServer: '+ 'current session is $_username@$_serverUrl',+ );return;}+ if (_accessToken == null || _authExpiryInProgress) return;_authExpiryInProgress = true;debugPrint('[Auth] Token refresh failed, forcing re-login 'diff --git a/lib/services/api_service.dart b/lib/services/api_service.dartindex 2c509ffc..5435cbe9 100644--- a/lib/services/api_service.dart+++ b/lib/services/api_service.dart@@ -200,7 +200,10 @@ class ApiService {final http.Client? _httpClient;/// Called after a successful token refresh so the auth layer can persist.- FutureOr<void> Function(String newAccessToken, String? newRefreshToken)?+ /// Returns whether the pair actually reached storage - a rotation that only+ /// lives in memory dies with the process and leaves a spent refresh token+ /// behind, so callers must be able to tell the difference.+ FutureOr<bool> Function(String newAccessToken, String? newRefreshToken)?onTokensRefreshed;/// Loads the latest persisted tokens before refreshing. Background isolates@@ -350,10 +353,14 @@ class ApiService {Future<void> _notifyTokensRefreshed() async {try {- await onTokensRefreshed?.call(_accessToken, _refreshToken);+ final persisted = await onTokensRefreshed?.call(_accessToken, _refreshToken);debugPrint(- '[API] Tokens handed to persistence: access=${tokenFp(_accessToken)} '- 'refresh=${tokenFp(_refreshToken)}',+ persisted == false+ ? '[API] Tokens NOT persisted (rotation held in memory only): '+ 'access=${tokenFp(_accessToken)} '+ 'refresh=${tokenFp(_refreshToken)}'+ : '[API] Tokens handed to persistence: access=${tokenFp(_accessToken)} '+ 'refresh=${tokenFp(_refreshToken)}',);} catch (e) {debugPrint('[API] Failed to persist refreshed tokens: $e');@@ -485,7 +492,8 @@ class ApiService {if (_refreshToken != refreshTokenSent && attempt == 0) continue;debugPrint('[API] Token refresh rejected: ${response.statusCode} '- '(sent refresh=${tokenFp(refreshTokenSent)})',+ '(sent refresh=${tokenFp(refreshTokenSent)})'+ '${_refreshToken == refreshTokenSent ? " - storage holds the same spent token, session is dead until re-login" : ""}',);_refreshCompleter!.complete(_RefreshOutcome.rejected);return _RefreshOutcome.rejected;diff --git a/lib/services/user_account_service.dart b/lib/services/user_account_service.dartindex 4d121c9a..3b6e1196 100644--- a/lib/services/user_account_service.dart+++ b/lib/services/user_account_service.dart@@ -2,6 +2,7 @@ import 'dart:convert';import 'package:flutter/foundation.dart';import 'package:shared_preferences/shared_preferences.dart';import '../utils/server_url.dart';+import 'api_service.dart';import 'auth_tokens.dart';/// Represents a saved user account (server + credentials).@@ -185,7 +186,16 @@ class UserAccountService {/// single-use - so a refresh whose result is only kept in memory strands/// the on-disk session with an expired access token and a consumed refresh/// token, and the next app launch can't sign in.- Future<void> persistRefreshedTokens(+ /// Persist a rotated token pair. Returns whether the pair actually reached+ /// storage.+ ///+ /// The server rotates refresh tokens single-use, so a new access token stored+ /// beside the PREVIOUS refresh token is a dead session: the stored refresh+ /// token has already been spent and every later refresh 401s, with no way+ /// back short of a re-login. That is exactly what happened on 2026-08-13.+ /// So the pair is written together or not at all, and the write is read back+ /// before it is called a success.+ Future<bool> persistRefreshedTokens(String accessToken,String? refreshToken, {required String serverUrl,@@ -198,7 +208,21 @@ class UserAccountService {if (activeServer == null ||normalizeServerUrl(activeServer) != normalizeServerUrl(serverUrl) ||activeUsername != username) {- return;+ debugPrint(+ '[Accounts] Not persisting rotated tokens: active session is '+ '${activeServer == null ? "(none)" : "$activeUsername@$activeServer"}, '+ 'rotation was for $username@$serverUrl',+ );+ return false;+ }+ // Half a pair is worse than none: keep the old, still-valid pair rather+ // than pairing a fresh access token with a spent refresh token.+ if (refreshToken == null && prefs.getString('refresh_token') != null) {+ debugPrint(+ '[Accounts] Not persisting rotated tokens: response carried no refresh '+ 'token and storage already holds one - refusing to store half a pair',+ );+ return false;}await prefs.setString('token', accessToken);if (refreshToken != null) await prefs.setString('refresh_token', refreshToken);@@ -206,6 +230,24 @@ class UserAccountService {if (_accounts.isEmpty) await init();await updateTokens(serverUrl, username, accessToken, refreshToken: refreshToken);}+ // Read back: another isolate holding stale state can clobber these keys+ // between the write and the next launch, and the failure is silent until+ // the session is already dead.+ await prefs.reload();+ final storedAccess = prefs.getString('token');+ final storedRefresh = prefs.getString('refresh_token');+ if (storedAccess != accessToken ||+ (refreshToken != null && storedRefresh != refreshToken)) {+ debugPrint(+ '[Accounts] Rotated tokens did NOT survive the write: '+ 'wrote access=${ApiService.tokenFp(accessToken)} '+ 'refresh=${ApiService.tokenFp(refreshToken)}, '+ 'read back access=${ApiService.tokenFp(storedAccess)} '+ 'refresh=${ApiService.tokenFp(storedRefresh)}',+ );+ return false;+ }+ return true;}/// Reload the active session from disk. SharedPreferences keeps an