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>
This commit is contained in:
nocodeandClaude Opus 5 committed 2026-09-24 18:46:26 +02:00
1 parent 9acb523510
commit a1e1de7734
11 files changed
+823

No files matched your search

+3
View File
@@ -92,6 +92,9 @@ DISCORD_CLIENT_SECRET=
# Jeton d'amorçage : ouvre l'assistant de configuration sans compte Discord. # Jeton d'amorçage : ouvre l'assistant de configuration sans compte Discord.
# À vider une fois le .env rempli. # À vider une fois le .env rempli.
WEB_SETUP_TOKEN= WEB_SETUP_TOKEN=
# Publie /status : bot en ligne, derniers déploiements, dernières releases.
# Les dépôts privés n'y apparaissent jamais par leur nom.
WEB_PUBLIC_STATUS=true
# Autorise les cibles de déploiement de type « commande shell » (Owner uniquement). # Autorise les cibles de déploiement de type « commande shell » (Owner uniquement).
WEB_ALLOW_COMMAND_DEPLOYS=false WEB_ALLOW_COMMAND_DEPLOYS=false
# Autorise le bouton « Redémarrer le bot » (nécessite un superviseur type systemd/pm2). # Autorise le bouton « Redémarrer le bot » (nécessite un superviseur type systemd/pm2).
+3
View File
@@ -92,6 +92,9 @@ export const env = Object.freeze({
// dashboard, so it stays off until it is explicitly enabled (M16-T06). // dashboard, so it stays off until it is explicitly enabled (M16-T06).
allowCommandDeploys: readBool('WEB_ALLOW_COMMAND_DEPLOYS'), allowCommandDeploys: readBool('WEB_ALLOW_COMMAND_DEPLOYS'),
allowRestart: readBool('WEB_ALLOW_RESTART'), allowRestart: readBool('WEB_ALLOW_RESTART'),
// The public status page is opt-out rather than opt-in: a bot people rely on
// owes them a place to check before asking.
publicStatus: readBool('WEB_PUBLIC_STATUS', true),
deployTimeoutMs: readInt('WEB_DEPLOY_TIMEOUT_MS', 900_000), deployTimeoutMs: readInt('WEB_DEPLOY_TIMEOUT_MS', 900_000),
rateLimitPerMinute: readInt('WEB_RATE_LIMIT_PER_MINUTE', 240), rateLimitPerMinute: readInt('WEB_RATE_LIMIT_PER_MINUTE', 240),
}, },
+4
View File
@@ -14,6 +14,7 @@ import { registerReleaseRoutes } from './releases.js';
import { registerRepositoryRoutes } from './repositories.js'; import { registerRepositoryRoutes } from './repositories.js';
import { registerSearchRoutes } from './search.js'; import { registerSearchRoutes } from './search.js';
import { registerSettingsRoutes } from './settings.js'; import { registerSettingsRoutes } from './settings.js';
import { registerStatusRoutes } from './status.js';
import { registerWikiRoutes } from './wiki.js'; import { registerWikiRoutes } from './wiki.js';
/** /**
@@ -39,6 +40,9 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) {
registerConfigurationRoutes(router); registerConfigurationRoutes(router);
// The public documentation stays reachable even while the bot is being set up. // The public documentation stays reachable even while the bot is being set up.
registerWikiRoutes(router); registerWikiRoutes(router);
// So does the status page: a bot still being configured is exactly what an
// uptime monitor, or a visitor, would want to be told.
registerStatusRoutes(router);
// Long-lived stream the pages listen to instead of polling (M16-T12). // Long-lived stream the pages listen to instead of polling (M16-T12).
router.get( router.get(
+21
View File
@@ -0,0 +1,21 @@
import { env } from '../../config/env.js';
import { notFound } from '../http.js';
import { statusSnapshot } from '../services/status-service.js';
/**
* Machine-readable twin of the public status page (M19).
*
* `/api/health` says whether the process is alive, which is what a load
* balancer asks. This says what state the service is in, which is what a person
* — or an uptime monitor with a dashboard — asks.
*/
export function registerStatusRoutes(router) {
router.get(
'/api/status',
async ({ context }) => {
if (!env.web.publicStatus) throw notFound('La page de statut est désactivée.');
return statusSnapshot(context);
},
{ public: true },
);
}
+172
View File
@@ -1333,6 +1333,171 @@ body[data-mode='simple'] .advanced-only {
min-width: 0; min-width: 0;
} }
/* --- Public status page --------------------------------------------------- */
.status-body {
background: var(--bg);
}
.status-page {
max-width: 820px;
margin: 0 auto;
padding: 2rem 1rem 3rem;
display: flex;
flex-direction: column;
gap: 1.5rem;
}
.status-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
}
.status-brand {
display: flex;
align-items: center;
gap: 0.6rem;
color: var(--text);
}
.status-brand:hover {
text-decoration: none;
}
.status-brand strong {
display: block;
font-size: 1rem;
}
.status-brand span {
font-size: 0.8rem;
color: var(--text-muted);
}
.status-muted {
color: var(--text-muted);
font-size: 0.84rem;
}
.status-banner {
border: 1px solid var(--border);
border-left: 4px solid var(--text-muted);
border-radius: var(--radius);
background: var(--bg-elevated);
padding: 1.2rem 1.4rem;
}
.status-banner h1 {
font-size: 1.35rem;
margin-bottom: 0.3rem;
}
.status-banner p {
color: var(--text-muted);
margin: 0;
}
.status-banner-ok {
border-left-color: var(--green);
}
.status-banner-busy {
border-left-color: var(--amber);
}
.status-banner-down {
border-left-color: var(--red);
}
.status-section h2 {
margin-bottom: 0.7rem;
}
.status-tiles {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 0.8rem;
}
.status-tile {
background: var(--bg-elevated);
border: 1px solid var(--border);
border-radius: var(--radius-sm);
padding: 0.8rem 0.9rem;
display: flex;
flex-direction: column;
gap: 0.1rem;
}
.status-tile-label {
font-size: 0.74rem;
letter-spacing: 0.06em;
text-transform: uppercase;
color: var(--text-muted);
}
.status-tile-value {
font-size: 1.15rem;
}
.status-tile-hint {
font-size: 0.76rem;
color: var(--text-muted);
}
.status-table {
width: 100%;
border-collapse: collapse;
font-size: 0.9rem;
}
.status-table th {
text-align: left;
font-size: 0.72rem;
letter-spacing: 0.07em;
text-transform: uppercase;
color: var(--text-muted);
padding: 0.4rem 0.6rem;
border-bottom: 1px solid var(--border);
}
.status-table td {
padding: 0.55rem 0.6rem;
border-bottom: 1px solid var(--border);
}
.status-pill {
display: inline-block;
font-size: 0.74rem;
font-weight: 600;
border-radius: 999px;
padding: 0.1rem 0.55rem;
background: var(--surface);
color: var(--text-muted);
}
.status-pill-ok {
background: color-mix(in srgb, var(--green) 20%, transparent);
color: var(--green);
}
.status-pill-busy {
background: color-mix(in srgb, var(--amber) 22%, transparent);
color: var(--amber);
}
.status-pill-down {
background: color-mix(in srgb, var(--red) 20%, transparent);
color: var(--red);
}
.status-releases {
list-style: none;
margin: 0;
padding: 0;
}
.status-releases li {
display: flex;
justify-content: space-between;
gap: 1rem;
flex-wrap: wrap;
padding: 0.5rem 0.6rem;
border-bottom: 1px solid var(--border);
}
.status-releases li:last-child {
border-bottom: none;
}
.status-empty {
color: var(--text-muted);
font-size: 0.9rem;
padding: 0.6rem;
}
.status-generated {
margin: 0;
}
.status-footer {
border-top: 1px solid var(--border);
padding-top: 1rem;
font-size: 0.85rem;
color: var(--text-muted);
}
@media (max-width: 900px) { @media (max-width: 900px) {
.shell { .shell {
grid-template-columns: 1fr; grid-template-columns: 1fr;
@@ -1357,4 +1522,11 @@ body[data-mode='simple'] .advanced-only {
.palette-overlay { .palette-overlay {
padding-top: 6vh; padding-top: 6vh;
} }
.status-page {
padding: 1.2rem 1rem 2rem;
}
.status-table {
font-size: 0.82rem;
}
} }
+21
View File
@@ -12,6 +12,8 @@ import { broadcast, closeEventStreams, topicForPath } from './events.js';
import { HttpError, readJsonBody, readRawBody, sendEmpty, sendHtml, sendJson, sendStatic } from './http.js'; import { HttpError, readJsonBody, readRawBody, sendEmpty, sendHtml, sendJson, sendStatic } from './http.js';
import { createRouter } from './router.js'; import { createRouter } from './router.js';
import { listPublished } from '../database/repositories/wiki-repository.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 { pagePath } from './services/wiki-seed.js';
import { renderIndex, renderNotFound, renderPage } from './services/wiki-render.js'; import { renderIndex, renderNotFound, renderPage } from './services/wiki-render.js';
import { ROOT_PAGES, seedWiki } from './services/wiki-seed.js'; import { ROOT_PAGES, seedWiki } from './services/wiki-seed.js';
@@ -140,6 +142,25 @@ export function createHandler({ client = null, setupOnly = false, startedAt = Da
return; 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, { const served = await sendStatic(response, publicDir, pathname, {
fallback: 'index.html', fallback: 'index.html',
request, request,
+9
View File
@@ -499,6 +499,15 @@ export const VARIABLES = Object.freeze([
generator: 'hex16', generator: 'hex16',
advanced: true, advanced: true,
}, },
{
key: 'WEB_PUBLIC_STATUS',
section: 'web',
label: 'Page de statut publique',
help: 'Publie `/status` : bot en ligne, dernier déploiement par environnement, dernières releases. Les dépôts privés n’y apparaissent jamais par leur nom.',
type: 'bool',
default: 'true',
restartRequired: true,
},
{ {
key: 'WEB_ALLOW_COMMAND_DEPLOYS', key: 'WEB_ALLOW_COMMAND_DEPLOYS',
section: 'web', section: 'web',
+197
View File
@@ -0,0 +1,197 @@
/**
* Public status page, rendered on the server (M19).
*
* Same reasoning as the wiki: a page that needs JavaScript to say whether the
* service is up is a page that reads as blank to a monitor, a crawler, or
* anyone on a connection bad enough to be checking the status in the first
* place. There is no script tag here, and the refresh is a meta tag.
*/
const escape = (text) =>
String(text ?? '')
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
const REFRESH_SECONDS = 60;
const STATE_LABELS = {
ok: 'Opérationnel',
down: 'Hors ligne',
busy: 'En cours',
unknown: 'Inconnu',
};
const DEPLOY_LABELS = {
success: 'Déployé',
failed: 'Échec',
running: 'En cours',
pending: 'En attente',
};
function duration(ms) {
const seconds = Math.floor(Number(ms) / 1000);
if (!Number.isFinite(seconds) || seconds < 0) return '—';
const days = Math.floor(seconds / 86_400);
const hours = Math.floor((seconds % 86_400) / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
if (days > 0) return `${days} j ${hours} h`;
if (hours > 0) return `${hours} h ${minutes} min`;
if (minutes > 0) return `${minutes} min`;
return `${seconds} s`;
}
function moment(value) {
if (!value) return '—';
const date = new Date(String(value).includes('T') ? value : `${value}Z`);
if (Number.isNaN(date.getTime())) return '—';
return date.toLocaleString('fr-FR', { dateStyle: 'medium', timeStyle: 'short' });
}
const pill = (tone, label) => `<span class="status-pill status-pill-${escape(tone)}">${escape(label)}</span>`;
const tile = (label, value, hint) => `
<div class="status-tile">
<span class="status-tile-label">${escape(label)}</span>
<strong class="status-tile-value">${escape(value)}</strong>
${hint ? `<span class="status-tile-hint">${escape(hint)}</span>` : ''}
</div>`;
function environmentRows(environments) {
if (environments.length === 0) {
return '<p class="status-empty">Aucun déploiement enregistré pour l’instant.</p>';
}
return `<table class="status-table">
<thead>
<tr><th>Environnement</th><th>Dépôt</th><th>Version</th><th>État</th><th>Le</th></tr>
</thead>
<tbody>
${environments
.map(
(entry) => `<tr>
<td><strong>${escape(entry.environment)}</strong></td>
<td>${entry.repository ? escape(entry.repository) : '<span class="status-muted">privé</span>'}</td>
<td>${entry.releaseTag ? `<code>${escape(entry.releaseTag)}</code>` : '—'}</td>
<td>${pill(entry.tone, DEPLOY_LABELS[entry.status] ?? entry.status)}</td>
<td class="status-muted">${escape(moment(entry.finishedAt))}</td>
</tr>`,
)
.join('\n ')}
</tbody>
</table>`;
}
function releaseList(releases) {
if (releases.length === 0) {
return '<p class="status-empty">Aucune release publiée pour l’instant.</p>';
}
return `<ul class="status-releases">
${releases
.map((release) => {
const label = `${release.repository} · ${release.name}`;
const title = release.htmlUrl
? `<a href="${escape(release.htmlUrl)}">${escape(label)}</a>`
: escape(label);
return `<li>
<div>${title}${release.prerelease ? ` ${pill('busy', 'préversion')}` : ''}</div>
<span class="status-muted">${escape(moment(release.publishedAt))}</span>
</li>`;
})
.join('\n ')}
</ul>`;
}
function footer(links) {
const entries = [
['/wiki', 'Documentation'],
['/terms-of-service', 'Conditions d’utilisation'],
['/privacy-policy', 'Politique de confidentialité'],
links.website && [links.website, 'Site'],
links.forge && [links.forge, 'Forge'],
links.discordInvite && [links.discordInvite, 'Discord'],
].filter(Boolean);
return `<footer class="status-footer">${entries
.map(([href, label]) => `<a href="${escape(href)}">${escape(label)}</a>`)
.join(' · ')}</footer>`;
}
/** Turns a snapshot from `status-service.js` into the finished page. */
export function renderStatus(snapshot) {
const { bot } = snapshot;
const failing = snapshot.environments.filter((entry) => entry.status === 'failed');
// The banner states the worst true thing: a green headline above a failed
// deployment is how a status page loses the only thing it has.
const headline = !bot.online
? { tone: 'down', title: 'Le bot est hors ligne', detail: 'Le service ne répond pas à Discord.' }
: failing.length > 0
? {
tone: 'busy',
title: 'Service opérationnel, déploiement en échec',
detail: `Le bot répond, mais ${failing.length} environnement(s) n’ont pas reçu leur dernière mise à jour.`,
}
: { tone: 'ok', title: 'Tous les services fonctionnent', detail: 'Le bot répond à Discord.' };
return `<!doctype html>
<html lang="fr" data-theme="dark">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="dark light" />
<meta name="description" content="État en direct des services FWS : bot Discord, déploiements et releases." />
<meta name="robots" content="index, follow" />
<meta http-equiv="refresh" content="${REFRESH_SECONDS}" />
<title>État des services · FWS</title>
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="stylesheet" href="/styles.css" />
</head>
<body class="status-body">
<main class="status-page">
<header class="status-head">
<a class="status-brand" href="/wiki">
<img src="/favicon.svg" alt="" width="40" height="40" />
<div><strong>FWS</strong><span>État des services</span></div>
</a>
<span class="status-muted">Actualisé automatiquement toutes les ${REFRESH_SECONDS} secondes</span>
</header>
<section class="status-banner status-banner-${escape(headline.tone)}">
<h1>${escape(headline.title)}</h1>
<p>${escape(headline.detail)}</p>
</section>
<section class="status-section">
<h2>Bot Discord</h2>
<div class="status-tiles">
${tile('État', STATE_LABELS[bot.state] ?? bot.state)}
${tile('En ligne depuis', duration(bot.uptimeMs), `Démarré le ${moment(bot.startedAt)}`)}
${tile('Latence Discord', bot.pingMs === null ? '—' : `${bot.pingMs} ms`)}
${tile('Version', bot.version)}
</div>
</section>
<section class="status-section">
<h2>Déploiements</h2>
${environmentRows(snapshot.environments)}
</section>
<section class="status-section">
<h2>Dernières releases</h2>
${releaseList(snapshot.releases)}
</section>
<p class="status-muted status-generated">
Relevé du <time datetime="${escape(snapshot.generatedAt)}">${escape(moment(snapshot.generatedAt))}</time>.
Version lisible par une machine : <a href="/api/status">/api/status</a>.
</p>
${footer(snapshot.links)}
</main>
</body>
</html>
`;
}
+133
View File
@@ -0,0 +1,133 @@
import { env } from '../../config/env.js';
import { createLogger } from '../../core/logger.js';
import { lastDeploymentPerEnvironment } from '../../database/repositories/deploy-repository.js';
import { org, repos, splitRepository } from '../../services/gitea/gitea-admin.js';
import { isGiteaConfigured } from '../../services/gitea/gitea-client.js';
import { VERSION } from './build-info.js';
/**
* What the public status page and `/api/status` both answer with (M19).
*
* Two rules shape this file. The page is **public**, so nothing here may name
* something the organization has not made public — a private repository leaking
* through a deployment row would be a real disclosure. And it is **unauthenticated**,
* so it may not turn a page load into a forge request: everything from Gitea is
* cached, and a failed refresh serves the previous answer rather than none.
*/
const log = createLogger('web:status');
const CACHE_TTL_MS = 60_000;
let cache = { at: 0, publicRepositories: null, releases: [] };
/** `success` is the only state worth claiming; everything else is spelled out. */
const DEPLOY_TONES = {
success: 'ok',
failed: 'down',
running: 'busy',
pending: 'busy',
};
async function refreshForge() {
if (!isGiteaConfigured()) return;
if (Date.now() - cache.at < CACHE_TTL_MS) return;
const repositories = await org.listRepos({ limit: 50 }).catch((error) => {
log.debug('Could not refresh the public repository list', error);
return null;
});
if (!repositories) return;
const open = repositories.filter((repository) => !repository.private && !repository.archived);
// One release request per repository would grow with the organization; the
// three most recently touched are what a status page is read for anyway.
const recent = open
.slice()
.sort((a, b) => new Date(b.updated_at) - new Date(a.updated_at))
.slice(0, 3);
const releases = (
await Promise.all(
recent.map(async (repository) => {
const parts = splitRepository(repository.full_name);
if (!parts) return null;
const release = await repos.latestRelease(parts.owner, parts.repo).catch(() => null);
if (!release || release.draft) return null;
return {
repository: repository.full_name,
tag: release.tag_name,
name: release.name || release.tag_name,
prerelease: Boolean(release.prerelease),
publishedAt: release.published_at ?? release.created_at ?? null,
htmlUrl: release.html_url ?? null,
};
}),
)
).filter(Boolean);
cache = {
at: Date.now(),
publicRepositories: new Set(open.map((repository) => repository.full_name)),
releases,
};
}
/**
* Deployment rows, stripped of anything the public has no business seeing.
*
* A repository the forge does not list as public is kept as a row — the
* environment is still meaningful — but loses its name.
*/
function environments() {
const guildId = env.discord.guildId;
if (!guildId) return [];
const rows = lastDeploymentPerEnvironment(guildId);
const known = cache.publicRepositories;
return rows.map((row) => ({
environment: row.environment,
repository: !known || known.has(row.repository) ? row.repository : null,
status: row.status,
tone: DEPLOY_TONES[row.status] ?? 'unknown',
releaseTag: row.release_tag ?? null,
finishedAt: row.finished_at ?? null,
}));
}
/** The snapshot behind `/status` and `/api/status`. Never throws. */
export async function statusSnapshot({ client = null, startedAt = Date.now() } = {}) {
await refreshForge().catch((error) => log.debug('Status refresh failed', error));
const online = Boolean(client?.isReady?.());
return {
bot: {
online,
state: online ? 'ok' : 'down',
uptimeMs: Date.now() - startedAt,
startedAt: new Date(startedAt).toISOString(),
version: VERSION,
// Round-trip to Discord: the one number that says the link is healthy
// rather than merely established.
pingMs: typeof client?.ws?.ping === 'number' && client.ws.ping >= 0 ? client.ws.ping : null,
},
environments: environments(),
releases: cache.releases,
links: {
website: env.links.website || null,
docs: env.links.docs || null,
discordInvite: env.links.discordInvite || null,
archRepo: env.links.archRepo || null,
forge: isGiteaConfigured() ? env.gitea.url : null,
},
generatedAt: new Date().toISOString(),
};
}
/** Lets the tests start from a known state. */
export function resetStatusCache() {
cache = { at: 0, publicRepositories: null, releases: [] };
}
+46
View File
@@ -0,0 +1,46 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { after, before, describe, it } from 'node:test';
/**
* `WEB_PUBLIC_STATUS=false` (M19).
*
* The switch decides what an anonymous visitor may learn about the
* infrastructure, so it gets a file of its own: the flag is read when the
* configuration module loads, and a suite cannot hold both answers at once.
*/
process.env.WEB_PUBLIC_STATUS = 'false';
const { closeDatabase, initDatabase } = await import('../src/database/index.js');
const { createHandler } = await import('../src/web/server.js');
describe('status page turned off', () => {
let app;
before(async () => {
initDatabase(':memory:');
app = createServer(createHandler({ client: null, setupOnly: false }));
await new Promise((resolve) => app.listen(0, '127.0.0.1', resolve));
});
after(async () => {
await new Promise((resolve) => app.close(resolve));
closeDatabase();
});
const call = (path) => fetch(`http://127.0.0.1:${app.address().port}${path}`);
it('does not serve the page', async () => {
const response = await call('/status');
assert.equal(response.status, 404);
assert.doesNotMatch(await response.text(), /État des services/);
});
it('does not answer in JSON either', async () => {
assert.equal((await call('/api/status')).status, 404);
});
it('leaves the health probe alone', async () => {
assert.equal((await call('/api/health')).status, 200);
});
});
+214
View File
@@ -0,0 +1,214 @@
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { after, before, beforeEach, describe, it } from 'node:test';
/**
* Public status page (M19).
*
* The guild id is set before the modules that read it are loaded — hence the
* dynamic imports, the same arrangement the Gitea import test uses.
*/
process.env.DISCORD_GUILD_ID = '900000000000000000';
const GUILD = process.env.DISCORD_GUILD_ID;
const { closeDatabase, getDatabase, initDatabase } = await import('../src/database/index.js');
const { createDeployment, finishDeployment } =
await import('../src/database/repositories/deploy-repository.js');
const { renderStatus } = await import('../src/web/services/status-render.js');
const { resetStatusCache, statusSnapshot } = await import('../src/web/services/status-service.js');
const { createHandler } = await import('../src/web/server.js');
const snapshot = (overrides = {}) => ({
bot: {
online: true,
state: 'ok',
uptimeMs: 3_600_000,
startedAt: new Date().toISOString(),
version: '1.2.3',
pingMs: 42,
},
environments: [],
releases: [],
links: {},
generatedAt: new Date().toISOString(),
...overrides,
});
const deploy = ({ environment, repository, status, releaseTag = null }) => {
const created = createDeployment({
guildId: GUILD,
targetName: environment,
repository,
environment,
releaseTag,
});
finishDeployment(created.id, { status });
return created;
};
describe('status page rendering', () => {
it('says everything works when the bot answers', () => {
const html = renderStatus(snapshot());
assert.match(html, /Tous les services fonctionnent/);
assert.match(html, /status-banner-ok/);
});
it('leads with the outage when the bot is down', () => {
const html = renderStatus(snapshot({ bot: { ...snapshot().bot, online: false, state: 'down' } }));
assert.match(html, /Le bot est hors ligne/);
assert.match(html, /status-banner-down/);
});
/** A green headline above a failed deployment is how a status page loses its point. */
it('refuses to look healthy while a deployment has failed', () => {
const html = renderStatus(
snapshot({
environments: [
{
environment: 'production',
repository: 'FWS/x',
status: 'failed',
tone: 'down',
releaseTag: null,
finishedAt: null,
},
],
}),
);
assert.match(html, /déploiement en échec/);
assert.match(html, /status-banner-busy/);
});
it('carries no script at all', () => {
assert.doesNotMatch(renderStatus(snapshot()), /<script/i);
});
it('refreshes itself without one', () => {
assert.match(renderStatus(snapshot()), /http-equiv="refresh"/);
});
it('escapes what it is given', () => {
const html = renderStatus(
snapshot({
environments: [
{
environment: '<img src=x onerror=alert(1)>',
repository: null,
status: 'success',
tone: 'ok',
releaseTag: null,
finishedAt: null,
},
],
}),
);
assert.doesNotMatch(html, /<img src=x/);
assert.match(html, /&lt;img src=x/);
});
it('keeps a private repository nameless rather than hiding the environment', () => {
const html = renderStatus(
snapshot({
environments: [
{
environment: 'staging',
repository: null,
status: 'success',
tone: 'ok',
releaseTag: 'v1',
finishedAt: null,
},
],
}),
);
assert.match(html, /staging/);
assert.match(html, /privé/);
});
it('points at the machine-readable version', () => {
assert.match(renderStatus(snapshot()), /\/api\/status/);
});
});
describe('status snapshot', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => {
getDatabase().exec('DELETE FROM deployments;');
resetStatusCache();
});
it('reports the bot as down when there is no client', async () => {
const data = await statusSnapshot({ client: null, startedAt: Date.now() });
assert.equal(data.bot.online, false);
assert.equal(data.bot.state, 'down');
});
it('keeps the last deployment of each environment', async () => {
deploy({ environment: 'production', repository: 'FWS/bot', status: 'success', releaseTag: 'v1.0.0' });
deploy({ environment: 'staging', repository: 'FWS/bot', status: 'failed' });
const { environments } = await statusSnapshot({ client: null });
const names = environments.map((entry) => entry.environment).sort();
assert.deepEqual(names, ['production', 'staging']);
assert.equal(environments.find((entry) => entry.environment === 'staging').tone, 'down');
});
it('names a tone for every deployment state', async () => {
deploy({ environment: 'production', repository: 'FWS/bot', status: 'running' });
const [entry] = (await statusSnapshot({ client: null })).environments;
assert.equal(entry.tone, 'busy');
});
});
describe('status over HTTP', () => {
let app;
before(async () => {
initDatabase(':memory:');
resetStatusCache();
app = createServer(createHandler({ client: null, setupOnly: false }));
await new Promise((resolve) => app.listen(0, '127.0.0.1', resolve));
});
after(async () => {
await new Promise((resolve) => app.close(resolve));
closeDatabase();
});
const call = (path) => fetch(`http://127.0.0.1:${app.address().port}${path}`);
it('serves the page to a visitor with no session', async () => {
const response = await call('/status');
const html = await response.text();
assert.equal(response.status, 200);
assert.match(response.headers.get('content-type'), /text\/html/);
assert.match(html, /État des services/);
});
it('forbids scripts in its own headers', async () => {
const policy = (await call('/status')).headers.get('content-security-policy');
assert.match(policy, /script-src 'none'/);
});
it('answers the same in JSON, without a session', async () => {
const response = await call('/api/status');
const body = await response.json();
assert.equal(response.status, 200);
assert.equal(typeof body.bot.online, 'boolean');
assert.ok(Array.isArray(body.environments));
assert.ok(Array.isArray(body.releases));
});
it('tolerates a trailing slash', async () => {
assert.equal((await call('/status/')).status, 200);
});
});