Files
TREK/client/src/theme/applyAppearance.ts
T
Maurice 2c2d008dc2 fix: clear every open Sonar security issue, and half the reliability ones (#2037)
* fix(security): mint idempotency keys properly, and resolve the extractor by path

Three findings out of a sweep of every open Sonar security issue. The other 49
turned out to be false positives and are documented in sonar-project.properties
rather than changed — each entry scoped to a file, never a whole rule, so a
future Math.random() on an auth path still fails.

The idempotency key is the one that can lose data. Both producers fell back to
Math.random when crypto.randomUUID was missing, and randomUUID needs a secure
context — TREK's own quickstart is http://localhost:3000 and LAN installs run on
http://192.168.x.x, so on the deployments the README documents the fallback is
what actually runs. The axios one was
`Math.random().toString(36).slice(2)`, which is not length-stable: 0.5 yields a
single character and 0 yields the empty string, which the interceptor reads as
"no key" and skips deduplication for entirely. Two writes sharing a key collapse
into one — the second gets the first one's cached response and the edit is gone
with no error anywhere. Both now come from utils/randomId, which has the
getRandomValues rung that works in insecure contexts too.

The extractor probe stored the bare binary name, so every extraction re-resolved
it through whatever PATH held at that moment. The official image sets
KITINERARY_EXTRACTOR_PATH and never reaches that branch, but a bare-metal install
without it ran an unqualified name from a PATH it does not control. It now walks
the search path itself and keeps the absolute path of the file it verified;
execFileSync also drops the /bin/sh hop the old probe needed. PATH comes through
app-config because process.env is walled off in src/.

* fix: four tests and sorts that were not doing what they claimed

Sonar reported 43 high-impact reliability issues. Reading all of them, four are
real; the rest are cosmetic or would be made worse by the suggested change.

budget.test.ts hand-built `paid: true`, but both emitters send `paid: body.paid
? 1 : 0` and the handler stores the value verbatim — the test asserted a payload
the server never sends. The line below it already used a number.

admin.controller.test.ts had a `.resolves` assertion with no await. The promise
was dropped, so that line could not fail the test.

The two to-do category lists sorted with a bare .sort(), which is byte order:
every accented name files behind the whole ASCII range, so in a German trip
"Übernachtung" lands after "Zelt". TREK ships 23 locales, so this is real data.
One side effect worth knowing: katColor picks a category's dot colour by its
index, so re-sorting can move which category shows which colour — it already
moves whenever a category is added, and the colour carries no meaning.

Deliberately not changed: the two `| 0` truncations (Math.trunc is not
equivalent — `| 0` wraps at 32 bits and these carry millisecond timestamps), the
two .map() callbacks whose second parameter is declared and used, and the sha1
in thumbnail.service (its own comment says a swap would orphan every existing
thumbnail).

* refactor: give every button a type, and prefer the Number statics

Two mechanical sweeps, no behaviour change intended in either.

A <button> with no type attribute is type="submit" per the HTML spec. Outside a
form that does nothing today, but it turns into a surprise the moment the markup
is wrapped in one, which is what Sonar's S9011 is warning about. 870 buttons get
an explicit type="button". Two things were left alone on purpose: buttons that
take a {...spread}, because the spread may carry a type and the merge order
decides which wins, and anything inside a <form> — there the answer is a
judgement call, and checking all eleven form files found every real submit button
already carrying type="submit".

The Number sweep covers only the three globals that are exactly equivalent to
their Number twin: parseInt, parseFloat and NaN. isNaN is NOT in it — the global
coerces its argument, so isNaN('abc') is true where Number.isNaN('abc') is false,
and renaming it would change what the code does. It reaches server and plugin-sdk
as well as the client; both copies of egress-policy.ts got the identical edit, so
the mirror the SDK's parity test guards stays intact.
2026-08-25 15:22:38 +02:00

169 lines
6.7 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { normalizeAppearance, type AppearanceConfig } from '@trek/shared'
/**
* The ONE place that writes appearance state to the DOM.
*
* Components never compute colors from the config — they only read CSS tokens.
* This writer toggles the `.dark` class (the single source of truth that 8+
* components observe), sets the `data-*` appearance attributes, and writes the
* handful of inline CSS variables that can't live in a static stylesheet
* (custom accent + type scales). It is idempotent and safe to call on every
* settings change.
*
* With DEFAULT_APPEARANCE every branch below is a no-op (default scheme sets no
* attribute, transparency stays on, all scales are 1), so the rendered result is
* byte-identical to TREK before this feature existed.
*
* Keep the snapshot shape and the apply logic in sync with the pre-paint boot
* script at client/public/theme-boot.js — that script mirrors this to kill FOUC.
*/
export type DarkModeSetting = boolean | string // 'light' | 'dark' | 'auto' | boolean
export const APPEARANCE_SNAPSHOT_KEY = 'trek_appearance'
export interface ApplyAppearanceInput {
darkMode: DarkModeSetting
/** Raw appearance value from settings (may be partial/missing — normalized here). */
appearance?: unknown
/** Public /shared and /public pages force the neutral default look. */
isSharedPage?: boolean
}
interface AppearanceSnapshot {
v: 1
darkMode: DarkModeSetting
scheme: AppearanceConfig['schemeId']
noTransparency: boolean
density: AppearanceConfig['density']
reduceMotion: boolean
accent: AppearanceConfig['accent']
accentText: { light: string; dark: string } | null
typeScale: AppearanceConfig['typeScale']
fontScale: number
}
function resolveDark(darkMode: DarkModeSetting, isSharedPage: boolean): boolean {
if (isSharedPage) return false
if (darkMode === 'auto') {
return typeof window !== 'undefined' && window.matchMedia('(prefers-color-scheme: dark)').matches
}
return darkMode === true || darkMode === 'dark'
}
/**
* Pick a legible text color (near-black or white) for a custom accent fill,
* using WCAG relative luminance. Keeps user-picked accents readable.
*/
function accentTextFor(hex: string): string {
const c = hex.replace('#', '')
const full = c.length === 3 ? c.split('').map((x) => x + x).join('') : c
const toLin = (v: number) => (v <= 0.03928 ? v / 12.92 : Math.pow((v + 0.055) / 1.055, 2.4))
const r = toLin(Number.parseInt(full.slice(0, 2), 16) / 255)
const g = toLin(Number.parseInt(full.slice(2, 4), 16) / 255)
const b = toLin(Number.parseInt(full.slice(4, 6), 16) / 255)
const luminance = 0.2126 * r + 0.7152 * g + 0.0722 * b
return luminance > 0.45 ? '#111827' : '#ffffff'
}
function setScaleVar(root: HTMLElement, name: string, value: number): void {
if (value === 1) root.style.removeProperty(name)
else root.style.setProperty(name, String(value))
}
function writeSnapshot(snap: AppearanceSnapshot): void {
try {
localStorage.setItem(APPEARANCE_SNAPSHOT_KEY, JSON.stringify(snap))
} catch {
/* private mode / quota — non-fatal, we just lose the FOUC optimisation */
}
}
/** Clear the per-device snapshot (call on logout so the next user on a shared
* browser doesn't get a flash of the previous user's theme). */
export function clearAppearanceSnapshot(): void {
try {
localStorage.removeItem(APPEARANCE_SNAPSHOT_KEY)
} catch {
/* non-fatal */
}
}
export function applyAppearance(input: ApplyAppearanceInput): AppearanceConfig {
const cfg = normalizeAppearance(input.appearance)
const isShared = !!input.isSharedPage
// Public pages render the neutral default regardless of the viewer's account.
const eff: AppearanceConfig = isShared
? { ...cfg, schemeId: 'default', accent: null, transparency: true }
: cfg
const dark = resolveDark(input.darkMode, isShared)
const root = document.documentElement
root.classList.toggle('dark', dark)
// data-scheme — only for non-default schemes (default keeps the monochrome accent).
if (eff.schemeId === 'default') root.removeAttribute('data-scheme')
else root.setAttribute('data-scheme', eff.schemeId)
// transparency-off marker
if (eff.transparency) root.removeAttribute('data-no-transparency')
else root.setAttribute('data-no-transparency', '')
// density — only 'compact' deviates from today.
if (eff.density === 'compact') root.setAttribute('data-density', 'compact')
else root.removeAttribute('data-density')
// user reduce-motion override (layered over the OS prefers-reduced-motion rule)
if (eff.reduceMotion) root.setAttribute('data-reduce-motion', '')
else root.removeAttribute('data-reduce-motion')
// custom accent inline vars (+ auto-derived legible text) — only for 'custom'.
const accentText =
eff.schemeId === 'custom' && eff.accent
? { light: accentTextFor(eff.accent.light), dark: accentTextFor(eff.accent.dark) }
: null
if (eff.schemeId === 'custom' && eff.accent && accentText) {
root.style.setProperty('--accent-custom-light', eff.accent.light)
root.style.setProperty('--accent-custom-dark', eff.accent.dark)
root.style.setProperty('--accent-custom-text-light', accentText.light)
root.style.setProperty('--accent-custom-text-dark', accentText.dark)
} else {
root.style.removeProperty('--accent-custom-light')
root.style.removeProperty('--accent-custom-dark')
root.style.removeProperty('--accent-custom-text-light')
root.style.removeProperty('--accent-custom-text-dark')
}
// Text scaling: each size-class var = global fontScale × its per-class factor.
// Inline px content (mapped by size) and the text-title/subtitle/body/caption
// utilities consume these; rem-based text additionally follows root font-size.
setScaleVar(root, '--fs-scale-title', eff.fontScale * eff.typeScale.title)
setScaleVar(root, '--fs-scale-subtitle', eff.fontScale * eff.typeScale.subtitle)
setScaleVar(root, '--fs-scale-body', eff.fontScale * eff.typeScale.body)
setScaleVar(root, '--fs-scale-caption', eff.fontScale * eff.typeScale.caption)
// root font-size scales rem-based text (navbar, menus, non-migrated text).
if (eff.fontScale === 1) root.style.removeProperty('font-size')
else root.style.fontSize = `${eff.fontScale * 100}%`
// theme-color meta — unchanged from before (dark #09090b / light #ffffff).
const meta = document.querySelector('meta[name="theme-color"]')
if (meta) meta.setAttribute('content', dark ? '#09090b' : '#ffffff')
writeSnapshot({
v: 1,
darkMode: input.darkMode,
scheme: eff.schemeId,
noTransparency: !eff.transparency,
density: eff.density,
reduceMotion: eff.reduceMotion,
accent: eff.accent,
accentText,
typeScale: eff.typeScale,
fontScale: eff.fontScale,
})
return cfg
}