fix(security #13,#14): revoke Emby token on logout; stable DeviceId prevents unbounded sessions
#13 Logout doesn't revoke Emby token: - Added in-memory tokenStore (userId -> { accessToken }) - AccessToken stored server-side after successful login; never sent to client - POST /logout calls Emby POST /Sessions/Logout with the stored token before clearing it; failure is warned but does not block the local cookie clear #14 Unbounded Emby session creation per login: - DeviceId in the Emby auth request is now a stable SHA-256 hash of the lowercase username (sofarr-<16 hex chars>) - Emby treats the same DeviceId as the same device and reuses the existing session slot instead of creating a new one each login
This commit is contained in:
+48
-13
@@ -1,8 +1,28 @@
|
|||||||
const express = require('express');
|
const express = require('express');
|
||||||
const axios = require('axios');
|
const axios = require('axios');
|
||||||
|
const crypto = require('crypto');
|
||||||
const rateLimit = require('express-rate-limit');
|
const rateLimit = require('express-rate-limit');
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
|
const EMBY_URL = process.env.EMBY_URL;
|
||||||
|
|
||||||
|
// Server-side token store: userId -> { accessToken }
|
||||||
|
// Keeps AccessToken off the client; required for logout revocation.
|
||||||
|
const tokenStore = new Map();
|
||||||
|
|
||||||
|
function storeToken(userId, accessToken) {
|
||||||
|
tokenStore.set(userId, { accessToken });
|
||||||
|
}
|
||||||
|
|
||||||
|
function getToken(userId) {
|
||||||
|
return tokenStore.get(userId) || null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearToken(userId) {
|
||||||
|
tokenStore.delete(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
const loginLimiter = rateLimit({
|
const loginLimiter = rateLimit({
|
||||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||||
max: 10,
|
max: 10,
|
||||||
@@ -18,13 +38,16 @@ router.post('/login', loginLimiter, async (req, res) => {
|
|||||||
|
|
||||||
console.log(`[Auth] Attempting login for user: ${username}`);
|
console.log(`[Auth] Attempting login for user: ${username}`);
|
||||||
|
|
||||||
// Authenticate with Emby
|
// 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.toLowerCase()).digest('hex').slice(0, 16);
|
||||||
const authResponse = await axios.post(`${EMBY_URL}/Users/authenticatebyname`, {
|
const authResponse = await axios.post(`${EMBY_URL}/Users/authenticatebyname`, {
|
||||||
Username: username,
|
Username: username,
|
||||||
Pw: password
|
Pw: password
|
||||||
}, {
|
}, {
|
||||||
headers: {
|
headers: {
|
||||||
'X-Emby-Authorization': `MediaBrowser Client="MediaDashboard", Device="Browser", DeviceId="dashboard-${Date.now()}", Version="1.0.0"`
|
'X-Emby-Authorization': `MediaBrowser Client="sofarr", Device="sofarr", DeviceId="${stableDeviceId}", Version="1.0.0"`
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -38,12 +61,13 @@ router.post('/login', loginLimiter, async (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const user = userResponse.data;
|
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 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).
|
||||||
const cookiePayload = JSON.stringify({ id: user.Id, name: user.Name, isAdmin });
|
const cookiePayload = JSON.stringify({ id: user.Id, name: user.Name, isAdmin });
|
||||||
const signed = !!process.env.COOKIE_SECRET;
|
const signed = !!process.env.COOKIE_SECRET;
|
||||||
res.cookie('emby_user', cookiePayload, {
|
res.cookie('emby_user', cookiePayload, {
|
||||||
@@ -56,11 +80,7 @@ router.post('/login', loginLimiter, async (req, res) => {
|
|||||||
|
|
||||||
res.json({
|
res.json({
|
||||||
success: true,
|
success: true,
|
||||||
user: {
|
user: { id: user.Id, name: user.Name, isAdmin }
|
||||||
id: user.Id,
|
|
||||||
name: user.Name,
|
|
||||||
isAdmin: isAdmin
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error(`[Auth] Login failed:`, error.message);
|
console.error(`[Auth] Login failed:`, error.message);
|
||||||
@@ -98,7 +118,22 @@ router.get('/me', (req, res) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Logout
|
// Logout
|
||||||
router.post('/logout', (req, res) => {
|
router.post('/logout', async (req, res) => {
|
||||||
|
const user = parseSessionCookie(req);
|
||||||
|
if (user) {
|
||||||
|
const stored = getToken(user.id);
|
||||||
|
if (stored) {
|
||||||
|
try {
|
||||||
|
await axios.post(`${EMBY_URL}/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', {
|
res.clearCookie('emby_user', {
|
||||||
httpOnly: true,
|
httpOnly: true,
|
||||||
secure: process.env.NODE_ENV === 'production',
|
secure: process.env.NODE_ENV === 'production',
|
||||||
|
|||||||
Reference in New Issue
Block a user