diff --git a/packages/gotrue/lib/gotrue.dart b/packages/gotrue/lib/gotrue.dart index dbe02de64..daa5c68ea 100644 --- a/packages/gotrue/lib/gotrue.dart +++ b/packages/gotrue/lib/gotrue.dart @@ -9,11 +9,13 @@ export 'src/helper.dart' show decodeJwt, validateExp; export 'src/types/auth_exception.dart'; export 'src/types/auth_response.dart' hide ToSnakeCase; export 'src/types/auth_state.dart'; +export 'src/types/error_code.dart'; export 'src/types/gotrue_async_storage.dart'; export 'src/types/jwt.dart'; export 'src/gotrue_admin_passkey_api.dart'; export 'src/types/mfa.dart'; export 'src/types/passkey.dart'; +export 'src/types/sign_out_reason.dart'; export 'src/types/types.dart'; export 'src/types/session.dart'; export 'src/types/user.dart'; diff --git a/packages/gotrue/lib/src/gotrue_client.dart b/packages/gotrue/lib/src/gotrue_client.dart index cce927256..93eb5f21d 100644 --- a/packages/gotrue/lib/src/gotrue_client.dart +++ b/packages/gotrue/lib/src/gotrue_client.dart @@ -962,7 +962,13 @@ class GoTrueClient { /// [scope] determines which sessions should be logged out. /// /// If using [SignOutScope.others] scope, no [AuthChangeEvent.signedOut] event is fired! - Future signOut({SignOutScope scope = SignOutScope.local}) async { + Future signOut({SignOutScope scope = SignOutScope.local}) => + _signOut(scope: scope, reason: SignOutReason.userInitiated); + + Future _signOut({ + required SignOutScope scope, + required SignOutReason reason, + }) async { _log.info('Signing out user with scope: ${scope.name}'); final accessToken = currentSession?.accessToken; @@ -971,7 +977,10 @@ class GoTrueClient { await _asyncStorage?.removeItem( key: '${Constants.defaultStorageKey}-code-verifier', ); - notifyAllSubscribers(AuthChangeEvent.signedOut); + notifyAllSubscribers( + AuthChangeEvent.signedOut, + signOutReason: reason, + ); } if (accessToken != null) { @@ -1129,8 +1138,16 @@ class GoTrueClient { final session = Session.fromJson(json.decode(jsonStr)); if (session == null) { // sign out to delete the local storage from supabase_flutter - await signOut(); - throw notifyException(AuthException('Initial session is missing data.')); + await _signOut( + scope: SignOutScope.local, + reason: SignOutReason.sessionMissing, + ); + throw notifyException( + AuthException( + 'Initial session is missing data.', + code: ErrorCode.sessionMissing.code, + ), + ); } _currentSession = session; @@ -1143,9 +1160,15 @@ class GoTrueClient { final session = Session.fromJson(json.decode(jsonStr)); if (session == null) { _log.warning("Can't recover session from string, session is null"); - await signOut(); + await _signOut( + scope: SignOutScope.local, + reason: SignOutReason.sessionMissing, + ); throw notifyException( - AuthException('Current session is missing data.'), + AuthException( + 'Current session is missing data.', + code: ErrorCode.sessionMissing.code, + ), ); } @@ -1165,8 +1188,16 @@ class GoTrueClient { if (_autoRefreshToken && refreshToken != null) { return await _callRefreshToken(refreshToken); } - await signOut(); - throw notifyException(AuthException('Session expired.')); + await _signOut( + scope: SignOutScope.local, + reason: SignOutReason.sessionExpired, + ); + throw notifyException( + AuthException( + 'Session expired.', + code: ErrorCode.sessionExpired.code, + ), + ); } final shouldEmitEvent = _currentSession == null || _currentSession!.user.id != session.user.id; @@ -1495,7 +1526,10 @@ class GoTrueClient { // user who just signed in. if (!_isDisposed && _sessionVersion == versionBeforeRefresh) { _removeSession(); - notifyAllSubscribers(AuthChangeEvent.signedOut); + notifyAllSubscribers( + AuthChangeEvent.signedOut, + signOutReason: SignOutReason.sessionExpired, + ); } } else if (!_isDisposed) { notifyException(error, stack); @@ -1525,6 +1559,7 @@ class GoTrueClient { AuthChangeEvent event, { Session? session, bool broadcast = true, + SignOutReason? signOutReason, }) { session ??= currentSession; if (broadcast && event != AuthChangeEvent.initialSession) { @@ -1533,7 +1568,12 @@ class GoTrueClient { 'session': session?.toJson(), }); } - final state = AuthState(event, session, fromBroadcast: !broadcast); + final state = AuthState( + event, + session, + fromBroadcast: !broadcast, + signOutReason: signOutReason, + ); _log.finest('onAuthStateChange: $state'); _onAuthStateChangeController.add(state); _onAuthStateChangeControllerSync.add(state); diff --git a/packages/gotrue/lib/src/types/auth_state.dart b/packages/gotrue/lib/src/types/auth_state.dart index cfbd17043..6975a1d58 100644 --- a/packages/gotrue/lib/src/types/auth_state.dart +++ b/packages/gotrue/lib/src/types/auth_state.dart @@ -1,18 +1,33 @@ import 'package:gotrue/src/constants.dart'; import 'package:gotrue/src/types/session.dart'; +import 'package:gotrue/src/types/sign_out_reason.dart'; class AuthState { final AuthChangeEvent event; final Session? session; + /// Why the user was signed out, when [event] is + /// [AuthChangeEvent.signedOut]. + /// + /// Lets listeners tell an explicit sign out apart from an involuntary one + /// (such as an expired session). It is `null` for every other event and for + /// `signedOut` events received from another tab via `web.BroadcastChannel`. + final SignOutReason? signOutReason; + /// Whether this state was broadcasted via `web.BroadcastChannel` on web from /// another tab or window. final bool fromBroadcast; - const AuthState(this.event, this.session, {this.fromBroadcast = false}); + const AuthState( + this.event, + this.session, { + this.fromBroadcast = false, + this.signOutReason, + }); @override String toString() { - return 'AuthState(event: ${event.name}, session: $session, fromBroadcast: $fromBroadcast)'; + return 'AuthState(event: ${event.name}, session: $session, ' + 'fromBroadcast: $fromBroadcast, signOutReason: $signOutReason)'; } } diff --git a/packages/gotrue/lib/src/types/error_code.dart b/packages/gotrue/lib/src/types/error_code.dart index 17afd2274..52302b726 100644 --- a/packages/gotrue/lib/src/types/error_code.dart +++ b/packages/gotrue/lib/src/types/error_code.dart @@ -13,6 +13,8 @@ enum ErrorCode { noAuthorization('no_authorization'), userNotFound('user_not_found'), sessionNotFound('session_not_found'), + sessionExpired('session_expired'), + sessionMissing('session_missing'), flowStateNotFound('flow_state_not_found'), flowStateExpired('flow_state_expired'), signupDisabled('signup_disabled'), diff --git a/packages/gotrue/lib/src/types/sign_out_reason.dart b/packages/gotrue/lib/src/types/sign_out_reason.dart new file mode 100644 index 000000000..4643e8fcd --- /dev/null +++ b/packages/gotrue/lib/src/types/sign_out_reason.dart @@ -0,0 +1,17 @@ +/// The reason why an [AuthChangeEvent.signedOut] event was emitted. +/// +/// Available on [AuthState.signOutReason] and lets listeners distinguish an +/// explicit sign out from an involuntary one, such as an expired session, +/// without inspecting error messages. +enum SignOutReason { + /// The user explicitly signed out by calling [GoTrueClient.signOut]. + userInitiated, + + /// The session could no longer be refreshed because its refresh token was + /// rejected (invalid or expired), so the session was removed. + sessionExpired, + + /// A stored session could not be recovered because it was missing required + /// data, so the session was removed. + sessionMissing, +} diff --git a/packages/gotrue/test/client_test.dart b/packages/gotrue/test/client_test.dart index ed626e1d9..6bdd35272 100644 --- a/packages/gotrue/test/client_test.dart +++ b/packages/gotrue/test/client_test.dart @@ -2,7 +2,6 @@ import 'dart:convert'; import 'package:dotenv/dotenv.dart'; import 'package:gotrue/gotrue.dart'; -import 'package:gotrue/src/types/error_code.dart'; import 'package:http/http.dart' as http; import 'package:http/http.dart'; import 'package:jwt_decode/jwt_decode.dart'; diff --git a/packages/gotrue/test/src/token_refresh_race_test.dart b/packages/gotrue/test/src/token_refresh_race_test.dart index 7eddf864c..dfc1b4fc8 100644 --- a/packages/gotrue/test/src/token_refresh_race_test.dart +++ b/packages/gotrue/test/src/token_refresh_race_test.dart @@ -302,15 +302,13 @@ void main() { test('signOut event is emitted when refresh fails and session is unchanged', () async { - final events = []; - client.onAuthStateChange.listen((state) { - events.add(state.event); - }); + final states = []; + client.onAuthStateChange.listen(states.add); // Set an initial session. final freshAt = _freshAccessToken(); await client.setSession('initial-token', accessToken: freshAt); - events.clear(); + states.clear(); // Now make a refresh that will fail with a non-retryable error. mockClient.tokenStatusOverride = 400; @@ -321,7 +319,68 @@ void main() { // Without any concurrent session changes, the failure should sign out. expect(client.currentSession, isNull); - expect(events, contains(AuthChangeEvent.signedOut)); + final signedOut = states.firstWhere( + (state) => state.event == AuthChangeEvent.signedOut, + ); + expect(signedOut.signOutReason, SignOutReason.sessionExpired); + }); + + test('explicit signOut reports a userInitiated reason', () async { + final states = []; + client.onAuthStateChange.listen(states.add); + + final freshAt = _freshAccessToken(); + await client.setSession('initial-token', accessToken: freshAt); + states.clear(); + + await client.signOut(); + + final signedOut = states.firstWhere( + (state) => state.event == AuthChangeEvent.signedOut, + ); + expect(signedOut.signOutReason, SignOutReason.userInitiated); + }); + + test('recoverSession with an expired session reports sessionExpired', + () async { + final states = []; + // recoverSession also surfaces the failure as a stream error, which we + // ignore here since we only assert on the emitted signedOut state. + client.onAuthStateChange.listen(states.add, onError: (_) {}); + + // Build an expired session string. With autoRefreshToken disabled it + // cannot be refreshed, so recovery signs the user out. + final expiredAt = _makeRawJwt({ + 'exp': DateTime.now().millisecondsSinceEpoch ~/ 1000 - 3600, + 'iat': DateTime.now().millisecondsSinceEpoch ~/ 1000 - 7200, + 'sub': 'mock-user-id', + }); + final expiredSession = jsonEncode({ + 'access_token': expiredAt, + 'token_type': 'bearer', + 'expires_in': -3600, + 'refresh_token': 'expired-refresh-token', + 'user': _mockUserJson, + }); + + await expectLater( + client.recoverSession(expiredSession), + throwsA( + isA().having( + (error) => error.code, + 'code', + ErrorCode.sessionExpired.code, + ), + ), + ); + + // Let the asynchronous state event flush before asserting. + await Future.delayed(Duration.zero); + + final signedOut = states.firstWhere( + (state) => state.event == AuthChangeEvent.signedOut, + ); + expect(signedOut.signOutReason, SignOutReason.sessionExpired); }); }); }