fix(wiki): render the public pages on the server

The documentation was assembled in the browser, so a client that runs no
script saw an empty shell — including whoever fetches the terms and privacy
links before approving an application, which is exactly what those pages are
for.

The wiki is now delivered as finished HTML, carries no script at all, and
declares itself indexable, unlike the panel. Search works through a plain
query string, an unknown page answers 404 rather than a blank page, and both
legal pages are linked from the footer of every page.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
nocodeandClaude Opus 5 committed 2026-09-23 23:31:27 +02:00
1 parent 3d0e21d7cb
commit 8869c74b7b
7 files changed
+348 -222

No files matched your search

+18
View File
@@ -59,6 +59,24 @@ export function sendJson(response, status, payload) {
response.end(body);
}
/**
* Sends a finished HTML document. Public pages carry a relaxed policy: they
* embed no script of their own, and must stay readable to whoever fetches them.
*/
export function sendHtml(response, status, html) {
const body = Buffer.from(html, 'utf8');
response.writeHead(status, {
...SECURITY_HEADERS,
'Content-Security-Policy':
"default-src 'self'; img-src 'self' data:; style-src 'self'; script-src 'none'; " +
"frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
'Content-Type': 'text/html; charset=utf-8',
'Content-Length': body.length,
'Cache-Control': 'no-cache',
});
response.end(body);
}
export function sendEmpty(response, status, headers = {}) {
response.writeHead(status, { ...SECURITY_HEADERS, ...headers }).end();
}
+31
View File
@@ -144,6 +144,37 @@
margin-bottom: 1.2rem;
}
.wiki-search {
margin: 0;
}
.wiki-index {
list-style: none;
margin: 0 0 1.4rem;
padding: 0;
}
.wiki-index li {
padding: 0.35rem 0;
border-bottom: 1px solid var(--border);
}
.wiki-index li:last-child {
border-bottom: none;
}
.wiki-footer {
margin-top: 3rem;
padding-top: 1rem;
border-top: 1px solid var(--border);
font-size: 0.8rem;
color: var(--text-muted);
}
.wiki-footer a {
color: var(--text-muted);
}
.wiki-footer a:hover {
color: var(--text);
}
.wiki-toc {
position: sticky;
top: 2rem;
-19
View File
@@ -1,19 +0,0 @@
<!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>
-187
View File
@@ -1,187 +0,0 @@
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 = () => {
// A page answers either at `/wiki/<slug>` or, for the legal ones, at
// `/<slug>`; the last segment is the slug in both cases.
const path = window.location.pathname.replace(/^\/wiki\/?/, '').replace(/^\/|\/$/g, '');
return decodeURIComponent(path) || null;
};
const pathOf = (page) => page?.path ?? (page?.slug ? `/wiki/${encodeURIComponent(page.slug)}` : '/wiki');
function navigate(target, { replace = false } = {}) {
const url = typeof target === 'string' ? target : pathOf(target);
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: pathOf(page),
text: page.title,
onClick: (event) => {
event.preventDefault();
search.value = '';
mount(results);
navigate(page);
},
}),
),
);
}, 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: pathOf(page),
text: page.title,
class: page.slug === state.slug ? 'active' : '',
onClick: (event) => {
event.preventDefault();
navigate(page);
},
}),
),
),
),
),
);
}
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();
+73 -10
View File
@@ -9,13 +9,71 @@ import { registerApiRoutes } from './api/index.js';
import { authenticate, assertSameOrigin } from './auth/session.js';
import { authorize } from './auth/guard.js';
import { broadcast, closeEventStreams, topicForPath } from './events.js';
import { HttpError, readJsonBody, readRawBody, sendEmpty, sendJson, sendStatic } from './http.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 { pagePath } from './services/wiki-seed.js';
import { renderIndex, renderNotFound, renderPage } from './services/wiki-render.js';
import { ROOT_PAGES, seedWiki } from './services/wiki-seed.js';
/** HTTP server of the dashboard (M16-T01). */
const log = createLogger('web');
/**
* The wiki address a path stands for: `''` for the index, a slug for a page,
* `null` when the path is not the wiki's business.
*/
function wikiSlug(pathname) {
const clean = pathname.replace(/\/+$/, '');
if (clean === '/wiki' || clean === '') return clean === '/wiki' ? '' : null;
if (clean.startsWith('/wiki/')) return decodeURIComponent(clean.slice('/wiki/'.length));
const root = clean.replace(/^\//, '');
return ROOT_PAGES.includes(root) ? root : null;
}
/** Answers with the finished HTML of a wiki page, or its index. */
function sendWiki(response, slug, term) {
let pages = [];
try {
pages = listPublished();
} catch (error) {
log.warn('Could not read the wiki pages', error);
}
const categories = [];
for (const page of pages) {
const entry = { ...page, path: pagePath(page.slug) };
let category = categories.find((item) => item.name === page.category);
if (!category) categories.push((category = { name: page.category, pages: [] }));
category.pages.push(entry);
}
const all = categories.flatMap((category) => category.pages);
if (slug === '') {
const needle = term.trim().toLowerCase();
const results =
needle.length >= 2
? all.filter((page) =>
[page.title, page.summary, page.content].some((field) =>
String(field ?? '')
.toLowerCase()
.includes(needle),
),
)
: null;
sendHtml(response, 200, renderIndex(categories, { term, results }));
return;
}
const page = all.find((entry) => entry.slug === slug);
if (!page) {
sendHtml(response, 404, renderNotFound(categories));
return;
}
sendHtml(response, 200, renderPage(page, categories));
}
const publicDir = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public');
/** Sliding window per client address, reset every minute. */
@@ -72,15 +130,20 @@ export function createHandler({ client = null, setupOnly = false, startedAt = Da
const isApi = pathname.startsWith('/api/') || pathname.startsWith('/auth/');
if (!isApi) {
// The wiki is a separate public page: it must never fall back to the
// dashboard shell, which would send a visitor to a login screen. The
// legal pages answer at the root, where platforms expect them.
const isWiki =
pathname === '/wiki' ||
pathname.startsWith('/wiki/') ||
ROOT_PAGES.includes(pathname.replace(/^\/|\/$/g, ''));
const fallback = isWiki ? 'wiki.html' : 'index.html';
const served = await sendStatic(response, publicDir, pathname, { fallback, request });
// The wiki is rendered here rather than in the browser: a terms page
// that needs scripts to show its text reads as blank to anything that
// does not run them, which includes whoever checks the link before
// approving an application.
const slug = wikiSlug(pathname);
if (slug !== null) {
sendWiki(response, slug, url.searchParams.get('q') ?? '');
return;
}
const served = await sendStatic(response, publicDir, pathname, {
fallback: 'index.html',
request,
});
if (!served) sendEmpty(response, 404);
return;
}
+182
View File
@@ -0,0 +1,182 @@
import { env } from '../../config/env.js';
import { render as renderMarkdown } from '../public/core/markdown.js';
import { pagePath } from './wiki-seed.js';
/**
* Server-rendered wiki (M17).
*
* The public documentation is delivered as finished HTML rather than assembled
* in the browser. A terms page that needs JavaScript to show its text is a page
* that reads as blank to anything that does not run scripts — a platform
* checking the link before approving an application, a crawler, a reader with
* scripts disabled — and those are exactly the readers it exists for.
*/
const escape = (text) =>
String(text ?? '')
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
const document = ({ title, description, body, noindex = false }) => `<!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="${escape(description)}" />
<meta name="robots" content="${noindex ? 'noindex, nofollow' : 'index, follow'}" />
<title>${escape(title)}</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">
${body}
</body>
</html>
`;
/** Sidebar: the page tree and a search box that works without scripts. */
function sidebar(categories, currentSlug, term = '') {
const groups = categories
.map(
(category) => `
<div class="nav-group">${escape(category.name)}</div>
${category.pages
.map(
(page) =>
`<a href="${escape(page.path ?? pagePath(page.slug))}"${
page.slug === currentSlug ? ' class="active" aria-current="page"' : ''
}>${escape(page.title)}</a>`,
)
.join('\n ')}`,
)
.join('\n');
return ` <aside class="wiki-side">
<a class="wiki-brand" href="/wiki">
<img src="/favicon.svg" alt="" width="36" height="36" />
<div><strong>FWS</strong><span>Documentation</span></div>
</a>
<form class="wiki-search" method="get" action="/wiki">
<input class="input" type="search" name="q" value="${escape(term)}" placeholder="Rechercher…" aria-label="Rechercher dans la documentation" />
</form>
<nav class="wiki-nav">
${groups}
</nav>
</aside>`;
}
/** Table of contents, built from the headings the renderer collected. */
const contents = (headings) =>
headings.length < 2
? ''
: ` <nav class="wiki-toc">
<div class="nav-group">Sur cette page</div>
${headings
.map(
(heading) =>
`<a href="#${escape(heading.id)}" data-level="${heading.level}">${escape(heading.text)}</a>`,
)
.join('\n ')}
</nav>`;
const footerLinks = () => {
const links = [
env.links.website && `<a href="${escape(env.links.website)}">Site</a>`,
env.links.docs && `<a href="${escape(env.links.docs)}">Documentation</a>`,
`<a href="/terms-of-service">Conditions d'utilisation</a>`,
`<a href="/privacy-policy">Politique de confidentialité</a>`,
].filter(Boolean);
return `<footer class="wiki-footer">${links.join(' · ')}</footer>`;
};
const shell = (categories, currentSlug, main, term) => ` <div class="wiki-shell">
${sidebar(categories, currentSlug, term)}
<main class="wiki-main">
${main}
${footerLinks()}
</main>
</div>`;
/** A page, with its body already turned into HTML. */
export function renderPage(page, categories) {
const { html, headings } = renderMarkdown(page.content);
const updated = new Date(`${page.updated_at}Z`);
const main = ` <div class="wiki-article">
<article>
<p class="muted">${escape(page.category)}</p>
<h1>${escape(page.title)}</h1>
${page.summary ? `<p class="wiki-summary">${escape(page.summary)}</p>` : ''}
<div class="wiki-content">
${html}
</div>
<footer class="muted wiki-updated">
Dernière modification :
<time datetime="${escape(updated.toISOString())}">${updated.toLocaleDateString('fr-FR', {
dateStyle: 'long',
})}</time>
</footer>
</article>
${contents(headings)}
</div>`;
return document({
title: `${page.title} · Documentation FWS`,
description: page.summary || `${page.title} — documentation de l'organisation FWS.`,
body: shell(categories, page.slug, main),
});
}
/** Landing page, and the search results when a term is given. */
export function renderIndex(categories, { term = '', results = null } = {}) {
const list = (pages) =>
pages.length === 0
? '<p class="empty">Aucun résultat.</p>'
: `<ul class="wiki-index">${pages
.map(
(page) =>
`<li><a href="${escape(page.path ?? pagePath(page.slug))}">${escape(page.title)}</a>${
page.summary ? ` — <span class="muted">${escape(page.summary)}</span>` : ''
}</li>`,
)
.join('')}</ul>`;
const main = results
? ` <article>
<h1>Recherche</h1>
<p class="muted">${results.length} résultat(s) pour « ${escape(term)} ».</p>
${list(results)}
</article>`
: ` <article>
<h1>Documentation FWS</h1>
<p class="wiki-summary">Tout ce qu'il faut savoir sur le bot et l'organisation.</p>
${categories
.map((category) => `<h2>${escape(category.name)}</h2>${list(category.pages)}`)
.join('\n ')}
</article>`;
return document({
title: 'Documentation FWS',
description: "Documentation publique de l'organisation open source FWS.",
body: shell(categories, null, main, term),
});
}
export function renderNotFound(categories) {
const main = ` <article>
<h1>Page introuvable</h1>
<p class="muted">Cette page n'existe pas, ou n'est pas encore publiée.</p>
<p><a href="/wiki">Revenir à la documentation</a></p>
</article>`;
return document({
title: 'Page introuvable · Documentation FWS',
description: 'Page introuvable.',
body: shell(categories, null, main),
noindex: true,
});
}