Critical fixes: - helmet middleware (X-Frame-Options, HSTS, X-Content-Type, CSP, etc) - Remove /admin from PUBLIC_PREFIXES (double auth: session + admin role) - Session cookie: httpOnly, sameSite=lax, 1-day expiry (was 30 days) - Session regeneration on login (prevent session fixation) - Blocked user check on login Rate limiting: - /auth/login: 10 req / 15 min (brute force protection) - /auth/register: 10 req / 15 min (spam protection) - /parse, /metadata, /text, /preview: 20 req / min (DDoS via server) Input sanitization: - Strip HTML tags from display_name (stored XSS prevention)
36 lines
1.3 KiB
JavaScript
36 lines
1.3 KiB
JavaScript
/**
|
|
* Auth middleware — requires user session for protected routes.
|
|
* Public: landing page, auth routes, static assets, health, placeholder API.
|
|
*/
|
|
|
|
const PUBLIC_PATHS = ['/', '/health', '/favicon.ico', '/status'];
|
|
const PUBLIC_API = ['/api/settings', '/api/tools', '/api/content/advantages', '/api/content/dashboard'];
|
|
const PUBLIC_PREFIXES = ['/auth/', '/vendor/', '/placeholder-img/', '/status/'];
|
|
const PUBLIC_FILES = ['/shared.css', '/shared.js', '/landing.html'];
|
|
|
|
function authMiddleware(req, res, next) {
|
|
// Public paths
|
|
if (PUBLIC_PATHS.includes(req.path)) return next();
|
|
if (PUBLIC_API.includes(req.path)) return next();
|
|
if (PUBLIC_FILES.includes(req.path)) return next();
|
|
if (PUBLIC_PREFIXES.some(p => req.path.startsWith(p))) return next();
|
|
|
|
// Authenticated user
|
|
if (req.session && req.session.user) return next();
|
|
|
|
// API requests — 401 JSON
|
|
if (req.path.startsWith('/api/') || req.path.startsWith('/download/')) {
|
|
return res.status(401).json({ error: 'Unauthorized' });
|
|
}
|
|
|
|
// Page requests — save return URL and redirect to login
|
|
if (req.method === 'GET') {
|
|
req.session.returnTo = req.originalUrl;
|
|
return res.redirect('/auth/login');
|
|
}
|
|
|
|
return res.status(401).json({ error: 'Unauthorized' });
|
|
}
|
|
|
|
module.exports = authMiddleware;
|