Skip to content

Commit

Permalink
fix: return redirect errors early (#1003)
Browse files Browse the repository at this point in the history
## What kind of change does this PR introduce?
* Fixes the bug introduced previously in
https://github.com/supabase/auth-js/pull/993/files#diff-3522461172efd6058d6b8da62fc2d30d8b524d2b64894ea2c67218c52f7fdff5R310,
where it attempted to always try to find a session in the URL, which led
to users being logged out on a page refresh
* This PR also reverts the previous PR #992, which returns the error
early if there's a redirect, since some redirect errors (like identity
linking) should not result in the existing session being removed.
* Tested the following scenarios:
  * Sign in and refresh the page
  * Sign in and attempt to link an already existing identity
  * Sign in and attempt to link a new identity
  • Loading branch information
kangmingtay authored Dec 17, 2024
1 parent 0f2b696 commit 9751b80
Showing 1 changed file with 53 additions and 29 deletions.
82 changes: 53 additions & 29 deletions src/GoTrueClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -307,11 +307,22 @@ export default class GoTrueClient {
*/
private async _initialize(): Promise<InitializeResult> {
try {
const isPKCEFlow = isBrowser() ? await this._isPKCEFlow() : false
this._debug('#_initialize()', 'begin', 'is PKCE flow', isPKCEFlow)

if (isPKCEFlow || (this.detectSessionInUrl && this._isImplicitGrantFlow())) {
const { data, error } = await this._getSessionFromURL(isPKCEFlow)
const params = parseParametersFromURL(window.location.href)
let callbackUrlType = 'none'
if (this._isImplicitGrantCallback(params)) {
callbackUrlType = 'implicit'
} else if (await this._isPKCECallback(params)) {
callbackUrlType = 'pkce'
}

/**
* Attempt to get the session from the URL only if these conditions are fulfilled
*
* Note: If the URL isn't one of the callback url types (implicit or pkce),
* then there could be an existing session so we don't want to prematurely remove it
*/
if (isBrowser() && this.detectSessionInUrl && callbackUrlType !== 'none') {
const { data, error } = await this._getSessionFromURL(params, callbackUrlType)
if (error) {
this._debug('#_initialize()', 'error detecting session from URL', error)

Expand Down Expand Up @@ -1414,7 +1425,10 @@ export default class GoTrueClient {
/**
* Gets the session data from a URL string
*/
private async _getSessionFromURL(isPKCEFlow: boolean): Promise<
private async _getSessionFromURL(
params: { [parameter: string]: string },
callbackUrlType: string
): Promise<
| {
data: { session: Session; redirectType: string | null }
error: null
Expand All @@ -1423,15 +1437,39 @@ export default class GoTrueClient {
> {
try {
if (!isBrowser()) throw new AuthImplicitGrantRedirectError('No browser detected.')
if (this.flowType === 'implicit' && !this._isImplicitGrantFlow()) {
throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.')
} else if (this.flowType == 'pkce' && !isPKCEFlow) {
throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.')

// If there's an error in the URL, it doesn't matter what flow it is, we just return the error.
if (params.error || params.error_description || params.error_code) {
// The error class returned implies that the redirect is from an implicit grant flow
// but it could also be from a redirect error from a PKCE flow.
throw new AuthImplicitGrantRedirectError(
params.error_description || 'Error in URL with unspecified error_description',
{
error: params.error || 'unspecified_error',
code: params.error_code || 'unspecified_code',
}
)
}

const params = parseParametersFromURL(window.location.href)
// Checks for mismatches between the flowType initialised in the client and the URL parameters
switch (callbackUrlType) {
case 'implicit':
if (this.flowType === 'pkce') {
throw new AuthPKCEGrantCodeExchangeError('Not a valid PKCE flow url.')
}
break
case 'pkce':
if (this.flowType === 'implicit') {
throw new AuthImplicitGrantRedirectError('Not a valid implicit grant flow url.')
}
break
default:
// there's no mismatch so we continue
}

if (isPKCEFlow) {
// Since this is a redirect for PKCE, we attempt to retrieve the code from the URL for the code exchange
if (callbackUrlType === 'pkce') {
this._debug('#_initialize()', 'begin', 'is PKCE flow', true)
if (!params.code) throw new AuthPKCEGrantCodeExchangeError('No code detected.')
const { data, error } = await this._exchangeCodeForSession(params.code)
if (error) throw error
Expand All @@ -1444,16 +1482,6 @@ export default class GoTrueClient {
return { data: { session: data.session, redirectType: null }, error: null }
}

if (params.error || params.error_description || params.error_code) {
throw new AuthImplicitGrantRedirectError(
params.error_description || 'Error in URL with unspecified error_description',
{
error: params.error || 'unspecified_error',
code: params.error_code || 'unspecified_code',
}
)
}

const {
provider_token,
provider_refresh_token,
Expand Down Expand Up @@ -1531,18 +1559,14 @@ export default class GoTrueClient {
/**
* Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2)
*/
private _isImplicitGrantFlow(): boolean {
const params = parseParametersFromURL(window.location.href)

return !!(isBrowser() && (params.access_token || params.error_description))
private _isImplicitGrantCallback(params: { [parameter: string]: string }): boolean {
return Boolean(params.access_token || params.error_description)
}

/**
* Checks if the current URL and backing storage contain parameters given by a PKCE flow
*/
private async _isPKCEFlow(): Promise<boolean> {
const params = parseParametersFromURL(window.location.href)

private async _isPKCECallback(params: { [parameter: string]: string }): Promise<boolean> {
const currentStorageContent = await getItemAsync(
this.storage,
`${this.storageKey}-code-verifier`
Expand Down

0 comments on commit 9751b80

Please sign in to comment.