Index: src/server.js
===================================================================
--- src/server.js	(revision 2165b6d3d57ceaa8b5d1f70491868482149470cf)
+++ src/server.js	(revision 7bc636b391c66ac399c33e54f7173a022c6a3cbd)
@@ -1,6 +1,6 @@
 /**
- * Klonkt Beta — server bootstrap
+ * PrutFolio v1 — server bootstrap
  *
- * Personal multi-site platform — Node + SQLite + htmx.
+ * Persoonlijk multi-site platform forked van PrutCMS v9 (PHP, file-based).
  * Stack: Express + better-sqlite3 + EJS + htmx + ws.
  */
@@ -13,16 +13,12 @@
 import path from 'path';
 import fs from 'fs';
-import crypto from 'crypto';
 import { fileURLToPath } from 'url';
 import http from 'http';
 import db, { initializeDatabase } from './config/database.js';
-import { startScheduler } from './services/Scheduler.js';
 import { SqliteSessionStore } from './services/SqliteSessionStore.js';
-import { ensurePrimarySite } from './services/ensurePrimarySite.js';
-import { getThumbnail, getRemoteThumbnail, verifyImg, THUMB_SIZES } from './services/ThumbnailService.js';
+import PrutterService from './services/PrutterService.js';
+import { WebSocketServer } from 'ws';
+
 import { resolveSite, loadAudioTracks, loadTheme } from './middleware/site.js';
-import { isViewer } from './middleware/auth.js';
-import { renderPage } from './middleware/render.js';
-import { audioEnabled } from './config/features.js';
 import authRoutes from './routes/auth.js';
 import accountRoutes from './routes/account.js';
@@ -30,11 +26,11 @@
 import adminAudioRoutes from './routes/admin-audio.js';
 import adminPlaylistsRoutes from './routes/admin-playlists.js';
-import adminListenersRoutes from './routes/admin-listeners.js';
 import adminSitesRoutes from './routes/admin-sites.js';
 import adminUsersRoutes from './routes/admin-users.js';
-import adminSettingsRoutes from './routes/admin-settings.js';
-import adminSeoRoutes from './routes/admin-seo.js';
+import adminCommentsRoutes from './routes/admin-comments.js';
+import prutterRoutes from './routes/prutter.js';
 import audioRoutes from './routes/audio.js';
 import searchRoutes from './routes/search.js';
+import commentsRoutes from './routes/comments.js';
 import tagsRoutes from './routes/tags.js';
 import typesRoutes from './routes/types.js';
@@ -42,133 +38,47 @@
 import feedRoutes from './routes/feed.js';
 import postsRoutes from './routes/posts.js';
-import paidRoutes from './routes/paid.js';
-import langRoutes from './routes/lang.js';
-import adminUpdatesRoutes from './routes/admin-updates.js';
-import adminPatreonRoutes from './routes/admin-patreon.js';
-import adminStatsRoutes from './routes/admin-stats.js';
-import adminPaidRoutes from './routes/admin-paid.js';
-import adminPushRoutes from './routes/admin-push.js';
-import pushRoutes from './routes/push.js';
-import guardianRoutes from './routes/guardian.js';
-import adminMediaRoutes from './routes/admin-media.js';
-import adminMigrateRoutes from './routes/admin-migrate.js';
-import circleRoutes from './routes/circle.js';
-import epkRoutes from './routes/epk.js';
-import newsletterRoutes from './routes/newsletter.js';
-import adminNewsletterRoutes from './routes/admin-newsletter.js';
-import downloadRoutes from './routes/download.js';
-import linkbioRoutes from './routes/linkbio.js';
-import embedRoutes from './routes/embed.js';
-import showsRoutes from './routes/shows.js';
-import adminShowsRoutes from './routes/admin-shows.js';
-import adminEpkRoutes from './routes/admin-epk.js';
-import changelogRoutes from './routes/changelog.js';
-import ogRoutes from './routes/og.js';
-import apRoutes from './routes/activitypub.js';
-import owaRoutes, { owaMiddleware } from './routes/openwebauth.js';
-import oauthRoutes from './routes/oauth.js';
-import { apWants, startDeliveryWorker, selfHealTimeline, migrateReactions } from './services/ActivityPubService.js';
-
-// SESSION_SECRET: use the env var if set. Otherwise auto-generate a strong one
-// and persist it next to the database, so it stays stable across restarts and
-// updates. This lets Docker / bare-Node installs run with zero manual config.
+
 if (!process.env.SESSION_SECRET) {
-  const dataDir = path.dirname(process.env.DATABASE_PATH || './storage/database.sqlite');
-  const secretFile = path.join(dataDir, '.session-secret');
-  try { process.env.SESSION_SECRET = fs.readFileSync(secretFile, 'utf8').trim(); } catch { /* not yet generated */ }
-  if (!process.env.SESSION_SECRET) {
-    fs.mkdirSync(dataDir, { recursive: true });
-    process.env.SESSION_SECRET = crypto.randomBytes(32).toString('hex');
-    fs.writeFileSync(secretFile, process.env.SESSION_SECRET, { mode: 0o600 });
-    console.log(`🔑 Generated a SESSION_SECRET (stored in ${secretFile})`);
-  }
-}
-
-// A SESSION_SECRET that was explicitly set in the env must still be strong in prod.
-if (process.env.NODE_ENV === 'production' && process.env.SESSION_SECRET.length < 32) {
-  console.error('❌ FATAL: SESSION_SECRET is too weak for production (set a longer, random one in .env)');
+  console.error('❌ FATAL: SESSION_SECRET is required');
   process.exit(1);
 }
 
