| [7bc636b] | 1 | /**
|
|---|
| [83faa57] | 2 | * Klonkt Beta — server bootstrap
|
|---|
| [7bc636b] | 3 | *
|
|---|
| [834bcc3] | 4 | * Personal multi-site platform — Node + SQLite + htmx.
|
|---|
| [7bc636b] | 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';
|
|---|
| [b9dc94c] | 18 | import { startScheduler } from './services/Scheduler.js';
|
|---|
| [7bc636b] | 19 | import { SqliteSessionStore } from './services/SqliteSessionStore.js';
|
|---|
| [bdc3c1e] | 20 | import { ensurePrimarySite } from './services/ensurePrimarySite.js';
|
|---|
| [7bc636b] | 21 | import { resolveSite, loadAudioTracks, loadTheme } from './middleware/site.js';
|
|---|
| [8afbdd6] | 22 | import { isViewer } from './middleware/auth.js';
|
|---|
| 23 | import { renderPage } from './middleware/render.js';
|
|---|
| [cb01666] | 24 | import { audioEnabled } from './config/features.js';
|
|---|
| [7bc636b] | 25 | import authRoutes from './routes/auth.js';
|
|---|
| 26 | import accountRoutes from './routes/account.js';
|
|---|
| [c9c6a2d] | 27 | import notificationsRoutes from './routes/notifications.js';
|
|---|
| [7bc636b] | 28 | import adminRoutes from './routes/admin.js';
|
|---|
| 29 | import adminAudioRoutes from './routes/admin-audio.js';
|
|---|
| 30 | import adminPlaylistsRoutes from './routes/admin-playlists.js';
|
|---|
| 31 | import adminSitesRoutes from './routes/admin-sites.js';
|
|---|
| 32 | import adminUsersRoutes from './routes/admin-users.js';
|
|---|
| 33 | import adminCommentsRoutes from './routes/admin-comments.js';
|
|---|
| [6351545] | 34 | import adminSettingsRoutes from './routes/admin-settings.js';
|
|---|
| [6623453] | 35 | import adminSeoRoutes from './routes/admin-seo.js';
|
|---|
| [7bc636b] | 36 | import audioRoutes from './routes/audio.js';
|
|---|
| 37 | import searchRoutes from './routes/search.js';
|
|---|
| 38 | import commentsRoutes from './routes/comments.js';
|
|---|
| 39 | import tagsRoutes from './routes/tags.js';
|
|---|
| 40 | import typesRoutes from './routes/types.js';
|
|---|
| 41 | import usersRoutes from './routes/users.js';
|
|---|
| 42 | import feedRoutes from './routes/feed.js';
|
|---|
| [bf61be7] | 43 | import hubRoutes from './routes/hub.js';
|
|---|
| [8afbdd6] | 44 | import artistsRoutes from './routes/artists.js';
|
|---|
| [7bc636b] | 45 | import postsRoutes from './routes/posts.js';
|
|---|
| [03fa548] | 46 | import langRoutes from './routes/lang.js';
|
|---|
| [b300682] | 47 | import federationRoutes from './routes/federation.js';
|
|---|
| [25d4041] | 48 | import { startCircleSyncLoop } from './services/CircleService.js';
|
|---|
| [0091cb7] | 49 | import adminCircleRoutes from './routes/admin-circle.js';
|
|---|
| [ff08153] | 50 | import adminUpdatesRoutes from './routes/admin-updates.js';
|
|---|
| [1b4d5dd] | 51 | import adminPatreonRoutes from './routes/admin-patreon.js';
|
|---|
| [d549549] | 52 | import adminStatsRoutes from './routes/admin-stats.js';
|
|---|
| [0091cb7] | 53 | import circleRoutes from './routes/circle.js';
|
|---|
| [255e3d3] | 54 | import epkRoutes from './routes/epk.js';
|
|---|
| [2e247e4] | 55 | import newsletterRoutes from './routes/newsletter.js';
|
|---|
| 56 | import adminNewsletterRoutes from './routes/admin-newsletter.js';
|
|---|
| [91094a4] | 57 | import downloadRoutes from './routes/download.js';
|
|---|
| [37edecd] | 58 | import linkbioRoutes from './routes/linkbio.js';
|
|---|
| [6be57b4] | 59 | import embedRoutes from './routes/embed.js';
|
|---|
| [8d32dcf] | 60 | import showsRoutes from './routes/shows.js';
|
|---|
| 61 | import adminShowsRoutes from './routes/admin-shows.js';
|
|---|
| [9d9f3c1] | 62 | import adminEpkRoutes from './routes/admin-epk.js';
|
|---|
| [90259da] | 63 | import changelogRoutes from './routes/changelog.js';
|
|---|
| [7bc636b] | 64 |
|
|---|
| 65 | if (!process.env.SESSION_SECRET) {
|
|---|
| 66 | console.error('❌ FATAL: SESSION_SECRET is required');
|
|---|
| 67 | process.exit(1);
|
|---|
| 68 | }
|
|---|
| 69 |
|
|---|
| 70 | if (process.env.NODE_ENV === 'production' && process.env.SESSION_SECRET.length < 32) {
|
|---|
| 71 | console.error('❌ FATAL: SESSION_SECRET too weak for production');
|
|---|
| 72 | process.exit(1);
|
|---|
| 73 | }
|
|---|
| 74 |
|
|---|
| 75 | const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|---|
| 76 | const PORT = process.env.PORT || 3000;
|
|---|
| 77 | const isDev = process.env.NODE_ENV !== 'production';
|
|---|
| 78 |
|
|---|
| 79 | const app = express();
|
|---|
| 80 | const server = http.createServer(app);
|
|---|
| 81 |
|
|---|
| 82 | app.use(helmet({
|
|---|
| 83 | contentSecurityPolicy: {
|
|---|
| 84 | directives: {
|
|---|
| 85 | defaultSrc: ["'self'"],
|
|---|
| [4c9f29a] | 86 | scriptSrc: [
|
|---|
| 87 | "'self'",
|
|---|
| 88 | "'unsafe-inline'",
|
|---|
| [834bcc3] | 89 | // Our custom embeds (embed-player.js) load the OFFICIAL player APIs
|
|---|
| 90 | // from these hosts. Without this whitelist the CSP silently blocks them
|
|---|
| 91 | // (only a console error) and the embed player fails.
|
|---|
| [4c9f29a] | 92 | "https://www.youtube.com", // YouTube IFrame Player API (+ www-widgetapi.js)
|
|---|
| [834bcc3] | 93 | "https://s.ytimg.com", // YouTube player assets
|
|---|
| [4c9f29a] | 94 | "https://w.soundcloud.com", // SoundCloud Widget API (api.js)
|
|---|
| [16b0c00] | 95 | "https://open.spotify.com", // Spotify iFrame API (loader)
|
|---|
| [834bcc3] | 96 | "https://*.spotifycdn.com", // Spotify iFrame API (real bundle: embed-cdn.spotifycdn.com)
|
|---|
| [4c9f29a] | 97 | ],
|
|---|
| [834bcc3] | 98 | // Helmet's default sets script-src-attr to 'none', which blocks ALL inline
|
|---|
| 99 | // event handlers (onchange/onclick/onsubmit) — causing e.g. the avatar
|
|---|
| 100 | // upload (<input onchange="this.form.submit()">) and the role dropdown to
|
|---|
| 101 | // silently do nothing. We explicitly allow inline handlers, consistent with
|
|---|
| 102 | // the already-allowed inline <script> above.
|
|---|
| [c869272] | 103 | scriptSrcAttr: ["'unsafe-inline'"],
|
|---|
| [7bc636b] | 104 | styleSrc: ["'self'", "'unsafe-inline'"],
|
|---|
| [834bcc3] | 105 | // blob: required for the image editor (Cropper) — it displays the chosen
|
|---|
| 106 | // photo via URL.createObjectURL(blob:…). Without blob: the CSP silently
|
|---|
| 107 | // blocks the <img> → empty edit window. (media-src already has blob: for audio.)
|
|---|
| [9effb80] | 108 | imgSrc: ["'self'", "data:", "https:", "blob:"],
|
|---|
| [16b0c00] | 109 | connectSrc: ["'self'", "wss:", "ws:", "https://*.spotifycdn.com", "https://*.scdn.co"],
|
|---|
| [353c39c] | 110 | // blob: is required for the audio player — it fetch()es track bytes and
|
|---|
| 111 | // plays from a blob: object URL (Spotify-style). Without blob: here the
|
|---|
| 112 | // CSP silently blocks <audio>.src = blob:… → the player fires 'error' and
|
|---|
| 113 | // auto-skips every track. 'self'/https: do NOT imply blob:.
|
|---|
| 114 | mediaSrc: ["'self'", "https:", "blob:"],
|
|---|
| [7bc636b] | 115 | fontSrc: ["'self'"],
|
|---|
| 116 | frameSrc: [
|
|---|
| 117 | "'self'",
|
|---|
| 118 | "https://open.spotify.com",
|
|---|
| 119 | "https://w.soundcloud.com",
|
|---|
| 120 | "https://bandcamp.com",
|
|---|
| 121 | "https://embed.music.apple.com",
|
|---|
| 122 | "https://www.youtube-nocookie.com",
|
|---|
| [834bcc3] | 123 | "https://www.youtube.com", // YouTube IFrame API sometimes creates a www.youtube.com iframe
|
|---|
| [7bc636b] | 124 | "https://player.vimeo.com",
|
|---|
| 125 | ],
|
|---|
| 126 | },
|
|---|
| 127 | },
|
|---|
| 128 | hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
|
|---|
| 129 | frameguard: { action: 'sameorigin' },
|
|---|
| 130 | referrerPolicy: { policy: 'no-referrer-when-downgrade' },
|
|---|
| 131 | }));
|
|---|
| 132 |
|
|---|
| 133 | app.set('view engine', 'ejs');
|
|---|
| 134 | app.set('views', path.join(__dirname, 'views'));
|
|---|
| 135 |
|
|---|
| 136 | app.use(bodyParser.urlencoded({ extended: true, limit: '10mb' }));
|
|---|
| 137 | app.use(bodyParser.json({ limit: '10mb' }));
|
|---|
| 138 |
|
|---|
| 139 | // Trust one upstream proxy in production. NPM (or Caddy / nginx) terminates
|
|---|
| 140 | // HTTPS and forwards to us over plain HTTP, setting X-Forwarded-Proto: https.
|
|---|
| 141 | // Without this, Express sees req.protocol === 'http' and won't issue secure
|
|---|
| 142 | // cookies — sessions never persist past the redirect after login.
|
|---|
| 143 | if (!isDev) app.set('trust proxy', 1);
|
|---|
| 144 |
|
|---|
| [834bcc3] | 145 | // Create/migrate the schema BEFORE anything touches the DB: the session store
|
|---|
| 146 | // queries the `sessions` table on construction, so on a fresh install the tables
|
|---|
| 147 | // must exist first (otherwise: "no such table: sessions" → crash loop on first boot).
|
|---|
| [5f43245] | 148 | initializeDatabase();
|
|---|
| [834bcc3] | 149 | startScheduler(); // release planning: publish scheduled posts when publish_at is reached
|
|---|
| [5f43245] | 150 |
|
|---|
| [834bcc3] | 151 | // Safety net: guarantee that there is always a primary site (solo/hub/circle).
|
|---|
| 152 | // Idempotent — does nothing if a site already exists or there is no admin yet.
|
|---|
| [bdc3c1e] | 153 | ensurePrimarySite();
|
|---|
| 154 |
|
|---|
| [7bc636b] | 155 | // Session middleware extracted into a variable so the WebSocket upgrade
|
|---|
| 156 | // handler can reuse it (it needs req.session to authenticate sockets).
|
|---|
| 157 | const sessionMiddleware = session({
|
|---|
| 158 | store: new SqliteSessionStore(),
|
|---|
| 159 | secret: process.env.SESSION_SECRET,
|
|---|
| 160 | resave: false,
|
|---|
| 161 | saveUninitialized: false,
|
|---|
| 162 | name: 'pcms.sid',
|
|---|
| 163 | cookie: {
|
|---|
| 164 | httpOnly: true,
|
|---|
| 165 | secure: !isDev,
|
|---|
| 166 | sameSite: 'lax',
|
|---|
| 167 | maxAge: 30 * 24 * 60 * 60 * 1000,
|
|---|
| 168 | },
|
|---|
| 169 | });
|
|---|
| 170 | app.use(sessionMiddleware);
|
|---|
| 171 |
|
|---|
| 172 | app.use('/assets', express.static(path.join(__dirname, 'assets'), { maxAge: isDev ? 0 : '1y' }));
|
|---|
| [fb02cc0] | 173 | app.use('/media', express.static(process.env.MEDIA_PATH || './storage/media', {
|
|---|
| [834bcc3] | 174 | // Public media (post covers, avatars) must be cross-origin embeddable by other
|
|---|
| 175 | // Klonkt sites in their CIRCLE. Helmet sets CORP=same-origin by default, which
|
|---|
| 176 | // causes the browser to block those images (the file arrives, but the browser
|
|---|
| 177 | // refuses to render it). Set cross-origin explicitly for /media.
|
|---|
| [fb02cc0] | 178 | setHeaders: (res) => res.setHeader('Cross-Origin-Resource-Policy', 'cross-origin'),
|
|---|
| 179 | }));
|
|---|
| [7bc636b] | 180 |
|
|---|
| [834bcc3] | 181 | // (Removed) TWA / digital-asset-links — only needed for the APK/TWA variant.
|
|---|
| 182 | // Klonkt is PWA-only; assetlinks.json is no longer served.
|
|---|
| [7bc636b] | 183 |
|
|---|
| [834bcc3] | 184 | // Circles: periodic background sync of remote instances (no-op unless tenancy='circle').
|
|---|
| [25d4041] | 185 | startCircleSyncLoop();
|
|---|
| 186 |
|
|---|
| [7bc636b] | 187 | // Bundle HTMX: copy from node_modules into our own assets dir so we can serve
|
|---|
| 188 | // it locally (no third-party CDN). Idempotent — only copies if size differs.
|
|---|
| 189 | (function ensureLocalHtmx() {
|
|---|
| 190 | const src = path.join(__dirname, '..', 'node_modules', 'htmx.org', 'dist', 'htmx.min.js');
|
|---|
| 191 | const dest = path.join(__dirname, 'assets', 'js', 'htmx.min.js');
|
|---|
| 192 | try {
|
|---|
| 193 | const srcStat = fs.statSync(src);
|
|---|
| 194 | const destStat = fs.existsSync(dest) ? fs.statSync(dest) : null;
|
|---|
| 195 | if (!destStat || destStat.size !== srcStat.size) {
|
|---|
| 196 | fs.copyFileSync(src, dest);
|
|---|
| 197 | console.log(`📦 HTMX bundled locally: ${srcStat.size} bytes`);
|
|---|
| 198 | }
|
|---|
| 199 | } catch (e) {
|
|---|
| 200 | console.warn('⚠️ Could not bundle HTMX:', e.message, '— run `npm install`');
|
|---|
| 201 | }
|
|---|
| 202 | })();
|
|---|
| 203 |
|
|---|
| [834bcc3] | 204 | // Circle federation: public, site-agnostic endpoints (/.klonkt/*).
|
|---|
| 205 | // Before resolveSite/theme — they don't need a site context.
|
|---|
| [b300682] | 206 | app.use(federationRoutes);
|
|---|
| 207 |
|
|---|
| [7bc636b] | 208 | app.use(resolveSite);
|
|---|
| 209 | app.use(loadAudioTracks);
|
|---|
| 210 | app.use(loadTheme);
|
|---|
| 211 |
|
|---|
| [834bcc3] | 212 | // Lightweight CSRF defense: reject cross-origin state-mutating requests.
|
|---|
| 213 | // Same-origin forms + HTMX send a matching Origin; missing Origin is allowed
|
|---|
| 214 | // through (non-browser clients). sameSite:'lax' on the session cookie is the
|
|---|
| 215 | // second layer. (Does not apply to GET/HEAD/OPTIONS.)
|
|---|
| [9e27d64] | 216 | app.use((req, res, next) => {
|
|---|
| 217 | if (req.method === 'GET' || req.method === 'HEAD' || req.method === 'OPTIONS') return next();
|
|---|
| 218 | const origin = req.get('origin');
|
|---|
| [834bcc3] | 219 | if (!origin) return next(); // no Origin → no browser CSRF vector
|
|---|
| [9e27d64] | 220 | let originHost;
|
|---|
| 221 | try { originHost = new URL(origin).host; } catch { return res.status(403).send('Ongeldige origin'); }
|
|---|
| 222 | if (originHost !== req.get('host')) return res.status(403).send('Cross-origin request geweigerd');
|
|---|
| 223 | next();
|
|---|
| 224 | });
|
|---|
| 225 |
|
|---|
| [834bcc3] | 226 | // Viewer accounts: may view everything (including Admin), change nothing. This is
|
|---|
| 227 | // the ONLY write gate — fail-closed, before all route handlers. Every state-mutating
|
|---|
| 228 | // method is rejected (the login POST sets the session after this guard, so it is
|
|---|
| 229 | // not affected). Instead of raw 403 text we render a clean page (or, for HTMX,
|
|---|
| 230 | // a swapped-in message).
|
|---|
| [640b39c] | 231 | app.use((req, res, next) => {
|
|---|
| [8afbdd6] | 232 | const mutating = req.method !== 'GET' && req.method !== 'HEAD' && req.method !== 'OPTIONS';
|
|---|
| 233 | if (mutating && isViewer(req.session?.user)) {
|
|---|
| 234 | if (req.headers['hx-request'] === 'true') {
|
|---|
| [834bcc3] | 235 | // htmx doesn't swap on 4xx; send 200 + retarget so the message appears in #pcms-main.
|
|---|
| [8afbdd6] | 236 | res.setHeader('HX-Retarget', '#pcms-main');
|
|---|
| 237 | res.setHeader('HX-Reswap', 'innerHTML');
|
|---|
| 238 | res.status(200);
|
|---|
| 239 | } else {
|
|---|
| 240 | res.status(403);
|
|---|
| 241 | }
|
|---|
| 242 | return renderPage(req, res, 'pages/viewer-blocked', {
|
|---|
| 243 | pageTitle: 'Kijker-modus',
|
|---|
| 244 | bodyClass: 'on-special',
|
|---|
| 245 | });
|
|---|
| [640b39c] | 246 | }
|
|---|
| 247 | next();
|
|---|
| 248 | });
|
|---|
| 249 |
|
|---|
| [7bc636b] | 250 | app.use('/auth', authRoutes);
|
|---|
| 251 | app.use('/account', accountRoutes);
|
|---|
| [c9c6a2d] | 252 | app.use('/notifications', notificationsRoutes);
|
|---|
| [cb01666] | 253 | if (audioEnabled()) {
|
|---|
| 254 | app.use('/admin/audio', adminAudioRoutes);
|
|---|
| 255 | app.use('/admin/playlists', adminPlaylistsRoutes);
|
|---|
| 256 | }
|
|---|
| [7bc636b] | 257 | app.use('/admin/sites', adminSitesRoutes);
|
|---|
| 258 | app.use('/admin/users', adminUsersRoutes);
|
|---|
| 259 | app.use('/admin/comments', adminCommentsRoutes);
|
|---|
| [6351545] | 260 | app.use('/admin/settings', adminSettingsRoutes);
|
|---|
| [6623453] | 261 | app.use('/admin/seo', adminSeoRoutes);
|
|---|
| [0091cb7] | 262 | app.use('/admin/circle', adminCircleRoutes);
|
|---|
| [ff08153] | 263 | app.use('/admin/updates', adminUpdatesRoutes);
|
|---|
| [1b4d5dd] | 264 | app.use('/admin/patreon', adminPatreonRoutes);
|
|---|
| [d549549] | 265 | app.use('/admin/stats', adminStatsRoutes);
|
|---|
| [2e247e4] | 266 | app.use('/admin/newsletter', adminNewsletterRoutes);
|
|---|
| [8d32dcf] | 267 | app.use('/admin/shows', adminShowsRoutes);
|
|---|
| [9d9f3c1] | 268 | app.use('/admin/epk', adminEpkRoutes);
|
|---|
| [7bc636b] | 269 | app.use('/admin', adminRoutes);
|
|---|
| [cb01666] | 270 | if (audioEnabled()) app.use('/audio', audioRoutes);
|
|---|
| [7bc636b] | 271 | app.use('/search', searchRoutes);
|
|---|
| 272 | app.use('/comments', commentsRoutes);
|
|---|
| 273 | app.use('/tag', tagsRoutes);
|
|---|
| 274 | app.use('/type', typesRoutes);
|
|---|
| 275 | app.use('/users', usersRoutes);
|
|---|
| 276 | // Feed/sitemap routes are mounted at root because they're at well-known paths
|
|---|
| 277 | app.use('/', feedRoutes);
|
|---|
| [834bcc3] | 278 | app.use('/leden', artistsRoutes); // searchable member directory (hub only; solo: next())
|
|---|
| [a1c8cb8] | 279 | app.get('/artiesten', (req, res) => res.redirect(301, req.originalUrl.replace(/^\/artiesten/, '/leden'))); // oude URL -> /leden
|
|---|
| [bf61be7] | 280 | app.use('/', hubRoutes); // hub-overview op '/' (solo: next() -> postsRoutes)
|
|---|
| [0091cb7] | 281 | app.use('/', circleRoutes); // /cirkel-feed (solo/hub: next() -> postsRoutes)
|
|---|
| [255e3d3] | 282 | app.use('/', epkRoutes); // /pers perskit (premium; niet-premium: next() -> 404)
|
|---|
| [2e247e4] | 283 | app.use('/', newsletterRoutes); // /nieuwsbrief in/uitschrijven (premium; niet-premium: next())
|
|---|
| [cb01666] | 284 | if (audioEnabled()) app.use('/', downloadRoutes); // /downloads + /download/:id (audio; lite: uit)
|
|---|
| [37edecd] | 285 | app.use('/', linkbioRoutes); // /links link-in-bio + klikstats (premium)
|
|---|
| [cb01666] | 286 | if (audioEnabled()) app.use('/', embedRoutes); // /embed inbedbare audiospeler (audio; lite: uit)
|
|---|
| [8d32dcf] | 287 | app.use('/', showsRoutes); // /shows agenda + notify-me (premium)
|
|---|
| [90259da] | 288 | app.use('/', changelogRoutes); // /changelog publieke release-/wijzigingen-pagina
|
|---|
| [03fa548] | 289 | app.use('/', langRoutes); // /lang/:code — interface-taal kiezen (vóór de catch-all)
|
|---|
| [7bc636b] | 290 | app.use('/', postsRoutes);
|
|---|
| 291 |
|
|---|
| 292 | app.get('/manifest.webmanifest', (req, res) => {
|
|---|
| 293 | const site = res.locals.site;
|
|---|
| 294 |
|
|---|
| 295 | // PWA scope: confines installed apps to ONE site. If a user is in the
|
|---|
| 296 | // bedrijf1 PWA and clicks a link to /sites/bedrijf2/..., the browser will
|
|---|
| 297 | // open it in a regular tab (out-of-scope) instead of within the PWA.
|
|---|
| 298 | // Same applies to APK packaging — the WebView is locked to this scope.
|
|---|
| 299 | //
|
|---|
| 300 | // For path-mounted sites: scope = /sites/<slug>/
|
|---|
| 301 | // For root/subdomain sites: scope = /
|
|---|
| 302 | const base = res.locals.siteUrlBase || ''; // '' or '/sites/<slug>'
|
|---|
| 303 | const scope = (base || '') + '/';
|
|---|
| 304 | const startUrl = (base || '') + '/?source=pwa';
|
|---|
| 305 |
|
|---|
| [7007d4c] | 306 | // A stable identity per site so installs don't collide (Chromium uses `id`).
|
|---|
| [834bcc3] | 307 | // NB: changing the id orphans existing PWA installs (no migration carries an
|
|---|
| 308 | // install across an id change) — anyone who already installed the site as a
|
|---|
| 309 | // PWA will need to reinstall once. Data stays server-side, so nothing is lost.
|
|---|
| [7007d4c] | 310 | const idBase = site?.slug ? `klonkt-${site.slug}` : 'klonkt';
|
|---|
| [7bc636b] | 311 |
|
|---|
| 312 | res.set('Cache-Control', 'no-cache');
|
|---|
| 313 | res.json({
|
|---|
| 314 | id: idBase,
|
|---|
| [7007d4c] | 315 | name: site?.title || 'Klonkt',
|
|---|
| [8afbdd6] | 316 | short_name: (site?.title || 'Klonkt').slice(0, 12),
|
|---|
| [7bc636b] | 317 | description: site?.description || site?.tagline || '',
|
|---|
| 318 | scope,
|
|---|
| 319 | start_url: startUrl,
|
|---|
| 320 | display: 'standalone',
|
|---|
| 321 | display_override: ['standalone', 'minimal-ui'],
|
|---|
| 322 | orientation: 'any',
|
|---|
| 323 | background_color: '#1a1a17',
|
|---|
| [dd7e2a2] | 324 | theme_color: site?.accent || '#e8b04b',
|
|---|
| [7bc636b] | 325 | lang: site?.language || 'nl',
|
|---|
| 326 | icons: [
|
|---|
| 327 | { src: '/favicon.svg', sizes: 'any', type: 'image/svg+xml' },
|
|---|
| 328 | { src: '/favicon.ico', sizes: '64x64', type: 'image/x-icon' },
|
|---|
| 329 | ],
|
|---|
| 330 | // Hint to capable browsers: capture all in-scope links inside the PWA
|
|---|
| 331 | capture_links: 'existing-client-navigate',
|
|---|
| 332 | });
|
|---|
| 333 | });
|
|---|
| 334 |
|
|---|
| 335 | // Favicon — served as SVG so it picks up the site's accent color dynamically.
|
|---|
| 336 | // Browsers also request /favicon.ico by convention; we serve the same SVG
|
|---|
| 337 | // content there with a forgiving content-type since modern browsers accept it.
|
|---|
| 338 | function _renderFavicon(res, accent) {
|
|---|
| [9b851e7] | 339 | const safeAccent = /^#[0-9a-fA-F]{3,8}$/.test(accent) ? accent : '#e8b04b';
|
|---|
| [5e95aac] | 340 | // Site mark: rounded square in the site accent + bold white 'K' (Klonkt)
|
|---|
| [7bc636b] | 341 | const svg = `<?xml version="1.0" encoding="UTF-8"?>
|
|---|
| 342 | <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64">
|
|---|
| 343 | <rect width="64" height="64" rx="14" fill="${safeAccent}"/>
|
|---|
| [5e95aac] | 344 | <text x="50%" y="50%" dy="0.35em" text-anchor="middle"
|
|---|
| [b5bae24] | 345 | font-family="Arial, Helvetica, sans-serif"
|
|---|
| [5e95aac] | 346 | font-size="42" font-weight="800" fill="#fff">K</text>
|
|---|
| [7bc636b] | 347 | </svg>`;
|
|---|
| 348 | res.set('Content-Type', 'image/svg+xml');
|
|---|
| 349 | res.set('Cache-Control', 'public, max-age=86400');
|
|---|
| 350 | res.send(svg);
|
|---|
| 351 | }
|
|---|
| 352 |
|
|---|
| 353 | app.get('/favicon.svg', (req, res) => {
|
|---|
| 354 | _renderFavicon(res, res.locals.site?.accent);
|
|---|
| 355 | });
|
|---|
| 356 | app.get('/favicon.ico', (req, res) => {
|
|---|
| 357 | // Browsers requesting .ico will accept SVG content; chrome/firefox both fine.
|
|---|
| 358 | // Keeping the route prevents 404 spam in the console.
|
|---|
| 359 | _renderFavicon(res, res.locals.site?.accent);
|
|---|
| 360 | });
|
|---|
| 361 |
|
|---|
| 362 | app.get('/sw.js', (req, res) => {
|
|---|
| 363 | res.set('Content-Type', 'application/javascript');
|
|---|
| 364 | res.set('Cache-Control', 'no-cache');
|
|---|
| 365 | res.send(`
|
|---|
| [b08b5bc] | 366 | const CACHE_VERSION = 'pcms-v11-' + new Date().toISOString().split('T')[0];
|
|---|
| [7bc636b] | 367 | self.addEventListener('install', e => {
|
|---|
| 368 | e.waitUntil(caches.open(CACHE_VERSION).then(c => c.addAll(['/'])));
|
|---|
| 369 | self.skipWaiting();
|
|---|
| 370 | });
|
|---|
| 371 | self.addEventListener('activate', e => {
|
|---|
| 372 | e.waitUntil(caches.keys().then(keys => Promise.all(
|
|---|
| 373 | keys.filter(k => k !== CACHE_VERSION).map(k => caches.delete(k))
|
|---|
| 374 | )));
|
|---|
| 375 | self.clients.claim();
|
|---|
| 376 | });
|
|---|
| [834bcc3] | 377 | // ONLY intercept navigations (HTML pages) for an offline fallback.
|
|---|
| 378 | // Do NOT touch images, CSS, JS or /media — let the browser handle those natively.
|
|---|
| 379 | // Otherwise a failed network fetch could fall back to an empty cache match
|
|---|
| 380 | // (undefined) and "break" an image on a normal refresh (hard reload bypasses
|
|---|
| 381 | // the SW, which is why that case worked fine).
|
|---|
| [7bc636b] | 382 | self.addEventListener('fetch', e => {
|
|---|
| 383 | if (e.request.method !== 'GET') return;
|
|---|
| [834bcc3] | 384 | if (e.request.mode !== 'navigate') return; // page loads only
|
|---|
| [b08b5bc] | 385 | e.respondWith(
|
|---|
| 386 | fetch(e.request).catch(() => caches.match('/').then(r => r || Response.error()))
|
|---|
| 387 | );
|
|---|
| [7bc636b] | 388 | });
|
|---|
| 389 | `);
|
|---|
| 390 | });
|
|---|
| 391 |
|
|---|
| 392 | process.on('unhandledRejection', (reason) => {
|
|---|
| 393 | console.error('⚠️ Unhandled Rejection:', reason);
|
|---|
| 394 | });
|
|---|
| 395 |
|
|---|
| 396 | app.use((err, req, res, next) => {
|
|---|
| 397 | console.error('❌ Error:', err);
|
|---|
| 398 | res.status(err.status || 500).send(
|
|---|
| 399 | isDev ? `<pre>${err.stack || err.message}</pre>` : 'Internal Server Error'
|
|---|
| 400 | );
|
|---|
| 401 | });
|
|---|
| 402 |
|
|---|
| 403 | app.use((req, res) => {
|
|---|
| [3b6e04a] | 404 | res.status(404);
|
|---|
| [834bcc3] | 405 | // Clean, mobile-friendly 404 via the shell (viewport + nav + site theme).
|
|---|
| 406 | // Falls back to bare HTML if rendering unexpectedly fails.
|
|---|
| [3b6e04a] | 407 | try {
|
|---|
| 408 | return renderPage(req, res, 'pages/404', {
|
|---|
| 409 | pageTitle: '404 — niet gevonden',
|
|---|
| 410 | bodyClass: 'on-special on-404',
|
|---|
| 411 | });
|
|---|
| 412 | } catch (e) {
|
|---|
| 413 | 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>');
|
|---|
| 414 | }
|
|---|
| [7bc636b] | 415 | });
|
|---|
| 416 |
|
|---|
| 417 | server.listen(PORT, () => {
|
|---|
| 418 | console.log('');
|
|---|
| [83faa57] | 419 | console.log('🪶 Klonkt Beta');
|
|---|
| [7bc636b] | 420 | console.log(` http://localhost:${PORT}`);
|
|---|
| 421 | console.log('');
|
|---|
| 422 | console.log(` ✓ Security: Helmet, CSP, secure sessions`);
|
|---|
| 423 | console.log(` ✓ Privacy: Self-hosted fonts, no third-party requests`);
|
|---|
| 424 | console.log(` ✓ Layout: v9 editorial feel (top nav, profile header)`);
|
|---|
| [9e27d64] | 425 | console.log(` ✓ Auth: wachtwoord (beheer) + Google (luisteraars) / logout`);
|
|---|
| [7bc636b] | 426 | console.log(` ✓ Posts: create / edit / view / archive`);
|
|---|
| 427 | console.log('');
|
|---|
| 428 | console.log(` Mode: ${isDev ? 'development' : 'PRODUCTION'}`);
|
|---|
| 429 | console.log('');
|
|---|
| 430 | });
|
|---|
| 431 |
|
|---|
| 432 | export default app;
|
|---|