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