source: Klonkt/src/server.js@ 8afbdd6

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

feat: viewer role + artists directory + Klonkt Hub Beta rebrand

Viewer role (replaces the separate view-mode/readonly toggle):

  • 'kijker' is now a real role (VALID_ROLES) selectable in Admin. May view EVERYTHING including Admin, but cannot modify anything.
  • isViewer(user) (= role kijker or legacy readonly flag) is the source; requireGod/requireSiteManager(BySlug) let a viewer through (viewing), the global guard 403s every write. Existing readonly accounts are migrated on each role change (readonly=0).
  • Write leaks via GET patched: /prutter/new (INSERT) blocks for viewers, /prutter/:id skips markAsRead (UPDATE); WS upgrade rejects viewers (the HTTP guard doesn't cover WebSockets).
  • Clean "Viewer mode" page (viewer-blocked) instead of raw 403 text; styled sticky banner; account page shows read-only UI instead of an upload button that silently 403s. canMutate hides write buttons.

Scalability (>50 artists):

  • Hub home shows max 24 (most active first) + "All N artists ->".
  • New searchable, paginated /artiesten directory (hub only).
  • 'user' + 'artiesten' reserved as slugs.

Rebrand PrutFolio v1 -> Klonkt Hub Beta (footer, PWA manifest, account/
admin texts, default page title, startup, README; internal package +
PWA id 'prutfolio' remain for stability).

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

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