source: Klonkt/src/middleware/render.js@ c1f5c23

main
Last change on this file since c1f5c23 was c6185fa, checked in by Robin <roboburr@…>, 7 weeks ago

Guardian-PWA: CSP-nonce injecteren zodat de JS laadt

DIT was de echte oorzaak van "guardian-PWA doet niks / hangt / niks functioneel",
en waarom cache legen en incognito nooit hielpen: het is geen caching.

De guardian-PWA wordt direct met res.render gerenderd, NIET via renderPage. Alleen
renderPage draait injectCspNonce over de HTML. Onze CSP is strict-dynamic + per-
request nonce, dus een <script src="/guardian/app.js"> zonder nonce wordt door de
browser geweigerd (precies de fout die Robin zag op boiert.eu). Gevolg: guardian.js
laadde nooit, dus alle knoppen deden niks. Dit gold ook al voor de oude
/assets/js/guardian.js; de no-cache-verhuizing veranderde daar niks aan.

Fix: de guardian-render door injectCspNonce halen, net als de rest van de app.
injectCspNonce is nu exporteerbaar. Geverifieerd: na injectie heeft het app.js-
script de per-request nonce.

Changed files:
src/middleware/render.js

  • injectCspNonce geexporteerd

src/routes/guardian.js

  • guardian-PWA gerenderd naar string en nonce geinjecteerd (anders blokkeert strict-dynamic de JS)

remarks: embed-player zet een eigen CSP (unsafe-inline) en is niet geraakt. Tests 6/6.

-robo
Co-Authored-By: Claude Opus 4.8 <noreply@…>

  • Property mode set to 100644
