Skip to content

MetaDevZone/secure-2fa

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

19 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Secure 2FA - Multi-Template OTP System

A production-ready, secure, and flexible Two-Factor Authentication (2FA) system with dynamic email templates, built with TypeScript and MongoDB.

βœ… Production Ready

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

🎯 Key Features

πŸ” Security First

  • 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

πŸ“§ Dynamic Email Templates

  • 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

πŸ—οΈ Flexible Architecture

  • 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

πŸ”§ Developer Experience

  • 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

πŸš€ Quick Start

Installation

npm install secure-2fa

Basic Usage

import {
  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);

Verify OTP

// 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!");
}

πŸ“§ Multi-Template System

Template at Generation Time

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,
});

Template Variables

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]

πŸ”§ Configuration

Rate Limiting

const otpService = new SecureEmailOtp(
  dbAdapter,
  emailProvider,
  rateLimiter,
  serverSecret,
  {
    rateLimit: {
      maxPerWindow: 3, // 3 requests per window
      windowMs: 15 * 60 * 1000, // 15 minutes
    },
  }
);

OTP Settings

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
  }
);

Email Providers

Console (Development)

import { ConsoleEmailAdapter } from "secure-2fa";

const emailProvider = new ConsoleEmailAdapter();

Brevo (Production)

import { BrevoAdapter } from "secure-2fa";

const emailProvider = new BrevoAdapter({
  apiKey: "your-brevo-api-key",
  senderEmail: "[email protected]",
  senderName: "Your Company",
});

Mailgun (Production)

import { MailgunAdapter } from "secure-2fa";

const emailProvider = new MailgunAdapter({
  apiKey: "your-mailgun-api-key",
  domain: "your-domain.com",
  senderEmail: "[email protected]",
});

πŸ§ͺ Testing

Run Tests

npm test

Test Coverage

  • βœ… 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 Results

Test Suites: 7 passed, 7 total
Tests:       79 passed, 79 total
Snapshots:   0 total
Time:        19.111 s

πŸ“š Documentation

πŸ“– Complete Documentation

🎯 Examples

πŸ”§ API Reference

  • Types - Complete TypeScript type definitions
  • Core Service - Main OTP service implementation
  • Adapters - Database, email, and rate limiter adapters

πŸš€ Production Deployment

βœ… Pre-Deployment Checklist

  • All tests passing (79/79)
  • Rate limiting configured
  • Email provider configured
  • Database connection stable
  • Error handling implemented
  • Monitoring configured
  • Health checks working

πŸ”§ Deployment Steps

  1. Install Dependencies

    npm install secure-2fa
  2. Configure Email Provider

    // Use production email provider
    const emailProvider = new BrevoAdapter({
      apiKey: process.env.BREVO_API_KEY,
      senderEmail: "[email protected]",
    });
  3. Set Up Monitoring

    // Health check endpoint
    app.get("/health", async (req, res) => {
      const health = await otpService.healthCheck();
      res.json(health);
    });
  4. Deploy and Monitor

    • Monitor OTP generation success rates
    • Track rate limiting effectiveness
    • Watch for date validation errors
    • Monitor email delivery success

πŸ”’ Security Features

βœ… Implemented Security Measures

  • 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

πŸ›‘οΈ Best Practices

  • Use HTTPS in production
  • Implement proper error handling
  • Monitor for suspicious activity
  • Regular security audits
  • Keep dependencies updated

🀝 Contributing

Development Setup

git clone <repository>
cd secure-2fa
npm install
npm run build
npm test

Code Quality

  • TypeScript for type safety
  • Jest for testing
  • ESLint for code quality
  • Prettier for formatting

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


πŸ†˜ Support

Getting Help

  1. Documentation: Check the comprehensive documentation
  2. Examples: Review the example files
  3. Tests: Run the test suite to verify functionality
  4. Issues: Report bugs and feature requests

Common Issues

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

πŸŽ‰ Production Ready

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

About

No description, website, or topics provided.

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Packages

 
 
 

Contributors