Dependencies have been added to backend/package.json:
speakeasy- TOTP generation and verificationqrcode- QR code generation@types/speakeasy- TypeScript types
Install with:
cd backend && npm installThe backend 2FA router is already integrated into src/index.ts:
apiV1Router.use('/auth/2fa', twoFactorAuthRouter);All endpoints are available at /api/v1/auth/2fa/*
Use the provided components in your application:
import { TwoFactorSetup } from '@/components/auth/TwoFactorSetup';
<TwoFactorSetup userId={userId} onSuccess={() => /* redirect */} />import { TwoFactorVerification } from '@/components/auth/TwoFactorVerification';
<TwoFactorVerification userId={userId} onSuccess={(deviceHash) => /* complete login */} />import { TwoFactorSettings } from '@/components/auth/TwoFactorSettings';
<TwoFactorSettings userId={userId} />import { TwoFactorRecovery } from '@/components/auth/TwoFactorRecovery';
<TwoFactorRecovery userId={userId} onSuccess={() => /* redirect */} />backend/src/
├── services/
│ ├── 2fa-service.ts # Core 2FA logic
│ └── __tests__/
│ └── 2fa-service.test.ts # Service tests
├── routes/
│ ├── 2fa.ts # API endpoints
│ └── __tests__/
│ └── 2fa.test.ts # Route tests
├── schemas/
│ └── 2fa.ts # Zod validation schemas
├── types/
│ └── 2fa.ts # TypeScript types
frontend/
├── components/auth/
│ ├── TwoFactorSetup.tsx # Setup component
│ ├── TwoFactorVerification.tsx # Verification component
│ ├── TwoFactorSettings.tsx # Settings component
│ └── TwoFactorRecovery.tsx # Recovery component
├── lib/hooks/
│ └── use2fa.ts # API hooks
├── types/
│ └── 2fa.ts # TypeScript types
docs/
└── 2FA_IMPLEMENTATION.md # Complete API documentation
In backend/src/services/2fa-service.ts, adjust these constants:
// Time window for token verification (±30s)
const TOKEN_WINDOW = 2;
// Number of backup codes
const BACKUP_CODE_COUNT = 10;
// Backup code length
const BACKUP_CODE_LENGTH = 8;
// Recovery token expiry in hours
const RECOVERY_TOKEN_EXPIRY_HOURS = 24;In frontend/lib/hooks/use2fa.ts, set the API URL:
const BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:3000';- User navigates to settings
- Clicks "Enable 2FA"
- Selects an authenticator app
- Component generates QR code
- User scans QR code with authenticator app
- User enters 6-digit code to confirm
- User saves backup codes
- 2FA is enabled
- User enters credentials
- If 2FA enabled, verification prompt appears
- User enters 6-digit code from authenticator app
- Or can use backup code if needed
- Option to "trust this device" for 30 days
- Login completes
- User clicks "Can't access your authenticator app?"
- Chooses recovery method (email or support ticket)
- Recovery instructions sent
- User completes verification
- New authenticator setup required
# Backend tests
cd backend
npm test
# Specifically 2FA tests
npm test -- 2fa- Create a new user account
- Navigate to security settings
- Enable 2FA and scan QR code
- Try logging out and back in with 2FA
- Test backup codes
- Test recovery process
- ✅ Time-based verification - TOTP with 60-second window and ±30s tolerance
- ✅ Backup codes - 10 codes for emergency access
- ✅ Device trust - Optional 30-day device memorization
- ✅ Activity logging - Complete audit trail of 2FA actions
- ✅ Recovery flow - Account recovery without authenticator app
- ✅ Rate limiting - (Implement in middleware)
- ✅ Code hashing - Backup codes stored as hashes
- In-Memory Storage: Currently stores in memory. Need database integration
- Email Service: Recovery emails not yet sent (integrate with email provider)
- Admin Controls: No admin override capability yet
- Rate Limiting: Implement rate limiting on verification attempts
- Transaction Enforcement: 2FA not yet enforced for high-value transactions
- Grace Period: No grace period for 2FA enablement
- WebAuthn/FIDO2 support for hardware keys
- SMS-based 2FA fallback
- Push-based verification
- Biometric verification options
- Admin dashboard for 2FA management
- Organization-wide 2FA policies
- Device fingerprinting improvements
- Anomaly detection and alerts
- Integration with identity providers (Auth0, etc.)
- Ensure adequate lighting
- Try a different authenticator app
- Enter the secret key manually from the app (shown below QR code)
- Use backup codes if available
- Use account recovery feature
- Contact support for manual verification
- Check device time synchronization
- Allow time window tolerance (±30 seconds already enabled)
- Manual time adjustment on device
- Regenerate backup codes from settings
- Save new codes securely
For complete API documentation, see 2FA_IMPLEMENTATION.md
Setup 2FA:
curl -X POST http://localhost:3000/api/v1/auth/2fa/setup \
-H "Content-Type: application/json" \
-d '{"userId":"550e8400-e29b-41d4-a716-446655440000"}'Verify Token:
curl -X POST http://localhost:3000/api/v1/auth/2fa/verify \
-H "Content-Type: application/json" \
-d '{"userId":"550e8400-e29b-41d4-a716-446655440000","token":"123456"}'Get Status:
curl http://localhost:3000/api/v1/auth/2fa/status/550e8400-e29b-41d4-a716-446655440000For issues or questions:
- Check error messages in the UI
- Review 2FA logs for activity
- Check browser console for client-side errors
- Review server logs for backend errors
- Refer to 2FA_IMPLEMENTATION.md for detailed documentation
When making changes to 2FA:
- Update both backend and frontend types
- Keep schemas in sync with types
- Add/update tests
- Document changes in this README
- Update API documentation if endpoints change
Part of AgenticPay project. See main LICENSE file.