diff --git a/src/App.tsx b/src/App.tsx index 4eaee7ff..05077585 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -46,6 +46,7 @@ import BlogPost from "./pages/BlogPost"; import AdminBlog from "./pages/AdminBlog"; import ForceLogout from "./pages/ForceLogout"; import AuthCallback from "./pages/AuthCallback"; +import MFAStepUp from "./pages/MFAStepUp"; const queryClient = new QueryClient({ defaultOptions: { @@ -93,6 +94,7 @@ function AppContent() { } /> } /> } /> + } /> } /> } /> } /> diff --git a/src/components/auth/MFARequiredAlert.tsx b/src/components/auth/MFARequiredAlert.tsx index 8268e590..68ec602a 100644 --- a/src/components/auth/MFARequiredAlert.tsx +++ b/src/components/auth/MFARequiredAlert.tsx @@ -2,21 +2,46 @@ import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert'; import { Button } from '@/components/ui/button'; import { Shield } from 'lucide-react'; import { useNavigate } from 'react-router-dom'; +import { useAuth } from '@/hooks/useAuth'; +import { useEffect, useState } from 'react'; export function MFARequiredAlert() { const navigate = useNavigate(); + const { checkAalStepUp } = useAuth(); + const [needsVerification, setNeedsVerification] = useState(false); + + useEffect(() => { + checkAalStepUp().then(result => { + setNeedsVerification(result.needsStepUp); + }); + }, [checkAalStepUp]); + + const handleAction = () => { + if (needsVerification) { + // User has MFA enrolled but needs to verify + sessionStorage.setItem('mfa_step_up_required', 'true'); + navigate('/auth/mfa-step-up'); + } else { + // User needs to enroll in MFA + navigate('/settings?tab=security'); + } + }; return ( Two-Factor Authentication Required -

Your role requires two-factor authentication to access this area.

+

+ {needsVerification + ? 'Please verify your identity with two-factor authentication to access this area.' + : 'Your role requires two-factor authentication to access this area.'} +

