import { type FormEvent, useEffect, useMemo, useState } from 'react'; import { Eye, EyeOff } from 'lucide-react'; import { Card, Input, Button, Alert, FormField } from '@cameleer/design-system'; import cameleerLogo from '@cameleer/design-system/assets/cameleer-logo.svg'; import { startAuthentication, startRegistration as startWebAuthnReg } from '@simplewebauthn/browser'; import { signIn, startRegistration, completeRegistration, startForgotPassword, forgotPasswordVerifyAndReset, verifyTotp, verifyBackupCode, submitMfa, startWebAuthnAuth, verifyWebAuthnAuth, startWebAuthnRegistration, verifyWebAuthnRegistration, bindMfaProfile, generateBackupCodes, createTotpSecret, verifyTotpSetup, skipMfaEnrollment, submitInteraction, MfaRequiredError, MfaEnrollmentError, } from './experience-api'; import styles from './SignInPage.module.css'; type Mode = 'signIn' | 'register' | 'verifyCode' | 'forgotPassword' | 'forgotPasswordVerify' | 'mfaVerify' | 'mfaBackupCode' | 'mfaWebauthn' | 'mfaMethodPicker' | 'mfaEnroll' | 'mfaEnrollTotp'; const SIGN_IN_SUBTITLES = [ "Prove you're not a mirage", "Only authorized cameleers beyond this dune", "Halt, traveler — state your business", "The caravan doesn't move without credentials", "No hitchhikers on this caravan", "This oasis requires a password", "Camels remember faces. We use passwords.", "You shall not pass... without logging in", "The desert is vast. Your session has expired.", "Another day, another dune to authenticate", "Papers, please. The caravan master is watching.", "Trust, but verify — ancient cameleer proverb", "Even the Silk Road had checkpoints", "Your camel is parked outside. Now identify yourself.", "One does not simply walk into the dashboard", "The sands shift, but your password shouldn't", "Unauthorized access? In this economy?", "Welcome back, weary traveler", "The dashboard awaits on the other side of this dune", "Keep calm and authenticate", "Who goes there? Friend or rogue exchange?", "Access denied looks the same in every desert", "May your routes be green and your tokens valid", "Forgot your password? That's between you and the dunes.", "No ticket, no caravan", ]; const REGISTER_SUBTITLES = [ "Every great journey starts with a single sign-up", "Welcome to the caravan — let's get you registered", "A new cameleer approaches the oasis", "Join the caravan. We have dashboards.", "The desert is better with company", "First time here? The camels don't bite.", "Pack your bags, you're joining the caravan", "Room for one more on this caravan", "New rider? Excellent. Credentials, please.", "The Silk Road awaits — just need your email first", ]; function pickRandom(arr: string[]) { return arr[Math.floor(Math.random() * arr.length)]; } function getInitialMode(): Mode { const params = new URLSearchParams(window.location.search); if (params.get('first_screen') === 'register') return 'register'; if (window.location.pathname.endsWith('/register')) return 'register'; return 'signIn'; } export function SignInPage() { const [mode, setMode] = useState(getInitialMode); const [registrationEnabled, setRegistrationEnabled] = useState(true); const [emailConnectorConfigured, setEmailConnectorConfigured] = useState(false); const subtitle = useMemo( () => pickRandom(mode === 'signIn' ? SIGN_IN_SUBTITLES : REGISTER_SUBTITLES), [mode === 'signIn' ? 'signIn' : 'register'], ); const [identifier, setIdentifier] = useState(''); const [password, setPassword] = useState(''); const [confirmPassword, setConfirmPassword] = useState(''); const [code, setCode] = useState(''); const [showPassword, setShowPassword] = useState(false); const [loading, setLoading] = useState(false); const [error, setError] = useState(null); const [verificationId, setVerificationId] = useState(''); const [newPassword, setNewPassword] = useState(''); const [confirmNewPassword, setConfirmNewPassword] = useState(''); const [webauthnError, setWebauthnError] = useState(''); const [webauthnLoading, setWebauthnLoading] = useState(false); // Fetch sign-in experience to check if registration is enabled useEffect(() => { fetch('/api/.well-known/sign-in-exp') .then((r) => r.json()) .then((data) => { const enabled = data.signInMode === 'SignInAndRegister'; setRegistrationEnabled(enabled); if (!enabled && mode !== 'signIn') setMode('signIn'); const hasEmailConnector = Array.isArray(data.signUp?.identifiers) && data.signUp.identifiers.includes('email'); setEmailConnectorConfigured(hasEmailConnector); }) .catch(() => {}); }, []); // Reset error when switching modes useEffect(() => { setError(null); }, [mode]); const switchMode = (next: Mode) => { setMode(next); setPassword(''); setConfirmPassword(''); setNewPassword(''); setConfirmNewPassword(''); setCode(''); setShowPassword(false); setVerificationId(''); }; // --- Sign-in --- const handleSignIn = async (e: FormEvent) => { e.preventDefault(); setError(null); setLoading(true); try { const redirectTo = await signIn(identifier, password); window.location.replace(redirectTo); } catch (err) { if (err instanceof MfaRequiredError) { const pref = localStorage.getItem('mfa_method_preference'); if (pref === 'webauthn') { setMode('mfaWebauthn'); } else if (pref === 'totp') { setMode('mfaVerify'); } else { setMode('mfaMethodPicker'); } setLoading(false); return; } if (err instanceof MfaEnrollmentError) { setMode('mfaEnroll'); setLoading(false); return; } setError(err instanceof Error ? err.message : 'Sign-in failed'); setLoading(false); } }; // --- Register step 1: send verification code --- const handleRegister = async (e: FormEvent) => { e.preventDefault(); setError(null); if (!identifier.includes('@')) { setError('Please enter a valid email address'); return; } if (password !== confirmPassword) { setError('Passwords do not match'); return; } if (password.length < 8) { setError('Password must be at least 8 characters'); return; } setLoading(true); try { const vId = await startRegistration(identifier); setVerificationId(vId); setMode('verifyCode'); } catch (err) { setError(err instanceof Error ? err.message : 'Registration failed'); } finally { setLoading(false); } }; // --- Register step 2: verify code + complete --- const handleVerifyCode = async (e: FormEvent) => { e.preventDefault(); setError(null); setLoading(true); try { const redirectTo = await completeRegistration(identifier, password, verificationId, code); window.location.replace(redirectTo); } catch (err) { if (err instanceof MfaEnrollmentError) { setMode('mfaEnroll'); setLoading(false); return; } setError(err instanceof Error ? err.message : 'Verification failed'); setLoading(false); } }; // --- Forgot password step 1: send reset code --- const handleForgotPassword = async (e: FormEvent) => { e.preventDefault(); setError(null); if (!identifier.includes('@')) { setError('Please enter your email address'); return; } setLoading(true); try { const vId = await startForgotPassword(identifier); setVerificationId(vId); setMode('forgotPasswordVerify'); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to send reset code'); } finally { setLoading(false); } }; // --- Forgot password step 2: verify code + set new password --- const handleForgotPasswordVerify = async (e: FormEvent) => { e.preventDefault(); setError(null); if (newPassword !== confirmNewPassword) { setError('Passwords do not match'); return; } if (newPassword.length < 8) { setError('Password must be at least 8 characters'); return; } setLoading(true); try { await forgotPasswordVerifyAndReset(identifier, verificationId, code, newPassword); // Send security notification email (fire-and-forget) fetch('/platform/api/password-reset-notification', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: identifier }), }).catch(() => {}); // Reset to sign-in with success message switchMode('signIn'); setError(null); setIdentifier(identifier); // preserve email for convenience alert('Password reset successful. Please sign in with your new password.'); } catch (err) { setError(err instanceof Error ? err.message : 'Password reset failed'); } finally { setLoading(false); } }; // --- MFA: TOTP verification --- const handleMfaVerify = async (e: FormEvent) => { e.preventDefault(); setError(null); setLoading(true); try { const verificationId = await verifyTotp(code); localStorage.setItem('mfa_method_preference', 'totp'); const redirectTo = await submitMfa(verificationId); window.location.replace(redirectTo); } catch (err) { setError(err instanceof Error ? err.message : 'Verification failed'); setLoading(false); } }; // --- MFA: WebAuthn/passkey verification --- async function handleWebAuthnVerify() { setWebauthnError(''); setWebauthnLoading(true); try { const options = await startWebAuthnAuth(); const credential = await startAuthentication({ optionsJSON: options as any }); const verificationId = await verifyWebAuthnAuth(credential as unknown as Record); localStorage.setItem('mfa_method_preference', 'webauthn'); const redirectTo = await submitMfa(verificationId); window.location.replace(redirectTo); } catch (err) { setWebauthnError(err instanceof Error ? err.message : 'Passkey verification failed'); setWebauthnLoading(false); } } // Auto-trigger passkey prompt when entering mfaWebauthn mode useEffect(() => { if (mode === 'mfaWebauthn') { handleWebAuthnVerify(); } // eslint-disable-next-line react-hooks/exhaustive-deps }, [mode]); // --- MFA: backup code verification --- const handleBackupCodeVerify = async (e: FormEvent) => { e.preventDefault(); setError(null); setLoading(true); try { const verificationId = await verifyBackupCode(code); const redirectTo = await submitMfa(verificationId); window.location.replace(redirectTo); } catch (err) { setError(err instanceof Error ? err.message : 'Verification failed'); setLoading(false); } }; // --- MFA enrollment --- const [totpSetup, setTotpSetup] = useState<{ secret: string; secretQrCode: string; verificationId: string } | null>(null); const [totpCode, setTotpCode] = useState(''); async function handleEnrollPasskey() { setError(null); setLoading(true); try { const { verificationId, registrationOptions } = await startWebAuthnRegistration(); const credential = await startWebAuthnReg({ optionsJSON: registrationOptions as any }); const verifiedId = await verifyWebAuthnRegistration(verificationId, credential as unknown as Record); await bindMfaProfile('WebAuthn', verifiedId); const bc = await generateBackupCodes(); await bindMfaProfile('BackupCode', bc.verificationId); const result = await submitInteraction(); window.location.replace(result); } catch (err) { if (err instanceof Error && err.name === 'NotAllowedError') { setLoading(false); return; } setError(err instanceof Error ? err.message : 'Passkey registration failed'); setLoading(false); } } async function handleStartTotpEnroll() { setError(null); setLoading(true); try { const data = await createTotpSecret(); setTotpSetup(data); setTotpCode(''); setMode('mfaEnrollTotp'); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to start TOTP setup'); } finally { setLoading(false); } } async function handleVerifyTotpEnroll(e: FormEvent) { e.preventDefault(); setError(null); setLoading(true); try { const verifiedId = await verifyTotpSetup(totpCode); await bindMfaProfile('Totp', verifiedId); const bc = await generateBackupCodes(); await bindMfaProfile('BackupCode', bc.verificationId); const result = await submitInteraction(); window.location.replace(result); } catch (err) { setError(err instanceof Error ? err.message : 'Verification failed'); setLoading(false); } } async function handleSkipEnrollment() { setLoading(true); try { const redirectTo = await skipMfaEnrollment(); window.location.replace(redirectTo); } catch (err) { setError(err instanceof Error ? err.message : 'Failed to continue'); setLoading(false); } } const passwordToggle = ( ); return (
Cameleer

{subtitle}

{error && (
{error}
)} {/* --- Sign-in form --- */} {mode === 'signIn' && (
setIdentifier(e.target.value)} placeholder="you@company.com" autoFocus autoComplete="username" disabled={loading} />
setPassword(e.target.value)} placeholder="••••••••" autoComplete="current-password" disabled={loading} /> {passwordToggle}
{emailConnectorConfigured && ( )} {registrationEnabled && (

Don't have an account?{' '}

)}
)} {/* --- Register form --- */} {mode === 'register' && (
setIdentifier(e.target.value)} placeholder="you@company.com" autoFocus autoComplete="email" disabled={loading} />
setPassword(e.target.value)} placeholder="At least 8 characters" autoComplete="new-password" disabled={loading} /> {passwordToggle}
setConfirmPassword(e.target.value)} placeholder="••••••••" autoComplete="new-password" disabled={loading} />

