using System.Net;
using Microsoft.AspNetCore.Hosting.Server;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Titano.Server.Configuration;
namespace Titano.Server.Hosting;
///
/// Serves the embedded admin panel at /admin. Requests over plain HTTP from another machine are redirected to
/// the HTTPS listener, because the session cookie is Secure (BRIEF ยง14.2) and would not survive plain HTTP.
///
public static class AdminPanel
{
public static void Map(WebApplication app, ServerOptions options)
{
var files = new EmbeddedStaticFiles(typeof(AdminPanel).Assembly, "admin/");
var server = app.Services.GetRequiredService();
app.MapGet("/", () => Results.Redirect("/admin/"));
app.MapMethods("/admin/{**path}", ["GET", "HEAD"], async (HttpContext context, string? path) =>
{
if (HttpsLocation(context, options, server) is { } secure)
{
context.Response.Redirect(secure);
return;
}
// Relative asset URLs need the trailing slash.
if (!context.Request.Path.Value!.EndsWith('/') && string.IsNullOrEmpty(path))
{
context.Response.Redirect("/admin/");
return;
}
if (!await files.TryServeAsync(context, path ?? string.Empty)) context.Response.StatusCode = StatusCodes.Status404NotFound;
});
}
private static string? HttpsLocation(HttpContext context, ServerOptions options, IServer server)
{
if (context.Request.IsHttps || options.TlsMode == TlsMode.Proxy) return null;
if (context.Connection.RemoteIpAddress is { } remote && IPAddress.IsLoopback(remote)) return null;
foreach (var address in server.Features.Get()?.Addresses ?? [])
{
if (!address.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) continue;
var port = address[(address.LastIndexOf(':') + 1)..].TrimEnd('/');
return $"https://{context.Request.Host.Host}:{port}{context.Request.PathBase}{context.Request.Path}{context.Request.QueryString}";
}
return null;
}
}