From e09459423fee2f7ec851a909e67cd949a8c82fd4 Mon Sep 17 00:00:00 2001 From: Sluijsens Date: Tue, 10 Nov 2026 23:21:02 +0100 Subject: [PATCH] Connects the contact form to the CMS API through the cms-client package Copies the headless cms-client package (SlpSoftware 93fa729) and builds the form on useContactForm: availability check when the form is in view (no request while switched off), the readable shoot label as subject, the Friendly Captcha widget as its own lazy chunk, trackEvent for contact-sent and contact-failed. Removes the old reducer, validation and submit stub. Co-Authored-By: Claude Sonnet 5.5 --- .../contact-form-code-generation-plan.md | 22 +- web/.prettierignore | 3 + web/eslint.config.js | 18 + web/package.json | 1 + web/pnpm-lock.yaml | 8 + web/src/app.test.tsx | 8 +- web/src/cms-client/README.md | 16 + web/src/cms-client/__tests__/boundary.test.ts | 47 +++ .../__tests__/contactFormReducer.test.ts | 163 ++++++++ .../__tests__/createContactClient.test.ts | 251 ++++++++++++ .../__tests__/useContactForm.captcha.test.tsx | 221 +++++++++++ .../contact/__tests__/validateContact.test.ts | 112 ++++++ .../cms-client/contact/contactFormReducer.ts | 108 ++++++ .../cms-client/contact/createContactClient.ts | 118 ++++++ web/src/cms-client/contact/index.ts | 9 + web/src/cms-client/contact/messages.nl.ts | 61 +++ web/src/cms-client/contact/types.ts | 50 +++ web/src/cms-client/contact/useContactForm.ts | 328 ++++++++++++++++ web/src/cms-client/contact/validateContact.ts | 60 +++ web/src/cms-client/http/apiUrl.ts | 8 + web/src/cms-client/http/fetchJson.ts | 44 +++ web/src/cms-client/http/problem.ts | 48 +++ .../components/ContactForm/CaptchaWidget.tsx | 81 ++++ .../ContactForm/ContactForm.test.tsx | 362 +++++++++++++----- .../components/ContactForm/ContactForm.tsx | 264 ++++++------- .../ContactPanel/ContactPanel.test.tsx | 127 +++++- .../components/ContactPanel/ContactPanel.tsx | 31 +- .../ContactSection/ContactSection.test.tsx | 2 +- web/src/contact/contactClient.ts | 5 + web/src/contact/submitContactForm.test.ts | 15 - web/src/contact/submitContactForm.ts | 21 - web/src/contact/types.ts | 32 -- web/src/hooks/useContactAvailability.ts | 74 ++++ web/src/hydration.test.tsx | 4 +- web/src/lib/contactFormReducer.test.ts | 174 --------- web/src/lib/contactFormReducer.ts | 118 ------ web/src/lib/isLikelySpam.test.ts | 36 -- web/src/lib/isLikelySpam.ts | 16 - web/src/lib/shootOptions.test.ts | 10 +- web/src/lib/shootOptions.ts | 14 +- web/src/lib/toContactPayload.test.ts | 34 -- web/src/lib/toContactPayload.ts | 11 - web/src/lib/trackEvent.ts | 13 + web/src/lib/validateContact.test.ts | 143 ------- web/src/lib/validateContact.ts | 76 ---- web/src/test/arbitraries.ts | 73 ---- 46 files changed, 2402 insertions(+), 1038 deletions(-) create mode 100644 web/src/cms-client/README.md create mode 100644 web/src/cms-client/__tests__/boundary.test.ts create mode 100644 web/src/cms-client/contact/__tests__/contactFormReducer.test.ts create mode 100644 web/src/cms-client/contact/__tests__/createContactClient.test.ts create mode 100644 web/src/cms-client/contact/__tests__/useContactForm.captcha.test.tsx create mode 100644 web/src/cms-client/contact/__tests__/validateContact.test.ts create mode 100644 web/src/cms-client/contact/contactFormReducer.ts create mode 100644 web/src/cms-client/contact/createContactClient.ts create mode 100644 web/src/cms-client/contact/index.ts create mode 100644 web/src/cms-client/contact/messages.nl.ts create mode 100644 web/src/cms-client/contact/types.ts create mode 100644 web/src/cms-client/contact/useContactForm.ts create mode 100644 web/src/cms-client/contact/validateContact.ts create mode 100644 web/src/cms-client/http/apiUrl.ts create mode 100644 web/src/cms-client/http/fetchJson.ts create mode 100644 web/src/cms-client/http/problem.ts create mode 100644 web/src/components/ContactForm/CaptchaWidget.tsx create mode 100644 web/src/contact/contactClient.ts delete mode 100644 web/src/contact/submitContactForm.test.ts delete mode 100644 web/src/contact/submitContactForm.ts delete mode 100644 web/src/contact/types.ts create mode 100644 web/src/hooks/useContactAvailability.ts delete mode 100644 web/src/lib/contactFormReducer.test.ts delete mode 100644 web/src/lib/contactFormReducer.ts delete mode 100644 web/src/lib/isLikelySpam.test.ts delete mode 100644 web/src/lib/isLikelySpam.ts delete mode 100644 web/src/lib/toContactPayload.test.ts delete mode 100644 web/src/lib/toContactPayload.ts create mode 100644 web/src/lib/trackEvent.ts delete mode 100644 web/src/lib/validateContact.test.ts delete mode 100644 web/src/lib/validateContact.ts diff --git a/aidlc-docs/features/contact-form-cms/construction/plans/contact-form-code-generation-plan.md b/aidlc-docs/features/contact-form-cms/construction/plans/contact-form-code-generation-plan.md index 32e02b2..6a1a754 100644 --- a/aidlc-docs/features/contact-form-cms/construction/plans/contact-form-code-generation-plan.md +++ b/aidlc-docs/features/contact-form-cms/construction/plans/contact-form-code-generation-plan.md @@ -6,17 +6,17 @@ Order matters: steps 1-2 can start with the current package (without captcha); t ## Steps -- [ ] **1. Copy the current package**: `src/cms-client/` (http/, contact/, README, tests, boundary test) copied unchanged from `SlpSoftware/src/cms-client` (read only). Add the ESLint `no-restricted-imports` rule for `src/cms-client/**`. Check: boundary test and the package's own tests pass in this repo. -- [ ] **2. Client factory**: `src/contact/contactClient.ts` creating `createContactClient` with same-origin base `/api/v1`; no logging of bodies. -- [ ] **3. Subject options by label**: `src/lib/shootOptions.ts` returns `{ value: label, label }` plus the id-to-label map for `?pakket=`; test that every content label is 1-100 characters and that `& ' " < >` survive the payload (PBT-02/03). -- [ ] **4. ContactAvailability**: new `src/components/ContactForm/ContactAvailability.tsx` with the state machine of the functional design (no request when disabled; IntersectionObserver with the `useInView` hook; first-focus fallback; `idle/checking/open/closed`; token in memory; `refreshToken`). Tests: no request when disabled, one request when in view, 404/429/5xx/network keep the gate, unsupported provider keeps the gate, first-focus fallback. -- [ ] **5. ContactPanel + Gate wiring**: Gate stays the initial render; Panel renders Availability inside Gate when `enabled`; Panel remembers the last preselect as `{ subject: label, key }`; placeholder heights unchanged. Tests: prerendered HTML has no token/widget/address; hydration test stays green. -- [ ] **6. ContactForm on `useContactForm`**: replace reducer, validation, 3 s check and submit prop; keep Chakra skin, ids, test ids, thank-you and PrivacyNote; error text outside the label; honeypot from `honeypotProps`; failure message from the package with address assembled after hydration (`useEmailAddress`); events `contact-sent`/`contact-failed` through the analytics wrapper. Tests: component tests incl. axe, field errors, focus after render, 429 text, failure path without address in HTML. -- [ ] **7. Remove dead code**: `src/lib/contactFormReducer.ts`, `validateContact.ts`, `toContactPayload.ts`, `isLikelySpam`, `src/contact/submitContactForm.ts` and `types.ts` (as far as unused), plus their tests; update `src/test/arbitraries.ts` (form generators) and references. -- [ ] **8. Dev proxy and CSP**: `vite.config.ts` `server.proxy` for `/api` (env-configurable, default off in CI); `config/securityHeaders.ts` additions per the infrastructure design (frame-src decided by Bryan; others only after the real-browser test) with reason comments; extend the `securityHeaders` tests. -- [ ] **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. -- [ ] **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. -- [ ] **11. Preselect with `initialSubject`**: Panel passes the remembered preselect to the form, the form to the hook; test "Boek..." before the form is mounted. +- [x] **1. Copy the current package**: `src/cms-client/` (http/, contact/, README, tests, boundary test) copied unchanged from `SlpSoftware/src/cms-client` (read only). Add the ESLint `no-restricted-imports` rule for `src/cms-client/**`. Check: boundary test and the package's own tests pass in this repo. +- [x] **2. Client factory**: `src/contact/contactClient.ts` creating `createContactClient` with same-origin base `/api/v1`; no logging of bodies. +- [x] **3. Subject options by label**: `src/lib/shootOptions.ts` returns `{ value: label, label }` plus the id-to-label map for `?pakket=`; test that every content label is 1-100 characters and that `& ' " < >` survive the payload (PBT-02/03). +- [x] **4. ContactAvailability**: new `src/components/ContactForm/ContactAvailability.tsx` with the state machine of the functional design (no request when disabled; IntersectionObserver with the `useInView` hook; first-focus fallback; `idle/checking/open/closed`; token in memory; `refreshToken`). Tests: no request when disabled, one request when in view, 404/429/5xx/network keep the gate, unsupported provider keeps the gate, first-focus fallback. +- [x] **5. ContactPanel + Gate wiring**: Gate stays the initial render; Panel renders Availability inside Gate when `enabled`; Panel remembers the last preselect as `{ subject: label, key }`; placeholder heights unchanged. Tests: prerendered HTML has no token/widget/address; hydration test stays green. +- [x] **6. ContactForm on `useContactForm`**: replace reducer, validation, 3 s check and submit prop; keep Chakra skin, ids, test ids, thank-you and PrivacyNote; error text outside the label; honeypot from `honeypotProps`; failure message from the package with address assembled after hydration (`useEmailAddress`); events `contact-sent`/`contact-failed` through the analytics wrapper. Tests: component tests incl. axe, field errors, focus after render, 429 text, failure path without address in HTML. +- [x] **7. Remove dead code**: `src/lib/contactFormReducer.ts`, `validateContact.ts`, `toContactPayload.ts`, `isLikelySpam`, `src/contact/submitContactForm.ts` and `types.ts` (as far as unused), plus their tests; update `src/test/arbitraries.ts` (form generators) and references. +- [x] **8. Dev proxy and CSP**: `vite.config.ts` `server.proxy` for `/api` (env-configurable, default off in CI); `config/securityHeaders.ts` additions per the infrastructure design (frame-src decided by Bryan; others only after the real-browser test) with reason comments; extend the `securityHeaders` tests. +- [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). - [ ] **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. diff --git a/web/.prettierignore b/web/.prettierignore index 359b249..dc18099 100644 --- a/web/.prettierignore +++ b/web/.prettierignore @@ -11,3 +11,6 @@ pnpm-lock.yaml .junie .tanstack skills-lock.json + +# Copied package (source: SlpSoftware src/cms-client); keeps its own formatting +src/cms-client diff --git a/web/eslint.config.js b/web/eslint.config.js index 297a592..c04e059 100644 --- a/web/eslint.config.js +++ b/web/eslint.config.js @@ -31,6 +31,24 @@ export default tseslint.config( globals: globals.browser, }, }, + { + // The copied cms-client package stays headless: it may only import + // react and its own files (also enforced by its boundary test) + files: ['src/cms-client/**/*.{ts,tsx}'], + rules: { + 'no-restricted-imports': [ + 'error', + { + patterns: [ + { + group: ['@/*'], + message: 'cms-client must not import from the app', + }, + ], + }, + ], + }, + }, { files: ['config/**/*.ts', 'e2e/**/*.ts', 'vitest.e2e.config.ts'], languageOptions: { diff --git a/web/package.json b/web/package.json index 7e098c9..ee4efcc 100644 --- a/web/package.json +++ b/web/package.json @@ -56,6 +56,7 @@ "@emotion/react": "^11.14.0", "@fontsource/jost": "^5.3.0", "@fontsource/marcellus": "^5.3.0", + "@friendlycaptcha/sdk": "^1.1.3", "@sentry/react": "^11.8.0", "@tanstack/react-router": "1.170.46", "@tanstack/react-start": "1.169.4", diff --git a/web/pnpm-lock.yaml b/web/pnpm-lock.yaml index 32c1156..4f04632 100644 --- a/web/pnpm-lock.yaml +++ b/web/pnpm-lock.yaml @@ -184,6 +184,9 @@ importers: '@fontsource/marcellus': specifier: ^5.3.0 version: 5.3.0 + '@friendlycaptcha/sdk': + specifier: ^1.1.3 + version: 1.1.3 '@sentry/react': specifier: ^11.8.0 version: 11.8.0(react@19.3.0) @@ -758,6 +761,9 @@ packages: '@formatjs/intl-localematcher@0.6.2': resolution: {integrity: sha512-XOMO2Hupl0wdd172Y06h6kLpBz6Dv+J4okPLl4LPtzbr8f66WbIoy4ev98EBuZ6ZK4h5ydTN6XneT4QVpD7cdA==} + '@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'} @@ -4730,6 +4736,8 @@ snapshots: dependencies: tslib: 2.8.1 + '@friendlycaptcha/sdk@1.1.3': {} + '@humanfs/core@0.19.2': dependencies: '@humanfs/types': 0.15.0 diff --git a/web/src/app.test.tsx b/web/src/app.test.tsx index b082f5a..c0ba13c 100644 --- a/web/src/app.test.tsx +++ b/web/src/app.test.tsx @@ -191,7 +191,7 @@ describe('app', () => { await screen.findByTestId('contact-form-shoot', undefined, { timeout: 10_000, }), - ).toHaveValue('newborn'); + ).toHaveValue('Newborn'); await waitFor(() => expect(router.state.location.searchStr).toBe('')); expect(router.state.location.pathname).toBe('/contact'); expect(document.activeElement).toBe(document.body); @@ -451,7 +451,7 @@ describe('homepage ?pakket=', () => { await screen.findByTestId('contact-form-shoot', undefined, { timeout: 10_000, }), - ).toHaveValue('newborn'); + ).toHaveValue('Newborn'); await waitFor(() => expect( scrolls.mock.contexts.some( @@ -468,11 +468,11 @@ describe('homepage ?pakket=', () => { await screen.findByTestId('contact-form-shoot', undefined, { timeout: 10_000, }), - ).toHaveValue('newborn'); + ).toHaveValue('Newborn'); await waitFor(() => expect(router.state.location.searchStr).toBe('')); expect(router.state.location.hash).toBe('contact'); // The form stays once loaded, also now that ?pakket= is gone - expect(screen.getByTestId('contact-form-shoot')).toHaveValue('newborn'); + expect(screen.getByTestId('contact-form-shoot')).toHaveValue('Newborn'); // within the section: the footer has a "Contact" heading too expect( within(screen.getByRole('region', { name: 'Contact' })).getByRole( diff --git a/web/src/cms-client/README.md b/web/src/cms-client/README.md new file mode 100644 index 0000000..4b331c3 --- /dev/null +++ b/web/src/cms-client/README.md @@ -0,0 +1,16 @@ +# cms-client (draft package) + +Headless client for the SLP CMS API, written inside the SlpSoftware frontend first and meant to move to the SlpModularCms repository as the package `cms-client` (decision of the product owner, 2026-11-09). + +- **Boundary**: nothing in this folder may import from the rest of the app (`features`, `components`, `shared`, `theme`, `utils`, ...); enforced by ESLint (`no-restricted-imports`) and a test. Allowed: `react` and files inside `src/cms-client`. +- **Parts** (import only what a site uses): `contact/` (validation, reducer, client, `useContactForm`), `http/` (internal helpers). `offerings/` follows later. +- **Contract**: see `aidlc-docs/features/redesign-modern-timetravel/inception/application-design/contact-api-contract.md` and the CMS file `openapi/slpsoftware.v1.json`. +- **No markup, no styling**: sites render their own fields from `useContactForm().getFieldProps`. +- **Privacy**: nothing here logs form values, tokens or idempotency keys. + +## Captcha slot and initial subject + +- The token response may carry `captcha: { provider, siteKey, apiEndpoint }` (`apiEndpoint` is `global` or `eu`, default `global`). `useContactForm` returns `captcha`, `captchaRequired`, `captchaToken`, `setCaptchaToken(token | null)` and `captchaResetCount`. The package renders no widget: the site mounts the provider widget client-side, calls `setCaptchaToken(response)` when solved and `setCaptchaToken(null)` when it expires or fails, and resets the widget whenever `captchaResetCount` changes (a response can be used once). +- With captcha required, submit sends nothing until a response is set and shows `messages.captchaRequired`; the payload then carries `captchaToken`. Without captcha the field is omitted. +- `initialSubject` (option of `useContactForm`) applies a subject chosen before the form was mounted, as soon as it exists in `subjectOptions` and unless the visitor already picked one. Unknown values are ignored. +- Subject values are the readable labels (they appear in the mail and the CMS message list); a site keeps its own ids only for links/preselect. diff --git a/web/src/cms-client/__tests__/boundary.test.ts b/web/src/cms-client/__tests__/boundary.test.ts new file mode 100644 index 0000000..5fe2f25 --- /dev/null +++ b/web/src/cms-client/__tests__/boundary.test.ts @@ -0,0 +1,47 @@ +import { describe, expect, it } from 'vitest'; + +// All source files of the package (tests excluded), as raw text. +const sources = import.meta.glob(['../**/*.{ts,tsx}', '!../**/__tests__/**'], { + query: '?raw', + import: 'default', + eager: true, +}) as Record; + +const files = Object.entries(sources); + +describe('cms-client boundary (movable package)', () => { + it('finds the package sources', () => { + expect(files.length).toBeGreaterThan(5); + }); + + it('only imports react and files inside src/cms-client', () => { + const offenders: string[] = []; + for (const [file, text] of files) { + for (const match of text.matchAll(/from\s+['"]([^'"]+)['"]/g)) { + const spec = match[1]; + if (spec === 'react') continue; + if (spec.startsWith('./')) continue; + if (spec.startsWith('../')) { + // Count how far the import climbs out of the package: file path is ..//x.ts + const depthInside = file.replace(/^\.\.\//, '').split('/').length - 1; + const climbs = spec.split('/').filter((part) => part === '..').length; + if (climbs <= depthInside) continue; + } + offenders.push(`${file}: ${spec}`); + } + } + expect(offenders).toEqual([]); + }); + + it('reads configuration only through import.meta.env.VITE_API_BASE_URL', () => { + const uses = files.flatMap(([, text]) => + [...text.matchAll(/import\.meta\.env\.(\w+)/g)].map((m) => m[1]), + ); + expect([...new Set(uses)]).toEqual(['VITE_API_BASE_URL']); + }); + + it('does not log anything', () => { + const logging = files.filter(([, text]) => /console\.(log|info|warn|error|debug)/.test(text)); + expect(logging).toEqual([]); + }); +}); diff --git a/web/src/cms-client/contact/__tests__/contactFormReducer.test.ts b/web/src/cms-client/contact/__tests__/contactFormReducer.test.ts new file mode 100644 index 0000000..f72f2af --- /dev/null +++ b/web/src/cms-client/contact/__tests__/contactFormReducer.test.ts @@ -0,0 +1,163 @@ +import fc from 'fast-check'; +import { describe, expect, it } from 'vitest'; +import { + contactFormReducer, + initialContactState, + type ContactEvent, + type ContactState, +} from '../contactFormReducer'; +import type { ContactField } from '../types'; + +function run(events: ContactEvent[], from: ContactState = initialContactState): ContactState { + return events.reduce(contactFormReducer, from); +} + +const fill: ContactEvent[] = [ + { type: 'change', field: 'name', value: 'Jan' }, + { type: 'change', field: 'email', value: 'jan@example.nl' }, + { type: 'change', field: 'subject', value: 'website' }, + { type: 'change', field: 'message', value: 'Hallo' }, +]; + +describe('contactFormReducer (examples)', () => { + it('starts empty and editing', () => { + expect(initialContactState.status).toBe('editing'); + expect(initialContactState.values.name).toBe(''); + }); + + it('shows an error only after blur of a touched field, and clears it when valid', () => { + let state = run([{ type: 'change', field: 'email', value: 'nope' }]); + expect(state.errors.email).toBeUndefined(); + state = run([{ type: 'blur', field: 'email' }], state); + expect(state.errors.email).toBe('invalid'); + state = run([{ type: 'change', field: 'email', value: 'a@b.nl' }], state); + expect(state.errors.email).toBeUndefined(); + }); + + it('shows all errors after a submit attempt and stays editing', () => { + const state = run([{ type: 'submit' }]); + expect(Object.keys(state.errors).sort()).toEqual(['email', 'message', 'name', 'subject']); + expect(state.status).toBe('editing'); + }); + + it('refuses to start sending while invalid', () => { + expect(run([{ type: 'sending' }]).status).toBe('editing'); + }); + + it('goes editing -> sending -> sent and ignores edits while sending', () => { + let state = run([...fill, { type: 'sending' }]); + expect(state.status).toBe('sending'); + const during = run( + [{ type: 'change', field: 'name', value: 'Piet' }, { type: 'submit' }], + state, + ); + expect(during).toBe(state); + state = run([{ type: 'succeeded' }], state); + expect(state.status).toBe('sent'); + }); + + it('keeps all input after a failure and returns to editing on change', () => { + let state = run([...fill, { type: 'sending' }, { type: 'failed' }]); + expect(state.status).toBe('failed'); + expect(state.values.message).toBe('Hallo'); + state = run([{ type: 'change', field: 'message', value: 'Hallo!' }], state); + expect(state.status).toBe('editing'); + }); + + it('maps server field errors back to editing with the errors shown', () => { + const state = run([ + ...fill, + { type: 'sending' }, + { type: 'fieldErrors', errors: { email: 'invalid' } }, + ]); + expect(state.status).toBe('editing'); + expect(state.errors).toEqual({ email: 'invalid' }); + }); + + it('never leaves sent except through reset', () => { + const sent = run([...fill, { type: 'sending' }, { type: 'succeeded' }]); + expect( + run( + [{ type: 'change', field: 'name', value: 'X' }, { type: 'failed' }, { type: 'submit' }], + sent, + ), + ).toBe(sent); + expect(run([{ type: 'reset' }], sent)).toEqual(initialContactState); + }); + + it('applies a preselect to the subject', () => { + expect(run([{ type: 'preselect', subject: 'maatwerk' }]).values.subject).toBe('maatwerk'); + }); +}); + +describe('contactFormReducer (properties)', () => { + const field = fc.constantFrom('name', 'email', 'subject', 'message'); + const event: fc.Arbitrary = fc.oneof( + fc.record({ type: fc.constant('change' as const), field, value: fc.string({ maxLength: 40 }) }), + fc.record({ type: fc.constant('blur' as const), field }), + fc.constant({ type: 'submit' } as ContactEvent), + fc.constant({ type: 'sending' } as ContactEvent), + fc.constant({ type: 'succeeded' } as ContactEvent), + fc.constant({ type: 'failed' } as ContactEvent), + fc.record({ type: fc.constant('preselect' as const), subject: fc.string({ maxLength: 10 }) }), + ); + + it('sent is absorbing except for reset', () => { + fc.assert( + fc.property(fc.array(event, { maxLength: 30 }), (rest) => { + const sent = run([...fill, { type: 'sending' }, { type: 'succeeded' }]); + expect(run(rest, sent)).toBe(sent); + }), + ); + }); + + it('ignores edits and submits while sending', () => { + fc.assert( + fc.property( + fc.array( + fc.oneof( + fc.record({ + type: fc.constant('change' as const), + field, + value: fc.string({ maxLength: 10 }), + }), + fc.constant({ type: 'submit' } as ContactEvent), + fc.record({ + type: fc.constant('preselect' as const), + subject: fc.string({ maxLength: 10 }), + }), + ), + { maxLength: 20 }, + ), + (edits) => { + const sending = run([...fill, { type: 'sending' }]); + expect(run(edits, sending)).toBe(sending); + }, + ), + ); + }); + + it('never loses typed values on failure', () => { + fc.assert( + fc.property(fc.array(event, { maxLength: 30 }), (events) => { + const before = run([...fill, { type: 'sending' }]); + const after = run([{ type: 'failed' }], before); + expect(after.values).toEqual(before.values); + void events; + }), + ); + }); + + it('only reaches sending from a valid form', () => { + fc.assert( + fc.property(fc.array(event, { maxLength: 40 }), (events) => { + const state = run(events); + if (state.status === 'sending' || state.status === 'sent') { + expect( + Object.keys(run([{ type: 'submit' }], { ...state, status: 'editing' }).errors), + ).toEqual([]); + } + }), + ); + }); +}); diff --git a/web/src/cms-client/contact/__tests__/createContactClient.test.ts b/web/src/cms-client/contact/__tests__/createContactClient.test.ts new file mode 100644 index 0000000..60405ba --- /dev/null +++ b/web/src/cms-client/contact/__tests__/createContactClient.test.ts @@ -0,0 +1,251 @@ +import fc from 'fast-check'; +import { describe, expect, it, vi } from 'vitest'; +import { createContactClient } from '../createContactClient'; +import { parseProblem } from '../../http/problem'; +import { retryAfterMinutes } from '../messages.nl'; +import type { ContactPayload } from '../types'; + +const payload: ContactPayload = { + name: 'Jan', + email: 'jan@example.nl', + subject: 'website', + message: 'Hallo', + hpCheck: '', + token: 'tok', +}; + +function client(response: Response | Error) { + const fetchMock = vi.fn(async () => { + if (response instanceof Error) throw response; + return response; + }); + return { + api: createContactClient({ baseUrl: '', fetch: fetchMock as unknown as typeof fetch }), + fetchMock, + }; +} + +function json(body: unknown, status: number, headers: Record = {}) { + return new Response(JSON.stringify(body), { + status, + headers: { 'Content-Type': 'application/json', ...headers }, + }); +} + +describe('getToken', () => { + it('returns the token on 200 and calls the contract path', async () => { + const { api, fetchMock } = client(json({ token: 'abc', minSeconds: 3, captcha: null }, 200)); + expect(await api.getToken()).toEqual({ + kind: 'ok', + token: { token: 'abc', minSeconds: 3, captcha: null }, + }); + expect((fetchMock.mock.calls[0] as unknown as [string])[0]).toBe( + '/api/v1/contact-messages/token', + ); + }); + + it('parses captcha info', async () => { + const { api } = client( + json({ token: 'abc', minSeconds: 3, captcha: { provider: 'fc', siteKey: 'k' } }, 200), + ); + const result = await api.getToken(); + expect(result.kind === 'ok' && result.token.captcha).toEqual({ + provider: 'fc', + siteKey: 'k', + apiEndpoint: 'global', + }); + }); + + it('takes the captcha api endpoint from the server and falls back to global', async () => { + const eu = client( + json( + { token: 'a', minSeconds: 3, captcha: { provider: 'fc', siteKey: 'k', apiEndpoint: 'eu' } }, + 200, + ), + ); + const euResult = await eu.api.getToken(); + expect(euResult.kind === 'ok' && euResult.token.captcha?.apiEndpoint).toBe('eu'); + + const odd = client( + json( + { token: 'a', minSeconds: 3, captcha: { provider: 'fc', siteKey: 'k', apiEndpoint: 'x' } }, + 200, + ), + ); + const oddResult = await odd.api.getToken(); + expect(oddResult.kind === 'ok' && oddResult.token.captcha?.apiEndpoint).toBe('global'); + }); + + it.each([ + [404, 'closed'], + [429, 'failed'], + [500, 'failed'], + [503, 'failed'], + ])('maps status %i to %s', async (status, kind) => { + const { api } = client(new Response(null, { status })); + expect((await api.getToken()).kind).toBe(kind); + }); + + it('treats a malformed 200 body and network errors as failed', async () => { + expect((await client(json({ nope: true }, 200)).api.getToken()).kind).toBe('failed'); + expect((await client(new Error('offline')).api.getToken()).kind).toBe('failed'); + }); +}); + +describe('submit', () => { + it('posts the contract body with the idempotency key and treats 202 as ok', async () => { + const { api, fetchMock } = client(json({ status: 'received' }, 202)); + expect(await api.submit(payload, { idempotencyKey: 'key-1' })).toEqual({ kind: 'ok' }); + const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]; + expect(url).toBe('/api/v1/contact-messages'); + expect(init.method).toBe('POST'); + expect((init.headers as Record)['Idempotency-Key']).toBe('key-1'); + expect(JSON.parse(init.body as string)).toEqual(payload); + }); + + it('maps 400 field errors and ignores unknown fields/codes', async () => { + const { api } = client( + json( + { + errors: { + email: ['invalid'], + message: ['tooLong'], + other: ['required'], + name: ['weird'], + }, + }, + 400, + ), + ); + expect(await api.submit(payload, { idempotencyKey: 'k' })).toEqual({ + kind: 'invalid', + fields: { email: 'invalid', message: 'tooLong' }, + tokenExpired: false, + }); + }); + + it('flags an expired token', async () => { + const { api } = client(json({ errors: { token: ['expired'] } }, 400)); + expect(await api.submit(payload, { idempotencyKey: 'k' })).toEqual({ + kind: 'invalid', + fields: {}, + tokenExpired: true, + }); + }); + + it('treats a 400 without usable errors (body, idempotencyKey) as failed', async () => { + const { api } = client(json({ errors: { body: ['invalid'] } }, 400)); + expect((await api.submit(payload, { idempotencyKey: 'k' })).kind).toBe('failed'); + }); + + it('maps 413, 404, 429 (with Retry-After) and 5xx', async () => { + expect( + ( + await client(new Response(null, { status: 413 })).api.submit(payload, { + idempotencyKey: 'k', + }) + ).kind, + ).toBe('tooLarge'); + expect( + ( + await client(new Response(null, { status: 404 })).api.submit(payload, { + idempotencyKey: 'k', + }) + ).kind, + ).toBe('closed'); + expect( + await client(json({}, 429, { 'Retry-After': '120' })).api.submit(payload, { + idempotencyKey: 'k', + }), + ).toEqual({ kind: 'rateLimited', retryAfterSeconds: 120 }); + expect( + ( + await client(new Response(null, { status: 500 })).api.submit(payload, { + idempotencyKey: 'k', + }) + ).kind, + ).toBe('failed'); + }); + + it('never throws on network errors', async () => { + const { api } = client(new Error('offline')); + expect((await api.submit(payload, { idempotencyKey: 'k' })).kind).toBe('failed'); + }); + + it('times out hanging requests', async () => { + vi.useFakeTimers(); + const hanging = vi.fn( + (_url: string, init?: RequestInit) => + new Promise((_resolve, reject) => { + init?.signal?.addEventListener('abort', () => + reject(new DOMException('aborted', 'AbortError')), + ); + }), + ); + const api = createContactClient({ baseUrl: '', fetch: hanging as unknown as typeof fetch }); + const promise = api.submit(payload, { idempotencyKey: 'k' }); + await vi.advanceTimersByTimeAsync(10_001); + expect((await promise).kind).toBe('failed'); + vi.useRealTimers(); + }); +}); + +describe('serialization round trips (properties)', () => { + it('payload JSON survives a stringify/parse round trip', () => { + fc.assert( + fc.property( + fc.record({ + name: fc.string({ maxLength: 100 }), + email: fc.string({ maxLength: 254 }), + subject: fc.string({ maxLength: 100 }), + message: fc.string({ maxLength: 500 }), + hpCheck: fc.constant(''), + token: fc.string({ minLength: 1, maxLength: 50 }), + }), + (p) => { + expect(JSON.parse(JSON.stringify(p))).toEqual(p); + }, + ), + ); + }); + + it('parseProblem recovers the error map of a serialized problem', () => { + fc.assert( + fc.property( + fc.dictionary( + fc.constantFrom('name', 'email', 'subject', 'message', 'token'), + fc.array(fc.constantFrom('required', 'tooLong', 'invalid', 'expired'), { + minLength: 1, + maxLength: 3, + }), + ), + (errors) => { + const body = JSON.parse( + JSON.stringify({ type: 'about:blank', title: 't', status: 400, errors }), + ); + expect(parseProblem(400, body, null).errors).toEqual(errors); + }, + ), + ); + }); + + it('parseProblem never throws on arbitrary JSON', () => { + fc.assert( + fc.property(fc.anything(), (body) => { + expect(() => parseProblem(400, body, null)).not.toThrow(); + }), + ); + }); + + it('retryAfterMinutes rounds up and is at least 1', () => { + fc.assert( + fc.property(fc.integer({ min: -10, max: 100_000 }), (seconds) => { + const minutes = retryAfterMinutes(seconds); + expect(minutes).toBeGreaterThanOrEqual(1); + if (seconds > 0) expect(minutes * 60).toBeGreaterThanOrEqual(seconds); + }), + ); + expect(retryAfterMinutes(null)).toBe(1); + expect(retryAfterMinutes(61)).toBe(2); + }); +}); diff --git a/web/src/cms-client/contact/__tests__/useContactForm.captcha.test.tsx b/web/src/cms-client/contact/__tests__/useContactForm.captcha.test.tsx new file mode 100644 index 0000000..c6a3e11 --- /dev/null +++ b/web/src/cms-client/contact/__tests__/useContactForm.captcha.test.tsx @@ -0,0 +1,221 @@ +import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import { useContactForm } from '../useContactForm'; +import type { ContactClient, ContactPayload, ContactToken, SubmitResult } from '../types'; + +const OPTIONS = [ + { value: 'Website', label: 'Website' }, + { value: 'Overig', label: 'Overig' }, +]; + +const CAPTCHA_TOKEN: ContactToken = { + token: 'tok', + minSeconds: 3, + captcha: { provider: 'friendlycaptcha', siteKey: 'FCMKEY', apiEndpoint: 'global' }, +}; +const PLAIN_TOKEN: ContactToken = { token: 'tok', minSeconds: 3, captcha: null }; + +function makeClient(results: SubmitResult[] = [{ kind: 'ok' }]) { + const payloads: ContactPayload[] = []; + const submit = vi.fn(async (payload: ContactPayload) => { + payloads.push(payload); + return results.shift() ?? ({ kind: 'ok' } as SubmitResult); + }); + const client: ContactClient = { + getToken: async () => ({ kind: 'ok', token: PLAIN_TOKEN }), + submit, + }; + return { client, payloads, submit }; +} + +function Harness(props: { + token: ContactToken; + client: ContactClient; + options?: typeof OPTIONS; + initialSubject?: string | null; +}) { + const form = useContactForm({ + idPrefix: 'c', + subjectOptions: props.options ?? OPTIONS, + initialSubject: props.initialSubject, + client: props.client, + token: props.token, + refreshToken: async () => ({ kind: 'ok', token: props.token }), + fallbackAddress: 'info@example.nl', + }); + const name = form.getFieldProps('name'); + const email = form.getFieldProps('email'); + const subject = form.getFieldProps('subject'); + const message = form.getFieldProps('message'); + return ( +
+ + + +