NGU-Web/server/src/theme.js
Zaldimmar be7e92417e Fix the Panel account bug and harden what the second audit found
- Panel: changing a role or disabling an account always failed
  (db.transaction doesn't exist on node:sqlite); it uses tx() now
- Feeds and link previews are scanned with indexOf, not whole-document
  regexes, so a hostile feed or page can't freeze the server; entity
  decoding can't throw; escaped-HTML descriptions make clean excerpts
- Feed reads share one fetch per feed and serve the stale copy while
  a refresh runs
- Deliberate HTTP errors (the CSRF 403) keep their status instead of
  becoming logged 500s; a JSON null body is handled
- url columns read the scheme the way the URL parser does, so
  control characters can't hide javascript:
- Google sign-in state cookie is __Host- and its return page is
  checked again; more reserved ranges blocked for previews and feeds,
  and a 15 s cap on each whole fetch
- Log lines from visitor text are made single-line and short; list
  limits can't go negative; entity names can't hit object prototypes
- A clip title can't point the clip tool at another file
- Uploads over 60 MP are refused before decoding; the Keep original
  help says a photo's location stays in it
- admin-cli add defaults to the editor role

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-29 02:34:26 -05:00

135 lines
4.9 KiB
JavaScript

/* ═══════════════════════════════════════════════════════════════
THEME
The admin's palette (Panel → Site settings → Colours, table
site_setting_colors) over the site's own colour tokens.
THEME_DEFAULTS must match @theme and the dark block in
src/index.css: the same tokens, the same light and dark values.
A blank override keeps the default.
themeCss() is written into every page's <head> (pageMeta.js).
It goes into the same cascade layers as index.css (theme for
light, base for dark), after it, so an override replaces exactly
the value it names: a light-only change leaves dark mode alone.
checkTheme() runs when Site settings is saved (the descriptor's
`check`, inside the save's transaction), and refuses a palette in
which any text would fall under WCAG AA (4.5:1) in either mode, so
an admin can't make the site unreadable.
═══════════════════════════════════════════════════════════════ */
import { HttpError } from "./admin-crud.js";
// light dark
export const THEME_DEFAULTS = {
ink: ["#073d4a", "#eaf6f8"],
body: ["#26454c", "#cde0e4"],
muted: ["#4a6b72", "#9fb9bf"],
link: ["#0f7183", "#5ccbdc"],
brand: ["#138ba0", "#2aa7bc"],
action: ["#0f7183", "#0f7183"],
"action-hover": ["#0b5c6a", "#0b5c6a"],
surface: ["#ffffff", "#0c1d21"],
tint: ["#eef9fb", "#11292e"],
"tint-soft": ["#f6fbfc", "#0f2428"],
danger: ["#b3261e", "#ff8a80"],
"danger-tint": ["#fdf3f2", "#3b1714"],
};
export const THEME_TOKENS = Object.keys(THEME_DEFAULTS);
const HEX = /^#[0-9a-f]{6}$/i;
const MODES = ["light", "dark"];
function overrides(db) {
const rows = db
.prepare(`SELECT token, light, dark FROM site_setting_colors WHERE settings_id = 'site'`)
.all();
// Checked again here, not only by the table's CHECK: this goes
// straight into a <style> element.
return rows.filter((row) => Object.hasOwn(THEME_DEFAULTS, row.token));
}
/* { light: { ink: '#…', … }, dark: { … } }, defaults with overrides. */
function palette(db) {
const out = { light: {}, dark: {} };
for (const [token, [light, dark]] of Object.entries(THEME_DEFAULTS)) {
out.light[token] = light;
out.dark[token] = dark;
}
for (const row of overrides(db)) {
MODES.forEach((mode) => {
if (HEX.test(row[mode] ?? "")) out[mode][row.token] = row[mode].toLowerCase();
});
}
return out;
}
export function themeCss(db) {
const rows = overrides(db);
const decls = (mode) =>
rows
.filter((row) => HEX.test(row[mode] ?? ""))
.map((row) => `--color-${row.token}:${row[mode].toLowerCase()}`)
.join(";");
const light = decls("light");
const dark = decls("dark");
if (!light && !dark) return "";
return [
light && `@layer theme{:root{${light}}}`,
dark &&
`@layer base{:root[data-theme="dark"]{${dark}}` +
`@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){${dark}}}}`,
]
.filter(Boolean)
.join("");
}
/* ── Contrast ──────────────────────────────────────────────────── */
function luminance(hex) {
const channel = (i) => {
const c = parseInt(hex.slice(i, i + 2), 16) / 255;
return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
};
return 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5);
}
export function contrast(a, b) {
const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
return (hi + 0.05) / (lo + 0.05);
}
const TEXT = ["ink", "body", "muted", "link", "danger"];
const BACKGROUNDS = ["surface", "tint", "tint-soft"];
/* Every pair that has to stay readable: [text, background, minimum]. */
function pairs(colors) {
const list = [];
for (const text of TEXT) {
for (const bg of BACKGROUNDS) list.push([text, colors[text], bg, colors[bg], 4.5]);
}
list.push(["danger", colors.danger, "danger-tint", colors["danger-tint"], 4.5]);
list.push(["white text", "#ffffff", "action", colors.action, 4.5]);
list.push(["white text", "#ffffff", "action-hover", colors["action-hover"], 4.5]);
// Decoration (borders, rules) only needs to be visible.
list.push(["brand", colors.brand, "surface", colors.surface, 3]);
return list;
}
export function checkTheme(db) {
const colors = palette(db);
const problems = [];
for (const mode of MODES) {
for (const [a, aHex, b, bHex, min] of pairs(colors[mode])) {
const ratio = contrast(aHex, bHex);
if (ratio < min) {
problems.push(`${a} on ${b} in ${mode} mode is ${ratio.toFixed(2)}:1, needs ${min}:1`);
}
}
}
if (problems.length) {
throw new HttpError(422, `These colours would be hard to read: ${problems.join("; ")}.`);
}
}