Files
FWS-DiscordBot/src/web/auth/session.js
T
nocodeandClaude Opus 5 20ff701430 fix(web): derive the OAuth2 redirect from the address actually used
`WEB_PUBLIC_URL` was the only source of the `redirect_uri`, so a hosting
panel or a proxy publishing the dashboard on another port produced a link
Discord refuses, with nothing on screen pointing at the port mismatch.

The browser's own origin is what Discord compares against, so the redirect
now comes from the request, honouring `X-Forwarded-Host` and
`X-Forwarded-Proto` when a proxy sits in front. `WEB_PUBLIC_URL` stays as
the fallback for links built outside a request, and the sign-in page prints
the exact value to declare in the portal.

The `Secure` cookie flag follows the same rule: announcing HTTPS in the
configuration while serving plain HTTP made the browser drop the session.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 20:12:44 +02:00

184 lines
6.1 KiB
JavaScript

import { createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
import { ACCESS_LEVELS } from '../../config/constants.js';
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import {
createSession,
deleteSession,
getLiveApiTokenByHash,
getLiveSessionByHash,
purgeExpiredSessions,
touchApiToken,
touchSession,
} from '../../database/repositories/web-session-repository.js';
import { appendCookie, clientIp, forbidden, parseCookies, serializeCookie } from '../http.js';
const log = createLogger('web:auth');
export const SESSION_COOKIE = 'fws_session';
export const STATE_COOKIE = 'fws_oauth_state';
/**
* Peppers the session tokens. Without `WEB_SESSION_SECRET` a random key is used,
* which keeps the dashboard usable but logs everyone out on restart.
*/
const pepper = (() => {
if (env.web.sessionSecret) return env.web.sessionSecret;
log.warn('WEB_SESSION_SECRET is not set: sessions will be dropped on every restart');
return randomBytes(32).toString('hex');
})();
const hash = (value) => createHmac('sha256', pepper).update(value).digest('hex');
/**
* A `Secure` cookie is dropped by the browser over plain HTTP, so the flag has
* to follow the scheme the visitor actually used rather than what the
* configuration announces.
*/
export const secureCookies = (request) => {
const forwarded = String(request?.headers?.['x-forwarded-proto'] ?? '')
.split(',')[0]
.trim();
if (forwarded) return forwarded === 'https';
if (request?.socket?.encrypted) return true;
return env.web.publicUrl.startsWith('https://');
};
export function issueToken() {
return randomBytes(32).toString('base64url');
}
/** Signs the OAuth2 `state` so the callback can prove it started the flow. */
export function signState(value) {
return `${value}.${createHmac('sha256', pepper).update(value).digest('base64url')}`;
}
export function verifyState(signed) {
const separator = String(signed ?? '').lastIndexOf('.');
if (separator < 0) return null;
const value = signed.slice(0, separator);
const expected = Buffer.from(createHmac('sha256', pepper).update(value).digest('base64url'));
const received = Buffer.from(signed.slice(separator + 1));
if (expected.length !== received.length || !timingSafeEqual(expected, received)) return null;
return value;
}
export function openSession(request, response, { user = {}, accessLevel, source = 'discord' }) {
purgeExpiredSessions();
const token = issueToken();
const ttlSeconds = Math.max(1, env.web.sessionTtlHours) * 3600;
const expiresAt = new Date(Date.now() + ttlSeconds * 1000).toISOString().replace('T', ' ').slice(0, 19);
const session = createSession({
id: randomUUID(),
tokenHash: hash(token),
userId: user.id ?? null,
username: user.username ?? null,
displayName: user.displayName ?? user.global_name ?? user.username ?? null,
avatar: user.avatar ?? null,
accessLevel,
source,
ip: clientIp(request),
userAgent: String(request.headers['user-agent'] ?? '').slice(0, 255),
expiresAt,
});
appendCookie(
response,
serializeCookie(SESSION_COOKIE, token, { maxAge: ttlSeconds, secure: secureCookies(request) }),
);
log.info('Dashboard session opened', { userId: session.user_id, source, accessLevel });
return session;
}
export function closeSession(request, response) {
const token = parseCookies(request.headers.cookie)[SESSION_COOKIE];
const session = token ? getLiveSessionByHash(hash(token)) : null;
if (session) deleteSession(session.id);
appendCookie(response, serializeCookie(SESSION_COOKIE, '', { maxAge: 0, secure: secureCookies(request) }));
}
/**
* Identifies the caller from its session cookie or its `Authorization: Bearer` token.
* Returns null for anonymous requests, the route guard decides what to do with it.
*/
export function authenticate(request) {
const token = parseCookies(request.headers.cookie)[SESSION_COOKIE];
if (token) {
const session = getLiveSessionByHash(hash(token));
if (session) {
touchSession(session.id);
return {
kind: 'session',
sessionId: session.id,
userId: session.user_id,
username: session.username,
displayName: session.display_name,
avatar: session.avatar,
accessLevel: session.access_level,
source: session.source,
};
}
}
const header = String(request.headers.authorization ?? '');
if (header.startsWith('Bearer ')) {
const apiToken = getLiveApiTokenByHash(hash(header.slice(7).trim()));
if (apiToken) {
touchApiToken(apiToken.id);
return {
kind: 'api-token',
userId: apiToken.created_by,
username: apiToken.name,
displayName: apiToken.name,
accessLevel: apiToken.access_level,
source: 'token',
};
}
}
return null;
}
export const hashToken = hash;
/**
* Blocks cross-site writes. Cookies are `SameSite=Lax`, so a cross-origin POST
* cannot carry them; the custom header adds a second barrier that a form post
* cannot forge, and the `Origin` check covers the rest (M16-T02).
*/
export function assertSameOrigin(request, actor) {
if (request.method === 'GET' || request.method === 'HEAD') return;
if (actor?.kind === 'api-token') return;
if (request.headers['x-requested-with'] !== 'fws-dashboard') {
throw forbidden('Requête rejetée : en-tête X-Requested-With manquant');
}
const origin = request.headers.origin;
if (!origin) return;
// The host the visitor used is what the browser puts in `Origin`; behind a
// proxy that is the forwarded one, not the socket's.
const hosts = [request.headers['x-forwarded-host'], request.headers.host]
.map((value) =>
String(value ?? '')
.split(',')[0]
.trim(),
)
.filter(Boolean);
const allowed = new Set([
env.web.publicUrl,
...hosts.flatMap((host) => [`http://${host}`, `https://${host}`]),
]);
if (!allowed.has(origin.replace(/\/+$/, ''))) {
throw forbidden('Requête rejetée : origine inattendue');
}
}
export const LEVEL_NAMES = Object.freeze(
Object.fromEntries(Object.entries(ACCESS_LEVELS).map(([name, value]) => [value, name])),
);