From e5b7303a01ff4b25e41a332deb1977f1aebaa202 Mon Sep 17 00:00:00 2001 From: nocode Date: Wed, 23 Sep 2026 21:35:46 +0200 Subject: [PATCH] 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) --- src/web/public/app.js | 8 ++ src/web/public/core/markdown.js | 168 ++++++++++++++++++++++ src/web/public/views/wiki.js | 240 ++++++++++++++++++++++++++++++++ src/web/public/wiki.css | 198 ++++++++++++++++++++++++++ src/web/public/wiki.html | 19 +++ src/web/public/wiki.js | 183 ++++++++++++++++++++++++ tests/web-wiki.test.js | 215 ++++++++++++++++++++++++++++ 7 files changed, 1031 insertions(+) create mode 100644 src/web/public/core/markdown.js create mode 100644 src/web/public/views/wiki.js create mode 100644 src/web/public/wiki.css create mode 100644 src/web/public/wiki.html create mode 100644 src/web/public/wiki.js create mode 100644 tests/web-wiki.test.js diff --git a/src/web/public/app.js b/src/web/public/app.js index b4f7de5..bb73d99 100644 --- a/src/web/public/app.js +++ b/src/web/public/app.js @@ -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: '≡', diff --git a/src/web/public/core/markdown.js b/src/web/public/core/markdown.js new file mode 100644 index 0000000..3b9d9d5 --- /dev/null +++ b/src/web/public/core/markdown.js @@ -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('&', '&') + .replaceAll('<', '<') + .replaceAll('>', '>') + .replaceAll('"', '"'); + +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, '$1') + .replace( + /!\[([^\]]*)\]\(([^)\s]+)\)/g, + (_, alt, src) => `${alt}`, + ) + .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 `${label}`; + }) + .replace(/\*\*([^*]+)\*\*/g, '$1') + .replace(/(^|[^*])\*([^*\n]+)\*/g, '$1$2') + .replace(/~~([^~]+)~~/g, '$1'); +} + +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(``); + }; + 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(`
${body.join('\n')}
`); + 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( + `
${header + .map((cell) => ``) + .join('')}${rows + .map((row) => `${row.map((cell) => ``).join('')}`) + .join('')}
${cell}
${cell}
`, + ); + 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(`${inline(text)}`); + index += 1; + continue; + } + + if (/^\s*(---|\*\*\*)\s*$/.test(line)) { + closeList(listStack); + out.push('
'); + index += 1; + continue; + } + + const quote = /^>\s?(.*)$/.exec(line); + if (quote) { + closeList(listStack); + const body = [quote[1]]; + index += 1; + while (index < lines.length && /^>\s?/.test(lines[index])) { + body.push(lines[index++].replace(/^>\s?/, '')); + } + out.push(`
${inline(body.join(' '))}
`); + 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(`
  • ${inline((bullet ?? ordered)[1])}
  • `); + 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|>|```)/.test(lines[index]) && + !lines[index].includes('|') + ) { + paragraph.push(lines[index++]); + } + out.push(`

    ${inline(paragraph.join(' '))}

    `); + } + + closeList(listStack); + return { html: out.join('\n'), headings }; +} diff --git a/src/web/public/views/wiki.js b/src/web/public/views/wiki.js new file mode 100644 index 0000000..b82c405 --- /dev/null +++ b/src/web/public/views/wiki.js @@ -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.' }, + ), + ), + ); + }, + ); +} diff --git a/src/web/public/wiki.css b/src/web/public/wiki.css new file mode 100644 index 0000000..add65ac --- /dev/null +++ b/src/web/public/wiki.css @@ -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; + } +} diff --git a/src/web/public/wiki.html b/src/web/public/wiki.html new file mode 100644 index 0000000..90bc8e3 --- /dev/null +++ b/src/web/public/wiki.html @@ -0,0 +1,19 @@ + + + + + + + + Documentation FWS + + + + + +
    + +
    + + + diff --git a/src/web/public/wiki.js b/src/web/public/wiki.js new file mode 100644 index 0000000..88ae525 --- /dev/null +++ b/src/web/public/wiki.js @@ -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(); diff --git a/tests/web-wiki.test.js b/tests/web-wiki.test.js new file mode 100644 index 0000000..25f994b --- /dev/null +++ b/tests/web-wiki.test.js @@ -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(''); + assert.doesNotMatch(html, /