feat(web): add the HTTP layer and Discord-backed sessions

Visitors sign in with Discord and inherit the very same access levels as the
slash commands, so there is no second permission model to keep in sync.

Writes require a header a cross-site form cannot forge, on top of the
`SameSite=Lax` cookie, and a bootstrap token opens the configuration wizard
alone for the case where no Discord application exists yet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
nocodeandClaude Opus 5 committed 2026-09-23 20:09:13 +02:00
1 parent 5abe713279
commit e03b184d68
7 files changed
+711

No files matched your search

+158
View File
@@ -0,0 +1,158 @@
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');
export const secureCookies = () => 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() }),
);
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() }));
}
/**
* 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;
const host = request.headers.host;
const allowed = new Set([env.web.publicUrl, `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])),
);