source: Klonkt/src/server.js@ 075185a

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

fix(activitypub): content-negotiation on canonical URLs

An AP request (Accept: application/activity+json) to a profile or post URL now
302-redirects to its /ap/* representation, so the same URL serves HTML to
browsers and AP-JSON to servers. Fixes Mastodon failing to resolve a pasted
profile/post URL (it received text/html). Gated on apWants() — no cost for
normal browser traffic.

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

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