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:
@@ -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(
|
||||
|
||||
@@ -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'"],
|
||||
|
||||
@@ -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" />
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
});
|
||||
@@ -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"
|
||||
/>,
|
||||
|
||||
@@ -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