source: Klonkt/src/server.js@ e2ea5c4

main
Last change on this file since e2ea5c4 was e2ea5c4, checked in by Robin <roboburr@…>, 7 weeks ago

Fix: online visitors always get the fresh site, never a cached copy

The service worker was already network-first, but two gaps let a stale page
through while online:

  • the SW's navigation fetch used the browser HTTP cache, so it could return a heuristically-cached page even though it "fetched",
  • full HTML pages carried no Cache-Control, so the browser was free to cache them heuristically.

Now the SW fetches navigations with { cache: 'no-store' } (straight to the
network, cache is only the offline .catch fallback), and renderPage sends
Cache-Control: no-cache on full pages (revalidate; still bfcache-friendly,
partials stay no-store). Verified live: /sw.js uses no-store and GET / returns
Cache-Control: no-cache. Bumped the SW cache name v17 -> v18.

Changed files:
src/server.js

  • sw.js navigation fetch uses { cache: 'no-store' }; cache name v18

src/middleware/render.js

  • full HTML pages get Cache-Control: no-cache (partials stay no-store)

-robo
Co-Authored-By: Claude Opus 4.8 <noreply@…>

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