The pages built so far now live inside the shell of the mockups instead of the M0 placeholder, every interface text comes from Resources/it-IT, and each user keeps their own look and start page. - Shell: top bar, collapsible side menu with fly-out sub-menus, status bar and tabs that keep each page alive (page type and route values per tab, so a tab never shows another page); at most 12 tabs, least-used clean tab evicted. - One shortcut table with Alt variants for the combinations browsers keep (Ctrl+W, Ctrl+Tab, Ctrl+N); command palette for pages and commands. - ITexts over embedded JSON; tests forbid literal texts in .razor components and check that every key used exists. - User settings in sys_user_settings / user_settings; theme written on the server; profile page with live preview, start page, sessions and shortcuts. - Home, coming-soon pages for later milestones, localized sign-in and error pages; ADR 0020; wiki, CHANGELOG, STATUS and data model updated. Refs #25 #26 #31 #33 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
176 lines
8.3 KiB
C#
176 lines
8.3 KiB
C#
using Khaemhat.Application.Configuration;
|
|
using Khaemhat.Application.Instance;
|
|
using Khaemhat.Application.Security;
|
|
using Khaemhat.Core.Common;
|
|
using Khaemhat.Infrastructure.Logging;
|
|
using Khaemhat.Infrastructure.Security;
|
|
using Khaemhat.Web.Components;
|
|
using Khaemhat.Web.Security;
|
|
using Microsoft.AspNetCore.Antiforgery;
|
|
using Microsoft.AspNetCore.Authentication;
|
|
using Microsoft.AspNetCore.Authorization;
|
|
using Microsoft.AspNetCore.Components.Authorization;
|
|
using Microsoft.AspNetCore.DataProtection;
|
|
using Microsoft.AspNetCore.DataProtection.KeyManagement;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace Khaemhat.Web.Hosting;
|
|
|
|
/// <summary>
|
|
/// Builds the Khaemhat web host: one process per instance (ADR 0001), Blazor Interactive Server (ADR 0003).
|
|
/// Kept apart from <c>Program.cs</c> so tests can start the real host on a free port.
|
|
/// </summary>
|
|
public static class KhaemhatApp
|
|
{
|
|
/// <summary>Creates the configured application, ready to run.</summary>
|
|
/// <param name="args">Command-line arguments (ASP.NET Core host conventions, e.g. <c>--urls</c>; also <c>--KHAEMHAT_*=value</c>).</param>
|
|
/// <returns>The application.</returns>
|
|
/// <exception cref="ConfigurationException">The <c>KHAEMHAT_*</c> variables are missing or not valid.</exception>
|
|
public static WebApplication Build(string[] args)
|
|
{
|
|
// ApplicationName pins the static web assets manifest to this assembly, also when tests host the app.
|
|
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
|
|
{
|
|
Args = args,
|
|
ApplicationName = typeof(KhaemhatApp).Assembly.GetName().Name,
|
|
});
|
|
|
|
// The variables of SPEC §6, with the _FILE variants of ADR 0014; any problem stops the start with every message.
|
|
var options = new EnvironmentConfigurationReader(name => builder.Configuration[name]).Read();
|
|
options.EnsureValid();
|
|
ApplyHostVariables(builder, options, args);
|
|
|
|
// One pipeline (SPEC §9.5): JSON lines on stdout outside development, and the database sink everywhere.
|
|
var logSink = new DbLogSink();
|
|
if (!builder.Environment.IsDevelopment())
|
|
{
|
|
builder.Logging.ClearProviders();
|
|
builder.Logging.AddJsonConsole(o =>
|
|
{
|
|
o.IncludeScopes = true;
|
|
o.UseUtcTimestamp = true;
|
|
o.TimestampFormat = "yyyy-MM-ddTHH:mm:ss.fffZ";
|
|
});
|
|
}
|
|
|
|
builder.Logging.AddProvider(new DbLoggerProvider(logSink));
|
|
builder.Logging.AddFilter<DbLoggerProvider>("Microsoft", LogLevel.Warning);
|
|
builder.Logging.AddFilter<DbLoggerProvider>("System", LogLevel.Warning);
|
|
builder.Logging.AddFilter<DbLoggerProvider>(typeof(SessionAuthenticationHandler).FullName, LogLevel.Warning);
|
|
|
|
builder.Services.AddKhaemhat(options, logSink);
|
|
|
|
// DataProtection keys in the system database, encrypted with the instance key (SPEC §1.5).
|
|
builder.Services.AddDataProtection().SetApplicationName("Khaemhat");
|
|
builder.Services.AddSingleton<IConfigureOptions<KeyManagementOptions>>(sp => new ConfigureOptions<KeyManagementOptions>(o =>
|
|
{
|
|
o.XmlRepository = new DataProtectionKeyStore(sp.GetRequiredService<Data.IUnitOfWorkFactory>());
|
|
o.XmlEncryptor = new SecretKeyXmlEncryptor(sp.GetRequiredService<Core.Security.ISecretProtector>());
|
|
}));
|
|
|
|
// Sign-in with the session cookie (SPEC §7.3) and policies for permissions, levels and modules.
|
|
builder.Services.AddAuthentication(SessionCookie.Scheme)
|
|
.AddScheme<AuthenticationSchemeOptions, SessionAuthenticationHandler>(SessionCookie.Scheme, null);
|
|
builder.Services.AddAuthorization();
|
|
builder.Services.AddSingleton<IAuthorizationPolicyProvider, KhaemhatPolicyProvider>();
|
|
builder.Services.AddSingleton<IAuthorizationHandler, KhaemhatAuthorizationHandler>();
|
|
builder.Services.AddCascadingAuthenticationState();
|
|
builder.Services.AddScoped<AuthenticationStateProvider, SessionRevalidatingStateProvider>();
|
|
|
|
builder.Services.AddSingleton(ProductVersion.FromAssembly(typeof(KhaemhatApp).Assembly));
|
|
builder.Services.AddRazorComponents()
|
|
.AddInteractiveServerComponents();
|
|
|
|
var app = builder.Build();
|
|
|
|
// TLS ends at the reverse proxy in front of the container (docs/DEPLOY.md): no HTTPS redirection here.
|
|
if (!app.Environment.IsDevelopment())
|
|
{
|
|
app.UseExceptionHandler("/Error", createScopeForErrors: true);
|
|
}
|
|
|
|
app.UseSecurityHeaders();
|
|
|
|
// Numbers, dates and texts in Italian (SPEC §10.8); a circuit keeps the culture of the request that opened it.
|
|
app.UseRequestLocalization(new RequestLocalizationOptions()
|
|
.SetDefaultCulture(KhaemhatServices.ItalianCulture.Name)
|
|
.AddSupportedCultures(KhaemhatServices.ItalianCulture.Name)
|
|
.AddSupportedUICultures(KhaemhatServices.ItalianCulture.Name));
|
|
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
|
|
app.MapHealthEndpoints();
|
|
app.UseStartingPage();
|
|
app.UseAuthentication();
|
|
app.UseLogScope();
|
|
app.UseCompanyAvailability();
|
|
app.UseLoginRateLimit();
|
|
app.UseAuthorization();
|
|
app.UseAntiforgery();
|
|
|
|
app.MapStaticAssets();
|
|
app.MapSignOut();
|
|
app.MapCompanySwitch();
|
|
app.MapRazorComponents<App>()
|
|
.AddInteractiveServerRenderMode();
|
|
|
|
return app;
|
|
}
|
|
|
|
// Host settings taken from the variables: listening addresses and log level.
|
|
private static void ApplyHostVariables(WebApplicationBuilder builder, KhaemhatOptions options, string[] args)
|
|
{
|
|
// KHAEMHAT_URLS wins over ASPNETCORE_HTTP_PORTS of the image; an explicit --urls argument wins over both.
|
|
if (!string.IsNullOrWhiteSpace(options.Urls) && !args.Any(a => a.StartsWith("--urls", StringComparison.Ordinal)))
|
|
{
|
|
builder.WebHost.UseUrls(options.Urls);
|
|
}
|
|
|
|
if (!string.IsNullOrWhiteSpace(options.LogLevel) && Enum.TryParse<LogLevel>(options.LogLevel, ignoreCase: true, out var level))
|
|
{
|
|
builder.Configuration["Logging:LogLevel:Default"] = level.ToString();
|
|
}
|
|
}
|
|
|
|
// POST /session/company: an instance account chooses the company of its session (top bar, SPEC §10.2). The page
|
|
// is reloaded, so the new circuit starts in the new company.
|
|
private static void MapCompanySwitch(this IEndpointRouteBuilder endpoints) =>
|
|
endpoints.MapPost("/session/company", async (HttpContext context, SessionStore sessions, CompanyContextResolver companies, IAntiforgery antiforgery) =>
|
|
{
|
|
if (!await antiforgery.IsRequestValidAsync(context).ConfigureAwait(false))
|
|
{
|
|
return Results.BadRequest();
|
|
}
|
|
|
|
var actor = SessionCookie.ActorOf(context.User);
|
|
var cookie = SessionCookie.Read(context);
|
|
var form = await context.Request.ReadFormAsync(context.RequestAborted).ConfigureAwait(false);
|
|
var code = form["code"].ToString();
|
|
if (actor is not { IsInstanceAccount: true } || cookie is null || string.IsNullOrWhiteSpace(code))
|
|
{
|
|
return Results.Forbid();
|
|
}
|
|
|
|
var result = await companies.ResolveAsync(actor, code, context.RequestAborted).ConfigureAwait(false);
|
|
if (result.Access != CompanyAccess.Granted || result.Company is null)
|
|
{
|
|
return Results.Redirect("/");
|
|
}
|
|
|
|
await sessions.SetCompanyAsync(cookie, result.Company.Code, context.RequestAborted).ConfigureAwait(false);
|
|
return Results.Redirect("/");
|
|
});
|
|
|
|
// POST /logout: closes the session and removes the cookie; a form with the antiforgery token posts here.
|
|
private static void MapSignOut(this IEndpointRouteBuilder endpoints) =>
|
|
endpoints.MapPost("/logout", async (HttpContext context, SignInService signIn, IAntiforgery antiforgery) =>
|
|
{
|
|
if (!await antiforgery.IsRequestValidAsync(context).ConfigureAwait(false))
|
|
{
|
|
return Results.BadRequest();
|
|
}
|
|
|
|
await signIn.SignOutAsync(SessionCookie.Read(context), context.RequestAborted).ConfigureAwait(false);
|
|
SessionCookie.Clear(context);
|
|
return Results.Redirect("/login");
|
|
});
|
|
}
|