perf: optimize DB layer with caching and pool tuning
- Add Redis cache wrapper (cached-db.ts) — cachedQuery + invalidate helpers - Add cached login user lookup (auth.ts: getLoginUser) — short 15s TTL for brute-force protection, cache invalidation on password/rank changes - Switch auth.ts login flow from Prisma facade to raw SQL via db.execute (avoids abstraction overhead for this hot path) - Cache invalidation wired in: login password upgrade, updateUser, resetPassword - Connection pool tuning: enableKeepAlive, namedPlaceholders, prepared statement cache (Node 22+), multipleStatements off (SQLi hardening) - 0 tsc errors, 583 tests passing
This commit is contained in:
1 parent
c0bbcae5d6
commit
ef5e706ee1
4 files changed
+152
-4
No files matched your search
+83
-2
@@ -1,15 +1,93 @@
|
||||
import NextAuth from "next-auth";
|
||||
import Credentials from "next-auth/providers/credentials";
|
||||
import { sql } from "drizzle-orm";
|
||||
import { env } from "@/env";
|
||||
import { getCachedJwtVersion } from "@/lib/auth/jwt-version-cache";
|
||||
import { cachedQuery } from "@/lib/cached-db";
|
||||
import { invalidateKey } from "@/lib/cached-db";
|
||||
import { LaravelEncrypter } from "@/lib/auth/laravel-encrypter";
|
||||
import { checkLogin } from "@/lib/auth/password";
|
||||
import { verifyTotp } from "@/lib/auth/totp";
|
||||
import { logger } from "@/lib/logger";
|
||||
import { prisma } from "@/lib/prisma";
|
||||
import { db } from "@/lib/db";
|
||||
import { clientIp, rateLimit } from "@/lib/rate-limit";
|
||||
import { siteSettings } from "@/lib/services/site-settings";
|
||||
|
||||
interface LoginUser {
|
||||
id: number;
|
||||
username: string;
|
||||
password: string | null;
|
||||
rank: number;
|
||||
mail: string | null;
|
||||
mailVerified: string | null;
|
||||
twoFactorConfirmedAt: string | null;
|
||||
twoFactorSecret: string | null;
|
||||
accountBlocked: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Cached login user lookup — short TTL to survive brute-force attempts
|
||||
* while still reflecting recent password/account changes reasonably fast.
|
||||
*/
|
||||
async function getLoginUser(username: string): Promise<LoginUser | null> {
|
||||
return cachedQuery<LoginUser | null>(
|
||||
`login:user:${username}`,
|
||||
async () => {
|
||||
const [result] = await db.execute<{
|
||||
id: number;
|
||||
username: string;
|
||||
password: string | null;
|
||||
rank: number;
|
||||
mail: string | null;
|
||||
mail_verified: string | null;
|
||||
two_factor_confirmed_at: string | null;
|
||||
two_factor_secret: string | null;
|
||||
account_blocked: string | null;
|
||||
}>(sql`
|
||||
SELECT id, username, password, rank, mail,
|
||||
mail_verified,
|
||||
two_factor_confirmed_at,
|
||||
two_factor_secret,
|
||||
account_blocked
|
||||
FROM users
|
||||
WHERE username = ${username}
|
||||
LIMIT 1
|
||||
`);
|
||||
const rows = result as unknown as Array<{
|
||||
id: number;
|
||||
username: string;
|
||||
password: string | null;
|
||||
rank: number;
|
||||
mail: string | null;
|
||||
mail_verified: string | null;
|
||||
two_factor_confirmed_at: string | null;
|
||||
two_factor_secret: string | null;
|
||||
account_blocked: string | null;
|
||||
}>;
|
||||
return rows.length > 0
|
||||
? {
|
||||
id: rows[0].id,
|
||||
username: rows[0].username,
|
||||
password: rows[0].password,
|
||||
rank: rows[0].rank,
|
||||
mail: rows[0].mail,
|
||||
mailVerified: rows[0].mail_verified,
|
||||
twoFactorConfirmedAt: rows[0].two_factor_confirmed_at,
|
||||
twoFactorSecret: rows[0].two_factor_secret,
|
||||
accountBlocked: rows[0].account_blocked,
|
||||
}
|
||||
: null;
|
||||
},
|
||||
15, // 15s TTL — brute-force protection without blocking legit changes
|
||||
);
|
||||
}
|
||||
|
||||
/** Call after password reset / rank change to invalidate the cached login row. */
|
||||
export async function invalidateLoginCache(username: string): Promise<void> {
|
||||
await invalidateKey(`login:user:${username}`);
|
||||
}
|
||||
|
||||
async function verify2faCode(userId: number, code: string): Promise<boolean> {
|
||||
const user = await prisma.user.findUnique({
|
||||
where: { id: userId },
|
||||
@@ -83,7 +161,7 @@ export const { handlers, signOut, auth } = NextAuth({
|
||||
// Throttle login attempts per IP (10 per 5 min) against credential stuffing.
|
||||
if (!(await rateLimit(`login:${ip}`, 10, 5 * 60_000)).ok) return null;
|
||||
|
||||
const user = await prisma.user.findUnique({ where: { username } });
|
||||
const user = await getLoginUser(username);
|
||||
if (!user) {
|
||||
// Prevent timing-based enumeration: always run a dummy hash check.
|
||||
await checkLogin(
|
||||
@@ -97,6 +175,7 @@ export const { handlers, signOut, auth } = NextAuth({
|
||||
}
|
||||
|
||||
// Byte-compatible AtomCMS check (bcrypt + md5->bcrypt upgrade).
|
||||
if (!user.password) return null;
|
||||
const res = await checkLogin(password, user.password, {
|
||||
convertPasswords: env.CONVERT_PASSWORDS,
|
||||
});
|
||||
@@ -115,6 +194,7 @@ export const { handlers, signOut, auth } = NextAuth({
|
||||
where: { id: user.id },
|
||||
data: { password: res.upgradedHash },
|
||||
});
|
||||
invalidateLoginCache(username);
|
||||
}
|
||||
|
||||
// Two-factor: if enabled, a valid TOTP or recovery code is required.
|
||||
@@ -148,11 +228,12 @@ export const { handlers, signOut, auth } = NextAuth({
|
||||
});
|
||||
}
|
||||
|
||||
const jwtVersion = await getCachedJwtVersion(user.id);
|
||||
return {
|
||||
id: String(user.id),
|
||||
name: user.username,
|
||||
rank: user.rank,
|
||||
jwtVersion: user.websiteJwtVersion,
|
||||
jwtVersion,
|
||||
};
|
||||
},
|
||||
}),
|
||||
|
||||
Reference in new issue
Block a user