Initial commit: BlackDice site rebuild with integrated CMS

Rebuilds content management around a single admin route (/admin —
"BlackDice Studio"), replacing blackdice-studio.html. Publishing writes
one JSON content document instead of regenerating HTML files, so it can
no longer overwrite hand-made site changes the way the old tool did.

- /admin: click-to-edit copy/images, article CRUD with a Word-safe rich
  text editor, demo clip management, per-page SEO, enquiry log, publish
  history with rollback
- Real per-page URLs for all pages and articles, each with its own
  meta/canonical/OG/JSON-LD
- Newsroom + article pages driven by the CMS post library, seeded from
  the old studio's export (17 articles) plus a drafted GSMA Open Gateway
  press release awaiting approval
- Demo sections on Mobile SDK and Halo CPE, interactive by default and
  upgradable to an uploaded clip per slot
- Dependency-free Node API server (auth, publish, uploads, snapshots,
  leads, live sitemap)
- Deployment configs for Node/nginx/IIS, Vercel and Netlify

See docs/ARCHITECTURE.md, docs/PROJECT-STRUCTURE.md, docs/CMS-GUIDE.md
and docs/DEPLOYMENT.md.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-12 23:52:44 +05:00
co-authored by Claude Sonnet 5
commit 63a36e0dca
77 changed files with 19487 additions and 0 deletions
+391
View File
@@ -0,0 +1,391 @@
/**
* 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 <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,
})
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,
})
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
}
// ── API ────────────────────────────────────────────────────────────────────────
const DATA_URL = /^data:([a-z0-9.+/-]+);base64,([A-Za-z0-9+/=\s]+)$/i
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',
}
async function handleApi(req, res, url) {
const route = url.pathname
const ip = req.socket.remoteAddress || 'unknown'
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 given = Buffer.from(String(password || ''))
const expected = Buffer.from(ADMIN_PASSWORD)
const ok = given.length === expected.length && crypto.timingSafeEqual(given, expected)
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') {
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' })
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.' })
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
if (status >= 500) console.error(err)
return send(res, status, { error: err?.message || 'Server 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.`)
}
})