Skip to content

fix: resolve & reset deferred upon refresh error #339

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Aug 10, 2022
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
33 changes: 17 additions & 16 deletions src/GoTrueClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import type {
SignInWithPasswordlessCredentials,
AuthResponse,
OAuthResponse,
CallRefreshTokenResult,
} from './lib/types'

polyfillGlobalThis() // Make "globalThis" available
Expand Down Expand Up @@ -82,10 +83,7 @@ export default class GoTrueClient {
protected refreshTokenTimer?: ReturnType<typeof setTimeout>
// eslint-disable-next-line @typescript-eslint/no-inferrable-types
protected networkRetries: number = 0
protected refreshingDeferred: Deferred<{
session: Session
error: null
}> | null = null
protected refreshingDeferred: Deferred<CallRefreshTokenResult> | null = null

/**
* Create a new client for use in the browser.
Expand Down Expand Up @@ -779,17 +777,14 @@ export default class GoTrueClient {
}
}

private async _callRefreshToken(refreshToken: string) {
try {
// refreshing is already in progress
if (this.refreshingDeferred) {
return await this.refreshingDeferred.promise
}
private async _callRefreshToken(refreshToken: string): Promise<CallRefreshTokenResult> {
// refreshing is already in progress
if (this.refreshingDeferred) {
return this.refreshingDeferred.promise
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Moved that out of the try block and removed the await. Otherwise a rejection would fall into catch and finally multiple times. As _callRefreshToken throws non AuthErorr's that should be the expected behavior.

}

this.refreshingDeferred = new Deferred<{
session: Session
error: null
}>()
try {
this.refreshingDeferred = new Deferred<CallRefreshTokenResult>()

if (!refreshToken) {
throw new AuthSessionMissingError()
Expand All @@ -804,15 +799,21 @@ export default class GoTrueClient {
const result = { session, error: null }

this.refreshingDeferred.resolve(result)
this.refreshingDeferred = null

return result
} catch (error) {
if (isAuthError(error)) {
return { session: null, error }
const result = { session: null, error }

this.refreshingDeferred?.resolve(result)

return result
}

this.refreshingDeferred?.reject(error)
throw error
} finally {
this.refreshingDeferred = null
}
}

Expand Down
10 changes: 10 additions & 0 deletions src/lib/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -272,3 +272,13 @@ type PromisifyMethods<T> = {
}

export type SupportedStorage = PromisifyMethods<Pick<Storage, 'getItem' | 'setItem' | 'removeItem'>>

export type CallRefreshTokenResult =
| {
session: Session
error: null
}
| {
session: null
error: AuthError
}
84 changes: 84 additions & 0 deletions test/GoTrueClient.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { AuthError } from '../src/lib/errors'
import {
authClient as auth,
authClientWithSession as authWithSession,
Expand Down Expand Up @@ -114,6 +115,89 @@ describe('GoTrueClient', () => {
expect(refreshAccessTokenSpy).toBeCalledTimes(1)
})

test('_callRefreshToken() should resolve all pending refresh requests and reset deferred upon AuthError', async () => {
const { email, password } = mockUserCredentials()
refreshAccessTokenSpy.mockImplementationOnce(() =>
Promise.resolve({
session: null,
error: new AuthError('Something did not work as expected'),
})
)

const { error, session } = await authWithSession.signUp({
email,
password,
})

expect(error).toBeNull()
expect(session).not.toBeNull()

const [{ session: session1, error: error1 }, { session: session2, error: error2 }] =
await Promise.all([
// @ts-expect-error 'Allow access to private _callRefreshToken()'
authWithSession._callRefreshToken(session?.refresh_token),
// @ts-expect-error 'Allow access to private _callRefreshToken()'
authWithSession._callRefreshToken(session?.refresh_token),
])

expect(error1).toHaveProperty('message')
expect(error2).toHaveProperty('message')
expect(session1).toBeNull()
expect(session2).toBeNull()

expect(refreshAccessTokenSpy).toBeCalledTimes(1)

// verify the deferred has been reset and successive calls can be made
// @ts-expect-error 'Allow access to private _callRefreshToken()'
const { session: session3, error: error3 } = await authWithSession._callRefreshToken(
session!.refresh_token
)

expect(error3).toBeNull()
expect(session3).toHaveProperty('access_token')
})

test('_callRefreshToken() should reject all pending refresh requests and reset deferred upon any non AuthError', async () => {
const mockError = new Error('Something did not work as expected')

const { email, password } = mockUserCredentials()
refreshAccessTokenSpy.mockImplementationOnce(() => Promise.reject(mockError))

const { error, session } = await authWithSession.signUp({
email,
password,
})

expect(error).toBeNull()
expect(session).not.toBeNull()

const [error1, error2] =
await Promise.allSettled([
// @ts-expect-error 'Allow access to private _callRefreshToken()'
authWithSession._callRefreshToken(session?.refresh_token),
// @ts-expect-error 'Allow access to private _callRefreshToken()'
authWithSession._callRefreshToken(session?.refresh_token),
])

expect(error1.status).toEqual('rejected')
expect(error2.status).toEqual('rejected')

// status === 'rejected' above makes sure it is a PromiseRejectedResult
expect((error1 as PromiseRejectedResult).reason).toEqual(mockError)
expect((error1 as PromiseRejectedResult).reason).toEqual(mockError)

expect(refreshAccessTokenSpy).toBeCalledTimes(1)

// vreify the deferred has been reset and successive calls can be made
// @ts-expect-error 'Allow access to private _callRefreshToken()'
const { session: session3, error: error3 } = await authWithSession._callRefreshToken(
session!.refresh_token
)

expect(error3).toBeNull()
expect(session3).toHaveProperty('access_token')
})

test('getSessionFromUrl() can only be called from a browser', async () => {
const { error, session } = await authWithSession.getSessionFromUrl()

Expand Down