Files
FWS-DiscordBot/src/web/server.js
T
nocodeandClaude Opus 5 405692f228 fix(web): give static assets a validator caches can check
The front-end was served with `no-cache` but no `ETag` and no
`Last-Modified`, so a cache had nothing to revalidate against and could keep
handing out modules older than the API they talk to — which surfaces as a
cryptic error in a view rather than as anything resembling a stale cache.

Assets now carry both, and an unchanged file answers 304.

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

181 lines
6.9 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { createServer } from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { env } from '../config/env.js';
import { ExternalApiError, PermissionDeniedError, UserFacingError } from '../core/errors.js';
import { createLogger } from '../core/logger.js';
import { handleGiteaWebhook } from '../webhooks/gitea-webhook.js';
import { registerApiRoutes } from './api/index.js';
import { authenticate, assertSameOrigin } from './auth/session.js';
import { authorize } from './auth/guard.js';
import { broadcast, closeEventStreams, topicForPath } from './events.js';
import { HttpError, readJsonBody, readRawBody, sendEmpty, sendJson, sendStatic } from './http.js';
import { createRouter } from './router.js';
import { seedWiki } from './services/wiki-seed.js';
/** HTTP server of the dashboard (M16-T01). */
const log = createLogger('web');
const publicDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public');
/** Sliding window per client address, reset every minute. */
function createRateLimiter(limit) {
const hits = new Map();
let windowStart = Date.now();
return (key) => {
const now = Date.now();
if (now - windowStart >= 60_000) {
hits.clear();
windowStart = now;
}
const count = (hits.get(key) ?? 0) + 1;
hits.set(key, count);
return count <= limit;
};
}
function statusOf(error) {
if (error instanceof HttpError) return error.status;
if (error instanceof PermissionDeniedError) return 403;
if (error instanceof UserFacingError) return 400;
if (error instanceof ExternalApiError) return 502;
return 500;
}
/**
* Builds the request handler. Exported on its own so the tests can drive it
* without opening a socket.
*/
export function createHandler({ client = null, setupOnly = false, startedAt = Date.now() } = {}) {
const router = registerApiRoutes(createRouter(), { setupOnly });
const context = { client, setupOnly, startedAt };
const allowWithinRate = createRateLimiter(env.web.rateLimitPerMinute);
// The webhook shares the port when both servers are configured on it.
const sharesWebhookPort = env.webhook.enabled && env.webhook.port === env.web.port;
return async function handle(request, response) {
const url = new URL(request.url, `http://${request.headers.host ?? 'localhost'}`);
const pathname = url.pathname;
if (sharesWebhookPort && request.method === 'POST' && pathname === env.webhook.path) {
try {
const rawBody = await readRawBody(request);
response.writeHead(await handleGiteaWebhook(client, request.headers, rawBody)).end();
} catch (error) {
log.error('Webhook handling failed', error);
response.writeHead(500).end();
}
return;
}
const isApi = pathname.startsWith('/api/') || pathname.startsWith('/auth/');
if (!isApi) {
// The wiki is a separate public page: it must never fall back to the
// dashboard shell, which would send a visitor to a login screen.
const fallback = pathname === '/wiki' || pathname.startsWith('/wiki/') ? 'wiki.html' : 'index.html';
const served = await sendStatic(response, publicDir, pathname, { fallback, request });
if (!served) sendEmpty(response, 404);
return;
}
if (!allowWithinRate(request.socket.remoteAddress ?? 'unknown')) {
sendJson(response, 429, { error: 'Trop de requêtes, réessaie dans une minute.' });
return;
}
try {
const route = router.resolve(request.method, pathname);
const actor = authenticate(request);
assertSameOrigin(request, actor);
authorize(actor, route.options);
const body = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(request.method)
? await readJsonBody(request)
: {};
const result = await route.handler({
request,
response,
params: route.params,
query: url.searchParams,
body,
actor,
context,
});
// A handler that wrote the response itself (a redirect, an event stream)
// returns nothing.
if (!response.headersSent) sendJson(response, 200, result ?? { ok: true });
// Announce the change only once it has gone through, so a dashboard never
// refreshes on a write that was rejected.
if (request.method !== 'GET') {
broadcast(topicForPath(pathname), { path: pathname, method: request.method });
}
} catch (error) {
const status = statusOf(error);
if (status >= 500) log.error(`${request.method} ${pathname} failed`, error);
else log.debug(`${request.method} ${pathname} rejected with ${status}`, { message: error.message });
if (!response.headersSent) {
sendJson(response, status, {
error: status >= 500 ? 'Une erreur interne est survenue.' : error.message,
...(error.details && { details: error.details }),
});
}
}
};
}
export function startWebServer({ client = null, setupOnly = false } = {}) {
// A bot that processes personal data owes its users a notice, so the legal
// pages are created before the site answers its first request.
try {
seedWiki();
} catch (error) {
log.warn('Could not seed the wiki', error);
}
const server = createServer(createHandler({ client, setupOnly, startedAt: Date.now() }));
server.listen(env.web.port, env.web.host, () => {
const url = env.web.publicUrl || `http://${env.web.host}:${env.web.port}`;
log.info(`Dashboard listening on ${env.web.host}:${env.web.port}`, { url, setupOnly });
// Inside a container, binding a port that is not published succeeds and is
// still unreachable from outside, which looks exactly like a crash from the
// browser. Say it once, here, where the port is known.
if (env.web.host === '0.0.0.0') {
log.info(
`Le tableau de bord écoute sur le port ${env.web.port}. Dans un conteneur ou sur un panel, ` +
'ce port doit aussi faire partie des allocations publiées, sinon il reste injoignable de l’extérieur.',
);
}
});
server.on('error', (error) => {
const causes = {
EADDRINUSE: `le port ${env.web.port} est déjà pris par un autre processus`,
EACCES: `le port ${env.web.port} est interdit à ce processus (port privilégié, ou restreint par l’hôte)`,
EADDRNOTAVAIL: `l’adresse ${env.web.host} n’existe pas sur cette machine`,
};
const cause = causes[error.code] ?? error.message;
log.error(
`Le tableau de bord n'a pas pu démarrer sur ${env.web.host}:${env.web.port} — ${cause}. ` +
'Le bot continue sans le site : corrige `WEB_HOST` ou `WEB_PORT`, puis redémarre.',
error,
);
});
// Open event streams would otherwise keep the server from closing.
server.on('close', closeEventStreams);
return server;
}
/** True when the webhook server does not need its own port. */
export function webhookSharesWebPort() {
return env.web.enabled && env.webhook.enabled && env.webhook.port === env.web.port;
}