feat(wiki): add the reading site and its editor

The renderer escapes HTML before any transformation and drops
`javascript:` links. Pages are written by the team, but a renderer that
relies on that is one mistake away from being a hole.

The editor previews as you type: legal pages are long, and writing Markdown
blind is how broken tables end up published.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
nocodeandClaude Opus 5 committed 2026-09-23 23:20:06 +02:00
1 parent c76c0b96eb
commit e5b7303a01
7 files changed
+1031

No files matched your search

+8
View File
@@ -68,6 +68,14 @@ const ROUTES = [
module: './views/community.js',
level: LEVELS.STAFF,
},
{
path: 'wiki',
icon: '📖',
label: 'Wiki',
group: 'Communauté',
module: './views/wiki.js',
level: LEVELS.STAFF,
},
{
path: 'logs',
icon: '≡',
+168
View File
@@ -0,0 +1,168 @@
/**
* Markdown renderer for the wiki (M17).
*
* Deliberately small: headings, lists, tables, code, quotes, links, emphasis.
* Everything is HTML-escaped **before** any transformation runs, so a page can
* never inject markup — the pages are written by the team, but a renderer that
* relies on that is one mistake away from being a hole.
*/
const escape = (text) =>
String(text ?? '')
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
export const slugify = (text) =>
String(text)
.toLowerCase()
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '');
/** Inline pass, applied to text that is already escaped. */
function inline(text) {
return text
.replace(/`([^`]+)`/g, '<code>$1</code>')
.replace(
/!\[([^\]]*)\]\(([^)\s]+)\)/g,
(_, alt, src) => `<img src="${src}" alt="${alt}" loading="lazy" />`,
)
.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, label, href) => {
// Only http(s) and in-page anchors: no `javascript:` sneaking through.
const safe = /^(https?:\/\/|\/|#)/.test(href) ? href : '#';
const external = safe.startsWith('http');
return `<a href="${safe}"${external ? ' target="_blank" rel="noreferrer noopener"' : ''}>${label}</a>`;
})
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
.replace(/(^|[^*])\*([^*\n]+)\*/g, '$1<em>$2</em>')
.replace(/~~([^~]+)~~/g, '<del>$1</del>');
}
const cells = (line) =>
line
.trim()
.replace(/^\||\|$/g, '')
.split('|')
.map((cell) => inline(cell.trim()));
/**
* Renders a page and returns `{ html, headings }`, the headings feeding the
* table of contents.
*/
export function render(markdown) {
const lines = escape(markdown).split('\n');
const out = [];
const headings = [];
let index = 0;
const closeList = (stack) => {
while (stack.length > 0) out.push(`</${stack.pop()}>`);
};
const listStack = [];
while (index < lines.length) {
const line = lines[index];
// Fenced code, kept verbatim.
if (/^\s*```/.test(line)) {
closeList(listStack);
const body = [];
index += 1;
while (index < lines.length && !/^\s*```/.test(lines[index])) body.push(lines[index++]);
index += 1;
out.push(`<pre><code>${body.join('\n')}</code></pre>`);
continue;
}
// Table: a header row followed by a separator row.
if (line.includes('|') && /^\s*\|?[\s:-]+\|[\s:|-]*$/.test(lines[index + 1] ?? '')) {
closeList(listStack);
const header = cells(line);
index += 2;
const rows = [];
while (index < lines.length && lines[index].includes('|') && lines[index].trim() !== '') {
rows.push(cells(lines[index++]));
}
out.push(
`<div class="table-wrap"><table class="table"><thead><tr>${header
.map((cell) => `<th>${cell}</th>`)
.join('')}</tr></thead><tbody>${rows
.map((row) => `<tr>${row.map((cell) => `<td>${cell}</td>`).join('')}</tr>`)
.join('')}</tbody></table></div>`,
);
continue;
}
const heading = /^(#{1,4})\s+(.*)$/.exec(line);
if (heading) {
closeList(listStack);
const level = heading[1].length;
const text = heading[2].trim();
const id = slugify(text);
if (level <= 3) headings.push({ id, text, level });
out.push(`<h${level} id="${id}">${inline(text)}</h${level}>`);
index += 1;
continue;
}
if (/^\s*(---|\*\*\*)\s*$/.test(line)) {
closeList(listStack);
out.push('<hr />');
index += 1;
continue;
}
const quote = /^&gt;\s?(.*)$/.exec(line);
if (quote) {
closeList(listStack);
const body = [quote[1]];
index += 1;
while (index < lines.length && /^&gt;\s?/.test(lines[index])) {
body.push(lines[index++].replace(/^&gt;\s?/, ''));
}
out.push(`<blockquote>${inline(body.join(' '))}</blockquote>`);
continue;
}
const bullet = /^\s*[-*]\s+(.*)$/.exec(line);
const ordered = /^\s*\d+\.\s+(.*)$/.exec(line);
if (bullet || ordered) {
const tag = bullet ? 'ul' : 'ol';
if (listStack.at(-1) !== tag) {
closeList(listStack);
out.push(`<${tag}>`);
listStack.push(tag);
}
out.push(`<li>${inline((bullet ?? ordered)[1])}</li>`);
index += 1;
continue;
}
if (line.trim() === '') {
closeList(listStack);
index += 1;
continue;
}
// Paragraph: consecutive non-empty lines are joined.
closeList(listStack);
const paragraph = [line];
index += 1;
while (
index < lines.length &&
lines[index].trim() !== '' &&
!/^\s*([-*]\s|\d+\.\s|#{1,4}\s|&gt;|```)/.test(lines[index]) &&
!lines[index].includes('|')
) {
paragraph.push(lines[index++]);
}
out.push(`<p>${inline(paragraph.join(' '))}</p>`);
}
closeList(listStack);
return { html: out.join('\n'), headings };
}
+240
View File
@@ -0,0 +1,240 @@
import { api } from '../core/api.js';
import { formatRelative, h } from '../core/dom.js';
import { autoRefresh } from '../core/live.js';
import { render as renderMarkdown } from '../core/markdown.js';
import {
badge,
button,
card,
confirmAction,
field,
input,
notice,
renderAsync,
table,
textarea,
toast,
toggle,
} from '../core/ui.js';
/** Editing the public documentation from the panel (M17). */
const LEVELS = { STAFF: 1, DEV: 2, OWNER: 3 };
const slugify = (text) =>
text
.toLowerCase()
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 80);
/**
* Editor with a live preview: legal pages are long, and writing Markdown blind
* is how broken tables end up published.
*/
async function editPage(existing, reload) {
const title = input({ value: existing?.title ?? '', placeholder: 'Titre de la page' });
const slug = input({ value: existing?.slug ?? '', placeholder: 'adresse-de-la-page' });
const summary = input({ value: existing?.summary ?? '', placeholder: 'Une phrase de résumé' });
const category = input({ value: existing?.category ?? 'Général', placeholder: 'Général' });
const position = input({ type: 'number', value: existing?.position ?? 0 });
const content = textarea({ value: existing?.content ?? '', style: { minHeight: '22rem' } });
let published = existing?.published ?? false;
// A new page gets its address from its title until the address is touched.
let slugTouched = Boolean(existing);
slug.addEventListener('input', () => (slugTouched = true));
title.addEventListener('input', () => {
if (!slugTouched) slug.value = slugify(title.value);
});
const preview = h('div', { class: 'wiki-content' });
const refreshPreview = () => {
preview.innerHTML = renderMarkdown(content.value).html;
};
content.addEventListener('input', refreshPreview);
refreshPreview();
const showPreview = h('div', { class: 'wiki-preview' }, preview);
showPreview.hidden = true;
const { modal } = await import('../core/ui.js');
const confirmed = await modal(
existing ? `Modifier « ${existing.title} »` : 'Nouvelle page',
() => ({
node: h(
'div',
{ class: 'stack' },
field('Titre', title),
field('Adresse', slug, { help: 'Minuscules, chiffres et tirets. Visible dans l’URL : /wiki/…' }),
field('Résumé', summary, { help: 'Affiché sous le titre et dans les résultats de recherche.' }),
field('Catégorie', category, { help: 'Regroupe les pages dans le menu du site public.' }),
field('Position', position, { help: 'Ordre dans la catégorie, du plus petit au plus grand.' }),
field('Contenu (Markdown)', content),
button(
'Afficher / masquer l’aperçu',
() => {
showPreview.hidden = !showPreview.hidden;
refreshPreview();
},
{ tone: 'ghost' },
),
showPreview,
toggle(published, (checked) => (published = checked), 'Publier (visible par tout le monde)'),
existing?.protected &&
notice('Page protégée : son contenu est modifiable, mais elle ne peut pas être supprimée.', 'info'),
),
submit: () => title.value.trim().length >= 2 && slug.value.trim() !== '',
}),
{ confirmLabel: existing ? 'Enregistrer' : 'Créer', tone: 'primary' },
);
if (!confirmed) return;
const payload = {
title: title.value.trim(),
slug: slug.value.trim(),
summary: summary.value.trim(),
category: category.value.trim() || 'Général',
position: Number(position.value) || 0,
content: content.value,
published,
};
try {
if (existing) await api.patch(`/api/wiki/admin/${existing.id}`, payload);
else await api.post('/api/wiki/admin', payload);
toast(existing ? 'Page enregistrée.' : 'Page créée.');
reload();
} catch (error) {
toast(error.message, 'error');
}
}
export function render(host, { state }) {
const level = state.me.accessLevel;
const reload = () => render(host, { state });
autoRefresh(reload, { topics: ['mutation'] });
return renderAsync(
host,
() => api.get('/api/wiki/admin'),
(data) => {
const published = data.pages.filter((page) => page.published).length;
return h(
'div',
{ class: 'stack' },
h(
'div',
{ class: 'page-head' },
h(
'div',
{},
h('h1', { text: 'Wiki' }),
h('p', {
class: 'muted',
text: 'Documentation publique, écrite ici et lisible sans compte sur /wiki.',
}),
),
h(
'div',
{ class: 'row' },
h('a', {
class: 'btn btn-ghost',
href: '/wiki',
target: '_blank',
rel: 'noreferrer',
text: '↗ Voir le site',
}),
level >= LEVELS.DEV && button('Nouvelle page', () => editPage(null, reload), { tone: 'primary' }),
),
),
published === 0 &&
notice('Aucune page publiée : le site public affichera une documentation vide.', 'warning'),
card(
'Pages',
{ subtitle: `${data.pages.length} page(s), dont ${published} publiée(s)` },
table(
[
{
label: 'Page',
render: (page) =>
h(
'div',
{},
h('strong', { text: page.title }),
h('div', { class: 'muted', text: page.summary || `/wiki/${page.slug}` }),
),
},
{ label: 'Catégorie', render: (page) => badge(page.category, 'info') },
{ label: 'Ordre', className: 'num advanced-only', key: 'position' },
{
label: 'État',
render: (page) =>
h(
'div',
{ class: 'row' },
page.published ? badge('Publiée', 'success') : badge('Brouillon', 'neutral'),
page.protected && badge('Protégée', 'warning'),
),
},
{
label: 'Modifiée',
className: 'nowrap',
render: (page) => formatRelative(page.updatedAt),
},
{
label: '',
render: (page) =>
h(
'div',
{ class: 'row' },
page.published &&
h('a', {
class: 'btn btn-ghost btn-sm',
href: `/wiki/${page.slug}`,
target: '_blank',
rel: 'noreferrer',
text: 'Voir',
}),
level >= LEVELS.DEV &&
button('Modifier', () => editPage(page, reload), { tone: 'ghost' }),
level >= LEVELS.DEV &&
button(
page.published ? 'Dépublier' : 'Publier',
async () => {
await api.patch(`/api/wiki/admin/${page.id}`, { published: !page.published });
toast(page.published ? 'Page dépubliée.' : 'Page publiée.');
reload();
},
{ tone: page.published ? 'ghost' : 'success' },
),
level >= LEVELS.OWNER &&
!page.protected &&
button(
'Supprimer',
async () => {
if (!(await confirmAction('Supprimer la page', `Supprimer « ${page.title} » ?`))) {
return;
}
await api.delete(`/api/wiki/admin/${page.id}`);
toast('Page supprimée.');
reload();
},
{ tone: 'danger' },
),
),
},
],
data.pages,
{ empty: 'Aucune page.' },
),
),
);
},
);
}
+198
View File
@@ -0,0 +1,198 @@
/* Public documentation site — reuses the dashboard tokens from styles.css (M17). */
.wiki-body {
background: var(--bg);
}
.wiki-shell {
display: grid;
grid-template-columns: 270px minmax(0, 1fr);
max-width: 1280px;
margin: 0 auto;
min-height: 100vh;
}
.wiki-side {
border-right: 1px solid var(--border);
padding: 1.2rem 1rem;
display: flex;
flex-direction: column;
gap: 0.8rem;
position: sticky;
top: 0;
height: 100vh;
overflow-y: auto;
}
.wiki-brand {
display: flex;
align-items: center;
gap: 0.6rem;
color: var(--text);
}
.wiki-brand:hover {
text-decoration: none;
}
.wiki-brand strong {
display: block;
font-size: 1rem;
}
.wiki-brand span {
display: block;
font-size: 0.75rem;
color: var(--text-muted);
}
.wiki-nav,
.wiki-results {
display: flex;
flex-direction: column;
gap: 0.1rem;
}
.wiki-nav a,
.wiki-results a {
display: block;
padding: 0.38rem 0.6rem;
border-radius: var(--radius-sm);
color: var(--text);
font-size: 0.88rem;
}
.wiki-nav a:hover,
.wiki-results a:hover {
background: var(--surface);
text-decoration: none;
}
.wiki-nav a.active {
background: color-mix(in srgb, var(--blue) 16%, transparent);
color: var(--blue-soft);
font-weight: 600;
box-shadow: inset 3px 0 0 var(--blue);
}
.wiki-main {
padding: 2rem 2.4rem 4rem;
min-width: 0;
}
.wiki-article {
display: grid;
grid-template-columns: minmax(0, 1fr) 200px;
gap: 2rem;
align-items: start;
}
.wiki-article h1 {
font-size: 2rem;
margin-bottom: 0.4rem;
}
.wiki-summary {
color: var(--text-muted);
font-size: 1.02rem;
margin-bottom: 1.4rem;
}
/* Comfortable measure: long legal text is unreadable across a full screen. */
.wiki-content {
max-width: 72ch;
font-size: 0.97rem;
line-height: 1.7;
}
.wiki-content h2 {
font-size: 1.32rem;
margin: 2rem 0 0.7rem;
padding-top: 0.6rem;
border-top: 1px solid var(--border);
}
.wiki-content h3 {
font-size: 1.08rem;
margin: 1.4rem 0 0.5rem;
}
.wiki-content h4 {
font-size: 0.97rem;
margin: 1.1rem 0 0.4rem;
color: var(--text-muted);
}
.wiki-content p {
margin: 0 0 0.9rem;
}
.wiki-content ul,
.wiki-content ol {
margin: 0 0 1rem;
padding-left: 1.35rem;
}
.wiki-content li {
margin-bottom: 0.35rem;
}
.wiki-content blockquote {
margin: 1rem 0;
padding: 0.7rem 1rem;
border-left: 3px solid var(--blue);
background: var(--surface);
border-radius: 0 var(--radius-sm) var(--radius-sm) 0;
color: var(--text-muted);
}
.wiki-content hr {
border: none;
border-top: 1px solid var(--border);
margin: 2rem 0;
}
.wiki-content img {
max-width: 100%;
border-radius: var(--radius-sm);
}
.wiki-content .table-wrap {
margin-bottom: 1.2rem;
}
.wiki-toc {
position: sticky;
top: 2rem;
display: flex;
flex-direction: column;
gap: 0.1rem;
border-left: 1px solid var(--border);
padding-left: 0.9rem;
}
.wiki-toc a {
font-size: 0.8rem;
color: var(--text-muted);
padding: 0.18rem 0;
}
.wiki-toc a:hover {
color: var(--text);
text-decoration: none;
}
.wiki-toc a[data-level='3'] {
padding-left: 0.7rem;
}
.wiki-updated {
margin-top: 2.5rem;
padding-top: 0.8rem;
border-top: 1px solid var(--border);
font-size: 0.8rem;
}
@media (max-width: 1080px) {
.wiki-article {
grid-template-columns: minmax(0, 1fr);
}
.wiki-toc {
display: none;
}
}
@media (max-width: 860px) {
.wiki-shell {
grid-template-columns: 1fr;
}
.wiki-side {
position: static;
height: auto;
border-right: none;
border-bottom: 1px solid var(--border);
}
.wiki-main {
padding: 1.2rem 1rem 3rem;
}
}
+19
View File
@@ -0,0 +1,19 @@
<!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="Documentation publique de l'organisation open source FWS." />
<title>Documentation FWS</title>
<link rel="icon" href="/favicon.svg" type="image/svg+xml" />
<link rel="stylesheet" href="/styles.css" />
<link rel="stylesheet" href="/wiki.css" />
</head>
<body class="wiki-body">
<div id="wiki">
<noscript>Cette documentation nécessite JavaScript.</noscript>
</div>
<script type="module" src="/wiki.js"></script>
</body>
</html>
+183
View File
@@ -0,0 +1,183 @@
import { h, mount, qs } from './core/dom.js';
import { render as renderMarkdown } from './core/markdown.js';
/**
* Public documentation site (M17).
*
* Standalone on purpose: no session, no dashboard shell, and its own small
* bundle — a visitor reading the privacy notice should never meet a login page.
*/
const state = { tree: null, slug: null, theme: localStorage.getItem('fws.theme') ?? 'dark' };
const api = async (path) => {
const response = await fetch(path, { headers: { Accept: 'application/json' } });
if (!response.ok) throw new Error((await response.json().catch(() => null))?.error ?? 'Page introuvable.');
return response.json();
};
const currentSlug = () => {
const path = window.location.pathname.replace(/^\/wiki\/?/, '').replace(/\/$/, '');
return decodeURIComponent(path) || null;
};
function navigate(slug, { replace = false } = {}) {
const url = slug ? `/wiki/${encodeURIComponent(slug)}` : '/wiki';
if (replace) window.history.replaceState({}, '', url);
else window.history.pushState({}, '', url);
draw();
}
function sidebar() {
const search = h('input', {
class: 'input',
type: 'search',
placeholder: 'Rechercher…',
'aria-label': 'Rechercher dans la documentation',
});
const results = h('div', { class: 'wiki-results' });
let timer = null;
search.addEventListener('input', () => {
clearTimeout(timer);
const term = search.value.trim();
if (term.length < 2) {
mount(results);
return;
}
timer = setTimeout(async () => {
const { results: found } = await api(`/api/wiki/search?q=${encodeURIComponent(term)}`).catch(() => ({
results: [],
}));
mount(
results,
found.length === 0
? h('p', { class: 'muted', text: 'Aucun résultat.' })
: found.map((page) =>
h('a', {
href: `/wiki/${page.slug}`,
text: page.title,
onClick: (event) => {
event.preventDefault();
search.value = '';
mount(results);
navigate(page.slug);
},
}),
),
);
}, 250);
});
return h(
'aside',
{ class: 'wiki-side' },
h(
'a',
{ class: 'wiki-brand', href: '/wiki' },
h('img', { src: '/favicon.svg', alt: '', width: 36, height: 36 }),
h('div', {}, h('strong', { text: 'FWS' }), h('span', { text: 'Documentation' })),
),
search,
results,
h(
'nav',
{ class: 'wiki-nav' },
(state.tree?.categories ?? []).map((category) =>
h(
'div',
{},
h('div', { class: 'nav-group', text: category.name }),
category.pages.map((page) =>
h('a', {
href: `/wiki/${page.slug}`,
text: page.title,
class: page.slug === state.slug ? 'active' : '',
onClick: (event) => {
event.preventDefault();
navigate(page.slug);
},
}),
),
),
),
),
);
}
function tableOfContents(headings) {
if (headings.length < 2) return null;
return h(
'nav',
{ class: 'wiki-toc' },
h('div', { class: 'nav-group', text: 'Sur cette page' }),
headings.map((heading) =>
h('a', { href: `#${heading.id}`, text: heading.text, dataset: { level: String(heading.level) } }),
),
);
}
async function article(host) {
const slug = state.slug ?? state.tree?.categories?.[0]?.pages?.[0]?.slug ?? null;
if (!slug) {
mount(host, h('p', { class: 'empty', text: 'Aucune page publiée pour l’instant.' }));
return;
}
let page;
try {
page = await api(`/api/wiki/pages/${encodeURIComponent(slug)}`);
} catch (error) {
mount(host, h('div', { class: 'notice notice-error' }, h('p', { text: error.message })));
return;
}
document.title = `${page.title} · Documentation FWS`;
const { html, headings } = renderMarkdown(page.content);
const body = h('div', { class: 'wiki-content' });
body.innerHTML = html;
mount(
host,
h(
'div',
{ class: 'wiki-article' },
h(
'article',
{},
h('p', { class: 'muted', text: page.category }),
h('h1', { text: page.title }),
page.summary && h('p', { class: 'wiki-summary', text: page.summary }),
body,
h('footer', {
class: 'muted wiki-updated',
text: `Dernière modification : ${new Date(`${page.updatedAt}Z`).toLocaleDateString('fr-FR', {
dateStyle: 'long',
})}`,
}),
),
tableOfContents(headings),
),
);
}
async function draw() {
state.slug = currentSlug();
const root = qs('#wiki');
if (!state.tree) {
state.tree = await api('/api/wiki').catch(() => ({ categories: [], site: {} }));
}
const main = h('main', { class: 'wiki-main' });
mount(root, h('div', { class: 'wiki-shell' }, sidebar(), main));
await article(main);
// In-page anchors only work once the article is on screen.
if (window.location.hash) qs(window.location.hash)?.scrollIntoView({ block: 'start' });
}
document.documentElement.dataset.theme = state.theme;
window.addEventListener('popstate', draw);
draw();
+215
View File
@@ -0,0 +1,215 @@
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('conditions-utilisation').published);
assert.ok(getPageBySlug('politique-confidentialite').published);
});
it('marks the legal pages as protected', () => {
seedWiki();
assert.equal(getPageBySlug('politique-confidentialite').protected, true);
assert.equal(getPageBySlug('accueil').protected, false);
});
it('names the Swiss law it is written against', () => {
seedWiki();
const privacy = getPageBySlug('politique-confidentialite').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('conditions-utilisation').id, { content: 'Notre propre texte.' });
assert.equal(seedWiki(), 0);
assert.equal(getPageBySlug('conditions-utilisation').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 ('politique-confidentialite', 'accueil')");
assert.equal(seedWiki(), 1);
assert.ok(getPageBySlug('politique-confidentialite'));
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/conditions-utilisation');
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('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/conditions-utilisation').then((response) => response.text());
assert.match(body, /wiki\.js/);
assert.doesNotMatch(body, /id="app"/);
});
});