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:
@@ -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));
|
||||
|
||||
@@ -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' });
|
||||
});
|
||||
});
|
||||
@@ -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."
|
||||
},
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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
@@ -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;
|
||||
|
||||
Vendored
+7
@@ -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';
|
||||
|
||||
Reference in New Issue
Block a user