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