Aanbod: RESTful routes zonder /admin, één OfferingDto en herordenen via PUT /offerings/order

Admin en bezoeker gebruiken dezelfde resource; alleen GET is anoniem, de rest vereist AdminOnly. OfferingAdminDto vervalt (displayOrder zit nu in OfferingDto), move-up/move-down zijn vervangen door de order-route die een onbekende of onvolledige lijst met 400 afwijst. De admin-frontend en alle tests zijn mee aangepast.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-10 13:06:08 +01:00
co-authored by Claude Sonnet 5.5
parent e6710781e5
commit bc763c8ef6
39 changed files with 968 additions and 395 deletions
@@ -0,0 +1,65 @@
# Application Design (minimal) — contact-forms-module
Scope: component names, boundaries, configuration keys, and the few design points the contract leaves open. Behaviour and field-level detail stay in contract v0.3.1.
## 1. Repo findings that shape the design (master `d9cc539`)
- Modules are `IModule` classes discovered via the host's project references (`orchestrator.DiscoverModules()`); a host gets a module by a `ProjectReference` in its `.csproj`. Phase 1 registers Contact in `Api.SlpSoftware` only; `Api.AndreaSlopFotografie` does not exist on master and gets the reference after the ASF merge (Phase 2).
- **Data Protection is already host-level**: `AddCmsDataProtection()` (CmsHost) persists keys in the database (`ApplicationDbContext`) with a fixed application discriminator. Contact therefore does **not** own a key ring; it only asks `IDataProtectionProvider` for a protector with a per-site purpose string. (This replaces the plan wording "keyring in own DbContext".)
- Controller convention: `[Route("offerings")]` under the global `/api/v1` prefix, class-level `[Authorize(Policy = "AdminOnly")]`, public actions `[AllowAnonymous]` + `[EnableRateLimiting("<policy>")]`, admin actions under `offerings/admin`. Existing public limiter policy: `offerings-public`.
- `/System/capabilities` lists `ModuleOrchestrator.ModuleNames`: a module named `Contact` appears automatically.
- `AvailabilityMiddleware` is prefix-bypass based, with verified-admin-token bypass. Existing admin routes are **not** under a common `/api/v1/admin/` prefix (they are `.../admin` suffixes or controllers such as `Users`).
## 2. Deviation to confirm (admin route shape)
Contract § 6 writes `/api/v1/admin/contact-messages`. Repo convention is `contact-messages/admin...` (as `offerings/admin`). **Proposal**: follow the repo convention: `GET /api/v1/contact-messages/admin`, `GET .../admin/{id}`, `PATCH .../admin/{id}`, `DELETE .../admin/{id}`, `POST .../admin/{id}/resend`. The 503-regression test then iterates over all endpoints without `[PublicSiteEndpoint]` instead of relying on a prefix. Redesign - SLS to update the contract (or veto).
## 3. Components
| Component | Project | Responsibility |
|---|---|---|
| `PublicSiteEndpointAttribute` | Core (`Availability`) | marker, `AttributeTargets.Method`; read via endpoint metadata |
| Availability check | Modules.Availability `AvailabilityMiddleware` | minimal change: after the prefix bypass, `context.GetEndpoint()?.Metadata.GetMetadata<PublicSiteEndpointAttribute>()` != null => `next` (deny-by-default otherwise) |
| 429 handling | Core `AddCmsRateLimiting` `OnRejected` | set `Retry-After` (from `MetadataName.RetryAfter` when available, else window), write `application/problem+json`; keep the security-event call |
| Offering category | Modules.Offerings | `Offering.Category` (nullable, max 100), DTOs/requests, `ICategoryOptions` (reads `Offerings:Categories`), validation in service |
| `ContactModule` | Modules.Contact | `IModule` "Contact"; registers DbContext (MySQL, same pattern), services, hosted services; `Migrate()` in `UseModule` |
| `ContactDbContext` | Modules.Contact | `ContactMessages`, `IdempotencyRecords` |
| `ContactMessagesController` | Modules.Contact | public token + submit (`[PublicSiteEndpoint]`, `[AllowAnonymous]`, limiter policies); admin actions `AdminOnly` (U4) |
| `ContactSubmissionService` | Modules.Contact | validate, classify (genuine/spam), idempotency, store, trigger mail |
| `ContactValidator` | Modules.Contact | pure function: input => `{field: [codes]}`; shared rules (trim, length, regex, control chars) |
| `ContactTokenService` | Modules.Contact | issue/verify via `IDataProtector` (purpose `SlpModularCms.Contact.Token.{siteId}`), `ITimeProvider`; verify result: valid / tooYoung / expired-or-invalid |
| `ICaptchaVerifier` (+`NullCaptchaVerifier`, later Friendly Captcha impl) | Modules.Contact | fail-open on provider failure, log without PII |
| `IContactMailSender` (+`NoOpContactMailSender`) | Modules.Contact | seam for mail; real implementation in Phase 2 (CMS-U5) |
| `ContactRetentionService` | Modules.Contact | daily `BackgroundService`: delete rows past `retentionUntil` and idempotency records > 24 h |
| `ContactSiteOptions` | Modules.Contact | `Contact:*` binding (validated on start; recipient/sender not required until mail is wired) |
| Log scrubbing | Core Observability | extra rule in `SecurityEventProcessor`/Sentry `BeforeSend` for the contact routes |
## 4. Configuration keys
| Key | Default | Notes |
|---|---|---|
| `Offerings:Categories` | `[]` | per host; empty list => category must be null |
| `Contact:SiteId` | host name | derived from host config, never from the request; used in the token purpose and stored on rows |
| `Contact:MinSeconds` | 3 | |
| `Contact:TokenLifetimeMinutes` | 120 | |
| `Contact:RetentionMonths` | 12 | per row at insert |
| `Contact:SpamRetentionDays` | 30 | |
| `Contact:MaxSpamRowsPerDay` | 200 | cap per site per day, then 202 without storing |
| `Contact:MaxBodyBytes` | 16384 | |
| `Contact:HoneypotField` | `hpCheck` | |
| `Contact:RecipientEmail`, `Contact:SenderEmail` | none | env-only for ASF; not committed (Phase 2) |
| `Contact:Captcha:Enabled/Provider/SiteKey/Secret` | false | secret via env/secrets |
| `RateLimiting:ContactForm` | 5 / 600 s | per client IP |
| `RateLimiting:ContactToken` | 20 / 600 s | per client IP |
| `RateLimiting:ContactResend` | 5 / 600 s | admin resend |
## 5. Data
- `ContactMessage`: `Id` (Guid), `SiteId`, `ReceivedAt`, `Name`, `Email`, `Subject`, `Message`, `Status` (`New|Read|Archived|Spam|Converted`), `MailStatus` (`Pending|Sent|Failed|NotApplicable`), `MailError` (code only), `MailAttempts`, `NextMailAttemptAt`, `RetentionUntil`. Indexes: `(SiteId, Status, ReceivedAt)`, `RetentionUntil`. No IP.
- `IdempotencyRecord`: `Key` (Guid), `SiteId`, `CreatedAt`, `StatusCode`; unique index `(SiteId, Key)`. No request content.
- `Offering.Category`: `varchar(100)` NULL.
## 6. OpenAPI export
- Committed file `openapi/cms-api.v1.json` in the repo root. A test builds the document from the SlpSoftware host (`AddOpenApi`) and compares it to the file; set `UPDATE_OPENAPI=1` to rewrite it. Drift fails the build, so `cms-client` always generates from a current file.
- The contract's response components (`Validation`, `TooLarge`, `RateLimited`, `Problem`) are declared through an `IOpenApiDocumentTransformer` so the exported shape matches contract § 8.
## 7. Cross-cutting decisions
- Identical 202 for genuine and spam: same code path up to the store step; spam differs only by `Status=Spam` and `RetentionUntil=+30d`, and never triggers mail.
- Invalid/forged/other-site/expired token => `errors.token = ["expired"]`; too-young token => silent spam path.
- Logging: only status code, site id and outcome enum for these routes; request logging for them is disabled; a test asserts that a thrown exception's log entry holds no body or field value.
- Security Baseline is checked at each stage (anonymous endpoint, input limits, no oracle, secrets only via env, generic 5xx, headers).
@@ -0,0 +1,34 @@
# Units of Work — contact-forms-module
Naming: CMS-U1..CMS-U6 (the SLS frontend plan has its own U1..U5). One feature branch `feature/contact-forms-module`, one commit minimum per unit, sequential. Each unit: Code Generation plan => approval by Redesign - SLS => code + tests + automatic build/test => status.
| Unit | Name | Phase | Depends on | New/changed projects | Migration |
|---|---|---|---|---|---|
| CMS-U1 | offerings-category | 1 | none | Modules.Offerings (+Tests) | `AddOfferingCategory` (Offerings context) |
| CMS-U2 | gate-and-limiter | 1 | none (marks offerings GET from U1's controller) | Core, Modules.Availability (+Tests), Core.Tests/Api.Tests | none |
| CMS-U3 | contact-core | 1 | U2 | NEW Modules.Contact, NEW Modules.Contact.Tests, Api.SlpSoftware (reference), solution file | `InitialCreate` (Contact context) |
| CMS-U4 | contact-admin-api | 1 | U3 | Modules.Contact (+Tests) | none (maybe an index) |
| CMS-U5 | contact-mail | 2 | ASF merge + rebase; U3, U4 | Modules.Contact, Core/Email use (new `MailKind`), Api.AndreaSlopFotografie reference | `AddContactMailFields` only if not already in InitialCreate (preferred: fields exist from U3) |
| CMS-U6 | admin-ui | 2 | ASF merge + rebase; U4 | `frontend/` (new files + menu entry) | none |
## Per-unit boundaries (what is NOT touched)
- **U1**: no Core, no Availability, no Email; only Offerings files and its migration/tests.
- **U2**: only `AddCmsRateLimiting`/`OnRejected` in Core, the marker attribute file, and `AvailabilityMiddleware` (minimal diff); no policy numbers changed; no Email, Identity, host config.
- **U3**: no changes to existing modules except the `.csproj` reference in Api.SlpSoftware, the `.sln`, and appsettings sample keys; no Core/Email; no Identity.
- **U4**: only Modules.Contact.
- **U5/U6**: after merge; Email code of the ASF session is used, never edited (new `MailKind` only).
## Test projects
- `SlpModularCms.Modules.Contact.Tests` mirrors the module (xUnit as the other test projects). Solution layout: module under Application/Modules, tests under Tests/Modules (per CLAUDE.md).
- PBT (partial): validator and token round-trips, using the repo's available property-testing library if present, otherwise parameterised generators; decided in Functional Design of U3.
## Order and gates
U1 -> U2 -> U3 -> U4 (each approved before start). After Bryan merges the ASF branch: rebase, regenerate migrations only if snapshots conflict, then U5 -> U6.
## Revision 2026-11-09 (Bryan via Redesign - SLS)
- New **CMS-U0 offerings-restful-routes** (Phase 1, first): no `/admin` segments; plan in `construction/plans/cms-u0-...`.
- **CMS-U1 offerings-category** revised: categories are CMS data (table + FK + CRUD routes), no `Offerings:Categories` config, no seeding.
- New **CMS-U1b offerings-categories-ui**: categories sub-section + select in OfferingForm (after U1).
- Availability `POST admin/status` -> `PUT /availability/status`: Phase 2 (after the ASF merge), new unit **CMS-U7 availability-restful-status**.
- Admin routes of Contact follow the RESTful scheme (no `/admin`): `GET/PATCH/DELETE /contact-messages[/{id:guid}]`, `POST /contact-messages/{id:guid}/resend`. Application-design § 2 is superseded accordingly.
- Order: U0 -> U1 -> U1b -> U2 -> U3 -> U4 | merge | U5 -> U6 -> U7.
@@ -0,0 +1,137 @@
# Execution Plan — contact-forms-module
## Detailed Analysis Summary
### Transformation Scope
- **Transformation Type**: Multiple components (new module + targeted changes in existing ones). No infrastructure/deployment model change.
- **Primary Changes**: new `Modules.Contact` (+ Tests); `category` on `Modules.Offerings`; `OnRejected` and a public-route marker in Core/Availability; later mail integration (Core/Email) and admin UI (frontend).
- **Related Components**: Core (rate limiting, hosting, observability), Modules.Availability (middleware), Modules.Offerings, Api.SlpSoftware (+ Api.AndreaSlopFotografie after the ASF merge), frontend (admin).
### Change Impact Assessment
- **User-facing changes**: Yes: public contact endpoints (consumed by `cms-client`), admin "Berichten" screen (unit 6).
- **Structural changes**: Yes: one new module, one new marker attribute in Core.
- **Data model changes**: Yes: new tables (`ContactMessage`, idempotency record, DataProtection key ring), new `Offering.Category` column. All additive.
- **API changes**: Yes: new endpoints + `category` on offerings; 429 body/header change on existing rate-limited endpoints.
- **NFR impact**: Yes: security baseline (anonymous PII endpoint), privacy (retention, logging), reliability (mail retry).
### Component Relationships
```mermaid
flowchart LR
FE["cms-client (SLP site)"] --> API["Api.SlpSoftware / Api.AndreaSlopFotografie"]
API --> CONTACT["Modules.Contact (NEW)"]
API --> OFF["Modules.Offerings (+category)"]
API --> AVAIL["Modules.Availability (middleware)"]
CONTACT --> CORE["Core (marker, rate limiter, observability)"]
AVAIL --> CORE
CONTACT -. "after ASF merge" .-> MAIL["Core/Email (ASF branch)"]
ADMIN["frontend admin: Berichten"] -. "after ASF merge" .-> CONTACT
classDef new fill:#9ae6b4,stroke:#2f855a,color:#000;
classDef changed fill:#f6e05e,stroke:#c05621,color:#000;
classDef ext fill:#bee3f8,stroke:#2b6cb0,color:#000;
classDef later fill:#e2e8f0,stroke:#4a5568,stroke-dasharray: 5 5,color:#000;
class CONTACT new;
class OFF,AVAIL,CORE,API changed;
class FE ext;
class MAIL,ADMIN later;
```
Text alternative: the Contact module (new, green) hangs off the API hosts and uses Core; Offerings, Availability, Core and the hosts change (yellow); mail and the admin UI (grey, dashed) wait for the ASF merge.
### Risk Assessment
- **Risk Level**: Medium (anonymous endpoint with PII; shared files with the ASF session).
- **Rollback Complexity**: Easy to Moderate (additive migrations; new module can be left unregistered per host).
- **Testing Complexity**: Moderate (gate regression, rate limiter behaviour, token/idempotency, background jobs).
## Workflow Visualization
```mermaid
flowchart TD
Start(["Request via Redesign - SLS"])
subgraph INCEPTION["🔵 INCEPTION"]
WD["Workspace Detection<br/><b>COMPLETED</b>"]
RE["Reverse Engineering<br/><b>SKIP (targeted review)</b>"]
RA["Requirements Analysis<br/><b>COMPLETED</b>"]
US["User Stories<br/><b>SKIP</b>"]
WP["Workflow Planning<br/><b>IN PROGRESS</b>"]
AD["Application Design<br/><b>EXECUTE (minimal)</b>"]
UG["Units Generation<br/><b>EXECUTE</b>"]
end
subgraph CONSTRUCTION["🟢 CONSTRUCTION (per unit)"]
FD["Functional Design<br/><b>EXECUTE (U3, U4, U5)</b>"]
NFR["NFR Requirements + Design<br/><b>EXECUTE (U2, U3)</b>"]
ID["Infrastructure Design<br/><b>SKIP (config noted in design)</b>"]
CG["Code Generation<br/><b>EXECUTE</b>"]
BT["Build and Test<br/><b>EXECUTE</b>"]
end
OPS["Operations<br/><b>UNDECIDED (at Build and Test)</b>"]
Start --> WD --> RA --> WP --> AD --> UG --> FD --> NFR --> CG --> BT --> OPS
style WD fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
style RA fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
style WP fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
style CG fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
style BT fill:#4CAF50,stroke:#1B5E20,stroke-width:3px,color:#fff
style AD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000
style UG fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000
style FD fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000
style NFR fill:#FFA726,stroke:#E65100,stroke-width:3px,stroke-dasharray: 5 5,color:#000
style RE fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000
style US fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000
style ID fill:#BDBDBD,stroke:#424242,stroke-width:2px,stroke-dasharray: 5 5,color:#000
style OPS fill:#FFF59D,stroke:#F9A825,stroke-width:2px,stroke-dasharray: 5 5,color:#000
style Start fill:#CE93D8,stroke:#6A1B9A,stroke-width:3px,color:#000
linkStyle default stroke:#333,stroke-width:2px
```
Text alternative: Inception runs Application Design and Units Generation, then each unit goes through design (where needed), Code Generation and Build and Test; Operations is undecided.
## Phases to Execute
### 🔵 INCEPTION
- [x] Workspace Detection (COMPLETED)
- [x] Reverse Engineering (SKIPPED by D10: targeted review recorded in requirements)
- [x] Requirements Analysis (COMPLETED, approved by Redesign - SLS)
- [x] User Stories (SKIPPED: contract-driven backend work; acceptance criteria live in the contract and the SLS requirements FR-13..19)
- [ ] Workflow Planning (IN PROGRESS)
- [ ] Application Design - EXECUTE (minimal depth)
- **Rationale**: new module, new Core marker attribute; must fix component/service names, config keys (`Offerings:Categories`, `Contact:*`, `RateLimiting:ContactForm`), OpenAPI export path, DataProtection key-ring storage, purpose strings.
- [ ] Units Generation - EXECUTE
- **Rationale**: six units with an ordering constraint and a split at the ASF merge.
### 🟢 CONSTRUCTION
- [ ] Functional Design - EXECUTE for U3, U4, U5 (validation rules, state/status machine, idempotency, spam cap, retry/backoff); SKIP for U1, U2, U6 (covered by contract/design)
- [ ] NFR Requirements + NFR Design - EXECUTE for U2 and U3 (security baseline: PII logging, token oracle, size limits, rate limiting); SKIP for the others (covered by baseline checks in code generation)
- [ ] Infrastructure Design - SKIP (no new infrastructure; key-ring storage and config keys are recorded in Application Design)
- [ ] Code Generation - EXECUTE per unit (plan approved by Redesign - SLS before any code); automatic build+test per unit
- [ ] Build and Test - EXECUTE (after U1-U4, again after U5-U6)
### 🟡 OPERATIONS
- [ ] UNDECIDED: resolved at Build and Test (D7)
## Units (execution order)
Phase 1: now, on the master base. Phase 2: only after Bryan merges `feature/identity-email-notifications` and the branch is rebased (not before; no rebase now).
| Unit | Scope | Delivers | Tests | Depends on |
|---|---|---|---|---|
| **U1 offerings-category** (a) | `Category` on Offering entity, public + admin DTOs, create/update requests; validation against `Offerings:Categories` (per host appsettings); null/empty allowed | additive migration `AddOfferingCategory` in Offerings; config key documented; handoff note for the frontend (field name and semantics) | Offerings.Tests: mapping, validation (in list / not in list / null), repository; migration builds | none |
| **U2 gate-and-limiter** (b) | `OnRejected`: `429 application/problem+json` + `Retry-After` for all policies; `[PublicSiteEndpoint]` marker in Core; `AvailabilityMiddleware` lets marked endpoints through (deny-by-default); mark `GET /api/v1/offerings`. Minimal diffs in these two files (R3) | marker attribute, middleware check, updated 429 response, security-event kept | Core.Tests/Api.Tests: 429 body + header for existing policies (adjust existing tests); Availability.Tests: marked route open while disabled/maintenance/master-down; **every `/api/v1/admin/*` route still 503**; `/api/v1/Availability/status` open; ~6-10 existing tests touched | none (U1 for the offerings route mark) |
| **U3 contact-core** (c) | new `Modules.Contact` (+Tests): entities `ContactMessage`, `IdempotencyRecord`; DbContext + migration; token endpoint (DataProtection, per-site purpose, persistent key ring in DB); submit endpoint (validation codes, 413 ProblemDetails, `Idempotency-Key`, honeypot `hpCheck`, min-time, `ICaptchaVerifier` + Null, identical 202, spam stored with daily cap and 30-day retention, site id from config); `ContactForm` rate-limit policies; both routes `[PublicSiteEndpoint]`; `IContactMailSender` interface with no-op implementation (mail is wired in U5); retention `BackgroundService`; log/Sentry scrubbing for the routes | module registered in Api.SlpSoftware (Andrea host later), additive migration `InitialCreate`, config section `Contact:*`, exported OpenAPI document (path fixed in design) | Contact.Tests: validation rules incl. PBT (partial: round-trips, trim/length invariants), token sign/verify/expiry/foreign-site, idempotency replay, spam paths identical response, spam cap, retention job, no-PII-in-log test, endpoint tests via WebApplicationFactory | U2 |
| **U4 contact-admin-api** (e) | AdminOnly endpoints: list (paging, unread count, spam separate), detail, PATCH status (new/read/archived), DELETE (hard), `POST resend` (rate-limited; calls `IContactMailSender`, so a no-op until U5); capabilities entry is automatic from the module name | admin controller + DTOs, OpenAPI updated | Contact.Tests: authorization (non-admin 403/401), paging, counts exclude spam, status transitions, hard delete, resend rate-limit | U3 |
| **U5 contact-mail** (d) | PHASE 2. Implement `IContactMailSender` on `Core/Email` with a **new `MailKind`**, dark-mode contrast kept; From/Reply-To rules, header-injection and HTML-encoding protections; `mailStatus`/`mailAttempts`; `BackgroundService` sweeping `pending` (minutes) and retrying `failed` with backoff/max attempts; "no SMTP host = store only + admin notice" | mail path + retry job; Andrea host registration via env-only addresses | Contact.Tests: sender with fake `IEmailSender`, retry/backoff, header injection, encoding, failure never fails the request | merge of ASF branch + rebase; U3, U4 |
| **U6 admin-ui** (f) | PHASE 2. "Berichten" in `frontend/`: list+paging+unread count, detail, status, delete, mail status + resend; menu entry via capabilities; only new files + menu entry | UI + tests | frontend unit tests (Vitest as in repo) | merge of ASF branch + rebase; U4 |
## Migration Approach
- Contact and Offerings have their **own DbContext and migration history**, applied with `Database.Migrate()` at startup (D8). All migrations are additive (new tables, one nullable column).
- ASF changes live in `Core/Migrations` and the Identity/Availability contexts, so snapshot conflicts with U1/U3 are not expected. If the rebase still produces conflicts in any snapshot, delete and regenerate my own migration after the rebase (R2).
- DataProtection key ring: table owned by the Contact module's context (persistent per host; per-site purpose string).
## Branch and Process
- Worktree `..\SlpModularCms-contact-forms`, branch `feature/contact-forms-module` from master `d9cc539`. The main checkout is never switched.
- One commit per unit minimum; no push, merge or PR without explicit instruction. Per unit: Code Generation plan -> approval by Redesign - SLS -> code + automatic build+test -> status message.
- Stage status reports to Redesign - SLS after each stage; contract deviations reported immediately.
## Estimated Timeline
- **Total units**: 6 (4 now, 2 after the ASF merge). Rough effort: U1 small, U2 small-medium, U3 large, U4 medium, U5 medium, U6 medium. No calendar estimate (depends on approval turnaround and the ASF merge).
## Success Criteria
- **Primary Goal**: contract v0.3.1 implemented on the CMS side without breaking ASF-owned behaviour.
- **Key Deliverables**: category on offerings; public contact endpoints; admin API; mail + retry; admin UI; exported OpenAPI.
- **Quality Gates**: per-unit build+test green; Security Baseline checked per stage; no PII in logs (tested); `/api/v1/admin/*` stays gated (tested); no ASF addresses in committed config.
@@ -0,0 +1,77 @@
# Requirements Verification Questions — contact-forms-module
Input: contact-api-contract v0.3.1-draft (decisions by Bryan are not asked again). Only repo-specific or still-open points below. Answers may be given by "Redesign - SLS" (within Bryan's decisions) or by Bryan.
## Question 1: Security Extensions
Should security extension rules be enforced for this feature?
- A) Yes — enforce all SECURITY rules as blocking constraints (recommended: public anonymous endpoint, PII, mail)
- B) No — skip all SECURITY rules
- X) Other (please describe after [Answer]: tag below)
[Answer]: A (Security Baseline enabled, per Bryan for the whole work) - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 2: Property-Based Testing Extension
Should property-based testing rules be enforced?
- A) Yes — all PBT rules
- B) Partial — only pure functions and serialization round-trips (validation rules, token/idempotency logic)
- C) No — skip all PBT rules
- X) Other (please describe after [Answer]: tag below)
[Answer]: B (partial: pure functions and serialization round-trips) - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 3: Operations phase
Should the Operations phase (deployment/monitoring/readiness) run for this feature? (Deployment already exists via the Gitea workflow.)
- A) No — closes after Build and Test; deployment follows existing workflow
- B) Yes — run the Operations phase
- C) Not sure yet — decide at Build and Test
- X) Other (please describe after [Answer]: tag below)
[Answer]: C (decide at Build and Test) - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 4: Module layout
Where does the new module live?
- A) New projects `SlpModularCms.Modules.Contact` + `SlpModularCms.Modules.Contact.Tests` (own DbContext + migration, like Offerings), referenced by Api.SlpSoftware and Api.AndreaSlopFotografie (recommended)
- B) Inside Modules.Offerings
- X) Other (please describe after [Answer]: tag below)
[Answer]: A - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 5: Database and migrations per host
Offerings uses MySQL with `Database.Migrate()` at startup. For the Contact module:
- A) Same approach: own DbContext, MySQL, additive migration applied at startup; migration regenerated after the rebase on identity-email-notifications (recommended)
- B) Reuse an existing DbContext (e.g. Core)
- X) Other (please describe after [Answer]: tag below)
[Answer]: A (migration regenerated after rebase) - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 6: Availability gate marker
Peer advice (ASF session): a `[PublicSiteEndpoint]` marker attribute in Core, read via endpoint metadata in `AvailabilityMiddleware`, deny-by-default, admin routes never exempt, `/api/v1/Availability/status` stays open. Own unit together with (b).
- A) Marker attribute (recommended)
- B) Prefix list next to the existing bypass list
- X) Other (please describe after [Answer]: tag below)
[Answer]: A ([PublicSiteEndpoint] marker, deny-by-default) - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 7: Reverse engineering
The `_shared/reverse-engineering` artifacts date from July 2026 (before Offerings, SlpSoftware and ASF hosts).
- A) Skip a full rerun; do a targeted review of the touched areas (Offerings, Email, rate limiter, Availability, capabilities, SecurityEvents) and record findings in the requirements (recommended)
- B) Full rerun
- X) Other (please describe after [Answer]: tag below)
[Answer]: A (targeted review; new MailKind, existing mail code untouched) - answered by Redesign - SLS (technical lead) 2026-11-09
## Question 8: Admin UI scope
Unit (f) admin UI ("Berichten") is in the existing React admin (`frontend/`). The ASF session is still changing auth/refresh, users and theme assets there.
- A) Build (f) last, on the rebased branch after their merge, only touching new files plus the menu entry (recommended)
- B) Build it in parallel on the current base
- X) Other (please describe after [Answer]: tag below)
[Answer]: A (admin UI last, after ASF merge; report if the merge takes too long) - answered by Redesign - SLS (technical lead) 2026-11-09
@@ -0,0 +1,60 @@
# Requirements — contact-forms-module
## 1. Intent Analysis
- **Request**: Build the CMS/API side of the contact form and related contract items: (a) `category` on Offerings, (b) rate-limit `Retry-After` + own ProblemDetails, public-route marker for the availability gate, (c) Contact module (token + submit), (d) mail + retry, (e) admin API, (f) admin UI "Berichten".
- **Source of truth**: `contact-api-contract.md` v0.3.1-draft (in the SlpSoftware repo, feature `redesign-modern-timetravel`). This document does not restate its field-level detail; it records scope, decisions, repo findings and deviations. Where they disagree, the contract wins unless listed under § 6.
- **Type**: New feature (multi-component). **Scope**: multiple components. **Complexity**: Complex. **Depth**: Standard (decisions already made by Bryan / technical lead).
- **Coordination**: stages approved by "Redesign - SLS" (leads the build; Bryan's permission runs through it).
## 2. Decisions (all recorded, not re-asked)
| # | Decision | Source |
|---|---|---|
| D1 | Admin "Berichten" view in scope, full version (list+paging+unread count, detail, status new/read/archived, delete, mail status + resend; AdminOnly; capabilities entry) | Bryan |
| D2 | Honeypot/too-fast submissions stored as `spam` (30 days, never mailed, per-site daily cap, outside unread count and default list), visitor sees normal 202 | Bryan |
| D3 | Captcha disabled by default; provider failure = fail-open | Bryan |
| D4 | Category list = fixed list per site in appsettings; admin only picks from it (no free text) | Bryan |
| D5 | Retention 12 months (per row, fixed at insert), daily cleanup job | Bryan |
| D6 | Availability gate blocks only CMS/admin routes; public routes stay open; deny-by-default; admin routes never exempt | Bryan |
| D7 | Security Baseline extension **enabled**; Property-Based Testing **partial** (pure functions + serialization round-trips: validation rules, token/idempotency logic); Operations phase **undecided** (decide at Build and Test) | Bryan via Redesign - SLS |
| D8 | New projects `SlpModularCms.Modules.Contact` + `.Contact.Tests`; own DbContext, MySQL, `Database.Migrate()` at startup, additive migration (like Offerings); migration regenerated after rebase | Redesign - SLS |
| D9 | Availability marker attribute `[PublicSiteEndpoint]` in Core, read from endpoint metadata in `AvailabilityMiddleware`; own unit together with (b); test that every `/api/v1/admin/*` route still returns 503; `/api/v1/Availability/status` stays open | Redesign - SLS |
| D10 | No full reverse-engineering rerun; targeted review (§ 3). Contact mail = **new `MailKind`**, existing mail code untouched, keep dark-mode contrast | Redesign - SLS |
| D11 | Admin UI (f) last, on rebased branch after the ASF merge, only new files + menu entry; report to SLS if the merge takes long | Redesign - SLS |
| D12 | No push/merge/PR; no ASF addresses in code/committed config (env-only); no PII in logs; no deploy to production | Bryan / SLS |
## 3. Targeted review findings (master `d9cc539`)
- **Module pattern**: `Modules.Offerings` = `IModule` (`RegisterServices` + `UseModule`), own `DbContext` (MySQL, `NonLockingMySQLHistoryRepository`), `Database.Migrate()` in `UseModule`. Contact follows this exactly.
- **Capabilities**: `SystemController` returns `ModuleOrchestrator.ModuleNames`; a registered module named "Contact" appears automatically. The frontend menu entry keys off it.
- **Availability**: `AvailabilityMiddleware` (Modules.Availability) blocks everything not on a prefix bypass list (`/api/v1/Availability/status`, `/Auth/`, `/Setup/status`, `/master/`, `/SlaveStatus`, `/health`) except verified Owner/Administrator tokens. The marker-attribute check slots in before the master/local gate.
- **Mail**: `Core/Email` (`IEmailSender`, `MailSendResult`, SMTP, templates) **does not exist on master**; it lives on the unmerged ASF branch `feature/identity-email-notifications`. `Api.AndreaSlopFotografie` is also not on master. Unit (d) therefore depends on that merge (or a rebase on their branch); see § 5.
- **Rate limiting**: `AddCmsRateLimiting` with named per-client policies; `OnRejected` currently logs a security event only (no body, no `Retry-After`). To be extended (unit b) for all policies, with existing tests adjusted. ForwardedHeaders/KnownProxies are env-configured (no code change).
- **Observability**: `SecurityEvents` / `SecurityEventProcessor` (Sentry): extra scrub rule for the contact routes; test that a logged exception holds no body.
- **Offerings**: has no `category` field; additive migration + DTO + admin DTO/requests + validation against the per-site configured list.
- **ASF-owned areas (do not touch without SLS)**: Email (MailTemplateRenderer, MailColours, EmailOptions, IdentityMailService), Identity, Core Hosting/Website/Proxy, Core migrations, frontend auth/users/theme. Expected rebase conflicts: appsettings, Program.cs/host config, AvailabilityMiddleware, EF snapshots.
## 4. Functional Requirements (summary; detail in contract)
- **FR-A Offerings category**: optional `category` string|null on offering (public + admin DTOs); value must be in the per-site configured list (`Offerings:Categories`); null/empty = no chip. Additive migration.
- **FR-B1 Rate limiter**: `OnRejected` writes `429 application/problem+json` with `Retry-After`; existing policies keep their numbers; new policy `ContactForm` (5/10 min per client IP, config `RateLimiting:ContactForm`) and token policy (20/10 min).
- **FR-B2 Gate**: `[PublicSiteEndpoint]` marker; applied to `GET /api/v1/offerings`, `GET /api/v1/contact-messages/token`, `POST /api/v1/contact-messages`.
- **FR-C Contact module**: `GET .../token` (DataProtection token, per-site purpose, persistent key ring); `POST .../contact-messages` with validation + error codes per contract § 3, own 413 ProblemDetails (16 KB), `Idempotency-Key` table (no PII), honeypot `hpCheck`, min-time, optional captcha behind `ICaptchaVerifier` (Null default, fail-open), identical 202, spam stored with daily cap, site id from host/config, retention fields.
- **FR-D Mail**: after commit, send via `IEmailSender` with a new `MailKind`; `From` fixed site sender (allow-list), `Reply-To` visitor, header-injection and HTML-encoding protections; `BackgroundService` sweeps `pending` frequently and retries `failed` with backoff and max attempts; no SMTP host = store only + admin notice.
- **FR-E Admin API**: `GET list/detail`, `PATCH status`, `DELETE` (hard), `POST resend` (rate-limited); AdminOnly; spam shown separately; unread count excludes spam.
- **FR-F Admin UI**: "Berichten" screen per D1 (last unit, after ASF merge).
- **FR-G Retention job**: daily deletion of rows past `retentionUntil` and idempotency records older than 24 h.
- **FR-H OpenAPI**: exported definitive OpenAPI document committed in the repo (path fixed in design) for `cms-client` type generation.
## 5. Non-Functional Requirements and risks
- **Security (baseline enabled)**: anonymous endpoint, so input validation, size limits, no oracle on token errors, no PII in logs/Sentry, secrets only via env/secrets manager, deny-by-default gate, generic 5xx, baseline rules checked at each stage.
- **Privacy**: IP not stored; retention per row; hard delete on erasure; privacy statement must mention backups and the captcha provider (site side).
- **Reliability**: mail failure never fails the request; at-least-once mail with attempt counter; idempotent submit.
- **Testability**: per-unit build + tests (xUnit); PBT partial per D7; `/admin/*` 503 regression test; token/validation round-trip tests.
- **Risk R1**: mail unit (d) depends on `Core/Email` being on the base branch. Options: wait for the ASF merge, or rebase the feature branch onto `feature/identity-email-notifications`. To be decided by SLS in the plan.
- **Risk R2**: EF migration snapshot conflicts after rebase; regenerate own migration (D8).
- **Risk R3**: `AvailabilityMiddleware` and rate-limiter edits overlap ASF-touched files; keep diffs minimal, coordinate via SLS.
## 6. Deviations / additions vs. contract v0.3.1
- None blocking. Additions: OpenAPI export path; `Offerings:Categories` config key name; Contact module named `Contact` (capabilities entry).
## 7. Open points for the plan stage (not blockers for requirements)
- Base for unit (d): wait for ASF merge vs. rebase now (R1).
- Exact config key names and OpenAPI export location (decide in Application Design).