wa-dev-tools/lib/auth.js
treamz 5b528d243a Refactor: modular architecture, security, config
- Split monolithic server.js (1111 lines) into route modules
- Add .env config (port, session secret, quality, limits)
- Add SSRF protection for parser/proxy/redirect endpoints
- Add optional password auth middleware
- Add structured logger (replaces raw fs.appendFileSync)
- Add graceful shutdown with timeout
- Add extended /health endpoint (uptime, memory, pid)
- Add ecosystem.config.js for PM2 (memory limit, restart policy)
- Make compress quality configurable (was hardcoded 60)
- Expand SVG AI icons library (7 -> 20 icons)
- Add dotenv dependency
2026-03-21 22:18:54 +03:00

45 lines
1.7 KiB
JavaScript

/**
* Optional password auth middleware.
* If AUTH_PASSWORD is set in .env, requires ?key=<password> or session auth.
* Static assets and health check are always public.
*/
const PUBLIC_PATHS = ['/health', '/favicon.ico'];
function authMiddleware(req, res, next) {
const password = process.env.AUTH_PASSWORD;
// No password set — everything is public
if (!password) return next();
// Always allow public paths and static assets
if (PUBLIC_PATHS.includes(req.path)) return next();
if (req.path.startsWith('/vendor/')) return next();
// Check session
if (req.session && req.session.authenticated) return next();
// Check query param
if (req.query.key === password) {
if (req.session) req.session.authenticated = true;
return next();
}
// Show login form for GET requests to pages
if (req.method === 'GET' && !req.path.startsWith('/api/') && !req.path.startsWith('/download/')) {
return res.status(401).send(`<!DOCTYPE html>
<html><head><meta charset="UTF-8"><title>Login</title>
<style>body{font-family:sans-serif;display:flex;justify-content:center;align-items:center;height:100vh;margin:0;background:#060c18;color:#c0c0c0}
form{background:#091020;padding:32px;border-radius:12px;border:1px solid #162040}
input{display:block;margin:8px 0;padding:10px;background:#0a1628;border:1px solid #162040;color:#c0c0c0;border-radius:6px;width:200px}
button{padding:10px 24px;background:#0054e6;color:#fff;border:none;border-radius:6px;cursor:pointer;width:100%}
</style></head><body>
<form method="GET"><label>Пароль</label><input type="password" name="key" autofocus><button>Войти</button></form>
</body></html>`);
}
return res.status(401).json({ error: 'Unauthorized' });
}
module.exports = authMiddleware;