File size: 14.3 KB
Line 
1/**
2 * Render helper — THE pattern for the entire app.
3 *
4 * Two modes:
5 * 1. HTMX request → render just the page content (no shell)
6 * 2. Full page request → render content, then embed in shell
7 *
8 * Usage:
9 * renderPage(req, res, 'pages/home', { posts, ...data })
10 */
11
12import fs from 'fs';
13import path from 'path';
14import { fileURLToPath } from 'url';
15import ejs from 'ejs';
16import db from '../config/database.js';
17import PermissionsService from '../services/PermissionsService.js';
18import { isViewer } from './auth.js';
19import { getSetting, apEnabled } from '../services/SettingsService.js';
20import { isPremium as isPremiumInstance, premiumEnabled, premiumUnlocked } from '../services/PatreonService.js';
21import ActivityPubService from '../services/ActivityPubService.js';
22import { imgProxyUrl } from '../services/ThumbnailService.js';
23import { audioEnabled as audioFeatureEnabled } from '../config/features.js';
24
25// Add the per-request CSP nonce to every <script> tag that doesn't already have one, so the
26// strict script-src (nonce + 'strict-dynamic') allows them — including scripts in htmx
27// partials. HTML-escaped "&lt;script" in rendered content (e.g. sanitized post bodies) won't
28// match, so this only touches real tags.
29export function injectCspNonce(html, nonce) {
30 if (!html || !nonce) return html;
31 return String(html).replace(/<script(?![^>]*\snonce=)/gi, () => `<script nonce="${nonce}"`);
32}
33import { PLATFORMS as PLATFORMS_CATALOG } from '../services/PlatformIcons.js';
34import { t as i18nT, resolveLang, SUPPORTED as LANGS, LANG_NAMES } from '../services/i18n.js';
35
36const __dirname = path.dirname(fileURLToPath(import.meta.url));
37const VIEWS_DIR = path.join(__dirname, '..', 'views');
38
39// App version (from package.json) + short commit hash (from .klonkt-version, written by
40// the deploy script) — shown in the footer next to "Klonkt Beta". The hash is updated
41// automatically on every deploy, so the displayed version is never stale.
42let APP_VERSION = '';
43try {
44 APP_VERSION = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8')).version || '';
45 try {
46 const sha = fs.readFileSync(path.join(__dirname, '..', '..', '.klonkt-version'), 'utf8').trim().slice(0, 7);
47 if (sha) APP_VERSION += ' · ' + sha;
48 } catch { /* no .klonkt-version (local dev) */ }
49} catch { /* no version available */ }
50
51// Site timezone (Admin → Settings). Empty = server default (UTC). Applied to
52// all server-side formatted dates so they display in the site's timezone instead of UTC.
53const siteTimezone = () => getSetting('timezone') || undefined;
54
55const formatDate = (iso) => {
56 if (!iso) return '';
57 return new Date(iso).toLocaleDateString('nl-NL', { timeZone: siteTimezone(), day: 'numeric', month: 'long', year: 'numeric' });
58};
59
60const formatDateTime = (iso) => {
61 if (!iso) return '';
62 return new Date(iso).toLocaleString('nl-NL', { timeZone: siteTimezone(), dateStyle: 'medium', timeStyle: 'short' });
63};
64
65export async function renderPage(req, res, viewName, data = {}) {
66 // Decide: partial (HTMX) or full?
67 const isPartial = req.headers['hx-request'] === 'true' || req.query.partial === '1';
68
69 // Prevent the browser from caching an htmx PARTIAL (only #pcms-main, without <head>/CSS)
70 // under the same URL and serving it as a full page on "back" → unstyled HTML.
71 // Vary: HX-Request separates partial and full responses in the cache;
72 // no-store on the partial forces "back" to always re-fetch the full page.
73 // (Vary also applies to intermediate caches / Cloudflare.)
74 res.setHeader('Vary', 'HX-Request');
75 // A full HTML page must always be revalidated so an online visitor gets the
76 // fresh site, never a heuristically-cached copy. no-cache (not no-store) still
77 // allows bfcache and conditional requests. Partials stay no-store (see above).
78 res.setHeader('Cache-Control', isPartial ? 'no-store' : 'no-cache');
79
80 // Does this (non-god) user own a site? Determines whether they see an "Admin"
81 // entry (artist self-manage). god always sees admin (by role).
82 let _u = req.session?.user || null;
83 // Refresh avatar + role from the DB so a stale session (e.g. after an
84 // avatar change or role switch) heals itself without a new login.
85 if (_u && _u.id) {
86 const _fresh = db.prepare('SELECT role, lang FROM users WHERE id = ?').get(_u.id);
87 if (_fresh) _u = { ..._u, role: _fresh.role, lang: _fresh.lang };
88 // ONE image: a user's avatar everywhere (nav, account, comments) is simply their SITE
89 // photo — there is no separate account avatar. Falls back to the initial-letter
90 // placeholder when the site has no photo yet.
91 const _sp = db.prepare("SELECT profile_photo FROM sites WHERE owner_id = ? AND profile_photo IS NOT NULL ORDER BY is_primary DESC, created_at ASC LIMIT 1").get(_u.id);
92 _u = { ..._u, avatar_url: (_sp && _sp.profile_photo) || null };
93 }
94 const userOwnsSite = !!(_u && _u.role !== 'god' &&
95 db.prepare('SELECT 1 FROM sites WHERE owner_id = ? LIMIT 1').get(_u.id));
96
97 const _site = data.site || res.locals.site || null;
98 // The site header uses the SITE photo (site.profile_photo) — the one and only image,
99 // set in site settings. (No separate account-avatar fallback anymore.)
100 const siteOwnerAvatar = null;
101
102 // Viewer mode: may view everything, change nothing. Views use canMutate
103 // to hide/disable write buttons (post, save, delete).
104 const _isViewer = isViewer(_u);
105
106 // Embeds are framed broadly (frame-src https: globally), EXCEPT on authorize_interaction:
107 // that page renders untrusted remote content next to the interact buttons, so lock its
108 // frame-src down to 'self' (no embeds → no clickjacking/overlay over the buttons).
109 if (viewName === 'pages/authorize-interaction') {
110 try {
111 const csp = res.getHeader('Content-Security-Policy');
112 if (csp) res.setHeader('Content-Security-Policy', String(csp).replace(/frame-src [^;]*/i, "frame-src 'self'"));
113 } catch { /* best-effort */ }
114 }
115
116 // Who sees the "Admin" link? god/admin, a site owner (artist self-manage),
117 // and a viewer (may view Admin read-only). One source of truth,
118 // mirrored in topnav/hub-nav/profile sheet — otherwise the link gets hidden
119 // for those who should see it (viewer didn't see it anywhere before).
120 const _role = _u ? _u.role : null;
121 const canSeeBeheer = !!(_u && (_role === 'god' || _role === 'admin' || _role === 'kijker' || userOwnsSite));
122 // Who may use the fediverse client (timeline/notifications/blocking) — actual
123 // site managers only (these routes are requireSiteManager; viewers are excluded).
124 const canManageFedi = !!(_u && (_role === 'god' || _role === 'admin' || userOwnsSite));
125
126 // Interface language: session choice (this session) → logged-in user's own preference
127 // (users.lang) → admin-set default (Admin → Settings) → env → browser → nl.
128 const _lang = resolveLang(req, {
129 userLang: _u && _u.lang,
130 defaultLang: getSetting('default_lang'),
131 });
132
133 // Common locals
134 const locals = {
135 user: _u,
136 lang: _lang,
137 t: (key, vars) => i18nT(_lang, key, vars),
138 langs: LANGS.map((c) => ({ code: c, name: LANG_NAMES[c], active: c === _lang })),
139 timezone: getSetting('timezone') || '',
140 notifUnread: (canManageFedi && _site) ? ActivityPubService.countUnseenNotifications(_site.slug) : 0,
141 userOwnsSite,
142 canSeeBeheer,
143 canManageFedi,
144 apEnabled: apEnabled(),
145 // Cirkel = the artists you feature (auto-boost). Shown when AP is on and you
146 // auto-boost ≥1 account, or (legacy) on a circle-tenancy site.
147 hasCirkel: !!(_site && apEnabled() && (ActivityPubService.autoBoostCount(_site.slug) > 0 || ActivityPubService.boostedCount(_site.slug) > 0)),
148 isViewer: _isViewer,
149 canMutate: !_isViewer,
150 isPremium: isPremiumInstance(),
151 premiumEnabled: premiumEnabled(),
152 premiumUnlocked: premiumUnlocked(),
153 siteOwnerAvatar,
154 site: _site,
155 audioEnabled: audioFeatureEnabled(),
156 audioTracks: data.audioTracks || res.locals.audioTracks || [],
157 siteUrlBase: res.locals.siteUrlBase || '',
158 tenancy: res.locals.tenancy || 'solo',
159 hubTitle: getSetting('hub_title') || '',
160 footerNewsletter: getSetting('footer_newsletter') === '1', // newsletter sign-up in footer (premium)
161 agendaEnabled: getSetting('agenda_enabled') === '1', // show agenda/events in the pill (premium, opt-in)
162 platforms_catalog: PLATFORMS_CATALOG,
163 permissions: PermissionsService,
164 formatDate,
165 formatDateTime,
166 // Rewrite a local /media/<file> cover to its on-demand downscaled thumbnail
167 // (crisp grid/list images). External URLs + already-thumb URLs pass through.
168 thumb: (url, w) => {
169 if (!url || typeof url !== 'string') return url;
170 // Local cover → local thumb route; remote (federated) cover → signed downscale
171 // proxy (same as avatars), so remote line-art covers aren't browser-downscaled jagged.
172 if (url.startsWith('/media/') && !url.startsWith('/media/thumb/')) return `/media/thumb/${w || 480}/${url.slice(7)}`;
173 if (/^https?:\/\//i.test(url)) return imgProxyUrl(url, w || 480);
174 return url;
175 },
176 // Crisp avatars: a local /media avatar goes through the local thumb route; a REMOTE
177 // (fediverse) avatar through the signed downscaling proxy. Same downscale, the remote
178 // one is just fetched first. Default 128px (covers feed 44px → profile ~120px).
179 avatar: (url, w) => {
180 if (!url || typeof url !== 'string') return url;
181 if (url.startsWith('/media/') && !url.startsWith('/media/thumb/')) return `/media/thumb/${w || 128}/${url.slice(7)}`;
182 if (/^https?:\/\//i.test(url)) return imgProxyUrl(url, w || 128);
183 return url;
184 },
185 // pageTitleKey (translated with the resolved language) wins over a raw pageTitle string,
186 // so admin page titles aren't hardcoded in one language. Falls back to the site title.
187 pageTitle: (data.pageTitleKey ? i18nT(_lang, data.pageTitleKey, data.pageTitleVars) : data.pageTitle)
188 || (data.site && data.site.title) || 'Klonkt',
189 appVersion: APP_VERSION,
190 bodyClass: data.bodyClass || 'on-home',
191 socialDescr: data.socialDescr || '',
192 socialImage: data.socialImage || '',
193 cspNonce: () => '',
194 currentPath: req.path,
195 // Absolute origin (for building absolute URLs like the generated og:image).
196 ogOrigin: (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host') || ''}`).replace(/\/+$/, ''),
197 ...data,
198 };
199
200 try {
201 // Step 1: Render the page view to HTML
202 const viewPath = path.join(VIEWS_DIR, viewName + '.ejs');
203 const pageContent = await ejs.renderFile(viewPath, locals, { async: false });
204
205 if (isPartial) {
206 // HTMX: just send the content. Set HX-Trigger for body class swap.
207 // HTTP-header values are Latin-1 only — a title with an em-dash, smart
208 // quote or emoji (e.g. "Welkom — gebouwd met Klonkt") would make
209 // setHeader throw ERR_INVALID_CHAR and 500 the partial, so the card
210 // looks "unclickable". Escape any non-ASCII to \uXXXX: the header stays
211 // ASCII-safe and remains valid JSON that htmx parses back unchanged.
212 // Per-site accent + palette live in the shell <head> (style#pcms-site-accent
213 // + html[data-palette]) and are NOT swapped during htmx navigation. Send them along
214 // so the client updates them — otherwise an artist inherits the previous page's
215 // colours (e.g. hub-purple instead of their own green). Same derivation as shell.ejs.
216 const _navAccent = (_site && _site.accent && /^#[0-9a-fA-F]{6}$/.test(_site.accent))
217 ? _site.accent : '#e8b04b';
218 const _navPalette = (_site && _site.palette) ? _site.palette : 'klonkt';
219 const triggerJson = JSON.stringify({
220 pcmsNav: { bodyClass: locals.bodyClass, accent: _navAccent, palette: _navPalette },
221 pcmsPostSwap: data.post ? {
222 title: data.post.title,
223 slug: data.post.slug,
224 pageTitle: locals.pageTitle,
225 } : null,
226 }).replace(/[€-￿]/g, (ch) => '\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0'));
227 res.setHeader('HX-Trigger-After-Settle', triggerJson);
228 // Render the site chrome out-of-band so the header (topnav/profile header/
229 // view-switcher) ALWAYS matches the new page/artist on navigation —
230 // while the audio player (separate in document.body) keeps playing (no
231 // interruption). htmx replaces #pcms-chrome via hx-swap-oob. Non-critical:
232 // if it fails, the old chrome remains (no crash).
233 let oobChrome = '';
234 try {
235 oobChrome = await ejs.renderFile(
236 path.join(VIEWS_DIR, 'partials', 'chrome.ejs'),
237 { ...locals, oob: true },
238 { async: false },
239 );
240 } catch (e) { /* skip chrome OOB */ }
241 return res.send(injectCspNonce(pageContent + oobChrome, res.locals.cspNonce));
242 }
243
244 // Full: wrap content in shell (rendered to a string so we can inject the CSP nonce).
245 locals.pageContent = pageContent;
246 const shellHtml = await ejs.renderFile(path.join(VIEWS_DIR, 'shell.ejs'), locals, { async: false });
247 res.send(injectCspNonce(shellHtml, res.locals.cspNonce));
248 } catch (err) {
249 console.error('[renderPage] Error rendering', viewName, err);
250 if (process.env.NODE_ENV === 'production') {
251 return res.status(500).send('Internal Server Error');
252 }
253 // Dev: surface the underlying cause prominently. EJS rewrites err.message
254 // to include the file/line/code-context, so we also surface name+stack
255 // separately in case the message was truncated or empty.
256 const escape = (s) => String(s == null ? '' : s)
257 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
258 res.status(500).send(`<!doctype html>
259<meta charset="utf-8">
260<title>Render error: ${escape(viewName)}</title>
261<style>
262 body { font: 14px/1.5 ui-monospace, monospace; max-width: 1100px; margin: 2rem auto; padding: 0 1rem; background:#1a1a1a; color:#eee; }
263 h1 { color:#dc2626; font-family: ui-sans-serif, system-ui; }
264 h2 { color:#fb923c; font-size:1rem; margin-top:1.5rem; }
265 pre { background:#0a0a0a; border:1px solid #333; border-radius:6px; padding:1rem; overflow:auto; white-space:pre-wrap; word-break:break-word; }
266 .cause { background:#3d0a0a; border-color:#7a1a1a; color:#fca5a5; font-weight:600; }
267</style>
268<h1>Render error in ${escape(viewName)}</h1>
269<h2>Cause</h2>
270<pre class="cause">${escape(err.name || 'Error')}: ${escape(err.message || '(no message)')}</pre>
271<h2>Stack</h2>
272<pre>${escape(err.stack || '(no stack)')}</pre>
273${err.path ? `<h2>File</h2><pre>${escape(err.path)}</pre>` : ''}
274`);
275 }
276}
Note: See TracBrowser for help on using the repository browser.