'use strict'; const jwt = require('jsonwebtoken'); const crypto = require('crypto'); const geoip = require('geoip-lite'); const { getDb } = require('./db'); const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour const SESSION_LAST_SEEN_WRITE_INTERVAL_MS = 60 * 1000; // throttle DB writes on active sessions const AUTH_SESSION_PURGE_INTERVAL_MS = 15 * 60 * 1000; // 15 minutes const AUTH_USER_CACHE_TTL_MS = 60 * 1000; const AUTH_REGION_CACHE_MAX_ENTRIES = 2048; const AUTH_SESSION_REVOKED_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours const AUTH_SESSION_IDLE_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours beyond idle timeout let authSessionPurgeTimer = null; const regionByIp = new Map(); const userCacheByUsername = new Map(); const authSessionCleanupState = { lastRunAt: null, lastPurgedCount: 0, lastDurationMs: 0, lastError: null, }; // Secret used to sign JWTs — generated fresh each server boot. // Tokens from a previous boot are automatically invalid. const JWT_SECRET = crypto.randomBytes(64).toString('hex'); // --------------------------------------------------------------------------- // Helpers // --------------------------------------------------------------------------- function getClientIp (req) { // Respect X-Forwarded-For only if you trust a reverse proxy in front. // For a direct Pi deployment, req.ip is sufficient. let ip = req.ip || req.connection.remoteAddress || ''; // Normalize IPv4-mapped IPv6 (::ffff:127.0.0.1) and IPv6 loopback (::1) // to plain IPv4 so token binding is stable across request variations. ip = ip.replace(/^::ffff:/, ''); if (ip === '::1') ip = '127.0.0.1'; return ip; } function getRegion (ip) { const key = String(ip || ''); if (!key) return 'local:'; const cached = regionByIp.get(key); if (cached) return cached; // ip is already normalized by getClientIp (no ::ffff: prefix, no ::1) const geo = geoip.lookup(key); // Private / RFC1918 addresses won't resolve — use ip itself as region. const region = geo ? `${geo.country}:${geo.region}` : `local:${key}`; if (regionByIp.size >= AUTH_REGION_CACHE_MAX_ENTRIES) { regionByIp.clear(); } regionByIp.set(key, region); return region; } function getCachedUser (username) { const key = String(username || ''); if (!key) return null; const cached = userCacheByUsername.get(key); const now = nowMs(); if (cached && (now - cached.cachedAt) < AUTH_USER_CACHE_TTL_MS) { return cached.user; } const db = getDb(); const user = db.prepare('SELECT id, username, is_admin, permissions FROM users WHERE username = ?') .get([key]); if (!user) return null; const parsed = { id: user.id, username: user.username, isAdmin: user.is_admin === 1, permissions: JSON.parse(user.permissions || '{}'), }; userCacheByUsername.set(key, { user: parsed, cachedAt: now }); return parsed; } function clearAuthUserCache (username) { if (username) { userCacheByUsername.delete(String(username)); return; } userCacheByUsername.clear(); } function touchSessionLastSeen (sessionId, lastSeenAt) { const db = getDb(); db.prepare('UPDATE auth_sessions SET last_seen_at = ? WHERE session_id = ?') .run([lastSeenAt, sessionId]); } function fingerprintHash (fingerprint) { return crypto.createHash('sha256').update(fingerprint || '').digest('hex'); } function nowMs () { return Date.now(); } function createSession (username, req, fingerprint) { const db = getDb(); const ip = getClientIp(req); const region = getRegion(ip); const fpHash = fingerprintHash(fingerprint); const createdAt = nowMs(); const sessionId = crypto.randomUUID(); db.prepare(` INSERT INTO auth_sessions (session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at) VALUES (?, ?, ?, ?, ?, ?, ?, NULL) `).run([sessionId, username, ip, region, fpHash, createdAt, createdAt]); return { sessionId, ip, region, fpHash }; } function revokeSession (sessionId) { if (!sessionId) return; const db = getDb(); db.prepare('UPDATE auth_sessions SET revoked_at = ? WHERE session_id = ? AND revoked_at IS NULL') .run([nowMs(), sessionId]); } function purgeStaleSessions (opts = {}) { const now = Number.isFinite(Number(opts.nowMs)) ? Number(opts.nowMs) : nowMs(); const revokedCutoffMs = now - AUTH_SESSION_REVOKED_RETENTION_MS; const idleCutoffMs = now - SESSION_IDLE_TIMEOUT_MS - AUTH_SESSION_IDLE_RETENTION_MS; const db = getDb(); const result = db.prepare(` DELETE FROM auth_sessions WHERE (revoked_at IS NOT NULL AND revoked_at <= ?) OR (last_seen_at <= ?) `).run([revokedCutoffMs, idleCutoffMs]); return Number(result && result.changes || 0); } function runAuthSessionCleanupOnce () { const startedAt = nowMs(); try { const purged = purgeStaleSessions(); authSessionCleanupState.lastRunAt = nowMs(); authSessionCleanupState.lastPurgedCount = Number(purged || 0); authSessionCleanupState.lastDurationMs = Math.max(0, authSessionCleanupState.lastRunAt - startedAt); authSessionCleanupState.lastError = null; return purged; } catch (err) { authSessionCleanupState.lastRunAt = nowMs(); authSessionCleanupState.lastPurgedCount = 0; authSessionCleanupState.lastDurationMs = Math.max(0, authSessionCleanupState.lastRunAt - startedAt); authSessionCleanupState.lastError = err && err.message ? String(err.message) : String(err); throw err; } } function startAuthSessionCleanupLoop () { if (authSessionPurgeTimer) return; // Run once immediately at startup to trim stale rows from earlier uptime. try { runAuthSessionCleanupOnce(); } catch { // Ignore purge failures and retry on the next interval. } authSessionPurgeTimer = setInterval(() => { try { runAuthSessionCleanupOnce(); } catch { // Keep server healthy even if cleanup temporarily fails. } }, AUTH_SESSION_PURGE_INTERVAL_MS); if (authSessionPurgeTimer && typeof authSessionPurgeTimer.unref === 'function') { authSessionPurgeTimer.unref(); } } function stopAuthSessionCleanupLoop () { if (!authSessionPurgeTimer) return; clearInterval(authSessionPurgeTimer); authSessionPurgeTimer = null; } function getAuthSessionCleanupSnapshot () { return { running: !!authSessionPurgeTimer, intervalMs: AUTH_SESSION_PURGE_INTERVAL_MS, lastRunAt: authSessionCleanupState.lastRunAt, lastPurgedCount: authSessionCleanupState.lastPurgedCount, lastDurationMs: authSessionCleanupState.lastDurationMs, lastError: authSessionCleanupState.lastError, revokedRetentionMs: AUTH_SESSION_REVOKED_RETENTION_MS, idleRetentionMs: AUTH_SESSION_IDLE_RETENTION_MS, }; } // --------------------------------------------------------------------------- // Token creation // --------------------------------------------------------------------------- /** * Returns a signed JWT that expires at end of the current calendar day (UTC). */ function createToken (username, req, fingerprint) { const session = createSession(username, req, fingerprint); const payload = { u: username, ip: session.ip, r: session.region, fp: session.fpHash, sid: session.sessionId, }; // Keep JWT short-lived; server-side idle checks are the primary control. return jwt.sign(payload, JWT_SECRET, { expiresIn: '12h' }); } // --------------------------------------------------------------------------- // Middleware // --------------------------------------------------------------------------- /** * Verifies the Bearer token in the Authorization header. * On success attaches `req.user = { username, isAdmin }`. * On failure sends 401 with a generic "session invalid" message. */ function requireAuth (req, res, next) { const header = req.headers['authorization'] || ''; const token = header.startsWith('Bearer ') ? header.slice(7) : null; if (!token) { return res.status(401).json({ error: 'Session invalid or expired.' }); } let payload; try { payload = jwt.verify(token, JWT_SECRET); } catch { return res.status(401).json({ error: 'Session invalid or expired.' }); } // Verify IP binding const currentIp = getClientIp(req); if (payload.ip !== currentIp) { // Intentionally identical error — do not reveal reason return res.status(401).json({ error: 'Session invalid or expired.' }); } // Verify region binding const currentRegion = getRegion(currentIp); if (payload.r !== currentRegion) { return res.status(401).json({ error: 'Session invalid or expired.' }); } // Verify fingerprint (sent on every request as X-Fp header) const fp = req.headers['x-fp'] || ''; if (payload.fp !== fingerprintHash(fp)) { return res.status(401).json({ error: 'Session invalid or expired.' }); } if (!payload.sid) { return res.status(401).json({ error: 'Session invalid or expired.' }); } const db = getDb(); const session = db.prepare(` SELECT session_id, username, ip, region, fp_hash, last_seen_at, revoked_at FROM auth_sessions WHERE session_id = ? `).get([payload.sid]); if (!session || session.revoked_at) { return res.status(401).json({ error: 'Session invalid or expired.' }); } if (session.username !== payload.u || session.ip !== currentIp || session.region !== currentRegion) { return res.status(401).json({ error: 'Session invalid or expired.' }); } if (session.fp_hash !== payload.fp) { return res.status(401).json({ error: 'Session invalid or expired.' }); } const now = nowMs(); if (now - Number(session.last_seen_at || 0) > SESSION_IDLE_TIMEOUT_MS) { revokeSession(payload.sid); return res.status(401).json({ error: 'Session invalid or expired.' }); } if (now - Number(session.last_seen_at || 0) >= SESSION_LAST_SEEN_WRITE_INTERVAL_MS) { touchSessionLastSeen(payload.sid, now); } const user = getCachedUser(payload.u); if (!user) { return res.status(401).json({ error: 'Session invalid or expired.' }); } req.user = user; req.authSessionId = payload.sid; next(); } /** * Middleware that additionally requires admin privileges. */ function requireAdmin (req, res, next) { if (!req.user || !req.user.isAdmin) { return res.status(403).json({ error: 'Admin access required.' }); } next(); } module.exports = { createToken, requireAuth, requireAdmin, getClientIp, getRegion, clearAuthUserCache, revokeSession, purgeStaleSessions, getAuthSessionCleanupSnapshot, startAuthSessionCleanupLoop, stopAuthSessionCleanupLoop, SESSION_IDLE_TIMEOUT_MS, AUTH_SESSION_PURGE_INTERVAL_MS, AUTH_SESSION_REVOKED_RETENTION_MS, AUTH_SESSION_IDLE_RETENTION_MS, };