/template recipe-otp-verification
Commercial License Required
MakerKit requires a commercial license. While Orchestre can help you build with it, you must obtain a valid license from MakerKit for commercial use.
Access: /template recipe-otp-verification or /t recipe-otp-verification
Purpose
Implements a complete OTP (One-Time Password) verification system for enhanced security in authentication flows, transaction confirmations, and sensitive operations. This recipe creates a robust OTP infrastructure with multiple delivery methods and security features.
How It Actually Works
The recipe:
- Analyzes your current authentication setup
- Creates OTP generation and storage infrastructure
- Implements delivery mechanisms (SMS, email, authenticator)
- Adds verification UI components
- Integrates rate limiting and security measures
- Sets up session management for verified states
Use Cases
- Two-Factor Authentication: Additional security layer for login
- Transaction Verification: Confirm high-value transactions
- Account Recovery: Secure password reset flows
- Phone Number Verification: Validate user contact information
- Email Verification: Confirm email ownership
- Sensitive Operations: Authorize account deletions, transfers
Examples
Basic SMS OTP
bash
/template recipe-otp-verification sms
# Implements SMS-based OTP with:
# - 6-digit numeric codes
# - 5-minute expiration
# - Twilio integration
# - Rate limiting (3 attempts)Email OTP System
bash
/template recipe-otp-verification email
# Creates email-based OTP with:
# - 8-character alphanumeric codes
# - 10-minute expiration
# - HTML email templates
# - Resend functionalityMulti-Channel OTP
bash
/template recipe-otp-verification multi-channel
# Comprehensive OTP system with:
# - SMS, email, and authenticator app support
# - User preference management
# - Fallback methods
# - Advanced security featuresWhat Gets Created
Database Schema
sql
-- OTP tokens table
create table otp_tokens (
id uuid primary key default gen_random_uuid(),
user_id uuid references auth.users(id) on delete cascade,
token text not null,
token_hash text not null,
type text not null check (type in ('sms', 'email', 'totp')),
channel text not null, -- phone number or email
expires_at timestamp with time zone not null,
verified_at timestamp with time zone,
attempts integer default 0,
metadata jsonb default '{}',
created_at timestamp with time zone default now(),
updated_at timestamp with time zone default now()
);
-- OTP settings per user
create table user_otp_settings (
user_id uuid primary key references auth.users(id) on delete cascade,
preferred_method text check (preferred_method in ('sms', 'email', 'totp')),
phone_verified boolean default false,
email_verified boolean default false,
totp_secret text,
totp_verified boolean default false,
backup_codes text[],
created_at timestamp with time zone default now(),
updated_at timestamp with time zone default now()
);
-- OTP rate limiting
create table otp_rate_limits (
identifier text primary key, -- IP or user_id
action text not null,
attempts integer default 0,
window_start timestamp with time zone default now(),
blocked_until timestamp with time zone
);API Routes
typescript
// app/api/otp/send/route.ts
POST /api/otp/send
- Generate and send OTP
- Rate limiting check
- Delivery method selection
// app/api/otp/verify/route.ts
POST /api/otp/verify
- Validate OTP token
- Update verification status
- Clear used tokens
// app/api/otp/resend/route.ts
POST /api/otp/resend
- Invalidate previous OTP
- Generate new token
- Apply rate limitsReact Components
typescript
// components/otp/otp-verification-form.tsx
- Input for OTP code
- Countdown timer
- Resend button
- Error handling
// components/otp/otp-setup-modal.tsx
- Method selection (SMS/Email/TOTP)
- Phone/email input
- QR code for TOTP
// components/otp/otp-method-selector.tsx
- Choose verification method
- Show available options
- Manage preferencesHooks and Utilities
typescript
// hooks/use-otp.ts
- useOtpVerification()
- useOtpSettings()
- useOtpCountdown()
// lib/otp/generator.ts
- Generate secure tokens
- Hash tokens for storage
- Validate token format
// lib/otp/delivery.ts
- SMS sender (Twilio/Vonage)
- Email sender
- Rate limiterTechnical Details
Security Implementation
typescript
// Token generation with crypto
import { randomBytes } from 'crypto';
function generateOTP(length: number = 6): string {
const digits = '0123456789';
const bytes = randomBytes(length);
return Array.from(bytes)
.map(byte => digits[byte % 10])
.join('');
}
// Secure token storage
function hashOTP(otp: string): string {
return crypto
.createHash('sha256')
.update(otp + process.env.OTP_SALT)
.digest('hex');
}Rate Limiting
typescript
// Advanced rate limiting
const rateLimiter = {
check: async (identifier: string, action: string) => {
const limit = await getLimit(identifier, action);
if (limit.isBlocked()) {
throw new Error('Too many attempts');
}
await incrementAttempts(identifier, action);
}
};Multi-Provider Support
typescript
// Provider abstraction
interface OTPProvider {
send(recipient: string, code: string): Promise<void>;
verify(id: string): Promise<boolean>;
}
class TwilioProvider implements OTPProvider { }
class SendGridProvider implements OTPProvider { }
class VonageProvider implements OTPProvider { }Memory Evolution
The recipe creates comprehensive contextual memory:
markdown
## OTP Verification System
### Current Implementation
- Primary method: SMS via Twilio
- Backup method: Email via Resend
- OTP length: 6 digits
- Expiration: 5 minutes
- Max attempts: 3
### Security Measures
- Rate limiting: 3 OTPs per hour per user
- IP-based blocking after 10 failed attempts
- Token hashing with environment salt
- Automatic cleanup of expired tokens
### Integration Points
- Auth flow: Required for sensitive operations
- User settings: OTP preferences in profile
- Admin panel: OTP analytics and logs
- Webhooks: Success/failure notificationsBest Practices
Security First
- Always hash OTP tokens before storage
- Use environment-specific salts
- Implement exponential backoff for retries
- Clear tokens immediately after use
User Experience
- Show clear countdown timers
- Provide resend functionality
- Support multiple delivery methods
- Remember user preferences
Performance
- Use database indexes on token lookups
- Implement token cleanup jobs
- Cache rate limit checks
- Batch SMS/email sending
Monitoring
- Track delivery success rates
- Monitor verification attempts
- Alert on suspicious patterns
- Log all OTP operations
Integration Points
With Authentication
typescript
// Enhance login flow
const loginWithOTP = async (email, password) => {
const user = await authenticate(email, password);
if (user.otpEnabled) {
await sendOTP(user.id, user.preferredMethod);
return { requiresOTP: true };
}
return { success: true };
};With Billing
typescript
// Secure payment operations
const confirmPayment = async (paymentId, otpCode) => {
await verifyOTP(user.id, otpCode);
return processPayment(paymentId);
};With User Management
typescript
// Account security
const deleteAccount = async (userId, otpCode) => {
await verifyOTP(userId, otpCode);
return permanentlyDeleteUser(userId);
};Troubleshooting
Common Issues
OTP Not Received
- Check SMS/email provider credentials
- Verify phone/email format
- Review provider logs
- Check spam folders
Rate Limit Errors
- Review rate limit configuration
- Check for IP blocking
- Clear rate limit cache
- Adjust thresholds
Token Expiration
- Increase expiration time
- Add grace period
- Show clear countdowns
- Auto-extend on user activity
Debug Helpers
typescript
// OTP debugging
if (process.env.NODE_ENV === 'development') {
console.log('OTP Generated:', otp);
// Also show in UI for testing
}Related Commands
/template add-two-factor- Basic 2FA setup/template add-security-headers- Security enhancements/template add-audit-log- Track OTP usage/template add-notification-system- OTP delivery options
