Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
21 commits
Select commit Hold shift + click to select a range
7b55eec
fix(gotrue): avoid duplicate auth error on recoverSession with invali…
spydon Jun 22, 2026
2aa1d1d
Merge branch 'main' into fix/recover-session-duplicate-auth-error
spydon Jun 22, 2026
f59a650
fix(gotrue): scope recoverSession fix to the refresh path only
spydon Jun 22, 2026
ad56b14
refactor(gotrue): move recoverSession refresh call outside the catch
spydon Jun 22, 2026
c0f4145
feat(gotrue): surface the sign-out reason on the signedOut event
spydon Jun 22, 2026
4d08f78
docs(gotrue): tighten recoverSession comment on the refresh path
spydon Jun 22, 2026
18fdc04
Merge branch 'fix/recover-session-duplicate-auth-error' into feat/sig…
spydon Jun 22, 2026
510262d
fix(gotrue): await refresh in recoverSession to keep it in stack traces
spydon Jun 22, 2026
9cf40b2
Merge branch 'fix/recover-session-duplicate-auth-error' into feat/sig…
spydon Jun 22, 2026
cd68201
fix(gotrue): keep recoverSession and caller in the stack trace on ref…
spydon Jun 22, 2026
8bc73c3
Merge branch 'fix/recover-session-duplicate-auth-error' into feat/sig…
spydon Jun 22, 2026
934b46c
test(gotrue): drop redundant comment in wrong refresh token test
spydon Jun 22, 2026
b3c3574
Merge branch 'fix/recover-session-duplicate-auth-error' into feat/sig…
spydon Jun 22, 2026
946f200
fix(gotrue): stop emitting recoverSession errors to the stream twice
spydon Jun 22, 2026
d9eb033
fix(gotrue): stop emitting recoverSession errors to the stream twice
spydon Jun 22, 2026
5d6c8e1
Merge branch 'fix/recover-session-duplicate-auth-error' into feat/sig…
spydon Jun 22, 2026
19f7d2d
refactor(gotrue): use a typed SignOutReason instead of an exception
spydon Jun 24, 2026
48b5746
Merge remote-tracking branch 'origin/main' into feat/signed-out-reason
spydon Jun 26, 2026
5f34275
docs(gotrue): clarify onError note and link error codes from SignOutR…
spydon Jun 26, 2026
479456e
chore: declare sign_out_reason capability in sdk-compliance
spydon Jun 26, 2026
967471c
Merge branch 'main' into feat/signed-out-reason
spydon Jun 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions packages/gotrue/lib/gotrue.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
64 changes: 54 additions & 10 deletions packages/gotrue/lib/src/gotrue_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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<void> signOut({SignOutScope scope = SignOutScope.local}) async {
Future<void> signOut({SignOutScope scope = SignOutScope.local}) =>
_signOut(scope: scope, reason: SignOutReason.userInitiated);

Future<void> _signOut({
required SignOutScope scope,
required SignOutReason reason,
}) async {
_log.info('Signing out user with scope: ${scope.name}');
final accessToken = currentSession?.accessToken;

Expand All @@ -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) {
Expand Down Expand Up @@ -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;
Expand All @@ -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) {
Expand All @@ -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) {
Expand Down Expand Up @@ -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);
Expand All @@ -1504,6 +1542,7 @@ class GoTrueClient {
AuthChangeEvent event, {
Session? session,
bool broadcast = true,
SignOutReason? signOutReason,
}) {
session ??= currentSession;
if (broadcast && event != AuthChangeEvent.initialSession) {
Expand All @@ -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);
Expand Down
23 changes: 21 additions & 2 deletions packages/gotrue/lib/src/types/auth_state.dart
Original file line number Diff line number Diff line change
@@ -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})';
}
}
2 changes: 2 additions & 0 deletions packages/gotrue/lib/src/types/error_code.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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'),
Expand Down
21 changes: 21 additions & 0 deletions packages/gotrue/lib/src/types/sign_out_reason.dart
Original file line number Diff line number Diff line change
@@ -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 {
Comment thread
Vinzent03 marked this conversation as resolved.
Resolved
/// 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,
}
1 change: 0 additions & 1 deletion packages/gotrue/test/client_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
92 changes: 92 additions & 0 deletions packages/gotrue/test/refresh_token_race_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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<StreamedResponse> 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));
Expand Down Expand Up @@ -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<AuthException>()),
);

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();
Expand Down
5 changes: 5 additions & 0 deletions sdk-compliance.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
Loading