source: Klonkt/src/server.js@ c88783e

main
Last change on this file since c88783e was 353c39c, checked in by Robin Genis <roboburr@…>, 4 months ago

audio: allow blob: in CSP media-src (fix Step-1 no-play/auto-skip loop)

Step 1 (blob playback) shipped without blob: in the CSP media-src directive
("self" https:). The browser silently blocked <audio>.src = blob:... so the
player fired error on every track and auto-skipped through the whole queue
without playing anything. self/https: do NOT imply blob:.

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

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