diff --git a/src/web/http.js b/src/web/http.js index e770e2f..9b00fa3 100644 --- a/src/web/http.js +++ b/src/web/http.js @@ -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(); } diff --git a/src/web/public/wiki.css b/src/web/public/wiki.css index add65ac..1d47d73 100644 --- a/src/web/public/wiki.css +++ b/src/web/public/wiki.css @@ -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; diff --git a/src/web/public/wiki.html b/src/web/public/wiki.html deleted file mode 100644 index 90bc8e3..0000000 --- a/src/web/public/wiki.html +++ /dev/null @@ -1,19 +0,0 @@ - - - - - - - - Documentation FWS - - - - - -
- -
- - - diff --git a/src/web/public/wiki.js b/src/web/public/wiki.js deleted file mode 100644 index 242e297..0000000 --- a/src/web/public/wiki.js +++ /dev/null @@ -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/` or, for the legal ones, at - // `/`; 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(); diff --git a/src/web/server.js b/src/web/server.js index f56c0c9..46f1f5d 100644 --- a/src/web/server.js +++ b/src/web/server.js @@ -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; } diff --git a/src/web/services/wiki-render.js b/src/web/services/wiki-render.js new file mode 100644 index 0000000..5aee81e --- /dev/null +++ b/src/web/services/wiki-render.js @@ -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('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"'); + +const document = ({ title, description, body, noindex = false }) => ` + + + + + + + + ${escape(title)} + + + + + +${body} + + +`; + +/** Sidebar: the page tree and a search box that works without scripts. */ +function sidebar(categories, currentSlug, term = '') { + const groups = categories + .map( + (category) => ` + + ${category.pages + .map( + (page) => + `${escape(page.title)}`, + ) + .join('\n ')}`, + ) + .join('\n'); + + return ` `; +} + +/** Table of contents, built from the headings the renderer collected. */ +const contents = (headings) => + headings.length < 2 + ? '' + : ` `; + +const footerLinks = () => { + const links = [ + env.links.website && `Site`, + env.links.docs && `Documentation`, + `Conditions d'utilisation`, + `Politique de confidentialité`, + ].filter(Boolean); + return `
${links.join(' · ')}
`; +}; + +const shell = (categories, currentSlug, main, term) => `
+${sidebar(categories, currentSlug, term)} +
+${main} +${footerLinks()} +
+
`; + +/** 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 = `
+
+

${escape(page.category)}

+

${escape(page.title)}

+ ${page.summary ? `

${escape(page.summary)}

` : ''} +
+${html} +
+
+ Dernière modification : + +
+
+${contents(headings)} +
`; + + 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 + ? '

Aucun résultat.

' + : ``; + + const main = results + ? `
+

Recherche

+

${results.length} résultat(s) pour « ${escape(term)} ».

+ ${list(results)} +
` + : `
+

Documentation FWS

+

Tout ce qu'il faut savoir sur le bot et l'organisation.

+ ${categories + .map((category) => `

${escape(category.name)}

${list(category.pages)}`) + .join('\n ')} +
`; + + 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 = ` `; + + return document({ + title: 'Page introuvable · Documentation FWS', + description: 'Page introuvable.', + body: shell(categories, null, main), + noindex: true, + }); +} diff --git a/tests/web-wiki.test.js b/tests/web-wiki.test.js index bede6b8..c55aa26 100644 --- a/tests/web-wiki.test.js +++ b/tests/web-wiki.test.js @@ -207,10 +207,48 @@ describe('wiki over HTTP', () => { 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`); + assert.match(response.headers.get('content-type'), /text\/html/); } }); + /** + * The point of the whole exercise: whoever checks these links before + * approving an application does not run scripts. + */ + it('delivers the legal text without any script', async () => { + const terms = await get('/terms-of-service').then((response) => response.text()); + const privacy = await get('/privacy-policy').then((response) => response.text()); + + assert.match(terms, /droit suisse/, 'les conditions ne sont pas dans le HTML'); + assert.match(privacy, /LPD/, 'la politique n’est pas dans le HTML'); + assert.match(privacy, /PFPDT/); + assert.doesNotMatch(terms, /