source: Klonkt/src/server.js@ 743bb81

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

hub: company overview on / (latest posts from all users) + /user/ routing

In hub mode '/' is no longer the primary PrutFolio but an overview:
hero (company site title) + "Latest posts" across ALL sites + "PrutFolio's"
list. Solo keeps '/' as the single PrutFolio.

  • routes/hub.js: GET / -> hub overview in hub, otherwise next() (solo -> posts.js).
  • views/pages/hub-home.ejs: overview layout (cards + user list).
  • middleware/site.js: PrutFolio's now accessible via /user/:slug (canonical) and /sites/:slug (legacy); siteUrlBase follows the used prefix.
  • server.js: hubRoutes mounted before postsRoutes.

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

  • Property mode set to 100644
File size: 13.3 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 adminSettingsRoutes from './routes/admin-settings.js';
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';
40import hubRoutes from './routes/hub.js';
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:"],
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:"],
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
122// (Verwijderd) TWA / digital-asset-links — alleen nodig voor de APK/TWA-variant.
123// Klonkt is PWA-only; geen assetlinks.json meer.
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
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
166app.use('/auth', authRoutes);
167app.use('/account', accountRoutes);
168app.use('/admin/audio', adminAudioRoutes);
169app.use('/admin/playlists', adminPlaylistsRoutes);
170app.use('/admin/sites', adminSitesRoutes);
171app.use('/admin/users', adminUsersRoutes);
172app.use('/admin/comments', adminCommentsRoutes);
173app.use('/admin/settings', adminSettingsRoutes);
174app.use('/admin', adminRoutes);
175app.use('/prutter', prutterRoutes);
176app.use('/audio', audioRoutes);
177app.use('/search', searchRoutes);
178app.use('/comments', commentsRoutes);
179app.use('/tag', tagsRoutes);
180app.use('/type', typesRoutes);
181app.use('/users', usersRoutes);
182// Feed/sitemap routes are mounted at root because they're at well-known paths
183app.use('/', feedRoutes);
184app.use('/', hubRoutes); // hub-overview op '/' (solo: next() -> postsRoutes)
185app.use('/', postsRoutes);
186
187app.get('/manifest.webmanifest', (req, res) => {
188 const site = res.locals.site;
189
190 // PWA scope: confines installed apps to ONE site. If a user is in the
191 // bedrijf1 PWA and clicks a link to /sites/bedrijf2/..., the browser will
192 // open it in a regular tab (out-of-scope) instead of within the PWA.
193 // Same applies to APK packaging — the WebView is locked to this scope.
194 //
195 // For path-mounted sites: scope = /sites/<slug>/
196 // For root/subdomain sites: scope = /
197 const base = res.locals.siteUrlBase || ''; // '' or '/sites/<slug>'
198 const scope = (base || '') + '/';
199 const startUrl = (base || '') + '/?source=pwa';
200
201 // A stable identity per site so installs don't collide (Chromium uses `id`)
202 const idBase = site?.slug ? `prutfolio-${site.slug}` : 'prutfolio';
203
204 res.set('Cache-Control', 'no-cache');
205 res.json({
206 id: idBase,
207 name: site?.title || 'PrutFolio',
208 short_name: (site?.title || 'PrutFolio').slice(0, 12),
209 description: site?.description || site?.tagline || '',
210 scope,
211 start_url: startUrl,
212 display: 'standalone',
213 display_override: ['standalone', 'minimal-ui'],
214 orientation: 'any',
215 background_color: '#1a1a17',
216 theme_color: site?.accent || '#c2410c',
217 lang: site?.language || 'nl',
218 icons: [
219 { src: '/favicon.svg', sizes: 'any', type: 'image/svg+xml' },
220 { src: '/favicon.ico', sizes: '64x64', type: 'image/x-icon' },
221 ],
222 // Hint to capable browsers: capture all in-scope links inside the PWA
223 capture_links: 'existing-client-navigate',
224 });
225});
226
227// Favicon — served as SVG so it picks up the site's accent color dynamically.
228// Browsers also request /favicon.ico by convention; we serve the same SVG
229// content there with a forgiving content-type since modern browsers accept it.
230function _renderFavicon(res, accent) {
231 const safeAccent = /^#[0-9a-fA-F]{3,8}$/.test(accent) ? accent : '#c2410c';
232 // Site mark: rounded square in the site accent + bold white 'SF'
233 const svg = `<?xml version="1.0" encoding="UTF-8"?>
234<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
235 <rect width="64" height="64" rx="14" fill="${safeAccent}"/>
236 <text x="50%" y="50%" dy="0.36em" text-anchor="middle"
237 font-family="Arial, Helvetica, sans-serif"
238 font-size="30" font-weight="800" letter-spacing="-1" fill="#fff">SF</text>
239</svg>`;
240 res.set('Content-Type', 'image/svg+xml');
241 res.set('Cache-Control', 'public, max-age=86400');
242 res.send(svg);
243}
244
245app.get('/favicon.svg', (req, res) => {
246 _renderFavicon(res, res.locals.site?.accent);
247});
248app.get('/favicon.ico', (req, res) => {
249 // Browsers requesting .ico will accept SVG content; chrome/firefox both fine.
250 // Keeping the route prevents 404 spam in the console.
251 _renderFavicon(res, res.locals.site?.accent);
252});
253
254app.get('/sw.js', (req, res) => {
255 res.set('Content-Type', 'application/javascript');
256 res.set('Cache-Control', 'no-cache');
257 res.send(`
258const CACHE_VERSION = 'pcms-v10-' + new Date().toISOString().split('T')[0];
259self.addEventListener('install', e => {
260 e.waitUntil(caches.open(CACHE_VERSION).then(c => c.addAll(['/'])));
261 self.skipWaiting();
262});
263self.addEventListener('activate', e => {
264 e.waitUntil(caches.keys().then(keys => Promise.all(
265 keys.filter(k => k !== CACHE_VERSION).map(k => caches.delete(k))
266 )));
267 self.clients.claim();
268});
269self.addEventListener('fetch', e => {
270 if (e.request.method !== 'GET') return;
271 e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
272});
273 `);
274});
275
276process.on('unhandledRejection', (reason) => {
277 console.error('⚠️ Unhandled Rejection:', reason);
278});
279
280app.use((err, req, res, next) => {
281 console.error('❌ Error:', err);
282 res.status(err.status || 500).send(
283 isDev ? `<pre>${err.stack || err.message}</pre>` : 'Internal Server Error'
284 );
285});
286
287app.use((req, res) => {
288 res.status(404).send(`
289 <div style="font-family:system-ui;max-width:500px;margin:4rem auto;text-align:center;padding:2rem;">
290 <h1 style="font-size:5rem;margin:0;color:#c33;">404</h1>
291 <p>Not found</p>
292 <a href="/" style="color:#c2410c;">← Home</a>
293 </div>
294 `);
295});
296
297// ==================== WebSocket: Prutter real-time ====================
298// Authenticate via the existing session cookie. We reuse sessionMiddleware
299// during the HTTP upgrade so req.session is populated; if no user, abort.
300const wss = new WebSocketServer({ noServer: true });
301
302server.on('upgrade', (req, socket, head) => {
303 if (req.url !== '/ws/prutter') {
304 socket.destroy();
305 return;
306 }
307 // Run session middleware on the upgrade request.
308 // (Express's middleware accepts (req, res, next); we pass a stub res.)
309 const stubRes = { setHeader: () => {}, getHeader: () => undefined, on: () => {}, end: () => {} };
310 sessionMiddleware(req, stubRes, () => {
311 if (!req.session?.user) {
312 socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
313 socket.destroy();
314 return;
315 }
316 wss.handleUpgrade(req, socket, head, (ws) => {
317 ws.userId = req.session.user.id;
318 wss.emit('connection', ws, req);
319 });
320 });
321});
322
323wss.on('connection', (ws) => {
324 prutter.addConnection(ws.userId, ws);
325 ws.on('close', () => prutter.removeConnection(ws.userId, ws));
326 ws.on('error', () => prutter.removeConnection(ws.userId, ws));
327 // Optional: ping every 30s to keep connections alive through proxies
328 ws.isAlive = true;
329 ws.on('pong', () => { ws.isAlive = true; });
330});
331const wsPing = setInterval(() => {
332 for (const ws of wss.clients) {
333 if (ws.isAlive === false) { ws.terminate(); continue; }
334 ws.isAlive = false;
335 try { ws.ping(); } catch {}
336 }
337}, 30000);
338if (wsPing.unref) wsPing.unref();
339
340server.listen(PORT, () => {
341 console.log('');
342 console.log('🪶 PrutFolio v1 — alpha');
343 console.log(` http://localhost:${PORT}`);
344 console.log('');
345 console.log(` ✓ Security: Helmet, CSP, secure sessions`);
346 console.log(` ✓ Privacy: Self-hosted fonts, no third-party requests`);
347 console.log(` ✓ Layout: v9 editorial feel (top nav, profile header)`);
348 console.log(` ✓ Auth: wachtwoord (beheer) + Google (luisteraars) / logout`);
349 console.log(` ✓ Posts: create / edit / view / archive`);
350 console.log(` ✓ Realtime: WebSocket server ready (Prutter)`);
351 console.log('');
352 console.log(` Mode: ${isDev ? 'development' : 'PRODUCTION'}`);
353 console.log('');
354});
355
356export default app;
Note: See TracBrowser for help on using the repository browser.