Files
sofarr/server/routes/auth.js
Gronod 8c829f9651
Some checks failed
Build and Push Docker Image / build (push) Successful in 35s
CI / Security audit (push) Successful in 58s
CI / Tests & coverage (push) Failing after 1m5s
docs: audit and update all documentation to reflect current codebase
ARCHITECTURE.md:
- Node version: 18+ → 22 (Alpine)
- Tech stack: add helmet, express-rate-limit, cookie-parser, testing tools
- Directory structure: add server/app.js, verifyCsrf.js, tokenStore.js,
  sanitizeError.js, tests/, docs/, .gitea/workflows/, vitest.config.js
- §4.1: document app.js factory (createApp) vs index.js entry point;
  CSP nonce, rate limiters, CSRF middleware, trust proxy
- §4.2: add CSRF Required column; document verifyCsrf; fix auth note
- §4.3: add tokenStore.js and sanitizeError.js descriptions
- §6 Auth flow: add rememberMe, rate limiter, stable DeviceId, server-side
  token store, CSRF token issuance, correct cookie TTL (session/30d not 24h)
- §9 API: add csrfToken to login response, rememberMe field, 400/429 codes;
  add GET /api/auth/csrf endpoint; fix /me response; fix /logout CSRF note
- §11 Config: add DATA_DIR, COOKIE_SECRET, TRUST_PROXY, NODE_ENV; split
  into Core / Emby / Service Instances / Tuning sections
- §12 Deployment: update Dockerfile description to multi-stage node:22-alpine;
  add COOKIE_SECRET, TRUST_PROXY, named volume to compose example;
  add security hardening checklist; add CI/CD table

diagrams/seq-auth.puml:
- Add TokenStore participant
- Add rememberMe, CSRF token issuance, stable DeviceId note
- Add login rate limiter note
- Add GET /csrf refresh flow
- Add server-side token revocation on logout

diagrams/class-server.puml:
- Add app.js createApp() factory class
- Add verifyCsrf middleware class
- Add TokenStore and SanitizeError utility classes
- Update auth.js routes (add GET /csrf)
- Fix relationships: entry → appfn → routes

diagrams/component.puml:
- Add app.js factory component
- Add helmet, express-rate-limit components
- Add verifyCsrf middleware component
- Add tokenStore.js and sanitizeError.js utility components
- Fix wiring: entry → createApp() → mounts routes

Dockerfile:
- Fix stale comments referencing better-sqlite3 and SQLite

server/routes/auth.js:
- Fix stale comment: SQLite-backed → JSON file-backed
2026-05-17 08:05:08 +01:00

186 lines
6.7 KiB
JavaScript

