feat(web): serve the dashboard and its interface
The front-end is plain JavaScript served as is: no build step to run before the bot starts, and no second toolchain to keep alive. A simple/advanced switch hides the technical panels without ever standing in for a permission. `npm run setup` starts the wizard alone, because the bot refuses to boot without a token and the `.env` has to be writable from somewhere. When the webhook and the dashboard share a port, a single HTTP server is started. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
23 files changed
+5850
-2
No files matched your search
@@ -0,0 +1,136 @@
|
||||
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 { HttpError, readJsonBody, readRawBody, sendEmpty, sendJson, sendStatic } from './http.js';
|
||||
import { createRouter } from './router.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) {
|
||||
// Anything else is the single page application; unknown paths fall back to
|
||||
// its shell so client-side routing works on a hard refresh.
|
||||
const served = await sendStatic(response, publicDir, pathname, { fallback: 'index.html' });
|
||||
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) returns nothing.
|
||||
if (!response.headersSent) sendJson(response, 200, result ?? { ok: true });
|
||||
} 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 } = {}) {
|
||||
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));
|
||||
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;
|
||||
}
|
||||
Reference in new issue
Block a user