Files
Khaemhat/src/Khaemhat.Web/Security/LoginFlow.cs
T
Alby96andClaude Opus 5.5 032c602b49
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
feat: system and security - start-up, accounts, sign-in, licences, log, jobs, companies (M2)
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>
2026-11-11 15:29:24 +01:00

71 lines
4.0 KiB
C#

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;
}