A production-ready, secure, and flexible Two-Factor Authentication (2FA) system with dynamic email templates, built with TypeScript and MongoDB.
Status: π READY FOR PRODUCTION DEPLOYMENT
- β 100% Test Success Rate (79/79 tests passing)
- β Multi-Template Support with dynamic template selection
- β Rate Limiting per email address
- β Robust Date Validation for MongoDB compatibility
- β Comprehensive Error Handling
- β TypeScript Support with full type safety
- β Health Monitoring and built-in checks
- Secure OTP Generation: Cryptographically secure random OTP codes
- Rate Limiting: Configurable rate limiting per email (3 requests per 15 minutes)
- HMAC Validation: Cryptographic integrity checks
- Session Management: Proper session ID handling
- Input Validation: Comprehensive parameter validation
- Template at Generation Time: Pass templates directly to
generate()function - Multiple Template Types: Login, registration, password reset, 2FA
- Custom Templates: Create your own templates for specific needs
- Template Variables: Support for dynamic content (OTP, expiry time, etc.)
- HTML & Text Support: Both rich HTML and plain text email formats
- Adapter Pattern: Pluggable database, email, and rate limiter adapters
- MongoDB Integration: Robust database adapter with date validation
- Multiple Email Providers: Console, Brevo, Mailgun, Postmark, custom
- Memory Rate Limiter: In-memory rate limiting for development/testing
- Event System: Comprehensive event handling and monitoring
- TypeScript: Full type safety and IntelliSense support
- Comprehensive Testing: 79 tests covering all functionality
- Error Handling: Detailed error messages and logging
- Health Checks: Built-in health monitoring
- Documentation: Complete guides and examples
npm install secure-2faimport {
SecureEmailOtp,
MongooseAdapter,
ConsoleEmailAdapter,
MemoryRateLimiterAdapter,
} from "secure-2fa";
import mongoose from "mongoose";
// Connect to MongoDB
await mongoose.connect("mongodb://localhost:27017/your-database");
// Initialize OTP service
const otpService = new SecureEmailOtp(
new MongooseAdapter({ connection: mongoose.connection }),
new ConsoleEmailAdapter(), // Use console for development
new MemoryRateLimiterAdapter(),
"your-server-secret-key-here-at-least-32-chars-long"
);
// Generate OTP with custom template
const result = await otpService.generate({
email: "[email protected]",
context: "login",
requestMeta: { ip: "127.0.0.1", userAgent: "Mozilla/5.0..." },
template: {
subject: "π Your Login Code",
html: "<h1>Code: {{otp}}</h1>",
text: "Code: {{otp}}",
},
});
console.log("OTP sent! Session ID:", result.sessionId);// Client sends hashed OTP
const clientHash = hashOtp("123456"); // Client-side hashing
const verification = await otpService.verify({
email: "[email protected]",
clientHash,
context: "login",
sessionId: result.sessionId,
requestMeta: { ip: "127.0.0.1", userAgent: "Mozilla/5.0..." },
});
if (verification.success) {
console.log("OTP verified successfully!");
}Templates are passed directly to the generate() function for maximum flexibility:
// Define templates for different purposes
const templates = {
login: {
subject: "π Login Verification Code",
html: "<h1>Login Code: {{otp}}</h1>",
text: "Login Code: {{otp}}",
senderName: "Security Team",
senderEmail: "[email protected]",
},
registration: {
subject: "π Welcome! Verify Your Email",
html: "<h1>Welcome! Your code: {{otp}}</h1>",
text: "Welcome! Your code: {{otp}}",
senderName: "Welcome Team",
senderEmail: "[email protected]",
},
};
// Use different templates based on context
const context = "login";
const template = templates[context];
const result = await otpService.generate({
email: "[email protected]",
context,
requestMeta: { ip: "127.0.0.1", userAgent: "Mozilla/5.0..." },
template,
});All templates support dynamic variables:
| Variable | Description | Example |
|---|---|---|
{{otp}} |
The actual OTP code | 123456 |
{{email}} |
User's email address | [email protected] |
{{context}} |
OTP context | login, registration |
{{expiryMinutes}} |
Expiration time | 2 minutes |
{{companyName}} |
Company name | Your Company |
{{supportEmail}} |
Support email | [email protected] |
const otpService = new SecureEmailOtp(
dbAdapter,
emailProvider,
rateLimiter,
serverSecret,
{
rateLimit: {
maxPerWindow: 3, // 3 requests per window
windowMs: 15 * 60 * 1000, // 15 minutes
},
}
);const otpService = new SecureEmailOtp(
dbAdapter,
emailProvider,
rateLimiter,
serverSecret,
{
otpLength: 6, // 6-digit OTP
expiryMs: 2 * 60 * 1000, // 2 minutes
maxRetries: 5, // 5 verification attempts
strictMode: true, // Strict metadata checking
}
);import { ConsoleEmailAdapter } from "secure-2fa";
const emailProvider = new ConsoleEmailAdapter();import { BrevoAdapter } from "secure-2fa";
const emailProvider = new BrevoAdapter({
apiKey: "your-brevo-api-key",
senderEmail: "[email protected]",
senderName: "Your Company",
});import { MailgunAdapter } from "secure-2fa";
const emailProvider = new MailgunAdapter({
apiKey: "your-mailgun-api-key",
domain: "your-domain.com",
senderEmail: "[email protected]",
});npm test- β OTP Generation: Secure OTP creation and validation
- β Email Templates: Template rendering and variable substitution
- β Rate Limiting: Rate limit enforcement and reset
- β Database Operations: MongoDB integration and date validation
- β Error Handling: Comprehensive error scenarios
- β Health Checks: System health monitoring
Test Suites: 7 passed, 7 total
Tests: 79 passed, 79 total
Snapshots: 0 total
Time: 19.111 s
- Multi-Template Guide - Comprehensive template system documentation
- Mongoose Fix Guide - Date validation and MongoDB compatibility
- Production Readiness Report - Production deployment guide
- Multi-Template Example - Full Express server with multiple templates
- Template at Generation Example - Simple usage demonstration
- Brevo Integration - Production email provider setup
- Types - Complete TypeScript type definitions
- Core Service - Main OTP service implementation
- Adapters - Database, email, and rate limiter adapters
- All tests passing (79/79)
- Rate limiting configured
- Email provider configured
- Database connection stable
- Error handling implemented
- Monitoring configured
- Health checks working
-
Install Dependencies
npm install secure-2fa
-
Configure Email Provider
// Use production email provider const emailProvider = new BrevoAdapter({ apiKey: process.env.BREVO_API_KEY, senderEmail: "[email protected]", });
-
Set Up Monitoring
// Health check endpoint app.get("/health", async (req, res) => { const health = await otpService.healthCheck(); res.json(health); });
-
Deploy and Monitor
- Monitor OTP generation success rates
- Track rate limiting effectiveness
- Watch for date validation errors
- Monitor email delivery success
- Rate Limiting: Prevents abuse and spam
- OTP Hashing: Secure bcrypt hashing of OTPs
- HMAC Validation: Cryptographic integrity checks
- Session Management: Proper session ID handling
- Input Validation: Comprehensive parameter validation
- Error Sanitization: No sensitive data in error messages
- Date Validation: Robust MongoDB date handling
- Use HTTPS in production
- Implement proper error handling
- Monitor for suspicious activity
- Regular security audits
- Keep dependencies updated
git clone <repository>
cd secure-2fa
npm install
npm run build
npm test- TypeScript for type safety
- Jest for testing
- ESLint for code quality
- Prettier for formatting
This project is licensed under the MIT License - see the LICENSE file for details.
- Documentation: Check the comprehensive documentation
- Examples: Review the example files
- Tests: Run the test suite to verify functionality
- Issues: Report bugs and feature requests
| Issue | Solution |
|---|---|
| Date validation errors | Check Mongoose Fix Guide |
| Template not working | Review Multi-Template Guide |
| Rate limiting issues | Check rate limit configuration |
| Email not sending | Verify email provider setup |
The Secure 2FA system is production ready with:
- β 100% Test Success Rate
- β Comprehensive Error Handling
- β Robust Rate Limiting
- β Flexible Template System
- β Production-Grade Security
- β Complete Documentation
Status: π READY FOR PRODUCTION DEPLOYMENT