const express = require('express');
const axios = require('axios');
const crypto = require('crypto');
const rateLimit = require('express-rate-limit');
const router = express.Router();
// Persistent JSON file-backed token store — survives restarts
const { storeToken, getToken, clearToken } = require('../utils/tokenStore');
// Read EMBY_URL at request time (not module load time) so the value
// can be overridden by environment variables set after the module loads.
const getEmbyUrl = () => process.env.EMBY_URL;
// Strict login limiter: 10 attempts per 15 min, then locked for the window.
// Set SKIP_RATE_LIMIT=1 in the test environment to prevent the limiter from
// interfering with integration tests (all requests come from 127.0.0.1).
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: process.env.SKIP_RATE_LIMIT ? Number.MAX_SAFE_INTEGER : 10,
standardHeaders: true,
legacyHeaders: false,
skipSuccessfulRequests: true, // only count failures toward the limit
message: { success: false, error: 'Too many login attempts, please try again later' }
});
// Authenticate user with Emby
router.post('/login', loginLimiter, async (req, res) => {
try {
const { username, password, rememberMe } = req.body;
// Input validation — reject obviously invalid inputs before hitting Emby
if (typeof username !== 'string' || username.trim().length === 0 || username.length > 128) {
return res.status(400).json({ success: false, error: 'Invalid username' });
}
if (typeof password !== 'string' || password.length === 0 || password.length > 256) {
return res.status(400).json({ success: false, error: 'Invalid password' });
}
console.log(`[Auth] Attempting login for user: ${username.trim()}`);
// Authenticate with Emby using a stable DeviceId derived from the username.
// Using a deterministic DeviceId causes Emby to reuse the existing session
// for this device rather than creating a new one on each login.
const stableDeviceId = 'sofarr-' + crypto.createHash('sha256').update(username.trim().toLowerCase()).digest('hex').slice(0, 16);
const authResponse = await axios.post(`${getEmbyUrl()}/Users/authenticatebyname`, {
Username: username.trim(),
Pw: password
}, {
headers: {
'X-Emby-Authorization': `MediaBrowser Client="sofarr", Device="sofarr", DeviceId="${stableDeviceId}", Version="1.0.0"`
}
});
const authData = authResponse.data;
// Get user info using the access token
const userResponse = await axios.get(`${getEmbyUrl()}/Users/${authData.User.Id || authData.User.id}`, {
headers: {
'X-MediaBrowser-Token': authData.AccessToken
}
});
const user = userResponse.data;
const isAdmin = !!(user.Policy && user.Policy.IsAdministrator);
console.log(`[Auth] Login successful for user: ${user.Name}, isAdmin: ${isAdmin}`);
// Store token server-side; it is never sent to the client.
storeToken(user.Id, authData.AccessToken);
// Set authentication cookie (signed when COOKIE_SECRET is set).
// rememberMe=true → persistent cookie, expires in 30 days
// rememberMe=false → session cookie, expires when browser closes
// secure is always true — the app should sit behind HTTPS in production;
// behind a reverse proxy set TRUST_PROXY=1 so req.secure works correctly.
const cookiePayload = JSON.stringify({ id: user.Id, name: user.Name, isAdmin });
const signed = !!process.env.COOKIE_SECRET;
const cookieOptions = {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
signed,
path: '/'
};
if (rememberMe) {
cookieOptions.maxAge = 30 * 24 * 60 * 60 * 1000; // 30 days
}
res.cookie('emby_user', cookiePayload, cookieOptions);
// Issue a CSRF token tied to this session so state-changing endpoints
// can validate the double-submit cookie pattern
const csrfToken = crypto.randomBytes(32).toString('hex');
res.cookie('csrf_token', csrfToken, {
httpOnly: false, // intentionally readable by JS for the double-submit pattern
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
path: '/'
});
res.json({
success: true,
user: { id: user.Id, name: user.Name, isAdmin },
csrfToken
});
} catch (error) {
console.error(`[Auth] Login failed:`, error.message);
res.status(401).json({
success: false,
error: 'Invalid username or password'
});
}
});
function parseSessionCookie(req) {
const signed = !!process.env.COOKIE_SECRET;
const raw = signed ? req.signedCookies.emby_user : req.cookies.emby_user;
if (!raw || raw === false) return null; // false = tampered signed cookie
try {
const u = JSON.parse(raw);
// Schema validation: require id (string), name (string), isAdmin (boolean)
if (typeof u.id !== 'string' || !u.id) return null;
if (typeof u.name !== 'string' || !u.name) return null;
if (typeof u.isAdmin !== 'boolean') u.isAdmin = !!u.isAdmin;
return u;
} catch {
return null;
}
}
// Get current authenticated user
router.get('/me', (req, res) => {
const user = parseSessionCookie(req);
if (!user) return res.json({ authenticated: false });
res.json({
authenticated: true,
user: { id: user.id, name: user.name, isAdmin: user.isAdmin }
});
});
// CSRF token refresh — lets the SPA get a new token without re-logging-in
// (e.g. after a page reload where the JS variable was lost)
router.get('/csrf', (req, res) => {
const csrfToken = crypto.randomBytes(32).toString('hex');
res.cookie('csrf_token', csrfToken, {
httpOnly: false,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
path: '/'
});
res.json({ csrfToken });
});
// Logout
router.post('/logout', async (req, res) => {
const user = parseSessionCookie(req);
if (user) {
const stored = getToken(user.id);
if (stored) {
try {
await axios.post(`${getEmbyUrl()}/Sessions/Logout`, {}, {
headers: { 'X-MediaBrowser-Token': stored.accessToken }
});
console.log(`[Auth] Revoked Emby token for user: ${user.name}`);
} catch (err) {
console.warn(`[Auth] Failed to revoke Emby token for ${user.name}:`, err.message);
}
clearToken(user.id);
}
}
res.clearCookie('emby_user', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
signed: !!process.env.COOKIE_SECRET,
path: '/'
});
res.clearCookie('csrf_token', {
httpOnly: false,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
path: '/'
});
res.json({ success: true });
});
module.exports = router;