source: Klonkt/src/server.js@ 99234c3

main
Last change on this file since 99234c3 was 48ca5fc, checked in by Robin Genis <roboburr@…>, 3 months ago

Remove hub mode (step 2/2): delete dead hub routes & views

Remove routes/hub.js, routes/artists.js (+ their server.js mounts/imports/redirect)
and the hub-home + artists-directory views. All were unreachable after step 1
(tenancy can no longer be 'hub'). Shared multi-site infra (getPrimarySite,
site_members, canAdminSite) stays — solo uses it too.

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

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