F1 and "?" now open the wiki page of the screen inside the application (/aiuto, mockup 011) from a copy of the wiki shipped next to the program, so help works offline and always matches the installed version. Markdown is converted in-house and fully encoded; images of the repository are served from the copy. KHAEMHAT_HELP_URL sets the online wiki behind "Apri nel wiki"; "Segnala un problema" opens a new issue of that repo. A test checks that every page and menu entry has an existing wiki page. The bell opens a notifications panel (mockup 010) with all/unread filters and mark read. Broadcast notifications are now read per user through sys_notification_reads / notification_reads instead of one shared read_at. The global search asks ISearchProvider implementations through GlobalSearchService after a short pause; the first provider finds help pages and sections, # and @ say which modules will fill them. Escape also closes a side panel when the focus fell out of it. Decisions in ADR 0023. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
368 lines
15 KiB
C#
368 lines
15 KiB
C#
using System.Globalization;
|
|
using System.Net.Mail;
|
|
using Khaemhat.Application.Security;
|
|
using Khaemhat.Data;
|
|
using Microsoft.Extensions.Logging;
|
|
|
|
namespace Khaemhat.Application.Configuration;
|
|
|
|
/// <summary>How the licences behave (<c>KHAEMHAT_LICENSE_MODE</c>).</summary>
|
|
public enum LicenseMode
|
|
{
|
|
/// <summary>Only signed licences count.</summary>
|
|
Production = 0,
|
|
|
|
/// <summary>The fictitious codes of SPEC §8.3 are accepted too. Never in production.</summary>
|
|
Test = 1,
|
|
}
|
|
|
|
/// <summary>The connection security of the mail server.</summary>
|
|
public enum SmtpSecurity
|
|
{
|
|
/// <summary>STARTTLS on a plain connection (port 587).</summary>
|
|
StartTls = 0,
|
|
|
|
/// <summary>TLS from the start (port 465).</summary>
|
|
Ssl = 1,
|
|
|
|
/// <summary>No encryption: only for a local relay.</summary>
|
|
None = 2,
|
|
}
|
|
|
|
/// <summary>A configuration that does not let the instance start. The message lists every problem, never a value.</summary>
|
|
public sealed class ConfigurationException : Exception
|
|
{
|
|
/// <summary>Creates the exception.</summary>
|
|
public ConfigurationException()
|
|
: this([])
|
|
{
|
|
}
|
|
|
|
/// <summary>Creates the exception.</summary>
|
|
/// <param name="message">The message.</param>
|
|
public ConfigurationException(string message)
|
|
: base(message) => Errors = [message];
|
|
|
|
/// <summary>Creates the exception.</summary>
|
|
/// <param name="message">The message.</param>
|
|
/// <param name="innerException">The cause.</param>
|
|
public ConfigurationException(string message, Exception innerException)
|
|
: base(message, innerException) => Errors = [message];
|
|
|
|
/// <summary>Creates the exception from a list of problems.</summary>
|
|
/// <param name="errors">The problems.</param>
|
|
public ConfigurationException(IReadOnlyList<string> errors)
|
|
: base(Describe(errors)) => Errors = errors;
|
|
|
|
/// <summary>The problems, one per line of the message.</summary>
|
|
public IReadOnlyList<string> Errors { get; }
|
|
|
|
private static string Describe(IReadOnlyList<string> errors) =>
|
|
"Khaemhat cannot start: the configuration is not valid (see docs/DEPLOY.md and the wiki page Installazione-Docker)."
|
|
+ string.Concat((errors ?? []).Select(e => Environment.NewLine + " - " + e));
|
|
}
|
|
|
|
/// <summary>
|
|
/// The instance configuration of SPEC §6, read from the environment by <see cref="EnvironmentConfigurationReader"/>.
|
|
/// Values stay in memory: nothing is written to disk. <see cref="Validate"/> checks everything before the host starts;
|
|
/// the typed accessors (<see cref="SystemDatabase"/>, <see cref="Mode"/>...) are meant for a validated instance.
|
|
/// </summary>
|
|
public sealed class KhaemhatOptions
|
|
{
|
|
/// <summary><c>KHAEMHAT_SYSTEM_DB</c>: the system database URL (required).</summary>
|
|
public string? SystemDb { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_DB_SERVER</c>: the PostgreSQL server where company databases are created.</summary>
|
|
public string? DbServer { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SECRET_KEY</c>: base64 of at least 32 bytes (required).</summary>
|
|
public string? SecretKey { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SECRET_KEY_NEW</c>: the new key during a rotation (SPEC §12.9).</summary>
|
|
public string? RotationSecretKey { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SUPERUSER</c>: the super user name, read only while <c>sys_users</c> is empty.</summary>
|
|
public string? SuperUser { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SUPERUSER_PASSWORD</c>: its first password, to change at the first access.</summary>
|
|
public string? SuperUserPassword { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SUPERUSER_EMAIL</c>: its e-mail address.</summary>
|
|
public string? SuperUserEmail { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_COMPANY_CODE</c>: the first company, read only while <c>sys_companies</c> is empty.</summary>
|
|
public string? CompanyCode { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_COMPANY_NAME</c>: its name.</summary>
|
|
public string? CompanyName { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_COUNTRY</c>: the fiscal package of the first company (default <c>IT</c>).</summary>
|
|
public string Country { get; init; } = "IT";
|
|
|
|
/// <summary><c>KHAEMHAT_LICENSE_MODE</c>: <c>production</c> (default) or <c>test</c>.</summary>
|
|
public string LicenseMode { get; init; } = "production";
|
|
|
|
/// <summary><c>KHAEMHAT_LICENSE</c>: the text of a <c>.khl</c> licence; absent means Trial.</summary>
|
|
public string? License { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_REDIS</c>: <c>redis://</c> or <c>rediss://</c>; absent means in-memory cache.</summary>
|
|
public string? Redis { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_DATA_DIR</c>: the only folder the instance writes to (default <c>/data</c>).</summary>
|
|
public string DataDir { get; init; } = "/data";
|
|
|
|
/// <summary><c>KHAEMHAT_URLS</c>: the listening addresses.</summary>
|
|
public string? Urls { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_PUBLIC_URL</c>: the address users reach, for links in e-mails.</summary>
|
|
public string? PublicUrl { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SMTP_HOST</c>.</summary>
|
|
public string? SmtpHost { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SMTP_PORT</c>.</summary>
|
|
public string? SmtpPort { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SMTP_USER</c>.</summary>
|
|
public string? SmtpUser { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SMTP_PASSWORD</c>.</summary>
|
|
public string? SmtpPassword { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SMTP_FROM</c>.</summary>
|
|
public string? SmtpFrom { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SMTP_SECURITY</c>: <c>starttls</c> (default), <c>ssl</c> or <c>none</c>.</summary>
|
|
public string? SmtpSecurity { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_LOG_LEVEL</c>: the minimum level on stdout.</summary>
|
|
public string? LogLevel { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SEED_BASE</c>: load the base tables when a company is created (default true).</summary>
|
|
public string? SeedBase { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_SEED_DEMO</c>: load the demo data into an empty company (default false).</summary>
|
|
public string? SeedDemo { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_UPDATE_FEED</c>: the package list read by the update check.</summary>
|
|
public string? UpdateFeed { get; init; }
|
|
|
|
/// <summary><c>KHAEMHAT_UPDATE_TOKEN</c>: a read-only token for the feed.</summary>
|
|
public string? UpdateToken { get; init; }
|
|
|
|
/// <summary>
|
|
/// <c>KHAEMHAT_HELP_URL</c>: the online wiki opened by "Apri nel wiki" (default the project wiki). The help itself
|
|
/// is the copy of the wiki shipped in the image, so it works offline.
|
|
/// </summary>
|
|
public string? HelpUrl { get; init; }
|
|
|
|
/// <summary><c>TZ</c>: the time zone of the container.</summary>
|
|
public string? TimeZone { get; init; }
|
|
|
|
/// <summary>The problems met while reading (both <c>X</c> and <c>X_FILE</c>, unreadable files).</summary>
|
|
public IReadOnlyList<string> ReadErrors { get; init; } = [];
|
|
|
|
/// <summary>The system database, parsed.</summary>
|
|
public DatabaseUrl SystemDatabase => DatabaseUrl.Parse(SystemDb ?? throw new ConfigurationException("KHAEMHAT_SYSTEM_DB is not set."));
|
|
|
|
/// <summary>
|
|
/// Where company databases are created: <see cref="DbServer"/> when set, otherwise the server (PostgreSQL) or the
|
|
/// folder (SQLite) of the system database.
|
|
/// </summary>
|
|
public DatabaseUrl CompanyServer => DbServer is { } server ? DatabaseUrl.Parse(server) : SystemDatabase;
|
|
|
|
/// <summary>The licence mode, parsed.</summary>
|
|
public LicenseMode Mode => string.Equals(LicenseMode, "test", StringComparison.OrdinalIgnoreCase)
|
|
? Configuration.LicenseMode.Test
|
|
: Configuration.LicenseMode.Production;
|
|
|
|
/// <summary>Whether base data is loaded into new companies.</summary>
|
|
public bool SeedBaseEnabled => ParseBool(SeedBase) ?? true;
|
|
|
|
/// <summary>Whether demo data is loaded into new, empty companies.</summary>
|
|
public bool SeedDemoEnabled => ParseBool(SeedDemo) ?? false;
|
|
|
|
/// <summary>The SMTP port, defaulting by security mode.</summary>
|
|
public int SmtpPortNumber => int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port)
|
|
? port
|
|
: SmtpSecurityMode == Configuration.SmtpSecurity.Ssl ? 465 : 587;
|
|
|
|
/// <summary>The SMTP security, parsed.</summary>
|
|
public SmtpSecurity SmtpSecurityMode => SmtpSecurity?.ToUpperInvariant() switch
|
|
{
|
|
"SSL" or "TLS" => Configuration.SmtpSecurity.Ssl,
|
|
"NONE" => Configuration.SmtpSecurity.None,
|
|
_ => Configuration.SmtpSecurity.StartTls,
|
|
};
|
|
|
|
/// <summary>
|
|
/// Checks the whole configuration. Messages name the variable and the expected form, never its value.
|
|
/// The variables needed only at first start (super user, first company) are checked by the bootstrap, which knows
|
|
/// whether the tables are still empty; here only their form is checked when they are set.
|
|
/// </summary>
|
|
/// <returns>The problems; empty when the instance can start.</returns>
|
|
public IReadOnlyList<string> Validate()
|
|
{
|
|
var errors = new List<string>(ReadErrors);
|
|
|
|
if (SystemDb is null)
|
|
{
|
|
if (!ReadErrors.Any(e => e.StartsWith("KHAEMHAT_SYSTEM_DB", StringComparison.Ordinal)))
|
|
{
|
|
errors.Add("KHAEMHAT_SYSTEM_DB is required: postgres://user:password@host:5432/khaemhat_system or sqlite:///data/system.db.");
|
|
}
|
|
}
|
|
else if (!DatabaseUrl.TryParse(SystemDb, out _))
|
|
{
|
|
errors.Add("KHAEMHAT_SYSTEM_DB is not a valid database URL: use postgres://user:password@host:5432/khaemhat_system or sqlite:///data/system.db.");
|
|
}
|
|
|
|
if (DbServer is not null && (!DatabaseUrl.TryParse(DbServer, out var server) || server.Engine != DbEngine.PostgreSql))
|
|
{
|
|
errors.Add("KHAEMHAT_DB_SERVER must be a PostgreSQL server URL: postgres://user:password@host:5432/ (a role with CREATEDB).");
|
|
}
|
|
|
|
CheckKey("KHAEMHAT_SECRET_KEY", SecretKey, required: true, errors);
|
|
CheckKey("KHAEMHAT_SECRET_KEY_NEW", RotationSecretKey, required: false, errors);
|
|
|
|
if (SuperUser is not null && !UserNames.IsValid(SuperUser))
|
|
{
|
|
errors.Add("KHAEMHAT_SUPERUSER must be 3 to 50 characters: letters, digits, dot, dash or underscore.");
|
|
}
|
|
|
|
if (SuperUserEmail is not null && !IsEmail(SuperUserEmail))
|
|
{
|
|
errors.Add("KHAEMHAT_SUPERUSER_EMAIL is not a valid e-mail address.");
|
|
}
|
|
|
|
if (CompanyCode is not null && !CompanyCodes.IsValid(CompanyCode.Trim().ToUpperInvariant()))
|
|
{
|
|
errors.Add("KHAEMHAT_COMPANY_CODE must be 1 to 20 characters: letters, digits or underscore, starting with a letter.");
|
|
}
|
|
|
|
if (CompanyName is { Length: > 200 })
|
|
{
|
|
errors.Add("KHAEMHAT_COMPANY_NAME is longer than 200 characters.");
|
|
}
|
|
|
|
if (!string.Equals(Country, "IT", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
errors.Add("KHAEMHAT_COUNTRY: the only fiscal package available is IT.");
|
|
}
|
|
|
|
if (!string.Equals(LicenseMode, "production", StringComparison.OrdinalIgnoreCase)
|
|
&& !string.Equals(LicenseMode, "test", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
errors.Add("KHAEMHAT_LICENSE_MODE must be production or test.");
|
|
}
|
|
|
|
if (Redis is not null && !(Uri.TryCreate(Redis, UriKind.Absolute, out var redis) && redis.Scheme is "redis" or "rediss"))
|
|
{
|
|
errors.Add("KHAEMHAT_REDIS must be redis://[:password@]host:6379/0 or rediss:// for TLS.");
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(DataDir) || !Path.IsPathFullyQualified(DataDir))
|
|
{
|
|
errors.Add("KHAEMHAT_DATA_DIR must be an absolute path (default /data).");
|
|
}
|
|
|
|
if (PublicUrl is not null && !IsHttpUrl(PublicUrl))
|
|
{
|
|
errors.Add("KHAEMHAT_PUBLIC_URL must be an absolute http or https address, for example https://gestionale.example.com.");
|
|
}
|
|
|
|
if (HelpUrl is not null && !IsHttpUrl(HelpUrl))
|
|
{
|
|
errors.Add("KHAEMHAT_HELP_URL must be an absolute http or https address, for example https://gitea.example.com/owner/khaemhat/wiki/.");
|
|
}
|
|
|
|
if (SmtpPort is not null && !(int.TryParse(SmtpPort, NumberStyles.None, CultureInfo.InvariantCulture, out var port) && port is > 0 and < 65536))
|
|
{
|
|
errors.Add("KHAEMHAT_SMTP_PORT must be a port number between 1 and 65535.");
|
|
}
|
|
|
|
if (SmtpSecurity is not null && SmtpSecurity.ToUpperInvariant() is not ("STARTTLS" or "SSL" or "TLS" or "NONE"))
|
|
{
|
|
errors.Add("KHAEMHAT_SMTP_SECURITY must be starttls, ssl or none.");
|
|
}
|
|
|
|
if (SmtpFrom is not null && !IsEmail(SmtpFrom))
|
|
{
|
|
errors.Add("KHAEMHAT_SMTP_FROM is not a valid e-mail address.");
|
|
}
|
|
|
|
if (LogLevel is not null && !(Enum.TryParse<LogLevel>(LogLevel, ignoreCase: true, out var level) && Enum.IsDefined(level)))
|
|
{
|
|
errors.Add("KHAEMHAT_LOG_LEVEL must be Trace, Debug, Information, Warning, Error, Critical or None.");
|
|
}
|
|
|
|
if (SeedBase is not null && ParseBool(SeedBase) is null)
|
|
{
|
|
errors.Add("KHAEMHAT_SEED_BASE must be true or false.");
|
|
}
|
|
|
|
if (SeedDemo is not null && ParseBool(SeedDemo) is null)
|
|
{
|
|
errors.Add("KHAEMHAT_SEED_DEMO must be true or false.");
|
|
}
|
|
|
|
if (UpdateFeed is not null && !IsHttpUrl(UpdateFeed))
|
|
{
|
|
errors.Add("KHAEMHAT_UPDATE_FEED must be an absolute http or https address.");
|
|
}
|
|
|
|
if (TimeZone is not null && !TimeZoneInfo.TryFindSystemTimeZoneById(TimeZone, out _))
|
|
{
|
|
errors.Add("TZ is not a known time zone, for example Europe/Rome.");
|
|
}
|
|
|
|
return errors;
|
|
}
|
|
|
|
/// <summary>Throws when <see cref="Validate"/> finds problems.</summary>
|
|
/// <exception cref="ConfigurationException">The configuration is not valid.</exception>
|
|
public void EnsureValid()
|
|
{
|
|
var errors = Validate();
|
|
if (errors.Count > 0)
|
|
{
|
|
throw new ConfigurationException(errors);
|
|
}
|
|
}
|
|
|
|
private static void CheckKey(string name, string? value, bool required, List<string> errors)
|
|
{
|
|
if (value is null)
|
|
{
|
|
if (required)
|
|
{
|
|
errors.Add($"{name} is required: the base64 of at least 32 random bytes (for example: openssl rand -base64 32).");
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
try
|
|
{
|
|
_ = Infrastructure.Security.SecretKey.FromBase64(value);
|
|
}
|
|
catch (FormatException ex)
|
|
{
|
|
errors.Add(ex.Message.Replace("KHAEMHAT_SECRET_KEY", name, StringComparison.Ordinal));
|
|
}
|
|
}
|
|
|
|
private static bool? ParseBool(string? value) => value?.Trim().ToUpperInvariant() switch
|
|
{
|
|
null => null,
|
|
"TRUE" or "1" or "YES" or "SI" => true,
|
|
"FALSE" or "0" or "NO" => false,
|
|
_ => null,
|
|
};
|
|
|
|
private static bool IsHttpUrl(string value) =>
|
|
Uri.TryCreate(value, UriKind.Absolute, out var uri) && (uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps);
|
|
|
|
private static bool IsEmail(string value) => MailAddress.TryCreate(value, out var address) && address.Address == value.Trim();
|
|
}
|