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