+if (process.env.NODE_ENV === 'production' && process.env.SESSION_SECRET.length < 32) {
+  console.error('❌ FATAL: SESSION_SECRET too weak for production');
+  process.exit(1);
+}
+
 const __dirname = path.dirname(fileURLToPath(import.meta.url));
 const PORT = process.env.PORT || 3000;
-// Interface to bind. Default 0.0.0.0 (needed for Docker port-forwarding). Behind a
-// reverse proxy on the same host, set HOST=127.0.0.1 so the app is NOT reachable
-// directly from the internet (only via the proxy) — see README/install docs.
-const HOST = process.env.HOST || '0.0.0.0';
 const isDev = process.env.NODE_ENV !== 'production';
 
 const app = express();
 const server = http.createServer(app);
-
-// Per-request CSP nonce for the strict script-src (nonce + strict-dynamic). Must be set
-// before helmet builds the CSP header below. The nonce is injected into every <script> tag
-// at render time (see middleware/render.js injectCspNonce).
-app.use((req, res, next) => { res.locals.cspNonce = crypto.randomBytes(16).toString('base64'); next(); });
-
-// HSTS. The default ships a plain long max-age — safe on ANY domain. includeSubDomains +
-// preload are aggressive (they affect the operator's OTHER subdomains and can get their
-// domain baked into browsers near-permanently), so they're opt-in via HSTS_STRICT=1 — set
-// only on domains you fully own (e.g. the klonkt.com fleet). Self-hosters get the safe default.
-// NB: Helmet defaults includeSubDomains to true, so the safe default must disable it explicitly.
-const hstsOptions = { maxAge: 31536000, includeSubDomains: false, preload: false };
-if (process.env.HSTS_STRICT === '1') { hstsOptions.includeSubDomains = true; hstsOptions.preload = true; }
 
 app.use(helmet({
   contentSecurityPolicy: {
     directives: {
-      defaultSrc: ["'none'"],
-      // Strict CSP: a per-request nonce + 'strict-dynamic' (no 'unsafe-inline', no broad host
-      // sources — securityheaders/Observatory flag those). Trusted (nonce'd) scripts may load
-      // further scripts, which covers htmx-swapped inline scripts AND the external player APIs
-      // that embed-player.js injects (YouTube/SoundCloud/Spotify). The nonce is added to every
-      // <script> tag at render time (middleware/render.js injectCspNonce).
-      scriptSrc: [
-        "'strict-dynamic'",
-        (req, res) => `'nonce-${res.locals.cspNonce}'`,
+      defaultSrc: ["'self'"],
+      scriptSrc: ["'self'", "'unsafe-inline'"],
+      styleSrc: ["'self'", "'unsafe-inline'"],
+      imgSrc: ["'self'", "data:", "https:"],
+      connectSrc: ["'self'", "wss:", "ws:"],
+      mediaSrc: ["'self'", "https:"],
+      fontSrc: ["'self'"],
+      frameSrc: [
+        "'self'",
+        "https://open.spotify.com",
+        "https://w.soundcloud.com",
+        "https://bandcamp.com",
+        "https://embed.music.apple.com",
+        "https://www.youtube-nocookie.com",
+        "https://player.vimeo.com",
       ],
-      // No inline event handlers anywhere: every on* attribute was moved to a
-      // delegated data-* handler (the shared script in shell.ejs), so inline
-      // handlers are blocked entirely — this closes the last 'unsafe-inline' in
-      // the script directives.
-      scriptSrcAttr: ["'none'"],
-      styleSrc: ["'self'", "'unsafe-inline'"],
-      // blob: required for the image editor (Cropper) — it displays the chosen
-      // photo via URL.createObjectURL(blob:…). Without blob: the CSP silently
-      // blocks the <img> → empty edit window. (media-src already has blob: for audio.)
-      imgSrc: ["'self'", "data:", "https:", "blob:"],
-      connectSrc: ["'self'", "wss:", "ws:", "https://*.spotifycdn.com", "https://*.scdn.co"],
-      // blob: is required for the audio player — it fetch()es track bytes and
-      // plays from a blob: object URL (Spotify-style). Without blob: here the
-      // CSP silently blocks <audio>.src = blob:… → the player fires 'error' and
-      // auto-skips every track. 'self'/https: do NOT imply blob:.
-      mediaSrc: ["'self'", "https:", "blob:"],
-      fontSrc: ["'self'"],
-      // Embeds (platform players + cross-site Klonkt audio players) are framed broadly:
-      // ANY https origin, so embeds work in any context (feed, htmx/PWA nav, public pages).
-      // The sensitive /authorize_interaction page tightens frame-src back to 'self' in
-      // renderPage — it shows untrusted remote content next to the interact buttons.
-      frameSrc: ["'self'", "https:"],
-      // default-src is 'none' (deny by default), so resource types that were implicitly covered
-      // by the old default-src 'self' must be listed explicitly: the PWA manifest and the
-      // service worker. (base-uri/form-action/frame-ancestors/object-src 'none' come from
-      // Helmet's defaults; img/style/connect/media/font/frame are set above.)
-      manifestSrc: ["'self'"],
-      workerSrc: ["'self'", "blob:"],
     },
   },
-  hsts: hstsOptions,
+  hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
   frameguard: { action: 'sameorigin' },
-  referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
+  referrerPolicy: { policy: 'no-referrer-when-downgrade' },
 }));
-
-// Permissions-Policy: disable powerful features Klonkt never uses (camera, microphone,
-// geolocation) and opt out of the Topics API. Features that embeds legitimately need
-// (autoplay, fullscreen, encrypted-media, picture-in-picture) are left at their default
-// allowlist, so YouTube/Spotify/SoundCloud players keep working.
-app.use((req, res, next) => {
-  res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=(), browsing-topics=()');
-  next();
-});
 
 app.set('view engine', 'ejs');
@@ -182,40 +92,5 @@
 // Without this, Express sees req.protocol === 'http' and won't issue secure
 // cookies — sessions never persist past the redirect after login.
-// Trust proxy hoort bij WAAR JE DRAAIT, niet bij dev/prod (Barts 429-jacht,
-// 9-8): klonkt-dev draait NODE_ENV=development ACHTER Caddy, en zonder trust
-// proxy was req.ip voor elk verzoek 127.0.0.1 -- de hele wereld plus de
-// honderd kudde-daemons deelden EEN rate-limit-emmer van 300/min. De kudde
-// leegde hem, en Barts refresh kreeg 'Too many requests' terwijl de live-lus
-// aan dezelfde 429's verhongerde. TRUST_PROXY=1 zet hem aan waar een proxy
-// voor de deur staat; kaal-op-poort blijft hem uit laten, want een direct
-// bereikbare server die X-Forwarded-For vertrouwt laat iedereen zijn eigen
-// IP kiezen -- en daarmee de limiter omzeilen.
-if (!isDev || process.env.TRUST_PROXY === '1') app.set('trust proxy', 1);
-
-// Collapse leading duplicate slashes in the path. A reverse proxy that proxies with
-// `RewriteRule ^(.*)$ http://localhost:3000/$1` (Apache [P]) sends "//" for the root and
-// "//path" for sub-paths (the captured $1 keeps its leading slash) → Express matches no
-// route → the whole site 404'd behind such a proxy. Normalising here makes Klonkt resilient
-// to that common reverse-proxy setup. (Only the leading slashes; the query string is intact.)
-app.use((req, res, next) => {
-  if (req.url.startsWith('//')) req.url = req.url.replace(/^\/+/, '/');
-  next();
-});
-
-// Create/migrate the schema BEFORE anything touches the DB: the session store
-// queries the `sessions` table on construction, so on a fresh install the tables
-// must exist first (otherwise: "no such table: sessions" → crash loop on first boot).
-initializeDatabase();
-startScheduler(); // release planning: publish scheduled posts when publish_at is reached
-startDeliveryWorker(); // retry failed fediverse deliveries with backoff
-// Once per REACTIONS_MIGRATION_VERSION bump: reacties naar de tussentabel, onder
-// de canonieke object-URI. Moet VOOR het serveren, want vanaf nu leest de code
-// die tabel -- draait hij niet, dan tonen oude likes als niet-gegeven.
-migrateReactions();
-selfHealTimeline(); // once per SELFHEAL_VERSION bump: re-sync the fediverse cache (covers/edits) after a drastic update
-
-// Safety net: guarantee that there is always a primary site (solo/hub/circle).
-// Idempotent — does nothing if a site already exists or there is no admin yet.
-ensurePrimarySite();
+if (!isDev) app.set('trust proxy', 1);
 
 // Session middleware extracted into a variable so the WebSocket upgrade
@@ -237,59 +112,16 @@
 
 app.use('/assets', express.static(path.join(__dirname, 'assets'), { maxAge: isDev ? 0 : '1y' }));
-
-// On-demand cover thumbnails: /media/thumb/<w>/<path> → a small lanczos-downscaled WebP
-// (cached on disk), so the browser doesn't jaggily shrink a high-res cover for the grid/
-// list. Mounted BEFORE the /media static so it catches the thumb path first.
-app.get('/media/thumb/:w/*', async (req, res) => {
-  const w = parseInt(req.params.w, 10);
-  const rel = req.params[0] || '';
-  if (!THUMB_SIZES.has(w)) return res.status(400).end();
-  let file = null;
-  try { file = await getThumbnail(rel, w); } catch { /* fall through to original */ }
-  if (!file) {
-    // Generation unavailable/failed → serve the original instead of 404'ing.
-    return res.redirect(302, '/media/' + rel.split('/').map(encodeURIComponent).join('/'));
-  }
-  res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
-  res.setHeader('Cache-Control', isDev ? 'no-cache' : 'public, max-age=31536000, immutable');
-  res.type('webp');
-  res.sendFile(file);
-});
-
-// Signed remote-image proxy: downscale a REMOTE avatar/image (SSRF-safe via safeFetch)
-// to a cached WebP, so line-art fediverse avatars don't render jagged. Only HMAC-signed
-// URLs (produced by the avatar() view helper) are accepted — not an open resizer.
-app.get('/img/a/:w', async (req, res) => {
-  const w = parseInt(req.params.w, 10);
-  const url = typeof req.query.u === 'string' ? req.query.u : '';
-  const sig = typeof req.query.s === 'string' ? req.query.s : '';
-  if (!THUMB_SIZES.has(w) || !verifyImg(url, w, sig)) return res.status(400).end();
-  let file = null;
-  try { file = await getRemoteThumbnail(url, w); } catch { /* fall through to original */ }
-  if (!file) return res.redirect(302, url); // fetch/downscale failed → let the browser load the remote original
-  res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
-  res.setHeader('Cache-Control', isDev ? 'no-cache' : 'public, max-age=604800');
-  res.type('webp');
-  res.sendFile(file);
-});
-
-app.use('/media', express.static(process.env.MEDIA_PATH || './storage/media', {
-  // Public media (post covers, avatars) must be cross-origin embeddable by other
-  // Klonkt sites in their CIRCLE. Helmet sets CORP=same-origin by default, which
-  // causes the browser to block those images (the file arrives, but the browser
-  // refuses to render it). Set cross-origin explicitly for /media.
-  setHeaders: (res) => res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'),
-  // An upload never changes under its name (unique filenames; a new upload is
-  // a new name), so say so. Without this the default is max-age=0 and every
-  // platform image-loader may re-ask for every image on every screen: Shaer's
-  // cards visibly re-loaded what the previous view had just shown. The thumbs
-  // and the avatar proxy already declared this; the originals were the one
-  // place that forgot.
-  maxAge: isDev ? 0 : '1y',
-  immutable: !isDev,
-}));
-
-// (Removed) TWA / digital-asset-links — only needed for the APK/TWA variant.
-// Klonkt is PWA-only; assetlinks.json is no longer served.
+app.use('/media', express.static(process.env.MEDIA_PATH || './storage/media'));
+
+// P64 — TWA / digital-asset-links: must be served at /.well-known/assetlinks.json
+// at the site root with Content-Type: application/json. Without this Android
+// shows the URL bar inside the installed PrutFolio app.
+app.get('/.well-known/assetlinks.json', (req, res) => {
+  res.type('application/json').sendFile(
+    path.join(__dirname, 'assets', '.well-known', 'assetlinks.json')
+  );
+});
+
+initializeDatabase();
 
 // Bundle HTMX: copy from node_modules into our own assets dir so we can serve
@@ -310,19 +142,7 @@
 })();
 
