source: Klonkt/src/server.js@ f79a471

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

feat(images): on-demand lanczos cover thumbnails for crisp grid/list

High-res covers (esp. line-art) looked jagged because the browser downscaled them to
the grid/list size. Downscale server-side with ffmpeg lanczos to a small cached WebP
instead. No re-upload/backfill: reads the existing original lazily on first request.

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