source: Klonkt/src/server.js@ a995698

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

fix(csrf): accept PUBLIC_BASE_URL host + X-Forwarded-Host in same-origin check

Behind a reverse proxy that doesn't preserve the Host (e.g. Apache .htaccess [P] proxying →
backend sees Host: localhost:3000), the same-origin CSRF check rejected every POST because it
compared Origin (the real domain) to the raw Host. Now it also accepts the operator-configured
PUBLIC_BASE_URL host and the proxy's X-Forwarded-Host — both operator/proxy-controlled, not
forgeable via a victim's browser. Makes Klonkt work behind common Apache/.htaccess setups.

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