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:
+2
@@ -18,3 +18,5 @@ Facts and risks:
|
||||
- Per-visitor rate limiting works only if Pi-Entry passes `X-Forwarded-For`/`-Proto` (not verified) and KnownProxies contains 192.168.1.102.
|
||||
- nginx on Pi-Main is not in the path; security headers come from the app. Whether Pi-Entry adds its own CSP/headers is unknown.
|
||||
- Announce any REQUIRED new variable in advance: a missing required variable caused a crashloop on ASF on 2026-11-08 (App__PublicBaseUrl). The contact variables are optional (module off by default).
|
||||
|
||||
- SLP captcha (U7, 2026-11-11): the SLP site renders the Friendly Captcha widget (shared lazy chunk) in design B and the E terminal form. `frame-src` (global, global0, global1 .frcapi.com) must be allowed where the SLP site HTML is served; which server that is has NOT been confirmed (Pi-Main: nginx not in path; Pi-Entry unknown). Captcha stays off in production (`Contact__Captcha__Enabled=false`) until a paid plan.
|
||||
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
# Code Generation Plan — captcha-slp (U7: Friendly Captcha for the SLP site, B and E)
|
||||
|
||||
Reason: Bryan wants SLP to support the captcha like ASF (2026-11-11). Until now the SLP form falls back to the mail button when the token response carries `captcha`. Production keeps captcha OFF (server `Contact__Captcha__Enabled=false`) until a paid Friendly Captcha plan exists; this unit makes the SLP site able to use it. Base: ASF's tested `CaptchaWidget` (read only) and the cms-client slot (93fa729).
|
||||
|
||||
## Steps
|
||||
- [x] 1. **Dependency**: add `@friendlycaptcha/sdk` 1.1.3 (pinned; check pnpm `minimumReleaseAge`, `pnpm audit --prod` stays clean).
|
||||
- [x] 2. **Shared widget** `src/shared/contact/CaptchaWidget.tsx` (framework-neutral styling, Tailwind): lazy SDK import (own chunk), `startMode: focus`, `language: nl`, `apiEndpoint` from the server, `onToken(token|null)` on complete/expire/error, `onProblem(boolean)` (error, blocked script/iframe, no sign of life within 15 s), `resetCount` resets the widget and clears the token, `destroy()` on unmount, reserved height (no layout shift), `theme` prop (`light|dark`), `aria` friendly label; loaded only when the form is open AND the server asks for a captcha.
|
||||
- [x] 3. **Availability** `useContactAvailability`: `captcha != null` with provider `friendlycaptcha` opens the form (other providers keep the mail button).
|
||||
- [x] 4. **Form B** `ContactFormView`: render the widget (Suspense, reserved height), wire `setCaptchaToken`, `captchaResetCount`; widget problem => clear message with the mail button (never silently blocked); `captchaRequired` message (role alert) from the package.
|
||||
- [x] 5. **Form E** `TerminalForm`: same wiring in terminal style (widget theme dark, amber frame), messages in terminal casing.
|
||||
- [x] 6. **Tests**: fake SDK (complete, expire, error, no sign of life, reset after attempt); B and E: widget only when captcha required, expired token never sent, submit blocked with message until solved, problem => mail button, captcha provider unknown => mail button, no widget chunk when no captcha.
|
||||
- [x] 7. **Quality gates**: lint, tests, build (new lazy chunk size noted; main bundle must not grow), `pnpm audit --prod`.
|
||||
- [x] 8. **Docs + infra note**: update code summary and `operations/host-config-checklist.md`: frame-src for the three hosts must be set where the SLP site HTML is served (not yet confirmed which server that is); captcha stays off in production until a paid plan.
|
||||
- [x] 9. **Commit, push, test-deploy** (deploy_test only). Real-browser run with the widget against the local SLP API (5290, captcha on) as Bryan's check.
|
||||
|
||||
## Not in this unit
|
||||
Enabling captcha in production, paid plan, EU switch (config only), privacy page for SLP (separate), CSP on the host that serves slpsoftware.nl (needs confirmation from the infra owner).
|
||||
@@ -17,6 +17,7 @@
|
||||
"@fontsource/jetbrains-mono": "^5.1.1",
|
||||
"@fontsource/open-sans": "^5.3.0",
|
||||
"@fontsource/vt323": "^5.3.0",
|
||||
"@friendlycaptcha/sdk": "1.1.3",
|
||||
"@sentry/react": "^10.68.0",
|
||||
"@tanstack/react-query": "^5.59.0",
|
||||
"@tanstack/react-router": "^1.79.0",
|
||||
|
||||
Generated
+8
@@ -20,6 +20,9 @@ importers:
|
||||
'@fontsource/vt323':
|
||||
specifier: ^5.3.0
|
||||
version: 5.3.0
|
||||
'@friendlycaptcha/sdk':
|
||||
specifier: 1.1.3
|
||||
version: 1.1.3
|
||||
'@sentry/react':
|
||||
specifier: ^10.68.0
|
||||
version: 10.68.0(react@18.3.1)
|
||||
@@ -415,6 +418,9 @@ packages:
|
||||
'@fontsource/vt323@5.3.0':
|
||||
resolution: {integrity: sha512-3w33Rg/0+R1587HQfz4t7Q7e0GGeCqr3wmzIwqdGInUnrGEwMA5eX39GP4Z9wpTQnwfhVOhYuxuRwRUeIcicbw==}
|
||||
|
||||
'@friendlycaptcha/sdk@1.1.3':
|
||||
resolution: {integrity: sha512-a2wJ46Ag6MGeZ/b+zyAO3MLT32816fgDN6fwQsVU6bRIUHyuU2/DHAWgQi5EiWAAr7Jj0uMrEdvukWhMPdnh1g==}
|
||||
|
||||
'@humanfs/core@0.19.2':
|
||||
resolution: {integrity: sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==}
|
||||
engines: {node: '>=18.18.0'}
|
||||
@@ -2212,6 +2218,8 @@ snapshots:
|
||||
|
||||
'@fontsource/vt323@5.3.0': {}
|
||||
|
||||
'@friendlycaptcha/sdk@1.1.3': {}
|
||||
|
||||
'@humanfs/core@0.19.2':
|
||||
dependencies:
|
||||
'@humanfs/types': 0.15.0
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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' });
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import type { WidgetHandle } from '@friendlycaptcha/sdk';
|
||||
import type { CaptchaInfo } from '../../cms-client/contact';
|
||||
|
||||
/** Room kept for the widget so nothing below it jumps when it appears. */
|
||||
export const CAPTCHA_MIN_HEIGHT = 76;
|
||||
|
||||
/** How long the widget gets to show a first sign of life. */
|
||||
export const CAPTCHA_LOAD_TIMEOUT_MS = 15_000;
|
||||
|
||||
interface CaptchaWidgetProps {
|
||||
captcha: CaptchaInfo;
|
||||
/** Goes up after every send attempt: a response can be used only once. */
|
||||
resetCount: number;
|
||||
/** The response when solved, null when it expired or failed. */
|
||||
onToken: (token: string | null) => void;
|
||||
/**
|
||||
* True when the widget cannot work (script or iframe blocked, network, provider down, no sign of
|
||||
* life in time); false again once it runs. The form then offers the mail button.
|
||||
*/
|
||||
onProblem: (problem: boolean) => void;
|
||||
theme?: 'light' | 'dark';
|
||||
/** Test seam: how long the widget gets before it counts as a problem. */
|
||||
loadTimeoutMs?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The Friendly Captcha v2 widget (bundled @friendlycaptcha/sdk). Client only and a separate chunk:
|
||||
* it loads when the form is open and the server asked for a captcha. The visitor starts it by
|
||||
* focusing the form. The API region comes from the server (token response), not from the site.
|
||||
*/
|
||||
export default function CaptchaWidget({
|
||||
captcha,
|
||||
resetCount,
|
||||
onToken,
|
||||
onProblem,
|
||||
theme = 'light',
|
||||
loadTimeoutMs = CAPTCHA_LOAD_TIMEOUT_MS,
|
||||
}: CaptchaWidgetProps) {
|
||||
const element = useRef<HTMLDivElement>(null);
|
||||
const widget = useRef<WidgetHandle | null>(null);
|
||||
const latestOnToken = useRef(onToken);
|
||||
const latestOnProblem = useRef(onProblem);
|
||||
useEffect(() => {
|
||||
latestOnToken.current = onToken;
|
||||
latestOnProblem.current = onProblem;
|
||||
}, [onToken, onProblem]);
|
||||
|
||||
const { siteKey, apiEndpoint } = captcha;
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let handle: WidgetHandle | null = null;
|
||||
// No sign of life in time is a problem too (a blocked iframe may not report an error).
|
||||
const timer = setTimeout(() => latestOnProblem.current(true), loadTimeoutMs);
|
||||
const alive = () => {
|
||||
clearTimeout(timer);
|
||||
latestOnProblem.current(false);
|
||||
};
|
||||
import('@friendlycaptcha/sdk').then(
|
||||
({ FriendlyCaptchaSDK }) => {
|
||||
if (cancelled || !element.current) {
|
||||
return;
|
||||
}
|
||||
const sdk = new FriendlyCaptchaSDK({ apiEndpoint });
|
||||
handle = sdk.createWidget({
|
||||
element: element.current,
|
||||
sitekey: siteKey,
|
||||
language: 'nl',
|
||||
theme,
|
||||
startMode: 'focus',
|
||||
});
|
||||
widget.current = handle;
|
||||
handle.addEventListener('frc:widget.statechange', (event) => {
|
||||
if (event.detail.state !== 'error') {
|
||||
alive();
|
||||
}
|
||||
});
|
||||
handle.addEventListener('frc:widget.complete', (event) => {
|
||||
alive();
|
||||
latestOnToken.current(event.detail.response);
|
||||
});
|
||||
handle.addEventListener('frc:widget.expire', () => latestOnToken.current(null));
|
||||
handle.addEventListener('frc:widget.error', () => {
|
||||
clearTimeout(timer);
|
||||
latestOnToken.current(null);
|
||||
latestOnProblem.current(true);
|
||||
});
|
||||
},
|
||||
() => {
|
||||
clearTimeout(timer);
|
||||
if (!cancelled) {
|
||||
latestOnProblem.current(true);
|
||||
}
|
||||
},
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
clearTimeout(timer);
|
||||
handle?.destroy();
|
||||
widget.current = null;
|
||||
};
|
||||
}, [siteKey, apiEndpoint, theme, loadTimeoutMs]);
|
||||
|
||||
// A used response is gone: start the widget over after each attempt.
|
||||
useEffect(() => {
|
||||
if (resetCount === 0) {
|
||||
return;
|
||||
}
|
||||
widget.current?.reset();
|
||||
latestOnToken.current(null);
|
||||
}, [resetCount]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={element}
|
||||
style={{ minHeight: CAPTCHA_MIN_HEIGHT }}
|
||||
data-testid="contact-form-captcha"
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
@@ -14,6 +14,8 @@ import { useContactPreselect } from '../../shared/contact/useContactPreselect';
|
||||
import { buildSubjectOptions, subjectForSlug } from '../../shared/contact/subjects';
|
||||
import { terminalText } from './eraContent';
|
||||
|
||||
const CaptchaWidget = lazy(() => import('../../shared/contact/CaptchaWidget'));
|
||||
|
||||
interface TerminalFormProps {
|
||||
client: ContactClient;
|
||||
token: ContactToken;
|
||||
@@ -72,6 +74,7 @@ export function TerminalForm({ client, token, refreshToken }: TerminalFormProps)
|
||||
onEvent: (event) => trackEvent(event === 'sent' ? 'contact-sent' : 'contact-failed'),
|
||||
});
|
||||
|
||||
const [captchaProblem, setCaptchaProblem] = useState(false);
|
||||
const successRef = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => {
|
||||
if (form.status === 'sent') {
|
||||
@@ -156,6 +159,29 @@ export function TerminalForm({ client, token, refreshToken }: TerminalFormProps)
|
||||
<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}
|
||||
theme="dark"
|
||||
/>
|
||||
</Suspense>
|
||||
</div>
|
||||
) : null}
|
||||
{captchaProblem ? (
|
||||
<p role="alert" className="e-term-error m-0" 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="e-term-error m-0" data-testid="contact-failure">
|
||||
{form.failureMessage}
|
||||
|
||||
Reference in New Issue
Block a user