source: Klonkt/src/server.js@ c1f5c23

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

Guardian 2: kloon van de Guardian-PWA als groeiplek voor losse guardians

Robins besluit: /guardian blijft zoals die is; op /guardian2 bouwen we de
losse-guardians-variant uit (guardian-only accounts zonder site, uitnodigings-
flow, per-account push, meekijken/follow-goedkeuring). Start is een 1-op-1
kloon met eigen assets en eigen manifest-id zodat beide PWA's naast elkaar
installeerbaar zijn.

New file:
src/routes/guardian2.js
src/views/pages/guardian2.ejs
src/assets/js/guardian2.js
src/assets/css/guardian2.css

  • kloon van v1, alle paden en manifest-id op guardian2

Changed files:
src/server.js

  • /guardian2 gemount naast /guardian

remarks: smoke: app.js 200 no-cache, page auth-gated, manifest eigen id;
npm test 164/164.

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

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