BlueGit

timfa filemanager

Files

filemanager / server / auth.js

auth.js

import project
timfa Tim Falken · pushed by timfa · 6 months ago
d3c0b911 History
auth.js 4.3 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
8// Secret used to sign JWTs — generated fresh each server boot.
9// Tokens from a previous boot are automatically invalid.
10const JWT_SECRET = crypto.randomBytes(64).toString('hex');
11
12// ---------------------------------------------------------------------------
13// Helpers
14// ---------------------------------------------------------------------------
15
16function getClientIp(req) {
17 // Respect X-Forwarded-For only if you trust a reverse proxy in front.
18 // For a direct Pi deployment, req.ip is sufficient.
19 let ip = req.ip || req.connection.remoteAddress || '';
20 // Normalize IPv4-mapped IPv6 (::ffff:127.0.0.1) and IPv6 loopback (::1)
21 // to plain IPv4 so token binding is stable across request variations.
22 ip = ip.replace(/^::ffff:/, '');
23 if (ip === '::1') ip = '127.0.0.1';
24 return ip;
25}
26
27function getRegion(ip) {
28 // ip is already normalized by getClientIp (no ::ffff: prefix, no ::1)
29 const geo = geoip.lookup(ip);
30 // Private / RFC1918 addresses won't resolve — use ip itself as region.
31 return geo ? `${geo.country}:${geo.region}` : `local:${ip}`;
32}
33
34function fingerprintHash(fingerprint) {
35 return crypto.createHash('sha256').update(fingerprint || '').digest('hex');
36}
37
38// ---------------------------------------------------------------------------
39// Token creation
40// ---------------------------------------------------------------------------
41
42/**
43 * Returns a signed JWT that expires at end of the current calendar day (UTC).
44 */
45function createToken(username, req, fingerprint) {
46 const ip = getClientIp(req);
47 const region = getRegion(ip);
48 const fpHash = fingerprintHash(fingerprint);
49
50 // Expire at 23:59:59 UTC today
51 const now = new Date();
52 const endOfDay = new Date(Date.UTC(
53 now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),
54 23, 59, 59,
55 ));
56
57 const payload = {
58 u: username,
59 ip: ip,
60 r: region,
61 fp: fpHash,
62 };
63
64 return jwt.sign(payload, JWT_SECRET, { expiresIn: Math.floor((endOfDay - Date.now()) / 1000) });
65}
66
67// ---------------------------------------------------------------------------
68// Middleware
69// ---------------------------------------------------------------------------
70
71/**
72 * Verifies the Bearer token in the Authorization header.
73 * On success attaches `req.user = { username, isAdmin }`.
74 * On failure sends 401 with a generic "session invalid" message.
75 */
76function requireAuth(req, res, next) {
77 const header = req.headers['authorization'] || '';
78 const token = header.startsWith('Bearer ') ? header.slice(7) : null;
79
80 if (!token) {
81 return res.status(401).json({ error: 'Session invalid or expired.' });
82 }
83
84 let payload;
85 try {
86 payload = jwt.verify(token, JWT_SECRET);
87 } catch {
88 return res.status(401).json({ error: 'Session invalid or expired.' });
89 }
90
91 // Verify IP binding
92 const currentIp = getClientIp(req);
93 if (payload.ip !== currentIp) {
94 // Intentionally identical error — do not reveal reason
95 return res.status(401).json({ error: 'Session invalid or expired.' });
96 }
97
98 // Verify region binding
99 const currentRegion = getRegion(currentIp);
100 if (payload.r !== currentRegion) {
101 return res.status(401).json({ error: 'Session invalid or expired.' });
102 }
103
104 // Verify fingerprint (sent on every request as X-Fp header)
105 const fp = req.headers['x-fp'] || '';
106 if (payload.fp !== fingerprintHash(fp)) {
107 return res.status(401).json({ error: 'Session invalid or expired.' });
108 }
109
110 // Load user from DB
111 const db = getDb();
112 const user = db.prepare('SELECT id, username, is_admin, permissions FROM users WHERE username = ?')
113 .get([payload.u]);
114
115 if (!user) {
116 return res.status(401).json({ error: 'Session invalid or expired.' });
117 }
118
119 req.user = {
120 id: user.id,
121 username: user.username,
122 isAdmin: user.is_admin === 1,
123 permissions: JSON.parse(user.permissions || '{}'),
124 };
125
126 next();
127}
128
129/**
130 * Middleware that additionally requires admin privileges.
131 */
132function requireAdmin(req, res, next) {
133 if (!req.user || !req.user.isAdmin) {
134 return res.status(403).json({ error: 'Admin access required.' });
135 }
136 next();
137}
138
139module.exports = { createToken, requireAuth, requireAdmin, getClientIp, getRegion };