source: Klonkt/src/server.js@ 09ee2bd

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

feat: auto-generate SESSION_SECRET if not set (zero-config Docker/manual)

If SESSION_SECRET is missing, generate a strong one on first boot and persist it
to <dataDir>/.session-secret (stable across restarts/updates). Env var still wins.
PUBLIC_BASE_URL already falls back to the request host. So Docker (B) and manual
(C) installs now run with no required .env editing. Docs + .env.example updated;
docker-compose comment translated to English.

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

  • Property mode set to 100644
File size: 19.6 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 notificationsRoutes from './routes/notifications.js';
29import adminRoutes from './routes/admin.js';
30import adminAudioRoutes from './routes/admin-audio.js';
31import adminPlaylistsRoutes from './routes/admin-playlists.js';
32import adminSitesRoutes from './routes/admin-sites.js';
33import adminUsersRoutes from './routes/admin-users.js';
34import adminCommentsRoutes from './routes/admin-comments.js';
35import adminSettingsRoutes from './routes/admin-settings.js';
36import adminSeoRoutes from './routes/admin-seo.js';
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';
44import hubRoutes from './routes/hub.js';
45import artistsRoutes from './routes/artists.js';
46import postsRoutes from './routes/posts.js';
47import langRoutes from './routes/lang.js';
48import federationRoutes from './routes/federation.js';
49import { startCircleSyncLoop } from './services/CircleService.js';
50import adminCircleRoutes from './routes/admin-circle.js';
51import adminUpdatesRoutes from './routes/admin-updates.js';
52import adminPatreonRoutes from './routes/admin-patreon.js';
53import adminStatsRoutes from './routes/admin-stats.js';
54import circleRoutes from './routes/circle.js';
55import epkRoutes from './routes/epk.js';
56import newsletterRoutes from './routes/newsletter.js';
57import adminNewsletterRoutes from './routes/admin-newsletter.js';
58import downloadRoutes from './routes/download.js';
59import linkbioRoutes from './routes/linkbio.js';
60import embedRoutes from './routes/embed.js';
61import showsRoutes from './routes/shows.js';
62import adminShowsRoutes from './routes/admin-shows.js';
63import adminEpkRoutes from './routes/admin-epk.js';
64import changelogRoutes from './routes/changelog.js';
65
66// SESSION_SECRET: use the env var if set. Otherwise auto-generate a strong one
67// and persist it next to the database, so it stays stable across restarts and
68// updates. This lets Docker / bare-Node installs run with zero manual config.
69if (!process.env.SESSION_SECRET) {
70 const dataDir = path.dirname(process.env.DATABASE_PATH || './storage/database.sqlite');
71 const secretFile = path.join(dataDir, '.session-secret');
72 try { process.env.SESSION_SECRET = fs.readFileSync(secretFile, 'utf8').trim(); } catch { /* not yet generated */ }
73 if (!process.env.SESSION_SECRET) {
74 fs.mkdirSync(dataDir, { recursive: true });
75 process.env.SESSION_SECRET = crypto.randomBytes(32).toString('hex');
76 fs.writeFileSync(secretFile, process.env.SESSION_SECRET, { mode: 0o600 });
77 console.log(`🔑 Generated a SESSION_SECRET (stored in ${secretFile})`);
78 }
79}
80
81// A SESSION_SECRET that was explicitly set in the env must still be strong in prod.
82if (process.env.NODE_ENV === 'production' && process.env.SESSION_SECRET.length < 32) {
83 console.error('❌ FATAL: SESSION_SECRET is too weak for production (set a longer, random one in .env)');
84 process.exit(1);
85}
86
87const __dirname = path.dirname(fileURLToPath(import.meta.url));
88const PORT = process.env.PORT || 3000;
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'"],
98 scriptSrc: [
99 "'self'",
100 "'unsafe-inline'",
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.
104 "https://www.youtube.com", // YouTube IFrame Player API (+ www-widgetapi.js)
105 "https://s.ytimg.com", // YouTube player assets
106 "https://w.soundcloud.com", // SoundCloud Widget API (api.js)
107 "https://open.spotify.com", // Spotify iFrame API (loader)
108 "https://*.spotifycdn.com", // Spotify iFrame API (real bundle: embed-cdn.spotifycdn.com)
109 ],
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.
115 scriptSrcAttr: ["'unsafe-inline'"],
116 styleSrc: ["'self'", "'unsafe-inline'"],
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.)
120 imgSrc: ["'self'", "data:", "https:", "blob:"],
121 connectSrc: ["'self'", "wss:", "ws:", "https://*.spotifycdn.com", "https://*.scdn.co"],
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:"],
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",
135 "https://www.youtube.com", // YouTube IFrame API sometimes creates a www.youtube.com iframe
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
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).
160initializeDatabase();
161startScheduler(); // release planning: publish scheduled posts when publish_at is reached
162
163// Safety net: guarantee that there is always a primary site (solo/hub/circle).
164// Idempotent — does nothing if a site already exists or there is no admin yet.
165ensurePrimarySite();
166
167// Session middleware extracted into a variable so the WebSocket upgrade
168// handler can reuse it (it needs req.session to authenticate sockets).
169const sessionMiddleware = session({
170 store: new SqliteSessionStore(),
171 secret: process.env.SESSION_SECRET,
172 resave: false,
173 saveUninitialized: false,
174 name: 'pcms.sid',
175 cookie: {
176 httpOnly: true,
177 secure: !isDev,
178 sameSite: 'lax',
179 maxAge: 30 * 24 * 60 * 60 * 1000,
180 },
181});
182app.use(sessionMiddleware);
183
184app.use('/assets', express.static(path.join(__dirname, 'assets'), { maxAge: isDev ? 0 : '1y' }));
185app.use('/media', express.static(process.env.MEDIA_PATH || './storage/media', {
186 // Public media (post covers, avatars) must be cross-origin embeddable by other
187 // Klonkt sites in their CIRCLE. Helmet sets CORP=same-origin by default, which
188 // causes the browser to block those images (the file arrives, but the browser
189 // refuses to render it). Set cross-origin explicitly for /media.
190 setHeaders: (res) => res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'),
191}));
192
193// (Removed) TWA / digital-asset-links — only needed for the APK/TWA variant.
194// Klonkt is PWA-only; assetlinks.json is no longer served.
195
196// Circles: periodic background sync of remote instances (no-op unless tenancy='circle').
197startCircleSyncLoop();
198
199// Bundle HTMX: copy from node_modules into our own assets dir so we can serve
200// it locally (no third-party CDN). Idempotent — only copies if size differs.
201(function ensureLocalHtmx() {
202 const src = path.join(__dirname, '..', 'node_modules', 'htmx.org', 'dist', 'htmx.min.js');
203 const dest = path.join(__dirname, 'assets', 'js', 'htmx.min.js');
204 try {
205 const srcStat = fs.statSync(src);
206 const destStat = fs.existsSync(dest) ? fs.statSync(dest) : null;
207 if (!destStat || destStat.size !== srcStat.size) {
208 fs.copyFileSync(src, dest);
209 console.log(`📦 HTMX bundled locally: ${srcStat.size} bytes`);
210 }
211 } catch (e) {
212 console.warn('⚠️ Could not bundle HTMX:', e.message, '— run `npm install`');
213 }
214})();
215
216// Circle federation: public, site-agnostic endpoints (/.klonkt/*).
217// Before resolveSite/theme — they don't need a site context.
218app.use(federationRoutes);
219
220app.use(resolveSite);
221app.use(loadAudioTracks);
222app.use(loadTheme);
223
224// Lightweight CSRF defense: reject cross-origin state-mutating requests.
225// Same-origin forms + HTMX send a matching Origin; missing Origin is allowed
226// through (non-browser clients). sameSite:'lax' on the session cookie is the
227// second layer. (Does not apply to GET/HEAD/OPTIONS.)
228app.use((req, res, next) => {
229 if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
230 const origin = req.get('origin');
231 if (!origin) return next(); // no Origin → no browser CSRF vector
232 let originHost;
233 try { originHost = new URL(origin).host; } catch { return res.status(403).send('Ongeldige origin'); }
234 if (originHost !== req.get('host')) return res.status(403).send('Cross-origin request geweigerd');
235 next();
236});
237
238// Viewer accounts: may view everything (including Admin), change nothing. This is
239// the ONLY write gate — fail-closed, before all route handlers. Every state-mutating
240// method is rejected (the login POST sets the session after this guard, so it is
241// not affected). Instead of raw 403 text we render a clean page (or, for HTMX,
242// a swapped-in message).
243app.use((req, res, next) => {
244 const mutating = req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS';
245 if (mutating && isViewer(req.session?.user)) {
246 if (req.headers['hx-request'] === 'true') {
247 // htmx doesn't swap on 4xx; send 200 + retarget so the message appears in #pcms-main.
248 res.setHeader('HX-Retarget', '#pcms-main');
249 res.setHeader('HX-Reswap', 'innerHTML');
250 res.status(200);
251 } else {
252 res.status(403);
253 }
254 return renderPage(req, res, 'pages/viewer-blocked', {
255 pageTitle: 'Kijker-modus',
256 bodyClass: 'on-special',
257 });
258 }
259 next();
260});
261
262app.use('/auth', authRoutes);
263app.use('/account', accountRoutes);
264app.use('/notifications', notificationsRoutes);
265if (audioEnabled()) {
266 app.use('/admin/audio', adminAudioRoutes);
267 app.use('/admin/playlists', adminPlaylistsRoutes);
268}
269app.use('/admin/sites', adminSitesRoutes);
270app.use('/admin/users', adminUsersRoutes);
271app.use('/admin/comments', adminCommentsRoutes);
272app.use('/admin/settings', adminSettingsRoutes);
273app.use('/admin/seo', adminSeoRoutes);
274app.use('/admin/circle', adminCircleRoutes);
275app.use('/admin/updates', adminUpdatesRoutes);
276app.use('/admin/patreon', adminPatreonRoutes);
277app.use('/admin/stats', adminStatsRoutes);
278app.use('/admin/newsletter', adminNewsletterRoutes);
279app.use('/admin/shows', adminShowsRoutes);
280app.use('/admin/epk', adminEpkRoutes);
281app.use('/admin', adminRoutes);
282if (audioEnabled()) app.use('/audio', audioRoutes);
283app.use('/search', searchRoutes);
284app.use('/comments', commentsRoutes);
285app.use('/tag', tagsRoutes);
286app.use('/type', typesRoutes);
287app.use('/users', usersRoutes);
288// Feed/sitemap routes are mounted at root because they're at well-known paths
289app.use('/', feedRoutes);
290app.use('/leden', artistsRoutes); // searchable member directory (hub only; solo: next())
291app.get('/artiesten', (req, res) => res.redirect(301, req.originalUrl.replace(/^\/artiesten/, '/leden'))); // oude URL -> /leden
292app.use('/', hubRoutes); // hub-overview op '/' (solo: next() -> postsRoutes)
293app.use('/', circleRoutes); // /cirkel-feed (solo/hub: next() -> postsRoutes)
294app.use('/', epkRoutes); // /pers perskit (premium; niet-premium: next() -> 404)
295app.use('/', newsletterRoutes); // /nieuwsbrief in/uitschrijven (premium; niet-premium: next())
296if (audioEnabled()) app.use('/', downloadRoutes); // /downloads + /download/:id (audio; lite: uit)
297app.use('/', linkbioRoutes); // /links link-in-bio + klikstats (premium)
298if (audioEnabled()) app.use('/', embedRoutes); // /embed inbedbare audiospeler (audio; lite: uit)
299app.use('/', showsRoutes); // /shows agenda + notify-me (premium)
300app.use('/', changelogRoutes); // /changelog publieke release-/wijzigingen-pagina
301app.use('/', langRoutes); // /lang/:code — interface-taal kiezen (vóór de catch-all)
302app.use('/', postsRoutes);
303
304app.get('/manifest.webmanifest', (req, res) => {
305 const site = res.locals.site;
306
307 // PWA scope: confines installed apps to ONE site. If a user is in the
308 // bedrijf1 PWA and clicks a link to /sites/bedrijf2/..., the browser will
309 // open it in a regular tab (out-of-scope) instead of within the PWA.
310 // Same applies to APK packaging — the WebView is locked to this scope.
311 //
312 // For path-mounted sites: scope = /sites/<slug>/
313 // For root/subdomain sites: scope = /
314 const base = res.locals.siteUrlBase || ''; // '' or '/sites/<slug>'
315 const scope = (base || '') + '/';
316 const startUrl = (base || '') + '/?source=pwa';
317
318 // A stable identity per site so installs don't collide (Chromium uses `id`).
319 // NB: changing the id orphans existing PWA installs (no migration carries an
320 // install across an id change) — anyone who already installed the site as a
321 // PWA will need to reinstall once. Data stays server-side, so nothing is lost.
322 const idBase = site?.slug ? `klonkt-${site.slug}` : 'klonkt';
323
324 res.set('Cache-Control', 'no-cache');
325 res.json({
326 id: idBase,
327 name: site?.title || 'Klonkt',
328 short_name: (site?.title || 'Klonkt').slice(0, 12),
329 description: site?.description || site?.tagline || '',
330 scope,
331 start_url: startUrl,
332 display: 'standalone',
333 display_override: ['standalone', 'minimal-ui'],
334 orientation: 'any',
335 background_color: '#1a1a17',
336 theme_color: site?.accent || '#e8b04b',
337 lang: site?.language || 'nl',
338 icons: [
339 { src: '/favicon.svg', sizes: 'any', type: 'image/svg+xml' },
340 { src: '/favicon.ico', sizes: '64x64', type: 'image/x-icon' },
341 ],
342 // Hint to capable browsers: capture all in-scope links inside the PWA
343 capture_links: 'existing-client-navigate',
344 });
345});
346
347// Favicon — served as SVG so it picks up the site's accent color dynamically.
348// Browsers also request /favicon.ico by convention; we serve the same SVG
349// content there with a forgiving content-type since modern browsers accept it.
350function _renderFavicon(res, accent) {
351 const safeAccent = /^#[0-9a-fA-F]{3,8}$/.test(accent) ? accent : '#e8b04b';
352 // Site mark: rounded square in the site accent + bold white 'K' (Klonkt)
353 const svg = `<?xml version="1.0" encoding="UTF-8"?>
354<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
355 <rect width="64" height="64" rx="14" fill="${safeAccent}"/>
356 <text x="50%" y="50%" dy="0.35em" text-anchor="middle"
357 font-family="Arial, Helvetica, sans-serif"
358 font-size="42" font-weight="800" fill="#fff">K</text>
359</svg>`;
360 res.set('Content-Type', 'image/svg+xml');
361 res.set('Cache-Control', 'public, max-age=86400');
362 res.send(svg);
363}
364
365app.get('/favicon.svg', (req, res) => {
366 _renderFavicon(res, res.locals.site?.accent);
367});
368app.get('/favicon.ico', (req, res) => {
369 // Browsers requesting .ico will accept SVG content; chrome/firefox both fine.
370 // Keeping the route prevents 404 spam in the console.
371 _renderFavicon(res, res.locals.site?.accent);
372});
373
374app.get('/sw.js', (req, res) => {
375 res.set('Content-Type', 'application/javascript');
376 res.set('Cache-Control', 'no-cache');
377 res.send(`
378const CACHE_VERSION = 'pcms-v11-' + new Date().toISOString().split('T')[0];
379self.addEventListener('install', e => {
380 e.waitUntil(caches.open(CACHE_VERSION).then(c => c.addAll(['/'])));
381 self.skipWaiting();
382});
383self.addEventListener('activate', e => {
384 e.waitUntil(caches.keys().then(keys => Promise.all(
385 keys.filter(k => k !== CACHE_VERSION).map(k => caches.delete(k))
386 )));
387 self.clients.claim();
388});
389// ONLY intercept navigations (HTML pages) for an offline fallback.
390// Do NOT touch images, CSS, JS or /media — let the browser handle those natively.
391// Otherwise a failed network fetch could fall back to an empty cache match
392// (undefined) and "break" an image on a normal refresh (hard reload bypasses
393// the SW, which is why that case worked fine).
394self.addEventListener('fetch', e => {
395 if (e.request.method !== 'GET') return;
396 if (e.request.mode !== 'navigate') return; // page loads only
397 e.respondWith(
398 fetch(e.request).catch(() => caches.match('/').then(r => r || Response.error()))
399 );
400});
401 `);
402});
403
404process.on('unhandledRejection', (reason) => {
405 console.error('⚠️ Unhandled Rejection:', reason);
406});
407
408app.use((err, req, res, next) => {
409 console.error('❌ Error:', err);
410 res.status(err.status || 500).send(
411 isDev ? `<pre>${err.stack || err.message}</pre>` : 'Internal Server Error'
412 );
413});
414
415app.use((req, res) => {
416 res.status(404);
417 // Clean, mobile-friendly 404 via the shell (viewport + nav + site theme).
418 // Falls back to bare HTML if rendering unexpectedly fails.
419 try {
420 return renderPage(req, res, 'pages/404', {
421 pageTitle: '404 — niet gevonden',
422 bodyClass: 'on-special on-404',
423 });
424 } catch (e) {
425 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>');
426 }
427});
428
429server.listen(PORT, () => {
430 console.log('');
431 console.log('🪶 Klonkt Beta');
432 console.log(` http://localhost:${PORT}`);
433 console.log('');
434 console.log(` ✓ Security: Helmet, CSP, secure sessions`);
435 console.log(` ✓ Privacy: Self-hosted fonts, no third-party requests`);
436 console.log(` ✓ Layout: v9 editorial feel (top nav, profile header)`);
437 console.log(` ✓ Auth: wachtwoord (beheer) + Google (luisteraars) / logout`);
438 console.log(` ✓ Posts: create / edit / view / archive`);
439 console.log('');
440 console.log(` Mode: ${isDev ? 'development' : 'PRODUCTION'}`);
441 console.log('');
442});
443
444export default app;
Note: See TracBrowser for help on using the repository browser.