source: Klonkt/src/server.js@ e951b7c

main
Last change on this file since e951b7c was 5a6a457, checked in by Robin Genis <roboburr@โ€ฆ>, 3 months ago

feat(fediverse): federate on save+scheduler, delivery retry-queue, music as listen-link

#1 Posts now federate to followers not only on create, but also when a draft/

scheduled post becomes published (editor save) and when the Scheduler flips a
scheduled post live โ€” previously those silently didn't reach followers.

#2 Delivery retry-queue (ap_delivery): a failed delivery (down server/timeout) is

queued and retried with backoff (1/5/15/60/180/360 min, 6 tries) by a worker,
instead of fire-and-forget. Signing key re-derived from the slug, never stored.

#3 Music posts: audio shortcodes federate as a '๐ŸŽต listen on the site' link to the

post (protected player) instead of the raw mp3 โ€” keeps Klonkt's audio friction
intact (no downloadable file handed to Mastodon).

Co-Authored-By: Claude <noreply@โ€ฆ>

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