Files
supabase/apps/studio/hooks/misc/withAuth.tsx
Charis 0abfbdd3d7 fix(studio): preserve session and redirect to MFA when AAL elevation is needed (#47145)
## I have read the
[CONTRIBUTING.md](https://github.com/supabase/supabase/blob/master/CONTRIBUTING.md)
file.

YES

## What kind of change does this PR introduce?

Bug fix.

## What is the current behavior?

`withAuth` calls `signOut()` and redirects to `/sign-in` whenever the
current AAL is below the required level. For IdP-initiated SSO logins —
where the user lands directly on `/dashboard` rather than passing
through `/sign-in-mfa` — this destroys the valid AAL1 session that was
just established. Subsequent mgmt-api requests then return 401
Unauthorized, and the user is dumped on `/sign-in` with no way to
recover except restarting the SSO flow (which loops them back to the
same state).

The platform already returns an actionable `403 Insufficient AAL: MFA
required` on the first mgmt-api request, but the dashboard does not
capture it.

## What is the new behavior?

`withAuth` now distinguishes between "not logged in" and "needs AAL
elevation":

- **Logged in but AAL1** → `router.push('/sign-in-mfa?returnTo=…')`,
session preserved. The existing `/sign-in-mfa` page picks up the
session, renders the MFA form, and bounces the user to `returnTo` after
a successful challenge.
- **Not logged in** → unchanged: `signOut()` then redirect to
`/sign-in?returnTo=…`.
- `/sign-in-mfa` is also added to the "already there, do nothing" guard
so the user isn't re-redirected mid-challenge.

This relies on the gotrue client's local AAL state via
`useAuthenticatorAssuranceLevelQuery`, which fires before any mgmt-api
request, so no fetcher-level error parsing is needed.

## Additional context

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Bug Fixes**
* Improved multi-factor authentication (MFA) elevation flow to preserve
user sessions instead of forcing sign-out and requiring users to restart
sign-in.
  * Fixed unnecessary redirects when users are already on sign-in pages.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->
2026-06-29 13:28:46 -04:00

168 lines
5.6 KiB
TypeScript

import { useAuth } from 'common'
import { useRouter } from 'next/router'
import { ComponentType, useCallback, useEffect, useRef, useState } from 'react'
import { toast } from 'sonner'
import { SessionTimeoutModal } from '@/components/interfaces/SignIn/SessionTimeoutModal'
import { usePermissionsQuery } from '@/data/permissions/permissions-query'
import { useAuthenticatorAssuranceLevelQuery } from '@/data/profile/mfa-authenticator-assurance-level-query'
import { useSignOut } from '@/lib/auth'
import { BASE_PATH, IS_PLATFORM } from '@/lib/constants'
import { isNextPageWithLayout, type NextPageWithLayout } from '@/types'
const MAX_TIMEOUT = 10000 // 10 seconds
export function withAuth<T>(
WrappedComponent: ComponentType<T> | NextPageWithLayout<T, T>,
options: {
/**
* The auth level used to check the user credentials. In most cases, if the user has MFA enabled
* we want the highest level (which is 2) for all pages. For certain pages, the user should be
* able to access them even if he didn't finished his login (typed in his MFA code), for example
* the support page: We want the user to be able to submit a ticket even if he's not fully
* signed in.
* @default true
*/
useHighestAAL: boolean
} = { useHighestAAL: true }
) {
// ignore auth in self-hosted
if (!IS_PLATFORM) {
return WrappedComponent
}
const WithAuthHOC: ComponentType<T> = (props) => {
const router = useRouter()
const signOut = useSignOut()
const { isLoading, session } = useAuth()
const timeoutIdRef = useRef<NodeJS.Timeout | null>(null)
const [isSessionTimeoutModalOpen, setIsSessionTimeoutModalOpen] = useState(false)
const {
isPending: isAALLoading,
data: aalData,
isError: isErrorAAL,
error: errorAAL,
} = useAuthenticatorAssuranceLevelQuery()
useEffect(() => {
if (isErrorAAL) {
toast.error(
`Failed to fetch authenticator assurance level: ${errorAAL?.message}. Try refreshing your browser, or reach out to us via a support ticket if the issue persists`
)
}
}, [isErrorAAL, errorAAL])
const { isError: isErrorPermissions, error: errorPermissions } = usePermissionsQuery()
useEffect(() => {
if (isErrorPermissions) {
toast.error(
`Failed to fetch permissions: ${errorPermissions?.message}. Try refreshing your browser, or reach out to us via a support ticket if the issue persists`
)
}
}, [isErrorPermissions, errorPermissions])
const isLoggedIn = Boolean(session)
const isFinishedLoading = !isLoading && !isAALLoading
const isCorrectLevel = options.useHighestAAL
? aalData?.currentLevel === aalData?.nextLevel
: true
const needsMfaElevation = isLoggedIn && !isCorrectLevel
const redirectToSignIn = useCallback(() => {
let pathname = location.pathname
if (BASE_PATH) {
pathname = pathname.replace(BASE_PATH, '')
}
if (pathname === '/sign-in' || pathname === '/sign-in-mfa') {
// If the user is already on the sign in page, we don't need to redirect them
return
}
const searchParams = new URLSearchParams(location.search)
searchParams.set('returnTo', pathname)
if (needsMfaElevation) {
// Session is valid at AAL1 but needs to be elevated to AAL2. Preserve the session
// and send the user to the MFA challenge — typically the IdP-initiated SSO path,
// where the user lands directly on /dashboard without going through /sign-in-mfa.
router.push(`/sign-in-mfa?${searchParams.toString()}`)
return
}
// Sign out before redirecting to sign in page incase the user is stuck in a loading state
signOut().finally(() => {
router.push(`/sign-in?${searchParams.toString()}`)
})
}, [router, signOut, needsMfaElevation])
useEffect(() => {
if (!isFinishedLoading) {
timeoutIdRef.current = setTimeout(() => {
setIsSessionTimeoutModalOpen(true)
}, MAX_TIMEOUT)
} else {
if (timeoutIdRef.current) {
clearTimeout(timeoutIdRef.current)
timeoutIdRef.current = null
}
}
return () => {
if (timeoutIdRef.current) {
clearTimeout(timeoutIdRef.current)
}
}
}, [isFinishedLoading, router, redirectToSignIn])
const shouldRedirect = isFinishedLoading && (!isLoggedIn || !isCorrectLevel)
useEffect(() => {
if (shouldRedirect) {
// Clear the timeout if it's still active and we are redirecting
if (timeoutIdRef.current) {
clearTimeout(timeoutIdRef.current)
timeoutIdRef.current = null
}
redirectToSignIn()
}
}, [redirectToSignIn, shouldRedirect])
const InnerComponent = WrappedComponent as any
const supportContext =
typeof router.query.ref === 'string' && router.pathname.startsWith('/project/')
? {
projectRef: router.query.ref,
...(typeof router.query.organizationSlug === 'string' && {
orgSlug: router.query.organizationSlug,
}),
}
: undefined
return (
<>
<SessionTimeoutModal
visible={isSessionTimeoutModalOpen}
onClose={() => setIsSessionTimeoutModalOpen(false)}
redirectToSignIn={redirectToSignIn}
supportContext={supportContext}
/>
<InnerComponent {...props} />
</>
)
}
WithAuthHOC.displayName = `withAuth(${WrappedComponent.displayName})`
if (isNextPageWithLayout(WrappedComponent)) {
;(WithAuthHOC as NextPageWithLayout<T, T>).getLayout = WrappedComponent.getLayout
}
return WithAuthHOC
}