source: Klonkt/src/server.js@ f99bbe8

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

security: bind to 127.0.0.1 by default behind a reverse proxy

New HOST env (default 0.0.0.0 for Docker/back-compat). The VPS installer now
writes HOST=127.0.0.1 and Docker maps the host port to loopback (127.0.0.1:3000:3000)
+ overrides HOST=0.0.0.0 inside the container — so the app is never reachable
directly on its port from the internet, only via the proxy. .env.example defaults
to 127.0.0.1 (manual installs); docs explain it. Existing installs hardened on
re-run of install.sh.

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

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