security: stop leaking the admin password length through timing (#395)

verifyAdminPassword compared the raw strings, so timingSafeEqual could
only run once the lengths already matched. The early return on a length
mismatch is observable: an attacker who can time login attempts learns
how long ADMIN_PASSWORD is, which is exactly the information that makes
a brute-force search tractable. The dummy comparison that guarded the
mismatch path did not help — it ran on Buffer.alloc(attempt.length),
which is attacker-sized and leaves the branch timing intact anyway.

HMAC both sides to a fixed 32 bytes first, then compare. Every attempt
now takes the same path regardless of length. Keyed with AUTH_SECRET
rather than a bare SHA-256 so the intermediate values are useless
without the secret, matching how lib/auth.ts already compares subpage
passwords.

MAX_PASSWORD_LENGTH caps an attempt at 1024 characters, rejected in the
route before the body reaches the hashing path and again in the library
so no caller can bypass it. 1024 is far above any real passphrase — a
cap a user could actually hit would be a lockout, not a fix.

Supersedes #390 and #388, which fixed the same comparison with an
unkeyed digest. The .jules/sentinel.md note the original branch carried
is left out: .jules/ is gitignored since cf2e8e6.

Adds 3 tests: a wrong password of exactly the right length, an
oversized attempt, and that a long configured password still logs in.

Verified: 210 unit tests passing (207 before), vitest exit 0, tsc 0
errors, production build exit 0, prettier clean.

Co-authored-by: ralksta <ralksta@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Ralksta
2026-08-05 12:13:32 +02:00
committed by GitHub
parent 0a67184335
commit 871d54fafb
3 changed files with 57 additions and 10 deletions

View File

@@ -6,6 +6,7 @@ import {
isAdminEnabled,
COOKIE_NAME,
SESSION_DURATION_MS,
MAX_PASSWORD_LENGTH,
} from '@/lib/admin/auth';
import { checkRateLimit, getClientIp, retryAfterSeconds } from '@/lib/rate-limit';
@@ -37,6 +38,11 @@ export async function POST(request: NextRequest) {
if (!body?.password || typeof body.password !== 'string') {
return NextResponse.json({ error: 'Password is required' }, { status: 400 });
}
// Reject before hashing rather than after: nothing downstream should have to
// carry an unbounded request body.
if (body.password.length > MAX_PASSWORD_LENGTH) {
return NextResponse.json({ error: 'Password is too long' }, { status: 400 });
}
if (!verifyAdminPassword(body.password)) {
return NextResponse.json({ error: 'Invalid password' }, { status: 401 });