-// ActivityPub: WebFinger + /ap/* (site-agnostic, resolves the site by slug).
-app.use(apRoutes);
-// OpenWebAuth (FEP-61cf): het token-endpoint en het inlogformulier.
-app.use(owaRoutes);
-// En op elk GET-verzoek kijken of er een token wordt ingewisseld (?owt=) of een
-// stroom gestart (?zid=). Na de sessie, want het resultaat gaat IN de sessie;
-// voor de pagina's, want een poort verderop moet de uitkomst al kunnen zien.
-app.use(owaMiddleware);
-// ActivityPub C2S: OAuth 2.0 (native/web clients). Site-agnostic; the consent
-// screen picks which site the token can post as.
-app.use(oauthRoutes);
-
-// Themed OG cards (/og/:slug.png) — resolve the site by slug themselves, so they
-// run before resolveSite and need no site context.
-app.use('/og', ogRoutes);
+// Singleton PrutterService — routes get it via req.app.locals.prutter.
+const prutter = new PrutterService(db);
+app.locals.prutter = prutter;
 
 app.use(resolveSite);
@@ -330,97 +150,16 @@
 app.use(loadTheme);
 
-// ActivityPub content negotiation on the human URLs: an AP request (Accept:
-// application/activity+json) to a profile/post URL is redirected to its /ap/*
-// representation — same URL serves HTML to browsers, AP-JSON to servers (this is
-// how Mastodon resolves a pasted profile/post URL). Gated on apWants() so normal
-// browser requests pay nothing.
-app.use((req, res, next) => {
-  if (req.method !== 'GET' || !apWants(req)) return next();
-  const site = res.locals.site;
-  if (!site || !site.slug) return next();
-  const seg = req.path.replace(/^\/+|\/+$/g, '');
-  if (seg === '') return res.redirect(302, `/ap/users/${encodeURIComponent(site.slug)}`);
-  if (!seg.includes('/')) {
-    try {
-      const post = db.prepare(
-        "SELECT id FROM posts WHERE site_id = ? AND slug = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
-      ).get(site.id, seg);
-      if (post) return res.redirect(302, `/ap/notes/${post.id}`);
-    } catch { /* fall through to normal HTML handling */ }
-  }
-  return next();
-});
-
-// Lightweight CSRF defense: reject cross-origin state-mutating requests.
-// Same-origin forms + HTMX send a matching Origin; missing Origin is allowed
-// through (non-browser clients). sameSite:'lax' on the session cookie is the
-// second layer. (Does not apply to GET/HEAD/OPTIONS.)
-app.use((req, res, next) => {
-  if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
-  const origin = req.get('origin');
-  if (!origin) return next(); // no Origin → no browser CSRF vector
-  let originHost;
-  try { originHost = new URL(origin).host; } catch { return res.status(403).send('Ongeldige origin'); }
-  // Behind a reverse proxy the raw Host is the backend bind (e.g. localhost:3000, when the
-  // proxy doesn't preserve it — common with Apache .htaccess proxying), so also accept the
-  // operator-configured PUBLIC_BASE_URL host and the proxy's X-Forwarded-Host. Both are
-  // operator/proxy-controlled and can't be forged via a victim's browser, so this is safe.
-  const allowedHosts = [req.get('host'), req.get('x-forwarded-host')];
-  if (process.env.PUBLIC_BASE_URL) { try { allowedHosts.push(new URL(process.env.PUBLIC_BASE_URL).host); } catch { /* ignore bad config */ } }
-  if (!allowedHosts.includes(originHost)) return res.status(403).send('Cross-origin request geweigerd');
-  next();
-});
-
-// Viewer accounts: may view everything (including Admin), change nothing. This is
-// the ONLY write gate — fail-closed, before all route handlers. Every state-mutating
-// method is rejected (the login POST sets the session after this guard, so it is
-// not affected). Instead of raw 403 text we render a clean page (or, for HTMX,
-// a swapped-in message).
-app.use((req, res, next) => {
-  const mutating = req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS';
-  if (mutating && isViewer(req.session?.user)) {
-    if (req.headers['hx-request'] === 'true') {
-      // htmx doesn't swap on 4xx; send 200 + retarget so the message appears in #pcms-main.
-      res.setHeader('HX-Retarget', '#pcms-main');
-      res.setHeader('HX-Reswap', 'innerHTML');
-      res.status(200);
-    } else {
-      res.status(403);
-    }
-    return renderPage(req, res, 'pages/viewer-blocked', {
-      pageTitle: 'Kijker-modus',
-      bodyClass: 'on-special',
-    });
-  }
-  next();
-});
-
 app.use('/auth', authRoutes);
 app.use('/account', accountRoutes);
