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 4700eb394..ad438ba83 100644 --- a/packages/gotrue/lib/src/gotrue_client.dart +++ b/packages/gotrue/lib/src/gotrue_client.dart @@ -104,6 +104,12 @@ class GoTrueClient { /// otherwise Dart will rethrow the error as an unhandled zone exception and /// crash the app. /// + /// When the user is signed out because the session could not be recovered + /// (e.g. an invalid or expired refresh token), an + /// [AuthChangeEvent.signedOut] event is emitted with [AuthState.signOutReason] + /// set to the matching [SignOutReason], so you can tell it apart from an + /// explicit [signOut] without relying on the `onError` handler. + /// /// ```dart /// supabase.auth.onAuthStateChange.listen( /// (data) { @@ -954,7 +960,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; @@ -963,7 +975,10 @@ class GoTrueClient { await _asyncStorage?.removeItem( key: '${Constants.defaultStorageKey}-code-verifier', ); - notifyAllSubscribers(AuthChangeEvent.signedOut); + notifyAllSubscribers( + AuthChangeEvent.signedOut, + signOutReason: reason, + ); } if (accessToken != null) { @@ -1111,8 +1126,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; @@ -1126,10 +1149,16 @@ 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, + ); // The `catch` below notifies subscribers, so throw without notifying // here to avoid emitting the error onto the stream twice. - throw AuthException('Current session is missing data.'); + throw AuthException( + 'Current session is missing data.', + code: ErrorCode.sessionMissing.code, + ); } if (!session.isExpired) { @@ -1156,8 +1185,14 @@ class GoTrueClient { final token = session.refreshToken; if (!_autoRefreshToken || token == null) { - await signOut(); - throw AuthException('Session expired.'); + await _signOut( + scope: SignOutScope.local, + reason: SignOutReason.sessionExpired, + ); + throw AuthException( + 'Session expired.', + code: ErrorCode.sessionExpired.code, + ); } refreshToken = token; } catch (error, stackTrace) { @@ -1481,7 +1516,10 @@ class GoTrueClient { // refreshing, otherwise we'd sign out a 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); @@ -1504,6 +1542,7 @@ class GoTrueClient { AuthChangeEvent event, { Session? session, bool broadcast = true, + SignOutReason? signOutReason, }) { session ??= currentSession; if (broadcast && event != AuthChangeEvent.initialSession) { @@ -1512,7 +1551,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..94f6b96b8 100644 --- a/packages/gotrue/lib/src/types/auth_state.dart +++ b/packages/gotrue/lib/src/types/auth_state.dart @@ -1,18 +1,37 @@ 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 [GoTrueClient.signOut] apart from an + /// involuntary sign out, such as an invalid or expired refresh token, directly + /// from the `signedOut` event rather than from the matching stream error. An + /// `onError` handler is still needed to catch the other exceptions emitted on + /// the stream. It is `null` for every event other than + /// [AuthChangeEvent.signedOut] 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?.name})'; } } 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..8703cc699 --- /dev/null +++ b/packages/gotrue/lib/src/types/sign_out_reason.dart @@ -0,0 +1,21 @@ +/// 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. + /// + /// Matches the [ErrorCode.sessionExpired] thrown on the stream. + sessionExpired, + + /// A stored session could not be recovered because it was missing required + /// data, so the session was removed. + /// + /// Matches the [ErrorCode.sessionMissing] thrown on the stream. + sessionMissing, +} diff --git a/packages/gotrue/test/client_test.dart b/packages/gotrue/test/client_test.dart index 74bd11da8..0f9c35322 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/refresh_token_race_test.dart b/packages/gotrue/test/refresh_token_race_test.dart index 97ee644e0..f8eba4455 100644 --- a/packages/gotrue/test/refresh_token_race_test.dart +++ b/packages/gotrue/test/refresh_token_race_test.dart @@ -129,6 +129,28 @@ class RefreshTokenTrackingHttpClient extends BaseClient { } } +/// HTTP client that always rejects a refresh with a non-retryable +/// "invalid refresh token" error, simulating a revoked or expired token. +class InvalidRefreshTokenHttpClient extends BaseClient { + @override + Future send(BaseRequest request) async { + return StreamedResponse( + Stream.value( + utf8.encode( + jsonEncode({ + 'code': 'refresh_token_not_found', + 'error_code': 'refresh_token_not_found', + 'msg': 'Invalid Refresh Token: Refresh Token Not Found', + }), + ), + ), + 400, + request: request, + headers: {'x-sb-api-version': '2024-01-01'}, + ); + } +} + /// Creates an expired session string for the test user (userId1) String createExpiredSessionForUser1() { final expireDateTime = DateTime.now().subtract(Duration(hours: 1)); @@ -443,6 +465,76 @@ void main() { 'Should not attempt refresh when current session is valid for same user'); }); + test( + 'signedOut event carries the sign-out reason on an invalid refresh ' + 'token', () async { + final client = GoTrueClient( + url: gotrueUrl, + asyncStorage: TestAsyncStorage(), + httpClient: InvalidRefreshTokenHttpClient(), + ); + + AuthState? signedOutState; + final subscription = client.onAuthStateChange.listen( + (state) { + if (state.event == AuthChangeEvent.signedOut) { + signedOutState = state; + } + }, + onError: (_) {}, + ); + + final expiredSession = createExpiredSessionForUser1(); + await expectLater( + client.recoverSession(expiredSession), + throwsA(isA()), + ); + + await pumpEventQueue(); + + expect(signedOutState, isNotNull, + reason: 'An invalid refresh token should sign the user out'); + expect(signedOutState!.signOutReason, SignOutReason.sessionExpired, + reason: 'The signedOut event should report why the session ended'); + expect(signedOutState!.session, isNull); + expect(client.currentSession, isNull); + + await subscription.cancel(); + }); + + test( + 'signedOut event reports a userInitiated reason on an explicit ' + 'signOut', () async { + final httpClient = RefreshTokenTrackingHttpClient(); + final client = GoTrueClient( + url: gotrueUrl, + asyncStorage: TestAsyncStorage(), + httpClient: httpClient, + ); + + await client.recoverSession(createExpiredSessionForUser1()); + expect(client.currentSession, isNotNull); + + AuthState? signedOutState; + final subscription = client.onAuthStateChange.listen( + (state) { + if (state.event == AuthChangeEvent.signedOut) { + signedOutState = state; + } + }, + onError: (_) {}, + ); + + await client.signOut(); + await pumpEventQueue(); + + expect(signedOutState, isNotNull); + expect(signedOutState!.signOutReason, SignOutReason.userInitiated, + reason: 'An explicit signOut should report a userInitiated reason'); + + await subscription.cancel(); + }); + test('recoverSession stays in the stack trace when the refresh fails', () async { final httpClient = RefreshTokenTrackingHttpClient(); diff --git a/sdk-compliance.yaml b/sdk-compliance.yaml index 255dc28a2..7ac630010 100644 --- a/sdk-compliance.yaml +++ b/sdk-compliance.yaml @@ -59,6 +59,11 @@ features: note: "Default scope is local (current session); JS defaults to global (all sessions)." auth.session.auto_refresh: implemented auth.session.subscribe_auth_events: implemented + auth.session.sign_out_reason: + status: implemented + symbols: + - AuthState.signOutReason + - SignOutReason # auth — identities auth.identities.link_identity: