Contactformulier: cms-client (validatie, reducer, client, hook), formulier in stijl B en beschikbaarheid

Headless pakket src/cms-client met importgrens, formulier dat pas verschijnt als de API antwoordt
(anders blijft de mailto-knop), honeypot, idempotentie, token-vernieuwing en property-based tests.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 13:13:24 +01:00
co-authored by Claude Sonnet 5.5
parent 9661b64635
commit aa843a5675
45 changed files with 2609 additions and 22 deletions
@@ -0,0 +1,30 @@
# Code Summary — contact-form (U4)
## What was built
- **Movable package `src/cms-client/`** (no imports from the app; ESLint `no-restricted-imports` plus a boundary test): `http/` (`apiUrl`, `fetchJson` with 10 s timeout, problem+json parsing), `contact/` (`validateContact`, `contactFormReducer`, `createContactClient`, `messages.nl`, `useContactForm`, types), `README.md`.
- **Validation** equal to the API (trim; 100/254/100/2000; email regex; control characters rejected except line breaks in the message; first failing rule per field). **Reducer**: `sent` only leaves through `reset`; edits and a second submit are ignored while `sending`; input is kept on `failed`.
- **Client**: `getToken` (200 → token, 404 → closed, anything else → failed, malformed body → failed) and `submit` (202 ok; 400 → field errors or token expired; 413; 404; 429 with `Retry-After`; 5xx/network → failed). Never throws, never logs.
- **Hook `useContactForm`**: prop getters with ids from `idPrefix`, `aria-invalid`/`aria-describedby`, honeypot props (silent success without a request when filled), one idempotency key per attempt series (reused on retry, renewed after success/reset), a single automatic token refresh on `expired`, preselect with change counter (unknown values ignored), focus on the first invalid field after the render, telemetry only through `onEvent('sent' | 'failed')`.
- **UI**: `ContactPanel` (mailto panel by default, upgrades to the form when `GET …/token` answers 200 without captcha; min height 280px), `MailtoPanel`, `ContactFormView` (design B: panel colours, underline inputs on `bg-field`, brand submit button, errors outside the labels, `role=alert` failure with the mail address, `role=status` success with focus, privacy sentence), hidden honeypot field. `useContactAvailability` starts the token request when the section nears the viewport (IntersectionObserver, `rootMargin 300px`), or on first focus without IntersectionObserver. Subject options = offerings (slug/title) + "Overig". `trackEvent('contact-sent' | 'contact-failed')` without data.
- **Tokens**: new `--color-danger` (error text) in all four sets, contrast-tested against `panel` and `field`.
- **Dependencies**: `fast-check` (dev) for property-based tests; no runtime dependency.
## Verification (Step 13.5, real output)
- Before this unit (after U3): 14 files / 154 tests. After: **19 files / 239 tests passed**; `pnpm lint` 0 errors (same 2 existing warnings, boundary rule active); `pnpm build` OK (JS 466 kB, CSS 58.8 kB).
- Found and fixed by the tests: (1) field errors inside the `<label>` polluted the accessible name of the input → errors now sit outside the label; (2) focus after server field errors did not move because inputs are disabled while sending → focus is applied after the render.
- New tests: validation examples and properties (trim invariance, inclusive limits, control characters, known codes), reducer examples and properties (absorbing `sent`, ignored edits while sending, values kept on failure), client against a contract-following mocked `fetch` (all status mappings, timeout, serialization and problem-parsing round trips), boundary, availability (200/404/500/429/captcha/malformed/network, once only, first-focus fallback), full UI flows (success with body/headers, validation + focus, blur errors, honeypot, server field errors, token refresh with same key, 413/429 minutes, failure + retry with same key, double submit, reset with new key, preselect, no PII in console/analytics).
## Notes and deviations
- **Mail address** is not assembled after mount (BR-U4-10): the address is already present as a literal in the section (visible mailto link) and the site is a client-rendered SPA, so the extra step would add nothing; kept simple.
- **No end-to-end test** against the real API is possible yet: the contact routes exist only on the unmerged CMS branch and answer 404 in production until released and switched on, which keeps the mailto panel (by design).
- `style-src 'unsafe-inline'` / headers: see the infrastructure design (Operations list).
## Enabling end to end later (checklist)
1. CMS branch rebased/merged and deployed; per-client rate limiting active on the API host.
2. `Contact:Enabled=true` on the host; then the CMS switch (`PUT /api/v1/contact-settings` or the Berichten screen).
3. Confirm the header/CSP setup of the delivering web server (SECURITY-04) and `connect-src 'self'`.
4. Check on the test environment first: token 200 → form appears; submit → message in the CMS.
## Hand-offs
- U5: build `ContactFormTerminal` on `useContactForm` (same options); reuse `ContactPanel` logic (availability) for the 1989 terminal; texts are injectable via `messages`.
- CMS: type generation from `openapi/slpsoftware.v1.json` and moving `src/cms-client` into SlpModularCms are follow-ups.
@@ -0,0 +1,43 @@
# Business Logic Model — contact-form (U4)
## Module layout (movable package)
`src/cms-client/` is self-contained (an ESLint `no-restricted-imports` rule forbids imports from outside it):
- `http/` — `apiUrl`, `parseProblem`, `ApiError`.
- `contact/` — `validateContact`, `contactFormReducer` + types, `messages.nl`, `createContactClient` (`getToken`, `submit`), `useContactForm`.
- `index.ts` per subpath (`@/cms-client/contact`, later `/offerings`) so a site imports only what it uses.
## Submission sequence
```mermaid
sequenceDiagram
box rgba(99,179,237,0.4) Browser
participant V as Visitor
participant H as useContactForm
participant C as contact client
end
box rgba(154,230,180,0.4) CMS API
participant A as contact-messages
end
H->>C: get token when section nears viewport
C->>A: GET token
A-->>C: 200 token and minSeconds
V->>H: fill fields and submit
H->>H: validate and honeypot check
H->>C: submit with token and idempotency key
C->>A: POST contact-messages
A-->>C: 202 received
C-->>H: ok
H-->>V: success state
```
Text alternative: the hook obtains a token via the client, validates on submit, posts with the token and an idempotency key and shows the success state after a 202.
## Pure units (unit- and property-tested)
- `validateContact(values) -> errors`: trimming, boundaries 100/254/100/2000 inclusive, control characters, email regex.
- `contactFormReducer(state, event)`: events `change`, `blur`, `submit`, `sending`, `succeeded`, `failed`, `fieldErrors`, `reset`, `preselect`; invariants: `sent` never reverts except `reset`; input kept on `failed`; edits ignored while `sending`.
- `mapApiErrors(problem) -> { fields, token, generic }` and `retryAfterMinutes(headerValue)`.
- Request/response serialization round trips (payload shape, problem+json parsing) — property-based (PBT partial per the extension decision).
## Integration of the pieces
- `ContactSection` (U2 frame) renders `ContactPanel`: availability `unknown/closed` → mailto panel; `open` → `ContactFormView` (B skin) using `useContactForm`.
- Subject options come from `usePackagesQuery` + "Overig"; `useContactPreselect` (U3) drives `preselect`.
- Umami events via the existing analytics component's API (no data), Sentry untouched except documented non-logging.
@@ -0,0 +1,66 @@
# Business Rules — contact-form (U4)
| Id | Rule |
|---|---|
| BR-U4-1 | **Fixed fields**: name, email, subject, message, all required (no builder, no phone, no "aanvraag/vraag" switch). |
| BR-U4-2 | **Progressive enhancement**: the contact panel starts as the mailto call-to-action (as in U2). When the contact section comes near the viewport the client fetches the token (`GET /api/v1/contact-messages/token`). `200` and no captcha → the panel switches to the form; `404`, any other status, network error, or `captcha != null` (no widget implemented in this repo) → the mailto panel stays. There is no build-time flag: the server (host switch + CMS switch) decides. |
| BR-U4-3 | **Token**: one token per page view, fetched once when the section nears the viewport (IntersectionObserver with fallback to the first focus where unavailable); not on page load, not in static HTML. On `errors.token = ["expired"]` one fresh token is fetched and the submit is repeated once automatically; a second failure shows the generic failure message. |
| BR-U4-4 | **Validation** is the same pure function on the client and (by contract) on the server: first failing rule per field wins (required, then length, then format). Errors appear on blur of a touched field or on submit and disappear as soon as the field is valid; on a stopped submit the focus moves to the first invalid field. The form uses `noValidate` and shows its own messages. |
| BR-U4-5 | **States**: `editing → sending → sent | failed`. While `sending`, edits and a second submit are ignored. `sent` never reverts (except an explicit "Nog een bericht sturen" reset). `failed` keeps all input and offers retry; the failure message includes the mail address (assembled after mount, see BR-U4-10). |
| BR-U4-6 | **Idempotency**: one UUID per attempt series, reused when the visitor retries after `failed` until success, renewed after success/reset. Sent as `Idempotency-Key`. |
| BR-U4-7 | **Honeypot**: a visually hidden field (off-screen, `aria-hidden`, `tabindex=-1`, `autocomplete=off`, implausible DOM name) sent as `hpCheck`. If it is filled the client does not call the API but shows the normal success state (silent drop); the server repeats the check. The server-signed token replaces any client time check (no `Date.now` needed). |
| BR-U4-8 | **Responses**: `202` → success state. `400` with `errors` → map codes to messages per field (and `token` as above); unknown codes → generic failure. `413` → "Je bericht is te groot." `429` → message with the minutes from `Retry-After` (rounded up, min 1). `404/5xx/network` → generic failure with the mailto fallback address. No automatic retry other than the token case. |
| BR-U4-9 | **Preselect**: when the contact preselect `key` changes (package CTA from U3), the subject is set to its `subject` if that value exists in the subject options; unknown values are ignored. A later manual choice stays until the next click (key change). |
| BR-U4-10 | **Mailto fallback**: the address is assembled in the browser after mount from `contactInfo` parts, not as a literal in prerendered HTML (the site is a SPA, so this is defence in depth); the existing mailto button and the visible address of the section stay. |
| BR-U4-11 | **Subject options**: the packages from the offerings query (value = `slug`, label = `title`, in API order, banner packages included) plus "Overig" (`other`); first option is a disabled placeholder "Kies een onderwerp". While offerings load or fail, only "Overig" is available. |
| BR-U4-12 | **Privacy**: below the submit button the sentence "Je gegevens gebruik ik alleen om op je bericht te reageren; ik bewaar ze maximaal 12 maanden." (no checkbox, no link). |
| BR-U4-13 | **Success**: the form is replaced by "Bedankt!" with "Je bericht is verstuurd. Je hoort binnen één werkdag van me." (role=status, focus moves to it) and a button "Nog een bericht sturen" that resets to an empty form with a new idempotency key. |
| BR-U4-14 | **Privacy of telemetry**: no field values or the API token/idempotency key are logged, sent to Sentry (breadcrumbs, extra context) or Umami; the only analytics events are `contact-sent` and `contact-failed` without data. Errors reported to Sentry carry no request/response bodies. |
| BR-U4-15 | **Accessibility**: real `<label>`s, errors linked with `aria-describedby` and `aria-invalid`, `role=alert` on the failure message, `role=status` + focus on success, visible focus, touch targets ≥ 44px, no animation dependency, honeypot invisible to assistive technology. |
| BR-U4-16 | **Headless boundary**: all logic (reducer, validation, hook, client) lives in `src/cms-client/` without imports from the app; the B skin (markup/classes) lives in the landing feature. Texts are injectable with Dutch defaults. |
## Decision flow: availability
```mermaid
graph TD
S([Contact section near viewport]) --> T[GET token]
T --> R{Status 200}
R -->|"no"| M[Keep mailto panel]
R -->|"yes"| C{Captcha required}
C -->|"yes"| M
C -->|"no"| F[Show form]
classDef start fill:#CE93D8,stroke:#6A1B9A,color:#000;
classDef decision fill:#FFF59D,stroke:#F57F17,color:#000;
classDef step fill:#63b3ed,stroke:#2b6cb0,color:#000;
class S start;
class R,C decision;
class T,M,F step;
```
Text alternative: when the section nears the viewport the token is requested; only a 200 without captcha shows the form, otherwise the mailto panel stays.
## Decision flow: submit
```mermaid
graph TD
A([Submit]) --> B{Sending already}
B -->|"yes"| X[Ignore]
B -->|"no"| V{Valid}
V -->|"no"| E[Show errors and focus first]
V -->|"yes"| H{Honeypot filled}
H -->|"yes"| OK[Show success without call]
H -->|"no"| P[POST with idempotency key]
P --> S{Result}
S -->|"202"| OK
S -->|"token expired"| T[Fetch token and repeat once]
S -->|"400 fields"| E
S -->|"429 or other"| FL[Failed with message and mailto]
classDef start fill:#CE93D8,stroke:#6A1B9A,color:#000;
classDef decision fill:#FFF59D,stroke:#F57F17,color:#000;
classDef step fill:#63b3ed,stroke:#2b6cb0,color:#000;
classDef bad fill:#ffab91,stroke:#bf360c,color:#000;
class A start;
class B,V,H,S decision;
class X,E,P,T,OK step;
class FL bad;
```
Text alternative: a submit is ignored while sending, validated, dropped silently if the honeypot is filled, otherwise posted; success, an expired token (one retry), field errors or a failure result.
@@ -0,0 +1,46 @@
# Domain Entities — contact-form (U4)
```mermaid
graph TD
CF[ContactFields] -->|"validated by"| VAL[validateContact]
VAL -->|"produces"| ERR[FieldErrors code per field]
CF -->|"sent with"| TOK[ContactToken]
CF -->|"sent with"| IDK[Idempotency key]
TOK -->|"from"| API1[GET token]
CF -->|"posted to"| API2[POST contact-messages]
ST[FormState] -->|"holds"| CF
ST -->|"holds"| ERR
ST -->|"status"| STA[editing sending sent failed]
PRE[ContactPreselect] -->|"subject"| CF
AV[Availability] -->|"open closed"| ST
classDef data fill:#63b3ed,stroke:#2b6cb0,color:#000;
classDef logic fill:#9ae6b4,stroke:#2f855a,color:#000;
classDef ext fill:#f6e05e,stroke:#c05621,color:#000;
class CF,ERR,ST,STA,PRE,AV data;
class VAL logic;
class TOK,IDK,API1,API2 ext;
```
Text alternative: the fields are validated into per-field error codes; submission needs a server token and an idempotency key and posts to the API; the form state holds fields, errors and status; the package preselect fills the subject; availability decides whether the form is shown at all.
## ContactFields
| Field | Type | Rules (same as the API) |
|---|---|---|
| `name` | string | trimmed, 1–100, no control characters |
| `email` | string | trimmed, 1–254, `^[^\s@]+@[^\s@]+\.[^\s@]{2,}$`, no control characters |
| `subject` | string | opaque value from the site's options (package slug or `other`), 1–100 |
| `message` | string | trimmed, 1–2000, control characters rejected except line breaks and tabs |
Payload to the API: the four fields (trimmed) + `hpCheck` (always `""` unless a bot filled the honeypot) + `token` + optional `captchaToken`.
## Error codes and messages
Codes `required | tooLong | invalid | expired`. Messages per field and code (Dutch, equal to the ASF texts where they exist): name required "Vul je naam in.", tooLong "De naam is te lang."; email required "Vul je e-mailadres in.", tooLong "Het e-mailadres is te lang.", invalid "Dit e-mailadres is ongeldig."; subject required "Kies een onderwerp."; message required "Schrijf hier je vraag.", tooLong "Het bericht is te lang.". Other texts: rate limit "Je hebt net al een bericht gestuurd. Probeer het over {minuten} minuten opnieuw.", too large "Je bericht is te groot.", server/network "Versturen lukte niet. Probeer het later nog eens of mail naar {adres}.", token expired is retried silently once.
## FormState
`status: 'editing' | 'sending' | 'sent' | 'failed'`; `values`; `touched` (per field); `errors` (shown); `attemptKey` (Idempotency-Key, one UUID per attempt series; kept on retry, renewed after success or reset).
## Availability
`unknown` (default, shows the mailto panel) → `open` (token received) | `closed` (404 on the token route, network error, captcha required or any other non-200) → mailto panel stays.
## ContactToken
`{ token, minSeconds, captcha: null | { provider, siteKey } }`; fetched lazily as described in BR-U4-3.
@@ -0,0 +1,58 @@
# Frontend Components — contact-form (U4)
## Component hierarchy
```mermaid
graph TD
cs[ContactSection] --> cp[ContactPanel]
cp --> ma[MailtoPanel]
cp --> fv[ContactFormView]
fv --> fld[Field components]
fv --> hp[Honeypot]
fv --> pn[PrivacyNote]
fv --> sm[StatusMessages]
cp -.uses.-> av[useContactAvailability]
fv -.uses.-> uf[useContactForm]
uf -.uses.-> cl[createContactClient]
cp -.uses.-> pre[useContactPreselect]
cp -.uses.-> pq[usePackagesQuery]
cl --> api[(contact-messages API)]
classDef page fill:#2196F3,stroke:#0d47a1,color:#000;
classDef ui fill:#4CAF50,stroke:#2e7d32,color:#000;
classDef hook fill:#9C27B0,stroke:#4a148c,color:#000;
classDef ext fill:#F44336,stroke:#b71c1c,color:#000;
class cs page;
class cp,ma,fv,fld,hp,pn,sm ui;
class av,uf,cl,pre,pq hook;
class api ext;
```
Text alternative: the contact section shows a panel that is either the mailto panel or the form; the form uses the headless hook and client, the preselect context and the offerings for subject options.
## Components and hooks
| Unit | Props / state |
|---|---|
| `ContactPanel` | decides between `MailtoPanel` and `ContactFormView` from `useContactAvailability`; keeps `data-testid="contact-panel"` |
| `MailtoPanel` | the U2 content (mailto button) with address assembled after mount |
| `ContactFormView` | `subjectOptions`, `preselect`, `token source`; renders fields, honeypot, privacy sentence, submit button "Verstuur", status messages; B skin (panel colours, underline inputs on `bg-field`, brand submit button) |
| `useContactAvailability(sectionRef)` | `'unknown' \| 'open' \| 'closed'` plus the token; IntersectionObserver trigger; never fetches during server/test render without observer support (falls back to first focus) |
| `useContactForm(options)` (headless) | per `component-methods.md`: values, errors, status, `getFieldProps`, `honeypot`, `formProps`, `retry`, `reset`, `focusFirstError`; options `idPrefix`, `subjectOptions`, `preselect`, `getToken`, `submit`, `messages`, `fallbackAddress` |
| `createContactClient` | `getToken()`, `submit(payload, ctx)`; injectable `fetch`; uses `apiUrl()` |
## User interaction flows
- Section scrolls near → token → form appears (or stays mailto). Fill → blur errors → submit → success or failure (with retry and mailto address).
- Package CTA → preselect → subject set, scroll to contact.
## Form validation rules
BR-U4-4 (same codes and limits as the API).
## API integration points
`GET /api/v1/contact-messages/token`, `POST /api/v1/contact-messages` (headers `Idempotency-Key`), offerings query for subject options.
## Acceptance tests
1. Validation table and property tests; reducer invariants; serialization round trips (PBT).
2. Availability: 200 → form; 404/500/network/captcha → mailto panel; no fetch before the section nears the viewport.
3. Submit success (202), honeypot silent success without call, 400 field errors mapped, token expired → one refetch and repeat, 413, 429 with minutes, 5xx/network failure keeps input, retry reuses the idempotency key, reset renews it.
4. Preselect fills the subject; unknown value ignored; second click with the same package re-applies.
5. Accessibility: labels, `aria-invalid`/`aria-describedby`, focus on first error, `role=alert`, `role=status` + focus on success, honeypot hidden from AT, 44px targets.
6. No PII in console/Sentry/Umami calls (spy) during a full flow.
7. Boundary: lint rule forbids imports from `src/cms-client` to the app (rule test).
@@ -0,0 +1,29 @@
# Infrastructure Design — contact-form (U4)
The frontend introduces **no new infrastructure**. The form needs only the same-origin API prefix that the offerings call already uses.
## Confirmed
- The example nginx configs in `aidlc-docs/features/react-frontend/operations/deployment/nginx/` only show `/` to the web server and `/sentry-tunnel`; they contain **no `/api/v1/` location and no security-header directives**. That repository documentation may be outdated compared with the real Pi configuration.
- The user: SLP Software already has an API that does not have to move.
- The session "CMS & API" (2026-11-10): the release going to production now contains **no** contact routes; they arrive with the contact feature and are switched on in production only after Bryan's go.
## Confirmed later the same day (via "CMS & API", from Pi-Main and the CMS code at 2818b74)
- The SLP .NET apps listen on Pi-Main: **test `:5100`, production `:5101`** (0.0.0.0, ufw only allows 192.168.1.102, the proxy Pi "Pi-Entry"). TLS ends on Pi-Entry; the app sees `http` with `Host: test.slpsoftware.nl` / `slpsoftware.nl`.
- Pi-Main's journal shows requests under both `/api/v1` and `/` reaching the same .NET app, so `/api/v1/` evidently reaches the app on test; the real Pi-Entry config is not visible to the AI sessions.
- Pi-Main's nginx sets **no security headers** for the SLP sites (only `Cache-Control: public` on static assets). The **CMS host sets them itself** (`SecurityHeadersMiddleware`, options `SecurityHeaders`: Enabled, DefaultPolicy Relaxed, PathPolicies with `/admin`, `/api/v1`, `/health` = Strict, AllowedScriptOrigins, AllowedConnectOrigins; CSP definitions in code; `TryAdd`, so headers set earlier by nginx win). Pi-Entry may set headers too (unknown).
- `Api.SlpSoftware` serves `/` only as SPA fallback from `wwwroot/web` when present (WebsiteMode SpaFallback); only the Andrea host runs PrerenderedPages.
## Still unconfirmed (do not treat as fact)
- Which application delivers the public pages of slpsoftware.nl today (the CMS `wwwroot/web` fallback or a separate static web server) and therefore which header policy applies to the HTML of this site; the site CSP below applies to that delivering server (for the CMS host: `SecurityHeaders:DefaultPolicy` and `AllowedScriptOrigins`/`AllowedConnectOrigins` must allow the Umami host).
- The Pi-Entry configuration (routing of `/api/v1/` vs `/`, headers).
To be confirmed by the user; the form itself only needs `connect-src 'self'` because `/api/v1` is on the same host.
## Required configuration (for deployment / Operations list)
1. **Reverse proxy**: `/api/v1/` must be forwarded as a prefix to the existing SLP API (no new route if that is already the case), preserving `Host`, `X-Forwarded-For`, `X-Forwarded-Proto`; request body limit of at least 32 KB; no response caching for `/api/v1/offerings` and `/api/v1/contact-messages*`. The API needs the real client IP for per-client rate limiting (`ForwardedHeaders:KnownProxies` on the API host).
2. **Security headers (SECURITY-04)** on HTML responses, if not present yet: `Content-Security-Policy` (e.g. `default-src 'self'; script-src 'self' <umami-host>; connect-src 'self' <umami-host>; img-src 'self' data:; style-src 'self' 'unsafe-inline'; font-src 'self'; frame-ancestors 'none'`), `Strict-Transport-Security: max-age=31536000; includeSubDomains`, `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: strict-origin-when-cross-origin`. The form itself needs only `connect-src 'self'`; fonts are self-hosted; `/theme-init.js` is same-origin. `style-src 'unsafe-inline'` is needed for inline style attributes (progress bars) and is an accepted, documented exception until those are replaced.
3. **Environment**: no new variables. `VITE_API_BASE_URL` stays a local-development override only.
4. **Switches**: the form appears only when the CMS host switch `Contact:Enabled` and the CMS switch are both on (token route answers 200); enabling is an Operations step after per-client rate limiting is on the API host.
5. **Observability**: Umami events `contact-sent` / `contact-failed` (no data); Sentry without bodies; reverse-proxy access logging is an Operations item (SECURITY-02).
## Security Baseline — Infrastructure scope
SECURITY-04: **open until confirmed** (unknown whether the real servers set the headers; the repository examples do not). Tracked for Operations (still undecided) and flagged to the user. SECURITY-07: only 80/443 exposed by the reverse proxy; the API upstream stays internal. Other rules N/A for this unit.
@@ -0,0 +1,23 @@
# Logical Components — contact-form (U4)
```mermaid
graph TD
UI[ContactFormView and ContactPanel] --> HOOK[useContactForm]
UI --> AVAIL[useContactAvailability]
HOOK --> PURE[validateContact reducer mapApiErrors]
HOOK --> CLIENT[createContactClient]
AVAIL --> CLIENT
CLIENT --> HTTP[http apiUrl fetch with timeout]
HTTP --> API[(CMS API same origin)]
HOOK --> TELE[analytics events without data]
classDef ui fill:#2196F3,stroke:#0d47a1,color:#000;
classDef core fill:#4CAF50,stroke:#2e7d32,color:#000;
classDef io fill:#9C27B0,stroke:#4a148c,color:#000;
classDef ext fill:#F44336,stroke:#b71c1c,color:#000;
class UI ui;
class HOOK,AVAIL,PURE core;
class CLIENT,HTTP,TELE io;
class API ext;
```
Text alternative: the UI uses the headless hook and the availability hook; both rely on the pure core and the client; the client uses the http helper with a timeout towards the same-origin API; telemetry carries no data.
@@ -0,0 +1,20 @@
# NFR Design Patterns — contact-form (U4)
| Pattern | Where | Purpose |
|---|---|---|
| Progressive enhancement | `ContactPanel` + `useContactAvailability` | form only when the API answers 200; mailto otherwise |
| Fail closed to a safe fallback | client/hook | any unexpected response or error ends in the failure state with the mail address |
| Idempotent retry | hook + `Idempotency-Key` | a retry never creates a second message |
| Pure core / thin shell | `validateContact`, reducer, `mapApiErrors` | testable without DOM or network (PBT) |
| Honeypot + server token | hook + API | bots learn nothing; no client clock |
| Request timeout | client | `AbortController` 10 s so the UI never hangs in `sending` |
| Data minimisation in telemetry | analytics calls | events without data; no values in logs |
| Single token refresh | client | `expired` handled once, then generic failure (no loops) |
| Layout reservation | `ContactPanel` | minimum height keeps the page stable when upgrading from mailto to form |
## Misuse / abuse scenarios considered
1. A bot fills every field including the honeypot: silent success on the client, the server drops or stores it as spam.
2. Rapid repeated submits (double click, flaky network): ignored while `sending`; same idempotency key on retry.
3. Visitor tampers with the token: the API answers `expired`; one refresh, then failure.
4. Very large input pasted: client length errors; the API answers 413, message "Je bericht is te groot."
5. API unavailable or deliberately closed (switches): the form never appears or falls back to mailto; no console spam.
@@ -0,0 +1,31 @@
# NFR Requirements — contact-form (U4)
| Id | Category | Requirement |
|---|---|---|
| NFR-U4-1 | Security / input | Client-side validation mirrors the API limits (100/254/100/2000, control characters, email regex); the API is authoritative. All API strings are rendered as plain text (no `dangerouslySetInnerHTML`). |
| NFR-U4-2 | Security / abuse | Honeypot, server-signed token (no client clock), idempotency key; no external captcha provider is loaded (captcha required => mailto fallback). The client never retries automatically except the single token refresh. |
| NFR-U4-3 | Privacy | No form values, token, idempotency key or response bodies in console output, Sentry (events, breadcrumbs, extra) or Umami. Only `contact-sent` / `contact-failed` events without data. Privacy sentence below the form (12 months). |
| NFR-U4-4 | Availability / resilience | The form is progressive: if the API is closed, slow or failing, the mailto panel stays. A failed submit keeps the visitor's input and offers retry plus the mail address. Token and submit requests abort after 10 s. |
| NFR-U4-5 | Performance | No request on page load; the token request starts when the contact section nears the viewport. The form code is part of the main bundle (small); no new runtime dependencies. No layout shift when the panel is upgraded (the panel keeps its minimum height). |
| NFR-U4-6 | Accessibility | WCAG 2.1 AA: labels, error association, focus handling, live regions, 44px targets, contrast (tokens already tested), no motion dependency. |
| NFR-U4-7 | Maintainability | `src/cms-client/` has no imports from the app (lint-enforced) and is documented as the future package; texts injectable; Dutch defaults. |
| NFR-U4-8 | Testability | Pure functions and the reducer are property/round-trip tested (partial PBT); the client is tested against a mocked `fetch` that follows the contract; the hook against the client interface. |
| NFR-U4-9 | Compatibility | Works with hash routing, static hosting and the same-origin API path `/api/v1/...`; `VITE_API_BASE_URL` stays a local-development override only. |
## Security Baseline compliance (extension enabled) — U4 scope
| Rule | Status | Note |
|---|---|---|
| SECURITY-01 | N/A | the frontend stores nothing; message storage and encryption belong to the CMS |
| SECURITY-02 | N/A | no load balancer/gateway defined in this unit (reverse-proxy logging is an Operations item) |
| SECURITY-03 | Compliant | no values/tokens/PII logged; no ad-hoc logging in the form code |
| SECURITY-04 | Open (Infrastructure) | security headers must be set by the web servers, not by the SPA; whether they are set today is **unconfirmed** (see infrastructure-design.md); must be confirmed or fixed before the contact routes go live |
| SECURITY-05 | Compliant (client side) | validation with allow-list regex and bounds, plain-text rendering; server validation by the API |
| SECURITY-06/07 | N/A | no IAM/network resources in this unit |
| SECURITY-08 | Compliant | only public endpoints are called (explicit public marker on the API); no admin calls from this site |
| SECURITY-09 | Compliant | generic error messages; no stack traces to visitors |
| SECURITY-10 | Compliant | no new runtime dependencies; lock file committed (dev dependency fast-check for tests only) |
| SECURITY-11 | Compliant | API rate limiting, honeypot/token/idempotency; misuse cases in nfr-design-patterns.md |
| SECURITY-12 | N/A | no authentication in this unit |
| SECURITY-13 | Compliant | JSON only with typed parsing; no new external scripts |
| SECURITY-14 | N/A (Operations) | alerting belongs to the Operations phase (undecided) |
| SECURITY-15 | Compliant | every external call has error handling; failure ends in the mailto fallback; global ErrorBoundary exists |
@@ -0,0 +1,7 @@
# Tech Stack Decisions — contact-form (U4)
- **No new runtime dependencies.** Plain `fetch` with `AbortController`, `crypto.randomUUID()` for the idempotency key (fallback to a `getRandomValues` based UUID where unavailable), React hooks/reducer.
- **Forms**: no form library; the headless hook owns state and validation (reusable by other sites).
- **Tests**: Vitest + Testing Library; `fast-check` as a **dev** dependency for the partial property-based testing (validation, reducer invariants, serialization round trips): vetted npm package, lock file committed, no runtime impact, respecting the repo's release-age policy (stop and report if blocked).
- **API types**: hand-written minimal types now; generated from the CMS file `openapi/slpsoftware.v1.json` is a follow-up when `cms-client` moves to SlpModularCms.
- **Boundary enforcement**: ESLint `no-restricted-imports` on `src/cms-client/**` (no imports from the app folders).