diff --git a/.env.example b/.env.example index 158f675..01a95b8 100644 --- a/.env.example +++ b/.env.example @@ -92,6 +92,9 @@ DISCORD_CLIENT_SECRET= # Jeton d'amorçage : ouvre l'assistant de configuration sans compte Discord. # À vider une fois le .env rempli. 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). WEB_ALLOW_COMMAND_DEPLOYS=false # Autorise le bouton « Redémarrer le bot » (nécessite un superviseur type systemd/pm2). diff --git a/src/config/env.js b/src/config/env.js index 72d4d98..44275e0 100644 --- a/src/config/env.js +++ b/src/config/env.js @@ -92,6 +92,9 @@ export const env = Object.freeze({ // dashboard, so it stays off until it is explicitly enabled (M16-T06). allowCommandDeploys: readBool('WEB_ALLOW_COMMAND_DEPLOYS'), 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), rateLimitPerMinute: readInt('WEB_RATE_LIMIT_PER_MINUTE', 240), }, diff --git a/src/web/api/index.js b/src/web/api/index.js index db3f9f6..00a6099 100644 --- a/src/web/api/index.js +++ b/src/web/api/index.js @@ -14,6 +14,7 @@ import { registerReleaseRoutes } from './releases.js'; import { registerRepositoryRoutes } from './repositories.js'; import { registerSearchRoutes } from './search.js'; import { registerSettingsRoutes } from './settings.js'; +import { registerStatusRoutes } from './status.js'; import { registerWikiRoutes } from './wiki.js'; /** @@ -39,6 +40,9 @@ export function registerApiRoutes(router, { setupOnly = false } = {}) { registerConfigurationRoutes(router); // The public documentation stays reachable even while the bot is being set up. 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). router.get( diff --git a/src/web/api/status.js b/src/web/api/status.js new file mode 100644 index 0000000..d530aa6 --- /dev/null +++ b/src/web/api/status.js @@ -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 }, + ); +} diff --git a/src/web/public/styles.css b/src/web/public/styles.css index f07009d..451f188 100644 --- a/src/web/public/styles.css +++ b/src/web/public/styles.css @@ -1333,6 +1333,171 @@ body[data-mode='simple'] .advanced-only { 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) { .shell { grid-template-columns: 1fr; @@ -1357,4 +1522,11 @@ body[data-mode='simple'] .advanced-only { .palette-overlay { padding-top: 6vh; } + + .status-page { + padding: 1.2rem 1rem 2rem; + } + .status-table { + font-size: 0.82rem; + } } diff --git a/src/web/server.js b/src/web/server.js index 46f1f5d..2d954c3 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -12,6 +12,8 @@ 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'; @@ -140,6 +142,25 @@ export function createHandler({ client = null, setupOnly = false, startedAt = Da 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, 'État indisponible

État indisponible.'); + } + return; + } + const served = await sendStatic(response, publicDir, pathname, { fallback: 'index.html', request, diff --git a/src/web/services/env-schema.js b/src/web/services/env-schema.js index 8fab04b..bfb2b44 100644 --- a/src/web/services/env-schema.js +++ b/src/web/services/env-schema.js @@ -499,6 +499,15 @@ export const VARIABLES = Object.freeze([ generator: 'hex16', 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', section: 'web', diff --git a/src/web/services/status-render.js b/src/web/services/status-render.js new file mode 100644 index 0000000..1fa5db5 --- /dev/null +++ b/src/web/services/status-render.js @@ -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('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"'); + +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) => `${escape(label)}`; + +const tile = (label, value, hint) => ` +

+ ${escape(label)} + ${escape(value)} + ${hint ? `${escape(hint)}` : ''} +
`; + +function environmentRows(environments) { + if (environments.length === 0) { + return '

Aucun déploiement enregistré pour l’instant.

'; + } + + return ` + + + + + ${environments + .map( + (entry) => ` + + + + + + `, + ) + .join('\n ')} + +
EnvironnementDépôtVersionÉtatLe
${escape(entry.environment)}${entry.repository ? escape(entry.repository) : 'privé'}${entry.releaseTag ? `${escape(entry.releaseTag)}` : '—'}${pill(entry.tone, DEPLOY_LABELS[entry.status] ?? entry.status)}${escape(moment(entry.finishedAt))}
`; +} + +function releaseList(releases) { + if (releases.length === 0) { + return '

Aucune release publiée pour l’instant.

'; + } + + return ``; +} + +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 ``; +} + +/** 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 ` + + + + + + + + + État des services · FWS + + + + +
+
+ + +
FWSÉtat des services
+
+ Actualisé automatiquement toutes les ${REFRESH_SECONDS} secondes +
+ +
+

${escape(headline.title)}

+

${escape(headline.detail)}

+
+ +
+

Bot Discord

+
+${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)} +
+
+ +
+

Déploiements

+ ${environmentRows(snapshot.environments)} +
+ +
+

Dernières releases

+ ${releaseList(snapshot.releases)} +
+ +

+ Relevé du . + Version lisible par une machine : /api/status. +

+ ${footer(snapshot.links)} +
+ + +`; +} diff --git a/src/web/services/status-service.js b/src/web/services/status-service.js new file mode 100644 index 0000000..8e12961 --- /dev/null +++ b/src/web/services/status-service.js @@ -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: [] }; +} diff --git a/tests/web-status-disabled.test.js b/tests/web-status-disabled.test.js new file mode 100644 index 0000000..53c16b5 --- /dev/null +++ b/tests/web-status-disabled.test.js @@ -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); + }); +}); diff --git a/tests/web-status.test.js b/tests/web-status.test.js new file mode 100644 index 0000000..40d88cc --- /dev/null +++ b/tests/web-status.test.js @@ -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()), /