feat(theming): brand-asset overrides and a cached, settings-aware HTML shell

Phase 5 of docs/website/THEMING_AND_NAV.md: uploaded logo/hero/favicon
overrides on top of the BRAND_* env defaults, delivered through an HTML
shell that is no longer built once at boot.

- utils/htmlShell.js owns the shell lifecycle: rendered lazily, cached per
  process, invalidated on a brand_assets/theme_visual write with a 5-minute
  TTL so other workers converge. A settings-read failure renders the
  env-only shell and caches that, so a DB outage is not a failing query per
  page view, and with no rows the output is byte-identical to what app.js
  served before.
- POST /admin/settings/brand-asset/:slot uploads one asset and writes the
  row in the same call, so an upload never leaves an unreferenced file. It
  reuses the shared multer allowlist and only tightens it per slot: favicons
  are PNG-only and capped at 512 KB, logos at 1 MB, heroes at 8 MB. Refused
  files are unlinked before the response.
- utils/brandAssets.js constrains a stored asset to a same-origin path under
  /uploads, /brand or /assets — these are the only settings values written
  straight into the page as a URL. Strict on write, forgiving on read.
- The shell also carries the resolved theme as a <style id="theme-boot">
  block, removing the first-paint flash phases 3-4 deferred; SiteContext
  drops that block once a successful settings fetch has been applied.
- BrandLogo renders beside the MoonDot on all six shells and renders nothing
  when no logo is set, which is the shipped default.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-08-07 20:09:56 -05:00
parent 02580ebda3
commit 847cfd2d2b
22 changed files with 1488 additions and 35 deletions

View File

