Adds SlpModularCms.Api.SlpSoftware and extracts shared CmsHost composition
Continuous Integration / config (pull_request) Successful in 11s
Continuous Integration / changes (pull_request) Successful in 21s
Continuous Integration / backend-build (pull_request) Successful in 6m10s
Continuous Integration / vulnerability-scan (pull_request) Successful in 4m59s
Continuous Integration / frontend-prepare (pull_request) Successful in 1m27s
Continuous Integration / backend-test (pull_request) Failing after 7m48s
Continuous Integration / frontend-build (pull_request) Successful in 2m5s
Continuous Integration / frontend-test (pull_request) Successful in 4m24s
Continuous Integration / frontend-lint (pull_request) Successful in 2m0s
Continuous Integration / publish-test (pull_request) Skipped
Continuous Integration / publish-production (pull_request) Skipped
Continuous Integration / deploy-test (pull_request) Skipped
Continuous Integration / deploy-production (pull_request) Skipped

Unit 1 of the slpsoftware-api feature (FR-1/FR-2/FR-3): a new Client project
in the Clients solution folder, intended to eventually become the deployed
API for test.slpsoftware.nl/slpsoftware.nl, hosting the same four modules as
SlpModularCms.Api plus a future Offerings module.

- Extracts SlpModularCms.Api/Program.cs's hosting-pipeline composition into
  SlpModularCms.Core.Hosting.CmsHost (ConfigureServices/ConfigurePipeline),
  shared by both Client projects so they cannot drift apart
- Moves StaticContentExtensions.cs + WebsitePlaceholder.html from Api into
  Core, since CmsHost cannot live in Api but Core cannot depend on Api
- Adds SlpModularCms.Api.SlpSoftware with its own isolated local dev database
  and dev ports (5286/7223, distinct from Api's and Api.Slave's)
- Adds SlpModularCms.Api.Tests with WebApplicationFactory-based pipeline
  regression tests (security headers, health check, SPA fallback, rate
  limiting), scoped to Api per NFR Design
