// Optional single-password login. Enabled only when AUTH_PASSWORD is set. // // Session = signed cookie "."; payload is base64url JSON { iat, exp }. // The HMAC key mixes SESSION_SECRET with a hash of the password, so changing AUTH_PASSWORD // invalidates every existing session. If SESSION_SECRET is unset, a random secret is // generated once and kept in DATA_DIR/session-secret (chmod 600) so restarts keep sessions. import crypto from 'node:crypto'; import fs from 'node:fs'; import path from 'node:path'; export const COOKIE_NAME = 'elorasmus_session'; const sha256 = (s) => crypto.createHash('sha256').update(s).digest(); const b64url = (buf) => Buffer.from(buf).toString('base64url'); function loadOrCreateSecret(dataDir) { const file = path.join(dataDir, 'session-secret'); try { const s = fs.readFileSync(file, 'utf8').trim(); if (s.length >= 32) return s; } catch (err) { if (err.code !== 'ENOENT') throw err; } const s = crypto.randomBytes(32).toString('hex'); fs.writeFileSync(file, s + '\n', { mode: 0o600 }); return s; } export class Auth { constructor(config) { this.enabled = Boolean(config.authPassword); this.config = config; this.failures = new Map(); // ip -> { count, until } if (!this.enabled) return; const secret = config.sessionSecret ?? loadOrCreateSecret(config.dataDir); this.key = crypto.createHmac('sha256', secret).update('elorasmus-v1:').update(sha256(config.authPassword)).digest(); this.passwordDigest = sha256(config.authPassword); } #sign(payload) { return b64url(crypto.createHmac('sha256', this.key).update(payload).digest()); } issueCookie(secure) { const now = Math.floor(Date.now() / 1000); const maxAge = this.config.sessionDays * 86400; const payload = b64url(JSON.stringify({ iat: now, exp: now + maxAge })); return cookieString(`${payload}.${this.#sign(payload)}`, maxAge, secure, this.config.basePath); } clearCookie(secure) { return cookieString('', 0, secure, this.config.basePath); } /** True if the request carries a valid, unexpired session cookie (always true when auth is off). */ isAuthenticated(req) { if (!this.enabled) return true; const token = parseCookies(req.headers.cookie)[COOKIE_NAME]; if (!token) return false; const [payload, sig] = token.split('.'); if (!payload || !sig) return false; const expected = Buffer.from(this.#sign(payload)); const given = Buffer.from(sig); if (expected.length !== given.length || !crypto.timingSafeEqual(expected, given)) return false; try { const { exp } = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8')); return typeof exp === 'number' && exp > Date.now() / 1000; } catch { return false; } } /** Seconds the client must wait before another attempt (0 = allowed). */ retryAfter(ip) { const f = this.failures.get(ip); if (!f) return 0; return Math.max(0, Math.ceil((f.until - Date.now()) / 1000)); } /** Constant-time password check with exponential backoff after 5 failures per IP. */ checkPassword(ip, password) { const ok = typeof password === 'string' && crypto.timingSafeEqual(sha256(password), this.passwordDigest); if (ok) { this.failures.delete(ip); return true; } const f = this.failures.get(ip) ?? { count: 0, until: 0 }; f.count += 1; // 5 free attempts, then 2s, 4s, 8s ... capped at 15 minutes. const delay = f.count <= 5 ? 0 : Math.min(900, 2 ** (f.count - 5)) * 1000; f.until = Date.now() + delay; this.failures.set(ip, f); if (this.failures.size > 10000) this.failures.clear(); // bound memory under abuse return false; } } function cookieString(value, maxAge, secure, basePath) { return [ `${COOKIE_NAME}=${value}`, `Path=${basePath}`, `Max-Age=${maxAge}`, 'HttpOnly', 'SameSite=Strict', secure ? 'Secure' : null, ].filter(Boolean).join('; '); } export function parseCookies(header = '') { const out = {}; for (const part of header.split(';')) { const i = part.indexOf('='); if (i > 0) out[part.slice(0, i).trim()] = part.slice(i + 1).trim(); } return out; }