CI / build (push) Has been cancelled
Fixes the two High-severity findings from Isaac Hague's 19/08/2026 review (F-01, F-02) plus F-03 through F-09: - F-01: content writes are now sanitised server-side (sanitize-html) as the real security boundary — the browser-side sanitiser is UX, not enforcement, and a direct API write bypassed it entirely. Also closes the javascript: href gap in sanitiseInline(). - F-02: refusing the factory admin password no longer depends on NODE_ENV; it's the unconditional default now, with an explicit ALLOW_DEV_PASSWORD=1 opt-in for local dev. - F-03: adds CSP (report-only — the legacy inline onclick="" handlers would break under enforcement) and HSTS, in both server/index.mjs and vercel.json. - F-04/F-05: rate-limits /api/leads and rotates leads.jsonl past 5MB; CSV export neutralises leading =+-@ so exports can't carry live formulas. - F-06: sessions drop from 12h to 4h and are tied to a per-boot random epoch, so a restart now actually revokes outstanding tokens. - F-07/F-08/F-09: generic messages on 5xx, fixed-length password comparison (no more length disclosure via the short-circuit), periodic throttle-map cleanup. F-10 (dependency advisories): applied the two non-breaking patches (nanoid, postcss); the vite/react-router-dom major bumps are left for a separate pass, per the report's own recommendation. F-11 (PDF Content-Disposition) and a CAPTCHA/honeypot on the enquiry form are deliberately left open — both are product/UX calls, not pure security fixes. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
561 lines
24 KiB
JavaScript
561 lines
24 KiB
JavaScript
/**
|
|
* 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 ────────────────────────────────────────────────────────────────────
|
|
// CSP ships in report-only mode: the legacy markup relies on inline onclick=""
|
|
// handlers, so enforcing script-src today would break navigation. Report-only
|
|
// costs nothing (it can't break the site) and surfaces exactly what a real
|
|
// policy needs to allow before anyone flips it to enforcing.
|
|
const CSP = [
|
|
"default-src 'self'",
|
|
"script-src 'self' 'unsafe-inline' https://*.hubspot.com https://*.hs-scripts.com https://*.hsforms.net https://*.usemessages.com",
|
|
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com",
|
|
"font-src 'self' https://fonts.gstatic.com",
|
|
"img-src 'self' data: https:",
|
|
"media-src 'self'",
|
|
"connect-src 'self' https://*.hubspot.com https://*.hsforms.com https://*.hs-analytics.net",
|
|
"frame-src https://*.hubspot.com https://*.hsforms.com",
|
|
"object-src 'none'",
|
|
"base-uri 'self'",
|
|
"frame-ancestors 'self'",
|
|
].join('; ')
|
|
|
|
const SECURITY_HEADERS = {
|
|
'X-Content-Type-Options': 'nosniff',
|
|
'X-Frame-Options': 'SAMEORIGIN',
|
|
'Referrer-Policy': 'strict-origin-when-cross-origin',
|
|
'Permissions-Policy': 'geolocation=(), camera=(), microphone=()',
|
|
'Content-Security-Policy-Report-Only': CSP,
|
|
// Harmless (and ignored) over plain HTTP; takes effect once a browser sees it over TLS.
|
|
'Strict-Transport-Security': 'max-age=63072000; includeSubDomains',
|
|
}
|
|
|
|
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',
|
|
...SECURITY_HEADERS,
|
|
...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)
|
|
|
|
// Unauthenticated flooding (even rate-limited) would otherwise grow this file
|
|
// without bound. Roll it over rather than letting a single flat file take the
|
|
// whole disk; the admin's /api/leads GET only ever reads the last 200 anyway.
|
|
const LEADS_MAX_BYTES = 5 * 1024 * 1024
|
|
async function rotateLeadsIfLarge() {
|
|
try {
|
|
const { size } = await fsp.stat(LEADS_FILE)
|
|
if (size > LEADS_MAX_BYTES) await fsp.rename(LEADS_FILE, `${LEADS_FILE}.${stamp()}.bak`)
|
|
} catch {
|
|
/* no existing file yet */
|
|
}
|
|
}
|
|
|
|
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 <video> seeking). */
|
|
async function serveFile(req, res, file, { immutable = false } = {}) {
|
|
let stat
|
|
try {
|
|
stat = await fsp.stat(file)
|
|
if (!stat.isFile()) return false
|
|
} catch {
|
|
return false
|
|
}
|
|
const type = MIME[path.extname(file).toLowerCase()] || 'application/octet-stream'
|
|
const cache = immutable ? 'public, max-age=31536000, immutable' : 'public, max-age=300'
|
|
const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range || '')
|
|
if (range) {
|
|
const start = range[1] ? Number(range[1]) : 0
|
|
const end = range[2] ? Number(range[2]) : stat.size - 1
|
|
res.writeHead(206, {
|
|
'Content-Type': type,
|
|
'Content-Range': `bytes ${start}-${end}/${stat.size}`,
|
|
'Accept-Ranges': 'bytes',
|
|
'Content-Length': end - start + 1,
|
|
'Cache-Control': cache,
|
|
...SECURITY_HEADERS,
|
|
})
|
|
fs.createReadStream(file, { start, end }).pipe(res)
|
|
return true
|
|
}
|
|
res.writeHead(200, {
|
|
'Content-Type': type,
|
|
'Content-Length': stat.size,
|
|
'Accept-Ranges': 'bytes',
|
|
'Cache-Control': cache,
|
|
...SECURITY_HEADERS,
|
|
})
|
|
fs.createReadStream(file).pipe(res)
|
|
return true
|
|
}
|
|
|
|
/** Resolves a URL path inside a root directory, refusing traversal. */
|
|
function safeJoin(root, urlPath) {
|
|
const decoded = decodeURIComponent(urlPath.split('?')[0])
|
|
const target = path.resolve(root, '.' + path.posix.normalize(decoded))
|
|
return target === root || target.startsWith(root + path.sep) ? target : null
|
|
}
|
|
|
|
// ── Content sanitisation ─────────────────────────────────────────────────────────
|
|
// Mirrors the allow-lists in src/cms/sanitise.ts. Two profiles: block-level
|
|
// article bodies, and inline rich text (the headline-style fields written
|
|
// into data-cms="" spans in the legacy markup — see src/cms/store.tsx).
|
|
const externalLink = (tagName, attribs) =>
|
|
/^https?:\/\//i.test(attribs.href || '') ? { tagName, attribs: { ...attribs, target: '_blank', rel: 'noopener' } } : { tagName, attribs }
|
|
|
|
const BODY_SANITIZE_OPTS = {
|
|
allowedTags: [
|
|
'h2', 'h3', 'h4', 'p', 'ul', 'ol', 'li', 'strong', 'em', 'u', 'a', 'br',
|
|
'blockquote', 'img', 'figure', 'figcaption', 'table', 'thead', 'tbody', 'tr', 'td', 'th', 'hr',
|
|
],
|
|
allowedAttributes: { a: ['href', 'target', 'rel'], img: ['src', 'alt'] },
|
|
allowedSchemes: ['http', 'https', 'mailto'],
|
|
transformTags: { h1: 'h2', h5: 'h4', h6: 'h4', b: 'strong', i: 'em', a: externalLink },
|
|
}
|
|
|
|
const INLINE_SANITIZE_OPTS = {
|
|
allowedTags: ['strong', 'em', 'b', 'i', 'u', 'br', 'span', 'a', 'sup', 'sub'],
|
|
allowedAttributes: { a: ['href'] },
|
|
allowedSchemes: ['http', 'https', 'mailto'],
|
|
}
|
|
|
|
const sanitiseBodyServer = (html) => sanitizeHtml(String(html ?? ''), BODY_SANITIZE_OPTS)
|
|
const sanitiseInlineServer = (html) => sanitizeHtml(String(html ?? ''), INLINE_SANITIZE_OPTS)
|
|
|
|
// ── API ────────────────────────────────────────────────────────────────────────
|
|
const DATA_URL = /^data:([a-z0-9.+/-]+);base64,([A-Za-z0-9+/=\s]+)$/i
|
|
// SVG deliberately excluded: it can carry <script>, and uploads are served from
|
|
// this origin with no sandboxing, so allowing it would be a stored-XSS vector.
|
|
const UPLOAD_EXT = {
|
|
'image/jpeg': '.jpg', 'image/png': '.png', 'image/webp': '.webp', 'image/gif': '.gif',
|
|
'video/mp4': '.mp4', 'video/webm': '.webm', 'application/pdf': '.pdf',
|
|
}
|
|
|
|
async function handleApi(req, res, url) {
|
|
const route = url.pathname
|
|
const ip = clientIp(req)
|
|
|
|
if (route === '/api/health') return send(res, 200, { ok: true, published: fs.existsSync(CONTENT_FILE) })
|
|
|
|
if (route === '/api/login' && req.method === 'POST') {
|
|
if (tooManyAttempts(ip)) return send(res, 429, { error: 'Too many attempts. Try again later.' })
|
|
const { password } = await readBody(req)
|
|
const ok = secretsEqual(Buffer.from(String(password || '')), Buffer.from(ADMIN_PASSWORD))
|
|
if (!ok) {
|
|
noteFailure(ip)
|
|
await new Promise((r) => setTimeout(r, 400))
|
|
return send(res, 401, { error: 'Incorrect password.' })
|
|
}
|
|
failures.delete(ip)
|
|
return send(res, 200, { ...issueToken(), usingDefaultPassword: ADMIN_PASSWORD === DEV_PASSWORD })
|
|
}
|
|
|
|
if (route === '/api/content' && req.method === 'GET') {
|
|
const doc = await readContent()
|
|
return send(res, 200, doc || { published: false })
|
|
}
|
|
|
|
if (route === '/api/leads' && req.method === 'POST') {
|
|
if (tooManyLeads(ip)) return send(res, 429, { error: 'Too many submissions. Try again shortly.' })
|
|
const body = await readBody(req)
|
|
const lead = {
|
|
at: new Date().toISOString(),
|
|
form: String(body.form || 'enquiry').slice(0, 40),
|
|
name: String(body.name || '').slice(0, 200),
|
|
email: String(body.email || '').slice(0, 200),
|
|
company: String(body.company || '').slice(0, 200),
|
|
phone: String(body.phone || '').slice(0, 60),
|
|
message: String(body.message || '').slice(0, 4000),
|
|
page: String(body.page || '').slice(0, 300),
|
|
ip,
|
|
}
|
|
if (!lead.email) return send(res, 400, { error: 'email required' })
|
|
noteLead(ip)
|
|
await rotateLeadsIfLarge()
|
|
await fsp.appendFile(LEADS_FILE, JSON.stringify(lead) + '\n')
|
|
return send(res, 200, { ok: true })
|
|
}
|
|
|
|
// ── everything below requires a session ──
|
|
if (!isAuthed(req)) return send(res, 401, { error: 'Not signed in.' })
|
|
|
|
if (route === '/api/session') return send(res, 200, { ok: true })
|
|
|
|
if (route === '/api/content' && req.method === 'POST') {
|
|
const doc = await readBody(req)
|
|
if (doc?.format !== 'blackdice-react-content') return send(res, 400, { error: 'Unexpected content format.' })
|
|
if (!Array.isArray(doc.posts)) return send(res, 400, { error: 'posts must be an array.' })
|
|
// The security boundary: src/cms/sanitise.ts only runs in the browser at edit
|
|
// time, so a request straight to this endpoint would otherwise store raw HTML
|
|
// verbatim. Re-sanitise here regardless of what the client already did.
|
|
doc.posts = doc.posts.map((p) => ({ ...p, body: sanitiseBodyServer(p?.body) }))
|
|
if (doc.content && typeof doc.content === 'object') {
|
|
doc.content = Object.fromEntries(Object.entries(doc.content).map(([id, html]) => [id, sanitiseInlineServer(html)]))
|
|
}
|
|
const previous = await readContent()
|
|
if (previous) {
|
|
await fsp.writeFile(path.join(VERSION_DIR, `site-content-${stamp()}.json`), JSON.stringify(previous))
|
|
const files = (await fsp.readdir(VERSION_DIR)).filter((f) => f.endsWith('.json')).sort()
|
|
for (const old of files.slice(0, Math.max(0, files.length - KEEP_VERSIONS))) {
|
|
await fsp.rm(path.join(VERSION_DIR, old), { force: true })
|
|
}
|
|
}
|
|
doc.savedAt = new Date().toISOString()
|
|
const tmp = CONTENT_FILE + '.tmp'
|
|
await fsp.writeFile(tmp, JSON.stringify(doc, null, 2))
|
|
await fsp.rename(tmp, CONTENT_FILE) // atomic: readers never see a half-written file
|
|
return send(res, 200, { ok: true, savedAt: doc.savedAt })
|
|
}
|
|
|
|
if (route === '/api/versions' && req.method === 'GET') {
|
|
const files = (await fsp.readdir(VERSION_DIR)).filter((f) => f.endsWith('.json')).sort().reverse()
|
|
const list = await Promise.all(
|
|
files.map(async (name) => ({ name, size: (await fsp.stat(path.join(VERSION_DIR, name))).size })),
|
|
)
|
|
return send(res, 200, { versions: list })
|
|
}
|
|
|
|
if (route.startsWith('/api/versions/') && req.method === 'GET') {
|
|
const name = path.basename(route.slice('/api/versions/'.length))
|
|
if (!/^site-content-[\w-]+\.json$/.test(name)) return send(res, 400, { error: 'bad version name' })
|
|
try {
|
|
return send(res, 200, JSON.parse(await fsp.readFile(path.join(VERSION_DIR, name), 'utf8')))
|
|
} catch {
|
|
return send(res, 404, { error: 'not found' })
|
|
}
|
|
}
|
|
|
|
if (route === '/api/upload' && req.method === 'POST') {
|
|
const { name, dataUrl } = await readBody(req)
|
|
const parsed = DATA_URL.exec(String(dataUrl || ''))
|
|
if (!parsed) return send(res, 400, { error: 'Expected a base64 data URL.' })
|
|
const ext = UPLOAD_EXT[parsed[1].toLowerCase()]
|
|
if (!ext) return send(res, 415, { error: `Unsupported type: ${parsed[1]}` })
|
|
const base = String(name || 'asset')
|
|
.replace(/\.[^.]*$/, '')
|
|
.toLowerCase()
|
|
.replace(/[^a-z0-9]+/g, '-')
|
|
.replace(/^-+|-+$/g, '')
|
|
.slice(0, 60) || 'asset'
|
|
const file = `${stamp()}-${base}${ext}`
|
|
await fsp.writeFile(path.join(UPLOAD_DIR, file), Buffer.from(parsed[2], 'base64'))
|
|
return send(res, 200, { url: `/content/uploads/${file}` })
|
|
}
|
|
|
|
if (route === '/api/uploads' && req.method === 'GET') {
|
|
const files = (await fsp.readdir(UPLOAD_DIR)).sort().reverse()
|
|
return send(res, 200, { uploads: files.map((f) => ({ name: f, url: `/content/uploads/${f}` })) })
|
|
}
|
|
|
|
if (route === '/api/leads' && req.method === 'GET') {
|
|
let text = ''
|
|
try {
|
|
text = await fsp.readFile(LEADS_FILE, 'utf8')
|
|
} catch {}
|
|
const leads = text.trim().split('\n').filter(Boolean).map((l) => {
|
|
try { return JSON.parse(l) } catch { return null }
|
|
}).filter(Boolean).reverse().slice(0, 200)
|
|
return send(res, 200, { leads })
|
|
}
|
|
|
|
return send(res, 404, { error: 'Unknown endpoint' })
|
|
}
|
|
|
|
// ── sitemap / robots ───────────────────────────────────────────────────────────
|
|
const SITE_PATHS = [
|
|
['/', '1.0'], ['/mobile-sdk', '0.9'], ['/dns-protect', '0.9'], ['/halo-cpe', '0.9'],
|
|
['/for-operators', '0.8'], ['/financial-services', '0.8'], ['/why-blackdice', '0.7'],
|
|
['/news', '0.8'], ['/investors', '0.6'], ['/contact', '0.7'],
|
|
]
|
|
|
|
async function sitemap() {
|
|
const doc = await readContent()
|
|
let posts = doc?.posts
|
|
if (!posts) {
|
|
// Fall back to the factory content shipped in the build.
|
|
try {
|
|
posts = JSON.parse(await fsp.readFile(path.join(ROOT, 'src/cms/generated/seedContent.json'), 'utf8')).posts
|
|
} catch {
|
|
posts = []
|
|
}
|
|
}
|
|
const today = new Date().toISOString().slice(0, 10)
|
|
const urls = [
|
|
...SITE_PATHS.map(([p, pri]) => ({ loc: SITE_URL + p, lastmod: today, pri })),
|
|
...posts
|
|
.filter((p) => p.status !== 'draft')
|
|
.map((p) => ({ loc: `${SITE_URL}/blog/${p.slug}`, lastmod: (p.updatedAt || p.date || today).slice(0, 10), pri: '0.6' })),
|
|
]
|
|
return (
|
|
'<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">\n' +
|
|
urls
|
|
.map((u) => ` <url>\n <loc>${u.loc}</loc>\n <lastmod>${u.lastmod}</lastmod>\n <priority>${u.pri}</priority>\n </url>`)
|
|
.join('\n') +
|
|
'\n</urlset>\n'
|
|
)
|
|
}
|
|
|
|
// ── Server ─────────────────────────────────────────────────────────────────────
|
|
const server = http.createServer(async (req, res) => {
|
|
const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`)
|
|
try {
|
|
if (url.pathname.startsWith('/api/')) return await handleApi(req, res, url)
|
|
|
|
if (url.pathname === '/sitemap.xml') {
|
|
return send(res, 200, await sitemap(), { 'Content-Type': 'application/xml; charset=utf-8', 'Cache-Control': 'public, max-age=3600' })
|
|
}
|
|
if (url.pathname === '/robots.txt') {
|
|
return send(res, 200, `User-agent: *\nAllow: /\n\nSitemap: ${SITE_URL}/sitemap.xml\n`)
|
|
}
|
|
|
|
// Uploaded media lives outside the build so publishing never overwrites it.
|
|
if (url.pathname.startsWith('/content/uploads/')) {
|
|
const file = safeJoin(UPLOAD_DIR, url.pathname.slice('/content/uploads'.length))
|
|
if (file && (await serveFile(req, res, file, { immutable: true }))) return
|
|
return send(res, 404, 'Not found')
|
|
}
|
|
// The published content document, read by the site on load.
|
|
if (url.pathname === '/content/site-content.json') {
|
|
const doc = await readContent()
|
|
return send(res, 200, doc || { published: false })
|
|
}
|
|
|
|
if (req.method !== 'GET' && req.method !== 'HEAD') return send(res, 405, 'Method not allowed')
|
|
|
|
const asset = safeJoin(DIST_DIR, url.pathname)
|
|
if (asset) {
|
|
const immutable = url.pathname.startsWith('/assets/')
|
|
if (await serveFile(req, res, asset, { immutable })) return
|
|
if (await serveFile(req, res, path.join(asset, 'index.html'))) return
|
|
}
|
|
// SPA fallback — every real URL (/mobile-sdk, /blog/slug, /admin) boots the app.
|
|
if (await serveFile(req, res, path.join(DIST_DIR, 'index.html'))) return
|
|
return send(res, 404, 'Not found — run `npm run build` first.')
|
|
} catch (err) {
|
|
const status = err?.status || 500
|
|
// Below 500 the message is one we deliberately threw ourselves (readBody's
|
|
// "invalid JSON", "payload too large") — safe to show. 500s are unexpected
|
|
// and may carry internal detail (stack traces, file paths), so log them and
|
|
// return a generic message instead.
|
|
if (status >= 500) {
|
|
console.error(err)
|
|
return send(res, status, { error: 'Server error' })
|
|
}
|
|
return send(res, status, { error: err?.message || 'Error' })
|
|
}
|
|
})
|
|
|
|
server.listen(PORT, () => {
|
|
console.log(`BlackDice server → http://localhost:${PORT}`)
|
|
console.log(` content dir ${CONTENT_DIR}`)
|
|
console.log(` serving ${DIST_DIR}`)
|
|
if (ADMIN_PASSWORD === DEV_PASSWORD) {
|
|
console.log(` ⚠ ADMIN_PASSWORD is unset — /admin accepts "${DEV_PASSWORD}". Set it before deploying.`)
|
|
}
|
|
})
|