source: Klonkt/src/server.js@ 61e3daf

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

Feature: paid posts slice 1, owner Patreon config (encrypted)

The site owner can connect their OWN Patreon campaign for paid posts
(klonkt-demo-aki), premium-gated in Beheer. Client id/secret, campaign
id and the creator access/refresh token are stored ENCRYPTED at rest
(new CryptoBox AES-256-GCM helper, key from PAID_SECRET), so a database
dump leaks nothing usable; the token auto-refreshes. Separate from
Klonkt Premium's license flow, which is untouched. Degrades gracefully:
without PAID_SECRET the admin page refuses to save rather than storing
plaintext. Nothing patron-facing yet (posts.paid + unlock come in
slices 2 to 4), so no changelog entry.

CryptoBox also carries the cookie-less signed-blob helper (signBlob/
verifyBlob) that slices 3 and 4 reuse for the OAuth state and the
WebAuthn challenge.

Changed files:
src/config/database.js

  • paid_patreon table (site_id PK, secrets encrypted)

src/server.js

  • mount /admin/paid

src/views/pages/admin.ejs

  • "Betaalde posts" button in Beheer

New file:
src/services/CryptoBox.js

  • aes-256-gcm encrypt/decrypt + HMAC signBlob/verifyBlob

src/services/PaidPatreonService.js

  • owner config CRUD (encrypted), token refresh, creatorAccessToken

src/routes/admin-paid.js

  • premium-gated config form (GET/POST/disconnect)

src/views/pages/admin-paid.ejs

  • the form + status

test/paid-patreon.test.js

  • crypto roundtrip, no-plaintext-in-DB, refresh, blob signing

docs/paid-posts-design.md, docs/privacy-betaalde-posts.md

  • concurrency property documented

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

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