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