Files
slp-modular-cms/src/SlpModularCms.Core/Hosting/StaticContentExtensions.cs
T

239 lines
9.9 KiB
C#

using System.Reflection;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.FileProviders;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using SlpModularCms.Core.Hosting.Website;
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>
/// <param name="app">The application.</param>
/// <param name="websiteMode">
/// In <see cref="WebsiteMode.PrerenderedPages"/> only the admin mount is registered here; the
/// website is served by <c>UseCmsPrerenderedSite</c> instead.
/// </param>
public static WebApplication UseCmsStaticContent(
this WebApplication app,
WebsiteMode websiteMode = WebsiteMode.SpaFallback)
{
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");
if (websiteMode == WebsiteMode.SpaFallback)
{
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);
if (websiteMode == WebsiteMode.SpaFallback)
{
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>
/// <param name="app">The application.</param>
/// <param name="websiteMode">
/// In <see cref="WebsiteMode.PrerenderedPages"/> the catch-all website fallback is NOT mapped: an
/// unknown path must be a real 404 (<c>MapCmsWebsiteNotFound</c>), never <c>index.html</c>.
/// </param>
public static WebApplication MapCmsSpaFallbacks(
this WebApplication app,
WebsiteMode websiteMode = WebsiteMode.SpaFallback)
{
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;
});
if (websiteMode == WebsiteMode.PrerenderedPages)
{
return app;
}
app.MapFallback("{*path:nonfile}", async context =>
{
if (File.Exists(websiteIndex))
{
// Website:KnownPaths (optional): only those paths are real pages; the rest is a real 404, still
// with the SPA shell as body so the app can render its own not-found page.
var known = context.RequestServices.GetService<IOptions<WebsiteOptions>>()?.Value.KnownPaths;
if (known is { Count: > 0 }
&& !known.Select(SpaSeoExtensions.NormalizePath).Contains(SpaSeoExtensions.NormalizePath(context.Request.Path.Value ?? "/")))
{
context.Response.StatusCode = StatusCodes.Status404NotFound;
}
context.Response.ContentType = "text/html; charset=utf-8";
// Modules fill marker comments in index.html (e.g. the current offerings); cached, with an ETag.
var injector = context.RequestServices.GetService<HtmlMarkerInjector>();
var page = injector is null
? null
: await injector.GetAsync(websiteIndex, context.Request, context.RequestAborted);
if (page is not null)
{
await InjectedPageWriter.WriteAsync(context, page, "text/html; charset=utf-8");
return;
}
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);
}
}