deckhearth/pages/api/auth/login.js

60 lines
1.7 KiB
JavaScript
Raw Normal View History

import bcrypt from 'bcryptjs';
import { sql } from '@vercel/postgres';
import { generateToken } from '../auth-utils.js';
fix(auth): tighten public auth surface — CORS + rate limit (Brief 4 of fix-auth-bypass) Adds rate limiting to /api/auth/login and /api/auth/register and removes their wide-open CORS allowlist. Rate limiting (@upstash/ratelimit + @upstash/redis): - 5 attempts per 15-minute sliding window per IP, prefix "tcgvault:auth" - new lib/rate-limit.js, lazy singleton, single source of truth - reads KV_REST_API_URL / KV_REST_API_TOKEN (Vercel Upstash Marketplace convention — auto-provisioned, no manual env-var setup needed) - fail-closed in production if env vars are missing (better to error one login than silently disable brute-force protection on live) - fail-open in dev/test if env vars are missing (single console.warn) - fail-open on Upstash backend outage (defense-in-depth — don't lock the entire userbase out if Upstash is down) - IP extracted from x-forwarded-for first hop, with socket fallback; NOT req.body.email (rotates) or Authorization header (absent on unauthenticated login) CORS: - Removed Access-Control-Allow-Origin: * + companion headers + OPTIONS preflight from login.js and register.js - These are first-party endpoints called from the same-origin SPA; the "*" allowlist was a development convenience that shipped to prod - verify.js is OUT OF SCOPE per architect's "cors-tighten" deferral (see convoy plan § Architect's calls) Other handler ordering preserved verbatim per brief: method gate first, then rate-limit check (returns 429 with Retry-After header), then the existing try/catch + body parsing + DB work. Pre-merge requirements: KV_REST_API_URL + KV_REST_API_TOKEN must be set in Vercel Production (already done — Upstash marketplace integration auto-provisioned both, confirmed by maintainer 2026-05-23). Convoy: fix-auth-bypass / Brief 4 Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 11:51:33 -04:00
import { checkAuthRateLimit } from '../../../lib/rate-limit.js';
export default async function handler(req, res) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
fix(auth): tighten public auth surface — CORS + rate limit (Brief 4 of fix-auth-bypass) Adds rate limiting to /api/auth/login and /api/auth/register and removes their wide-open CORS allowlist. Rate limiting (@upstash/ratelimit + @upstash/redis): - 5 attempts per 15-minute sliding window per IP, prefix "tcgvault:auth" - new lib/rate-limit.js, lazy singleton, single source of truth - reads KV_REST_API_URL / KV_REST_API_TOKEN (Vercel Upstash Marketplace convention — auto-provisioned, no manual env-var setup needed) - fail-closed in production if env vars are missing (better to error one login than silently disable brute-force protection on live) - fail-open in dev/test if env vars are missing (single console.warn) - fail-open on Upstash backend outage (defense-in-depth — don't lock the entire userbase out if Upstash is down) - IP extracted from x-forwarded-for first hop, with socket fallback; NOT req.body.email (rotates) or Authorization header (absent on unauthenticated login) CORS: - Removed Access-Control-Allow-Origin: * + companion headers + OPTIONS preflight from login.js and register.js - These are first-party endpoints called from the same-origin SPA; the "*" allowlist was a development convenience that shipped to prod - verify.js is OUT OF SCOPE per architect's "cors-tighten" deferral (see convoy plan § Architect's calls) Other handler ordering preserved verbatim per brief: method gate first, then rate-limit check (returns 429 with Retry-After header), then the existing try/catch + body parsing + DB work. Pre-merge requirements: KV_REST_API_URL + KV_REST_API_TOKEN must be set in Vercel Production (already done — Upstash marketplace integration auto-provisioned both, confirmed by maintainer 2026-05-23). Convoy: fix-auth-bypass / Brief 4 Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-23 11:51:33 -04:00
const { allowed, reset } = await checkAuthRateLimit(req);
if (!allowed) {
res.setHeader('Retry-After', Math.ceil((reset - Date.now()) / 1000));
return res.status(429).json({ error: 'Too many attempts. Try again later.' });
}
try {
const { email, password } = req.body;
if (!email || !password) {
return res.status(400).json({ error: 'Email and password are required' });
}
// Get user from database
const result = await sql`
SELECT id, email, password, role, created_at
FROM users
WHERE email = ${email}
`;
if (result.rows.length === 0) {
return res.status(401).json({ error: 'Invalid credentials' });
}
const user = result.rows[0];
// Verify password
const isValidPassword = await bcrypt.compare(password, user.password);
if (!isValidPassword) {
return res.status(401).json({ error: 'Invalid credentials' });
}
// Generate JWT token
const token = generateToken({ id: user.id, email: user.email, role: user.role });
// Return user data (without password) and token
const { password: _, ...userWithoutPassword } = user;
res.status(200).json({
success: true,
user: userWithoutPassword,
token
});
} catch (error) {
console.error('Login error:', error);
res.status(500).json({ error: 'Internal server error' });
}
}