feat(brand): phase 2 — the branding pipeline
All checks were successful
PR checks / checks (pull_request) Successful in 9m9s

PLAN.md §7: swapping a logo or recolouring the site is a file copy and a
container restart, never a rebuild. Phase 2 builds the mechanism and the
checks that keep it true.

GET /brand/* resolves every file against the mount first and the baked-in
defaults second, per file, at stable unhashed URLs with an ETag and a five
minute TTL. Nothing goes through Vite, which would fingerprint the names out
of the mount's reach. An X-Brand-Source header says which step answered.

Three decisions were taken with the org lead (recorded as D14-D16 in §7):

D14 — one raster in, every size out. brand-default holds a single logo.png;
the header mark at three pixel ratios, both install icons, the apple-touch
icon, the favicons and a real multi-resolution favicon.ico are derived on
request from whichever logo.png is in force, cached, and limited to an
allowlist of sizes. Shipping fifteen precomputed files would have meant an
operator producing fifteen to change a mark — and getting a new header with
the old favicon.

D15 — brand text is applied at boot. Pages are prerendered, so §7's promise
about the site name, tagline and links could not hold at render time.
npm start now runs scripts/applyBrand.mjs first, rewriting the built HTML
from what it last applied to what the mount says. It rewrites from a record
in dist/.brand-applied.json rather than from the defaults, because the naive
version works exactly once and then silently ignores every later edit. An
empty mount is a no-op; removing a mount restores the stock build byte for
byte. Verified both ways, plus a second rename.

D16 — the header shows the real emblem, replacing phase 1's placeholder
glyph, so the site, the product and the Android launcher icon are one mark.
It is raster art, so theme.css cannot recolour it; replacing logo.png is how
the mark changes.

Two defects found and fixed while proving it:

The mounted theme.css did not win. Astro emits its own stylesheet after the
head markup, so linking the operator's last was not enough and every override
was silently a no-op. tokens.css now lives in @layer tokens and the mounted
file is unlayered, which takes order out of the mechanism entirely.

The documentation was a different site. Starlight builds its own head, so the
docs linked a Starlight default /favicon.svg that does not exist here, carried
no manifest or OG card, and never loaded the brand stylesheet — a mounted
theme recoloured the marketing pages and left the docs stock. A Head override
fixes it; half a rebrand looks like a product bug rather than a missed step.

brand-default/wordmark.svg and og-image.png are generated by
scripts/buildBrandAssets.mjs from the emblem and Cinzel's outlines and are
committed, so CI needs neither the artwork nor a font. Type is converted to
paths, because an SVG in an <img> can see neither the page's @font-face rules
nor fontconfig — the same isolation that broke currentColor in phase 1. Its
glyphs are drawn at the origin and translated: opentype.js emits NaN
coordinates at a non-zero origin for some glyphs, and a path parser stops at
the first malformed command, so the first lockup read "Runic Gate" and looked
like a typo rather than a bug.

scripts/checkBrand.mjs is the mechanism for the two failures that are
otherwise silent: it puts every literal /brand/... URL in the source through
the route's own classifier, so a size that is not on the allowlist fails the
build instead of 404ing in a browser, and it rejects a brand string short
enough that a blind replacement at boot could corrupt a page. Negative-tested
three ways before being trusted. It runs in CI ahead of the type check.

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2026-08-19 23:14:17 -05:00
parent dae7964ca6
commit fe4abe0ebf
24 changed files with 1822 additions and 172 deletions

232
scripts/applyBrand.mjs Normal file
View File

@@ -0,0 +1,232 @@
#!/usr/bin/env node
/**
* applyBrand.mjs — brand TEXT from the bind mount (PLAN.md §7)
*
* Runs immediately before the server, as part of `npm start`. For an empty mount — the
* stock deployment, and the common case — it reads two small files, finds nothing to do
* and exits. It is not a build step and it is not a template engine.
*
* ---------------------------------------------------------------------------------------
* THE PROBLEM THIS SOLVES
* ---------------------------------------------------------------------------------------
* §7 promises that renaming the product, changing the Discord invite or publishing a
* different contact address is the same class of change as swapping a logo: edit the file
* in the mount, restart, done. §6 prerenders every page. Those two are in direct conflict,
* because a value read at build time is baked into HTML that no mounted file can reach.
*
* Assets escape the conflict by being served per request from `/brand/*`. Text cannot: it
* is inside the markup.
*
* Three ways out were considered and the org lead chose this one (2026-08-20):
*
* 1. THIS — rewrite the built HTML at boot, before the server opens a socket. Every page
* stays prerendered, Pagefind still has static HTML to index in phase 10, and the docs
* are covered by the same pass as the marketing pages.
* 2. Mark the brand-bearing pages `prerender = false`. Simpler, but the footer is on
* every page, so "the handful" is the whole site — and the docs would have to stay
* static for search anyway, leaving them showing the stock name.
* 3. Accept text as build-time and amend §7. Cheapest, and it gives up the promise.
*
* ---------------------------------------------------------------------------------------
* WHY IT REWRITES FROM A RECORD RATHER THAN FROM THE DEFAULTS
* ---------------------------------------------------------------------------------------
* The obvious version of this script replaces the DEFAULT value with the mounted one. It
* works exactly once. The second time an operator edits the mount — renaming from "Foo" to
* "Bar" — the default no longer appears anywhere in the HTML, every replacement matches
* nothing, and the site silently keeps saying "Foo". The bug would surface as "the first
* change worked and the second did nothing", which is a miserable thing to debug.
*
* So the script records what it baked, in `dist/.brand-applied.json`, and the next run
* rewrites from that record to the new values. A fresh image has no record and starts from
* the defaults, which is the same thing said differently.
*
* ---------------------------------------------------------------------------------------
* WHAT MAKES PLAIN STRING REPLACEMENT SAFE HERE
* ---------------------------------------------------------------------------------------
* Not much, on its own — which is why `scripts/checkBrand.mjs` exists. It fails the build
* if any rewritable default is short enough to collide with ordinary markup or prose. The
* check is the mechanism; the eight-character minimum below is only its last line.
*
* Replacing the site name across the docs as well as the marketing pages is deliberate. If
* the product is renamed, prose that says "Runic Gateway" should say the new name too.
*/
import { readFileSync, writeFileSync, existsSync, readdirSync, statSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
const ROOT = fileURLToPath(new URL('..', import.meta.url));
const DIST = process.env.BRAND_DIST || path.join(ROOT, 'dist');
const CLIENT = path.join(DIST, 'client');
const RECORD = path.join(DIST, '.brand-applied.json');
const MOUNT_DIR = process.env.BRAND_DIR || path.join(process.cwd(), 'brand');
const DEFAULT_DIR = process.env.BRAND_DEFAULT_DIR || path.join(process.cwd(), 'brand-default');
/**
* The fields that appear in markup as literal text, and may therefore be rewritten.
*
* `demoUrl` is not one of them and is handled separately below: its default is the empty
* string, and there is no such thing as replacing every occurrence of "".
*/
const TEXT_FIELDS = ['siteName', 'tagline', 'contactEmail', 'discordInvite', 'giteaOrg'];
/**
* Below this length a value is too likely to occur inside unrelated markup — a class name,
* an attribute, a word in a sentence — for a blind replacement to be safe. `checkBrand.mjs`
* enforces the same floor at build time, where the failure is cheap; this is the copy that
* runs in production, where being wrong means corrupted pages.
*/
const MIN_REWRITABLE_LENGTH = 8;
const REWRITABLE_EXTENSIONS = new Set(['.html', '.webmanifest']);
function readJson(file, label) {
try {
return JSON.parse(readFileSync(file, 'utf8'));
} catch (error) {
if (error.code === 'ENOENT') return null;
// A malformed mounted brand.json must not take the site down.
//
// The alternative — exit non-zero and let the container crash-loop — surfaces the typo
// immediately, and that is genuinely tempting. But an operator editing a mount is
// watching the logs, whereas the restart six months later that trips over the same file
// is unattended, and a marketing site that is up with stock branding beats one that is
// down with correct branding.
console.error(`\n[brand] ${label} is not valid JSON and will be IGNORED:\n ${file}\n ${error.message}\n`);
return null;
}
}
/** `$comment` keys are documentation for whoever opens the mounted copy, not fields. */
const fieldsOf = (object) =>
Object.fromEntries(Object.entries(object || {}).filter(([key]) => !key.startsWith('$')));
const defaults = fieldsOf(readJson(path.join(DEFAULT_DIR, 'brand.json'), 'the stock brand.json'));
const mounted = fieldsOf(readJson(path.join(MOUNT_DIR, 'brand.json'), 'the mounted brand.json'));
if (!Object.keys(defaults).length) {
console.error(
`\n[brand] no stock brand.json at ${path.join(DEFAULT_DIR, 'brand.json')}.\n` +
`brand-default/ is baked into the image and must always be complete (§7).\n`
);
process.exit(1);
}
for (const key of Object.keys(mounted)) {
if (!(key in defaults)) {
console.warn(`[brand] the mounted brand.json sets an unknown field "${key}" — ignoring it.`);
}
}
const resolved = { ...defaults, ...mounted };
const previous = { ...defaults, ...(fieldsOf(readJson(RECORD, 'the applied-brand record')) || {}) };
/* ---------------------------------------------------------------------------------------
Work out what actually changed
--------------------------------------------------------------------------------------- */
const escapeHtml = (value) =>
value.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
const replacements = [];
for (const field of TEXT_FIELDS) {
const from = previous[field];
const to = resolved[field];
if (typeof from !== 'string' || typeof to !== 'string' || from === to) continue;
if (from.length < MIN_REWRITABLE_LENGTH) {
console.error(
`[brand] refusing to rewrite "${field}": the value being replaced (${JSON.stringify(from)}) ` +
`is under ${MIN_REWRITABLE_LENGTH} characters and would match unrelated markup.`
);
continue;
}
replacements.push({ field, from, to });
// Astro escapes `&`, `<`, `>` and `"` when it writes a value into markup, so a Discord
// invite or a Gitea URL carrying a query string appears in the HTML in its escaped form.
// Adding the escaped pair rather than unescaping the document keeps this a string
// operation on bytes, with no parser to disagree with the browser's.
const escapedFrom = escapeHtml(from);
if (escapedFrom !== from) replacements.push({ field, from: escapedFrom, to: escapeHtml(to) });
}
/**
* The demo slot (§15 / D12) is a rendering decision rather than a piece of text, and this
* is the one place a string replacement can still express it.
*
* The markup contract, which phase 3 writes and this script relies on:
*
* <a class="demo-cta" href="" data-demo-url="">See it running</a>
*
* `global.css` hides `[data-demo-url='']`, so a stock build renders nothing. Setting
* `demoUrl` in the mount turns both empty attributes into the URL, which fills the link and
* reveals it in the same edit. Going back to an empty value reverses it, because the
* previous value is in the record.
*/
const demoFrom = previous.demoUrl || '';
const demoTo = resolved.demoUrl || '';
if (demoFrom !== demoTo) {
const attr = (value) => `href="${escapeHtml(value)}" data-demo-url="${escapeHtml(value)}"`;
replacements.push({ field: 'demoUrl', from: attr(demoFrom), to: attr(demoTo) });
}
if (!replacements.length) {
console.log('[brand] mount matches what is already applied; nothing to rewrite.');
process.exit(0);
}
/* ---------------------------------------------------------------------------------------
Rewrite
--------------------------------------------------------------------------------------- */
if (!existsSync(CLIENT)) {
console.error(`\n[brand] no build to rewrite at ${CLIENT}. Run \`npm run build\` first.\n`);
process.exit(1);
}
function* walk(dir) {
for (const entry of readdirSync(dir, { withFileTypes: true })) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) yield* walk(full);
else if (REWRITABLE_EXTENSIONS.has(path.extname(entry.name))) yield full;
}
}
const counts = new Map(replacements.map((r) => [r.field, 0]));
let filesTouched = 0;
for (const file of walk(CLIENT)) {
const before = readFileSync(file, 'utf8');
let after = before;
for (const { field, from, to } of replacements) {
if (!after.includes(from)) continue;
counts.set(field, counts.get(field) + after.split(from).length - 1);
after = after.split(from).join(to);
}
if (after !== before) {
writeFileSync(file, after);
filesTouched++;
}
}
writeFileSync(RECORD, `${JSON.stringify(resolved, null, 2)}\n`);
console.log(`[brand] applied the mounted brand to ${filesTouched} file(s):`);
for (const { field, from, to } of replacements) {
if (from.startsWith('href=')) continue; // the demo pair, reported once below
console.log(` ${field.padEnd(14)} ${JSON.stringify(from)} -> ${JSON.stringify(to)} (${counts.get(field)}x)`);
}
if (demoFrom !== demoTo) {
console.log(` ${'demoUrl'.padEnd(14)} ${demoTo ? `slot shown -> ${demoTo}` : 'slot hidden'} (${counts.get('demoUrl')}x)`);
}
// Pagefind builds its search index from the HTML at BUILD time (phase 10), so a rename
// applied here reaches the pages but not the search results. Worth fixing when search
// lands; recorded here rather than in a plan section nobody will re-read.

