source: Klonkt/src/server.js@ 1ff0043

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

chore(hsts): make includeSubDomains+preload opt-in via HSTS_STRICT

Default ships a plain long max-age (safe on any domain a self-hoster runs). The
aggressive includeSubDomains+preload (which affect the operator's other subdomains and
can bake their domain into browsers) are opt-in via HSTS_STRICT=1, set on domains we own.

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