source: Klonkt/src/server.js@ 297c77d

main
Last change on this file since 297c77d was 4c47eff, checked in by Robin Genis <roboburr@…>, 3 months ago

refactor(cirkel): remove the legacy circle auto-migration (no auto-fediverse)

autoMigrateCircles auto-sent Follows on boot to re-establish legacy circle_links
as AP follows. That violates the rule 'the code never throws anything into the
fediverse automatically' — at scale it would surprise-Follow on behalf of operators
who never asked. Removed the boot call, the function, its export, and the manual
scripts/migrate-circles.mjs (bulk Follows). resolveApActor stays (used by bare-domain
follows). Dead circle_links table is left as harmless dead data; an operator restores
an old cirkel by re-following in /volgend (their own click). We can do this clean
removal now precisely because we're still small-scale.

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

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