Files
FWS-DiscordBot/src/web/server.js
T
nocodeandClaude Opus 5 faa296937d feat(wiki): serve a public documentation written from the panel
Pages live in SQLite and are read without a session: documentation nobody
can reach without an account is not documentation. Drafts answer 404 even
when their address is guessed, and the site never falls back to the
dashboard shell, which would send a visitor to a login screen.

The wiki ships with terms of use and a privacy policy written against the
revised Swiss LPD, describing table by table what this codebase actually
stores. Both are marked protected: they can be rewritten, not deleted, and
a deleted one comes back on the next start — a bot that processes personal
data must always be able to show its notice.

The bracketed details still have to be completed and the whole reviewed;
this is a starting point written from the schema, not legal advice.

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

157 lines
5.8 KiB
JavaScript

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 });
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 });
});
server.on('error', (error) => log.error('Dashboard server error', 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;
}