source: Klonkt/src/server.js@ f1ee40e

main
Last change on this file since f1ee40e was f1ee40e, checked in by Robin Genis <roboburr@…>, 2 months ago

chore(server): startup log shows PUBLIC_BASE_URL when set (was hardcoded localhost)

PUBLIC_BASE_URL already includes scheme+host, so it's logged as-is (no :PORT); the local bind
HOST:PORT is shown as a secondary line. Falls back to http://localhost:PORT when unset.

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