This implementation provides TOTP (Time-based One-Time Password) based two-factor authentication using authenticator apps like Google Authenticator, Authy, Microsoft Authenticator, or FreeOTP.
- ✅ TOTP secret generation with QR code
- ✅ TOTP token verification with time window tolerance
- ✅ Backup codes generation and validation (10 codes, 8 characters each)
- ✅ 2FA setup and confirmation workflow
- ✅ Device trust/remember device for 30 days
- ✅ Account recovery through email or support tickets
- ✅ 2FA activity logging and audit trail
- ✅ Backup code regeneration
- ✅ 2FA enforcement on high-value transactions
- ✅
TwoFactorSetup- Initial 2FA setup with QR code scanning - ✅
TwoFactorVerification- Login verification component - ✅
TwoFactorSettings- Settings management and backup codes - ✅
TwoFactorRecovery- Account recovery interface
Initialize TOTP setup for a user.
Request:
{
"userId": "550e8400-e29b-41d4-a716-446655440000"
}Response:
{
"secret": "JBSWY3DPEBLW64TMMQ======",
"qrCode": "data:image/png;base64,...",
"backupCodes": [
"ABCD1234",
"EFGH5678",
...
]
}Confirm 2FA setup by verifying a TOTP token.
Request:
{
"userId": "550e8400-e29b-41d4-a716-446655440000",
"token": "123456",
"backupCodesConfirmed": true
}Response:
{
"success": true,
"message": "2FA has been successfully enabled"
}Verify a TOTP token during login.
Request:
{
"userId": "550e8400-e29b-41d4-a716-446655440000",
"token": "123456",
"rememberDevice": true
}Response:
{
"success": true,
"message": "2FA verification successful",
"backupCodesRemaining": 9,
"deviceHash": "abc123..."
}Get 2FA status for a user.
Response:
{
"userId": "550e8400-e29b-41d4-a716-446655440000",
"enabled": true,
"verifiedAt": "2024-04-27T10:00:00Z",
"lastUsedAt": "2024-04-27T11:30:00Z",
"backupCodesRemaining": 8
}Disable 2FA for a user.
Request:
{
"token": "123456",
"reason": "Lost device"
}Response:
{
"success": true,
"message": "2FA has been disabled",
"reason": "Lost device"
}Get backup codes (requires verification).
Request:
{
"userId": "550e8400-e29b-41d4-a716-446655440000",
"token": "123456"
}Response:
{
"backupCodes": [
"ABCD1234",
"EFGH5678",
...
]
}Regenerate backup codes.
Request:
{
"userId": "550e8400-e29b-41d4-a716-446655440000",
"token": "123456"
}Response:
{
"backupCodes": [
"IJKL9012",
"MNOP3456",
...
],
"message": "Backup codes have been regenerated"
}Get 2FA activity logs.
Response:
{
"logs": [
{
"id": "log-uuid",
"action": "2fa_verified",
"success": true,
"ipAddress": "192.168.1.1",
"userAgent": "Mozilla/5.0...",
"createdAt": "2024-04-27T11:30:00Z"
}
],
"total": 42
}Request account recovery.
Request:
{
"userId": "550e8400-e29b-41d4-a716-446655440000",
"method": "email"
}Response:
{
"recoveryToken": "recovery-token-uuid",
"message": "Recovery instructions have been sent via email",
"expiresIn": 24
}Complete account recovery.
Request:
{
"userId": "550e8400-e29b-41d4-a716-446655440000",
"recoveryToken": "recovery-token-uuid",
"newSecret": "optional-new-secret"
}Response:
{
"success": true,
"message": "Account recovery completed successfully",
"requiresVerification": true
}Check if a device is remembered.
Request:
{
"userId": "550e8400-e29b-41d4-a716-446655440000",
"deviceHash": "abc123..."
}Response:
{
"isRemembered": true
}import { TwoFactorSetup } from '@/components/auth/TwoFactorSetup';
export function SettingsPage() {
const userId = useAuthStore((s) => s.userId);
return (
<TwoFactorSetup
userId={userId}
onSuccess={() => {
// Redirect or show success message
}}
/>
);
}import { TwoFactorVerification } from '@/components/auth/TwoFactorVerification';
export function LoginPage() {
const [requiresVerification, setRequiresVerification] = useState(false);
return requiresVerification ? (
<TwoFactorVerification
userId={userId}
onSuccess={(deviceHash) => {
// Save deviceHash to localStorage for "remember device"
// Complete login
}}
/>
) : (
<LoginForm />
);
}import { TwoFactorSettings } from '@/components/auth/TwoFactorSettings';
export function AccountSettingsPage() {
const userId = useAuthStore((s) => s.userId);
return (
<TwoFactorSettings userId={userId} />
);
}import { TwoFactorRecovery } from '@/components/auth/TwoFactorRecovery';
export function RecoveryPage() {
return (
<TwoFactorRecovery
userId={userId}
onSuccess={() => {
// Show success message
}}
/>
);
}- The implementation allows for 2 time windows (±30 seconds) to handle clock skew
- Adjust
TOKEN_WINDOWin2fa-service.tsif needed
- Backup codes are hashed before storage to prevent timing attacks
- Users should securely store backup codes (offline, password manager, etc.)
- Consider implementing rate limiting on verification endpoints
- Max attempts before temporary lockout
- Recovery tokens expire after 24 hours
- Configure
RECOVERY_TOKEN_EXPIRY_HOURSin2fa-service.ts
- Remembered devices expire after 30 days
- Device trust is based on both IP and user-agent
- Configure device expiry in
rememberDevicefunction
The current implementation uses in-memory storage. For production, you'll need to:
-
Create database tables for:
two_factor_setupstwo_factor_logsremembered_devicesrecovery_tokens
-
Replace Map-based storage with database queries
-
Consider caching frequently accessed data
- Setup 2FA and scan QR code
- Confirm setup with correct token
- Verify token during login
- Use backup codes
- Regenerate backup codes
- Remember device for 30 days
- Request and complete recovery
- View 2FA logs
- Disable 2FA
- Test with incorrect tokens
- Invalid QR code scanning
- Token expired (outside time window)
- All backup codes used
- Multiple simultaneous setups
- Recovery token expiration
- Device re-memorization
- In-Memory Storage: Current implementation doesn't persist data
- Email/SMS: Recovery methods need integration with email service
- Admin Disable: No admin override for disabling user's 2FA
- Transaction Enforcement: 2FA enforcement on high-value transactions not yet implemented
- Grace Period: No grace period for 2FA enablement
- WebAuthn/FIDO2 support
- SMS-based 2FA
- Push-based verification
- Biometric verification
- 2FA enforcement policies per organization
- Admin dashboard for 2FA management
- Historical device trust tracking
- Anomaly detection on failed attempts
- Integration with identity providers
For issues or questions:
- Check the API response error messages
- Review 2FA logs for activity
- Use recovery process if locked out
- Contact support team for account recovery