Friendly Captcha ook voor de SLP-site: gedeelde widget in formulier B en het terminalformulier van E

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 23:47:39 +01:00
co-authored by Claude Sonnet 5.5
parent a13ffa6bc7
commit 81bceb257a
10 changed files with 436 additions and 3 deletions
@@ -0,0 +1,226 @@
import { act, fireEvent, render, screen, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import type { ComponentType } from 'react';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { ContactSection } from '../components/ContactSection';
import { Era1989 } from '../../../variants/e/Era1989';
import { packages } from '../data/content';
import { ContactPreselectProvider } from '../../../shared/contact/ContactPreselectProvider';
type Handler = (event: { detail: { response?: string; state?: string } }) => void;
const fake = vi.hoisted(() => {
const state = {
handlers: new Map<string, Handler>(),
resets: 0,
destroys: 0,
created: [] as Array<{ sitekey: string; theme?: string }>,
endpoints: [] as string[],
failToLoad: false,
};
return state;
});
vi.mock('@friendlycaptcha/sdk', () => {
if (fake.failToLoad) {
throw new Error('no sdk');
}
return {
FriendlyCaptchaSDK: class {
constructor(options: { apiEndpoint: string }) {
fake.endpoints.push(options.apiEndpoint);
}
createWidget(options: { sitekey: string; theme?: string }) {
fake.created.push({ sitekey: options.sitekey, theme: options.theme });
return {
addEventListener: (name: string, handler: Handler) => fake.handlers.set(name, handler),
reset: () => {
fake.resets += 1;
},
destroy: () => {
fake.destroys += 1;
},
};
}
},
};
});
class FakeIntersectionObserver {
static instances: FakeIntersectionObserver[] = [];
constructor(private readonly callback: IntersectionObserverCallback) {
FakeIntersectionObserver.instances.push(this);
}
observe() {}
unobserve() {}
disconnect() {}
takeRecords() {
return [];
}
trigger() {
this.callback(
[{ isIntersecting: true } as IntersectionObserverEntry],
this as unknown as IntersectionObserver,
);
}
}
const jsonResponse = (body: unknown, status = 200) =>
new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
const CAPTCHA = { provider: 'friendlycaptcha', siteKey: 'FCKEY', apiEndpoint: 'eu' };
function setup(Section: ComponentType, captcha: unknown = CAPTCHA, submitStatus = 202) {
const submits: Array<Record<string, unknown>> = [];
vi.stubGlobal(
'fetch',
vi.fn(async (url: string, init?: RequestInit) => {
if (url.endsWith('/api/v1/offerings')) return jsonResponse(packages);
if (url.endsWith('/contact-messages/token')) {
return jsonResponse({ token: 'tok', minSeconds: 3, captcha });
}
if (url.endsWith('/contact-messages') && init?.method === 'POST') {
submits.push(JSON.parse(String(init.body)) as Record<string, unknown>);
return submitStatus === 202
? jsonResponse({ status: 'received' }, 202)
: new Response(null, { status: submitStatus });
}
return new Response(null, { status: 404 });
}),
);
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
render(
<QueryClientProvider client={queryClient}>
<ContactPreselectProvider>
<Section />
</ContactPreselectProvider>
</QueryClientProvider>,
);
return { submits };
}
async function open() {
await act(async () => {
FakeIntersectionObserver.instances.forEach((o) => o.trigger());
});
await screen.findByTestId('contact-form');
await waitFor(() => expect(screen.getByRole('option', { name: /website/i })).toBeInTheDocument());
}
function fill() {
fireEvent.change(screen.getByLabelText(/^Naam/), { target: { value: 'Jan Jansen' } });
fireEvent.change(screen.getByLabelText(/^E-mail/), { target: { value: 'jan@example.nl' } });
fireEvent.change(screen.getByLabelText(/^Onderwerp/), { target: { value: 'Website' } });
fireEvent.change(screen.getByLabelText(/^Bericht/), { target: { value: 'Ik wil een offerte.' } });
}
function send() {
fireEvent.submit(screen.getByTestId('contact-form'));
}
const VARIANTS: Array<[string, ComponentType]> = [
['design B', ContactSection],
['variant E terminal', Era1989],
];
describe.each(VARIANTS)('friendly captcha in %s', (_name, Section) => {
beforeEach(() => {
FakeIntersectionObserver.instances = [];
vi.stubGlobal('IntersectionObserver', FakeIntersectionObserver);
vi.stubEnv('VITE_API_BASE_URL', '');
fake.handlers.clear();
fake.resets = 0;
fake.destroys = 0;
fake.created = [];
fake.endpoints = [];
});
afterEach(() => {
vi.unstubAllGlobals();
vi.unstubAllEnvs();
vi.useRealTimers();
});
it('shows the widget with the site key and region from the server', async () => {
setup(Section);
await open();
await screen.findByTestId('contact-form-captcha');
await waitFor(() => expect(fake.created).toHaveLength(1));
expect(fake.created[0].sitekey).toBe('FCKEY');
expect(fake.endpoints).toEqual(['eu']);
});
it('blocks the submit until the captcha is solved and shows the message', async () => {
const { submits } = setup(Section);
await open();
await waitFor(() => expect(fake.handlers.has('frc:widget.complete')).toBe(true));
fill();
send();
expect(await screen.findByTestId('contact-failure')).toHaveTextContent('geen robot');
expect(submits).toHaveLength(0);
});
it('sends the solved response and resets the widget after the attempt', async () => {
const { submits } = setup(Section);
await open();
await waitFor(() => expect(fake.handlers.has('frc:widget.complete')).toBe(true));
fill();
act(() => fake.handlers.get('frc:widget.complete')!({ detail: { response: 'frc-token' } }));
send();
await screen.findByTestId('contact-success');
expect(submits[0].captchaToken).toBe('frc-token');
});
it('resets the widget after a failed attempt, because a response is single-use', async () => {
setup(Section, CAPTCHA, 500);
await open();
await waitFor(() => expect(fake.handlers.has('frc:widget.complete')).toBe(true));
fill();
act(() => fake.handlers.get('frc:widget.complete')!({ detail: { response: 'frc-token' } }));
send();
await screen.findByTestId('contact-failure');
await waitFor(() => expect(fake.resets).toBeGreaterThan(0));
});
it('never sends an expired response', async () => {
const { submits } = setup(Section);
await open();
await waitFor(() => expect(fake.handlers.has('frc:widget.expire')).toBe(true));
fill();
act(() => fake.handlers.get('frc:widget.complete')!({ detail: { response: 'frc-token' } }));
act(() => fake.handlers.get('frc:widget.expire')!({ detail: {} }));
send();
expect(await screen.findByTestId('contact-failure')).toHaveTextContent('geen robot');
expect(submits).toHaveLength(0);
});
it('offers the mail button when the widget reports an error', async () => {
setup(Section);
await open();
await waitFor(() => expect(fake.handlers.has('frc:widget.error')).toBe(true));
act(() => fake.handlers.get('frc:widget.error')!({ detail: {} }));
const problem = await screen.findByTestId('contact-captcha-problem');
expect(problem.querySelector('a')).toHaveAttribute('href', expect.stringMatching(/^mailto:/));
});
it('keeps the mail button for an unsupported captcha provider', async () => {
setup(Section, { provider: 'other', siteKey: 'k', apiEndpoint: 'global' });
await act(async () => {
FakeIntersectionObserver.instances.forEach((o) => o.trigger());
});
await waitFor(() =>
expect(screen.getByTestId('contact-panel')).toHaveAttribute('data-availability', 'closed'),
);
expect(screen.queryByTestId('contact-form')).not.toBeInTheDocument();
expect(fake.created).toHaveLength(0);
});
it('does not load the widget when the server asks for no captcha', async () => {
setup(Section, null);
await open();
expect(screen.queryByTestId('contact-form-captcha')).not.toBeInTheDocument();
expect(fake.created).toHaveLength(0);
});
});
@@ -1,4 +1,4 @@
import { useEffect, useMemo, useRef } from 'react';
import { lazy, Suspense, useEffect, useMemo, useRef, useState } from 'react';
import type { ReactNode } from 'react';
import {
useContactForm,
@@ -13,6 +13,8 @@ import { buildSubjectOptions, subjectForSlug } from '../../../shared/contact/sub
import { contactForm, contactInfo } from '../data/content';
import { usePackagesQuery } from '../hooks/usePackagesQuery';
const CaptchaWidget = lazy(() => import('../../../shared/contact/CaptchaWidget'));
const INPUT =
'w-full rounded-none border-0 border-b-2 border-text bg-field px-3.5 py-[13px] text-[17px] font-normal text-text focus-visible:outline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-accent disabled:opacity-70';
@@ -69,6 +71,7 @@ export function ContactFormView({ client, token, refreshToken }: ContactFormView
onEvent: (event) => trackEvent(event === 'sent' ? 'contact-sent' : 'contact-failed'),
});
const [captchaProblem, setCaptchaProblem] = useState(false);
const successRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (form.status === 'sent') {
@@ -139,6 +142,28 @@ export function ContactFormView({ client, token, refreshToken }: ContactFormView
<input type="text" id={hpId} {...hpProps} />
</div>
{/* Robot check (Friendly Captcha) when the server asks for it; client only, own chunk. */}
{form.captcha ? (
<div style={{ minHeight: 76 }}>
<Suspense fallback={null}>
<CaptchaWidget
captcha={form.captcha}
resetCount={form.captchaResetCount}
onToken={form.setCaptchaToken}
onProblem={setCaptchaProblem}
/>
</Suspense>
</div>
) : null}
{captchaProblem ? (
<p role="alert" className="font-medium text-danger" data-testid="contact-captcha-problem">
{contactForm.captchaProblem}{' '}
<a href={`mailto:${contactInfo.email}`} className="underline">
{contactInfo.email}
</a>
</p>
) : null}
{form.failureMessage ? (
<p role="alert" className="font-medium text-danger" data-testid="contact-failure">
{form.failureMessage}
+2
View File
@@ -198,6 +198,8 @@ export const aboutFacts: AboutFact[] = [
export const contactForm = {
otherSubjectLabel: 'Overig',
successText: 'Je bericht is verstuurd. Je hoort binnen één werkdag van me.',
captchaProblem:
'De controle tegen spam kan niet worden geladen. Probeer het later opnieuw of mail me direct:',
privacyNote:
'Je gegevens gebruik ik alleen om op je bericht te reageren; ik bewaar ze maximaal 12 maanden.',
};
@@ -2,6 +2,9 @@ import { useCallback, useEffect, useRef, useState } from 'react';
import type { RefObject } from 'react';
import type { ContactClient, ContactToken, TokenResult } from '../../../cms-client/contact';
/** The only captcha provider this site can render; any other keeps the mail button. */
export const SUPPORTED_CAPTCHA = 'friendlycaptcha';
export type ContactAvailability =
{ status: 'unknown' } | { status: 'closed' } | { status: 'open'; token: ContactToken };
@@ -20,7 +23,10 @@ export function useContactAvailability(ref: RefObject<HTMLElement | null>, clien
}
started.current = true;
const result = await client.getToken();
if (result.kind === 'ok' && result.token.captcha === null) {
if (
result.kind === 'ok' &&
(result.token.captcha === null || result.token.captcha.provider === SUPPORTED_CAPTCHA)
) {
setAvailability({ status: 'open', token: result.token });
} else {
setAvailability({ status: 'closed' });