source: Klonkt/src/server.js@ b5bae24

main
Last change on this file since b5bae24 was b5bae24, checked in by Robin Genis <roboburr@…>, 3 months ago

reconcile: commit uncommitted live /srv state (playback fix + prefetch, SF favicon, smooth scroll, scripts)

The live working tree /srv/prutfolio was ahead of the bare repo with direct
server edits that had never been committed back. The deploy hook does
checkout -f main, so the next deploy would have reverted the 3 modified
tracked files to f33db01 and lost this work:

  • audio-player.js: robust playback — retry+backoff on network hiccups (no longer skipping immediately) + next-track prefetch (downloads the next track while the current one plays -> ended->next swaps instantly, covering the autoplay lapse). Fix for the sometimes-next-doesn't-play bug.
  • server.js: favicon mark p -> SF (SoundFabrics rebrand). shell.ejs: audio-player.js cache buster ?v=5 -> ?v=6 + favicon ?v=sf.
  • Plus previously untracked project files committed: lenis.min.js + smooth-scroll.js (not yet wired), scripts/ (v9 import/migration), deploy/ docs (DEPLOY.md/backup.sh/nginx/verify.ps1), .well-known/assetlinks.json. audio-player.js.bak.20260614 deliberately NOT committed.

Co-Authored-By: Claude <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 // 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
233app.get('/favicon.svg', (req, res) => {
234 _renderFavicon(res, res.locals.site?.accent);
235});
236app.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
242app.get('/sw.js', (req, res) => {
243 res.set('Content-Type', 'application/javascript');
244 res.set('Cache-Control', 'no-cache');
245 res.send(`
246const CACHE_VERSION = 'pcms-v10-' + new Date().toISOString().split('T')[0];
247self.addEventListener('install', e => {
248 e.waitUntil(caches.open(CACHE_VERSION).then(c => c.addAll(['/'])));
249 self.skipWaiting();
250});
251self.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});
257self.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
264process.on('unhandledRejection', (reason) => {
265 console.error('⚠️ Unhandled Rejection:', reason);
266});
267
268app.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
275app.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.
288const wss = new WebSocketServer({ noServer: true });
289
290server.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
311wss.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});
319const 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);
326if (wsPing.unref) wsPing.unref();
327
328server.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
344export default app;
Note: See TracBrowser for help on using the repository browser.