Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Recovery codes: allow users to use recovery codes to access their account (#50569)

Gildas Garciad276f75c89a0
diff --git a/apps/studio/TANSTACK_MIGRATION.md b/apps/studio/TANSTACK_MIGRATION.md
index 2de144cdf7d..07db3d5658b 100644
--- a/apps/studio/TANSTACK_MIGRATION.md
+++ b/apps/studio/TANSTACK_MIGRATION.md
@@ -351,6 +351,7 @@ These are the layout-only TanStack files. Most hold a single product layout comp
- [x] A `routes/_auth/sign-in-sso.tsx` ← `pages/sign-in-sso.tsx`
- [x] A `routes/_auth/sign-in-partner.tsx` ← `pages/sign-in-partner.tsx`
- [x] A `routes/_auth/sign-in-mfa.tsx` ← `pages/sign-in-mfa.tsx` (page inlines SignInLayout)
+- [x] A `routes/_auth/sign-in-recovery-code.tsx` ← `pages/sign-in-recovery-code.tsx` (page inlines SignInLayout)
- [x] A `routes/_auth/forgot-password.tsx` ← `pages/forgot-password.tsx`
- [x] A `routes/_auth/forgot-password-mfa.tsx` ← `pages/forgot-password-mfa.tsx` (page inlines ForgotPasswordLayout)
- [x] A `routes/_auth/reset-password.tsx` ← `pages/reset-password.tsx` (page default already withAuth-wrapped)
diff --git a/apps/studio/components/interfaces/Account/TOTPFactors/index.tsx b/apps/studio/components/interfaces/Account/TOTPFactors/index.tsx
index 07656cbe0b9..e328a2824e5 100644
--- a/apps/studio/components/interfaces/Account/TOTPFactors/index.tsx
+++ b/apps/studio/components/interfaces/Account/TOTPFactors/index.tsx
@@ -44,7 +44,7 @@ export const TOTPFactors = () => {
return (
<>
- {enableAuthRecoveryCodes && (
+ {enableAuthRecoveryCodes && shouldVerifyRecoveryCodes && (
<PageSection>
<PageSectionMeta>
<PageSectionSummary>
diff --git a/apps/studio/components/interfaces/SignIn/SignInMfaForm.tsx b/apps/studio/components/interfaces/SignIn/SignInMfaForm.tsx
index 11880b2a875..9c6e73dd10a 100644
--- a/apps/studio/components/interfaces/SignIn/SignInMfaForm.tsx
+++ b/apps/studio/components/interfaces/SignIn/SignInMfaForm.tsx
@@ -1,9 +1,10 @@
import { zodResolver } from '@hookform/resolvers/zod'
import type { Factor } from '@supabase/supabase-js'
import { useQueryClient } from '@tanstack/react-query'
-import { useAuthError, useParams } from 'common'
+import { useAuthError, useFlag, useParams } from 'common'
import { Lock } from 'lucide-react'
import Link from 'next/link'
+import { useSearchParams } from 'next/navigation'
import { useRouter } from 'next/router'
import { useEffect, useState } from 'react'
import { SubmitHandler, useForm, useWatch } from 'react-hook-form'
@@ -16,6 +17,7 @@ import { AlertError } from '@/components/ui/AlertError'
import { useAddLoginEvent } from '@/data/misc/audit-login-mutation'
import { useMfaChallengeAndVerifyMutation } from '@/data/profile/mfa-challenge-and-verify-mutation'
import { useMfaListFactorsQuery } from '@/data/profile/mfa-list-factors-query'
+import { useRecoveryCodesStatusQuery } from '@/data/recovery-codes/recovery-codes-status-query'
import { useSignOut } from '@/lib/auth'
import { getReturnToPath } from '@/lib/gotrue'
import { useTrack } from '@/lib/telemetry/track'
@@ -41,7 +43,12 @@ export const SignInMfaForm = ({ context = 'sign-in' }: SignInMfaFormProps) => {
const router = useRouter()
const signOut = useSignOut()
const queryClient = useQueryClient()
+ const searchParams = useSearchParams()
const { method: signInMethod = 'unknown' } = useParams()
+ const enableAuthRecoveryCodes = useFlag('enableAuthRecoveryCodes')
+ const { data: recoveryCodesStatus } = useRecoveryCodesStatusQuery({
+ enabled: enableAuthRecoveryCodes,
+ })
const track = useTrack()
const { mutate: addLoginEvent } = useAddLoginEvent()
@@ -230,7 +237,8 @@ export const SignInMfaForm = ({ context = 'sign-in' }: SignInMfaFormProps) => {
<ul className="list-disc pl-6">
{factors?.totp.length === 2 && (
<li>
- <a
+ <button
+ tabIndex={0}
className="text-sm text-foreground-light hover:text-foreground cursor-pointer"
onClick={() =>
setSelectedFactor(factors.totp.find((f) => f.id !== selectedFactor?.id)!)
@@ -241,7 +249,17 @@ export const SignInMfaForm = ({ context = 'sign-in' }: SignInMfaFormProps) => {
{getFactorDisplayName(factors.totp.find((f) => f.id !== selectedFactor?.id))}
</strong>
?
- </a>
+ </button>
+ </li>
+ )}
+ {enableAuthRecoveryCodes && recoveryCodesStatus?.status === 'available' && (
+ <li>
+ <Link
+ href={`/sign-in-recovery-code?${searchParams}`}
+ className="text-sm transition text-foreground-light hover:text-foreground"
+ >
+ Authenticate using a recovery code
+ </Link>
</li>
)}
<li>
diff --git a/apps/studio/components/interfaces/SignIn/SignInRecoveryCodeForm.tsx b/apps/studio/components/interfaces/SignIn/SignInRecoveryCodeForm.tsx
new file mode 100644
index 00000000000..0789b140f9a
--- /dev/null
+++ b/apps/studio/components/interfaces/SignIn/SignInRecoveryCodeForm.tsx
@@ -0,0 +1,245 @@
+import { zodResolver } from '@hookform/resolvers/zod'
+import { useQueryClient } from '@tanstack/react-query'
+import { useAuthError, useFeatureFlags, useFlag } from 'common'
+import { EyeIcon, EyeOffIcon, LockIcon } from 'lucide-react'
+import Link from 'next/link'
+import { useRouter } from 'next/router'
+import { useEffect, useRef, useState } from 'react'
+import { SubmitHandler, useForm } from 'react-hook-form'
+import {
+ Button,
+ Form,
+ FormControl,
+ FormField,
+ FormInputGroupInput,
+ InputGroup,
+ InputGroupAddon,
+ InputGroupButton,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from 'ui'
+import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout'
+import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
+import z from 'zod'
+
+import { AlertError } from '@/components/ui/AlertError'
+import { useAddLoginEvent } from '@/data/misc/audit-login-mutation'
+import { useRecoveryCodesStatusQuery } from '@/data/recovery-codes/recovery-codes-status-query'
+import { useRecoveryCodesVerifyMutation } from '@/data/recovery-codes/recovery-codes-verify-mutation'
+import { useSignOut } from '@/lib/auth'
+import { getReturnToPath } from '@/lib/gotrue'
+import { useTrack } from '@/lib/telemetry/track'
+
+const schema = z.object({
+ code: z.string().min(1, 'Recovery Code is required'),
+})
+
+const formId = 'sign-in-recovery-code-form'
+
+const SUPPORT_EMAIL_HREF = `mailto:[email protected]?subject=${encodeURIComponent('Unable to sign in via MFA')}`
+
+export const SignInRecoveryCodeForm = () => {
+ const router = useRouter()
+ const signOut = useSignOut()
+ const queryClient = useQueryClient()
+ const { hasLoaded } = useFeatureFlags()
+ const enableAuthRecoveryCodes = useFlag('enableAuthRecoveryCodes')
+ const {
+ data: recoveryCodesStatus,
+ isPending: recoveryCodesStatusIsPending,
+ isError: recoveryCodesStatusIsError,
+ error: recoveryCodesStatusError,
+ } = useRecoveryCodesStatusQuery({
+ enabled: enableAuthRecoveryCodes,
+ })
+
+ const track = useTrack()
+ const { mutate: addLoginEvent } = useAddLoginEvent()
+
+ const form = useForm<z.infer<typeof schema>>({
+ resolver: zodResolver(schema),
+ defaultValues: { code: '' },
+ })
+
+ const {
+ mutate: verifyRecoveryCode,
+ isPending: isVerifying,
+ isSuccess,
+ } = useRecoveryCodesVerifyMutation({
+ onSuccess: async () => {
+ track('sign_in', { category: 'account', method: 'recovery-code' })
+ addLoginEvent({})
+
+ await queryClient.resetQueries()
+
+ router.push(getReturnToPath())
+ },
+ })
+
+ const onClickLogout = async () => {
+ if (isVerifying) return
+ await signOut()
+ await router.replace('/sign-in')
+ }
+
+ const onSubmit: SubmitHandler<z.infer<typeof schema>> = async ({ code }) => {
+ if (isVerifying) return
+ verifyRecoveryCode({ code })
+ }
+
+ useEffect(() => {
+ // if users wander into this page and he has no recovery code setup or is on platform where it's not enabled
+ if (hasLoaded && (!enableAuthRecoveryCodes || recoveryCodesStatus?.status === 'unenrolled')) {
+ queryClient.resetQueries().then(() => router.push(getReturnToPath()))
+ }
+ }, [hasLoaded, enableAuthRecoveryCodes, recoveryCodesStatus, router, queryClient])
+
+ const error = useAuthError()
+
+ const [isCodeRevealed, setIsCodeRevealed] = useState(false)
+ const formRef = useRef<HTMLFormElement>(null)
+
+ if (error) {
+ return (
+ <AlertError
+ error={error}
+ subject="Error while signing in"
+ hideContactSupport
+ additionalActions={
+ <>
+ <Button asChild>
+ <Link href="/sign-in">Back to sign in</Link>
+ </Button>
+ <Button asChild>
+ <a href={SUPPORT_EMAIL_HREF}>Email support</a>
+ </Button>
+ </>
+ }
+ />
+ )
+ }
+
+ return (
+ <>
+ {recoveryCodesStatusIsPending && <GenericSkeletonLoader />}
+
+ {recoveryCodesStatusIsError && (
+ <AlertError
+ error={recoveryCodesStatusError}
+ subject="Failed to retrieve recovery codes status"
+ description="Try refreshing your browser. If the issue persists, email [email protected]."
+ hideContactSupport
+ />
+ )}
+
+ {recoveryCodesStatus?.status === 'available' && (
+ <Form {...form}>
+ <form
+ ref={formRef}
+ id={formId}
+ method="POST"
+ className="flex flex-col gap-4"
+ onSubmit={form.handleSubmit(onSubmit)}
+ >
+ <FormField
+ key="code"
+ name="code"
+ control={form.control}
+ render={({ field }) => (
+ <FormItemLayout name="code" label="Recovery code">
+ <InputGroup>
+ <FormControl>
+ <FormInputGroupInput
+ {...field}
+ className="pl-10 font-mono"
+ autoFocus
+ autoComplete="off"
+ autoCorrect="off"
+ autoCapitalize="none"
+ spellCheck="false"
+ placeholder="****************"
+ type={isCodeRevealed ? 'text' : 'password'}
+ onPaste={(event) => {
+ // If users paste something, it's most probably a valid code so we can safely try submitting it immediately
+ // onPaste is triggered before the paste operation is complete so we have to emulate it to avoid using an unreliable setTimeout
+ event.preventDefault()
+ field.onChange(event.clipboardData.getData('text'))
+ formRef.current?.dispatchEvent(
+ new Event('submit', { cancelable: true, bubbles: true })
+ )
+ }}
+ />
+ </FormControl>
+ <InputGroupAddon align="inline-start">
+ <LockIcon />
+ </InputGroupAddon>
+ <InputGroupAddon align="inline-end" className="pr-1 has-[>button]:mr-0">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <InputGroupButton
+ aria-label={isCodeRevealed ? 'Hide code' : 'Show code'}
+ aria-describedby={undefined}
+ onClick={() => setIsCodeRevealed((previous) => !previous)}
+ >
+ {isCodeRevealed ? (
+ <EyeIcon className="size-4" />
+ ) : (
+ <EyeOffIcon className="size-4" />
+ )}
+ </InputGroupButton>
+ </TooltipTrigger>
+ <TooltipContent>
+ {isCodeRevealed ? 'Hide code' : 'Show code'}
+ </TooltipContent>
+ </Tooltip>
+ </InputGroupAddon>
+ </InputGroup>
+ </FormItemLayout>
+ )}
+ />
+
+ <div className="flex items-center justify-between gap-x-2">
+ <Button
+ block
+ variant="outline"
+ size="large"
+ onClick={onClickLogout}
+ disabled={isVerifying || isSuccess}
+ className="opacity-80 hover:opacity-100 transition"
+ >
+ Cancel
+ </Button>
+ <Button
+ variant="primary"
+ block
+ form={formId}
+ type="submit"
+ size="large"
+ loading={isVerifying || isSuccess}
+ >
+ {isVerifying ? 'Verifying' : isSuccess ? 'Signing in' : 'Verify'}
+ </Button>
+ </div>
+ </form>
+ </Form>
+ )}
+
+ <div className="my-8">
+ <div className="text-sm">
+ <span className="text-foreground-light">Unable to sign in?</span>{' '}
+ </div>
+ <ul className="list-disc pl-6">
+ <li>
+ <Link
+ href="/logout"
+ className="text-sm transition text-foreground-light hover:text-foreground"
+ >
+ Force sign out and clear cookies
+ </Link>
+ </li>
+ </ul>
+ </div>
+ </>
+ )
+}
diff --git a/apps/studio/components/layouts/SignInLayout/SignInLayout.tsx b/apps/studio/components/layouts/SignInLayout/SignInLayout.tsx
index 127e58a1e5f..e27fe5a2d1c 100644
--- a/apps/studio/components/layouts/SignInLayout/SignInLayout.tsx
+++ b/apps/studio/components/layouts/SignInLayout/SignInLayout.tsx
@@ -105,6 +105,10 @@ export const SignInLayout = ({
}
if (data) {
+ // we're already where we need to be
+ if (router.pathname === '/sign-in-recovery-code') {
+ return
+ }
// we're already where we need to be
if (router.pathname === '/sign-in-mfa') {
return
diff --git a/apps/studio/data/recovery-codes/recovery-codes-verify-mutation.ts b/apps/studio/data/recovery-codes/recovery-codes-verify-mutation.ts
new file mode 100644
index 00000000000..cd8ed5c0e14
--- /dev/null
+++ b/apps/studio/data/recovery-codes/recovery-codes-verify-mutation.ts
@@ -0,0 +1,47 @@
+import type { AuthMFAVerifyResponse, MFARecoveryCodesVerifyParams } from '@supabase/auth-js'
+import { useMutation } from '@tanstack/react-query'
+import { toast } from 'sonner'
+
+import { captureCriticalError } from '@/lib/error-reporting'
+import { auth } from '@/lib/gotrue'
+import { UseCustomMutationOptions } from '@/types'
+
+export const recoveryCodesVerify = async (params: MFARecoveryCodesVerifyParams) => {
+ const { error, data } = await auth.mfa.recoveryCodes.verify(params)
+ if (error) throw error
+ return data
+}
+
+type RecoveryCodesVerifyResponse = NonNullable<AuthMFAVerifyResponse['data']>
+type RecoveryCodesVerifyError = NonNullable<AuthMFAVerifyResponse['error']>
+
+export const useRecoveryCodesVerifyMutation = ({
+ onSuccess,
+ onError,
+ ...options
+}: Omit<
+ UseCustomMutationOptions<
+ RecoveryCodesVerifyResponse,
+ RecoveryCodesVerifyError,
+ MFARecoveryCodesVerifyParams
+ >,
+ 'mutationFn'
+> = {}) => {
+ return useMutation({
+ mutationFn: (vars) => {
+ return recoveryCodesVerify(vars)
+ },
+ async onSuccess(data, variables, context) {
+ await onSuccess?.(data, variables, context)
+ },
+ async onError(data, variables, context) {
+ if (onError === undefined) {
+ toast.error(`Failed to verify recovery code: ${data.message}`)
+ } else {
+ onError(data, variables, context)
+ }
+ captureCriticalError(data, 'recovery code verify')
+ },
+ ...options,
+ })
+}
diff --git a/apps/studio/pages/sign-in-recovery-code.tsx b/apps/studio/pages/sign-in-recovery-code.tsx
new file mode 100644
index 00000000000..4fbf92cea9b
--- /dev/null
+++ b/apps/studio/pages/sign-in-recovery-code.tsx
@@ -0,0 +1,19 @@
+import { SignInRecoveryCodeForm } from '@/components/interfaces/SignIn/SignInRecoveryCodeForm'
+import { SignInLayout } from '@/components/layouts/SignInLayout/SignInLayout'
+import type { NextPageWithLayout } from '@/types'
+
+const SignInRecoveryCodePage: NextPageWithLayout = () => {
+ return (
+ <SignInLayout
+ heading="Recovery code authentication"
+ subheading="Enter a recovery code"
+ logoLinkToMarketingSite={true}
+ >
+ <div className="flex flex-col gap-5">
+ <SignInRecoveryCodeForm />
+ </div>
+ </SignInLayout>
+ )
+}
+
+export default SignInRecoveryCodePage
diff --git a/apps/studio/routeTree.gen.ts b/apps/studio/routeTree.gen.ts
index 5aad3a52cf1..462138879cd 100644
--- a/apps/studio/routeTree.gen.ts
+++ b/apps/studio/routeTree.gen.ts
@@ -42,6 +42,7 @@ import { Route as ApiCliReleaseVersionRouteImport } from './routes/api/cli-relea
import { Route as ApiCheckCnameRouteImport } from './routes/api/check-cname'
import { Route as AuthSignUpRouteImport } from './routes/_auth/sign-up'
import { Route as AuthSignInSsoRouteImport } from './routes/_auth/sign-in-sso'
+import { Route as AuthSignInRecoveryCodeRouteImport } from './routes/_auth/sign-in-recovery-code'
import { Route as AuthSignInPartnerRouteImport } from './routes/_auth/sign-in-partner'
import { Route as AuthSignInMfaRouteImport } from './routes/_auth/sign-in-mfa'
import { Route as AuthSignInRouteImport } from './routes/_auth/sign-in'
@@ -499,6 +500,11 @@ const AuthSignInSsoRoute = AuthSignInSsoRouteImport.update({
path: '/sign-in-sso',
getParentRoute: () => AuthRoute,
} as any)
+const AuthSignInRecoveryCodeRoute = AuthSignInRecoveryCodeRouteImport.update({
+ id: '/sign-in-recovery-code',
+ path: '/sign-in-recovery-code',
+ getParentRoute: () => AuthRoute,
+} as any)
const AuthSignInPartnerRoute = AuthSignInPartnerRouteImport.update({
id: '/sign-in-partner',
path: '/sign-in-partner',
@@ -2153,6 +2159,7 @@ export interface FileRoutesByFullPath {
'/sign-in': typeof AuthSignInRoute
'/sign-in-mfa': typeof AuthSignInMfaRoute
'/sign-in-partner': typeof AuthSignInPartnerRoute
+ '/sign-in-recovery-code': typeof AuthSignInRecoveryCodeRoute
'/sign-in-sso': typeof AuthSignInSsoRoute
'/sign-up': typeof AuthSignUpRoute
'/api/check-cname': typeof ApiCheckCnameRoute
@@ -2474,6 +2481,7 @@ export interface FileRoutesByTo {
'/sign-in': typeof AuthSignInRoute
'/sign-in-mfa': typeof AuthSignInMfaRoute
'/sign-in-partner': typeof AuthSignInPartnerRoute
+ '/sign-in-recovery-code': typeof AuthSignInRecoveryCodeRoute
'/sign-in-sso': typeof AuthSignInSsoRoute
'/sign-up': typeof AuthSignUpRoute
'/api/check-cname': typeof ApiCheckCnameRoute
@@ -2785,6 +2793,7 @@ export interface FileRoutesById {
'/_auth/sign-in': typeof AuthSignInRoute
'/_auth/sign-in-mfa': typeof AuthSignInMfaRoute
'/_auth/sign-in-partner': typeof AuthSignInPartnerRoute
+ '/_auth/sign-in-recovery-code': typeof AuthSignInRecoveryCodeRoute
'/_auth/sign-in-sso': typeof AuthSignInSsoRoute
'/_auth/sign-up': typeof AuthSignUpRoute
'/api/check-cname': typeof ApiCheckCnameRoute
@@ -3109,6 +3118,7 @@ export interface FileRouteTypes {
| '/sign-in'
| '/sign-in-mfa'
| '/sign-in-partner'
+ | '/sign-in-recovery-code'
| '/sign-in-sso'
| '/sign-up'
| '/api/check-cname'
@@ -3430,6 +3440,7 @@ export interface FileRouteTypes {
| '/sign-in'
| '/sign-in-mfa'
| '/sign-in-partner'
+ | '/sign-in-recovery-code'
| '/sign-in-sso'
| '/sign-up'
| '/api/check-cname'
@@ -3740,6 +3751,7 @@ export interface FileRouteTypes {
| '/_auth/sign-in'
| '/_auth/sign-in-mfa'
| '/_auth/sign-in-partner'
+ | '/_auth/sign-in-recovery-code'
| '/_auth/sign-in-sso'
| '/_auth/sign-up'
| '/api/check-cname'
@@ -4401,6 +4413,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof AuthSignInSsoRouteImport
parentRoute: typeof AuthRoute
}
+ '/_auth/sign-in-recovery-code': {
+ id: '/_auth/sign-in-recovery-code'
+ path: '/sign-in-recovery-code'
+ fullPath: '/sign-in-recovery-code'
+ preLoaderRoute: typeof AuthSignInRecoveryCodeRouteImport
+ parentRoute: typeof AuthRoute
+ }
'/_auth/sign-in-partner': {
id: '/_auth/sign-in-partner'
path: '/sign-in-partner'
@@ -6515,6 +6534,7 @@ interface AuthRouteChildren {
AuthSignInRoute: typeof AuthSignInRoute
AuthSignInMfaRoute: typeof AuthSignInMfaRoute
AuthSignInPartnerRoute: typeof AuthSignInPartnerRoute
+ AuthSignInRecoveryCodeRoute: typeof AuthSignInRecoveryCodeRoute
AuthSignInSsoRoute: typeof AuthSignInSsoRoute
AuthSignUpRoute: typeof AuthSignUpRoute
AuthCliLoginRoute: typeof AuthCliLoginRoute
@@ -6528,6 +6548,7 @@ const AuthRouteChildren: AuthRouteChildren = {
AuthSignInRoute: AuthSignInRoute,
AuthSignInMfaRoute: AuthSignInMfaRoute,
AuthSignInPartnerRoute: AuthSignInPartnerRoute,
+ AuthSignInRecoveryCodeRoute: AuthSignInRecoveryCodeRoute,
AuthSignInSsoRoute: AuthSignInSsoRoute,
AuthSignUpRoute: AuthSignUpRoute,
AuthCliLoginRoute: AuthCliLoginRoute,
diff --git a/apps/studio/routes/_auth/sign-in-recovery-code.tsx b/apps/studio/routes/_auth/sign-in-recovery-code.tsx
new file mode 100644
index 00000000000..c626a13c8fb
--- /dev/null
+++ b/apps/studio/routes/_auth/sign-in-recovery-code.tsx
@@ -0,0 +1,12 @@
+import { createFileRoute } from '@tanstack/react-router'
+
+import SignInRecoveryCodePage from '@/pages/sign-in-recovery-code'
+
+export const Route = createFileRoute('/_auth/sign-in-recovery-code')({
+ component: SignInRecoveryCode,
+})
+
+function SignInRecoveryCode() {
+ // The Next page inlines its own SignInLayout; just render it.
+ return <SignInRecoveryCodePage dehydratedState={undefined} />
+}