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:
2026-11-10 23:27:29 +01:00
co-authored by Claude Sonnet 5.5
parent e09459423f
commit a1444b7b2a
13 changed files with 391 additions and 41 deletions
@@ -0,0 +1,36 @@
# Privacy statement: draft text for the contact form (needs Bryan's approval)
Status: DRAFT. Nothing of this is in the site yet: the page `/privacyverklaring` is still the placeholder "Deze pagina is nog in de maak". The text is site copy in Dutch, so Bryan (and Andrea, as the controller) decide the wording. Items marked **[CHECK]** are facts that must be confirmed before publishing; they are not guessed here.
## What the form sends and stores (from the API contract v0.3.x)
- Sent: name, e-mail address, the chosen shoot (the readable label, e.g. "Newborn"), the message, a signed time token, and (when the captcha is on) the captcha response.
- Stored by the CMS: the four fields, the time of receipt, a status and the mail status. **No IP address is stored** by the contact module (contract section 4.2). Retention period: **[CHECK]** (`retentionUntil` is fixed per message from the server setting; the value for ASF is not decided yet).
- Mail: each message is sent to Andrea's mailbox. **[CHECK]** mail provider and where it processes the data.
- The reply: Andrea answers by e-mail to the address given.
## Captcha (only when switched on)
- Provider: Friendly Captcha (Friendly Captcha GmbH, Germany). Region: the server decides. With the **global** endpoint (free key, tests only) the visitor's IP address can be processed outside the EU; the EU endpoint (`eu`, paid plan) keeps it in the EU. According to the provider the widget uses no cookies and does no tracking (Bryan's note via SLS-Main). **[CHECK]** exactly what the widget sends to the provider (quote the provider's privacy documentation) and whether a processing agreement is needed.
- Commercial use of the free tier is not allowed (Bryan's note): the captcha stays off in production until a paid plan exists, so this paragraph is only published together with the captcha.
## Draft text (Dutch)
### Contactformulier
Als je het contactformulier gebruikt, verwerk ik de gegevens die je invult: je naam, je e-mailadres, de soort shoot waarvoor je interesse hebt en je bericht. Ik gebruik die gegevens alleen om te reageren op je vraag. Het bericht wordt opgeslagen in het beheersysteem van deze website en als e-mail naar mij gestuurd. Je IP-adres wordt daarbij niet bewaard. Ik bewaar je bericht **[CHECK: bewaartermijn]** en verwijder het daarna.
Je kunt me ook gewoon mailen via de knop onder het formulier; dan gebruik je het formulier niet.
### Beveiliging tegen spam
Om spam tegen te gaan gebruikt het formulier een onzichtbaar veld en een korte wachttijd voordat je kunt versturen. **[Alleen bij ingeschakelde captcha:]** Daarnaast controleert de dienst Friendly Captcha (Friendly Captcha GmbH, Duitsland) of je een persoon bent. Volgens de aanbieder gebruikt die controle geen cookies en volgt hij je niet. Daarbij wordt wel je IP-adres naar de dienst gestuurd. **[Bij het gratis `global`-endpoint kan dat buiten de EU verwerkt worden; bij het EU-endpoint blijft het binnen de EU. Kies de zin die past.]** **[CHECK: welke gegevens deze dienst precies ontvangt, dit uit hun privacyinformatie overnemen]**
### Je rechten
Je kunt me vragen welke gegevens ik van je heb, ze te laten corrigeren of verwijderen. Mail daarvoor naar het adres onder het formulier.
## Where it appears
1. `PrivacyNote` under the form already links to `/privacyverklaring`; no change to that line is needed.
2. The page `routes/privacyverklaring.tsx` still has to be written; this draft is the part about the form. A full privacy statement (analytics: Umami without cookies, Sentry, hosting) is a separate piece of content.
## Questions for Bryan (via SLP Software - SLS - Main)
1. Retention period of contact messages for ASF (server setting `retentionUntil`).
2. Is Andrea the controller, and which contact address goes into the text?
3. Approve the wording, or change it.
4. The privacy page is still a placeholder: should the full privacy page be a separate feature, and is the form allowed to go live (test only) before it exists?
@@ -17,7 +17,7 @@ Order matters: steps 1-2 can start with the current package (without captcha); t
- [x] **9. Final package** (after SLS-Main's message): replace `src/cms-client/` by the final version (captcha slot, `initialSubject`); re-run boundary and package tests.
- [x] **10. CaptchaWidget**: new lazy chunk `src/components/ContactForm/CaptchaWidget.tsx` using `@friendlycaptcha/sdk` (`createWidget`, `startMode: focus`, `language: nl`, `apiEndpoint` per Bryan's host choice); complete -> `setCaptchaToken(response)`; expire/error -> `setCaptchaToken(null)` and `reset()`; `destroy()` on unmount; reserved height; add the pinned dependency (check `minimumReleaseAge` rules of pnpm). Tests with a fake SDK: expired token not sent, error resets, unsupported or missing provider keeps the gate, submit blocked with message until solved.
- [x] **11. Preselect with `initialSubject`**: Panel passes the remembered preselect to the form, the form to the hook; test "Boek..." before the form is mounted.
- [ ] **12. Privacy text**: PrivacyNote and the privacy page name the captcha provider and what the form stores (wording needs Bryan's approval; draft goes to SLS-Main for routing).
- [x] **12. Privacy text (draft, for Bryan's approval; not in the site)**: PrivacyNote and the privacy page name the captcha provider and what the form stores (wording needs Bryan's approval; draft goes to SLS-Main for routing).
- [ ] **13. PBT and e2e**: fast-check properties (PBT-02/03/07/08/09) for the label/payload mapping and trim; e2e with a mocked `/api` route: token 200 -> form, 404 -> gate, 202 success, 400 expired -> retry, prerendered HTML check; extend `noJs` e2e (gate and mail button without JS).
- [ ] **14. Documentation**: update `LAYOUT.md` if the contact block changes; README note for the copied package (source and sync rule); `aidlc-docs` code summary.
- [ ] **15. Automatic build and test (Step 13.5)**: `pnpm` typecheck, lint, unit tests, e2e where available, build and prerender; fix and repeat; report any decision only Bryan can make.
+24 -3
View File
@@ -3,6 +3,11 @@ import { contentSecurityPolicy, securityHeaders } from './securityHeaders';
const umami = 'https://analytics.slpsoftware.nl';
const sentry = 'https://o4511795618185216.ingest.de.sentry.io';
const captchaFrames = [
'https://global.frcapi.com',
'https://global0.frcapi.com',
'https://global1.frcapi.com',
];
const directive = (csp: string, name: string) =>
csp.split('; ').find((d) => d.startsWith(name + ' ')) ?? '';
@@ -21,19 +26,35 @@ describe('securityHeaders', () => {
it('productie-CSP opent alleen Umami en Sentry, op de juiste plekken (M7)', () => {
const csp = contentSecurityPolicy('production');
const externalHosts = new Set(csp.match(/https:\/\/[^\s;]+/g));
expect([...externalHosts].sort()).toEqual([sentry, umami].sort());
expect([...externalHosts].sort()).toEqual(
[sentry, umami, ...captchaFrames].sort(),
);
expect(directive(csp, 'connect-src')).toBe(
`connect-src 'self' ${umami} ${sentry}`,
);
// Alleen script-src en connect-src noemen een externe host
// Alleen script-src, connect-src en frame-src noemen een externe host
for (const d of csp.split('; ')) {
if (!/^(script|connect)-src /.test(d)) {
if (!/^(script|connect|frame)-src /.test(d)) {
expect(d).not.toContain('https://');
}
}
expect(csp).not.toContain('*');
});
it('productie-CSP laat het captcha-venster alleen van de drie vaste hosts toe', () => {
const csp = contentSecurityPolicy('production');
expect(directive(csp, 'frame-src')).toBe(
`frame-src ${captchaFrames.join(' ')}`,
);
// Geen wildcard en niets extra's totdat een echte browser het eist
expect(csp).not.toContain('*');
expect(directive(csp, 'script-src')).toBe(`script-src 'self' ${umami}`);
expect(directive(csp, 'worker-src')).toBe('');
expect(directive(csp, 'connect-src')).toBe(
`connect-src 'self' ${umami} ${sentry}`,
);
});
it('dev-CSP voegt alleen toe wat Vite nodig heeft', () => {
const csp = contentSecurityPolicy('development');
expect(directive(csp, 'script-src')).toBe(
+14
View File
@@ -8,6 +8,19 @@ type Mode = 'production' | 'development';
// Chakra/Emotion zetten tijdens runtime <style>-tags in de pagina, daarom
// staat style-src 'unsafe-inline' toe. Scripts komen van de eigen site en het
// Umami-script; verbindingen alleen naar Umami en Sentry (monitoring-plan M7).
// Friendly Captcha (contactformulier): de widget laadt zijn iframes van het
// hoofdhost en twee reservehosts, die de SDK bij een storing probeert. Exact
// deze drie, geen wildcard (besluit Bryan, 2026-11-10). Bij de overstap naar
// het EU-endpoint komen eu, eu0 en eu1 in de plaats; dat regelt de server
// (token-antwoord) en deze lijst moet dan mee. De SDK zelf zit in de eigen
// bundel, dus script-src verandert niet. connect-src en worker-src komen er
// pas bij als een test met een echte browser laat zien dat ze nodig zijn.
export const captchaFrameOrigins = [
'https://global.frcapi.com',
'https://global0.frcapi.com',
'https://global1.frcapi.com',
];
const productionCsp: Record<string, string[]> = {
'default-src': ["'self'"],
'script-src': ["'self'", umamiOrigin],
@@ -15,6 +28,7 @@ const productionCsp: Record<string, string[]> = {
'img-src': ["'self'", 'data:'],
'font-src': ["'self'"],
'connect-src': ["'self'", umamiOrigin, sentryIngestOrigin],
'frame-src': captchaFrameOrigins,
'object-src': ["'none'"],
'base-uri': ["'self'"],
'form-action': ["'self'"],
+1 -1
View File
@@ -61,7 +61,7 @@
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
<add name="Content-Security-Policy" value="default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" />
<add name="Content-Security-Policy" value="default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" />
<add name="Strict-Transport-Security" value="max-age=31536000; includeSubDomains" />
<add name="X-Content-Type-Options" value="nosniff" />
<add name="X-Frame-Options" value="DENY" />
+7 -7
View File
@@ -53,7 +53,7 @@ server {
# /index.html gaan, dat hierboven naar / doorverwijst (lus)
autoindex off;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
@@ -92,7 +92,7 @@ server {
# Testsite nooit indexeren
location = /robots.txt {
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
@@ -105,7 +105,7 @@ server {
# Zonder dit zou $uri.html de pagina met 200 tonen
location = /404 {
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
@@ -118,7 +118,7 @@ server {
# Alleen bereikbaar via error_page; een direct verzoek geeft 404
location = /404.html {
internal;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
@@ -129,7 +129,7 @@ server {
# Bestanden met een hash in de naam: lang cachen
location /assets/ {
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
@@ -141,7 +141,7 @@ server {
# Geen index-directive: de beginpagina staat hier uitdrukkelijk
location = / {
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
@@ -156,7 +156,7 @@ server {
# Nooit een slash achter de variabele zetten: dat geeft nginx' eigen
# mapdoorverwijzing.
location / {
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; frame-src https://global.frcapi.com https://global0.frcapi.com https://global1.frcapi.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
+135
View File
@@ -0,0 +1,135 @@
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
import siteContent from '../src/content/siteContent.ts';
import {
eventually,
openPage,
waitForHydration,
type OpenedPage,
} from './support/browser.ts';
import { startServer } from './support/server.ts';
// Het contactformulier tegen de gebouwde site, met een nagebootste API
// (page.route). Welke tests draaien hangt af van de schakelaar in de content:
// uit (nu) betekent dat de site de server niets vraagt; aan betekent dat het
// formulier opent als de server het toestaat.
const enabled = siteContent.contactForm.enabled;
let server: Awaited<ReturnType<typeof startServer>>;
beforeAll(async () => {
server = await startServer();
});
afterAll(() => server.close());
const TOKEN = {
token: 'signed-token',
minSeconds: 3,
captcha: null,
};
// Houdt bij welke API-verzoeken de pagina doet en beantwoordt ze
function mockApi(options: {
token?: { status: number; body?: unknown };
submit?: { status: number; body?: unknown };
}) {
const requests: string[] = [];
const bodies: unknown[] = [];
return {
requests,
bodies,
prepare: async (page: OpenedPage['page']) => {
await page.route('**/api/v1/**', async (route) => {
const request = route.request();
const path = new URL(request.url()).pathname;
requests.push(`${request.method()} ${path}`);
if (path.endsWith('/token')) {
const { status, body } = options.token ?? {
status: 200,
body: TOKEN,
};
return route.fulfill({
status,
contentType: 'application/json',
body: JSON.stringify(body ?? {}),
});
}
bodies.push(request.postDataJSON());
const { status, body } = options.submit ?? {
status: 202,
body: { status: 'received' },
};
return route.fulfill({
status,
contentType: 'application/json',
body: JSON.stringify(body ?? {}),
});
});
},
};
}
describe.skipIf(enabled)('contactformulier uitgeschakeld', () => {
it('vraagt de server niets en toont de poort op /contact', async () => {
const api = mockApi({});
const { page, ...opened } = await openPage(server.origin + '/contact', {
prepare: api.prepare,
});
await waitForHydration(page);
await eventually(() =>
page.getByTestId('contact-gate-notice').count(),
).toBe(1);
// Scrollen naar het formulier mag ook geen verzoek opleveren
await page.getByTestId('contact-gate-notice').scrollIntoViewIfNeeded();
await page.waitForTimeout(500);
expect(api.requests).toEqual([]);
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
});
});
describe.skipIf(!enabled)('contactformulier ingeschakeld', () => {
const fill = async (page: OpenedPage['page']) => {
await page.getByTestId('contact-form-naam').fill('Demi');
await page.getByTestId('contact-form-email').fill('demi@example.nl');
await page.getByTestId('contact-form-shoot').selectOption('Newborn');
await page
.getByTestId('contact-form-bericht')
.fill('Wanneer heb je plek?');
};
it('opent als de server het toestaat en verstuurt het bericht', async () => {
const api = mockApi({});
const { page, ...opened } = await openPage(server.origin + '/contact', {
prepare: api.prepare,
});
await waitForHydration(page);
await eventually(() =>
page.getByTestId('contact-gate-notice').count(),
).toBe(0);
await fill(page);
await page.getByTestId('contact-form-submit').click();
await eventually(() =>
page.getByTestId('contact-form-sent').count(),
).toBe(1);
expect(api.requests).toEqual([
'GET /api/v1/contact-messages/token',
'POST /api/v1/contact-messages',
]);
expect(api.bodies[0]).toMatchObject({
name: 'Demi',
subject: 'Newborn',
token: 'signed-token',
});
expect(opened.messages).toEqual([]);
expect(opened.violations).toEqual([]);
});
it('blijft bij de poort als het formulier dicht is (404)', async () => {
const api = mockApi({ token: { status: 404 } });
const { page } = await openPage(server.origin + '/contact', {
prepare: api.prepare,
});
await waitForHydration(page);
await eventually(async () => api.requests.length).toBe(1);
expect(await page.getByTestId('contact-gate-notice').count()).toBe(1);
});
});
+2 -2
View File
@@ -168,7 +168,7 @@ describe('zoekwaarden na de hydratatie', () => {
server.origin + '/?pakket=gezin#contact',
);
await waitForHydration(page);
await eventually(() => shootField(page).inputValue()).toBe('gezin');
await eventually(() => shootField(page).inputValue()).toBe('Gezin');
// De tidy-navigatie haalt de zoekwaarde weg, de hash blijft
await page.waitForFunction(() => location.search === '');
expect(new URL(page.url()).hash).toBe('#contact');
@@ -181,7 +181,7 @@ describe('zoekwaarden na de hydratatie', () => {
server.origin + '/contact?pakket=gezin',
);
await waitForHydration(page);
await eventually(() => shootField(page).inputValue()).toBe('gezin');
await eventually(() => shootField(page).inputValue()).toBe('Gezin');
await page.waitForFunction(() => location.search === '');
expect(new URL(page.url()).pathname).toBe('/contact');
expect(opened.messages).toEqual([]);
@@ -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"
/>,
+41 -1
View File
@@ -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}
+24
View File
@@ -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);
},
),
);
});
});