/** * BlackDice site + CMS server. * * Serves the built site from dist/, the published content document from * CONTENT_DIR, and the small API that /admin writes through. Otherwise * dependency-free (node: built-ins only) so it runs anywhere Node runs — VPS, * container, or behind IIS/nginx as a reverse proxy. The one exception is * sanitize-html: content writes are the actual security boundary (the * browser-side sanitiser in src/cms/sanitise.ts is UX, not enforcement — a * direct API call bypasses it entirely), and a hand-rolled regex HTML parser * is the wrong tool for that job, so a maintained one is used instead. * * node server/index.mjs * * Environment — read from the real process environment in production; for * local dev, .env.local (falling back to .env) is loaded automatically below. * PORT listen port (default 8787) * ADMIN_PASSWORD password for /admin (required — see below) * ALLOW_DEV_PASSWORD set to 1 to accept "blackdice" (local development only) * ADMIN_SECRET token signing secret (default: derived from password) * CONTENT_DIR where published content is kept (default ./content) * DIST_DIR built site to serve (default ./dist) * SITE_URL canonical origin for sitemap.xml (default https://www.blackdice.ai) * TRUST_PROXY trust X-Forwarded-For's first hop for login rate limiting * (only set this if a reverse proxy you control strips/sets it) */ import http from 'node:http' import fs from 'node:fs' import fsp from 'node:fs/promises' import path from 'node:path' import crypto from 'node:crypto' import { fileURLToPath } from 'node:url' import sanitizeHtml from 'sanitize-html' const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') // Local dev convenience: load .env.local (or .env) into process.env if present. // Production deploys set real environment variables and don't need this — // missing files are silently ignored. for (const name of ['.env.local', '.env']) { try { process.loadEnvFile(path.join(ROOT, name)) break } catch { /* file doesn't exist — try the next one */ } } const PORT = Number(process.env.PORT || 8787) const CONTENT_DIR = path.resolve(process.env.CONTENT_DIR || path.join(ROOT, 'content')) const DIST_DIR = path.resolve(process.env.DIST_DIR || path.join(ROOT, 'dist')) const UPLOAD_DIR = path.join(CONTENT_DIR, 'uploads') const VERSION_DIR = path.join(CONTENT_DIR, 'versions') const CONTENT_FILE = path.join(CONTENT_DIR, 'site-content.json') const LEADS_FILE = path.join(CONTENT_DIR, 'leads.jsonl') const SITE_URL = (process.env.SITE_URL || 'https://www.blackdice.ai').replace(/\/+$/, '') const TRUST_PROXY = process.env.TRUST_PROXY === '1' || process.env.TRUST_PROXY === 'true' const DEV_PASSWORD = 'blackdice' const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || DEV_PASSWORD const ALLOW_DEV_PASSWORD = process.env.ALLOW_DEV_PASSWORD === '1' || process.env.ALLOW_DEV_PASSWORD === 'true' // Safe-by-default: refusing to start on the factory password used to depend on // NODE_ENV=production, which meant the unsafe state was whatever you get from // forgetting to set an environment variable. Now the safe state is the default; // local development opts in explicitly. if (ADMIN_PASSWORD === DEV_PASSWORD && !ALLOW_DEV_PASSWORD) { console.error('✗ ADMIN_PASSWORD is unset (or "blackdice"). Refusing to start.') console.error(' Set a real ADMIN_PASSWORD — see .env.example / docs/DEPLOYMENT.md.') console.error(' For local development only, set ALLOW_DEV_PASSWORD=1 to accept "blackdice".') process.exit(1) } // Mixed into session signing so every server restart invalidates outstanding // sessions, independent of ADMIN_PASSWORD/ADMIN_SECRET (which are otherwise // stable across restarts and can't be rotated without changing the password). const SESSION_EPOCH = crypto.randomBytes(16).toString('hex') const SECRET = (process.env.ADMIN_SECRET || crypto.createHash('sha256').update('bd:' + ADMIN_PASSWORD).digest('hex')) + SESSION_EPOCH const SESSION_MS = 4 * 60 * 60 * 1000 const MAX_BODY = 32 * 1024 * 1024 // uploads arrive as data URLs const KEEP_VERSIONS = 60 for (const dir of [CONTENT_DIR, UPLOAD_DIR, VERSION_DIR]) fs.mkdirSync(dir, { recursive: true }) // ── Auth ─────────────────────────────────────────────────────────────────────── const sign = (payload) => crypto.createHmac('sha256', SECRET).update(String(payload)).digest('base64url') // Hashing both sides to a fixed length before the timing-safe compare means the // two buffers are always equal-length, so there's no length short-circuit to // leak the real password's length through response timing. function secretsEqual(a, b) { const ha = crypto.createHash('sha256').update(a).digest() const hb = crypto.createHash('sha256').update(b).digest() return crypto.timingSafeEqual(ha, hb) } function issueToken() { const exp = Date.now() + SESSION_MS return { token: `${exp}.${sign(exp)}`, expiresAt: exp } } function validToken(token) { const [exp, sig] = String(token || '').split('.') if (!exp || !sig || Number(exp) < Date.now()) return false const expected = sign(exp) const a = Buffer.from(sig) const b = Buffer.from(expected) return a.length === b.length && crypto.timingSafeEqual(a, b) } const bearer = (req) => (req.headers.authorization || '').replace(/^Bearer\s+/i, '') const isAuthed = (req) => validToken(bearer(req)) // Only honour X-Forwarded-For when TRUST_PROXY is set — otherwise a client can // spoof it to dodge (or trigger) the login throttle below. function clientIp(req) { if (TRUST_PROXY) { const fwd = String(req.headers['x-forwarded-for'] || '').split(',')[0].trim() if (fwd) return fwd } return req.socket.remoteAddress || 'unknown' } // Crude but effective throttle: 10 failures per IP per 15 minutes. const THROTTLE_WINDOW_MS = 15 * 60 * 1000 const failures = new Map() function tooManyAttempts(ip) { const rec = failures.get(ip) if (!rec) return false if (Date.now() - rec.first > THROTTLE_WINDOW_MS) { failures.delete(ip) return false } return rec.count >= 10 } function noteFailure(ip) { const rec = failures.get(ip) if (!rec || Date.now() - rec.first > THROTTLE_WINDOW_MS) failures.set(ip, { first: Date.now(), count: 1 }) else rec.count++ } // Same shape, separate budget: unauthenticated public form submissions. const LEADS_WINDOW_MS = 10 * 60 * 1000 const leadAttempts = new Map() function tooManyLeads(ip) { const rec = leadAttempts.get(ip) if (!rec) return false if (Date.now() - rec.first > LEADS_WINDOW_MS) { leadAttempts.delete(ip) return false } return rec.count >= 8 } function noteLead(ip) { const rec = leadAttempts.get(ip) if (!rec || Date.now() - rec.first > LEADS_WINDOW_MS) leadAttempts.set(ip, { first: Date.now(), count: 1 }) else rec.count++ } // Both maps are IP-keyed and only ever grow while an IP is mid-window; sweep // stale entries periodically so a long-running process doesn't accumulate them. setInterval(() => { const now = Date.now() for (const [ip, rec] of failures) if (now - rec.first > THROTTLE_WINDOW_MS) failures.delete(ip) for (const [ip, rec] of leadAttempts) if (now - rec.first > LEADS_WINDOW_MS) leadAttempts.delete(ip) }, THROTTLE_WINDOW_MS).unref() // ── Helpers ──────────────────────────────────────────────────────────────────── // script-src has no 'unsafe-inline': the legacy markup's onclick="" attributes // were migrated to a single delegated listener (siteController.js), and no // inline