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:
7 files changed
+711
No files matched your search
@@ -0,0 +1,114 @@
|
|||||||
|
import { ACCESS_LEVELS } from '../../config/constants.js';
|
||||||
|
import { env } from '../../config/env.js';
|
||||||
|
import { ExternalApiError } from '../../core/errors.js';
|
||||||
|
import { createLogger } from '../../core/logger.js';
|
||||||
|
|
||||||
|
const log = createLogger('web:oauth');
|
||||||
|
const DISCORD_API = 'https://discord.com/api/v10';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `identify` names the visitor, `guilds.members.read` reads their roles on the FWS
|
||||||
|
* guild so the dashboard can apply the very same access levels as the slash
|
||||||
|
* commands (M16-T02).
|
||||||
|
*/
|
||||||
|
const SCOPES = ['identify', 'guilds.members.read'];
|
||||||
|
|
||||||
|
export const redirectUri = () => `${env.web.publicUrl}/auth/callback`;
|
||||||
|
|
||||||
|
/** True when the OAuth2 login can actually run. */
|
||||||
|
export function isOauthConfigured() {
|
||||||
|
return Boolean(env.discord.clientId && env.web.oauthClientSecret && env.web.publicUrl);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function authorizeUrl(state) {
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
client_id: env.discord.clientId,
|
||||||
|
response_type: 'code',
|
||||||
|
redirect_uri: redirectUri(),
|
||||||
|
scope: SCOPES.join(' '),
|
||||||
|
state,
|
||||||
|
prompt: 'none',
|
||||||
|
});
|
||||||
|
return `https://discord.com/oauth2/authorize?${params}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function discordFetch(endpoint, options = {}) {
|
||||||
|
const response = await fetch(`${DISCORD_API}${endpoint}`, {
|
||||||
|
...options,
|
||||||
|
signal: AbortSignal.timeout(10_000),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = new ExternalApiError('discord', `${endpoint} failed with ${response.status}`);
|
||||||
|
error.status = response.status;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
return response.status === 204 ? null : response.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function exchangeCode(code) {
|
||||||
|
const body = new URLSearchParams({
|
||||||
|
client_id: env.discord.clientId,
|
||||||
|
client_secret: env.web.oauthClientSecret,
|
||||||
|
grant_type: 'authorization_code',
|
||||||
|
code,
|
||||||
|
redirect_uri: redirectUri(),
|
||||||
|
});
|
||||||
|
|
||||||
|
return discordFetch('/oauth2/token', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
|
body,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Best effort cleanup: the dashboard never needs the user token again. */
|
||||||
|
export async function revokeToken(accessToken) {
|
||||||
|
const body = new URLSearchParams({
|
||||||
|
client_id: env.discord.clientId,
|
||||||
|
client_secret: env.web.oauthClientSecret,
|
||||||
|
token: accessToken,
|
||||||
|
});
|
||||||
|
await discordFetch('/oauth2/token/revoke', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||||
|
body,
|
||||||
|
}).catch((error) => log.debug('Token revocation failed', error));
|
||||||
|
}
|
||||||
|
|
||||||
|
export function fetchUser(accessToken) {
|
||||||
|
return discordFetch('/users/@me', { headers: { Authorization: `Bearer ${accessToken}` } });
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returns null when the visitor is not a member of the guild. */
|
||||||
|
export async function fetchGuildMember(accessToken, guildId) {
|
||||||
|
try {
|
||||||
|
return await discordFetch(`/users/@me/guilds/${guildId}/member`, {
|
||||||
|
headers: { Authorization: `Bearer ${accessToken}` },
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (error.status === 404 || error.status === 403) return null;
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Same ladder as `core/permissions.js`, applied to the raw role ids returned by
|
||||||
|
* the OAuth2 member endpoint (which has no discord.js `GuildMember` to offer).
|
||||||
|
*/
|
||||||
|
export function resolveAccessLevel({ member, userId, guildOwnerId, roles = env.roles }) {
|
||||||
|
if (userId && guildOwnerId && userId === guildOwnerId) return ACCESS_LEVELS.OWNER;
|
||||||
|
if (!member) return null;
|
||||||
|
|
||||||
|
const owned = new Set(member.roles ?? []);
|
||||||
|
const has = (roleId) => Boolean(roleId) && owned.has(roleId);
|
||||||
|
if (has(roles.owner)) return ACCESS_LEVELS.OWNER;
|
||||||
|
if (has(roles.dev)) return ACCESS_LEVELS.DEV;
|
||||||
|
if (has(roles.staff)) return ACCESS_LEVELS.STAFF;
|
||||||
|
return ACCESS_LEVELS.USER;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function avatarUrl(user) {
|
||||||
|
if (!user?.id) return null;
|
||||||
|
if (!user.avatar) return `https://cdn.discordapp.com/embed/avatars/${(BigInt(user.id) >> 22n) % 6n}.png`;
|
||||||
|
return `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png?size=128`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js';
|
||||||
|
import { forbidden, unauthorized } from '../http.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Route level access control (M16-T03).
|
||||||
|
*
|
||||||
|
* A route declares `{ access: ACCESS_LEVELS.DEV }`. Two exceptions exist:
|
||||||
|
* - `public: true` skips authentication entirely (login page, health check);
|
||||||
|
* - `setup: true` marks the routes a bootstrap session may reach. Bootstrap
|
||||||
|
* sessions exist before Discord is configured, so they are deliberately
|
||||||
|
* confined to the configuration wizard.
|
||||||
|
*/
|
||||||
|
export function authorize(actor, options = {}) {
|
||||||
|
if (options.public) return;
|
||||||
|
|
||||||
|
if (!actor) throw unauthorized();
|
||||||
|
|
||||||
|
if (actor.source === 'setup' && !options.setup) {
|
||||||
|
throw forbidden("Session d'amorçage : seule la configuration est accessible");
|
||||||
|
}
|
||||||
|
|
||||||
|
const required = options.access ?? ACCESS_LEVELS.OWNER;
|
||||||
|
if (actor.accessLevel < required) {
|
||||||
|
throw forbidden(`Niveau ${ACCESS_LABELS[required]} requis pour cette action`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function canReach(accessLevel, required) {
|
||||||
|
return accessLevel >= required;
|
||||||
|
}
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
import { randomBytes } from 'node:crypto';
|
||||||
|
import { ACCESS_LABELS, ACCESS_LEVELS } from '../../config/constants.js';
|
||||||
|
import { env } from '../../config/env.js';
|
||||||
|
import { createLogger } from '../../core/logger.js';
|
||||||
|
import { logEvent } from '../../database/repositories/event-log-repository.js';
|
||||||
|
import { appendCookie, forbidden, parseCookies, redirect, serializeCookie } from '../http.js';
|
||||||
|
import { hasSetupToken, isSetupTokenValid } from '../setup-state.js';
|
||||||
|
import {
|
||||||
|
authorizeUrl,
|
||||||
|
avatarUrl,
|
||||||
|
exchangeCode,
|
||||||
|
fetchGuildMember,
|
||||||
|
fetchUser,
|
||||||
|
isOauthConfigured,
|
||||||
|
resolveAccessLevel,
|
||||||
|
revokeToken,
|
||||||
|
} from './discord-oauth.js';
|
||||||
|
import { STATE_COOKIE, closeSession, openSession, secureCookies, signState, verifyState } from './session.js';
|
||||||
|
|
||||||
|
const log = createLogger('web:auth');
|
||||||
|
|
||||||
|
/** Registers the login, callback, logout and identity routes (M16-T02). */
|
||||||
|
export function registerAuthRoutes(router) {
|
||||||
|
router.get(
|
||||||
|
'/api/auth/config',
|
||||||
|
({ context }) => ({
|
||||||
|
oauthConfigured: isOauthConfigured(),
|
||||||
|
setupAvailable: hasSetupToken(),
|
||||||
|
setupOnly: context.setupOnly,
|
||||||
|
guildConfigured: Boolean(env.discord.guildId),
|
||||||
|
loginUrl: '/auth/login',
|
||||||
|
}),
|
||||||
|
{ public: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
'/auth/login',
|
||||||
|
({ response }) => {
|
||||||
|
if (!isOauthConfigured()) {
|
||||||
|
redirect(response, '/#/login?error=oauth-not-configured');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const state = signState(randomBytes(16).toString('base64url'));
|
||||||
|
appendCookie(response, serializeCookie(STATE_COOKIE, state, { maxAge: 600, secure: secureCookies() }));
|
||||||
|
redirect(response, authorizeUrl(state));
|
||||||
|
},
|
||||||
|
{ public: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
'/auth/callback',
|
||||||
|
async ({ request, response, query, context }) => {
|
||||||
|
const failure = (reason) => redirect(response, `/#/login?error=${reason}`);
|
||||||
|
|
||||||
|
if (query.get('error')) return failure(query.get('error'));
|
||||||
|
|
||||||
|
const state = query.get('state');
|
||||||
|
const expected = parseCookies(request.headers.cookie)[STATE_COOKIE];
|
||||||
|
appendCookie(response, serializeCookie(STATE_COOKIE, '', { maxAge: 0, secure: secureCookies() }));
|
||||||
|
if (!state || state !== expected || !verifyState(state)) return failure('state-mismatch');
|
||||||
|
|
||||||
|
const code = query.get('code');
|
||||||
|
if (!code) return failure('missing-code');
|
||||||
|
|
||||||
|
let grant;
|
||||||
|
try {
|
||||||
|
grant = await exchangeCode(code);
|
||||||
|
} catch (error) {
|
||||||
|
log.warn('OAuth2 code exchange failed', error);
|
||||||
|
return failure('exchange-failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
const user = await fetchUser(grant.access_token);
|
||||||
|
const member = await fetchGuildMember(grant.access_token, env.discord.guildId);
|
||||||
|
await revokeToken(grant.access_token);
|
||||||
|
|
||||||
|
const guildOwnerId = context.client?.guilds?.cache?.get(env.discord.guildId)?.ownerId ?? null;
|
||||||
|
const accessLevel = resolveAccessLevel({ member, userId: user.id, guildOwnerId });
|
||||||
|
|
||||||
|
if (accessLevel === null) {
|
||||||
|
log.warn('Login refused, user is not a member of the guild', { userId: user.id });
|
||||||
|
return failure('not-a-member');
|
||||||
|
}
|
||||||
|
if (accessLevel < ACCESS_LEVELS.STAFF) {
|
||||||
|
log.warn('Login refused, insufficient level', { userId: user.id, accessLevel });
|
||||||
|
return failure('insufficient-level');
|
||||||
|
}
|
||||||
|
|
||||||
|
openSession(request, response, {
|
||||||
|
user: {
|
||||||
|
id: user.id,
|
||||||
|
username: user.username,
|
||||||
|
displayName: member?.nick || user.global_name || user.username,
|
||||||
|
avatar: avatarUrl(user),
|
||||||
|
},
|
||||||
|
accessLevel,
|
||||||
|
});
|
||||||
|
logEvent({
|
||||||
|
guildId: env.discord.guildId || null,
|
||||||
|
type: 'web.login',
|
||||||
|
actorId: user.id,
|
||||||
|
payload: { accessLevel },
|
||||||
|
});
|
||||||
|
redirect(response, '/#/');
|
||||||
|
},
|
||||||
|
{ public: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bootstrap login. Only opens a session confined to the configuration wizard,
|
||||||
|
* never a full dashboard session (M16-T09).
|
||||||
|
*/
|
||||||
|
router.post(
|
||||||
|
'/api/auth/setup',
|
||||||
|
({ request, response, body }) => {
|
||||||
|
if (!hasSetupToken()) throw forbidden("Aucun jeton d'amorçage n'est configuré");
|
||||||
|
if (!isSetupTokenValid(body.token)) throw forbidden("Jeton d'amorçage invalide");
|
||||||
|
|
||||||
|
openSession(request, response, {
|
||||||
|
user: { id: null, username: 'setup', displayName: 'Assistant de configuration' },
|
||||||
|
accessLevel: ACCESS_LEVELS.OWNER,
|
||||||
|
source: 'setup',
|
||||||
|
});
|
||||||
|
return { ok: true, source: 'setup' };
|
||||||
|
},
|
||||||
|
{ public: true },
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post('/api/auth/logout', ({ request, response }) => {
|
||||||
|
closeSession(request, response);
|
||||||
|
return { ok: true };
|
||||||
|
});
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
'/api/me',
|
||||||
|
({ actor }) => {
|
||||||
|
if (!actor) return { authenticated: false };
|
||||||
|
return {
|
||||||
|
authenticated: true,
|
||||||
|
userId: actor.userId,
|
||||||
|
username: actor.username,
|
||||||
|
displayName: actor.displayName,
|
||||||
|
avatar: actor.avatar,
|
||||||
|
accessLevel: actor.accessLevel,
|
||||||
|
accessLabel: ACCESS_LABELS[actor.accessLevel],
|
||||||
|
source: actor.source,
|
||||||
|
kind: actor.kind,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
{ public: true },
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -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])),
|
||||||
|
);
|
||||||
+162
@@ -0,0 +1,162 @@
|
|||||||
|
import { createReadStream } from 'node:fs';
|
||||||
|
import { stat } from 'node:fs/promises';
|
||||||
|
import path from 'node:path';
|
||||||
|
|
||||||
|
/** Request and response helpers shared by every dashboard route (M16-T01). */
|
||||||
|
|
||||||
|
const MAX_BODY_BYTES = 2 * 1024 * 1024;
|
||||||
|
|
||||||
|
const MIME_TYPES = Object.freeze({
|
||||||
|
'.html': 'text/html; charset=utf-8',
|
||||||
|
'.css': 'text/css; charset=utf-8',
|
||||||
|
'.js': 'text/javascript; charset=utf-8',
|
||||||
|
'.json': 'application/json; charset=utf-8',
|
||||||
|
'.svg': 'image/svg+xml',
|
||||||
|
'.png': 'image/png',
|
||||||
|
'.jpg': 'image/jpeg',
|
||||||
|
'.webp': 'image/webp',
|
||||||
|
'.ico': 'image/x-icon',
|
||||||
|
'.woff2': 'font/woff2',
|
||||||
|
'.txt': 'text/plain; charset=utf-8',
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sent on every response. The dashboard ships no third-party asset, so the policy
|
||||||
|
* can stay restricted to `self` without breaking anything.
|
||||||
|
*/
|
||||||
|
const SECURITY_HEADERS = Object.freeze({
|
||||||
|
'X-Content-Type-Options': 'nosniff',
|
||||||
|
'X-Frame-Options': 'DENY',
|
||||||
|
'Referrer-Policy': 'same-origin',
|
||||||
|
'Content-Security-Policy':
|
||||||
|
"default-src 'self'; img-src 'self' data: https://cdn.discordapp.com; " +
|
||||||
|
"style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self'; " +
|
||||||
|
"frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
||||||
|
});
|
||||||
|
|
||||||
|
export class HttpError extends Error {
|
||||||
|
constructor(status, message, details = null) {
|
||||||
|
super(message);
|
||||||
|
this.name = 'HttpError';
|
||||||
|
this.status = status;
|
||||||
|
this.details = details;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export const badRequest = (message, details) => new HttpError(400, message, details);
|
||||||
|
export const unauthorized = (message = 'Authentification requise') => new HttpError(401, message);
|
||||||
|
export const forbidden = (message = 'Accès refusé') => new HttpError(403, message);
|
||||||
|
export const notFound = (message = 'Ressource introuvable') => new HttpError(404, message);
|
||||||
|
|
||||||
|
export function sendJson(response, status, payload) {
|
||||||
|
const body = JSON.stringify(payload ?? null);
|
||||||
|
response.writeHead(status, {
|
||||||
|
...SECURITY_HEADERS,
|
||||||
|
'Content-Type': 'application/json; charset=utf-8',
|
||||||
|
'Content-Length': Buffer.byteLength(body),
|
||||||
|
'Cache-Control': 'no-store',
|
||||||
|
});
|
||||||
|
response.end(body);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function sendEmpty(response, status, headers = {}) {
|
||||||
|
response.writeHead(status, { ...SECURITY_HEADERS, ...headers }).end();
|
||||||
|
}
|
||||||
|
|
||||||
|
export function redirect(response, location, headers = {}) {
|
||||||
|
sendEmpty(response, 302, { ...headers, Location: location });
|
||||||
|
}
|
||||||
|
|
||||||
|
export function readRawBody(request, limit = MAX_BODY_BYTES) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const chunks = [];
|
||||||
|
let size = 0;
|
||||||
|
request.on('data', (chunk) => {
|
||||||
|
size += chunk.length;
|
||||||
|
if (size > limit) {
|
||||||
|
reject(new HttpError(413, 'Corps de requête trop volumineux'));
|
||||||
|
request.destroy();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
chunks.push(chunk);
|
||||||
|
});
|
||||||
|
request.on('end', () => resolve(Buffer.concat(chunks)));
|
||||||
|
request.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function readJsonBody(request) {
|
||||||
|
const raw = await readRawBody(request);
|
||||||
|
if (raw.length === 0) return {};
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(raw.toString('utf8'));
|
||||||
|
if (parsed === null || typeof parsed !== 'object') throw new Error('not an object');
|
||||||
|
return parsed;
|
||||||
|
} catch {
|
||||||
|
throw badRequest('Corps JSON invalide');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export function parseCookies(header = '') {
|
||||||
|
const jar = {};
|
||||||
|
for (const part of header.split(';')) {
|
||||||
|
const index = part.indexOf('=');
|
||||||
|
if (index < 0) continue;
|
||||||
|
jar[part.slice(0, index).trim()] = decodeURIComponent(part.slice(index + 1).trim());
|
||||||
|
}
|
||||||
|
return jar;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function serializeCookie(name, value, { maxAge, secure = false, path: cookiePath = '/' } = {}) {
|
||||||
|
const parts = [`${name}=${encodeURIComponent(value)}`, `Path=${cookiePath}`, 'HttpOnly', 'SameSite=Lax'];
|
||||||
|
if (secure) parts.push('Secure');
|
||||||
|
if (maxAge !== undefined) parts.push(`Max-Age=${Math.floor(maxAge)}`);
|
||||||
|
return parts.join('; ');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Appends a cookie without dropping the ones already queued on the response. */
|
||||||
|
export function appendCookie(response, cookie) {
|
||||||
|
const existing = response.getHeader('Set-Cookie');
|
||||||
|
const list = existing ? [].concat(existing) : [];
|
||||||
|
response.setHeader('Set-Cookie', [...list, cookie]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Client address, trusting `X-Forwarded-For` only for its left-most entry. */
|
||||||
|
export function clientIp(request) {
|
||||||
|
const forwarded = request.headers['x-forwarded-for'];
|
||||||
|
if (typeof forwarded === 'string' && forwarded.length > 0) return forwarded.split(',')[0].trim();
|
||||||
|
return request.socket.remoteAddress ?? '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Serves a file from `root`, refusing anything that escapes it.
|
||||||
|
* Returns false when the file does not exist, so the caller can fall back.
|
||||||
|
*/
|
||||||
|
export async function sendStatic(response, root, requestPath, { fallback = null } = {}) {
|
||||||
|
const relative = decodeURIComponent(requestPath).replace(/^\/+/, '');
|
||||||
|
const resolved = path.resolve(root, relative || 'index.html');
|
||||||
|
const target = resolved.startsWith(path.resolve(root)) ? resolved : null;
|
||||||
|
|
||||||
|
let file = target;
|
||||||
|
if (file) {
|
||||||
|
const info = await stat(file).catch(() => null);
|
||||||
|
if (info?.isDirectory()) file = path.join(file, 'index.html');
|
||||||
|
else if (!info?.isFile()) file = null;
|
||||||
|
}
|
||||||
|
if (!file && fallback) file = path.resolve(root, fallback);
|
||||||
|
if (!file) return false;
|
||||||
|
|
||||||
|
const info = await stat(file).catch(() => null);
|
||||||
|
if (!info?.isFile()) return false;
|
||||||
|
|
||||||
|
const extension = path.extname(file).toLowerCase();
|
||||||
|
response.writeHead(200, {
|
||||||
|
...SECURITY_HEADERS,
|
||||||
|
'Content-Type': MIME_TYPES[extension] ?? 'application/octet-stream',
|
||||||
|
'Content-Length': info.size,
|
||||||
|
// The SPA shell must never be cached, its modules are revalidated on each load.
|
||||||
|
'Cache-Control': extension === '.html' ? 'no-store' : 'no-cache',
|
||||||
|
});
|
||||||
|
createReadStream(file).pipe(response);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { HttpError, notFound } from './http.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Minimal router: `/api/repositories/:owner/:repo` style patterns, no dependency (M16-T01).
|
||||||
|
* A trailing `*` captures the rest of the path under `params.rest`.
|
||||||
|
*/
|
||||||
|
|
||||||
|
function compile(pattern) {
|
||||||
|
const segments = pattern.split('/').filter(Boolean);
|
||||||
|
return { segments, pattern };
|
||||||
|
}
|
||||||
|
|
||||||
|
function match(route, segments) {
|
||||||
|
const params = {};
|
||||||
|
for (const [index, expected] of route.segments.entries()) {
|
||||||
|
if (expected === '*') {
|
||||||
|
params.rest = segments.slice(index).join('/');
|
||||||
|
return params;
|
||||||
|
}
|
||||||
|
const actual = segments[index];
|
||||||
|
if (actual === undefined) return null;
|
||||||
|
if (expected.startsWith(':')) params[expected.slice(1)] = decodeURIComponent(actual);
|
||||||
|
else if (expected !== actual) return null;
|
||||||
|
}
|
||||||
|
return segments.length === route.segments.length ? params : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createRouter() {
|
||||||
|
const routes = [];
|
||||||
|
|
||||||
|
const add = (method, pattern, handler, options = {}) => {
|
||||||
|
routes.push({ method, ...compile(pattern), handler, options });
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
get: (pattern, handler, options) => add('GET', pattern, handler, options),
|
||||||
|
post: (pattern, handler, options) => add('POST', pattern, handler, options),
|
||||||
|
put: (pattern, handler, options) => add('PUT', pattern, handler, options),
|
||||||
|
patch: (pattern, handler, options) => add('PATCH', pattern, handler, options),
|
||||||
|
delete: (pattern, handler, options) => add('DELETE', pattern, handler, options),
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Finds the handler for a request.
|
||||||
|
* Throws 405 when the path exists under another method, which is easier to
|
||||||
|
* debug from the browser console than a plain 404.
|
||||||
|
*/
|
||||||
|
resolve(method, pathname) {
|
||||||
|
const segments = pathname.split('/').filter(Boolean);
|
||||||
|
let pathMatched = false;
|
||||||
|
|
||||||
|
for (const route of routes) {
|
||||||
|
const params = match(route, segments);
|
||||||
|
if (!params) continue;
|
||||||
|
pathMatched = true;
|
||||||
|
if (route.method === method) return { ...route, params };
|
||||||
|
}
|
||||||
|
|
||||||
|
throw pathMatched ? new HttpError(405, `Méthode ${method} non autorisée ici`) : notFound();
|
||||||
|
},
|
||||||
|
|
||||||
|
list: () => routes.map((route) => `${route.method} ${route.pattern}`),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
import { randomBytes, timingSafeEqual } from 'node:crypto';
|
||||||
|
import { env } from '../config/env.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bootstrap access to the configuration wizard (M16-T09).
|
||||||
|
*
|
||||||
|
* Before `.env` exists there is no Discord application to log in with, so the
|
||||||
|
* wizard accepts a single shared token: either `WEB_SETUP_TOKEN`, or one
|
||||||
|
* generated for the lifetime of `npm run setup` and printed in the console.
|
||||||
|
*/
|
||||||
|
|
||||||
|
let runtimeToken = null;
|
||||||
|
|
||||||
|
export function generateRuntimeSetupToken() {
|
||||||
|
runtimeToken = randomBytes(24).toString('base64url');
|
||||||
|
return runtimeToken;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasSetupToken() {
|
||||||
|
return Boolean(env.web.setupToken || runtimeToken);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isSetupTokenValid(candidate) {
|
||||||
|
const value = String(candidate ?? '');
|
||||||
|
if (value.length === 0) return false;
|
||||||
|
|
||||||
|
return [env.web.setupToken, runtimeToken].filter(Boolean).some((expected) => {
|
||||||
|
const a = Buffer.from(expected);
|
||||||
|
const b = Buffer.from(value);
|
||||||
|
return a.length === b.length && timingSafeEqual(a, b);
|
||||||
|
});
|
||||||
|
}
|
||||||
Reference in new issue
Block a user