#7 isAdmin trusted from unsigned cookie: - isAdmin is derived server-side from Emby Policy at login time - Cookie is now signed (HMAC) when COOKIE_SECRET env var is set; Express rejects tampered signatures (signedCookies returns false) - dashboard.js /user-downloads and /status now use requireAuth middleware (req.user) instead of re-parsing cookie directly #8 cookie-parser used without signing secret: - cookieParser(COOKIE_SECRET) in index.js when env var is set - Hard-fails at startup in production if COOKIE_SECRET unset - Warns in development #9 Cookie JSON parsed without schema validation: - parseSessionCookie() in auth.js and requireAuth.js both validate: id (non-empty string), name (non-empty string), isAdmin (boolean) - Invalid/tampered cookies return null / 401 respectively
112 lines
3.4 KiB
JavaScript
112 lines
3.4 KiB
JavaScript
const express = require('express');
|
|
const axios = require('axios');
|
|
const rateLimit = require('express-rate-limit');
|
|
const router = express.Router();
|
|
|
|
const loginLimiter = rateLimit({
|
|
windowMs: 15 * 60 * 1000, // 15 minutes
|
|
max: 10,
|
|
standardHeaders: true,
|
|
legacyHeaders: false,
|
|
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 } = req.body;
|
|
|
|
console.log(`[Auth] Attempting login for user: ${username}`);
|
|
|
|
// Authenticate with Emby
|
|
const authResponse = await axios.post(`${EMBY_URL}/Users/authenticatebyname`, {
|
|
Username: username,
|
|
Pw: password
|
|
}, {
|
|
headers: {
|
|
'X-Emby-Authorization': `MediaBrowser Client="MediaDashboard", Device="Browser", DeviceId="dashboard-${Date.now()}", Version="1.0.0"`
|
|
}
|
|
});
|
|
|
|
const authData = authResponse.data;
|
|
|
|
// Get user info using the access token
|
|
const userResponse = await axios.get(`${EMBY_URL}/Users/${authData.User.Id || authData.User.id}`, {
|
|
headers: {
|
|
'X-MediaBrowser-Token': authData.AccessToken
|
|
}
|
|
});
|
|
|
|
const user = userResponse.data;
|
|
console.log(`[Auth] Login successful for user: ${user.Name}, isAdmin: ${!!(user.Policy && user.Policy.IsAdministrator)}`);
|
|
|
|
// Set authentication cookie.
|
|
// Note: token is intentionally excluded from the cookie — it is not needed client-side.
|
|
// Cookie is signed when COOKIE_SECRET is set (recommended in production).
|
|
const isAdmin = !!(user.Policy && user.Policy.IsAdministrator);
|
|
const cookiePayload = JSON.stringify({ id: user.Id, name: user.Name, isAdmin });
|
|
const signed = !!process.env.COOKIE_SECRET;
|
|
res.cookie('emby_user', cookiePayload, {
|
|
httpOnly: true,
|
|
secure: process.env.NODE_ENV === 'production',
|
|
sameSite: 'strict',
|
|
signed,
|
|
maxAge: 24 * 60 * 60 * 1000 // 24 hours
|
|
});
|
|
|
|
res.json({
|
|
success: true,
|
|
user: {
|
|
id: user.Id,
|
|
name: user.Name,
|
|
isAdmin: isAdmin
|
|
}
|
|
});
|
|
} 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 }
|
|
});
|
|
});
|
|
|
|
// Logout
|
|
router.post('/logout', (req, res) => {
|
|
res.clearCookie('emby_user', {
|
|
httpOnly: true,
|
|
secure: process.env.NODE_ENV === 'production',
|
|
sameSite: 'strict',
|
|
signed: !!process.env.COOKIE_SECRET
|
|
});
|
|
res.json({ success: true });
|
|
});
|
|
|
|
module.exports = router;
|