Starts the contact form feature: AI-DLC inception and design, dev proxy for /api

Adds the contact-form-cms feature docs (requirements, execution plan,
functional and infrastructure design, code generation plan) and an optional
Vite dev proxy for /api through API_PROXY_TARGET.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 23:04:16 +01:00
co-authored by Claude Sonnet 5.5
parent 7d594ffa1d
commit 4da314c0ba
10 changed files with 490 additions and 1 deletions
@@ -0,0 +1,115 @@
# Functional design: contact-form (unit 1, web)
Status: DRAFT for approval by SLP Software - SLS - Main (on behalf of Bryan). Based on the package in `SlpSoftware/src/cms-client` (current version without captcha) and the existing ASF components. Details marked **[slot]** depend on the captcha slot that SLS-Main still builds.
## 1. Components and responsibilities
```mermaid
flowchart TD
CP[ContactPanel<br/>existing: packages, ?pakket=, lazy chunk] --> GATE[ContactFormGate<br/>existing: dimmed Binnenkort]
GATE -->|enabled=true| AV[ContactAvailability<br/>NEW: token fetch when in view]
AV -->|token ok and provider supported| CF[ContactForm<br/>ADAPTED: skin on useContactForm]
AV -->|anything else| GATE
CF --> HOOK[useContactForm<br/>cms-client]
CF --> CAP[CaptchaWidget<br/>NEW: client only, reserved height]
HOOK --> CLIENT[createContactClient<br/>cms-client]
CLIENT --> API[(/api/v1/contact-messages)]
classDef existing fill:#9ae6b4,stroke:#2f855a,color:#000;
classDef newc fill:#63b3ed,stroke:#2b6cb0,color:#000;
classDef pkg fill:#f6e05e,stroke:#c05621,color:#000;
class CP,GATE existing;
class AV,CAP newc;
class CF newc;
class HOOK,CLIENT pkg;
```
Text alternative: ContactPanel renders the gate; when enabled, ContactAvailability fetches the token and only then mounts the adapted ContactForm, which uses the package hook and, when needed, the captcha widget.
| Part | Change |
|---|---|
| `ContactPanel` | Keeps shoot options, `?pakket=` and the lazy chunk. Maps the chosen package id to its **label** and remembers the last preselect (FR-CF-08). Passes `enabled` through. |
| `ContactFormGate` | Unchanged look. Stays the initial render and the closed state. Its mail button keeps the `useEmailAddress` approach (no address in HTML before hydration). |
| `ContactAvailability` (new) | Only when `enabled`: waits until the form area is in view (IntersectionObserver, wide rootMargin; fallback first focus/pointer when IO is missing), then calls `client.getToken()` once. Exposes `{ state: 'idle' \| 'checking' \| 'open' \| 'closed', token, refreshToken }`. Renders children only in `open`. No request when `enabled=false`. |
| `ContactForm` | Keeps the Chakra skin, ids, test ids, thank-you and privacy note. State, validation, submit, idempotency and token refresh come from `useContactForm`. The old reducer, `validateContact`, `toContactPayload` and `submitContactForm` are deleted. |
| `CaptchaWidget` (new) | Renders the Friendly Captcha widget only when the token response says `captcha` with a supported provider. Client-only, after mount, in a reserved height. **[slot]** |
| `cms-client` | Copied unchanged into `web/src/cms-client/` (final version after SLS-Main's message). |
## 2. Availability state machine (ContactAvailability)
| From | Event | To | Note |
|---|---|---|---|
| idle | `enabled=false` | idle | no request, gate stays |
| idle | in view (or first focus without IO) and `enabled` | checking | one `getToken()` |
| checking | `ok` and (`captcha=null` or provider supported) | open | token kept in memory only |
| checking | `ok` and unsupported provider | closed | gate; no log of the provider value beyond a generic event |
| checking | `closed` (404) / `failed` / 429 / network | closed | gate; no retry loop (a later page view tries again) |
| open | submit reports `expired` | open | `refreshToken()` once (package) |
| closed | - | closed | terminal for this page view |
Prerender and first client render are always `idle` (the gate), so there is no hydration mismatch and no layout shift: the placeholder heights 649/547 px stay.
## 3. Field mapping and validation
| Visible field | Package field | Limit | Notes |
|---|---|---|---|
| Naam | `name` | 100 | `autoComplete="name"` |
| E-mail | `email` | 254 | `type=email`, `autoComplete="email"` |
| In welke shoot... | `subject` | 100 | **value = readable label**; options are `{ value: label, label }` from `shootOptions`; "Overig" is the fixed label for other |
| Stel hier je vraag | `message` | 2000 | |
- Validation and the Dutch messages come from the package (`required`, `tooLong`, `invalid`). Error texts of the old reducer are gone; where the package text differs from the old text, the package wins (SLS-Main and Bryan accepted: no forks).
- Trim is done by the package (`trimFields`). Maximum lengths also stay as `maxLength` on the inputs.
- `?pakket=` resolves to a package id (existing `packageFromSearch`) and then to that package's label before reaching the hook (`subject` is the label).
## 4. Submit flow (package)
1. Submit with errors: errors show per field, focus moves after the render to the first invalid field (inputs are disabled while sending).
2. Valid: `Idempotency-Key` per attempt series, honeypot `hpCheck` from the hook, token from availability, `captchaToken` **[slot]**.
3. `202`: thank-you (`Bedankt voor je bericht! Ik reageer binnen {replyTime}.`) takes focus; event `contact-sent`.
4. `400 expired`: one refresh and retry (package). Field errors map to fields.
5. 413 / 429 / 5xx / network: failure message from the package (429 with Retry-After in minutes); mail fallback text with the address assembled client-side after hydration; event `contact-failed`. The visitor can try again; the form keeps the typed values.
6. Spam (honeypot filled): silent success, no request (package).
Events go through the existing analytics wrapper with only `contact-sent` and `contact-failed`. No field values, token or idempotency key reach logs, Sentry or Umami.
## 5. Preselect (FR-CF-08)
`ContactPanel` keeps `{ subject: label, key }` from the first "Boek..." click, also before the form chunk has mounted, and `ContactForm` passes it to the hook as `initialSubject` (added to the package by SLP Software - SLS - Main together with the captcha slot) plus the `preselect` change counter for later clicks. The earlier key-bump workaround is dropped. Until the final package arrives, the code is written against `initialSubject` and tested with a fake of the hook.
## 6. Captcha **[slot]**
- Data: token response `captcha: { provider, siteKey }` or `null`.
- Supported: `friendlycaptcha` only. Anything else keeps the gate.
- Hook offers `setCaptchaToken(token|null)` and `captchaRequired`. The widget calls `setCaptchaToken` on solve, `setCaptchaToken(null)` and a reset on expiry or error.
- Decided by Bryan: Friendly Captcha v2 with the bundled npm package `@friendlycaptcha/sdk`. The CSP guide says the widget uses iframes, so `frame-src` is needed (see infrastructure design); no external script tag.
- SDK details verified against the current docs (developer.friendlycaptcha.com, v2):
- Package `@friendlycaptcha/sdk`; `FriendlyCaptchaSDK.createWidget({ element, sitekey, apiEndpoint, language, theme, startMode, formFieldName })`; `startMode` is `auto`, `focus` (default) or `none`; `apiEndpoint` accepts the shortcuts `"global"` (default) and `"eu"`; `formFieldName` default `frc-captcha-response`; `theme` `light | dark | auto`.
- Widget handle: `reset()`, `destroy()`, `getResponse()`, `start()`, `getState()`, `getElement()`.
- Events on the widget element: `frc:widget.complete` (`event.detail.response` is the token), `frc:widget.expire` (response `.EXPIRED`), `frc:widget.error` (response `.ERROR`, `detail.error.code`), `frc:widget.statechange`.
- We use the `response` of `complete` as `captchaToken` (not the form field), and set it to null on `expire`/`error`, then `reset()`.
- Choices for ASF: `startMode: "focus"` (starts when the visitor focuses the form), `language: "nl"`, `theme: "light"`, `apiEndpoint` from the host Bryan picks (`"eu"` recommended).
- Still to verify in Build and Test with a real browser: exact behaviour on `reset()` and the CSP entries marked "test".
- A missing token counts as spam on the server (still `202`), so the client blocks the submit with a clear message until the captcha is solved when `captchaRequired`; the client never relies on the server to tell the visitor.
- The widget code is a separate lazy chunk, loaded only in `open` with captcha required; reserved height; no script in prerendered HTML.
- Provider outage is fail-open on the server; the client never decides that.
## 7. Accessibility
Labels stay `Field.Label`; error text is outside the label (accessible name stays clean); `aria-invalid` and `aria-describedby` come from the hook; success and failure use `role="status"`/`role="alert"`; the honeypot stays off-screen, `aria-hidden`, `tabIndex=-1`, `autoComplete="off"`; focus order unchanged; axe tests stay part of the component tests.
## 8. Business rules (BR-CF)
- BR-CF-01 No token request unless `enabled` and the form is in view.
- BR-CF-02 The form is interactive only when the server said `200` and (captcha absent or supported).
- BR-CF-03 Subject sent is always the visible label, 1-100 characters.
- BR-CF-04 No personal data, token or idempotency key leaves the form except in the POST body.
- BR-CF-05 Prerendered HTML contains no token, widget or e-mail address.
- BR-CF-06 Failure never exposes technical text; the mail fallback is always offered.
- BR-CF-07 An expired captcha token is never sent.
## 9. Testability and PBT (partial)
- PBT-02/03 (round trip, invariants): `label -> payload.subject` (length 1-100 for all content labels; labels with & ' " < > survive the JSON round trip); `trimFields` idempotent.
- PBT-07/08/09: generators for form values shared in `src/test/arbitraries.ts`, shrinkable, seeds logged by the existing setup.
- Example-based tests: gate states, no request when disabled, unsupported captcha keeps gate, expired captcha token not sent, 429 text from the package, failure path without the address in HTML, preselect before mount.
- E2E (mocked `/api` route): token 200 -> form; 404 -> gate; submit 202; submit 400 expired -> retry; prerendered HTML check (no token/widget/address).
- Manual run against the temporary environment (192.168.1.2) with evidence.
## 10. Open items
1. Final package (captcha slot) and the exact captcha version/CSP: pending SLS-Main and CMS-U9.
2. Package text changes versus the old texts (small differences) are accepted unless Bryan objects to wording.
3. `initialSubject` arrives with the final package (SLS-Main).
4. Host (EU or global), exact versus wildcard `frame-src` and the plan needed for the EU endpoint: Bryan decides.
@@ -0,0 +1,64 @@
# Infrastructure design: contact-form (unit 1, web)
Status: DRAFT for approval by SLP Software - SLS - Main (on behalf of Bryan).
## 1. Request path
All calls are same-origin: `/api/v1/contact-messages/token` and `/api/v1/contact-messages`. The site is served by the CMS host (test now, ASF production on IIS later), which also serves `/api`; no CORS and no new origin for the API.
```mermaid
flowchart LR
B[Browser] -->|same origin /api/v1| H[ASF CMS host<br/>contact module]
H --> M[(MariaDB)]
H --> S[SMTP]
B -.captcha API.-> F[Friendly Captcha<br/>global.frcapi.com provisional]
classDef c fill:#f6e05e,stroke:#c05621,color:#000;
classDef s fill:#63b3ed,stroke:#2b6cb0,color:#000;
classDef x fill:#fbb6ce,stroke:#97266d,color:#000;
class B c;
class H,M,S s;
class F x;
```
Text alternative: the browser talks only to the ASF CMS host on the same origin, plus the captcha provider's API when a captcha is required.
## 2. Content Security Policy
Two places define the CSP and both must match:
- `web/config/securityHeaders.ts` (the prescription and the Vite dev/preview headers) - changed in this feature.
- The ASF CMS host's security header options (set by the CMS session `AndreaSlopFotografie`) - requested from them, not edited here.
Planned additions (provisional; Friendly Captcha v2 with the bundled `@friendlycaptcha/sdk`). The official CSP guide (developer.friendlycaptcha.com/docs/v2/guides/csp) says the widget uses iframes and needs at least `frame-src https://*.frcapi.com`; it names no other directive. Bryan decides exact origin versus wildcard and the host (EU recommended, `eu.frcapi.com`; the EU endpoint needs a Friendly Captcha Advanced or Enterprise plan, to be checked by Bryan). Everything marked "test" is added only if a real-browser test proves it necessary; no wildcards beyond what Bryan accepts.
| Directive | Now | Add |
|---|---|---|
| frame-src | not set (falls back to default-src) | the exact origin of the chosen host (`https://eu.frcapi.com` or `https://global.frcapi.com`), or `https://*.frcapi.com` if Bryan accepts the wildcard the docs name |
| connect-src | `'self'` + Umami + Sentry | test: the chosen host origin (the SDK fetches from its API endpoint) |
| script-src | `'self'` + Umami | nothing planned (SDK bundled, first-party chunk); test: `'wasm-unsafe-eval'` only if the SDK needs WebAssembly |
| worker-src | not set | test: `blob:` only if the SDK needs it |
Rules: add only what a real-browser test proves necessary (except the documented frame-src); each added entry gets a comment with the reason; the existing test `securityHeaders` gets assertions for the exact directives; no `unsafe-eval`, no wildcard hosts. The captcha script chunk is first-party, so `script-src 'self'` still holds.
## 3. Dev proxy
`vite.config.ts` `server.proxy`: `/api` to `http://192.168.1.2:5290` (the temporary environment) for local development, configurable through an env variable (default off in CI). Production and preview have no proxy. The dev CSP `connect-src` stays `'self' ws:` plus the above; the proxy keeps requests same-origin in the browser.
## 4. Build and delivery
- New code is in the lazy ContactForm chunk and a separate captcha chunk; pages without a form in view load no new JS (Lighthouse budgets in `lighthouserc.cjs` must stay green; a measurement is part of Build and Test).
- `web/src/cms-client/` is plain TypeScript/React inside the existing build. ESLint `no-restricted-imports` and the boundary test copy over with the package.
- `siteContent.contactForm.enabled` stays `false` in the merge; Bryan switches it on after the server is ready and he gives the explicit go.
- The CI pipeline is unchanged (unit, e2e, lint, Lighthouse); the CMS-check mode of deploy-test is unchanged.
## 5. Configuration and secrets
No secrets in the client. The captcha `siteKey` is public and arrives in the token response, so there is no new build-time variable. Server settings (`Contact__RecipientEmail`, `Contact:Enabled`, `MinSeconds`, retention, `ForwardedHeaders:KnownProxies`/`ClientPartitionKey`, `Email:AllowedFromAddresses`) belong to the CMS sessions and are requested through SLP Software - SLS - Main.
## 6. Observability
Events `contact-sent` and `contact-failed` through the existing analytics wrapper; nothing else, no field values, no tokens. Sentry captures unexpected exceptions without breadcrumbs from form fields (existing scrubbing configuration is checked in Build and Test).
## 7. Rollback and go-live
- Rollback: set `siteContent.contactForm.enabled = false` and redeploy; the gate returns and no token request is made. The server can also close the form (`Contact:Enabled` off gives 404, which keeps the gate).
- Go-live needs: server module deployed on the ASF host, recipient and sender configured, captcha configured (or off), Bryan's explicit go.
## 8. Dependencies on other sessions
| Item | Owner |
|---|---|
| Package captcha slot (branch and commit) | SLP Software - SLS - Main |
| Server contact module, captcha verifier, openapi for ASF | SLS Software - CMS |
| ASF host config (CSP options, recipient, proxies, Contact:Enabled) | AndreaSlopFotografie (via SLS-Main) |
| ASF test host with the endpoint | after Bryan merges the CMS branch (not requested yet) |
@@ -0,0 +1,31 @@
# Code generation plan: contact-form (unit 1, web)
Status: DRAFT for approval by SLP Software - SLS - Main (on behalf of Bryan). No code until approved. All paths under `web/` in the worktree `AndreaSlopFotografie-contact-form`, branch `feature/contact-form-cms`. Nothing is pushed or merged without Bryan.
Order matters: steps 1-2 can start with the current package (without captcha); the final package (captcha slot and `initialSubject`) is copied in step 9 after SLS-Main's message, and steps 10-12 need it.
## 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.
- [ ] **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.
- [ ] **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.
## Not in this plan
- Server module, verifier, openapi, ASF host configuration (other sessions).
- Switching `siteContent.contactForm.enabled` to true, push, merge, deploy (Bryan).
- Real-browser CSP verification and manual run against the temporary environment: Build and Test stage.
## Traceability
FR-CF-01 -> 1, 9; FR-CF-02 -> 6, 7; FR-CF-03 -> 3, 6; FR-CF-04/05 -> 4, 5; FR-CF-06/07 -> 6; FR-CF-08 -> 5, 11; FR-CF-09 -> 10; FR-CF-10 -> 12; FR-CF-11 -> 8; FR-CF-12 -> 6; NFR-CF-01 -> 8, 10; NFR-CF-02 -> 4, 10 (lazy chunks); NFR-CF-03 -> 3, 4, 6, 10, 13.