ci / test (postgres) (push) Successful in 6m37s
ci / test (sqlite) (push) Successful in 7m51s
ci / test (postgres) (pull_request) Successful in 5m40s
ci / test (sqlite) (pull_request) Successful in 7m31s
ci / image (push) Successful in 2m29s
ci / image (pull_request) Successful in 59s
Two reviewers with a clean context read the engine and the screens. The isotonic calibration took its floor from the first step, even of two cases, so with few winners it flattened every estimate: the first model is rebuilt with the fix. Learning failures no longer forget the multiplier an operation was born with, nor stop a decision or the nightly check; recovered decisions read the outside world as it was when due; models estimate only the strategies they studied; a newer history does not repeat what was lived. The screens count examples instead of verifications, show the next threshold and never round an alarm to 50%; two forms now check the antiforgery token. Each defect has its test, on both engines. ADR 0018 point 17 has the list. refs #67 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1164 lines
54 KiB
C#
1164 lines
54 KiB
C#
using Anubis.Access;
|
|
using Anubis.Core;
|
|
using Anubis.Db;
|
|
using Anubis.Platform;
|
|
|
|
namespace Anubis.Server;
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
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("/telegram", SaveTelegramAsync);
|
|
signed.MapPost("/telegram/prova", TestTelegramAsync);
|
|
signed.MapPost("/telegram/togli", RemoveTelegramAsync);
|
|
signed.MapPost("/segnale-di-vita", SaveHeartbeatAsync);
|
|
signed.MapPost("/segnale-di-vita/togli", RemoveHeartbeatAsync);
|
|
signed.MapPost("/assenza/{id:guid}/vista", AbsenceSeenAsync);
|
|
signed.MapPost("/laboratorio", PlanTrialAsync);
|
|
signed.MapPost("/stime-di-costo/{id:guid}/{choice}", DecideCostAsync);
|
|
signed.MapPost("/modello", SetModelAsync);
|
|
signed.MapPost("/modello/annulla-promozione", UndoPromotionAsync);
|
|
signed.MapPost("/strategie/{strategy}/{choice}", StrategyStageAsync);
|
|
signed.MapPost("/rischio/limiti", SetLimitsAsync);
|
|
signed.MapPost("/rischio/{key}", SetRiskSettingAsync);
|
|
signed.MapPost("/notizie/fonti/{id:guid}", SetNewsSourceAsync);
|
|
signed.MapPost("/chiavi-dati/{name}", SaveDataKeyAsync);
|
|
signed.MapPost("/chiavi-dati/{name}/togli", RemoveDataKeyAsync);
|
|
}
|
|
|
|
/// <summary>The optional keys of SPEC 13.5 that are not a broker's: the language model, Finnhub, FRED.</summary>
|
|
internal static readonly IReadOnlyList<string> DataKeys = [Anubis.News.NewsModelSettings.KeySecret, "FINNHUB_API_KEY", "FRED_API_KEY"];
|
|
|
|
private static async Task<IResult> SetNewsSourceAsync(Guid id, 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#notizie");
|
|
}
|
|
|
|
var enabled = form["attiva"].ToString() == "on";
|
|
var trusted = form["affidabile"].ToString() == "on";
|
|
var found = await new Anubis.News.NewsStore(services.Db, host.Clock).SetSourceAsync(id, enabled, trusted, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
|
return Results.Redirect(back + (found ? "?ok=fonte#notizie" : "?errore=fonte#notizie"));
|
|
}
|
|
|
|
// A key is saved as it is: FRED and Finnhub say whether it works at the next round, in the state of the sources.
|
|
private static async Task<IResult> SaveDataKeyAsync(string name, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
|
{
|
|
const string back = "/impostazioni";
|
|
if (!DataKeys.Contains(name))
|
|
{
|
|
return Results.Redirect(back + "?errore=impostazione#notizie");
|
|
}
|
|
|
|
if (host.IsDemo || host.Services is not { } services)
|
|
{
|
|
return Results.Redirect(back + "?errore=motore#notizie");
|
|
}
|
|
|
|
if ((await services.Secrets.StatusAsync(name, ct).ConfigureAwait(false)).FromEnvironment)
|
|
{
|
|
return Results.Redirect(back + "?errore=chiave-ambiente#notizie");
|
|
}
|
|
|
|
var value = form["chiave"].ToString().Trim();
|
|
if (value.Length is 0 or > 512 || value.Any(c => char.IsWhiteSpace(c) || char.IsControl(c)))
|
|
{
|
|
return Results.Redirect(back + "?errore=chiave#notizie");
|
|
}
|
|
|
|
await services.Secrets.SetAsync(name, value, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
|
return Results.Redirect(back + "?ok=chiave#notizie");
|
|
}
|
|
|
|
private static async Task<IResult> RemoveDataKeyAsync(string name, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
|
{
|
|
const string back = "/impostazioni";
|
|
if (!DataKeys.Contains(name) || host.IsDemo || host.Services is not { } services)
|
|
{
|
|
return Results.Redirect(back + "?errore=motore#notizie");
|
|
}
|
|
|
|
await services.Secrets.RemoveAsync(name, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
|
return Results.Redirect(back + "?ok=chiave-tolta#notizie");
|
|
}
|
|
|
|
/// <summary>The notice of a long absence (SPEC 5.6) goes away once the user has seen it.</summary>
|
|
// The form is bound even when unused: binding it is what makes the antiforgery check run on the route.
|
|
private static async Task<IResult> AbsenceSeenAsync(Guid id, IFormCollection form, AnubisHost host, CancellationToken ct)
|
|
{
|
|
if (!host.IsDemo && host.Services is { } services)
|
|
{
|
|
await new Anubis.Trading.AbsenceBook(services.Db, host.Clock).AcknowledgeAsync(id, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
return Results.Redirect("/");
|
|
}
|
|
|
|
private static string Back(IFormCollection form, string fallback)
|
|
{
|
|
var back = form["ritorno"].ToString();
|
|
|
|
return IsLocalPath(back) ? back : fallback;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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").
|
|
/// </summary>
|
|
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<IResult> 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<IResult> 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<IResult> 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<IResult> 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<IResult> 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<IResult> SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
|
{
|
|
var back = Back(form, "/impostazioni");
|
|
var news = Anubis.News.NewsRuleSettings.All.Any(d => d.Key == key);
|
|
var model = Anubis.News.NewsModelSettings.All.Any(d => d.Key == key);
|
|
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key && key != SettingsStore.CentralBankMeetings.Key && key != SettingsStore.TelegramStatus.Key &&
|
|
!news && !model)
|
|
{
|
|
return Results.Redirect(With(back, "errore", "impostazione"));
|
|
}
|
|
|
|
if ((news || model) && host.IsDemo)
|
|
{
|
|
return Results.Redirect(With(back, "errore", "motore"));
|
|
}
|
|
|
|
if (model)
|
|
{
|
|
// Amounts as the user writes them, "0,50" or "0,50 €", stored as "0.50"; the other values trimmed.
|
|
var value = form["valore"].ToString().Trim();
|
|
if (Anubis.News.NewsModelSettings.IsAmount(key))
|
|
{
|
|
value = Anubis.News.NewsModelSettings.Amount(value)?.ToString(System.Globalization.CultureInfo.InvariantCulture) ?? value;
|
|
}
|
|
|
|
var definition = SettingsStore.Definition(key);
|
|
if ((definition.Check?.Invoke(value) is not null) || (definition.Allowed is { } allowed && !allowed.Contains(value, StringComparer.Ordinal)))
|
|
{
|
|
return Results.Redirect(With(back, "errore", key == Anubis.News.NewsModelSettings.DailyCap.Key ? "tetto" : "modello"));
|
|
}
|
|
|
|
var saved = await Endpoints.SetSettingAsync(host, key, value, context, ct).ConfigureAwait(false);
|
|
return Results.Redirect(saved is IStatusCodeHttpResult { StatusCode: StatusCodes.Status204NoContent } ? back : 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<IResult> BotAsync(string command, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
|
{
|
|
var back = Back(form, "/");
|
|
var (ok, message) = await Endpoints.BotCommandAsync(host, command, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
|
return Results.Redirect(ok ? back : With(back, "errore", message.Contains("STOP", StringComparison.Ordinal) ? "file-stop" : "bot"));
|
|
}
|
|
|
|
/// <summary>The user's choice for an account in prudent mode after the 15 minutes (SPEC 7.4): align or leave out.</summary>
|
|
// The form is bound even when unused: binding it is what makes the antiforgery check run on the route.
|
|
private static async Task<IResult> 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);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
private static async Task<IResult> 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");
|
|
}
|
|
|
|
/// <summary>
|
|
/// The bot's Telegram (SPEC 14): a test message first, sent at once; token and chat are saved only when it left.
|
|
/// </summary>
|
|
private static async Task<IResult> SaveTelegramAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
|
{
|
|
const string back = "/impostazioni";
|
|
if (host.IsDemo || host.Services is not { Telegram: { } telegram } services)
|
|
{
|
|
return Results.Redirect(back + "?errore=motore#telegram");
|
|
}
|
|
|
|
if ((await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.TokenSecret, ct).ConfigureAwait(false)).FromEnvironment
|
|
|| (await services.Secrets.StatusAsync(Anubis.Notifications.TelegramSettings.ChatSecret, ct).ConfigureAwait(false)).FromEnvironment)
|
|
{
|
|
return Results.Redirect(back + "?errore=telegram-ambiente#telegram");
|
|
}
|
|
|
|
var token = form["token"].ToString().Trim();
|
|
var chat = form["chat"].ToString().Trim();
|
|
if (token.Length is 0 or > 200 || chat.Length is 0 or > 40)
|
|
{
|
|
return Results.Redirect(back + "?errore=telegram-vuoto#telegram");
|
|
}
|
|
|
|
if (await telegram.TestAsync(new Anubis.Notifications.TelegramSettings(token, chat), ct).ConfigureAwait(false) is not null)
|
|
{
|
|
return Results.Redirect(back + "?errore=telegram-rifiutato#telegram");
|
|
}
|
|
|
|
var who = context.User.Identity?.Name ?? "utente";
|
|
await services.Secrets.SetAsync(Anubis.Notifications.TelegramSettings.TokenSecret, token, who, ct).ConfigureAwait(false);
|
|
await services.Secrets.SetAsync(Anubis.Notifications.TelegramSettings.ChatSecret, chat, who, ct).ConfigureAwait(false);
|
|
return Results.Redirect(back + "?ok=telegram#telegram");
|
|
}
|
|
|
|
// The form is bound even when unused: binding it is what makes the antiforgery check run on the route.
|
|
private static async Task<IResult> TestTelegramAsync(IFormCollection form, AnubisHost host, CancellationToken ct)
|
|
{
|
|
const string back = "/impostazioni";
|
|
if (host.IsDemo || host.Services is not { Telegram: { } telegram }
|
|
|| await telegram.ReadAsync(ct).ConfigureAwait(false) is not { } settings)
|
|
{
|
|
return Results.Redirect(back + "?errore=telegram-vuoto#telegram");
|
|
}
|
|
|
|
return Results.Redirect(await telegram.TestAsync(settings, ct).ConfigureAwait(false) is null ? back + "?ok=telegram-prova#telegram" : back + "?errore=telegram-prova#telegram");
|
|
}
|
|
|
|
private static async Task<IResult> RemoveTelegramAsync(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#telegram");
|
|
}
|
|
|
|
var who = context.User.Identity?.Name ?? "utente";
|
|
await services.Secrets.RemoveAsync(Anubis.Notifications.TelegramSettings.TokenSecret, who, ct).ConfigureAwait(false);
|
|
await services.Secrets.RemoveAsync(Anubis.Notifications.TelegramSettings.ChatSecret, who, ct).ConfigureAwait(false);
|
|
return Results.Redirect(back + "?ok=telegram-tolto#telegram");
|
|
}
|
|
|
|
/// <summary>The address of the checking service (SPEC 14): called once as a test, saved encrypted only when it answered.</summary>
|
|
private static async Task<IResult> SaveHeartbeatAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
|
{
|
|
const string back = "/impostazioni";
|
|
if (host.IsDemo || host.Services is not { Telegram: { ConfiguredHeartbeat: null } telegram } services)
|
|
{
|
|
return Results.Redirect(back + "?errore=motore#telegram");
|
|
}
|
|
|
|
var address = form["indirizzo"].ToString().Trim();
|
|
if (address.Length is 0 or > 500 || Anubis.Notifications.Heartbeat.Check(address) is not null)
|
|
{
|
|
return Results.Redirect(back + "?errore=segnale#telegram");
|
|
}
|
|
|
|
var probe = new Anubis.Notifications.Heartbeat(telegram.Http, host.Clock, _ => Task.FromResult<Uri?>(new Uri(address)), Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance);
|
|
if (!await probe.BeatAsync(ct).ConfigureAwait(false))
|
|
{
|
|
return Results.Redirect(back + "?errore=segnale-fallito#telegram");
|
|
}
|
|
|
|
await services.Secrets.SetAsync(TelegramServices.HeartbeatSecret, address, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
|
await telegram.Heartbeat.BeatAsync(ct).ConfigureAwait(false);
|
|
return Results.Redirect(back + "?ok=segnale#telegram");
|
|
}
|
|
|
|
private static async Task<IResult> RemoveHeartbeatAsync(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#telegram");
|
|
}
|
|
|
|
await services.Secrets.RemoveAsync(TelegramServices.HeartbeatSecret, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
|
return Results.Redirect(back + "?ok=segnale-tolto#telegram");
|
|
}
|
|
|
|
private static async Task<IResult> 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");
|
|
}
|
|
|
|
/// <summary>The capital entrusted to a broker, in euro (SPEC 7.1, 8.6): only the user sets it.</summary>
|
|
private static async Task<IResult> SetCapitalAsync(string broker, IFormCollection form, AnubisHost host, IClock clock, 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!, clock, 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");
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
private static async Task<IResult> 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",
|
|
"backtest" => "backtest",
|
|
"observation" => "osservazione-giorni",
|
|
"account" => "conto",
|
|
Anubis.Risk.RiskReasons.NoConsent => "consenso",
|
|
_ => "scelta",
|
|
};
|
|
return Results.Redirect("/strategie?errore=" + error);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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).
|
|
/// </summary>
|
|
private static async Task<IResult> SetLimitsAsync(IFormCollection form, AnubisHost host, IClock clock, 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<string, string>(StringComparer.Ordinal);
|
|
var next = new Dictionary<string, string>(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, clock, 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");
|
|
}
|
|
|
|
/// <summary>The day-trade guard and the scenarios of the Rischio screen: they change no limit, so no procedure.</summary>
|
|
private static async Task<IResult> 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");
|
|
}
|
|
|
|
/// <summary>Null when more risk may go ahead; otherwise the error code for the page.</summary>
|
|
private static async Task<string?> RaiseRefusalAsync(AppServices services, IClock clock, string? broker, IFormCollection form, CancellationToken ct)
|
|
{
|
|
// Without the trading engine no strategy can hold real money, so the stage book only has to say so.
|
|
var stages = services.Trading?.Stages ?? new Anubis.Trading.StageBook(services.Db, clock, 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 switch
|
|
{
|
|
"phrase" => "frase-rischio",
|
|
"demotion" => "retrocessione-rischio",
|
|
_ => "password-rischio",
|
|
};
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 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.
|
|
/// </summary>
|
|
private static async Task<IResult> 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<string, IReadOnlyList<decimal>>(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));
|
|
}
|
|
}
|
|
|
|
/// <summary>A lower slippage estimate waits for the user (SPEC 11.6). The form is bound for the antiforgery check.</summary>
|
|
private static async Task<IResult> DecideCostAsync(Guid id, string choice, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct)
|
|
{
|
|
if (host.IsDemo || host.Services is not { } services || choice is not ("conferma" or "rifiuta"))
|
|
{
|
|
return Results.Redirect("/laboratorio?errore=motore#stime");
|
|
}
|
|
|
|
var book = new Anubis.Learning.CostBook(services.Db, host.Clock);
|
|
var done = await book.DecideAsync(id, choice == "conferma", context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
|
|
if (done && services.Trading is { } trading)
|
|
{
|
|
await trading.RefreshCostsAsync(ct).ConfigureAwait(false);
|
|
}
|
|
|
|
return Results.Redirect(done ? "/laboratorio#stime" : "/laboratorio?errore=stima#stime");
|
|
}
|
|
|
|
/// <summary>
|
|
/// The thresholds of the multiplier and the manual set-aside (SPEC 13.5), all at once. A choice that lets operations be
|
|
/// bigger while a strategy has real money needs the phrase and the password, like a risk limit (SPEC 12.4).
|
|
/// </summary>
|
|
private static async Task<IResult> SetModelAsync(IFormCollection form, AnubisHost host, IClock clock, HttpContext context, CancellationToken ct)
|
|
{
|
|
const string back = "/impostazioni";
|
|
if (host.IsDemo || host.Services is not { } services)
|
|
{
|
|
return Results.Redirect(back + "?errore=motore#modello");
|
|
}
|
|
|
|
var current = new Dictionary<string, string>(StringComparer.Ordinal);
|
|
var next = new Dictionary<string, string>(StringComparer.Ordinal);
|
|
foreach (var definition in Anubis.Learning.LearningSettings.All)
|
|
{
|
|
var value = await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false);
|
|
current[definition.Key] = value.Value;
|
|
var chosen = form[definition.Key].ToString();
|
|
if (value.ReadOnly || chosen.Length == 0)
|
|
{
|
|
next[definition.Key] = value.Value;
|
|
continue;
|
|
}
|
|
|
|
if (!definition.Allowed!.Contains(chosen, StringComparer.Ordinal))
|
|
{
|
|
return Results.Redirect(back + "?errore=impostazione#modello");
|
|
}
|
|
|
|
next[definition.Key] = chosen;
|
|
}
|
|
|
|
if (Anubis.Learning.LearningSettings.Raised(k => current[k], k => next[k]) && await RaiseRefusalAsync(services, clock, null, form, ct).ConfigureAwait(false) is { } refusal)
|
|
{
|
|
return Results.Redirect(back + "?errore=" + refusal + "#modello");
|
|
}
|
|
|
|
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=apprendimento#modello");
|
|
}
|
|
|
|
/// <summary>One click takes back the last promotion (SPEC 11.4).</summary>
|
|
private static async Task<IResult> UndoPromotionAsync(IFormCollection form, AnubisHost host, CancellationToken ct)
|
|
{
|
|
var (page, anchor) = Back(form, "/apprendimento") == "/impostazioni" ? ("/impostazioni", "#modello") : ("/apprendimento", "");
|
|
if (host.IsDemo || host.Services is not { } services)
|
|
{
|
|
return Results.Redirect(page + "?errore=motore" + anchor);
|
|
}
|
|
|
|
var done = await Anubis.Learning.LearningCycle.UndoPromotionAsync(services.Db, host.Clock, ct).ConfigureAwait(false);
|
|
return Results.Redirect(page + (done ? "?ok=promozione" : "?errore=promozione") + anchor);
|
|
}
|
|
|
|
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;
|
|
|
|
/// <summary>Values of a grid as people type them: "10, 20, 30" or "10 20 30"; decimals with a point.</summary>
|
|
internal static IReadOnlyList<decimal>? ParseList(string text)
|
|
{
|
|
var result = new List<decimal>();
|
|
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;
|
|
}
|
|
|
|
/// <summary>An amount as people type it: "1500", "1.500", "1500,50", "1.500,50", "1500.50".</summary>
|
|
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<IResult> BackupAsync(IFormCollection form, AnubisHost host, ILogger<AnubisHost> 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(),
|
|
};
|
|
}
|
|
|
|
/// <summary>Opens the database without creating anything and asks it one question.</summary>
|
|
private static async Task<string?> 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<IResult> 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<IResult> FirstRunAsync(IFormCollection form, AnubisHost host, HttpContext context, ILogger<AnubisHost> 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<IResult> ServiceChoiceAsync(string choice, IFormCollection form, AnubisHost host, IClock clock, LoginLimiter limiter,
|
|
HttpContext context, ILogger<AnubisHost> 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("/");
|
|
}
|
|
|
|
/// <summary>What a damaged or unsuitable archive throws: reported on the page, not as a crash.</summary>
|
|
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);
|
|
}
|
|
|
|
/// <summary>Second-factor secrets being set up, one per session, kept for 15 minutes.</summary>
|
|
internal sealed class SecondFactorDrafts(IClock clock)
|
|
{
|
|
private static readonly TimeSpan _life = TimeSpan.FromMinutes(15);
|
|
private readonly System.Collections.Concurrent.ConcurrentDictionary<Guid, (byte[] Secret, DateTimeOffset Until)> _drafts = new();
|
|
|
|
/// <summary>The draft of this session, or a new one.</summary>
|
|
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 _);
|
|
}
|
|
|
|
/// <summary>What the error page can offer.</summary>
|
|
internal static class ServiceChoices
|
|
{
|
|
/// <summary>Archives under data/import, one folder each with its index.json.</summary>
|
|
public static IReadOnlyList<string> ImportFolders(DataDirectory data) =>
|
|
!Directory.Exists(data.Import)
|
|
? []
|
|
: Directory.EnumerateDirectories(data.Import).Where(d => File.Exists(Path.Combine(d, Archive.IndexFile))).Order(StringComparer.Ordinal).ToList();
|
|
}
|