View File

@@ -0,0 +1,407 @@
#!/usr/bin/env node
/**
* buildBrandAssets.mjs — PLAN.md §7, §11, D11
*
* Generates the stock brand assets in `brand-default/` from the project's real artwork.
* Its output is COMMITTED: `brand-default/` is baked into the image and must always be
* complete (§7), and CI must not need the artwork, a font file, or a working network to
* build the site. This script is an authoring tool, run by hand when the mark changes.
*
* node scripts/buildBrandAssets.mjs # regenerate everything
* node scripts/buildBrandAssets.mjs --check # verify the committed output is current
*
* WHAT IT WRITES, AND WHAT IT DELIBERATELY DOES NOT
* -------------------------------------------------------------------------------------
* Four files, and only four:
*
* logo.png 512x512 the canonical raster mark
* wordmark.svg the horizontal lockup, emblem + "Runic Gateway"
* og-image.png 1200x630 the link preview card
* theme.css written by hand, not here — listed only so the set is legible
*
* Every other size and format the site asks for — logo-64.webp, icon-192.png, favicon.ico,
* apple-touch-icon.png — is DERIVED AT RUNTIME by `src/pages/brand/[...file].ts` from
* whichever `logo.png` is in force. That is the decision that keeps §7's promise literally
* true: "swapping a logo is a file copy" means ONE file, not fifteen. Precomputing the
* derivatives here would mean an operator who drops in a new logo.png gets a new header
* mark and the old favicon, which is worse than either outcome.
*
* THE SOURCES LIVE OUTSIDE THIS REPOSITORY, ON PURPOSE
* -------------------------------------------------------------------------------------
* The emblem belongs to the product (D11 — the same file is the website's logo and the
* Android launcher icon; adopting it is what makes the three surfaces one product), and
* Cinzel's outlines come from the Android app's font directory because opentype.js cannot
* read the WOFF2 that `@fontsource-variable/cinzel` ships. Both are read from the sibling
* checkouts in the workspace and neither is vendored: a 1.4 MB PNG and a 125 KB TTF in a
* repository that needs them once per redesign is a cost paid on every clone forever.
*
* Override either with --emblem / --cinzel / --inter if the workspace is laid out
* differently. Without them the script fails loudly rather than quietly skipping a file,
* because a half-regenerated brand-default is worse than an untouched one.
*/
import { createHash } from 'node:crypto';
import { existsSync, readFileSync, writeFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import opentype from 'opentype.js';
import sharp from 'sharp';
const ROOT = fileURLToPath(new URL('..', import.meta.url));
const WORKSPACE = path.resolve(ROOT, '..');
const OUT = path.join(ROOT, 'brand-default');
const argv = process.argv.slice(2);
const CHECK_ONLY = argv.includes('--check');
function flag(name, fallback) {
const at = argv.indexOf(`--${name}`);
return at !== -1 && argv[at + 1] ? path.resolve(argv[at + 1]) : fallback;
}
const SOURCES = {
emblem: flag(
'emblem',
path.join(WORKSPACE, 'website/client/public/assets/img/runic-emblem.png')
),
cinzel: flag(
'cinzel',
path.join(WORKSPACE, 'android-app/app/src/main/res/font/cinzel_variable.ttf')
),
inter: flag(
'inter',
path.join(WORKSPACE, 'android-app/app/src/main/res/font/inter_variable.ttf')
),
};
for (const [name, file] of Object.entries(SOURCES)) {
if (existsSync(file)) continue;
console.error(
`\nbuildBrandAssets: the ${name} source is missing.\n\n expected: ${file}\n\n` +
`This script reads the product's own artwork from the sibling checkouts in the\n` +
`workspace (see the header). Pass --${name} <path> if yours is elsewhere.\n`
);
process.exit(1);
}
/* -------------------------------------------------------------------------------------
Tokens
-------------------------------------------------------------------------------------
The generated assets are part of the design system, so their colours come from the token
file rather than from this script. Same flat regex as `src/lib/tokens.mjs`, for the same
reason: the file is one we own and keep flat, and a CSS parser here would be a
dependency bought for four lookups.
Note the direction of the exception. `checkTokens.mjs` forbids a colour literal in
`src/`; the literals it writes into `brand-default/` are fine and are meant to be there,
because those files ARE the stock brand — the very thing an operator replaces. */
const tokens = Object.fromEntries(
readFileSync(path.join(ROOT, 'src/styles/tokens.css'), 'utf8')
.replace(/\/\*[\s\S]*?\*\//g, '')
.matchAll(/(--[a-z0-9-]+)\s*:\s*([^;]+);/gi)
.map((m) => [m[1], m[2].trim()])
);
const brand = JSON.parse(readFileSync(path.join(OUT, 'brand.json'), 'utf8'));
/* -------------------------------------------------------------------------------------
Type
------------------------------------------------------------------------------------- */
/**
* Cinzel and Inter both ship as variable fonts, and opentype.js reads the DEFAULT instance
* unless told otherwise — for Cinzel that is wght 400, which is too light to carry a
* wordmark. `variation.set` moves the axis before the outlines are taken.
*/
function loadFont(file, weight) {
const font = opentype.parse(readFileSync(file).buffer);
font.variation.set({ wght: weight });
return font;
}
/**
* Text as outlines, never as a `<text>` element.
*
* An SVG referencing a font family only renders correctly where that font is installed.
* Loaded through `<img>` — which is how `wordmark.svg` is used — the SVG is an independent
* document that cannot see the page's `@font-face` rules, and librsvg (which sharp uses to
* rasterise the OG card) resolves families through fontconfig, where Cinzel is not. Both
* would silently fall back to a serif default. Outlines have no such dependency: the shape
* is the file.
*
* The same class of mistake as phase 1's `currentColor`-through-`<img>` bug — an SVG in an
* `<img>` inherits nothing from the page, neither colour nor fonts.
*/
function textPath(font, text, size, { x = 0, y = 0, tracking = 0, fill }) {
const scale = size / font.unitsPerEm;
const parts = [];
let cursor = x;
// `charToGlyph` per character rather than `stringToGlyphs`, which runs opentype.js's
// shaper and throws on Cinzel: "substitutionType : 62 lookupType: 6 - substFormat: 2 is
// not yet supported", from a `ccmp` lookup it cannot read. Shaping buys nothing here —
// the strings are Latin, and Cinzel is an all-caps face with no ligatures to form — so
// the plain mapping is both sufficient and the more predictable of the two.
const glyphs = [...text].map((char) => font.charToGlyph(char));
for (const [i, glyph] of glyphs.entries()) {
// Every glyph is drawn at the ORIGIN and moved into place with a transform, rather
// than drawn at `cursor` directly.
//
// Asking opentype.js for a path at a non-zero origin produces NaN coordinates in some
// glyphs — which glyph depends on the exact cursor value, so it moves as the string or
// the tracking changes. An SVG path parser stops at the first malformed command and
// renders what it had, so the failure is silent and partial: the first draft of this
// lockup read "Runic Gate" and looked like a typo rather than a bug. At the origin the
// output is clean for every glyph, with and without the variation axis set.
const glyphPath = glyph.getPath(0, 0, size);
if (glyphPath.commands.length) {
const dx = cursor.toFixed(2);
const dy = y.toFixed(2);
parts.push(`<path transform="translate(${dx} ${dy})" d="${glyphPath.toPathData(2)}"/>`);
}
cursor += glyph.advanceWidth * scale + tracking;
// Kerning is per PAIR, so it is applied looking ahead rather than per glyph.
if (glyphs[i + 1]) cursor += font.getKerningValue(glyph, glyphs[i + 1]) * scale;
}
const markup = `<g fill="${fill}">${parts.join('')}</g>`;
// The guard that makes the bug above unable to ship again. A malformed path degrades
// quietly in every renderer; this file is generated once and committed, so the check
// costs nothing and the alternative is noticing in a link preview.
if (markup.includes('NaN') || markup.includes('undefined')) {
throw new Error(
`buildBrandAssets: the outlines for ${JSON.stringify(text)} contain a malformed ` +
`coordinate. This is the opentype.js positioning bug described above — the glyphs ` +
`must be drawn at the origin and translated.`
);
}
return { width: cursor - x, markup };
}
/** The advance width of a run, without building the outlines — for centring. */
function measure(font, text, size, tracking = 0) {
return textPath(font, text, size, { tracking, fill: 'none' }).width;
}
/* -------------------------------------------------------------------------------------
The mark
------------------------------------------------------------------------------------- */
/**
* The emblem is a 1024x1024 illustration that does not fill its canvas — trimmed it is
* 931x975, and off-centre by 43px. Left alone, a 40px header logo would render the mark at
* about 36px and sit visibly high.
*
* So: trim the transparent margin, then re-centre on a square canvas with a small even
* margin. Every derivative the runtime produces descends from this, which is what makes
* "the header mark and the favicon are the same shape" true by construction rather than by
* care.
*/
async function canonicalLogo(size = 512) {
const margin = 0.02; // 2%, so the ring never touches a rounded mask's edge
const inner = Math.round(size * (1 - margin * 2));
const trimmed = await sharp(SOURCES.emblem)
.trim({ threshold: 1 })
.resize(inner, inner, { fit: 'contain', background: { r: 0, g: 0, b: 0, alpha: 0 } })
.png()
.toBuffer();
return sharp({
create: {
width: size,
height: size,
channels: 4,
background: { r: 0, g: 0, b: 0, alpha: 0 },
},
})
.composite([{ input: trimmed, gravity: 'centre' }])
.png({ compressionLevel: 9, palette: false })
.toBuffer();
}
/* -------------------------------------------------------------------------------------
The outputs
------------------------------------------------------------------------------------- */
/**
* The horizontal lockup (§7): the emblem beside the product name.
*
* The emblem rides along as a base64 PNG rather than a link, because a `<img src>`-loaded
* SVG cannot fetch a sibling file — same isolation rule as the fonts above. It is embedded
* at 2x the drawn size so the lockup stays sharp on a retina display without carrying the
* full 512.
*/
async function buildWordmark() {
const cinzel = loadFont(SOURCES.cinzel, 600);
const H = 120;
// The mark does not fill the lockup's height. `canonicalLogo` trims the artwork to its
// own edges, so a mark drawn at the full 120 touches the top and bottom of the canvas and
// reads as cropped — the ring's extremities sit exactly on the boundary. The inset is
// optical breathing room, not padding to align anything.
const markSize = 104;
const gap = 26;
const type = 62;
const tracking = type * 0.04; // matches .brand-lockup__name letter-spacing in global.css
const embedded = await sharp(await canonicalLogo(512))
.resize(markSize * 2, markSize * 2)
.png({ compressionLevel: 9 })
.toBuffer();
// Cap height rather than baseline: Cinzel is all-caps, so optical centring means
// centring the caps box, not the em box.
const capHeight = cinzel.tables.os2.sCapHeight
? (cinzel.tables.os2.sCapHeight / cinzel.unitsPerEm) * type
: type * 0.7;
const baseline = H / 2 + capHeight / 2;
const name = textPath(cinzel, brand.siteName, type, {
x: markSize + gap,
y: baseline,
tracking,
fill: tokens['--gold'],
});
const width = Math.ceil(markSize + gap + name.width);
const svg = `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${width}" height="${H}" viewBox="0 0 ${width} ${H}" role="img" aria-label="${brand.siteName}">
<title>${brand.siteName}</title>
<image x="0" y="${(H - markSize) / 2}" width="${markSize}" height="${markSize}" xlink:href="data:image/png;base64,${embedded.toString('base64')}"/>
${name.markup}
</svg>
`;
return Buffer.from(svg, 'utf8');
}
/**
* The link preview card (§7).
*
* Everything on it is derived: the mark from the emblem, the name and tagline from
* `brand.json`, every colour from `tokens.css`. Nothing is typed in twice, so the card
* cannot drift from the site the way a hand-made one does.
*
* It is a committed FILE rather than a runtime render because an operator who changes the
* tagline in the mounted `brand.json` should be able to replace the card by dropping in a
* PNG, which is the same gesture as replacing the logo — and because rendering type at
* request time would put a font dependency into the container for one image.
*/
async function buildOgImage() {
const W = 1200;
const H = 630;
const cinzel = loadFont(SOURCES.cinzel, 600);
const inter = loadFont(SOURCES.inter, 400);
const markSize = 180;
const nameSize = 74;
const nameTracking = nameSize * 0.04;
const taglineSize = 30;
const nameWidth = measure(cinzel, brand.siteName, nameSize, nameTracking);
const taglineWidth = measure(inter, brand.tagline, taglineSize);
const markY = 118;
const nameBaseline = markY + markSize + 96;
const taglineBaseline = nameBaseline + 74;
const mark = await sharp(await canonicalLogo(512))
.resize(markSize, markSize)
.png()
.toBuffer();
const name = textPath(cinzel, brand.siteName, nameSize, {
x: (W - nameWidth) / 2,
y: nameBaseline,
tracking: nameTracking,
fill: tokens['--gold'],
});
const tagline = textPath(inter, brand.tagline, taglineSize, {
x: (W - taglineWidth) / 2,
y: taglineBaseline,
fill: tokens['--muted'],
});
// The glow is the portal's own colour at low opacity — the same treatment §11 asks for
// behind the diagrams, so the card reads as part of the site rather than a poster of it.
const backdrop = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}">
<defs>
<radialGradient id="glow" cx="50%" cy="${((markY + markSize / 2) / H) * 100}%" r="46%">
<stop offset="0%" stop-color="${tokens['--portal-deep']}" stop-opacity="0.30"/>
<stop offset="65%" stop-color="${tokens['--portal-deep']}" stop-opacity="0.06"/>
<stop offset="100%" stop-color="${tokens['--portal-deep']}" stop-opacity="0"/>
</radialGradient>
</defs>
<rect width="${W}" height="${H}" fill="${tokens['--bg']}"/>
<rect width="${W}" height="${H}" fill="url(#glow)"/>
<rect x="0" y="${H - 6}" width="${W}" height="6" fill="${tokens['--gold-deep']}"/>
</svg>`;
const type = `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}">
${name.markup}
${tagline.markup}
</svg>`;
return sharp(Buffer.from(backdrop))
.composite([
{ input: mark, left: Math.round((W - markSize) / 2), top: markY },
{ input: Buffer.from(type), left: 0, top: 0 },
])
.png({ compressionLevel: 9 })
.toBuffer();
}
/* -------------------------------------------------------------------------------------
Write, or verify
------------------------------------------------------------------------------------- */
const artifacts = [
['logo.png', await canonicalLogo(512)],
['wordmark.svg', await buildWordmark()],
['og-image.png', await buildOgImage()],
];
const digest = (buffer) => createHash('sha256').update(buffer).digest('hex').slice(0, 12);
let stale = 0;
for (const [name, bytes] of artifacts) {
const file = path.join(OUT, name);
const existing = existsSync(file) ? readFileSync(file) : null;
const unchanged = existing && existing.equals(bytes);
const size = `${(bytes.length / 1024).toFixed(1)} kB`.padStart(9);
if (CHECK_ONLY) {
if (unchanged) {
console.log(` ok ${name.padEnd(14)} ${size} ${digest(bytes)}`);
} else {
stale++;
console.error(` STALE ${name.padEnd(14)} ${size} ${digest(bytes)}`);
}
continue;
}
writeFileSync(file, bytes);
console.log(` ${unchanged ? 'same' : 'wrote'.padEnd(4)} ${name.padEnd(14)} ${size} ${digest(bytes)}`);
}
if (CHECK_ONLY && stale) {
console.error(
`\nbuildBrandAssets --check: ${stale} committed asset(s) no longer match what the\n` +
`sources produce. Run \`node scripts/buildBrandAssets.mjs\` and commit the result.\n`
);
process.exit(1);
}
console.log(
CHECK_ONLY
? '\nbuildBrandAssets: the committed brand-default assets are current.'
: '\nbuildBrandAssets: brand-default is regenerated. Commit the result.'
);

