'use strict'; const jwt = require('jsonwebtoken'); const crypto = require('crypto'); const geoip = require('geoip-lite'); const { getDb } = require('./db'); // 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) { // ip is already normalized by getClientIp (no ::ffff: prefix, no ::1) const geo = geoip.lookup(ip); // Private / RFC1918 addresses won't resolve — use ip itself as region. return geo ? `${geo.country}:${geo.region}` : `local:${ip}`; } function fingerprintHash(fingerprint) { return crypto.createHash('sha256').update(fingerprint || '').digest('hex'); } // --------------------------------------------------------------------------- // Token creation // --------------------------------------------------------------------------- /** * Returns a signed JWT that expires at end of the current calendar day (UTC). */ function createToken(username, req, fingerprint) { const ip = getClientIp(req); const region = getRegion(ip); const fpHash = fingerprintHash(fingerprint); // Expire at 23:59:59 UTC today const now = new Date(); const endOfDay = new Date(Date.UTC( now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), 23, 59, 59, )); const payload = { u: username, ip: ip, r: region, fp: fpHash, }; return jwt.sign(payload, JWT_SECRET, { expiresIn: Math.floor((endOfDay - Date.now()) / 1000) }); } // --------------------------------------------------------------------------- // 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.' }); } // Load user from DB const db = getDb(); const user = db.prepare('SELECT id, username, is_admin, permissions FROM users WHERE username = ?') .get([payload.u]); if (!user) { return res.status(401).json({ error: 'Session invalid or expired.' }); } req.user = { id: user.id, username: user.username, isAdmin: user.is_admin === 1, permissions: JSON.parse(user.permissions || '{}'), }; 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 };