Index: src/middleware/auth.js
===================================================================
--- src/middleware/auth.js	(revision 2165b6d3d57ceaa8b5d1f70491868482149470cf)
+++ src/middleware/auth.js	(revision 7bc636b391c66ac399c33e54f7173a022c6a3cbd)
@@ -2,7 +2,4 @@
  * Auth middleware
  */
-
-import db from '../config/database.js';
-import PermissionsService from '../services/PermissionsService.js';
 
 /**
@@ -38,44 +35,9 @@
 }
 
-// A 'kijker' (viewer) may VIEW everything (incl. Admin) but CHANGE nothing. The
-// write block lives in the global guard in server.js; this helper only determines
-// "is this a read-only account?". `readonly` is the legacy flag we still include
-// so unmigrated demo accounts remain blocked.
-export function isViewer(user) {
-  return !!user && (user.role === 'kijker' || !!user.readonly);
-}
-
 export function requireGod(req, res, next) {
   if (!req.session?.user) return loginRedirect(req, res);
-  const role = req.session.user.role;
-  // god manages; a viewer MAY see the Admin panel (read-only) — the
-  // global guard 403s every write, so this only grants view access.
-  if (role !== 'god' && role !== 'kijker') {
+  if (req.session.user.role !== 'god') {
     return res.status(403).send('God role required');
   }
   next();
 }
-
-// Can the logged-in user manage the CURRENT site (res.locals.site)? god always;
-// otherwise only the owner of that site. Used for site-scoped admin routes
-// that an artist reaches via /user/<own-slug>/admin/... (res.locals.site is then
-// their own site; a foreign slug yields a different site -> 403).
-export function requireSiteManager(req, res, next) {
-  if (!req.session?.user) return loginRedirect(req, res);
-  const u = req.session.user;
-  if (u.role === 'god' || u.role === 'kijker') return next(); // viewer = read-only view access
-  const site = res.locals.site;
-  // owner OR assigned co-admin (site_members) — canAdminSite covers both.
-  if (site && PermissionsService.canAdminSite(u, site)) return next();
-  return res.status(403).send('Geen toegang tot deze site.');
-}
-
-// Same, but the site is determined by the :slug parameter (e.g. site-edit).
-export function requireSiteManagerBySlug(req, res, next) {
-  if (!req.session?.user) return loginRedirect(req, res);
-  const u = req.session.user;
-  if (u.role === 'god' || u.role === 'kijker') return next(); // viewer = read-only view access
-  const site = db.prepare('SELECT id, owner_id FROM sites WHERE slug = ?').get(req.params.slug);
-  if (site && PermissionsService.canAdminSite(u, site)) return next();
-  return res.status(403).send('Geen toegang tot deze site.');
-}
Index: src/middleware/rate-limit.js
===================================================================
--- src/middleware/rate-limit.js	(revision 2165b6d3d57ceaa8b5d1f70491868482149470cf)
+++ src/middleware/rate-limit.js	(revision 7bc636b391c66ac399c33e54f7173a022c6a3cbd)
@@ -13,28 +13,4 @@
 import rateLimit from 'express-rate-limit';
 import { renderPage } from './render.js';
-
-// Behind Cloudflare/Caddy, req.ip can arrive as "1.2.3.4:11046" (IPv4 with
-// port). express-rate-limit v7 validates the IP and otherwise throws
-// ERR_ERL_INVALID_IP_ADDRESS — uncaught async → the process crashes (and pm2
-// enters a restart loop). Strip a trailing IPv4 port, fall back to the
-// socket address, and leave IPv6 (multiple colons) untouched.
-function clientKey(req) {
-  let ip = req.ip || req.socket?.remoteAddress || '';
-  // Strip a trailing IPv4 port (1.2.3.4:11046 -> 1.2.3.4)
-  if (/^\d{1,3}(\.\d{1,3}){3}:\d+$/.test(ip)) ip = ip.split(':')[0];
-  // IPv6-mapped IPv4 (::ffff:1.2.3.4) -> the plain IPv4
-  const mapped = ip.match(/^::ffff:(\d{1,3}(?:\.\d{1,3}){3})$/i);
-  if (mapped) return mapped[1];
-  // Real IPv6: key on the /64 network prefix, not the full address. A single
-  // user/allocation is usually a whole /64, so this stops an attacker from
-  // getting a fresh budget by rotating addresses within their own range.
-  if (ip.includes(':')) {
-    const left = ip.includes('::') ? ip.split('::')[0] : ip;
-    const groups = left.split(':').filter(Boolean);
-    while (groups.length < 4) groups.push('0');
-    return groups.slice(0, 4).join(':') + '::/64';
-  }
-  return ip || 'unknown';
-}
 
 function blockedHandler(viewName, bodyClass, friendlyMsg) {
@@ -66,6 +42,4 @@
   standardHeaders: true,
   legacyHeaders: false,
-  keyGenerator: clientKey,
-  validate: { ip: false },
   // Only count failed attempts. Successful logins don't burn the budget.
   skipSuccessfulRequests: true,
@@ -78,65 +52,5 @@
   standardHeaders: true,
   legacyHeaders: false,
-  keyGenerator: clientKey,
-  validate: { ip: false },
   skipSuccessfulRequests: false,   // any attempt counts (registration spam is the concern)
   handler: blockedHandler('pages/auth-register', 'on-special', 'Too many signup attempts.'),
 });
-
-// ─── Fediverse (/ap/*) ────────────────────────────────────────────
-// These endpoints are hit by REMOTE SERVERS, not browsers, so the default
-// plain-text 429 is the right response (no HTML page). Deliberately generous:
-// legitimate federation from one instance never comes close, but a flood from
-// a single IP is capped. Per-IP via the same /64-aware clientKey.
-
-// Baseline read cap across all /ap/* (actor, outbox, notes, webfinger, …).
-// 5 req/sec per IP — far above any real Mastodon polling.
-export const apReadLimiter = rateLimit({
-  windowMs: 60 * 1000,
-  max: 300,
-  standardHeaders: true,
-  legacyHeaders: false,
-  keyGenerator: clientKey,
-  validate: { ip: false },
-});
-
-// ─── OpenWebAuth /magic ───────────────────────────────────────────
-// Elke poging doet EEN RSA-ontsleuteling met de actorsleutel van een site. Dat
-// is precies de vorm waar een Bleichenbacher/Marvin-orakel op draait: veel
-// aangepaste ciphertexts, en uit de antwoorden de sleutel afleiden. De
-// ontsleuteling zelf is daartegen gehard (implicit rejection in
-// OpenWebAuthService.decryptToken), maar echte constant-time code bestaat niet
-// in JavaScript. Een grens op het AANTAL pogingen doet daarom het zware werk:
-// een orakel heeft er honderdduizenden nodig.
-//
-// TELT ALLE POGINGEN, niet alleen de mislukte. Een teller die alleen faalt
-// meetelt is zelf weer een orakel -- dan leest een aanvaller aan het knijpen af
-// of zijn padding klopte, en is de vertakking die we bij de ontsleuteling
-// weghaalden aan de achterdeur terug.
-//
-// Per SITE-SLUG, want dat is wat een sleutelpaar heeft (getOrCreateKeys(slug)):
-// de grens hoort bij de sleutel die beschermd wordt, niet bij het IP van de
-// eigenaar of bij de doel-host die de aanvaller zelf kiest.
-//
-// Twintig per uur is voor een mens onzichtbaar -- je klikt een handvol keer per
-// dag naar een andere site -- en voor een orakel dodelijk.
-export const owaMagicLimiter = rateLimit({
-  windowMs: 60 * 60 * 1000,
-  max: 20,
-  standardHeaders: true,
-  legacyHeaders: false,
-  keyGenerator: (req) => 'owa:' + String((req.body && req.body.slug) || (req.session && req.session.user && req.session.user.id) || 'onbekend'),
-  validate: { ip: false },
-});
-
-// Inbox POSTs each trigger an outbound actor fetch (signature verify) → cap the
-// amplification/queue-inflation a single source can drive. 120/min/IP is still
-// generous for a small site's inbound federation; bump if a busy instance trips it.
-export const apInboxLimiter = rateLimit({
-  windowMs: 60 * 1000,
-  max: 120,
-  standardHeaders: true,
-  legacyHeaders: false,
-  keyGenerator: clientKey,
-  validate: { ip: false },
-});
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);
Index: src/middleware/site.js
===================================================================
--- src/middleware/site.js	(revision 2165b6d3d57ceaa8b5d1f70491868482149470cf)
+++ src/middleware/site.js	(revision 7bc636b391c66ac399c33e54f7173a022c6a3cbd)
@@ -1,52 +1,47 @@
 /**
  * Site middleware — resolve which site this request is for.
- *
- * Resolution order (hub-modus):
- *   1. Pad /user/:slug → die site  (legacy /sites/:slug → 301 naar /user/)
- *   2. Anders (solo, of hub-landing): de primaire/hoofd-site
- *
+ * 
+ * Resolution order:
+ *   1. Path /sites/:slug → that site
+ *   2. (Future) Subdomain bedrijf1.example.com → matching site
+ *   3. Default site (first one in DB)
+ * 
  * Sets res.locals.site for all downstream handlers.
  */
 
 import db from '../config/database.js';
