Files
supabase/apps/studio/lib/gotrue.ts
Joshen Lim 0c95428678 fix(studio): strip auth error and method params when building sign-in redirects (#53598)
## Context

Bit of an odd bug that I happened to come across which I can't remember
how to reproduce from scratch but its a valid issue.

If i try to log in on the sign-in route with `method` and
`error_description` query params in the URL, the `error_description`
param gets carried forward to the next page, which if my account has
MFA, it'll then bounce back to `/sign-in`

`/sign-in?error_description=Unable+to+exchange+external+code%3A+53f8&method=github`

Am opting to strip transient params when building the sign-in redirects

## To test
- [ ] Ensure that you've got an account with MFA
- [ ] Try logging in via this URL
`/sign-in?error_description=Unable+to+exchange+external+code%3A+53f8&method=github`
- [ ] You should be able to land on the sign-in-mfa page with no issue +
no error toasts
2026-11-19 13:10:07 +07:00

168 lines
5.6 KiB
TypeScript

import type { JwtPayload } from '@supabase/supabase-js'
import { type User } from 'common/auth'
import { gotrueClient } from 'common/gotrue'
export const auth = gotrueClient
export const DEFAULT_FALLBACK_PATH = '/organizations'
export const DEFAULT_SIGNUP_RETURN_PATH = '/new'
/**
* When unauthenticated users hit protected dashboard routes, withAuth sets
* returnTo to the current path. Marketing entry via /dashboard often ends up
* as returnTo=/org (or /organizations). New users who switch to sign-up should
* start org creation instead.
*/
export function getSignUpReturnTo(returnTo: string | string[] | undefined): string {
const value = Array.isArray(returnTo) ? returnTo[0] : returnTo
if (!value) {
return DEFAULT_SIGNUP_RETURN_PATH
}
const [pathname, query] = value.split('?', 2)
if (pathname === DEFAULT_FALLBACK_PATH || pathname === '/org') {
return query ? `${DEFAULT_SIGNUP_RETURN_PATH}?${query}` : DEFAULT_SIGNUP_RETURN_PATH
}
return value
}
/**
* Query for the link from sign-up back to sign-in. The sign-up link sets returnTo=/new by default,
* which is only meant for new users, so existing users fall back to the default path instead.
*/
export function getSignInQuery(query: Record<string, string | string[] | undefined>) {
const { returnTo, ...rest } = query
const value = Array.isArray(returnTo) ? returnTo[0] : returnTo
return value === DEFAULT_SIGNUP_RETURN_PATH ? rest : query
}
/** Post-signup redirect path, normalising returnTo and excluding it from merged query params. */
export function buildSignUpReturnPath(returnTo: string | string[] | undefined): string {
const basePath = validateReturnTo(getSignUpReturnTo(returnTo), DEFAULT_SIGNUP_RETURN_PATH)
const [pathOnly, pathQuery] = basePath.split('?', 2)
const pathnameSearchParams = new URLSearchParams(pathQuery || '')
if (typeof location === 'undefined') {
const queryString = pathnameSearchParams.toString()
return queryString ? `${pathOnly}?${queryString}` : pathOnly
}
const mergedParams = stripTransientAuthParams(new URLSearchParams(location.search))
mergedParams.delete('returnTo')
for (const [key, val] of pathnameSearchParams.entries()) {
mergedParams.set(key, val)
}
const queryString = mergedParams.toString()
return queryString ? `${pathOnly}?${queryString}` : pathOnly
}
export const validateReturnTo = (
returnTo: string,
fallback: string = DEFAULT_FALLBACK_PATH
): string => {
// Block protocol-relative URLs and external URLs
if (returnTo.startsWith('//') || returnTo.includes('://')) {
return fallback
}
// For internal paths:
// 1. Must start with /
// 2. Only allow alphanumeric chars, slashes, hyphens, underscores
// 3. For query params, also allow =, &, and ?
const safePathPattern = /^\/[a-zA-Z0-9/\-_]*(?:\?[a-zA-Z0-9\-_=&]*)?$/
return safePathPattern.test(returnTo) ? returnTo : fallback
}
export const getUserClaims = async (
token: String
): Promise<{ error: any | null; claims: JwtPayload | null }> => {
try {
const { data, error } = await auth.getClaims(token.replace(/bearer /i, ''))
if (error) throw error
return { claims: data?.claims ?? null, error: null }
} catch (err) {
console.error(err)
return { claims: null, error: err }
}
}
export const getAuth0Id = (provider: String, providerId: String): String => {
return `${provider}|${providerId}`
}
export const getIdentity = (gotrueUser: User) => {
try {
if (gotrueUser !== undefined && gotrueUser.identities !== undefined) {
return { identity: gotrueUser.identities[0], error: null }
}
throw 'Missing identity'
} catch (err) {
return { identity: null, error: err }
}
}
const TRANSIENT_AUTH_PARAMS = ['error', 'error_code', 'error_description']
const stripTransientAuthParams = (params: URLSearchParams) => {
TRANSIENT_AUTH_PARAMS.forEach((key) => params.delete(key))
return params
}
/**
* Transfers the search params from the current location path to a newly built path
*/
export const buildPathWithParams = (pathname: string) => {
const [basePath, existingParams] = pathname.split('?', 2)
const pathnameSearchParams = new URLSearchParams(existingParams || '')
// Merge the parameters, with pathname parameters taking precedence
// over the current location's search parameters
const mergedParams = stripTransientAuthParams(new URLSearchParams(location.search))
for (const [key, value] of pathnameSearchParams.entries()) {
mergedParams.set(key, value)
}
const queryString = mergedParams.toString()
return queryString ? `${basePath}?${queryString}` : basePath
}
export const getReturnToPath = (fallback = DEFAULT_FALLBACK_PATH) => {
// If we're in a server environment, return the fallback
if (typeof location === 'undefined') {
return fallback
}
const searchParams = stripTransientAuthParams(new URLSearchParams(location.search))
let returnTo = searchParams.get('returnTo') ?? fallback
if (process.env.NEXT_PUBLIC_BASE_PATH) {
returnTo = returnTo.replace(process.env.NEXT_PUBLIC_BASE_PATH, '')
}
searchParams.delete('returnTo')
const remainingSearchParams = searchParams.toString()
const validReturnTo = validateReturnTo(returnTo, fallback)
const [path, existingQuery] = validReturnTo.split('?')
const finalSearchParams = new URLSearchParams(existingQuery || '')
// Add all remaining search params to the final search params
if (remainingSearchParams) {
const remainingParams = new URLSearchParams(remainingSearchParams)
remainingParams.forEach((value, key) => {
finalSearchParams.append(key, value)
})
}
const finalQuery = finalSearchParams.toString()
return path + (finalQuery ? `?${finalQuery}` : '')
}