import { zodResolver } from '@hookform/resolvers/zod' import { PropsWithChildren, useEffect, useId, useState } from 'react' import { useForm } from 'react-hook-form' import { Button, CardContent, CardFooter, Dialog, DialogContent, DialogTitle, Form, FormControl, FormField, Input, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from 'ui' import { FormItemLayout } from 'ui-patterns/form/FormItemLayout/FormItemLayout' import { z } from 'zod' import { VerificationInterstitialLogo } from './VerificationInterstitialLogo' import { InterstitialLayout } from '@/components/layouts/InterstitialLayout' import { AlertError } from '@/components/ui/AlertError' import { profileKeys } from '@/data/profile/keys' import { getMfaAuthenticatorAssuranceLevel, useAuthenticatorAssuranceLevelQuery, } from '@/data/profile/mfa-authenticator-assurance-level-query' import { useMfaChallengeAndVerifyMutation } from '@/data/profile/mfa-challenge-and-verify-mutation' import { useMfaListFactorsQuery, type MFAFactor } from '@/data/profile/mfa-list-factors-query' import { BASE_PATH } from '@/lib/constants' const VerificationSchema = z.object({ code: z.string().trim().min(1, 'Enter an authentication code'), factorId: z.string().min(1, 'Choose an authenticator app'), }) type VerificationValues = z.infer interface IdentityVerificationProps { canUseRecoveryCodes?: boolean returnTo?: string factorToAvoidId?: string onCancel: () => void onCheckingChange?: (isChecking: boolean) => void } export const IdentityVerification = ({ canUseRecoveryCodes = false, returnTo = '/account/security', factorToAvoidId, onCancel, onCheckingChange, children, }: PropsWithChildren) => { const verificationId = useId() const [restoreFocusTo] = useState(() => typeof document !== 'undefined' && document.activeElement instanceof HTMLElement ? document.activeElement : null ) const [hasVerified, setHasVerified] = useState(false) const [error, setError] = useState<{ message: string } | null>(null) const assurance = useAuthenticatorAssuranceLevelQuery({ queryKey: profileKeys.identityVerification(verificationId), staleTime: 0, retry: false, refetchOnMount: 'always', refetchOnWindowFocus: false, }) const isCheckingAssurance = assurance.isFetching const isVerified = hasVerified || (assurance.isFetchedAfterMount && !assurance.isError && assurance.data?.currentLevel === 'aal2') const needsCode = !isVerified && assurance.isFetchedAfterMount && !assurance.isError && !assurance.isFetching const factors = useMfaListFactorsQuery({ enabled: needsCode }) const verifiedFactors = (factors.data?.totp ?? []).filter( (factor) => factor.status === 'verified' ) const handleVerified = async () => { setError(null) try { const session = await getMfaAuthenticatorAssuranceLevel() if (session?.currentLevel !== 'aal2') { setError({ message: 'Verification did not update your session. Enter a new code and try again.', }) return } setHasVerified(true) } catch (error) { setError({ message: error instanceof Error ? error.message : 'Unable to check your session. Try again.', }) } } const readError = assurance.error ?? (needsCode ? factors.error : null) useEffect(() => { onCheckingChange?.(isCheckingAssurance) return () => onCheckingChange?.(false) }, [isCheckingAssurance, onCheckingChange]) return ( <> {isVerified && children} !open && onCancel()} > event.preventDefault()} onCloseAutoFocus={(event) => { event.preventDefault() if (!isVerified && restoreFocusTo?.isConnected) restoreFocusTo.focus() }} > Identity verification } title="Verify your identity" description="We need to make sure it’s you before making sensitive changes." > {readError && ( { if (assurance.isError) void assurance.refetch() else void factors.refetch() }} > Retry } /> )} {!readError && needsCode && factors.isSuccess && ( )} ) } const VerificationForm = ({ verifiedFactors, factorToAvoidId, canUseRecoveryCodes, returnTo, error, onVerified, }: { verifiedFactors: MFAFactor[] factorToAvoidId?: string canUseRecoveryCodes: boolean returnTo: string error: { message: string } | null onVerified: () => Promise }) => { const preferredFactor = verifiedFactors.find((factor) => factor.id !== factorToAvoidId) ?? verifiedFactors[0] const form = useForm({ resolver: zodResolver(VerificationSchema), defaultValues: { code: '', factorId: preferredFactor?.id ?? '' }, }) const { mutate: verify, isPending: loading } = useMfaChallengeAndVerifyMutation({ onSuccess: onVerified, onError: (error) => { if (error.code === 'mfa_verification_failed') { form.setError( 'code', { type: 'server', message: 'Incorrect code. Enter a new code and try again.', }, { shouldFocus: true } ) } else { form.setError('root', { type: 'server', message: error.message }) } }, }) const { errors } = form.formState const handleVerify = ({ code, factorId }: VerificationValues) => { if (loading) return form.clearErrors() verify({ code, factorId, refreshFactors: false }) } return (
{verifiedFactors.length > 1 && ( ( )} /> )} ( { form.clearErrors('code') field.onChange(event) }} autoFocus autoComplete="one-time-code" inputMode="numeric" disabled={loading} /> )} /> {(error || errors.root) && (

{error?.message ?? errors.root?.message}

)}
{canUseRecoveryCodes && ( )}
) }