diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.ts index e1666d2..c9210e3 100644 --- a/app/api/auth/login/route.ts +++ b/app/api/auth/login/route.ts @@ -1,5 +1,9 @@ import { createAdminSessionToken } from "@/core/auth/adminSession"; -import { verifyAdminCredentials } from "@/core/auth/adminUsers"; +import { + clearAdminLoginAttempts, + consumeAdminLoginAttempt, + verifyAdminCredentials, +} from "@/core/auth/adminUsers"; import { NextRequest, NextResponse } from "next/server"; import { createHash, timingSafeEqual } from "node:crypto"; @@ -37,6 +41,27 @@ export async function POST(request: NextRequest) { ); } + let throttleDecision; + try { + throttleDecision = await consumeAdminLoginAttempt(email, sessionSecret); + } catch { + return NextResponse.json( + { error: "Admin authentication is temporarily unavailable." }, + { status: 503 }, + ); + } + if (!throttleDecision.allowed) { + return NextResponse.json( + { error: "Too many sign-in attempts. Try again later." }, + { + status: 429, + headers: { + "Retry-After": String(throttleDecision.retryAfterSeconds), + }, + }, + ); + } + let authenticated = false; if (process.env.NODE_ENV !== "production" && !process.env.DATABASE_URL) { const adminEmail = process.env.DATASTACK_ADMIN_EMAIL; @@ -65,6 +90,15 @@ export async function POST(request: NextRequest) { ); } + try { + await clearAdminLoginAttempts(email, sessionSecret); + } catch { + return NextResponse.json( + { error: "Admin authentication is temporarily unavailable." }, + { status: 503 }, + ); + } + const remember = body.remember === true; const maxAge = remember ? REMEMBERED_SESSION_SECONDS : SESSION_SECONDS; const expiresAt = Date.now() + maxAge * 1000; diff --git a/core/auth/adminUsers.ts b/core/auth/adminUsers.ts index a644e23..ac635a0 100644 --- a/core/auth/adminUsers.ts +++ b/core/auth/adminUsers.ts @@ -1,14 +1,32 @@ import { createHash, + createHmac, randomBytes, scrypt as scryptCallback, timingSafeEqual, } from "node:crypto"; -import { Pool } from "pg"; +import { Pool, type PoolClient } from "pg"; const PASSWORD_HASH_BYTES = 64; const PASSWORD_SALT_BYTES = 16; const DATABASE_LOCK_ID = "72025102501"; +const LOGIN_ATTEMPT_LIMIT = 5; +const LOGIN_WINDOW_MS = 15 * 60 * 1000; +const LOGIN_BLOCK_MS = 15 * 60 * 1000; +const LOCAL_THROTTLE_MAX_ENTRIES = 5000; +const LOCAL_THROTTLE_CLEANUP_MS = 60 * 1000; + +interface LoginThrottleEntry { + windowStartedAt: number; + failedAttempts: number; + blockedUntil: number; + updatedAt: number; +} + +interface LoginThrottleDecision { + allowed: boolean; + retryAfterSeconds: number; +} type AdminDatabaseGlobals = typeof globalThis & { __dataStackAdminPool?: Pool; @@ -16,6 +34,9 @@ type AdminDatabaseGlobals = typeof globalThis & { }; const globals = globalThis as AdminDatabaseGlobals; +const localLoginThrottle = new Map(); +let lastLocalThrottleCleanup = 0; +let lastDatabaseThrottleCleanup = 0; function getPool() { const connectionString = process.env.DATABASE_URL; @@ -34,8 +55,8 @@ function getPool() { } async function ensureAdminTable() { - globals.__dataStackAdminSchema ??= getPool() - .query( + globals.__dataStackAdminSchema ??= Promise.all([ + getPool().query( ` CREATE TABLE IF NOT EXISTS admin_users ( id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1), @@ -45,8 +66,19 @@ async function ensureAdminTable() { created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ) `, - ) - .then(() => undefined); + ), + getPool().query( + ` + CREATE TABLE IF NOT EXISTS admin_login_attempts ( + key_hash TEXT PRIMARY KEY, + window_started_at TIMESTAMPTZ NOT NULL, + failed_attempts INTEGER NOT NULL, + blocked_until TIMESTAMPTZ, + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ) + `, + ), + ]).then(() => undefined); try { await globals.__dataStackAdminSchema; @@ -71,6 +103,200 @@ function matchesSecret(candidate: string, expected: string) { return timingSafeEqual(candidateHash, expectedHash); } +function createLoginThrottleKeys(email: string, secret: string) { + return [createHmac("sha256", secret).update(`email:${email}`).digest("hex")]; +} + +function getAdvisoryLockId(keyHash: string) { + return BigInt.asIntN(64, BigInt(`0x${keyHash.slice(0, 16)}`)).toString(); +} + +async function lockLoginThrottleKeys(client: PoolClient, keyHashes: string[]) { + const lockIds = [...new Set(keyHashes.map(getAdvisoryLockId))].sort( + (left, right) => (BigInt(left) < BigInt(right) ? -1 : 1), + ); + + for (const lockId of lockIds) { + await client.query("SELECT pg_advisory_xact_lock($1::bigint)", [lockId]); + } +} + +function cleanupLocalLoginThrottle(now: number) { + if (now - lastLocalThrottleCleanup < LOCAL_THROTTLE_CLEANUP_MS) return; + lastLocalThrottleCleanup = now; + + for (const [keyHash, entry] of localLoginThrottle) { + if (now - entry.updatedAt >= LOGIN_WINDOW_MS + LOGIN_BLOCK_MS) { + localLoginThrottle.delete(keyHash); + } + } + + while (localLoginThrottle.size > LOCAL_THROTTLE_MAX_ENTRIES) { + const oldestKey = localLoginThrottle.keys().next().value; + if (!oldestKey) break; + localLoginThrottle.delete(oldestKey); + } +} + +function consumeLocalLoginAttempt( + keyHashes: string[], + now: number, +): LoginThrottleDecision { + cleanupLocalLoginThrottle(now); + + const blockedUntil = keyHashes.reduce( + (latest, keyHash) => + Math.max(latest, localLoginThrottle.get(keyHash)?.blockedUntil ?? 0), + 0, + ); + if (blockedUntil > now) { + return { + allowed: false, + retryAfterSeconds: Math.max(1, Math.ceil((blockedUntil - now) / 1000)), + }; + } + + for (const keyHash of keyHashes) { + const previous = localLoginThrottle.get(keyHash); + const windowExpired = + !previous || now - previous.windowStartedAt >= LOGIN_WINDOW_MS; + const failedAttempts = windowExpired ? 1 : previous.failedAttempts + 1; + localLoginThrottle.set(keyHash, { + windowStartedAt: windowExpired ? now : previous.windowStartedAt, + failedAttempts, + blockedUntil: + failedAttempts >= LOGIN_ATTEMPT_LIMIT ? now + LOGIN_BLOCK_MS : 0, + updatedAt: now, + }); + } + + return { allowed: true, retryAfterSeconds: 0 }; +} + +async function consumeDatabaseLoginAttempt( + keyHashes: string[], + now: number, +): Promise { + await ensureAdminTable(); + const client = await getPool().connect(); + + try { + await client.query("BEGIN"); + await lockLoginThrottleKeys(client, keyHashes); + const result = await client.query( + `SELECT key_hash, window_started_at, failed_attempts, blocked_until + FROM admin_login_attempts + WHERE key_hash = ANY($1::text[]) + FOR UPDATE`, + [keyHashes], + ); + + const entries = new Map( + result.rows.map((row) => [row.key_hash as string, row]), + ); + const blockedUntil = result.rows.reduce((latest, row) => { + const timestamp = row.blocked_until + ? new Date(row.blocked_until as string | Date).getTime() + : 0; + return Math.max(latest, timestamp); + }, 0); + + if (blockedUntil > now) { + await client.query("COMMIT"); + return { + allowed: false, + retryAfterSeconds: Math.max(1, Math.ceil((blockedUntil - now) / 1000)), + }; + } + + for (const keyHash of keyHashes) { + const previous = entries.get(keyHash); + const windowStartedAt = previous + ? new Date(previous.window_started_at as string | Date).getTime() + : 0; + const windowExpired = + !previous || now - windowStartedAt >= LOGIN_WINDOW_MS; + const failedAttempts = windowExpired + ? 1 + : Number(previous.failed_attempts) + 1; + const nextWindowStartedAt = windowExpired + ? new Date(now) + : new Date(windowStartedAt); + const nextBlockedUntil = + failedAttempts >= LOGIN_ATTEMPT_LIMIT + ? new Date(now + LOGIN_BLOCK_MS) + : null; + + await client.query( + `INSERT INTO admin_login_attempts + (key_hash, window_started_at, failed_attempts, blocked_until, updated_at) + VALUES ($1, $2, $3, $4, NOW()) + ON CONFLICT (key_hash) DO UPDATE SET + window_started_at = EXCLUDED.window_started_at, + failed_attempts = EXCLUDED.failed_attempts, + blocked_until = EXCLUDED.blocked_until, + updated_at = NOW()`, + [keyHash, nextWindowStartedAt, failedAttempts, nextBlockedUntil], + ); + } + + if (now - lastDatabaseThrottleCleanup >= LOCAL_THROTTLE_CLEANUP_MS) { + await client.query( + "DELETE FROM admin_login_attempts WHERE updated_at < NOW() - INTERVAL '24 hours'", + ); + lastDatabaseThrottleCleanup = now; + } + + await client.query("COMMIT"); + return { allowed: true, retryAfterSeconds: 0 }; + } catch (error) { + await client.query("ROLLBACK").catch(() => undefined); + throw error; + } finally { + client.release(); + } +} + +export async function consumeAdminLoginAttempt( + email: string, + secret: string, +): Promise { + const keyHashes = createLoginThrottleKeys(email, secret); + const now = Date.now(); + + if (!process.env.DATABASE_URL) { + return consumeLocalLoginAttempt(keyHashes, now); + } + + return consumeDatabaseLoginAttempt(keyHashes, now); +} + +export async function clearAdminLoginAttempts(email: string, secret: string) { + const keyHashes = createLoginThrottleKeys(email, secret); + + if (!process.env.DATABASE_URL) { + keyHashes.forEach((keyHash) => localLoginThrottle.delete(keyHash)); + return; + } + + await ensureAdminTable(); + const client = await getPool().connect(); + try { + await client.query("BEGIN"); + await lockLoginThrottleKeys(client, keyHashes); + await client.query( + "DELETE FROM admin_login_attempts WHERE key_hash = ANY($1::text[])", + [keyHashes], + ); + await client.query("COMMIT"); + } catch (error) { + await client.query("ROLLBACK").catch(() => undefined); + throw error; + } finally { + client.release(); + } +} + export function verifyAdminSetupKey(candidate: string) { const expected = process.env.DATASTACK_ADMIN_SETUP_KEY; if (!expected || expected.length < 32) return false;