Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
53 changes: 52 additions & 1 deletion packages/core/auth-js/src/GoTrueClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,23 @@ export default class GoTrueClient {
* Keep extra care to never reject or throw uncaught errors
*/
protected initializePromise: Promise<InitializeResult> | null = null
/**
* Non-null only while `initialize()` is running. While open,
* `_notifyAllSubscribers` enqueues init-chain notifications (those fired with
* `broadcast = true`, i.e. from `_recoverAndRefresh`) into this array instead
* of firing directly, so that `initializePromise` is guaranteed to be
* resolved before any subscriber callback runs. Callbacks that call
* `getSession()` / `getUser()` etc. would otherwise deadlock because those
* methods await `initializePromise`. Notifications from the incoming
* BroadcastChannel handler (`broadcast = false`) are not enqueued — they fire
* immediately. Flushed (in order) by `initialize()` after `initializePromise`
* settles.
*/
private _pendingInitNotifications: Array<{
event: AuthChangeEvent
session: Session | null
broadcast: boolean
}> | null = null
protected detectSessionInUrl:
| boolean
| ((url: URL, params: { [parameter: string]: string }) => boolean) = true
Expand Down Expand Up @@ -584,6 +601,16 @@ export default class GoTrueClient {
return await this.initializePromise
}

// Open the notification queue before _initialize() runs so that every
// _notifyAllSubscribers call inside the init chain enqueues instead of
// firing. Without this, a callback receiving SIGNED_IN (or TOKEN_REFRESHED
// / SIGNED_OUT) during _recoverAndRefresh would deadlock if it called
// getSession() / getUser() — those methods await initializePromise, which
// can only resolve after the callback returns, which can only return after
// getSession() resolves. The queue is flushed below after initializePromise
// has settled, so callbacks run with a fully resolved initializePromise.
this._pendingInitNotifications = []

this.initializePromise = (async () => {
if (this.lock != null) {
// TODO(v3): remove legacy lock path
Expand All @@ -594,7 +621,17 @@ export default class GoTrueClient {
return await this._initialize()
})()

return await this.initializePromise
const result = await this.initializePromise

// initializePromise is now resolved — flush queued notifications in order.
// Callbacks can safely call getSession() / getUser() / signOut() etc.
const queue = this._pendingInitNotifications ?? []
this._pendingInitNotifications = null
for (const n of queue) {
await this._notifyAllSubscribers(n.event, n.session, n.broadcast)
}

return result
}

/**
Expand Down Expand Up @@ -5011,6 +5048,20 @@ export default class GoTrueClient {
session: Session | null,
broadcast = true
) {
if (this._pendingInitNotifications !== null && broadcast) {
// We're inside initialize() before initializePromise has resolved, and
// this notification originates from the init chain (_recoverAndRefresh),
// which always fires with broadcast = true. Enqueue instead of firing so
// that callbacks can safely call getSession() / getUser() without
// deadlocking on initializePromise.
//
// Notifications with broadcast = false come from the incoming
// BroadcastChannel handler (a cross-tab event), not the init chain, so
// they are fired immediately to preserve multi-tab ordering.
this._pendingInitNotifications.push({ event, session, broadcast })
return
}

const debugName = `#_notifyAllSubscribers(${event})`
this._debug(debugName, 'begin', session, `broadcast = ${broadcast}`)

Expand Down
127 changes: 127 additions & 0 deletions packages/core/auth-js/test/GoTrueClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3702,6 +3702,133 @@ describe('Lockless coordination (default) and legacy lock opt-in', () => {
})
})

describe('initializePromise deadlock fix', () => {
// Regression tests for: getSession()/getUser() called from inside an
// onAuthStateChange callback that fires during _recoverAndRefresh().
// Before the fix, those methods awaited initializePromise which was still
// pending — causing a permanent circular deadlock.

const plantInitSession = async (
storage: ReturnType<typeof memoryLocalStorageAdapter>,
secondsUntilExpiry: number
): Promise<Session> => {
const session: Session = {
access_token: 'jwt.accesstoken.signature',
refresh_token: 'refresh-token-init-test',
token_type: 'bearer',
expires_in: secondsUntilExpiry,
expires_at: Math.floor(Date.now() / 1000) + secondsUntilExpiry,
user: { id: 'user-init', email: 'init@example.com' } as any,
}
await setItemAsync(storage, STORAGE_KEY, session)
return session
}

const noDeadlock = (promise: Promise<unknown>) =>
Promise.race([
promise,
new Promise((_, reject) =>
setTimeout(() => reject(new Error('deadlock: promise did not settle within 2s')), 2000)
),
])

test('getSession() inside SIGNED_IN callback (valid session at init) resolves without deadlock', async () => {
const storage = memoryLocalStorageAdapter()
// 120s > EXPIRY_MARGIN_MS (90s): session is valid, no refresh needed.
// _recoverAndRefresh fires SIGNED_IN synchronously — the old code path
// that deadlocked.
await plantInitSession(storage, 120)

const client = new GoTrueClient({
url: GOTRUE_URL_SIGNUP_ENABLED_AUTO_CONFIRM_ON,
storage,
autoRefreshToken: false,
persistSession: true,
skipAutoInitialize: true,
})

let sessionFromCallback: Session | null | undefined = undefined
client.onAuthStateChange(async (event) => {
if (event === 'SIGNED_IN') {
const { data } = await client.getSession()
sessionFromCallback = data.session
}
})

await expect(noDeadlock(client.initialize())).resolves.toBeDefined()
expect(sessionFromCallback).not.toBeUndefined()
expect(sessionFromCallback).not.toBeNull()
})

test('getSession() inside TOKEN_REFRESHED callback (near-expiry session at init) resolves without deadlock', async () => {
const storage = memoryLocalStorageAdapter()
// 60s < EXPIRY_MARGIN_MS (90s): triggers proactive refresh during init.
// _callRefreshToken fires TOKEN_REFRESHED — another deadlock path.
await plantInitSession(storage, 60)

const client = new GoTrueClient({
url: GOTRUE_URL_SIGNUP_ENABLED_AUTO_CONFIRM_ON,
storage,
autoRefreshToken: true,
persistSession: true,
skipAutoInitialize: true,
})

// @ts-expect-error access protected for test
client._refreshAccessToken = jest.fn(async () => ({
data: {
session: {
access_token: 'new.access.token',
refresh_token: 'new-refresh-token',
token_type: 'bearer',
expires_in: 3600,
expires_at: Math.floor(Date.now() / 1000) + 3600,
user: { id: 'user-init', email: 'init@example.com' } as any,
},
},
error: null,
}))

let sessionFromCallback: Session | null | undefined = undefined
client.onAuthStateChange(async (event) => {
if (event === 'TOKEN_REFRESHED') {
const { data } = await client.getSession()
sessionFromCallback = data.session
}
})

await expect(noDeadlock(client.initialize())).resolves.toBeDefined()
expect(sessionFromCallback).not.toBeUndefined()
})

test('initialize() fires SIGNED_IN after initializePromise resolves (getSession works in callback)', async () => {
const storage = memoryLocalStorageAdapter()
await plantInitSession(storage, 120)

const client = new GoTrueClient({
url: GOTRUE_URL_SIGNUP_ENABLED_AUTO_CONFIRM_ON,
storage,
autoRefreshToken: false,
persistSession: true,
skipAutoInitialize: true,
})

// Track whether initializePromise was resolved at the time the callback ran.
let initResolvedDuringCallback = false
client.onAuthStateChange(async (event) => {
if (event === 'SIGNED_IN') {
// @ts-expect-error access protected for test
initResolvedDuringCallback = client.initializePromise !== null
}
})

await noDeadlock(client.initialize())
// The SIGNED_IN callback ran after initializePromise was set (non-null),
// meaning it was already resolved when the callback executed.
expect(initResolvedDuringCallback).toBe(true)
})
})

describe('dispose() lifecycle', () => {
test('idempotent: safe to call repeatedly', async () => {
const client = new GoTrueClient({
Expand Down
Loading