source: Klonkt/src/server.js@ ab544fd

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

auth: read-only view accounts (view everything, modify nothing)

New users.readonly column + readonly in the session. Global guard in server.js
blocks every state-modifying method (POST/PUT/PATCH/DELETE) for read-only
accounts -> no comments, saves, settings, nothing. GET remains free, so they
can view everything (including admin panels). Sticky "read-only demo" banner in
the shell when such an account is logged in.

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

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