@@ -16,6 +16,7 @@ const brand = require('./config/brand')
const csp = require('./config/csp')
const { cspReportLimiter } = require('./middleware/rateLimit')
const createLogger = require('./utils/logger')
const htmlShell = require('./utils/htmlShell')
const { applyTrustProxy, trustProxyDebug } = require('./utils/trustProxy')
const botScore = require('./middleware/botScore')
@@ -96,31 +97,6 @@ const htmlEscape = (s) =>
(c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]),
)
// Template the built index.html <head> with instance branding (title, meta
// description, Open Graph/Twitter, favicon). Done once at boot from BRAND_* env,
// so the prebuilt SPA image serves per-instance metadata without a rebuild.
function renderIndexHtml(html) {
const title = htmlEscape(brand.name)
const desc = htmlEscape(brand.description)
const tags = [
`<meta property="og:title" content="${title}" />`,
`<meta property="og:description" content="${desc}" />`,
'<meta property="og:type" content="website" />',
brand.url ? `<meta property="og:url" content="${htmlEscape(brand.url)}" />` : '',
brand.logo ? `<meta property="og:image" content="${htmlEscape(brand.logo)}" />` : '',
'<meta name="twitter:card" content="summary_large_image" />',
`<meta name="twitter:title" content="${title}" />`,
`<meta name="twitter:description" content="${desc}" />`,
brand.favicon ? `<link rel="icon" href="${htmlEscape(brand.favicon)}" />` : '',
]
.filter(Boolean)
.join('\n ')
return html
.replace(/<title>[\s\S]*?<\/title>/i, `<title>${title}</title>`)
.replace(/(<meta\s+name="description"\s+content=")[\s\S]*?("\s*\/?>)/i, `$1${desc}$2`)
.replace(/<\/head>/i, ` ${tags}\n </head>`)
}
// Uploaded images — always served, even during maintenance. Force nosniff so a
// stored file is never interpreted as anything other than its declared type
// (defense in depth alongside helmet's global X-Content-Type-Options, and in
@@ -204,9 +180,23 @@ if (fs.existsSync(BRAND_DIR)) {
if (fs.existsSync(path.join(CLIENT_DIST, 'index.html'))) {
// Serve a branded copy of the index.html shell for every SPA route; assets keep
// their own cache-friendly static handler.
const indexHtml = renderIndexHtml(fs.readFileSync(path.join(CLIENT_DIST, 'index.html'), 'utf8'))
//
// The shell is templated from BRAND_* env *and* the admin's brand_assets /
// theme_visual rows, so it is rendered lazily and cached rather than built once
// at boot: see utils/htmlShell.js for the caching, the invalidation and why a
// DB fault still serves a page.
htmlShell.init(fs.readFileSync(path.join(CLIENT_DIST, 'index.html'), 'utf8'))
app.use(express.static(CLIENT_DIST, { index: false }))
app.get('*', (req, res) => res.type('html').send(indexHtml))
app.get('*', async (req, res, next) => {
// htmlShell.get() swallows a settings-read failure itself; the try is for
// anything unforeseen, since an async handler that rejects in Express 4
// hangs the request instead of reaching the error handler below.
try {
res.type('html').send(await htmlShell.get())
} catch (err) {
next(err)
}
})
} else {
app.get('*', (req, res) =>
res

View File

@@ -2,6 +2,7 @@ const settingsDb = require('./settings.db')
const brand = require('../../config/brand')
const { parseJsonSetting } = require('../../utils/settingsJson')
const { resolveThemeTokens } = require('../../utils/themeResolve')
const { resolveBrandAssets } = require('../../utils/brandAssets')
// Keys safe to expose on the public site.
const PUBLIC_KEYS = [
@@ -158,10 +159,11 @@ async function getPublic() {
// site actually paints. See THEMING_AND_NAV.md §6.
const theme = resolveThemeTokens(all.theme_visual)
if (theme) out.theme = theme
// Uploaded brand-asset overrides (§6.3). Written by the Phase 5 admin UI;
// resolved here so every consumer of the brand block — the SPA, the Android
// app, the Discord bot — picks them up through the one contract.
const brandAssets = parseJsonSetting(all.brand_assets) || {}
// Uploaded brand-asset overrides (§6.3), resolved here so every consumer of
// the brand block — the SPA, the Android app, the Discord bot — picks them up
// through the one contract. Forgiving on read like the theme: a slot holding
// something we would not emit as a URL is dropped and its neighbours kept.
const brandAssets = resolveBrandAssets(parseJsonSetting(all.brand_assets))
// Instance branding (BRAND_* env defaults). The admin-editable settings —
// site title, contact email, and now the theme accent and uploaded assets —
// override the env value when set, so existing installs keep their
@@ -199,6 +201,28 @@ async function getPublic() {
return out
}
/**
* What the HTML shell needs, resolved exactly as getPublic() resolves it: the
* effective favicon and logo, plus the theme token map for the boot <style>
* block. Kept here rather than in utils/htmlShell.js so there is one authority
* for "which asset wins", and so the shell can never disagree with the payload
* the SPA fetches a moment later.
*
* Throws on a DB fault — the caller (utils/htmlShell.js) decides what a failure
* means for the page, and for it the answer is "serve the env-only shell".
*
* @returns {Promise<{logo: string, favicon: string, theme: object|null}>}
*/
async function getShellBrand() {
const all = await getAll()
const assets = resolveBrandAssets(parseJsonSetting(all.brand_assets))
return {
logo: assets.logo || brand.logo,
favicon: assets.favicon || brand.favicon,
theme: resolveThemeTokens(all.theme_visual),
}
}
// The two nav-override keys their own audiences need but cannot read from
// GET /admin/settings (admin-only, while AdminLayout renders for editors and
// moderators and PlayerPortalLayout renders for players — THEMING_AND_NAV.md
@@ -230,6 +254,7 @@ module.exports = {
setMany,
getAll,
getPublic,
getShellBrand,
getNav,
getInstanceName,
PUBLIC_KEYS,

View File

@@ -1,3 +1,5 @@
const fs = require('fs')
const posts = require('../../../model/posts/posts.model')
const wiki = require('../../../model/wiki/wiki.model')
const settings = require('../../../model/settings/settings.model')
@@ -11,6 +13,8 @@ const pushDispatch = require('../../../utils/pushDispatch')
const { cleanBody } = require('../../../utils/sanitizeHtml')
const { parseJsonSetting } = require('../../../utils/settingsJson')
const { validateThemeVisual } = require('../../../utils/themeResolve')
const { validateBrandAssets, resolveBrandAssets } = require('../../../utils/brandAssets')
const htmlShell = require('../../../utils/htmlShell')
const log = require('../../../utils/logger')('admin')
@@ -547,8 +551,28 @@ async function updateSettings(req, res) {
if (!check.ok) return res.status(400).json({ message: check.message })
updates.theme_visual = JSON.stringify(parsed)
}
// brand_assets holds the only settings values written straight into HTML the
// browser then fetches (an <img src>, a <link rel="icon">, an og:image), so
// the accepted shape is narrow — see utils/brandAssets.js. Cleared slots are
// dropped rather than stored as null, keeping "a field is absent" the single
// meaning of "falls back to BRAND_* env".
if ('brand_assets' in updates) {
const raw = updates.brand_assets
const parsed = typeof raw === 'string' ? parseJsonSetting(raw) : raw
if (typeof raw === 'string' && parsed === null) {
return res.status(400).json({ message: 'brand_assets must be a JSON object' })
}
const check = validateBrandAssets(parsed)
if (!check.ok) return res.status(400).json({ message: check.message })
updates.brand_assets = JSON.stringify(resolveBrandAssets(parsed))
}
try {
await settings.setMany(updates, req.user.id)
// The HTML shell is templated from brand_assets and theme_visual, and is
// cached per process (utils/htmlShell.js) — a write that can change it has
// to say so, or the favicon an admin just uploaded appears only after the
// cache's TTL.
if ('brand_assets' in updates || 'theme_visual' in updates) htmlShell.invalidate()
await activity.log({ req, action: 'settings.update', detail: { keys: Object.keys(updates) } })
return res.json(await settings.getAll())
} catch (err) {
@@ -557,6 +581,87 @@ async function updateSettings(req, res) {
}
}
// ── Brand assets ──────────────────────────────────────────────────────
//
// Per-slot rules applied on top of the shared multer allowlist. The allowlist
// itself is never widened (§9: "no second upload path with weaker validation") —
// these only ever tighten it:
//
// • favicon — PNG only. .ico would mean adding a new type to MIME_EXT, and the
// fact that the stored extension comes from that map is exactly what makes
// the upload path safe (§4.10). Every browser this app supports takes a PNG
// icon. Small cap: a favicon is a handful of KB.
// • logo — a header mark next to the site title, not a page image.
// • hero — a full-bleed background, so it keeps the shared ceiling.
//
// The cap is checked after multer has written the file rather than by a second
// multer instance: one upload config, one allowlist, and the oversized file is
// unlinked before we answer.
const ASSET_RULES = {
logo: { maxBytes: 1024 * 1024, mimetypes: null, label: 'Logo' },
hero: { maxBytes: 8 * 1024 * 1024, mimetypes: null, label: 'Hero image' },
favicon: { maxBytes: 512 * 1024, mimetypes: ['image/png'], label: 'Favicon' },
}
const prettyBytes = (n) => (n >= 1024 * 1024 ? `${Math.round(n / (1024 * 1024))} MB` : `${Math.round(n / 1024)} KB`)
// Best-effort cleanup of a file we have decided not to keep. A failure here is
// a stray file in /uploads, not something the caller can act on.
async function discardUpload(file) {
try {
await fs.promises.unlink(file.path)
} catch (err) {
log.error('discardUpload', err)
}
}
/**
* POST /admin/settings/brand-asset/:slot — upload one brand asset and point the
* brand_assets row at it in the same call.
*
* One call rather than "upload, then PUT the settings row": a half-completed
* save would otherwise leave a file in /uploads that nothing references, and the
* per-slot rules above need the slot at upload time anyway. Admin-only, matching
* the gate on the settings it writes — POST /admin/uploads is reachable by
* editors, who have no business changing the site's identity.
*/
async function uploadBrandAsset(req, res) {
const { slot } = req.params
const rules = ASSET_RULES[slot]
if (!rules) {
if (req.file) await discardUpload(req.file)
return res.status(400).json({ message: `Unknown brand asset '${slot}'` })
}
if (!req.file) return res.status(400).json({ message: 'No file uploaded' })
if (rules.mimetypes && !rules.mimetypes.includes(req.file.mimetype)) {
await discardUpload(req.file)
return res.status(400).json({ message: `${rules.label} must be a PNG image` })
}
if (req.file.size > rules.maxBytes) {
await discardUpload(req.file)
return res.status(400).json({ message: `${rules.label} must be ${prettyBytes(rules.maxBytes)} or smaller` })
}
const url = `/uploads/${req.file.filename}`
try {
// Read-modify-write the row: uploading a logo must not clear a hero the
// admin set earlier (§6.3). Resolved on the way in, so a hand-edited row
// with one bad slot does not block setting another.
const current = resolveBrandAssets(parseJsonSetting(await settings.get('brand_assets')))
const next = { ...current, [slot]: url }
await settings.set('brand_assets', JSON.stringify(next), req.user.id)
htmlShell.invalidate()
await activity.log({ req, action: 'settings.brandAsset', detail: { slot, url } })
return res.status(201).json({ url, brand_assets: next })
} catch (err) {
log.error('uploadBrandAsset', err)
// The row is the point of the call; a stored file nothing points at is
// litter, so it goes back out with the error.
await discardUpload(req.file)
return res.status(500).json({ message: 'Internal Server Error' })
}
}
// Delete one settings row — the "reset to defaults" primitive.
//
// For the theming/nav keys, defaults live in BRAND_* env, theme.css and the
@@ -576,6 +681,7 @@ async function deleteSetting(req, res) {
}
try {
await settings.remove(key)
if (key === 'brand_assets' || key === 'theme_visual') htmlShell.invalidate()
await activity.log({ req, action: 'settings.reset', detail: { key } })
return res.json({ message: 'Setting reset to default' })
} catch (err) {
@@ -810,6 +916,8 @@ module.exports = {
getSettings,
updateSettings,
deleteSetting,
uploadBrandAsset,
ASSET_RULES,
listActivity,
listUsers,
createUser,

View File

@@ -12,6 +12,7 @@
const express = require('express')
const ctrl = require('./admin.controller')
const { upload } = require('./imageUpload')
const { requireRole } = require('../../../utils/auth')
const settingsRouter = express.Router()
@@ -41,6 +42,26 @@ settingsRouter.put(
adminOnly,
ctrl.updateSettings,
)
// Upload one brand asset (logo/hero/favicon) and point brand_assets at it in the
// same call — see the controller for why it is one call and not "upload, then
// PUT". Uses the shared multer config (one upload directory, one mimetype
// allowlist); the per-slot PNG rule and size caps are applied in the handler.
settingsRouter.post(
'/brand-asset/:slot',
// #swagger.tags = ['Admin · Settings']
// #swagger.summary = 'Upload a brand asset and set it as the override (admin only)'
// #swagger.description = 'Stores the image and writes the brand_assets settings row in one call, so an upload never leaves an unreferenced file. Favicons must be PNG (max 512 KB); logos max 1 MB; heroes max 8 MB. Absent slots keep falling back to the BRAND_* env defaults — uploading a logo does not clear a hero.'
// #swagger.security = [{ "cookieAuth": [] }, { "bearerAuth": [] }]
/* #swagger.parameters['slot'] = { in: 'path', required: true, description: 'Which asset to replace', schema: { type: 'string', enum: ['logo', 'hero', 'favicon'] } } */
/* #swagger.requestBody = { required: true, content: { "multipart/form-data": { schema: { type: "object", properties: { image: { type: "string", format: "binary" } } } } } } */
/* #swagger.responses[201] = { description: 'Stored file URL and the updated overrides', content: { "application/json": { schema: { type: "object", properties: { url: { type: "string", example: "/uploads/1712345678901-ab12cd34.png" }, brand_assets: { type: "object", properties: { logo: { type: "string" }, hero: { type: "string" }, favicon: { type: "string" } } } } } } } } */
/* #swagger.responses[400] = { description: 'No file, unknown slot, disallowed type, or over the slot size cap', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[401] = { description: 'Not authenticated', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
/* #swagger.responses[403] = { description: 'Admin role required', content: { "application/json": { schema: { $ref: "#/components/schemas/Error" } } } } */
adminOnly,
upload.single('image'),
ctrl.uploadBrandAsset,
)
// Reset one setting to its default by deleting the row. Only the keys whose
// default lives outside the store (theming, nav, hero draft) are deletable —
// the controller holds the allowlist.

View File

@@ -0,0 +1,95 @@
// Uploaded brand-asset overrides — the `brand_assets` settings row.
//
// { "logo": "/uploads/1234-ab.png", "hero": null, "favicon": null }
//
// Each field, once set, holds a stored upload URL; a null or absent field falls
// back to brand.logo / brand.hero / brand.favicon from BRAND_* env. Uploading a
// logo does not force the admin to also pick a hero
// (docs/website/THEMING_AND_NAV.md §6.3).
//
// These values are the only part of the settings store that is written straight
// into HTML the browser then fetches — an <img src>, a <link rel="icon">, an
// og:image. So the accepted shape is deliberately narrow: a same-origin path
// under one of the three directories this app serves, and nothing else. No
// scheme, no protocol-relative `//host`, no `..`. The upload route only ever
// produces `/uploads/…`, so the other two prefixes exist for an admin who wants
// to point at an asset already baked into the image or mounted at /brand.
//
// Same strict-on-write / forgiving-on-read asymmetry as the theme
// (utils/themeResolve.js): a bad write is rejected with the field named, while a
// bad *stored* value is dropped field by field so a hand-edited row degrades to
// the env default instead of rendering a broken page.
// The three overridable assets, in the order the admin UI shows them.
const SLOTS = ['logo', 'hero', 'favicon']
// Directories this server actually serves: /uploads (UPLOAD_DIR), /brand
// (BRAND_DIR, optional) and /assets (the built SPA's static files).
const ALLOWED_PREFIXES = ['/uploads/', '/brand/', '/assets/']
/**
* Is this a value we are willing to emit as a URL into the page?
* @param {unknown} value
* @returns {boolean}
*/
function isSafeAssetPath(value) {
if (typeof value !== 'string' || value === '') return false
// A leading `//` is protocol-relative and would load from another origin
// despite looking like a path; `..` could climb out of the served directory.
if (value.startsWith('//') || value.includes('..')) return false
// Whitespace and control characters have no place in a stored path and are the
// raw material for `javascript:` smuggling past a naive prefix check.
if (/[\s<>"'\\]/.test(value)) return false
return ALLOWED_PREFIXES.some((prefix) => value.startsWith(prefix))
}
/**
* Validate a brand_assets object for WRITING. Strict: names the offending field.
* @param {unknown} value the parsed object (or null to clear every slot)
* @returns {{ok: true} | {ok: false, message: string}}
*/
function validateBrandAssets(value) {
if (value === null || value === undefined) return { ok: true }
if (typeof value !== 'object' || Array.isArray(value)) {
return { ok: false, message: 'brand_assets must be a JSON object' }
}
for (const [slot, url] of Object.entries(value)) {
if (!SLOTS.includes(slot)) {
return { ok: false, message: `Unknown brand asset '${slot}'` }
}
// null/'' is how a slot is cleared back to the env default — allowed, and
// stripped by the caller so the stored row never carries dead fields.
if (url === null || url === '') continue
if (!isSafeAssetPath(url)) {
return {
ok: false,
message: `brand_assets.${slot} must be an uploaded path under /uploads/, /brand/ or /assets/`,
}
}
}
return { ok: true }
}
/**
* Keep only the slots that hold a usable path. Serves both directions on
* purpose:
*
* • writing — an admin who removes their logo stores `{}` (and the caller
* deletes the row entirely) rather than a row full of nulls, which would
* read as "set to nothing" rather than "never set";
* • reading — an unusable stored field is dropped and its neighbours kept, so
* one bad slot cannot cost the admin the other two.
*
* @param {object|null} value an object, or a parseJsonSetting result
* @returns {{logo?: string, hero?: string, favicon?: string}}
*/
function resolveBrandAssets(value) {
const out = {}
if (!value || typeof value !== 'object') return out
for (const slot of SLOTS) {
if (isSafeAssetPath(value[slot])) out[slot] = value[slot]
}
return out
}
module.exports = { SLOTS, ALLOWED_PREFIXES, isSafeAssetPath, validateBrandAssets, resolveBrandAssets }

View File

@@ -0,0 +1,187 @@
// The SPA's HTML shell: index.html templated with this instance's branding.
//
// This used to be a one-liner at module load in app.js — read the built
// index.html, template it from BRAND_* env, serve that one string forever. The
// admin-configurable brand assets (docs/website/THEMING_AND_NAV.md §4.3) make
// the favicon and OG image settings-driven, which is a lifecycle change rather
// than an `await`: the shell now depends on a row that can change while the
// process runs.
//
// Three properties this module exists to guarantee:
//
// • It is a cached string in the steady state. A settings read per page view
// would put the database on the critical path of every SPA route, including
// during an outage where the API is already degraded.
// • A DB fault never fails the page. A read error renders the env-only shell —
// exactly what the code did before this feature — and that fallback is
// cached like any other, so an outage cannot turn every page view into a
// failing query.
// • With no brand_assets and no theme_visual row it is BYTE-IDENTICAL to what
// app.js served before. That is an acceptance criterion of §9, and the
// reason the theme <style> block and the asset overrides are appended only
// when they exist rather than always emitted with default values.
//
// Invalidation is explicit — the settings controller calls invalidate() after a
// successful write to brand_assets or theme_visual — with a TTL as a safety net.
// The cache is per process: in a scaled deployment the process that handled the
// write is the only one that learns of it, so without the TTL every other worker
// would serve the old favicon until the next restart.
const brand = require('../config/brand')
// How long a rendered shell is trusted without an explicit invalidation. Short
// enough that a second process converges on its own, long enough that this is
// still one render per process per five minutes rather than one per request.
const TTL_MS = 5 * 60 * 1000
// A stored theme reaches the browser twice: in this block, and again as inline
// properties once the SPA has fetched /public/settings. The block exists purely
// so a themed instance does not paint the shipped palette for one frame first;
// the client drops it (by id) as soon as it has the authoritative payload — see
// contexts/SiteContext.jsx.
const THEME_STYLE_ID = 'theme-boot'
// Belt and braces over the theme validators. Every token name comes from a fixed
// map and every value from a closed set (hex color, curated font stack, bounded
// px, listed shadow), so nothing that reaches here can carry markup today. These
// two patterns make that a property of the HTML writer rather than of a validator
// three modules away that someone may one day loosen.
const SAFE_TOKEN_NAME = /^--[a-zA-Z0-9-_]+$/
const SAFE_TOKEN_VALUE = /^[a-zA-Z0-9 ,.()#%_'"/-]+$/
let template = null // the built index.html, read once
let cached = null // { html, at }
let inflight = null // de-dupes a burst of requests on a cold cache
let generation = 0 // bumped by invalidate(); an in-flight render checks it
// Escape user/brand text for safe interpolation into the HTML shell.
function htmlEscape(s) {
return String(s).replace(
/[&<>"']/g,
(c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]),
)
}
/**
* An uploaded asset path is always relative (`/uploads/…`), but og:image is read
* off-site by scrapers that handle a relative URL poorly. Absolutize it against
* BRAND_URL when we have one.
*
* Env values pass through untouched even when relative: the shell an instance
* gets today is the operator's choice and must not change just because this
* module now exists.
*/
function absolutize(url) {
if (!brand.url || !url.startsWith('/')) return url
return `${brand.url.replace(/\/+$/, '')}${url}`
}
/**
* Render the shell. Pure — every input is a parameter, so a test can assert the
* byte-identical property without a database.
*
* @param {string} html the built index.html
* @param {{logo?: string, favicon?: string, theme?: object|null}} [overrides]
* effective brand assets and theme; anything absent falls back to BRAND_* env
* @returns {string}
*/
function render(html, overrides = {}) {
const title = htmlEscape(brand.name)
const desc = htmlEscape(brand.description)
// Effective values: an uploaded override wins over env, absence means env.
const logo = overrides.logo ? absolutize(overrides.logo) : brand.logo
const favicon = overrides.favicon || brand.favicon
const tags = [
`<meta property="og:title" content="${title}" />`,
`<meta property="og:description" content="${desc}" />`,
'<meta property="og:type" content="website" />',
brand.url ? `<meta property="og:url" content="${htmlEscape(brand.url)}" />` : '',
logo ? `<meta property="og:image" content="${htmlEscape(logo)}" />` : '',
'<meta name="twitter:card" content="summary_large_image" />',
`<meta name="twitter:title" content="${title}" />`,
`<meta name="twitter:description" content="${desc}" />`,
favicon ? `<link rel="icon" href="${htmlEscape(favicon)}" />` : '',
themeStyleTag(overrides.theme),
]
.filter(Boolean)
.join('\n ')
return html
.replace(/<title>[\s\S]*?<\/title>/i, `<title>${title}</title>`)
.replace(/(<meta\s+name="description"\s+content=")[\s\S]*?("\s*\/?>)/i, `$1${desc}$2`)
.replace(/<\/head>/i, ` ${tags}\n </head>`)
}
// The admin theme as a :root block, or '' when this instance has never been
// themed. Injected last in <head> so it follows the built stylesheet and wins
// the equal-specificity tie against theme.css's own :root.
function themeStyleTag(theme) {
if (!theme || typeof theme !== 'object') return ''
const decls = Object.entries(theme)
.filter(([name, value]) => SAFE_TOKEN_NAME.test(name) && typeof value === 'string' && SAFE_TOKEN_VALUE.test(value))
.map(([name, value]) => `${name}:${value}`)
.join(';')
return decls ? `<style id="${THEME_STYLE_ID}">:root{${decls}}</style>` : ''
}
/**
* Provide the built index.html. Called once at boot by app.js; a separate step
* from get() so the file read stays synchronous and startup still fails loudly
* if the client build is unreadable.
*/
function init(html) {
template = html
cached = null
inflight = null
generation += 1
}
/** Drop the cached shell. Called after any write that can change it. */
function invalidate() {
cached = null
inflight = null
generation += 1
}
/**
* The current shell. Renders on a cold or expired cache, otherwise returns the
* cached string. Never rejects: a settings read that fails yields the env-only
* shell.
*
* @returns {Promise<string>}
*/
async function get() {
if (template === null) throw new Error('htmlShell.init() was never called')
if (cached && Date.now() - cached.at < TTL_MS) return cached.html
if (inflight) return inflight
const startedAt = generation
const run = (async () => {
let overrides = {}
try {
// Required lazily: this module is loaded by app.js at boot, and the
// settings model pulls in the DB pool. Requiring it at the top would make
// the HTML shell a startup-time dependency of the database.
// eslint-disable-next-line global-require
const settings = require('../model/settings/settings.model')
overrides = await settings.getShellBrand()
} catch {
// A DB fault must never fail the page (§4.3). Fall back to the env-only
// shell — the pre-feature behaviour — and cache it, so an outage does not
// mean a failing query per page view.
overrides = {}
}
const html = render(template, overrides)
// An invalidation that landed while this read was in flight means the value
// we just read may already be stale. Serve it, but do not cache it.
if (generation === startedAt) cached = { html, at: Date.now() }
// Only retire our own registration: an invalidation during the read may have
// already started a newer render, and clearing that one would cost an extra
// render on the next request.
if (inflight === run) inflight = null
return html
})()
inflight = run
return run
}
module.exports = { init, get, invalidate, render, TTL_MS, THEME_STYLE_ID }