source: Klonkt/src/middleware/render.js@ 5421ce1

main
Last change on this file since 5421ce1 was 5421ce1, checked in by Robin Genis <roboburr@…>, 3 months ago

fix(csp): per-domain frame-src for cross-site embeds on the document (not authorize_interaction)

  • middleware/render.js — renderPage now appends the site's timeline origins (followed + boosted, from ap_timeline, 60s cache) to the document CSP frame-src for a logged-in site manager, so cross-site Klonkt embeds also load after an htmx/PWA navigation (the per-/news injection is ignored once you navigate via htmx). Excluded on pages/authorize-interaction — untrusted remote content next to the interact buttons, so no embeds / no frame-src loosening there (clickjacking).
  • Property mode set to 100644
File size: 13.3 KB
RevLine 
[7bc636b]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
[83faa57]12import fs from 'fs';
[7bc636b]13import path from 'path';
14import { fileURLToPath } from 'url';
15import ejs from 'ejs';
[8cb1dc7]16import db from '../config/database.js';
[7bc636b]17import PermissionsService from '../services/PermissionsService.js';
[8afbdd6]18import { isViewer } from './auth.js';
[283f618]19import { getSetting, apEnabled } from '../services/SettingsService.js';
[8aa85d0]20import { isPremium as isPremiumInstance, premiumEnabled, premiumUnlocked } from '../services/PatreonService.js';
[e951b7c]21import ActivityPubService from '../services/ActivityPubService.js';
[cb01666]22import { audioEnabled as audioFeatureEnabled } from '../config/features.js';
[7bc636b]23import { PLATFORMS as PLATFORMS_CATALOG } from '../services/PlatformIcons.js';
[03fa548]24import { t as i18nT, resolveLang, SUPPORTED as LANGS, LANG_NAMES } from '../services/i18n.js';
[7bc636b]25
26const __dirname = path.dirname(fileURLToPath(import.meta.url));
27const VIEWS_DIR = path.join(__dirname, '..', 'views');
28
[834bcc3]29// App version (from package.json) + short commit hash (from .klonkt-version, written by
30// the deploy script) — shown in the footer next to "Klonkt Beta". The hash is updated
31// automatically on every deploy, so the displayed version is never stale.
[83faa57]32let APP_VERSION = '';
33try {
34 APP_VERSION = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8')).version || '';
[3bb8719]35 try {
36 const sha = fs.readFileSync(path.join(__dirname, '..', '..', '.klonkt-version'), 'utf8').trim().slice(0, 7);
37 if (sha) APP_VERSION += ' · ' + sha;
[834bcc3]38 } catch { /* no .klonkt-version (local dev) */ }
39} catch { /* no version available */ }
[83faa57]40
[834bcc3]41// Site timezone (Admin → Settings). Empty = server default (UTC). Applied to
42// all server-side formatted dates so they display in the site's timezone instead of UTC.
[421c2d4]43const siteTimezone = () => getSetting('timezone') || undefined;
44
[7bc636b]45const formatDate = (iso) => {
46 if (!iso) return '';
[421c2d4]47 return new Date(iso).toLocaleDateString('nl-NL', { timeZone: siteTimezone(), day: 'numeric', month: 'long', year: 'numeric' });
[7bc636b]48};
49
50const formatDateTime = (iso) => {
51 if (!iso) return '';
[421c2d4]52 return new Date(iso).toLocaleString('nl-NL', { timeZone: siteTimezone(), dateStyle: 'medium', timeStyle: 'short' });
[7bc636b]53};
54
[5421ce1]55// Cross-site Klonkt audio embeds (a followed/boosted site's /embed player) need their
56// origins in the DOCUMENT CSP frame-src — the per-/news injection is ignored once you
57// navigate there via htmx (the document's CSP governs, not the partial's). Collect the
58// distinct origins from the site's timeline (followed + boosted). Cached 60s.
59const _embedOriginsCache = new Map(); // slug -> { origins, exp }
60function embedOriginsFor(slug) {
61 const now = Date.now();
62 const c = _embedOriginsCache.get(slug);
63 if (c && c.exp > now) return c.origins;
64 let origins = [];
65 try {
66 const rows = db.prepare('SELECT DISTINCT url FROM ap_timeline WHERE slug = ? AND url IS NOT NULL').all(slug);
67 const set = new Set();
68 for (const r of rows) { try { set.add(new URL(r.url).origin); } catch { /* skip bad url */ } }
69 origins = [...set];
70 } catch { origins = []; }
71 _embedOriginsCache.set(slug, { origins, exp: now + 60000 });
72 return origins;
73}
74
[7bc636b]75export async function renderPage(req, res, viewName, data = {}) {
76 // Decide: partial (HTMX) or full?
77 const isPartial = req.headers['hx-request'] === 'true' || req.query.partial === '1';
78
[834bcc3]79 // Prevent the browser from caching an htmx PARTIAL (only #pcms-main, without <head>/CSS)
80 // under the same URL and serving it as a full page on "back" → unstyled HTML.
81 // Vary: HX-Request separates partial and full responses in the cache;
82 // no-store on the partial forces "back" to always re-fetch the full page.
83 // (Vary also applies to intermediate caches / Cloudflare.)
[d5e78f7]84 res.setHeader('Vary', 'HX-Request');
85 if (isPartial) res.setHeader('Cache-Control', 'no-store');
86
[834bcc3]87 // Does this (non-god) user own a site? Determines whether they see an "Admin"
88 // entry (artist self-manage). god always sees admin (by role).
[1ee967d]89 let _u = req.session?.user || null;
[834bcc3]90 // Refresh avatar + role from the DB so a stale session (e.g. after an
91 // avatar change or role switch) heals itself without a new login.
[1ee967d]92 if (_u && _u.id) {
[5e61b17]93 const _fresh = db.prepare('SELECT avatar_url, role, lang FROM users WHERE id = ?').get(_u.id);
94 if (_fresh) _u = { ..._u, avatar_url: _fresh.avatar_url, role: _fresh.role, lang: _fresh.lang };
[82079ad]95 // One identity: no own account avatar → fall back to the user's site photo,
96 // so the same picture shows everywhere (nav, account, comments).
97 if (_u && !_u.avatar_url) {
98 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);
99 if (_sp && _sp.profile_photo) _u = { ..._u, avatar_url: _sp.profile_photo };
100 }
[1ee967d]101 }
[8cb1dc7]102 const userOwnsSite = !!(_u && _u.role !== 'god' &&
103 db.prepare('SELECT 1 FROM sites WHERE owner_id = ? LIMIT 1').get(_u.id));
104
[834bcc3]105 // The avatar of the SITE OWNER (not the viewer!) — for the Klonkt site header,
106 // so the artist can use their own account photo as the site photo.
[ab544fd]107 const _site = data.site || res.locals.site || null;
108 const siteOwnerAvatar = (_site && _site.owner_id)
109 ? (db.prepare('SELECT avatar_url FROM users WHERE id = ?').get(_site.owner_id)?.avatar_url || null)
110 : null;
111
[834bcc3]112 // Viewer mode: may view everything, change nothing. Views use canMutate
113 // to hide/disable write buttons (post, save, delete).
[8afbdd6]114 const _isViewer = isViewer(_u);
115
[5421ce1]116 // Per-domain CSP: let a logged-in site manager frame the Klonkt players of the sites in
117 // their timeline (followed + boosted) on the DOCUMENT, so cross-site embeds also work
118 // after an htmx/PWA navigation. NEVER on authorize_interaction — that page shows
119 // untrusted remote content next to the interact buttons, so no embeds / no frame-src
120 // loosening there (clickjacking risk).
121 try {
122 if (_site && _site.slug && viewName !== 'pages/authorize-interaction' && _u && PermissionsService.canAdminSite(_u, _site)) {
123 const origins = embedOriginsFor(_site.slug);
124 if (origins.length) {
125 const csp = res.getHeader('Content-Security-Policy');
126 if (csp) res.setHeader('Content-Security-Policy', String(csp).replace(/frame-src ([^;]*)/i, (m, g) => `frame-src ${g} ${origins.join(' ')}`));
127 }
128 }
129 } catch { /* CSP extension is best-effort */ }
130
[834bcc3]131 // Who sees the "Admin" link? god/admin, a site owner (artist self-manage),
132 // and a viewer (may view Admin read-only). One source of truth,
133 // mirrored in topnav/hub-nav/profile sheet — otherwise the link gets hidden
134 // for those who should see it (viewer didn't see it anywhere before).
[a3169f5]135 const _role = _u ? _u.role : null;
136 const canSeeBeheer = !!(_u && (_role === 'god' || _role === 'admin' || _role === 'kijker' || userOwnsSite));
[f5c3870]137 // Who may use the fediverse client (timeline/notifications/blocking) — actual
138 // site managers only (these routes are requireSiteManager; viewers are excluded).
139 const canManageFedi = !!(_u && (_role === 'god' || _role === 'admin' || userOwnsSite));
[a3169f5]140
[834bcc3]141 // Interface language: session choice (this session) → logged-in user's own preference
142 // (users.lang) → admin-set default (Admin → Settings) → env → browser → nl.
[5e61b17]143 const _lang = resolveLang(req, {
144 userLang: _u && _u.lang,
145 defaultLang: getSetting('default_lang'),
146 });
[03fa548]147
[7bc636b]148 // Common locals
149 const locals = {
[8cb1dc7]150 user: _u,
[03fa548]151 lang: _lang,
152 t: (key, vars) => i18nT(_lang, key, vars),
153 langs: LANGS.map((c) => ({ code: c, name: LANG_NAMES[c], active: c === _lang })),
[421c2d4]154 timezone: getSetting('timezone') || '',
[e951b7c]155 notifUnread: (canManageFedi && _site) ? ActivityPubService.countUnseenNotifications(_site.slug) : 0,
[8cb1dc7]156 userOwnsSite,
[a3169f5]157 canSeeBeheer,
[f5c3870]158 canManageFedi,
[283f618]159 apEnabled: apEnabled(),
[2c22bb5]160 // Cirkel = the artists you feature (auto-boost). Shown when AP is on and you
161 // auto-boost ≥1 account, or (legacy) on a circle-tenancy site.
[5045c30]162 hasCirkel: !!(_site && apEnabled() && (ActivityPubService.autoBoostCount(_site.slug) > 0 || ActivityPubService.boostedCount(_site.slug) > 0)),
[8afbdd6]163 isViewer: _isViewer,
164 canMutate: !_isViewer,
[1b4d5dd]165 isPremium: isPremiumInstance(),
166 premiumEnabled: premiumEnabled(),
[8aa85d0]167 premiumUnlocked: premiumUnlocked(),
[ab544fd]168 siteOwnerAvatar,
169 site: _site,
[cb01666]170 audioEnabled: audioFeatureEnabled(),
[7bc636b]171 audioTracks: data.audioTracks || res.locals.audioTracks || [],
172 siteUrlBase: res.locals.siteUrlBase || '',
[2cc887b]173 tenancy: res.locals.tenancy || 'solo',
[42081fb]174 hubTitle: getSetting('hub_title') || '',
[834bcc3]175 footerNewsletter: getSetting('footer_newsletter') === '1', // newsletter sign-up in footer (premium)
176 agendaEnabled: getSetting('agenda_enabled') === '1', // show agenda/events in the pill (premium, opt-in)
[7bc636b]177 platforms_catalog: PLATFORMS_CATALOG,
178 permissions: PermissionsService,
179 formatDate,
180 formatDateTime,
[83faa57]181 pageTitle: data.pageTitle || (data.site && data.site.title) || 'Klonkt Beta',
182 appVersion: APP_VERSION,
[7bc636b]183 bodyClass: data.bodyClass || 'on-home',
184 socialDescr: data.socialDescr || '',
185 socialImage: data.socialImage || '',
186 cspNonce: () => '',
187 currentPath: req.path,
[69815b2]188 // Absolute origin (for building absolute URLs like the generated og:image).
189 ogOrigin: (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host') || ''}`).replace(/\/+$/, ''),
[7bc636b]190 ...data,
191 };
192
193 try {
194 // Step 1: Render the page view to HTML
195 const viewPath = path.join(VIEWS_DIR, viewName + '.ejs');
196 const pageContent = await ejs.renderFile(viewPath, locals, { async: false });
197
198 if (isPartial) {
[00d54bc]199 // HTMX: just send the content. Set HX-Trigger for body class swap.
200 // HTTP-header values are Latin-1 only — a title with an em-dash, smart
201 // quote or emoji (e.g. "Welkom — gebouwd met Klonkt") would make
202 // setHeader throw ERR_INVALID_CHAR and 500 the partial, so the card
203 // looks "unclickable". Escape any non-ASCII to \uXXXX: the header stays
204 // ASCII-safe and remains valid JSON that htmx parses back unchanged.
[834bcc3]205 // Per-site accent + palette live in the shell <head> (style#pcms-site-accent
206 // + html[data-palette]) and are NOT swapped during htmx navigation. Send them along
207 // so the client updates them — otherwise an artist inherits the previous page's
208 // colours (e.g. hub-purple instead of their own green). Same derivation as shell.ejs.
[a3e2f17]209 const _navAccent = (_site && _site.accent && /^#[0-9a-fA-F]{6}$/.test(_site.accent))
[9b851e7]210 ? _site.accent : '#e8b04b';
[dd7e2a2]211 const _navPalette = (_site && _site.palette) ? _site.palette : 'klonkt';
[00d54bc]212 const triggerJson = JSON.stringify({
[a3e2f17]213 pcmsNav: { bodyClass: locals.bodyClass, accent: _navAccent, palette: _navPalette },
[7bc636b]214 pcmsPostSwap: data.post ? {
215 title: data.post.title,
216 slug: data.post.slug,
217 pageTitle: locals.pageTitle,
218 } : null,
[00d54bc]219 }).replace(/[€-￿]/g, (ch) => '\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0'));
220 res.setHeader('HX-Trigger-After-Settle', triggerJson);
[834bcc3]221 // Render the site chrome out-of-band so the header (topnav/profile header/
222 // view-switcher) ALWAYS matches the new page/artist on navigation —
223 // while the audio player (separate in document.body) keeps playing (no
224 // interruption). htmx replaces #pcms-chrome via hx-swap-oob. Non-critical:
225 // if it fails, the old chrome remains (no crash).
[3cd1aaa]226 let oobChrome = '';
227 try {
228 oobChrome = await ejs.renderFile(
229 path.join(VIEWS_DIR, 'partials', 'chrome.ejs'),
230 { ...locals, oob: true },
231 { async: false },
232 );
[834bcc3]233 } catch (e) { /* skip chrome OOB */ }
[3cd1aaa]234 return res.send(pageContent + oobChrome);
[7bc636b]235 }
236
237 // Full: wrap content in shell
238 locals.pageContent = pageContent;
239 res.render('shell', locals);
240 } catch (err) {
241 console.error('[renderPage] Error rendering', viewName, err);
242 if (process.env.NODE_ENV === 'production') {
243 return res.status(500).send('Internal Server Error');
244 }
245 // Dev: surface the underlying cause prominently. EJS rewrites err.message
246 // to include the file/line/code-context, so we also surface name+stack
247 // separately in case the message was truncated or empty.
248 const escape = (s) => String(s == null ? '' : s)
249 .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
250 res.status(500).send(`<!doctype html>
251<meta charset="utf-8">
252<title>Render error: ${escape(viewName)}</title>
253<style>
254 body { font: 14px/1.5 ui-monospace, monospace; max-width: 1100px; margin: 2rem auto; padding: 0 1rem; background:#1a1a1a; color:#eee; }
255 h1 { color:#dc2626; font-family: ui-sans-serif, system-ui; }
256 h2 { color:#fb923c; font-size:1rem; margin-top:1.5rem; }
257 pre { background:#0a0a0a; border:1px solid #333; border-radius:6px; padding:1rem; overflow:auto; white-space:pre-wrap; word-break:break-word; }
258 .cause { background:#3d0a0a; border-color:#7a1a1a; color:#fca5a5; font-weight:600; }
259</style>
260<h1>Render error in ${escape(viewName)}</h1>
261<h2>Cause</h2>
262<pre class="cause">${escape(err.name || 'Error')}: ${escape(err.message || '(no message)')}</pre>
263<h2>Stack</h2>
264<pre>${escape(err.stack || '(no stack)')}</pre>
265${err.path ? `<h2>File</h2><pre>${escape(err.path)}</pre>` : ''}
266`);
267 }
268}
Note: See TracBrowser for help on using the repository browser.