source: Klonkt/src/server.js@ 5b22ea9

main
Last change on this file since 5b22ea9 was 7bc636b, checked in by Robin <robin@…>, 4 months ago

Initial commit — PrutFolio v1 source (pulled from Hetzner /srv/prutfolio)

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