A cross platform Audiobookshelf client for Android and iOS
Dart
Refresh the login token before it expires instead of after a request fails
Barnabas0447eb68b5a0
diff --git a/lib/providers/auth_provider.dart b/lib/providers/auth_provider.dartindex ec45994c..ba5e0222 100644--- a/lib/providers/auth_provider.dart+++ b/lib/providers/auth_provider.dart@@ -775,9 +775,12 @@ class AuthProvider extends ChangeNotifier {try {final prefs = await SharedPreferences.getInstance();await prefs.setString('server_url', _serverUrl!);- if (_accessToken != null) await prefs.setString('token', _accessToken!);+ // Refresh token first: a crash between the two writes then leaves the old+ // access token beside the NEW refresh token, which recovers itself. The+ // other order is the one that strands a spent refresh token.if (_refreshToken != null)await prefs.setString('refresh_token', _refreshToken!);+ if (_accessToken != null) await prefs.setString('token', _accessToken!);if (_username != null) await prefs.setString('username', _username!);if (_userId != null) await prefs.setString('user_id', _userId!);if (_defaultLibraryId != null) {@@ -978,9 +981,12 @@ class AuthProvider extends ChangeNotifier {try {final prefs = await SharedPreferences.getInstance();await prefs.setString('server_url', _serverUrl!);- if (_accessToken != null) await prefs.setString('token', _accessToken!);+ // Refresh token first: a crash between the two writes then leaves the old+ // access token beside the NEW refresh token, which recovers itself. The+ // other order is the one that strands a spent refresh token.if (_refreshToken != null)await prefs.setString('refresh_token', _refreshToken!);+ if (_accessToken != null) await prefs.setString('token', _accessToken!);if (_username != null) await prefs.setString('username', _username!);if (_userId != null) await prefs.setString('user_id', _userId!);if (_defaultLibraryId != null) {@@ -1317,12 +1323,13 @@ class AuthProvider extends ChangeNotifier {try {final prefs = await SharedPreferences.getInstance();await prefs.setString('server_url', _serverUrl!);- if (_accessToken != null) await prefs.setString('token', _accessToken!);+ // Refresh token first, for the same reason as the other persist sites.if (_refreshToken != null) {await prefs.setString('refresh_token', _refreshToken!);} else {await prefs.remove('refresh_token');}+ if (_accessToken != null) await prefs.setString('token', _accessToken!);if (_username != null) await prefs.setString('username', _username!);if (_userId != null) {await prefs.setString('user_id', _userId!);diff --git a/lib/services/api_service.dart b/lib/services/api_service.dartindex 5435cbe9..a23b3094 100644--- a/lib/services/api_service.dart+++ b/lib/services/api_service.dart@@ -353,7 +353,10 @@ class ApiService {Future<void> _notifyTokensRefreshed() async {try {- final persisted = await onTokensRefreshed?.call(_accessToken, _refreshToken);+ final persisted = await onTokensRefreshed?.call(+ _accessToken,+ _refreshToken,+ );debugPrint(persisted == false? '[API] Tokens NOT persisted (rotation held in memory only): '@@ -521,13 +524,94 @@ class ApiService {}}+ /// Seconds of headroom before the access token's own expiry at which we stop+ /// trusting it. Generous because a slow request that starts valid can still+ /// arrive expired.+ static const _accessTokenSkew = Duration(seconds: 60);++ /// Expiry stamped in the access token, or null when it can't be read+ /// (legacy static tokens, opaque tokens, malformed payloads).+ DateTime? get _accessTokenExpiry {+ final parts = _accessToken.split('.');+ if (parts.length != 3) return null;+ try {+ final payload = jsonDecode(+ utf8.decode(base64Url.decode(base64Url.normalize(parts[1]))),+ );+ if (payload is! Map) return null;+ final exp = payload['exp'];+ if (exp is! int) return null;+ return DateTime.fromMillisecondsSinceEpoch(exp * 1000);+ } catch (_) {+ return null;+ }+ }++ /// Suppresses the pre-flight after a refresh that couldn't reach the server.+ /// Static because callers construct a fresh ApiService per use.+ static DateTime? _preflightCooldownUntil;+ static const _preflightCooldown = Duration(minutes: 2);++ /// Static state outlives a single test, so a test that trips the cooldown+ /// would otherwise silently disable the pre-flight for whatever runs next.+ @visibleForTesting+ static void resetPreflightCooldown() => _preflightCooldownUntil = null;++ /// Refresh BEFORE spending a known-expired access token, rather than firing+ /// the request, taking a 401, and recovering afterwards.+ ///+ /// Reactive-only refresh means every parallel call that happens to fall after+ /// expiry races into its own recovery - four concurrent refreshes inside one+ /// second showed up in the 2026-08-13 logout log - and it widens the window+ /// in which a rotation can be lost. The server's grace period for a spent+ /// refresh token is only ten minutes, so noticing early matters.+ ///+ /// The cooldown is what keeps this from being worse than the old behaviour+ /// when the server is routable but not answering (LAN-only server, away from+ /// home): without it every call would spend two 15s refresh timeouts, holding+ /// the token mutation lock, before its own request even started - so a+ /// handful of queued calls turn into minutes. After one unreachable attempt+ /// we go back to letting the request itself fail.+ Future<void> _ensureFreshAccessToken() async {+ if (_isLegacyToken || _refreshToken == null) return;+ final cooldownUntil = _preflightCooldownUntil;+ if (cooldownUntil != null && DateTime.now().isBefore(cooldownUntil)) return;+ final expiry = _accessTokenExpiry;+ if (expiry == null) return;+ if (DateTime.now().add(_accessTokenSkew).isBefore(expiry)) return;+ final outcome = await _refreshAccessToken();+ switch (outcome) {+ case _RefreshOutcome.refreshed:+ _preflightCooldownUntil = null;+ case _RefreshOutcome.rejected:+ _preflightCooldownUntil = null;+ onAuthExpired?.call();+ case _RefreshOutcome.transientFailure:+ _preflightCooldownUntil = DateTime.now().add(_preflightCooldown);+ debugPrint(+ '[API] Pre-flight refresh could not reach the server - '+ 'falling back to on-401 refresh for '+ '${_preflightCooldown.inMinutes}m',+ );+ }+ }+/// Make an authenticated GET request, retrying once on 401 with a refreshed token.+ ///+ /// [sendRefreshTokenHeader] adds `x-refresh-token` from whatever the current+ /// pair is once the pre-flight has run, rather than from a value the caller+ /// captured earlier.Future<http.Response> _authGet(Uri url, {Map<String, String>? headers,+ bool sendRefreshTokenHeader = false,Duration timeout = const Duration(seconds: 15),}) async {- final h = headers ?? _headers;+ await _ensureFreshAccessToken();+ var h = headers ?? _headers;+ if (sendRefreshTokenHeader && _refreshToken != null) {+ h = {...h, 'x-refresh-token': _refreshToken!};+ }var response = await _get(url, headers: h).timeout(timeout);if (response.statusCode == 401) {debugPrint(@@ -557,6 +641,7 @@ class ApiService {Object? body,Duration timeout = const Duration(seconds: 15),}) async {+ await _ensureFreshAccessToken();final h = headers ?? _headers;var response = await _post(url, headers: h, body: body).timeout(timeout);if (response.statusCode == 401 && !_isLegacyToken) {@@ -582,6 +667,7 @@ class ApiService {Object? body,Duration timeout = const Duration(seconds: 15),}) async {+ await _ensureFreshAccessToken();final h = headers ?? _headers;var response = await _patch(url, headers: h, body: body).timeout(timeout);if (response.statusCode == 401 && !_isLegacyToken) {@@ -606,6 +692,7 @@ class ApiService {Map<String, String>? headers,Duration timeout = const Duration(seconds: 15),}) async {+ await _ensureFreshAccessToken();final h = headers ?? _headers;var response = await _delete(url, headers: h).timeout(timeout);if (response.statusCode == 401 && !_isLegacyToken) {@@ -1087,15 +1174,14 @@ class ApiService {int itemsPerPage = 20,}) async {try {- final refreshToken = _refreshToken;+ // Headers are built by _authGet AFTER its pre-flight refresh, so this+ // can't be snapshotted here - a rotation would leave both the Bearer and+ // the x-refresh-token stale, guaranteeing a 401 and a second rotation.final response = await _authGet(Uri.parse('$_cleanBaseUrl/api/me/sessions?page=$page&itemsPerPage=$itemsPerPage',),- headers: {- ..._headers,- if (refreshToken != null) 'x-refresh-token': refreshToken,- },+ sendRefreshTokenHeader: true,timeout: const Duration(seconds: 10),);if (response.statusCode == 404) {@@ -3105,10 +3191,7 @@ class ApiService {/// Get all users (admin only)Future<List<dynamic>> getUsers() async {try {- final r = await _authGet(- Uri.parse('$_cleanBaseUrl/api/users'),- headers: _headers,- );+ final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/users'));if (r.statusCode == 200) {final data = jsonDecode(r.body);if (data is List) return data;@@ -3130,10 +3213,7 @@ class ApiService {/// Get online users (admin only)Future<List<dynamic>> getOnlineUsers() async {try {- final r = await _authGet(- Uri.parse('$_cleanBaseUrl/api/users/online'),- headers: _headers,- );+ final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/users/online'));if (r.statusCode == 200) {final data = jsonDecode(r.body);if (data is Map && data['usersOnline'] is List)@@ -3198,10 +3278,7 @@ class ApiService {/// Get all backups (admin only)Future<List<dynamic>> getBackups() async {try {- final r = await _authGet(- Uri.parse('$_cleanBaseUrl/api/backups'),- headers: _headers,- );+ final r = await _authGet(Uri.parse('$_cleanBaseUrl/api/backups'));if (r.statusCode == 200) {final data = jsonDecode(r.body);return (data['backups'] as List<dynamic>?) ?? [];diff --git a/lib/services/user_account_service.dart b/lib/services/user_account_service.dartindex 3b6e1196..20c55fd0 100644--- a/lib/services/user_account_service.dart+++ b/lib/services/user_account_service.dart@@ -193,8 +193,13 @@ class UserAccountService {/// 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.+ ///+ /// SharedPreferences has no multi-key transaction, so the two keys are+ /// written in the order that makes a crash between them survivable: refresh+ /// FIRST. Dying after it leaves the old access token beside the NEW refresh+ /// token, which self-heals - the stale access token 401s and the refresh+ /// succeeds. The other order is the unrecoverable one. The write is also read+ /// back before it is called a success.Future<bool> persistRefreshedTokens(String accessToken,String? refreshToken, {@@ -224,8 +229,8 @@ class UserAccountService {);return false;}- await prefs.setString('token', accessToken);if (refreshToken != null) await prefs.setString('refresh_token', refreshToken);+ await prefs.setString('token', accessToken);if (username != null) {if (_accounts.isEmpty) await init();await updateTokens(serverUrl, username, accessToken, refreshToken: refreshToken);diff --git a/pubspec.yaml b/pubspec.yamlindex db962fd9..1c5388f3 100644--- a/pubspec.yaml+++ b/pubspec.yaml@@ -1,7 +1,7 @@name: absorbdescription: An Audiobookshelf Clientpublish_to: 'none'-version: 1.9.3+233+version: 1.9.3+234environment:sdk: '>=3.10.0 <4.0.0'