Files
FWS-DiscordBot/tests/web-status.test.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

215 lines
6.4 KiB
JavaScript

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);
});
});