feat: Kh component library, record pages and profile security (M3, part 2)

Adds the building blocks every later screen uses, so modules are built from
one set of components instead of ad hoc markup:

- Form components (KhForm, KhTextBox, KhNumberBox, KhDateBox, KhSelect,
  KhCheck, KhSwitch, KhHotlink) with Italian number and date input, inline
  calculation (=10*3), field messages plus a summary that focuses the field,
  and service errors added by field name.
- Display and window components (panels, tiles, badges, chips, money, tabs
  with Alt+1..9, steps, dialog, side drawer and DrawerService).
- KhIconToolbar that keeps one line and moves less used commands into the
  "..." menu, KhDocHead, and the RecordPage/DocumentPage/MasterDataPage bases
  with standard commands, shortcuts and save/cancel/delete flow (#27, #29).
- Development-only component catalog and sample document page.
- Profile: personal data, password change that ends other sessions, TOTP
  enable/disable and recovery codes through ProfileService (#31).

Refs #27 #29 #31

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-11 18:11:16 +01:00
1 parent cf6f849cc1
commit d958e7372d
57 files changed
+5249 -12

No files matched your search

@@ -237,11 +237,40 @@ public sealed class AccountSecurity
}
account.TotpEnabled = true;
return NewRecoveryCodes(account);
}
/// <summary>Replaces the recovery codes with ten new ones; the old ones stop working.</summary>
/// <param name="account">The account.</param>
/// <returns>The new codes, to show once.</returns>
public static IReadOnlyList<string> NewRecoveryCodes(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
var codes = Enumerable.Range(0, 10).Select(_ => SecureTokenGenerator.CreateReadableCode(2)).ToList();
account.TotpRecoveryCodes = JsonSerializer.Serialize(codes.Select(c => SecureTokenGenerator.Hash(c)).ToList());
return codes;
}
/// <summary>How many recovery codes are still unused.</summary>
/// <param name="account">The account.</param>
/// <returns>The number of codes left.</returns>
public static int RecoveryCodesLeft(IAccount account)
{
ArgumentNullException.ThrowIfNull(account);
return account.TotpEnabled ? Deserialize(account.TotpRecoveryCodes).Count : 0;
}
/// <summary>Checks the current password without counting failures (profile changes that ask for it again).</summary>
/// <param name="account">The account.</param>
/// <param name="password">The password typed.</param>
/// <returns>Whether it is right.</returns>
public static bool IsCurrentPassword(IAccount account, string password)
{
ArgumentNullException.ThrowIfNull(account);
ArgumentNullException.ThrowIfNull(password);
return account.PasswordHash is not null && PasswordHasher.Verify(account.PasswordHash, password) != PasswordVerification.Failed;
}
/// <summary>Checks a TOTP code at sign-in. A code is never accepted twice.</summary>
/// <param name="account">The account.</param>
/// <param name="code">The code.</param>
@@ -0,0 +1,270 @@
using System.Net.Mail;
using Khaemhat.Application.Audit;
using Khaemhat.Core.Security;
using Khaemhat.Infrastructure.Security;
namespace Khaemhat.Application.Security;
/// <summary>What the profile page shows about the signed-in account (SPEC §12, mockup 008).</summary>
/// <param name="UserName">The sign-in name.</param>
/// <param name="DisplayName">The name shown in the interface.</param>
/// <param name="Email">The e-mail address.</param>
/// <param name="IsInstanceAccount">Whether it is an instance account (super user or administrator).</param>
/// <param name="TotpEnabled">Whether the two-step verification is active.</param>
/// <param name="TotpRequired">Whether the two-step verification is mandatory, so it cannot be turned off.</param>
/// <param name="RecoveryCodesLeft">Unused recovery codes.</param>
/// <param name="HasPassword">Whether the account signs in with a password (technical users do not).</param>
/// <param name="PasswordChangedAt">When the password was last set (UTC).</param>
/// <param name="LastLoginAt">The last successful sign-in (UTC).</param>
public sealed record ProfileInfo(
string UserName,
string DisplayName,
string? Email,
bool IsInstanceAccount,
bool TotpEnabled,
bool TotpRequired,
int RecoveryCodesLeft,
bool HasPassword,
DateTime? PasswordChangedAt,
DateTime? LastLoginAt);
/// <summary>
/// The changes users make to their own account from the profile (SPEC §12, issue #31): name and e-mail, password,
/// two-step verification and recovery codes. Unlike <see cref="SignInService"/> it works from the session owner, not
/// from the cookie, because the profile runs in the interactive circuit where the cookie cannot be read. Every change is
/// recorded in <c>sys_security_audit</c>; a password change closes the other sessions of the account.
/// </summary>
/// <param name="systemUsers">Instance accounts.</param>
/// <param name="companyUsers">Company users.</param>
/// <param name="security">Credential rules.</param>
/// <param name="sessions">Sessions.</param>
/// <param name="audit">The security audit.</param>
public sealed class ProfileService(
SystemUserService systemUsers,
UserService companyUsers,
AccountSecurity security,
SessionStore sessions,
ISecurityAuditLog audit)
{
/// <summary>The longest display name accepted.</summary>
public const int DisplayNameMaxLength = 100;
/// <summary>The display name is empty or too long.</summary>
public const string DisplayNameInvalid = "display_name_invalid";
/// <summary>The e-mail address is not valid.</summary>
public const string EmailInvalid = "email_invalid";
/// <summary>The two-step verification is mandatory for the account and cannot be turned off.</summary>
public const string TotpRequiredError = "totp_required";
/// <summary>Reads the account of a session owner.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The profile, or <see langword="null"/> when the account no longer exists or is disabled.</returns>
public async Task<ProfileInfo?> GetAsync(SessionOwner owner, CancellationToken cancellationToken = default)
{
var account = await LoadAsync(owner, cancellationToken).ConfigureAwait(false);
return account is null ? null : InfoOf(account, owner);
}
/// <summary>Changes name and e-mail.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="displayName">The new name.</param>
/// <param name="email">The new e-mail, or empty to remove it.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The error codes; empty when saved.</returns>
public async Task<IReadOnlyList<string>> UpdateAsync(SessionOwner owner, string? displayName, string? email, CancellationToken cancellationToken = default)
{
var name = displayName?.Trim() ?? string.Empty;
var mail = string.IsNullOrWhiteSpace(email) ? null : email.Trim();
var errors = new List<string>();
if (name.Length is 0 or > DisplayNameMaxLength)
{
errors.Add(DisplayNameInvalid);
}
if (mail is not null && !IsEmail(mail))
{
errors.Add(EmailInvalid);
}
if (errors.Count > 0)
{
return errors;
}
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
account.DisplayName = name;
account.Email = mail;
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.profile-updated", account, owner, cancellationToken).ConfigureAwait(false);
return [];
}
/// <summary>Changes the password, checking the current one, and closes every other session of the account.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="currentSessionId">The session that stays open.</param>
/// <param name="currentPassword">The current password.</param>
/// <param name="newPassword">The new password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The error codes (<see cref="SecurityErrors"/>); empty when changed.</returns>
public async Task<IReadOnlyList<string>> ChangePasswordAsync(
SessionOwner owner, long? currentSessionId, string currentPassword, string newPassword, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(currentPassword);
ArgumentNullException.ThrowIfNull(newPassword);
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (!AccountSecurity.IsCurrentPassword(account, currentPassword))
{
await AuditAsync("user.password-change-refused", account, owner, cancellationToken).ConfigureAwait(false);
return [SecurityErrors.CurrentPasswordWrong];
}
var errors = security.ChangePassword(account, newPassword);
if (errors.Count > 0)
{
return errors;
}
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await sessions.RevokeAllAsync(owner, "password_changed", currentSessionId, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.password-changed", account, owner, cancellationToken).ConfigureAwait(false);
return [];
}
/// <summary>Starts turning on the two-step verification; reloading the page shows the same secret.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="companyCode">The company of the session, shown in the label of the authenticator app.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The secret to show, or <see langword="null"/> when the verification is already active.</returns>
public async Task<TotpSetup?> BeginTotpSetupAsync(SessionOwner owner, string? companyCode, CancellationToken cancellationToken = default)
{
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (account.TotpEnabled)
{
return null;
}
var secret = security.PendingTotpSecret(account);
if (secret is null)
{
secret = security.BeginTotpSetup(account);
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
}
var label = companyCode is null ? account.UserName : account.UserName + "@" + companyCode;
return new TotpSetup(secret, TotpGenerator.ProvisioningUri(secret, label));
}
/// <summary>Completes turning on the two-step verification with the first code from the app.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="code">The code.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The ten recovery codes to show once, or <see langword="null"/> when the code is wrong.</returns>
public async Task<IReadOnlyList<string>?> ConfirmTotpSetupAsync(SessionOwner owner, string code, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(code);
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (account.TotpEnabled)
{
return null;
}
var codes = security.ConfirmTotpSetup(account, code.Trim());
if (codes is null)
{
return null;
}
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.totp-enabled", account, owner, cancellationToken).ConfigureAwait(false);
return codes;
}
/// <summary>Replaces the recovery codes, asking the password again.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="password">The current password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The new codes, or <see langword="null"/> when the password is wrong or the verification is off.</returns>
public async Task<IReadOnlyList<string>?> RenewRecoveryCodesAsync(SessionOwner owner, string password, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(password);
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (!account.TotpEnabled || !AccountSecurity.IsCurrentPassword(account, password))
{
return null;
}
var codes = AccountSecurity.NewRecoveryCodes(account);
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.recovery-codes-renewed", account, owner, cancellationToken).ConfigureAwait(false);
return codes;
}
/// <summary>Turns the two-step verification off, asking the password again; refused when it is mandatory.</summary>
/// <param name="owner">The session owner.</param>
/// <param name="password">The current password.</param>
/// <param name="cancellationToken">Cancellation.</param>
/// <returns>The error codes; empty when turned off.</returns>
public async Task<IReadOnlyList<string>> DisableTotpAsync(SessionOwner owner, string password, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(password);
var account = await RequireAsync(owner, cancellationToken).ConfigureAwait(false);
if (IsTotpRequired(account, owner))
{
return [TotpRequiredError];
}
if (!AccountSecurity.IsCurrentPassword(account, password))
{
return [SecurityErrors.CurrentPasswordWrong];
}
AccountSecurity.ResetTotp(account);
await SaveAsync(account, owner, cancellationToken).ConfigureAwait(false);
await AuditAsync("user.totp-disabled", account, owner, cancellationToken).ConfigureAwait(false);
return [];
}
private static bool IsEmail(string value) =>
value.Length <= 254 && MailAddress.TryCreate(value, out var address) && address.Address == value && value.Contains('.', StringComparison.Ordinal);
private bool IsTotpRequired(IAccount account, SessionOwner owner) =>
owner.IsInstanceAccount || account is CompanyUser { TotpRequired: true } || security.Options.TotpRequiredForUsers;
private ProfileInfo InfoOf(IAccount account, SessionOwner owner) => new(
account.UserName,
account.DisplayName,
account.Email,
owner.IsInstanceAccount,
account.TotpEnabled,
IsTotpRequired(account, owner),
AccountSecurity.RecoveryCodesLeft(account),
account.PasswordHash is not null,
account.PasswordChangedAt,
account.LastLoginAt);
private async Task<IAccount?> LoadAsync(SessionOwner owner, CancellationToken cancellationToken)
{
ArgumentNullException.ThrowIfNull(owner);
IAccount? account = owner.IsInstanceAccount
? await systemUsers.GetAsync(owner.UserId, cancellationToken).ConfigureAwait(false)
: await companyUsers.GetAsync(owner.CompanyDatabase!, owner.UserId, cancellationToken).ConfigureAwait(false);
return account is { IsActive: true } ? account : null;
}
private async Task<IAccount> RequireAsync(SessionOwner owner, CancellationToken cancellationToken) =>
await LoadAsync(owner, cancellationToken).ConfigureAwait(false)
?? throw new AccessDeniedException(SecurityErrors.InvalidCredentials, "The account no longer exists or is disabled.");
private Task SaveAsync(IAccount account, SessionOwner owner, CancellationToken cancellationToken) => account switch
{
SystemUser system => systemUsers.SaveAsync(system, cancellationToken),
CompanyUser user => companyUsers.SaveAsync(owner.CompanyDatabase!, user, cancellationToken),
_ => throw new InvalidOperationException("Unknown account type."),
};
private Task AuditAsync(string action, IAccount account, SessionOwner owner, CancellationToken cancellationToken) =>
audit.WriteAsync(new SecurityEvent(action, account.UserName, owner.CompanyDatabase), cancellationToken);
}