using Anubis.Access; using Anubis.Core; using Anubis.Db; using Anubis.Platform; namespace Anubis.Server; /// /// Form actions of the pages: plain HTML forms with the CSRF field, answered with a redirect (post, redirect, get). /// Errors travel back as a short code in the address, never with the values typed in. /// internal static partial class Forms { public static void Map(WebApplication app) { var open = app.MapGroup("/azioni").AllowAnonymous(); open.MapPost("/accesso", SignInAsync); open.MapPost("/primo-avvio/prova", TestDatabaseAsync); open.MapPost("/primo-avvio", FirstRunAsync); open.MapPost("/servizio/{choice}", ServiceChoiceAsync); var signed = app.MapGroup("/azioni").RequireAuthorization(); signed.MapPost("/esci", SignOutAsync); signed.MapPost("/primo-accesso", (IFormCollection form, AnubisHost host, StartupConfig config, HttpContext context, CancellationToken ct) => ChangePasswordAsync(form, host, context, config.AdminPassword, "/primo-accesso", "/", ct)); signed.MapPost("/password", (IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) => ChangePasswordAsync(form, host, context, null, "/impostazioni", "/impostazioni", ct)); signed.MapPost("/due-fattori/attiva", EnableSecondFactorAsync); signed.MapPost("/due-fattori/disattiva", DisableSecondFactorAsync); signed.MapPost("/impostazioni/{key}", SetSettingAsync); signed.MapPost("/bot/{command}", BotAsync); signed.MapPost("/salvataggio", BackupAsync); signed.MapPost("/conti/{id:guid}/{choice}", ResolveAccountAsync); signed.MapPost("/chiavi/{broker}", SaveKeysAsync); signed.MapPost("/chiavi/{broker}/togli", RemoveKeysAsync); signed.MapPost("/capitale/{broker}", SetCapitalAsync); signed.MapPost("/laboratorio", PlanTrialAsync); signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync); signed.MapPost("/rischio/limiti", SetLimitsAsync); signed.MapPost("/rischio/{key}", SetRiskSettingAsync); } private static string Back(IFormCollection form, string fallback) { var back = form["ritorno"].ToString(); return IsLocalPath(back) ? back : fallback; } /// /// Only paths of this site: "/x" yes; "//other.site", "https://..." no; no backslash and no control characters, /// which browsers drop or turn into "/" while reading an address ("/\t/other.site" becomes "//other.site"). /// internal static bool IsLocalPath(string path) => path.StartsWith('/') && !path.StartsWith("//", StringComparison.Ordinal) && !path.Any(c => char.IsControl(c) || c == '\\'); private static string With(string path, string key, string value) { var hash = path.IndexOf('#', StringComparison.Ordinal); var anchor = hash >= 0 ? path[hash..] : ""; var bare = hash >= 0 ? path[..hash] : path; return bare + (bare.Contains('?', StringComparison.Ordinal) ? "&" : "?") + key + "=" + Uri.EscapeDataString(value) + anchor; } private static async Task SignInAsync(IFormCollection form, AnubisHost host, LoginLimiter limiter, HttpContext context, CancellationToken ct) { var services = host.Services; if (services is null) { return Results.Redirect("/"); } var address = context.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto"; var back = Back(form, "/"); var wait = limiter.Begin(address); if (wait > TimeSpan.Zero) { var minutes = Math.Max(1, (int)Math.Ceiling(wait.TotalMinutes)); return Results.Redirect(With(With("/accesso", "errore", "attesa"), "minuti", minutes.ToString(System.Globalization.CultureInfo.InvariantCulture))); } var code = form["codice"].ToString(); var (result, token) = await services.Access.SignInAsync(form["password"].ToString(), code, context.Request.Headers.UserAgent.ToString(), address, ct) .ConfigureAwait(false); switch (result) { case LoginResult.Ok: limiter.Succeeded(address); SessionAuthentication.WriteCookie(context, token!); return Results.Redirect(back); case LoginResult.SecondFactorNeeded: limiter.Forgive(address); return Results.Redirect(With(With("/accesso", "fattore", "1"), "ritorno", back)); case LoginResult.WrongSecondFactor: return Results.Redirect(With(With(With("/accesso", "fattore", "1"), "errore", "codice"), "ritorno", back)); default: return Results.Redirect(With(With("/accesso", "errore", "password"), "ritorno", back)); } } private static async Task SignOutAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { if (context.Request.Cookies.TryGetValue(SessionAuthentication.Cookie, out var token) && host.Services is { } services) { await services.Access.SignOutAsync(token, ct).ConfigureAwait(false); } SessionAuthentication.ClearCookie(context); return Results.Redirect("/accesso"); } private static async Task ChangePasswordAsync(IFormCollection form, AnubisHost host, HttpContext context, string? initial, string page, string done, CancellationToken ct) { if (host.IsDemo) { return Results.Redirect(With(page, "errore", "demo")); } var replacement = form["nuova"].ToString(); if (replacement != form["conferma"].ToString()) { return Results.Redirect(With(page, "errore", "diverse")); } if (Passwords.Problem(replacement, initial) is not null) { return Results.Redirect(With(page, "errore", replacement.Length < Passwords.MinimumLength ? "corta" : "uguale")); } var ok = await host.Services!.Access.ChangePasswordAsync(CurrentUser.Id(context.User), form["attuale"].ToString(), replacement, CurrentUser.Session(context.User), ct) .ConfigureAwait(false); return Results.Redirect(ok ? With(done, "ok", "password") : With(page, "errore", "attuale")); } private static async Task EnableSecondFactorAsync(IFormCollection form, AnubisHost host, SecondFactorDrafts drafts, HttpContext context, CancellationToken ct) { // The secret shown on the page stays on the server, tied to this session: it never travels in a form or an address. var session = CurrentUser.Session(context.User); if (host.IsDemo || drafts.Peek(session) is not { } secret) { return Results.Redirect("/impostazioni?errore=segreto#sicurezza"); } var ok = await host.Services!.Access.EnableSecondFactorAsync(CurrentUser.Id(context.User), secret, form["codice"].ToString(), ct).ConfigureAwait(false); if (ok) { drafts.Remove(session); } return Results.Redirect(ok ? "/impostazioni?ok=due-fattori#sicurezza" : "/impostazioni?errore=codice#sicurezza"); } private static async Task DisableSecondFactorAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { var ok = !host.IsDemo && await host.Services!.Access.DisableSecondFactorAsync(CurrentUser.Id(context.User), form["password"].ToString(), form["codice"].ToString(), ct).ConfigureAwait(false); return Results.Redirect(ok ? "/impostazioni?ok=due-fattori-tolti#sicurezza" : "/impostazioni?errore=attuale#sicurezza"); } private static async Task SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { var back = Back(form, "/impostazioni"); if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key) { return Results.Redirect(With(back, "errore", "impostazione")); } if (key == SettingsStore.CentralBankMeetings.Key && Anubis.Data.CentralBanks.Check(form["valore"].ToString()) is not null) { return Results.Redirect(With(back, "errore", "riunioni")); } var result = await Endpoints.SetSettingAsync(host, key, form["valore"].ToString(), context, ct).ConfigureAwait(false); return Results.Redirect(result is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back : With(back, "errore", "impostazione")); } private static async Task BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { var back = Back(form, "/"); var (ok, message) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false); return Results.Redirect(ok ? back : With(back, "errore", message.Contains("STOP", StringComparison.Ordinal) ? "file-stop" : "bot")); } /// The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out. // The form is bound even when unused: binding it is what makes the antiforgery check run on the route. private static async Task ResolveAccountAsync(Guid id, string choice, IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct) { if (choice is not ("allinea" or "escludi")) { return Results.Redirect("/conti?errore=scelta"); } if (host.IsDemo || host.Services?.Trading is not { } trading || trading.ManagerOf(id) is not { } manager) { return Results.Redirect("/conti?errore=motore"); } var state = await trading.Reconciler.StateAsync(id, ct).ConfigureAwait(false); if (state.ModeReason == Anubis.Trading.Reconciler.KeyReason) { return Results.Redirect("/conti?errore=chiave"); } if (!state.WaitsForUser(clock.UtcNow, trading.Reconciler.Grace)) { // The choice exists only after the 15 minutes (SPEC 7.4): before, the difference may still explain itself. return Results.Redirect("/conti?errore=presto"); } await trading.Reconciler.ResolveAsync(manager, choice == "allinea" ? Anubis.Trading.ReconcileChoice.Align : Anubis.Trading.ReconcileChoice.Exclude, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); return Results.Redirect("/conti?ok=" + choice); } /// /// New practice keys for a broker (SPEC 13.5): asked to the broker first, kept only if they may trade and may not /// withdraw (SPEC 2.2), saved encrypted, never shown again. The engine then restarts to use them. /// private static async Task SaveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { const string back = "/impostazioni"; if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca)) { return Results.Redirect(back + "?errore=conto#conti"); } if (host.IsDemo || host.Services is not { Trading: { } trading } services) { return Results.Redirect(back + "?errore=motore#conti"); } var fields = Anubis.Trading.TradingService.KeyFields(broker); foreach (var (name, _) in fields) { if ((await services.Secrets.StatusAsync(name, ct).ConfigureAwait(false)).FromEnvironment) { return Results.Redirect(back + "?errore=ambiente#conti"); } } var values = fields.Select(f => form[f.Name].ToString().Trim()).ToList(); if (values.Any(v => v.Length == 0 || v.Length > 512)) { return Results.Redirect(back + "?errore=chiavi-vuote#conti"); } Anubis.Trading.KeyPermissions permissions; try { permissions = await trading.TestKeysAsync(broker, values, ct).ConfigureAwait(false); } catch (Anubis.Trading.BrokerException) { return Results.Redirect(back + "?errore=chiavi-rifiutate#conti"); } if (permissions.CanWithdraw) { return Results.Redirect(back + "?errore=prelievo#conti"); } if (!permissions.CanTrade) { return Results.Redirect(back + "?errore=sola-lettura#conti"); } var who = context.User.Identity?.Name ?? "utente"; for (var i = 0; i < fields.Count; i++) { await services.Secrets.SetAsync(fields[i].Name, values[i], who, ct).ConfigureAwait(false); } await host.RestartServicesAsync(ct).ConfigureAwait(false); await WaitBrieflyAsync(host).ConfigureAwait(false); return Results.Redirect(back + "?ok=chiavi#conti"); } private static async Task RemoveKeysAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { const string back = "/impostazioni"; if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca) || host.IsDemo || host.Services is not { } services) { return Results.Redirect(back + "?errore=conto#conti"); } var who = context.User.Identity?.Name ?? "utente"; foreach (var (name, _) in Anubis.Trading.TradingService.KeyFields(broker)) { await services.Secrets.RemoveAsync(name, who, ct).ConfigureAwait(false); } await host.RestartServicesAsync(ct).ConfigureAwait(false); await WaitBrieflyAsync(host).ConfigureAwait(false); return Results.Redirect(back + "?ok=chiavi-tolte#conti"); } /// The capital entrusted to a broker, in euro (SPEC 7.1, 8.6): only the user sets it. private static async Task SetCapitalAsync(string broker, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { const string back = "/impostazioni"; if (broker is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca)) { return Results.Redirect(back + "?errore=conto#conti"); } if (host.IsDemo || host.Services?.Trading is not { } trading) { return Results.Redirect(back + "?errore=motore#conti"); } if (ParseEuro(form["euro"].ToString()) is not { } amount || amount < 0m || amount > 100_000_000m) { return Results.Redirect(back + "?errore=importo#conti"); } // More capital while a strategy of this broker has real money is more risk: it needs the procedure (SPEC 12.4). if ((await trading.Capital.EntrustedAsync(broker, ct).ConfigureAwait(false))?.AmountEur is { } before && amount > before && await RaiseRefusalAsync(host.Services!, broker, form, ct).ConfigureAwait(false) is { } refusal) { return Results.Redirect(back + "?errore=" + refusal + "#conti"); } try { await trading.SetCapitalAsync(broker, amount, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false); } catch (Anubis.Trading.CapitalException ex) when (ex.Message.StartsWith("Manca il cambio", StringComparison.Ordinal)) { return Results.Redirect(back + "?errore=cambio#conti"); } catch (Anubis.Trading.CapitalException) { return Results.Redirect(back + "?errore=capitale#conti"); } return Results.Redirect(back + "?ok=capitale#conti"); } /// /// The user's choices on the Strategie screen (SPEC 12.3, 12.4): observation and simulation from a button, real /// money only through the procedure, with the phrase, the password and the second factor checked by the stage book. /// private static async Task StrategyStageAsync(string strategy, string choice, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { if (host.IsDemo || host.Services is not { } services || !Anubis.Trading.StrategyNames.Base.Any(b => b.Name == strategy)) { return Results.Redirect("/strategie?errore=scelta"); } if (services.Trading?.Stages is not { } stages) { return Results.Redirect("/strategie?errore=motore"); } var by = context.User.Identity?.Name ?? "utente"; try { switch (choice) { case "simulazione": var stage = await stages.GetAsync(strategy, ct).ConfigureAwait(false); if (stage?.Qualification is not { Passed: true }) { // A strategy that did not pass its backtest stays in observation (SPEC 12.3). return Results.Redirect("/strategie?errore=backtest"); } await stages.MoveAsync(strategy, Anubis.Trading.StrategyStages.Simulation, "user", by, ct).ConfigureAwait(false); return Results.Redirect("/strategie?ok=simulazione"); case "osservazione": var current = await stages.GetAsync(strategy, ct).ConfigureAwait(false); if (current is not null && Anubis.Trading.StrategyStages.IsLive(current.Stage)) { await stages.RevokeAsync(strategy, by, "user", ct).ConfigureAwait(false); return Results.Redirect("/strategie?ok=simulazione"); } await stages.MoveAsync(strategy, Anubis.Trading.StrategyStages.Observation, "user", by, ct).ConfigureAwait(false); return Results.Redirect("/strategie?ok=osservazione"); case "reale" when Guid.TryParse(form["conto"].ToString(), out var account): var code = form["codice"].ToString(); await stages.ConfirmLiveAsync(new Anubis.Trading.LiveConfirmation(strategy, account, form["frase"].ToString(), form["password"].ToString(), string.IsNullOrWhiteSpace(code) ? null : code.Trim(), by), ct).ConfigureAwait(false); return Results.Redirect("/strategie?ok=reale"); default: return Results.Redirect("/strategie?errore=scelta"); } } catch (Anubis.Trading.LiveConfirmationException ex) { var error = ex.Code switch { "phrase" => "frase", "password" => "password", "requirements" => "requisiti", "account" => "conto", Anubis.Risk.RiskReasons.NoConsent => "consenso", _ => "scelta", }; return Results.Redirect("/strategie?errore=" + error); } } /// /// The risk limits (SPEC 9.2, 13.5), all at once. Lowering is always allowed; raising any of them while a strategy /// has real money needs the phrase, the password and the second factor (SPEC 12.4). /// private static async Task SetLimitsAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { const string back = "/impostazioni"; if (host.IsDemo || host.Services is not { } services) { return Results.Redirect(back + "?errore=motore#rischio"); } var current = new Dictionary(StringComparer.Ordinal); var next = new Dictionary(StringComparer.Ordinal); foreach (var definition in Anubis.Risk.RiskSettings.Limits) { current[definition.Key] = (await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false)).Value; var typed = form[definition.Key].ToString().Trim().Replace(',', '.'); if (typed.Length == 0) { next[definition.Key] = current[definition.Key]; continue; } if (definition.Check?.Invoke(typed) is not null) { return Results.Redirect(back + "?errore=limite#rischio"); } next[definition.Key] = typed; } var limits = Anubis.Risk.RiskSettings.From(k => next[k]); if (limits.DrawdownHalf >= limits.DrawdownStop || limits.DailyLoss > limits.WeeklyLoss) { return Results.Redirect(back + "?errore=ordine-limiti#rischio"); } if (Anubis.Risk.RiskSettings.From(k => current[k]).RaisedBy(limits)) { if (await RaiseRefusalAsync(services, null, form, ct).ConfigureAwait(false) is { } refusal) { return Results.Redirect(back + "?errore=" + refusal + "#rischio"); } } var by = context.User.Identity?.Name ?? "utente"; foreach (var (key, value) in next.Where(n => n.Value != current[n.Key])) { await services.Settings.SetAsync(key, value, by, ct).ConfigureAwait(false); } return Results.Redirect(back + "?ok=limiti#rischio"); } /// The day-trade guard and the scenarios of the Rischio screen: they change no limit, so no procedure. private static async Task SetRiskSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { const string back = "/impostazioni"; if (key != Anubis.Risk.RiskSettings.PdtGuard.Key && key != Anubis.Risk.Scenarios.Setting.Key) { return Results.Redirect(back + "?errore=impostazione#rischio"); } var result = await Endpoints.SetSettingAsync(host, key, form["valore"].ToString(), context, ct).ConfigureAwait(false); return Results.Redirect(result is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back + "?ok=rischio#rischio" : back + "?errore=scenari#rischio"); } /// Null when more risk may go ahead; otherwise the error code for the page. private static async Task RaiseRefusalAsync(AppServices services, string? broker, IFormCollection form, CancellationToken ct) { var stages = services.Trading?.Stages ?? new Anubis.Trading.StageBook(services.Db, new SystemClock(), Anubis.Trading.TradingConsent.None, (_, _, _) => Task.FromResult(false)); try { var code = form["codice"].ToString(); await stages.ConfirmRaiseAsync(broker, form["frase"].ToString(), form["password"].ToString(), string.IsNullOrWhiteSpace(code) ? null : code.Trim(), ct).ConfigureAwait(false); return null; } catch (Anubis.Trading.LiveConfirmationException ex) { return ex.Code == "phrase" ? "frase-rischio" : "password-rischio"; } } /// /// A new backtest trial (SPEC 12.2): the plan is written and queued at once, then the page of the trial follows it. /// A field that cannot be read goes back as a code; the chosen strategy is kept, nothing typed travels in the address. /// private static async Task PlanTrialAsync(IFormCollection form, AnubisHost host, CancellationToken ct) { var family = Anubis.Strategies.StrategyCatalog.Find(form["strategia"].ToString()); string Back(string code) => "/laboratorio?errore=" + code + (family is null ? "" : "&strategia=" + Uri.EscapeDataString(family.Id)) + "#nuovo"; if (host.IsDemo || host.Services?.Lab is not { } lab) { return Results.Redirect(Back("motore")); } if (family is null) { return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Strategy)); } var source = form["origine"].ToString(); var venue = source == Anubis.Backtest.TrialSources.Research ? Anubis.Data.Venues.Binance : form["mercato"].ToString(); if (source == Anubis.Backtest.TrialSources.Database && venue is not (Anubis.Data.Venues.Okx or Anubis.Data.Venues.Alpaca)) { return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Source)); } if (ParseDay(form["dal"].ToString()) is not { } from || ParseDay(form["al"].ToString()) is not { } to) { return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Dates)); } if (ParseEuro(form["capitale"].ToString()) is not { } capital) { return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Capital)); } var grid = new Dictionary>(StringComparer.Ordinal); foreach (var p in family.Parameters) { var text = form["griglia_" + p.Name].ToString(); if (string.IsNullOrWhiteSpace(text)) { continue; } if (ParseList(text) is not { } values) { return Results.Redirect(Back(Anubis.Backtest.TrialRequestErrors.Grid)); } grid[p.Name] = values; } var symbols = form["strumenti"].ToString() .Split([',', ';', ' ', '\n', '\r', '\t'], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) .Select(x => x.ToUpperInvariant()) .ToList(); try { var trial = await lab.PlanAsync(new Anubis.Backtest.TrialRequest(family.Id, source, venue, symbols, from, to, capital, grid), ct).ConfigureAwait(false); return Results.Redirect("/laboratorio/" + trial.Id.ToString("D")); } catch (Anubis.Backtest.TrialRequestException ex) { return Results.Redirect(Back(ex.Code)); } } private static DateOnly? ParseDay(string text) => DateOnly.TryParseExact(text, "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out var day) ? day : null; /// Values of a grid as people type them: "10, 20, 30" or "10 20 30"; decimals with a point. internal static IReadOnlyList? ParseList(string text) { var result = new List(); foreach (var item in (text ?? "").Split([',', ';', ' '], StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)) { if (!decimal.TryParse(item, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var value)) { return null; } result.Add(value); } return result.Count is > 0 and <= 20 ? result : null; } /// An amount as people type it: "1500", "1.500", "1500,50", "1.500,50", "1500.50". internal static decimal? ParseEuro(string text) { var clean = (text ?? "").Replace(" ", "", StringComparison.Ordinal).Replace("€", "", StringComparison.Ordinal); if (clean.Contains(',', StringComparison.Ordinal)) { clean = clean.Replace(".", "", StringComparison.Ordinal).Replace(',', '.'); } else if (clean.LastIndexOf('.') is var dot and >= 0 && clean.Length - dot - 1 == 3) { clean = clean.Replace(".", "", StringComparison.Ordinal); } return decimal.TryParse(clean, System.Globalization.NumberStyles.AllowDecimalPoint, System.Globalization.CultureInfo.InvariantCulture, out var value) ? Math.Round(value, 2, MidpointRounding.ToZero) : null; } private static async Task BackupAsync(IFormCollection form, AnubisHost host, ILogger logger, CancellationToken ct) { var services = host.Services!; try { await services.Backups.TakeAsync(services.Db, "a-mano", ct).ConfigureAwait(false); return Results.Redirect("/impostazioni?ok=salvataggio#sistema"); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException) { LogBackupFailed(logger, ex); return Results.Redirect("/impostazioni?errore=salvataggio#sistema"); } } // ---- Desktop first run (SPEC 15.6): only from the computer itself, only while the wizard is due. ---- private static DbSettings ReadDatabase(IFormCollection form, StartupConfig config) { if (form["motore"].ToString() != "postgres") { return new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = config.Data.SqliteFile }; } return new DbSettings { Engine = DbEngine.Postgres, Host = form["host"].ToString().Trim(), Port = int.TryParse(form["porta"].ToString(), out var port) && port is > 0 and < 65536 ? port : 5432, Database = string.IsNullOrWhiteSpace(form["nome"]) ? "anubis" : form["nome"].ToString().Trim(), User = string.IsNullOrWhiteSpace(form["utente"]) ? "anubis" : form["utente"].ToString().Trim(), Password = form["dbpassword"].ToString(), }; } /// Opens the database without creating anything and asks it one question. private static async Task TryConnectAsync(DbSettings settings, CancellationToken ct) { if (settings.Engine == DbEngine.Postgres && string.IsNullOrWhiteSpace(settings.Host)) { return "Manca l'indirizzo del server PostgreSQL."; } Redactor.Register(settings.Password); try { await using var db = Database.Open(settings, allowCreate: settings.Engine == DbEngine.Sqlite); using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); timeout.CancelAfter(TimeSpan.FromSeconds(8)); await db.PingAsync(timeout.Token).ConfigureAwait(false); return null; } catch (Exception ex) when (!ct.IsCancellationRequested) { return Redactor.Redact(ex.Message); } } private static bool WizardAllowed(AnubisHost host, HttpContext context) => host.Status.Mode == HostMode.FirstRun && host.Config.Platform == PlatformKind.Desktop && CurrentUser.IsLocal(context); private static async Task TestDatabaseAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) { if (!WizardAllowed(host, context)) { return Endpoints.Error(StatusCodes.Status403Forbidden, "non_ammesso", "La procedura guidata si usa solo dal computer su cui gira Anubis, al primo avvio."); } var problem = await TryConnectAsync(ReadDatabase(form, host.Config), ct).ConfigureAwait(false); return Results.Json(new { ok = problem is null, message = problem ?? "Connessione riuscita." }); } private static async Task FirstRunAsync(IFormCollection form, AnubisHost host, HttpContext context, ILogger logger, CancellationToken ct) { if (!WizardAllowed(host, context)) { return Results.Redirect("/"); } var password = form["password"].ToString(); if (password != form["conferma"].ToString()) { return Results.Redirect("/primo-avvio?errore=diverse"); } if (Passwords.Problem(password) is not null) { return Results.Redirect("/primo-avvio?errore=corta"); } var config = host.Config; if (!config.IsComplete) { var settings = ReadDatabase(form, config); if (await TryConnectAsync(settings, ct).ConfigureAwait(false) is not null) { return Results.Redirect("/primo-avvio?errore=database"); } // config.toml without the database password: that goes to the protected store (SPEC 15.6). DesktopPlatform.WriteConfig(config.Data, ProtectedSecretKey.DefaultStore(config.Data), settings, config.Port, allowNetwork: false); } host.PendingPassword = password; host.Wake(); try { await host.WaitForAsync(HostMode.Ready, TimeSpan.FromSeconds(60)).ConfigureAwait(false); } catch (OperationCanceledException) { LogFirstRunSlow(logger); return Results.Redirect("/"); } var (result, token) = await host.Services!.Access.SignInAsync(password, null, context.Request.Headers.UserAgent.ToString(), context.Connection.RemoteIpAddress?.ToString(), ct).ConfigureAwait(false); if (result == LoginResult.Ok) { SessionAuthentication.WriteCookie(context, token!); } return Results.Redirect("/"); } // ---- Choices of the error page (SPEC 15.1): Docker asks the startup password, desktop only the computer itself. ---- private static async Task ServiceChoiceAsync(string choice, IFormCollection form, AnubisHost host, IClock clock, LoginLimiter limiter, HttpContext context, ILogger logger, CancellationToken ct) { var config = host.Config; if (config.Platform == PlatformKind.Docker) { // The startup password, asked by a page anyone on the network can open: same attempt limit as the sign-in. var address = context.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto"; if (limiter.Begin(address) > TimeSpan.Zero) { return Results.Redirect("/?errore=attesa"); } if (!Endpoints.SameSecret(form["password"].ToString(), config.AdminPassword)) { LogChoiceRefused(logger, choice); return Results.Redirect("/?errore=password"); } limiter.Succeeded(address); } else if (!CurrentUser.IsLocal(context)) { return Results.Redirect("/?errore=password"); } // The startup loop stays still until the choice is done and the installation renewed. using var exclusive = await host.ExclusiveAsync(ct).ConfigureAwait(false); var status = host.Status; var db = host.Database; if (status.Mode != HostMode.IdentityProblem || status.Identity is null || db is null) { return Results.Redirect("/"); } var verdict = status.Identity.Verdict; try { switch (choice) { case "ripristina" when verdict == IdentityVerdict.EmptyDatabase: var backup = new Backups(config.Data, clock).List().FirstOrDefault(b => b.Name == form["salvataggio"].ToString()); if (backup is null) { return Results.Redirect("/?errore=scelta"); } await Archive.ImportAsync(db, Path.Combine(backup.Folder, Backups.ArchiveFolder), clock, ct).ConfigureAwait(false); await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false); break; case "importa" when verdict == IdentityVerdict.EmptyDatabase: var folder = ServiceChoices.ImportFolders(config.Data).FirstOrDefault(f => Path.GetFileName(f) == form["archivio"].ToString()); if (folder is null) { return Results.Redirect("/?errore=scelta"); } await Archive.ImportAsync(db, folder, clock, ct).ConfigureAwait(false); await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false); break; case "da-capo" when verdict == IdentityVerdict.EmptyDatabase: Installation.StartOver(config.Data, clock); break; case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase: await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: true, ct).ConfigureAwait(false); break; default: return Results.Redirect("/?errore=scelta"); } } catch (Exception ex) when (IsArchiveProblem(ex)) { LogChoiceFailed(logger, ex, choice); return Results.Redirect("/?errore=importazione"); } LogChoice(logger, choice); // Reset while the loop is still held: released first, it could start the application again before the reset // and then lose the services it had just built while showing "ready". await host.ResetAsync().ConfigureAwait(false); exclusive.Dispose(); await WaitBrieflyAsync(host).ConfigureAwait(false); return Results.Redirect("/"); } /// What a damaged or unsuitable archive throws: reported on the page, not as a crash. internal static bool IsArchiveProblem(Exception ex) => ex is IOException or UnauthorizedAccessException or InvalidOperationException or InvalidDataException or FormatException or OverflowException or SchemaException or System.Text.Json.JsonException or System.Data.Common.DbException; private static async Task WaitBrieflyAsync(AnubisHost host) { try { await host.WaitForAsync(HostMode.Ready, TimeSpan.FromSeconds(10)).ConfigureAwait(false); } catch (OperationCanceledException) { } } [LoggerMessage(Level = LogLevel.Error, Message = "Backup on request failed")] private static partial void LogBackupFailed(ILogger logger, Exception exception); [LoggerMessage(Level = LogLevel.Warning, Message = "First run: the application is not ready after 60 seconds")] private static partial void LogFirstRunSlow(ILogger logger); [LoggerMessage(Level = LogLevel.Warning, Message = "Error page choice {Choice} confirmed")] private static partial void LogChoice(ILogger logger, string choice); [LoggerMessage(Level = LogLevel.Warning, Message = "Error page choice {Choice} refused: wrong startup password")] private static partial void LogChoiceRefused(ILogger logger, string choice); [LoggerMessage(Level = LogLevel.Error, Message = "Error page choice {Choice} failed")] private static partial void LogChoiceFailed(ILogger logger, Exception exception, string choice); } /// Second-factor secrets being set up, one per session, kept for 15 minutes. internal sealed class SecondFactorDrafts(IClock clock) { private static readonly TimeSpan _life = TimeSpan.FromMinutes(15); private readonly System.Collections.Concurrent.ConcurrentDictionary _drafts = new(); /// The draft of this session, or a new one. public byte[] For(Guid session) { var now = clock.UtcNow; foreach (var expired in _drafts.Where(d => d.Value.Until <= now).Select(d => d.Key).ToList()) { _drafts.TryRemove(expired, out _); } return _drafts.AddOrUpdate(session, _ => (Totp.NewSecret(), now + _life), (_, d) => d.Until > now ? d : (Totp.NewSecret(), now + _life)).Secret; } public byte[]? Peek(Guid session) => _drafts.TryGetValue(session, out var d) && d.Until > clock.UtcNow ? d.Secret : null; public void Remove(Guid session) => _drafts.TryRemove(session, out _); } /// What the error page can offer. internal static class ServiceChoices { /// Archives under data/import, one folder each with its index.json. public static IReadOnlyList ImportFolders(DataDirectory data) => !Directory.Exists(data.Import) ? [] : Directory.EnumerateDirectories(data.Import).Where(d => File.Exists(Path.Combine(d, Archive.IndexFile))).Order(StringComparer.Ordinal).ToList(); }