source: Klonkt/src/server.js@ 19fbe03

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

refactor(comments): remove native comments — social is fediverse-only

Removes routes/comments.js + admin-comments.js (+ mounts), the comment section &
reply UI on posts, comment loading in the post route, the admin moderation page +
links, and the per-site comment-moderation settings. The 'From the fediverse'
section is now the post's comment area. The .comment CSS stays (reused there);
the comments table is left in place (dead) so old-data cascade-deletes still work.

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

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