231
scripts/checkBrand.mjs Normal file
View File

@@ -0,0 +1,231 @@
#!/usr/bin/env node
/**
* checkBrand.mjs — PLAN.md §7
*
* The branding pipeline makes two promises that nothing else in the build can verify, and
* both fail quietly rather than loudly. This is their mechanism, in the same spirit as
* `checkTokens.mjs`: diligence does not survive contact with a year of commits.
*
* 1. EVERY `/brand/*` URL THE SITE ASKS FOR MUST ACTUALLY RESOLVE.
* The route serves an allowlist of names and derives a fixed set of sizes. A template
* that asks for `/brand/logo-44.webp` — a plausible number that is not on the list —
* gets a 404, and a missing logo is exactly the kind of thing that looks like a
* styling glitch and survives review. So every literal `/brand/...` in the source is
* put through the route's own classifier, rather than a copy of its rules.
*
* 2. EVERY REWRITABLE BRAND STRING MUST BE SAFE TO REPLACE BLINDLY.
* `applyBrand.mjs` swaps brand text in built HTML with plain string replacement.
* That is safe only while the values are distinctive: a `siteName` of "Site", or a
* tagline that contains the site name inside it, would corrupt pages at boot on a
* machine nobody is watching. Checking it here makes the failure a red build.
*
* 3. `brand-default/` must be complete, because §7 says it always is.
*
* node scripts/checkBrand.mjs
*/
import { readFileSync, existsSync, statSync } from 'node:fs';
import { readdir } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import sharp from 'sharp';
import { classify } from '../src/lib/brandAssets.mjs';
const ROOT = fileURLToPath(new URL('..', import.meta.url));
const DEFAULTS = path.join(ROOT, 'brand-default');
const failures = [];
const fail = (message) => failures.push(message);
/* =======================================================================================
1. brand-default is complete
======================================================================================= */
/**
* The stock set is deliberately small. Everything else the site requests — every logo size,
* both PWA icons, the apple-touch icon, the favicons and the .ico — is derived at runtime
* from `logo.png`, so that an operator rebrands by replacing one file rather than fifteen.
* Adding a precomputed derivative here would quietly undo that.
*/
const REQUIRED = ['brand.json', 'theme.css', 'logo.png', 'wordmark.svg', 'og-image.png'];
for (const name of REQUIRED) {
const file = path.join(DEFAULTS, name);
if (!existsSync(file)) {
fail(`brand-default/${name} is missing — §7 requires the stock brand to be complete.`);
} else if (statSync(file).size === 0) {
fail(`brand-default/${name} is empty.`);
}
}
if (existsSync(path.join(DEFAULTS, 'logo.png'))) {
const meta = await sharp(path.join(DEFAULTS, 'logo.png')).metadata();
if (meta.width !== meta.height) {
fail(`brand-default/logo.png is ${meta.width}x${meta.height}; the mark must be square.`);
}
// 512 is the largest thing anything asks for (icon-512.png). A smaller source would be
// upscaled into an installed app icon, which is where it would be most visible.
if (meta.width < 512) {
fail(`brand-default/logo.png is ${meta.width}px; derivatives go up to 512 and must not upscale.`);
}
if (!meta.hasAlpha) {
fail('brand-default/logo.png has no alpha channel; the mark would carry a background.');
}
}
/* =======================================================================================
2. Every /brand/* URL in the source resolves
======================================================================================= */
const SCAN_EXT = new Set(['.astro', '.ts', '.tsx', '.js', '.mjs', '.css', '.md', '.mdx', '.json']);
async function* walk(dir) {
let entries;
try {
entries = await readdir(dir, { withFileTypes: true });
} catch {
return;
}
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (entry.name === 'node_modules' || entry.name.startsWith('.')) continue;
yield* walk(full);
} else if (SCAN_EXT.has(path.extname(entry.name))) {
yield full;
}
}
}
const referenced = new Map(); // name -> [where]
for await (const file of walk(path.join(ROOT, 'src'))) {
const source = readFileSync(file, 'utf8');
const relative = path.relative(ROOT, file);
for (const match of source.matchAll(/\/brand\/([a-z0-9][a-z0-9._-]*)/g)) {
const name = match[1];
const line = source.slice(0, match.index).split('\n').length;
if (!referenced.has(name)) referenced.set(name, []);
referenced.get(name).push(`${relative}:${line}`);
}
}
for (const [name, sites] of referenced) {
// The classifier is imported from the route's own module rather than reimplemented, so
// this check cannot drift from what the server will actually do.
if (!classify(name)) {
fail(
`/brand/${name} is requested by ${sites.join(', ')} but the route would 404 it.\n` +
` Add it to STATIC_FILES, NAMED_DERIVATIVES or DERIVABLE_SIZES in ` +
`src/lib/brandAssets.mjs — or use a size that is already on the list.`
);
}
}
/* =======================================================================================
3. The rewritable brand strings are safe to replace blindly
======================================================================================= */
const brandPath = path.join(DEFAULTS, 'brand.json');
let brand = null;
if (existsSync(brandPath)) {
try {
brand = JSON.parse(readFileSync(brandPath, 'utf8'));
} catch (error) {
fail(`brand-default/brand.json is not valid JSON: ${error.message}`);
}
}
if (brand) {
const REQUIRED_FIELDS = [
'siteName',
'tagline',
'contactEmail',
'discordInvite',
'giteaOrg',
'demoUrl',
];
for (const field of REQUIRED_FIELDS) {
if (typeof brand[field] !== 'string') {
fail(`brand.json is missing the string field "${field}".`);
}
}
/**
* Kept in step with `TEXT_FIELDS` in `applyBrand.mjs` by reading that file rather than by
* restating the list. A field added there and forgotten here would be unchecked; a field
* added here and forgotten there would be silently build-time only. Either way the two
* disagreeing is the bug, so the check is that they agree.
*/
const applySource = readFileSync(path.join(ROOT, 'scripts/applyBrand.mjs'), 'utf8');
const declared = applySource.match(/const TEXT_FIELDS = \[([^\]]*)\]/);
if (!declared) {
fail('could not find TEXT_FIELDS in scripts/applyBrand.mjs — has it been renamed?');
} else {
const rewritable = [...declared[1].matchAll(/'([^']+)'/g)].map((m) => m[1]);
for (const field of rewritable) {
if (!(field in brand)) {
fail(`applyBrand.mjs rewrites "${field}", which brand.json does not define.`);
continue;
}
const value = brand[field];
if (value.length < 8) {
fail(
`brand.json's "${field}" is ${JSON.stringify(value)} — under 8 characters.\n` +
` applyBrand.mjs replaces this string across every built page at boot; a short\n` +
` value will match unrelated markup and corrupt the output.`
);
}
if (/[<>]|="/.test(value)) {
fail(`brand.json's "${field}" contains markup characters, which the boot rewrite cannot survive.`);
}
// A value that occurs inside another value is the subtler failure: replacing the
// shorter one first leaves the longer one half-rewritten, and which runs first is an
// accident of declaration order.
for (const other of rewritable) {
if (other === field) continue;
if (typeof brand[other] === 'string' && brand[other].includes(value)) {
fail(
`brand.json's "${field}" (${JSON.stringify(value)}) occurs inside "${other}".\n` +
` The boot rewrite would corrupt one while replacing the other.`
);
}
}
}
// demoUrl is gated by markup rather than replaced as text (see applyBrand.mjs), so it
// is correct for it NOT to be in TEXT_FIELDS. Saying so out loud, because "the demo URL
// is missing from the rewrite list" is an easy and wrong thing to conclude.
if (rewritable.includes('demoUrl')) {
fail(
'demoUrl must not be in TEXT_FIELDS: its default is the empty string, which cannot\n' +
' be string-replaced. It is handled by the data-attribute gate instead.'
);
}
}
}
/* ======================================================================================= */
if (failures.length) {
console.error('\ncheckBrand: the branding pipeline has problems.\n');
for (const failure of failures) console.error(` - ${failure}`);
console.error('');
process.exit(1);
}
console.log(
`checkBrand: brand-default is complete, ${referenced.size} /brand/ URL(s) resolve, ` +
`and every rewritable string is safe to replace.`
);