-// NB: /notifications is the fediverse notifications page (in postsRoutes). The old
-// user-notifications route was removed — it collided with the fedi route after the
-// /meldingen -> /notifications rename, and the user-notifications system is dead.
-if (audioEnabled()) {
-  app.use('/admin/audio', adminAudioRoutes);
-  app.use('/admin/playlists', adminPlaylistsRoutes);
-  app.use('/admin/listeners', adminListenersRoutes);
-}
-app.use('/admin/media', adminMediaRoutes); // image library + cleanup (works in lite mode too)
-app.use('/admin/migrate', adminMigrateRoutes); // posts + media naar/van een andere Klonkt
+app.use('/admin/audio', adminAudioRoutes);
+app.use('/admin/playlists', adminPlaylistsRoutes);
 app.use('/admin/sites', adminSitesRoutes);
 app.use('/admin/users', adminUsersRoutes);
-app.use('/admin/settings', adminSettingsRoutes);
-app.use('/admin/seo', adminSeoRoutes);
-app.use('/admin/updates', adminUpdatesRoutes);
-app.use('/admin/patreon', adminPatreonRoutes);
-app.use('/admin/stats', adminStatsRoutes);
-app.use('/admin/paid', adminPaidRoutes);
-app.use('/admin/push', adminPushRoutes);
-app.use('/admin/newsletter', adminNewsletterRoutes);
-app.use('/admin/shows', adminShowsRoutes);
-app.use('/admin/epk', adminEpkRoutes);
+app.use('/admin/comments', adminCommentsRoutes);
 app.use('/admin', adminRoutes);
