Skip to content
Merged
16 changes: 10 additions & 6 deletions MIGRATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -1212,16 +1212,20 @@ if (response.redirectType == AuthRedirectType.passwordRecovery) {
revoke request, so with `SignOutScope.global` an offline device was signed out while the other
devices stayed signed in, and the token needed to retry was gone.

- With `SignOutScope.local`, the default, signing out on the device completes right away and no
longer throws. The session is revoked on the server in the background, and a failure to do so is
- With `SignOutScope.local`, the default, the session is removed from the device first, so signing
out works offline and `AuthSignedOut` is emitted right away. `signOut()` then waits up to 10
seconds for the server to revoke the session, refreshing an expired access token first, so
disposing the client afterwards cannot abort the request. It no longer throws: a failed revoke is
logged.
- With `SignOutScope.global` and `SignOutScope.others` the server is asked first, after refreshing
an expired access token. When that fails, `signOut()` throws and the session is kept, so you can
retry. `SignOutScope.global` signs out on the device once the server has revoked the sessions.
an expired access token. When that fails, including when the access token has expired and cannot
be refreshed, `signOut()` throws and the session is kept, so you can retry.
`SignOutScope.global` signs out on the device once the server has revoked the sessions.

Remove any `try`/`catch` around a local `signOut()` that only existed to ignore offline failures.
Where you sign out globally, handle the exception, for example by offering a retry or falling back
to a local sign-out.
Since the session is gone from the device as soon as `signOut()` is called, you can navigate away
without awaiting it. Where you sign out globally, handle the exception, for example by offering a
retry or falling back to a local sign-out.

#### `FlutterWebAuth2OAuthLauncher` reports cancel and exchange failures without throwing

Expand Down
231 changes: 157 additions & 74 deletions packages/supabase_auth/lib/src/auth_client.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1489,80 +1489,108 @@ class AuthClient {
///
/// [scope] determines which sessions should be logged out.
///
/// With [SignOutScope.local] the session is removed from this device right
/// away, so signing out works offline. Revoking it on the server runs in
/// the background and is best effort: when that fails it is logged rather
/// than thrown, and the refresh token stays valid on the server until it
/// expires.
/// With [SignOutScope.local] the session is removed from this device and
/// [AuthChangeEvent.signedOut] is emitted as soon as this is called, so
/// signing out works offline and the app can navigate away without awaiting
/// the returned future. The session is then revoked on the server,
/// refreshing an expired access token before. The future waits for the
/// revoke for up to 10 seconds, so disposing the client after awaiting it
/// cannot abort a revoke that finished in time. A revoke still running
/// after that continues in the background. It never throws: the session is
/// already gone from this device, so a failed revoke is logged, and the
/// refresh token stays valid on the server until it expires.
///
/// With [SignOutScope.global] and [SignOutScope.others] the sessions are
/// revoked on the server first, refreshing an expired access token before.
/// When that fails, this throws and the session is kept, so the call can be
/// retried. With [SignOutScope.global] the session is removed from this
/// device once the server has revoked it, unless another sign-in or
/// sign-out happened in the meantime.
/// retried. When the server rejects the refresh token, the session can no
/// longer be used, so the failed refresh signs out this device as it does
/// for [getSession], and this throws. With [SignOutScope.global] the
/// session is removed from this device once the server has revoked it,
/// unless another sign-in or sign-out happened in the meantime.
///
/// If using [SignOutScope.others] scope, no [AuthChangeEvent.signedOut] event
/// is fired!
Future<void> signOut({SignOutScope scope = SignOutScope.local}) =>
_signOut(scope: scope, reason: SignOutReason.userInitiated);

Future<void> _signOut({
required SignOutScope scope,
required SignOutReason reason,
}) async {
/// is fired, unless the refresh token was rejected.
Future<void> signOut({SignOutScope scope = SignOutScope.local}) async {
authLogger.info('Signing out user with scope: ${scope.name}');

if (scope == SignOutScope.local) {
final accessToken = currentSession?.accessToken;
await _signOutLocally(reason);
if (accessToken != null) {
unawaited(
_revokeSessions(accessToken, scope).then(
(_) {},
onError: (Object error, StackTrace stackTrace) {
authLogger.warning(
'Signed out locally, but could not revoke the session on the '
'server',
error,
stackTrace,
);
},
),
);
final session = _currentSession;
await _signOutLocally(SignOutReason.userInitiated);
if (session != null) {
await _revokeRemovedSessionOrLog(session);
Comment thread
spydon marked this conversation as resolved.
Resolved
}
return;
}

// An expired access token would be rejected with a 401, which counts as
// already signed out, so the sessions would never be revoked.
String? accessToken;
final sessionBeforeRefresh = _currentSession;
Session? session;
try {
accessToken = (await getSession())?.accessToken;
session = await getSession();
} on AuthException {
if (_currentSession == null) {
// The failed refresh has already signed the session out.
await _pkceVerifierStore?.removeAll();
return;
final current = _currentSession;
if (current == null) {
// The failed refresh has already signed this device out, but no
// session was revoked on the server.
if (scope == SignOutScope.global) {
await _removePkceVerifiers();
}
Comment thread
spydon marked this conversation as resolved.
Resolved
rethrow;
}
// The server rejects an expired access token with a 401, so the
// sessions could not be revoked with it.
if (!identical(current, sessionBeforeRefresh) ||
current.isExpiredWithoutMargin) {
rethrow;
}
accessToken = _currentSession?.accessToken;
session = current;
}
// A sign-in or sign-out that happened while the session was refreshed or
// the request was in flight is newer than this sign-out.
final isCurrentSession = identical(session, _currentSession);
final versionBeforeRevoke = _sessionVersion;
Comment thread
spydon marked this conversation as resolved.
Resolved
if (accessToken != null) {
await _revokeSessions(accessToken, scope);
if (session != null) {
await _revokeSessions(session, scope);
}
// A sign-in or sign-out that happened while the request was in flight is
// newer than this sign-out.
if (scope == SignOutScope.global &&
isCurrentSession &&
_sessionVersion == versionBeforeRevoke) {
await _signOutLocally(reason);
await _signOutLocally(SignOutReason.userInitiated);
}
}

/// Signs out on this device for [reason], revoking the session on the
/// server in the background on a best effort basis.
Future<void> _discardSession(SignOutReason reason) async {
final session = _currentSession;
await _signOutLocally(reason);
if (session != null) {
unawaited(_revokeRemovedSessionOrLog(session));
}
}

/// Revokes [session] like [_revokeRemovedSession], logging a failure
/// instead of throwing it.
Future<void> _revokeRemovedSessionOrLog(Session session) async {
try {
await _revokeRemovedSession(session);
} catch (error, stackTrace) {
authLogger.warning(
'Signed out locally, but could not revoke the session on the server',
error,
stackTrace,
);
}
}

/// Removes the session and every pending PKCE verifier from this device.
Future<void> _signOutLocally(SignOutReason reason) async {
_removeSession();
notifyAllSubscribers(AuthChangeEvent.signedOut, signOutReason: reason);
await _removePkceVerifiers();
}

Future<void> _removePkceVerifiers() async {
try {
await _pkceVerifierStore?.removeAll();
} catch (error, stackTrace) {
Expand All @@ -1574,20 +1602,79 @@ class AuthClient {
}
}

/// Revokes the sessions [scope] covers on the server.
Future<void> _revokeSessions(String accessToken, SignOutScope scope) async {
/// Refresh and logout errors that prove the session can no longer be used,
/// so there is nothing left to revoke.
static final _sessionGoneCodes = {
ErrorCode.refreshTokenNotFound.code,
ErrorCode.refreshTokenAlreadyUsed.code,
ErrorCode.sessionNotFound.code,
ErrorCode.sessionExpired.code,
ErrorCode.userNotFound.code,
};

/// Revokes [session], which was already removed from this device, on the
/// server, refreshing it first when its access token is about to expire.
Future<void> _revokeRemovedSession(Session session) async {
Future<void> revoke() async {
var current = session;
if (current.isExpired) {
final refreshToken = current.refreshToken;
try {
if (refreshToken == null) {
throw AuthException(
'Could not revoke the session on the server, its access token '
'has expired and it has no refresh token.',
errorCode: ErrorCode.sessionExpired.code,
);
}
// A single attempt, so the logout request still fits in the
// timeout.
current = await _refreshAccessToken(
refreshToken,
attemptOptions: const SupabaseRetryOptions(enabled: false),
);
} on AuthException catch (error) {
if (error is AuthApiException &&
_sessionGoneCodes.contains(error.errorCode)) {
return;
}
// An access token inside the expiry margin can still revoke the
// session.
if (current.isExpiredWithoutMargin) rethrow;
}
}
await _revokeSessions(current, SignOutScope.local);
}

try {
await revoke().timeout(AuthConstants.signOutRevokeTimeout);
} on TimeoutException catch (error) {
throw AuthRetryableFetchException(
message: 'Timed out revoking the session on the server.',
cause: error,
);
}
}

/// Revokes the sessions [scope] covers on the server, using the access token
/// of [session].
Future<void> _revokeSessions(Session session, SignOutScope scope) async {
try {
await admin.signOut(accessToken, scope: scope);
await admin.signOut(session.accessToken, scope: scope);
} on AuthApiException catch (error) {
// Ignore 401s since an invalid or expired JWT should sign out the
// current session.
// Ignore 403s since the user might not exist anymore.
// Ignore 404s since the user might not exist anymore.
if (error.statusCode != 401 &&
error.statusCode != 403 &&
error.statusCode != 404) {
rethrow;
}
// A rejected access token, such as an expired one, says nothing about
// the sessions. Servers that answer without an error code only say so
// in the message.
final ignored = switch (error) {
AuthApiException(:final errorCode?) => _sessionGoneCodes.contains(
errorCode,
),
AuthApiException(statusCode: 404) => true,
AuthApiException(statusCode: 401 || 403) =>
!error.message.contains('expired') && !session.isExpiredWithoutMargin,
_ => false,
};
if (!ignored) rethrow;
}
}

Expand Down Expand Up @@ -1729,10 +1816,7 @@ class AuthClient {
final session = Session.fromJson(json.decode(jsonString));
if (session == null) {
// sign out to delete the local storage from supabase_flutter
await _signOut(
scope: SignOutScope.local,
reason: SignOutReason.sessionMissing,
);
await _discardSession(SignOutReason.sessionMissing);
throw notifyException(
AuthSessionMissingException(
message: 'Initial session is missing data.',
Expand Down Expand Up @@ -1763,10 +1847,7 @@ class AuthClient {
authLogger.warning(
"Can't recover session from string, session is null",
);
await _signOut(
scope: SignOutScope.local,
reason: SignOutReason.sessionMissing,
);
await _discardSession(SignOutReason.sessionMissing);
// The `catch` below notifies subscribers, so throw without notifying
// here to avoid emitting the error onto the stream twice.
throw AuthSessionMissingException(
Expand Down Expand Up @@ -1801,10 +1882,7 @@ class AuthClient {

final token = session.refreshToken;
if (token == null) {
await _signOut(
scope: SignOutScope.local,
reason: SignOutReason.sessionExpired,
);
await _discardSession(SignOutReason.sessionExpired);
throw AuthException(
'Session expired.',
errorCode: ErrorCode.sessionExpired.code,
Expand Down Expand Up @@ -1931,15 +2009,20 @@ class AuthClient {

/// Generates a new JWT.
/// [refreshToken] A valid refresh token that was returned on login.
Future<Session> _refreshAccessToken(String refreshToken) async {
Future<Session> _refreshAccessToken(
String refreshToken, {
SupabaseRetryOptions? attemptOptions,
}) async {
final effectiveRetryOptions = attemptOptions ?? retryOptions;
final startedAt = clock.now();
var attempt = 0;
Duration? retryAfterOf(Object outcome) => outcome is SupabaseApiException
? parseRetryAfter(outcome.headers)
: null;
final unjittered = retryOptions.copyWith(randomizationFactor: 0);
final unjittered = effectiveRetryOptions.copyWith(randomizationFactor: 0);
Duration longestBackoff(int retries) =>
unjittered.delay(retries) * (1 + retryOptions.randomizationFactor);
unjittered.delay(retries) *
(1 + effectiveRetryOptions.randomizationFactor);

return await retry(
() async {
Expand All @@ -1957,7 +2040,7 @@ class AuthClient {
);
return _sessionFromResponse(response);
},
options: retryOptions,
options: effectiveRetryOptions,
retryAfter: retryAfterOf,
retryIf: (e) {
// Do not retry if the next retry could come after the next tick. The
Expand Down
4 changes: 4 additions & 0 deletions packages/supabase_auth/lib/src/auth_constants.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ class AuthConstants {
/// Current session will be checked for refresh at this interval.
static const autoRefreshTickDuration = Duration(seconds: 10);

/// How long a local sign out waits for the session to be revoked on the
/// server.
static const signOutRevokeTimeout = Duration(seconds: 10);

/// A token refresh will be attempted this many ticks before the current
/// session expires.
static const autoRefreshTickThreshold = 3;
Expand Down
1 change: 1 addition & 0 deletions packages/supabase_auth/pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ dev_dependencies:
dotenv: ^4.2.0
supabase_lints: ^0.1.2
supabase_test: 0.5.2
fake_async: ^1.3.3
test: ^1.25.0
otp: ^3.2.0

Expand Down
Loading
Loading