refactor: extract shared login credential verification into auth/login-core
CI / check (push) Successful in 35s
CI / release (push) Skipped
CI / deploy (push) Successful in 58s

The username normalization, dummy-hash constant, password check and
email-verification gate were duplicated between precheckLogin and the
NextAuth credentials authorize handler. Move them into a single
login-core module so both paths share one source of truth and stay
consistent.
This commit is contained in:
openhands committed 2026-08-27 15:17:54 +02:00
1 parent e3ed37d170
commit 89c1751e79
4 files changed
+187 -174

No files matched your search

+122
View File
@@ -0,0 +1,122 @@
import { sql } from "drizzle-orm";
import { env } from "@/env";
import { checkLogin } from "@/lib/auth/password";
import { cachedQuery, invalidateKey } from "@/lib/cached-db";
import { db } from "@/lib/db";
import { siteSettings } from "@/lib/services/site-settings";
export interface LoginUser {
id: number;
username: string;
password: string | null;
rank: number;
mail: string | null;
mailVerified: string | null;
twoFactorConfirmedAt: string | null;
twoFactorSecret: string | null;
}
/**
* Fixed dummy bcrypt hash used to keep timing roughly constant when a username
* does not exist, so attackers can't enumerate accounts by response time.
*/
const DUMMY_BCRYPT_HASH =
"$2y$12$abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZabcd";
/**
* Normalize credentials exactly like the registration flow hashes them, so
* accounts with accented/non-ASCII usernames or passwords verify correctly.
*/
export function normalizeLoginInput(username: unknown, password: unknown) {
return {
username: String(username ?? "")
.normalize("NFC")
.trim(),
password: String(password ?? "").normalize("NFC"),
};
}
/**
* Cached login user lookup — short TTL to survive brute-force attempts
* while still reflecting recent password/account changes reasonably fast.
*/
export 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;
}>(sql`
SELECT id, username, password, rank, mail,
mail_verified,
two_factor_confirmed_at,
two_factor_secret
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;
}>;
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,
}
: 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}`);
}
/** Runs a dummy hash check so missing-user responses stay timing-constant. */
export async function runDummyHashCheck(password: string): Promise<void> {
await checkLogin(password, DUMMY_BCRYPT_HASH, { convertPasswords: false });
}
/** Verifies the password against the stored hash and reports a possible upgrade. */
export async function verifyLoginPassword(
user: LoginUser,
password: string,
): Promise<{ valid: boolean; upgradedHash?: string }> {
if (!user.password) return { valid: false };
return checkLogin(password, user.password, {
convertPasswords: env.CONVERT_PASSWORDS,
});
}
/** True when email verification is required but this account hasn't verified yet. */
export async function isEmailUnverified(user: LoginUser): Promise<boolean> {
return (
(await siteSettings.getBool("require_email_verification", false)) &&
!!user.mail &&
user.mailVerified !== "1"
);
}