-if (audioEnabled()) app.use('/audio', audioRoutes);
+app.use('/prutter', prutterRoutes);
+app.use('/audio', audioRoutes);
 app.use('/search', searchRoutes);
+app.use('/comments', commentsRoutes);
 app.use('/tag', tagsRoutes);
 app.use('/type', typesRoutes);
@@ -428,16 +167,4 @@
 // Feed/sitemap routes are mounted at root because they're at well-known paths
 app.use('/', feedRoutes);
-app.use('/', circleRoutes); // /cirkel-feed (solo: next() -> postsRoutes)
-app.use('/', epkRoutes); // /pers perskit (premium; niet-premium: next() -> 404)
-app.use('/', newsletterRoutes); // /nieuwsbrief in/uitschrijven (premium; niet-premium: next())
-if (audioEnabled()) app.use('/', downloadRoutes); // /downloads + /download/:id (audio; lite: uit)
-app.use('/', linkbioRoutes); // /links link-in-bio + klikstats (premium)
-if (audioEnabled()) app.use('/', embedRoutes); // /embed inbedbare audiospeler (audio; lite: uit)
-app.use('/', showsRoutes); // /shows agenda + notify-me (premium)
-app.use('/', changelogRoutes); // /changelog publieke release-/wijzigingen-pagina
-app.use('/', langRoutes); // /lang/:code — interface-taal kiezen (vóór de catch-all)
-app.use('/paid', paidRoutes);   // paid-posts patron/passkey flow (before the /:slug catch-all)
-app.use('/push', pushRoutes);   // web-push subscribe/test (before the /:slug catch-all)
-app.use('/guardian', guardianRoutes);   // the Guardian PWA (FEP-633c): losse guardians, meekijken, follow-gating, wave, invite (was guardian2, v1 verwijderd)
 app.use('/', postsRoutes);
 
