source: Klonkt/src/server.js@ f7d142f

main
Last change on this file since f7d142f was f7d142f, checked in by Robin Genis <roboburr@…>, 2 months ago

chore(csp): drop the last script unsafe-inline + add Permissions-Policy

Move every inline on* handler to a shared delegated data-* handler, so script-src-attr
can be 'none' instead of 'unsafe-inline'. Add a Permissions-Policy header disabling
camera/microphone/geolocation/Topics (embed features left at default).

  • views/shell.ejs — shared delegated submit/change/click/error handler (data-confirm, data-autosubmit, data-lang-switch, data-selectall, data-back, data-fallback)
  • views/{pages,partials}/*.ejs — 18 inline on* handlers -> data-* attributes (14 files)
  • server.js — scriptSrcAttr 'unsafe-inline' -> 'none'; Permissions-Policy header
  • Property mode set to 100644
File size: 23.3 KB
Line 
1/**
2 * Klonkt Beta — server bootstrap
3 *
4 * Personal multi-site platform — Node + SQLite + htmx.
5 * Stack: Express + better-sqlite3 + EJS + htmx + ws.
6 */
7
8import 'dotenv/config';
9import express from 'express';
10import helmet from 'helmet';
11import session from 'express-session';
12import bodyParser from 'body-parser';
13import path from 'path';
14import fs from 'fs';
15import crypto from 'crypto';
16import { fileURLToPath } from 'url';
17import http from 'http';
18import db, { initializeDatabase } from './config/database.js';
19import { startScheduler } from './services/Scheduler.js';
20import { SqliteSessionStore } from './services/SqliteSessionStore.js';
21import { ensurePrimarySite } from './services/ensurePrimarySite.js';
22import { resolveSite, loadAudioTracks, loadTheme } from './middleware/site.js';
23import { isViewer } from './middleware/auth.js';
24import { renderPage } from './middleware/render.js';
25import { audioEnabled } from './config/features.js';
26import authRoutes from './routes/auth.js';
27import accountRoutes from './routes/account.js';
28import adminRoutes from './routes/admin.js';
29import adminAudioRoutes from './routes/admin-audio.js';
30import adminPlaylistsRoutes from './routes/admin-playlists.js';
31import adminSitesRoutes from './routes/admin-sites.js';
32import adminUsersRoutes from './routes/admin-users.js';
33import adminSettingsRoutes from './routes/admin-settings.js';
34import adminSeoRoutes from './routes/admin-seo.js';
35import audioRoutes from './routes/audio.js';
36import searchRoutes from './routes/search.js';
37import tagsRoutes from './routes/tags.js';
38import typesRoutes from './routes/types.js';
39import usersRoutes from './routes/users.js';
40import feedRoutes from './routes/feed.js';
41import postsRoutes from './routes/posts.js';
42import langRoutes from './routes/lang.js';
43import adminUpdatesRoutes from './routes/admin-updates.js';
44import adminPatreonRoutes from './routes/admin-patreon.js';
45import adminStatsRoutes from './routes/admin-stats.js';
46import circleRoutes from './routes/circle.js';
47import epkRoutes from './routes/epk.js';
48import newsletterRoutes from './routes/newsletter.js';
49import adminNewsletterRoutes from './routes/admin-newsletter.js';
50import downloadRoutes from './routes/download.js';
51import linkbioRoutes from './routes/linkbio.js';
52import embedRoutes from './routes/embed.js';
53import showsRoutes from './routes/shows.js';
54import adminShowsRoutes from './routes/admin-shows.js';
55import adminEpkRoutes from './routes/admin-epk.js';
56import changelogRoutes from './routes/changelog.js';
57import ogRoutes from './routes/og.js';
58import apRoutes from './routes/activitypub.js';
59import { apWants, startDeliveryWorker, selfHealTimeline } from './services/ActivityPubService.js';
60
61// SESSION_SECRET: use the env var if set. Otherwise auto-generate a strong one
62// and persist it next to the database, so it stays stable across restarts and
63// updates. This lets Docker / bare-Node installs run with zero manual config.
64if (!process.env.SESSION_SECRET) {
65 const dataDir = path.dirname(process.env.DATABASE_PATH || './storage/database.sqlite');
66 const secretFile = path.join(dataDir, '.session-secret');
67 try { process.env.SESSION_SECRET = fs.readFileSync(secretFile, 'utf8').trim(); } catch { /* not yet generated */ }
68 if (!process.env.SESSION_SECRET) {
69 fs.mkdirSync(dataDir, { recursive: true });
70 process.env.SESSION_SECRET = crypto.randomBytes(32).toString('hex');
71 fs.writeFileSync(secretFile, process.env.SESSION_SECRET, { mode: 0o600 });
72 console.log(`🔑 Generated a SESSION_SECRET (stored in ${secretFile})`);
73 }
74}
75
76// A SESSION_SECRET that was explicitly set in the env must still be strong in prod.
77if (process.env.NODE_ENV === 'production' && process.env.SESSION_SECRET.length < 32) {
78 console.error('❌ FATAL: SESSION_SECRET is too weak for production (set a longer, random one in .env)');
79 process.exit(1);
80}
81
82const __dirname = path.dirname(fileURLToPath(import.meta.url));
83const PORT = process.env.PORT || 3000;
84// Interface to bind. Default 0.0.0.0 (needed for Docker port-forwarding). Behind a
85// reverse proxy on the same host, set HOST=127.0.0.1 so the app is NOT reachable
86// directly from the internet (only via the proxy) — see README/install docs.
87const HOST = process.env.HOST || '0.0.0.0';
88const isDev = process.env.NODE_ENV !== 'production';
89
90const app = express();
91const server = http.createServer(app);
92
93// Per-request CSP nonce for the strict script-src (nonce + strict-dynamic). Must be set
94// before helmet builds the CSP header below. The nonce is injected into every <script> tag
95// at render time (see middleware/render.js injectCspNonce).
96app.use((req, res, next) => { res.locals.cspNonce = crypto.randomBytes(16).toString('base64'); next(); });
97
98app.use(helmet({
99 contentSecurityPolicy: {
100 directives: {
101 defaultSrc: ["'none'"],
102 // Strict CSP: a per-request nonce + 'strict-dynamic' (no 'unsafe-inline', no broad host
103 // sources — securityheaders/Observatory flag those). Trusted (nonce'd) scripts may load
104 // further scripts, which covers htmx-swapped inline scripts AND the external player APIs
105 // that embed-player.js injects (YouTube/SoundCloud/Spotify). The nonce is added to every
106 // <script> tag at render time (middleware/render.js injectCspNonce).
107 scriptSrc: [
108 "'strict-dynamic'",
109 (req, res) => `'nonce-${res.locals.cspNonce}'`,
110 ],
111 // No inline event handlers anywhere: every on* attribute was moved to a
112 // delegated data-* handler (the shared script in shell.ejs), so inline
113 // handlers are blocked entirely — this closes the last 'unsafe-inline' in
114 // the script directives.
115 scriptSrcAttr: ["'none'"],
116 styleSrc: ["'self'", "'unsafe-inline'"],
117 // blob: required for the image editor (Cropper) — it displays the chosen
118 // photo via URL.createObjectURL(blob:…). Without blob: the CSP silently
119 // blocks the <img> → empty edit window. (media-src already has blob: for audio.)
120 imgSrc: ["'self'", "data:", "https:", "blob:"],
121 connectSrc: ["'self'", "wss:", "ws:", "https://*.spotifycdn.com", "https://*.scdn.co"],
122 // blob: is required for the audio player — it fetch()es track bytes and
123 // plays from a blob: object URL (Spotify-style). Without blob: here the
124 // CSP silently blocks <audio>.src = blob:… → the player fires 'error' and
125 // auto-skips every track. 'self'/https: do NOT imply blob:.
126 mediaSrc: ["'self'", "https:", "blob:"],
127 fontSrc: ["'self'"],
128 // Embeds (platform players + cross-site Klonkt audio players) are framed broadly:
129 // ANY https origin, so embeds work in any context (feed, htmx/PWA nav, public pages).
130 // The sensitive /authorize_interaction page tightens frame-src back to 'self' in
131 // renderPage — it shows untrusted remote content next to the interact buttons.
132 frameSrc: ["'self'", "https:"],
133 // default-src is 'none' (deny by default), so resource types that were implicitly covered
134 // by the old default-src 'self' must be listed explicitly: the PWA manifest and the
135 // service worker. (base-uri/form-action/frame-ancestors/object-src 'none' come from
136 // Helmet's defaults; img/style/connect/media/font/frame are set above.)
137 manifestSrc: ["'self'"],
138 workerSrc: ["'self'", "blob:"],
139 },
140 },
141 hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
142 frameguard: { action: 'sameorigin' },
143 referrerPolicy: { policy: 'strict-origin-when-cross-origin' },
144}));
145
146// Permissions-Policy: disable powerful features Klonkt never uses (camera, microphone,
147// geolocation) and opt out of the Topics API. Features that embeds legitimately need
148// (autoplay, fullscreen, encrypted-media, picture-in-picture) are left at their default
149// allowlist, so YouTube/Spotify/SoundCloud players keep working.
150app.use((req, res, next) => {
151 res.setHeader('Permissions-Policy', 'camera=(), microphone=(), geolocation=(), browsing-topics=()');
152 next();
153});
154
155app.set('view engine', 'ejs');
156app.set('views', path.join(__dirname, 'views'));
157
158app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));
159app.use(bodyParser.json({ limit: '10mb' }));
160
161// Trust one upstream proxy in production. NPM (or Caddy / nginx) terminates
162// HTTPS and forwards to us over plain HTTP, setting X-Forwarded-Proto: https.
163// Without this, Express sees req.protocol === 'http' and won't issue secure
164// cookies — sessions never persist past the redirect after login.
165if (!isDev) app.set('trust proxy', 1);
166
167// Collapse leading duplicate slashes in the path. A reverse proxy that proxies with
168// `RewriteRule ^(.*)$ http://localhost:3000/$1` (Apache [P]) sends "//" for the root and
169// "//path" for sub-paths (the captured $1 keeps its leading slash) → Express matches no
170// route → the whole site 404'd behind such a proxy. Normalising here makes Klonkt resilient
171// to that common reverse-proxy setup. (Only the leading slashes; the query string is intact.)
172app.use((req, res, next) => {
173 if (req.url.startsWith('//')) req.url = req.url.replace(/^\/+/, '/');
174 next();
175});
176
177// Create/migrate the schema BEFORE anything touches the DB: the session store
178// queries the `sessions` table on construction, so on a fresh install the tables
179// must exist first (otherwise: "no such table: sessions" → crash loop on first boot).
180initializeDatabase();
181startScheduler(); // release planning: publish scheduled posts when publish_at is reached
182startDeliveryWorker(); // retry failed fediverse deliveries with backoff
183selfHealTimeline(); // once per SELFHEAL_VERSION bump: re-sync the fediverse cache (covers/edits) after a drastic update
184
185// Safety net: guarantee that there is always a primary site (solo/hub/circle).
186// Idempotent — does nothing if a site already exists or there is no admin yet.
187ensurePrimarySite();
188
189// Session middleware extracted into a variable so the WebSocket upgrade
190// handler can reuse it (it needs req.session to authenticate sockets).
191const sessionMiddleware = session({
192 store: new SqliteSessionStore(),
193 secret: process.env.SESSION_SECRET,
194 resave: false,
195 saveUninitialized: false,
196 name: 'pcms.sid',
197 cookie: {
198 httpOnly: true,
199 secure: !isDev,
200 sameSite: 'lax',
201 maxAge: 30 * 24 * 60 * 60 * 1000,
202 },
203});
204app.use(sessionMiddleware);
205
206app.use('/assets', express.static(path.join(__dirname, 'assets'), { maxAge: isDev ? 0 : '1y' }));
207app.use('/media', express.static(process.env.MEDIA_PATH || './storage/media', {
208 // Public media (post covers, avatars) must be cross-origin embeddable by other
209 // Klonkt sites in their CIRCLE. Helmet sets CORP=same-origin by default, which
210 // causes the browser to block those images (the file arrives, but the browser
211 // refuses to render it). Set cross-origin explicitly for /media.
212 setHeaders: (res) => res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'),
213}));
214
215// (Removed) TWA / digital-asset-links — only needed for the APK/TWA variant.
216// Klonkt is PWA-only; assetlinks.json is no longer served.
217
218// Bundle HTMX: copy from node_modules into our own assets dir so we can serve
219// it locally (no third-party CDN). Idempotent — only copies if size differs.
220(function ensureLocalHtmx() {
221 const src = path.join(__dirname, '..', 'node_modules', 'htmx.org', 'dist', 'htmx.min.js');
222 const dest = path.join(__dirname, 'assets', 'js', 'htmx.min.js');
223 try {
224 const srcStat = fs.statSync(src);
225 const destStat = fs.existsSync(dest) ? fs.statSync(dest) : null;
226 if (!destStat || destStat.size !== srcStat.size) {
227 fs.copyFileSync(src, dest);
228 console.log(`📦 HTMX bundled locally: ${srcStat.size} bytes`);
229 }
230 } catch (e) {
231 console.warn('⚠️ Could not bundle HTMX:', e.message, '— run `npm install`');
232 }
233})();
234
235// ActivityPub: WebFinger + /ap/* (site-agnostic, resolves the site by slug).
236app.use(apRoutes);
237
238// Themed OG cards (/og/:slug.png) — resolve the site by slug themselves, so they
239// run before resolveSite and need no site context.
240app.use('/og', ogRoutes);
241
242app.use(resolveSite);
243app.use(loadAudioTracks);
244app.use(loadTheme);
245
246// ActivityPub content negotiation on the human URLs: an AP request (Accept:
247// application/activity+json) to a profile/post URL is redirected to its /ap/*
248// representation — same URL serves HTML to browsers, AP-JSON to servers (this is
249// how Mastodon resolves a pasted profile/post URL). Gated on apWants() so normal
250// browser requests pay nothing.
251app.use((req, res, next) => {
252 if (req.method !== 'GET' || !apWants(req)) return next();
253 const site = res.locals.site;
254 if (!site || !site.slug) return next();
255 const seg = req.path.replace(/^\/+|\/+$/g, '');
256 if (seg === '') return res.redirect(302, `/ap/users/${encodeURIComponent(site.slug)}`);
257 if (!seg.includes('/')) {
258 try {
259 const post = db.prepare(
260 "SELECT id FROM posts WHERE site_id = ? AND slug = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
261 ).get(site.id, seg);
262 if (post) return res.redirect(302, `/ap/notes/${post.id}`);
263 } catch { /* fall through to normal HTML handling */ }
264 }
265 return next();
266});
267
268// Lightweight CSRF defense: reject cross-origin state-mutating requests.
269// Same-origin forms + HTMX send a matching Origin; missing Origin is allowed
270// through (non-browser clients). sameSite:'lax' on the session cookie is the
271// second layer. (Does not apply to GET/HEAD/OPTIONS.)
272app.use((req, res, next) => {
273 if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
274 const origin = req.get('origin');
275 if (!origin) return next(); // no Origin → no browser CSRF vector
276 let originHost;
277 try { originHost = new URL(origin).host; } catch { return res.status(403).send('Ongeldige origin'); }
278 // Behind a reverse proxy the raw Host is the backend bind (e.g. localhost:3000, when the
279 // proxy doesn't preserve it — common with Apache .htaccess proxying), so also accept the
280 // operator-configured PUBLIC_BASE_URL host and the proxy's X-Forwarded-Host. Both are
281 // operator/proxy-controlled and can't be forged via a victim's browser, so this is safe.
282 const allowedHosts = [req.get('host'), req.get('x-forwarded-host')];
283 if (process.env.PUBLIC_BASE_URL) { try { allowedHosts.push(new URL(process.env.PUBLIC_BASE_URL).host); } catch { /* ignore bad config */ } }
284 if (!allowedHosts.includes(originHost)) return res.status(403).send('Cross-origin request geweigerd');
285 next();
286});
287
288// Viewer accounts: may view everything (including Admin), change nothing. This is
289// the ONLY write gate — fail-closed, before all route handlers. Every state-mutating
290// method is rejected (the login POST sets the session after this guard, so it is
291// not affected). Instead of raw 403 text we render a clean page (or, for HTMX,
292// a swapped-in message).
293app.use((req, res, next) => {
294 const mutating = req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS';
295 if (mutating && isViewer(req.session?.user)) {
296 if (req.headers['hx-request'] === 'true') {
297 // htmx doesn't swap on 4xx; send 200 + retarget so the message appears in #pcms-main.
298 res.setHeader('HX-Retarget', '#pcms-main');
299 res.setHeader('HX-Reswap', 'innerHTML');
300 res.status(200);
301 } else {
302 res.status(403);
303 }
304 return renderPage(req, res, 'pages/viewer-blocked', {
305 pageTitle: 'Kijker-modus',
306 bodyClass: 'on-special',
307 });
308 }
309 next();
310});
311
312app.use('/auth', authRoutes);
313app.use('/account', accountRoutes);
314// NB: /notifications is the fediverse notifications page (in postsRoutes). The old
315// user-notifications route was removed — it collided with the fedi route after the
316// /meldingen -> /notifications rename, and the user-notifications system is dead.
317if (audioEnabled()) {
318 app.use('/admin/audio', adminAudioRoutes);
319 app.use('/admin/playlists', adminPlaylistsRoutes);
320}
321app.use('/admin/sites', adminSitesRoutes);
322app.use('/admin/users', adminUsersRoutes);
323app.use('/admin/settings', adminSettingsRoutes);
324app.use('/admin/seo', adminSeoRoutes);
325app.use('/admin/updates', adminUpdatesRoutes);
326app.use('/admin/patreon', adminPatreonRoutes);
327app.use('/admin/stats', adminStatsRoutes);
328app.use('/admin/newsletter', adminNewsletterRoutes);
329app.use('/admin/shows', adminShowsRoutes);
330app.use('/admin/epk', adminEpkRoutes);
331app.use('/admin', adminRoutes);
332if (audioEnabled()) app.use('/audio', audioRoutes);
333app.use('/search', searchRoutes);
334app.use('/tag', tagsRoutes);
335app.use('/type', typesRoutes);
336app.use('/users', usersRoutes);
337// Feed/sitemap routes are mounted at root because they're at well-known paths
338app.use('/', feedRoutes);
339app.use('/', circleRoutes); // /cirkel-feed (solo: next() -> postsRoutes)
340app.use('/', epkRoutes); // /pers perskit (premium; niet-premium: next() -> 404)
341app.use('/', newsletterRoutes); // /nieuwsbrief in/uitschrijven (premium; niet-premium: next())
342if (audioEnabled()) app.use('/', downloadRoutes); // /downloads + /download/:id (audio; lite: uit)
343app.use('/', linkbioRoutes); // /links link-in-bio + klikstats (premium)
344if (audioEnabled()) app.use('/', embedRoutes); // /embed inbedbare audiospeler (audio; lite: uit)
345app.use('/', showsRoutes); // /shows agenda + notify-me (premium)
346app.use('/', changelogRoutes); // /changelog publieke release-/wijzigingen-pagina
347app.use('/', langRoutes); // /lang/:code — interface-taal kiezen (vóór de catch-all)
348app.use('/', postsRoutes);
349
350app.get('/manifest.webmanifest', (req, res) => {
351 const site = res.locals.site;
352
353 // PWA scope: confines installed apps to ONE site. If a user is in the
354 // bedrijf1 PWA and clicks a link to /sites/bedrijf2/..., the browser will
355 // open it in a regular tab (out-of-scope) instead of within the PWA.
356 // Same applies to APK packaging — the WebView is locked to this scope.
357 //
358 // For path-mounted sites: scope = /sites/<slug>/
359 // For root/subdomain sites: scope = /
360 const base = res.locals.siteUrlBase || ''; // '' or '/sites/<slug>'
361 const scope = (base || '') + '/';
362 const startUrl = (base || '') + '/?source=pwa';
363
364 // A stable identity per site so installs don't collide (Chromium uses `id`).
365 // NB: changing the id orphans existing PWA installs (no migration carries an
366 // install across an id change) — anyone who already installed the site as a
367 // PWA will need to reinstall once. Data stays server-side, so nothing is lost.
368 const idBase = site?.slug ? `klonkt-${site.slug}` : 'klonkt';
369
370 res.set('Cache-Control', 'no-cache');
371 res.json({
372 id: idBase,
373 name: site?.title || 'Klonkt',
374 short_name: (site?.title || 'Klonkt').slice(0, 12),
375 description: site?.description || site?.tagline || '',
376 scope,
377 start_url: startUrl,
378 display: 'standalone',
379 display_override: ['standalone', 'minimal-ui'],
380 orientation: 'any',
381 background_color: '#1a1a17',
382 theme_color: site?.accent || '#e8b04b',
383 lang: site?.language || 'nl',
384 icons: [
385 { src: '/favicon.svg', sizes: 'any', type: 'image/svg+xml' },
386 { src: '/favicon.ico', sizes: '64x64', type: 'image/x-icon' },
387 ],
388 // Hint to capable browsers: capture all in-scope links inside the PWA
389 capture_links: 'existing-client-navigate',
390 });
391});
392
393// Favicon — served as SVG so it picks up the site's accent color dynamically.
394// Browsers also request /favicon.ico by convention; we serve the same SVG
395// content there with a forgiving content-type since modern browsers accept it.
396function _renderFavicon(res, accent) {
397 const safeAccent = /^#[0-9a-fA-F]{3,8}$/.test(accent) ? accent : '#e8b04b';
398 // Site mark: rounded square in the site accent + bold white 'K' (Klonkt)
399 const svg = `<?xml version="1.0" encoding="UTF-8"?>
400<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
401 <rect width="64" height="64" rx="14" fill="${safeAccent}"/>
402 <text x="50%" y="50%" dy="0.35em" text-anchor="middle"
403 font-family="Arial, Helvetica, sans-serif"
404 font-size="42" font-weight="800" fill="#fff">K</text>
405</svg>`;
406 res.set('Content-Type', 'image/svg+xml');
407 res.set('Cache-Control', 'public, max-age=86400');
408 res.send(svg);
409}
410
411app.get('/favicon.svg', (req, res) => {
412 _renderFavicon(res, res.locals.site?.accent);
413});
414app.get('/favicon.ico', (req, res) => {
415 // Browsers requesting .ico will accept SVG content; chrome/firefox both fine.
416 // Keeping the route prevents 404 spam in the console.
417 _renderFavicon(res, res.locals.site?.accent);
418});
419
420app.get('/sw.js', (req, res) => {
421 res.set('Content-Type', 'application/javascript');
422 res.set('Cache-Control', 'no-cache');
423 res.send(`
424const CACHE_VERSION = 'pcms-v16-' + new Date().toISOString().split('T')[0];
425self.addEventListener('install', e => {
426 e.waitUntil(caches.open(CACHE_VERSION).then(c => c.addAll(['/'])));
427 self.skipWaiting();
428});
429self.addEventListener('activate', e => {
430 e.waitUntil(caches.keys().then(keys => Promise.all(
431 keys.filter(k => k !== CACHE_VERSION).map(k => caches.delete(k))
432 )));
433 self.clients.claim();
434});
435// ONLY intercept navigations (HTML pages) for an offline fallback.
436// Do NOT touch images, CSS, JS or /media — let the browser handle those natively.
437// Otherwise a failed network fetch could fall back to an empty cache match
438// (undefined) and "break" an image on a normal refresh (hard reload bypasses
439// the SW, which is why that case worked fine).
440self.addEventListener('fetch', e => {
441 if (e.request.method !== 'GET') return;
442 if (e.request.mode !== 'navigate') return; // page loads only
443 // Same-origin ONLY. A cross-origin navigate request is an <iframe> embed
444 // (YouTube/Spotify/SoundCloud …) — routing those through the SW yields an
445 // opaque/altered response the iframe cannot render → blank embeds in the
446 // installed PWA (which is always SW-controlled). Let the browser load them.
447 try { if (new URL(e.request.url).origin !== self.location.origin) return; } catch (err) { return; }
448 e.respondWith(
449 fetch(e.request).catch(() => caches.match('/').then(r => r || Response.error()))
450 );
451});
452 `);
453});
454
455process.on('unhandledRejection', (reason) => {
456 console.error('⚠️ Unhandled Rejection:', reason);
457});
458
459app.use((err, req, res, next) => {
460 console.error('❌ Error:', err);
461 res.status(err.status || 500).send(
462 isDev ? `<pre>${err.stack || err.message}</pre>` : 'Internal Server Error'
463 );
464});
465
466app.use((req, res) => {
467 res.status(404);
468 // Clean, mobile-friendly 404 via the shell (viewport + nav + site theme).
469 // Falls back to bare HTML if rendering unexpectedly fails.
470 try {
471 return renderPage(req, res, 'pages/404', {
472 pageTitle: '404 — niet gevonden',
473 bodyClass: 'on-special on-404',
474 });
475 } catch (e) {
476 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>');
477 }
478});
479
480server.listen(PORT, HOST, () => {
481 const baseUrl = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
482 console.log('');
483 console.log('🪶 Klonkt');
484 console.log(` ${baseUrl || `http://localhost:${PORT}`}`);
485 if (baseUrl) console.log(` (bound to ${HOST}:${PORT})`);
486 console.log('');
487 console.log(` ✓ Security: Helmet, CSP, secure sessions`);
488 console.log(` ✓ Privacy: Self-hosted fonts, no third-party requests`);
489 console.log(` ✓ Layout: v9 editorial feel (top nav, profile header)`);
490 console.log(` ✓ Auth: wachtwoord (beheer) + Google (luisteraars) / logout`);
491 console.log(` ✓ Posts: create / edit / view / archive`);
492 console.log('');
493 console.log(` Mode: ${isDev ? 'development' : 'PRODUCTION'}`);
494 console.log('');
495});
496
497export default app;
Note: See TracBrowser for help on using the repository browser.