diff --git a/src/components/auth/TOTPSetup.tsx b/src/components/auth/TOTPSetup.tsx index 1d369d0a..b7040e88 100644 --- a/src/components/auth/TOTPSetup.tsx +++ b/src/components/auth/TOTPSetup.tsx @@ -111,16 +111,31 @@ export function TOTPSetup() { if (verifyError) throw verifyError; + // Check if user signed in via OAuth + const { data: { session } } = await supabase.auth.getSession(); + const provider = session?.user?.app_metadata?.provider; + const isOAuthUser = provider === 'google' || provider === 'discord'; + toast({ title: 'TOTP Enabled', - description: 'Please sign in again to activate MFA protection.' + description: isOAuthUser + ? 'Please verify with your authenticator code to continue.' + : 'Please sign in again to activate MFA protection.' }); - // Force sign out to get new session with AAL2 - setTimeout(async () => { - await supabase.auth.signOut(); - window.location.href = '/auth'; - }, 2000); + if (isOAuthUser) { + // For OAuth users, trigger step-up flow immediately + setTimeout(() => { + sessionStorage.setItem('mfa_step_up_required', 'true'); + window.location.href = '/auth/mfa-step-up'; + }, 1500); + } else { + // For email/password users, force sign out to require MFA on next login + setTimeout(async () => { + await supabase.auth.signOut(); + window.location.href = '/auth'; + }, 2000); + } } catch (error: any) { toast({ title: 'Error', diff --git a/src/hooks/useAuth.tsx b/src/hooks/useAuth.tsx index f13a48a6..26e1ec59 100644 --- a/src/hooks/useAuth.tsx +++ b/src/hooks/useAuth.tsx @@ -5,6 +5,12 @@ import type { Profile } from '@/types/database'; import { toast } from '@/hooks/use-toast'; import { authLog, authWarn, authError } from '@/lib/authLogger'; +export interface CheckAalResult { + needsStepUp: boolean; + hasMfaEnrolled: boolean; + currentLevel: 'aal1' | 'aal2' | null; +} + interface AuthContextType { user: User | null; session: Session | null; @@ -15,6 +21,7 @@ interface AuthContextType { signOut: () => Promise; verifySession: () => Promise; clearPendingEmail: () => void; + checkAalStepUp: () => Promise; } const AuthContext = createContext(undefined); @@ -221,6 +228,29 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) { setPendingEmail(null); }; + const checkAalStepUp = async (): Promise => { + if (!session?.user) { + return { needsStepUp: false, hasMfaEnrolled: false, currentLevel: null }; + } + + try { + const { data: { currentLevel } } = + await supabase.auth.mfa.getAuthenticatorAssuranceLevel(); + + const { data: factors } = await supabase.auth.mfa.listFactors(); + const hasMfaEnrolled = factors?.totp?.some(f => f.status === 'verified') || false; + + return { + needsStepUp: hasMfaEnrolled && currentLevel === 'aal1', + hasMfaEnrolled, + currentLevel: currentLevel as 'aal1' | 'aal2' | null, + }; + } catch (error) { + authError('[Auth] Failed to check AAL status:', error); + return { needsStepUp: false, hasMfaEnrolled: false, currentLevel: null }; + } + }; + const value = { user, session, @@ -231,6 +261,7 @@ function AuthProviderComponent({ children }: { children: React.ReactNode }) { signOut, verifySession, clearPendingEmail, + checkAalStepUp, }; return {children}; diff --git a/src/pages/AuthCallback.tsx b/src/pages/AuthCallback.tsx index ffbeb065..1c80f3d2 100644 --- a/src/pages/AuthCallback.tsx +++ b/src/pages/AuthCallback.tsx @@ -71,6 +71,33 @@ export default function AuthCallback() { } } + // Check if MFA step-up is required for OAuth users + if (isOAuthUser) { + console.log('[AuthCallback] Checking MFA requirements for OAuth user...'); + + try { + const { data: factors } = await supabase.auth.mfa.listFactors(); + const hasMfaEnrolled = factors?.totp?.some(f => f.status === 'verified'); + + const { data: { currentLevel } } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel(); + + console.log('[AuthCallback] MFA status:', { + hasMfaEnrolled, + currentLevel, + }); + + if (hasMfaEnrolled && currentLevel === 'aal1') { + console.log('[AuthCallback] MFA step-up required, redirecting...'); + sessionStorage.setItem('mfa_step_up_required', 'true'); + navigate('/auth/mfa-step-up'); + return; + } + } catch (error) { + console.error('[AuthCallback] Failed to check MFA status:', error); + // Continue anyway - don't block sign-in + } + } + setStatus('success'); // Show success message diff --git a/src/pages/MFAStepUp.tsx b/src/pages/MFAStepUp.tsx new file mode 100644 index 00000000..6005112a --- /dev/null +++ b/src/pages/MFAStepUp.tsx @@ -0,0 +1,116 @@ +import { useEffect, useState } from 'react'; +import { useNavigate } from 'react-router-dom'; +import { supabase } from '@/integrations/supabase/client'; +import { useToast } from '@/hooks/use-toast'; +import { Header } from '@/components/layout/Header'; +import { MFAChallenge } from '@/components/auth/MFAChallenge'; +import { Shield } from 'lucide-react'; + +export default function MFAStepUp() { + const navigate = useNavigate(); + const { toast } = useToast(); + const [factorId, setFactorId] = useState(null); + + useEffect(() => { + const checkStepUpRequired = async () => { + // Check if this page was accessed via proper flow + const needsStepUp = sessionStorage.getItem('mfa_step_up_required'); + if (!needsStepUp) { + console.log('[MFAStepUp] No step-up flag found, redirecting to auth'); + navigate('/auth'); + return; + } + + // Get the verified TOTP factor + const { data: factors } = await supabase.auth.mfa.listFactors(); + const totpFactor = factors?.totp?.find(f => f.status === 'verified'); + + if (!totpFactor) { + console.log('[MFAStepUp] No verified TOTP factor found'); + toast({ + variant: 'destructive', + title: 'MFA not enrolled', + description: 'Please enroll in two-factor authentication first.', + }); + sessionStorage.removeItem('mfa_step_up_required'); + navigate('/settings?tab=security'); + return; + } + + setFactorId(totpFactor.id); + }; + + checkStepUpRequired(); + }, [navigate, toast]); + + const handleSuccess = async () => { + console.log('[MFAStepUp] MFA verification successful'); + + // Clear the step-up flag + sessionStorage.removeItem('mfa_step_up_required'); + + toast({ + title: 'Verification successful', + description: 'You now have full access to all features.', + }); + + // Redirect to home or intended destination + const intendedPath = sessionStorage.getItem('mfa_intended_path') || '/'; + sessionStorage.removeItem('mfa_intended_path'); + navigate(intendedPath); + }; + + const handleCancel = async () => { + console.log('[MFAStepUp] MFA verification cancelled'); + + // Clear flags + sessionStorage.removeItem('mfa_step_up_required'); + sessionStorage.removeItem('mfa_intended_path'); + + // Sign out for security + await supabase.auth.signOut(); + + toast({ + title: 'Verification cancelled', + description: 'You have been signed out.', + }); + + navigate('/auth'); + }; + + return ( +
+
+ +
+
+
+
+
+
+ +
+
+

Additional Verification Required

+

+ Your role requires two-factor authentication. Please verify your identity to continue. +

+
+ + {factorId ? ( + + ) : ( +
+
+
+ )} +
+
+
+
+ ); +}