Files
FWS-DiscordBot/src/web/server.js
T
nocodeandClaude Opus 5 a1e1de7734 feat(web): publish a public status page at /status
Checking whether the service is up required an account, so the answer
lived where the people asking could not reach it.

The page is rendered on the server with no script at all and refreshes
through a meta tag: a status page that needs a working browser is
useless at the moment it is read. Two rules follow from it being public.
A repository the forge does not list as public keeps its environment
visible but loses its name, and the banner always states the worst true
thing — a failed deployment forbids the green headline even while the
bot answers. WEB_PUBLIC_STATUS=false removes page and route together.

/api/status gives the same in JSON, which is what a monitor should watch
rather than /api/health — the latter only says the process is alive.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-24 18:46:26 +02:00

270 lines
10 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, sendHtml, sendJson, sendStatic } from './http.js';
import { createRouter } from './router.js';
import { listPublished } from '../database/repositories/wiki-repository.js';
import { renderStatus } from './services/status-render.js';
import { statusSnapshot } from './services/status-service.js';
import { pagePath } from './services/wiki-seed.js';
import { renderIndex, renderNotFound, renderPage } from './services/wiki-render.js';
import { ROOT_PAGES, seedWiki } from './services/wiki-seed.js';
/** HTTP server of the dashboard (M16-T01). */
const log = createLogger('web');
/**
* The wiki address a path stands for: `''` for the index, a slug for a page,
* `null` when the path is not the wiki's business.
*/
function wikiSlug(pathname) {
const clean = pathname.replace(/\/+$/, '');
if (clean === '/wiki' || clean === '') return clean === '/wiki' ? '' : null;
if (clean.startsWith('/wiki/')) return decodeURIComponent(clean.slice('/wiki/'.length));
const root = clean.replace(/^\//, '');
return ROOT_PAGES.includes(root) ? root : null;
}
/** Answers with the finished HTML of a wiki page, or its index. */
function sendWiki(response, slug, term) {
let pages = [];
try {
pages = listPublished();
} catch (error) {
log.warn('Could not read the wiki pages', error);
}
const categories = [];
for (const page of pages) {
const entry = { ...page, path: pagePath(page.slug) };
let category = categories.find((item) => item.name === page.category);
if (!category) categories.push((category = { name: page.category, pages: [] }));
category.pages.push(entry);
}
const all = categories.flatMap((category) => category.pages);
if (slug === '') {
const needle = term.trim().toLowerCase();
const results =
needle.length >= 2
? all.filter((page) =>
[page.title, page.summary, page.content].some((field) =>
String(field ?? '')
.toLowerCase()
.includes(needle),
),
)
: null;
sendHtml(response, 200, renderIndex(categories, { term, results }));
return;
}
const page = all.find((entry) => entry.slug === slug);
if (!page) {
sendHtml(response, 404, renderNotFound(categories));
return;
}
sendHtml(response, 200, renderPage(page, categories));
}
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 rendered here rather than in the browser: a terms page
// that needs scripts to show its text reads as blank to anything that
// does not run them, which includes whoever checks the link before
// approving an application.
const slug = wikiSlug(pathname);
if (slug !== null) {
sendWiki(response, slug, url.searchParams.get('q') ?? '');
return;
}
// Same reasoning for the status page, with one addition: it is read when
// something is wrong, which is the worst moment to need a working browser.
// Turned off, it answers 404 rather than falling through to the dashboard
// shell — « this address does not exist here » is the honest answer, and
// a shell served at /status only looks like a broken status page.
if (pathname.replace(/\/+$/, '') === '/status') {
if (!env.web.publicStatus) {
sendEmpty(response, 404);
return;
}
try {
sendHtml(response, 200, renderStatus(await statusSnapshot(context)));
} catch (error) {
log.error('Could not render the status page', error);
sendHtml(response, 503, '<!doctype html><title>État indisponible</title><p>État indisponible.');
}
return;
}
const served = await sendStatic(response, publicDir, pathname, {
fallback: 'index.html',
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;
}