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
+20
View File
@@ -0,0 +1,20 @@
name: CI
on:
push:
branches: [main]
pull_request:
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 22
cache: npm
- run: npm ci
# tsc --noEmit runs first (see package.json), so a type error fails the
# build here before anything gets deployed.
- run: npm run build
+7 -5
View File
@@ -109,12 +109,14 @@ redeploy — the build copies neither automatically, so they must be placed alon
## Release checklist ## Release checklist
1. `npm ci && npm run build` — the build fails on type errors, so it gates itself. 1. `npm ci && npm run build` — the build fails on type errors, so it gates itself.
2. `node scripts/generate-sitemap.mjs https://www.blackdice.ai` if the static `build` also regenerates `public/sitemap.xml`/`robots.txt` from whatever is in
sitemap needs refreshing (the server's live one needs nothing). `content/site-content.json` (falling back to factory content) before `vite
3. Deploy `dist/`, `server/`, `package.json`, and keep `content/` in place. build` copies `public/` into `dist/`, so the static sitemap can't go stale
4. Check: `/`, `/mobile-sdk`, `/news`, one `/blog/<slug>` deep link, `/sitemap.xml`, relative to the last build. Set `SITE_URL` if it isn't `https://www.blackdice.ai`.
2. Deploy `dist/`, `server/`, `package.json`, and keep `content/` in place.
3. Check: `/`, `/mobile-sdk`, `/news`, one `/blog/<slug>` deep link, `/sitemap.xml`,
`/admin` login. `/admin` login.
5. In Search Console, submit `https://www.blackdice.ai/sitemap.xml` and request 4. In Search Console, submit `https://www.blackdice.ai/sitemap.xml` and request
indexing for the product pages — they now have their own URLs to index. indexing for the product pages — they now have their own URLs to index.
## After the first deploy ## After the first deploy
+1 -1
View File
@@ -7,7 +7,7 @@
"dev": "node scripts/dev.mjs", "dev": "node scripts/dev.mjs",
"dev:web": "vite", "dev:web": "vite",
"dev:api": "node server/index.mjs", "dev:api": "node server/index.mjs",
"build": "tsc --noEmit && vite build", "build": "tsc --noEmit && node scripts/generate-sitemap.mjs && vite build",
"start": "node server/index.mjs", "start": "node server/index.mjs",
"preview": "vite preview", "preview": "vite preview",
"cms:ids": "node scripts/inject-cms-ids.mjs", "cms:ids": "node scripts/inject-cms-ids.mjs",
Binary file not shown.

After

Width:  |  Height:  |  Size: 137 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 606 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 74 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 272 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 148 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 206 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 139 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 166 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 349 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 301 KiB

+10 -10
View File
@@ -2,52 +2,52 @@
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<url> <url>
<loc>https://www.blackdice.ai/</loc> <loc>https://www.blackdice.ai/</loc>
<lastmod>2026-08-12</lastmod> <lastmod>2026-08-13</lastmod>
<priority>1.0</priority> <priority>1.0</priority>
</url> </url>
<url> <url>
<loc>https://www.blackdice.ai/mobile-sdk</loc> <loc>https://www.blackdice.ai/mobile-sdk</loc>
<lastmod>2026-08-12</lastmod> <lastmod>2026-08-13</lastmod>
<priority>0.9</priority> <priority>0.9</priority>
</url> </url>
<url> <url>
<loc>https://www.blackdice.ai/dns-protect</loc> <loc>https://www.blackdice.ai/dns-protect</loc>
<lastmod>2026-08-12</lastmod> <lastmod>2026-08-13</lastmod>
<priority>0.9</priority> <priority>0.9</priority>
</url> </url>
<url> <url>
<loc>https://www.blackdice.ai/halo-cpe</loc> <loc>https://www.blackdice.ai/halo-cpe</loc>
<lastmod>2026-08-12</lastmod> <lastmod>2026-08-13</lastmod>
<priority>0.9</priority> <priority>0.9</priority>
</url> </url>
<url> <url>
<loc>https://www.blackdice.ai/for-operators</loc> <loc>https://www.blackdice.ai/for-operators</loc>
<lastmod>2026-08-12</lastmod> <lastmod>2026-08-13</lastmod>
<priority>0.8</priority> <priority>0.8</priority>
</url> </url>
<url> <url>
<loc>https://www.blackdice.ai/financial-services</loc> <loc>https://www.blackdice.ai/financial-services</loc>
<lastmod>2026-08-12</lastmod> <lastmod>2026-08-13</lastmod>
<priority>0.8</priority> <priority>0.8</priority>
</url> </url>
<url> <url>
<loc>https://www.blackdice.ai/why-blackdice</loc> <loc>https://www.blackdice.ai/why-blackdice</loc>
<lastmod>2026-08-12</lastmod> <lastmod>2026-08-13</lastmod>
<priority>0.7</priority> <priority>0.7</priority>
</url> </url>
<url> <url>
<loc>https://www.blackdice.ai/news</loc> <loc>https://www.blackdice.ai/news</loc>
<lastmod>2026-08-12</lastmod> <lastmod>2026-08-13</lastmod>
<priority>0.8</priority> <priority>0.8</priority>
</url> </url>
<url> <url>
<loc>https://www.blackdice.ai/investors</loc> <loc>https://www.blackdice.ai/investors</loc>
<lastmod>2026-08-12</lastmod> <lastmod>2026-08-13</lastmod>
<priority>0.6</priority> <priority>0.6</priority>
</url> </url>
<url> <url>
<loc>https://www.blackdice.ai/contact</loc> <loc>https://www.blackdice.ai/contact</loc>
<lastmod>2026-08-12</lastmod> <lastmod>2026-08-13</lastmod>
<priority>0.7</priority> <priority>0.7</priority>
</url> </url>
<url> <url>
+51 -3
View File
@@ -8,13 +8,16 @@
* *
* node server/index.mjs * 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) * PORT listen port (default 8787)
* ADMIN_PASSWORD password for /admin (required in production) * ADMIN_PASSWORD password for /admin (required in production)
* ADMIN_SECRET token signing secret (default: derived from password) * ADMIN_SECRET token signing secret (default: derived from password)
* CONTENT_DIR where published content is kept (default ./content) * CONTENT_DIR where published content is kept (default ./content)
* DIST_DIR built site to serve (default ./dist) * DIST_DIR built site to serve (default ./dist)
* SITE_URL canonical origin for sitemap.xml (default https://www.blackdice.ai) * 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 http from 'node:http'
import fs from 'node:fs' import fs from 'node:fs'
@@ -24,6 +27,19 @@ import crypto from 'node:crypto'
import { fileURLToPath } from 'node:url' import { fileURLToPath } from 'node:url'
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.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 PORT = Number(process.env.PORT || 8787)
const CONTENT_DIR = path.resolve(process.env.CONTENT_DIR || path.join(ROOT, 'content')) 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 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 CONTENT_FILE = path.join(CONTENT_DIR, 'site-content.json')
const LEADS_FILE = path.join(CONTENT_DIR, 'leads.jsonl') const LEADS_FILE = path.join(CONTENT_DIR, 'leads.jsonl')
const SITE_URL = (process.env.SITE_URL || 'https://www.blackdice.ai').replace(/\/+$/, '') 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 DEV_PASSWORD = 'blackdice'
const ADMIN_PASSWORD = process.env.ADMIN_PASSWORD || DEV_PASSWORD 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 SECRET = process.env.ADMIN_SECRET || crypto.createHash('sha256').update('bd:' + ADMIN_PASSWORD).digest('hex')
const SESSION_MS = 12 * 60 * 60 * 1000 const SESSION_MS = 12 * 60 * 60 * 1000
const MAX_BODY = 32 * 1024 * 1024 // uploads arrive as data URLs 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 bearer = (req) => (req.headers.authorization || '').replace(/^Bearer\s+/i, '')
const isAuthed = (req) => validToken(bearer(req)) 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. // Crude but effective throttle: 10 failures per IP per 15 minutes.
const failures = new Map() const failures = new Map()
function tooManyAttempts(ip) { function tooManyAttempts(ip) {
@@ -80,11 +112,23 @@ function noteFailure(ip) {
} }
// ── Helpers ──────────────────────────────────────────────────────────────────── // ── 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 send = (res, status, body, headers = {}) => {
const payload = typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body) const payload = typeof body === 'string' || Buffer.isBuffer(body) ? body : JSON.stringify(body)
res.writeHead(status, { res.writeHead(status, {
'Content-Type': typeof body === 'object' && !Buffer.isBuffer(body) ? 'application/json' : 'text/plain; charset=utf-8', 'Content-Type': typeof body === 'object' && !Buffer.isBuffer(body) ? 'application/json' : 'text/plain; charset=utf-8',
'Cache-Control': 'no-store', 'Cache-Control': 'no-store',
...SECURITY_HEADERS,
...headers, ...headers,
}) })
res.end(payload) res.end(payload)
@@ -154,6 +198,7 @@ async function serveFile(req, res, file, { immutable = false } = {}) {
'Accept-Ranges': 'bytes', 'Accept-Ranges': 'bytes',
'Content-Length': end - start + 1, 'Content-Length': end - start + 1,
'Cache-Control': cache, 'Cache-Control': cache,
...SECURITY_HEADERS,
}) })
fs.createReadStream(file, { start, end }).pipe(res) fs.createReadStream(file, { start, end }).pipe(res)
return true return true
@@ -163,6 +208,7 @@ async function serveFile(req, res, file, { immutable = false } = {}) {
'Content-Length': stat.size, 'Content-Length': stat.size,
'Accept-Ranges': 'bytes', 'Accept-Ranges': 'bytes',
'Cache-Control': cache, 'Cache-Control': cache,
...SECURITY_HEADERS,
}) })
fs.createReadStream(file).pipe(res) fs.createReadStream(file).pipe(res)
return true return true
@@ -177,14 +223,16 @@ function safeJoin(root, urlPath) {
// ── API ──────────────────────────────────────────────────────────────────────── // ── API ────────────────────────────────────────────────────────────────────────
const DATA_URL = /^data:([a-z0-9.+/-]+);base64,([A-Za-z0-9+/=\s]+)$/i 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 = { const UPLOAD_EXT = {
'image/jpeg': '.jpg', 'image/png': '.png', 'image/webp': '.webp', 'image/gif': '.gif', '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) { async function handleApi(req, res, url) {
const route = url.pathname 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) }) if (route === '/api/health') return send(res, 200, { ok: true, published: fs.existsSync(CONTENT_FILE) })
+29 -4
View File
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import SiteApp from '../../site/SiteApp' import SiteApp from '../../site/SiteApp'
import { checkSession, fileToOptimisedDataUrl, getToken, login, setToken, uploadAsset } from '../api' import { checkSession, fileToOptimisedDataUrl, getToken, login, SESSION_EXPIRED_EVENT, setToken, uploadAsset } from '../api'
import { useDraft } from './useDraft' import { useDraft } from './useDraft'
import { useInlineEditor } from './useInlineEditor' import { useInlineEditor } from './useInlineEditor'
import { originals } from './originals' import { originals } from './originals'
@@ -34,6 +34,7 @@ const TABS: { id: Tab; label: string }[] = [
export default function AdminApp() { export default function AdminApp() {
const [authed, setAuthed] = useState(Boolean(getToken())) const [authed, setAuthed] = useState(Boolean(getToken()))
const [checking, setChecking] = useState(Boolean(getToken())) const [checking, setChecking] = useState(Boolean(getToken()))
const [sessionExpired, setSessionExpired] = useState(false)
useEffect(() => { useEffect(() => {
if (!getToken()) return if (!getToken()) return
@@ -46,7 +47,30 @@ export default function AdminApp() {
.finally(() => setChecking(false)) .finally(() => setChecking(false))
}, []) }, [])
if (!authed) return <LoginScreen onSignedIn={() => setAuthed(true)} busy={checking} /> // A publish/upload/etc. can 401 mid-session if the token expires or is
// revoked — drop back to the login screen instead of stranding the editor
// on a raw "Not signed in" error with no way forward.
useEffect(() => {
const onExpired = () => {
setAuthed(false)
setSessionExpired(true)
}
window.addEventListener(SESSION_EXPIRED_EVENT, onExpired)
return () => window.removeEventListener(SESSION_EXPIRED_EVENT, onExpired)
}, [])
if (!authed) {
return (
<LoginScreen
onSignedIn={() => {
setSessionExpired(false)
setAuthed(true)
}}
busy={checking}
expired={sessionExpired}
/>
)
}
return <Studio onSignOut={() => { return <Studio onSignOut={() => {
setToken('') setToken('')
setAuthed(false) setAuthed(false)
@@ -54,7 +78,7 @@ export default function AdminApp() {
} }
// ── Sign in ──────────────────────────────────────────────────────────────────── // ── Sign in ────────────────────────────────────────────────────────────────────
function LoginScreen({ onSignedIn, busy }: { onSignedIn: () => void; busy: boolean }) { function LoginScreen({ onSignedIn, busy, expired = false }: { onSignedIn: () => void; busy: boolean; expired?: boolean }) {
const [password, setPassword] = useState('') const [password, setPassword] = useState('')
const [error, setError] = useState('') const [error, setError] = useState('')
const [working, setWorking] = useState(false) const [working, setWorking] = useState(false)
@@ -82,6 +106,7 @@ function LoginScreen({ onSignedIn, busy }: { onSignedIn: () => void; busy: boole
<form className="bdcms-login-box" onSubmit={submit}> <form className="bdcms-login-box" onSubmit={submit}>
<h1>BlackDice Studio</h1> <h1>BlackDice Studio</h1>
<p>Sign in to edit the website, publish articles and manage the product demos.</p> <p>Sign in to edit the website, publish articles and manage the product demos.</p>
{expired ? <p className="bdcms-err">Your session expired. Sign in again to continue.</p> : null}
<div className="bdcms-field"> <div className="bdcms-field">
<label>PASSWORD</label> <label>PASSWORD</label>
<input <input
@@ -145,7 +170,7 @@ function Studio({ onSignOut }: { onSignOut: () => void }) {
pendingImage.current = null pendingImage.current = null
if (!file || !id) return if (!file || !id) return
if (!/^image\//.test(file.type)) { if (!/^image\//.test(file.type)) {
flash('Choose an image file (PNG, JPG, SVG or WebP).') flash('Choose an image file (PNG, JPG, GIF or WebP).')
return return
} }
try { try {
+18 -5
View File
@@ -2,7 +2,16 @@ import { useEffect, useRef, useState } from 'react'
import type { Post, SiteContent } from '../types' import type { Post, SiteContent } from '../types'
import { getVersion, listVersions } from '../api' import { getVersion, listVersions } from '../api'
import { resolveContent } from '../store' import { resolveContent } from '../store'
import { slugify } from '../sanitise' import { sanitiseBody, slugify } from '../sanitise'
// A version snapshot or an imported content file was written by *some* prior
// publish, possibly by an older build with looser sanitisation. Re-sanitising
// on the way back in is idempotent for already-clean bodies and closes off any
// stored-XSS route through a crafted "content file" or stale studio draft.
const sanitisePosts = (content: SiteContent): SiteContent => ({
...content,
posts: content.posts.map((p) => ({ ...p, body: sanitiseBody(p.body) })),
})
interface Props { interface Props {
draft: SiteContent draft: SiteContent
@@ -33,7 +42,7 @@ export default function HistoryPanel({ draft, published, replace, discard, toast
if (!window.confirm(`Load the snapshot from ${label(name)} into the editor? Nothing goes live until you publish.`)) return if (!window.confirm(`Load the snapshot from ${label(name)} into the editor? Nothing goes live until you publish.`)) return
try { try {
const doc = await getVersion(name) const doc = await getVersion(name)
replace(await resolveContent(doc), `SNAPSHOT ${label(name)} LOADED`) replace(sanitisePosts(await resolveContent(doc)), `SNAPSHOT ${label(name)} LOADED`)
toast('Snapshot loaded into the editor. Review it, then publish.') toast('Snapshot loaded into the editor. Review it, then publish.')
} catch (e) { } catch (e) {
setError(e instanceof Error ? e.message : 'Could not load that snapshot.') setError(e instanceof Error ? e.message : 'Could not load that snapshot.')
@@ -58,7 +67,7 @@ export default function HistoryPanel({ draft, published, replace, discard, toast
try { try {
const parsed = JSON.parse(await file.text()) const parsed = JSON.parse(await file.text())
if (parsed.format === 'blackdice-react-content') { if (parsed.format === 'blackdice-react-content') {
replace(await resolveContent(parsed), 'CONTENT FILE IMPORTED') replace(sanitisePosts(await resolveContent(parsed)), 'CONTENT FILE IMPORTED')
toast('Content imported into the editor.') toast('Content imported into the editor.')
return return
} }
@@ -73,7 +82,7 @@ export default function HistoryPanel({ draft, published, replace, discard, toast
author: p.author || 'BlackDice Cyber', author: p.author || 'BlackDice Cyber',
excerpt: p.excerpt || '', excerpt: p.excerpt || '',
hero: p.hero || '', hero: p.hero || '',
body: p.body || '', body: sanitiseBody(p.body || ''),
status: 'published', status: 'published',
updatedAt: new Date().toISOString(), updatedAt: new Date().toISOString(),
})) as Post[] })) as Post[]
@@ -105,7 +114,11 @@ export default function HistoryPanel({ draft, published, replace, discard, toast
? `Last published ${new Date(published.savedAt).toLocaleString()}.` ? `Last published ${new Date(published.savedAt).toLocaleString()}.`
: 'Nothing has been published yet — the site is showing the content it shipped with.'} : 'Nothing has been published yet — the site is showing the content it shipped with.'}
</p> </p>
<button className="bdcms-btn" onClick={discard}> <button
className="bdcms-btn"
onClick={() => {
if (window.confirm('Discard all unpublished edits and reload exactly what is live? This cannot be undone.')) discard()
}}>
Discard my draft Discard my draft
<small>Throw away local edits and show exactly what is live</small> <small>Throw away local edits and show exactly what is live</small>
</button> </button>
+23 -1
View File
@@ -25,6 +25,7 @@ const uniqueSlug = (posts: Post[], base: string, ignoreId: string) => {
/** Blogs, news, press releases and event write-ups — the whole post library. */ /** Blogs, news, press releases and event write-ups — the whole post library. */
export default function PostsPanel({ draft, update, selected, onSelect, toast }: Props) { export default function PostsPanel({ draft, update, selected, onSelect, toast }: Props) {
const [filter, setFilter] = useState<PostCategory | 'all'>('all') const [filter, setFilter] = useState<PostCategory | 'all'>('all')
const [search, setSearch] = useState('')
const [busy, setBusy] = useState(false) const [busy, setBusy] = useState(false)
const heroRef = useRef<HTMLInputElement>(null) const heroRef = useRef<HTMLInputElement>(null)
@@ -32,7 +33,12 @@ export default function PostsPanel({ draft, update, selected, onSelect, toast }:
() => draft.posts.slice().sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0)), () => draft.posts.slice().sort((a, b) => (a.date < b.date ? 1 : a.date > b.date ? -1 : 0)),
[draft.posts], [draft.posts],
) )
const shown = filter === 'all' ? posts : posts.filter((p) => p.category === filter) const shown = useMemo(() => {
const byCategory = filter === 'all' ? posts : posts.filter((p) => p.category === filter)
const q = search.trim().toLowerCase()
if (!q) return byCategory
return byCategory.filter((p) => p.title.toLowerCase().includes(q) || p.excerpt.toLowerCase().includes(q))
}, [posts, filter, search])
const post = posts.find((p) => p.slug === selected) || null const post = posts.find((p) => p.slug === selected) || null
const patch = (id: string, changes: Partial<Post>) => const patch = (id: string, changes: Partial<Post>) =>
@@ -110,6 +116,13 @@ export default function PostsPanel({ draft, update, selected, onSelect, toast }:
</button> </button>
<div className="bdcms-h">LIBRARY · {posts.length} ARTICLES</div> <div className="bdcms-h">LIBRARY · {posts.length} ARTICLES</div>
<input
className="bdcms-inp"
style={{ marginBottom: 8 }}
placeholder="Search by title or excerpt…"
value={search}
onChange={(e) => setSearch(e.target.value)}
/>
<div className="bdcms-tabs" style={{ padding: 0, border: 'none', marginBottom: 8 }}> <div className="bdcms-tabs" style={{ padding: 0, border: 'none', marginBottom: 8 }}>
{[{ id: 'all', label: 'All' }, ...POST_CATEGORIES].map((cat) => ( {[{ id: 'all', label: 'All' }, ...POST_CATEGORIES].map((cat) => (
<button <button
@@ -259,6 +272,15 @@ export default function PostsPanel({ draft, update, selected, onSelect, toast }:
value={post.hero} value={post.hero}
onChange={(e) => patch(post.id, { hero: e.target.value.trim() })} onChange={(e) => patch(post.id, { hero: e.target.value.trim() })}
/> />
{post.hero ? (
<input
className="bdcms-inp"
style={{ marginTop: 8 }}
placeholder={`Alt text — describe the image (defaults to "${post.title}")`}
value={post.heroAlt || ''}
onChange={(e) => patch(post.id, { heroAlt: e.target.value })}
/>
) : null}
<input <input
ref={heroRef} ref={heroRef}
type="file" type="file"
+17 -6
View File
@@ -21,18 +21,30 @@ export const setToken = (token: string) => {
} }
} }
// Dispatched whenever an authenticated request comes back 401 — the token
// expired or was revoked mid-session. AdminApp listens for this to drop back
// to the login screen instead of leaving the editor showing a raw error.
export const SESSION_EXPIRED_EVENT = 'bd-session-expired'
async function request<T>(url: string, init: RequestInit = {}): Promise<T> { async function request<T>(url: string, init: RequestInit = {}): Promise<T> {
const hadToken = Boolean(getToken())
const res = await fetch(url, { const res = await fetch(url, {
...init, ...init,
headers: { headers: {
...(init.body ? { 'Content-Type': 'application/json' } : {}), ...(init.body ? { 'Content-Type': 'application/json' } : {}),
...(getToken() ? { Authorization: `Bearer ${getToken()}` } : {}), ...(hadToken ? { Authorization: `Bearer ${getToken()}` } : {}),
...init.headers, ...init.headers,
}, },
}) })
const text = await res.text() const text = await res.text()
const data = text ? JSON.parse(text) : {} const data = text ? JSON.parse(text) : {}
if (!res.ok) throw Object.assign(new Error(data.error || `${res.status} ${res.statusText}`), { status: res.status }) if (!res.ok) {
if (res.status === 401 && hadToken && url !== '/api/login') {
setToken('')
window.dispatchEvent(new Event(SESSION_EXPIRED_EVENT))
}
throw Object.assign(new Error(data.error || `${res.status} ${res.statusText}`), { status: res.status })
}
return data as T return data as T
} }
@@ -94,10 +106,9 @@ export function fileToOptimisedDataUrl(file: File, maxWidth = 1920, quality = 0.
return return
} }
if (file.type === 'image/svg+xml') { if (file.type === 'image/svg+xml') {
const reader = new FileReader() // The server rejects SVG uploads (they can carry <script>) — fail fast
reader.onload = () => resolve(String(reader.result)) // with a clear message instead of letting it round-trip to a 415.
reader.onerror = () => reject(new Error('Could not read that file.')) reject(new Error('SVG images are not supported. Use PNG, JPG, WebP or GIF.'))
reader.readAsDataURL(file)
return return
} }
const url = URL.createObjectURL(file) const url = URL.createObjectURL(file)
File diff suppressed because one or more lines are too long
+35 -2
View File
@@ -65,8 +65,9 @@ export function applyMeta({ title, description, path, image, type = 'website', s
metaByName('twitter:image').setAttribute('content', absImage) metaByName('twitter:image').setAttribute('content', absImage)
} }
/** Structured data for the current view; replaces any previous block. */ /** Structured data for the current view; replaces any previous block. Accepts
export function applyJsonLd(data: object | null) { * one object or several (rendered as a JSON-LD array in a single script tag). */
export function applyJsonLd(data: object | object[] | null) {
const id = 'bd-jsonld' const id = 'bd-jsonld'
document.getElementById(id)?.remove() document.getElementById(id)?.remove()
if (!data) return if (!data) return
@@ -77,6 +78,38 @@ export function applyJsonLd(data: object | null) {
document.head.appendChild(script) document.head.appendChild(script)
} }
/** Home › Section › Page, for rich-result breadcrumbs. */
export const breadcrumbJsonLd = (items: { name: string; url: string }[]) => ({
'@context': 'https://schema.org',
'@type': 'BreadcrumbList',
itemListElement: items.map((item, i) => ({
'@type': 'ListItem',
position: i + 1,
name: item.name,
item: item.url,
})),
})
/** The newsroom listing (/news) as an indexable collection of articles. */
export const newsroomJsonLd = (
posts: { title: string; slug: string; date: string }[],
siteUrl = DEFAULT_SITE_URL,
) => ({
'@context': 'https://schema.org',
'@type': 'CollectionPage',
name: 'Newsroom | BlackDice Cyber',
url: `${siteUrl}/news`,
mainEntity: {
'@type': 'ItemList',
itemListElement: posts.map((post, i) => ({
'@type': 'ListItem',
position: i + 1,
url: `${siteUrl}/blog/${post.slug}`,
name: post.title,
})),
},
})
export const organisationJsonLd = (siteUrl = DEFAULT_SITE_URL) => ({ export const organisationJsonLd = (siteUrl = DEFAULT_SITE_URL) => ({
'@context': 'https://schema.org', '@context': 'https://schema.org',
'@type': 'Organization', '@type': 'Organization',
+2
View File
@@ -18,6 +18,8 @@ export interface Post {
excerpt: string excerpt: string
/** URL of the hero image ('' for none). */ /** URL of the hero image ('' for none). */
hero: string hero: string
/** Alt text for the hero image. Falls back to the title when empty. */
heroAlt?: string
/** Article body as sanitised HTML. */ /** Article body as sanitised HTML. */
body: string body: string
status: PostStatus status: PostStatus
+1 -1
View File
@@ -54,7 +54,7 @@ ReactDOM.createRoot(document.getElementById('root')!).render(
{/* Legacy hash-era and mistyped URLs still land on a working page. */} {/* Legacy hash-era and mistyped URLs still land on a working page. */}
<Route path="/blog" element={<SiteApp pageId="p7" />} /> <Route path="/blog" element={<SiteApp pageId="p7" />} />
<Route path="/blog.html" element={<SiteApp pageId="p7" />} /> <Route path="/blog.html" element={<SiteApp pageId="p7" />} />
<Route path="*" element={<SiteApp pageId="p1" />} /> <Route path="*" element={<SiteApp notFound />} />
</Routes> </Routes>
</ContentProvider> </ContentProvider>
} }
+49
View File
@@ -0,0 +1,49 @@
import { useEffect } from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { useContent } from '../cms/store'
import { applyJsonLd, applyMeta } from '../cms/seo'
/**
* Rendered for any URL that doesn't match a real page, article or demo route.
* A dedicated noindex page (rather than silently showing the homepage) keeps
* mistyped/stale links from being indexed as duplicate homepage content.
*/
export default function NotFoundPage({ suppressMeta = false }: { suppressMeta?: boolean }) {
const content = useContent()
const navigate = useNavigate()
const location = useLocation()
useEffect(() => {
if (suppressMeta) return
applyMeta({
title: 'Page not found | BlackDice Cyber',
description: 'The page you are looking for does not exist.',
path: location.pathname,
siteUrl: content.settings.siteUrl,
robots: 'noindex, follow',
})
applyJsonLd(null)
}, [suppressMeta, location.pathname, content.settings.siteUrl])
return (
<section className="bd-sect t">
<div className="bd-si" style={{ maxWidth: 720 }}>
<span className="ey">404</span>
<h1 className="h1" style={{ fontSize: 'clamp(28px,3vw,40px)', marginBottom: 16 }}>
We can't find that page.
</h1>
<p style={{ color: 'var(--t2)', fontSize: 16, marginBottom: 24 }}>
There's nothing at <code>{location.pathname}</code>. It may have been moved or the link may be out of date.
</p>
<div className="btn-row">
<button className="btn-p" onClick={() => navigate('/')}>
Back to the homepage
</button>
<button className="btn-g" onClick={() => navigate('/news')}>
Visit the newsroom
</button>
</div>
</div>
</section>
)
}
+36 -9
View File
@@ -12,11 +12,12 @@ import { configureForms, initSite, setSiteNavigator, showPage, teardownSite } fr
import ThreatDemosSlider from '../demo/threats/ThreatDemosSlider' import ThreatDemosSlider from '../demo/threats/ThreatDemosSlider'
import NewsGrid from './blog/NewsGrid' import NewsGrid from './blog/NewsGrid'
import ArticlePage from './blog/ArticlePage' import ArticlePage from './blog/ArticlePage'
import NotFoundPage from './NotFoundPage'
import DemoSection from './demos/DemoSection' import DemoSection from './demos/DemoSection'
import DemoPlayer from './demos/DemoPlayer' import DemoPlayer from './demos/DemoPlayer'
import { applyContent, useContent } from '../cms/store' import { applyContent, publishedPosts, useContent } from '../cms/store'
import { pageById } from '../cms/pages' import { pageById } from '../cms/pages'
import { applyJsonLd, applyMeta, organisationJsonLd } from '../cms/seo' import { applyJsonLd, applyMeta, breadcrumbJsonLd, newsroomJsonLd, organisationJsonLd } from '../cms/seo'
import { submitLead } from '../cms/api' import { submitLead } from '../cms/api'
import type { SiteContent } from '../cms/types' import type { SiteContent } from '../cms/types'
@@ -33,17 +34,25 @@ const ISLANDS = [
] as const ] as const
export interface SiteAppProps { export interface SiteAppProps {
/** Page to show (p1…p12). Ignored when `articleSlug` is set. */ /** Page to show (p1…p12). Ignored when `articleSlug` or `notFound` is set. */
pageId?: string pageId?: string
/** Renders the article view at /blog/<slug>. */ /** Renders the article view at /blog/<slug>. */
articleSlug?: string articleSlug?: string
/** Renders a noindex 404 instead of a real page — for unmatched routes. */
notFound?: boolean
/** Admin preview: content comes from the editor's draft, not the published doc. */ /** Admin preview: content comes from the editor's draft, not the published doc. */
previewContent?: SiteContent previewContent?: SiteContent
/** Suppress meta/JSON-LD writes (the admin owns the document head). */ /** Suppress meta/JSON-LD writes (the admin owns the document head). */
suppressMeta?: boolean suppressMeta?: boolean
} }
export default function SiteApp({ pageId = 'p1', articleSlug, previewContent, suppressMeta = false }: SiteAppProps) { export default function SiteApp({
pageId = 'p1',
articleSlug,
notFound = false,
previewContent,
suppressMeta = false,
}: SiteAppProps) {
const navigate = useNavigate() const navigate = useNavigate()
const wrapRef = useRef<HTMLDivElement>(null) const wrapRef = useRef<HTMLDivElement>(null)
const publishedContent = useContent() const publishedContent = useContent()
@@ -77,7 +86,7 @@ export default function SiteApp({ pageId = 'p1', articleSlug, previewContent, su
// Boot the ported controller and hand it the router. // Boot the ported controller and hand it the router.
setSiteNavigator((path: string) => navigate(path)) setSiteNavigator((path: string) => navigate(path))
initSite(articleSlug ? 'article' : pageId) initSite(articleSlug || notFound ? 'article' : pageId)
// Reliably wire the "Talk to us" CTAs to open the Request-a-demonstration // Reliably wire the "Talk to us" CTAs to open the Request-a-demonstration
// modal (in case the inline onclick handler doesn't bind in some contexts). // modal (in case the inline onclick handler doesn't bind in some contexts).
@@ -137,13 +146,14 @@ export default function SiteApp({ pageId = 'p1', articleSlug, previewContent, su
// ── Route → page ──────────────────────────────────────────────────────────── // ── Route → page ────────────────────────────────────────────────────────────
useEffect(() => { useEffect(() => {
if (articleSlug) showPage('article', 'p7') if (articleSlug) showPage('article', 'p7')
else if (notFound) showPage('article') // no nav item highlighted for a generic 404
else showPage(pageId) else showPage(pageId)
}, [pageId, articleSlug]) }, [pageId, articleSlug, notFound])
// ── Metadata ──────────────────────────────────────────────────────────────── // ── Metadata ────────────────────────────────────────────────────────────────
const seo = useMemo(() => content.seo[pageId], [content, pageId]) const seo = useMemo(() => content.seo[pageId], [content, pageId])
useEffect(() => { useEffect(() => {
if (suppressMeta || articleSlug) return // ArticlePage owns article metadata if (suppressMeta || articleSlug || notFound) return // ArticlePage/NotFoundPage own their own metadata
const page = pageById(pageId) const page = pageById(pageId)
if (!page || !seo) return if (!page || !seo) return
applyMeta({ applyMeta({
@@ -154,8 +164,21 @@ export default function SiteApp({ pageId = 'p1', articleSlug, previewContent, su
siteUrl: content.settings.siteUrl, siteUrl: content.settings.siteUrl,
robots: page.indexable ? 'index, follow' : 'noindex, follow', robots: page.indexable ? 'index, follow' : 'noindex, follow',
}) })
applyJsonLd(pageId === 'p1' ? organisationJsonLd(content.settings.siteUrl) : null) if (pageId === 'p1') {
}, [pageId, seo, articleSlug, suppressMeta, content.settings.siteUrl]) applyJsonLd(organisationJsonLd(content.settings.siteUrl))
} else if (pageId === 'p7') {
const siteUrl = content.settings.siteUrl
applyJsonLd([
breadcrumbJsonLd([
{ name: 'Home', url: siteUrl },
{ name: 'News', url: `${siteUrl}/news` },
]),
newsroomJsonLd(publishedPosts(content), siteUrl),
])
} else {
applyJsonLd(null)
}
}, [pageId, seo, articleSlug, notFound, suppressMeta, content])
return ( return (
<> <>
@@ -194,6 +217,10 @@ export default function SiteApp({ pageId = 'p1', articleSlug, previewContent, su
<ArticlePage slug={articleSlug} suppressMeta={suppressMeta} content={content} />, <ArticlePage slug={articleSlug} suppressMeta={suppressMeta} content={content} />,
mounts['pg-article'], mounts['pg-article'],
)} )}
{notFound &&
mounts['pg-article'] &&
createPortal(<NotFoundPage suppressMeta={suppressMeta} />, mounts['pg-article'])}
</> </>
) )
} }
+17 -13
View File
@@ -1,8 +1,9 @@
import { useEffect, useMemo } from 'react' import { useEffect, useMemo } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { formatPostDate, publishedPosts, useContent } from '../../cms/store' import { formatPostDate, publishedPosts, useContent } from '../../cms/store'
import { applyJsonLd, applyMeta, articleJsonLd } from '../../cms/seo' import { applyJsonLd, applyMeta, articleJsonLd, breadcrumbJsonLd } from '../../cms/seo'
import { categoryMeta, splitAuthor } from './NewsGrid' import { categoryMeta, splitAuthor } from './blogHelpers'
import PostCard from './PostCard'
import type { Post, SiteContent } from '../../cms/types' import type { Post, SiteContent } from '../../cms/types'
/** /**
@@ -55,7 +56,18 @@ export default function ArticlePage({
siteUrl: content.settings.siteUrl, siteUrl: content.settings.siteUrl,
robots: post.status === 'draft' ? 'noindex, nofollow' : 'index, follow', robots: post.status === 'draft' ? 'noindex, nofollow' : 'index, follow',
}) })
applyJsonLd(post.status === 'draft' ? null : articleJsonLd(post, content.settings.siteUrl)) applyJsonLd(
post.status === 'draft'
? null
: [
breadcrumbJsonLd([
{ name: 'Home', url: content.settings.siteUrl },
{ name: 'News', url: `${content.settings.siteUrl}/news` },
{ name: post.title, url: `${content.settings.siteUrl}/blog/${post.slug}` },
]),
articleJsonLd(post, content.settings.siteUrl),
],
)
}, [post, slug, content.settings.siteUrl, suppressMeta]) }, [post, slug, content.settings.siteUrl, suppressMeta])
if (!post) { if (!post) {
@@ -104,7 +116,7 @@ export default function ArticlePage({
<div className="bd-si bd-article-wrap"> <div className="bd-si bd-article-wrap">
{post.hero ? ( {post.hero ? (
<figure className="bd-article-hero-img"> <figure className="bd-article-hero-img">
<img src={post.hero} alt={post.title} /> <img src={post.hero} alt={post.heroAlt || post.title} />
{credit ? <figcaption>{credit}</figcaption> : null} {credit ? <figcaption>{credit}</figcaption> : null}
</figure> </figure>
) : null} ) : null}
@@ -121,15 +133,7 @@ export default function ArticlePage({
</div> </div>
<div className="news-grid"> <div className="news-grid">
{related.map((other) => ( {related.map((other) => (
<article key={other.id} className="news-card bd-news-card" onClick={() => navigate(`/blog/${other.slug}`)}> <PostCard key={other.id} post={other} onOpen={(p) => navigate(`/blog/${p.slug}`)} />
<span className={`news-tag ${categoryMeta(other.category).cls}`}>
{categoryMeta(other.category).label.toUpperCase()}
</span>
<h3>{other.title}</h3>
<p className="bd-news-meta">{formatPostDate(other.date)}</p>
<p>{other.excerpt}</p>
<span className="bd-news-more">Read more →</span>
</article>
))} ))}
</div> </div>
</div> </div>
+3 -43
View File
@@ -1,48 +1,8 @@
import { useMemo, useState } from 'react' import { useMemo, useState } from 'react'
import { useNavigate } from 'react-router-dom' import { useNavigate } from 'react-router-dom'
import { POST_CATEGORIES, type Post, type PostCategory, type SiteContent } from '../../cms/types' import { POST_CATEGORIES, type Post, type PostCategory, type SiteContent } from '../../cms/types'
import { formatPostDate, publishedPosts, useContent } from '../../cms/store' import { publishedPosts, useContent } from '../../cms/store'
import PostCard from './PostCard'
export const categoryMeta = (id: string) => POST_CATEGORIES.find((c) => c.id === id) || POST_CATEGORIES[0]
/** Authors are stored as "Paul Hague (Image by … on Unsplash)" — split the credit out. */
export function splitAuthor(author: string) {
const match = /^(.*?)\s*\(([^)]*)\)\s*$/.exec(author || '')
return match ? { name: match[1].trim(), credit: match[2].trim() } : { name: (author || '').trim(), credit: '' }
}
function Card({ post, onOpen }: { post: Post; onOpen: (post: Post) => void }) {
const cat = categoryMeta(post.category)
const { name } = splitAuthor(post.author)
return (
<article
className="news-card bd-news-card"
role="link"
tabIndex={0}
onClick={() => onOpen(post)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
onOpen(post)
}
}}>
{post.hero ? (
<div className="bd-news-thumb">
<img src={post.hero} alt="" loading="lazy" />
</div>
) : null}
<span className={`news-tag ${cat.cls}`}>{cat.label.toUpperCase()}</span>
{post.status === 'draft' ? <span className="bd-news-draft">DRAFT</span> : null}
<h3>{post.title}</h3>
<p className="bd-news-meta">
{formatPostDate(post.date)}
{name ? ` · ${name}` : ''}
</p>
<p>{post.excerpt}</p>
<span className="bd-news-more">Read more →</span>
</article>
)
}
/** /**
* The newsroom grid (/news) and the home page's latest-three strip. Both read the * The newsroom grid (/news) and the home page's latest-three strip. Both read the
@@ -118,7 +78,7 @@ export default function NewsGrid({
<div className="news-grid"> <div className="news-grid">
{posts.map((post) => ( {posts.map((post) => (
<Card key={post.id} post={post} onOpen={open} /> <PostCard key={post.id} post={post} onOpen={open} />
))} ))}
</div> </div>
</> </>
+37
View File
@@ -0,0 +1,37 @@
import { formatPostDate } from '../../cms/store'
import type { Post } from '../../cms/types'
import { categoryMeta, splitAuthor } from './blogHelpers'
/** A single card in the newsroom grid, the home strip, and an article's "keep reading" list. */
export default function PostCard({ post, onOpen }: { post: Post; onOpen: (post: Post) => void }) {
const cat = categoryMeta(post.category)
const { name } = splitAuthor(post.author)
return (
<article
className="news-card bd-news-card"
role="link"
tabIndex={0}
onClick={() => onOpen(post)}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault()
onOpen(post)
}
}}>
{post.hero ? (
<div className="bd-news-thumb">
<img src={post.hero} alt={post.heroAlt || post.title} loading="lazy" />
</div>
) : null}
<span className={`news-tag ${cat.cls}`}>{cat.label.toUpperCase()}</span>
{post.status === 'draft' ? <span className="bd-news-draft">DRAFT</span> : null}
<h3>{post.title}</h3>
<p className="bd-news-meta">
{formatPostDate(post.date)}
{name ? ` · ${name}` : ''}
</p>
<p>{post.excerpt}</p>
<span className="bd-news-more">Read more →</span>
</article>
)
}
+9
View File
@@ -0,0 +1,9 @@
import { POST_CATEGORIES } from '../../cms/types'
export const categoryMeta = (id: string) => POST_CATEGORIES.find((c) => c.id === id) || POST_CATEGORIES[0]
/** Authors are stored as "Paul Hague (Image by … on Unsplash)" — split the credit out. */
export function splitAuthor(author: string) {
const match = /^(.*?)\s*\(([^)]*)\)\s*$/.exec(author || '')
return match ? { name: match[1].trim(), credit: match[2].trim() } : { name: (author || '').trim(), credit: '' }
}
+47 -1
View File
@@ -201,7 +201,10 @@ function goHome() {
function toggleMob() { function toggleMob() {
var mob = document.getElementById("mob-nav"); var mob = document.getElementById("mob-nav");
if (!mob) return; if (!mob) return;
mob.style.display = mob.style.display === "none" ? "block" : "none"; var opening = mob.style.display === "none";
mob.style.display = opening ? "block" : "none";
var ham = document.querySelector(".bd-ham");
if (ham) ham.setAttribute("aria-expanded", opening ? "true" : "false");
} }
// ── Scroll ───────────────────────────────────────────────────────────────── // ── Scroll ─────────────────────────────────────────────────────────────────
@@ -225,6 +228,40 @@ function scrollDown() {
} }
// ── Demo modal ───────────────────────────────────────────────────────────── // ── Demo modal ─────────────────────────────────────────────────────────────
// A modal needs to trap focus and close on Escape to be usable by keyboard
// and screen-reader visitors — otherwise Tab can walk out into the hidden
// page behind it, with no keyboard way back in or out.
var __bdModalLastFocus = null;
function __bdModalFocusables() {
var box = document.querySelector("#modal-ov .modal-box");
if (!box) return [];
return Array.prototype.filter.call(
box.querySelectorAll('button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'),
function (el) { return !el.disabled && el.offsetParent !== null; },
);
}
function __bdModalKeydown(e) {
if (e.key === "Escape" || e.key === "Esc") {
e.preventDefault();
closeDemo();
return;
}
if (e.key !== "Tab") return;
var focusables = __bdModalFocusables();
if (!focusables.length) return;
var first = focusables[0];
var last = focusables[focusables.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
}
function showDemo() { function showDemo() {
var ov = document.getElementById("modal-ov"); var ov = document.getElementById("modal-ov");
@@ -235,11 +272,19 @@ function showDemo() {
if (form) form.style.display = "block"; if (form) form.style.display = "block";
if (sent) sent.style.display = "none"; if (sent) sent.style.display = "none";
if (err) err.style.display = "none"; if (err) err.style.display = "none";
__bdModalLastFocus = document.activeElement;
document.addEventListener("keydown", __bdModalKeydown, true);
var focusables = __bdModalFocusables();
if (focusables.length) focusables[0].focus();
} }
function closeDemo() { function closeDemo() {
var ov = document.getElementById("modal-ov"); var ov = document.getElementById("modal-ov");
if (ov) ov.style.display = "none"; if (ov) ov.style.display = "none";
document.removeEventListener("keydown", __bdModalKeydown, true);
if (__bdModalLastFocus && typeof __bdModalLastFocus.focus === "function") __bdModalLastFocus.focus();
__bdModalLastFocus = null;
} }
function closeBg(e) { function closeBg(e) {
@@ -457,4 +502,5 @@ export function initSite(startPage) {
export function teardownSite() { export function teardownSite() {
window.removeEventListener('scroll', onScroll); window.removeEventListener('scroll', onScroll);
if (__bdFeedTimer) { clearInterval(__bdFeedTimer); __bdFeedTimer = null; } if (__bdFeedTimer) { clearInterval(__bdFeedTimer); __bdFeedTimer = null; }
document.removeEventListener('keydown', __bdModalKeydown, true);
} }
+2 -2
View File
@@ -21,7 +21,7 @@
</div> </div>
<button data-cms="c0012" class="bd-nl bd-nav-cta" onclick="showDemo()">Talk to us</button> <button data-cms="c0012" class="bd-nl bd-nav-cta" onclick="showDemo()">Talk to us</button>
</div> </div>
<button class="bd-ham" onclick="toggleMob()" aria-label="Menu"><span></span><span></span><span></span></button> <button class="bd-ham" onclick="toggleMob()" aria-label="Menu" aria-expanded="false" aria-controls="mob-nav"><span></span><span></span><span></span></button>
</nav> </nav>
<!-- MOBILE NAV --> <!-- MOBILE NAV -->
@@ -3968,7 +3968,7 @@
<!-- ═══ DEMO MODAL ═══ --> <!-- ═══ DEMO MODAL ═══ -->
<div id="modal-ov" class="modal-ov" style="display:none" onclick="closeBg(event)"> <div id="modal-ov" class="modal-ov" style="display:none" onclick="closeBg(event)">
<div class="modal-box"> <div class="modal-box" role="dialog" aria-modal="true" aria-label="Request a demonstration">
<button data-cms="c0630" class="modal-x" onclick="closeDemo()">✕</button> <button data-cms="c0630" class="modal-x" onclick="closeDemo()">✕</button>
<div id="modal-form" style="display:block"> <div id="modal-form" style="display:block">
<span data-cms="c0631" <span data-cms="c0631"
+11 -1
View File
@@ -1,6 +1,16 @@
{ {
"rewrites": [ "rewrites": [
{ "source": "/api/(.*)", "destination": "/api/$1" },
{ "source": "/((?!assets/|content/|logo.svg|robots.txt|sitemap.xml).*)", "destination": "/index.html" } { "source": "/((?!assets/|content/|logo.svg|robots.txt|sitemap.xml).*)", "destination": "/index.html" }
],
"headers": [
{
"source": "/(.*)",
"headers": [
{ "key": "X-Content-Type-Options", "value": "nosniff" },
{ "key": "X-Frame-Options", "value": "SAMEORIGIN" },
{ "key": "Referrer-Policy", "value": "strict-origin-when-cross-origin" },
{ "key": "Permissions-Policy", "value": "geolocation=(), camera=(), microphone=()" }
]
}
] ]
} }