BlueGit

timfa filemanager

Files

filemanager / server / auth.js

auth.js

Cursor Optimisation pass
timfa Tim Falken · pushed by timfa · 5 months ago
7e6dfc52 History
auth.js 10.5 KiB Download Raw
1'use strict';
2
3const jwt = require('jsonwebtoken');
4const crypto = require('crypto');
5const geoip = require('geoip-lite');
6const { getDb } = require('./db');
7
8const SESSION_IDLE_TIMEOUT_MS = 60 * 60 * 1000; // 1 hour
9const SESSION_LAST_SEEN_WRITE_INTERVAL_MS = 60 * 1000; // throttle DB writes on active sessions
10const AUTH_SESSION_PURGE_INTERVAL_MS = 15 * 60 * 1000; // 15 minutes
11const AUTH_USER_CACHE_TTL_MS = 60 * 1000;
12const AUTH_REGION_CACHE_MAX_ENTRIES = 2048;
13const AUTH_SESSION_REVOKED_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours
14const AUTH_SESSION_IDLE_RETENTION_MS = 24 * 60 * 60 * 1000; // 24 hours beyond idle timeout
15
16let authSessionPurgeTimer = null;
17const regionByIp = new Map();
18const userCacheByUsername = new Map();
19const authSessionCleanupState = {
20 lastRunAt: null,
21 lastPurgedCount: 0,
22 lastDurationMs: 0,
23 lastError: null,
24};
25
26// Secret used to sign JWTs — generated fresh each server boot.
27// Tokens from a previous boot are automatically invalid.
28const JWT_SECRET = crypto.randomBytes(64).toString('hex');
29
30// ---------------------------------------------------------------------------
31// Helpers
32// ---------------------------------------------------------------------------
33
34function getClientIp (req)
35{
36 // Respect X-Forwarded-For only if you trust a reverse proxy in front.
37 // For a direct Pi deployment, req.ip is sufficient.
38 let ip = req.ip || req.connection.remoteAddress || '';
39 // Normalize IPv4-mapped IPv6 (::ffff:127.0.0.1) and IPv6 loopback (::1)
40 // to plain IPv4 so token binding is stable across request variations.
41 ip = ip.replace(/^::ffff:/, '');
42 if (ip === '::1') ip = '127.0.0.1';
43 return ip;
44}
45
46function getRegion (ip)
47{
48 const key = String(ip || '');
49 if (!key) return 'local:';
50
51 const cached = regionByIp.get(key);
52 if (cached) return cached;
53
54 // ip is already normalized by getClientIp (no ::ffff: prefix, no ::1)
55 const geo = geoip.lookup(key);
56 // Private / RFC1918 addresses won't resolve — use ip itself as region.
57 const region = geo ? `${geo.country}:${geo.region}` : `local:${key}`;
58
59 if (regionByIp.size >= AUTH_REGION_CACHE_MAX_ENTRIES)
60 {
61 regionByIp.clear();
62 }
63 regionByIp.set(key, region);
64 return region;
65}
66
67function getCachedUser (username)
68{
69 const key = String(username || '');
70 if (!key) return null;
71
72 const cached = userCacheByUsername.get(key);
73 const now = nowMs();
74 if (cached && (now - cached.cachedAt) < AUTH_USER_CACHE_TTL_MS)
75 {
76 return cached.user;
77 }
78
79 const db = getDb();
80 const user = db.prepare('SELECT id, username, is_admin, permissions FROM users WHERE username = ?')
81 .get([key]);
82 if (!user) return null;
83
84 const parsed = {
85 id: user.id,
86 username: user.username,
87 isAdmin: user.is_admin === 1,
88 permissions: JSON.parse(user.permissions || '{}'),
89 };
90
91 userCacheByUsername.set(key, { user: parsed, cachedAt: now });
92 return parsed;
93}
94
95function clearAuthUserCache (username)
96{
97 if (username)
98 {
99 userCacheByUsername.delete(String(username));
100 return;
101 }
102 userCacheByUsername.clear();
103}
104
105function touchSessionLastSeen (sessionId, lastSeenAt)
106{
107 const db = getDb();
108 db.prepare('UPDATE auth_sessions SET last_seen_at = ? WHERE session_id = ?')
109 .run([lastSeenAt, sessionId]);
110}
111
112function fingerprintHash (fingerprint)
113{
114 return crypto.createHash('sha256').update(fingerprint || '').digest('hex');
115}
116
117function nowMs ()
118{
119 return Date.now();
120}
121
122function createSession (username, req, fingerprint)
123{
124 const db = getDb();
125 const ip = getClientIp(req);
126 const region = getRegion(ip);
127 const fpHash = fingerprintHash(fingerprint);
128 const createdAt = nowMs();
129 const sessionId = crypto.randomUUID();
130
131 db.prepare(`
132 INSERT INTO auth_sessions (session_id, username, ip, region, fp_hash, created_at, last_seen_at, revoked_at)
133 VALUES (?, ?, ?, ?, ?, ?, ?, NULL)
134 `).run([sessionId, username, ip, region, fpHash, createdAt, createdAt]);
135
136 return { sessionId, ip, region, fpHash };
137}
138
139function revokeSession (sessionId)
140{
141 if (!sessionId) return;
142 const db = getDb();
143 db.prepare('UPDATE auth_sessions SET revoked_at = ? WHERE session_id = ? AND revoked_at IS NULL')
144 .run([nowMs(), sessionId]);
145}
146
147function purgeStaleSessions (opts = {})
148{
149 const now = Number.isFinite(Number(opts.nowMs)) ? Number(opts.nowMs) : nowMs();
150 const revokedCutoffMs = now - AUTH_SESSION_REVOKED_RETENTION_MS;
151 const idleCutoffMs = now - SESSION_IDLE_TIMEOUT_MS - AUTH_SESSION_IDLE_RETENTION_MS;
152 const db = getDb();
153
154 const result = db.prepare(`
155 DELETE FROM auth_sessions
156 WHERE (revoked_at IS NOT NULL AND revoked_at <= ?)
157 OR (last_seen_at <= ?)
158 `).run([revokedCutoffMs, idleCutoffMs]);
159
160 return Number(result && result.changes || 0);
161}
162
163function runAuthSessionCleanupOnce ()
164{
165 const startedAt = nowMs();
166 try
167 {
168 const purged = purgeStaleSessions();
169 authSessionCleanupState.lastRunAt = nowMs();
170 authSessionCleanupState.lastPurgedCount = Number(purged || 0);
171 authSessionCleanupState.lastDurationMs = Math.max(0, authSessionCleanupState.lastRunAt - startedAt);
172 authSessionCleanupState.lastError = null;
173 return purged;
174 } catch (err)
175 {
176 authSessionCleanupState.lastRunAt = nowMs();
177 authSessionCleanupState.lastPurgedCount = 0;
178 authSessionCleanupState.lastDurationMs = Math.max(0, authSessionCleanupState.lastRunAt - startedAt);
179 authSessionCleanupState.lastError = err && err.message ? String(err.message) : String(err);
180 throw err;
181 }
182}
183
184function startAuthSessionCleanupLoop ()
185{
186 if (authSessionPurgeTimer) return;
187
188 // Run once immediately at startup to trim stale rows from earlier uptime.
189 try
190 {
191 runAuthSessionCleanupOnce();
192 } catch
193 {
194 // Ignore purge failures and retry on the next interval.
195 }
196
197 authSessionPurgeTimer = setInterval(() =>
198 {
199 try
200 {
201 runAuthSessionCleanupOnce();
202 } catch
203 {
204 // Keep server healthy even if cleanup temporarily fails.
205 }
206 }, AUTH_SESSION_PURGE_INTERVAL_MS);
207
208 if (authSessionPurgeTimer && typeof authSessionPurgeTimer.unref === 'function')
209 {
210 authSessionPurgeTimer.unref();
211 }
212}
213
214function stopAuthSessionCleanupLoop ()
215{
216 if (!authSessionPurgeTimer) return;
217 clearInterval(authSessionPurgeTimer);
218 authSessionPurgeTimer = null;
219}
220
221function getAuthSessionCleanupSnapshot ()
222{
223 return {
224 running: !!authSessionPurgeTimer,
225 intervalMs: AUTH_SESSION_PURGE_INTERVAL_MS,
226 lastRunAt: authSessionCleanupState.lastRunAt,
227 lastPurgedCount: authSessionCleanupState.lastPurgedCount,
228 lastDurationMs: authSessionCleanupState.lastDurationMs,
229 lastError: authSessionCleanupState.lastError,
230 revokedRetentionMs: AUTH_SESSION_REVOKED_RETENTION_MS,
231 idleRetentionMs: AUTH_SESSION_IDLE_RETENTION_MS,
232 };
233}
234
235// ---------------------------------------------------------------------------
236// Token creation
237// ---------------------------------------------------------------------------
238
239/**
240 * Returns a signed JWT that expires at end of the current calendar day (UTC).
241 */
242function createToken (username, req, fingerprint)
243{
244 const session = createSession(username, req, fingerprint);
245
246 const payload = {
247 u: username,
248 ip: session.ip,
249 r: session.region,
250 fp: session.fpHash,
251 sid: session.sessionId,
252 };
253
254 // Keep JWT short-lived; server-side idle checks are the primary control.
255 return jwt.sign(payload, JWT_SECRET, { expiresIn: '12h' });
256}
257
258// ---------------------------------------------------------------------------
259// Middleware
260// ---------------------------------------------------------------------------
261
262/**
263 * Verifies the Bearer token in the Authorization header.
264 * On success attaches `req.user = { username, isAdmin }`.
265 * On failure sends 401 with a generic "session invalid" message.
266 */
267function requireAuth (req, res, next)
268{
269 const header = req.headers['authorization'] || '';
270 const token = header.startsWith('Bearer ') ? header.slice(7) : null;
271
272 if (!token)
273 {
274 return res.status(401).json({ error: 'Session invalid or expired.' });
275 }
276
277 let payload;
278 try
279 {
280 payload = jwt.verify(token, JWT_SECRET);
281 } catch
282 {
283 return res.status(401).json({ error: 'Session invalid or expired.' });
284 }
285
286 // Verify IP binding
287 const currentIp = getClientIp(req);
288 if (payload.ip !== currentIp)
289 {
290 // Intentionally identical error — do not reveal reason
291 return res.status(401).json({ error: 'Session invalid or expired.' });
292 }
293
294 // Verify region binding
295 const currentRegion = getRegion(currentIp);
296 if (payload.r !== currentRegion)
297 {
298 return res.status(401).json({ error: 'Session invalid or expired.' });
299 }
300
301 // Verify fingerprint (sent on every request as X-Fp header)
302 const fp = req.headers['x-fp'] || '';
303 if (payload.fp !== fingerprintHash(fp))
304 {
305 return res.status(401).json({ error: 'Session invalid or expired.' });
306 }
307
308 if (!payload.sid)
309 {
310 return res.status(401).json({ error: 'Session invalid or expired.' });
311 }
312
313 const db = getDb();
314 const session = db.prepare(`
315 SELECT session_id, username, ip, region, fp_hash, last_seen_at, revoked_at
316 FROM auth_sessions
317 WHERE session_id = ?
318 `).get([payload.sid]);
319
320 if (!session || session.revoked_at)
321 {
322 return res.status(401).json({ error: 'Session invalid or expired.' });
323 }
324
325 if (session.username !== payload.u || session.ip !== currentIp || session.region !== currentRegion)
326 {
327 return res.status(401).json({ error: 'Session invalid or expired.' });
328 }
329
330 if (session.fp_hash !== payload.fp)
331 {
332 return res.status(401).json({ error: 'Session invalid or expired.' });
333 }
334
335 const now = nowMs();
336 if (now - Number(session.last_seen_at || 0) > SESSION_IDLE_TIMEOUT_MS)
337 {
338 revokeSession(payload.sid);
339 return res.status(401).json({ error: 'Session invalid or expired.' });
340 }
341
342 if (now - Number(session.last_seen_at || 0) >= SESSION_LAST_SEEN_WRITE_INTERVAL_MS)
343 {
344 touchSessionLastSeen(payload.sid, now);
345 }
346
347 const user = getCachedUser(payload.u);
348 if (!user)
349 {
350 return res.status(401).json({ error: 'Session invalid or expired.' });
351 }
352
353 req.user = user;
354 req.authSessionId = payload.sid;
355
356 next();
357}
358
359/**
360 * Middleware that additionally requires admin privileges.
361 */
362function requireAdmin (req, res, next)
363{
364 if (!req.user || !req.user.isAdmin)
365 {
366 return res.status(403).json({ error: 'Admin access required.' });
367 }
368 next();
369}
370
371module.exports = {
372 createToken,
373 requireAuth,
374 requireAdmin,
375 getClientIp,
376 getRegion,
377 clearAuthUserCache,
378 revokeSession,
379 purgeStaleSessions,
380 getAuthSessionCleanupSnapshot,
381 startAuthSessionCleanupLoop,
382 stopAuthSessionCleanupLoop,
383 SESSION_IDLE_TIMEOUT_MS,
384 AUTH_SESSION_PURGE_INTERVAL_MS,
385 AUTH_SESSION_REVOKED_RETENTION_MS,
386 AUTH_SESSION_IDLE_RETENTION_MS,
387};