Voeg Api.AndreaSlopFotografie toe met setup-token, proxy-bewuste limiters en ASF-admin-thema

- Core: opt-in ForwardedHeaders:KnownProxies en rate limiters per clientadres
  (zonder configuratie ongewijzigd gedrag)
- Identity: optioneel setup-token (X-Setup-Token), beide setup-endpoints onder de
  login-limiter, beveiligingsgebeurtenis setup_token_rejected (5007)
- Nieuw client-project SlpModularCms.Api.AndreaSlopFotografie (Identity + Availability)
  met bijbehorende tests
- Frontend: thema asf (VITE_THEME), VITE_DEFAULT_LANGUAGE, tokenveld op de setup-pagina
- CI: jobs publish/deploy-asf-test achter ASF_TEST_DEPLOY_ENABLED
- Fix U1: 301-Location wordt nu percent-encoded (gevonden door de property-test)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-07 01:16:34 +01:00
co-authored by Claude Sonnet 5.5
parent e523e670ad
commit 88f5d20a78
55 changed files with 1828 additions and 67 deletions
+9
View File
@@ -45,3 +45,12 @@ VITE_UMAMI_WEBSITE_ID=
# VITE_API_BASE_URL=https://localhost:7223
# VITE_APP_TITLE=SlpModularCms (SlpSoftware)
# and run `pnpm dev:slpsoftware` (uses --mode slpsoftware, port 5175) instead of `pnpm dev`.
# --- Local SlpModularCms.Api.AndreaSlopFotografie dev setup (themed admin) ---
# Copy this file to `.env.asf.local` with:
# VITE_API_BASE_URL=https://localhost:7200
# VITE_APP_TITLE=Andrea Slop Fotografie
# VITE_THEME=asf
# VITE_DEFAULT_LANGUAGE=nl
# and run `pnpm dev:asf` (uses --mode asf, port 5176). VITE_THEME selects frontend/themes/<name>
# (unset = the default look); VITE_DEFAULT_LANGUAGE ('nl' | 'en') applies until a user picks a language.
+3
View File
@@ -7,6 +7,7 @@
"dev": "vite",
"dev:slave": "vite --mode slave --port 5174",
"dev:slpsoftware": "vite --mode slpsoftware --port 5175",
"dev:asf": "vite --mode asf --port 5176",
"dev:all": "concurrently -n master,slave -c blue,magenta \"pnpm dev\" \"pnpm dev:slave\"",
"build": "tsc -b && vite build",
"lint": "eslint .",
@@ -21,6 +22,8 @@
"@dnd-kit/core": "^6.3.1",
"@dnd-kit/sortable": "^10.0.0",
"@dnd-kit/utilities": "^3.2.2",
"@fontsource/jost": "5.3.0",
"@fontsource/marcellus": "5.3.0",
"@hookform/resolvers": "^5.4.0",
"@radix-ui/react-dialog": "^1.1.17",
"@radix-ui/react-dropdown-menu": "^2.1.18",
+16
View File
@@ -17,6 +17,12 @@ importers:
'@dnd-kit/utilities':
specifier: ^3.2.2
version: 3.2.2(react@19.2.7)
'@fontsource/jost':
specifier: 5.3.0
version: 5.3.0
'@fontsource/marcellus':
specifier: 5.3.0
version: 5.3.0
'@hookform/resolvers':
specifier: ^5.4.0
version: 5.4.0(react-hook-form@7.79.0(react@19.2.7))
@@ -380,6 +386,12 @@ packages:
'@floating-ui/utils@0.2.11':
resolution: {integrity: sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg==}
'@fontsource/jost@5.3.0':
resolution: {integrity: sha512-lORv5y49hSoLVxjGb0qNuBzXvnaNYI3B94200uGPGJFei8fao6d6LLz2ziWbOZubGfZnibzuT6GVNX8fBw8WQQ==}
'@fontsource/marcellus@5.3.0':
resolution: {integrity: sha512-cMnanjpiPIC7Rq4GXIA/Zal5WLSoDV5Mc681tMkWsWfKHXnRnLGlhuGeBnLF6HrqtFkiSdiuy4NCSPfOrz266w==}
'@hookform/resolvers@5.4.0':
resolution: {integrity: sha512-EIsqr/t/qbinPIhGjMdtvutIN1Kk4uwbROE9/UQ93CAVGR7GkA7Y92+fX80OzXi/OB67jVFYwKGO1WzkxmkFZw==}
peerDependencies:
@@ -2626,6 +2638,10 @@ snapshots:
'@floating-ui/utils@0.2.11': {}
'@fontsource/jost@5.3.0': {}
'@fontsource/marcellus@5.3.0': {}
'@hookform/resolvers@5.4.0(react-hook-form@7.79.0(react@19.2.7))':
dependencies:
'@standard-schema/utils': 0.3.0
@@ -49,6 +49,22 @@ export const setupUninitializedHandlers = [
),
];
/** Override: setup requires the token; only 'correct-token' is accepted (401 otherwise, like the host). */
export const setupTokenRequiredHandlers = [
http.get(`${API_BASE}/api/v1/Setup/status`, () =>
HttpResponse.json<SetupStatus>({ initialized: false, tokenRequired: true }),
),
http.post(`${API_BASE}/api/v1/Setup/owner`, ({ request }) => {
if (request.headers.get('X-Setup-Token') !== 'correct-token') {
return HttpResponse.json(
{ title: 'Setup token ontbreekt of is onjuist.', status: 401 },
{ status: 401 },
);
}
return HttpResponse.json({ message: 'System initialized' }, { status: 201 });
}),
];
/** Override: POST /Setup/owner returns 409 — system already initialized. */
export const setupConflictHandlers = [
...setupUninitializedHandlers,
@@ -3,7 +3,7 @@ import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderApp, mockGuest } from '@/test/utils';
import { server } from '@/mocks/server';
import { setupUninitializedHandlers, setupConflictHandlers } from '@/mocks/index';
import { setupUninitializedHandlers, setupConflictHandlers, setupTokenRequiredHandlers } from '@/mocks/index';
import { _resetSetupStatusCache } from '@/router';
// Each test starts with a fresh setup status cache so the MSW handler controls
@@ -105,4 +105,70 @@ describe('SetupPage', () => {
expect(await screen.findByTestId('login-form-submit-button')).toBeInTheDocument();
});
describe('setup token', () => {
const fillValidForm = async (user: ReturnType<typeof userEvent.setup>) => {
await user.type(await screen.findByTestId('setup-name-input'), 'Alice Owner');
await user.type(screen.getByTestId('setup-email-input'), 'alice@example.com');
await user.type(screen.getByTestId('setup-password-input'), 'ValidPass1!');
await user.type(screen.getByTestId('setup-confirmPassword-input'), 'ValidPass1!');
};
it('does not show a token field when the host does not require one', async () => {
server.use(...setupUninitializedHandlers);
mockGuest();
renderApp('/setup');
await screen.findByTestId('setup-name-input');
expect(screen.queryByTestId('setup-token-input')).not.toBeInTheDocument();
});
it('shows the token field when the host requires one', async () => {
server.use(...setupTokenRequiredHandlers);
mockGuest();
renderApp('/setup');
expect(await screen.findByTestId('setup-token-input')).toBeInTheDocument();
});
it('blocks submission without a token', async () => {
server.use(...setupTokenRequiredHandlers);
mockGuest();
const user = userEvent.setup();
renderApp('/setup');
await fillValidForm(user);
await user.click(screen.getByTestId('setup-submit-button'));
expect(await screen.findByTestId('setup-token-error')).toBeInTheDocument();
expect(screen.queryByTestId('setup-success')).not.toBeInTheDocument();
});
it('shows a clear message for a wrong token and stays on the page', async () => {
server.use(...setupTokenRequiredHandlers);
mockGuest();
const user = userEvent.setup();
renderApp('/setup');
await fillValidForm(user);
await user.type(screen.getByTestId('setup-token-input'), 'wrong-token');
await user.click(screen.getByTestId('setup-submit-button'));
expect(await screen.findByTestId('form-error-banner')).toBeInTheDocument();
expect(screen.getByTestId('setup-form')).toBeInTheDocument();
});
it('sends the token in X-Setup-Token and completes setup', async () => {
server.use(...setupTokenRequiredHandlers);
mockGuest();
const user = userEvent.setup();
renderApp('/setup');
await fillValidForm(user);
await user.type(screen.getByTestId('setup-token-input'), 'correct-token');
await user.click(screen.getByTestId('setup-submit-button'));
expect(await screen.findByTestId('setup-success')).toBeInTheDocument();
});
});
});
@@ -13,7 +13,7 @@ import { FieldError } from '@/components/ui/FieldError';
import { useSetup } from '@/features/setup/services/useSetup';
import { ProblemDetailsError, NetworkError } from '@/lib/api-client';
import { changeLanguage } from '@/i18n/config';
import { _markSystemInitialized } from '@/router';
import { _markSystemInitialized, isSetupTokenRequired } from '@/router';
interface FormError {
message: string;
@@ -26,6 +26,9 @@ export function SetupPage() {
const [successMessage, setSuccessMessage] = useState(false);
const setupMutation = useSetup();
const tokenRequired = isSetupTokenRequired();
const [setupToken, setSetupToken] = useState('');
const [tokenMissing, setTokenMissing] = useState(false);
const {
register,
@@ -46,9 +49,14 @@ export function SetupPage() {
const onSubmit = handleSubmit(async (values) => {
setServerError(null);
if (tokenRequired && setupToken.trim() === '') {
setTokenMissing(true);
return;
}
setTokenMissing(false);
try {
const { confirmPassword: _, ...payload } = values;
await setupMutation.mutateAsync(payload);
await setupMutation.mutateAsync(payload, tokenRequired ? setupToken.trim() : undefined);
await changeLanguage(values.language);
_markSystemInitialized();
setSuccessMessage(true);
@@ -56,7 +64,9 @@ export function SetupPage() {
navigate({ to: '/login' });
}, 2000);
} catch (err) {
if (err instanceof ProblemDetailsError) {
if (err instanceof ProblemDetailsError && err.status === 401) {
setServerError({ message: t('setup.tokenInvalid') });
} else if (err instanceof ProblemDetailsError) {
setServerError({ message: err.problem.detail || err.message || t('errors.generic') });
} else if (err instanceof NetworkError) {
setServerError({ message: t('errors.network') });
@@ -99,6 +109,23 @@ export function SetupPage() {
onDismiss={() => setServerError(null)}
/>
{tokenRequired && (
<div className="space-y-2">
<Label htmlFor="setupToken">{t('setup.tokenLabel')}</Label>
<Input
id="setupToken"
type="password"
autoComplete="off"
data-testid="setup-token-input"
aria-invalid={tokenMissing}
value={setupToken}
onChange={(e) => setSetupToken(e.target.value)}
/>
<p className="text-xs text-muted-foreground">{t('setup.tokenHelp')}</p>
{tokenMissing && <FieldError message={t('setup.tokenRequiredError')} testId="setup-token-error" />}
</div>
)}
<div className="space-y-2">
<Label htmlFor="name">{t('setup.nameLabel')}</Label>
<Input
@@ -1,6 +1,8 @@
// Setup status (used by guards during bootstrap).
export interface SetupStatus {
initialized: boolean;
/** True when the host requires the first-administrator setup token (X-Setup-Token). */
tokenRequired?: boolean;
}
export interface SetupRequest {
@@ -22,11 +22,16 @@ export function useSetup() {
const [isPending, setIsPending] = useState(false);
const [error, setError] = useState<Error | null>(null);
const mutateAsync = useCallback(async (data: SetupRequest): Promise<SetupResponse> => {
const mutateAsync = useCallback(async (data: SetupRequest, setupToken?: string): Promise<SetupResponse> => {
setIsPending(true);
setError(null);
try {
const response = await api.post('/api/v1/Setup/owner', data);
// skipAuthRefresh: a rejected token is a 401, and nobody is signed in yet, so the
// client must not try (and fail) a session refresh that would signal an auth failure.
const response = await api.post('/api/v1/Setup/owner', data, {
skipAuthRefresh: true,
headers: setupToken ? { 'X-Setup-Token': setupToken } : undefined,
});
return response as SetupResponse;
} catch (err) {
const error = err instanceof Error ? err : new Error(String(err));
+13
View File
@@ -0,0 +1,13 @@
import { describe, expect, it } from 'vitest';
import { languageDetection } from '@/i18n/config';
describe('languageDetection', () => {
it('without a default language keeps the old order: stored choice, then browser, fallback English', () => {
expect(languageDetection(undefined)).toEqual({ order: ['localStorage', 'navigator'], fallbackLng: 'en' });
});
it('with a default language: stored choice first, then that default, and the browser is not consulted', () => {
expect(languageDetection('nl')).toEqual({ order: ['localStorage'], fallbackLng: 'nl' });
expect(languageDetection('en')).toEqual({ order: ['localStorage'], fallbackLng: 'en' });
});
});
+15 -2
View File
@@ -3,6 +3,7 @@ import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import enTranslation from './locales/en/translation.json';
import nlTranslation from './locales/nl/translation.json';
import { getAppConfig } from '@/lib/config';
export const SUPPORTED_LANGUAGES = ['en', 'nl'] as const;
export type SupportedLanguage = (typeof SUPPORTED_LANGUAGES)[number];
@@ -12,6 +13,18 @@ export const LANGUAGE_LABELS: Record<SupportedLanguage, string> = {
nl: 'Nederlands',
};
/**
* Language resolution order: a stored user choice always wins; otherwise the build-time
* VITE_DEFAULT_LANGUAGE; otherwise the browser language (the behaviour before this option existed).
*/
export function languageDetection(defaultLanguage: SupportedLanguage | undefined) {
return defaultLanguage === undefined
? { order: ['localStorage', 'navigator'], fallbackLng: 'en' }
: { order: ['localStorage'], fallbackLng: defaultLanguage };
}
const detectionSetup = languageDetection(getAppConfig().defaultLanguage);
// Both supported locales are bundled eagerly so the detected language is
// available immediately on init — no async gap that would cause an English flash.
void i18n
@@ -22,12 +35,12 @@ void i18n
en: { translation: enTranslation },
nl: { translation: nlTranslation },
},
fallbackLng: 'en',
fallbackLng: detectionSetup.fallbackLng,
supportedLngs: SUPPORTED_LANGUAGES as unknown as string[],
nonExplicitSupportedLngs: true,
interpolation: { escapeValue: false },
detection: {
order: ['localStorage', 'navigator'],
order: detectionSetup.order,
caches: ['localStorage'],
},
react: { useSuspense: false },
@@ -43,6 +43,10 @@
"passwordLabel": "Password",
"confirmPasswordLabel": "Confirm password",
"languageLabel": "Language preference",
"tokenLabel": "Setup token",
"tokenHelp": "Required to create the first administrator. You received it from whoever installed this site.",
"tokenRequiredError": "Enter the setup token.",
"tokenInvalid": "The setup token is missing or incorrect.",
"submitButton": "Create owner account",
"successMessage": "Account created. You can now sign in."
},
@@ -43,6 +43,10 @@
"passwordLabel": "Wachtwoord",
"confirmPasswordLabel": "Wachtwoord bevestigen",
"languageLabel": "Taalkeuze",
"tokenLabel": "Setup-token",
"tokenHelp": "Nodig om de eerste beheerder aan te maken. Je hebt het ontvangen van degene die deze site heeft geïnstalleerd.",
"tokenRequiredError": "Vul het setup-token in.",
"tokenInvalid": "Het setup-token ontbreekt of is onjuist.",
"submitButton": "Owner-account aanmaken",
"successMessage": "Account aangemaakt. Je kunt nu inloggen."
},
+37 -1
View File
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getAppConfig, resetAppConfigCache } from '@/lib/config';
import { getAppConfig, parseDefaultLanguage, resetAppConfigCache } from '@/lib/config';
/**
* The empty-base case is the production configuration, and the one nobody runs locally — so it is
@@ -81,3 +81,39 @@ describe('getAppConfig', () => {
expect(config.umamiWebsiteId).toBeUndefined();
});
});
describe('parseDefaultLanguage', () => {
it.each([
['nl', 'nl'],
['en', 'en'],
[' NL ', 'nl'],
['EN', 'en'],
])('accepts %j as %s', (input, expected) => {
expect(parseDefaultLanguage(input)).toBe(expected);
});
it.each([undefined, '', ' ', 'de', 'nl-NL', 'dutch'])('treats %j as no default', (input) => {
expect(parseDefaultLanguage(input)).toBeUndefined();
});
});
describe('getAppConfig defaultLanguage', () => {
afterEach(() => {
vi.unstubAllEnvs();
resetAppConfigCache();
});
it('reads VITE_DEFAULT_LANGUAGE', () => {
resetAppConfigCache();
vi.stubEnv('VITE_DEFAULT_LANGUAGE', 'nl');
expect(getAppConfig().defaultLanguage).toBe('nl');
});
it('is undefined when VITE_DEFAULT_LANGUAGE is absent', () => {
resetAppConfigCache();
vi.stubEnv('VITE_DEFAULT_LANGUAGE', undefined as unknown as string);
expect(getAppConfig().defaultLanguage).toBeUndefined();
});
});
+8
View File
@@ -21,10 +21,17 @@ const configSchema = z.object({
appEnv: z.string().optional(),
umamiScriptUrl: z.string().optional(),
umamiWebsiteId: z.string().optional(),
defaultLanguage: z.enum(['en', 'nl']).optional(),
});
export type AppConfig = z.infer<typeof configSchema>;
/** Only a supported language counts; anything else (typo, empty) means "no default" and falls back to the browser. */
export function parseDefaultLanguage(value: string | undefined): 'en' | 'nl' | undefined {
const v = value?.trim().toLowerCase();
return v === 'en' || v === 'nl' ? v : undefined;
}
let cached: AppConfig | null = null;
export function getAppConfig(): AppConfig {
@@ -43,6 +50,7 @@ export function getAppConfig(): AppConfig {
appEnv: import.meta.env.VITE_APP_ENV,
umamiScriptUrl: import.meta.env.VITE_UMAMI_SCRIPT_URL,
umamiWebsiteId: import.meta.env.VITE_UMAMI_WEBSITE_ID,
defaultLanguage: parseDefaultLanguage(import.meta.env.VITE_DEFAULT_LANGUAGE),
};
if (import.meta.env.DEV) {
+2
View File
@@ -3,6 +3,8 @@ import { createRoot } from 'react-dom/client';
import { RouterProvider } from '@tanstack/react-router';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import './index.css';
// Per-site admin theme chosen at build time (VITE_THEME); an empty file when none is selected.
import '@theme';
import './i18n/config';
import { AuthProvider } from '@/features/auth/context/AuthProvider';
import { useAuth } from '@/features/auth/context/auth-context';
+1 -1
View File
@@ -12,7 +12,7 @@ export const handlers = [...authHandlers, ...userHandlers, ...setupHandlers, ...
export { authHandlers } from '@/features/auth/mocks/handlers';
export { userHandlers } from '@/features/users/mocks/handlers';
export { setupHandlers, setupUninitializedHandlers, setupConflictHandlers, setupNetworkErrorHandlers } from '@/features/setup/mocks/handlers';
export { setupHandlers, setupUninitializedHandlers, setupConflictHandlers, setupTokenRequiredHandlers, setupNetworkErrorHandlers } from '@/features/setup/mocks/handlers';
export { invitationHandlers } from '@/features/invitation/mocks/handlers';
export { availabilityHandlers } from '@/features/availability/mocks/handlers';
export { cmsHandlers, resetMockCmsInstances, getMockCmsInstances } from '@/features/cms/mocks/handlers';
+12 -2
View File
@@ -31,10 +31,15 @@ async function fetchSetupStatus(): Promise<SetupStatus> {
if (_setupStatusCache !== null) return _setupStatusCache;
if (_setupStatusPromise === null) {
_setupStatusPromise = api
.get<{ initialized?: boolean; Initialized?: boolean }>('/api/v1/Setup/status')
.get<{ initialized?: boolean; Initialized?: boolean; tokenRequired?: boolean; TokenRequired?: boolean }>(
'/api/v1/Setup/status',
)
.then((raw) => {
// Backend may return PascalCase (Initialized) if no camelCase policy is set.
const s: SetupStatus = { initialized: raw.initialized ?? raw.Initialized ?? false };
const s: SetupStatus = {
initialized: raw.initialized ?? raw.Initialized ?? false,
tokenRequired: raw.tokenRequired ?? raw.TokenRequired ?? false,
};
_setupStatusCache = s;
return s;
})
@@ -52,6 +57,11 @@ export function _resetSetupStatusCache(): void {
_setupStatusPromise = null;
}
/** Whether the setup page must ask for the setup token (known once the InitGuard fetched the status). */
export function isSetupTokenRequired(): boolean {
return _setupStatusCache?.tokenRequired === true;
}
export function _markSystemInitialized(): void {
_setupStatusCache = { initialized: true };
_setupStatusPromise = null;
+7
View File
@@ -15,6 +15,10 @@ interface ImportMetaEnv {
readonly VITE_SENTRY_DSN?: string;
/** Build-time environment tag ('test' | 'production'). Both use `vite build`, so MODE alone cannot tell them apart. */
readonly VITE_APP_ENV?: string;
/** Admin theme folder under frontend/themes (e.g. 'asf'). Absent = the default look. Read by vite.config.ts at build time. */
readonly VITE_THEME?: string;
/** Initial language when the user has not chosen one yet ('nl' | 'en'). Absent = browser language. */
readonly VITE_DEFAULT_LANGUAGE?: string;
/** Self-hosted Umami tracking script URL, e.g. https://analytics.example.com/script.js */
readonly VITE_UMAMI_SCRIPT_URL?: string;
/** Umami website ID, created per environment in the Umami dashboard. */
@@ -28,3 +32,6 @@ interface ImportMeta {
/** App version at build time (from package.json), injected via vite.config.ts `define`. Used as the Sentry `release` tag. */
declare const __APP_VERSION__: string;
/** Alias to the selected theme stylesheet (see vite.config.ts and themes/). */
declare module '@theme';
+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" role="img" aria-label="ASF">
<rect width="64" height="64" rx="8" fill="#5f6a58"/>
<text x="32" y="41" text-anchor="middle" font-family="Georgia, 'Times New Roman', serif" font-size="26" fill="#faf7f2">ASF</text>
</svg>

After

Width:  |  Height:  |  Size: 283 B

+115
View File
@@ -0,0 +1,115 @@
/*
* Theme "asf" - Andrea Slop Fotografie.
*
* Re-declares the admin design tokens only (colours, radius, fonts); no layout or component changes.
* Colours are exactly those of the Andrea Slop Fotografie website (decision Q5 = B): no contrast
* adjustment was made, so a few pairs may fall below WCAG AA - see the hand-back note.
*
* Fonts are self-hosted through the @fontsource packages (the admin CSP is font-src 'self').
* Selected at build time with VITE_THEME=asf.
*/
@import '@fontsource/jost/latin-400.css';
@import '@fontsource/jost/latin-500.css';
@import '@fontsource/jost/latin-600.css';
@import '@fontsource/marcellus/latin-400.css';
:root {
/* Website palette */
--asf-paper: #faf7f2;
--asf-paper-2: #f1ebe2;
--asf-paper-3: #e8e0d5;
--asf-ink: #232120;
--asf-ink-2: #55504b;
--asf-ink-3: #8a827a;
--asf-line: #e2dad0;
--asf-accent: #7f8b76;
--asf-accent-deep: #5f6a58;
--asf-accent-deeper: #475042;
--asf-sand: #d9cdbc;
--asf-error: #a4443a;
--asf-font-heading: 'Marcellus', Georgia, 'Times New Roman', serif;
--asf-font-body: 'Jost', system-ui, 'Segoe UI', Roboto, sans-serif;
--background: var(--asf-paper);
--foreground: var(--asf-ink);
--card: var(--asf-paper-2);
--card-foreground: var(--asf-ink);
--popover: var(--asf-paper-2);
--popover-foreground: var(--asf-ink);
--primary: var(--asf-accent-deep);
--primary-foreground: var(--asf-paper);
--secondary: var(--asf-paper-2);
--secondary-foreground: var(--asf-ink);
--muted: var(--asf-paper-2);
--muted-foreground: var(--asf-ink-2);
--accent: var(--asf-paper-3);
--accent-foreground: var(--asf-accent-deeper);
--destructive: var(--asf-error);
--destructive-foreground: var(--asf-paper);
--border: var(--asf-line);
--input: var(--asf-line);
--ring: var(--asf-accent-deep);
--radius: 0.25rem;
--font-sans: var(--asf-font-body);
}
/*
* Dark mode: the website has no dark variant, so these values are derived from its palette (ink as
* background, paper as text, a slightly lighter accent #8a9681 so button text stays above 4.5:1).
*/
.dark {
--background: var(--asf-ink);
--foreground: var(--asf-paper);
--card: #2d2a28;
--card-foreground: var(--asf-paper);
--popover: #2d2a28;
--popover-foreground: var(--asf-paper);
--primary: #8a9681;
--primary-foreground: var(--asf-ink);
--secondary: #353130;
--secondary-foreground: var(--asf-paper);
--muted: #353130;
--muted-foreground: var(--asf-sand);
--accent: #353130;
--accent-foreground: var(--asf-paper-3);
--destructive: #d9776b;
--destructive-foreground: var(--asf-ink);
--border: #433e3b;
--input: #433e3b;
--ring: #8a9681;
}
body {
font-family: var(--asf-font-body);
}
h1,
h2,
h3,
h4,
h5,
h6,
[data-slot='card-title'],
[data-slot='dialog-title'] {
font-family: var(--asf-font-heading);
font-weight: 400;
}
+1
View File
@@ -0,0 +1 @@
/* Intentionally empty: used when VITE_THEME is unset, so the admin keeps its default look. */
+73
View File
@@ -0,0 +1,73 @@
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { describe, expect, it } from 'vitest';
import { availableThemes, resolveTheme } from './resolveTheme';
describe('resolveTheme', () => {
it.each([undefined, '', ' '])('maps %j to the empty module (the default admin)', (name) => {
const theme = resolveTheme(name);
expect(path.basename(theme.css)).toBe('none.css');
expect(theme.favicon).toBeNull();
expect(fs.readFileSync(theme.css, 'utf-8')).not.toMatch(/--[a-z-]+\s*:/);
});
it('resolves the asf theme with its stylesheet and favicon', () => {
const theme = resolveTheme('asf');
expect(fs.existsSync(theme.css)).toBe(true);
expect(theme.css.replaceAll('\\', '/')).toMatch(/themes\/asf\/theme\.css$/);
expect(theme.favicon !== null && fs.existsSync(theme.favicon)).toBe(true);
});
it('lists the available themes', () => {
expect(availableThemes()).toContain('asf');
});
it.each(['nope', '../asf', 'asf/../asf', '..', 'ASF', 'asf asf'])('rejects %j loudly, naming the real themes', (name) => {
expect(() => resolveTheme(name)).toThrow(/Unknown VITE_THEME .*Available themes: .*asf/);
});
it('reports (none) when no theme exists', () => {
const empty = fs.mkdtempSync(path.join(os.tmpdir(), 'themes-'));
try {
expect(() => resolveTheme('x', empty)).toThrow(/\(none\)/);
} finally {
fs.rmSync(empty, { recursive: true, force: true });
}
});
});
describe('asf theme tokens', () => {
const tokens = (css: string, block: string) => {
const m = css.match(new RegExp(`${block}\\s*\\{([^}]*)\\}`));
return new Set([...(m?.[1] ?? '').matchAll(/(--[a-z-]+)\s*:/g)].map((x) => x[1]));
};
const base = fs.readFileSync(path.resolve(__dirname, '../src/index.css'), 'utf-8');
const theme = fs.readFileSync(path.resolve(__dirname, 'asf/theme.css'), 'utf-8');
it('overrides every existing light and dark design token and invents no structural one', () => {
for (const block of ['\\:root', '\\.dark']) {
const existing = tokens(base, block);
const themed = tokens(theme, block);
for (const t of existing) expect(themed, `${block} ${t}`).toContain(t);
// Anything beyond the existing tokens must be the theme's own --asf-* palette or the font token.
for (const t of themed) {
if (!existing.has(t)) expect(t).toMatch(/^--(asf-|font-sans$)/);
}
}
});
it('uses the website palette colours exactly', () => {
for (const hex of ['#faf7f2', '#f1ebe2', '#e8e0d5', '#232120', '#55504b', '#8a827a', '#e2dad0', '#7f8b76', '#5f6a58', '#475042', '#d9cdbc', '#a4443a']) {
expect(theme.toLowerCase()).toContain(hex);
}
});
it('self-hosts its fonts (no remote url)', () => {
expect(theme).not.toMatch(/https?:\/\//);
expect(theme).toContain('@fontsource/jost');
expect(theme).toContain('@fontsource/marcellus');
});
});
+46
View File
@@ -0,0 +1,46 @@
import fs from 'node:fs';
import path from 'node:path';
export interface ResolvedTheme {
/** Absolute path of the CSS file to import (the empty module when no theme is selected). */
css: string;
/** Absolute path of the theme favicon, or null when there is no theme or it ships none. */
favicon: string | null;
}
const THEMES_DIR = import.meta.dirname;
/** Theme folders available next to this file (each holds a theme.css). */
export function availableThemes(dir: string = THEMES_DIR): string[] {
return fs
.readdirSync(dir, { withFileTypes: true })
.filter((e) => e.isDirectory() && fs.existsSync(path.join(dir, e.name, 'theme.css')))
.map((e) => e.name)
.sort();
}
/**
* Resolves VITE_THEME to files. Unset or blank means "no theme": an empty CSS module, so the admin
* looks exactly as it always did. An unknown name is a build error, never a silent fallback, so a
* typo in the pipeline cannot ship an unthemed admin unnoticed.
*/
export function resolveTheme(name: string | undefined, dir: string = THEMES_DIR): ResolvedTheme {
const trimmed = (name ?? '').trim();
if (trimmed === '') {
return { css: path.join(dir, 'none.css'), favicon: null };
}
// The name becomes a path segment: only known theme folders are accepted.
const known = availableThemes(dir);
if (!known.includes(trimmed)) {
throw new Error(
`Unknown VITE_THEME "${trimmed}". Available themes: ${known.length > 0 ? known.join(', ') : '(none)'}.`,
);
}
const favicon = path.join(dir, trimmed, 'favicon.svg');
return {
css: path.join(dir, trimmed, 'theme.css'),
favicon: fs.existsSync(favicon) ? favicon : null,
};
}
+1 -1
View File
@@ -20,5 +20,5 @@
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
"include": ["vite.config.ts", "themes/resolveTheme.ts"]
}
+41 -3
View File
@@ -1,15 +1,51 @@
/// <reference types="vitest/config" />
import path from 'node:path';
import { defineConfig } from 'vite';
import fs from 'node:fs';
import { defineConfig, loadEnv, type Plugin } from 'vite';
import react from '@vitejs/plugin-react';
import tailwindcss from '@tailwindcss/vite';
import { version } from './package.json';
import { resolveTheme } from './themes/resolveTheme';
/** VITE_THEME selects themes/<name>/theme.css at build time (unset = today's admin, unchanged). */
function themeFor(mode: string) {
return resolveTheme({ ...loadEnv(mode, process.cwd(), 'VITE_'), ...process.env }.VITE_THEME);
}
/**
* Per-site favicon (VITE_THEME): the page links the theme favicon instead of the default one.
* Build emits it as an asset; the dev server serves it from the theme folder.
*/
function themeFavicon(faviconPath: string | null): Plugin {
const publicName = 'favicon-theme.svg';
return {
name: 'cms-theme-favicon',
// 'post': Vite has already prefixed the base path (/admin/) by then, so match any prefix.
transformIndexHtml: {
order: 'post',
handler(html) {
return faviconPath === null ? html : html.replace(/href="([^"]*)favicon\.svg"/, `href="$1${publicName}"`);
},
},
configureServer(server) {
if (faviconPath === null) return;
server.middlewares.use(`/${publicName}`, (_req, res) => {
res.setHeader('Content-Type', 'image/svg+xml');
res.end(fs.readFileSync(faviconPath));
});
},
generateBundle() {
if (faviconPath === null) return;
this.emitFile({ type: 'asset', fileName: publicName, source: fs.readFileSync(faviconPath) });
},
};
}
// https://vite.dev/config/
export default defineConfig(({ command }) => ({
export default defineConfig(({ command, mode }) => ({
// Production builds are deployed under /admin (see Program.cs); the dev server keeps serving from '/'.
base: command === 'build' ? '/admin/' : '/',
plugins: [react(), tailwindcss()],
plugins: [react(), tailwindcss(), themeFavicon(themeFor(mode).favicon)],
define: {
// Injected at build time, used as the Sentry `release` tag (see src/lib/sentry.ts).
__APP_VERSION__: JSON.stringify(version),
@@ -17,6 +53,8 @@ export default defineConfig(({ command }) => ({
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
// The selected theme's CSS (or an empty file); imported once from main.tsx.
'@theme': themeFor(mode).css,
},
},
server: {