Files
FWS-DiscordBot/tests/web-configuration.test.js
nocodeandClaude Opus 5 40032ec091 fix(config): warn when a public address is announced but only loopback is bound
`WEB_HOST=127.0.0.1` is the right default behind a reverse proxy on the same
machine, and the wrong one inside a container or on a hosting panel, where
the process has to bind the allocation. The guidance only mentioned the
first case, so a `.env` written from the wizard could leave the dashboard
listening where nothing could reach it — every request timing out with
nothing saying why.

The wizard now flags the contradiction between a loopback bind and a public
URL, and both the help text and `.env.example` name the container case.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 23:20:07 +02:00

209 lines
7.7 KiB
JavaScript

import assert from 'node:assert/strict';
import { mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { after, before, describe, it } from 'node:test';
import {
diffValues,
maskValues,
mergeValues,
parseEnv,
renderEnvFile,
secretStatus,
writeEnvFile,
} from '../src/web/services/env-file.js';
import {
BY_KEY,
SECTIONS,
VARIABLES,
crossCheck,
requiredKeys,
validateAll,
validateValue,
} from '../src/web/services/env-schema.js';
describe('env schema', () => {
it('declares every variable inside a known section', () => {
const sectionIds = new Set(SECTIONS.map((section) => section.id));
for (const variable of VARIABLES) {
assert.ok(sectionIds.has(variable.section), `${variable.key} points at an unknown section`);
}
});
it('documents every variable with a label and a help text', () => {
for (const variable of VARIABLES) {
assert.ok(variable.label?.length > 0, `${variable.key} has no label`);
assert.ok(variable.help?.length > 0, `${variable.key} has no help`);
}
});
it('covers the variables the bot refuses to start without', () => {
assert.deepEqual(requiredKeys().sort(), ['DISCORD_CLIENT_ID', 'DISCORD_GUILD_ID', 'DISCORD_TOKEN']);
});
it('mirrors the keys used by .env.example', () => {
const example = parseEnv(readFileSync('.env.example', 'utf8'));
for (const key of Object.keys(example)) {
assert.ok(key in BY_KEY, `${key} is in .env.example but missing from the schema`);
}
for (const variable of VARIABLES) {
assert.ok(variable.key in example, `${variable.key} is in the schema but missing from .env.example`);
}
});
it('validates Discord identifiers', () => {
assert.equal(validateValue('DISCORD_GUILD_ID', '123456789012345678'), null);
assert.match(validateValue('DISCORD_GUILD_ID', 'abc'), /17 à 20 chiffres/);
});
it('validates numbers against their bounds', () => {
assert.equal(validateValue('WEB_PORT', '3080'), null);
assert.match(validateValue('WEB_PORT', '99999'), /Maximum/);
assert.match(validateValue('WEB_PORT', 'abc'), /nombre entier/);
});
it('validates booleans, enums and urls', () => {
assert.equal(validateValue('WEB_ENABLED', 'true'), null);
assert.match(validateValue('WEB_ENABLED', 'oui'), /true` ou `false/);
assert.equal(validateValue('LOG_LEVEL', 'debug'), null);
assert.match(validateValue('LOG_LEVEL', 'verbose'), /Valeurs possibles/);
assert.equal(validateValue('GITEA_URL', 'https://gitea.example.org'), null);
assert.match(validateValue('GITEA_URL', 'gitea.example.org'), /URL invalide/);
});
it('accepts an empty optional value but not an empty required one', () => {
assert.equal(validateValue('ROLE_OWNER_ID', ''), null);
assert.match(validateValue('DISCORD_TOKEN', ''), /obligatoire/);
});
it('reports every invalid key at once', () => {
const errors = validateAll({ DISCORD_TOKEN: 'x', DISCORD_CLIENT_ID: 'nope', DISCORD_GUILD_ID: '' });
assert.ok(errors.DISCORD_CLIENT_ID);
assert.ok(errors.DISCORD_GUILD_ID);
assert.equal(errors.DISCORD_TOKEN, undefined);
});
it('warns about combinations no single field can catch', () => {
const warnings = crossCheck({ WEBHOOK_ENABLED: 'true', GITEA_WEBHOOK_SECRET: '' });
assert.ok(warnings.some((warning) => warning.includes('rejetés')));
});
it('warns when a public address is announced but only loopback is bound', () => {
// The failure it prevents: the site answers on the loopback while a domain
// points at it, so every request times out and nothing says why.
const warnings = crossCheck({
WEB_ENABLED: 'true',
WEB_HOST: '127.0.0.1',
WEB_PUBLIC_URL: 'https://bot.example.org',
DISCORD_CLIENT_SECRET: 'x',
WEB_SESSION_SECRET: 'y',
});
assert.ok(warnings.some((warning) => warning.includes('boucle locale')));
});
it('stays quiet when the loopback matches the announced address', () => {
const warnings = crossCheck({
WEB_ENABLED: 'true',
WEB_HOST: '127.0.0.1',
WEB_PUBLIC_URL: 'http://localhost:3080',
DISCORD_CLIENT_SECRET: 'x',
WEB_SESSION_SECRET: 'y',
});
assert.ok(!warnings.some((warning) => warning.includes('boucle locale')));
});
it('warns when the dashboard is exposed without HTTPS', () => {
const warnings = crossCheck({
WEB_ENABLED: 'true',
WEB_HOST: '0.0.0.0',
WEB_PUBLIC_URL: 'http://bot.example.org',
DISCORD_CLIENT_SECRET: 'x',
WEB_SESSION_SECRET: 'y',
});
assert.ok(warnings.some((warning) => warning.includes('en clair')));
});
});
describe('env file', () => {
let directory;
let file;
before(() => {
directory = mkdtempSync(path.join(tmpdir(), 'fws-env-'));
file = path.join(directory, '.env');
});
after(() => rmSync(directory, { recursive: true, force: true }));
it('parses quoted, unquoted and commented lines', () => {
const values = parseEnv('# comment\nA=1\nB="deux mots"\nC=\'trois\'\nexport D=4\ninvalid\n');
assert.deepEqual(values, { A: '1', B: 'deux mots', C: 'trois', D: '4' });
});
it('renders a file that documents every variable', () => {
const content = renderEnvFile({ DISCORD_TOKEN: 'secret', WEB_PORT: '3080' });
for (const variable of VARIABLES) {
assert.ok(content.includes(`${variable.key}=`), `${variable.key} is missing from the rendered file`);
assert.ok(content.includes(variable.label), `${variable.label} is missing from the rendered file`);
}
});
it('keeps variables it does not know about', () => {
const content = renderEnvFile({}, { CUSTOM_THING: 'valeur' });
assert.match(content, /CUSTOM_THING=valeur/);
});
it('quotes values that need it', () => {
const content = renderEnvFile({ GITEA_OWNER: 'deux mots' });
assert.match(content, /GITEA_OWNER="deux mots"/);
});
it('writes the file with 600 permissions and backs up the previous one', () => {
writeFileSync(file, 'DISCORD_TOKEN=ancien\n');
const result = writeEnvFile({ DISCORD_TOKEN: 'nouveau' }, { file });
assert.ok(result.backup, 'no backup was made');
assert.match(readFileSync(result.backup, 'utf8'), /ancien/);
assert.match(readFileSync(file, 'utf8'), /DISCORD_TOKEN=nouveau/);
assert.equal(statSync(file).mode & 0o777, 0o600);
});
it('keeps the stored secret when the submitted one is empty', () => {
const merged = mergeValues(
{ DISCORD_TOKEN: 'garde-moi', GITEA_OWNER: 'FWS' },
{ DISCORD_TOKEN: '', GITEA_OWNER: 'AUTRE' },
);
assert.equal(merged.DISCORD_TOKEN, 'garde-moi');
assert.equal(merged.GITEA_OWNER, 'AUTRE');
});
it('ignores keys that are not part of the schema', () => {
const merged = mergeValues({}, { NOT_A_REAL_KEY: 'x' });
assert.equal(merged.NOT_A_REAL_KEY, undefined);
});
it('never sends a secret back to the browser', () => {
const masked = maskValues({ DISCORD_TOKEN: 'tres-secret', GITEA_OWNER: 'FWS' });
assert.equal(masked.DISCORD_TOKEN, '');
assert.equal(masked.GITEA_OWNER, 'FWS');
const status = secretStatus({ DISCORD_TOKEN: 'tres-secret' });
assert.equal(status.DISCORD_TOKEN, true);
assert.equal(status.GITEA_TOKEN, false);
});
it('describes a change without revealing the secret', () => {
const diff = diffValues(
{ DISCORD_TOKEN: 'avant', WEB_PORT: '3080' },
{ DISCORD_TOKEN: 'apres', WEB_PORT: '4000' },
);
const token = diff.find((entry) => entry.key === 'DISCORD_TOKEN');
assert.equal(token.before, '••••••');
assert.equal(token.after, '••••••');
assert.equal(token.restartRequired, true);
const port = diff.find((entry) => entry.key === 'WEB_PORT');
assert.equal(port.after, '4000');
});
});