| 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 |
|
|---|
| 8 | import 'dotenv/config';
|
|---|
| 9 | import express from 'express';
|
|---|
| 10 | import helmet from 'helmet';
|
|---|
| 11 | import session from 'express-session';
|
|---|
| 12 | import bodyParser from 'body-parser';
|
|---|
| 13 | import path from 'path';
|
|---|
| 14 | import fs from 'fs';
|
|---|
| 15 | import { fileURLToPath } from 'url';
|
|---|
| 16 | import http from 'http';
|
|---|
| 17 | import db, { initializeDatabase } from './config/database.js';
|
|---|
| 18 | import { SqliteSessionStore } from './services/SqliteSessionStore.js';
|
|---|
| 19 | import PrutterService from './services/PrutterService.js';
|
|---|
| 20 | import { WebSocketServer } from 'ws';
|
|---|
| 21 |
|
|---|
| 22 | import { resolveSite, loadAudioTracks, loadTheme } from './middleware/site.js';
|
|---|
| 23 | import authRoutes from './routes/auth.js';
|
|---|
| 24 | import accountRoutes from './routes/account.js';
|
|---|
| 25 | import adminRoutes from './routes/admin.js';
|
|---|
| 26 | import adminAudioRoutes from './routes/admin-audio.js';
|
|---|
| 27 | import adminPlaylistsRoutes from './routes/admin-playlists.js';
|
|---|
| 28 | import adminSitesRoutes from './routes/admin-sites.js';
|
|---|
| 29 | import adminUsersRoutes from './routes/admin-users.js';
|
|---|
| 30 | import adminCommentsRoutes from './routes/admin-comments.js';
|
|---|
| 31 | import prutterRoutes from './routes/prutter.js';
|
|---|
| 32 | import audioRoutes from './routes/audio.js';
|
|---|
| 33 | import searchRoutes from './routes/search.js';
|
|---|
| 34 | import commentsRoutes from './routes/comments.js';
|
|---|
| 35 | import tagsRoutes from './routes/tags.js';
|
|---|
| 36 | import typesRoutes from './routes/types.js';
|
|---|
| 37 | import usersRoutes from './routes/users.js';
|
|---|
| 38 | import feedRoutes from './routes/feed.js';
|
|---|
| 39 | import postsRoutes from './routes/posts.js';
|
|---|
| 40 |
|
|---|
| 41 | if (!process.env.SESSION_SECRET) {
|
|---|
| 42 | console.error('❌ FATAL: SESSION_SECRET is required');
|
|---|
| 43 | process.exit(1);
|
|---|
| 44 | }
|
|---|
| 45 |
|
|---|
| 46 | if (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 |
|
|---|
| 51 | const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|---|
| 52 | const PORT = process.env.PORT || 3000;
|
|---|
| 53 | const isDev = process.env.NODE_ENV !== 'production';
|
|---|
| 54 |
|
|---|
| 55 | const app = express();
|
|---|
| 56 | const server = http.createServer(app);
|
|---|
| 57 |
|
|---|
| 58 | app.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 |
|
|---|
| 88 | app.set('view engine', 'ejs');
|
|---|
| 89 | app.set('views', path.join(__dirname, 'views'));
|
|---|
| 90 |
|
|---|
| 91 | app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));
|
|---|
| 92 | app.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.
|
|---|
| 98 | if (!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).
|
|---|
| 102 | const 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 | });
|
|---|
| 115 | app.use(sessionMiddleware);
|
|---|
| 116 |
|
|---|
| 117 | app.use('/assets', express.static(path.join(__dirname, 'assets'), { maxAge: isDev ? 0 : '1y' }));
|
|---|
| 118 | app.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.
|
|---|
| 123 | app.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 |
|
|---|
| 129 | initializeDatabase();
|
|---|
| 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.
|
|---|
| 149 | const prutter = new PrutterService(db);
|
|---|
| 150 | app.locals.prutter = prutter;
|
|---|
| 151 |
|
|---|
| 152 | app.use(resolveSite);
|
|---|
| 153 | app.use(loadAudioTracks);
|
|---|
| 154 | app.use(loadTheme);
|
|---|
| 155 |
|
|---|
| 156 | app.use('/auth', authRoutes);
|
|---|
| 157 | app.use('/account', accountRoutes);
|
|---|
| 158 | app.use('/admin/audio', adminAudioRoutes);
|
|---|
| 159 | app.use('/admin/playlists', adminPlaylistsRoutes);
|
|---|
| 160 | app.use('/admin/sites', adminSitesRoutes);
|
|---|
| 161 | app.use('/admin/users', adminUsersRoutes);
|
|---|
| 162 | app.use('/admin/comments', adminCommentsRoutes);
|
|---|
| 163 | app.use('/admin', adminRoutes);
|
|---|
| 164 | app.use('/prutter', prutterRoutes);
|
|---|
| 165 | app.use('/audio', audioRoutes);
|
|---|
| 166 | app.use('/search', searchRoutes);
|
|---|
| 167 | app.use('/comments', commentsRoutes);
|
|---|
| 168 | app.use('/tag', tagsRoutes);
|
|---|
| 169 | app.use('/type', typesRoutes);
|
|---|
| 170 | app.use('/users', usersRoutes);
|
|---|
| 171 | // Feed/sitemap routes are mounted at root because they're at well-known paths
|
|---|
| 172 | app.use('/', feedRoutes);
|
|---|
| 173 | app.use('/', postsRoutes);
|
|---|
| 174 |
|
|---|
| 175 | app.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.
|
|---|
| 218 | function _renderFavicon(res, accent) {
|
|---|
| 219 | const safeAccent = /^#[0-9a-fA-F]{3,8}$/.test(accent) ? accent : '#c2410c';
|
|---|
| 220 | // Site mark: rounded square in the site accent + bold white 'SF'
|
|---|
| 221 | const svg = `<?xml version="1.0" encoding="UTF-8"?>
|
|---|
| 222 | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
|---|
| 223 | <rect width="64" height="64" rx="14" fill="${safeAccent}"/>
|
|---|
| 224 | <text x="50%" y="50%" dy="0.36em" text-anchor="middle"
|
|---|
| 225 | font-family="Arial, Helvetica, sans-serif"
|
|---|
| 226 | font-size="30" font-weight="800" letter-spacing="-1" fill="#fff">SF</text>
|
|---|
| 227 | </svg>`;
|
|---|
| 228 | res.set('Content-Type', 'image/svg+xml');
|
|---|
| 229 | res.set('Cache-Control', 'public, max-age=86400');
|
|---|
| 230 | res.send(svg);
|
|---|
| 231 | }
|
|---|
| 232 |
|
|---|
| 233 | app.get('/favicon.svg', (req, res) => {
|
|---|
| 234 | _renderFavicon(res, res.locals.site?.accent);
|
|---|
| 235 | });
|
|---|
| 236 | app.get('/favicon.ico', (req, res) => {
|
|---|
| 237 | // Browsers requesting .ico will accept SVG content; chrome/firefox both fine.
|
|---|
| 238 | // Keeping the route prevents 404 spam in the console.
|
|---|
| 239 | _renderFavicon(res, res.locals.site?.accent);
|
|---|
| 240 | });
|
|---|
| 241 |
|
|---|
| 242 | app.get('/sw.js', (req, res) => {
|
|---|
| 243 | res.set('Content-Type', 'application/javascript');
|
|---|
| 244 | res.set('Cache-Control', 'no-cache');
|
|---|
| 245 | res.send(`
|
|---|
| 246 | const CACHE_VERSION = 'pcms-v10-' + new Date().toISOString().split('T')[0];
|
|---|
| 247 | self.addEventListener('install', e => {
|
|---|
| 248 | e.waitUntil(caches.open(CACHE_VERSION).then(c => c.addAll(['/'])));
|
|---|
| 249 | self.skipWaiting();
|
|---|
| 250 | });
|
|---|
| 251 | self.addEventListener('activate', e => {
|
|---|
| 252 | e.waitUntil(caches.keys().then(keys => Promise.all(
|
|---|
| 253 | keys.filter(k => k !== CACHE_VERSION).map(k => caches.delete(k))
|
|---|
| 254 | )));
|
|---|
| 255 | self.clients.claim();
|
|---|
| 256 | });
|
|---|
| 257 | self.addEventListener('fetch', e => {
|
|---|
| 258 | if (e.request.method !== 'GET') return;
|
|---|
| 259 | e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
|
|---|
| 260 | });
|
|---|
| 261 | `);
|
|---|
| 262 | });
|
|---|
| 263 |
|
|---|
| 264 | process.on('unhandledRejection', (reason) => {
|
|---|
| 265 | console.error('⚠️ Unhandled Rejection:', reason);
|
|---|
| 266 | });
|
|---|
| 267 |
|
|---|
| 268 | app.use((err, req, res, next) => {
|
|---|
| 269 | console.error('❌ Error:', err);
|
|---|
| 270 | res.status(err.status || 500).send(
|
|---|
| 271 | isDev ? `<pre>${err.stack || err.message}</pre>` : 'Internal Server Error'
|
|---|
| 272 | );
|
|---|
| 273 | });
|
|---|
| 274 |
|
|---|
| 275 | app.use((req, res) => {
|
|---|
| 276 | res.status(404).send(`
|
|---|
| 277 | <div style="font-family:system-ui;max-width:500px;margin:4rem auto;text-align:center;padding:2rem;">
|
|---|
| 278 | <h1 style="font-size:5rem;margin:0;color:#c33;">404</h1>
|
|---|
| 279 | <p>Not found</p>
|
|---|
| 280 | <a href="/" style="color:#c2410c;">← Home</a>
|
|---|
| 281 | </div>
|
|---|
| 282 | `);
|
|---|
| 283 | });
|
|---|
| 284 |
|
|---|
| 285 | // ==================== WebSocket: Prutter real-time ====================
|
|---|
| 286 | // Authenticate via the existing session cookie. We reuse sessionMiddleware
|
|---|
| 287 | // during the HTTP upgrade so req.session is populated; if no user, abort.
|
|---|
| 288 | const wss = new WebSocketServer({ noServer: true });
|
|---|
| 289 |
|
|---|
| 290 | server.on('upgrade', (req, socket, head) => {
|
|---|
| 291 | if (req.url !== '/ws/prutter') {
|
|---|
| 292 | socket.destroy();
|
|---|
| 293 | return;
|
|---|
| 294 | }
|
|---|
| 295 | // Run session middleware on the upgrade request.
|
|---|
| 296 | // (Express's middleware accepts (req, res, next); we pass a stub res.)
|
|---|
| 297 | const stubRes = { setHeader: () => {}, getHeader: () => undefined, on: () => {}, end: () => {} };
|
|---|
| 298 | sessionMiddleware(req, stubRes, () => {
|
|---|
| 299 | if (!req.session?.user) {
|
|---|
| 300 | socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
|
|---|
| 301 | socket.destroy();
|
|---|
| 302 | return;
|
|---|
| 303 | }
|
|---|
| 304 | wss.handleUpgrade(req, socket, head, (ws) => {
|
|---|
| 305 | ws.userId = req.session.user.id;
|
|---|
| 306 | wss.emit('connection', ws, req);
|
|---|
| 307 | });
|
|---|
| 308 | });
|
|---|
| 309 | });
|
|---|
| 310 |
|
|---|
| 311 | wss.on('connection', (ws) => {
|
|---|
| 312 | prutter.addConnection(ws.userId, ws);
|
|---|
| 313 | ws.on('close', () => prutter.removeConnection(ws.userId, ws));
|
|---|
| 314 | ws.on('error', () => prutter.removeConnection(ws.userId, ws));
|
|---|
| 315 | // Optional: ping every 30s to keep connections alive through proxies
|
|---|
| 316 | ws.isAlive = true;
|
|---|
| 317 | ws.on('pong', () => { ws.isAlive = true; });
|
|---|
| 318 | });
|
|---|
| 319 | const wsPing = setInterval(() => {
|
|---|
| 320 | for (const ws of wss.clients) {
|
|---|
| 321 | if (ws.isAlive === false) { ws.terminate(); continue; }
|
|---|
| 322 | ws.isAlive = false;
|
|---|
| 323 | try { ws.ping(); } catch {}
|
|---|
| 324 | }
|
|---|
| 325 | }, 30000);
|
|---|
| 326 | if (wsPing.unref) wsPing.unref();
|
|---|
| 327 |
|
|---|
| 328 | server.listen(PORT, () => {
|
|---|
| 329 | console.log('');
|
|---|
| 330 | console.log('🪶 PrutFolio v1 — alpha');
|
|---|
| 331 | console.log(` http://localhost:${PORT}`);
|
|---|
| 332 | console.log('');
|
|---|
| 333 | console.log(` ✓ Security: Helmet, CSP, secure sessions`);
|
|---|
| 334 | console.log(` ✓ Privacy: Self-hosted fonts, no third-party requests`);
|
|---|
| 335 | console.log(` ✓ Layout: v9 editorial feel (top nav, profile header)`);
|
|---|
| 336 | console.log(` ✓ Auth: login / register / logout`);
|
|---|
| 337 | console.log(` ✓ Posts: create / edit / view / archive`);
|
|---|
| 338 | console.log(` ✓ Realtime: WebSocket server ready (Prutter)`);
|
|---|
| 339 | console.log('');
|
|---|
| 340 | console.log(` Mode: ${isDev ? 'development' : 'PRODUCTION'}`);
|
|---|
| 341 | console.log('');
|
|---|
| 342 | });
|
|---|
| 343 |
|
|---|
| 344 | export default app;
|
|---|