Files
FWS-DiscordBot/tests/web-wiki.test.js
T
nocodeandClaude Opus 5 3d0e21d7cb feat(wiki): serve the legal pages at /terms-of-service and /privacy-policy
Discord, and most platforms, ask for a terms URL and a privacy URL in a
form field; pasting a `/wiki/...` address there reads like an afterthought.
Both pages now answer at the root, while everything else stays under
`/wiki/`.

The API states each page's address instead of leaving the front to rebuild
it, so there is one place that decides. Existing pages are renamed rather
than recreated, keeping whatever has already been written in them.

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

241 lines
8.8 KiB
JavaScript

import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { after, before, beforeEach, describe, it } from 'node:test';
import { closeDatabase, getDatabase, initDatabase } from '../src/database/index.js';
import {
createPage,
getPageBySlug,
listPublished,
removePage,
searchPublished,
updatePage,
} from '../src/database/repositories/wiki-repository.js';
import { render } from '../src/web/public/core/markdown.js';
import { createHandler } from '../src/web/server.js';
import { seedWiki } from '../src/web/services/wiki-seed.js';
/** Public wiki and its Markdown renderer (M17). */
describe('markdown renderer', () => {
it('escapes HTML before doing anything else', () => {
const { html } = render('<script>alert(1)</script>');
assert.doesNotMatch(html, /<script>/);
assert.match(html, /&lt;script&gt;/);
});
it('escapes HTML inside a heading and a table cell too', () => {
assert.doesNotMatch(render('## <img src=x onerror=1>').html, /<img src=x/);
assert.doesNotMatch(render('| a |\n| --- |\n| <b>x</b> |').html, /<b>x<\/b>/);
});
it('refuses a javascript: link', () => {
const { html } = render('[clique](javascript:alert(1))');
assert.doesNotMatch(html, /javascript:/);
assert.match(html, /href="#"/);
});
it('keeps http links and opens them in a new tab', () => {
const { html } = render('[Discord](https://discord.com/terms)');
assert.match(html, /href="https:\/\/discord\.com\/terms"/);
assert.match(html, /rel="noreferrer noopener"/);
});
it('renders headings with anchors and collects them', () => {
const { html, headings } = render('## Durée de conservation\n### Détail');
assert.match(html, /<h2 id="duree-de-conservation">/);
assert.deepEqual(
headings.map((heading) => heading.id),
['duree-de-conservation', 'detail'],
);
});
it('renders a table', () => {
const { html } = render('| Donnée | Quand |\n| --- | --- |\n| Pseudo | À la connexion |');
assert.match(html, /<th>Donnée<\/th>/);
assert.match(html, /<td>À la connexion<\/td>/);
});
it('renders lists, quotes and fenced code verbatim', () => {
assert.match(render('- un\n- deux').html, /<ul>\n<li>un<\/li>/);
assert.match(render('1. un\n2. deux').html, /<ol>\n<li>un<\/li>/);
assert.match(render('> attention').html, /<blockquote>attention<\/blockquote>/);
assert.match(render('```\nnpm run setup\n```').html, /<pre><code>npm run setup<\/code><\/pre>/);
});
it('renders inline code and emphasis', () => {
const { html } = render('Voir `LOG_RETENTION_DAYS` et **le reste**.');
assert.match(html, /<code>LOG_RETENTION_DAYS<\/code>/);
assert.match(html, /<strong>le reste<\/strong>/);
});
it('survives an empty page', () => {
assert.deepEqual(render(''), { html: '', headings: [] });
assert.deepEqual(render(undefined), { html: '', headings: [] });
});
});
describe('wiki repository', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM wiki_pages;'));
const page = (overrides = {}) =>
createPage({ slug: 'guide', title: 'Guide', content: 'Bonjour', published: true, ...overrides });
it('stores and reads a page back', () => {
const created = page();
assert.equal(created.published, true);
assert.equal(created.protected, false);
assert.deepEqual(getPageBySlug('guide'), created);
});
it('lists only the published pages, in reading order', () => {
page({ slug: 'b', title: 'B', category: 'Général', position: 2 });
page({ slug: 'a', title: 'A', category: 'Général', position: 1 });
page({ slug: 'draft', title: 'Brouillon', published: false });
assert.deepEqual(
listPublished().map((entry) => entry.slug),
['a', 'b'],
);
});
it('searches titles and bodies', () => {
page({ slug: 'vie-privee', title: 'Confidentialité', content: 'Conservation des données' });
assert.equal(searchPublished('conservation').length, 1);
assert.equal(searchPublished('introuvable').length, 0);
});
it('refuses to delete a protected page', () => {
const locked = page({ slug: 'legal', isProtected: true });
assert.equal(removePage(locked.id), 0);
assert.ok(getPageBySlug('legal'));
});
it('records who last changed a page', () => {
const created = page();
const updated = updatePage(created.id, { title: 'Guide revu' }, 'u1');
assert.equal(updated.title, 'Guide revu');
assert.equal(updated.updated_by, 'u1');
});
});
describe('wiki seeding', () => {
before(() => initDatabase(':memory:'));
after(() => closeDatabase());
beforeEach(() => getDatabase().exec('DELETE FROM wiki_pages;'));
it('creates the welcome page and both legal pages', () => {
assert.equal(seedWiki(), 3);
assert.ok(getPageBySlug('terms-of-service').published);
assert.ok(getPageBySlug('privacy-policy').published);
});
it('marks the legal pages as protected', () => {
seedWiki();
assert.equal(getPageBySlug('privacy-policy').protected, true);
assert.equal(getPageBySlug('accueil').protected, false);
});
it('names the Swiss law it is written against', () => {
seedWiki();
const privacy = getPageBySlug('privacy-policy').content;
assert.match(privacy, /LPD/);
assert.match(privacy, /PFPDT/);
assert.match(privacy, /art\. 25 LPD/);
});
it('never overwrites what the organisation has written', () => {
seedWiki();
updatePage(getPageBySlug('terms-of-service').id, { content: 'Notre propre texte.' });
assert.equal(seedWiki(), 0);
assert.equal(getPageBySlug('terms-of-service').content, 'Notre propre texte.');
});
it('brings a deleted legal page back, but not the welcome one', () => {
seedWiki();
getDatabase().exec("DELETE FROM wiki_pages WHERE slug IN ('privacy-policy', 'accueil')");
assert.equal(seedWiki(), 1);
assert.ok(getPageBySlug('privacy-policy'));
assert.equal(getPageBySlug('accueil'), null);
});
});
describe('wiki over HTTP', () => {
let app;
before(async () => {
initDatabase(':memory:');
seedWiki();
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 get = (path) => fetch(`http://127.0.0.1:${app.address().port}${path}`);
it('serves the page tree without a session', async () => {
const response = await get('/api/wiki');
const body = await response.json();
assert.equal(response.status, 200);
assert.ok(body.categories.some((category) => category.name === 'Légal'));
});
it('serves a published page without a session', async () => {
const response = await get('/api/wiki/pages/terms-of-service');
assert.equal(response.status, 200);
assert.match((await response.json()).content, /droit suisse/);
});
it('hides a draft even when its address is known', async () => {
createPage({ slug: 'secret', title: 'Secret', content: 'chut', published: false });
assert.equal((await get('/api/wiki/pages/secret')).status, 404);
});
it('searches without a session', async () => {
const body = await get('/api/wiki/search?q=confidentialite').then((response) => response.json());
assert.ok(Array.isArray(body.results));
});
it('serves the legal pages at the root, where platforms expect them', async () => {
for (const path of ['/terms-of-service', '/privacy-policy']) {
const response = await get(path);
assert.equal(response.status, 200, `${path} ne répond pas`);
assert.match(await response.text(), /wiki\.js/, `${path} ne sert pas le site public`);
}
});
it('tells each page where it lives', async () => {
const body = await get('/api/wiki').then((response) => response.json());
const pages = body.categories.flatMap((category) => category.pages);
assert.equal(pages.find((page) => page.slug === 'terms-of-service').path, '/terms-of-service');
assert.equal(pages.find((page) => page.slug === 'privacy-policy').path, '/privacy-policy');
assert.equal(pages.find((page) => page.slug === 'accueil').path, '/wiki/accueil');
});
it('keeps an ordinary page under /wiki', async () => {
createPage({ slug: 'guide', title: 'Guide', content: 'x', published: true });
const response = await get('/guide');
// Not a wiki root page: it falls back to the dashboard shell.
assert.doesNotMatch(await response.text(), /wiki\.js/);
});
it('keeps the administration behind the login', async () => {
assert.equal((await get('/api/wiki/admin')).status, 401);
});
it('serves its own page rather than the dashboard shell', async () => {
const body = await get('/wiki/terms-of-service').then((response) => response.text());
assert.match(body, /wiki\.js/);
assert.doesNotMatch(body, /id="app"/);
});
});