feat: system and security - start-up, accounts, sign-in, licences, log, jobs, companies (M2)
CI / Build and test (SQLite) (pull_request) Successful in 55s
CI / PostgreSQL 16 integration (pull_request) Skipped
CI / PostgreSQL 17 integration (pull_request) Skipped
CI / YAML check (pull_request) Successful in 5s
CI / Docker image (pull_request) Failing after 2m4s

The instance now starts on its own from KHAEMHAT_* variables: it migrates the system
and company databases, creates the super user and the first company, and only then
reports ready. Users sign in with password and TOTP through revocable database
sessions, and licences decide which modules and how many companies are available.

- Configuration: every wrong variable reported at once (exit code 2), _FILE variants
- Accounts, password policy and lockout, TOTP with recovery codes, session states
  with token rotation, security audit with a hash chain
- Sign-in pages (mockups 001-003), authorization attributes, security headers and a
  CSP without inline scripts, login rate limit
- Signed licences, activation codes, test mode, licence tool
- DataProtection keys in the system database, encrypted with the instance key
- Memory or Redis cache (in-house RESP client) that falls back to memory
- Database log by section with trace id; cron scheduler with locks and system jobs;
  record history (audit_log)
- Company creation, states, company context and X-Company, 503 in maintenance
- In-memory SQLite databases stay alive for the process (tests, demo)
- Tests for all of the above, ADR 0019, wiki, SECURITY, CHANGELOG, STATUS, DATA-MODEL

Refs #15 #16 #17 #18 #19 #20 #21 #22 #23 #24

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 15:29:24 +01:00
1 parent 4582837b70
commit 032c602b49
107 files changed
+12202 -116

No files matched your search

