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
@@ -0,0 +1,14 @@
using SlpModularCms.Core.Hosting;
var builder = WebApplication.CreateBuilder(args);
// Load local developer overrides
builder.Configuration.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true);
var orchestrator = CmsHost.ConfigureServices(builder, new CmsHostOptions());
var app = builder.Build();
CmsHost.ConfigurePipeline(app, orchestrator, new CmsHostOptions());
app.Run();
@@ -0,0 +1,25 @@
{
"$schema": "https://json.schemastore.org/launchsettings.json",
"profiles": {
"http": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "http://localhost:5286",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"launchUrl": "scalar"
},
"https": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"applicationUrl": "https://localhost:7223;http://localhost:5286",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"launchUrl": "scalar"
}
}
}
@@ -0,0 +1,34 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Asp.Versioning.Mvc" Version="10.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.9" />
<PackageReference Include="Microsoft.AspNetCore.OpenApi" Version="10.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.9">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Scalar.AspNetCore" Version="2.16.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Availability\SlpModularCms.Modules.Availability.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Identity\SlpModularCms.Modules.Identity.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Master\SlpModularCms.Modules.Master.csproj" />
</ItemGroup>
<!--
The admin SPA (frontend/) is served at /admin (see CmsHost.ConfigurePipeline) from
wwwroot/admin, but is deliberately NOT built by an MSBuild target hooked to Build/Publish
here — see SlpModularCms.Api.csproj for the full explanation (files must exist on disk
before dotnet publish/build runs; the CI workflow handles this as its own step).
-->
</Project>
@@ -0,0 +1,55 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"ConnectionStrings": {
// Own, isolated local dev database (Infrastructure Design decision Q1 = B) — deliberately
// separate from SlpModularCms.Api's local database, so developing/testing this project
// (and the future Offerings module) never touches Api's local data, or vice versa.
"DefaultConnection": "Server=127.0.0.1;Port=3306;Database=SlpModularCmsSlpSoftwareDev;Uid=root;Pwd=<your-local-mariadb-password>"
},
"JwtSettings": {
"Secret": "SuperSecretKeyForDevelopmentOnly_MustBeLongerThan32Bytes!",
"Issuer": "SlpModularCms",
"Audience": "SlpModularCmsPortal",
"ExpiryMinutes": 60,
"RefreshTokenExpiryDays": 7,
"CookieSameSite": "None"
},
"Availability": {
"CircuitBreakerSeconds": 30,
"StatusCacheSeconds": 1
},
"MasterPolling": {
"PollIntervalSeconds": 15,
"FailOpenAfterMinutes": 2,
"HttpTimeoutSeconds": 5
},
"MasterModule": {
"IntegrityCheckIntervalMinutes": 60,
"HttpTimeoutSeconds": 10,
"MasterUrl": "https://localhost:7223"
},
"Cors": {
// Port 5175, not 5173: that's Api's own frontend dev port (see frontend/package.json's
// plain `pnpm dev`). This project is reached via `pnpm dev:slpsoftware`, which runs the
// frontend dev server on 5175 (see .env.slpsoftware.local / package.json).
"AllowedOrigins": [
"http://localhost:5175",
"https://localhost:5175"
]
},
"RateLimiting": {
"Login": {
"PermitLimit": 100,
"WindowSeconds": 60
},
"Refresh": {
"PermitLimit": 500,
"WindowSeconds": 60
}
}
}
@@ -0,0 +1,75 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Information",
// Pinned at Warning deliberately. At Information, EF prints every SQL statement INCLUDING
// parameter values, and the login path passes a normalised email address through it.
"Microsoft.EntityFrameworkCore.Database.Command": "Warning"
}
},
"AllowedHosts": "*",
"ConnectionStrings": {
"DefaultConnection": "Server=<production-db-host>;Port=3306;Database=SlpSoftware<Env>;Uid=<db-user>;Pwd=<db-password>"
},
"JwtSettings": {
"Secret": "<secure-long-random-secret-key-from-env>",
"Issuer": "SlpModularCms",
"Audience": "SlpModularCmsPortal",
"ExpiryMinutes": 60,
"RefreshTokenExpiryDays": 7
},
"Availability": {
"CircuitBreakerSeconds": 30,
"StatusCacheSeconds": 1
},
"MasterModule": {
"IntegrityCheckIntervalMinutes": 60,
"HttpTimeoutSeconds": 10,
"MasterUrl": "<public-url-of-this-master-instance>"
},
"MasterPolling": {
"PollIntervalSeconds": 30,
"FailOpenAfterMinutes": 5,
"HttpTimeoutSeconds": 5
},
"Cors": {
"AllowedOrigins": []
},
"RateLimiting": {
"Login": {
"PermitLimit": 5,
"WindowSeconds": 60
},
"Refresh": {
"PermitLimit": 20,
"WindowSeconds": 60
},
"SentryTunnel": {
"PermitLimit": 60,
"WindowSeconds": 60
}
},
"SecurityHeaders": {
"Enabled": true,
"DefaultPolicy": "Relaxed",
"PathPolicies": [
{ "PathPrefix": "/admin", "Policy": "Strict" },
{ "PathPrefix": "/api/v1", "Policy": "Strict" },
{ "PathPrefix": "/health", "Policy": "Strict" }
],
"AllowedScriptOrigins": [],
"AllowedConnectOrigins": []
},
"Observability": {
// Supplied per environment as Observability__SentryDsn. Empty means Sentry is skipped
// entirely and console logging continues — a normal, supported state, not an error.
"SentryDsn": "",
// Falls back to ASPNETCORE_ENVIRONMENT when empty.
"Environment": "",
// Sentry's free plan counts transactions against the same quota as errors, and this setup's
// value is in errors rather than performance traces.
"TracesSampleRate": 0.1,
"TunnelMaxPayloadBytes": 204800
}
}
@@ -0,0 +1,106 @@
using System.Net;
using FluentAssertions;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
namespace SlpModularCms.Api.Tests;
/// <summary>
/// Regression guard for the hosting pipeline extracted into <c>CmsHost</c> (NFR-CS-01).
/// </summary>
/// <remarks>
/// Requires a reachable local MariaDB matching <c>SlpModularCms.Api/appsettings.Development.json</c>
/// (the same one a developer needs to run <c>SlpModularCms.Api</c> locally, per the root README) —
/// <c>CmsHost.ConfigurePipeline</c> runs a startup database migration before any endpoint is
/// reachable, so there is no way to exercise the real pipeline without it.
/// </remarks>
public class ApiWebApplicationFactory : WebApplicationFactory<Program>
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
// Development, not the default: the Production connection string in appsettings.json is a
// placeholder host, and the startup migration would fail before any endpoint could be
// tested. This also means Strict-Transport-Security is deliberately absent in these tests
// — see SecurityHeadersMiddleware's constructor comment — which is asserted below, not
// worked around.
builder.UseEnvironment("Development");
}
}
public class PipelineTests : IClassFixture<ApiWebApplicationFactory>
{
private readonly ApiWebApplicationFactory _factory;
public PipelineTests(ApiWebApplicationFactory factory)
{
_factory = factory;
}
[Fact]
public async Task Health_endpoint_is_reachable()
{
var client = _factory.CreateClient();
var response = await client.GetAsync("/health");
response.IsSuccessStatusCode.Should().BeTrue();
}
[Fact]
public async Task Html_response_carries_the_required_security_headers()
{
var client = _factory.CreateClient();
// A non-file, non-admin path with no website deployed falls through to the built-in
// placeholder (StaticContentExtensions.WritePlaceholderAsync) — an HTML response that does
// not depend on any built frontend/admin assets being present in this test run.
var response = await client.GetAsync("/some-page-that-does-not-exist");
response.Content.Headers.ContentType?.MediaType.Should().Be("text/html");
response.Headers.TryGetValues("X-Content-Type-Options", out _).Should().BeTrue();
response.Headers.TryGetValues("Content-Security-Policy", out _).Should().BeTrue();
response.Headers.TryGetValues("X-Frame-Options", out _).Should().BeTrue();
response.Headers.TryGetValues("Referrer-Policy", out _).Should().BeTrue();
// Deliberately NOT asserting presence: SecurityHeadersMiddleware intentionally skips HSTS
// in Development (localhost is shared with every other local project), so its ABSENCE
// here is the correct, tested behavior, not an oversight.
response.Headers.TryGetValues("Strict-Transport-Security", out _).Should().BeFalse();
}
[Fact]
public async Task Admin_spa_fallback_returns_not_found_when_no_admin_build_is_present()
{
var client = _factory.CreateClient();
// No frontend/dist build exists in this test run, so the admin mount's fallback correctly
// 404s rather than serving something else — this proves the /admin fallback route itself
// is registered and reachable (a broken registration, or the wrong ordering relative to
// the website's own fallback, would surface as a different status code or as the website
// placeholder being served under /admin instead).
var response = await client.GetAsync("/admin/some-page-that-does-not-exist");
response.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public async Task Sentry_tunnel_rate_limiter_engages_after_the_configured_permit_limit()
{
var client = _factory.CreateClient();
// Must track RateLimiting:SentryTunnel:PermitLimit in SlpModularCms.Api/appsettings.json.
const int permitLimit = 60;
HttpResponseMessage? last = null;
for (var i = 0; i < permitLimit + 1; i++)
{
last = await client.PostAsync("/sentry-tunnel", new ByteArrayContent([]));
}
// The request beyond the permit limit, within the same fixed window, must be rejected —
// regardless of whether a Sentry DSN is configured (an unconfigured DSN 404s every
// request instead, which would otherwise mask a rate limiter that silently stopped
// engaging).
last!.StatusCode.Should().Be(HttpStatusCode.TooManyRequests);
}
}
@@ -0,0 +1,38 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="coverlet.collector" Version="6.0.4" />
<PackageReference Include="FluentAssertions" Version="8.10.0" />
<!-- Provides WebApplicationFactory<TEntryPoint>, used to test the real, composed HTTP pipeline
rather than individual option/handler classes in isolation (NFR-CS-01). -->
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="10.0.9" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.14.1" />
<PackageReference Include="xunit" Version="2.9.3" />
<PackageReference Include="xunit.runner.visualstudio" Version="3.1.4" />
</ItemGroup>
<ItemGroup>
<Using Include="Xunit" />
</ItemGroup>
<ItemGroup>
<!--
Targets SlpModularCms.Api specifically (Infrastructure/NFR Design decision Q1 = C) — the
shared CmsHost composition is exercised through this project; SlpModularCms.Api.SlpSoftware
is not separately pipeline-tested in this unit.
-->
<ProjectReference Include="..\SlpModularCms.Api\SlpModularCms.Api.csproj" />
</ItemGroup>
</Project>
+2 -106
View File
@@ -1,118 +1,14 @@
using SlpModularCms.Api.Extensions;
using SlpModularCms.Core.Hosting;
using SlpModularCms.Core.Hosting.Health;
using SlpModularCms.Core.Hosting.Observability;
using SlpModularCms.Core.Hosting.Security;
using Scalar.AspNetCore;
var builder = WebApplication.CreateBuilder(args);
// Load local developer overrides
builder.Configuration.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: true);
// 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(options =>
{
options.Conventions.Add(new ApiPrefixConvention("api/v1"));
})
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.Converters.Add(new System.Text.Json.Serialization.JsonStringEnumConverter());
});
var orchestrator = CmsHost.ConfigureServices(builder, new CmsHostOptions());
var app = builder.Build();
// 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();
CmsHost.ConfigurePipeline(app, orchestrator, new CmsHostOptions());
app.Run();
@@ -17,16 +17,6 @@
<PackageReference Include="Scalar.AspNetCore" Version="2.16.3" />
</ItemGroup>
<!--
Served at '/' 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.
-->
<ItemGroup>
<EmbeddedResource Include="Extensions\WebsitePlaceholder.html" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\SlpModularCms.Core\SlpModularCms.Core.csproj" />
<ProjectReference Include="..\SlpModularCms.Modules.Availability\SlpModularCms.Modules.Availability.csproj" />
@@ -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
{
}
@@ -1,10 +1,11 @@
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.Api.Extensions;
namespace SlpModularCms.Core.Hosting;
/// <summary>
/// Serves the two independent front-ends this host carries.
@@ -32,7 +33,7 @@ public static class StaticContentExtensions
/// <summary>Request path the admin SPA is mounted at.</summary>
public const string AdminRequestPath = "/admin";
private const string PlaceholderResourceName = "SlpModularCms.Api.Extensions.WebsitePlaceholder.html";
private const string PlaceholderResourceName = "SlpModularCms.Core.Hosting.WebsitePlaceholder.html";
/// <summary>
/// Registers both static mounts and the <c>/admin</c> trailing-slash redirect.
@@ -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>