source: Klonkt/src/server.js@ b79466e

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

feat(fediverse): self-heal the timeline cache once per SELFHEAL_VERSION bump

selfHealTimeline() re-fetches cached ap_timeline notes and refreshes content +
media (recovers covers/edits delivered during a flux window, e.g. a fleet-wide
update) and drops gone (404/410) notes. Gated by a selfheal_version setting so it
runs ONCE after a SELFHEAL_VERSION bump, not on every boot. Async + bounded
(latest 200) like autoMigrateCircles. Closes prutfolio-src-5gl.

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

  • Property mode set to 100644
File size: 20.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 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 postsRoutes from './routes/posts.js';
43import langRoutes from './routes/lang.js';
44import adminUpdatesRoutes from './routes/admin-updates.js';
45import adminPatreonRoutes from './routes/admin-patreon.js';
46import adminStatsRoutes from './routes/admin-stats.js';
47import circleRoutes from './routes/circle.js';
48import epkRoutes from './routes/epk.js';
49import newsletterRoutes from './routes/newsletter.js';
50import adminNewsletterRoutes from './routes/admin-newsletter.js';
51import downloadRoutes from './routes/download.js';
52import linkbioRoutes from './routes/linkbio.js';
53import embedRoutes from './routes/embed.js';
54import showsRoutes from './routes/shows.js';
55import adminShowsRoutes from './routes/admin-shows.js';
56import adminEpkRoutes from './routes/admin-epk.js';
57import changelogRoutes from './routes/changelog.js';
58import ogRoutes from './routes/og.js';
59import apRoutes from './routes/activitypub.js';
60import { apWants, startDeliveryWorker, autoMigrateCircles, selfHealTimeline } from './services/ActivityPubService.js';
61
62// SESSION_SECRET: use the env var if set. Otherwise auto-generate a strong one
63// and persist it next to the database, so it stays stable across restarts and
64// updates. This lets Docker / bare-Node installs run with zero manual config.
65if (!process.env.SESSION_SECRET) {
66 const dataDir = path.dirname(process.env.DATABASE_PATH || './storage/database.sqlite');
67 const secretFile = path.join(dataDir, '.session-secret');
68 try { process.env.SESSION_SECRET = fs.readFileSync(secretFile, 'utf8').trim(); } catch { /* not yet generated */ }
69 if (!process.env.SESSION_SECRET) {
70 fs.mkdirSync(dataDir, { recursive: true });
71 process.env.SESSION_SECRET = crypto.randomBytes(32).toString('hex');
72 fs.writeFileSync(secretFile, process.env.SESSION_SECRET, { mode: 0o600 });
73 console.log(`🔑 Generated a SESSION_SECRET (stored in ${secretFile})`);
74 }
75}
76
77// A SESSION_SECRET that was explicitly set in the env must still be strong in prod.
78if (process.env.NODE_ENV === 'production' && process.env.SESSION_SECRET.length < 32) {
79 console.error('❌ FATAL: SESSION_SECRET is too weak for production (set a longer, random one in .env)');
80 process.exit(1);
81}
82
83const __dirname = path.dirname(fileURLToPath(import.meta.url));
84const PORT = process.env.PORT || 3000;
85// Interface to bind. Default 0.0.0.0 (needed for Docker port-forwarding). Behind a
86// reverse proxy on the same host, set HOST=127.0.0.1 so the app is NOT reachable
87// directly from the internet (only via the proxy) — see README/install docs.
88const HOST = process.env.HOST || '0.0.0.0';
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
162startDeliveryWorker(); // retry failed fediverse deliveries with backoff
163autoMigrateCircles(); // one-time: convert legacy circle_links -> AP auto-boost follows
164selfHealTimeline(); // once per SELFHEAL_VERSION bump: re-sync the fediverse cache (covers/edits) after a drastic update
165
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.
168ensurePrimarySite();
169
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' }));
188app.use('/media', express.static(process.env.MEDIA_PATH || './storage/media', {
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.
193 setHeaders: (res) => res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'),
194}));
195
196// (Removed) TWA / digital-asset-links — only needed for the APK/TWA variant.
197// Klonkt is PWA-only; assetlinks.json is no longer served.
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// ActivityPub: WebFinger + /ap/* (site-agnostic, resolves the site by slug).
217app.use(apRoutes);
218
219// Themed OG cards (/og/:slug.png) — resolve the site by slug themselves, so they
220// run before resolveSite and need no site context.
221app.use('/og', ogRoutes);
222
223app.use(resolveSite);
224app.use(loadAudioTracks);
225app.use(loadTheme);
226
227// ActivityPub content negotiation on the human URLs: an AP request (Accept:
228// application/activity+json) to a profile/post URL is redirected to its /ap/*
229// representation — same URL serves HTML to browsers, AP-JSON to servers (this is
230// how Mastodon resolves a pasted profile/post URL). Gated on apWants() so normal
231// browser requests pay nothing.
232app.use((req, res, next) => {
233 if (req.method !== 'GET' || !apWants(req)) return next();
234 const site = res.locals.site;
235 if (!site || !site.slug) return next();
236 const seg = req.path.replace(/^\/+|\/+$/g, '');
237 if (seg === '') return res.redirect(302, `/ap/users/${encodeURIComponent(site.slug)}`);
238 if (!seg.includes('/')) {
239 try {
240 const post = db.prepare(
241 "SELECT id FROM posts WHERE site_id = ? AND slug = ? AND status = 'published' AND (fan_only IS NULL OR fan_only = 0)"
242 ).get(site.id, seg);
243 if (post) return res.redirect(302, `/ap/notes/${post.id}`);
244 } catch { /* fall through to normal HTML handling */ }
245 }
246 return next();
247});
248
249// Lightweight CSRF defense: reject cross-origin state-mutating requests.
250// Same-origin forms + HTMX send a matching Origin; missing Origin is allowed
251// through (non-browser clients). sameSite:'lax' on the session cookie is the
252// second layer. (Does not apply to GET/HEAD/OPTIONS.)
253app.use((req, res, next) => {
254 if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
255 const origin = req.get('origin');
256 if (!origin) return next(); // no Origin → no browser CSRF vector
257 let originHost;
258 try { originHost = new URL(origin).host; } catch { return res.status(403).send('Ongeldige origin'); }
259 if (originHost !== req.get('host')) return res.status(403).send('Cross-origin request geweigerd');
260 next();
261});
262
263// Viewer accounts: may view everything (including Admin), change nothing. This is
264// the ONLY write gate — fail-closed, before all route handlers. Every state-mutating
265// method is rejected (the login POST sets the session after this guard, so it is
266// not affected). Instead of raw 403 text we render a clean page (or, for HTMX,
267// a swapped-in message).
268app.use((req, res, next) => {
269 const mutating = req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS';
270 if (mutating && isViewer(req.session?.user)) {
271 if (req.headers['hx-request'] === 'true') {
272 // htmx doesn't swap on 4xx; send 200 + retarget so the message appears in #pcms-main.
273 res.setHeader('HX-Retarget', '#pcms-main');
274 res.setHeader('HX-Reswap', 'innerHTML');
275 res.status(200);
276 } else {
277 res.status(403);
278 }
279 return renderPage(req, res, 'pages/viewer-blocked', {
280 pageTitle: 'Kijker-modus',
281 bodyClass: 'on-special',
282 });
283 }
284 next();
285});
286
287app.use('/auth', authRoutes);
288app.use('/account', accountRoutes);
289app.use('/notifications', notificationsRoutes);
290if (audioEnabled()) {
291 app.use('/admin/audio', adminAudioRoutes);
292 app.use('/admin/playlists', adminPlaylistsRoutes);
293}
294app.use('/admin/sites', adminSitesRoutes);
295app.use('/admin/users', adminUsersRoutes);
296app.use('/admin/settings', adminSettingsRoutes);
297app.use('/admin/seo', adminSeoRoutes);
298app.use('/admin/updates', adminUpdatesRoutes);
299app.use('/admin/patreon', adminPatreonRoutes);
300app.use('/admin/stats', adminStatsRoutes);
301app.use('/admin/newsletter', adminNewsletterRoutes);
302app.use('/admin/shows', adminShowsRoutes);
303app.use('/admin/epk', adminEpkRoutes);
304app.use('/admin', adminRoutes);
305if (audioEnabled()) app.use('/audio', audioRoutes);
306app.use('/search', searchRoutes);
307app.use('/tag', tagsRoutes);
308app.use('/type', typesRoutes);
309app.use('/users', usersRoutes);
310// Feed/sitemap routes are mounted at root because they're at well-known paths
311app.use('/', feedRoutes);
312app.use('/', circleRoutes); // /cirkel-feed (solo: next() -> postsRoutes)
313app.use('/', epkRoutes); // /pers perskit (premium; niet-premium: next() -> 404)
314app.use('/', newsletterRoutes); // /nieuwsbrief in/uitschrijven (premium; niet-premium: next())
315if (audioEnabled()) app.use('/', downloadRoutes); // /downloads + /download/:id (audio; lite: uit)
316app.use('/', linkbioRoutes); // /links link-in-bio + klikstats (premium)
317if (audioEnabled()) app.use('/', embedRoutes); // /embed inbedbare audiospeler (audio; lite: uit)
318app.use('/', showsRoutes); // /shows agenda + notify-me (premium)
319app.use('/', changelogRoutes); // /changelog publieke release-/wijzigingen-pagina
320app.use('/', langRoutes); // /lang/:code — interface-taal kiezen (vóór de catch-all)
321app.use('/', postsRoutes);
322
323app.get('/manifest.webmanifest', (req, res) => {
324 const site = res.locals.site;
325
326 // PWA scope: confines installed apps to ONE site. If a user is in the
327 // bedrijf1 PWA and clicks a link to /sites/bedrijf2/..., the browser will
328 // open it in a regular tab (out-of-scope) instead of within the PWA.
329 // Same applies to APK packaging — the WebView is locked to this scope.
330 //
331 // For path-mounted sites: scope = /sites/<slug>/
332 // For root/subdomain sites: scope = /
333 const base = res.locals.siteUrlBase || ''; // '' or '/sites/<slug>'
334 const scope = (base || '') + '/';
335 const startUrl = (base || '') + '/?source=pwa';
336
337 // A stable identity per site so installs don't collide (Chromium uses `id`).
338 // NB: changing the id orphans existing PWA installs (no migration carries an
339 // install across an id change) — anyone who already installed the site as a
340 // PWA will need to reinstall once. Data stays server-side, so nothing is lost.
341 const idBase = site?.slug ? `klonkt-${site.slug}` : 'klonkt';
342
343 res.set('Cache-Control', 'no-cache');
344 res.json({
345 id: idBase,
346 name: site?.title || 'Klonkt',
347 short_name: (site?.title || 'Klonkt').slice(0, 12),
348 description: site?.description || site?.tagline || '',
349 scope,
350 start_url: startUrl,
351 display: 'standalone',
352 display_override: ['standalone', 'minimal-ui'],
353 orientation: 'any',
354 background_color: '#1a1a17',
355 theme_color: site?.accent || '#e8b04b',
356 lang: site?.language || 'nl',
357 icons: [
358 { src: '/favicon.svg', sizes: 'any', type: 'image/svg+xml' },
359 { src: '/favicon.ico', sizes: '64x64', type: 'image/x-icon' },
360 ],
361 // Hint to capable browsers: capture all in-scope links inside the PWA
362 capture_links: 'existing-client-navigate',
363 });
364});
365
366// Favicon — served as SVG so it picks up the site's accent color dynamically.
367// Browsers also request /favicon.ico by convention; we serve the same SVG
368// content there with a forgiving content-type since modern browsers accept it.
369function _renderFavicon(res, accent) {
370 const safeAccent = /^#[0-9a-fA-F]{3,8}$/.test(accent) ? accent : '#e8b04b';
371 // Site mark: rounded square in the site accent + bold white 'K' (Klonkt)
372 const svg = `<?xml version="1.0" encoding="UTF-8"?>
373<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
374 <rect width="64" height="64" rx="14" fill="${safeAccent}"/>
375 <text x="50%" y="50%" dy="0.35em" text-anchor="middle"
376 font-family="Arial, Helvetica, sans-serif"
377 font-size="42" font-weight="800" fill="#fff">K</text>
378</svg>`;
379 res.set('Content-Type', 'image/svg+xml');
380 res.set('Cache-Control', 'public, max-age=86400');
381 res.send(svg);
382}
383
384app.get('/favicon.svg', (req, res) => {
385 _renderFavicon(res, res.locals.site?.accent);
386});
387app.get('/favicon.ico', (req, res) => {
388 // Browsers requesting .ico will accept SVG content; chrome/firefox both fine.
389 // Keeping the route prevents 404 spam in the console.
390 _renderFavicon(res, res.locals.site?.accent);
391});
392
393app.get('/sw.js', (req, res) => {
394 res.set('Content-Type', 'application/javascript');
395 res.set('Cache-Control', 'no-cache');
396 res.send(`
397const CACHE_VERSION = 'pcms-v11-' + new Date().toISOString().split('T')[0];
398self.addEventListener('install', e => {
399 e.waitUntil(caches.open(CACHE_VERSION).then(c => c.addAll(['/'])));
400 self.skipWaiting();
401});
402self.addEventListener('activate', e => {
403 e.waitUntil(caches.keys().then(keys => Promise.all(
404 keys.filter(k => k !== CACHE_VERSION).map(k => caches.delete(k))
405 )));
406 self.clients.claim();
407});
408// ONLY intercept navigations (HTML pages) for an offline fallback.
409// Do NOT touch images, CSS, JS or /media — let the browser handle those natively.
410// Otherwise a failed network fetch could fall back to an empty cache match
411// (undefined) and "break" an image on a normal refresh (hard reload bypasses
412// the SW, which is why that case worked fine).
413self.addEventListener('fetch', e => {
414 if (e.request.method !== 'GET') return;
415 if (e.request.mode !== 'navigate') return; // page loads only
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 console.log('');
450 console.log('🪶 Klonkt Beta');
451 console.log(` http://localhost:${PORT}`);
452 console.log('');
453 console.log(` ✓ Security: Helmet, CSP, secure sessions`);
454 console.log(` ✓ Privacy: Self-hosted fonts, no third-party requests`);
455 console.log(` ✓ Layout: v9 editorial feel (top nav, profile header)`);
456 console.log(` ✓ Auth: wachtwoord (beheer) + Google (luisteraars) / logout`);
457 console.log(` ✓ Posts: create / edit / view / archive`);
458 console.log('');
459 console.log(` Mode: ${isDev ? 'development' : 'PRODUCTION'}`);
460 console.log('');
461});
462
463export default app;
Note: See TracBrowser for help on using the repository browser.