feat: throttle admin login attempts
This commit is contained in:
1 parent
98d610271f
commit
31b310d1b9
2 files changed
+266
-6
No files matched your search
@@ -1,5 +1,9 @@
|
|||||||
import { createAdminSessionToken } from "@/core/auth/adminSession";
|
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 { NextRequest, NextResponse } from "next/server";
|
||||||
import { createHash, timingSafeEqual } from "node:crypto";
|
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;
|
let authenticated = false;
|
||||||
if (process.env.NODE_ENV !== "production" && !process.env.DATABASE_URL) {
|
if (process.env.NODE_ENV !== "production" && !process.env.DATABASE_URL) {
|
||||||
const adminEmail = process.env.DATASTACK_ADMIN_EMAIL;
|
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 remember = body.remember === true;
|
||||||
const maxAge = remember ? REMEMBERED_SESSION_SECONDS : SESSION_SECONDS;
|
const maxAge = remember ? REMEMBERED_SESSION_SECONDS : SESSION_SECONDS;
|
||||||
const expiresAt = Date.now() + maxAge * 1000;
|
const expiresAt = Date.now() + maxAge * 1000;
|
||||||
|
|||||||
+231
-5
@@ -1,14 +1,32 @@
|
|||||||
import {
|
import {
|
||||||
createHash,
|
createHash,
|
||||||
|
createHmac,
|
||||||
randomBytes,
|
randomBytes,
|
||||||
scrypt as scryptCallback,
|
scrypt as scryptCallback,
|
||||||
timingSafeEqual,
|
timingSafeEqual,
|
||||||
} from "node:crypto";
|
} from "node:crypto";
|
||||||
import { Pool } from "pg";
|
import { Pool, type PoolClient } from "pg";
|
||||||
|
|
||||||
const PASSWORD_HASH_BYTES = 64;
|
const PASSWORD_HASH_BYTES = 64;
|
||||||
const PASSWORD_SALT_BYTES = 16;
|
const PASSWORD_SALT_BYTES = 16;
|
||||||
const DATABASE_LOCK_ID = "72025102501";
|
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 & {
|
type AdminDatabaseGlobals = typeof globalThis & {
|
||||||
__dataStackAdminPool?: Pool;
|
__dataStackAdminPool?: Pool;
|
||||||
@@ -16,6 +34,9 @@ type AdminDatabaseGlobals = typeof globalThis & {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const globals = globalThis as AdminDatabaseGlobals;
|
const globals = globalThis as AdminDatabaseGlobals;
|
||||||
|
const localLoginThrottle = new Map<string, LoginThrottleEntry>();
|
||||||
|
let lastLocalThrottleCleanup = 0;
|
||||||
|
let lastDatabaseThrottleCleanup = 0;
|
||||||
|
|
||||||
function getPool() {
|
function getPool() {
|
||||||
const connectionString = process.env.DATABASE_URL;
|
const connectionString = process.env.DATABASE_URL;
|
||||||
@@ -34,8 +55,8 @@ function getPool() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function ensureAdminTable() {
|
async function ensureAdminTable() {
|
||||||
globals.__dataStackAdminSchema ??= getPool()
|
globals.__dataStackAdminSchema ??= Promise.all([
|
||||||
.query(
|
getPool().query(
|
||||||
`
|
`
|
||||||
CREATE TABLE IF NOT EXISTS admin_users (
|
CREATE TABLE IF NOT EXISTS admin_users (
|
||||||
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
id SMALLINT PRIMARY KEY DEFAULT 1 CHECK (id = 1),
|
||||||
@@ -45,8 +66,19 @@ async function ensureAdminTable() {
|
|||||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
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 {
|
try {
|
||||||
await globals.__dataStackAdminSchema;
|
await globals.__dataStackAdminSchema;
|
||||||
@@ -71,6 +103,200 @@ function matchesSecret(candidate: string, expected: string) {
|
|||||||
return timingSafeEqual(candidateHash, expectedHash);
|
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<LoginThrottleDecision> {
|
||||||
|
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<LoginThrottleDecision> {
|
||||||
|
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) {
|
export function verifyAdminSetupKey(candidate: string) {
|
||||||
const expected = process.env.DATASTACK_ADMIN_SETUP_KEY;
|
const expected = process.env.DATASTACK_ADMIN_SETUP_KEY;
|
||||||
if (!expected || expected.length < 32) return false;
|
if (!expected || expected.length < 32) return false;
|
||||||
|
|||||||
Reference in new issue
Block a user