-import { audioUrl } from '../services/AudioStreamService.js';
-import { audioEnabled } from '../config/features.js';
-import * as Guardianship from '../services/guardianship/index.js';
-
-/**
- * The primary/main site — ONE source of truth (replaces the "oldest site ="
- * main" assumption that was previously scattered across resolveSite/hub/account/admin).
- * Reads the explicit is_primary flag; falls back to the oldest if it isn't set
- * anywhere yet, so existing behaviour is preserved exactly.
- */
-export function getPrimarySite() {
-  return db.prepare('SELECT * FROM sites WHERE is_primary = 1 LIMIT 1').get()
-      || db.prepare('SELECT * FROM sites ORDER BY created_at ASC LIMIT 1').get()
-      || null;
-}
 
 export function resolveSite(req, res, next) {
-  // One instance is one owner (Robins besluit, 31-7): there is one site tree,
-  // pinned to the primary site. The /user/:slug routing that hub mode needed
-  // is gone with it.
-  const defaultSite = getPrimarySite();
+  // Try /sites/:slug pattern
+  const m = req.path.match(/^\/sites\/([a-zA-Z0-9_-]+)(\/.*)?$/);
+  if (m) {
+    const slug = m[1];
+    const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(slug);
+    if (site) {
+      res.locals.site = site;
+      // Strip /sites/:slug from req.url so downstream routes see the rest
+      req.url = (m[2] || '/');
+      // Also rewrite originalUrl for redirect targets to keep the prefix
+      res.locals.siteUrlBase = `/sites/${slug}`;
+      return next();
+    }
+  }
+
+  // Future: subdomain mapping
+  const host = req.get('host')?.toLowerCase().replace(/:\d+$/, '');
+  if (host) {
+    const site = db.prepare('SELECT * FROM sites WHERE slug = ?').get(host);
+    if (site) {
+      res.locals.site = site;
+      res.locals.siteUrlBase = '';
+      return next();
+    }
+  }
+
+  // Default: pick first site
+  const defaultSite = db.prepare('SELECT * FROM sites ORDER BY created_at ASC LIMIT 1').get();
   if (defaultSite) {
     res.locals.site = defaultSite;
     res.locals.siteUrlBase = '';
-    // Mag deze account antwoorden (shaer-r4c)? Eén keer hier, zodat de
-    // antwoordvelden in de views hem kunnen lezen zonder dat elke route hem
-    // apart doorgeeft. De server weigert het antwoord toch al in deliverReply;
-    // dit voorkomt alleen dat een kind tegen een deur duwt die op slot zit.
-    try {
-      const isWard = Guardianship.listGuardians(defaultSite.slug).length > 0;
-      res.locals.mayReply = Guardianship.wardGateAllowed(defaultSite.gate_replies, isWard);
-    } catch { res.locals.mayReply = true; }
-    // Verhuisd (FEP-7628)? Dan staat de uitgaande kant op slot. Om dezelfde reden
-    // hier en niet per route: elke view moet kunnen grijzen wat toch geweigerd
-    // wordt. Een knop die niets doet is erger dan geen knop, want je gaat zoeken
-    // naar een storing die er niet is. De poort zelf zit in de service; dit is
-    // alleen de deurbel die zegt dat er niet opengedaan wordt.
-    res.locals.movedTo = defaultSite.moved_to && /^https?:\/\//i.test(String(defaultSite.moved_to))
-      ? String(defaultSite.moved_to) : null;
   }
 
@@ -61,5 +56,4 @@
  */
 export function loadAudioTracks(req, res, next) {
-  if (!audioEnabled()) { res.locals.audioTracks = []; return next(); }   // lite-modus
   const site = res.locals.site;
   if (!site || site.enable_audio_player === 0) {
@@ -69,9 +63,7 @@
 
   try {
-    // m.filename = the bare filename; the playable URL is the gated stream route
-    // (audioUrl). The media table has NO url column — the old query selected
-    // m.url and always failed silently (empty player). Now we build the URL from filename.
-    const rows = db.prepare(`
-      SELECT t.id, t.title, t.artist, t.duration, t.position, m.filename
+    res.locals.audioTracks = db.prepare(`
+      SELECT t.id, t.title, t.artist, t.duration, t.position,
+             m.url AS media_url
       FROM audio_tracks t
       LEFT JOIN media m ON m.id = t.media_id
@@ -79,8 +71,4 @@
       ORDER BY t.position ASC, t.created_at ASC
     `).all(site.id);
-    res.locals.audioTracks = rows.map((r) => ({
-      id: r.id, title: r.title, artist: r.artist, duration: r.duration, position: r.position,
-      media_url: r.filename ? audioUrl(r.filename) : null,
-    }));
   } catch (e) {
     // media table might not be queryable in some test setups — fall back gracefully
@@ -95,17 +83,14 @@
  */
 export function loadTheme(req, res, next) {
-  const PALETTES = ['klonkt','forest','ocean','teal','lilac','sunset','candy','amber'];
+  const PALETTES = ['sage','paper','ocean','forest','stone','midnight','sunset','cream'];
   
   const user = req.session?.user;
   const site = res.locals.site;
   
-  // A site always renders in ITS OWN palette, regardless of who is viewing. There is
-  // no per-user palette UI (user.palette is vestigial/stale data from old migrations),
-  // and the htmx pcmsNav path (render.js) already uses the site palette only — so reading
-  // user.palette here made a full page load (owner logged in) flip to the viewer's stale
-  // palette while htmx-nav kept the site's, i.e. "palette changes on hard refresh".
-  const palette = (site && PALETTES.includes(site.palette) ? site.palette : null)
-                || 'klonkt';
-
+  // Priority: user setting > site setting > default
+  const palette = (user && PALETTES.includes(user.palette) ? user.palette : null)
+                || (site && PALETTES.includes(site.palette) ? site.palette : null)
+                || 'sage';
+  
   res.locals.palette = palette;
   res.locals.theme = (user && ['dark','light'].includes(user.theme)) ? user.theme : 'dark';
