source: Klonkt/src/server.js@ 3e86f1c

main
Last change on this file since 3e86f1c was 4c9f29a, checked in by roboburr <roboburr@…>, 3 months ago

feat: on-brand media embeds via the real player APIs

Replaces bare platform iframes with on-brand cards, powered by the
official JS APIs so play/pause/progress are in our own hands:

  • YouTube (IFrame Player API) + SoundCloud (Widget API): fully custom controls, native chrome hidden.
  • Spotify (iFrame API): our frame around it + controls (their player UI remains; restyling not possible without Premium+OAuth).
  • Shared PlaybackRegistry: mutual exclusion -- only 1 thing plays at a time (incl. the site audio player). Replaces the focus/blur heuristic with real play events (blur stays as fallback for iframe-only embeds).
  • Progressive enhancement: if an ad-blocker blocks the platform API, falls back seamlessly to the bare platform iframe (autoplay). The resting-state card is our brand for everyone.

AudioEmbedService now renders a placeholder div (data-embed-*) for YT/SC/
Spotify instead of an iframe; embed-player.js builds the card client-side.
CSP scriptSrc extended with the player API hosts.

Adversarial review (workflow) -> 6 bugs fixed: HTMX swap leak (poll timers/
adapters -> MutationObserver teardown + adapter.destroy()), javascript: URL XSS
(scheme guard in detectProvider + safeHref client-side), Spotify ended
misdetection (no more reset-to-0), ytId/server regex on exact 11, blur scope
limited to .folio-embed.

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

  • Property mode set to 100644
