source: Klonkt/src/server.js@ c72e45e

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

Trust proxy hoort bij waar je draait, niet bij dev of prod (Barts 429-jacht)

De wortel van drie klachten tegelijk. klonkt-dev draait NODE_ENV=
development ACHTER Caddy, en trust proxy hing aan !isDev: voor elk
verzoek was req.ip dus 127.0.0.1, en de hele wereld deelde EEN
rate-limit-emmer van 300/min met de honderd kudde-daemons van de
caseload-test. De kudde leegde hem; Barts refresh kreeg 'Too many
requests', en de live-lus van de app verhongerde aan dezelfde 429's --
die schakelt bij fouten terug naar een poging per minuut, dus 'live
hulpaanvragen komen niet binnen' was hetzelfde gat.

TRUST_PROXY=1 (nu in dev's .env) zet hem aan waar een proxy voor de
deur staat; kaal-op-poort blijft uit, want een direct bereikbare server
die X-Forwarded-For vertrouwt laat iedereen zijn eigen IP kiezen -- en
daarmee de limiter omzeilen.

De push bleek intussen NIET stuk: push_subscriptions.last_ok_at staat op
22:57:54, seconden na de hulpvraag van @mee -- de server leverde met
succes bij FCM af. Wat er daarna met de notificatie gebeurt is aan het
ontvangende toestel (permissie, service worker, niet-storen), niet aan
deze kant.

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

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