source: Klonkt/src/server.js@ 96c714f

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

Feature: web push slice 2, enable/disable UI + service worker delivery

The visible half of docs/webpush-design.md: an owner can now turn on
notifications per device, pick what to be notified about, and send a test.

  • Routes: GET /push/vapid (the public key, public by design), POST /push/subscribe|/unsubscribe|/alerts|/test (logged-in; a subscription row is personal, only its creator may touch it). Mounted before the /:slug catch-all, like /paid.
  • Service worker: push handler (shows the encrypted JSON payload {type,title,body,url}; same-type bursts collapse via tag) and notificationclick (focus an open tab and navigate, else open a window). Cache name bumped to v19.
  • Beheer -> Notificaties (/admin/push): per-device toggle, alert-type checkboxes (saved prefs shown for the current device), test button, linked-devices list with remove, iOS install hint (push needs an installed PWA there), plain <script> so injectCspNonce provides the real nonce.
  • Not premium-gated: notifications are infrastructure, not an extra.

Verified live on a dev server: /push/vapid serves the generated key,
storage/.vapid is 0600, sw.js carries both handlers, and an unauthenticated
subscribe is refused.

Changed files:
src/server.js

  • mount /push + /admin/push; sw.js push/notificationclick handlers, v19

src/views/pages/admin.ejs

  • "Notificaties" button (always visible, not premium)

New file:
src/routes/push.js

  • vapid/subscribe/unsubscribe/alerts/test

src/routes/admin-push.js

  • the Beheer page (requireSiteManager)

src/views/pages/admin-push.ejs

  • device toggle, prefs, test, device list, iOS hint

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

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