import { useState } from 'react' import { AuthFailure, MfaFailure, type TotpFactor } from '@faunosteo/supabase' import { getSupabaseClient } from '@/lib/supabase' import { verifiedFactors } from './stepUp' interface PendingStepUp { factors: TotpFactor[] resume: () => void } /** The open challenge: its factors, and what verifying or cancelling it does. */ export interface StepUpChallenge { factors: TotpFactor[] onVerified: () => void onCancel: () => void } /** GoTrue refused because the session is below `aal2` (IDENTITY.md ยง4.1). */ export function isAal2Required(error: unknown): boolean { return ( (error instanceof MfaFailure || error instanceof AuthFailure) && error.kind === 'aal2_required' ) } /** * An action GoTrue may refuse below `aal2` (a password change, a second * factor, the removal of a verified one): `open` shows the challenge for one * of the account's verified factors and keeps the action to resume once the * session is `aal2`; it answers false when the account has no verified factor * (nothing to step up with) or the factors cannot be read. Never a bypass: * the retried action goes to GoTrue again. */ export function useStepUp() { const [pending, setPending] = useState(null) async function open(resume: () => void): Promise { const client = getSupabaseClient() if (!client) return false try { const factors = await verifiedFactors(client) if (factors.length === 0) return false setPending({ factors, resume }) return true } catch { return false } } const challenge: StepUpChallenge | null = pending && { factors: pending.factors, onVerified: () => { setPending(null) pending.resume() }, onCancel: () => setPending(null), } return { open, challenge } }