- Adds a frontend dev:slpsoftware pnpm script mirroring dev:slave
- Fixes GlobalExceptionHandler logging routine 401s (e.g. an expired/missing
  refresh token) as unhandled errors -- pre-existing, unrelated to this
  feature's own scope, found while testing the new instance

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FWyStNL2ZsjrS7FLd7xvvN
This commit is contained in:
2026-08-02 01:28:39 +02:00
co-authored by Claude Sonnet 5
parent dcc82cdf62
commit fa389e42ee
51 changed files with 3119 additions and 127 deletions
@@ -27,15 +27,31 @@ public class GlobalExceptionHandler : IExceptionHandler
CancellationToken cancellationToken)
{
var traceId = Activity.Current?.Id ?? httpContext.TraceIdentifier;
_logger.LogError(
exception,
"Ongehandled exception opgetreden op {MachineName}. TraceId: {TraceId}",
Environment.MachineName,
traceId);
var (statusCode, title) = MapException(exception);
// Only a genuinely unmapped exception (falls through to 500) is unexpected and worth an
// Error-level log with a full stack trace. A mapped exception (e.g. UnauthorizedException
// -> 401 on an invalid/missing refresh token) is routine, expected request handling — every
// occurrence being logged as an "unhandled exception" made ordinary auth-flow noise
// indistinguishable from a real defect, in both the console and Sentry.
if (statusCode >= StatusCodes.Status500InternalServerError)
{
_logger.LogError(
exception,
"Onbehandelde fout opgetreden op {MachineName}. TraceId: {TraceId}",
Environment.MachineName,
traceId);
}
else
{
_logger.LogWarning(
exception,
"Verwachte fout ({StatusCode}) afgehandeld op {MachineName}. TraceId: {TraceId}",
statusCode,
Environment.MachineName,
traceId);
}
var problemDetails = new ProblemDetails
{
Status = statusCode,
+149
View File
@@ -0,0 +1,149 @@
using System.Text.Json.Serialization;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using SlpModularCms.Core.Hosting.Health;
using SlpModularCms.Core.Hosting.Observability;
using SlpModularCms.Core.Hosting.Security;
using Scalar.AspNetCore;
namespace SlpModularCms.Core.Hosting;
/// <summary>
/// Shared hosting composition for every Client project (<c>Api</c>, <c>Api.SlpSoftware</c>, ...).
/// </summary>
/// <remarks>
/// Extracted from what was originally <c>SlpModularCms.Api/Program.cs</c> in full, so that adding a
/// second (and any future) Client project does not mean duplicating this composition — a change
/// made here applies to every Client project automatically. The two methods mirror the two halves
/// of a minimal ASP.NET Core <c>Program.cs</c>: service registration (before <c>builder.Build()</c>)
/// and pipeline configuration (after it). Each caller's own <c>Program.cs</c> keeps only the two
/// lines that must stay per-project: constructing the <see cref="WebApplicationBuilder"/> itself and
/// loading that project's own <c>appsettings.local.json</c>.
/// </remarks>
public static class CmsHost
{
/// <summary>
/// Registers every service a Client project needs: logging, Sentry, module discovery and
/// registration, core infrastructure, and MVC controllers.
/// </summary>
/// <returns>
/// The <see cref="ModuleOrchestrator"/> used during registration, so the caller can pass the
/// same instance into <see cref="ConfigurePipeline"/> after <c>builder.Build()</c>.
/// </returns>
public static ModuleOrchestrator ConfigureServices(WebApplicationBuilder builder, CmsHostOptions options)
{
// Logging FIRST, so a problem initialising Sentry below is itself logged. Puts the W3C trace id
// into the scope of every entry from every category — the correlation id that also travels to
// the slave via traceparent and appears as `traceId` in ProblemDetails responses.
builder.Logging.AddCmsLogging(builder.Environment);
// Then Sentry. Does nothing at all when no DSN is configured, which is a normal, fully
// supported state rather than an error.
builder.WebHost.UseCmsSentry(builder.Configuration);
// 1. Initialize Module Orchestrator
var loggerFactory = LoggerFactory.Create(lb => lb.AddConsole());
var orchestrator = new ModuleOrchestrator(loggerFactory.CreateLogger<ModuleOrchestrator>());
orchestrator.DiscoverModules();
// 2. Add Core Infrastructure
builder.Services.AddCoreInfrastructure(builder.Configuration);
builder.Services.AddCmsCors(builder.Configuration);
builder.Services.AddCmsRateLimiting(builder.Configuration);
builder.Services.AddCmsHealthChecks();
builder.Services.AddCmsSecurityHeaders(builder.Configuration);
builder.Services.AddCmsObservability(builder.Configuration);
// Registered BEFORE module services: modules must not configure Data Protection themselves,
// because a later registration would override this persistent key store (see
// DataProtectionExtensions).
builder.Services.AddCmsDataProtection();
// 3. Add Module Services
orchestrator.RegisterModuleServices(builder.Services);
builder.Services.AddSingleton(orchestrator);
// 4. Global Controller Configuration with Conventions
builder.Services.AddControllers(controllerOptions =>
{
controllerOptions.Conventions.Add(new ApiPrefixConvention("api/v1"));
})
.AddJsonOptions(jsonOptions =>
{
jsonOptions.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter());
});
return orchestrator;
}
/// <summary>
/// Configures the HTTP pipeline every Client project needs, in the exact order the original
/// <c>Api/Program.cs</c> used — that order encodes real constraints, documented inline below.
/// </summary>
public static void ConfigurePipeline(WebApplication app, ModuleOrchestrator orchestrator, CmsHostOptions options)
{
// Bring the Core schema up to date before serving any traffic. Runs before the module
// middleware below, because the Data Protection keys table lives in this context and the
// modules resolve an IDataProtector as soon as they start. Fails fast: a host that cannot
// migrate does not start, so /health goes silent and monitoring goes red — which is exactly
// what makes a liveness-only health check trustworthy.
app.MigrateCoreDatabase();
// 5. Global Exception Handling
app.UseExceptionHandler();
// First thing INSIDE the exception handler, and before the static-file middleware below.
// Both directions matter: the exception handler re-executes the pipeline from within itself,
// so anything registered outside it never sees the ProblemDetails response; and static files
// short-circuit the pipeline, so anything after them is invisible to the public website —
// which is almost all of the HTML this host serves.
app.UseCmsSecurityHeaders();
app.UseRateLimiter();
// 6. Configure Pipeline
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
app.MapScalarApiReference();
}
app.UseHttpsRedirection();
// Serve the public website ('/') and the CMS admin SPA ('/admin') from wwwroot.
// wwwroot/web/index.html + assets -> public website (built and deployed separately, not part of this repo)
// wwwroot/admin/index.html + assets -> CMS admin build (see frontend/, copied in on publish)
// Registered before the module middleware below: static files short-circuit the pipeline, so
// anything that must observe them has to come first.
app.UseCmsStaticContent();
app.UseCors();
// 7. Use Module Middleware
orchestrator.UseModules(app);
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
// Infrastructure liveness. Deliberately outside /api/v1 and on the availability gate's bypass
// list: this reports whether the process is alive, which is a different question from whether
// the CMS is switched on (/api/v1/Availability/status) or which modules it carries
// (/api/v1/System/capabilities). Those are CMS domain state and must not be used for monitoring.
app.MapCmsHealthChecks();
// Forwards browser Sentry envelopes through this origin, because ad blockers block requests to
// Sentry domains outright. Mapped before the SPA catch-all below, and deliberately NOT on the
// availability gate's bypass list: if the instance is switched off, losing admin-SPA error
// reports is acceptable, and that is one fewer anonymous outbound-capable endpoint reachable on
// a disabled instance.
app.MapSentryTunnel();
// SPA fallbacks so client-side routes (e.g. /admin/dashboard) resolve to the right index.html
// instead of 404ing. The "nonfile" constraint keeps genuinely missing assets (e.g. /admin/assets/x.js) as 404s.
app.MapCmsSpaFallbacks();
}
}
@@ -0,0 +1,13 @@
namespace SlpModularCms.Core.Hosting;
/// <summary>
/// Extension point for future per-project differences between <c>CmsHost</c> callers.
/// </summary>
/// <remarks>
/// Deliberately empty today — both current Client projects (<c>Api</c>, <c>Api.SlpSoftware</c>)
/// pass identical values. Introduced now so a future real difference is a property added here,
/// not a signature change to <see cref="CmsHost.ConfigureServices"/>/<see cref="CmsHost.ConfigurePipeline"/>.
/// </remarks>
public sealed class CmsHostOptions
{
}
@@ -0,0 +1,188 @@
using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
namespace SlpModularCms.Core.Hosting;
/// <summary>
/// Serves the two independent front-ends this host carries.
/// </summary>
/// <remarks>
/// Shared hosting typically allows only one site or application pool, so this single process
/// serves everything:
/// <list type="bullet">
/// <item><description><c>/</c> — the customer's public website, from <c>wwwroot/web/</c>. Built and
/// deployed separately; it is NOT part of this repository and must survive every CMS deploy.</description></item>
/// <item><description><c>/admin</c> — the CMS admin SPA, from <c>wwwroot/admin/</c>, produced by
/// <c>dotnet publish</c>.</description></item>
/// </list>
/// Each mount gets its own file provider so neither can ever serve files belonging to the other,
/// and so each can later carry its own headers or caching without disturbing the other.
/// </remarks>
public static class StaticContentExtensions
{
/// <summary>Directory under the web root holding the customer's public website.</summary>
public const string WebsiteDirectoryName = "web";
/// <summary>Directory under the web root holding the admin SPA.</summary>
public const string AdminDirectoryName = "admin";
/// <summary>Request path the admin SPA is mounted at.</summary>
public const string AdminRequestPath = "/admin";
private const string PlaceholderResourceName = "SlpModularCms.Core.Hosting.WebsitePlaceholder.html";
/// <summary>
/// Registers both static mounts and the <c>/admin</c> trailing-slash redirect.
/// Must be called BEFORE any middleware that needs to observe static responses, because
/// static files short-circuit the pipeline.
/// </summary>
public static WebApplication UseCmsStaticContent(this WebApplication app)
{
var webRoot = app.Environment.WebRootPath
?? Path.Combine(app.Environment.ContentRootPath, "wwwroot");
var adminRoot = Path.Combine(webRoot, AdminDirectoryName);
var websiteRoot = Path.Combine(webRoot, WebsiteDirectoryName);
var logger = app.Services.GetRequiredService<ILoggerFactory>()
.CreateLogger(typeof(StaticContentExtensions).FullName!);
WarnIfMissing(logger, adminRoot, "admin SPA");
WarnIfMissing(logger, websiteRoot, "public website");
// A request for exactly "/admin" must become "/admin/", or the SPA — built with
// base '/admin/' — resolves its relative asset references one level too high and
// fails in a way that looks like a broken deployment.
app.Use(async (context, next) =>
{
if (context.Request.Path.Equals(AdminRequestPath, StringComparison.OrdinalIgnoreCase))
{
var target = $"{AdminRequestPath}/{context.Request.QueryString}";
context.Response.Redirect(target, permanent: true);
return;
}
await next();
});
// The admin mount is registered FIRST. Registered the other way around, a request for
// /admin/... would be resolved against the website root.
RegisterMount(app, adminRoot, AdminRequestPath);
RegisterMount(app, websiteRoot, requestPath: string.Empty);
return app;
}
/// <summary>
/// Maps the SPA fallbacks for both mounts.
/// </summary>
/// <remarks>
/// The <c>nonfile</c> constraint on both routes is deliberate: a request for a path that
/// looks like a file (has an extension) and does not exist must stay a 404. Serving HTML
/// for a missing script would turn a clear "asset is missing" into a confusing parse error.
/// </remarks>
public static WebApplication MapCmsSpaFallbacks(this WebApplication app)
{
var webRoot = app.Environment.WebRootPath
?? Path.Combine(app.Environment.ContentRootPath, "wwwroot");
var adminIndex = Path.Combine(webRoot, AdminDirectoryName, "index.html");
var websiteIndex = Path.Combine(webRoot, WebsiteDirectoryName, "index.html");
app.MapFallback($"{AdminRequestPath}/{{*path:nonfile}}", async context =>
{
if (File.Exists(adminIndex))
{
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.SendFileAsync(adminIndex);
return;
}
context.Response.StatusCode = StatusCodes.Status404NotFound;
});
app.MapFallback("{*path:nonfile}", async context =>
{
if (File.Exists(websiteIndex))
{
context.Response.ContentType = "text/html; charset=utf-8";
await context.Response.SendFileAsync(websiteIndex);
return;
}
// No website deployed yet. Serving the placeholder rather than a 404 makes a fresh
// installation self-explanatory and doubles as proof the CMS itself is running.
await WritePlaceholderAsync(context);
});
return app;
}
private static void RegisterMount(WebApplication app, string physicalRoot, string requestPath)
{
// Tolerating a missing directory is required, not defensive: a fresh deployment has no
// wwwroot/web/ until a website workspace deploys into it, and the CMS must still start
// and serve /admin and /api/v1.
if (!Directory.Exists(physicalRoot))
{
return;
}
var provider = new PhysicalFileProvider(physicalRoot);
app.UseDefaultFiles(new DefaultFilesOptions
{
FileProvider = provider,
RequestPath = requestPath
});
app.UseStaticFiles(new StaticFileOptions
{
FileProvider = provider,
RequestPath = requestPath
// Directory browsing is not enabled — a request for a directory resolves to its
// default file or falls through to the fallback rules, never to a file listing.
});
}
private static async Task WritePlaceholderAsync(HttpContext context)
{
context.Response.StatusCode = StatusCodes.Status200OK;
context.Response.ContentType = "text/html; charset=utf-8";
// Embedded in the assembly rather than placed in wwwroot/web/, because that directory is
// owned and overwritten by a website workspace: a file there would be deleted by the first
// real website deployment, or mistaken for part of the customer's site.
await using var stream = typeof(StaticContentExtensions).Assembly
.GetManifestResourceStream(PlaceholderResourceName);
if (stream is null)
{
await context.Response.WriteAsync("<!doctype html><title>Nog geen website geplaatst</title>" +
"<p>Er staat hier nog geen website. Beheer via <a href=\"/admin/\">/admin/</a>.</p>");
return;
}
await stream.CopyToAsync(context.Response.Body);
}
private static void WarnIfMissing(ILogger logger, string path, string description)
{
if (Directory.Exists(path))
{
return;
}
// Normal on a fresh installation, but on a running production instance it means the
// content has disappeared — worth being visible in Sentry without blocking startup.
logger.LogWarning(
"Static content directory for the {Description} was not found at {Path}. " +
"The application will start, but this path will not serve any files until content is deployed there.",
description,
path);
}
}
@@ -0,0 +1,57 @@
<!doctype html>
<html lang="nl">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex, nofollow">
<title>Nog geen website geplaatst</title>
<style>
:root { color-scheme: light dark; }
body {
margin: 0;
min-height: 100svh;
display: grid;
place-items: center;
padding: 2rem;
font-family: system-ui, -apple-system, "Segoe UI", sans-serif;
line-height: 1.6;
background: #fafafa;
color: #1a1a1a;
}
@media (prefers-color-scheme: dark) {
body { background: #141414; color: #ededed; }
code { background: #262626; color: #141414; }
a { color: #ff6b6b; }
}
main { max-width: 34rem; }
h1 { font-size: 1.5rem; margin: 0 0 1rem; }
p { margin: 0 0 1rem; }
code {
background: #ececec;
color: #1a1a1a;
padding: 0.15em 0.4em;
border-radius: 4px;
font-family: ui-monospace, "Cascadia Code", Consolas, monospace;
font-size: 0.9em;
}
a { color: #ac0000; }
.muted { font-size: 0.9rem; opacity: 0.75; }
</style>
</head>
<body>
<main>
<h1>Er staat hier nog geen website</h1>
<p>
Het CMS draait, maar er is nog geen publieke website geplaatst. De website
wordt apart aangeleverd en hoort in de map <code>wwwroot/web/</code> te staan,
met een <code>index.html</code> in de hoofdmap daarvan.
</p>
<p>
Beheerders kunnen inloggen via <a href="/admin/">/admin/</a>.
</p>
<p class="muted">
Deze pagina wordt automatisch vervangen zodra de website is geplaatst.
</p>
</main>
</body>
</html>
@@ -53,6 +53,21 @@
-->
<PackageReference Include="Microsoft.OpenApi" Version="2.11.0" />
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.10" />
<!-- CmsHost.ConfigurePipeline calls MapScalarApiReference() (Development-only) — moved here
from SlpModularCms.Api along with the rest of the composed pipeline. -->
<PackageReference Include="Scalar.AspNetCore" Version="2.16.3" />
</ItemGroup>
<!--
Served at '/' by StaticContentExtensions.UseCmsStaticContent when no public website has been
deployed into wwwroot/web/ yet. Embedded rather than shipped as a file under wwwroot/web/,
because that directory is owned and overwritten by a separate website workspace — a file there
would be deleted by the first real website deployment, or mistaken for part of the customer's
site. Moved here from SlpModularCms.Api so every Client project (Api, Api.SlpSoftware) shares
the same hosting composition via CmsHost.
-->
<ItemGroup>
<EmbeddedResource Include="Hosting\WebsitePlaceholder.html" />
</ItemGroup>
</Project>