AIDLC-documentatie voor andreaslop-site-hosting (U1 tot en met Code Generation)

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-06 15:52:04 +01:00
co-authored by Claude Sonnet 5.5
parent 7d21d9024a
commit d355519cec
31 changed files with 1598 additions and 0 deletions
@@ -0,0 +1,28 @@
# Application Design (consolidated) - andreaslop-site-hosting
Details: `components.md`, `component-methods.md`, `services.md`, `component-dependency.md`.
## Decisions
| # | Decision | Source |
|---|---|---|
| D1 | `CmsHostOptions.WebsiteMode` (`SpaFallback` default, `PrerenderedPages`); existing clients unchanged | Brief, FR-U1-01 |
| D2 | All nginx-parity rules live in one pure `WebsitePathResolver` taking a file-exists predicate; the middleware is a thin adapter | Requirements FR-U1-02 |
| D3 | A page is "known" by a per-request file-exists check on the lowercased name; no cache, no restart needed after a site delivery | Q2 = A |
| D4 | `StrictSite` policy in `CspPolicyCatalog`, byte-identical to the site's current CSP; origins from new `AllowedSiteScriptOrigins` / `AllowedSiteConnectOrigins`, so admin policies stay as strict as today | Q1 = A |
| D5 | Compression only for non-reserved paths; `/api/v1` and `/admin` not compressed by this feature | Requirements open point 5 |
| D6 | Unknown website paths get `404.html` with status 404 in a final pipeline stage after API routes; an unknown `/api/v1` path stays an API 404 | FR-U1-03/04/10 |
| D7 | Setup token: `Identity:Setup:Token` optional, header `X-Setup-Token`, constant-time compare, `GET /Setup/status` returns `tokenRequired`, setup page shows the field only when required | Q3 = A, FR-U2-07 |
| D8 | Theme is a build-time CSS override of existing tokens (`VITE_THEME`), language default via `VITE_DEFAULT_LANGUAGE`; no runtime theme API | Brief D2, Q5 |
| D9 | Module set of the Andrea client = its project references; `Availability` included only if the admin needs it (decided in U2 NFR/Code Generation, reported to the requester) | Brief D1 |
| D10 | Unit order: U1 Core (with regression run), hand-back and wait for the requester's "go", then U2 | Brief, execution plan |
## Risks carried into Construction
1. The existing security-header writer treats CSP/frame/referrer as HTML-only; website 301/asset/robots responses may need the full set (FR-U1-09). Settled in U1 Functional Design with tests.
2. `UseHttpsRedirection` on plain HTTP behind the proxy Pi, and absent forwarded-headers handling: verify no loop or absolute `http://` redirect (website redirects are relative).
3. Per-request `File.Exists` on a Pi SD card or `/mnt/storage1`: low cost expected; measured in U1 NFR Design.
4. Setup endpoints and rate limiting: confirm the login limiter covers `/Setup/owner` (NFR Design U2).
5. Frontend setup page change touches an existing screen (small, covered by tests).
## Security Baseline / PBT applicability (design stage)
- Security: path input validation centralised in one pure function; secure-by-default configuration (new settings default to today's behaviour); no secrets in repo (token and DB password come from the environment); constant-time token compare; no new dependencies. Compliant / N/A items are tabulated in the NFR stages.
- PBT (partial): the resolver (PBT-02/03 invariants), canonical idempotence, policy round trip are pure and directly testable.
@@ -0,0 +1,63 @@
# Component Dependencies - andreaslop-site-hosting
## Dependency matrix (row depends on column)
| | Core hosting | Security (CSP) | Identity | Frontend | CI/CD |
|---|---|---|---|---|---|
| C2 WebsiteMode | - | | | | |
| C3 Site serving | uses | uses (headers precede it) | | | |
| C4 StrictSite | | - | | | |
| C1 Andrea client | references | configures | references | consumes built admin | built by |
| C5 Theme | | | | - | selected by |
| C7 Setup token | | | - (in module) | setup page | |
| C6 CI/CD | | | | builds | - |
- C3a (pure resolver) depends on nothing but `System`; the predicate is injected. This keeps property-based testing trivial and keeps traversal safety in one testable place.
- `Api` and `Api.SlpSoftware` depend on Core only through unchanged defaults (`WebsiteMode.SpaFallback`, empty site origin lists, no setup token configured).
```mermaid
graph TD
opts["CmsHostOptions.WebsiteMode (C2)"]
host["CmsHost / StaticContentExtensions"]
mw["PrerenderedSiteMiddleware (C3c)"]
res["WebsitePathResolver (C3a, pure)"]
wopt["WebsiteOptions (C3b)"]
csp["CspPolicyCatalog + SecurityHeadersOptions (C4)"]
sethdr["SecurityHeadersMiddleware"]
ident["Identity: SetupController + ISetupTokenValidator (C7)"]
client["Api.AndreaSlopFotografie (C1)"]
fe["frontend theme + setup page (C5, C7)"]
ci["Gitea workflows (C6)"]
host --> opts
host --> mw
mw --> res
mw --> wopt
host --> sethdr
sethdr --> csp
client --> host
client --> ident
client --> csp
fe --> ident
ci --> client
ci --> fe
classDef core fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
classDef pure fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
classDef newc fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
classDef ext fill:#d6bcfa,stroke:#553c9a,stroke-width:1px,color:#000;
class opts,host,mw,wopt,sethdr,csp core;
class res pure;
class client,ident,fe newc;
class ci ext;
```
Text alternative: the host wires the options, the site middleware and the security-header middleware; the middleware depends on the pure resolver; the Andrea client references host and Identity and configures the policy; the frontend and CI build the client.
## Communication patterns
- In-process only; no new network calls from the host.
- Website to API: browser calls same-origin `/api/v1` where needed; Sentry and Umami origins are called directly by the site (listed in `StrictSite`).
- Configuration is the only coupling between a client and a policy: `DefaultPolicy`, `PathPolicies`, `AllowedSite*Origins`, `Website:NoIndex`, `Identity:Setup:Token`.
## Delivery coupling (website files)
`wwwroot/web` is owned by the website delivery (web CI or a symlink to `/mnt/storage1/www/html/andreaslop-test`); the host only reads it. Because pages are resolved per request without cache (Q2=A), both delivery variants work without restart.
@@ -0,0 +1,72 @@
# Component Methods - andreaslop-site-hosting
Signatures are indicative; business rules are detailed in U1 Functional Design.
## Core - hosting
```csharp
public enum WebsiteMode { SpaFallback = 0, PrerenderedPages = 1 }
public sealed class CmsHostOptions { public WebsiteMode WebsiteMode { get; init; } = WebsiteMode.SpaFallback; }
```
## C3a WebsitePathResolver
```csharp
public abstract record WebsiteResolution
{
public sealed record ServeFile(string RelativePath, bool IsNotFoundPage = false) : WebsiteResolution;
public sealed record Redirect(string Location) : WebsiteResolution; // always 301, relative Location
public sealed record NotFound : WebsiteResolution;
}
public static class WebsitePathResolver
{
// Total: never throws, never returns a path outside the website root.
// fileExists receives a relative, forward-slash, already-validated candidate ("over-mij.html").
public static WebsiteResolution Resolve(string? rawPath, string? queryString, Func<string, bool> fileExists);
public static bool IsReservedPath(string? rawPath); // /admin, /api/v1, /health (whole segments, case-insensitive)
}
```
## C3b/C3c Website serving
```csharp
public sealed class WebsiteOptions { public const string SectionName = "Website"; public bool NoIndex { get; set; } }
public static class PrerenderedSiteExtensions
{
public static IServiceCollection AddCmsWebsite(this IServiceCollection s, IConfiguration c); // options + validation + compression
public static WebApplication UseCmsPrerenderedSite(this WebApplication app); // compression (UseWhen), noindex, resolver middleware
}
public sealed class PrerenderedSiteMiddleware(RequestDelegate next, IWebHostEnvironment env, IOptions<WebsiteOptions> options)
{
public Task InvokeAsync(HttpContext context);
}
```
`StaticContentExtensions.UseCmsStaticContent` / `MapCmsSpaFallbacks` branch on `WebsiteMode`: in `PrerenderedPages` they register the admin mount and the `/admin` fallback only, the website mount is `UseCmsPrerenderedSite`, and the catch-all website fallback is replaced by the middleware's 404 handling placed after API routes.
## C4 Security
```csharp
public static class CspPolicyCatalog
{
public const string StrictSite = "StrictSite";
public static SecurityHeaderSet Build(string policy,
IEnumerable<string> allowedScriptOrigins, IEnumerable<string> allowedConnectOrigins,
IEnumerable<string>? siteScriptOrigins = null, IEnumerable<string>? siteConnectOrigins = null);
}
public sealed class SecurityHeadersOptions { /* + */ public IList<string> AllowedSiteScriptOrigins { get; set; } = []; public IList<string> AllowedSiteConnectOrigins { get; set; } = []; }
```
Existing call sites keep compiling (new parameters optional).
## C7 Setup token
```csharp
public sealed class SetupOptions { public const string SectionName = "Identity:Setup"; public string? Token { get; set; } }
public interface ISetupTokenValidator { bool IsRequired { get; } bool IsValid(string? presentedToken); } // fixed-time comparison
// SetupController
// GET /Setup/status -> { initialized, tokenRequired }
// POST /Setup/owner -> 401/403 problem details when token required and missing/wrong; header X-Setup-Token
```
## Frontend
- `theme.ts`/Vite plugin: resolves `VITE_THEME` to `themes/<name>/theme.css` import (no-op when unset).
- `i18n init`: `lng = stored ?? import.meta.env.VITE_DEFAULT_LANGUAGE ?? browser default`.
- Setup page: optional `setupToken` field; API client adds `X-Setup-Token` header.
@@ -0,0 +1,39 @@
# Components - andreaslop-site-hosting
Numbering follows the brief (C1-C6); C7 is added by this design (setup token, requirements FR-U2-07).
## C2 WebsiteMode option (Core, `SlpModularCms.Core.Hosting`)
- **Purpose**: Per-client choice of how the public website is served.
- **Responsibilities**: `enum WebsiteMode { SpaFallback, PrerenderedPages }`; property `CmsHostOptions.WebsiteMode` (default `SpaFallback`).
- **Interface**: read by `CmsHost.ConfigureServices/ConfigurePipeline` and `StaticContentExtensions`.
## C3 Prerendered site serving (Core, `SlpModularCms.Core.Hosting.Website`, new folder)
Active only when `WebsiteMode = PrerenderedPages`.
| Part | Kind | Responsibility |
|---|---|---|
| C3a `WebsitePathResolver` | static, pure | Total function: (raw path, query string, `Func<string,bool> fileExists`) -> `WebsiteResolution` (`ServeFile(relativePath)`, `Redirect(location)`, `NotFound`). Contains every nginx-parity rule (canonical form, trailing slash, `/index`, traversal and backslash rejection, file-looking paths, reserved prefixes). No I/O, no clock, no logging. |
| C3b `WebsiteOptions` | options | `Website:NoIndex` (default false), validated at startup. |
| C3c `PrerenderedSiteMiddleware` | middleware | Adapter between HTTP and the resolver: supplies the file-exists predicate (confined to `wwwroot/web`), writes status, `Location`, `Cache-Control`, `X-Robots-Tag`, streams the file, serves `404.html` with status 404, answers `/robots.txt` when `NoIndex`. Never handles reserved prefixes. |
| C3d Website compression | registration | Built-in response compression for the text MIME types, applied only to non-reserved paths (`UseWhen`), so `/api/v1` and `/admin` responses are never compressed by this feature. |
## C4 StrictSite policy (Core, `SlpModularCms.Core.Hosting.Security`)
- **Purpose**: A third CSP policy for a prerendered public site, reproducing the site's current header byte for byte.
- **Responsibilities**: `CspPolicyCatalog.StrictSite` constant, added to `KnownPolicies`; `Build` produces the site CSP with `X-Frame-Options: DENY` and `Referrer-Policy: strict-origin-when-cross-origin`; `SecurityHeadersOptions` gains `AllowedSiteScriptOrigins` and `AllowedSiteConnectOrigins`, used **only** by `StrictSite` (decision Q1=A). `Strict` and `Relaxed` outputs are unchanged.
- **Check**: HSTS, `X-Content-Type-Options`, `Referrer-Policy` and the CSP appear on website pages, assets, 301s, 404 and robots.txt (FR-U1-09). The existing writer emits CSP/frame/referrer as "HTML-only" headers; whether non-HTML website responses also need them is settled in U1 Functional Design.
## C1 Client `SlpModularCms.Api.AndreaSlopFotografie` (Clients)
- **Purpose**: Deployable host for Andrea's instance.
- **Responsibilities**: thin `Program.cs` on `CmsHost` with `WebsiteMode.PrerenderedPages`; `.csproj` references the modules (Core, Identity, and Availability only if the admin needs it); three-file appsettings; own database connection string template (no password in repo); own dev port; `SecurityHeaders:DefaultPolicy = StrictSite` plus the site origin lists; `Website:NoIndex = true` for test.
## C5 Admin theme (frontend)
- **Purpose**: Per-site look of the admin, fixed at build time.
- **Responsibilities**: `frontend/themes/<name>/theme.css` overriding existing design tokens; theme assets (logo, favicon, self-hosted Marcellus and Jost); build-time selection by `VITE_THEME`; `VITE_DEFAULT_LANGUAGE` initial language (user choice still wins); unset variables reproduce today's admin.
## C6 CI/CD (Gitea workflows)
- **Purpose**: Build and deploy each client with its own admin build.
- **Responsibilities**: per-client admin build (`VITE_THEME`, `VITE_DEFAULT_LANGUAGE`, `VITE_APP_TITLE`), ARM64 publish of the new host, deploy to the test Pi using the existing atomic release switch, `wwwroot/web` outside the release directory; production path of `Api.SlpSoftware` untouched.
## C7 First-admin setup token (Identity module + frontend)
- **Purpose**: Stop a stranger from claiming the first administrator on a freshly deployed, publicly reachable instance.
- **Responsibilities**: `SetupOptions` (`Identity:Setup:Token`, optional); `ISetupTokenValidator` (constant-time compare, true when no token is configured); `SetupController.GetStatus` returns `tokenRequired`; `CreateOwner` requires header `X-Setup-Token` when configured; setup page in the frontend shows a token field only when `tokenRequired` is true (decision Q3=A). Existing hosts without the setting behave exactly as before.
@@ -0,0 +1,66 @@
# Services and Orchestration - andreaslop-site-hosting
No new domain services or database tables. Orchestration is host composition and one request pipeline.
## Host composition (`CmsHost`)
- `ConfigureServices`: `AddCmsSecurityHeaders` (now with site origin lists), `AddCmsWebsite` (only when `WebsiteMode = PrerenderedPages`). Identity registers `SetupOptions` and `ISetupTokenValidator` in its own module registration.
- `ConfigurePipeline` order (documented in `CmsHost`):
```mermaid
flowchart TD
A["Exception handler"] --> B["Security headers"]
B --> C["Rate limiter"]
C --> D["HTTPS redirection (no-op on plain HTTP)"]
D --> E["Admin static mount + /admin redirect"]
E --> F["Website: compression (non-reserved paths) + noindex"]
F --> G["Website resolver middleware (pages, assets, redirects, robots)"]
G --> H["CORS, module middleware, auth"]
H --> I["MapControllers (/api/v1)"]
I --> J["Health checks, Sentry tunnel"]
J --> K["Admin SPA fallback"]
K --> L["Website 404 (404.html, status 404)"]
classDef sec fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
classDef site fill:#63b3ed,stroke:#2b6cb0,stroke-width:1px,color:#000;
classDef api fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
class A,B,C,D sec;
class E,F,G,K,L site;
class H,I,J api;
```
Text alternative: security stages first (yellow), then the admin and website mounts (blue), then API routes (green); unknown website paths fall to 404 last, so API 404s are never replaced by the website page.
Notes:
- The resolver middleware passes reserved prefixes (`/admin`, `/api/v1`, `/health`) straight on, and passes on unknown paths **only** after API routes had a chance; the final 404 stage serves `404.html` with status 404 for non-reserved paths. Pages that resolve (`ServeFile`, `Redirect`) are answered in step G, before the API; this is safe because the pure resolver never resolves reserved prefixes.
- `SpaFallback` mode keeps today's pipeline untouched.
## Request flow (website page)
```mermaid
sequenceDiagram
box rgba(246,224,94,0.4) Client
participant B as Browser or proxy Pi
end
box rgba(99,179,237,0.4) Host
participant M as SiteMiddleware
participant R as PathResolver
participant F as wwwroot web
end
B->>M: GET /Over-Mij?x=1
M->>R: Resolve path, query, fileExists
R->>F: fileExists over-mij.html
F-->>R: true
R-->>M: Redirect /over-mij?x=1
M-->>B: 301 Location /over-mij?x=1 plus security headers
B->>M: GET /over-mij
M->>R: Resolve
R-->>M: ServeFile over-mij.html
M-->>B: 200 html, no-cache, compressed
```
Text alternative: the middleware asks the pure resolver, which uses a file-exists check; a non-canonical request gets one 301, then the canonical request is served as a file.
## Setup flow
Browser loads setup page -> `GET /Setup/status` -> `tokenRequired` decides whether the token field is shown -> `POST /Setup/owner` with `X-Setup-Token` -> `ISetupTokenValidator` -> existing `ISetupService.CreateInitialOwnerAsync`. Login rate limiting policy also covers the setup endpoints (verified in NFR Design).
## Build and deploy flow (C6)
CI: admin build per client (env: theme, language, title) -> copy into client `wwwroot/admin` -> `dotnet publish` (linux-arm64) -> scp to `releases/<id>` -> atomic switch of `current` -> restart user unit -> smoke checks (`/health`, `/api/v1/System/capabilities`, a website page). `wwwroot/web` is a symlink in `shared/`, so it survives every release.
@@ -0,0 +1,22 @@
# Unit Dependencies - andreaslop-site-hosting
| Unit | Depends on | Reason |
|---|---|---|
| U1 | existing Core | extends it additively |
| U2 | U1 | client uses `WebsiteMode.PrerenderedPages`, `StrictSite`, `Website:NoIndex` |
| U2 | requester "go" | hand-back gate |
```mermaid
flowchart LR
U1["U1 core-site-hosting"] --> H1["Hand-back + go from CMS & API"] --> U2["U2 andreaslop-client"] --> BT["Build and Test"] --> OP["Operations"]
classDef u fill:#f6e05e,stroke:#c05621,stroke-width:1px,color:#000;
classDef g fill:#d6bcfa,stroke:#553c9a,stroke-width:1px,color:#000;
classDef n fill:#9ae6b4,stroke:#2f855a,stroke-width:1px,color:#000;
class U1,U2 u;
class H1 g;
class BT,OP n;
```
Text alternative: U1, then the hand-back gate, then U2, then Build and Test and Operations.
Shared contract between units: configuration names (`WebsiteMode` in code, `Website:NoIndex`, `SecurityHeaders:DefaultPolicy=StrictSite`, `SecurityHeaders:AllowedSiteScriptOrigins`, `SecurityHeaders:AllowedSiteConnectOrigins`). U1 fixes these names; U2 only uses them.
@@ -0,0 +1,13 @@
# Requirement-to-Unit Map (User Stories skipped)
| Requirement | Unit |
|---|---|
| FR-U1-01 .. FR-U1-11 | U1 |
| FR-U2-01 client project, FR-U2-02 module set | U2 |
| FR-U2-03 theme | U2 |
| FR-U2-04 CI/CD, FR-U2-05 test deploy, FR-U2-06 Pi provisioning | U2 |
| FR-U2-07 setup token, FR-U2-08 auth unchanged | U2 |
| Security Baseline, PBT partial, per-unit build/test | both |
| Git rules (one branch, no push, PR after U2) | both |
All requirements are assigned to a unit.
@@ -0,0 +1,22 @@
# Units of Work - andreaslop-site-hosting
Terminology: both units are changes to the same deployable codebase ("Unit of Work" = planning/delivery slice), delivered on one branch, commits per unit.
## U1 core-site-hosting
- **Scope**: C2 WebsiteMode, C3 prerendered site serving (resolver, middleware, options, compression), C4 StrictSite policy and site origin lists, pipeline order, docs (`README.md`, `WEBSITE_WORKSPACE.md`).
- **Code locations**: `src/SlpModularCms.Core/Hosting/**` (+ `src/SlpModularCms.Core.Tests/**`).
- **Not touched**: `Api`, `Api.SlpSoftware` sources (only regression-tested), Identity, frontend, CI.
- **Construction stages**: Functional Design, NFR Requirements, NFR Design, Code Generation (Infrastructure Design skipped).
- **Done when**: requirements acceptance (U1) met, per-unit build and tests green, `Api`/`Api.SlpSoftware` regression green, hand-back note sent, **requester's "go" received**.
- **Commit(s)**: on `feature/andreaslop-site-hosting`; no push.
## U2 andreaslop-client
- **Scope**: C1 client project and solution entry (Clients), C5 theme and build variables, C7 setup token (Identity + setup page), C6 CI/CD, Pi manual-step list, test deploy (with Bryan's go, test only).
- **Code locations**: `src/SlpModularCms.Api.AndreaSlopFotografie/**`, `src/SlpModularCms.Modules.Identity/**` (+ tests), `frontend/**`, `.gitea/workflows/**`, `SlpModularCms.sln`, docs.
- **Construction stages**: NFR Requirements, NFR Design, Infrastructure Design, Code Generation (Functional Design skipped).
- **Starts**: only after U1 hand-back and the requester's "go".
- **Done when**: requirements acceptance (U2) met, hand-back note sent.
- **Commit(s)**: same branch; one PR after U2 when Bryan asks.
## Cross-unit
Build and Test (all units), then Operations (Deployment Setup, Monitoring Setup, Production Readiness for the test environment).