source: Klonkt/src/server.js@ 99989f9

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

feat(images): downscale remote (fediverse) avatars via a signed proxy

Remote avatars live on other servers, so the browser shrank full-res line-art to ~44px
(jagged). Fetch them once (SSRF-safe via safeFetch), downscale identically (lanczos -> WebP),
cache, serve. HMAC-signed proxy URLs → not an open resizer.

  • services/ActivityPubService.js — export safeFetch
  • services/ThumbnailService.js — getRemoteThumbnail + signed imgProxyUrl/verifyImg; +128px size
  • server.js — GET /img/a/:w signed proxy route
  • middleware/render.js — avatar(url,w) helper (local thumb / remote proxy)
  • views: news.ejs, fedi-node.ejs, following.ejs avatars -> avatar()
  • Property mode set to 100644
File size: 25.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, 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 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
236// Signed remote-image proxy: downscale a REMOTE avatar/image (SSRF-safe via safeFetch)
237// to a cached WebP, so line-art fediverse avatars don't render jagged. Only HMAC-signed
238// URLs (produced by the avatar() view helper) are accepted — not an open resizer.
239app.get('/img/a/:w', async (req, res) => {
240 const w = parseInt(req.params.w, 10);
241 const url = typeof req.query.u === 'string' ? req.query.u : '';
242 const sig = typeof req.query.s === 'string' ? req.query.s : '';
243 if (!THUMB_SIZES.has(w) || !verifyImg(url, w, sig)) return res.status(400).end();
244 let file = null;
245 try { file = await getRemoteThumbnail(url, w); } catch { /* fall through to original */ }
246 if (!file) return res.redirect(302, url); // fetch/downscale failed → let the browser load the remote original
247 res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin');
248 res.setHeader('Cache-Control', isDev ? 'no-cache' : 'public, max-age=604800');
249 res.type('webp');
250 res.sendFile(file);
251});
252
253app.use('/media', express.static(process.env.MEDIA_PATH || './storage/media', {
254 // Public media (post covers, avatars) must be cross-origin embeddable by other
255 // Klonkt sites in their CIRCLE. Helmet sets CORP=same-origin by default, which
256 // causes the browser to block those images (the file arrives, but the browser
257 // refuses to render it). Set cross-origin explicitly for /media.
258 setHeaders: (res) => res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'),
259}));
260
261// (Removed) TWA / digital-asset-links — only needed for the APK/TWA variant.
262// Klonkt is PWA-only; assetlinks.json is no longer served.
263
264// Bundle HTMX: copy from node_modules into our own assets dir so we can serve
265// it locally (no third-party CDN). Idempotent — only copies if size differs.
266(function ensureLocalHtmx() {
267 const src = path.join(__dirname, '..', 'node_modules', 'htmx.org', 'dist', 'htmx.min.js');
268 const dest = path.join(__dirname, 'assets', 'js', 'htmx.min.js');
269 try {
270 const srcStat = fs.statSync(src);
271 const destStat = fs.existsSync(dest) ? fs.statSync(dest) : null;
272 if (!destStat || destStat.size !== srcStat.size) {
273 fs.copyFileSync(src, dest);
274 console.log(`📦 HTMX bundled locally: ${srcStat.size} bytes`);
275 }
276 } catch (e) {
277 console.warn('⚠️ Could not bundle HTMX:', e.message, '— run `npm install`');
278 }
279})();
280
281// ActivityPub: WebFinger + /ap/* (site-agnostic, resolves the site by slug).
282app.use(apRoutes);
283
284// Themed OG cards (/og/:slug.png) — resolve the site by slug themselves, so they
285// run before resolveSite and need no site context.
286app.use('/og', ogRoutes);
287
288app.use(resolveSite);
289app.use(loadAudioTracks);
290app.use(loadTheme);
291
292// ActivityPub content negotiation on the human URLs: an AP request (Accept:
293// application/activity+json) to a profile/post URL is redirected to its /ap/*
294// representation — same URL serves HTML to browsers, AP-JSON to servers (this is
295// how Mastodon resolves a pasted profile/post URL). Gated on apWants() so normal
296// browser requests pay nothing.
297app.use((req, res, next) => {
298 if (req.method !== 'GET' || !apWants(req)) return next();
299 const site = res.locals.site;
300 if (!site || !site.slug) return next();
301 const seg = req.path.replace(/^\/+|\/+$/g, '');
302 if (seg === '') return res.redirect(302, `/ap/users/${encodeURIComponent(site.slug)}`);
303 if (!seg.includes('/')) {
304 try {
305 const post = db.prepare(
306 "SELECT id FROM posts WHERE site_id = ? AND slug = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
307 ).get(site.id, seg);
308 if (post) return res.redirect(302, `/ap/notes/${post.id}`);
309 } catch { /* fall through to normal HTML handling */ }
310 }
311 return next();
312});
313
314// Lightweight CSRF defense: reject cross-origin state-mutating requests.
315// Same-origin forms + HTMX send a matching Origin; missing Origin is allowed
316// through (non-browser clients). sameSite:'lax' on the session cookie is the
317// second layer. (Does not apply to GET/HEAD/OPTIONS.)
318app.use((req, res, next) => {
319 if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
320 const origin = req.get('origin');
321 if (!origin) return next(); // no Origin → no browser CSRF vector
322 let originHost;
323 try { originHost = new URL(origin).host; } catch { return res.status(403).send('Ongeldige origin'); }
324 // Behind a reverse proxy the raw Host is the backend bind (e.g. localhost:3000, when the
325 // proxy doesn't preserve it — common with Apache .htaccess proxying), so also accept the
326 // operator-configured PUBLIC_BASE_URL host and the proxy's X-Forwarded-Host. Both are
327 // operator/proxy-controlled and can't be forged via a victim's browser, so this is safe.
328 const allowedHosts = [req.get('host'), req.get('x-forwarded-host')];
329 if (process.env.PUBLIC_BASE_URL) { try { allowedHosts.push(new URL(process.env.PUBLIC_BASE_URL).host); } catch { /* ignore bad config */ } }
330 if (!allowedHosts.includes(originHost)) return res.status(403).send('Cross-origin request geweigerd');
331 next();
332});
333
334// Viewer accounts: may view everything (including Admin), change nothing. This is
335// the ONLY write gate — fail-closed, before all route handlers. Every state-mutating
336// method is rejected (the login POST sets the session after this guard, so it is
337// not affected). Instead of raw 403 text we render a clean page (or, for HTMX,
338// a swapped-in message).
339app.use((req, res, next) => {
340 const mutating = req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS';
341 if (mutating && isViewer(req.session?.user)) {
342 if (req.headers['hx-request'] === 'true') {
343 // htmx doesn't swap on 4xx; send 200 + retarget so the message appears in #pcms-main.
344 res.setHeader('HX-Retarget', '#pcms-main');
345 res.setHeader('HX-Reswap', 'innerHTML');
346 res.status(200);
347 } else {
348 res.status(403);
349 }
350 return renderPage(req, res, 'pages/viewer-blocked', {
351 pageTitle: 'Kijker-modus',
352 bodyClass: 'on-special',
353 });
354 }
355 next();
356});
357
358app.use('/auth', authRoutes);
359app.use('/account', accountRoutes);
360// NB: /notifications is the fediverse notifications page (in postsRoutes). The old
361// user-notifications route was removed — it collided with the fedi route after the
362// /meldingen -> /notifications rename, and the user-notifications system is dead.
363if (audioEnabled()) {
364 app.use('/admin/audio', adminAudioRoutes);
365 app.use('/admin/playlists', adminPlaylistsRoutes);
366}
367app.use('/admin/sites', adminSitesRoutes);
368app.use('/admin/users', adminUsersRoutes);
369app.use('/admin/settings', adminSettingsRoutes);
370app.use('/admin/seo', adminSeoRoutes);
371app.use('/admin/updates', adminUpdatesRoutes);
372app.use('/admin/patreon', adminPatreonRoutes);
373app.use('/admin/stats', adminStatsRoutes);
374app.use('/admin/newsletter', adminNewsletterRoutes);
375app.use('/admin/shows', adminShowsRoutes);
376app.use('/admin/epk', adminEpkRoutes);
377app.use('/admin', adminRoutes);
378if (audioEnabled()) app.use('/audio', audioRoutes);
379app.use('/search', searchRoutes);
380app.use('/tag', tagsRoutes);
381app.use('/type', typesRoutes);
382app.use('/users', usersRoutes);
383// Feed/sitemap routes are mounted at root because they're at well-known paths
384app.use('/', feedRoutes);
385app.use('/', circleRoutes); // /cirkel-feed (solo: next() -> postsRoutes)
386app.use('/', epkRoutes); // /pers perskit (premium; niet-premium: next() -> 404)
387app.use('/', newsletterRoutes); // /nieuwsbrief in/uitschrijven (premium; niet-premium: next())
388if (audioEnabled()) app.use('/', downloadRoutes); // /downloads + /download/:id (audio; lite: uit)
389app.use('/', linkbioRoutes); // /links link-in-bio + klikstats (premium)
390if (audioEnabled()) app.use('/', embedRoutes); // /embed inbedbare audiospeler (audio; lite: uit)
391app.use('/', showsRoutes); // /shows agenda + notify-me (premium)
392app.use('/', changelogRoutes); // /changelog publieke release-/wijzigingen-pagina
393app.use('/', langRoutes); // /lang/:code — interface-taal kiezen (vóór de catch-all)
394app.use('/', postsRoutes);
395
396app.get('/manifest.webmanifest', (req, res) => {
397 const site = res.locals.site;
398
399 // PWA scope: confines installed apps to ONE site. If a user is in the
400 // bedrijf1 PWA and clicks a link to /sites/bedrijf2/..., the browser will
401 // open it in a regular tab (out-of-scope) instead of within the PWA.
402 // Same applies to APK packaging — the WebView is locked to this scope.
403 //
404 // For path-mounted sites: scope = /sites/<slug>/
405 // For root/subdomain sites: scope = /
406 const base = res.locals.siteUrlBase || ''; // '' or '/sites/<slug>'
407 const scope = (base || '') + '/';
408 const startUrl = (base || '') + '/?source=pwa';
409
410 // A stable identity per site so installs don't collide (Chromium uses `id`).
411 // NB: changing the id orphans existing PWA installs (no migration carries an
412 // install across an id change) — anyone who already installed the site as a
413 // PWA will need to reinstall once. Data stays server-side, so nothing is lost.
414 const idBase = site?.slug ? `klonkt-${site.slug}` : 'klonkt';
415
416 res.set('Cache-Control', 'no-cache');
417 res.json({
418 id: idBase,
419 name: site?.title || 'Klonkt',
420 short_name: (site?.title || 'Klonkt').slice(0, 12),
421 description: site?.description || site?.tagline || '',
422 scope,
423 start_url: startUrl,
424 display: 'standalone',
425 display_override: ['standalone', 'minimal-ui'],
426 orientation: 'any',
427 background_color: '#1a1a17',
428 theme_color: site?.accent || '#e8b04b',
429 lang: site?.language || 'nl',
430 icons: [
431 { src: '/favicon.svg', sizes: 'any', type: 'image/svg+xml' },
432 { src: '/favicon.ico', sizes: '64x64', type: 'image/x-icon' },
433 ],
434 // Hint to capable browsers: capture all in-scope links inside the PWA
435 capture_links: 'existing-client-navigate',
436 });
437});
438
439// Favicon — served as SVG so it picks up the site's accent color dynamically.
440// Browsers also request /favicon.ico by convention; we serve the same SVG
441// content there with a forgiving content-type since modern browsers accept it.
442function _renderFavicon(res, accent) {
443 const safeAccent = /^#[0-9a-fA-F]{3,8}$/.test(accent) ? accent : '#e8b04b';
444 // Site mark: rounded square in the site accent + bold white 'K' (Klonkt)
445 const svg = `<?xml version="1.0" encoding="UTF-8"?>
446<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
447 <rect width="64" height="64" rx="14" fill="${safeAccent}"/>
448 <text x="50%" y="50%" dy="0.35em" text-anchor="middle"
449 font-family="Arial, Helvetica, sans-serif"
450 font-size="42" font-weight="800" fill="#fff">K</text>
451</svg>`;
452 res.set('Content-Type', 'image/svg+xml');
453 res.set('Cache-Control', 'public, max-age=86400');
454 res.send(svg);
455}
456
457app.get('/favicon.svg', (req, res) => {
458 _renderFavicon(res, res.locals.site?.accent);
459});
460app.get('/favicon.ico', (req, res) => {
461 // Browsers requesting .ico will accept SVG content; chrome/firefox both fine.
462 // Keeping the route prevents 404 spam in the console.
463 _renderFavicon(res, res.locals.site?.accent);
464});
465
466app.get('/sw.js', (req, res) => {
467 res.set('Content-Type', 'application/javascript');
468 res.set('Cache-Control', 'no-cache');
469 res.send(`
470const CACHE_VERSION = 'pcms-v16-' + new Date().toISOString().split('T')[0];
471self.addEventListener('install', e => {
472 e.waitUntil(caches.open(CACHE_VERSION).then(c => c.addAll(['/'])));
473 self.skipWaiting();
474});
475self.addEventListener('activate', e => {
476 e.waitUntil(caches.keys().then(keys => Promise.all(
477 keys.filter(k => k !== CACHE_VERSION).map(k => caches.delete(k))
478 )));
479 self.clients.claim();
480});
481// ONLY intercept navigations (HTML pages) for an offline fallback.
482// Do NOT touch images, CSS, JS or /media — let the browser handle those natively.
483// Otherwise a failed network fetch could fall back to an empty cache match
484// (undefined) and "break" an image on a normal refresh (hard reload bypasses
485// the SW, which is why that case worked fine).
486self.addEventListener('fetch', e => {
487 if (e.request.method !== 'GET') return;
488 if (e.request.mode !== 'navigate') return; // page loads only
489 // Same-origin ONLY. A cross-origin navigate request is an <iframe> embed
490 // (YouTube/Spotify/SoundCloud …) — routing those through the SW yields an
491 // opaque/altered response the iframe cannot render → blank embeds in the
492 // installed PWA (which is always SW-controlled). Let the browser load them.
493 try { if (new URL(e.request.url).origin !== self.location.origin) return; } catch (err) { return; }
494 e.respondWith(
495 fetch(e.request).catch(() => caches.match('/').then(r => r || Response.error()))
496 );
497});
498 `);
499});
500
501process.on('unhandledRejection', (reason) => {
502 console.error('⚠️ Unhandled Rejection:', reason);
503});
504
505app.use((err, req, res, next) => {
506 console.error('❌ Error:', err);
507 res.status(err.status || 500).send(
508 isDev ? `<pre>${err.stack || err.message}</pre>` : 'Internal Server Error'
509 );
510});
511
512app.use((req, res) => {
513 res.status(404);
514 // Clean, mobile-friendly 404 via the shell (viewport + nav + site theme).
515 // Falls back to bare HTML if rendering unexpectedly fails.
516 try {
517 return renderPage(req, res, 'pages/404', {
518 pageTitle: '404 — niet gevonden',
519 bodyClass: 'on-special on-404',
520 });
521 } catch (e) {
522 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>');
523 }
524});
525
526server.listen(PORT, HOST, () => {
527 const baseUrl = (process.env.PUBLIC_BASE_URL || '').replace(/\/+$/, '');
528 console.log('');
529 console.log('🪶 Klonkt');
530 console.log(` ${baseUrl || `http://localhost:${PORT}`}`);
531 if (baseUrl) console.log(` (bound to ${HOST}:${PORT})`);
532 console.log('');
533 console.log(` ✓ Security: Helmet, CSP, secure sessions`);
534 console.log(` ✓ Privacy: Self-hosted fonts, no third-party requests`);
535 console.log(` ✓ Layout: v9 editorial feel (top nav, profile header)`);
536 console.log(` ✓ Auth: wachtwoord (beheer) + Google (luisteraars) / logout`);
537 console.log(` ✓ Posts: create / edit / view / archive`);
538 console.log('');
539 console.log(` Mode: ${isDev ? 'development' : 'PRODUCTION'}`);
540 console.log('');
541});
542
543export default app;
Note: See TracBrowser for help on using the repository browser.