Adds the captcha frame hosts to the CSP and handles a widget that cannot load
frame-src gets the three exact Friendly Captcha global hosts (no wildcard). When the widget errors, is blocked or shows no sign of life, the form says so and offers the mail button instead of blocking silently. Adds an e2e for the form with a mocked API, a draft privacy text for approval, and label tests. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -13,8 +13,17 @@ type CaptchaWidgetProps = {
|
||||
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 instead of blocking silently.
|
||||
onProblem: (problem: boolean) => void;
|
||||
// Test seam: how long the widget gets before it counts as a problem
|
||||
loadTimeoutMs?: number;
|
||||
};
|
||||
|
||||
// How long the widget gets to show a first sign of life
|
||||
export const CAPTCHA_LOAD_TIMEOUT_MS = 15_000;
|
||||
|
||||
// The Friendly Captcha v2 widget (the bundled @friendlycaptcha/sdk). Client
|
||||
// only: it is a separate chunk that loads when the form is open and needs a
|
||||
// captcha, never part of the prerendered page. The visitor starts it by
|
||||
@@ -24,45 +33,72 @@ export default function CaptchaWidget({
|
||||
captcha,
|
||||
resetCount,
|
||||
onToken,
|
||||
onProblem,
|
||||
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;
|
||||
}, [onToken]);
|
||||
latestOnProblem.current = onProblem;
|
||||
}, [onToken, onProblem]);
|
||||
|
||||
const { siteKey, apiEndpoint } = captcha;
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
let handle: WidgetHandle | null = null;
|
||||
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: 'light',
|
||||
startMode: 'focus',
|
||||
});
|
||||
widget.current = handle;
|
||||
handle.addEventListener('frc:widget.complete', (event) =>
|
||||
latestOnToken.current(event.detail.response),
|
||||
);
|
||||
handle.addEventListener('frc:widget.expire', () =>
|
||||
latestOnToken.current(null),
|
||||
);
|
||||
handle.addEventListener('frc:widget.error', () =>
|
||||
latestOnToken.current(null),
|
||||
);
|
||||
});
|
||||
// No sign of life in time counts as a problem (a blocked iframe or
|
||||
// script may not report an error at all)
|
||||
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: 'light',
|
||||
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]);
|
||||
}, [siteKey, apiEndpoint, loadTimeoutMs]);
|
||||
|
||||
// A used response is gone: start the widget over after each attempt
|
||||
useEffect(() => {
|
||||
|
||||
@@ -18,7 +18,9 @@ import ContactForm, { type FormAvailability } from './ContactForm';
|
||||
// A stand-in for the Friendly Captcha SDK: widgets the test can solve,
|
||||
// expire and watch
|
||||
const sdk = vi.hoisted(() => {
|
||||
type Listener = (event: { detail: { response: string } }) => void;
|
||||
type Listener = (event: {
|
||||
detail: { response: string; state?: string };
|
||||
}) => void;
|
||||
class FakeWidget {
|
||||
listeners = new Map<string, Listener>();
|
||||
reset = vi.fn();
|
||||
@@ -30,8 +32,8 @@ const sdk = vi.hoisted(() => {
|
||||
addEventListener(type: string, listener: Listener) {
|
||||
this.listeners.set(type, listener);
|
||||
}
|
||||
emit(type: string, response = '') {
|
||||
this.listeners.get(type)?.({ detail: { response } });
|
||||
emit(type: string, response = '', state?: string) {
|
||||
this.listeners.get(type)?.({ detail: { response, state } });
|
||||
}
|
||||
}
|
||||
const state = {
|
||||
@@ -93,6 +95,7 @@ const renderForm = (
|
||||
<ContactForm
|
||||
idPrefix="test"
|
||||
options={options}
|
||||
mailSubject="Vraag via andreaslop.nl"
|
||||
email={siteContent.email}
|
||||
replyTime="1-2 werkdagen"
|
||||
availability={open()}
|
||||
@@ -266,6 +269,7 @@ describe('ContactForm', () => {
|
||||
idPrefix="test"
|
||||
options={options}
|
||||
preselect={preselect}
|
||||
mailSubject="Vraag via andreaslop.nl"
|
||||
email={siteContent.email}
|
||||
replyTime="1-2 werkdagen"
|
||||
availability={open()}
|
||||
@@ -381,6 +385,44 @@ describe('ContactForm with a captcha', () => {
|
||||
expect(created.destroy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('says so and offers the mail button when the widget reports an error', async () => {
|
||||
await renderForm({ availability: open(CAPTCHA) });
|
||||
const created = await widget();
|
||||
act(() => created.emit('frc:widget.error', '.ERROR'));
|
||||
const problem = await screen.findByTestId(
|
||||
'contact-form-captcha-problem',
|
||||
);
|
||||
expect(problem).toHaveTextContent('kon niet laden');
|
||||
expect(
|
||||
await screen.findByRole('link', { name: 'info@andreaslop.nl' }),
|
||||
).toHaveAttribute(
|
||||
'href',
|
||||
'mailto:info@andreaslop.nl?subject=Vraag%20via%20andreaslop.nl',
|
||||
);
|
||||
});
|
||||
|
||||
it('says so when the widget shows no sign of life in time', async () => {
|
||||
await renderForm({
|
||||
availability: open(CAPTCHA),
|
||||
captchaLoadTimeoutMs: 50,
|
||||
});
|
||||
await widget();
|
||||
expect(
|
||||
await screen.findByTestId('contact-form-captcha-problem'),
|
||||
).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows no problem when the widget starts in time', async () => {
|
||||
await renderForm({
|
||||
availability: open(CAPTCHA),
|
||||
captchaLoadTimeoutMs: 150,
|
||||
});
|
||||
const created = await widget();
|
||||
act(() => created.emit('frc:widget.statechange', '', 'ready'));
|
||||
await new Promise((resolve) => setTimeout(resolve, 300));
|
||||
expect(screen.queryByTestId('contact-form-captcha-problem')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows no widget without a captcha', async () => {
|
||||
await renderForm();
|
||||
expect(screen.queryByTestId('contact-form-captcha')).toBeNull();
|
||||
@@ -394,6 +436,7 @@ describe('ContactForm in the prerendered HTML', () => {
|
||||
<ContactForm
|
||||
idPrefix="test"
|
||||
options={options}
|
||||
mailSubject="Vraag via andreaslop.nl"
|
||||
email={siteContent.email}
|
||||
replyTime="1-2 werkdagen"
|
||||
/>,
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
import { lazy, Suspense, useEffect, useRef } from 'react';
|
||||
import { lazy, Suspense, useEffect, useRef, useState } from 'react';
|
||||
import {
|
||||
Box,
|
||||
chakra,
|
||||
Field,
|
||||
Input,
|
||||
Link,
|
||||
NativeSelect,
|
||||
SimpleGrid,
|
||||
Stack,
|
||||
@@ -24,6 +25,7 @@ import {
|
||||
import { contactClient } from '@/contact/contactClient';
|
||||
import type { EmailAddress } from '@/content/types';
|
||||
import useEmailAddress from '@/hooks/useEmailAddress';
|
||||
import { mailtoLink } from '@/lib/mailLink';
|
||||
import { trackContactEvent } from '@/lib/trackEvent';
|
||||
import { CAPTCHA_HEIGHT } from './CaptchaWidget';
|
||||
|
||||
@@ -51,12 +53,15 @@ type ContactFormProps = {
|
||||
// A package chosen via "Boek ..." (its label); key changes on every
|
||||
// click, so the same package can be applied again after a change
|
||||
preselect?: { subject: string; key: number };
|
||||
mailSubject: string;
|
||||
email: EmailAddress;
|
||||
// How soon Andrea answers, e.g. '1-2 werkdagen' (siteContent)
|
||||
replyTime: string;
|
||||
// Null while the form is only shown behind the gate
|
||||
availability?: FormAvailability | null;
|
||||
client?: ContactClient;
|
||||
// Test seam, see CaptchaWidget
|
||||
captchaLoadTimeoutMs?: number;
|
||||
};
|
||||
|
||||
// The test ids keep the Dutch field names of the page; the package fields
|
||||
@@ -76,15 +81,19 @@ export default function ContactForm({
|
||||
idPrefix,
|
||||
options,
|
||||
preselect,
|
||||
mailSubject,
|
||||
email,
|
||||
replyTime,
|
||||
availability = null,
|
||||
client = contactClient,
|
||||
captchaLoadTimeoutMs,
|
||||
}: ContactFormProps) {
|
||||
const formControl = useRecipe({ key: 'formControl' });
|
||||
const linkButton = useRecipe({ key: 'linkButton' });
|
||||
const { address } = useEmailAddress(email);
|
||||
const sentMessage = useRef<HTMLDivElement>(null);
|
||||
// The robot check cannot work: say so and offer the mail button
|
||||
const [captchaProblem, setCaptchaProblem] = useState(false);
|
||||
|
||||
const { token, refreshToken } = availability ?? PREVIEW_AVAILABILITY;
|
||||
const form = useContactForm({
|
||||
@@ -253,9 +262,40 @@ export default function ContactForm({
|
||||
captcha={form.captcha}
|
||||
resetCount={form.captchaResetCount}
|
||||
onToken={form.setCaptchaToken}
|
||||
onProblem={setCaptchaProblem}
|
||||
loadTimeoutMs={captchaLoadTimeoutMs}
|
||||
/>
|
||||
</Suspense>
|
||||
)}
|
||||
{captchaProblem && (
|
||||
<Box
|
||||
role="alert"
|
||||
data-testid="contact-form-captcha-problem"
|
||||
p={4}
|
||||
borderStartWidth="2px"
|
||||
borderStartColor="error"
|
||||
bg="paper.alt"
|
||||
fontSize="sm"
|
||||
>
|
||||
<Text>
|
||||
De controle dat je geen robot bent kon niet laden.
|
||||
Ververs de pagina of
|
||||
{address ? (
|
||||
<>
|
||||
{' mail naar '}
|
||||
<Link
|
||||
variant="underline"
|
||||
href={mailtoLink(address, mailSubject)}
|
||||
>
|
||||
{address}
|
||||
</Link>
|
||||
</>
|
||||
) : (
|
||||
' mail me.'
|
||||
)}
|
||||
</Text>
|
||||
</Box>
|
||||
)}
|
||||
|
||||
{form.failureMessage && (
|
||||
<Box
|
||||
|
||||
@@ -104,6 +104,7 @@ export default function ContactPanel({
|
||||
idPrefix={idPrefix}
|
||||
options={options}
|
||||
preselect={preselect}
|
||||
mailSubject={subject}
|
||||
email={email}
|
||||
replyTime={replyTime}
|
||||
availability={open ? availability : null}
|
||||
|
||||
@@ -29,4 +29,28 @@ describe('shootOptions', () => {
|
||||
}),
|
||||
);
|
||||
});
|
||||
it('has 1 to 100 characters per label and no double values (the subject limits)', () => {
|
||||
const options = shootOptions(packages);
|
||||
for (const option of options) {
|
||||
expect(option.label.length).toBeGreaterThanOrEqual(1);
|
||||
expect(option.label.length).toBeLessThanOrEqual(100);
|
||||
// The label is what is sent, so the value is the label
|
||||
expect(option.value).toBe(option.label);
|
||||
}
|
||||
expect(new Set(options.map((o) => o.value)).size).toBe(options.length);
|
||||
});
|
||||
|
||||
it('keeps a label with special characters unchanged through the JSON of the payload (round trip)', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.string({ minLength: 1, maxLength: 100 }),
|
||||
fc.constantFrom('&', "'", '"', '<', '>'),
|
||||
(text, special) => {
|
||||
const label = `${special}${text}${special}`.slice(0, 100);
|
||||
const payload = JSON.stringify({ subject: label });
|
||||
expect(JSON.parse(payload).subject).toBe(label);
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user