Sign-in lockout with console unlock, and forgotten-password reset
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 29s

- Wrong passwords in a row are counted across every device and kept in
  the database. The first 3 are free; from the 3rd the next attempt
  waits 15 s, 30 s, 1, 2, 5, 15 and 30 minutes; the 10th locks sign-in
  until the unlock code printed to the server log (and saved to
  unlock-code.txt) is entered. Signed-in devices keep working. Only one
  password check runs at a time, so parallel guesses cannot skip a wait.
- "Forgot password?" prints a reset code to the log (reset-code.txt),
  valid once for 15 minutes. It sets a new password, signs out every
  device, lifts any lockout and signs in. Asking again while a code is
  valid prints nothing new.
- Codes are stored hashed; wrong codes count toward the per-address
  limit. RESET_ADMIN_PASSWORD also lifts a lockout.
- Sign-in page: a live countdown during a wait, an unlock step and a
  reset step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-16 15:46:16 -07:00
parent fe94dbf876
commit 917954d12d
7 changed files with 522 additions and 18 deletions

View file

@ -54,6 +54,104 @@ export function resetRateLimits(): void {
buckets.clear();
}
/* ------------------------------ sign-in lockout ------------------------------ */
/**
* Wrong passwords in a row, counted across every device and kept in the database so a restart
* does not clear them. The first three are free; from the third, each one makes the next
* attempt wait longer (seconds, by number of failures: 15 s, 30 s, 1, 2, 5, 15, 30 min); the
* tenth locks sign-in until the unlock code printed to the server console is entered. A correct password, an unlock or a password reset starts the count again.
* Devices that are already signed in are not affected.
*/
export const LOGIN_WAITS = [0, 0, 0, 15, 30, 60, 120, 300, 900, 1800];
export const LOCKOUT_AFTER = 10;
const GUARD_KEY = 'auth.guard';
const RESET_KEY = 'auth.reset_code';
const RESET_MS = 15 * 60_000;
interface Guard {
failures: number;
waitUntil: number;
locked: boolean;
/** sha256 of the unlock code while locked. */
unlockHash: string | null;
}
function readGuard(app: AppContext): Guard {
return { failures: 0, waitUntil: 0, locked: false, unlockHash: null, ...getSetting<Partial<Guard>>(app.db, GUARD_KEY, {}) };
}
function clearGuard(app: AppContext): void {
deleteSetting(app.db, GUARD_KEY);
fs.rmSync(consoleCodeFile(app, 'unlock'), { force: true });
}
/** Seconds until the next sign-in attempt is allowed (0 when it is). */
function waitLeft(guard: Guard): number {
return Math.max(0, Math.ceil((guard.waitUntil - now()) / 1000));
}
function describeWait(seconds: number): string {
return seconds < 60 ? `${seconds} second${seconds === 1 ? '' : 's'}` : `${Math.ceil(seconds / 60)} minute${seconds > 60 ? 's' : ''}`;
}
/** A one-time code shown only on the server console, like the first-run setup code: XXXXX-XXXXX. */
function newConsoleCode(): string {
return crypto.randomBytes(5).toString('hex').toUpperCase().replace(/(.{5})/, '$1-');
}
function codeHash(code: string): string {
return sha256(code.trim().toUpperCase().replace(/[\s-]/g, ''));
}
function consoleCodeFile(app: AppContext, kind: 'unlock' | 'reset'): string {
return path.join(app.config.dataDir, `${kind}-code.txt`);
}
/** Prints a console code to the server log and saves it in the data folder (readable only by the server's user). */
function announceCode(app: AppContext, kind: 'unlock' | 'reset', code: string, what: string): void {
const file = consoleCodeFile(app, kind);
try {
fs.writeFileSync(file, `${code}\n`, { mode: 0o600 });
} catch {
/* the log line below is enough */
}
app.log('warn', `${what}: ${code} (also saved to ${file})`);
}
/** Wrong password: count it, and set the next wait or lock sign-in. Returns the message for the client. */
function recordWrongPassword(app: AppContext): { message: string; retryAfter?: number; locked?: boolean; attemptsLeft: number } {
const guard = readGuard(app);
guard.failures += 1;
const attemptsLeft = Math.max(0, LOCKOUT_AFTER - guard.failures);
if (guard.failures >= LOCKOUT_AFTER) {
const code = newConsoleCode();
guard.locked = true;
guard.unlockHash = codeHash(code);
setSetting(app.db, GUARD_KEY, guard);
announceCode(app, 'unlock', code, `Sign-in locked after ${LOCKOUT_AFTER} incorrect passwords in a row. Unlock code`);
return { message: `Sign-in is locked after ${LOCKOUT_AFTER} incorrect passwords. Enter the unlock code from the server console.`, locked: true, attemptsLeft: 0 };
}
const wait = LOGIN_WAITS[guard.failures] ?? LOGIN_WAITS[LOGIN_WAITS.length - 1]!;
guard.waitUntil = now() + wait * 1000;
setSetting(app.db, GUARD_KEY, guard);
const parts = ['Incorrect password.'];
if (wait > 0) parts.push(`Wait ${describeWait(wait)} before trying again.`);
if (attemptsLeft <= 3) parts.push(`${attemptsLeft} more incorrect ${attemptsLeft === 1 ? 'attempt' : 'attempts'} will lock sign-in.`);
return { message: parts.join(' '), retryAfter: wait || undefined, attemptsLeft };
}
/** Throws when sign-in is locked or a wait is running. */
function assertGuardOpen(app: AppContext): void {
const guard = readGuard(app);
if (guard.locked) throw new HttpError(423, 'locked', `Sign-in is locked after ${LOCKOUT_AFTER} incorrect passwords. Enter the unlock code from the server console.`);
const left = waitLeft(guard);
if (left > 0) throw new HttpError(429, 'rate_limited', `Too many incorrect passwords. Try again in ${describeWait(left)}.`, { retryAfter: left });
}
/** One password check at a time per server, so parallel guesses cannot slip past a wait. */
const checking = new WeakSet<AppContext>();
/* ------------------------------ request helpers ------------------------------ */
export function clientIp(c: Context, trustProxy: boolean): string {
@ -172,6 +270,7 @@ export async function initAuth(app: AppContext): Promise<void> {
passwordSchema.parse(config.resetAdminPassword);
await storePassword(app, config.resetAdminPassword);
db.run('DELETE FROM sessions');
clearGuard(app);
app.log('warn', 'Administrator password was reset from RESET_ADMIN_PASSWORD. Remove that variable and restart.');
return;
}
@ -200,7 +299,10 @@ export async function initAuth(app: AppContext): Promise<void> {
export function authRoutes(app: AppContext): Hono {
const r = new Hono();
r.get('/status', (c) => c.json({ configured: isConfigured(app), authenticated: isAuthenticated(app, c) }));
r.get('/status', (c) => {
const guard = readGuard(app);
return c.json({ configured: isConfigured(app), authenticated: isAuthenticated(app, c), locked: guard.locked, retryAfter: guard.locked ? 0 : waitLeft(guard) });
});
r.post('/setup', async (c) => {
if (isConfigured(app)) throw new HttpError(409, 'already_configured', 'Study Desk is already set up');
@ -224,10 +326,75 @@ export function authRoutes(app: AppContext): Hono {
const body = await readBody(c, z.object({ password: z.string().max(256) }));
const hash = getSetting<string | null>(app.db, HASH_KEY, null);
if (!hash) throw new HttpError(409, 'not_configured', 'Study Desk has not been set up yet');
if (!(await verifyPassword(body.password, hash))) {
recordFailure(ip);
throw new HttpError(401, 'bad_password', 'Incorrect password');
assertGuardOpen(app);
if (checking.has(app)) throw new HttpError(429, 'rate_limited', 'Another sign-in is being checked. Try again in a moment.', { retryAfter: 1 });
checking.add(app);
let ok: boolean;
try {
ok = await verifyPassword(body.password, hash);
} finally {
checking.delete(app);
}
if (!ok) {
// Wrong passwords follow the lockout schedule alone; the per-IP limit is for wrong codes.
const wrong = recordWrongPassword(app);
if (wrong.locked) throw new HttpError(423, 'locked', wrong.message);
throw new HttpError(401, 'bad_password', wrong.message, { retryAfter: wrong.retryAfter, attemptsLeft: wrong.attemptsLeft });
}
if (readGuard(app).failures > 0) deleteSetting(app.db, GUARD_KEY);
createSession(app, c);
return c.json({ ok: true });
});
/** Lifts a lockout with the code printed to the server console. The password is still needed to sign in. */
r.post('/unlock', async (c) => {
const ip = clientIp(c, app.config.trustProxy);
assertNotLimited(ip);
const body = await readBody(c, z.object({ code: z.string().max(40) }));
const guard = readGuard(app);
if (!guard.locked) return c.json({ ok: true });
if (!guard.unlockHash || !safeEqual(codeHash(body.code), guard.unlockHash)) {
recordFailure(ip);
throw new HttpError(403, 'bad_code', 'That unlock code is not correct. Check the server console or unlock-code.txt in the data folder.');
}
clearGuard(app);
app.log('info', 'Sign-in unlocked with the console code.');
return c.json({ ok: true });
});
/**
* Forgotten password, step 1: prints a reset code to the server console (valid 15 minutes).
* While a code is still valid, asking again does not print another.
*/
r.post('/reset/request', (c) => {
if (!isConfigured(app)) throw new HttpError(409, 'not_configured', 'Study Desk has not been set up yet');
assertNotLimited(clientIp(c, app.config.trustProxy));
const current = getSetting<{ hash: string; expiresAt: number } | null>(app.db, RESET_KEY, null);
if (current && current.expiresAt > now()) return c.json({ ok: true, expiresAt: current.expiresAt });
const code = newConsoleCode();
const expiresAt = now() + RESET_MS;
setSetting(app.db, RESET_KEY, { hash: codeHash(code), expiresAt });
announceCode(app, 'reset', code, 'Password reset requested. Reset code (valid 15 minutes)');
return c.json({ ok: true, expiresAt });
});
/** Forgotten password, step 2: the console code sets a new password, signs out every device, lifts any lockout and signs in here. */
r.post('/reset', async (c) => {
const ip = clientIp(c, app.config.trustProxy);
assertNotLimited(ip);
const body = await readBody(c, z.object({ code: z.string().max(40), password: passwordSchema }));
const current = getSetting<{ hash: string; expiresAt: number } | null>(app.db, RESET_KEY, null);
if (!current || current.expiresAt <= now()) throw new HttpError(410, 'code_expired', 'That reset code has expired. Ask for a new one.');
if (!safeEqual(codeHash(body.code), current.hash)) {
recordFailure(ip);
throw new HttpError(403, 'bad_code', 'That reset code is not correct. Check the server console or reset-code.txt in the data folder.');
}
await storePassword(app, body.password);
deleteSetting(app.db, RESET_KEY);
fs.rmSync(consoleCodeFile(app, 'reset'), { force: true });
clearGuard(app);
app.db.run('DELETE FROM sessions');
app.log('warn', 'Administrator password was reset with the console code. Every device was signed out.');
createSession(app, c);
return c.json({ ok: true });
});