Address High/Medium findings from the web app security assessment
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>
This commit is contained in:
2026-08-19 18:08:24 +05:00
co-authored by Claude Sonnet 5
parent 5570eb0a9d
commit 28d0addfc0
8 changed files with 366 additions and 60 deletions
+147 -26
View File
@@ -2,22 +2,27 @@
* 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.
* 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 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)
* 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)
* 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'
@@ -25,6 +30,7 @@ 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)), '..')
@@ -52,13 +58,23 @@ const TRUST_PROXY = process.env.TRUST_PROXY === '1' || process.env.TRUST_PROXY =
const DEV_PASSWORD = 'blackdice'
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || DEV_PASSWORD
if (process.env.NODE_ENV === 'production' && ADMIN_PASSWORD === DEV_PASSWORD) {
console.error('✗ ADMIN_PASSWORD is unset (or "blackdice") with NODE_ENV=production. Refusing to start.')
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)
}
const SECRET = process.env.ADMIN_SECRET || crypto.createHash('sha256').update('bd:' + ADMIN_PASSWORD).digest('hex')
const SESSION_MS = 12 * 60 * 60 * 1000
// 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
@@ -67,6 +83,15 @@ for (const dir of [CONTENT_DIR, UPLOAD_DIR, VERSION_DIR]) fs.mkdirSync(dir, { re
// ── 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 }
@@ -95,11 +120,12 @@ function clientIp(req) {
}
// 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 > 15 * 60 * 1000) {
if (Date.now() - rec.first > THROTTLE_WINDOW_MS) {
failures.delete(ip)
return false
}
@@ -107,20 +133,61 @@ function tooManyAttempts(ip) {
}
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 })
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 ────────────────────────────────────────────────────────────────────
// Applied to every response. Kept narrow (no site-wide CSP): the legacy markup
// relies on inline onclick="" handlers and third-party embeds (HubSpot), so a
// script-src lockdown would need to be introduced carefully, with the real site
// exercised in a browser first, rather than blind here.
// 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 = {}) => {
@@ -168,6 +235,19 @@ const readContent = async () => {
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',
@@ -221,6 +301,32 @@ function safeJoin(root, urlPath) {
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
@@ -239,9 +345,7 @@ async function handleApi(req, res, url) {
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 given = Buffer.from(String(password || ''))
const expected = Buffer.from(ADMIN_PASSWORD)
const ok = given.length === expected.length && crypto.timingSafeEqual(given, expected)
const ok = secretsEqual(Buffer.from(String(password || '')), Buffer.from(ADMIN_PASSWORD))
if (!ok) {
noteFailure(ip)
await new Promise((r) => setTimeout(r, 400))
@@ -257,6 +361,7 @@ async function handleApi(req, res, url) {
}
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(),
@@ -270,6 +375,8 @@ async function handleApi(req, res, url) {
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 })
}
@@ -283,6 +390,13 @@ async function handleApi(req, res, url) {
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))
@@ -424,8 +538,15 @@ const server = http.createServer(async (req, res) => {
return send(res, 404, 'Not found — run `npm run build` first.')
} catch (err) {
const status = err?.status || 500
if (status >= 500) console.error(err)
return send(res, status, { error: err?.message || 'Server error' })
// 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' })
}
})