source: Klonkt/src/server.js@ 6053c6c

main
Last change on this file since 6053c6c was f24b795, checked in by roboburr <roboburr@…>, 2 months ago

feat(media): Beheer -> Media — image library with usage + cleanup of orphan files

A new /admin/media page lists uploaded images (storage/media/post-images), shows how many posts use
each, lets you copy a URL, and deletes unused files — including the loop-MP4 + poster siblings of an
animated cover. The Beheer "Audio" nav link becomes "Media" (Audio stays a tab linking to
/admin/audio) so the nav doesn't grow. Mounted unconditionally (works in lite/no-audio mode).

  • src/routes/admin-media.js — list / delete / cleanup (path-traversal-safe, god-only)
  • src/views/pages/admin-media.ejs — grid + copy/delete/cleanup (CSP-safe nonce'd script)
  • server.js mount; admin.ejs nav Audio->Media; i18n nl/en/de

Co-Authored-By: Claude <noreply@…>

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