From 4a0764cce4816c087df7b2ec30ba18f500b0292c Mon Sep 17 00:00:00 2001 From: Katerina Skroumpelou Date: Fri, 5 Jun 2026 18:04:10 +0300 Subject: [PATCH 1/2] fix(auth): preserve valid session on refresh failure and cooldown repeat failures --- packages/core/auth-js/src/GoTrueClient.ts | 72 +++++- packages/core/auth-js/src/lib/constants.ts | 11 + packages/core/auth-js/src/lib/fetch.ts | 8 +- .../core/auth-js/test/GoTrueClient.test.ts | 230 ++++++++++++++++++ 4 files changed, 317 insertions(+), 4 deletions(-) diff --git a/packages/core/auth-js/src/GoTrueClient.ts b/packages/core/auth-js/src/GoTrueClient.ts index a178f26891b..b8a3a76cbf5 100644 --- a/packages/core/auth-js/src/GoTrueClient.ts +++ b/packages/core/auth-js/src/GoTrueClient.ts @@ -6,6 +6,7 @@ import { EXPIRY_MARGIN_MS, GOTRUE_URL, JWKS_TTL, + REFRESH_FAILURE_COOLDOWN_MS, STORAGE_KEY, } from './lib/constants' import { @@ -288,6 +289,17 @@ export default class GoTrueClient { protected autoRefreshTickTimeout: ReturnType | null = null protected visibilityChangedCallback: (() => Promise) | null = null protected refreshingDeferred: Deferred | null = null + /** + * Cache of the most recent refresh failure. Serial callers arriving within + * `REFRESH_FAILURE_COOLDOWN_MS` (including subsequent auto-refresh ticks) + * receive this cached result instead of firing another /token request. + * Cleared on any successful refresh (locally or via BroadcastChannel from + * another tab) and on `_removeSession`. + * + * Pairs with `refreshingDeferred`: concurrent callers share the in-flight + * promise, serial callers within the cooldown share the failure result. + */ + protected lastRefreshFailure: { result: CallRefreshTokenResult; expiresAt: number } | null = null /** * Monotonic counter incremented at the top of `_removeSession`, before any * `await`. The commit guard inside `_callRefreshToken` captures this value @@ -482,6 +494,12 @@ export default class GoTrueClient { this.broadcastChannel?.addEventListener('message', async (event) => { this._debug('received broadcast notification from other tab or client', event) + // Another tab successfully refreshed the session — any cached failure + // in this tab is stale and should not block the next refresh attempt. + if (event.data.event === 'TOKEN_REFRESHED' || event.data.event === 'SIGNED_IN') { + this.lastRefreshFailure = null + } + try { await this._notifyAllSubscribers(event.data.event, event.data.session, false) // broadcast = false so we don't get an endless loop of messages } catch (error) { @@ -4787,6 +4805,18 @@ export default class GoTrueClient { return this.refreshingDeferred.promise } + // Serial failure cooldown: every caller that arrived after a recent + // non-retryable failure receives the cached result instead of firing + // another /token request. This is what stops the proactive-refresh + // storm pattern where every `getSession()` call inside the 90s + // EXPIRY_MARGIN_MS window kept re-firing against the same broken + // refresh token. Concurrent callers already share `refreshingDeferred`; + // this cache covers serial callers spaced across cooldown windows. + if (this.lastRefreshFailure && Date.now() < this.lastRefreshFailure.expiresAt) { + this._debug('#_callRefreshToken()', 'returning cached failure (cooldown active)') + return this.lastRefreshFailure.result + } + // Refresh tokens are long-lived bearer credentials; do NOT include any // fragment of the token in the debug tag, even when `debug: true` is // enabled (logs may be forwarded to third-party services). @@ -4870,6 +4900,10 @@ export default class GoTrueClient { const result = { data: data.session, error: null } + // Refresh succeeded — clear any cached failure so the next caller + // (including the auto-refresh ticker) attempts a real refresh again. + this.lastRefreshFailure = null + this.refreshingDeferred.resolve(result) return result @@ -4879,8 +4913,40 @@ export default class GoTrueClient { if (isAuthError(error)) { const result = { data: null, error } + // Cache any AuthError so serial callers (and the next auto-refresh + // tick) within the cooldown window receive the cached failure + // synchronously instead of firing another /token call. This is what + // stops the proactive-refresh storm pattern where every getSession() + // call inside the 90s EXPIRY_MARGIN_MS window kept hammering the + // server with the same broken refresh token. + this.lastRefreshFailure = { + result, + expiresAt: Date.now() + REFRESH_FAILURE_COOLDOWN_MS, + } + if (!isAuthRetryableFetchError(error)) { - await this._removeSession() + // Non-retryable error from GoTrue. Proactive vs reactive + // distinction: a refresh fires whenever the access token is + // within EXPIRY_MARGIN_MS of expiry. If the access token is + // *still valid* at this moment, the refresh was proactive and + // the existing session is still usable until its real expiry. + // Destroying it now would log out a user whose access token + // works. If the access token has actually expired, the refresh + // token is the only credential left and it just got rejected — + // the session is genuinely dead. + const storedNow = (await getItemAsync(this.storage, this.storageKey)) as Session | null + const accessTokenStillValid = !!( + storedNow?.expires_at && storedNow.expires_at * 1000 > Date.now() + ) + + if (accessTokenStillValid) { + this._debug( + debugName, + 'proactive refresh failed, access token still valid — preserving session' + ) + } else { + await this._removeSession() + } } this.refreshingDeferred?.resolve(result) @@ -4984,6 +5050,10 @@ export default class GoTrueClient { this._sessionRemovalEpoch += 1 this._debug('#_removeSession()') + // The session is gone — no point holding on to a cached refresh failure + // for a token that no longer exists. + this.lastRefreshFailure = null + this.suppressGetSessionWarning = false await removeItemAsync(this.storage, this.storageKey) diff --git a/packages/core/auth-js/src/lib/constants.ts b/packages/core/auth-js/src/lib/constants.ts index edb77ef6f2b..29394ce3fc2 100644 --- a/packages/core/auth-js/src/lib/constants.ts +++ b/packages/core/auth-js/src/lib/constants.ts @@ -12,6 +12,17 @@ export const AUTO_REFRESH_TICK_THRESHOLD = 3 */ export const EXPIRY_MARGIN_MS = AUTO_REFRESH_TICK_THRESHOLD * AUTO_REFRESH_TICK_DURATION_MS +/** + * After a refresh fails, serial callers (including the next auto-refresh + * tick) within this window receive the cached failure instead of firing + * another /token request. Set to two ticks so each outage burns at most one + * /token call every other tick — halves the storm volume vs today without + * introducing a separate exponential-backoff mechanism. Cleared on any + * successful refresh (locally or via BroadcastChannel from another tab) and + * on `_removeSession`. + */ +export const REFRESH_FAILURE_COOLDOWN_MS = 2 * AUTO_REFRESH_TICK_DURATION_MS + export const GOTRUE_URL = 'http://localhost:9999' export const STORAGE_KEY = 'supabase.auth.token' export const AUDIENCE = '' diff --git a/packages/core/auth-js/src/lib/fetch.ts b/packages/core/auth-js/src/lib/fetch.ts index e38cbcee789..cdef4a8a5c0 100644 --- a/packages/core/auth-js/src/lib/fetch.ts +++ b/packages/core/auth-js/src/lib/fetch.ts @@ -69,10 +69,12 @@ const _getErrorMessage = (err: unknown): string => { return JSON.stringify(err) } -// 502, 503, 504: Standard server/gateway errors -// 520-524, 530: Cloudflare-specific error codes (web server down, connection timed out, etc.) +// 500, 501, 502, 503, 504: Standard server/gateway errors +// 520-529, 530: Cloudflare-specific error codes (web server down, connection timed out, etc.) // These are infrastructure errors and should not cause session invalidation. -const NETWORK_ERROR_CODES = [502, 503, 504, 520, 521, 522, 523, 524, 530] +const NETWORK_ERROR_CODES = [ + 500, 501, 502, 503, 504, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, +] export async function handleError(error: unknown) { if (!looksLikeFetchResponse(error)) { diff --git a/packages/core/auth-js/test/GoTrueClient.test.ts b/packages/core/auth-js/test/GoTrueClient.test.ts index 52d3b3eb434..208eafbe978 100644 --- a/packages/core/auth-js/test/GoTrueClient.test.ts +++ b/packages/core/auth-js/test/GoTrueClient.test.ts @@ -4213,3 +4213,233 @@ describe('GoTrueClient with skipAutoInitialize option', () => { expect(data.user).toBeDefined() }) }) + +describe('Refresh-token lifecycle (proactive/reactive, cooldown)', () => { + const plantSession = async ( + storage: ReturnType, + overrides: { secondsUntilExpiry?: number; refreshToken?: string } = {} + ) => { + const secondsUntilExpiry = overrides.secondsUntilExpiry ?? 60 + const session: Session = { + access_token: 'jwt.accesstoken.signature', + refresh_token: overrides.refreshToken ?? 'refresh-token-r1', + token_type: 'bearer', + expires_in: secondsUntilExpiry, + expires_at: Math.floor(Date.now() / 1000) + secondsUntilExpiry, + user: { id: 'user-1', email: 'u@example.com' } as any, + } + await setItemAsync(storage, STORAGE_KEY, session) + return session + } + + const buildClient = (storage: ReturnType) => + new GoTrueClient({ + url: GOTRUE_URL_SIGNUP_ENABLED_AUTO_CONFIRM_ON, + storage, + autoRefreshToken: false, + persistSession: true, + }) + + test('proactive refresh failure preserves session when access token still valid', async () => { + const storage = memoryLocalStorageAdapter() + const client = buildClient(storage) + await client.initialize() + await plantSession(storage, { secondsUntilExpiry: 60 }) + + // 400 invalid_grant — non-retryable, but access token is still valid. + // @ts-expect-error access protected for test + client._refreshAccessToken = jest.fn(async () => ({ + data: { session: null, user: null }, + error: Object.assign(new AuthError('Invalid Refresh Token: Already Used', 400), { + name: 'AuthApiError', + code: 'refresh_token_already_used', + __isAuthError: true, + }), + })) + + // @ts-expect-error access protected for test + const result = await client._callRefreshToken('refresh-token-r1') + + expect(result.data).toBeNull() + expect((result.error as AuthError)?.code).toBe('refresh_token_already_used') + + // Session preserved: storage still holds the original session. + const stored = (await getItemAsync(storage, STORAGE_KEY)) as Session | null + expect(stored).not.toBeNull() + expect(stored?.access_token).toBe('jwt.accesstoken.signature') + expect(stored?.refresh_token).toBe('refresh-token-r1') + }) + + test('reactive refresh failure removes session when access token already expired', async () => { + const storage = memoryLocalStorageAdapter() + const client = buildClient(storage) + await client.initialize() + await plantSession(storage, { secondsUntilExpiry: -60 }) // expired a minute ago + + // @ts-expect-error access protected for test + client._refreshAccessToken = jest.fn(async () => ({ + data: { session: null, user: null }, + error: Object.assign(new AuthError('Invalid Refresh Token: Already Used', 400), { + name: 'AuthApiError', + code: 'refresh_token_already_used', + __isAuthError: true, + }), + })) + + // @ts-expect-error access protected for test + const result = await client._callRefreshToken('refresh-token-r1') + + expect(result.data).toBeNull() + expect((result.error as AuthError)?.code).toBe('refresh_token_already_used') + + // Session removed: access token was already dead, refresh token rejected. + const stored = (await getItemAsync(storage, STORAGE_KEY)) as Session | null + expect(stored).toBeNull() + }) + + test('cooldown dedupes serial callers within REFRESH_FAILURE_COOLDOWN_MS', async () => { + const storage = memoryLocalStorageAdapter() + const client = buildClient(storage) + await client.initialize() + await plantSession(storage, { secondsUntilExpiry: 60 }) + + const refreshSpy = jest.fn(async () => ({ + data: { session: null, user: null }, + error: Object.assign(new AuthError('Invalid Refresh Token', 400), { + name: 'AuthApiError', + code: 'refresh_token_already_used', + __isAuthError: true, + }), + })) + // @ts-expect-error access protected for test + client._refreshAccessToken = refreshSpy + + // First call — actually attempts the refresh. + // @ts-expect-error access protected for test + await client._callRefreshToken('refresh-token-r1') + expect(refreshSpy).toHaveBeenCalledTimes(1) + + // Subsequent serial callers in the cooldown window must reuse the cached + // failure without firing another /token request. + for (let i = 0; i < 50; i++) { + // @ts-expect-error access protected for test + const result = await client._callRefreshToken('refresh-token-r1') + expect(result.data).toBeNull() + expect((result.error as AuthError)?.code).toBe('refresh_token_already_used') + } + expect(refreshSpy).toHaveBeenCalledTimes(1) + }) + + test('successful refresh clears the cooldown cache', async () => { + const storage = memoryLocalStorageAdapter() + const client = buildClient(storage) + await client.initialize() + await plantSession(storage, { secondsUntilExpiry: 60 }) + + // Plant a stale failure manually — simulates a prior cooldown still in + // effect from earlier in the session. + // @ts-expect-error access protected for test + client.lastRefreshFailure = { + result: { + data: null, + error: Object.assign(new AuthError('stale failure', 400), { + name: 'AuthApiError', + code: 'refresh_token_already_used', + __isAuthError: true, + }), + } as any, + expiresAt: Date.now() + 30_000, + } + + const newSession = { + access_token: 'jwt.new.signature', + refresh_token: 'refresh-token-r2', + token_type: 'bearer', + expires_in: 3600, + expires_at: Math.floor(Date.now() / 1000) + 3600, + user: { id: 'user-1', email: 'u@example.com' }, + } + // @ts-expect-error access protected for test + client._refreshAccessToken = jest.fn(async () => ({ + data: { session: newSession, user: newSession.user }, + error: null, + })) + + // The cooldown should be returned BEFORE the refresh runs — confirm that + // the stale cache short-circuits the call. This documents the contract. + // @ts-expect-error access protected for test + const cooled = await client._callRefreshToken('refresh-token-r1') + expect(cooled.error).not.toBeNull() + + // Now manually expire the cooldown and confirm a real refresh resets it. + // @ts-expect-error access protected for test + client.lastRefreshFailure = null + + // @ts-expect-error access protected for test + const fresh = await client._callRefreshToken('refresh-token-r1') + expect(fresh.error).toBeNull() + expect(fresh.data?.refresh_token).toBe('refresh-token-r2') + + // @ts-expect-error access protected for test + expect(client.lastRefreshFailure).toBeNull() + }) + + test('transient network error caches failure and preserves session', async () => { + const storage = memoryLocalStorageAdapter() + const client = buildClient(storage) + await client.initialize() + await plantSession(storage, { secondsUntilExpiry: 60 }) + + // Simulate DNS failure — wrapped by handleError into AuthRetryableFetchError. + // @ts-expect-error access protected for test + client._refreshAccessToken = jest.fn(async () => ({ + data: { session: null, user: null }, + error: Object.assign(new AuthError('Failed to fetch', 0), { + name: 'AuthRetryableFetchError', + __isAuthError: true, + }), + })) + + // @ts-expect-error access protected for test + const result = await client._callRefreshToken('refresh-token-r1') + expect(result.data).toBeNull() + expect((result.error as AuthError)?.name).toBe('AuthRetryableFetchError') + + // Storage MUST NOT be touched on a transient failure, regardless of + // whether the access token is still valid. + const stored = (await getItemAsync(storage, STORAGE_KEY)) as Session | null + expect(stored?.refresh_token).toBe('refresh-token-r1') + + // The failure is cached under the same single-TTL cooldown so a + // subsequent tick gets the cached failure synchronously instead of + // hitting the network again. + // @ts-expect-error access protected for test + expect(client.lastRefreshFailure).not.toBeNull() + }) + + test('_removeSession clears the cooldown cache', async () => { + const storage = memoryLocalStorageAdapter() + const client = buildClient(storage) + await client.initialize() + await plantSession(storage, { secondsUntilExpiry: 60 }) + + // @ts-expect-error access protected for test + client.lastRefreshFailure = { + result: { + data: null, + error: Object.assign(new AuthError('x', 400), { + name: 'AuthApiError', + code: 'refresh_token_already_used', + __isAuthError: true, + }), + } as any, + expiresAt: Date.now() + 30_000, + } + + // @ts-expect-error access protected for test + await client._removeSession() + + // @ts-expect-error access protected for test + expect(client.lastRefreshFailure).toBeNull() + }) +}) From b7ca8d761092dd511becccaecb73160c4169abc7 Mon Sep 17 00:00:00 2001 From: Katerina Skroumpelou Date: Tue, 9 Jun 2026 18:04:29 +0300 Subject: [PATCH 2/2] fix(auth): failimg test --- packages/core/auth-js/test/GoTrueClient.test.ts | 6 ++++++ packages/core/auth-js/test/fetch.test.ts | 4 ++-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/core/auth-js/test/GoTrueClient.test.ts b/packages/core/auth-js/test/GoTrueClient.test.ts index 208eafbe978..ec67c17d533 100644 --- a/packages/core/auth-js/test/GoTrueClient.test.ts +++ b/packages/core/auth-js/test/GoTrueClient.test.ts @@ -405,6 +405,12 @@ describe('GoTrueClient', () => { expect(refreshAccessTokenSpy).toHaveBeenCalledTimes(1) + // The failure cooldown would normally short-circuit the next serial + // caller; clear it to verify the deferred itself has been reset and + // a fresh refresh can proceed. + // @ts-expect-error 'Allow access to private lastRefreshFailure' + authWithSession.lastRefreshFailure = null + // verify the deferred has been reset and successive calls can be made // @ts-expect-error 'Allow access to private _callRefreshToken()' const { data: session3, error: error3 } = await authWithSession._callRefreshToken( diff --git a/packages/core/auth-js/test/fetch.test.ts b/packages/core/auth-js/test/fetch.test.ts index 5a1e2e3fa5d..079c1c84906 100644 --- a/packages/core/auth-js/test/fetch.test.ts +++ b/packages/core/auth-js/test/fetch.test.ts @@ -47,7 +47,7 @@ describe('fetch', () => { expect(route).toHaveBeenCalledTimes(1) }) - test('should not throw AuthRetryableFetchError upon internal server error', async () => { + test('should throw AuthRetryableFetchError upon internal server error', async () => { const route = server .get('/') .mockImplementationOnce((ctx) => { @@ -60,7 +60,7 @@ describe('fetch', () => { const url = server.getURL().toString() - await expect(_request(fetch, 'GET', url)).rejects.not.toBeInstanceOf(AuthRetryableFetchError) + await expect(_request(fetch, 'GET', url)).rejects.toBeInstanceOf(AuthRetryableFetchError) expect(route).toHaveBeenCalledTimes(1) })