File size: 15.9 KB
Line 
1/**
2 * Klonkt Hub Beta — server bootstrap
3 *
4 * Persoonlijk multi-site platform forked van PrutCMS v9 (PHP, file-based).
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 { SqliteSessionStore } from './services/SqliteSessionStore.js';
19import PrutterService from './services/PrutterService.js';
20import { WebSocketServer } from 'ws';
21
22import { resolveSite, loadAudioTracks, loadTheme } from './middleware/site.js';
23import { isViewer } from './middleware/auth.js';
24import { renderPage } from './middleware/render.js';
25import authRoutes from './routes/auth.js';
26import accountRoutes from './routes/account.js';
27import adminRoutes from './routes/admin.js';
28import adminAudioRoutes from './routes/admin-audio.js';
29import adminPlaylistsRoutes from './routes/admin-playlists.js';
30import adminSitesRoutes from './routes/admin-sites.js';
31import adminUsersRoutes from './routes/admin-users.js';
32import adminCommentsRoutes from './routes/admin-comments.js';
33import adminSettingsRoutes from './routes/admin-settings.js';
34import prutterRoutes from './routes/prutter.js';
35import audioRoutes from './routes/audio.js';
36import searchRoutes from './routes/search.js';
37import commentsRoutes from './routes/comments.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';
45
46if (!process.env.SESSION_SECRET) {
47 console.error('❌ FATAL: SESSION_SECRET is required');
48 process.exit(1);
49}
50
51if (process.env.NODE_ENV === 'production' && process.env.SESSION_SECRET.length < 32) {
52 console.error('❌ FATAL: SESSION_SECRET too weak for production');
53 process.exit(1);
54}
55
56const __dirname = path.dirname(fileURLToPath(import.meta.url));
57const PORT = process.env.PORT || 3000;
58const isDev = process.env.NODE_ENV !== 'production';
59
60const app = express();
61const server = http.createServer(app);
62
63app.use(helmet({
64 contentSecurityPolicy: {
65 directives: {
66 defaultSrc: ["'self'"],
67 scriptSrc: [
68 "'self'",
69 "'unsafe-inline'",
70 // Eigen custom-embeds (embed-player.js) laden de OFFICIELE player-API's
71 // van deze hosts. Zonder deze whitelist blokkeert de CSP ze stil (alleen
72 // een console-fout) en faalt de embed-speler.
73 "https://www.youtube.com", // YouTube IFrame Player API (+ www-widgetapi.js)
74 "https://s.ytimg.com", // YouTube player-assets
75 "https://w.soundcloud.com", // SoundCloud Widget API (api.js)
76 "https://open.spotify.com", // Spotify iFrame API
77 ],
78 // Helmet's default zet script-src-attr op 'none', wat ALLE inline event-
79 // handlers (onchange/onclick/onsubmit) blokkeert — daardoor deed o.a. de
80 // avatar-upload (<input onchange="this.form.submit()">) en de rol-dropdown
81 // niets. We staan inline handlers expliciet toe, consistent met de al
82 // toegestane inline <script> hierboven.
83 scriptSrcAttr: ["'unsafe-inline'"],
84 styleSrc: ["'self'", "'unsafe-inline'"],
85 imgSrc: ["'self'", "data:", "https:"],
86 connectSrc: ["'self'", "wss:", "ws:"],
87 // blob: is required for the audio player — it fetch()es track bytes and
88 // plays from a blob: object URL (Spotify-style). Without blob: here the
89 // CSP silently blocks <audio>.src = blob:… → the player fires 'error' and
90 // auto-skips every track. 'self'/https: do NOT imply blob:.
91 mediaSrc: ["'self'", "https:", "blob:"],
92 fontSrc: ["'self'"],
93 frameSrc: [
94 "'self'",
95 "https://open.spotify.com",
96 "https://w.soundcloud.com",
97 "https://bandcamp.com",
98 "https://embed.music.apple.com",
99 "https://www.youtube-nocookie.com",
100 "https://www.youtube.com", // YouTube IFrame API maakt soms een www.youtube.com-iframe
101 "https://player.vimeo.com",
102 ],
103 },
104 },
105 hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
106 frameguard: { action: 'sameorigin' },
107 referrerPolicy: { policy: 'no-referrer-when-downgrade' },
108}));
109
110app.set('view engine', 'ejs');
111app.set('views', path.join(__dirname, 'views'));
112
113app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));
114app.use(bodyParser.json({ limit: '10mb' }));
115
116// Trust one upstream proxy in production. NPM (or Caddy / nginx) terminates
117// HTTPS and forwards to us over plain HTTP, setting X-Forwarded-Proto: https.
118// Without this, Express sees req.protocol === 'http' and won't issue secure
119// cookies — sessions never persist past the redirect after login.
120if (!isDev) app.set('trust proxy', 1);
121
122// Session middleware extracted into a variable so the WebSocket upgrade
123// handler can reuse it (it needs req.session to authenticate sockets).
124const sessionMiddleware = session({
125 store: new SqliteSessionStore(),
126 secret: process.env.SESSION_SECRET,
127 resave: false,
128 saveUninitialized: false,
129 name: 'pcms.sid',
130 cookie: {
131 httpOnly: true,
132 secure: !isDev,
133 sameSite: 'lax',
134 maxAge: 30 * 24 * 60 * 60 * 1000,
135 },
136});
137app.use(sessionMiddleware);
138
139app.use('/assets', express.static(path.join(__dirname, 'assets'), { maxAge: isDev ? 0 : '1y' }));
140app.use('/media', express.static(process.env.MEDIA_PATH || './storage/media'));
141
142// (Verwijderd) TWA / digital-asset-links — alleen nodig voor de APK/TWA-variant.
143// Klonkt is PWA-only; geen assetlinks.json meer.
144
145initializeDatabase();
146
147// Bundle HTMX: copy from node_modules into our own assets dir so we can serve
148// it locally (no third-party CDN). Idempotent — only copies if size differs.
149(function ensureLocalHtmx() {
150 const src = path.join(__dirname, '..', 'node_modules', 'htmx.org', 'dist', 'htmx.min.js');
151 const dest = path.join(__dirname, 'assets', 'js', 'htmx.min.js');
152 try {
153 const srcStat = fs.statSync(src);
154 const destStat = fs.existsSync(dest) ? fs.statSync(dest) : null;
155 if (!destStat || destStat.size !== srcStat.size) {
156 fs.copyFileSync(src, dest);
157 console.log(`📦 HTMX bundled locally: ${srcStat.size} bytes`);
158 }
159 } catch (e) {
160 console.warn('⚠️ Could not bundle HTMX:', e.message, '— run `npm install`');
161 }
162})();
163
164// Singleton PrutterService — routes get it via req.app.locals.prutter.
165const prutter = new PrutterService(db);
166app.locals.prutter = prutter;
167
168app.use(resolveSite);
169app.use(loadAudioTracks);
170app.use(loadTheme);
171
172// Lichtgewicht CSRF-defense: weiger cross-origin state-wijzigende requests.
173// Same-origin forms + HTMX sturen een matchende Origin; ontbreekt Origin dan
174// laten we door (non-browser clients). sameSite:'lax' op de sessiecookie is de
175// tweede laag. (Geldt niet voor GET/HEAD/OPTIONS.)
176app.use((req, res, next) => {
177 if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
178 const origin = req.get('origin');
179 if (!origin) return next(); // geen Origin -> geen browser-CSRF-vector
180 let originHost;
181 try { originHost = new URL(origin).host; } catch { return res.status(403).send('Ongeldige origin'); }
182 if (originHost !== req.get('host')) return res.status(403).send('Cross-origin request geweigerd');
183 next();
184});
185
186// Kijker-accounts: alles bekijken mag (incl. Beheer), niets wijzigen. Dit is de
187// ENIGE schrijf-blokkade — fail-closed, vóór alle route-handlers. Elke state-
188// wijzigende methode wordt geweigerd (de login-POST zet de sessie pas ná deze
189// guard, dus die valt er niet onder). I.p.v. rauwe 403-tekst tonen we een nette
190// pagina (of, bij HTMX, een ingeswapte melding).
191app.use((req, res, next) => {
192 const mutating = req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS';
193 if (mutating && isViewer(req.session?.user)) {
194 if (req.headers['hx-request'] === 'true') {
195 // htmx swapt niet op 4xx; stuur 200 + retarget zodat de melding in #pcms-main verschijnt.
196 res.setHeader('HX-Retarget', '#pcms-main');
197 res.setHeader('HX-Reswap', 'innerHTML');
198 res.status(200);
199 } else {
200 res.status(403);
201 }
202 return renderPage(req, res, 'pages/viewer-blocked', {
203 pageTitle: 'Kijker-modus',
204 bodyClass: 'on-special',
205 });
206 }
207 next();
208});
209
210app.use('/auth', authRoutes);
211app.use('/account', accountRoutes);
212app.use('/admin/audio', adminAudioRoutes);
213app.use('/admin/playlists', adminPlaylistsRoutes);
214app.use('/admin/sites', adminSitesRoutes);
215app.use('/admin/users', adminUsersRoutes);
216app.use('/admin/comments', adminCommentsRoutes);
217app.use('/admin/settings', adminSettingsRoutes);
218app.use('/admin', adminRoutes);
219app.use('/prutter', prutterRoutes);
220app.use('/audio', audioRoutes);
221app.use('/search', searchRoutes);
222app.use('/comments', commentsRoutes);
223app.use('/tag', tagsRoutes);
224app.use('/type', typesRoutes);
225app.use('/users', usersRoutes);
226// Feed/sitemap routes are mounted at root because they're at well-known paths
227app.use('/', feedRoutes);
228app.use('/leden', artistsRoutes); // doorzoekbare leden-directory (alleen hub; solo: next())
229app.get('/artiesten', (req, res) => res.redirect(301, req.originalUrl.replace(/^\/artiesten/, '/leden'))); // oude URL -> /leden
230app.use('/', hubRoutes); // hub-overview op '/' (solo: next() -> postsRoutes)
231app.use('/', postsRoutes);
232
233app.get('/manifest.webmanifest', (req, res) => {
234 const site = res.locals.site;
235
236 // PWA scope: confines installed apps to ONE site. If a user is in the
237 // bedrijf1 PWA and clicks a link to /sites/bedrijf2/..., the browser will
238 // open it in a regular tab (out-of-scope) instead of within the PWA.
239 // Same applies to APK packaging — the WebView is locked to this scope.
240 //
241 // For path-mounted sites: scope = /sites/<slug>/
242 // For root/subdomain sites: scope = /
243 const base = res.locals.siteUrlBase || ''; // '' or '/sites/<slug>'
244 const scope = (base || '') + '/';
245 const startUrl = (base || '') + '/?source=pwa';
246
247 // A stable identity per site so installs don't collide (Chromium uses `id`)
248 const idBase = site?.slug ? `prutfolio-${site.slug}` : 'prutfolio';
249
250 res.set('Cache-Control', 'no-cache');
251 res.json({
252 id: idBase,
253 name: site?.title || 'Klonkt Hub Beta',
254 short_name: (site?.title || 'Klonkt').slice(0, 12),
255 description: site?.description || site?.tagline || '',
256 scope,
257 start_url: startUrl,
258 display: 'standalone',
259 display_override: ['standalone', 'minimal-ui'],
260 orientation: 'any',
261 background_color: '#1a1a17',
262 theme_color: site?.accent || '#c2410c',
263 lang: site?.language || 'nl',
264 icons: [
265 { src: '/favicon.svg', sizes: 'any', type: 'image/svg+xml' },
266 { src: '/favicon.ico', sizes: '64x64', type: 'image/x-icon' },
267 ],
268 // Hint to capable browsers: capture all in-scope links inside the PWA
269 capture_links: 'existing-client-navigate',
270 });
271});
272
273// Favicon — served as SVG so it picks up the site's accent color dynamically.
274// Browsers also request /favicon.ico by convention; we serve the same SVG
275// content there with a forgiving content-type since modern browsers accept it.
276function _renderFavicon(res, accent) {
277 const safeAccent = /^#[0-9a-fA-F]{3,8}$/.test(accent) ? accent : '#c2410c';
278 // Site mark: rounded square in the site accent + bold white 'K' (Klonkt)
279 const svg = `<?xml version="1.0" encoding="UTF-8"?>
280<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
281 <rect width="64" height="64" rx="14" fill="${safeAccent}"/>
282 <text x="50%" y="50%" dy="0.35em" text-anchor="middle"
283 font-family="Arial, Helvetica, sans-serif"
284 font-size="42" font-weight="800" fill="#fff">K</text>
285</svg>`;
286 res.set('Content-Type', 'image/svg+xml');
287 res.set('Cache-Control', 'public, max-age=86400');
288 res.send(svg);
289}
290
291app.get('/favicon.svg', (req, res) => {
292 _renderFavicon(res, res.locals.site?.accent);
293});
294app.get('/favicon.ico', (req, res) => {
295 // Browsers requesting .ico will accept SVG content; chrome/firefox both fine.
296 // Keeping the route prevents 404 spam in the console.
297 _renderFavicon(res, res.locals.site?.accent);
298});
299
300app.get('/sw.js', (req, res) => {
301 res.set('Content-Type', 'application/javascript');
302 res.set('Cache-Control', 'no-cache');
303 res.send(`
304const CACHE_VERSION = 'pcms-v10-' + new Date().toISOString().split('T')[0];
305self.addEventListener('install', e => {
306 e.waitUntil(caches.open(CACHE_VERSION).then(c => c.addAll(['/'])));
307 self.skipWaiting();
308});
309self.addEventListener('activate', e => {
310 e.waitUntil(caches.keys().then(keys => Promise.all(
311 keys.filter(k => k !== CACHE_VERSION).map(k => caches.delete(k))
312 )));
313 self.clients.claim();
314});
315self.addEventListener('fetch', e => {
316 if (e.request.method !== 'GET') return;
317 e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
318});
319 `);
320});
321
322process.on('unhandledRejection', (reason) => {
323 console.error('⚠️ Unhandled Rejection:', reason);
324});
325
326app.use((err, req, res, next) => {
327 console.error('❌ Error:', err);
328 res.status(err.status || 500).send(
329 isDev ? `<pre>${err.stack || err.message}</pre>` : 'Internal Server Error'
330 );
331});
332
333app.use((req, res) => {
334 res.status(404).send(`
335 <div style="font-family:system-ui;max-width:500px;margin:4rem auto;text-align:center;padding:2rem;">
336 <h1 style="font-size:5rem;margin:0;color:#c33;">404</h1>
337 <p>Not found</p>
338 <a href="/" style="color:#c2410c;">← Home</a>
339 </div>
340 `);
341});
342
343// ==================== WebSocket: Prutter real-time ====================
344// Authenticate via the existing session cookie. We reuse sessionMiddleware
345// during the HTTP upgrade so req.session is populated; if no user, abort.
346const wss = new WebSocketServer({ noServer: true });
347
348server.on('upgrade', (req, socket, head) => {
349 if (req.url !== '/ws/prutter') {
350 socket.destroy();
351 return;
352 }
353 // Run session middleware on the upgrade request.
354 // (Express's middleware accepts (req, res, next); we pass a stub res.)
355 const stubRes = { setHeader: () => {}, getHeader: () => undefined, on: () => {}, end: () => {} };
356 sessionMiddleware(req, stubRes, () => {
357 if (!req.session?.user) {
358 socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
359 socket.destroy();
360 return;
361 }
362 // Kijker-accounts zijn alleen-lezen: weiger de WS-upgrade. De HTTP-guard
363 // dekt geen WS, dus dit is de plek om schrijven via een (toekomstige)
364 // message-handler te voorkomen.
365 if (isViewer(req.session.user)) {
366 socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
367 socket.destroy();
368 return;
369 }
370 wss.handleUpgrade(req, socket, head, (ws) => {
371 ws.userId = req.session.user.id;
372 wss.emit('connection', ws, req);
373 });
374 });
375});
376
377wss.on('connection', (ws) => {
378 prutter.addConnection(ws.userId, ws);
379 ws.on('close', () => prutter.removeConnection(ws.userId, ws));
380 ws.on('error', () => prutter.removeConnection(ws.userId, ws));
381 // Optional: ping every 30s to keep connections alive through proxies
382 ws.isAlive = true;
383 ws.on('pong', () => { ws.isAlive = true; });
384});
385const wsPing = setInterval(() => {
386 for (const ws of wss.clients) {
387 if (ws.isAlive === false) { ws.terminate(); continue; }
388 ws.isAlive = false;
389 try { ws.ping(); } catch {}
390 }
391}, 30000);
392if (wsPing.unref) wsPing.unref();
393
394server.listen(PORT, () => {
395 console.log('');
396 console.log('🪶 Klonkt Hub Beta');
397 console.log(` http://localhost:${PORT}`);
398 console.log('');
399 console.log(` ✓ Security: Helmet, CSP, secure sessions`);
400 console.log(` ✓ Privacy: Self-hosted fonts, no third-party requests`);
401 console.log(` ✓ Layout: v9 editorial feel (top nav, profile header)`);
402 console.log(` ✓ Auth: wachtwoord (beheer) + Google (luisteraars) / logout`);
403 console.log(` ✓ Posts: create / edit / view / archive`);
404 console.log(` ✓ Realtime: WebSocket server ready (Prutter)`);
405 console.log('');
406 console.log(` Mode: ${isDev ? 'development' : 'PRODUCTION'}`);
407 console.log('');
408});
409
410export default app;
Note: See TracBrowser for help on using the repository browser.