source: Klonkt/src/server.js@ a301d7a

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

i18n: translate Dutch code comments to English across src/

Comments in routes/services/views/config/middleware/assets translated to
English for the public repo. A few dev-facing throw/console message strings
were Englished too. No user-facing UI strings or i18n dictionary values changed
(src/services/i18n.js untouched). Logic unchanged.

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

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