feat: add 6-digit code email verification to signup flow
- POST /v1/signup/free now returns verification code (temp in response) - New POST /v1/signup/verify endpoint to verify code and get API key - Codes expire after 15 minutes, max 3 attempts - Frontend updated with 2-step signup modal (email → code → key) - Legacy token verification kept for existing links
This commit is contained in:
parent
0a3f935af1
commit
f59b99203e
4 changed files with 219 additions and 59 deletions
|
|
@ -1,26 +1,28 @@
|
|||
import { Router, Request, Response } from "express";
|
||||
import rateLimit from "express-rate-limit";
|
||||
import { createFreeKey } from "../services/keys.js";
|
||||
import { createVerification, verifyToken, isEmailVerified, getVerifiedApiKey } from "../services/verification.js";
|
||||
import { createVerification, createPendingVerification, verifyCode, isEmailVerified, getVerifiedApiKey } from "../services/verification.js";
|
||||
import { sendVerificationEmail } from "../services/email.js";
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Rate limiting for signup - 5 signups per IP per hour
|
||||
const signupLimiter = rateLimit({
|
||||
windowMs: 60 * 60 * 1000,
|
||||
max: 5,
|
||||
message: {
|
||||
error: "Too many signup attempts. Please try again in 1 hour.",
|
||||
retryAfter: "1 hour"
|
||||
},
|
||||
message: { error: "Too many signup attempts. Please try again in 1 hour.", retryAfter: "1 hour" },
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
skipSuccessfulRequests: false,
|
||||
skipFailedRequests: false,
|
||||
});
|
||||
|
||||
// Self-service free API key signup — now requires email verification
|
||||
const verifyLimiter = rateLimit({
|
||||
windowMs: 15 * 60 * 1000,
|
||||
max: 15,
|
||||
message: { error: "Too many verification attempts. Please try again later." },
|
||||
standardHeaders: true,
|
||||
legacyHeaders: false,
|
||||
});
|
||||
|
||||
// Step 1: Request signup — generates 6-digit code
|
||||
router.post("/free", signupLimiter, async (req: Request, res: Response) => {
|
||||
const { email } = req.body || {};
|
||||
|
||||
|
|
@ -31,26 +33,69 @@ router.post("/free", signupLimiter, async (req: Request, res: Response) => {
|
|||
|
||||
const cleanEmail = email.trim().toLowerCase();
|
||||
|
||||
// If already verified, tell them
|
||||
if (isEmailVerified(cleanEmail)) {
|
||||
res.status(409).json({ error: "This email is already registered. Check your inbox for the original verification email, or contact support." });
|
||||
res.status(409).json({ error: "This email is already registered. Contact support if you need help." });
|
||||
return;
|
||||
}
|
||||
|
||||
// Create the API key (but don't reveal it yet)
|
||||
const keyInfo = createFreeKey(cleanEmail);
|
||||
const pending = createPendingVerification(cleanEmail);
|
||||
|
||||
// Create verification record
|
||||
const verification = createVerification(cleanEmail, keyInfo.key);
|
||||
|
||||
// Send verification email
|
||||
await sendVerificationEmail(cleanEmail, verification.token);
|
||||
// TODO: Send code via email once SMTP is configured
|
||||
// For now, return code in response for testing
|
||||
console.log(`📧 Verification code for ${cleanEmail}: ${pending.code}`);
|
||||
|
||||
res.json({
|
||||
message: "Check your email for a verification link to get your API key.",
|
||||
status: "verification_required",
|
||||
message: "Check your email for a verification code",
|
||||
email: cleanEmail,
|
||||
verified: false,
|
||||
code: pending.code, // TEMP: remove once email infra is live
|
||||
});
|
||||
});
|
||||
|
||||
// Step 2: Verify code — creates API key
|
||||
router.post("/verify", verifyLimiter, (req: Request, res: Response) => {
|
||||
const { email, code } = req.body || {};
|
||||
|
||||
if (!email || !code) {
|
||||
res.status(400).json({ error: "Email and code are required." });
|
||||
return;
|
||||
}
|
||||
|
||||
const cleanEmail = email.trim().toLowerCase();
|
||||
const cleanCode = String(code).trim();
|
||||
|
||||
if (isEmailVerified(cleanEmail)) {
|
||||
res.status(409).json({ error: "This email is already verified." });
|
||||
return;
|
||||
}
|
||||
|
||||
const result = verifyCode(cleanEmail, cleanCode);
|
||||
|
||||
switch (result.status) {
|
||||
case "ok": {
|
||||
const keyInfo = createFreeKey(cleanEmail);
|
||||
// Mark as verified via legacy system too
|
||||
const verification = createVerification(cleanEmail, keyInfo.key);
|
||||
verification.verifiedAt = new Date().toISOString();
|
||||
|
||||
res.json({
|
||||
status: "verified",
|
||||
message: "Email verified! Here's your API key.",
|
||||
apiKey: keyInfo.key,
|
||||
tier: keyInfo.tier,
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "expired":
|
||||
res.status(410).json({ error: "Verification code has expired. Please sign up again." });
|
||||
break;
|
||||
case "max_attempts":
|
||||
res.status(429).json({ error: "Too many failed attempts. Please sign up again to get a new code." });
|
||||
break;
|
||||
case "invalid":
|
||||
res.status(400).json({ error: "Invalid verification code." });
|
||||
break;
|
||||
}
|
||||
});
|
||||
|
||||
export { router as signupRouter };
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { randomBytes } from "crypto";
|
||||
import { existsSync, mkdirSync } from "fs";
|
||||
import { randomBytes, randomInt } from "crypto";
|
||||
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
|
||||
|
|
@ -7,9 +7,6 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|||
const DATA_DIR = path.join(__dirname, "../../data");
|
||||
const DB_PATH = path.join(DATA_DIR, "verifications.json");
|
||||
|
||||
// Simple JSON-based store (no SQLite dependency needed)
|
||||
import { readFileSync, writeFileSync } from "fs";
|
||||
|
||||
export interface Verification {
|
||||
email: string;
|
||||
token: string;
|
||||
|
|
@ -18,50 +15,60 @@ export interface Verification {
|
|||
verifiedAt: string | null;
|
||||
}
|
||||
|
||||
export interface PendingVerification {
|
||||
email: string;
|
||||
code: string;
|
||||
createdAt: string;
|
||||
expiresAt: string;
|
||||
attempts: number;
|
||||
}
|
||||
|
||||
let verifications: Verification[] = [];
|
||||
let pendingVerifications: PendingVerification[] = [];
|
||||
|
||||
function ensureDataDir(): void {
|
||||
if (!existsSync(DATA_DIR)) {
|
||||
mkdirSync(DATA_DIR, { recursive: true });
|
||||
}
|
||||
if (!existsSync(DATA_DIR)) mkdirSync(DATA_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function load(): void {
|
||||
ensureDataDir();
|
||||
if (existsSync(DB_PATH)) {
|
||||
try {
|
||||
verifications = JSON.parse(readFileSync(DB_PATH, "utf-8"));
|
||||
const data = JSON.parse(readFileSync(DB_PATH, "utf-8"));
|
||||
// Support both old format (array) and new format (object)
|
||||
if (Array.isArray(data)) {
|
||||
verifications = data;
|
||||
pendingVerifications = [];
|
||||
} else {
|
||||
verifications = data.verifications || [];
|
||||
pendingVerifications = data.pendingVerifications || [];
|
||||
}
|
||||
} catch {
|
||||
verifications = [];
|
||||
pendingVerifications = [];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function save(): void {
|
||||
ensureDataDir();
|
||||
writeFileSync(DB_PATH, JSON.stringify(verifications, null, 2));
|
||||
writeFileSync(DB_PATH, JSON.stringify({ verifications, pendingVerifications }, null, 2));
|
||||
}
|
||||
|
||||
// Initialize on import
|
||||
load();
|
||||
|
||||
const TOKEN_EXPIRY_MS = 24 * 60 * 60 * 1000; // 24 hours
|
||||
const TOKEN_EXPIRY_MS = 24 * 60 * 60 * 1000;
|
||||
const CODE_EXPIRY_MS = 15 * 60 * 1000; // 15 minutes
|
||||
const MAX_ATTEMPTS = 3;
|
||||
|
||||
// Legacy token-based verification (keep for existing links)
|
||||
export function createVerification(email: string, apiKey: string): Verification {
|
||||
// Check for existing pending verification for this email
|
||||
const existing = verifications.find(
|
||||
(v) => v.email === email && !v.verifiedAt
|
||||
);
|
||||
const existing = verifications.find(v => v.email === email && !v.verifiedAt);
|
||||
if (existing) {
|
||||
// Check if expired
|
||||
const age = Date.now() - new Date(existing.createdAt).getTime();
|
||||
if (age < TOKEN_EXPIRY_MS) {
|
||||
return existing; // Return existing pending verification
|
||||
}
|
||||
// Expired — remove it
|
||||
verifications = verifications.filter((v) => v !== existing);
|
||||
if (age < TOKEN_EXPIRY_MS) return existing;
|
||||
verifications = verifications.filter(v => v !== existing);
|
||||
}
|
||||
|
||||
const verification: Verification = {
|
||||
email,
|
||||
token: randomBytes(32).toString("hex"),
|
||||
|
|
@ -75,24 +82,70 @@ export function createVerification(email: string, apiKey: string): Verification
|
|||
}
|
||||
|
||||
export function verifyToken(token: string): { status: "ok"; verification: Verification } | { status: "invalid" | "expired" | "already_verified"; verification?: Verification } {
|
||||
const v = verifications.find((v) => v.token === token);
|
||||
const v = verifications.find(v => v.token === token);
|
||||
if (!v) return { status: "invalid" };
|
||||
|
||||
if (v.verifiedAt) return { status: "already_verified", verification: v };
|
||||
|
||||
const age = Date.now() - new Date(v.createdAt).getTime();
|
||||
if (age > TOKEN_EXPIRY_MS) return { status: "expired" };
|
||||
|
||||
v.verifiedAt = new Date().toISOString();
|
||||
save();
|
||||
return { status: "ok", verification: v };
|
||||
}
|
||||
|
||||
// New 6-digit code verification
|
||||
export function createPendingVerification(email: string): PendingVerification {
|
||||
// Remove any existing pending for this email
|
||||
pendingVerifications = pendingVerifications.filter(p => p.email !== email);
|
||||
|
||||
const now = new Date();
|
||||
const pending: PendingVerification = {
|
||||
email,
|
||||
code: String(randomInt(100000, 999999)),
|
||||
createdAt: now.toISOString(),
|
||||
expiresAt: new Date(now.getTime() + CODE_EXPIRY_MS).toISOString(),
|
||||
attempts: 0,
|
||||
};
|
||||
pendingVerifications.push(pending);
|
||||
save();
|
||||
return pending;
|
||||
}
|
||||
|
||||
export function verifyCode(email: string, code: string): { status: "ok" | "invalid" | "expired" | "max_attempts" } {
|
||||
const cleanEmail = email.trim().toLowerCase();
|
||||
const pending = pendingVerifications.find(p => p.email === cleanEmail);
|
||||
|
||||
if (!pending) return { status: "invalid" };
|
||||
|
||||
if (new Date() > new Date(pending.expiresAt)) {
|
||||
pendingVerifications = pendingVerifications.filter(p => p !== pending);
|
||||
save();
|
||||
return { status: "expired" };
|
||||
}
|
||||
|
||||
if (pending.attempts >= MAX_ATTEMPTS) {
|
||||
pendingVerifications = pendingVerifications.filter(p => p !== pending);
|
||||
save();
|
||||
return { status: "max_attempts" };
|
||||
}
|
||||
|
||||
pending.attempts++;
|
||||
|
||||
if (pending.code !== code) {
|
||||
save();
|
||||
return { status: "invalid" };
|
||||
}
|
||||
|
||||
// Success - remove pending
|
||||
pendingVerifications = pendingVerifications.filter(p => p !== pending);
|
||||
save();
|
||||
return { status: "ok" };
|
||||
}
|
||||
|
||||
export function isEmailVerified(email: string): boolean {
|
||||
return verifications.some((v) => v.email === email && v.verifiedAt !== null);
|
||||
return verifications.some(v => v.email === email && v.verifiedAt !== null);
|
||||
}
|
||||
|
||||
export function getVerifiedApiKey(email: string): string | null {
|
||||
const v = verifications.find((v) => v.email === email && v.verifiedAt !== null);
|
||||
const v = verifications.find(v => v.email === email && v.verifiedAt !== null);
|
||||
return v?.apiKey ?? null;
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue