Index: src/middleware/render.js
===================================================================
--- src/middleware/render.js	(revision 2165b6d3d57ceaa8b5d1f70491868482149470cf)
+++ src/middleware/render.js	(revision 7bc636b391c66ac399c33e54f7173a022c6a3cbd)
@@ -10,112 +10,24 @@
  */
 
-import fs from 'fs';
 import path from 'path';
 import { fileURLToPath } from 'url';
 import ejs from 'ejs';
-import db from '../config/database.js';
 import PermissionsService from '../services/PermissionsService.js';
-import { isViewer } from './auth.js';
-import { getSetting, apEnabled } from '../services/SettingsService.js';
-import { isPremium as isPremiumInstance, premiumEnabled, premiumUnlocked } from '../services/PatreonService.js';
-import { emojiHtml, emojiName, parseQuote } from '../services/NoteRender.js';
-import ActivityPubService from '../services/ActivityPubService.js';
-import { imgProxyUrl } from '../services/ThumbnailService.js';
-import { audioEnabled as audioFeatureEnabled } from '../config/features.js';
-
-// Add the per-request CSP nonce to every <script> tag that doesn't already have one, so the
-// strict script-src (nonce + 'strict-dynamic') allows them — including scripts in htmx
-// partials. HTML-escaped "&lt;script" in rendered content (e.g. sanitized post bodies) won't
-// match, so this only touches real tags.
-export function injectCspNonce(html, nonce) {
-  if (!html || !nonce) return html;
-  return String(html).replace(/<script(?![^>]*\snonce=)/gi, () => `<script nonce="${nonce}"`);
-}
 import { PLATFORMS as PLATFORMS_CATALOG } from '../services/PlatformIcons.js';
-import { t as i18nT, resolveLang, SUPPORTED as LANGS, LANG_NAMES } from '../services/i18n.js';
 
 const __dirname = path.dirname(fileURLToPath(import.meta.url));
 const VIEWS_DIR = path.join(__dirname, '..', 'views');
 
-/**
- * Render a post body to an HTML string with the SAME partial de Krant uses.
- *
- * For surfaces that are not an EJS page: the Guardian PWA builds its cards in
- * the browser, so it gets the finished HTML in its state blob instead of the
- * raw columns. One renderer, so a post cannot drift into looking different
- * depending on where you run into it.
- */
-export function renderNoteBody(nb, lang) {
-  if (!nb || !nb.content) return '';
-  const _l = lang || 'nl';
-  // ejs.renderFile hands back a Promise even with async:false, and the callers
-  // here are plain synchronous route code. Compile the file ourselves instead;
-  // `filename` is what lets the partial's own relative includes resolve.
-  const file = path.join(VIEWS_DIR, 'partials', 'note-body.ejs');
-  try {
-    return ejs.render(fs.readFileSync(file, 'utf8'), {
-      nb,
-      t: (key, vars) => i18nT(_l, key, vars),
-      emojiHtml,
-      emojiName,
-      noteQuote: parseQuote,
-      thumb: (url, w) => (typeof url === 'string' && /^https?:\/\//i.test(url) ? imgProxyUrl(url, w || 480) : url),
-      avatar: (url, w) => (typeof url === 'string' && /^https?:\/\//i.test(url) ? imgProxyUrl(url, w || 128) : url),
-    }, { filename: file, async: false });
-  } catch (e) {
-    console.warn('[render] note body failed:', e.message);
-    return '';
-  }
-}
-
-// App version (from package.json) + short commit hash (from .klonkt-version, written by
-// the deploy script) — shown in the footer next to "Klonkt Beta". The hash is updated
-// automatically on every deploy, so the displayed version is never stale.
-let APP_VERSION = '';
-try {
-  APP_VERSION = JSON.parse(fs.readFileSync(path.join(__dirname, '..', '..', 'package.json'), 'utf8')).version || '';
-  try {
-    const sha = fs.readFileSync(path.join(__dirname, '..', '..', '.klonkt-version'), 'utf8').trim().slice(0, 7);
-    if (sha) APP_VERSION += ' · ' + sha;
-  } catch { /* no .klonkt-version (local dev) */ }
-} catch { /* no version available */ }
-
-// Site timezone (Admin → Settings). Empty = server default (UTC). Applied to
-// all server-side formatted dates so they display in the site's timezone instead of UTC.
-const siteTimezone = () => getSetting('timezone') || undefined;
-
-/**
- * Read a stored timestamp as the moment it actually is.
- *
- * SQLite's CURRENT_TIMESTAMP writes UTC without saying so ("2026-07-28
- * 18:20:33"), and new Date() reads a string in that shape as LOCAL time. That
- * is right only as long as the server runs on UTC; set the machine to
- * Europe/Amsterdam and every stored date silently shifts two hours. So say UTC
- * out loud. Anything already carrying a zone (AP `published` ends in Z) is left
- * to the normal parser.
- */
-const parseStamp = (v) => {
-  if (!v) return null;
-  if (typeof v === 'number') {   // epoch ms (e.g. an availability endTime)
-    const d = new Date(v);
-    return Number.isNaN(d.getTime()) ? null : d;
-  }
-  const s = String(v);
-  const d = /^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(:\d{2})?$/.test(s)
-    ? new Date(`${s.replace(' ', 'T')}Z`)
-    : new Date(s);
-  return Number.isNaN(d.getTime()) ? null : d;
+const formatDate = (iso) => {
+  if (!iso) return '';
+  const d = new Date(iso);
+  const months = ['januari','februari','maart','april','mei','juni','juli','augustus','september','oktober','november','december'];
+  return `${d.getDate()} ${months[d.getMonth()]} ${d.getFullYear()}`;
 };
 
-const formatDate = (iso) => {
-  const d = parseStamp(iso);
-  return d ? d.toLocaleDateString('nl-NL', { timeZone: siteTimezone(), day: 'numeric', month: 'long', year: 'numeric' }) : '';
-};
-
-/** A timestamp in the site's own timezone (Beheer → Instellingen). Exported so
- *  surfaces outside the EJS pages (the Guardian PWA) read the same clock. */
-export const formatDateTime = (iso) => {
-  const d = parseStamp(iso);
-  return d ? d.toLocaleString('nl-NL', { timeZone: siteTimezone(), dateStyle: 'medium', timeStyle: 'short' }) : '';
+const formatDateTime = (iso) => {
+  if (!iso) return '';
+  const d = new Date(iso);
+  return d.toLocaleString('nl-NL', { dateStyle: 'medium', timeStyle: 'short' });
 };
 
@@ -124,140 +36,20 @@
   const isPartial = req.headers['hx-request'] === 'true' || req.query.partial === '1';
 
-  // Prevent the browser from caching an htmx PARTIAL (only #pcms-main, without <head>/CSS)
-  // under the same URL and serving it as a full page on "back" → unstyled HTML.
-  // Vary: HX-Request separates partial and full responses in the cache;
-  // no-store on the partial forces "back" to always re-fetch the full page.
-  // (Vary also applies to intermediate caches / Cloudflare.)
-  res.setHeader('Vary', 'HX-Request');
-  // A full HTML page must always be revalidated so an online visitor gets the
-  // fresh site, never a heuristically-cached copy. no-cache (not no-store) still
-  // allows bfcache and conditional requests. Partials stay no-store (see above).
-  res.setHeader('Cache-Control', isPartial ? 'no-store' : 'no-cache');
-
-  // Does this (non-god) user own a site? Determines whether they see an "Admin"
-  // entry (artist self-manage). god always sees admin (by role).
-  let _u = req.session?.user || null;
-  // Refresh avatar + role from the DB so a stale session (e.g. after an
-  // avatar change or role switch) heals itself without a new login.
-  if (_u && _u.id) {
-    const _fresh = db.prepare('SELECT role, lang FROM users WHERE id = ?').get(_u.id);
-    if (_fresh) _u = { ..._u, role: _fresh.role, lang: _fresh.lang };
-    // ONE image: a user's avatar everywhere (nav, account, comments) is simply their SITE
-    // photo — there is no separate account avatar. Falls back to the initial-letter
-    // placeholder when the site has no photo yet.
-    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);
-    _u = { ..._u, avatar_url: (_sp && _sp.profile_photo) || null };
-  }
-  const userOwnsSite = !!(_u && _u.role !== 'god' &&
-    db.prepare('SELECT 1 FROM sites WHERE owner_id = ? LIMIT 1').get(_u.id));
-
-  const _site = data.site || res.locals.site || null;
-  // The site header uses the SITE photo (site.profile_photo) — the one and only image,
-  // set in site settings. (No separate account-avatar fallback anymore.)
-  const siteOwnerAvatar = null;
-
-  // Viewer mode: may view everything, change nothing. Views use canMutate
-  // to hide/disable write buttons (post, save, delete).
-  const _isViewer = isViewer(_u);
-
-  // Embeds are framed broadly (frame-src https: globally), EXCEPT on authorize_interaction:
-  // that page renders untrusted remote content next to the interact buttons, so lock its
-  // frame-src down to 'self' (no embeds → no clickjacking/overlay over the buttons).
-  if (viewName === 'pages/authorize-interaction') {
-    try {
-      const csp = res.getHeader('Content-Security-Policy');
-      if (csp) res.setHeader('Content-Security-Policy', String(csp).replace(/frame-src [^;]*/i, "frame-src 'self'"));
-    } catch { /* best-effort */ }
-  }
-
-  // Who sees the "Admin" link? god/admin, a site owner (artist self-manage),
-  // and a viewer (may view Admin read-only). One source of truth,
-  // mirrored in topnav/hub-nav/profile sheet — otherwise the link gets hidden
-  // for those who should see it (viewer didn't see it anywhere before).
-  const _role = _u ? _u.role : null;
-  const canSeeBeheer = !!(_u && (_role === 'god' || _role === 'admin' || _role === 'kijker' || userOwnsSite));
-  // Who may use the fediverse client (timeline/notifications/blocking) — actual
-  // site managers only (these routes are requireSiteManager; viewers are excluded).
-  const canManageFedi = !!(_u && (_role === 'god' || _role === 'admin' || userOwnsSite));
-
-  // Interface language: session choice (this session) → logged-in user's own preference
-  // (users.lang) → admin-set default (Admin → Settings) → env → browser → nl.
-  const _lang = resolveLang(req, {
-    userLang: _u && _u.lang,
-    defaultLang: getSetting('default_lang'),
-  });
-
   // Common locals
   const locals = {
-    user: _u,
-    lang: _lang,
-    t: (key, vars) => i18nT(_lang, key, vars),
-    langs: LANGS.map((c) => ({ code: c, name: LANG_NAMES[c], active: c === _lang })),
-    timezone: getSetting('timezone') || '',
-    notifUnread: (canManageFedi && _site) ? ActivityPubService.countUnseenNotifications(_site.slug) : 0,
-    userOwnsSite,
-    canSeeBeheer,
-    canManageFedi,
-    apEnabled: apEnabled(),
-    // Cirkel = the artists you feature (auto-boost): shown when AP is on and
-    // you auto-boost at least one account.
-    hasCirkel: !!(_site && apEnabled() && (ActivityPubService.autoBoostCount(_site.slug) > 0 || ActivityPubService.boostedCount(_site.slug) > 0)),
-    isViewer: _isViewer,
-    canMutate: !_isViewer,
-    isPremium: isPremiumInstance(),
-    premiumEnabled: premiumEnabled(),
-    premiumUnlocked: premiumUnlocked(),
-    siteOwnerAvatar,
-    site: _site,
-    audioEnabled: audioFeatureEnabled(),
+    user: req.session?.user || null,
+    site: data.site || res.locals.site || null,
     audioTracks: data.audioTracks || res.locals.audioTracks || [],
     siteUrlBase: res.locals.siteUrlBase || '',
-    footerNewsletter: getSetting('footer_newsletter') === '1', // newsletter sign-up in footer (premium)
-    agendaEnabled: getSetting('agenda_enabled') === '1', // show agenda/events in the pill (premium, opt-in)
     platforms_catalog: PLATFORMS_CATALOG,
     permissions: PermissionsService,
     formatDate,
     formatDateTime,
-    // Render the Shaer-native bits server-side so the web timeline matches the
-    // apps: FEP-9098 custom emojis in content/names, and the FEP-044f quote.
-    emojiHtml,   // (html, emoji_json) → HTML with :shortcode: as <img>
-    emojiName,   // (text, emoji_json) → escaped name with :shortcode: as <img>
-    noteQuote: parseQuote,   // (quote_json) → the resolved quoted-post object or null
-    // Rewrite a local /media/<file> cover to its on-demand downscaled thumbnail
-    // (crisp grid/list images). External URLs + already-thumb URLs pass through.
-    thumb: (url, w) => {
-      if (!url || typeof url !== 'string') return url;
-      // Local cover → local thumb route; remote (federated) cover → signed downscale
-      // proxy (same as avatars), so remote line-art covers aren't browser-downscaled jagged.
-      if (url.startsWith('/media/') && !url.startsWith('/media/thumb/')) return `/media/thumb/${w || 480}/${url.slice(7)}`;
-      if (/^https?:\/\//i.test(url)) return imgProxyUrl(url, w || 480);
-      return url;
-    },
-    // Crisp avatars: a local /media avatar goes through the local thumb route; a REMOTE
-    // (fediverse) avatar through the signed downscaling proxy. Same downscale, the remote
-    // one is just fetched first. Default 128px (covers feed 44px → profile ~120px).
-    avatar: (url, w) => {
-      if (!url || typeof url !== 'string') return url;
-      if (url.startsWith('/media/') && !url.startsWith('/media/thumb/')) return `/media/thumb/${w || 128}/${url.slice(7)}`;
-      if (/^https?:\/\//i.test(url)) return imgProxyUrl(url, w || 128);
-      return url;
-    },
-    // pageTitleKey (translated with the resolved language) wins over a raw pageTitle string,
-    // so admin page titles aren't hardcoded in one language. Falls back to the site title.
-    pageTitle: (data.pageTitleKey ? i18nT(_lang, data.pageTitleKey, data.pageTitleVars) : data.pageTitle)
-      || (data.site && data.site.title) || 'Klonkt',
-    appVersion: APP_VERSION,
+    pageTitle: data.pageTitle || (data.site && data.site.title) || 'PrutCMS',
     bodyClass: data.bodyClass || 'on-home',
-    // Welke module(s) deze pagina nodig heeft (shaer-bqr). De shell zet ze op
-    // body[data-js]; de bootstrap daar importeert ze uit /assets/js/mod/.
-    // Alleen kleine letters, cijfers, streepjes en spaties -- de naam wordt een
-    // pad.
-    pageJs: /^[a-z0-9 -]*$/.test(String(data.pageJs || '')) ? (data.pageJs || '') : '',
     socialDescr: data.socialDescr || '',
     socialImage: data.socialImage || '',
     cspNonce: () => '',
     currentPath: req.path,
-    // Absolute origin (for building absolute URLs like the generated og:image).
-    ogOrigin: (process.env.PUBLIC_BASE_URL || `${req.protocol}://${req.get('host') || ''}`).replace(/\/+$/, ''),
     ...data,
   };
@@ -269,32 +61,7 @@
 
     if (isPartial) {
-      // A "Load more" append (hx-swap=beforeend into a sub-list) is NOT a
-      // navigation: it only adds rows to the existing page. It must NOT touch
-      // the site chrome or the body class. Emitting the nav HX-Trigger + OOB
-      // chrome here (below) rebuilds the header for the DEFAULT bodyClass —
-      // which, on a 'on-special' page like Messages, swaps in the full Klonkt
-      // header that the page had hidden. So for an append, send content only.
-      if (req.query.append === '1') {
-        return res.send(injectCspNonce(pageContent, res.locals.cspNonce));
-      }
-      // HTMX: just send the content. Set HX-Trigger for body class swap.
-      // HTTP-header values are Latin-1 only — a title with an em-dash, smart
-      // quote or emoji (e.g. "Welkom — gebouwd met Klonkt") would make
-      // setHeader throw ERR_INVALID_CHAR and 500 the partial, so the card
-      // looks "unclickable". Escape any non-ASCII to \uXXXX: the header stays
-      // ASCII-safe and remains valid JSON that htmx parses back unchanged.
-      // Per-site accent + palette live in the shell <head> (style#pcms-site-accent
-      // + html[data-palette]) and are NOT swapped during htmx navigation. Send them along
-      // so the client updates them — otherwise an artist inherits the previous page's
-      // colours (e.g. hub-purple instead of their own green). Same derivation as shell.ejs.
-      const _navAccent = (_site && _site.accent && /^#[0-9a-fA-F]{6}$/.test(_site.accent))
-        ? _site.accent : '#e8b04b';
-      const _navPalette = (_site && _site.palette) ? _site.palette : 'klonkt';
-      // Welke modules de nieuwe pagina wil (shaer-bqr). De bootstrap in de shell
-      // zet dit op de body en haalt op wat er nieuw bij staat; 'chrome' hoort er
-      // altijd bij, want die komt bij elke navigatie opnieuw binnen.
-      const _navJs = ('chrome ' + (locals.pageJs || '')).trim();
-      const triggerJson = JSON.stringify({
-        pcmsNav: { bodyClass: locals.bodyClass, accent: _navAccent, palette: _navPalette, js: _navJs },
+      // HTMX: just send the content. Set HX-Trigger for body class swap
+      res.setHeader('HX-Trigger-After-Settle', JSON.stringify({
+        pcmsNav: { bodyClass: locals.bodyClass },
         pcmsPostSwap: data.post ? {
           title: data.post.title,
@@ -302,26 +69,11 @@
           pageTitle: locals.pageTitle,
         } : null,
-      }).replace(/[-￿]/g, (ch) => '\\u' + ch.charCodeAt(0).toString(16).padStart(4, '0'));
-      res.setHeader('HX-Trigger-After-Settle', triggerJson);
-      // Render the site chrome out-of-band so the header (topnav/profile header/
-      // view-switcher) ALWAYS matches the new page/artist on navigation —
-      // while the audio player (separate in document.body) keeps playing (no
-      // interruption). htmx replaces #pcms-chrome via hx-swap-oob. Non-critical:
-      // if it fails, the old chrome remains (no crash).
-      let oobChrome = '';
-      try {
-        oobChrome = await ejs.renderFile(
-          path.join(VIEWS_DIR, 'partials', 'chrome.ejs'),
-          { ...locals, oob: true },
-          { async: false },
-        );
-      } catch (e) { /* skip chrome OOB */ }
-      return res.send(injectCspNonce(pageContent + oobChrome, res.locals.cspNonce));
+      }));
+      return res.send(pageContent);
     }
 
-    // Full: wrap content in shell (rendered to a string so we can inject the CSP nonce).
+    // Full: wrap content in shell
     locals.pageContent = pageContent;
-    const shellHtml = await ejs.renderFile(path.join(VIEWS_DIR, 'shell.ejs'), locals, { async: false });
-    res.send(injectCspNonce(shellHtml, res.locals.cspNonce));
+    res.render('shell', locals);
   } catch (err) {
     console.error('[renderPage] Error rendering', viewName, err);
