| 1 | /**
|
|---|
| 2 | * Klonkt Beta — server bootstrap
|
|---|
| 3 | *
|
|---|
| 4 | * Persoonlijk multi-site platform — Node + SQLite + htmx.
|
|---|
| 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 { startScheduler } from './services/Scheduler.js';
|
|---|
| 19 | import { SqliteSessionStore } from './services/SqliteSessionStore.js';
|
|---|
| 20 | import { ensurePrimarySite } from './services/ensurePrimarySite.js';
|
|---|
| 21 | import PrutterService from './services/PrutterService.js';
|
|---|
| 22 | import { WebSocketServer } from 'ws';
|
|---|
| 23 |
|
|---|
| 24 | import { resolveSite, loadAudioTracks, loadTheme } from './middleware/site.js';
|
|---|
| 25 | import { isViewer } from './middleware/auth.js';
|
|---|
| 26 | import { renderPage } from './middleware/render.js';
|
|---|
| 27 | import authRoutes from './routes/auth.js';
|
|---|
| 28 | import accountRoutes from './routes/account.js';
|
|---|
| 29 | import notificationsRoutes from './routes/notifications.js';
|
|---|
| 30 | import adminRoutes from './routes/admin.js';
|
|---|
| 31 | import adminAudioRoutes from './routes/admin-audio.js';
|
|---|
| 32 | import adminPlaylistsRoutes from './routes/admin-playlists.js';
|
|---|
| 33 | import adminSitesRoutes from './routes/admin-sites.js';
|
|---|
| 34 | import adminUsersRoutes from './routes/admin-users.js';
|
|---|
| 35 | import adminCommentsRoutes from './routes/admin-comments.js';
|
|---|
| 36 | import adminSettingsRoutes from './routes/admin-settings.js';
|
|---|
| 37 | import adminSeoRoutes from './routes/admin-seo.js';
|
|---|
| 38 | import prutterRoutes from './routes/prutter.js';
|
|---|
| 39 | import audioRoutes from './routes/audio.js';
|
|---|
| 40 | import searchRoutes from './routes/search.js';
|
|---|
| 41 | import commentsRoutes from './routes/comments.js';
|
|---|
| 42 | import tagsRoutes from './routes/tags.js';
|
|---|
| 43 | import typesRoutes from './routes/types.js';
|
|---|
| 44 | import usersRoutes from './routes/users.js';
|
|---|
| 45 | import feedRoutes from './routes/feed.js';
|
|---|
| 46 | import hubRoutes from './routes/hub.js';
|
|---|
| 47 | import artistsRoutes from './routes/artists.js';
|
|---|
| 48 | import postsRoutes from './routes/posts.js';
|
|---|
| 49 | import langRoutes from './routes/lang.js';
|
|---|
| 50 | import federationRoutes from './routes/federation.js';
|
|---|
| 51 | import { startCircleSyncLoop } from './services/CircleService.js';
|
|---|
| 52 | import adminCircleRoutes from './routes/admin-circle.js';
|
|---|
| 53 | import adminUpdatesRoutes from './routes/admin-updates.js';
|
|---|
| 54 | import adminPatreonRoutes from './routes/admin-patreon.js';
|
|---|
| 55 | import adminStatsRoutes from './routes/admin-stats.js';
|
|---|
| 56 | import circleRoutes from './routes/circle.js';
|
|---|
| 57 | import epkRoutes from './routes/epk.js';
|
|---|
| 58 | import newsletterRoutes from './routes/newsletter.js';
|
|---|
| 59 | import adminNewsletterRoutes from './routes/admin-newsletter.js';
|
|---|
| 60 | import downloadRoutes from './routes/download.js';
|
|---|
| 61 | import linkbioRoutes from './routes/linkbio.js';
|
|---|
| 62 | import embedRoutes from './routes/embed.js';
|
|---|
| 63 | import showsRoutes from './routes/shows.js';
|
|---|
| 64 | import adminShowsRoutes from './routes/admin-shows.js';
|
|---|
| 65 | import adminEpkRoutes from './routes/admin-epk.js';
|
|---|
| 66 | import changelogRoutes from './routes/changelog.js';
|
|---|
| 67 |
|
|---|
| 68 | if (!process.env.SESSION_SECRET) {
|
|---|
| 69 | console.error('❌ FATAL: SESSION_SECRET is required');
|
|---|
| 70 | process.exit(1);
|
|---|
| 71 | }
|
|---|
| 72 |
|
|---|
| 73 | if (process.env.NODE_ENV === 'production' && process.env.SESSION_SECRET.length < 32) {
|
|---|
| 74 | console.error('❌ FATAL: SESSION_SECRET too weak for production');
|
|---|
| 75 | process.exit(1);
|
|---|
| 76 | }
|
|---|
| 77 |
|
|---|
| 78 | const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|---|
| 79 | const PORT = process.env.PORT || 3000;
|
|---|
| 80 | const isDev = process.env.NODE_ENV !== 'production';
|
|---|
| 81 |
|
|---|
| 82 | const app = express();
|
|---|
| 83 | const server = http.createServer(app);
|
|---|
| 84 |
|
|---|
| 85 | app.use(helmet({
|
|---|
| 86 | contentSecurityPolicy: {
|
|---|
| 87 | directives: {
|
|---|
| 88 | defaultSrc: ["'self'"],
|
|---|
| 89 | scriptSrc: [
|
|---|
| 90 | "'self'",
|
|---|
| 91 | "'unsafe-inline'",
|
|---|
| 92 | // Eigen custom-embeds (embed-player.js) laden de OFFICIELE player-API's
|
|---|
| 93 | // van deze hosts. Zonder deze whitelist blokkeert de CSP ze stil (alleen
|
|---|
| 94 | // een console-fout) en faalt de embed-speler.
|
|---|
| 95 | "https://www.youtube.com", // YouTube IFrame Player API (+ www-widgetapi.js)
|
|---|
| 96 | "https://s.ytimg.com", // YouTube player-assets
|
|---|
| 97 | "https://w.soundcloud.com", // SoundCloud Widget API (api.js)
|
|---|
| 98 | "https://open.spotify.com", // Spotify iFrame API (loader)
|
|---|
| 99 | "https://*.spotifycdn.com", // Spotify iFrame API (echte bundle: embed-cdn.spotifycdn.com)
|
|---|
| 100 | ],
|
|---|
| 101 | // Helmet's default zet script-src-attr op 'none', wat ALLE inline event-
|
|---|
| 102 | // handlers (onchange/onclick/onsubmit) blokkeert — daardoor deed o.a. de
|
|---|
| 103 | // avatar-upload (<input onchange="this.form.submit()">) en de rol-dropdown
|
|---|
| 104 | // niets. We staan inline handlers expliciet toe, consistent met de al
|
|---|
| 105 | // toegestane inline <script> hierboven.
|
|---|
| 106 | scriptSrcAttr: ["'unsafe-inline'"],
|
|---|
| 107 | styleSrc: ["'self'", "'unsafe-inline'"],
|
|---|
| 108 | // blob: nodig voor de afbeeldings-editor (Cropper) — die toont de gekozen
|
|---|
| 109 | // foto via een URL.createObjectURL(blob:…). Zonder blob: blokkeert de CSP
|
|---|
| 110 | // de <img> stil → leeg bewerk-venster. (media-src heeft blob: al voor audio.)
|
|---|
| 111 | imgSrc: ["'self'", "data:", "https:", "blob:"],
|
|---|
| 112 | connectSrc: ["'self'", "wss:", "ws:", "https://*.spotifycdn.com", "https://*.scdn.co"],
|
|---|
| 113 | // blob: is required for the audio player — it fetch()es track bytes and
|
|---|
| 114 | // plays from a blob: object URL (Spotify-style). Without blob: here the
|
|---|
| 115 | // CSP silently blocks <audio>.src = blob:… → the player fires 'error' and
|
|---|
| 116 | // auto-skips every track. 'self'/https: do NOT imply blob:.
|
|---|
| 117 | mediaSrc: ["'self'", "https:", "blob:"],
|
|---|
| 118 | fontSrc: ["'self'"],
|
|---|
| 119 | frameSrc: [
|
|---|
| 120 | "'self'",
|
|---|
| 121 | "https://open.spotify.com",
|
|---|
| 122 | "https://w.soundcloud.com",
|
|---|
| 123 | "https://bandcamp.com",
|
|---|
| 124 | "https://embed.music.apple.com",
|
|---|
| 125 | "https://www.youtube-nocookie.com",
|
|---|
| 126 | "https://www.youtube.com", // YouTube IFrame API maakt soms een www.youtube.com-iframe
|
|---|
| 127 | "https://player.vimeo.com",
|
|---|
| 128 | ],
|
|---|
| 129 | },
|
|---|
| 130 | },
|
|---|
| 131 | hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
|
|---|
| 132 | frameguard: { action: 'sameorigin' },
|
|---|
| 133 | referrerPolicy: { policy: 'no-referrer-when-downgrade' },
|
|---|
| 134 | }));
|
|---|
| 135 |
|
|---|
| 136 | app.set('view engine', 'ejs');
|
|---|
| 137 | app.set('views', path.join(__dirname, 'views'));
|
|---|
| 138 |
|
|---|
| 139 | app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));
|
|---|
| 140 | app.use(bodyParser.json({ limit: '10mb' }));
|
|---|
| 141 |
|
|---|
| 142 | // Trust one upstream proxy in production. NPM (or Caddy / nginx) terminates
|
|---|
| 143 | // HTTPS and forwards to us over plain HTTP, setting X-Forwarded-Proto: https.
|
|---|
| 144 | // Without this, Express sees req.protocol === 'http' and won't issue secure
|
|---|
| 145 | // cookies — sessions never persist past the redirect after login.
|
|---|
| 146 | if (!isDev) app.set('trust proxy', 1);
|
|---|
| 147 |
|
|---|
| 148 | // Schema aanmaken/bijwerken VÓÓR iets de DB aanraakt: de session-store doet
|
|---|
| 149 | // bij constructie al een query op de `sessions`-tabel, dus bij een verse
|
|---|
| 150 | // install moeten de tabellen eerst bestaan (anders: "no such table: sessions"
|
|---|
| 151 | // → crash-loop op de allereerste boot).
|
|---|
| 152 | initializeDatabase();
|
|---|
| 153 | startScheduler(); // release-planning: zet geplande posts live zodra publish_at bereikt is
|
|---|
| 154 |
|
|---|
| 155 | // Vangnet: garandeer dat er altijd een primaire site is (solo/hub/circle).
|
|---|
| 156 | // Idempotent — doet niets als er al een site is of nog geen beheerder.
|
|---|
| 157 | ensurePrimarySite();
|
|---|
| 158 |
|
|---|
| 159 | // Session middleware extracted into a variable so the WebSocket upgrade
|
|---|
| 160 | // handler can reuse it (it needs req.session to authenticate sockets).
|
|---|
| 161 | const sessionMiddleware = session({
|
|---|
| 162 | store: new SqliteSessionStore(),
|
|---|
| 163 | secret: process.env.SESSION_SECRET,
|
|---|
| 164 | resave: false,
|
|---|
| 165 | saveUninitialized: false,
|
|---|
| 166 | name: 'pcms.sid',
|
|---|
| 167 | cookie: {
|
|---|
| 168 | httpOnly: true,
|
|---|
| 169 | secure: !isDev,
|
|---|
| 170 | sameSite: 'lax',
|
|---|
| 171 | maxAge: 30 * 24 * 60 * 60 * 1000,
|
|---|
| 172 | },
|
|---|
| 173 | });
|
|---|
| 174 | app.use(sessionMiddleware);
|
|---|
| 175 |
|
|---|
| 176 | app.use('/assets', express.static(path.join(__dirname, 'assets'), { maxAge: isDev ? 0 : '1y' }));
|
|---|
| 177 | app.use('/media', express.static(process.env.MEDIA_PATH || './storage/media', {
|
|---|
| 178 | // Publieke media (post-covers, avatars) moet door andere Klonkt-sites in hun
|
|---|
| 179 | // CIRKEL cross-origin embedbaar zijn. Helmet zet standaard CORP=same-origin,
|
|---|
| 180 | // wat die afbeeldingen in de browser blokkeert (bestand komt wél binnen, maar
|
|---|
| 181 | // de browser weigert 'm te tonen). Voor /media dus expliciet cross-origin.
|
|---|
| 182 | setHeaders: (res) => res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'),
|
|---|
| 183 | }));
|
|---|
| 184 |
|
|---|
| 185 | // (Verwijderd) TWA / digital-asset-links — alleen nodig voor de APK/TWA-variant.
|
|---|
| 186 | // Klonkt is PWA-only; geen assetlinks.json meer.
|
|---|
| 187 |
|
|---|
| 188 | // Cirkels: periodieke achtergrond-sync van remote instances (no-op tenzij tenancy='circle').
|
|---|
| 189 | startCircleSyncLoop();
|
|---|
| 190 |
|
|---|
| 191 | // Bundle HTMX: copy from node_modules into our own assets dir so we can serve
|
|---|
| 192 | // it locally (no third-party CDN). Idempotent — only copies if size differs.
|
|---|
| 193 | (function ensureLocalHtmx() {
|
|---|
| 194 | const src = path.join(__dirname, '..', 'node_modules', 'htmx.org', 'dist', 'htmx.min.js');
|
|---|
| 195 | const dest = path.join(__dirname, 'assets', 'js', 'htmx.min.js');
|
|---|
| 196 | try {
|
|---|
| 197 | const srcStat = fs.statSync(src);
|
|---|
| 198 | const destStat = fs.existsSync(dest) ? fs.statSync(dest) : null;
|
|---|
| 199 | if (!destStat || destStat.size !== srcStat.size) {
|
|---|
| 200 | fs.copyFileSync(src, dest);
|
|---|
| 201 | console.log(`📦 HTMX bundled locally: ${srcStat.size} bytes`);
|
|---|
| 202 | }
|
|---|
| 203 | } catch (e) {
|
|---|
| 204 | console.warn('⚠️ Could not bundle HTMX:', e.message, '— run `npm install`');
|
|---|
| 205 | }
|
|---|
| 206 | })();
|
|---|
| 207 |
|
|---|
| 208 | // Singleton PrutterService — routes get it via req.app.locals.prutter.
|
|---|
| 209 | const prutter = new PrutterService(db);
|
|---|
| 210 | app.locals.prutter = prutter;
|
|---|
| 211 |
|
|---|
| 212 | // Cirkels-federatie: publieke, site-agnostische endpoints (/.klonkt/*).
|
|---|
| 213 | // Vóór resolveSite/theme — ze hebben geen site-context nodig.
|
|---|
| 214 | app.use(federationRoutes);
|
|---|
| 215 |
|
|---|
| 216 | app.use(resolveSite);
|
|---|
| 217 | app.use(loadAudioTracks);
|
|---|
| 218 | app.use(loadTheme);
|
|---|
| 219 |
|
|---|
| 220 | // Lichtgewicht CSRF-defense: weiger cross-origin state-wijzigende requests.
|
|---|
| 221 | // Same-origin forms + HTMX sturen een matchende Origin; ontbreekt Origin dan
|
|---|
| 222 | // laten we door (non-browser clients). sameSite:'lax' op de sessiecookie is de
|
|---|
| 223 | // tweede laag. (Geldt niet voor GET/HEAD/OPTIONS.)
|
|---|
| 224 | app.use((req, res, next) => {
|
|---|
| 225 | if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
|
|---|
| 226 | const origin = req.get('origin');
|
|---|
| 227 | if (!origin) return next(); // geen Origin -> geen browser-CSRF-vector
|
|---|
| 228 | let originHost;
|
|---|
| 229 | try { originHost = new URL(origin).host; } catch { return res.status(403).send('Ongeldige origin'); }
|
|---|
| 230 | if (originHost !== req.get('host')) return res.status(403).send('Cross-origin request geweigerd');
|
|---|
| 231 | next();
|
|---|
| 232 | });
|
|---|
| 233 |
|
|---|
| 234 | // Kijker-accounts: alles bekijken mag (incl. Beheer), niets wijzigen. Dit is de
|
|---|
| 235 | // ENIGE schrijf-blokkade — fail-closed, vóór alle route-handlers. Elke state-
|
|---|
| 236 | // wijzigende methode wordt geweigerd (de login-POST zet de sessie pas ná deze
|
|---|
| 237 | // guard, dus die valt er niet onder). I.p.v. rauwe 403-tekst tonen we een nette
|
|---|
| 238 | // pagina (of, bij HTMX, een ingeswapte melding).
|
|---|
| 239 | app.use((req, res, next) => {
|
|---|
| 240 | const mutating = req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS';
|
|---|
| 241 | if (mutating && isViewer(req.session?.user)) {
|
|---|
| 242 | if (req.headers['hx-request'] === 'true') {
|
|---|
| 243 | // htmx swapt niet op 4xx; stuur 200 + retarget zodat de melding in #pcms-main verschijnt.
|
|---|
| 244 | res.setHeader('HX-Retarget', '#pcms-main');
|
|---|
| 245 | res.setHeader('HX-Reswap', 'innerHTML');
|
|---|
| 246 | res.status(200);
|
|---|
| 247 | } else {
|
|---|
| 248 | res.status(403);
|
|---|
| 249 | }
|
|---|
| 250 | return renderPage(req, res, 'pages/viewer-blocked', {
|
|---|
| 251 | pageTitle: 'Kijker-modus',
|
|---|
| 252 | bodyClass: 'on-special',
|
|---|
| 253 | });
|
|---|
| 254 | }
|
|---|
| 255 | next();
|
|---|
| 256 | });
|
|---|
| 257 |
|
|---|
| 258 | app.use('/auth', authRoutes);
|
|---|
| 259 | app.use('/account', accountRoutes);
|
|---|
| 260 | app.use('/notifications', notificationsRoutes);
|
|---|
| 261 | app.use('/admin/audio', adminAudioRoutes);
|
|---|
| 262 | app.use('/admin/playlists', adminPlaylistsRoutes);
|
|---|
| 263 | app.use('/admin/sites', adminSitesRoutes);
|
|---|
| 264 | app.use('/admin/users', adminUsersRoutes);
|
|---|
| 265 | app.use('/admin/comments', adminCommentsRoutes);
|
|---|
| 266 | app.use('/admin/settings', adminSettingsRoutes);
|
|---|
| 267 | app.use('/admin/seo', adminSeoRoutes);
|
|---|
| 268 | app.use('/admin/circle', adminCircleRoutes);
|
|---|
| 269 | app.use('/admin/updates', adminUpdatesRoutes);
|
|---|
| 270 | app.use('/admin/patreon', adminPatreonRoutes);
|
|---|
| 271 | app.use('/admin/stats', adminStatsRoutes);
|
|---|
| 272 | app.use('/admin/newsletter', adminNewsletterRoutes);
|
|---|
| 273 | app.use('/admin/shows', adminShowsRoutes);
|
|---|
| 274 | app.use('/admin/epk', adminEpkRoutes);
|
|---|
| 275 | app.use('/admin', adminRoutes);
|
|---|
| 276 | app.use('/prutter', prutterRoutes);
|
|---|
| 277 | app.use('/audio', audioRoutes);
|
|---|
| 278 | app.use('/search', searchRoutes);
|
|---|
| 279 | app.use('/comments', commentsRoutes);
|
|---|
| 280 | app.use('/tag', tagsRoutes);
|
|---|
| 281 | app.use('/type', typesRoutes);
|
|---|
| 282 | app.use('/users', usersRoutes);
|
|---|
| 283 | // Feed/sitemap routes are mounted at root because they're at well-known paths
|
|---|
| 284 | app.use('/', feedRoutes);
|
|---|
| 285 | app.use('/leden', artistsRoutes); // doorzoekbare leden-directory (alleen hub; solo: next())
|
|---|
| 286 | app.get('/artiesten', (req, res) => res.redirect(301, req.originalUrl.replace(/^\/artiesten/, '/leden'))); // oude URL -> /leden
|
|---|
| 287 | app.use('/', hubRoutes); // hub-overview op '/' (solo: next() -> postsRoutes)
|
|---|
| 288 | app.use('/', circleRoutes); // /cirkel-feed (solo/hub: next() -> postsRoutes)
|
|---|
| 289 | app.use('/', epkRoutes); // /pers perskit (premium; niet-premium: next() -> 404)
|
|---|
| 290 | app.use('/', newsletterRoutes); // /nieuwsbrief in/uitschrijven (premium; niet-premium: next())
|
|---|
| 291 | app.use('/', downloadRoutes); // /downloads + /download/:id download-voor-email (premium)
|
|---|
| 292 | app.use('/', linkbioRoutes); // /links link-in-bio + klikstats (premium)
|
|---|
| 293 | app.use('/', embedRoutes); // /embed inbedbare audiospeler (premium)
|
|---|
| 294 | app.use('/', showsRoutes); // /shows agenda + notify-me (premium)
|
|---|
| 295 | app.use('/', changelogRoutes); // /changelog publieke release-/wijzigingen-pagina
|
|---|
| 296 | app.use('/', langRoutes); // /lang/:code — interface-taal kiezen (vóór de catch-all)
|
|---|
| 297 | app.use('/', postsRoutes);
|
|---|
| 298 |
|
|---|
| 299 | app.get('/manifest.webmanifest', (req, res) => {
|
|---|
| 300 | const site = res.locals.site;
|
|---|
| 301 |
|
|---|
| 302 | // PWA scope: confines installed apps to ONE site. If a user is in the
|
|---|
| 303 | // bedrijf1 PWA and clicks a link to /sites/bedrijf2/..., the browser will
|
|---|
| 304 | // open it in a regular tab (out-of-scope) instead of within the PWA.
|
|---|
| 305 | // Same applies to APK packaging — the WebView is locked to this scope.
|
|---|
| 306 | //
|
|---|
| 307 | // For path-mounted sites: scope = /sites/<slug>/
|
|---|
| 308 | // For root/subdomain sites: scope = /
|
|---|
| 309 | const base = res.locals.siteUrlBase || ''; // '' or '/sites/<slug>'
|
|---|
| 310 | const scope = (base || '') + '/';
|
|---|
| 311 | const startUrl = (base || '') + '/?source=pwa';
|
|---|
| 312 |
|
|---|
| 313 | // A stable identity per site so installs don't collide (Chromium uses `id`).
|
|---|
| 314 | // NB: een id-wissel orphant bestaande PWA-installs (er is geen migratie die een
|
|---|
| 315 | // install over een id-verandering heen tilt) — wie een site al als PWA had,
|
|---|
| 316 | // moet 'm één keer opnieuw installeren. Data blijft server-side, dus niets kwijt.
|
|---|
| 317 | const idBase = site?.slug ? `klonkt-${site.slug}` : 'klonkt';
|
|---|
| 318 |
|
|---|
| 319 | res.set('Cache-Control', 'no-cache');
|
|---|
| 320 | res.json({
|
|---|
| 321 | id: idBase,
|
|---|
| 322 | name: site?.title || 'Klonkt',
|
|---|
| 323 | short_name: (site?.title || 'Klonkt').slice(0, 12),
|
|---|
| 324 | description: site?.description || site?.tagline || '',
|
|---|
| 325 | scope,
|
|---|
| 326 | start_url: startUrl,
|
|---|
| 327 | display: 'standalone',
|
|---|
| 328 | display_override: ['standalone', 'minimal-ui'],
|
|---|
| 329 | orientation: 'any',
|
|---|
| 330 | background_color: '#1a1a17',
|
|---|
| 331 | theme_color: site?.accent || '#c2410c',
|
|---|
| 332 | lang: site?.language || 'nl',
|
|---|
| 333 | icons: [
|
|---|
| 334 | { src: '/favicon.svg', sizes: 'any', type: 'image/svg+xml' },
|
|---|
| 335 | { src: '/favicon.ico', sizes: '64x64', type: 'image/x-icon' },
|
|---|
| 336 | ],
|
|---|
| 337 | // Hint to capable browsers: capture all in-scope links inside the PWA
|
|---|
| 338 | capture_links: 'existing-client-navigate',
|
|---|
| 339 | });
|
|---|
| 340 | });
|
|---|
| 341 |
|
|---|
| 342 | // Favicon — served as SVG so it picks up the site's accent color dynamically.
|
|---|
| 343 | // Browsers also request /favicon.ico by convention; we serve the same SVG
|
|---|
| 344 | // content there with a forgiving content-type since modern browsers accept it.
|
|---|
| 345 | function _renderFavicon(res, accent) {
|
|---|
| 346 | const safeAccent = /^#[0-9a-fA-F]{3,8}$/.test(accent) ? accent : '#c2410c';
|
|---|
| 347 | // Site mark: rounded square in the site accent + bold white 'K' (Klonkt)
|
|---|
| 348 | const svg = `<?xml version="1.0" encoding="UTF-8"?>
|
|---|
| 349 | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
|---|
| 350 | <rect width="64" height="64" rx="14" fill="${safeAccent}"/>
|
|---|
| 351 | <text x="50%" y="50%" dy="0.35em" text-anchor="middle"
|
|---|
| 352 | font-family="Arial, Helvetica, sans-serif"
|
|---|
| 353 | font-size="42" font-weight="800" fill="#fff">K</text>
|
|---|
| 354 | </svg>`;
|
|---|
| 355 | res.set('Content-Type', 'image/svg+xml');
|
|---|
| 356 | res.set('Cache-Control', 'public, max-age=86400');
|
|---|
| 357 | res.send(svg);
|
|---|
| 358 | }
|
|---|
| 359 |
|
|---|
| 360 | app.get('/favicon.svg', (req, res) => {
|
|---|
| 361 | _renderFavicon(res, res.locals.site?.accent);
|
|---|
| 362 | });
|
|---|
| 363 | app.get('/favicon.ico', (req, res) => {
|
|---|
| 364 | // Browsers requesting .ico will accept SVG content; chrome/firefox both fine.
|
|---|
| 365 | // Keeping the route prevents 404 spam in the console.
|
|---|
| 366 | _renderFavicon(res, res.locals.site?.accent);
|
|---|
| 367 | });
|
|---|
| 368 |
|
|---|
| 369 | app.get('/sw.js', (req, res) => {
|
|---|
| 370 | res.set('Content-Type', 'application/javascript');
|
|---|
| 371 | res.set('Cache-Control', 'no-cache');
|
|---|
| 372 | res.send(`
|
|---|
| 373 | const CACHE_VERSION = 'pcms-v11-' + new Date().toISOString().split('T')[0];
|
|---|
| 374 | self.addEventListener('install', e => {
|
|---|
| 375 | e.waitUntil(caches.open(CACHE_VERSION).then(c => c.addAll(['/'])));
|
|---|
| 376 | self.skipWaiting();
|
|---|
| 377 | });
|
|---|
| 378 | self.addEventListener('activate', e => {
|
|---|
| 379 | e.waitUntil(caches.keys().then(keys => Promise.all(
|
|---|
| 380 | keys.filter(k => k !== CACHE_VERSION).map(k => caches.delete(k))
|
|---|
| 381 | )));
|
|---|
| 382 | self.clients.claim();
|
|---|
| 383 | });
|
|---|
| 384 | // ALLEEN navigaties (HTML-pagina's) onderscheppen, voor een offline-fallback.
|
|---|
| 385 | // Afbeeldingen, CSS, JS en /media NIET aanraken — laat de browser die native
|
|---|
| 386 | // afhandelen. Anders kon een mislukte netwerk-fetch terugvallen op een lege
|
|---|
| 387 | // cache-match (undefined) en zo een afbeelding "kapot" maken bij een gewone
|
|---|
| 388 | // refresh (hard reload omzeilt de SW en werkte daarom wél).
|
|---|
| 389 | self.addEventListener('fetch', e => {
|
|---|
| 390 | if (e.request.method !== 'GET') return;
|
|---|
| 391 | if (e.request.mode !== 'navigate') return; // alleen page-loads
|
|---|
| 392 | e.respondWith(
|
|---|
| 393 | fetch(e.request).catch(() => caches.match('/').then(r => r || Response.error()))
|
|---|
| 394 | );
|
|---|
| 395 | });
|
|---|
| 396 | `);
|
|---|
| 397 | });
|
|---|
| 398 |
|
|---|
| 399 | process.on('unhandledRejection', (reason) => {
|
|---|
| 400 | console.error('⚠️ Unhandled Rejection:', reason);
|
|---|
| 401 | });
|
|---|
| 402 |
|
|---|
| 403 | app.use((err, req, res, next) => {
|
|---|
| 404 | console.error('❌ Error:', err);
|
|---|
| 405 | res.status(err.status || 500).send(
|
|---|
| 406 | isDev ? `<pre>${err.stack || err.message}</pre>` : 'Internal Server Error'
|
|---|
| 407 | );
|
|---|
| 408 | });
|
|---|
| 409 |
|
|---|
| 410 | app.use((req, res) => {
|
|---|
| 411 | res.status(404);
|
|---|
| 412 | // Nette, mobielvriendelijke 404 via de shell (viewport + nav + huisstijl).
|
|---|
| 413 | // Valt terug op kale HTML als het renderen onverhoopt faalt.
|
|---|
| 414 | try {
|
|---|
| 415 | return renderPage(req, res, 'pages/404', {
|
|---|
| 416 | pageTitle: '404 — niet gevonden',
|
|---|
| 417 | bodyClass: 'on-special on-404',
|
|---|
| 418 | });
|
|---|
| 419 | } catch (e) {
|
|---|
| 420 | return res.send('<!doctype html><meta name="viewport" content="width=device-width,initial-scale=1"><div style="font-family:system-ui;max-width:500px;margin:4rem auto;text-align:center;padding:2rem"><h1 style="font-size:4rem;margin:0">404</h1><p>Pagina niet gevonden</p><a href="/">← Home</a></div>');
|
|---|
| 421 | }
|
|---|
| 422 | });
|
|---|
| 423 |
|
|---|
| 424 | // ==================== WebSocket: Prutter real-time ====================
|
|---|
| 425 | // Authenticate via the existing session cookie. We reuse sessionMiddleware
|
|---|
| 426 | // during the HTTP upgrade so req.session is populated; if no user, abort.
|
|---|
| 427 | const wss = new WebSocketServer({ noServer: true });
|
|---|
| 428 |
|
|---|
| 429 | server.on('upgrade', (req, socket, head) => {
|
|---|
| 430 | if (req.url !== '/ws/prutter') {
|
|---|
| 431 | socket.destroy();
|
|---|
| 432 | return;
|
|---|
| 433 | }
|
|---|
| 434 | // Run session middleware on the upgrade request.
|
|---|
| 435 | // (Express's middleware accepts (req, res, next); we pass a stub res.)
|
|---|
| 436 | const stubRes = { setHeader: () => {}, getHeader: () => undefined, on: () => {}, end: () => {} };
|
|---|
| 437 | sessionMiddleware(req, stubRes, () => {
|
|---|
| 438 | if (!req.session?.user) {
|
|---|
| 439 | socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
|
|---|
| 440 | socket.destroy();
|
|---|
| 441 | return;
|
|---|
| 442 | }
|
|---|
| 443 | // Kijker-accounts zijn alleen-lezen: weiger de WS-upgrade. De HTTP-guard
|
|---|
| 444 | // dekt geen WS, dus dit is de plek om schrijven via een (toekomstige)
|
|---|
| 445 | // message-handler te voorkomen.
|
|---|
| 446 | if (isViewer(req.session.user)) {
|
|---|
| 447 | socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
|
|---|
| 448 | socket.destroy();
|
|---|
| 449 | return;
|
|---|
| 450 | }
|
|---|
| 451 | wss.handleUpgrade(req, socket, head, (ws) => {
|
|---|
| 452 | ws.userId = req.session.user.id;
|
|---|
| 453 | wss.emit('connection', ws, req);
|
|---|
| 454 | });
|
|---|
| 455 | });
|
|---|
| 456 | });
|
|---|
| 457 |
|
|---|
| 458 | wss.on('connection', (ws) => {
|
|---|
| 459 | prutter.addConnection(ws.userId, ws);
|
|---|
| 460 | ws.on('close', () => prutter.removeConnection(ws.userId, ws));
|
|---|
| 461 | ws.on('error', () => prutter.removeConnection(ws.userId, ws));
|
|---|
| 462 | // Optional: ping every 30s to keep connections alive through proxies
|
|---|
| 463 | ws.isAlive = true;
|
|---|
| 464 | ws.on('pong', () => { ws.isAlive = true; });
|
|---|
| 465 | });
|
|---|
| 466 | const wsPing = setInterval(() => {
|
|---|
| 467 | for (const ws of wss.clients) {
|
|---|
| 468 | if (ws.isAlive === false) { ws.terminate(); continue; }
|
|---|
| 469 | ws.isAlive = false;
|
|---|
| 470 | try { ws.ping(); } catch {}
|
|---|
| 471 | }
|
|---|
| 472 | }, 30000);
|
|---|
| 473 | if (wsPing.unref) wsPing.unref();
|
|---|
| 474 |
|
|---|
| 475 | server.listen(PORT, () => {
|
|---|
| 476 | console.log('');
|
|---|
| 477 | console.log('🪶 Klonkt Beta');
|
|---|
| 478 | console.log(` http://localhost:${PORT}`);
|
|---|
| 479 | console.log('');
|
|---|
| 480 | console.log(` ✓ Security: Helmet, CSP, secure sessions`);
|
|---|
| 481 | console.log(` ✓ Privacy: Self-hosted fonts, no third-party requests`);
|
|---|
| 482 | console.log(` ✓ Layout: v9 editorial feel (top nav, profile header)`);
|
|---|
| 483 | console.log(` ✓ Auth: wachtwoord (beheer) + Google (luisteraars) / logout`);
|
|---|
| 484 | console.log(` ✓ Posts: create / edit / view / archive`);
|
|---|
| 485 | console.log(` ✓ Realtime: WebSocket server ready (Prutter)`);
|
|---|
| 486 | console.log('');
|
|---|
| 487 | console.log(` Mode: ${isDev ? 'development' : 'PRODUCTION'}`);
|
|---|
| 488 | console.log('');
|
|---|
| 489 | });
|
|---|
| 490 |
|
|---|
| 491 | export default app;
|
|---|