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

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

tenancy: runtime Solo/Hub mode + mode-aware /admin (Phase 1)

Admin can switch live between modes in Admin -> Settings:

  • solo: exactly one site (the primary/owner site), no /sites routing, leaner /admin.
  • hub: main site + /sites/:slug routing (company; /gebruikers + assignment flow = Phase 2).

Switching is non-destructive (hides only, deletes nothing).

  • app_settings (key/value singleton) + SettingsService (cached getTenancy/setTenancy).
  • resolveSite: solo pins to the primary site + disables /sites/:slug + host mapping.
  • /admin/settings (god-only) toggle; /admin dashboard rewritten, mode-aware.

Tested on the demo: solo/hub dashboard tiles, /sites routing per mode, toggle back/forth.

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

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