source: Klonkt/src/server.js@ 41a7637

main
Last change on this file since 41a7637 was dd1028a, checked in by Robin Genis <roboburr@…>, 3 months ago

fix(activitypub): content-negotiation on canonical URLs

An AP request (Accept: application/activity+json) to a profile or post URL now
302-redirects to its /ap/* representation, so the same URL serves HTML to
browsers and AP-JSON to servers. Fixes Mastodon failing to resolve a pasted
profile/post URL (it received text/html). Gated on apWants() — no cost for
normal browser traffic.

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

  • Property mode set to 100644
File size: 21.3 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';
[7bc636b]22import { resolveSite, loadAudioTracks, loadTheme } from './middleware/site.js';
[8afbdd6]23import { isViewer } from './middleware/auth.js';
24import { renderPage } from './middleware/render.js';
[cb01666]25import { audioEnabled } from './config/features.js';
[7bc636b]26import authRoutes from './routes/auth.js';
27import accountRoutes from './routes/account.js';
[c9c6a2d]28import notificationsRoutes from './routes/notifications.js';
[7bc636b]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 adminCommentsRoutes from './routes/admin-comments.js';
[6351545]35import adminSettingsRoutes from './routes/admin-settings.js';
[6623453]36import adminSeoRoutes from './routes/admin-seo.js';
[7bc636b]37import audioRoutes from './routes/audio.js';
38import searchRoutes from './routes/search.js';
39import commentsRoutes from './routes/comments.js';
40import tagsRoutes from './routes/tags.js';
41import typesRoutes from './routes/types.js';
42import usersRoutes from './routes/users.js';
43import feedRoutes from './routes/feed.js';
[bf61be7]44import hubRoutes from './routes/hub.js';
[8afbdd6]45import artistsRoutes from './routes/artists.js';
[7bc636b]46import postsRoutes from './routes/posts.js';
[03fa548]47import langRoutes from './routes/lang.js';
[b300682]48import federationRoutes from './routes/federation.js';
[25d4041]49import { startCircleSyncLoop } from './services/CircleService.js';
[0091cb7]50import adminCircleRoutes from './routes/admin-circle.js';
[ff08153]51import adminUpdatesRoutes from './routes/admin-updates.js';
[1b4d5dd]52import adminPatreonRoutes from './routes/admin-patreon.js';
[d549549]53import adminStatsRoutes from './routes/admin-stats.js';
[0091cb7]54import circleRoutes from './routes/circle.js';
[255e3d3]55import epkRoutes from './routes/epk.js';
[2e247e4]56import newsletterRoutes from './routes/newsletter.js';
57import adminNewsletterRoutes from './routes/admin-newsletter.js';
[91094a4]58import downloadRoutes from './routes/download.js';
[37edecd]59import linkbioRoutes from './routes/linkbio.js';
[6be57b4]60import embedRoutes from './routes/embed.js';
[8d32dcf]61import showsRoutes from './routes/shows.js';
62import adminShowsRoutes from './routes/admin-shows.js';
[9d9f3c1]63import adminEpkRoutes from './routes/admin-epk.js';
[90259da]64import changelogRoutes from './routes/changelog.js';
[69815b2]65import ogRoutes from './routes/og.js';
[6bd25d1]66import apRoutes from './routes/activitypub.js';
[dd1028a]67import { apWants } from './services/ActivityPubService.js';
[7bc636b]68
[09ee2bd]69// SESSION_SECRET: use the env var if set. Otherwise auto-generate a strong one
70// and persist it next to the database, so it stays stable across restarts and
71// updates. This lets Docker / bare-Node installs run with zero manual config.
[7bc636b]72if (!process.env.SESSION_SECRET) {
[09ee2bd]73 const dataDir = path.dirname(process.env.DATABASE_PATH || './storage/database.sqlite');
74 const secretFile = path.join(dataDir, '.session-secret');
75 try { process.env.SESSION_SECRET = fs.readFileSync(secretFile, 'utf8').trim(); } catch { /* not yet generated */ }
76 if (!process.env.SESSION_SECRET) {
77 fs.mkdirSync(dataDir, { recursive: true });
78 process.env.SESSION_SECRET = crypto.randomBytes(32).toString('hex');
79 fs.writeFileSync(secretFile, process.env.SESSION_SECRET, { mode: 0o600 });
80 console.log(`🔑 Generated a SESSION_SECRET (stored in ${secretFile})`);
81 }
[7bc636b]82}
83
[09ee2bd]84// A SESSION_SECRET that was explicitly set in the env must still be strong in prod.
[7bc636b]85if (process.env.NODE_ENV === 'production' && process.env.SESSION_SECRET.length < 32) {
[09ee2bd]86 console.error('❌ FATAL: SESSION_SECRET is too weak for production (set a longer, random one in .env)');
[7bc636b]87 process.exit(1);
88}
89
90const __dirname = path.dirname(fileURLToPath(import.meta.url));
91const PORT = process.env.PORT || 3000;
[f99bbe8]92// Interface to bind. Default 0.0.0.0 (needed for Docker port-forwarding). Behind a
93// reverse proxy on the same host, set HOST=127.0.0.1 so the app is NOT reachable
94// directly from the internet (only via the proxy) — see README/install docs.
95const HOST = process.env.HOST || '0.0.0.0';
[7bc636b]96const isDev = process.env.NODE_ENV !== 'production';
97
98const app = express();
99const server = http.createServer(app);
100
101app.use(helmet({
102 contentSecurityPolicy: {
103 directives: {
104 defaultSrc: ["'self'"],
[4c9f29a]105 scriptSrc: [
106 "'self'",
107 "'unsafe-inline'",
[834bcc3]108 // Our custom embeds (embed-player.js) load the OFFICIAL player APIs
109 // from these hosts. Without this whitelist the CSP silently blocks them
110 // (only a console error) and the embed player fails.
[4c9f29a]111 "https://www.youtube.com", // YouTube IFrame Player API (+ www-widgetapi.js)
[834bcc3]112 "https://s.ytimg.com", // YouTube player assets
[4c9f29a]113 "https://w.soundcloud.com", // SoundCloud Widget API (api.js)
[16b0c00]114 "https://open.spotify.com", // Spotify iFrame API (loader)
[834bcc3]115 "https://*.spotifycdn.com", // Spotify iFrame API (real bundle: embed-cdn.spotifycdn.com)
[4c9f29a]116 ],
[834bcc3]117 // Helmet's default sets script-src-attr to 'none', which blocks ALL inline
118 // event handlers (onchange/onclick/onsubmit) — causing e.g. the avatar
119 // upload (<input onchange="this.form.submit()">) and the role dropdown to
120 // silently do nothing. We explicitly allow inline handlers, consistent with
121 // the already-allowed inline <script> above.
[c869272]122 scriptSrcAttr: ["'unsafe-inline'"],
[7bc636b]123 styleSrc: ["'self'", "'unsafe-inline'"],
[834bcc3]124 // blob: required for the image editor (Cropper) — it displays the chosen
125 // photo via URL.createObjectURL(blob:…). Without blob: the CSP silently
126 // blocks the <img> → empty edit window. (media-src already has blob: for audio.)
[9effb80]127 imgSrc: ["'self'", "data:", "https:", "blob:"],
[16b0c00]128 connectSrc: ["'self'", "wss:", "ws:", "https://*.spotifycdn.com", "https://*.scdn.co"],
[353c39c]129 // blob: is required for the audio player — it fetch()es track bytes and
130 // plays from a blob: object URL (Spotify-style). Without blob: here the
131 // CSP silently blocks <audio>.src = blob:… → the player fires 'error' and
132 // auto-skips every track. 'self'/https: do NOT imply blob:.
133 mediaSrc: ["'self'", "https:", "blob:"],
[7bc636b]134 fontSrc: ["'self'"],
135 frameSrc: [
136 "'self'",
137 "https://open.spotify.com",
138 "https://w.soundcloud.com",
139 "https://bandcamp.com",
140 "https://embed.music.apple.com",
141 "https://www.youtube-nocookie.com",
[834bcc3]142 "https://www.youtube.com", // YouTube IFrame API sometimes creates a www.youtube.com iframe
[7bc636b]143 "https://player.vimeo.com",
144 ],
145 },
146 },
147 hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
148 frameguard: { action: 'sameorigin' },
149 referrerPolicy: { policy: 'no-referrer-when-downgrade' },
150}));
151
152app.set('view engine', 'ejs');
153app.set('views', path.join(__dirname, 'views'));
154
155app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));
156app.use(bodyParser.json({ limit: '10mb' }));
157
158// Trust one upstream proxy in production. NPM (or Caddy / nginx) terminates
159// HTTPS and forwards to us over plain HTTP, setting X-Forwarded-Proto: https.
160// Without this, Express sees req.protocol === 'http' and won't issue secure
161// cookies — sessions never persist past the redirect after login.
162if (!isDev) app.set('trust proxy', 1);
163
[834bcc3]164// Create/migrate the schema BEFORE anything touches the DB: the session store
165// queries the `sessions` table on construction, so on a fresh install the tables
166// must exist first (otherwise: "no such table: sessions" → crash loop on first boot).
[5f43245]167initializeDatabase();
[834bcc3]168startScheduler(); // release planning: publish scheduled posts when publish_at is reached
[5f43245]169
[834bcc3]170// Safety net: guarantee that there is always a primary site (solo/hub/circle).
171// Idempotent — does nothing if a site already exists or there is no admin yet.
[bdc3c1e]172ensurePrimarySite();
173
[7bc636b]174// Session middleware extracted into a variable so the WebSocket upgrade
175// handler can reuse it (it needs req.session to authenticate sockets).
176const sessionMiddleware = session({
177 store: new SqliteSessionStore(),
178 secret: process.env.SESSION_SECRET,
179 resave: false,
180 saveUninitialized: false,
181 name: 'pcms.sid',
182 cookie: {
183 httpOnly: true,
184 secure: !isDev,
185 sameSite: 'lax',
186 maxAge: 30 * 24 * 60 * 60 * 1000,
187 },
188});
189app.use(sessionMiddleware);
190
191app.use('/assets', express.static(path.join(__dirname, 'assets'), { maxAge: isDev ? 0 : '1y' }));
[fb02cc0]192app.use('/media', express.static(process.env.MEDIA_PATH || './storage/media', {
[834bcc3]193 // Public media (post covers, avatars) must be cross-origin embeddable by other
194 // Klonkt sites in their CIRCLE. Helmet sets CORP=same-origin by default, which
195 // causes the browser to block those images (the file arrives, but the browser
196 // refuses to render it). Set cross-origin explicitly for /media.
[fb02cc0]197 setHeaders: (res) => res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'),
198}));
[7bc636b]199
[834bcc3]200// (Removed) TWA / digital-asset-links — only needed for the APK/TWA variant.
201// Klonkt is PWA-only; assetlinks.json is no longer served.
[7bc636b]202
[834bcc3]203// Circles: periodic background sync of remote instances (no-op unless tenancy='circle').
[25d4041]204startCircleSyncLoop();
205
[7bc636b]206// Bundle HTMX: copy from node_modules into our own assets dir so we can serve
207// it locally (no third-party CDN). Idempotent — only copies if size differs.
208(function ensureLocalHtmx() {
209 const src = path.join(__dirname, '..', 'node_modules', 'htmx.org', 'dist', 'htmx.min.js');
210 const dest = path.join(__dirname, 'assets', 'js', 'htmx.min.js');
211 try {
212 const srcStat = fs.statSync(src);
213 const destStat = fs.existsSync(dest) ? fs.statSync(dest) : null;
214 if (!destStat || destStat.size !== srcStat.size) {
215 fs.copyFileSync(src, dest);
216 console.log(`📦 HTMX bundled locally: ${srcStat.size} bytes`);
217 }
218 } catch (e) {
219 console.warn('⚠️ Could not bundle HTMX:', e.message, '— run `npm install`');
220 }
221})();
222
[834bcc3]223// Circle federation: public, site-agnostic endpoints (/.klonkt/*).
224// Before resolveSite/theme — they don't need a site context.
[b300682]225app.use(federationRoutes);
226
[6bd25d1]227// ActivityPub: WebFinger + /ap/* (site-agnostic, resolves the site by slug).
228app.use(apRoutes);
229
[69815b2]230// Themed OG cards (/og/:slug.png) — resolve the site by slug themselves, so they
231// run before resolveSite and need no site context.
232app.use('/og', ogRoutes);
233
[7bc636b]234app.use(resolveSite);
235app.use(loadAudioTracks);
236app.use(loadTheme);
237
[dd1028a]238// ActivityPub content negotiation on the human URLs: an AP request (Accept:
239// application/activity+json) to a profile/post URL is redirected to its /ap/*
240// representation — same URL serves HTML to browsers, AP-JSON to servers (this is
241// how Mastodon resolves a pasted profile/post URL). Gated on apWants() so normal
242// browser requests pay nothing.
243app.use((req, res, next) => {
244 if (req.method !== 'GET' || !apWants(req)) return next();
245 const site = res.locals.site;
246 if (!site || !site.slug) return next();
247 const seg = req.path.replace(/^\/+|\/+$/g, '');
248 if (seg === '') return res.redirect(302, `/ap/users/${encodeURIComponent(site.slug)}`);
249 if (!seg.includes('/')) {
250 try {
251 const post = db.prepare(
252 "SELECT id FROM posts WHERE site_id = ? AND slug = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
253 ).get(site.id, seg);
254 if (post) return res.redirect(302, `/ap/notes/${post.id}`);
255 } catch { /* fall through to normal HTML handling */ }
256 }
257 return next();
258});
259
[834bcc3]260// Lightweight CSRF defense: reject cross-origin state-mutating requests.
261// Same-origin forms + HTMX send a matching Origin; missing Origin is allowed
262// through (non-browser clients). sameSite:'lax' on the session cookie is the
263// second layer. (Does not apply to GET/HEAD/OPTIONS.)
[9e27d64]264app.use((req, res, next) => {
265 if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
266 const origin = req.get('origin');
[834bcc3]267 if (!origin) return next(); // no Origin → no browser CSRF vector
[9e27d64]268 let originHost;
269 try { originHost = new URL(origin).host; } catch { return res.status(403).send('Ongeldige origin'); }
270 if (originHost !== req.get('host')) return res.status(403).send('Cross-origin request geweigerd');
271 next();
272});
273
[834bcc3]274// Viewer accounts: may view everything (including Admin), change nothing. This is
275// the ONLY write gate — fail-closed, before all route handlers. Every state-mutating
276// method is rejected (the login POST sets the session after this guard, so it is
277// not affected). Instead of raw 403 text we render a clean page (or, for HTMX,
278// a swapped-in message).
[640b39c]279app.use((req, res, next) => {
[8afbdd6]280 const mutating = req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS';
281 if (mutating && isViewer(req.session?.user)) {
282 if (req.headers['hx-request'] === 'true') {
[834bcc3]283 // htmx doesn't swap on 4xx; send 200 + retarget so the message appears in #pcms-main.
[8afbdd6]284 res.setHeader('HX-Retarget', '#pcms-main');
285 res.setHeader('HX-Reswap', 'innerHTML');
286 res.status(200);
287 } else {
288 res.status(403);
289 }
290 return renderPage(req, res, 'pages/viewer-blocked', {
291 pageTitle: 'Kijker-modus',
292 bodyClass: 'on-special',
293 });
[640b39c]294 }
295 next();
296});
297
[7bc636b]298app.use('/auth', authRoutes);
299app.use('/account', accountRoutes);
[c9c6a2d]300app.use('/notifications', notificationsRoutes);
[cb01666]301if (audioEnabled()) {
302 app.use('/admin/audio', adminAudioRoutes);
303 app.use('/admin/playlists', adminPlaylistsRoutes);
304}
[7bc636b]305app.use('/admin/sites', adminSitesRoutes);
306app.use('/admin/users', adminUsersRoutes);
307app.use('/admin/comments', adminCommentsRoutes);
[6351545]308app.use('/admin/settings', adminSettingsRoutes);
[6623453]309app.use('/admin/seo', adminSeoRoutes);
[0091cb7]310app.use('/admin/circle', adminCircleRoutes);
[ff08153]311app.use('/admin/updates', adminUpdatesRoutes);
[1b4d5dd]312app.use('/admin/patreon', adminPatreonRoutes);
[d549549]313app.use('/admin/stats', adminStatsRoutes);
[2e247e4]314app.use('/admin/newsletter', adminNewsletterRoutes);
[8d32dcf]315app.use('/admin/shows', adminShowsRoutes);
[9d9f3c1]316app.use('/admin/epk', adminEpkRoutes);
[7bc636b]317app.use('/admin', adminRoutes);
[cb01666]318if (audioEnabled()) app.use('/audio', audioRoutes);
[7bc636b]319app.use('/search', searchRoutes);
320app.use('/comments', commentsRoutes);
321app.use('/tag', tagsRoutes);
322app.use('/type', typesRoutes);
323app.use('/users', usersRoutes);
324// Feed/sitemap routes are mounted at root because they're at well-known paths
325app.use('/', feedRoutes);
[834bcc3]326app.use('/leden', artistsRoutes); // searchable member directory (hub only; solo: next())
[a1c8cb8]327app.get('/artiesten', (req, res) => res.redirect(301, req.originalUrl.replace(/^\/artiesten/, '/leden'))); // oude URL -> /leden
[bf61be7]328app.use('/', hubRoutes); // hub-overview op '/' (solo: next() -> postsRoutes)
[0091cb7]329app.use('/', circleRoutes); // /cirkel-feed (solo/hub: next() -> postsRoutes)
[255e3d3]330app.use('/', epkRoutes); // /pers perskit (premium; niet-premium: next() -> 404)
[2e247e4]331app.use('/', newsletterRoutes); // /nieuwsbrief in/uitschrijven (premium; niet-premium: next())
[cb01666]332if (audioEnabled()) app.use('/', downloadRoutes); // /downloads + /download/:id (audio; lite: uit)
[37edecd]333app.use('/', linkbioRoutes); // /links link-in-bio + klikstats (premium)
[cb01666]334if (audioEnabled()) app.use('/', embedRoutes); // /embed inbedbare audiospeler (audio; lite: uit)
[8d32dcf]335app.use('/', showsRoutes); // /shows agenda + notify-me (premium)
[90259da]336app.use('/', changelogRoutes); // /changelog publieke release-/wijzigingen-pagina
[03fa548]337app.use('/', langRoutes); // /lang/:code — interface-taal kiezen (vóór de catch-all)
[7bc636b]338app.use('/', postsRoutes);
339
340app.get('/manifest.webmanifest', (req, res) => {
341 const site = res.locals.site;
342
343 // PWA scope: confines installed apps to ONE site. If a user is in the
344 // bedrijf1 PWA and clicks a link to /sites/bedrijf2/..., the browser will
345 // open it in a regular tab (out-of-scope) instead of within the PWA.
346 // Same applies to APK packaging — the WebView is locked to this scope.
347 //
348 // For path-mounted sites: scope = /sites/<slug>/
349 // For root/subdomain sites: scope = /
350 const base = res.locals.siteUrlBase || ''; // '' or '/sites/<slug>'
351 const scope = (base || '') + '/';
352 const startUrl = (base || '') + '/?source=pwa';
353
[7007d4c]354 // A stable identity per site so installs don't collide (Chromium uses `id`).
[834bcc3]355 // NB: changing the id orphans existing PWA installs (no migration carries an
356 // install across an id change) — anyone who already installed the site as a
357 // PWA will need to reinstall once. Data stays server-side, so nothing is lost.
[7007d4c]358 const idBase = site?.slug ? `klonkt-${site.slug}` : 'klonkt';
[7bc636b]359
360 res.set('Cache-Control', 'no-cache');
361 res.json({
362 id: idBase,
[7007d4c]363 name: site?.title || 'Klonkt',
[8afbdd6]364 short_name: (site?.title || 'Klonkt').slice(0, 12),
[7bc636b]365 description: site?.description || site?.tagline || '',
366 scope,
367 start_url: startUrl,
368 display: 'standalone',
369 display_override: ['standalone', 'minimal-ui'],
370 orientation: 'any',
371 background_color: '#1a1a17',
[dd7e2a2]372 theme_color: site?.accent || '#e8b04b',
[7bc636b]373 lang: site?.language || 'nl',
374 icons: [
375 { src: '/favicon.svg', sizes: 'any', type: 'image/svg+xml' },
376 { src: '/favicon.ico', sizes: '64x64', type: 'image/x-icon' },
377 ],
378 // Hint to capable browsers: capture all in-scope links inside the PWA
379 capture_links: 'existing-client-navigate',
380 });
381});
382
383// Favicon — served as SVG so it picks up the site's accent color dynamically.
384// Browsers also request /favicon.ico by convention; we serve the same SVG
385// content there with a forgiving content-type since modern browsers accept it.
386function _renderFavicon(res, accent) {
[9b851e7]387 const safeAccent = /^#[0-9a-fA-F]{3,8}$/.test(accent) ? accent : '#e8b04b';
[5e95aac]388 // Site mark: rounded square in the site accent + bold white 'K' (Klonkt)
[7bc636b]389 const svg = `<?xml version="1.0" encoding="UTF-8"?>
390<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
391 <rect width="64" height="64" rx="14" fill="${safeAccent}"/>
[5e95aac]392 <text x="50%" y="50%" dy="0.35em" text-anchor="middle"
[b5bae24]393 font-family="Arial, Helvetica, sans-serif"
[5e95aac]394 font-size="42" font-weight="800" fill="#fff">K</text>
[7bc636b]395</svg>`;
396 res.set('Content-Type', 'image/svg+xml');
397 res.set('Cache-Control', 'public, max-age=86400');
398 res.send(svg);
399}
400
401app.get('/favicon.svg', (req, res) => {
402 _renderFavicon(res, res.locals.site?.accent);
403});
404app.get('/favicon.ico', (req, res) => {
405 // Browsers requesting .ico will accept SVG content; chrome/firefox both fine.
406 // Keeping the route prevents 404 spam in the console.
407 _renderFavicon(res, res.locals.site?.accent);
408});
409
410app.get('/sw.js', (req, res) => {
411 res.set('Content-Type', 'application/javascript');
412 res.set('Cache-Control', 'no-cache');
413 res.send(`
[b08b5bc]414const CACHE_VERSION = 'pcms-v11-' + new Date().toISOString().split('T')[0];
[7bc636b]415self.addEventListener('install', e => {
416 e.waitUntil(caches.open(CACHE_VERSION).then(c => c.addAll(['/'])));
417 self.skipWaiting();
418});
419self.addEventListener('activate', e => {
420 e.waitUntil(caches.keys().then(keys => Promise.all(
421 keys.filter(k => k !== CACHE_VERSION).map(k => caches.delete(k))
422 )));
423 self.clients.claim();
424});
[834bcc3]425// ONLY intercept navigations (HTML pages) for an offline fallback.
426// Do NOT touch images, CSS, JS or /media — let the browser handle those natively.
427// Otherwise a failed network fetch could fall back to an empty cache match
428// (undefined) and "break" an image on a normal refresh (hard reload bypasses
429// the SW, which is why that case worked fine).
[7bc636b]430self.addEventListener('fetch', e => {
431 if (e.request.method !== 'GET') return;
[834bcc3]432 if (e.request.mode !== 'navigate') return; // page loads only
[b08b5bc]433 e.respondWith(
434 fetch(e.request).catch(() => caches.match('/').then(r => r || Response.error()))
435 );
[7bc636b]436});
437 `);
438});
439
440process.on('unhandledRejection', (reason) => {
441 console.error('⚠️ Unhandled Rejection:', reason);
442});
443
444app.use((err, req, res, next) => {
445 console.error('❌ Error:', err);
446 res.status(err.status || 500).send(
447 isDev ? `<pre>${err.stack || err.message}</pre>` : 'Internal Server Error'
448 );
449});
450
451app.use((req, res) => {
[3b6e04a]452 res.status(404);
[834bcc3]453 // Clean, mobile-friendly 404 via the shell (viewport + nav + site theme).
454 // Falls back to bare HTML if rendering unexpectedly fails.
[3b6e04a]455 try {
456 return renderPage(req, res, 'pages/404', {
457 pageTitle: '404 — niet gevonden',
458 bodyClass: 'on-special on-404',
459 });
460 } catch (e) {
461 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>');
462 }
[7bc636b]463});
464
[f99bbe8]465server.listen(PORT, HOST, () => {
[7bc636b]466 console.log('');
[83faa57]467 console.log('🪶 Klonkt Beta');
[7bc636b]468 console.log(` http://localhost:${PORT}`);
469 console.log('');
470 console.log(` ✓ Security: Helmet, CSP, secure sessions`);
471 console.log(` ✓ Privacy: Self-hosted fonts, no third-party requests`);
472 console.log(` ✓ Layout: v9 editorial feel (top nav, profile header)`);
[9e27d64]473 console.log(` ✓ Auth: wachtwoord (beheer) + Google (luisteraars) / logout`);
[7bc636b]474 console.log(` ✓ Posts: create / edit / view / archive`);
475 console.log('');
476 console.log(` Mode: ${isDev ? 'development' : 'PRODUCTION'}`);
477 console.log('');
478});
479
480export default app;
Note: See TracBrowser for help on using the repository browser.