AIDLC-documentatie U2 (NFR, infrastructuur, code generation)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-07 01:16:34 +01:00
co-authored by Claude Sonnet 5.5
parent 88f5d20a78
commit c69ef9188e
16 changed files with 628 additions and 3 deletions
@@ -5,7 +5,7 @@
- **Feature Slug**: andreaslop-site-hosting
- **Project Type**: Brownfield
- **Start Date**: 2026-11-06T00:06:13Z
- **Current Stage**: CONSTRUCTION - U1 complete; waiting for the requester go before U2
- **Current Stage**: CONSTRUCTION - U2 Code Generation (code complete, awaiting approval)
- **Branch**: feature/andreaslop-site-hosting
- **Request Type**: Feature (two units: U1 core-site-hosting, U2 andreaslop-client)
@@ -293,3 +293,115 @@
**Context**: Construction, U1 complete.
---
## U2 go received
**Timestamp**: 2026-11-06T14:20:00Z
**Input (CMS & API)**: "U1 hand-back accepted. Go for U2." Notes: run Api.Tests where MariaDB exists and report in handback-u2; observe forwarded headers/HTTP 1.0 on the first test deploy; measure file lookup on the Pi if cheap; U2 Infrastructure Design must end with the complete manual-steps list (both web-delivery variants) and I must tell them when complete. Boundaries unchanged: test only, no production, no push until Bryan asks.
**Context**: Construction, starting U2 andreaslop-client.
---
## U2 NFR Requirements - questions issued
**Timestamp**: 2026-11-06T14:50:00Z
**AI Response**: "U2 Functional Design skipped per execution plan. Created andreaslop-client-nfr-requirements-plan.md (5 questions: deploy trigger, pipeline structure, setup rate limiting, setup token on test, theme contrast). Waiting for Bryan."
**Context**: Construction, U2 NFR Requirements.
---
## U2 NFR Requirements - answers received and artifacts generated
**Timestamp**: 2026-11-06T15:10:00Z
**User Response**: Relayed by CMS and API: Q1 Zelfde als nu (auto test deploy on push to master plus manual box; must skip cleanly while Andrea is not set up), Q2 = A, Q3 = A, Q4 = A, Q5 = B (brand colours exactly, no contrast check; Bryan explicit choice, overrides brief hint).
**AI Response**: Generated nfr-requirements.md (skip-clean via variable ANDREA_TEST_DEPLOY_ENABLED, trade-off recorded) and tech-stack-decisions.md. Awaiting approval.
**Context**: Construction, U2 NFR Requirements.
---
## U2 NFR Requirements - approved
**Timestamp**: 2026-11-06T15:30:00Z
**User Response**: "ga verder"
**Status**: Approved. NFR Design artifacts generated without questions (category evaluation in the plan); awaiting approval.
**Context**: Construction, U2.
---
## U2 decision: proxy-aware rate limiting (option B)
**Timestamp**: 2026-11-06T16:00:00Z
**User Response**: "Ik wil het meteen goed opzetten. Als dat betekent dat de bestaande pipelines of omgevingen ook moeten worden aangepast is dat goed. Dus dan optie B, want dat is de meest volledige toch?"
**AI Response**: Added NFR-SEC-09..13, P11, P12, T10 to the U2 NFR documents. Shared Core change (touches Api, Api.SlpSoftware, Api.Slave) is opt-in via ForwardedHeaders:KnownProxies; limiters become per-client. Existing environments need the env var and proxy-Pi headers as manual steps. Awaiting approval of the updated NFR design.
**Context**: Construction, U2 NFR Design.
---
## U2 NFR Design - approved; Infrastructure Design questions issued
**Timestamp**: 2026-11-06T16:30:00Z
**User Response**: "Akkoord, ga verder"
**AI Response**: Created andreaslop-client-infrastructure-design-plan.md (3 questions: web delivery variant, first-deploy/health check sequence, Sentry). Waiting for Bryan.
**Context**: Construction, U2 Infrastructure Design.
---
## U2 Infrastructure Design - answers received (relayed)
**Timestamp**: 2026-11-06T17:00:00Z
**User Response**: Relayed by CMS and API: Q1 = A (symlink to /mnt/storage1/www/html/andreaslop-test), Q2 = A (switch proxy-Pi route first, then first deploy; downtime accepted; explicit order incl. nginx fallback revert), Q3 = B (reuse the website Sentry project/DSN).
**AI Response**: Checked Sentry: admin reports through the same-origin /sentry-tunnel (connect-src self suffices); tunnel target derives from the backend DSN. Generating infrastructure artifacts and the ordered manual-steps list.
---
## U2 Infrastructure Design - artifacts generated
**Timestamp**: 2026-11-06T17:20:00Z
**AI Response**: Generated infrastructure-design.md, deployment-architecture.md and manual-steps-for-bryan.md (18 ordered steps in phases A prepare, B cut over, C verify, plus rollback and optional existing-host steps). Awaiting approval; then CMS and API is told the list is final.
**Context**: Construction, U2 Infrastructure Design.
---
## U2 Infrastructure Design - naming convention applied
**Timestamp**: 2026-11-07
**User Input (relayed by "CMS & API")**: Company is "Andrea Slop Fotografie"; new names use AndreaSlopFotografie/ASF/Asf, never "Andrea"/"AndreaSlop" alone. Clarified: Sentry Q3=B is the ASF website's own Sentry project; Umami only in the website CSP.
**AI Response**: Renamed in all U2/inception docs: ANDREA_TEST_* -> ASF_TEST_*, VITE_SENTRY_DSN_ANDREA -> VITE_SENTRY_DSN_ASF, jobs publish/deploy-asf-test, theme folder themes/asf (VITE_THEME=asf). Convention and Sentry/Umami clarification recorded in infrastructure-design.md. Earlier audit entries keep their historical wording (append-only). Awaiting approval.
## U2 Infrastructure Design - approval
**Timestamp**: 2026-11-07
**User Input**: "Akkoord, ga verder"
**AI Response**: Infrastructure Design approved; manual-steps list FINAL. Peer notified. Code Generation plan written (`andreaslop-client-code-generation-plan.md`), awaiting approval.
## U2 Infrastructure Design - correction (proxy block)
**Timestamp**: 2026-11-07
**Input (peer "CMS & API")**: The live proxy-Pi block for test.andreaslop.nl already sets Host, X-Forwarded-For, X-Forwarded-Proto, X-Real-IP; only proxy_pass changes (http://192.168.1.103 -> :5200). Generator in website repo updated in U3.
**AI Response**: manual-steps step 11 reworded (verify headers, change target only); earlier statement was wrong.
## U2 Code Generation - plan approval
**Timestamp**: 2026-11-07
**User Input**: "Approve plan"
**AI Response**: Plan approved; starting Part A (Core forwarded headers + per-client limiters).
## U2 Code Generation - complete
**Timestamp**: 2026-11-07
**AI Response**: Parts A-F implemented (see construction/andreaslop-client/code/code-summary.md). Core 351, Identity 57, Availability 82, Master 57, Offerings 57, ASF host config 5, frontend 293 tests green; ESLint/tsc clean; Api.Tests and ASF host pipeline tests need MariaDB (not available locally, run in CI). U1 defect found by the property test (unencoded 301 Location) fixed with regression tests. No push, no deploy. Awaiting approval.
@@ -0,0 +1,37 @@
# Code Summary - andreaslop-client (U2)
Names follow the ASF convention (see `infrastructure-design.md`). Test environment only; nothing was pushed or deployed.
## Part A - Core: forwarded headers and per-client limiters (option B)
- `Core/Hosting/Proxy/ForwardedHeadersSettings.cs`: `ForwardedHeaders:KnownProxies`, `ParseKnownProxies` (unparsable entry and any-address `0.0.0.0`/`::` fail at startup).
- `ForwardedHeadersExtensions.cs`: `AddCmsForwardedHeaders` (XForwardedFor|XForwardedProto, ForwardLimit 1, default known proxies/networks cleared) and `UseCmsForwardedHeaders` (adds the middleware only when a proxy is configured). `CmsHost.ConfigurePipeline` calls it first after the database migration.
- `ClientPartitionKey.cs` + `AddCmsRateLimiting`: `login`, `refresh`, sentry-tunnel and `offerings-public` are now partitioned per client address (IPv4-mapped IPv6 normalised, fallback key `(unknown)`).
- Safe degradation: without `KnownProxies` the headers are ignored and every caller shares the proxy address, i.e. the old single bucket.
- Tests (`Core.Tests/Hosting/Proxy`): parsing, partition key (PBT: injective over addresses), TestServer pipeline (no proxy = headers ignored and shared bucket; trusted proxy = real address, scheme and separate buckets; untrusted peer cannot spoof; wildcard fails at startup).
## Part B - Identity: setup token
- `Modules.Identity/Setup`: `SetupOptions` (`Identity:Setup:Token`, whitespace-only = startup error via `ValidateOnStart`), `ISetupTokenValidator`/`SetupTokenValidator` (SHA-256 + `CryptographicOperations.FixedTimeEquals`).
- `SetupController`: `[EnableRateLimiting("login")]` on both endpoints; `POST owner` requires header `X-Setup-Token` when configured and answers an identical 401 for missing and wrong tokens; `GET status` returns `initialized` + `tokenRequired`.
- `SecurityEvents.SetupTokenRejected` (event id 5007, tag `setup_token_rejected`, added to `SecurityEventProcessor`); the presented token is never logged.
- Tests: validator (examples, PBT: only the exact token passes, never throws), controller (401 uniformity, no owner created, event logged without the token, header passed on), options validation, security-event tests extended to seven events.
## Part C - Client `SlpModularCms.Api.AndreaSlopFotografie`
- New project under Clients: Identity + Availability only (no Master, no Offerings; Availability kept because the admin reads its status). `CmsHostOptions { WebsiteMode = PrerenderedPages }`, `public partial class Program` for host tests.
- appsettings.json (no secrets; `SecurityHeaders:DefaultPolicy=StrictSite` + website Umami/Sentry origins for the site lists only, `Website:NoIndex=true`, empty `Identity:Setup:Token` and `ForwardedHeaders:KnownProxies`), appsettings.Development.json (own dev DB, CORS for `pnpm dev:asf`), launchSettings port 5200/7200. `appsettings.local.json` is optional and git-ignored like in the other clients.
- Tests project `Api.AndreaSlopFotografie.Tests` (solution folder Tests): `HostConfigurationTests` (5, no database) and `HostPipelineTests` (5, need MariaDB like `Api.Tests`; they run in CI `backend-test`, which starts MariaDB).
## Part D - Frontend
- `frontend/themes/asf/theme.css` (website palette exactly, Q5 = B; light and a derived dark variant; Marcellus/Jost self-hosted via `@fontsource/*@5.3.0`), `favicon.svg` (placeholder monogram, see hand-back), `none.css`, `resolveTheme.ts` (unknown theme = build error). `vite.config.ts`: alias `@theme`, favicon plugin. `main.tsx` imports `@theme`.
- `VITE_DEFAULT_LANGUAGE`: `parseDefaultLanguage`, `languageDetection` (stored choice > default > browser).
- Setup page: token field only when `tokenRequired`, header `X-Setup-Token`, `skipAuthRefresh` so a 401 does not trigger a session refresh; nl/en texts.
- Verified: default build unchanged (no theme CSS, no fonts), `VITE_THEME=asf` build contains the palette, 4 woff2 files, no `data:` fonts (admin CSP `font-src 'self'`), favicon link swapped; `VITE_THEME=nope` fails the build.
- Vitest 293 passed, ESLint and `tsc -b` clean.
## Part E - CI
- `continuous_integration.yaml` only gained the `deploy_asf_test` dispatch input and three jobs at the end (`config-asf`, `publish-asf-test`, `deploy-asf-test`), all gated by `vars.ASF_TEST_DEPLOY_ENABLED == 'true'`. Diff = additions only; `deploy-scp.yaml` unchanged.
## Defect found and fixed in U1 along the way
- `WebsitePathResolver` built the 301 `Location` from the decoded path without re-encoding (`/a%3Fb/` redirected to `/a?b`, `#` started a fragment, non-ASCII ended up raw in a header). Found by the existing property test (flaky 1 in ~15 runs); fixed with `PathString.ToUriComponent`, regression tests added, property test now models the browser (splits the Location, decodes the path).
## Not verified here
- `Api.Tests` and `Api.AndreaSlopFotografie.Tests/HostPipelineTests` need MariaDB (none on this machine); they run in CI. Behaviour behind the real proxy (forwarded headers, HTTP/1.0), `vars` in job-level `if:` on this Gitea, and the Pi timing are only observable on the first test deploy.
@@ -0,0 +1,50 @@
# Deployment Architecture - andreaslop-client (U2, test)
## Runtime topology
```mermaid
flowchart LR
V["Visitor / Andrea"] --> P["Proxy Pi 192.168.1.102 (TLS, certbot)"]
P -- "HTTP/1.0 + X-Forwarded-For/-Proto :5200" --> A["App Pi: ufw 5200 only from proxy"]
A --> H["andreaslopfotografie-test.service (.NET host)"]
H --> D[("MariaDB AndreaSlopFotografieTest")]
H --> W["shared/wwwroot-web -> /mnt/storage1/www/html/andreaslop-test"]
WS["Website repo deploy"] --> W
H -. "/sentry-tunnel" .-> S["Sentry (website project)"]
N["nginx on app Pi (fallback, old route)"]
classDef user fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
classDef net fill:#d6bcfa,stroke:#553c9a,stroke-width:1px,color:#000;
classDef app fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
classDef data fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
class V user;
class P,A,N net;
class H app;
class D,W,WS,S data;
```
Text alternative: visitors reach the proxy Pi, which forwards to the host on port 5200 with the client address in headers; the host reads the database and the website files (a symlinked folder that the website repo's own deploy writes), and forwards browser error reports to Sentry. The old nginx route remains as a fallback.
## Deploy sequence (CI, automatic on push to master or via the manual box, only when `ASF_TEST_DEPLOY_ENABLED=true`)
```mermaid
sequenceDiagram
box rgba(214,188,250,0.4) CI
participant G as Gitea runner
end
box rgba(99,179,237,0.4) App Pi
participant R as releases/ts
participant S as shared
participant U as systemd user unit
end
G->>G: build admin (VITE_THEME=asf, nl), publish linux-arm64
G->>R: scp release to releases/ts
G->>S: mkdir -p shared/wwwroot-web (symlink already exists)
G->>R: wwwroot/web -> ../../../shared/wwwroot-web
G->>U: ln -sfn current, restart unit
G->>G: curl https://test.andreaslop.nl/health (10 tries)
G->>R: prune to current + 1 previous
```
Text alternative: build, upload to a timestamped release, link the persistent website folder, switch `current` atomically, restart, check `/health` through the public URL, prune old releases.
## Rollback
`ln -sfn releases/<previous> current && systemctl --user restart andreaslopfotografie-test`; the previous release is always kept. Route rollback: restore the saved nginx block on the proxy Pi (see the manual steps).
@@ -0,0 +1,68 @@
# Infrastructure Design - andreaslop-client (U2, test environment only)
Status of the facts: the Pi details come from the Pi-Main inventory (unverified by this session) and are confirmed against `deploy-scp.yaml`. Items marked **(verify)** must be checked on the Pi by Bryan or the Pi-Main session before use. Production is out of scope.
## Naming convention (project decision, Bryan, relayed by "CMS & API")
The website/company is **Andrea Slop Fotografie**. New names in code, config and infrastructure use `AndreaSlopFotografie` / `andreaslopfotografie` / `andrea-slop-fotografie` or the abbreviation `ASF` / `Asf`, whichever fits the local convention (env vars and Gitea variables/secrets `ASF_...`, PascalCase identifiers `Asf...` or the full name). Never "Andrea" or "AndreaSlop" alone for NEW names. Existing names stay (domain `andreaslop.nl`, host `test.andreaslop.nl`, website repo, feature slug `andreaslop-site-hosting`, DB `AndreaSlopFotografieTest`, DB user `AndreaSlopFotografie`).
Final new names: Gitea variables `ASF_TEST_DEPLOY_ENABLED`, `DEPLOY_PATH_ASF_TEST`, `SERVICE_NAME_ASF_TEST`, `HEALTH_CHECK_URL_ASF_TEST`, `VITE_SENTRY_DSN_ASF`; jobs `publish-asf-test`, `deploy-asf-test`; theme folder `frontend/themes/asf/` with `VITE_THEME=asf`; project `SlpModularCms.Api.AndreaSlopFotografie`; Pi folder `apps/andreaslopfotografie/test`; unit `andreaslopfotografie-test.service`; env file `shared/env`; security-event label `setup_token_rejected` (generic, unchanged).
## Which Sentry project (Q3 = B)
The DSNs (`Observability__SentryDsn` and `VITE_SENTRY_DSN_ASF`) must come from the existing Sentry project of the **Andrea Slop Fotografie website**, NOT from SlpSoftware's admin project. The Umami origin (`analytics.slpsoftware.nl`) appears only in the website CSP (`StrictSite`); the host and admin set up no Umami.
## Component mapping
| Logical component | Infrastructure |
|---|---|
| `Api.AndreaSlopFotografie` host | One .NET process (linux-arm64, framework-dependent) as systemd **user** unit `andreaslopfotografie-test.service` of user `gitea-workflow`, listening on `http://0.0.0.0:5200` |
| Admin SPA (themed) | Built in CI, shipped inside the release (`wwwroot/admin`) |
| Website files | `wwwroot/web` -> `shared/wwwroot-web` -> symlink to `/mnt/storage1/www/html/andreaslop-test` (Q1 = A). The website repo's own deploy keeps writing there; no host restart needed. |
| Database | MariaDB 10.11 on the same Pi: database `AndreaSlopFotografieTest`, user `AndreaSlopFotografie`@`localhost`, rights on that database only (the host runs its own migrations at start) |
| TLS + public hostname | Proxy Pi (192.168.1.102): `test.andreaslop.nl` -> HTTP/1.0 -> app Pi port 5200; certbot stays on the proxy Pi |
| Firewall | ufw on the app Pi: port 5200/tcp only from 192.168.1.102 |
| Build + deploy | Gitea Actions: new jobs `publish-asf-test` (ubuntu-latest, `-r linux-arm64`) and `deploy-asf-test` (reuses `deploy-scp.yaml`, SSH as `gitea-workflow` with the existing `PI_MAIN_*` secrets) |
| Error reporting | Existing website Sentry project (Q3 = B) |
| Backups | Pi-Main adds `AndreaSlopFotografieTest` to the DB backup script |
## Pi layout (under the home of `gitea-workflow`, **(verify)** the absolute path)
```
apps/andreaslopfotografie/test/
releases/<yyyymmddHHMMSS>/ written by the deploy
current -> releases/<latest> switched atomically by the deploy
shared/
env mode 600, secrets, read by the unit
wwwroot-web -> /mnt/storage1/www/html/andreaslop-test
modules/ created by the deploy (empty)
```
## Environment file `shared/env` (names only; values are created by Bryan, never committed)
| Variable | Value / source |
|---|---|
| `ASPNETCORE_ENVIRONMENT` | `Production` |
| `ASPNETCORE_URLS` | `http://0.0.0.0:5200` |
| `ConnectionStrings__DefaultConnection` | `Server=localhost;Port=3306;Database=AndreaSlopFotografieTest;Uid=AndreaSlopFotografie;Pwd=<db password>` |
| `JwtSettings__Secret` | random, at least 64 characters |
| `Identity__Setup__Token` | random, at least 32 characters; remove after the first administrator exists |
| `Observability__SentryDsn` | the website's existing Sentry DSN (backend; the admin reports through the same-origin `/sentry-tunnel`) |
| `Observability__Environment` | `test` |
| `ForwardedHeaders__KnownProxies__0` | `192.168.1.102` |
| `Logging__LogLevel__SlpModularCms.Website` | `Information` (test only) |
Committed defaults (in the client's `appsettings.json`, no secrets): `SecurityHeaders` with `DefaultPolicy=StrictSite`, the site's Umami and Sentry origins, `Website:NoIndex=true` (secure default; a later production setup must set it to `false` explicitly), JWT issuer/audience, rate limiting values.
## Gitea (repository SlpModularCms) variables and secrets
| Name | Kind | Value |
|---|---|---|
| `DEPLOY_PATH_ASF_TEST` | variable | absolute path of `apps/andreaslopfotografie/test` **(verify)** |
| `SERVICE_NAME_ASF_TEST` | variable | `andreaslopfotografie-test` (**check** whether the existing SlpSoftware variable includes `.service`; use the same form) |
| `HEALTH_CHECK_URL_ASF_TEST` | variable | `https://test.andreaslop.nl/health` |
| `VITE_SENTRY_DSN_ASF` | variable | the website's Sentry DSN (a public DSN, same value as backend) |
| `ASF_TEST_DEPLOY_ENABLED` | variable | `true` ONLY when everything else is ready (the on/off switch) |
| `PI_MAIN_USERNAME`, `PI_MAIN_PASSWORD`, `PI_MAIN_PORT`, `PI_MAIN_ADDRESS` | secrets | **already exist** and are reused; they must point at the same Pi and user (`gitea-workflow`, SSH port 2224) |
Fixed in the workflow (not variables): `VITE_THEME=asf`, `VITE_DEFAULT_LANGUAGE=nl`, `VITE_APP_ENV=test`, `VITE_APP_TITLE`. No Umami for the admin.
## Sentry and CSP check (answer to the question from the website side)
The admin sends browser errors to the same-origin path `/sentry-tunnel` (`tunnel` option), and the host forwards them to the destination derived from `Observability__SentryDsn`. The admin policy `Strict` (`connect-src 'self'`) therefore needs **no** Sentry ingest origin; the website's own `StrictSite` list keeps its direct ingest host for the website's browser code. Variable names: backend `Observability__SentryDsn` (in `shared/env`), frontend build `VITE_SENTRY_DSN_ASF` (Gitea variable, passed to the build as `VITE_SENTRY_DSN`). Events from admin, host and website share one project; the environment tag (`test`) and the release/URL tell them apart.
## Existing hosts touched by the shared change (option B)
`Api`, `Api.SlpSoftware`, `Api.Slave` get the new opt-in forwarded-headers code and per-client limiters. Until `ForwardedHeaders__KnownProxies__0` is set in their environment and their proxy block passes `X-Forwarded-For`/`-Proto`, they behave as before (all callers share the proxy's address, same as today's global bucket). Enabling it for SlpSoftware test/production is an optional separate step in the manual list.
@@ -0,0 +1,39 @@
# Manual steps for Bryan - Andrea Slop Fotografie (ASF) test host (ordered, complete)
Scope: test environment only. Nothing here touches production. Commands are drafted by the Pi-Main session (via "CMS & API") from this list; this list says WHAT and in WHICH ORDER. Items marked **(verify)** are facts from the inventory that were not verified by the author.
Legend: **[Pi]** app Pi, **[Proxy]** proxy Pi 192.168.1.102, **[Gitea]** the CMS repository settings, **[Code]** needs the code on Gitea.
## Phase A - Prepare (nothing is live yet; the old nginx route keeps serving)
1. **[Pi] Verify prerequisites**: user `gitea-workflow` exists and has lingering enabled for user units (`loginctl enable-linger gitea-workflow`) (verify); `dotnet` runtime 10 is installed and its path is known (verify); port 5200 is free; the folder `/mnt/storage1/www/html/andreaslop-test` exists and `gitea-workflow` can read it (group/mode; the SlpSoftware setup needed a cross-account permission fix of the same kind) (verify).
2. **[Pi] Database** (sudo): create database `AndreaSlopFotografieTest` (utf8mb4) and user `AndreaSlopFotografie`@`localhost` with a strong password; grant all privileges on that database only. Note the password for step 4. Do not confuse with the WordPress database `andreaslop`.
3. **[Pi] Directories** as `gitea-workflow`: `apps/andreaslopfotografie/test/{releases,shared}`. Create the symlink `shared/wwwroot-web` -> `/mnt/storage1/www/html/andreaslop-test`. (Variant B, only if you choose it later: skip the symlink; the website pipeline then copies into `shared/wwwroot-web` itself.)
4. **[Pi] `shared/env`** (mode 600, owner `gitea-workflow`) with the variables from `infrastructure-design.md`: `ASPNETCORE_ENVIRONMENT`, `ASPNETCORE_URLS`, `ConnectionStrings__DefaultConnection`, `JwtSettings__Secret`, `Identity__Setup__Token`, `Observability__SentryDsn`, `Observability__Environment`, `ForwardedHeaders__KnownProxies__0`, `Logging__LogLevel__SlpModularCms.Website`. Generate the JWT secret (64+ chars) and the setup token (32+ chars) randomly; keep the token for step 17.
5. **[Pi] systemd user unit** `~/.config/systemd/user/andreaslopfotografie-test.service`: `WorkingDirectory=<deploy path>/current`, `EnvironmentFile=<deploy path>/shared/env`, `ExecStart=<dotnet path> SlpModularCms.Api.AndreaSlopFotografie.dll`, `Restart=on-failure`, `KillSignal=SIGINT`, `WantedBy=default.target`. Run `systemctl --user daemon-reload` and `systemctl --user enable` (do **not** start yet: `current` does not exist until the first deploy).
6. **[Pi] Firewall**: allow 5200/tcp only from 192.168.1.102; verify with `ufw status`.
7. **[Pi, Pi-Main] Backup**: add `AndreaSlopFotografieTest` to the DB backup script.
8. **[Gitea] Variables** (repository SlpModularCms): `DEPLOY_PATH_ASF_TEST`, `SERVICE_NAME_ASF_TEST` (same form as the SlpSoftware one), `HEALTH_CHECK_URL_ASF_TEST=https://test.andreaslop.nl/health`, `VITE_SENTRY_DSN_ASF` (the website's Sentry DSN). The existing secrets `PI_MAIN_*` are reused: confirm they point at the same Pi and user. **Do NOT set `ASF_TEST_DEPLOY_ENABLED` yet.** Until it is `true` the ASF jobs are skipped and the pipeline stays as it is.
9. **[Code] Make the code available to Gitea**: this feature's branch must be pushed (or merged into master) before any deploy can run. I do not push; tell me when you want that. A merge to master with the switch off changes nothing for Andrea.
## Phase B - Cut over (this causes the short test downtime you accepted)
10. **[Proxy] Save the current server block** for `test.andreaslop.nl` (copy the file; this is the revert point).
11. **[Proxy] Switch the route**: the block for `test.andreaslop.nl` (website repo copy: `web/deploy/nginx/test.andreaslop.nl.proxy.conf`, generated by `web/config/serverConfig.ts`) already sets `Host`, `X-Forwarded-For` (`$proxy_add_x_forwarded_for`), `X-Forwarded-Proto` (`$scheme`) and `X-Real-IP`. **Verify** these three forwarded headers are present in the live block (grep), then change only the target: `proxy_pass http://192.168.1.103;` (port 80, nginx fallback) -> `proxy_pass http://192.168.1.103:5200;`. Keep the certbot TLS settings. Test the config, reload nginx. Until the first deploy the site answers 502/503 (expected). The generator in the website repo is updated in U3 so the repo copy matches.
12. **[Gitea] Set `ASF_TEST_DEPLOY_ENABLED=true`.**
13. **[Gitea/Code] Run the first deploy**: push to master, or start "Continuous Integration" manually with the box "Deploy ASF test" ticked. Watch the job: build admin, publish, upload, link, switch, restart, `/health` check on the public URL, prune.
## Phase C - Verify (can be done together with this session)
14. `curl -I https://test.andreaslop.nl/` -> 200 with CSP, HSTS, `X-Robots-Tag: noindex, nofollow`; `/over-mij` (or any page) 200; `/Over-Mij` -> one 301; an unknown path -> 404 with the 404 page; `/robots.txt` -> `Disallow: /`.
15. `https://test.andreaslop.nl/health` -> healthy; `/api/v1/System/capabilities` -> no `Offerings`.
16. `/admin/`: Andrea's theme, Dutch; the setup page asks for the setup token.
17. Create the first administrator with the setup token. Afterwards **remove `Identity__Setup__Token` from `shared/env`** and restart the unit (the setup endpoint is closed once initialised; removing the token is hygiene).
18. Report what you see for the forwarded headers (visitor address in the logs/limiter rather than 192.168.1.102) and optionally time a page request on the Pi; both are asked for in the hand-back.
## Rollback
- **Release**: `ln -sfn releases/<previous> current` and `systemctl --user restart andreaslopfotografie-test`.
- **Route**: restore the saved nginx block on the proxy Pi (step 10) and reload; the old nginx fallback on the app Pi serves the test site again.
- **Switch off CI**: set `ASF_TEST_DEPLOY_ENABLED` to anything but `true`.
## Optional, separate (existing hosts; only if you want per-visitor rate limits there too)
- **SlpSoftware test**: add `ForwardedHeaders__KnownProxies__0=192.168.1.102` to its `shared/env`, make sure its proxy-Pi block sets `X-Forwarded-For`/`-Proto`, restart the unit after the next deploy of the new code.
- **SlpSoftware production and other hosts**: the same two things, later, when you decide. Until then they behave exactly as before.
- Production Andrea: out of scope for this feature (when it comes: `Website__NoIndex=false`, its own database/port 5201/route).
@@ -0,0 +1,39 @@
# Logical Components - andreaslop-client (U2)
No new infrastructure components. All changes are in-process code, CSS and workflow files.
| Component | Location (planned) | Role |
|---|---|---|
| `SlpModularCms.Api.AndreaSlopFotografie` | `src/` (solution folder Clients) | Thin host: `CmsHostOptions { WebsiteMode = PrerenderedPages }`, three-file appsettings, own `launchSettings` port |
| `SetupOptions`, `ISetupTokenValidator`, `SetupTokenValidator` | `Modules.Identity` | P1-P3 |
| `SetupController` (changed) | `Modules.Identity/Controllers` | Limiter, token check, `tokenRequired` in status |
| `SecurityEvents.SetupTokenRejected` | `Core/Observability` | P6 |
| Setup page change | `frontend/src/features/setup` | Token field only when `tokenRequired`; header `X-Setup-Token` |
| Theme | `frontend/themes/asf/` + Vite alias + `VITE_THEME` | P9 |
| i18n default language | `frontend/src/i18n/config.ts` | P10 |
| `publish-asf-test`, `deploy-asf-test` | `.gitea/workflows/continuous_integration.yaml` | P8 |
| `ForwardedHeaders` options + registration (new), `CmsHost` pipeline (changed: first middleware) | `Core/Hosting` | P11; shared by all clients, opt-in |
| `AddCmsRateLimiting` (changed) + `ClientPartitionKey` | `Core/Hosting` | P12; shared by all clients |
| Test projects | `Modules.Identity.Tests`, `frontend` Vitest | Validator (incl. PBT), controller, setup page, theme/i18n |
| `Api.AndreaSlopFotografie` tests | host regression: `capabilities` has no `Offerings` | Needs MariaDB like `Api.Tests` |
```mermaid
flowchart TD
CI["continuous_integration.yaml"] --> PUB["publish-asf-test"]
PUB --> FE["frontend build (VITE_THEME=asf, VITE_DEFAULT_LANGUAGE=nl)"]
PUB --> HOST["Api.AndreaSlopFotografie publish (linux-arm64)"]
CI --> DEP["deploy-asf-test"]
DEP --> SCP["deploy-scp.yaml (unchanged)"]
HOST --> CORE["Core: CmsHost, WebsiteMode, StrictSite"]
HOST --> IDM["Modules.Identity: setup token"]
FE --> TH["themes/asf"]
classDef ci fill:#d6bcfa,stroke:#553c9a,stroke-width:1px,color:#000;
classDef app fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
classDef fe fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
class CI,PUB,DEP,SCP ci;
class HOST,CORE,IDM app;
class FE,TH fe;
```
Text alternative: the pipeline builds the themed admin and publishes the Andrea host, which uses Core and the Identity module; the deploy job reuses the existing SCP workflow.
@@ -0,0 +1,43 @@
# NFR Design Patterns - andreaslop-client (U2)
| # | Pattern | Realises | Design |
|---|---|---|---|
| P1 | Optional guard with secure default | NFR-SEC-01/02 | `ISetupTokenValidator { IsRequired; IsValid(presented) }`. `IsRequired` is true only when `Identity:Setup:Token` is a non-empty string. With no token configured everything behaves as today (existing hosts unaffected). `CreateOwner` checks the validator **before** calling `ISetupService`, so a wrong token creates nothing. |
| P2 | Constant-time comparison | NFR-SEC-01 | Both sides are hashed with SHA-256 to 32 bytes and compared with `CryptographicOperations.FixedTimeEquals`. Equal length by construction, so no length leak; null/empty presented token is simply invalid. The validator never throws. |
| P3 | Fail closed on bad configuration | NFR-SEC-02 | A whitespace-only configured token is treated as a configuration error at startup (options validation), not as "no token". |
| P4 | No information leak | NFR-SEC-02 | `GET /Setup/status` returns `{ initialized, tokenRequired }` only. A rejected token answers `401` with the same problem-details body whatever the reason (missing or wrong). |
| P5 | Reuse the existing limiter | NFR-SEC-03 | `[EnableRateLimiting("login")]` on `GetStatus` and `CreateOwner`. Limits come from the existing `RateLimiting:Login` settings (5 per 60 s). A 429 already produces the `rate_limit_triggered` security event. |
| P6 | Alertable security event | NFR-SEC-03 | New constant event name `setup_token_rejected` (event id 5007) in `SecurityEventNames`/`SecurityEvents`, source-generated like the others, constant template, endpoint as the only field; no token, no email. Level Warning so it crosses the Sentry threshold. |
| P7 | Secrets only from the environment | NFR-SEC-04/05 | Committed appsettings hold placeholders. Real values come from `shared/env` via the systemd unit: `ConnectionStrings__DefaultConnection`, `JwtSettings__Secret`, `Identity__Setup__Token`, `Observability__SentryDsn`, `SecurityHeaders__...`. The infrastructure design lists them. |
| P8 | Explicit skip switch for CI | NFR-DEP-02, DEP-03 | Job-level condition `vars.ASF_TEST_DEPLOY_ENABLED == 'true'` on `publish-asf-test` and `deploy-asf-test`. Failing/skipped ASF jobs are not in any SlpSoftware job's `needs`. The Andrea deploy job reuses `deploy-scp.yaml` with its own path, service and health-check variables. |
| P9 | Build-time theme selection | NFR-UX-01/02 | `VITE_THEME` selects `themes/<name>/theme.css` via a Vite alias; unset = empty module (today's admin). The CSS only re-declares existing tokens (`--background`, `--primary`, `--radius`, fonts ...), nothing structural. |
| P10 | Language default without overriding the user | NFR-UX-01 | i18n init order: stored choice, then `VITE_DEFAULT_LANGUAGE`, then browser detection. |
| P11 | Trusted-proxy forwarded headers (opt-in) | NFR-SEC-09/10/12 | `ForwardedHeadersOptions` built from `ForwardedHeaders:KnownProxies`; `KnownProxies`/`KnownNetworks` cleared first (framework default trusts loopback), `ForwardLimit = 1`, `ForwardedHeaders = XForwardedFor \| XForwardedProto`. Added with `UseForwardedHeaders()` as the **first** middleware after the database migration, only when at least one proxy is configured. Options validation (`ValidateOnStart`): every entry parses as an IP address and is not any-address. |
| P12 | Per-client limiter partitions | NFR-SEC-11 | A helper `ClientPartitionKey(HttpContext)` returns `RemoteIpAddress` text or a fixed fallback. Each named limiter is registered with `AddPolicy(name, context => RateLimitPartition.GetFixedWindowLimiter(key, _ => options))` (sliding for `refresh`), keeping the same permit/window/queue settings. Rejection callback and `rate_limit_triggered` event unchanged. Idle partitions are reclaimed by the framework. |
## Where the checks sit
```mermaid
flowchart LR
R["POST /api/v1/Setup/owner"] --> L{"login limiter"}
L -- over limit --> T429["429 + rate_limit_triggered"]
L -- ok --> V{"token required?"}
V -- no --> S["ISetupService.CreateInitialOwnerAsync"]
V -- yes --> C{"X-Setup-Token valid? (fixed time)"}
C -- yes --> S
C -- no --> T401["401 + setup_token_rejected"]
classDef ok fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
classDef bad fill:#feb2b2,stroke:#c53030,stroke-width:1px,color:#000;
classDef step fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
class S ok;
class T429,T401 bad;
class L,V,C step;
```
Text alternative: the limiter runs first, then the token check when a token is configured; only a valid (or not required) token reaches the setup service.
## Open verification items (settled in Code Generation or on the first test deploy)
1. (Resolved by option B, P11/P12.) Finding: the limiters were global buckets and no host handled forwarded headers. After this change, behind the proxy Pi the limiter only partitions per visitor once `KnownProxies` is set and the proxy-Pi block passes `X-Forwarded-For`/`-Proto`; the proxy must set the header from the real client address (`$remote_addr`), and the host takes the last entry (forward limit 1). Verified by tests with a simulated trusted and an untrusted proxy.
2. Gitea `vars` in a job-level `if:` (used already in step `if:` elsewhere): verify the syntax in the workflow file with a dry read; the skip behaviour is observed on the first run.
3. Forwarded headers / HTTP/1.0 behind the proxy Pi: observed on the first test deploy (peer request).
@@ -0,0 +1,58 @@
# NFR Requirements - andreaslop-client (U2)
Answers: Q1 deploy trigger "Zelfde als nu" (automatic on push to master + manual box, test only, must skip cleanly while Andrea is not set up); Q2 = A separate jobs; Q3 = A setup endpoints under the `login` limiter + security event; Q4 = A token required on test; Q5 = B brand colours exactly, no contrast check.
## Security (Security Baseline, blocking)
| ID | Requirement |
|---|---|
| NFR-SEC-01 | First-admin setup token: `Identity:Setup:Token` from configuration (env `Identity__Setup__Token`), compared with `CryptographicOperations.FixedTimeEquals` over fixed-length hashes; no short-circuit on length. Header `X-Setup-Token`. |
| NFR-SEC-02 | Token configured = `POST /Setup/owner` without or with a wrong token answers 401 problem details and creates nothing; not configured = behaviour exactly as today (existing hosts unaffected). `GET /Setup/status` returns `tokenRequired` only, never the token or its length. |
| NFR-SEC-03 | Both setup endpoints get `[EnableRateLimiting("login")]` (5 per 60 s per the existing policy). A rejected token attempt is logged as a security event through the existing `SecurityEvents` mechanism (no token value, no email in the message). |
| NFR-SEC-04 | The token is a deploy-time secret: only in `shared/env` (mode 600) on the Pi, never in the repository, workflow logs or appsettings; removable after the first administrator exists (the setup endpoint already refuses once initialised). |
| NFR-SEC-05 | Secrets in general (DB password, JWT secret, Sentry DSN, setup token): environment only. Committed appsettings contain placeholders only (like `Api.SlpSoftware`). |
| NFR-SEC-06 | The Andrea client starts with `Website:NoIndex=true` and `StrictSite` on test; production values are out of scope. |
| NFR-SEC-07 | The pipeline never touches production for Andrea: no production deploy job, no production variables. |
| NFR-SEC-08 | No new NuGet or npm dependencies in production code. |
### Added after the requirements approval: proxy-aware rate limiting (Bryan chose option B)
Finding: the named limiters (`login`, `refresh`, `sentry-tunnel`, `offerings-public`) are single global buckets, and no host handles forwarded headers. Decision (Bryan, in chat): "meteen goed opzetten", changing existing hosts and pipelines is acceptable.
| ID | Requirement |
|---|---|
| NFR-SEC-09 | Opt-in forwarded-headers support in the shared host: section `ForwardedHeaders` with `KnownProxies` (list of IP addresses). Empty or absent = middleware not added = behaviour of every host without a proxy unchanged. |
| NFR-SEC-10 | Only the listed proxies are trusted (`X-Forwarded-For`, `X-Forwarded-Proto`; forward limit 1). Startup validation refuses unparsable addresses and any wildcard/any-address (`0.0.0.0`, `::`), so a client can never spoof its address to dodge a limiter. The middleware runs before everything that uses the client address or scheme (limiter, HTTPS redirection). |
| NFR-SEC-11 | The four named limiters are partitioned per client address (resulting `RemoteIpAddress`; fallback key when unknown) instead of one global bucket, with the existing permit/window settings. A missing/unreadable address maps to one shared fallback partition, never to "unlimited". |
| NFR-SEC-12 | Safe degradation: if a host has a proxy but `KnownProxies` is not (yet) configured, all callers share the proxy's address, which equals today's global bucket. No new failure mode. |
| NFR-SEC-13 | Existing environments (`Api`, `Api.SlpSoftware`, `Api.Slave`) change only by this shared code; their deployment config stays as is until Bryan sets `ForwardedHeaders__KnownProxies__0` in their `shared/env` and the proxy-Pi blocks pass the headers (listed in the manual steps, test and production separately; production is not touched by this feature). |
## Deployment and availability
| ID | Requirement |
|---|---|
| NFR-DEP-01 | Automatic deploy of the Andrea client to the test host on every push to master, and via the manual box `deploy_andrea_test` (Q1). Test only. |
| NFR-DEP-02 | **Skip cleanly while Andrea is not set up**: the Andrea publish/deploy jobs only run when the Gitea variable `ASF_TEST_DEPLOY_ENABLED` equals `true` (Bryan sets it after the Pi and secrets exist). Until then the jobs are skipped, the existing pipeline stays green and unchanged, and nothing about Andrea can fail the run. (Secrets cannot be tested in an `if:`, hence the explicit variable.) |
| NFR-DEP-03 | Separate jobs (Q2): `publish-asf-test` and `deploy-asf-test`, reusing `deploy-scp.yaml` unchanged; the `Api.SlpSoftware` jobs, the env block and `deploy-scp.yaml` stay byte-for-byte unchanged. A failure in an Andrea job must not block the SlpSoftware deploy and vice versa. |
| NFR-DEP-04 | Deploy keeps the existing guarantees: timestamped release, atomic `current` switch, `/health` check, one previous release kept. Website delivery works in both variants (CI/web job writes into `shared/wwwroot-web`, or `shared/wwwroot-web` is a symlink to `/mnt/storage1/www/html/andreaslop-test`). |
| NFR-DEP-05 | Smoke checks after deploy: `/health`, `/api/v1/System/capabilities` (no `Offerings`), one website page, headers (CSP, noindex). Observe forwarded-header / HTTP 1.0 behaviour behind the proxy Pi on the first deploy and report it. |
| NFR-DEP-06 | linux-arm64 publish, `--self-contained false`, same as SlpSoftware. |
## Usability and theme (Q5 = B)
| ID | Requirement |
|---|---|
| NFR-UX-01 | Theme = CSS variables overriding the existing admin design tokens, chosen at build time (`VITE_THEME`); unset reproduces today's admin exactly. Language default `nl` via `VITE_DEFAULT_LANGUAGE`; a user's stored choice still wins. |
| NFR-UX-02 | **Brand colours exactly as the website; no contrast check (Bryan's explicit choice).** Trade-off recorded: some token pairs (for example muted text on a light background, or white text on a light brand accent) may fall below WCAG AA (4.5:1 text, 3:1 large text and UI components). This overrides the brief's accessibility hint. The theme does not invent extra colours to compensate; error and destructive states use the exact brand tokens if the website defines them, otherwise the existing admin tokens, so they stay as readable as the brand allows. A short list of pairs that fall below AA goes into the hand-back as information. |
| NFR-UX-03 | Fonts (Marcellus, Jost) are self-hosted with the theme (no third-party font request, consistent with `font-src 'self'`). |
## Reliability and operations
| ID | Requirement |
|---|---|
| NFR-OPS-01 | Own database `AndreaSlopFotografieTest`, user `AndreaSlopFotografie@localhost`; startup migration runs as today. |
| NFR-OPS-02 | Systemd user unit with restart on failure; environment from `shared/env`. |
| NFR-OPS-03 | Logs: warnings by default, `SlpModularCms.Website` at Information on test (U1). |
| NFR-OPS-04 | Tests of the changed parts stay green; `Api.Tests` is run against a real MariaDB (Pi test DB or local) during U2 and reported in handback-u2. |
## Performance / scalability
N/A beyond U1 (one small instance). The per-request file lookup is measured on the Pi if cheap (peer request).
## Property-based testing (partial)
- PBT-02/03 in U2: setup-token validator. A presented token is accepted iff it equals the configured one (generated strings including unicode and empty); never throws; a prefix or different token is rejected.
- PBT-07/08/09 follow U1's helpers and framework (FsCheck.Xunit, test-only; referenced from `Modules.Identity.Tests`).
@@ -0,0 +1,14 @@
# Tech Stack Decisions - andreaslop-client (U2)
| # | Decision | Rationale |
|---|---|---|
| T1 | New project `SlpModularCms.Api.AndreaSlopFotografie` (net10.0, Microsoft.NET.Sdk.Web), thin `Program.cs` on `CmsHost` with `WebsiteMode.PrerenderedPages`; same package references as `Api.SlpSoftware`, only the modules it needs | Brief; no new packages |
| T2 | Modules: Core + Identity; `Master` and `Offerings` not referenced (capabilities must not list `Offerings`); `Availability` decided in Code Generation by checking whether the admin needs it | Brief D1/D9 |
| T3 | Setup token: `SetupOptions` + `ISetupTokenValidator` in `Modules.Identity`; comparison via `CryptographicOperations.FixedTimeEquals` on SHA-256 digests | Constant time, no length leak, in-box API |
| T4 | Rate limiting: reuse the `login` fixed-window policy via `[EnableRateLimiting("login")]` | Q3 = A; existing, tested mechanism |
| T5 | Theme: plain CSS custom properties in `frontend/themes/asf/theme.css`, imported through a build-time Vite alias driven by `VITE_THEME`; fonts, logo and favicon as theme assets | No new dependency; Q5 = B |
| T6 | Language default: `VITE_DEFAULT_LANGUAGE` read in i18n init | Existing i18next setup |
| T7 | CI: new jobs `publish-asf-test` and `deploy-asf-test` in `continuous_integration.yaml`, gated by the Gitea variable `ASF_TEST_DEPLOY_ENABLED`; reuse `deploy-scp.yaml` unchanged | Q1, Q2; NFR-DEP-02 |
| T8 | Gitea variables for ASF (non-secret): `DEPLOY_PATH_ASF_TEST`, `SERVICE_NAME_ASF_TEST`, `HEALTH_CHECK_URL_ASF_TEST`, `ASF_TEST_DEPLOY_ENABLED`; the SSH secrets `PI_MAIN_*` are the existing ones | Mirrors the existing pattern |
| T10 | Forwarded headers: built-in `ForwardedHeadersMiddleware`, options from section `ForwardedHeaders` (`KnownProxies`), registered only when configured; limiters re-registered with `AddPolicy` and `RateLimitPartition.Get*Limiter` keyed on the client address | Option B; in-box APIs, no new packages |
| T9 | Tests: xUnit + FluentAssertions + FsCheck.Xunit (test-only) for the validator and controller; Vitest for the setup page and theme/i18n; `Api.Tests` on MariaDB for regression | Existing frameworks |
@@ -0,0 +1,51 @@
# Code Generation Plan - andreaslop-client (U2)
Single source of truth for U2 code generation. Brownfield. Application code under `src/` and `frontend/`; workflow under `.gitea/workflows/`; docs summary under `construction/andreaslop-client/code/`. Names follow the ASF convention (see infrastructure-design.md). No push; one local commit per part.
## Unit context
- Implements FR-U2-01..05, NFR-* and P1-P12 (NFR design), infrastructure design (test only).
- Depends on U1 (done): `WebsiteMode.PrerenderedPages`, `StrictSite`, `Website:NoIndex`.
- Shared change (option B) touches `Api`, `Api.SlpSoftware`, `Api.Slave`: opt-in, safe degradation, full regression required.
- Tests needing MariaDB (`Api.Tests`, host regression) are run if a local/Pi DB is reachable; otherwise reported as not runnable.
## Part A - Core: forwarded headers and per-client limiters (P11, P12)
- [x] **A1** `Core/Hosting/ForwardedHeadersOptions` (`ForwardedHeaders:KnownProxies`), validation (unparsable and any-address entries rejected), registration; `UseForwardedHeaders` first in `CmsHost` only when proxies are configured (ForwardLimit 1, XForwardedFor|XForwardedProto, default known proxies cleared).
- [x] **A2** `ClientPartitionKey` + `AddCmsRateLimiting`: per-client-address partitions for `login`, `refresh`, sentry-tunnel, `offerings-public`; fallback key when address unknown. Behaviour with no config is unchanged.
- [x] **A3** Tests: options validation, partition key (incl. PBT: distinct addresses never share a bucket, same address always does), integration via TestServer (spoofed header from untrusted peer ignored; trusted proxy honoured; limiter isolates clients).
- [x] **A4** Build + test Core and all three existing hosts' projects; regression for Api/Api.SlpSoftware/Api.Slave (MariaDB-dependent ones reported). (non-DB suites green; Api.Tests needs MariaDB, run in CI)
## Part B - Identity: setup token (P1-P3, P6)
- [x] **B1** `SetupOptions` (`Identity:Setup:Token`), whitespace-only token = startup error; `ISetupTokenValidator` / `SetupTokenValidator` (SHA-256 + `CryptographicOperations.FixedTimeEquals`, header `X-Setup-Token`).
- [x] **B2** `SetupController`: `[EnableRateLimiting("login")]` on both endpoints; `POST owner` checks token (identical 401 for missing/wrong, no detail); `GET status` returns `initialized` + `tokenRequired`.
- [x] **B3** `SecurityEvents.SetupTokenRejected` (id 5007, `setup_token_rejected`), logged on failed attempts without echoing the token.
- [x] **B4** Tests: validator (examples + PBT: only the exact token passes, any other string fails, no exception), controller (no token configured = today's behaviour; token required; 401 uniformity; event logged), status payload.
- [x] **B5** Build + test `Modules.Identity` and its tests.
## Part C - New client project `SlpModularCms.Api.AndreaSlopFotografie`
- [x] **C1** Project in `src/`, added to the solution under **Clients**; thin `Program.cs` with `CmsHostOptions { WebsiteMode = PrerenderedPages }`; Identity module; Availability module only if required (capabilities must not list `Offerings`).
- [x] **C2** Three-file appsettings per the `dotnet-appsettings` skill (`appsettings.json` without secrets: `SecurityHeaders` `DefaultPolicy=StrictSite` + site Umami/Sentry origins, `Website:NoIndex=true`, JWT issuer/audience, rate limits), `launchSettings` port 5200, publish settings like Api.SlpSoftware.
- [x] **C3** Tests: host regression (capabilities has no `Offerings`, `/health`, website serving from a temp `wwwroot/web`, headers), needs MariaDB like `Api.Tests`. (config tests run; pipeline tests need MariaDB, run in CI)
- [x] **C4** Build + test.
## Part D - Frontend: ASF theme, language, setup token (P9, P10)
- [x] **D1** `frontend/themes/asf/theme.css`: CSS variables only, ASF palette exactly as the website (Q5 = B, no contrast adjustment; trade-off recorded), self-hosted Marcellus/Jost, logo + favicon assets.
- [x] **D2** Vite alias driven by `VITE_THEME` (unset = empty module, today's admin); `VITE_DEFAULT_LANGUAGE` in `i18n/config.ts` (stored choice > env default > browser).
- [x] **D3** Setup page: token field only when `tokenRequired`; sends `X-Setup-Token`; translations nl/en.
- [x] **D4** Vitest: theme alias unset/set, language order, setup page with/without token. Compute below-AA contrast pairs for the hand-back.
- [x] **D5** Frontend lint, type-check, test, build for both default and `VITE_THEME=asf`.
## Part E - CI/CD (P8)
- [x] **E1** `continuous_integration.yaml`: add `publish-asf-test` and `deploy-asf-test`, gated by `vars.ASF_TEST_DEPLOY_ENABLED == 'true'`, reusing `deploy-scp.yaml`; manual box "Deploy ASF test". Existing SlpSoftware jobs, env block and `deploy-scp.yaml` byte-for-byte unchanged (verified by diff). Admin build env: `VITE_THEME=asf`, `VITE_DEFAULT_LANGUAGE=nl`, `VITE_APP_ENV=test`, `VITE_SENTRY_DSN` from `VITE_SENTRY_DSN_ASF`.
- [x] **E2** Validate YAML; confirm via diff that nothing else changed; note the open verification item (Gitea `vars` in job-level `if:`).
## Part F - Documentation and wrap-up
- [x] **F1** Update `README.md`/`AGENTS.md` (+ mirrors `CLAUDE.md`, `.junie/guidelines.md`, `.github/copilot-instructions.md` together) for the new Clients project and the opt-in `ForwardedHeaders` setting; `WEBSITE_WORKSPACE.md` if affected.
- [x] **F2** `construction/andreaslop-client/code/code-summary.md`.
- [x] **F3** Full solution build and all tests; report results honestly.
- [x] **F4** Local commits (code, then docs); no push.
## Deployment artifacts
Workflow jobs (Part E) and appsettings (C2); Pi steps are in `manual-steps-for-bryan.md`. The test deploy itself only happens with Bryan's explicit go.
## Traceability
A -> option B / NFR (proxy awareness); B -> FR-U2-05 (setup token); C -> FR-U2-01/02; D -> FR-U2-03; E -> FR-U2-04; F -> docs.
@@ -0,0 +1,43 @@
# Infrastructure Design Plan - andreaslop-client (U2)
## Steps
- [x] Analyse design artifacts (NFR requirements/design, `pi-inventory-notes.md`, `deploy-scp.yaml`, `continuous_integration.yaml`)
- [x] Collect answers to the questions below
- [x] Generate `infrastructure-design/infrastructure-design.md` (components, Pi layout, env variables, Gitea variables/secrets)
- [x] Generate `infrastructure-design/deployment-architecture.md` (diagrams, deploy sequence)
- [x] Generate `infrastructure-design/manual-steps-for-bryan.md` (complete ordered list, both web-delivery variants)
- [x] Tell "CMS & API" the list is complete so Pi-Main can draft the commands
## Category evaluation
- Deployment environment: on-premise Pis, test only (decided). Pattern copied from SlpSoftware test.
- Compute: one .NET process (~250-300 MB), systemd user unit, port 5200; sizing fits the Pi 4 (decided).
- Storage: MariaDB 10.11 `AndreaSlopFotografieTest` / `AndreaSlopFotografie@localhost` (decided); website files either in the release tree or on `/mnt/storage1` (Question 1).
- Messaging: not applicable.
- Networking: proxy Pi (TLS, certbot) forwards HTTP/1.0 to 192.168.1.102 -> app port 5200; ufw only from the proxy Pi; the proxy block must pass `X-Forwarded-For`/`-Proto` (decided by option B); first-deploy sequence (Question 2).
- Monitoring: `/health`, logs via journald, Sentry (Question 3).
- Shared infrastructure: runner (arm64 label for builds is NOT needed: publish runs on ubuntu-latest with `-r linux-arm64` exactly like SlpSoftware), the SSH deploy secrets `PI_MAIN_*`, the DB backup script (Pi-Main adds the new DB).
## Question 1: How does the website reach `wwwroot/web` on the test host?
Both variants work without restart (U1 looks pages up per request). Which one do we document as THE path?
- A) Symlink: `shared/wwwroot-web` points to `/mnt/storage1/www/html/andreaslop-test`, the folder the existing web deploy already writes to, so the current website pipeline keeps working unchanged (recommended: no change in the website repo; files live on the big disk, not on the SD card)
- B) Direct: the website CI copies its build into `shared/wwwroot-web` on the SD card (needs a change in the website pipeline and its target path)
- X) Other (please describe after [Answer]: tag below)
[Answer]: A (relayed via CMS and API, Bryan): symlink shared/wwwroot-web to /mnt/storage1/www/html/andreaslop-test; website repo deploy unchanged.
## Question 2: Health check and the first deploy
The deploy workflow checks `/health` on the PUBLIC test URL after switching the release. That URL (`test.andreaslop.nl`) still points at the old nginx fallback until you switch the proxy-Pi route, so a first deploy before the switch fails its health check (the new release is then already live on port 5200, only the job is red).
- A) Switch the proxy-Pi route to port 5200 first, then run the first deploy; the test site is down only for the minutes between the switch and the first successful deploy (recommended: simplest, test environment)
- B) Deploy first with the health-check variable pointing to a temporary URL that already reaches port 5200 (extra hostname + certificate work for you), then switch the route
- C) Deploy first, accept one red health check, verify manually on port 5200 from the proxy Pi, then switch the route
- X) Other (please describe after [Answer]: tag below)
[Answer]: A (relayed via CMS and API, Bryan): switch the proxy-Pi route to port 5200 first, then run the first deploy; short downtime accepted; order and nginx fallback revert explicit in the manual steps.
## Question 3: Sentry for the new host and its admin
- A) A new, separate Sentry project for the CMS host and admin, DSNs supplied through `shared/env` (backend `Observability__SentryDsn`) and the Gitea variable `VITE_SENTRY_DSN_ASF` (frontend) (recommended: keeps the website's own Sentry project clean)
- B) Reuse the website's existing Sentry project (same DSN) for host and admin
- C) No Sentry for now (empty DSN is a supported state); add later
- X) Other (please describe after [Answer]: tag below)
[Answer]: B (relayed via CMS and API, Bryan): reuse the website existing Sentry project (same DSN) for host and admin.
@@ -0,0 +1,14 @@
# NFR Design Plan - andreaslop-client (U2)
## Steps
- [x] Analyse NFR requirements (nfr-requirements.md, tech-stack-decisions.md)
- [x] Evaluate question categories; no open questions (justification below)
- [x] Generate `nfr-design/nfr-design-patterns.md`
- [x] Generate `nfr-design/logical-components.md`
## Category evaluation (why no questions)
- Resilience: deploy resilience is inherited from `deploy-scp.yaml` (atomic switch, health check, previous release kept); the new part is only the skip switch (NFR-DEP-02), which has one obvious design.
- Scalability and performance: N/A for U2 (one small instance).
- Security: the token check, limiter and security event follow the answers Q3/Q4 and the existing `SecurityEvents` and rate-limiting mechanisms; placement has one sensible solution.
- Logical components: no new infrastructure; one validator, one controller change, one security event, one CSS theme, two CI jobs.
- Open verification items are listed in `nfr-design-patterns.md` and are settled by tests or the first test deploy.
@@ -0,0 +1,57 @@
# NFR Requirements Plan - andreaslop-client (U2)
U2 Functional Design is skipped (execution plan: no new business domain).
## Steps
- [x] Analyse unit context (requirements FR-U2-01..08, application design C1/C5/C6/C7, existing `continuous_integration.yaml`, `deploy-scp.yaml`, `SetupController`)
- [x] Collect answers to the questions below
- [x] Generate `nfr-requirements/nfr-requirements.md` and `tech-stack-decisions.md`
- [x] Security Baseline and PBT applicability (tabulated in the artifacts)
## Findings from the existing code that shape the questions
- `continuous_integration.yaml` deploys `Api.SlpSoftware` to its test host **automatically on every push to master** and has a separate opt-in production deploy. The reusable `deploy-scp.yaml` already does what Andrea needs (timestamped release, `shared/wwwroot-web` symlink, atomic `current` switch, health check), so both website-delivery variants only differ in what `shared/wwwroot-web` is.
- `POST /Setup/owner` and `GET /Setup/status` are anonymous and have **no rate limiter**; only `/Auth/login` (`login` policy: 5 per 60 s) and refresh are limited.
- The shared admin frontend is built once per publish job with Vite variables; it has `dev:slpsoftware` modes and a `useTheme` hook (light/dark).
## Pre-filled assumptions
- Scale/availability: one small instance on the test Pi; no HA; rollback = previous release kept by `deploy-scp.yaml`.
- Secrets (DB password, JWT secret, setup token, Sentry DSN) only in `shared/env` on the Pi and Gitea secrets/variables, never in the repository.
- Tech stack: no new packages; theme is plain CSS variables; token comparison via `CryptographicOperations.FixedTimeEquals`.
## Question 1: When does the ASF test deploy run?
- A) Only when someone starts the workflow manually and ticks a new box "Deploy ASF test" (recommended: a merge to master never touches Andrea's site by surprise; test only)
- B) Automatically on every push to master, like `Api.SlpSoftware`, plus the manual box
- X) Other (please describe after [Answer]: tag below)
[Answer]: B-ish (relayed via CMS and API, Bryan: Zelfde als nu): automatic test deploy on every push to master like Api.SlpSoftware, plus the manual box. Test only. Must skip cleanly while Andrea deploy variables and secrets are unset.
## Question 2: How do the pipelines relate?
- A) Add separate jobs for the Andrea client (build its admin with its theme, publish its project, call the existing `deploy-scp.yaml`); the `Api.SlpSoftware` jobs stay byte-for-byte as they are (recommended: zero risk for the existing deploy)
- B) Turn the existing publish job into a matrix over both clients (less duplication, but changes the working SlpSoftware pipeline)
- X) Other (please describe after [Answer]: tag below)
[Answer]: A (relayed via CMS and API)
## Question 3: Rate limiting for the first-admin setup endpoints
`/Setup/owner` and `/Setup/status` have no limiter today. With the optional setup token a stranger could still guess the token.
- A) Put both setup endpoints under the existing `login` limiter policy (5 per 60 s), and log failed token attempts as a security event (recommended)
- B) A new, separate `setup` limiter policy with its own settings
- C) No limiter, only the token
- X) Other (please describe after [Answer]: tag below)
[Answer]: A (relayed via CMS and API)
## Question 4: Setup token on the test instance
- A) Required on test (set in `shared/env`); the token is only needed until the first administrator exists, and it can be removed from `shared/env` afterwards (recommended)
- B) Optional on test (not set); the setup page is open until the first admin is created
- X) Other (please describe after [Answer]: tag below)
[Answer]: A (relayed via CMS and API)
## Question 5: Theme accessibility target
The theme maps Andrea's brand colours onto the admin's design tokens.
- A) Text and interactive elements must reach WCAG AA contrast (4.5:1 text, 3:1 large text and UI); where the brand colour fails, the admin uses a darker/lighter variant of it (recommended)
- B) Use the brand colours exactly as the website does, without a contrast check
- X) Other (please describe after [Answer]: tag below)
[Answer]: B (relayed via CMS and API, Bryan explicit choice): brand colours exactly as the website, no contrast check. Trade-off recorded in nfr-requirements.md.
@@ -33,7 +33,7 @@ graph TD
core -->|"PrerenderedPages + StrictSite (U1)"| andrea
andrea --> ident
andrea -.->|"only if required"| avail
fe -->|"VITE_THEME=andreaslop"| andrea
fe -->|"VITE_THEME=asf"| andrea
ci -->|"build + deploy (test only)"| andrea
andrea --> pi
@@ -40,7 +40,7 @@
- **FR-U2-01 Client project** `SlpModularCms.Api.AndreaSlopFotografie` under **Clients** in the solution: thin `Program.cs` on `CmsHost`, `WebsiteMode = PrerenderedPages`, three-file appsettings (`appsettings.json`, `appsettings.{Env}.json`, uncommitted `appsettings.local.json`), own database, own dev port, `SecurityHeaders:DefaultPolicy = StrictSite` with the Umami (`https://analytics.slpsoftware.nl`) and Sentry (`https://o4511795618185216.ingest.de.sentry.io`) origins, `Website:NoIndex = true` for test.
- **FR-U2-02 Module set** = module projects the client references (no config filter). Determine and report the minimum (Identity; is Availability required?). `Offerings` not referenced; `/api/v1/System/capabilities` must not list it.
- **FR-U2-03 Admin theme.** `frontend/themes/andreaslop/` with CSS overriding the existing design tokens (colours, radius, font), plus logo and favicon. `VITE_THEME` selects it at build time (unset = today's look). New `VITE_DEFAULT_LANGUAGE` (`nl` for Andrea; English stays selectable). Palette: paper `#faf7f2` / `#f1ebe2` / `#e8e0d5`, ink `#232120` / `#55504b` / `#8a827a`, line `#e2dad0`, accent `#7f8b76`, accent-deep `#5f6a58` (text/buttons), accent-deeper `#475042`, sand `#d9cdbc`, error `#a4443a`. Fonts Marcellus (headings) and Jost (body) with the site's fallbacks, **self-hosted** (the admin's CSP is `font-src 'self'`). Scope per Q5: tokens + logo + favicon only, no layout or component changes. Contrast stays accessible (destructive and focus-ring colours readable on paper).
- **FR-U2-03 Admin theme.** `frontend/themes/asf/` with CSS overriding the existing design tokens (colours, radius, font), plus logo and favicon. `VITE_THEME` selects it at build time (unset = today's look). New `VITE_DEFAULT_LANGUAGE` (`nl` for Andrea; English stays selectable). Palette: paper `#faf7f2` / `#f1ebe2` / `#e8e0d5`, ink `#232120` / `#55504b` / `#8a827a`, line `#e2dad0`, accent `#7f8b76`, accent-deep `#5f6a58` (text/buttons), accent-deeper `#475042`, sand `#d9cdbc`, error `#a4443a`. Fonts Marcellus (headings) and Jost (body) with the site's fallbacks, **self-hosted** (the admin's CSP is `font-src 'self'`). Scope per Q5: tokens + logo + favicon only, no layout or component changes. Contrast stays accessible (destructive and focus-ring colours readable on paper).
- **FR-U2-04 CI/CD.** Build the admin per deployable client with its `VITE_THEME`, `VITE_DEFAULT_LANGUAGE`, `VITE_APP_TITLE`; publish the new host; deploy to the **test** host with the existing atomic release switch; `wwwroot/web/` stays outside the swapped release directory so the site survives every CMS deploy. The production path for `Api.SlpSoftware` is not touched.
- **FR-U2-05 Test deploy** (Q3, relayed): the pipeline may deploy to the test host, and this session may start the test deploy itself once pipeline and Pi are ready - **test only, never production**. Bryan's go is confirmed in this session before the first deploy.
- **FR-U2-06 Host provisioning** (Q4): the Raspberry Pi accounts exist, but paths, secrets, environment variables, database, service unit and reverse proxy are not set up yet. The infrastructure design lists every remaining step as a manual checklist for Bryan. Pi inventory comes via "CMS & API" from "Pi-Main - Server"; this session does not contact that session directly.