source: Klonkt/src/server.js@ 8ed65a6

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

Feature: OAuth 2.0 for ActivityPub C2S (phase 1 — auth handshake)

First half of AP Client-to-Server: the auth layer native/web clients (Shaer)
need before they can drive a Klonkt account. The AP spec's own C2S half is what
keeps this inside-spec instead of cloning Mastodon's REST API.

  • OAuthService: public-client OAuth (RFC 8252), PKCE S256 REQUIRED, no secrets. Dynamic registration (RFC 7591 subset) with strict redirect_uri validation (https / loopback http / reverse-DNS custom scheme). Single-use 10-min codes; tokens stored sha256-hashed; a token is scoped to one user + one site.
  • routes/oauth.js: /oauth/register, /oauth/authorize (session-authed consent screen picking the site), /oauth/token, and RFC 8414 server metadata at /.well-known/oauth-authorization-server. Redirect params are appended to the registered URI verbatim (no new URL() round-trip that would mangle a native custom scheme). Pre-redirect validation errors never bounce to an unvalidated URI (open-redirect guard).
  • Actor doc advertises oauthAuthorizationEndpoint/oauthTokenEndpoint/uploadMedia in endpoints{} — all AP-spec terms, added to the AS2 conformance allowlist — so clients discover paths instead of hardcoding them (Klonkt's /ap/users/:slug differs from the daemon's /actors/:name; discovery makes that irrelevant).
  • oauth_clients/oauth_codes/oauth_tokens tables (additive).
  • i18n NL/EN/DE for the consent screen.

7 new OAuth tests (PKCE round-trip, replay protection, wrong-verifier reject,
bearer resolution incl. revoke, redirect-uri validation); 73 green. Verified
the full HTTP flow end to end (register → consent → code → token → bearer) and
that the raw Location header preserves the native redirect URI exactly. Beads:
klonkt-demo-srr. Next: klonkt-demo-1w4 (POST outbox accepts the activities).

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

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