cms-client: captcha-slot, initialSubject en apiEndpoint; fixes voor erasableSyntaxOnly en recursieve attempt

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 23:10:14 +01:00
co-authored by Claude Sonnet 5.5
parent 75086362ee
commit 93fa729ad7
10 changed files with 360 additions and 19 deletions
+7
View File
@@ -7,3 +7,10 @@ Headless client for the SLP CMS API, written inside the SlpSoftware frontend fir
- **Contract**: see `aidlc-docs/features/redesign-modern-timetravel/inception/application-design/contact-api-contract.md` and the CMS file `openapi/slpsoftware.v1.json`.
- **No markup, no styling**: sites render their own fields from `useContactForm().getFieldProps`.
- **Privacy**: nothing here logs form values, tokens or idempotency keys.
## Captcha slot and initial subject
- The token response may carry `captcha: { provider, siteKey, apiEndpoint }` (`apiEndpoint` is `global` or `eu`, default `global`). `useContactForm` returns `captcha`, `captchaRequired`, `captchaToken`, `setCaptchaToken(token | null)` and `captchaResetCount`. The package renders no widget: the site mounts the provider widget client-side, calls `setCaptchaToken(response)` when solved and `setCaptchaToken(null)` when it expires or fails, and resets the widget whenever `captchaResetCount` changes (a response can be used once).
- With captcha required, submit sends nothing until a response is set and shows `messages.captchaRequired`; the payload then carries `captchaToken`. Without captcha the field is omitted.
- `initialSubject` (option of `useContactForm`) applies a subject chosen before the form was mounted, as soon as it exists in `subjectOptions` and unless the visitor already picked one. Unknown values are ignored.
- Subject values are the readable labels (they appear in the mail and the CMS message list); a site keeps its own ids only for links/preselect.
@@ -39,7 +39,9 @@ describe('getToken', () => {
kind: 'ok',
token: { token: 'abc', minSeconds: 3, captcha: null },
});
expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe('/api/v1/contact-messages/token');
expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe(
'/api/v1/contact-messages/token',
);
});
it('parses captcha info', async () => {
@@ -47,7 +49,31 @@ describe('getToken', () => {
json({ token: 'abc', minSeconds: 3, captcha: { provider: 'fc', siteKey: 'k' } }, 200),
);
const result = await api.getToken();
expect(result.kind === 'ok' && result.token.captcha).toEqual({ provider: 'fc', siteKey: 'k' });
expect(result.kind === 'ok' && result.token.captcha).toEqual({
provider: 'fc',
siteKey: 'k',
apiEndpoint: 'global',
});
});
it('takes the captcha api endpoint from the server and falls back to global', async () => {
const eu = client(
json(
{ token: 'a', minSeconds: 3, captcha: { provider: 'fc', siteKey: 'k', apiEndpoint: 'eu' } },
200,
),
);
const euResult = await eu.api.getToken();
expect(euResult.kind === 'ok' && euResult.token.captcha?.apiEndpoint).toBe('eu');
const odd = client(
json(
{ token: 'a', minSeconds: 3, captcha: { provider: 'fc', siteKey: 'k', apiEndpoint: 'x' } },
200,
),
);
const oddResult = await odd.api.getToken();
expect(oddResult.kind === 'ok' && oddResult.token.captcha?.apiEndpoint).toBe('global');
});
it.each([
@@ -0,0 +1,221 @@
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { describe, expect, it, vi } from 'vitest';
import { useContactForm } from '../useContactForm';
import type { ContactClient, ContactPayload, ContactToken, SubmitResult } from '../types';
const OPTIONS = [
{ value: 'Website', label: 'Website' },
{ value: 'Overig', label: 'Overig' },
];
const CAPTCHA_TOKEN: ContactToken = {
token: 'tok',
minSeconds: 3,
captcha: { provider: 'friendlycaptcha', siteKey: 'FCMKEY', apiEndpoint: 'global' },
};
const PLAIN_TOKEN: ContactToken = { token: 'tok', minSeconds: 3, captcha: null };
function makeClient(results: SubmitResult[] = [{ kind: 'ok' }]) {
const payloads: ContactPayload[] = [];
const submit = vi.fn(async (payload: ContactPayload) => {
payloads.push(payload);
return results.shift() ?? ({ kind: 'ok' } as SubmitResult);
});
const client: ContactClient = {
getToken: async () => ({ kind: 'ok', token: PLAIN_TOKEN }),
submit,
};
return { client, payloads, submit };
}
function Harness(props: {
token: ContactToken;
client: ContactClient;
options?: typeof OPTIONS;
initialSubject?: string | null;
}) {
const form = useContactForm({
idPrefix: 'c',
subjectOptions: props.options ?? OPTIONS,
initialSubject: props.initialSubject,
client: props.client,
token: props.token,
refreshToken: async () => ({ kind: 'ok', token: props.token }),
fallbackAddress: 'info@example.nl',
});
const name = form.getFieldProps('name');
const email = form.getFieldProps('email');
const subject = form.getFieldProps('subject');
const message = form.getFieldProps('message');
return (
<form {...form.formProps}>
<input aria-label="naam" {...name.inputProps} />
<input aria-label="mail" {...email.inputProps} />
<select aria-label="onderwerp" {...subject.inputProps}>
<option value="" />
{(props.options ?? OPTIONS).map((o) => (
<option key={o.value} value={o.value}>
{o.label}
</option>
))}
</select>
<textarea aria-label="bericht" {...message.inputProps} />
<button type="submit">verstuur</button>
<output data-testid="captcha-required">{String(form.captchaRequired)}</output>
<output data-testid="captcha-site-key">{form.captcha?.siteKey ?? '-'}</output>
<output data-testid="captcha-endpoint">{form.captcha?.apiEndpoint ?? '-'}</output>
<output data-testid="reset-count">{form.captchaResetCount}</output>
<output data-testid="failure">{form.failureMessage ?? ''}</output>
<output data-testid="status">{form.status}</output>
<button type="button" onClick={() => form.setCaptchaToken('frc-response')}>
solved
</button>
<button type="button" onClick={() => form.setCaptchaToken(null)}>
expired
</button>
</form>
);
}
function fill() {
fireEvent.change(screen.getByLabelText('naam'), { target: { value: 'Jan' } });
fireEvent.change(screen.getByLabelText('mail'), { target: { value: 'jan@example.nl' } });
fireEvent.change(screen.getByLabelText('onderwerp'), { target: { value: 'Website' } });
fireEvent.change(screen.getByLabelText('bericht'), { target: { value: 'Hallo daar' } });
}
describe('captcha slot', () => {
it('exposes the captcha info from the token response', () => {
render(<Harness token={CAPTCHA_TOKEN} client={makeClient().client} />);
expect(screen.getByTestId('captcha-required')).toHaveTextContent('true');
expect(screen.getByTestId('captcha-site-key')).toHaveTextContent('FCMKEY');
expect(screen.getByTestId('captcha-endpoint')).toHaveTextContent('global');
});
it('reports no captcha when the server asks for none', () => {
render(<Harness token={PLAIN_TOKEN} client={makeClient().client} />);
expect(screen.getByTestId('captcha-required')).toHaveTextContent('false');
});
it('does not send until the captcha is solved and shows the message', async () => {
const { client, submit } = makeClient();
render(<Harness token={CAPTCHA_TOKEN} client={client} />);
fill();
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
await waitFor(() =>
expect(screen.getByTestId('failure')).toHaveTextContent(
'Bevestig eerst dat je geen robot bent.',
),
);
expect(submit).not.toHaveBeenCalled();
expect(screen.getByTestId('status')).toHaveTextContent('editing');
});
it('sends the captcha response with the payload and asks for a widget reset afterwards', async () => {
const { client, payloads } = makeClient();
render(<Harness token={CAPTCHA_TOKEN} client={client} />);
fill();
fireEvent.click(screen.getByText('solved'));
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
await waitFor(() => expect(screen.getByTestId('status')).toHaveTextContent('sent'));
expect(payloads[0].captchaToken).toBe('frc-response');
expect(screen.getByTestId('reset-count')).toHaveTextContent('1');
});
it('never sends an expired captcha response', async () => {
const { client, submit } = makeClient();
render(<Harness token={CAPTCHA_TOKEN} client={client} />);
fill();
fireEvent.click(screen.getByText('solved'));
fireEvent.click(screen.getByText('expired'));
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
await waitFor(() => expect(screen.getByTestId('failure')).toHaveTextContent('geen robot'));
expect(submit).not.toHaveBeenCalled();
});
it('needs a new captcha response after a failed attempt', async () => {
const { client, submit } = makeClient([{ kind: 'failed' }]);
render(<Harness token={CAPTCHA_TOKEN} client={client} />);
fill();
fireEvent.click(screen.getByText('solved'));
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
await waitFor(() => expect(screen.getByTestId('status')).toHaveTextContent('failed'));
expect(screen.getByTestId('reset-count')).toHaveTextContent('1');
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
await waitFor(() => expect(screen.getByTestId('failure')).toHaveTextContent('geen robot'));
expect(submit).toHaveBeenCalledTimes(1);
});
it('omits captchaToken when no captcha is configured', async () => {
const { client, payloads } = makeClient();
render(<Harness token={PLAIN_TOKEN} client={client} />);
fill();
fireEvent.submit(screen.getByRole('button', { name: 'verstuur' }).closest('form')!);
await waitFor(() => expect(screen.getByTestId('status')).toHaveTextContent('sent'));
expect('captchaToken' in payloads[0]).toBe(false);
});
});
describe('initialSubject', () => {
it('applies a subject chosen before the form was mounted', async () => {
render(<Harness token={PLAIN_TOKEN} client={makeClient().client} initialSubject="Website" />);
await waitFor(() =>
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('Website'),
);
});
it('waits until the option exists and ignores unknown values', async () => {
const { rerender } = render(
<Harness
token={PLAIN_TOKEN}
client={makeClient().client}
options={[{ value: 'Overig', label: 'Overig' }]}
initialSubject="Website"
/>,
);
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('');
await act(async () => {
rerender(
<Harness
token={PLAIN_TOKEN}
client={makeClient().client}
options={OPTIONS}
initialSubject="Website"
/>,
);
});
await waitFor(() =>
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('Website'),
);
});
it('does not override a subject the visitor already chose', async () => {
const { rerender } = render(
<Harness
token={PLAIN_TOKEN}
client={makeClient().client}
options={[{ value: 'Overig', label: 'Overig' }]}
initialSubject="Website"
/>,
);
fireEvent.change(screen.getByLabelText('onderwerp'), { target: { value: 'Overig' } });
await act(async () => {
rerender(
<Harness
token={PLAIN_TOKEN}
client={makeClient().client}
options={OPTIONS}
initialSubject="Website"
/>,
);
});
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('Overig');
});
it('ignores an unknown initial subject', () => {
render(
<Harness token={PLAIN_TOKEN} client={makeClient().client} initialSubject="Bestaat niet" />,
);
expect((screen.getByLabelText('onderwerp') as HTMLSelectElement).value).toBe('');
});
});
@@ -27,11 +27,12 @@ function parseToken(body: unknown): ContactToken | null {
}
let parsedCaptcha: ContactToken['captcha'] = null;
if (captcha && typeof captcha === 'object') {
const { provider, siteKey } = captcha as Record<string, unknown>;
const { provider, siteKey, apiEndpoint } = captcha as Record<string, unknown>;
if (typeof provider !== 'string' || typeof siteKey !== 'string') {
return null;
}
parsedCaptcha = { provider, siteKey };
// Additive field: absent or unknown means the default (global) endpoint.
parsedCaptcha = { provider, siteKey, apiEndpoint: apiEndpoint === 'eu' ? 'eu' : 'global' };
}
return { token, minSeconds, captcha: parsedCaptcha };
}
+3
View File
@@ -6,6 +6,8 @@ export interface ContactMessages {
fallbackFieldError: string;
rateLimited: (minutes: number) => string;
tooLarge: string;
/** Shown when the captcha has not been solved (or has expired) at submit time. */
captchaRequired: string;
failed: (address: string) => string;
sendingLabel: string;
}
@@ -37,6 +39,7 @@ export const messagesNl: ContactMessages = {
rateLimited: (minutes) =>
`Je hebt net al een bericht gestuurd. Probeer het over ${minutes} ${minutes === 1 ? 'minuut' : 'minuten'} opnieuw.`,
tooLarge: 'Je bericht is te groot.',
captchaRequired: 'Bevestig eerst dat je geen robot bent.',
failed: (address) => `Versturen lukte niet. Probeer het later nog eens of mail naar ${address}.`,
sendingLabel: 'Versturen…',
};
+11 -1
View File
@@ -10,10 +10,20 @@ export const CONTACT_LIMITS = { name: 100, email: 254, subject: 100, message: 20
export const EMPTY_FIELDS: ContactFields = { name: '', email: '', subject: '', message: '' };
/** Region of the captcha provider API; the site passes it to the widget. */
export type CaptchaApiEndpoint = 'global' | 'eu';
/** Captcha the server asks for; `null` in the token response means no captcha. */
export interface CaptchaInfo {
provider: string;
siteKey: string;
apiEndpoint: CaptchaApiEndpoint;
}
export interface ContactToken {
token: string;
minSeconds: number;
captcha: { provider: string; siteKey: string } | null;
captcha: CaptchaInfo | null;
}
/** Body of POST /api/v1/contact-messages. */
+79 -11
View File
@@ -23,7 +23,10 @@ export interface SubjectOption {
}
export type ContactFailure =
{ kind: 'generic' } | { kind: 'tooLarge' } | { kind: 'rateLimited'; minutes: number };
| { kind: 'generic' }
| { kind: 'tooLarge' }
| { kind: 'captchaRequired' }
| { kind: 'rateLimited'; minutes: number };
export interface UseContactFormOptions {
/** Prefix of all DOM ids so the form can appear more than once. */
@@ -31,6 +34,12 @@ export interface UseContactFormOptions {
subjectOptions: SubjectOption[];
/** Value + change counter; a new `key` re-applies the subject. Unknown values are ignored. */
preselect?: { subject: string | null; key: number };
/**
* Subject chosen before the form was mounted (e.g. a package link clicked earlier). Applied as
* soon as it is among `subjectOptions` (they may arrive later) unless the visitor already
* touched the subject field. Unknown values are ignored.
*/
initialSubject?: string | null;
client: ContactClient;
/** Server-signed token obtained by the availability check. */
token: ContactToken;
@@ -66,6 +75,7 @@ export function useContactForm(options: UseContactFormOptions) {
idPrefix,
subjectOptions,
preselect,
initialSubject,
client,
token,
refreshToken,
@@ -80,6 +90,10 @@ export function useContactForm(options: UseContactFormOptions) {
const tokenRef = useRef(token);
const sendingRef = useRef(false);
const lastPreselectKey = useRef(preselect?.key ?? 0);
const pendingInitialSubject = useRef(initialSubject ?? null);
const [captchaToken, setCaptchaTokenState] = useState<string | null>(null);
const [captchaResetCount, setCaptchaResetCount] = useState(0);
const captchaTokenRef = useRef<string | null>(null);
useEffect(() => {
tokenRef.current = token;
@@ -96,6 +110,23 @@ export function useContactForm(options: UseContactFormOptions) {
}
}, [preselect, subjectOptions]);
// Subject chosen before the form existed: apply once, when its option is available.
useEffect(() => {
const wanted = pendingInitialSubject.current;
if (wanted === null || !subjectOptions.some((o) => o.value === wanted)) {
return;
}
pendingInitialSubject.current = null;
if (!state.touched.subject && state.values.subject === '') {
dispatch({ type: 'preselect', subject: wanted });
}
}, [subjectOptions, state.touched.subject, state.values.subject]);
const setCaptchaToken = useCallback((value: string | null) => {
captchaTokenRef.current = value;
setCaptchaTokenState(value);
}, []);
const fieldId = useCallback((field: ContactField) => `${idPrefix}-${field}`, [idPrefix]);
// Focus is applied after the render in which the fields are enabled and the errors are shown
@@ -112,17 +143,22 @@ export function useContactForm(options: UseContactFormOptions) {
}, [state, fieldId]);
const attempt = useCallback(
async (payload: ContactPayload, key: string, canRefresh: boolean): Promise<SubmitResult> => {
const result = await client.submit(payload, { idempotencyKey: key });
if (result.kind === 'invalid' && result.tokenExpired && canRefresh) {
const fresh = await refreshToken();
if (fresh.kind === 'ok') {
tokenRef.current = fresh.token;
return attempt({ ...payload, token: fresh.token.token }, key, false);
async (payload: ContactPayload, key: string): Promise<SubmitResult> => {
let current = payload;
// At most one automatic token refresh (BR-U4-10): only the first answer may be `expired`.
for (let round = 0; round < 2; round++) {
const result = await client.submit(current, { idempotencyKey: key });
if (!(result.kind === 'invalid' && result.tokenExpired && round === 0)) {
return result;
}
const fresh = await refreshToken();
if (fresh.kind !== 'ok') {
return { kind: 'failed' };
}
return result;
tokenRef.current = fresh.token;
current = { ...current, token: fresh.token.token };
}
return { kind: 'failed' };
},
[client, refreshToken],
);
@@ -147,6 +183,13 @@ export function useContactForm(options: UseContactFormOptions) {
return;
}
// The captcha must be solved first; the server would count a missing token as spam while
// answering 202, so the visitor has to be told here.
if (tokenRef.current.captcha !== null && !captchaTokenRef.current) {
setFailure({ kind: 'captchaRequired' });
return;
}
sendingRef.current = true;
setFailure(null);
dispatch({ type: 'sending' });
@@ -161,8 +204,9 @@ export function useContactForm(options: UseContactFormOptions) {
...trimFields(state.values),
hpCheck: '',
token: tokenRef.current.token,
...(tokenRef.current.captcha !== null ? { captchaToken: captchaTokenRef.current } : {}),
};
const result = await attempt(payload, keyRef.current, true);
const result = await attempt(payload, keyRef.current);
switch (result.kind) {
case 'ok':
keyRef.current = null;
@@ -191,8 +235,22 @@ export function useContactForm(options: UseContactFormOptions) {
}
} finally {
sendingRef.current = false;
if (tokenRef.current.captcha !== null) {
// A captcha response is single-use: the site resets its widget after every attempt.
setCaptchaToken(null);
setCaptchaResetCount((count) => count + 1);
}
}, [attempt, finishFailure, focusFirstInvalid, honeypot, onEvent, state.status, state.values]);
}
}, [
attempt,
finishFailure,
focusFirstInvalid,
honeypot,
onEvent,
setCaptchaToken,
state.status,
state.values,
]);
const reset = useCallback(() => {
keyRef.current = null;
@@ -206,6 +264,8 @@ export function useContactForm(options: UseContactFormOptions) {
? messages.rateLimited(failure.minutes)
: failure.kind === 'tooLarge'
? messages.tooLarge
: failure.kind === 'captchaRequired'
? messages.captchaRequired
: messages.failed(fallbackAddress)
: null;
@@ -256,5 +316,13 @@ export function useContactForm(options: UseContactFormOptions) {
retry: submit,
reset,
messages,
/** Captcha the server asked for (null = none). The site renders the widget. */
captcha: token.captcha,
captchaRequired: token.captcha !== null,
captchaToken,
/** Call with the widget response when solved, and with null when it expires or errors. */
setCaptchaToken,
/** Increments after every attempt; the site resets its widget when it changes. */
captchaResetCount,
};
}
+4 -1
View File
@@ -10,8 +10,11 @@ export type TransportFailure = 'network' | 'timeout';
/** Thrown by `fetchJson` when no HTTP answer was received. */
export class TransportError extends Error {
constructor(public readonly kind: TransportFailure) {
readonly kind: TransportFailure;
constructor(kind: TransportFailure) {
super(kind);
this.kind = kind;
this.name = 'TransportError';
}
}
@@ -61,6 +61,7 @@ export function ContactFormView({ client, token, refreshToken }: ContactFormView
idPrefix: 'contact',
subjectOptions,
preselect: { subject: subjectForSlug(packages, preselect.subject), key: preselect.key },
initialSubject: subjectForSlug(packages, preselect.subject),
client,
token,
refreshToken,
+1
View File
@@ -64,6 +64,7 @@ export function TerminalForm({ client, token, refreshToken }: TerminalFormProps)
idPrefix: 'contact',
subjectOptions,
preselect: { subject: subjectForSlug(packages, preselect.subject), key: preselect.key },
initialSubject: subjectForSlug(packages, preselect.subject),
client,
token,
refreshToken,