@@ -456,15 +183,12 @@
   const startUrl = (base || '') + '/?source=pwa';
 
-  // A stable identity per site so installs don't collide (Chromium uses `id`).
-  // NB: changing the id orphans existing PWA installs (no migration carries an
-  // install across an id change) — anyone who already installed the site as a
-  // PWA will need to reinstall once. Data stays server-side, so nothing is lost.
-  const idBase = site?.slug ? `klonkt-${site.slug}` : 'klonkt';
+  // A stable identity per site so installs don't collide (Chromium uses `id`)
+  const idBase = site?.slug ? `prutfolio-${site.slug}` : 'prutfolio';
 
   res.set('Cache-Control', 'no-cache');
   res.json({
     id: idBase,
-    name: site?.title || 'Klonkt',
-    short_name: (site?.title || 'Klonkt').slice(0, 12),
+    name: site?.title || 'PrutFolio',
+    short_name: (site?.title || 'PrutFolio').slice(0, 12),
     description: site?.description || site?.tagline || '',
     scope,
@@ -474,5 +198,5 @@
     orientation: 'any',
     background_color: '#1a1a17',
-    theme_color: site?.accent || '#e8b04b',
+    theme_color: site?.accent || '#c2410c',
     lang: site?.language || 'nl',
     icons: [
@@ -489,12 +213,13 @@
 // content there with a forgiving content-type since modern browsers accept it.
 function _renderFavicon(res, accent) {
-  const safeAccent = /^#[0-9a-fA-F]{3,8}$/.test(accent) ? accent : '#e8b04b';
-  // Site mark: rounded square in the site accent + bold white 'K' (Klonkt)
+  const safeAccent = /^#[0-9a-fA-F]{3,8}$/.test(accent) ? accent : '#c2410c';
+  // Simple PrutFolio mark: a rounded square in the site accent + lowercase 'p'
+  // (display font is server-side unavailable, so we use a generic serif fallback)
   const svg = `<?xml version="1.0" encoding="UTF-8"?>
 <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
   <rect width="64" height="64" rx="14" fill="${safeAccent}"/>
-  <text x="50%" y="50%" dy="0.35em" text-anchor="middle"
-        font-family="Arial, Helvetica, sans-serif"
-        font-size="42" font-weight="800" fill="#fff">K</text>
+  <text x="50%" y="50%" dy="0.36em" text-anchor="middle"
+        font-family="Georgia, 'Times New Roman', serif"
+        font-size="44" font-weight="700" fill="#fff">p</text>
 </svg>`;
   res.set('Content-Type', 'image/svg+xml');
@@ -516,5 +241,5 @@
   res.set('Cache-Control', 'no-cache');
   res.send(`
-const CACHE_VERSION = 'pcms-v19-' + new Date().toISOString().split('T')[0];
+const CACHE_VERSION = 'pcms-v10-' + new Date().toISOString().split('T')[0];
 self.addEventListener('install', e => {
   e.waitUntil(caches.open(CACHE_VERSION).then(c => c.addAll(['/'])));
@@ -527,69 +252,7 @@
   self.clients.claim();
 });
-// ONLY intercept navigations (HTML pages) for an offline fallback.
-// Do NOT touch images, CSS, JS or /media — let the browser handle those natively.
-// Otherwise a failed network fetch could fall back to an empty cache match
-// (undefined) and "break" an image on a normal refresh (hard reload bypasses
-// the SW, which is why that case worked fine).
 self.addEventListener('fetch', e => {
   if (e.request.method !== 'GET') return;
-  if (e.request.mode !== 'navigate') return; // page loads only
-  // Same-origin ONLY. A cross-origin navigate request is an <iframe> embed
-  // (YouTube/Spotify/SoundCloud …) — routing those through the SW yields an
-  // opaque/altered response the iframe cannot render → blank embeds in the
-  // installed PWA (which is always SW-controlled). Let the browser load them.
-  try { if (new URL(e.request.url).origin !== self.location.origin) return; } catch (err) { return; }
-  e.respondWith(
-    // { cache: 'no-store' }: go to the network for the page, bypassing the browser's
-    // HTTP cache, so an online visitor ALWAYS gets the fresh site and never a
-    // heuristically-cached copy served through the SW. The cache is only a
-    // last-resort offline fallback (the .catch below).
-    fetch(e.request, { cache: 'no-store' }).then(resp => {
-      // Network-first: always serve fresh when online. Also refresh the '/' offline
-      // fallback with the homepage we just served, so a later cold start on a flaky or
-      // offline connection no longer shows the stale install-time snapshot ("old data
-      // on first PWA load").
-      try {
-        if (resp && resp.ok && new URL(e.request.url).pathname === '/') {
-          const copy = resp.clone();
-          e.waitUntil(caches.open(CACHE_VERSION).then(c => c.put('/', copy)).catch(() => {}));
-        }
-      } catch (err) { /* ignore cache refresh failures */ }
-      return resp;
-    }).catch(() => caches.match('/').then(r => r || Response.error()))
-  );
-});
-// Web push (docs/webpush-design.md): payload is JSON {type,title,body,url},
-// encrypted end-to-end to this browser (RFC 8291). Show it; click opens url.
-self.addEventListener('push', e => {
-  let d = {};
-  try { d = e.data ? e.data.json() : {}; } catch (err) { /* non-JSON push */ }
-  const title = d.title || 'Klonkt';
-  e.waitUntil(Promise.all([
-    self.registration.showNotification(title, {
-      body: d.body || '',
-      icon: '/favicon.svg',
-      badge: '/favicon.svg',
-      tag: d.type ? ('klonkt-' + d.type) : undefined,   // collapse same-type bursts
-      data: { url: d.url || '/' },
-    }),
-    // Wek ook een pagina die al openstaat. De push IS het teken dat er iets
-    // veranderd is, dus een aparte live-verbinding ernaast zou hetzelfde nog
-    // eens doen -- en die tweede zou alleen werken zolang de app open is,
-    // terwijl dit kanaal er ook is als hij dicht is. Een kanaal, twee doelen.
-    self.clients.matchAll({ type: 'window', includeUncontrolled: true })
-      .then(list => { for (const c of list) c.postMessage({ klonkt: 'push', type: d.type || null }); })
-      .catch(() => { /* geen open venster: niets te wekken */ }),
-  ]));
-});
-self.addEventListener('notificationclick', e => {
-  e.notification.close();
-  const url = (e.notification.data && e.notification.data.url) || '/';
-  e.waitUntil(clients.matchAll({ type: 'window', includeUncontrolled: true }).then(list => {
-    for (const c of list) {
-      if (new URL(c.url).origin === self.location.origin && 'focus' in c) { c.navigate(url); return c.focus(); }
-    }
-    return clients.openWindow(url);
-  }));
+  e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
 });
   `);
@@ -608,29 +271,67 @@
 
 app.use((req, res) => {
-  res.status(404);
-  // Clean, mobile-friendly 404 via the shell (viewport + nav + site theme).
-  // Falls back to bare HTML if rendering unexpectedly fails.
-  try {
-    return renderPage(req, res, 'pages/404', {
-      pageTitle: '404 — niet gevonden',
-      bodyClass: 'on-special on-404',
+  res.status(404).send(`
+    <div style="font-family:system-ui;max-width:500px;margin:4rem auto;text-align:center;padding:2rem;">
+      <h1 style="font-size:5rem;margin:0;color:#c33;">404</h1>
+      <p>Not found</p>
+      <a href="/" style="color:#c2410c;">← Home</a>
+    </div>
+  `);
+});
+
+// ==================== WebSocket: Prutter real-time ====================
+// Authenticate via the existing session cookie. We reuse sessionMiddleware
+// during the HTTP upgrade so req.session is populated; if no user, abort.
+const wss = new WebSocketServer({ noServer: true });
+
+server.on('upgrade', (req, socket, head) => {
+  if (req.url !== '/ws/prutter') {
+    socket.destroy();
+    return;
+  }
+  // Run session middleware on the upgrade request.
+  // (Express's middleware accepts (req, res, next); we pass a stub res.)
+  const stubRes = { setHeader: () => {}, getHeader: () => undefined, on: () => {}, end: () => {} };
+  sessionMiddleware(req, stubRes, () => {
+    if (!req.session?.user) {
+      socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
+      socket.destroy();
+      return;
+    }
+    wss.handleUpgrade(req, socket, head, (ws) => {
+      ws.userId = req.session.user.id;
+      wss.emit('connection', ws, req);
     });
-  } catch (e) {
-    return res.send('<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><div style="font-family:system-ui;max-width:500px;margin:4rem auto;text-align:center;padding:2rem"><h1 style="font-size:4rem;margin:0">404</h1><p>Pagina niet gevonden</p><a href="/">← Home</a></div>');
+  });
+});
+
+wss.on('connection', (ws) => {
+  prutter.addConnection(ws.userId, ws);
+  ws.on('close', () => prutter.removeConnection(ws.userId, ws));
+  ws.on('error', () => prutter.removeConnection(ws.userId, ws));
+  // Optional: ping every 30s to keep connections alive through proxies
+  ws.isAlive = true;
+  ws.on('pong', () => { ws.isAlive = true; });
+});
+const wsPing = setInterval(() => {
+  for (const ws of wss.clients) {
+    if (ws.isAlive === false) { ws.terminate(); continue; }
+    ws.isAlive = false;
+    try { ws.ping(); } catch {}
   }
-});
-
-server.listen(PORT, HOST, () => {
-  const baseUrl = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
+}, 30000);
+if (wsPing.unref) wsPing.unref();
+
+server.listen(PORT, () => {
   console.log('');
-  console.log('🪶 Klonkt');
-  console.log(`   ${baseUrl || `http://localhost:${PORT}`}`);
-  if (baseUrl) console.log(`   (bound to ${HOST}:${PORT})`);
+  console.log('🪶 PrutFolio v1 — alpha');
+  console.log(`   http://localhost:${PORT}`);
   console.log('');
   console.log(`   ✓ Security: Helmet, CSP, secure sessions`);
   console.log(`   ✓ Privacy:  Self-hosted fonts, no third-party requests`);
   console.log(`   ✓ Layout:   v9 editorial feel (top nav, profile header)`);
-  console.log(`   ✓ Auth:     wachtwoord (beheer) + Google (luisteraars) / logout`);
+  console.log(`   ✓ Auth:     login / register / logout`);
   console.log(`   ✓ Posts:    create / edit / view / archive`);
+  console.log(`   ✓ Realtime: WebSocket server ready (Prutter)`);
   console.log('');
   console.log(`   Mode: ${isDev ? 'development' : 'PRODUCTION'}`);
