import fs from 'node:fs'; import path from 'node:path'; import crypto from 'node:crypto'; import { Hono, type Context, type MiddlewareHandler } from 'hono'; import { deleteCookie, getCookie, setCookie } from 'hono/cookie'; import { getConnInfo } from '@hono/node-server/conninfo'; import { z } from 'zod'; import { hashPassword, safeEqual, verifyPassword } from './crypto.ts'; import { HttpError, readBody, type AppContext } from './http.ts'; import { deleteSetting, getSetting, setSetting } from './settings.ts'; import { newToken, now, sha256 } from './util.ts'; const COOKIE = 'sd_session'; const SESSION_MS = 30 * 86_400_000; const PASSWORD_MIN = 8; const passwordSchema = z.string().min(PASSWORD_MIN, `Use at least ${PASSWORD_MIN} characters`).max(256); /* ------------------------------ rate limiting ------------------------------ */ interface Bucket { failures: number[]; } const WINDOW_MS = 15 * 60_000; const MAX_PER_IP = 8; const MAX_GLOBAL = 40; const buckets = new Map(); function recent(key: string, at: number): number[] { const bucket = buckets.get(key) ?? { failures: [] }; bucket.failures = bucket.failures.filter((t) => at - t < WINDOW_MS); buckets.set(key, bucket); return bucket.failures; } function assertNotLimited(ip: string): void { const at = now(); const mine = recent(`ip:${ip}`, at); const all = recent('global', at); if (mine.length >= MAX_PER_IP || all.length >= MAX_GLOBAL) { const oldest = (mine.length >= MAX_PER_IP ? mine : all)[0]; const retry = Math.max(1, Math.ceil((oldest + WINDOW_MS - at) / 1000)); throw new HttpError(429, 'rate_limited', `Too many attempts. Try again in ${Math.ceil(retry / 60)} minute${retry > 60 ? 's' : ''}.`, { retryAfter: retry }); } } function recordFailure(ip: string): void { const at = now(); recent(`ip:${ip}`, at).push(at); recent('global', at).push(at); } 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>(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(); /* ------------------------------ request helpers ------------------------------ */ export function clientIp(c: Context, trustProxy: boolean): string { if (trustProxy) { const fwd = c.req.header('x-forwarded-for'); if (fwd) return fwd.split(',')[0].trim(); const real = c.req.header('x-real-ip'); if (real) return real.trim(); } try { return getConnInfo(c).remote.address ?? 'unknown'; } catch { return 'unknown'; } } export function isHttps(c: Context, trustProxy: boolean): boolean { if (trustProxy) { const proto = c.req.header('x-forwarded-proto'); if (proto) return proto.split(',')[0].trim() === 'https'; } return new URL(c.req.url).protocol === 'https:'; } /* ------------------------------ sessions ------------------------------ */ function createSession(app: AppContext, c: Context): void { const token = newToken(); const at = now(); app.db.run( 'INSERT INTO sessions (token_hash, created_at, expires_at, last_seen_at, user_agent, ip) VALUES (?, ?, ?, ?, ?, ?)', sha256(token), at, at + SESSION_MS, at, (c.req.header('user-agent') ?? '').slice(0, 300), clientIp(c, app.config.trustProxy), ); app.db.run('DELETE FROM sessions WHERE expires_at < ?', at); const secure = app.config.cookieSecure === 'auto' ? isHttps(c, app.config.trustProxy) : app.config.cookieSecure; setCookie(c, COOKIE, token, { httpOnly: true, sameSite: 'Lax', secure, path: '/', maxAge: Math.floor(SESSION_MS / 1000) }); } /** The stored hash of this request's session token, or null when there is no session cookie. */ export function sessionHash(c: Context): string | null { const token = getCookie(c, COOKIE); return token ? sha256(token) : null; } export function isAuthenticated(app: AppContext, c: Context): boolean { const token = getCookie(c, COOKIE); if (!token) return false; const hash = sha256(token); const at = now(); const row = app.db.get<{ expires_at: number; last_seen_at: number }>('SELECT expires_at, last_seen_at FROM sessions WHERE token_hash = ?', hash); if (!row || row.expires_at < at) return false; // Sliding expiry, written at most once an hour. if (at - row.last_seen_at > 3_600_000) { app.db.run('UPDATE sessions SET last_seen_at = ?, expires_at = ? WHERE token_hash = ?', at, at + SESSION_MS, hash); } return true; } export function requireAuth(app: AppContext): MiddlewareHandler { return async (c, next) => { if (!isAuthenticated(app, c)) throw new HttpError(401, 'unauthorized', 'Sign in to continue'); await next(); }; } /** * CSRF defence for cookie-authenticated requests: state-changing calls must carry a custom * header (which a cross-site form cannot send, and which forces a CORS preflight that this * server never approves), and must not be flagged cross-site by the browser. */ export function csrfGuard(): MiddlewareHandler { return async (c, next) => { const method = c.req.method; if (method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS') { if (c.req.header('x-requested-with') !== 'studydesk') throw new HttpError(403, 'csrf', 'Missing request header'); // Fetch metadata is set by the browser and cannot be forged by page script. Using it // (rather than comparing Origin to Host) keeps this working behind proxies that rewrite Host. if (c.req.header('sec-fetch-site') === 'cross-site') throw new HttpError(403, 'csrf', 'Cross-site request blocked'); } await next(); }; } /* ------------------------------ password storage ------------------------------ */ const HASH_KEY = 'auth.password_hash'; const SETUP_KEY = 'auth.setup_code'; export function isConfigured(app: AppContext): boolean { return Boolean(getSetting(app.db, HASH_KEY, null)); } function setupCodeFile(app: AppContext): string { return path.join(app.config.dataDir, 'setup-code.txt'); } async function storePassword(app: AppContext, password: string): Promise { setSetting(app.db, HASH_KEY, await hashPassword(password)); deleteSetting(app.db, SETUP_KEY); fs.rmSync(setupCodeFile(app), { force: true }); } /** * Runs at startup. Applies ADMIN_PASSWORD / RESET_ADMIN_PASSWORD, or prepares a one-time * setup code (printed to the log and written to the data folder) so that only someone with * access to the server can claim a fresh install. */ export async function initAuth(app: AppContext): Promise { const { config, db } = app; if (config.resetAdminPassword) { 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; } if (isConfigured(app)) return; if (config.adminPassword) { passwordSchema.parse(config.adminPassword); await storePassword(app, config.adminPassword); app.log('info', 'Administrator password initialised from ADMIN_PASSWORD.'); return; } let code = getSetting(db, SETUP_KEY, null); if (!code) { code = crypto.randomBytes(5).toString('hex').toUpperCase().replace(/(.{5})/, '$1-'); setSetting(db, SETUP_KEY, code); } try { fs.writeFileSync(setupCodeFile(app), `${code}\n`, { mode: 0o600 }); } catch { /* the log line below is enough */ } app.log('info', `First-run setup code: ${code} (also saved to ${setupCodeFile(app)})`); } /* ------------------------------ routes ------------------------------ */ export function authRoutes(app: AppContext): Hono { const r = new Hono(); 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'); const ip = clientIp(c, app.config.trustProxy); assertNotLimited(ip); const body = await readBody(c, z.object({ code: z.string().max(40), password: passwordSchema })); const expected = getSetting(app.db, SETUP_KEY, null); const given = body.code.trim().toUpperCase(); if (!expected || !(safeEqual(given, expected) || safeEqual(given, expected.replace('-', '')))) { recordFailure(ip); throw new HttpError(403, 'bad_setup_code', 'That setup code is not correct. Check the server log or setup-code.txt in the data folder.'); } await storePassword(app, body.password); createSession(app, c); return c.json({ ok: true }); }); r.post('/login', async (c) => { const ip = clientIp(c, app.config.trustProxy); assertNotLimited(ip); const body = await readBody(c, z.object({ password: z.string().max(256) })); const hash = getSetting(app.db, HASH_KEY, null); if (!hash) throw new HttpError(409, 'not_configured', 'Study Desk has not been set up yet'); 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 }); }); r.post('/logout', (c) => { const token = getCookie(c, COOKIE); if (token) app.db.run('DELETE FROM sessions WHERE token_hash = ?', sha256(token)); deleteCookie(c, COOKIE, { path: '/' }); return c.json({ ok: true }); }); r.post('/password', requireAuth(app), async (c) => { const ip = clientIp(c, app.config.trustProxy); assertNotLimited(ip); const body = await readBody(c, z.object({ current: z.string().max(256), next: passwordSchema })); const hash = getSetting(app.db, HASH_KEY, null); if (!hash || !(await verifyPassword(body.current, hash))) { recordFailure(ip); throw new HttpError(403, 'bad_password', 'Current password is incorrect'); } await storePassword(app, body.next); // Sign out every other device. const token = getCookie(c, COOKIE); app.db.run('DELETE FROM sessions WHERE token_hash != ?', token ? sha256(token) : ''); return c.json({ ok: true }); }); r.get('/sessions', requireAuth(app), (c) => { const current = sha256(getCookie(c, COOKIE) ?? ''); const rows = app.db.all<{ token_hash: string; created_at: number; last_seen_at: number; user_agent: string; ip: string }>( 'SELECT token_hash, created_at, last_seen_at, user_agent, ip FROM sessions WHERE expires_at > ? ORDER BY last_seen_at DESC', now(), ); return c.json({ sessions: rows.map((s) => ({ id: s.token_hash.slice(0, 12), createdAt: s.created_at, lastSeenAt: s.last_seen_at, userAgent: s.user_agent, ip: s.ip, current: s.token_hash === current, })), }); }); r.post('/sessions/revoke-others', requireAuth(app), (c) => { const current = sha256(getCookie(c, COOKIE) ?? ''); const { changes } = app.db.run('DELETE FROM sessions WHERE token_hash != ?', current); return c.json({ revoked: changes }); }); return r; }