+11 -3
View File
@@ -12,14 +12,22 @@
<ResourcePreloader />
<link rel="stylesheet" href="@Assets["app.css"]" />
<link rel="stylesheet" href="@Assets["Khaemhat.Web.styles.css"]" />
<ImportMap />
<HeadOutlet @rendermode="InteractiveServer" />
@* No <ImportMap />: it is an inline script, and the content security policy allows none (no JS modules yet). *@
<HeadOutlet @rendermode="PageRenderMode" />
</head>
<body>
<Routes @rendermode="InteractiveServer" />
<Routes @rendermode="PageRenderMode" />
<ReconnectModal />
<script src="@Assets["_framework/blazor.web.js"]"></script>
</body>
</html>
@code {
[CascadingParameter]
private HttpContext HttpContext { get; set; } = default!;
// The sign-in pages are static server-rendered forms (they set the cookie); everything else is interactive.
private IComponentRenderMode? PageRenderMode => HttpContext.AcceptsInteractiveRouting() ? InteractiveServer : null;
}
@@ -0,0 +1,26 @@
@inherits LayoutComponentBase
@using Khaemhat.Core.Common
@inject ProductVersion Version
@* Mockups 001-003: brand panel on the left, the form on the right. Texts move to the it-IT resources in M3. *@
<div class="kh-auth">
<aside class="brand">
<div class="brand-top">
<img class="mark" src="icon.svg" alt="" width="56" height="56" />
<h2>Khaemhat</h2>
<p>Gestionale ERP + CRM per PMI italiane: documenti, magazzino, contabilità e fatturazione elettronica in un'unica applicazione web.</p>
</div>
<ul class="features">
<li><strong>Contabilità italiana completa</strong> prima nota, IVA, registri, bilancio CEE</li>
<li><strong>Fatturazione elettronica</strong> SDI, conservazione, bollo, autofatture</li>
<li><strong>CRM</strong> lead, opportunità, attività, campagne</li>
<li><strong>Più aziende</strong> un database per azienda, backup integrati</li>
</ul>
</aside>
<main class="panel">
<section class="card">
@Body
</section>
<footer>Khaemhat @Version.Version · <a href="https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki">Documentazione</a></footer>
</main>
</div>
@@ -0,0 +1,12 @@
@page "/accesso-negato"
@attribute [ExcludeFromInteractiveRouting]
<PageTitle>Khaemhat · accesso negato</PageTitle>
<main class="kh-construction">
<section class="hero">
<h1>Accesso negato</h1>
<p class="lead">Il tuo profilo non ha il permesso per questa pagina, oppure il modulo non è compreso nella licenza.</p>
<ul class="links"><li><a href="/">Torna alla pagina iniziale</a></li></ul>
</section>
</main>
+30 -9
View File
@@ -1,21 +1,42 @@
@page "/"
@attribute [Authorize]
@using Khaemhat.Application.Licensing
@using Khaemhat.Core.Common
@inject ProductVersion Version
@inject ILicenseGate Licenses
@* Placeholder until the shell of M3 (SPEC §20, M0): brand, icon and version, styled after the login hero (mockup 001).
Texts move to the it-IT resources with the localization of M3. *@
<PageTitle>Khaemhat · in costruzione</PageTitle>
@* Placeholder until the shell of M3 (SPEC §20): who is signed in, in which company, with which licence. Texts move to
the it-IT resources with the localization of M3. *@
<PageTitle>Khaemhat</PageTitle>
<main class="kh-construction">
<section class="hero">
<img class="mark" src="icon.svg" alt="" width="96" height="96" />
<h1>Khaemhat <span class="ver">v @Version.MajorMinor</span></h1>
<p class="lead">Gestionale ERP + CRM per piccole e medie imprese italiane.</p>
<p class="state">Installazione in costruzione: le funzioni arrivano milestone dopo milestone.</p>
<ul class="links">
<li><a href="https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki/Roadmap">Roadmap</a></li>
<li><a href="https://gitea.encke-hake.ts.net/BalboSoft/Khaemhat/wiki">Documentazione</a></li>
</ul>
<AuthorizeView>
<p class="lead">Benvenuto, <strong>@context.User.FindFirst(SessionCookie.DisplayNameClaim)?.Value</strong>
(@LevelLabel(context.User.FindFirst(SessionCookie.LevelClaim)?.Value))
@if (context.User.FindFirst(SessionCookie.CompanyClaim)?.Value is { } company)
{
<span> · azienda <strong>@company</strong></span>
}
</p>
</AuthorizeView>
<p class="state">Accesso, utenti, ruoli, licenze e log sono pronti; le schermate di lavoro arrivano con l'interfaccia della milestone 3.
Licenza: @(Licenses.Current.Kind == LicenseKind.Trial ? "prova" : Licenses.Current.Licensee) · moduli @string.Join(", ", Licenses.Current.Modules.Order())</p>
<form method="post" action="/logout" class="links">
<AntiforgeryToken />
<button type="submit" class="kh-btn ghost">Esci</button>
</form>
<p class="build">Versione @Version.Full</p>
</section>
</main>
@code {
private static string LevelLabel(string? level) => level switch
{
"SuperUser" => "super utente",
"Administrator" => "amministratore",
_ => "utente",
};
}
@@ -0,0 +1,116 @@
@page "/login"
@attribute [ExcludeFromInteractiveRouting]
@layout AuthLayout
@using Khaemhat.Application.Licensing
@using Khaemhat.Application.Security
@using Khaemhat.Core.Instance
@using Khaemhat.Data.Companies
@inject SignInService SignIn
@inject ICompanyRegistry Companies
@inject ILicenseGate Licenses
@inject SecurityPolicyOptions Policy
@inject NavigationManager Navigation
@inject TimeProvider Clock
<PageTitle>Accedi · Khaemhat</PageTitle>
<h1>Accedi</h1>
<p class="sub">Scegli l'azienda e inserisci le credenziali.</p>
@foreach (var message in Errors)
{
<div class="kh-alert err" role="alert">@message</div>
}
<EditForm Model="Input" method="post" FormName="login" OnSubmit="SubmitAsync" class="kh-form">
<label for="company">Azienda</label>
<InputSelect id="company" @bind-Value="Input.CompanyCode">
<option value="">Nessuna (account di istanza)</option>
@foreach (var company in AvailableCompanies)
{
<option value="@company.Code">@company.Name (@company.Code)</option>
}
</InputSelect>
<label for="user">Nome utente</label>
<InputText id="user" @bind-Value="Input.UserName" autocomplete="username" autofocus required />
<label for="password">Password</label>
<InputText id="password" type="password" @bind-Value="Input.Password" autocomplete="current-password" required />
<label class="check"><InputCheckbox @bind-Value="Input.Remember" /> Ricordami su questo dispositivo</label>
<button type="submit" class="kh-btn primary">Accedi</button>
</EditForm>
@if (TrialNotice is not null)
{
<div class="kh-alert warn">@TrialNotice</div>
}
@code {
[CascadingParameter]
private HttpContext HttpContext { get; set; } = default!;
[SupplyParameterFromForm]
private LoginInput Input { get; set; } = default!;
[SupplyParameterFromQuery]
private string? ReturnUrl { get; set; }
private IReadOnlyList<Company> AvailableCompanies { get; set; } = [];
private IReadOnlyList<string> Errors { get; set; } = [];
private string? TrialNotice { get; set; }
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
Input ??= new LoginInput();
AvailableCompanies = [.. (await Companies.ListAsync(HttpContext.RequestAborted)).Where(c => c.Status is CompanyStatus.Active or CompanyStatus.ReadOnly)];
if (HttpMethods.IsGet(HttpContext.Request.Method) && string.IsNullOrEmpty(Input.CompanyCode))
{
Input.CompanyCode = AvailableCompanies.FirstOrDefault(c => c.IsDefault)?.Code;
}
var license = Licenses.Current;
if (license.Kind == LicenseKind.Trial)
{
TrialNotice = $"Licenza in modalità prova: restano {license.DaysLeft(Clock.GetUtcNow().UtcDateTime)} giorni, con i moduli Base e Contabilità e {license.MaxConcurrentUsers} utenti collegati.";
}
else if (license.Status != LicenseStatus.Valid)
{
TrialNotice = "La licenza è scaduta: rivolgiti all'amministratore.";
}
}
private async Task SubmitAsync()
{
var request = new SignInRequest(
Input.CompanyCode, Input.UserName ?? string.Empty, Input.Password ?? string.Empty, Input.Remember,
HttpContext.Connection.RemoteIpAddress?.ToString(), HttpContext.Request.Headers.UserAgent.ToString());
var result = await SignIn.SignInAsync(request, HttpContext.RequestAborted);
Input.Password = null;
if (!result.Succeeded || result.Cookie is null)
{
Errors = LoginFlow.Messages(result.Error);
return;
}
var persistent = result.State == SessionState.Active && Input.Remember ? Clock.GetUtcNow() + Policy.PersistentSessionLifetime : (DateTimeOffset?)null;
SessionCookie.Write(HttpContext, result.Cookie, persistent);
Navigation.NavigateTo(LoginFlow.NextPage(result.State, ReturnUrl));
}
private sealed class LoginInput
{
public string? CompanyCode { get; set; }
public string? UserName { get; set; }
public string? Password { get; set; }
public bool Remember { get; set; }
}
}
@@ -0,0 +1,106 @@
@page "/login/cambio-password"
@attribute [ExcludeFromInteractiveRouting]
@layout AuthLayout
@using Khaemhat.Application.Security
@inject SignInService SignIn
@inject SecurityPolicyOptions Policy
@inject NavigationManager Navigation
@inject TimeProvider Clock
<PageTitle>Cambio password · Khaemhat</PageTitle>
<h1>Scegli una nuova password</h1>
<p class="sub">Al primo accesso, o dopo una password provvisoria, serve una password personale.</p>
@foreach (var message in Errors)
{
<div class="kh-alert err" role="alert">@message</div>
}
<EditForm Model="Input" method="post" FormName="password-change" OnSubmit="SubmitAsync" class="kh-form">
<label for="current">Password attuale o provvisoria</label>
<InputText id="current" type="password" @bind-Value="Input.Current" autocomplete="current-password" autofocus required />
<label for="new">Nuova password</label>
<InputText id="new" type="password" @bind-Value="Input.New" autocomplete="new-password" required />
<label for="confirm">Ripeti la nuova password</label>
<InputText id="confirm" type="password" @bind-Value="Input.Confirm" autocomplete="new-password" required />
<ul class="kh-rules">
<li>Almeno @Policy.MinimumLength caratteri</li>
<li>Almeno tre tipi tra minuscole, maiuscole, cifre e simboli</li>
<li>Diversa dal nome utente e dalle ultime @Policy.HistorySize password</li>
</ul>
<button type="submit" class="kh-btn primary">Salva e continua</button>
</EditForm>
@code {
[CascadingParameter]
private HttpContext HttpContext { get; set; } = default!;
[SupplyParameterFromForm]
private PasswordInput Input { get; set; } = default!;
[SupplyParameterFromQuery]
private string? ReturnUrl { get; set; }
private IReadOnlyList<string> Errors { get; set; } = [];
private SessionIdentity? Identity { get; set; }
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
Input ??= new PasswordInput();
Identity = await SignIn.ResolveAsync(SessionCookie.Read(HttpContext), HttpContext.RequestAborted);
if (Identity?.State != SessionState.PendingPasswordChange)
{
Navigation.NavigateTo(Identity is null ? LoginFlow.LoginPage : LoginFlow.NextPage(Identity.State, ReturnUrl));
}
}
private async Task SubmitAsync()
{
if (Identity?.State != SessionState.PendingPasswordChange)
{
return;
}
if (!string.Equals(Input.New, Input.Confirm, StringComparison.Ordinal))
{
Errors = ["Le due nuove password non coincidono."];
Clear();
return;
}
var result = await SignIn.ChangePasswordAsync(SessionCookie.Read(HttpContext)!, Input.Current ?? string.Empty, Input.New ?? string.Empty, HttpContext.RequestAborted);
Clear();
if (!result.Succeeded || result.Cookie is null)
{
Errors = LoginFlow.Messages(result.Error);
return;
}
var persistent = result.State == SessionState.Active && Identity.Persistent ? Clock.GetUtcNow() + Policy.PersistentSessionLifetime : (DateTimeOffset?)null;
SessionCookie.Write(HttpContext, result.Cookie, persistent);
Navigation.NavigateTo(LoginFlow.NextPage(result.State, ReturnUrl));
}
private void Clear()
{
Input.Current = null;
Input.New = null;
Input.Confirm = null;
}
private sealed class PasswordInput
{
public string? Current { get; set; }
public string? New { get; set; }
public string? Confirm { get; set; }
}
}
@@ -0,0 +1,85 @@
@page "/login/verifica"
@attribute [ExcludeFromInteractiveRouting]
@layout AuthLayout
@using Khaemhat.Application.Security
@inject SignInService SignIn
@inject SecurityPolicyOptions Policy
@inject NavigationManager Navigation
@inject TimeProvider Clock
<PageTitle>Verifica in due passaggi · Khaemhat</PageTitle>
<h1>Verifica in due passaggi</h1>
<p class="sub">Inserisci il codice a 6 cifre dell'app di autenticazione.</p>
@foreach (var message in Errors)
{
<div class="kh-alert err" role="alert">@message</div>
}
<EditForm Model="Input" method="post" FormName="totp" OnSubmit="SubmitAsync" class="kh-form">
<label for="code">Codice</label>
<InputText id="code" class="otp" @bind-Value="Input.Code" inputmode="numeric" autocomplete="one-time-code" maxlength="20" autofocus required />
<div class="row">
<button type="submit" class="kh-btn primary">Verifica</button>
<span class="hint">Oppure un codice di recupero (XXXX-XXXX)</span>
</div>
</EditForm>
<div class="kh-alert info">Il codice cambia ogni 30 secondi. L'autenticazione a due fattori è obbligatoria per amministratori e super utente.</div>
@code {
[CascadingParameter]
private HttpContext HttpContext { get; set; } = default!;
[SupplyParameterFromForm]
private CodeInput Input { get; set; } = default!;
[SupplyParameterFromQuery]
private string? ReturnUrl { get; set; }
private IReadOnlyList<string> Errors { get; set; } = [];
private SessionIdentity? Identity { get; set; }
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
Input ??= new CodeInput();
Identity = await SignIn.ResolveAsync(SessionCookie.Read(HttpContext), HttpContext.RequestAborted);
if (Identity?.State != SessionState.PendingTotp)
{
Navigation.NavigateTo(Identity is null ? LoginFlow.LoginPage : LoginFlow.NextPage(Identity.State, ReturnUrl));
}
}
private async Task SubmitAsync()
{
if (Identity?.State != SessionState.PendingTotp)
{
return;
}
var result = await SignIn.VerifyTotpAsync(SessionCookie.Read(HttpContext)!, (Input.Code ?? string.Empty).Replace(" ", string.Empty, StringComparison.Ordinal), HttpContext.RequestAborted);
Input.Code = null;
if (!result.Succeeded || result.Cookie is null)
{
Errors = LoginFlow.Messages(result.Error);
if (result.Error == SecurityErrors.AccountLocked)
{
SessionCookie.Clear(HttpContext);
}
return;
}
var persistent = result.State == SessionState.Active && Identity.Persistent ? Clock.GetUtcNow() + Policy.PersistentSessionLifetime : (DateTimeOffset?)null;
SessionCookie.Write(HttpContext, result.Cookie, persistent);
Navigation.NavigateTo(LoginFlow.NextPage(result.State, ReturnUrl));
}
private sealed class CodeInput
{
public string? Code { get; set; }
}
}
@@ -0,0 +1,113 @@
@page "/login/configura-verifica"
@attribute [ExcludeFromInteractiveRouting]
@layout AuthLayout
@using Khaemhat.Application.Security
@inject SignInService SignIn
@inject SecurityPolicyOptions Policy
@inject NavigationManager Navigation
@inject TimeProvider Clock
<PageTitle>Configura la verifica in due passaggi · Khaemhat</PageTitle>
@if (RecoveryCodes is not null)
{
<h1>Codici di recupero</h1>
<p class="sub">Conservali in un luogo sicuro: ognuno vale una volta sola, al posto del codice dell'app, se perdi il telefono. Non verranno mostrati di nuovo.</p>
<ul class="kh-codes">
@foreach (var recovery in RecoveryCodes)
{
<li><code>@recovery</code></li>
}
</ul>
<a class="kh-btn primary" href="@NextUrl">Ho salvato i codici, continua</a>
}
else
{
<h1>Configura la verifica in due passaggi</h1>
<p class="sub">Aggiungi l'account a un'app di autenticazione (Google Authenticator, Microsoft Authenticator, Aegis, 2FAS...) e inserisci il primo codice.</p>
@foreach (var message in Errors)
{
<div class="kh-alert err" role="alert">@message</div>
}
@if (Setup is not null)
{
<dl class="kh-secret">
<dt>Chiave da inserire nell'app</dt>
<dd><code>@Grouped(Setup.Secret)</code></dd>
<dt>Sul telefono</dt>
<dd><a href="@Setup.ProvisioningUri">Apri nell'app di autenticazione</a></dd>
</dl>
}
<EditForm Model="Input" method="post" FormName="totp-setup" OnSubmit="SubmitAsync" class="kh-form">
<label for="code">Primo codice dell'app</label>
<InputText id="code" class="otp" @bind-Value="Input.Code" inputmode="numeric" autocomplete="one-time-code" maxlength="6" autofocus required />
<button type="submit" class="kh-btn primary">Attiva</button>
</EditForm>
}
@code {
[CascadingParameter]
private HttpContext HttpContext { get; set; } = default!;
[SupplyParameterFromForm]
private CodeInput Input { get; set; } = default!;
[SupplyParameterFromQuery]
private string? ReturnUrl { get; set; }
private IReadOnlyList<string> Errors { get; set; } = [];
private SessionIdentity? Identity { get; set; }
private TotpSetup? Setup { get; set; }
private IReadOnlyList<string>? RecoveryCodes { get; set; }
private string NextUrl { get; set; } = "/";
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
Input ??= new CodeInput();
Identity = await SignIn.ResolveAsync(SessionCookie.Read(HttpContext), HttpContext.RequestAborted);
if (Identity?.State != SessionState.PendingTotpSetup)
{
Navigation.NavigateTo(Identity is null ? LoginFlow.LoginPage : LoginFlow.NextPage(Identity.State, ReturnUrl));
return;
}
Setup = await SignIn.BeginTotpSetupAsync(SessionCookie.Read(HttpContext)!, HttpContext.RequestAborted);
}
private async Task SubmitAsync()
{
if (Identity?.State != SessionState.PendingTotpSetup)
{
return;
}
var (result, codes) = await SignIn.ConfirmTotpSetupAsync(SessionCookie.Read(HttpContext)!, (Input.Code ?? string.Empty).Trim(), HttpContext.RequestAborted);
Input.Code = null;
if (!result.Succeeded || result.Cookie is null || codes is null)
{
Errors = LoginFlow.Messages(result.Error);
return;
}
var persistent = result.State == SessionState.Active && Identity.Persistent ? Clock.GetUtcNow() + Policy.PersistentSessionLifetime : (DateTimeOffset?)null;
SessionCookie.Write(HttpContext, result.Cookie, persistent);
RecoveryCodes = codes;
NextUrl = LoginFlow.NextPage(result.State, ReturnUrl);
}
private static string Grouped(string secret) =>
string.Join(' ', Enumerable.Range(0, (secret.Length + 3) / 4).Select(i => secret.Substring(i * 4, Math.Min(4, secret.Length - (i * 4)))));
private sealed class CodeInput
{
public string? Code { get; set; }
}
}
@@ -0,0 +1,21 @@
@inject NavigationManager Navigation
@* Inside an interactive circuit: a page needs a signed-in user (or the session ended) - back to the login page. *@
@code {
[CascadingParameter]
private Task<AuthenticationState>? AuthenticationState { get; set; }
/// <inheritdoc />
protected override async Task OnInitializedAsync()
{
var signedIn = AuthenticationState is not null && (await AuthenticationState).User.Identity?.IsAuthenticated == true;
if (signedIn)
{
Navigation.NavigateTo("/accesso-negato", forceLoad: true);
return;
}
var path = "/" + Navigation.ToBaseRelativePath(Navigation.Uri);
Navigation.NavigateTo(LoginFlow.LoginPage + (path.Length > 1 ? "?returnUrl=" + Uri.EscapeDataString(path) : string.Empty), forceLoad: true);
}
}
+5 -1
View File
@@ -1,6 +1,10 @@
<Router AppAssembly="typeof(Program).Assembly" NotFoundPage="typeof(Pages.NotFound)">
<Found Context="routeData">
<RouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)" />
<AuthorizeRouteView RouteData="routeData" DefaultLayout="typeof(Layout.MainLayout)">
<NotAuthorized>
<RedirectToLogin />
</NotAuthorized>
</AuthorizeRouteView>
<FocusOnNavigate RouteData="routeData" Selector="h1" />
</Found>
</Router>
@@ -1,5 +1,7 @@
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components.Authorization
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@@ -9,3 +11,5 @@
@using Khaemhat.Web
@using Khaemhat.Web.Components
@using Khaemhat.Web.Components.Layout
@using Khaemhat.Core.Security
@using Khaemhat.Web.Security
@@ -0,0 +1,81 @@
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Instance;
using Khaemhat.Data.Migrations;
using Khaemhat.Infrastructure.Logging;
namespace Khaemhat.Web.Hosting;
/// <summary>
/// Runs the start sequence in the background, so that <c>/health/live</c> answers at once and <c>/health/ready</c>
/// answers 503 until the databases are migrated. A failure stops the process with exit code 1: the container restart
/// policy retries, and the log says why.
/// </summary>
/// <param name="orchestrator">The start sequence.</param>
/// <param name="state">The start state.</param>
/// <param name="logSink">The database log, flushed at shutdown.</param>
/// <param name="lifetime">Stops the host on failure.</param>
/// <param name="logger">The log.</param>
internal sealed partial class BootstrapService(
StartupOrchestrator orchestrator, BootstrapState state, DbLogSink logSink, IHostApplicationLifetime lifetime, ILogger<BootstrapService> logger)
: BackgroundService
{
/// <summary>
/// Migrates the system database before the host serves anything (this service is registered before DataProtection,
/// whose key ring lives there), then lets the rest of the sequence run in the background. A failure here stops the
/// start: without the system database nothing can work.
/// </summary>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>A task.</returns>
public override async Task StartAsync(CancellationToken cancellationToken)
{
try
{
await orchestrator.PrepareSystemDatabaseAsync(cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
state.MarkFailed(Describe(ex));
LogStartFailed(logger, ex, Describe(ex));
throw;
}
await base.StartAsync(cancellationToken).ConfigureAwait(false);
}
/// <inheritdoc />
public override async Task StopAsync(CancellationToken cancellationToken)
{
await base.StopAsync(cancellationToken).ConfigureAwait(false);
await logSink.DisposeAsync().ConfigureAwait(false);
}
/// <inheritdoc />
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
await orchestrator.RunAsync(stoppingToken).ConfigureAwait(false);
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
}
catch (Exception ex)
{
var reason = Describe(ex);
state.MarkFailed(reason);
LogStartFailed(logger, ex, reason);
Environment.ExitCode = 1;
lifetime.StopApplication();
}
}
private static string Describe(Exception ex) => ex switch
{
ConfigurationException config => string.Join(" ", config.Errors),
MigrationException migration => migration.Message,
_ => ex.GetType().Name + ": " + ex.Message,
};
[LoggerMessage(Level = LogLevel.Critical, Message = "Khaemhat cannot start: {Reason}")]
private static partial void LogStartFailed(ILogger logger, Exception exception, string reason);
}
+15 -9
View File
@@ -1,3 +1,4 @@
using Khaemhat.Application.Instance;
using Khaemhat.Core.Common;
namespace Khaemhat.Web.Hosting;
@@ -5,13 +6,14 @@ namespace Khaemhat.Web.Hosting;
/// <summary>
/// Health endpoints for Docker and reverse proxies (SPEC §16.1, ADR 0012):
/// <c>/health/live</c> says the process answers (the image HEALTHCHECK), <c>/health/ready</c> says it can serve
/// requests (from M1 it also checks the system database), <c>/health</c> summarises both with the version.
/// requests (the start sequence completed: databases migrated), <c>/health</c> summarises both with the version.
/// They carry no personal or configuration data and need no authentication.
/// </summary>
public static class HealthEndpoints
{
/// <summary>Maps the three health endpoints.</summary>
/// <param name="endpoints">The application's route builder.</param>
/// <returns>The route builder.</returns>
public static IEndpointRouteBuilder MapHealthEndpoints(this IEndpointRouteBuilder endpoints)
{
ArgumentNullException.ThrowIfNull(endpoints);
@@ -19,22 +21,26 @@ public static class HealthEndpoints
endpoints.MapGet("/health/live", () => Results.Text("live", "text/plain"))
.ExcludeFromDescription();
endpoints.MapGet("/health/ready", () => Results.Text("ready", "text/plain"))
endpoints.MapGet("/health/ready", (BootstrapState state) => state.IsReady
? Results.Text("ready", "text/plain")
: Results.Text(state.Phase == BootstrapPhase.Failed ? "failed" : "starting", "text/plain", statusCode: StatusCodes.Status503ServiceUnavailable))
.ExcludeFromDescription();
endpoints.MapGet("/health", (ProductVersion version) => Results.Json(new HealthReport(
Status: "ok",
Live: true,
Ready: true,
Version: version.Version,
Revision: version.Revision)))
endpoints.MapGet("/health", (ProductVersion version, BootstrapState state) => Results.Json(
new HealthReport(
Status: state.IsReady ? "ok" : state.Phase == BootstrapPhase.Failed ? "failed" : "starting",
Live: true,
Ready: state.IsReady,
Version: version.Version,
Revision: version.Revision),
statusCode: state.IsReady ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable))
.ExcludeFromDescription();
return endpoints;
}
/// <summary>The body of <c>/health</c>.</summary>
/// <param name="Status"><c>ok</c> when the instance is live and ready.</param>
/// <param name="Status"><c>ok</c> when the instance is live and ready, <c>starting</c> or <c>failed</c> otherwise.</param>
/// <param name="Live">Whether the process answers.</param>
/// <param name="Ready">Whether the instance can serve requests.</param>
/// <param name="Version">Product version (SemVer).</param>
+72 -23
View File
@@ -1,6 +1,17 @@
using Khaemhat.Application.Configuration;
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;
@@ -11,7 +22,9 @@ namespace Khaemhat.Web.Hosting;
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>).</param>
/// <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.
@@ -21,9 +34,13 @@ public static class KhaemhatApp
ApplicationName = typeof(KhaemhatApp).Assembly.GetName().Name,
});
ApplyInstanceVariables(builder, args);
// 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 JSON line per event on stdout outside development (SPEC §9.5); the database sink arrives in M2.
// 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();
@@ -35,11 +52,29 @@ public static class KhaemhatApp
});
}
// Until the database key store of M2 exists, keys live in memory: nothing is written outside the data
// folder (SPEC §1.5). Antiforgery and circuit tokens therefore reset when the container restarts.
builder.Services.AddDataProtection()
.SetApplicationName("Khaemhat")
.UseEphemeralDataProtectionProvider();
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()
@@ -53,37 +88,51 @@ public static class KhaemhatApp
app.UseExceptionHandler("/Error", createScopeForErrors: true);
}
app.UseSecurityHeaders();
app.UseStatusCodePagesWithReExecute("/not-found", createScopeForStatusCodePages: true);
app.MapHealthEndpoints();
app.UseStartingPage();
app.UseAuthentication();
app.UseLogScope();
app.UseCompanyAvailability();
app.UseLoginRateLimit();
app.UseAuthorization();
app.UseAntiforgery();
app.MapHealthEndpoints();
app.MapStaticAssets();
app.MapSignOut();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
return app;
}
// The KHAEMHAT_* variables of SPEC §6 that the host itself needs. The full validation (KhaemhatOptions) is M1.
private static void ApplyInstanceVariables(WebApplicationBuilder builder, string[] args)
// 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.
var urls = builder.Configuration["KHAEMHAT_URLS"];
if (!string.IsNullOrWhiteSpace(urls) && !args.Any(a => a.StartsWith("--urls", StringComparison.Ordinal)))
if (!string.IsNullOrWhiteSpace(options.Urls) && !args.Any(a => a.StartsWith("--urls", StringComparison.Ordinal)))
{
builder.WebHost.UseUrls(urls);
builder.WebHost.UseUrls(options.Urls);
}
var level = builder.Configuration["KHAEMHAT_LOG_LEVEL"];
if (!string.IsNullOrWhiteSpace(level))
if (!string.IsNullOrWhiteSpace(options.LogLevel) && Enum.TryParse<LogLevel>(options.LogLevel, ignoreCase: true, out var level))
{
if (!Enum.TryParse<LogLevel>(level, ignoreCase: true, out var parsed) || !Enum.IsDefined(parsed))
{
throw new InvalidOperationException(
$"KHAEMHAT_LOG_LEVEL '{level}' is not valid: use Trace, Debug, Information, Warning, Error, Critical or None.");
}
builder.Configuration["Logging:LogLevel:Default"] = parsed.ToString();
builder.Configuration["Logging:LogLevel:Default"] = level.ToString();
}
}
// 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");
});
}
@@ -0,0 +1,141 @@
using Khaemhat.Application.Audit;
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Instance;
using Khaemhat.Application.Jobs;
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Modules;
using Khaemhat.Application.Notifications;
using Khaemhat.Application.Security;
using Khaemhat.Core.Caching;
using Khaemhat.Core.Logging;
using Khaemhat.Core.Security;
using Khaemhat.Data;
using Khaemhat.Data.Companies;
using Khaemhat.Data.Execution;
using Khaemhat.Data.Mapping;
using Khaemhat.Data.Migrations;
using Khaemhat.Data.PostgreSql;
using Khaemhat.Data.Sqlite;
using Khaemhat.Infrastructure.Caching;
using Khaemhat.Infrastructure.Licensing;
using Khaemhat.Infrastructure.Logging;
using Khaemhat.Infrastructure.Security;
using Khaemhat.Web.Security;
namespace Khaemhat.Web.Hosting;
/// <summary>
/// The composition of the instance (SPEC §3): data access on the configured databases, security, licences, log and
/// the start sequence. Services are singletons: they hold no per-request state and open a unit of work per call.
/// </summary>
internal static class KhaemhatServices
{
/// <summary>Registers every service of the instance.</summary>
/// <param name="services">The container.</param>
/// <param name="options">The validated variables.</param>
/// <param name="logSink">The database log queue, already plugged into the logging pipeline.</param>
/// <returns>The container.</returns>
public static IServiceCollection AddKhaemhat(this IServiceCollection services, KhaemhatOptions options, DbLogSink logSink)
{
var dataAssembly = typeof(CompanyRegistry).Assembly;
services.AddSingleton(options);
services.AddSingleton(logSink);
services.AddSingleton(TimeProvider.System);
services.AddSingleton<BootstrapState>();
services.AddHttpContextAccessor();
services.AddSingleton<CurrentUserName>();
// Secrets and data access.
services.AddSingleton(SecretKey.FromBase64(options.SecretKey!));
services.AddSingleton<SecretProtector>();
services.AddSingleton<ISecretProtector>(sp => sp.GetRequiredService<SecretProtector>());
services.AddSingleton(new DbProviderCatalog(new SqliteProvider(), new PostgresProvider()));
services.AddSingleton(new MapRegistry().AddFromAssembly(dataAssembly));
services.AddSingleton(sp =>
{
var slow = sp.GetRequiredService<ILoggerFactory>().CreateLogger("Khaemhat.Performance.SlowQueries");
var user = sp.GetRequiredService<CurrentUserName>();
return new DataAccessContext(sp.GetRequiredService<TimeProvider>(), user.Get)
{
SlowQueryObserver = query =>
{
using var section = slow.BeginScope(LogSections.Scope(LogSection.Performance));
slow.LogWarning(
"Slow query on {Database}: {Milliseconds} ms. {Sql}",
query.Database, (long)query.Duration.TotalMilliseconds, query.Sql.Length > 2000 ? query.Sql[..2000] : query.Sql);
},
};
});
services.AddSingleton(sp => sp.GetRequiredService<DbProviderCatalog>().Resolve(options.SystemDatabase));
services.AddSingleton<ICompanyRegistry>(sp => new CompanyRegistry(
sp.GetRequiredService<DatabaseTarget>(), sp.GetRequiredService<DbProviderCatalog>(), sp.GetRequiredService<ISecretProtector>(),
sp.GetRequiredService<MapRegistry>(), sp.GetRequiredService<DataAccessContext>()));
services.AddSingleton<IDatabaseLocator>(sp => new DatabaseLocator(sp.GetRequiredService<DatabaseTarget>(), sp.GetRequiredService<ICompanyRegistry>()));
services.AddSingleton<IUnitOfWorkFactory, UnitOfWorkFactory>();
services.AddSingleton<MigrationRunner>();
services.AddSingleton(new InstanceDatabases(
options.SystemDatabase, options.CompanyServer, MigrationCatalog.ForSystem(dataAssembly), MigrationCatalog.ForCompany(dataAssembly)));
// Cache: in memory, or on Redis when KHAEMHAT_REDIS is set (falling back to memory while Redis is down).
if (options.Redis is { } redis)
{
services.AddSingleton(new RedisClient(RedisEndpoint.Parse(redis)));
services.AddSingleton<ICacheProvider>(sp => new RedisCacheProvider(
sp.GetRequiredService<RedisClient>(), sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<ILogger<RedisCacheProvider>>()));
}
else
{
services.AddSingleton<ICacheProvider>(sp => new MemoryCacheProvider(sp.GetRequiredService<TimeProvider>()));
}
// Security.
services.AddSingleton(new SecurityPolicyOptions());
services.AddSingleton<PasswordPolicy>();
services.AddSingleton<AccountSecurity>();
services.AddSingleton<ISecurityAuditLog, SecurityAuditLog>();
services.AddSingleton<SystemSettingsStore>();
services.AddSingleton(ModuleRegistry.Default);
services.AddSingleton(LicenseVerifier.Product);
services.AddSingleton(new LicenseSettings(options.License, options.Mode));
services.AddSingleton<LicenseGate>();
services.AddSingleton<ILicenseGate>(sp => sp.GetRequiredService<LicenseGate>());
services.AddSingleton<ILicenseActivationService, OfflineActivationService>();
services.AddSingleton<PermissionService>();
services.AddSingleton<RoleService>();
services.AddSingleton<SystemUserService>();
services.AddSingleton<UserService>();
services.AddSingleton<SessionStore>();
services.AddSingleton<NotificationDispatcher>();
services.AddSingleton<SignInService>();
// Companies and start.
services.AddSingleton<ICompanySeeder, PredefinedRolesSeeder>();
services.AddSingleton<CompanyService>();
services.AddSingleton<CompanyContextResolver>();
services.AddScoped<ICompanyContext, WebCompanyContext>();
services.AddSingleton(sp => new StartupOrchestrator(
sp.GetRequiredService<InstanceDatabases>(), sp.GetRequiredService<DbProviderCatalog>(), sp.GetRequiredService<MigrationRunner>(),
sp.GetRequiredService<SystemSettingsStore>(), sp.GetRequiredService<RoleService>(), sp.GetRequiredService<ILicenseGate>(),
sp.GetRequiredService<SystemUserService>(), sp.GetRequiredService<CompanyService>(), options, sp.GetRequiredService<IUnitOfWorkFactory>(),
logSink, sp.GetRequiredService<BootstrapState>(), sp.GetRequiredService<TimeProvider>(), sp.GetRequiredService<ILogger<StartupOrchestrator>>()));
services.AddHostedService<BootstrapService>();
// History of the records and scheduled tasks.
services.AddSingleton<AuditTrail>();
services.AddSingleton<IScheduledJob, SessionCleanupJob>();
services.AddSingleton<IScheduledJob, LicenseCheckJob>();
services.AddSingleton<IScheduledJob, LogRetentionJob>();
services.AddSingleton<JobScheduler>();
services.AddHostedService<JobSchedulerService>();
return services;
}
}
/// <summary>The user name written in the audit columns: the signed-in user of the current request, else <c>system</c>.</summary>
/// <param name="accessor">The current request.</param>
internal sealed class CurrentUserName(IHttpContextAccessor accessor)
{
/// <summary>The name.</summary>
/// <returns>The user name, or <see langword="null"/> outside requests.</returns>
public string? Get() => accessor.HttpContext?.User.Identity is { IsAuthenticated: true, Name: { } name } ? name : null;
}
+186
View File
@@ -0,0 +1,186 @@
using System.Diagnostics;
using System.Net;
using System.Threading.RateLimiting;
using Khaemhat.Application.Instance;
using Khaemhat.Core.Logging;
using Khaemhat.Web.Security;
namespace Khaemhat.Web.Hosting;
/// <summary>The middleware of the instance, in pipeline order.</summary>
internal static class KhaemhatMiddleware
{
/// <summary>
/// Security headers on every response (SPEC §7.3): a content security policy without inline scripts, no framing,
/// no MIME sniffing, no referrer outside the site.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
public static IApplicationBuilder UseSecurityHeaders(this IApplicationBuilder app) => app.Use(async (context, next) =>
{
context.Response.OnStarting(() =>
{
var headers = context.Response.Headers;
headers.ContentSecurityPolicy =
"default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; " +
"connect-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'self'; object-src 'none'";
headers.XContentTypeOptions = "nosniff";
headers.XFrameOptions = "DENY";
headers["Referrer-Policy"] = "same-origin";
headers["Permissions-Policy"] = "camera=(), microphone=(), geolocation=(), payment=()";
headers["Cross-Origin-Opener-Policy"] = "same-origin";
return Task.CompletedTask;
});
await next(context).ConfigureAwait(false);
});
/// <summary>
/// While the start sequence runs (migrations), every request except health checks and static files gets a 503 page
/// that refreshes itself.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
public static IApplicationBuilder UseStartingPage(this IApplicationBuilder app) => app.Use(async (context, next) =>
{
var state = context.RequestServices.GetRequiredService<BootstrapState>();
var path = context.Request.Path;
if (state.IsReady || path.StartsWithSegments("/health") || Path.HasExtension(path.Value) || path.StartsWithSegments("/_framework"))
{
await next(context).ConfigureAwait(false);
return;
}
var message = state.Phase == BootstrapPhase.Failed
? "Avvio non riuscito: controlla il log del container."
: "Avvio in corso: aggiornamento dei database. La pagina si ricarica da sola.";
await WriteUnavailablePageAsync(context, message, refreshSeconds: 5).ConfigureAwait(false);
});
/// <summary>
/// Company states (SPEC §5.4): a company in maintenance answers 503 to company accounts (the API with a JSON body,
/// pages with a notice), a disabled company to everybody; an API call whose <c>X-Company</c> names another company
/// than the account's own gets 403. Sign-in, health checks and static files are never blocked.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
public static IApplicationBuilder UseCompanyAvailability(this IApplicationBuilder app) => app.Use(async (context, next) =>
{
var path = context.Request.Path;
var actor = SessionCookie.ActorOf(context.User);
if (actor is null || Path.HasExtension(path.Value) || path.StartsWithSegments("/_framework") || path.StartsWithSegments("/_blazor")
|| path.StartsWithSegments("/health") || path.StartsWithSegments("/login") || path.StartsWithSegments("/logout"))
{
await next(context).ConfigureAwait(false);
return;
}
var isApi = path.StartsWithSegments("/api");
var resolver = context.RequestServices.GetRequiredService<CompanyContextResolver>();
var requested = isApi ? context.Request.Headers[CompanyContextResolver.Header].ToString() : null;
var result = await resolver.ResolveAsync(actor, requested, context.RequestAborted).ConfigureAwait(false);
var refused = isApi && result.Access is CompanyAccess.Forbidden or CompanyAccess.NotFound;
if (!result.IsUnavailable && !refused)
{
await next(context).ConfigureAwait(false);
return;
}
if (isApi)
{
context.Response.StatusCode = result.IsUnavailable ? StatusCodes.Status503ServiceUnavailable
: result.Access == CompanyAccess.Forbidden ? StatusCodes.Status403Forbidden : StatusCodes.Status404NotFound;
if (result.IsUnavailable)
{
context.Response.Headers.RetryAfter = "60";
}
await context.Response.WriteAsJsonAsync(new { error = ErrorCode(result.Access) }, context.RequestAborted).ConfigureAwait(false);
return;
}
var message = result.Access == CompanyAccess.Maintenance
? "L'azienda è in manutenzione. Riprova tra qualche minuto."
: "L'azienda è disattivata. Rivolgiti all'amministratore.";
await WriteUnavailablePageAsync(context, message, refreshSeconds: result.Access == CompanyAccess.Maintenance ? 60 : null).ConfigureAwait(false);
});
/// <summary>
/// Puts trace identifier, request, user and company in the logging scope of the request (SPEC §9.5: one trace
/// identifier follows the request across the log) and returns the identifier in <c>X-Trace-Id</c>.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
public static IApplicationBuilder UseLogScope(this IApplicationBuilder app) => app.Use(async (context, next) =>
{
var traceId = Activity.Current?.TraceId.ToString() ?? context.TraceIdentifier;
context.Response.Headers["X-Trace-Id"] = traceId;
var logger = context.RequestServices.GetRequiredService<ILoggerFactory>().CreateLogger("Khaemhat.Web.Requests");
var actor = SessionCookie.ActorOf(context.User);
using var scope = logger.BeginScope(new Dictionary<string, object?>
{
[LogSections.TraceIdKey] = traceId,
[LogSections.RequestKey] = context.Request.Method + " " + context.Request.Path,
[LogSections.UserKey] = actor?.UserName,
[LogSections.CompanyKey] = actor?.CompanyCode,
});
await next(context).ConfigureAwait(false);
});
/// <summary>
/// Limits sign-in attempts per client address (SPEC §7.3): 10 posts a minute on the login pages; beyond that 429.
/// Account lockout after 5 wrong passwords is separate and lives in the account.
/// </summary>
/// <param name="app">The application.</param>
/// <returns>The application.</returns>
public static IApplicationBuilder UseLoginRateLimit(this IApplicationBuilder app)
{
var limiter = PartitionedRateLimiter.Create<HttpContext, string>(context =>
RateLimitPartition.GetFixedWindowLimiter(
context.Connection.RemoteIpAddress?.ToString() ?? "unknown",
_ => new FixedWindowRateLimiterOptions { PermitLimit = 10, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 }));
return app.Use(async (context, next) =>
{
if (HttpMethods.IsPost(context.Request.Method) && context.Request.Path.StartsWithSegments("/login"))
{
using var lease = await limiter.AcquireAsync(context, 1, context.RequestAborted).ConfigureAwait(false);
if (!lease.IsAcquired)
{
context.Response.StatusCode = StatusCodes.Status429TooManyRequests;
context.Response.Headers.RetryAfter = "60";
await context.Response.WriteAsync("Troppi tentativi di accesso: riprova tra un minuto.", context.RequestAborted).ConfigureAwait(false);
return;
}
}
await next(context).ConfigureAwait(false);
});
}
private static string ErrorCode(CompanyAccess access) => access switch
{
CompanyAccess.Maintenance => "company_maintenance",
CompanyAccess.Disabled => "company_disabled",
CompanyAccess.Forbidden => "company_forbidden",
_ => "company_not_found",
};
private static Task WriteUnavailablePageAsync(HttpContext context, string message, int? refreshSeconds)
{
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
context.Response.ContentType = "text/html; charset=utf-8";
var refresh = string.Empty;
if (refreshSeconds is { } seconds)
{
var text = seconds.ToString(System.Globalization.CultureInfo.InvariantCulture);
context.Response.Headers.RetryAfter = text;
refresh = "<meta http-equiv=\"refresh\" content=\"" + text + "\">";
}
return context.Response.WriteAsync(
"<!DOCTYPE html><html lang=\"it\"><head><meta charset=\"utf-8\">" + refresh +
"<title>Khaemhat</title><link rel=\"stylesheet\" href=\"/app.css\"></head><body><main class=\"kh-construction\"><section class=\"hero\">" +
"<img class=\"mark\" src=\"/icon.svg\" alt=\"\" width=\"96\" height=\"96\"><h1>Khaemhat</h1><p class=\"state\">" + WebUtility.HtmlEncode(message) +
"</p></section></main></body></html>",
context.RequestAborted);
}
}
+25 -1
View File
@@ -1,3 +1,27 @@
using Khaemhat.Application.Configuration;
using Khaemhat.Web.Hosting;
await KhaemhatApp.Build(args).RunAsync().ConfigureAwait(false);
try
{
await KhaemhatApp.Build(args).RunAsync().ConfigureAwait(false);
}
catch (ConfigurationException ex)
{
// A missing or wrong variable: every problem on stderr, no value printed, exit code 2 (SPEC §6).
await Console.Error.WriteLineAsync("Khaemhat cannot start, the configuration is not valid:").ConfigureAwait(false);
foreach (var error in ex.Errors)
{
await Console.Error.WriteLineAsync(" - " + error).ConfigureAwait(false);
}
return 2;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
// The start failed after the configuration was read (system database unreachable, migration refused): the log
// already has the details; the container restart policy decides what happens next.
await Console.Error.WriteLineAsync("Khaemhat stopped: " + ex.Message).ConfigureAwait(false);
return 1;
}
return Environment.ExitCode;
+120
View File
@@ -0,0 +1,120 @@
using Khaemhat.Application.Licensing;
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Options;
namespace Khaemhat.Web.Security;
/// <summary>Requires a permission (SPEC §7.2), checked with the licence: <c>[RequirePermission("sales.invoices.create")]</c>.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class RequirePermissionAttribute : AuthorizeAttribute
{
/// <summary>Creates the attribute.</summary>
/// <param name="code">The permission code.</param>
public RequirePermissionAttribute(string code)
: base(KhaemhatPolicies.PermissionPrefix + code) => Code = code;
/// <summary>The permission code.</summary>
public string Code { get; }
}
/// <summary>Requires a level: <c>[RequireLevel(UserLevel.Administrator)]</c> for instance administration.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
public sealed class RequireLevelAttribute : AuthorizeAttribute
{
/// <summary>Creates the attribute.</summary>
/// <param name="level">The minimum level.</param>
public RequireLevelAttribute(UserLevel level)
: base(KhaemhatPolicies.LevelPrefix + level) => Level = level;
/// <summary>The minimum level.</summary>
public UserLevel Level { get; }
}
/// <summary>Requires a licensed module: <c>[RequireModule("CRM")]</c>.</summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = true)]
public sealed class RequireModuleAttribute : AuthorizeAttribute
{
/// <summary>Creates the attribute.</summary>
/// <param name="moduleCode">The module code.</param>
public RequireModuleAttribute(string moduleCode)
: base(KhaemhatPolicies.ModulePrefix + moduleCode) => ModuleCode = moduleCode;
/// <summary>The module code.</summary>
public string ModuleCode { get; }
}
/// <summary>The policy names built from the attributes.</summary>
public static class KhaemhatPolicies
{
/// <summary>Prefix of permission policies.</summary>
public const string PermissionPrefix = "perm:";
/// <summary>Prefix of level policies.</summary>
public const string LevelPrefix = "level:";
/// <summary>Prefix of module policies.</summary>
public const string ModulePrefix = "module:";
}
/// <summary>A requirement built from a policy name.</summary>
/// <param name="Kind">The prefix.</param>
/// <param name="Value">The permission, level or module.</param>
internal sealed record KhaemhatRequirement(string Kind, string Value) : IAuthorizationRequirement;
/// <summary>Builds the policies named by <see cref="KhaemhatPolicies"/> on demand; other names go to the default provider.</summary>
/// <param name="options">The authorization options.</param>
internal sealed class KhaemhatPolicyProvider(IOptions<AuthorizationOptions> options) : IAuthorizationPolicyProvider
{
private readonly DefaultAuthorizationPolicyProvider _fallback = new(options);
/// <inheritdoc />
public Task<AuthorizationPolicy> GetDefaultPolicyAsync() => _fallback.GetDefaultPolicyAsync();
/// <inheritdoc />
public Task<AuthorizationPolicy?> GetFallbackPolicyAsync() => _fallback.GetFallbackPolicyAsync();
/// <inheritdoc />
public Task<AuthorizationPolicy?> GetPolicyAsync(string policyName)
{
foreach (var prefix in (string[])[KhaemhatPolicies.PermissionPrefix, KhaemhatPolicies.LevelPrefix, KhaemhatPolicies.ModulePrefix])
{
if (policyName.StartsWith(prefix, StringComparison.Ordinal))
{
return Task.FromResult<AuthorizationPolicy?>(new AuthorizationPolicyBuilder(SessionCookie.Scheme)
.RequireAuthenticatedUser()
.AddRequirements(new KhaemhatRequirement(prefix, policyName[prefix.Length..]))
.Build());
}
}
return _fallback.GetPolicyAsync(policyName);
}
}
/// <summary>Evaluates <see cref="KhaemhatRequirement"/> with the permission service and the licence.</summary>
/// <param name="permissions">The permissions.</param>
/// <param name="licenses">The licence.</param>
internal sealed class KhaemhatAuthorizationHandler(PermissionService permissions, ILicenseGate licenses) : AuthorizationHandler<KhaemhatRequirement>
{
/// <inheritdoc />
protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, KhaemhatRequirement requirement)
{
if (SessionCookie.ActorOf(context.User) is not { } actor)
{
return;
}
var allowed = requirement.Kind switch
{
KhaemhatPolicies.LevelPrefix => Enum.TryParse<UserLevel>(requirement.Value, out var level) && actor.Level >= level,
KhaemhatPolicies.ModulePrefix => licenses.IsModuleActive(requirement.Value),
_ => (await permissions.CheckAsync(actor, requirement.Value).ConfigureAwait(false)).Allowed,
};
if (allowed)
{
context.Succeed(requirement);
}
}
}
+70
View File
@@ -0,0 +1,70 @@
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
namespace Khaemhat.Web.Security;
/// <summary>The pages of the sign-in flow and the messages shown for the error codes of <see cref="SecurityErrors"/>.</summary>
public static class LoginFlow
{
/// <summary>The login page (mockup 001).</summary>
public const string LoginPage = "/login";
/// <summary>The TOTP page (mockup 002).</summary>
public const string TotpPage = "/login/verifica";
/// <summary>The TOTP setup page.</summary>
public const string TotpSetupPage = "/login/configura-verifica";
/// <summary>The forced password change (mockup 003).</summary>
public const string PasswordChangePage = "/login/cambio-password";
/// <summary>Where a session in a state goes next.</summary>
/// <param name="state">The state reached.</param>
/// <param name="returnUrl">Where the user wanted to go.</param>
/// <returns>The local address.</returns>
public static string NextPage(SessionState? state, string? returnUrl) => state switch
{
SessionState.PendingTotp => TotpPage + Carry(returnUrl),
SessionState.PendingTotpSetup => TotpSetupPage + Carry(returnUrl),
SessionState.PendingPasswordChange => PasswordChangePage + Carry(returnUrl),
SessionState.Active => SafeReturnUrl(returnUrl),
_ => LoginPage,
};
/// <summary>A return address only when it stays on this site.</summary>
/// <param name="returnUrl">The address asked for.</param>
/// <returns>The address, or <c>/</c>.</returns>
public static string SafeReturnUrl(string? returnUrl) =>
returnUrl is { Length: > 0 } url && url[0] == '/' && !url.StartsWith("//", StringComparison.Ordinal) && !url.StartsWith("/\\", StringComparison.Ordinal)
&& !url.StartsWith("/login", StringComparison.OrdinalIgnoreCase)
? url
: "/";
/// <summary>The Italian message of an error code (several codes may be joined by commas).</summary>
/// <param name="error">The code(s).</param>
/// <returns>The messages.</returns>
public static IReadOnlyList<string> Messages(string? error) =>
string.IsNullOrEmpty(error) ? [] : [.. error.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).Select(Message)];
private static string Message(string code) => code switch
{
SecurityErrors.InvalidCredentials => "Azienda, utente o password non corretti.",
SecurityErrors.AccountLocked => "Troppi tentativi non riusciti: l'account è bloccato per 15 minuti.",
SecurityErrors.AccountDisabled => "L'account è disattivato: rivolgiti all'amministratore.",
SecurityErrors.TemporaryPasswordExpired => "La password provvisoria è scaduta: chiedine una nuova all'amministratore.",
SecurityErrors.PasswordTooShort => "La nuova password è troppo corta: servono almeno 10 caratteri.",
SecurityErrors.PasswordTooSimple => "La nuova password deve contenere almeno tre tipi di carattere tra minuscole, maiuscole, cifre e simboli.",
SecurityErrors.PasswordContainsUserName => "La nuova password non può contenere il nome utente.",
SecurityErrors.PasswordReused => "La nuova password è uguale a una delle ultime cinque.",
SecurityErrors.CurrentPasswordWrong => "La password attuale non è corretta.",
SecurityErrors.TotpInvalid => "Codice non valido: controlla l'ora del telefono e riprova.",
SecurityErrors.RateLimited => "Troppi tentativi: riprova tra un minuto.",
SecurityErrors.ConcurrentUsersExceeded => "È stato raggiunto il numero massimo di utenti collegati previsto dalla licenza.",
SecurityErrors.CompanyUnavailable => "L'azienda è in manutenzione o non è disponibile.",
SecurityErrors.LicenseLimitReached => "La licenza non consente altri accessi di questo tipo.",
_ => "Accesso non riuscito.",
};
private static string Carry(string? returnUrl) =>
SafeReturnUrl(returnUrl) is var url && url != "/" ? "?returnUrl=" + Uri.EscapeDataString(url) : string.Empty;
}
@@ -0,0 +1,216 @@
using System.Globalization;
using System.Security.Claims;
using System.Text.Encodings.Web;
using Khaemhat.Application.Configuration;
using Khaemhat.Application.Security;
using Khaemhat.Core.Security;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Components.Server;
using Microsoft.Extensions.Options;
namespace Khaemhat.Web.Security;
/// <summary>The session cookie and the claims built from it.</summary>
public static class SessionCookie
{
/// <summary>The authentication scheme.</summary>
public const string Scheme = "KhaemhatSession";
/// <summary>The cookie name.</summary>
public const string Name = "khaemhat_session";
/// <summary>Claim: the session row.</summary>
public const string SessionIdClaim = "kh:session";
/// <summary>Claim: the database holding the account (<c>_</c> for instance accounts).</summary>
public const string OwnerClaim = "kh:owner";
/// <summary>Claim: the account row.</summary>
public const string UserIdClaim = "kh:user";
/// <summary>Claim: the level.</summary>
public const string LevelClaim = "kh:level";
/// <summary>Claim: the company the session works in.</summary>
public const string CompanyClaim = "kh:company";
/// <summary>Claim: the linked company user of an administrator.</summary>
public const string LinkedUserClaim = "kh:linked";
/// <summary>Claim: the name shown.</summary>
public const string DisplayNameClaim = "kh:display";
/// <summary>Sets the cookie.</summary>
/// <param name="context">The request.</param>
/// <param name="value">The cookie value.</param>
/// <param name="persistentUntil">Expiry for "remember me"; <see langword="null"/> for a browser-session cookie.</param>
public static void Write(HttpContext context, string value, DateTimeOffset? persistentUntil = null)
{
ArgumentNullException.ThrowIfNull(context);
context.Response.Cookies.Append(Name, value, Options(context, persistentUntil));
}
/// <summary>Removes the cookie.</summary>
/// <param name="context">The request.</param>
public static void Clear(HttpContext context)
{
ArgumentNullException.ThrowIfNull(context);
context.Response.Cookies.Delete(Name, Options(context, null));
}
/// <summary>The cookie of the request.</summary>
/// <param name="context">The request.</param>
/// <returns>The value, or <see langword="null"/>.</returns>
public static string? Read(HttpContext context) => context?.Request.Cookies[Name];
/// <summary>The claims of a signed-in session.</summary>
/// <param name="identity">The session.</param>
/// <returns>The principal.</returns>
public static ClaimsPrincipal Principal(SessionIdentity identity)
{
ArgumentNullException.ThrowIfNull(identity);
var claims = new List<Claim>
{
new(ClaimTypes.Name, identity.UserName),
new(DisplayNameClaim, identity.DisplayName),
new(SessionIdClaim, identity.SessionId.ToString(CultureInfo.InvariantCulture)),
new(OwnerClaim, identity.Owner.CompanyDatabase ?? "_"),
new(UserIdClaim, identity.Owner.UserId.ToString(CultureInfo.InvariantCulture)),
new(LevelClaim, identity.Level.ToString()),
};
if (identity.CompanyCode is not null)
{
claims.Add(new Claim(CompanyClaim, identity.CompanyCode));
}
if (identity.LinkedUserId is { } linked)
{
claims.Add(new Claim(LinkedUserClaim, linked.ToString(CultureInfo.InvariantCulture)));
}
return new ClaimsPrincipal(new ClaimsIdentity(claims, Scheme, ClaimTypes.Name, LevelClaim));
}
/// <summary>The actor of a principal built by <see cref="Principal"/>.</summary>
/// <param name="user">The principal.</param>
/// <returns>The actor, or <see langword="null"/> when not signed in.</returns>
public static Actor? ActorOf(ClaimsPrincipal? user)
{
if (user?.Identity is not { IsAuthenticated: true, Name: { } name } || OwnerOf(user) is not { } owner)
{
return null;
}
var level = Enum.TryParse<UserLevel>(user.FindFirst(LevelClaim)?.Value, out var parsed) ? parsed : UserLevel.Standard;
var company = user.FindFirst(CompanyClaim)?.Value;
var linked = long.TryParse(user.FindFirst(LinkedUserClaim)?.Value, NumberStyles.None, CultureInfo.InvariantCulture, out var l) ? l : (long?)null;
return owner.IsInstanceAccount
? new Actor(name, level, owner.UserId, linked, company)
: new Actor(name, UserLevel.Standard, null, owner.UserId, company);
}
/// <summary>The account of a principal.</summary>
/// <param name="user">The principal.</param>
/// <returns>The owner, or <see langword="null"/>.</returns>
public static SessionOwner? OwnerOf(ClaimsPrincipal? user)
{
var database = user?.FindFirst(OwnerClaim)?.Value;
return database is not null && long.TryParse(user!.FindFirst(UserIdClaim)?.Value, NumberStyles.None, CultureInfo.InvariantCulture, out var id)
? new SessionOwner(database == "_" ? null : database, id)
: null;
}
/// <summary>The session row of a principal.</summary>
/// <param name="user">The principal.</param>
/// <returns>The session id, or <see langword="null"/>.</returns>
public static long? SessionIdOf(ClaimsPrincipal? user) =>
long.TryParse(user?.FindFirst(SessionIdClaim)?.Value, NumberStyles.None, CultureInfo.InvariantCulture, out var id) ? id : null;
private static CookieOptions Options(HttpContext context, DateTimeOffset? persistentUntil)
{
var publicUrl = context.RequestServices.GetService<KhaemhatOptions>()?.PublicUrl;
return new CookieOptions
{
HttpOnly = true,
IsEssential = true,
SameSite = SameSiteMode.Lax,
Path = "/",
Secure = context.Request.IsHttps || (publicUrl?.StartsWith("https://", StringComparison.OrdinalIgnoreCase) ?? false),
Expires = persistentUntil,
};
}
}
/// <summary>
/// Authenticates requests with the session cookie (SPEC §7.3): only sessions that completed every sign-in step count;
/// a pending session (TOTP, password change) is handled by the login pages themselves.
/// </summary>
/// <param name="options">The scheme options.</param>
/// <param name="logger">The log factory.</param>
/// <param name="encoder">The URL encoder.</param>
/// <param name="signIn">Resolves sessions.</param>
internal sealed class SessionAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options, ILoggerFactory logger, UrlEncoder encoder, SignInService signIn)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
/// <summary>The key of the resolved identity in <see cref="HttpContext.Items"/>.</summary>
public const string IdentityItem = "kh:identity";
/// <inheritdoc />
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var cookie = SessionCookie.Read(Context);
if (string.IsNullOrEmpty(cookie))
{
return AuthenticateResult.NoResult();
}
var identity = await signIn.ResolveAsync(cookie, Context.RequestAborted).ConfigureAwait(false);
if (identity is null)
{
return AuthenticateResult.NoResult();
}
Context.Items[IdentityItem] = identity;
return identity.State == SessionState.Active
? AuthenticateResult.Success(new AuthenticationTicket(SessionCookie.Principal(identity), SessionCookie.Scheme))
: AuthenticateResult.NoResult();
}
/// <inheritdoc />
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
var path = Request.Path + Request.QueryString;
Response.Redirect("/login" + (path.Length > 1 ? "?returnUrl=" + Uri.EscapeDataString(path) : string.Empty));
return Task.CompletedTask;
}
/// <inheritdoc />
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
{
Response.Redirect("/accesso-negato");
return Task.CompletedTask;
}
}
/// <summary>
/// Checks every minute that the session behind an open Blazor circuit is still valid: a revoked or expired session
/// (sign-out elsewhere, maintenance, disabled account) ends the circuit's authentication.
/// </summary>
/// <param name="loggerFactory">The log factory.</param>
/// <param name="sessions">The sessions.</param>
internal sealed class SessionRevalidatingStateProvider(ILoggerFactory loggerFactory, SessionStore sessions)
: RevalidatingServerAuthenticationStateProvider(loggerFactory)
{
/// <inheritdoc />
protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(1);
/// <inheritdoc />
protected override async Task<bool> ValidateAuthenticationStateAsync(AuthenticationState authenticationState, CancellationToken cancellationToken)
{
var user = authenticationState.User;
return SessionCookie.OwnerOf(user) is { } owner && SessionCookie.SessionIdOf(user) is { } id
&& await sessions.IsActiveAsync(owner, id, cancellationToken).ConfigureAwait(false);
}
}
@@ -0,0 +1,46 @@
using System.Security.Claims;
using Khaemhat.Application.Instance;
using Microsoft.AspNetCore.Components.Authorization;
namespace Khaemhat.Web.Security;
/// <summary>
/// The company of a Blazor circuit or of an HTTP request: the user comes from the authentication state of the circuit,
/// or from the request outside circuits, where an API call may also name the company in <c>X-Company</c>.
/// </summary>
/// <param name="authentication">The authentication state of the circuit.</param>
/// <param name="http">The current request, outside circuits.</param>
/// <param name="resolver">The rules.</param>
internal sealed class WebCompanyContext(AuthenticationStateProvider authentication, IHttpContextAccessor http, CompanyContextResolver resolver) : ICompanyContext
{
private CompanyContextResult? _result;
/// <inheritdoc />
public async ValueTask<CompanyContextResult> GetAsync(CancellationToken cancellationToken = default)
{
if (_result is not null)
{
return _result;
}
ClaimsPrincipal? user;
string? requested = null;
try
{
user = (await authentication.GetAuthenticationStateAsync().ConfigureAwait(false)).User;
}
catch (InvalidOperationException)
{
// Outside a circuit the authentication state is not set: use the request.
var context = http.HttpContext;
user = context?.User;
if (context?.Request.Path.StartsWithSegments("/api") == true)
{
requested = context.Request.Headers[CompanyContextResolver.Header].ToString();
}
}
_result = await resolver.ResolveAsync(SessionCookie.ActorOf(user), requested, cancellationToken).ConfigureAwait(false);
return _result;
}
}
+51
View File
@@ -29,3 +29,54 @@ body { font-family: var(--kh-font); font-size: 13px; background: var(--kh-bg); -
#blazor-error-ui { background: #FADEDC; color: #1E2733; bottom: 0; box-shadow: 0 -1px 2px rgba(0, 0, 0, .2);
display: none; left: 0; padding: .6rem 1.25rem .7rem 1.25rem; position: fixed; width: 100%; z-index: 1000; }
#blazor-error-ui .dismiss { cursor: pointer; position: absolute; right: .75rem; top: .5rem; }
/* Sign-in pages (mockups 001-003): brand panel on the left, form card on the right. */
.kh-auth { min-height: 100vh; display: grid; grid-template-columns: minmax(320px, 52%) 1fr; color: #1E2733; }
.kh-auth .brand { display: flex; flex-direction: column; justify-content: space-between; padding: 48px 44px 36px; color: #E8EDF5;
background: radial-gradient(1100px 620px at 15% 0%, #243A5E 0%, #17243A 55%, #0F1826 100%); }
.kh-auth .brand .mark { border-radius: 14px; box-shadow: 0 10px 30px rgba(0, 0, 0, .35); }
.kh-auth .brand h2 { font-size: 30px; letter-spacing: -.5px; margin: 18px 0 10px; font-weight: 650; }
.kh-auth .brand p { max-width: 460px; color: #B8C5DA; font-size: 14px; line-height: 1.5; margin: 0; }
.kh-auth .features { list-style: none; margin: 32px 0 0; padding: 0; display: grid; grid-template-columns: 1fr 1fr; gap: 10px; }
.kh-auth .features li { padding: 10px 12px; border-radius: 8px; font-size: 11.5px; color: #B8C5DA; line-height: 1.4;
background: rgba(255, 255, 255, .05); border: 1px solid rgba(255, 255, 255, .09); }
.kh-auth .features strong { display: block; color: #E8EDF5; font-weight: 600; margin-bottom: 2px; }
.kh-auth .panel { display: flex; flex-direction: column; align-items: center; justify-content: center; padding: 32px 24px; background: var(--kh-bg); }
.kh-auth .card { width: 100%; max-width: 380px; }
.kh-auth h1 { font-size: 20px; margin: 0 0 4px; font-weight: 650; }
.kh-auth .sub { color: #5B6776; margin: 0 0 18px; line-height: 1.45; }
.kh-auth footer { margin-top: 28px; font-size: 11.5px; color: #8A95A3; }
.kh-auth footer a { color: #1F5FA8; text-decoration: none; }
.kh-form { display: flex; flex-direction: column; gap: 4px; }
.kh-form label { font-size: 11.5px; font-weight: 600; color: #5B6776; margin-top: 8px; }
.kh-form input[type=text], .kh-form input[type=password], .kh-form input:not([type]), .kh-form select {
height: 32px; padding: 0 10px; border: 1px solid #C5CDD7; border-radius: 6px; background: #FFF; font: inherit; color: inherit; }
.kh-form input:focus, .kh-form select:focus { outline: 2px solid #1F5FA8; outline-offset: -1px; border-color: #1F5FA8; }
.kh-form .check { display: flex; align-items: center; gap: 8px; font-weight: 400; color: #1E2733; margin-top: 12px; }
.kh-form .otp { height: 44px; font-size: 22px; letter-spacing: 8px; text-align: center; font-variant-numeric: tabular-nums; }
.kh-form .row { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-top: 12px; }
.kh-form .row .kh-btn { margin-top: 0; }
.kh-form .hint { font-size: 11.5px; color: #8A95A3; }
.kh-btn { display: inline-flex; align-items: center; justify-content: center; height: 32px; padding: 0 14px; margin-top: 16px; border-radius: 6px;
border: 1px solid transparent; font: inherit; font-weight: 600; cursor: pointer; text-decoration: none; }
.kh-btn.primary { background: #1F5FA8; color: #FFF; align-self: flex-start; }
.kh-btn.primary:hover { background: #174A85; }
.kh-btn.ghost { background: transparent; color: #F0C86A; border-color: rgba(240, 200, 106, .5); }
.kh-alert { padding: 10px 12px; border-radius: 6px; margin: 12px 0; line-height: 1.45; font-size: 12.5px; }
.kh-alert.err { background: #FADEDC; color: #9E362D; }
.kh-alert.warn { background: #FBEFD9; color: #8B5511; margin-top: 20px; }
.kh-alert.info { background: #E3ECF8; color: #174A85; margin-top: 20px; }
.kh-rules { margin: 10px 0 0; padding-left: 18px; color: #5B6776; font-size: 11.5px; line-height: 1.6; }
.kh-secret { margin: 0 0 6px; }
.kh-secret dt { font-size: 11.5px; font-weight: 600; color: #5B6776; margin-top: 8px; }
.kh-secret dd { margin: 4px 0 0; }
.kh-secret code { font-size: 15px; letter-spacing: 1px; word-break: break-all; }
.kh-codes { list-style: none; padding: 0; margin: 0 0 8px; display: grid; grid-template-columns: 1fr 1fr; gap: 6px; }
.kh-codes code { display: block; padding: 6px 8px; background: #FFF; border: 1px solid #DDE3EA; border-radius: 6px; text-align: center; font-size: 14px; }
@media (max-width: 760px) {
.kh-auth { grid-template-columns: 1fr; }
.kh-auth .brand { padding: 24px; }
.kh-auth .features { display: none; }
}