Already have an account?{' '}

)} {/* --- Verification code form --- */} {mode === 'verifyCode' && (

We sent a verification code to {identifier}

setCode(e.target.value.replace(/\D/g, '').slice(0, 6))} placeholder="000000" autoFocus autoComplete="one-time-code" disabled={loading} />

)} {/* --- Forgot password: email entry --- */} {mode === 'forgotPassword' && (

Enter your email address and we'll send you a code to reset your password.

setIdentifier(e.target.value)} placeholder="you@company.com" autoFocus autoComplete="email" disabled={loading} />

)} {/* --- Forgot password: verify code + new password --- */} {mode === 'forgotPasswordVerify' && (

We sent a verification code to {identifier}

setCode(e.target.value.replace(/\D/g, '').slice(0, 6))} placeholder="000000" autoFocus autoComplete="one-time-code" disabled={loading} />
setNewPassword(e.target.value)} placeholder="At least 8 characters" autoComplete="new-password" disabled={loading} /> {passwordToggle}
setConfirmNewPassword(e.target.value)} placeholder="••••••••" autoComplete="new-password" disabled={loading} />

)} {/* --- MFA: TOTP verification --- */} {mode === 'mfaVerify' && (

Enter the 6-digit code from your authenticator app.

setCode(e.target.value.replace(/\D/g, '').slice(0, 6))} placeholder="000000" autoFocus autoComplete="one-time-code" disabled={loading} />

Lost your device?

)} {/* --- MFA: backup code verification --- */} {mode === 'mfaBackupCode' && (

Enter one of your 10 backup codes.

setCode(e.target.value)} placeholder="Enter backup code" autoFocus autoComplete="off" disabled={loading} />

)} {/* --- MFA: method picker --- */} {mode === 'mfaMethodPicker' && (

Verify your identity

Choose a verification method

)} {/* --- MFA: WebAuthn/passkey verification --- */} {mode === 'mfaWebauthn' && (

Passkey verification

Use your fingerprint, face, or security key

{webauthnError && {webauthnError}}
)} {/* --- MFA enrollment: choose method --- */} {mode === 'mfaEnroll' && (

Secure your account

Add an extra layer of security to your account.

{error && {error}}
)} {/* --- MFA enrollment: TOTP setup --- */} {mode === 'mfaEnrollTotp' && totpSetup && (

Set up authenticator

Scan this QR code with your authenticator app, then enter the 6-digit code.

{error && {error}}
TOTP QR Code
{totpSetup.secret}
setTotpCode(e.target.value.replace(/\D/g, '').slice(0, 6))} placeholder="Enter 6-digit code" autoFocus autoComplete="one-time-code" />
)}
); }