/** * 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. Dependency-free * (node: built-ins only) so it runs anywhere Node runs — VPS, container, or * behind IIS/nginx as a reverse proxy. * * node server/index.mjs * * Environment * PORT listen port (default 8787) * ADMIN_PASSWORD password for /admin (required in production) * 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) */ 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' const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') 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 DEV_PASSWORD = 'blackdice' const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || DEV_PASSWORD const SECRET = process.env.ADMIN_SECRET || crypto.createHash('sha256').update('bd:' + ADMIN_PASSWORD).digest('hex') const SESSION_MS = 12 * 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') 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)) // Crude but effective throttle: 10 failures per IP per 15 minutes. const failures = new Map() function tooManyAttempts(ip) { const rec = failures.get(ip) if (!rec) return false if (Date.now() - rec.first > 15 * 60 * 1000) { failures.delete(ip) return false } return rec.count >= 10 } function noteFailure(ip) { const rec = failures.get(ip) if (!rec || Date.now() - rec.first > 15 * 60 * 1000) failures.set(ip, { first: Date.now(), count: 1 }) else rec.count++ } // ── Helpers ──────────────────────────────────────────────────────────────────── const send = (res, status, body, headers = {}) => { const payload = typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body) res.writeHead(status, { 'Content-Type': typeof body === 'object' && !Buffer.isBuffer(body) ? 'application/json' : 'text/plain; charset=utf-8', 'Cache-Control': 'no-store', ...headers, }) res.end(payload) } function readBody(req) { return new Promise((resolve, reject) => { let size = 0 const chunks = [] req.on('data', (c) => { size += c.length if (size > MAX_BODY) { reject(Object.assign(new Error('payload too large'), { status: 413 })) req.destroy() return } chunks.push(c) }) req.on('end', () => { try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}) } catch { reject(Object.assign(new Error('invalid JSON'), { status: 400 })) } }) req.on('error', reject) }) } const readContent = async () => { try { return JSON.parse(await fsp.readFile(CONTENT_FILE, 'utf8')) } catch { return null } } const stamp = () => new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19) const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json; charset=utf-8', '.svg': 'image/svg+xml', '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg', '.webp': 'image/webp', '.gif': 'image/gif', '.ico': 'image/x-icon', '.mp4': 'video/mp4', '.webm': 'video/webm', '.woff2': 'font/woff2', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8', '.pdf': 'application/pdf', } /** Serves a file with range support (needed for