Harden CMS security, fix SEO/a11y gaps, and fill in missing article images
CI / build (push) Has been cancelled

Server: refuse to start in production with the default admin password,
drop SVG from the upload allow-list (stored-XSS risk), add baseline
security headers, make the login rate limiter proxy-aware via TRUST_PROXY,
and auto-load .env.local/.env in dev.

Admin: sanitise post bodies on content import/snapshot restore (previously
bypassed sanitiseBody), confirm before discarding a draft, drop back to the
login screen on a mid-session 401 instead of a stuck error, add hero-image
alt text and a title/excerpt search to the articles panel.

Site: replace the soft-404-to-homepage fallback with a real noindex 404
page, add a focus trap/Escape handling/aria-modal to the enquiry modal,
aria-expanded on the mobile nav toggle, ItemList/breadcrumb structured data
for the newsroom and articles, and wire sitemap generation into the build
so it can't go stale. Extract the duplicated NewsGrid/ArticlePage card
markup into a shared PostCard component.

Content: 13 of 18 seed articles shipped with no hero image (one pointed at
a dead WordPress URL); the live blackdice.ai site turned out to still be
the old blackdice-studio.html export, so recovering the originals wasn't
feasible. Filled the gap with freely-licensed Unsplash placeholders,
credited in the author field, until real photography is ready.

Also adds a Gitea Actions CI workflow (typecheck + build).

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-13 13:54:38 +05:00
co-authored by Claude Sonnet 5
parent 410463e0ed
commit f02461b456
35 changed files with 477 additions and 146 deletions
+51 -3
View File
@@ -8,13 +8,16 @@
*
* node server/index.mjs
*
* Environment
* 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)
*/
import http from 'node:http'
import fs from 'node:fs'
@@ -24,6 +27,19 @@ import crypto from 'node:crypto'
import { fileURLToPath } from 'node:url'
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'))
@@ -32,9 +48,15 @@ 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
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.')
console.error(' Set a real ADMIN_PASSWORD — see .env.example / docs/DEPLOYMENT.md.')
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
const MAX_BODY = 32 * 1024 * 1024 // uploads arrive as data URLs
@@ -62,6 +84,16 @@ function validToken(token) {
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 failures = new Map()
function tooManyAttempts(ip) {
@@ -80,11 +112,23 @@ function noteFailure(ip) {
}
// ── 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.
const SECURITY_HEADERS = {
'X-Content-Type-Options': 'nosniff',
'X-Frame-Options': 'SAMEORIGIN',
'Referrer-Policy': 'strict-origin-when-cross-origin',
'Permissions-Policy': 'geolocation=(), camera=(), microphone=()',
}
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)
@@ -154,6 +198,7 @@ async function serveFile(req, res, file, { immutable = false } = {}) {
'Accept-Ranges': 'bytes',
'Content-Length': end - start + 1,
'Cache-Control': cache,
...SECURITY_HEADERS,
})
fs.createReadStream(file, { start, end }).pipe(res)
return true
@@ -163,6 +208,7 @@ async function serveFile(req, res, file, { immutable = false } = {}) {
'Content-Length': stat.size,
'Accept-Ranges': 'bytes',
'Cache-Control': cache,
...SECURITY_HEADERS,
})
fs.createReadStream(file).pipe(res)
return true
@@ -177,14 +223,16 @@ function safeJoin(root, urlPath) {
// ── 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',
'image/svg+xml': '.svg', 'video/mp4': '.mp4', 'video/webm': '.webm', 'application/pdf': '.pdf',
'video/mp4': '.mp4', 'video/webm': '.webm', 'application/pdf': '.pdf',
}
async function handleApi(req, res, url) {
const route = url.pathname
const ip = req.socket.remoteAddress || 'unknown'
const ip = clientIp(req)
if (route === '/api/health') return send(res, 200, { ok: true, published: fs.existsSync(CONTENT_FILE) })