feat(server): web server, interface shell, demo mode and Docker image (refs #11 #12 #13 #14 #15 #16 #17)
ci / test (postgres) (push) Successful in 2m22s
ci / test (sqlite) (push) Failing after 2m27s
ci / image (push) Skipped

Phase 1 completed on top of the library foundations:
- Server: startup state machine (config, first run, database down, schema,
  identity, ready) with an error page that retries by itself; the configured
  database is the only one ever opened, and a vanished SQLite file is never
  recreated. REST API and status WebSocket; session cookie auth, CSRF on
  every form and write call; desktop and demo answer only the computer itself.
- Interface: static Blazor rendering with plain forms (no interactive
  runtime), menu, top bar and phone bottom bar as in the mockups, light and
  dark themes with appendix C tokens and a contrast test, Panoramica, Diario,
  Rischio, Impostazioni; service pages for sign-in, first access, desktop
  first run and the database error page with its choices.
- Demo mode (tasks seed-demo): appendix F in a database of its own under the
  temp folder, frozen clock, never touches the configured installation.
- Docker: entrypoint gives /data to PUID:PGID and drops root with setpriv,
  HEALTHCHECK through bash /dev/tcp; proven with SQLite, PostgreSQL, a wrong
  configuration and a database that goes away and comes back.
- tasks screenshots drives the installed Edge/Chrome through DevTools for
  exact 1440 and 390 pixel shots; anubis db export|import on the command line.

Fixes from the independent review: return paths without control characters,
Host check against DNS rebinding, attempt limit counted before the check and
also on the error-page password, one-use TOTP codes and a code to switch the
second factor off, error-page choices serialized with the startup loop,
identity checked before migrating, restore restarts with "Ferma tutto" on,
damaged archives reported instead of crashing. Running the server tests on
PostgreSQL exposed pages rendered before their data arrived; data-loading
components now load first (LoadedComponent).

Decisions in ADR 0007. Tests: 100 on SQLite and on PostgreSQL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-10 12:40:15 +01:00
1 parent 53ca01b7c3
commit f9d71559e8
71 files changed
+5853 -80

No files matched your search

+8
View File
@@ -2,6 +2,8 @@
<PropertyGroup>
<RootNamespace>Anubis.Server</RootNamespace>
<InvariantGlobalization>false</InvariantGlobalization>
<!-- Static rendering only: no blazor.web.js, so no Microsoft.AspNetCore.App.Internal.Assets package (ADR 0007). -->
<RequiresAspNetWebAssets>false</RequiresAspNetWebAssets>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\Anubis\Anubis.csproj" />
@@ -9,4 +11,10 @@
<ItemGroup>
<InternalsVisibleTo Include="Anubis.Tests" />
</ItemGroup>
<ItemGroup>
<!-- Style and scripts served from the assembly: no static web assets pipeline, no files to lose (ADR 0007). -->
<EmbeddedResource Include="Assets\*" LogicalName="Anubis.Server.Assets.%(Filename)%(Extension)" />
<!-- The logo comes only from docs/design/logo (ADR 0005). -->
<EmbeddedResource Include="..\..\docs\design\logo\*.svg;..\..\docs\design\logo\*.png;..\..\docs\design\logo\*.ico" LogicalName="Anubis.Server.Brand.%(Filename)%(Extension)" />
</ItemGroup>
</Project>
+486
View File
@@ -0,0 +1,486 @@
using Anubis.Access;
using Anubis.Core;
using Anubis.Db;
using Anubis.Demo;
using Anubis.Platform;
namespace Anubis.Server;
public enum HostMode
{
Starting,
/// <summary>The startup configuration is missing or wrong: the error page lists what to fix.</summary>
ConfigProblem,
/// <summary>Desktop without config.toml, or without a user yet: the first-run wizard.</summary>
FirstRun,
/// <summary>The configured database does not answer: error page, retry, never another database (trap 20).</summary>
DatabaseUnavailable,
/// <summary>The database schema is newer than this version or was altered.</summary>
SchemaProblem,
/// <summary>Database and data folder do not belong together (SPEC 15.1): the user chooses.</summary>
IdentityProblem,
Ready,
}
public sealed record HostStatus(HostMode Mode, string? Detail, IdentityCheck? Identity, DateTimeOffset Since, int Attempts);
/// <summary>Published on the bus whenever the host changes mode.</summary>
internal sealed record HostChanged(HostMode Mode);
/// <summary>Everything that needs the database, built once it is reachable and the installation checks out.</summary>
internal sealed record AppServices(Database Db, SettingsStore Settings, SecretStore Secrets, AccessStore Access, Backups Backups, Scheduler Scheduler);
/// <summary>
/// The startup state machine of the server (SPEC 15.1, 15.6): reads the startup configuration, opens the configured
/// database and nothing else, migrates it after a backup, checks the installation identity, then runs. While anything
/// is wrong the interface shows the error page and the host retries by itself; when the database comes back the
/// application resumes without a restart.
/// </summary>
internal sealed partial class AnubisHost(
ServerOptions options,
StartupConfig initialConfig,
IReadOnlyDictionary<string, string?> environment,
IClock clock,
EventBus bus,
ILogger<AnubisHost> logger,
ServerOverrides? overrides = null) : BackgroundService
{
private readonly TimeSpan _interval = overrides?.DatabaseCheckInterval ?? TimeSpan.FromSeconds(5);
private readonly Lock _gate = new();
// One step of the loop or one error-page choice at a time: a restore must not race the start that would follow it.
private readonly SemaphoreSlim _exclusive = new(1, 1);
private TaskCompletionSource _wake = new(TaskCreationOptions.RunContinuationsAsynchronously);
private Database? _db;
private Task? _schedulerLoop;
private CancellationTokenSource? _schedulerStop;
private volatile HostStatus _status = new(HostMode.Starting, null, null, clock.UtcNow, 0);
private volatile AppServices? _services;
public StartupConfig Config { get; private set; } = initialConfig;
public bool IsDemo => options.Demo;
public HostStatus Status => _status;
/// <summary>The running services; null until the first successful start.</summary>
public AppServices? Services => _status.Mode == HostMode.Ready ? _services : null;
/// <summary>Desktop first run: the password chosen in the wizard, used once the database is ready.</summary>
public string? PendingPassword { get; set; }
public int PasswordIterations => overrides?.PasswordIterations ?? Passwords.DefaultIterations;
/// <summary>Asks the loop to check again now (after the wizard or an error-page choice).</summary>
public void Wake()
{
lock (_gate)
{
_wake.TrySetResult();
}
}
/// <summary>Waits until the host reaches <paramref name="mode"/>; for tests and the CLI.</summary>
public async Task WaitForAsync(HostMode mode, TimeSpan timeout)
{
using var cts = new CancellationTokenSource(timeout);
while (_status.Mode != mode)
{
await Task.Delay(20, cts.Token).ConfigureAwait(false);
}
}
/// <summary>Last time the database answered: the "Dati aggiornati" of the top bar.</summary>
public DateTimeOffset? LastCheckUtc { get; private set; }
/// <summary>The scheduler loop is alive (health check).</summary>
public bool SchedulerRunning => _schedulerLoop is { IsCompleted: false };
/// <summary>The database even when not ready (error-page choices need it to restore or import).</summary>
internal Database? Database => _db;
/// <summary>Holds the loop still while an error-page choice works on the database.</summary>
internal async Task<IDisposable> ExclusiveAsync(CancellationToken cancellationToken)
{
await _exclusive.WaitAsync(cancellationToken).ConfigureAwait(false);
return new Releaser(_exclusive);
}
private sealed class Releaser(SemaphoreSlim semaphore) : IDisposable
{
private int _released;
public void Dispose()
{
if (Interlocked.Exchange(ref _released, 1) == 0)
{
semaphore.Release();
}
}
}
public override void Dispose()
{
base.Dispose();
_exclusive.Dispose();
_schedulerStop?.Dispose();
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
if (options.Demo)
{
LogDemo(logger, Config.Data.Root);
}
while (!stoppingToken.IsCancellationRequested)
{
Task wake;
lock (_gate)
{
if (_wake.Task.IsCompleted)
{
_wake = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
}
wake = _wake.Task;
}
try
{
using (await ExclusiveAsync(stoppingToken).ConfigureAwait(false))
{
await StepAsync(stoppingToken).ConfigureAwait(false);
}
}
catch (OperationCanceledException) when (stoppingToken.IsCancellationRequested)
{
break;
}
catch (Exception ex)
{
LogStepFailed(logger, ex);
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
}
await Task.WhenAny(wake, Task.Delay(_interval, stoppingToken)).ConfigureAwait(false);
}
await StopSchedulerAsync().ConfigureAwait(false);
if (_db is not null)
{
await _db.DisposeAsync().ConfigureAwait(false);
}
}
private async Task StepAsync(CancellationToken cancellationToken)
{
// Desktop: the wizard may have written config.toml, or the user fixed it by hand.
if (Config.Platform == PlatformKind.Desktop && !options.Demo && !Config.IsComplete)
{
Config = options.LoadConfig(environment);
}
if (Config.NeedsFirstRun)
{
SetStatus(HostMode.FirstRun, null);
return;
}
if (!Config.IsComplete)
{
SetStatus(HostMode.ConfigProblem, null);
return;
}
if (_services is not null)
{
await CheckRunningAsync(cancellationToken).ConfigureAwait(false);
return;
}
Config.Data.Ensure();
// A data folder that belongs to an installation never gets a new empty SQLite file by itself (trap 20).
_db ??= Database.Open(Config.Db!, allowCreate: !File.Exists(Config.Data.InstallationFile));
try
{
await _db.PingAsync(cancellationToken).ConfigureAwait(false);
LastCheckUtc = clock.UtcNow;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
if (Config.Db!.Engine == DbEngine.Sqlite)
{
// Reopen next time: the file may come back, or the folder may be released.
await _db.DisposeAsync().ConfigureAwait(false);
_db = null;
}
return;
}
// Identity first, migration after: a database that belongs elsewhere is never written to, and an empty one stays
// empty, so a backup taken with an older schema can still be restored into it.
var backups = new Backups(Config.Data, clock);
IdentityCheck identity;
try
{
var schema = await Migrations.StatusAsync(_db, cancellationToken).ConfigureAwait(false);
if (schema.IsEmpty && File.Exists(Config.Data.InstallationFile))
{
identity = new IdentityCheck(IdentityVerdict.EmptyDatabase, Installation.ReadFile(Config.Data), null);
}
else
{
if (schema.IsEmpty)
{
await MigrateAsync(backups, cancellationToken).ConfigureAwait(false);
}
identity = await Installation.CheckAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
if (identity.CanStart)
{
await MigrateAsync(backups, cancellationToken).ConfigureAwait(false);
}
}
}
catch (SchemaException ex)
{
SetStatus(HostMode.SchemaProblem, ex.Message);
return;
}
if (!identity.CanStart)
{
SetStatus(HostMode.IdentityProblem, null, identity);
return;
}
var key = Config.SecretKey.GetOrCreateKey();
var settings = new SettingsStore(_db, clock, bus, StartupOverrides());
var secrets = new SecretStore(_db, clock, key, Config.EnvironmentKeys);
var access = new AccessStore(_db, clock, secrets, PasswordIterations);
if (options.Demo && identity.Verdict == IdentityVerdict.Created)
{
await DemoMode.SeedAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
}
if (!await EnsureUserAsync(access, cancellationToken).ConfigureAwait(false))
{
SetStatus(HostMode.FirstRun, null);
return;
}
var scheduler = new Scheduler(clock, bus);
_services = new AppServices(_db, settings, secrets, access, backups, scheduler);
StartScheduler(scheduler, backups);
SetStatus(HostMode.Ready, null);
}
private async Task MigrateAsync(Backups backups, CancellationToken cancellationToken)
{
var applied = await Migrations.MigrateAsync(_db!, clock, ct => backups.TakeAsync(_db!, "prima-della-migrazione", ct), cancellationToken).ConfigureAwait(false);
if (applied > 0)
{
LogMigrated(logger, applied, Migrations.Latest);
}
}
private async Task<bool> EnsureUserAsync(AccessStore access, CancellationToken cancellationToken)
{
if (await access.HasUserAsync(cancellationToken).ConfigureAwait(false))
{
return true;
}
if (options.Demo)
{
// The demo signs in by itself (see SessionAuthentication); the password exists only to fill the table.
await access.EnsureUserAsync(Ids.NewToken(), mustChange: false, cancellationToken).ConfigureAwait(false);
return true;
}
if (Config.Platform == PlatformKind.Docker && Config.AdminPassword is { } initial)
{
await access.EnsureUserAsync(initial, mustChange: true, cancellationToken).ConfigureAwait(false);
return true;
}
if (PendingPassword is { } chosen)
{
await access.EnsureUserAsync(chosen, mustChange: false, cancellationToken).ConfigureAwait(false);
PendingPassword = null;
return true;
}
return false;
}
// While running: the database is checked every few seconds. If it stops answering, the error page shows and the
// engine waits; when it answers again the installation is checked again (it might be another copy) and the
// application resumes by itself.
private async Task CheckRunningAsync(CancellationToken cancellationToken)
{
try
{
await _db!.PingAsync(cancellationToken).ConfigureAwait(false);
LastCheckUtc = clock.UtcNow;
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
if (_status.Mode != HostMode.DatabaseUnavailable)
{
LogLost(logger, Redactor.Redact(ex.Message));
}
SetStatus(HostMode.DatabaseUnavailable, Redactor.Redact(ex.Message));
return;
}
if (_status.Mode == HostMode.Ready)
{
return;
}
var identity = await Installation.CheckAsync(_db, Config.Data, clock, cancellationToken).ConfigureAwait(false);
if (!identity.CanStart)
{
await StopSchedulerAsync().ConfigureAwait(false);
_services = null;
SetStatus(HostMode.IdentityProblem, null, identity);
return;
}
LogBack(logger);
SetStatus(HostMode.Ready, null);
}
/// <summary>After an error-page choice changed the database: forget the services so the next step starts over.</summary>
internal async Task ResetAsync()
{
await StopSchedulerAsync().ConfigureAwait(false);
_services = null;
Wake();
}
private void StartScheduler(Scheduler scheduler, Backups backups)
{
scheduler.Add(new ScheduledJob("backup", "Salvataggio del database", Schedule.Daily(new TimeOnly(3, 30), Config.TimeZone),
async ct => await backups.TakeAsync(_db!, "notturno", ct).ConfigureAwait(false))
{ MaxLateness = TimeSpan.FromHours(2) });
_schedulerStop = new CancellationTokenSource();
var token = _schedulerStop.Token;
_schedulerLoop = Task.Run(async () =>
{
using var runs = bus.Subscribe<JobRun>();
var recorder = RecordJobsAsync(runs, token);
try
{
await scheduler.RunAsync(token).ConfigureAwait(false);
}
catch (OperationCanceledException) when (token.IsCancellationRequested)
{
}
await recorder.ConfigureAwait(false);
}, CancellationToken.None);
}
// The jobs table keeps the outcome of the last run of each job (Diario e sistema, SPEC 13.6).
private async Task RecordJobsAsync(EventSubscription<JobRun> runs, CancellationToken cancellationToken)
{
try
{
await foreach (var run in runs.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
try
{
await _db!.WriteAsync(async s =>
{
var description = _services?.Scheduler.Upcoming(100).FirstOrDefault(u => u.Name == run.Name)?.Description ?? run.Name;
var updated = await s.ExecuteAsync(
"UPDATE jobs SET last_due_at = @d, last_started_at = @s, last_finished_at = @f, last_outcome = @o, last_error = @e, updated_at = @f WHERE name = @n",
("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc), ("o", run.Outcome.ToString().ToLowerInvariant()), ("e", run.Error), ("n", run.Name)).ConfigureAwait(false);
if (updated == 0)
{
await s.ExecuteAsync(
"INSERT INTO jobs (id, name, description, last_due_at, last_started_at, last_finished_at, last_outcome, last_error, created_at, updated_at) VALUES (@id, @n, @desc, @d, @s, @f, @o, @e, @f, @f)",
("id", Ids.NewId(clock)), ("n", run.Name), ("desc", description), ("d", run.DueUtc), ("s", run.StartedUtc), ("f", run.FinishedUtc),
("o", run.Outcome.ToString().ToLowerInvariant()), ("e", run.Error)).ConfigureAwait(false);
}
}, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
LogJobRecordFailed(logger, ex, run.Name);
}
}
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
}
private async Task StopSchedulerAsync()
{
if (_schedulerStop is null)
{
return;
}
await _schedulerStop.CancelAsync().ConfigureAwait(false);
if (_schedulerLoop is not null)
{
await _schedulerLoop.ConfigureAwait(false);
}
_schedulerStop.Dispose();
_schedulerStop = null;
_schedulerLoop = null;
}
// Values of the startup configuration that also exist as settings are read-only in the interface (SPEC 13.5).
private static Dictionary<string, StartupOverride> StartupOverrides() => [];
private void SetStatus(HostMode mode, string? detail, IdentityCheck? identity = null)
{
var previous = _status;
var attempts = previous.Mode == mode ? previous.Attempts + 1 : 1;
var since = previous.Mode == mode ? previous.Since : clock.UtcNow;
_status = new HostStatus(mode, detail, identity, since, attempts);
if (previous.Mode != mode)
{
LogMode(logger, mode);
bus.Publish(new HostChanged(mode));
}
}
[LoggerMessage(Level = LogLevel.Information, Message = "Mode: {Mode}")]
private static partial void LogMode(ILogger logger, HostMode mode);
[LoggerMessage(Level = LogLevel.Warning, Message = "Demo mode: separate database in {Folder}")]
private static partial void LogDemo(ILogger logger, string folder);
[LoggerMessage(Level = LogLevel.Information, Message = "Applied {Count} migrations, schema version {Version}")]
private static partial void LogMigrated(ILogger logger, int count, int version);
[LoggerMessage(Level = LogLevel.Error, Message = "Database lost: {Reason}")]
private static partial void LogLost(ILogger logger, string reason);
[LoggerMessage(Level = LogLevel.Information, Message = "Database back: resuming")]
private static partial void LogBack(ILogger logger);
[LoggerMessage(Level = LogLevel.Error, Message = "Startup step failed")]
private static partial void LogStepFailed(ILogger logger, Exception exception);
[LoggerMessage(Level = LogLevel.Warning, Message = "Could not record the run of job {Job}")]
private static partial void LogJobRecordFailed(ILogger logger, Exception exception, string job);
}
+362
View File
@@ -0,0 +1,362 @@
/* Anubis — tokens of appendix C (SPEC), light and dark. ContrastTests reads this block: keep one token per line. */
:root {
--page: #f1f3f0;
--surface: #fbfcfa;
--surface-2: #e9ede8;
--track: #dfe4de;
--rule: #d9ded8;
--rule-inner: #e3e7e2;
--control: #8a948e;
--text: #141a17;
--text-2: #46504a;
--text-3: #5f6963;
--link: #1c5cab;
--info-bg: #e3eefb;
--gain: #0a6b55;
--gain-bg: #dff2ea;
--loss: #b42f1a;
--loss-bg: #fbe5df;
--attention: #7a5000;
--attention-bg: #fbefcf;
--s-crypto-trend: #2a78d6;
--s-equity-momentum: #eb6834;
--s-equity-meanrev: #4a3aa7;
--bench: #8a948e;
--cash: #c5cbc4;
}
:root[data-theme="dark"] {
--page: #101412;
--surface: #181d1a;
--surface-2: #222924;
--track: #2c342f;
--rule: #2c342f;
--rule-inner: #262d28;
--control: #6c766f;
--text: #f2f5f1;
--text-2: #c3cbc4;
--text-3: #9aa39c;
--link: #86b6ef;
--info-bg: #17304f;
--gain: #4cc9a4;
--gain-bg: #12372d;
--loss: #ff8d78;
--loss-bg: #45201a;
--attention: #f2c14e;
--attention-bg: #3d2f0c;
--s-crypto-trend: #17a2b8;
--s-equity-momentum: #d95926;
--s-equity-meanrev: #9085e9;
--bench: #6c766f;
--cash: #3a433d;
}
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) {
--page: #101412;
--surface: #181d1a;
--surface-2: #222924;
--track: #2c342f;
--rule: #2c342f;
--rule-inner: #262d28;
--control: #6c766f;
--text: #f2f5f1;
--text-2: #c3cbc4;
--text-3: #9aa39c;
--link: #86b6ef;
--info-bg: #17304f;
--gain: #4cc9a4;
--gain-bg: #12372d;
--loss: #ff8d78;
--loss-bg: #45201a;
--attention: #f2c14e;
--attention-bg: #3d2f0c;
--s-crypto-trend: #17a2b8;
--s-equity-momentum: #d95926;
--s-equity-meanrev: #9085e9;
--bench: #6c766f;
--cash: #3a433d;
}
}
/* Instrument Sans when installed; the file served by the app arrives once its licence and download are approved (ADR 0007). */
:root {
--font: "Instrument Sans", "Segoe UI Variable Text", "Segoe UI", system-ui, -apple-system, "Helvetica Neue", Arial, sans-serif;
color-scheme: light dark;
}
*, *::before, *::after { box-sizing: border-box; }
html { -webkit-text-size-adjust: 100%; }
body {
margin: 0;
background: var(--page);
color: var(--text);
font-family: var(--font);
font-size: 14px;
line-height: 20px;
font-variant-numeric: proportional-nums;
}
a { color: var(--link); }
h1, h2, h3 { margin: 0; font-weight: 650; }
h1 { font-size: 22px; line-height: 28px; }
h2 { font-size: 17px; line-height: 24px; }
h3 { font-size: 14px; line-height: 20px; }
p { margin: 0; }
code { font-family: ui-monospace, "Cascadia Mono", Consolas, monospace; font-size: 12.5px; overflow-wrap: anywhere; }
:focus-visible { outline: 2px solid var(--link); outline-offset: 2px; border-radius: 4px; }
.sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; }
.icon { flex: none; }
.logo-dark { display: none; }
:root[data-theme="dark"] .logo-light { display: none; }
:root[data-theme="dark"] .logo-dark { display: inline; }
@media (prefers-color-scheme: dark) {
:root:not([data-theme="light"]) .logo-light { display: none; }
:root:not([data-theme="light"]) .logo-dark { display: inline; }
}
@media (prefers-reduced-motion: reduce) {
*, *::before, *::after { transition: none !important; animation: none !important; scroll-behavior: auto !important; }
}
/* ---- Shell ---- */
.shell { display: grid; grid-template-columns: 220px minmax(0, 1fr); min-height: 100vh; }
.sidebar {
position: sticky; top: 0; height: 100vh; overflow-y: auto;
background: var(--surface); border-right: 1px solid var(--rule);
padding: 20px 12px 24px;
}
.brand { display: flex; align-items: center; justify-content: space-between; padding: 0 8px 0 10px; margin-bottom: 20px; min-height: 40px; }
.brand-link { display: flex; align-items: center; gap: 14px; color: var(--text); text-decoration: none; font-size: 20px; font-weight: 650; }
.icon-button {
display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px;
border: 0; border-radius: 8px; background: transparent; color: var(--text-3); cursor: pointer;
}
.icon-button:hover { background: var(--surface-2); color: var(--text); }
.when-closed { display: none; }
.nav-group { list-style: none; margin: 0; padding: 0; }
.nav-group + .nav-group { margin-top: 22px; }
.nav-item {
display: flex; align-items: center; gap: 12px; min-height: 40px; padding: 8px 12px; margin-bottom: 2px;
border-radius: 8px; color: var(--text-2); text-decoration: none; font-size: 14px;
}
.nav-item:hover { background: var(--surface-2); color: var(--text); }
.nav-item.active { background: var(--surface-2); color: var(--text); font-weight: 600; }
:root[data-nav="collapsed"] .shell { grid-template-columns: 72px minmax(0, 1fr); }
:root[data-nav="collapsed"] .brand { flex-direction: column; gap: 8px; padding: 0; }
:root[data-nav="collapsed"] .brand-name,
:root[data-nav="collapsed"] .nav-label { display: none; }
:root[data-nav="collapsed"] .nav-item { justify-content: center; padding: 10px; }
:root[data-nav="collapsed"] .when-open { display: none; }
:root[data-nav="collapsed"] .when-closed { display: inline; }
.main { min-width: 0; display: flex; flex-direction: column; }
.topbar {
display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: nowrap;
padding: 16px 32px; background: var(--surface); border-bottom: 1px solid var(--rule);
}
.topbar-title { min-width: 0; flex: 1 1 auto; }
.status-line { color: var(--text-3); font-size: 13px; line-height: 18px; margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.topbar-actions { display: flex; align-items: center; gap: 8px; flex: none; }
@media (max-width: 1240px) {
.topbar { flex-wrap: wrap; }
.topbar-actions { flex-wrap: wrap; }
}
.topbar-actions form { margin: 0; }
.phone-brand, .phone-bot, .mode-band, .bottombar { display: none; }
.pill {
display: inline-flex; align-items: center; gap: 8px; height: 32px; padding: 0 12px;
border-radius: 999px; font-size: 14px; font-weight: 550; white-space: nowrap;
}
.pill-bot { border: 1px solid var(--rule); background: var(--surface); color: var(--text); margin-right: 0; }
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--gain); flex: none; }
[data-state="paused"] .dot { background: var(--attention); }
[data-state="stopped"] .dot { background: var(--loss); }
.pill-mode { background: var(--info-bg); color: var(--link); margin-right: 12px; }
.btn {
display: inline-flex; align-items: center; justify-content: center; gap: 10px; height: 40px; padding: 0 16px;
border: 1px solid var(--control); border-radius: 8px; background: var(--surface); color: var(--text);
font: inherit; font-size: 14px; font-weight: 550; cursor: pointer; text-decoration: none; white-space: nowrap;
}
.btn:hover { background: var(--surface-2); }
.btn:disabled { opacity: .55; cursor: not-allowed; }
.btn-small { height: 32px; padding: 0 12px; }
.btn-danger { border-color: var(--loss); color: var(--loss); }
.btn-danger:hover { background: var(--loss-bg); }
.btn-primary { background: var(--text); border-color: var(--text); color: var(--surface); }
.btn-primary:hover { background: var(--text-2); }
.currency { position: relative; }
.currency select, select, input:not([type="radio"]):not([type="checkbox"]):not([type="hidden"]) {
height: 40px; border: 1px solid var(--control); border-radius: 8px; background: var(--surface); color: var(--text);
font: inherit; font-size: 14px; padding: 0 12px;
}
.currency select { appearance: none; padding: 0 40px 0 16px; font-weight: 550; cursor: pointer; }
.select-chevron { position: absolute; right: 14px; top: 12px; pointer-events: none; color: var(--text-2); }
.stale-notice {
display: flex; align-items: center; gap: 10px; margin: 12px 32px 0; padding: 10px 12px; border-radius: 10px;
background: var(--attention-bg); color: var(--attention); font-size: 13.5px;
}
.stale-notice[hidden] { display: none; }
.page { padding: 28px 32px 36px; display: flex; flex-direction: column; gap: 28px; flex: 1; }
.page-footer { color: var(--text-3); font-size: 13px; line-height: 18px; }
/* ---- Components ---- */
.panel { background: var(--surface); border: 1px solid var(--rule); border-radius: 14px; padding: 20px 22px; }
.panel > h2 { display: flex; align-items: center; gap: 10px; margin-bottom: 12px; }
.panel > h3, .panel h3 { margin: 20px 0 8px; }
.note { color: var(--text-3); font-size: 13px; line-height: 18px; }
.hint { color: var(--text-3); font-size: 13px; line-height: 18px; }
.empty { display: flex; flex-direction: column; gap: 8px; color: var(--text-2); max-width: 70ch; }
.empty-title { color: var(--text); font-weight: 600; font-size: 15px; }
.notice {
display: flex; align-items: flex-start; gap: 10px; padding: 10px 12px; border-radius: 10px; font-size: 13.5px; line-height: 20px;
}
.notice .icon { margin-top: 2px; }
.notice-loss { background: var(--loss-bg); color: var(--loss); }
.notice-gain { background: var(--gain-bg); color: var(--gain); }
.notice-attention { background: var(--attention-bg); color: var(--attention); }
.badge { display: inline-flex; align-items: center; gap: 8px; padding: 6px 12px; border-radius: 8px; font-size: 18px; line-height: 24px; font-weight: 600; }
.badge-gain { background: var(--gain-bg); color: var(--gain); }
.badge-loss { background: var(--loss-bg); color: var(--loss); }
.gain { color: var(--gain); }
.loss { color: var(--loss); }
.arrow { flex: none; }
.table-wrap { overflow-x: auto; }
.table { width: 100%; border-collapse: collapse; font-size: 13.5px; line-height: 20px; font-variant-numeric: tabular-nums; }
.table th { text-align: left; font-size: 12.5px; font-weight: 500; color: var(--text-3); padding: 9px 12px 9px 0; border-bottom: 1px solid var(--rule-inner); }
.table td { padding: 10px 12px 10px 0; border-bottom: 1px solid var(--rule-inner); vertical-align: top; }
.table .num { text-align: right; }
.nowrap { white-space: nowrap; }
.facts { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 8px 20px; margin: 0; }
.facts dt { color: var(--text-3); }
.facts dd { margin: 0; overflow-wrap: anywhere; }
.facts + .hint, .facts + h2, .facts + h3 { margin-top: 16px; }
.form { display: flex; flex-direction: column; gap: 8px; max-width: 420px; }
.form label { font-weight: 550; margin-top: 6px; }
.form .btn { align-self: flex-start; margin-top: 10px; }
.form-inline { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; margin: 8px 0; }
.form-inline label { min-width: 80px; font-weight: 550; }
.row { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
.row > div { display: flex; flex-direction: column; gap: 8px; }
.choice { display: flex; gap: 10px; align-items: flex-start; font-weight: 400 !important; padding: 10px 12px; border: 1px solid var(--rule); border-radius: 10px; }
.choice input { margin-top: 4px; }
fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }
legend { display: flex; align-items: center; gap: 10px; font-size: 17px; font-weight: 650; margin-bottom: 8px; padding: 0; }
.step { display: inline-flex; width: 26px; height: 26px; border-radius: 50%; background: var(--surface-2); align-items: center; justify-content: center; font-size: 14px; }
.postgres-fields { display: flex; flex-direction: column; gap: 8px; margin-top: 4px; }
.postgres-fields[hidden] { display: none; }
.test-result:empty { display: none; }
.steps { margin: 8px 0; padding-left: 20px; display: flex; flex-direction: column; gap: 6px; }
.secret { background: var(--surface-2); padding: 2px 6px; border-radius: 6px; }
.tabs { display: flex; gap: 16px; flex-wrap: wrap; }
.tabs a { color: var(--text-2); text-decoration: none; font-weight: 550; }
.tabs a:hover { color: var(--text); text-decoration: underline; }
.columns { display: grid; grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); gap: 20px; align-items: start; }
.more-list { list-style: none; margin: 0; padding: 0; }
.more-list a { display: flex; align-items: center; gap: 12px; min-height: 48px; color: var(--text); text-decoration: none; border-bottom: 1px solid var(--rule-inner); }
/* ---- Panoramica ---- */
.head-block { display: grid; grid-template-columns: 1.35fr 1fr; padding: 0; }
.half { padding: 24px 28px; min-width: 0; }
.half + .half { border-left: 1px solid var(--rule); }
.half-head { display: flex; align-items: center; justify-content: space-between; gap: 16px; flex-wrap: wrap; min-height: 44px; }
.half-head h2 { display: flex; align-items: center; gap: 12px; }
.segmented { display: inline-flex; padding: 4px; border-radius: 10px; background: var(--surface-2); gap: 2px; }
.segmented a { padding: 6px 14px; border-radius: 8px; color: var(--text-2); text-decoration: none; font-size: 14px; }
.segmented a.on { background: var(--surface); color: var(--text); font-weight: 550; }
.lead { color: var(--text-2); font-size: 17px; line-height: 24px; margin-top: 20px; }
.big-result { display: flex; align-items: center; gap: 20px; flex-wrap: wrap; margin-top: 4px; }
.big-number { font-size: 60px; line-height: 60px; font-weight: 650; letter-spacing: -0.025em; }
.half-past .note { margin-top: 10px; }
.cells { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; margin-top: 20px; padding: 16px 0; border-top: 1px solid var(--rule); border-bottom: 1px solid var(--rule); }
.cell { display: flex; flex-direction: column; gap: 2px; }
.cell-label { color: var(--text-3); font-size: 13px; }
.cell-value { font-size: 18px; line-height: 24px; font-weight: 650; letter-spacing: -0.015em; }
.cell-change { display: inline-flex; align-items: center; gap: 6px; font-size: 13px; font-weight: 550; }
.statement { font-size: 20px; line-height: 28px; font-weight: 650; margin: 20px 0 8px; }
.list-title { color: var(--text-3); font-weight: 550; margin-top: 20px !important; padding-bottom: 8px; border-bottom: 1px solid var(--rule); }
.moves { list-style: none; margin: 0; padding: 0; }
.moves li { display: grid; grid-template-columns: 72px minmax(0, 1fr); gap: 12px; padding: 12px 0; border-bottom: 1px solid var(--rule-inner); }
.move-time { font-weight: 650; font-variant-numeric: tabular-nums; }
.moves-past .move-time { font-weight: 500; color: var(--text-3); }
.more { display: inline-block; margin-top: 12px; }
.chart { margin: 20px 0 0; }
.chart-box { position: relative; display: grid; grid-template-columns: 64px minmax(0, 1fr) 84px; height: 284px; }
.chart-axis { position: relative; }
.chart-axis span { position: absolute; left: 0; transform: translateY(-50%); color: var(--text-3); font-size: 13px; font-variant-numeric: tabular-nums; }
.chart-plot { position: relative; }
.chart-plot svg { position: absolute; inset: 0; width: 100%; height: 100%; overflow: visible; }
.chart .grid { stroke: var(--rule-inner); stroke-width: 1; }
.chart .area { fill: var(--text); opacity: .05; }
.chart .equity { fill: none; stroke: var(--text); stroke-width: 2; stroke-linejoin: round; }
.chart .bench { fill: none; stroke: var(--bench); stroke-width: 2; stroke-linejoin: round; }
.end-dot { position: absolute; width: 14px; height: 14px; margin: -7px 0 0 -7px; border-radius: 50%; background: var(--text); border: 2px solid var(--surface); }
.end-dot.bench-dot { background: var(--bench); }
.end-label { position: absolute; left: 100%; margin-left: 14px; transform: translateY(-50%); font-weight: 650; font-size: 13px; white-space: nowrap; }
.end-label.bench-label { font-weight: 400; color: var(--text-3); }
.legend { display: flex; gap: 20px; margin-top: 12px; color: var(--text-2); font-size: 13px; }
.key { display: inline-flex; align-items: center; gap: 8px; }
.key::before { content: ""; width: 18px; height: 2px; background: var(--text); }
.key-bench::before { background: var(--bench); }
.chart-table { margin-top: 8px; font-size: 13px; }
.chart-table summary { color: var(--link); cursor: pointer; }
.chart-table .table-wrap { max-height: 280px; overflow: auto; margin-top: 8px; }
/* ---- Service pages ---- */
.service { min-height: 100vh; display: flex; justify-content: center; padding: 48px 16px; }
.service-box { width: 100%; max-width: 720px; display: flex; flex-direction: column; gap: 16px; }
.service-brand { display: flex; align-items: center; gap: 14px; font-size: 22px; font-weight: 650; margin-bottom: 8px; }
.service-section { background: var(--surface); border: 1px solid var(--rule); border-radius: 14px; padding: 20px 22px; display: flex; flex-direction: column; gap: 10px; }
.service-section h2 { display: flex; align-items: center; gap: 10px; }
.service-foot { color: var(--text-3); font-size: 13px; margin-top: 8px; }
.problems td:first-child { white-space: nowrap; }
/* ---- Phone (SPEC 13.4, appendix C): 390 px and below the tablet width ---- */
@media (max-width: 760px) {
.shell { display: block; padding-bottom: 76px; }
.sidebar { display: none; }
.topbar { flex-wrap: nowrap; padding: 12px 16px; }
.topbar h1, .status-line, .pill, .currency, .topbar-actions form:not(.stop-form) { display: none; }
.topbar-title { display: flex; align-items: center; gap: 14px; }
.phone-brand { display: flex; align-items: center; gap: 10px; color: var(--text); text-decoration: none; font-size: 18px; font-weight: 650; }
.phone-bot { display: inline-flex; align-items: center; gap: 8px; color: var(--text-2); font-size: 14px; }
.btn-danger { height: 44px; }
.mode-band { display: flex; align-items: center; gap: 10px; padding: 10px 16px; background: var(--info-bg); color: var(--link); font-weight: 550; font-size: 14px; }
.stale-notice { margin: 12px 16px 0; }
.page { padding: 16px; gap: 14px; }
.panel { padding: 18px; }
.head-block { grid-template-columns: 1fr; gap: 14px; padding: 0; background: none; border: 0; }
.half { padding: 18px; background: var(--surface); border: 1px solid var(--rule); border-radius: 14px; }
.half + .half { border-left: 1px solid var(--rule); }
.segmented, .cell-change, .cell-extra, .long, .chart-axis { display: none; }
.lead { margin-top: 12px; }
.big-result { gap: 12px; }
.big-number { font-size: 46px; line-height: 48px; }
.badge { font-size: 15px; padding: 4px 10px; }
.cells { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.chart-box { grid-template-columns: minmax(0, 1fr) 80px; height: 200px; }
.legend { flex-direction: column; gap: 4px; }
.statement { font-size: 18px; line-height: 26px; margin-top: 12px; }
.columns { grid-template-columns: 1fr; }
.row { grid-template-columns: 1fr; }
.facts { grid-template-columns: 1fr; gap: 2px; }
.facts dd { margin-bottom: 8px; }
.bottombar {
display: grid; grid-template-columns: repeat(5, 1fr); gap: 4px; position: fixed; left: 0; right: 0; bottom: 0;
padding: 6px 6px calc(6px + env(safe-area-inset-bottom)); background: var(--surface); border-top: 1px solid var(--rule); z-index: 10;
}
.bottom-item {
display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 4px; min-height: 52px;
border-radius: 10px; color: var(--text-2); text-decoration: none; font-size: 11.5px; line-height: 14px;
}
.bottom-item.active { background: var(--surface-2); color: var(--text); font-weight: 650; }
.nav-item, .btn, .more-list a { min-height: 44px; }
}
+128
View File
@@ -0,0 +1,128 @@
// Anubis: the few behaviours the server-rendered pages need. No libraries, no requests to other servers.
(function () {
"use strict";
// Collapsible menu, remembered on this device.
var collapse = document.querySelector("[data-collapse]");
if (collapse) {
var sync = function () {
var closed = document.documentElement.dataset.nav === "collapsed";
collapse.setAttribute("aria-expanded", closed ? "false" : "true");
collapse.setAttribute("aria-label", closed ? "Espandi il menu" : "Comprimi il menu");
};
sync();
collapse.addEventListener("click", function () {
var closed = document.documentElement.dataset.nav !== "collapsed";
if (closed) {
document.documentElement.dataset.nav = "collapsed";
} else {
delete document.documentElement.dataset.nav;
}
try { localStorage.setItem("anubis.nav", closed ? "collapsed" : "open"); } catch (e) { /* storage blocked */ }
sync();
});
}
// Selects that apply at once (currency, theme).
document.querySelectorAll("select[data-autosubmit]").forEach(function (select) {
select.addEventListener("change", function () { select.form.submit(); });
});
// Buttons that ask before acting ("Ferma tutto").
document.querySelectorAll("[data-confirm]").forEach(function (button) {
button.addEventListener("click", function (event) {
if (!window.confirm(button.getAttribute("data-confirm"))) {
event.preventDefault();
}
});
});
// First run: PostgreSQL fields only when chosen; "Prova la connessione" without leaving the page.
var wizard = document.querySelector("[data-wizard]");
if (wizard) {
var fields = wizard.querySelector("[data-postgres]");
var engines = wizard.querySelectorAll("[data-engine]");
var showFields = function () {
if (!fields) { return; }
var pg = wizard.querySelector("[data-engine]:checked");
fields.hidden = !(pg && pg.value === "postgres");
};
engines.forEach(function (radio) { radio.addEventListener("change", showFields); });
showFields();
var test = wizard.querySelector("[data-test-connection]");
var result = wizard.querySelector("[data-test-result]");
if (test && result) {
test.addEventListener("click", function (event) {
event.preventDefault();
result.textContent = "Provo…";
fetch("/azioni/primo-avvio/prova", { method: "POST", body: new FormData(wizard), credentials: "same-origin" })
.then(function (response) { return response.json(); })
.then(function (answer) { result.textContent = answer.message; result.className = "test-result " + (answer.ok ? "gain" : "loss"); })
.catch(function () { result.textContent = "Non riesco a fare la prova adesso. Riprova tra poco."; result.className = "test-result loss"; });
});
}
}
// Live status over the WebSocket: bot state, freshness of the data, and a discreet notice when the link drops.
var age = document.querySelector("[data-live='age']");
if (!age || !("WebSocket" in window)) { return; }
var lastAge = Number(age.getAttribute("data-age")) || 0;
var lastAt = Date.now();
var lastMessage = Date.now();
var connected = false;
var retry = 1000;
var stale = document.querySelector("[data-stale]");
var staleText = document.querySelector("[data-stale-text]");
var ago = function (seconds) {
seconds = Math.max(0, Math.floor(seconds));
if (seconds < 60) { return seconds + (seconds === 1 ? " secondo fa" : " secondi fa"); }
var minutes = Math.floor(seconds / 60);
if (minutes < 60) { return minutes + (minutes === 1 ? " minuto fa" : " minuti fa"); }
var hours = Math.floor(minutes / 60);
return hours + (hours === 1 ? " ora fa" : " ore fa");
};
var tick = function () {
var seconds = lastAge + (Date.now() - lastAt) / 1000;
age.textContent = "Dati aggiornati " + ago(seconds);
var silent = (Date.now() - lastMessage) / 1000;
if (stale && (!connected || silent > 15)) {
stale.hidden = false;
staleText.textContent = "Collegamento interrotto: i dati sono fermi da " + ago(seconds).replace(" fa", "") + ". Riprovo da solo.";
} else if (stale) {
stale.hidden = true;
}
};
var apply = function (status) {
lastAge = status.ageSeconds;
lastAt = Date.now();
document.querySelectorAll("[data-live='bot']").forEach(function (el) { el.setAttribute("data-state", status.bot); });
document.querySelectorAll("[data-live='bot-label']").forEach(function (el) { el.textContent = status.botLabel; });
document.querySelectorAll("[data-live='bot-short']").forEach(function (el) { el.textContent = status.botShort; });
var now = document.querySelector("[data-live='now']");
if (now) { now.textContent = status.now; }
};
var connect = function () {
var socket = new WebSocket((location.protocol === "https:" ? "wss://" : "ws://") + location.host + "/ws");
socket.onopen = function () { connected = true; retry = 1000; };
socket.onmessage = function (event) {
lastMessage = Date.now();
try {
var message = JSON.parse(event.data);
if (message.type === "status") { apply(message.status); }
} catch (e) { /* ignore a malformed message */ }
};
socket.onclose = function () {
connected = false;
setTimeout(connect, retry);
retry = Math.min(retry * 2, 30000);
};
};
connect();
setInterval(tick, 1000);
})();
+10
View File
@@ -0,0 +1,10 @@
// Runs before the page paints: applies the remembered menu state so the menu does not jump (SPEC 13.4).
(function () {
try {
if (localStorage.getItem("anubis.nav") === "collapsed") {
document.documentElement.dataset.nav = "collapsed";
}
} catch (e) {
// Storage blocked: the menu simply starts open.
}
})();
@@ -0,0 +1,12 @@
@if (Docker)
{
<label for="@_id">Password della configurazione d'avvio (<code>ANUBIS_ADMIN_PASSWORD</code>)</label>
<input id="@_id" name="password" type="password" autocomplete="off" required />
}
@code {
private readonly string _id = "admin-" + Guid.NewGuid().ToString("N")[..6];
[Parameter]
public bool Docker { get; set; }
}
+28
View File
@@ -0,0 +1,28 @@
@inherits LoadedComponent
@inject ShellData Shell
<!DOCTYPE html>
<html lang="it" data-theme="@_theme">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light dark" />
<link rel="icon" href="/favicon.ico" />
<link rel="stylesheet" href="/assets/app.css?v=@AnubisInfo.Version" />
<script src="/assets/early.js?v=@AnubisInfo.Version"></script>
<HeadOutlet />
</head>
<body>
<Routes />
<script src="/assets/app.js?v=@AnubisInfo.Version" defer></script>
</body>
</html>
@code {
private string? _theme;
protected override async Task LoadAsync()
{
var snapshot = await Shell.SnapshotAsync(CancellationToken.None);
_theme = snapshot.Theme == "auto" ? null : snapshot.Theme;
}
}
+16
View File
@@ -0,0 +1,16 @@
@* A small filled triangle: the direction is never told by colour alone (SPEC 13.2). *@
<svg class="arrow" width="10" height="10" viewBox="0 0 10 10" aria-hidden="true" focusable="false">
@if (Up)
{
<path d="M5 1.5 9.3 8.5H.7Z" fill="currentColor" />
}
else
{
<path d="M5 8.5.7 1.5h8.6Z" fill="currentColor" />
}
</svg>
@code {
[Parameter]
public bool Up { get; set; }
}
@@ -0,0 +1,102 @@
@inject ShellData Shell
@* Equity against the "senza bot" comparison (SPEC 13.4): one scale, 2 px lines, faint grid, direct label on the last
point, legend, and the same numbers in a table. Lines are SVG stretched to the box; texts and the end point are
HTML placed in percent, so nothing gets distorted at any width. *@
@if (Points.Count >= 2)
{
var values = Points.Select(p => Shell.Convert(p.Equity, Currency)).ToList();
var bench = Points.Select(p => p.Benchmark is { } b ? Shell.Convert(b, Currency) : (decimal?)null).ToList();
var all = values.Concat(bench.OfType<decimal>()).ToList();
var (lo, hi, step) = Scale(all.Min(), all.Max());
double X(int i) => i * 1000.0 / (Points.Count - 1);
double Y(decimal v) => (double)((hi - v) / (hi - lo)) * 1000.0;
string Line(IEnumerable<(int I, decimal V)> pts) => string.Join(" ", pts.Select(p => Fmt(X(p.I)) + "," + Fmt(Y(p.V))));
var equityLine = Line(values.Select((v, i) => (i, v)));
var benchLine = Line(bench.Select((v, i) => (i, v)).Where(p => p.v is not null).Select(p => (p.i, p.v!.Value)));
var last = values[^1];
<figure class="chart" aria-label="Patrimonio nel tempo, con il bot e senza">
<div class="chart-box">
<div class="chart-axis" aria-hidden="true">
@for (var t = lo; t <= hi; t += step)
{
<span style="top:@Pct(Y(t) / 10)">@Format.Number(t)</span>
}
</div>
<div class="chart-plot">
<svg viewBox="0 0 1000 1000" preserveAspectRatio="none" aria-hidden="true" focusable="false">
@for (var t = lo; t <= hi; t += step)
{
<line class="grid" x1="0" x2="1000" y1="@Fmt(Y(t))" y2="@Fmt(Y(t))" vector-effect="non-scaling-stroke" />
}
<polygon class="area" points="0,1000 @equityLine 1000,1000" />
@if (benchLine.Length > 0)
{
<polyline class="bench" points="@benchLine" vector-effect="non-scaling-stroke" />
}
<polyline class="equity" points="@equityLine" vector-effect="non-scaling-stroke" />
</svg>
@if (bench[^1] is { } lastBench)
{
// Two labels never overlap: the lower one moves down when they are closer than one line.
var gap = Math.Abs(Y(last) - Y(lastBench)) / 10;
var benchTop = gap < 7 ? Y(last) / 10 + (Y(lastBench) >= Y(last) ? 7 : -7) : Y(lastBench) / 10;
<span class="end-dot bench-dot" style="left:100%;top:@Pct(Y(lastBench) / 10)"></span>
<span class="end-label bench-label" style="top:@Pct(benchTop)">@Shell.Money(Points[^1].Benchmark!.Value, Currency, decimals: 0)</span>
}
<span class="end-dot" style="left:100%;top:@Pct(Y(last) / 10)"></span>
<span class="end-label" style="top:@Pct(Y(last) / 10)">@Shell.Money(Points[^1].Equity, Currency, decimals: 0)</span>
</div>
</div>
<figcaption class="legend">
<span class="key key-equity">Con Anubis</span>
@if (benchLine.Length > 0)
{
<span class="key key-bench">Senza bot: Bitcoin e S&amp;P 500 comprati e tenuti</span>
}
</figcaption>
<details class="chart-table">
<summary>Vedi i numeri in una tabella</summary>
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col">Giorno</th><th scope="col" class="num">Con il bot</th><th scope="col" class="num">Senza bot</th></tr></thead>
<tbody>
@foreach (var p in Points.AsEnumerable().Reverse())
{
<tr><td>@Format.LongDate(p.Day)</td><td class="num">@Shell.Money(p.Equity, Currency)</td><td class="num">@(p.Benchmark is { } b ? Shell.Money(b, Currency) : "—")</td></tr>
}
</tbody>
</table>
</div>
</details>
</figure>
}
@code {
[Parameter, EditorRequired]
public IReadOnlyList<EquityPoint> Points { get; set; } = [];
[Parameter]
public string Currency { get; set; } = "EUR";
private static string Fmt(double v) => v.ToString("0.##", CultureInfo.InvariantCulture);
private static string Pct(double v) => v.ToString("0.###", CultureInfo.InvariantCulture) + "%";
// Round steps (1, 2, 2.5, 3, 5 times a power of ten) giving three to five grid lines.
internal static (decimal Lo, decimal Hi, decimal Step) Scale(decimal min, decimal max)
{
if (max <= min)
{
max = min + 1;
}
var raw = (double)(max - min) / 4;
var power = Math.Pow(10, Math.Floor(Math.Log10(raw)));
var step = new[] { 1, 2, 2.5, 3, 5, 10 }.Select(m => m * power).First(s => s >= raw);
var stepValue = (decimal)step;
var lo = Math.Floor(min / stepValue) * stepValue;
var hi = Math.Ceiling(max / stepValue) * stepValue;
return (lo, hi == lo ? lo + stepValue : hi, stepValue);
}
}
+95
View File
@@ -0,0 +1,95 @@
@* Line icons drawn for Anubis: 24 grid, stroke 2, round ends (appendix C). Decorative: the text next to them says it all. *@
<svg class="icon @Class" width="@Size" height="@Size" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" focusable="false">
@switch (Name)
{
case "grid":
<rect x="3.5" y="3.5" width="7" height="7" rx="1.5" /><rect x="13.5" y="3.5" width="7" height="7" rx="1.5" /><rect x="3.5" y="13.5" width="7" height="7" rx="1.5" /><rect x="13.5" y="13.5" width="7" height="7" rx="1.5" />
break;
case "card":
<rect x="3" y="5.5" width="18" height="13" rx="2.5" /><path d="M3 10h18M16 14.5h2" />
break;
case "arrows":
<path d="M5 8h14M15 4l4 4-4 4M19 16H5M9 12l-4 4 4 4" />
break;
case "layers":
<path d="M12 3 3 8l9 5 9-5-9-5Z" /><path d="m3 12.5 9 5 9-5" /><path d="m3 16.5 9 5 9-5" />
break;
case "news":
<rect x="3.5" y="4" width="17" height="16" rx="2.5" /><path d="M7.5 9h9M7.5 12.5h9M7.5 16h5" />
break;
case "network":
<circle cx="5.5" cy="5.5" r="2.2" /><circle cx="18.5" cy="5.5" r="2.2" /><circle cx="12" cy="18.5" r="2.2" /><path d="M7.5 6.5 11 16.4M16.5 6.5 13 16.4M7.7 5.5h8.6" />
break;
case "shield":
<path d="M12 3 5 6v5.5c0 4.4 3 8 7 9.5 4-1.5 7-5.1 7-9.5V6l-7-3Z" /><path d="m9 12 2.2 2.2L15.5 10" />
break;
case "list":
<path d="M9 6h11M9 12h11M9 18h11" /><circle cx="4.5" cy="6" r="0.6" /><circle cx="4.5" cy="12" r="0.6" /><circle cx="4.5" cy="18" r="0.6" />
break;
case "flask":
<path d="M9.5 3h5M10 3v6.2L4.8 18.3A1.8 1.8 0 0 0 6.4 21h11.2a1.8 1.8 0 0 0 1.6-2.7L14 9.2V3" /><path d="M7.3 15h9.4" />
break;
case "sliders":
<path d="M4 7h9M17 7h3M4 17h3M11 17h9" /><circle cx="15" cy="7" r="2" /><circle cx="9" cy="17" r="2" />
break;
case "dots":
<circle cx="5.5" cy="12" r="1" /><circle cx="12" cy="12" r="1" /><circle cx="18.5" cy="12" r="1" />
break;
case "collapse":
<path d="m11 17-5-5 5-5M18 17l-5-5 5-5" />
break;
case "expand":
<path d="m13 17 5-5-5-5M6 17l5-5-5-5" />
break;
case "pause":
<path d="M9.5 6v12M14.5 6v12" />
break;
case "play":
<path d="M8 5.5v13l10-6.5-10-6.5Z" />
break;
case "stop":
<path d="M8.3 3h7.4L21 8.3v7.4L15.7 21H8.3L3 15.7V8.3L8.3 3Z" /><rect x="9.5" y="9.5" width="5" height="5" rx="0.6" />
break;
case "chevron":
<path d="m6 9 6 6 6-6" />
break;
case "clock":
<circle cx="12" cy="12" r="8.5" /><path d="M12 7.5V12l3 2" />
break;
case "half":
<path d="M12 3.5a8.5 8.5 0 0 0 0 17Z" fill="currentColor" />
break;
case "next":
<path d="M8 3.5h1a8.5 8.5 0 0 1 0 17H8Z" />
break;
case "alert":
<path d="M12 4 2.8 19.5h18.4L12 4Z" /><path d="M12 10v4M12 17h.01" />
break;
case "info":
<circle cx="12" cy="12" r="8.5" /><path d="M12 11v5M12 8h.01" />
break;
case "check":
<circle cx="12" cy="12" r="8.5" /><path d="m8.5 12 2.4 2.4 4.6-4.8" />
break;
case "database":
<ellipse cx="12" cy="6" rx="7.5" ry="2.8" /><path d="M4.5 6v12c0 1.5 3.4 2.8 7.5 2.8s7.5-1.3 7.5-2.8V6M4.5 12c0 1.5 3.4 2.8 7.5 2.8s7.5-1.3 7.5-2.8" />
break;
case "lock":
<rect x="5" y="10.5" width="14" height="10" rx="2.2" /><path d="M8.5 10.5V7.8a3.5 3.5 0 0 1 7 0v2.7" />
break;
case "logout":
<path d="M14 4h4.5A1.5 1.5 0 0 1 20 5.5v13a1.5 1.5 0 0 1-1.5 1.5H14M10 16l-4-4 4-4M6 12h10" />
break;
}
</svg>
@code {
[Parameter, EditorRequired]
public string Name { get; set; } = "";
[Parameter]
public int Size { get; set; } = 20;
[Parameter]
public string? Class { get; set; }
}
@@ -0,0 +1,125 @@
@inject AnubisHost Host
@inject IClock Clock
@* SPEC 15.1: database and data folder disagree. The user chooses; Docker asks the startup password because users
and sessions live in the database that is missing, desktop accepts choices only from the computer itself. *@
@{
var verdict = Status.Identity!.Verdict;
var data = Host.Config.Data;
var docker = Host.Config.Platform == PlatformKind.Docker;
var canChoose = docker || Local;
}
@switch (verdict)
{
case IdentityVerdict.EmptyDatabase:
<p>Il database è vuoto, ma la cartella dei dati appartiene a un'installazione che esiste già. Il motore resta spento: se partisse, comincerebbe da zero e i conti risulterebbero diversi dal registro.</p>
break;
case IdentityVerdict.DifferentInstallation:
<p>Il database appartiene a un'altra installazione di Anubis. Il motore resta spento: due registri sugli stessi conti produrrebbero ordini doppi.</p>
break;
case IdentityVerdict.StaleDatabase:
<p>È il database di questa installazione, ma una copia più vecchia: dopo l'ultimo ripristino o spostamento ne è nata una più recente. Il motore resta spento per non lavorare su dati superati.</p>
break;
}
<dl class="facts">
<dt>Database</dt><dd>@Host.Config.Db?.Describe()</dd>
<dt>Cartella dei dati</dt><dd>@data.Root</dd>
@if (Status.Identity.File is { } file)
{
<dt>Installazione della cartella</dt><dd>@file.InstallationId.ToString("D")[..8], nata il @Format.ShortDate(file.CreatedAt, Clock.UtcNow, Host.Config.TimeZone, withTime: false)</dd>
}
@if (Status.Identity.Row is { } row)
{
<dt>Installazione del database</dt><dd>@row.Id.ToString("D")[..8], nata il @Format.ShortDate(row.CreatedAt, Clock.UtcNow, Host.Config.TimeZone, withTime: false)</dd>
}
</dl>
<p class="hint">La soluzione più sicura spesso è correggere la configurazione perché punti al database giusto. Altrimenti scegli qui sotto. Dopo un ripristino o un'importazione il bot riparte protetto: "Ferma tutto" acceso finché non confermi.</p>
@if (!canChoose)
{
<p class="notice notice-attention" role="status"><Icon Name="lock" Size="16" />Queste scelte si fanno solo dal computer su cui gira Anubis.</p>
}
else
{
@if (verdict == IdentityVerdict.EmptyDatabase)
{
var backups = new Backups(data, Clock).List();
var imports = ServiceChoices.ImportFolders(data);
<section class="service-section">
<h2>Ripristina un salvataggio</h2>
@if (backups.Count == 0)
{
<p class="hint">Nessun salvataggio nella cartella <code>@data.Backups</code>.</p>
}
else
{
<form method="post" action="/azioni/servizio/ripristina" class="form">
<AntiforgeryToken />
<label for="salvataggio">Salvataggio</label>
<select id="salvataggio" name="salvataggio">
@foreach (var backup in backups)
{
<option value="@backup.Name">@Format.ShortDate(backup.TakenAt, Clock.UtcNow, Host.Config.TimeZone) · @backup.Reason</option>
}
</select>
<AdminPassword Docker="docker" />
<button class="btn btn-primary" type="submit">Ripristina</button>
</form>
}
</section>
<section class="service-section">
<h2>Importa un archivio</h2>
@if (imports.Count == 0)
{
<p class="hint">Metti la cartella di un archivio esportato (con il suo <code>index.json</code>) dentro <code>@data.Import</code> e ricarica la pagina.</p>
}
else
{
<form method="post" action="/azioni/servizio/importa" class="form">
<AntiforgeryToken />
<label for="archivio">Archivio</label>
<select id="archivio" name="archivio">
@foreach (var folder in imports)
{
<option value="@Path.GetFileName(folder)">@Path.GetFileName(folder)</option>
}
</select>
<AdminPassword Docker="docker" />
<button class="btn btn-primary" type="submit">Importa</button>
</form>
}
</section>
<section class="service-section">
<h2>Comincia da capo</h2>
<p class="hint">Una nuova installazione in questo database vuoto. Il file d'identità della cartella viene messo da parte, non cancellato.</p>
<form method="post" action="/azioni/servizio/da-capo" class="form">
<AntiforgeryToken />
<AdminPassword Docker="docker" />
<button class="btn btn-danger" type="submit" data-confirm="Cominciare da capo con un database vuoto? Lo storico precedente resta nei salvataggi.">Comincia da capo</button>
</form>
</section>
}
else
{
<section class="service-section">
<h2>Usa comunque questo database</h2>
<p class="hint">Diventa il database di questa installazione con una nuova impronta. Ogni altra copia non verrà più accettata. Il bot riparte protetto.</p>
<form method="post" action="/azioni/servizio/usa-questo" class="form">
<AntiforgeryToken />
<AdminPassword Docker="docker" />
<button class="btn btn-danger" type="submit" data-confirm="Usare questo database da ora in poi? Le altre copie non saranno più accettate.">Usa questo database</button>
</form>
</section>
}
}
@code {
[Parameter, EditorRequired]
public HostStatus Status { get; set; } = null!;
[Parameter]
public bool Local { get; set; }
}
@@ -0,0 +1,118 @@
@inherits LoadedLayout
@inject ShellData Shell
@inject NavigationManager Navigation
@* The shell of SPEC 13.4: menu on the left (collapsible, remembered), top bar with state and commands, on phones a
bottom bar with five entries. Rendered on the server; app.js keeps state and freshness live over the WebSocket. *@
<div class="shell" data-shell>
<nav class="sidebar" aria-label="Menu principale">
<div class="brand">
<a class="brand-link" href="/">
<img class="logo logo-light" src="/brand/anubis.svg" alt="" width="28" height="28" />
<img class="logo logo-dark" src="/brand/anubis-dark.svg" alt="" width="28" height="28" />
<span class="brand-name">Anubis</span>
</a>
<button type="button" class="icon-button collapse" data-collapse aria-label="Comprimi il menu" aria-expanded="true">
<Icon Name="collapse" Class="when-open" /><Icon Name="expand" Class="when-closed" />
</button>
</div>
@foreach (var group in Menu.Groups)
{
<ul class="nav-group">
@foreach (var item in group)
{
<li>
<a class="nav-item @(IsActive(item.Path) ? "active" : null)" href="@item.Path" aria-current="@(IsActive(item.Path) ? "page" : null)" title="@item.Label">
<Icon Name="@item.Icon" /><span class="nav-label">@item.Label</span>
</a>
</li>
}
</ul>
}
</nav>
<div class="main">
<header class="topbar">
<div class="topbar-title">
<a class="phone-brand" href="/">
<img class="logo logo-light" src="/brand/anubis.svg" alt="" width="24" height="24" />
<img class="logo logo-dark" src="/brand/anubis-dark.svg" alt="" width="24" height="24" />
<span>Anubis</span>
</a>
<span class="phone-bot" data-live="bot" data-state="@_shell.Bot"><span class="dot"></span><span data-live="bot-short">@_shell.BotShort</span></span>
<h1>@Menu.Title(_path)</h1>
<p class="status-line">
<span data-live="now">@_shell.Now</span>. <span data-live="age" data-age="@_shell.AgeSeconds">Dati aggiornati @Format.Ago(TimeSpan.FromSeconds(_shell.AgeSeconds))</span>.
</p>
</div>
<div class="topbar-actions">
<span class="pill pill-bot" data-live="bot" data-state="@_shell.Bot"><span class="dot"></span><span data-live="bot-label">@_shell.BotLabel</span></span>
<span class="pill pill-mode"><Icon Name="flask" Size="16" />Simulazione: nessun soldo reale</span>
<form class="currency" method="post" action="/azioni/impostazioni/appearance.currency">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="@_back" />
<label class="sr-only" for="valuta">Valuta di visualizzazione</label>
<select id="valuta" name="valore" data-autosubmit>
<option value="EUR" selected="@(_shell.Currency == "EUR")">EUR</option>
<option value="USD" selected="@(_shell.Currency == "USD")">USD</option>
</select>
<Icon Name="chevron" Size="16" Class="select-chevron" />
<noscript><button class="btn btn-small" type="submit">Cambia</button></noscript>
</form>
@if (_shell.Bot == "paused")
{
<form method="post" action="/azioni/bot/riprendi"><AntiforgeryToken /><input type="hidden" name="ritorno" value="@_back" /><button class="btn" type="submit"><Icon Name="play" Size="18" />Riprendi</button></form>
}
else if (_shell.Bot == "active")
{
<form method="post" action="/azioni/bot/pausa"><AntiforgeryToken /><input type="hidden" name="ritorno" value="@_back" /><button class="btn" type="submit"><Icon Name="pause" Size="18" />Metti in pausa</button></form>
}
<form class="stop-form" method="post" action="/azioni/bot/ferma"><AntiforgeryToken /><input type="hidden" name="ritorno" value="@_back" /><button class="btn btn-danger" type="submit" data-confirm="Ferma tutto: il bot non apre né gestisce nuove operazioni finché non lo riattivi dalla pagina Rischio. Confermi?" disabled="@(_shell.Bot == "stopped")"><Icon Name="stop" Size="18" />Ferma tutto</button></form>
</div>
</header>
<div class="mode-band"><Icon Name="flask" Size="16" />Simulazione: nessun soldo reale</div>
<div class="stale-notice" data-stale hidden role="status"><Icon Name="alert" Size="16" /><span data-stale-text>Collegamento interrotto.</span></div>
<main class="page" id="contenuto">
@Body
<footer class="page-footer">
@if (Shell.IsDemo)
{
<p>Modalità dimostrativa. Numeri, titoli e notizie sono dati di esempio.</p>
}
else
{
<p>Anubis @AnubisInfo.Version</p>
}
</footer>
</main>
</div>
<nav class="bottombar" aria-label="Menu del telefono">
@foreach (var item in Menu.Phone)
{
<a class="bottom-item @(IsActive(item.Path) ? "active" : null)" href="@item.Path" aria-current="@(IsActive(item.Path) ? "page" : null)">
<Icon Name="@item.Icon" Size="22" /><span>@item.Label</span>
</a>
}
</nav>
</div>
@code {
private ShellSnapshot _shell = null!;
private string _path = "/";
private string _back = "/";
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
protected override async Task LoadAsync()
{
_shell = await Shell.SnapshotAsync(HttpContext?.RequestAborted ?? CancellationToken.None);
var uri = new Uri(Navigation.Uri);
_path = uri.AbsolutePath;
_back = uri.PathAndQuery;
}
private bool IsActive(string path) => path == "/" ? _path == "/" : _path.StartsWith(path, StringComparison.Ordinal);
}
@@ -0,0 +1,15 @@
@inherits LayoutComponentBase
@inject ShellData Shell
@* Pages outside the shell: sign-in, first run, first access, error page. *@
<div class="service">
<div class="service-box">
<div class="service-brand">
<img class="logo logo-light" src="/brand/anubis.svg" alt="" width="36" height="36" />
<img class="logo logo-dark" src="/brand/anubis-dark.svg" alt="" width="36" height="36" />
<span>Anubis</span>
</div>
@Body
<p class="service-foot">Anubis @AnubisInfo.Version@(Shell.IsDemo ? " · modalità dimostrativa" : "")</p>
</div>
</div>
+49
View File
@@ -0,0 +1,49 @@
using Microsoft.AspNetCore.Components;
namespace Anubis.Server.Components;
/// <summary>
/// A component that reads its data before drawing anything. With static rendering, a plain <c>OnInitializedAsync</c>
/// that really waits (PostgreSQL does; SQLite answers at once) lets Blazor draw the component once with its fields
/// still empty. Here the data are loaded first, then the component renders once.
/// </summary>
public abstract class LoadedComponent : ComponentBase
{
private bool _loaded;
public override async Task SetParametersAsync(ParameterView parameters)
{
parameters.SetParameterProperties(this);
if (!_loaded)
{
_loaded = true;
await LoadAsync().ConfigureAwait(true);
}
await base.SetParametersAsync(ParameterView.Empty).ConfigureAwait(true);
}
/// <summary>Reads what the component shows. Parameters, cascading values and query values are already set.</summary>
protected abstract Task LoadAsync();
}
/// <summary>The same for the layout.</summary>
public abstract class LoadedLayout : LayoutComponentBase
{
private bool _loaded;
public override async Task SetParametersAsync(ParameterView parameters)
{
parameters.SetParameterProperties(this);
if (!_loaded)
{
_loaded = true;
await LoadAsync().ConfigureAwait(true);
}
await base.SetParametersAsync(ParameterView.Empty).ConfigureAwait(true);
}
/// <inheritdoc cref="LoadedComponent.LoadAsync"/>
protected abstract Task LoadAsync();
}
+39
View File
@@ -0,0 +1,39 @@
namespace Anubis.Server.Components;
internal sealed record MenuItem(string Path, string Label, string Icon, string Title);
/// <summary>The screens of SPEC 13.6 in the order of the mockups.</summary>
internal static class Menu
{
public static readonly MenuItem Overview = new("/", "Panoramica", "grid", "Panoramica");
public static readonly MenuItem Accounts = new("/conti", "Conti e posizioni", "card", "Conti e posizioni");
public static readonly MenuItem Trades = new("/operazioni", "Operazioni", "arrows", "Operazioni");
public static readonly MenuItem Strategies = new("/strategie", "Strategie", "layers", "Strategie");
public static readonly MenuItem News = new("/notizie", "Notizie e mercato", "news", "Notizie e mercato");
public static readonly MenuItem Learning = new("/apprendimento", "Apprendimento", "network", "Apprendimento");
public static readonly MenuItem Risk = new("/rischio", "Rischio", "shield", "Rischio");
public static readonly MenuItem Journal = new("/diario", "Diario e sistema", "list", "Diario e sistema");
public static readonly MenuItem Lab = new("/laboratorio", "Laboratorio", "flask", "Laboratorio");
public static readonly MenuItem Settings = new("/impostazioni", "Impostazioni", "sliders", "Impostazioni");
public static readonly MenuItem More = new("/altro", "Altro", "dots", "Altro");
public static readonly IReadOnlyList<IReadOnlyList<MenuItem>> Groups =
[
[Overview, Accounts, Trades],
[Strategies, News, Learning],
[Risk, Journal, Lab, Settings],
];
/// <summary>The bottom bar of the phone (SPEC 13.4).</summary>
public static readonly IReadOnlyList<MenuItem> Phone =
[
Overview,
Accounts with { Label = "Conti" },
Journal with { Label = "Diario" },
Risk,
More,
];
public static string Title(string path) =>
Groups.SelectMany(g => g).Append(More).FirstOrDefault(i => i.Path == "/" ? path == "/" : path.StartsWith(i.Path, StringComparison.Ordinal))?.Title ?? "Anubis";
}
@@ -0,0 +1,46 @@
@page "/accesso"
@layout ServiceLayout
@attribute [AllowAnonymous]
<PageTitle>Accesso · Anubis</PageTitle>
<h1>Accedi</h1>
@if (Message is { } message)
{
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
}
<form method="post" action="/azioni/accesso" class="form">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="@(Ritorno is { } r && Forms.IsLocalPath(r) ? r : "/")" />
<label for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="current-password" required autofocus />
@if (Fattore == "1")
{
<label for="codice">Codice dell'app di autenticazione</label>
<input id="codice" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
<p class="hint">Sei cifre, cambiano ogni 30 secondi. Scrivi di nuovo anche la password.</p>
}
<button class="btn btn-primary" type="submit">Accedi</button>
</form>
@code {
[SupplyParameterFromQuery(Name = "errore")]
public string? Errore { get; set; }
[SupplyParameterFromQuery(Name = "minuti")]
public string? Minuti { get; set; }
[SupplyParameterFromQuery(Name = "fattore")]
public string? Fattore { get; set; }
[SupplyParameterFromQuery(Name = "ritorno")]
public string? Ritorno { get; set; }
private string? Message => Errore switch
{
"password" => "Password sbagliata. Riprova: dopo 5 tentativi sbagliati l'accesso si blocca per 15 minuti.",
"codice" => "Il codice non è giusto o è scaduto. Usa quello che l'app mostra adesso.",
"attesa" => $"Troppi tentativi sbagliati. Riprova tra {Minuti ?? "15"} minuti.",
_ => null,
};
}
@@ -0,0 +1,44 @@
@inherits LoadedComponent
@page "/altro"
@inject ShellData Shell
<PageTitle>Altro · Anubis</PageTitle>
@* On the phone: the screens that do not fit the bottom bar, the pause and the currency (SPEC 13.4). *@
<section class="panel">
<ul class="more-list">
@foreach (var item in Menu.Groups.SelectMany(g => g).Where(i => !Menu.Phone.Any(p => p.Path == i.Path)))
{
<li><a href="@item.Path"><Icon Name="@item.Icon" />@item.Label</a></li>
}
</ul>
</section>
<section class="panel">
<h2>Comandi</h2>
<div class="form-inline">
@if (_shell.Bot == "active")
{
<form method="post" action="/azioni/bot/pausa"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/altro" /><button class="btn" type="submit"><Icon Name="pause" Size="18" />Metti in pausa</button></form>
}
else if (_shell.Bot == "paused")
{
<form method="post" action="/azioni/bot/riprendi"><AntiforgeryToken /><input type="hidden" name="ritorno" value="/altro" /><button class="btn" type="submit"><Icon Name="play" Size="18" />Riprendi</button></form>
}
<form method="post" action="/azioni/impostazioni/appearance.currency">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/altro" />
<input type="hidden" name="valore" value="@(_shell.Currency == "EUR" ? "USD" : "EUR")" />
<button class="btn" type="submit">Mostra in @(_shell.Currency == "EUR" ? "dollari" : "euro")</button>
</form>
@if (!Shell.IsDemo)
{
<form method="post" action="/azioni/esci"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="logout" Size="18" />Esci</button></form>
}
</div>
</section>
@code {
private ShellSnapshot _shell = null!;
protected override async Task LoadAsync() => _shell = await Shell.SnapshotAsync(CancellationToken.None);
}
@@ -0,0 +1,5 @@
@page "/apprendimento"
<PageTitle>Apprendimento · Anubis</PageTitle>
<Pending Title="Il modello non è ancora in osservazione.">Comincia a imparare quando ci sono abbastanza segnali: qui vedrai quanti ne mancano e quanto è preciso su casi mai visti.</Pending>
@@ -0,0 +1,5 @@
@page "/conti"
<PageTitle>Conti e posizioni · Anubis</PageTitle>
<Pending Title="Nessun conto collegato.">Conti, posizioni e ordini arrivano con la contabilità: lì aggiungerai le chiavi dei conti di prova e vedrai patrimonio, liquidità e commissioni di ciascuno.</Pending>
@@ -0,0 +1,90 @@
@inherits LoadedComponent
@page "/diario"
@inject AnubisHost Host
@inject ShellData Shell
<PageTitle>Diario e sistema · Anubis</PageTitle>
<div class="columns">
<section class="panel">
<h2>Diario</h2>
@if (_entries.Count == 0)
{
<p class="note">Ancora nessuna voce.</p>
}
else
{
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col">Quando</th><th scope="col">Tipo</th><th scope="col">Voce</th></tr></thead>
<tbody>
@foreach (var e in _entries)
{
<tr><td class="nowrap">@Format.ShortDate(e.At, Shell.Now, Shell.Zone)</td><td>@e.Kind</td><td>@e.Text</td></tr>
}
</tbody>
</table>
</div>
}
</section>
<section class="panel">
<h2>Sistema</h2>
<dl class="facts">
<dt>Versione</dt><dd>@AnubisInfo.Version</dd>
<dt>Piattaforma</dt><dd>@(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop")</dd>
<dt>Database</dt><dd>@(Host.Config.Db?.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite") · risponde</dd>
<dt>In funzione da</dt><dd>@Format.Ago(Shell.Now - _since).Replace(" fa", "", StringComparison.Ordinal)</dd>
</dl>
<h3 class="list-title">Lavori in programma</h3>
<ul class="moves">
@foreach (var job in _upcoming)
{
<li><span class="move-time">@Format.ShortDate(job.DueUtc, Shell.Now, Shell.Zone)</span><span>@job.Description</span></li>
}
</ul>
@if (_jobs.Count > 0)
{
<h3 class="list-title">Ultimi lavori</h3>
<ul class="moves moves-past">
@foreach (var job in _jobs)
{
<li><span class="move-time">@(job.Finished is { } f ? Format.ShortDate(f, Shell.Now, Shell.Zone) : "—")</span><span>@job.Description: @Outcome(job.Outcome)</span></li>
}
</ul>
}
</section>
</div>
@code {
private List<(DateTimeOffset At, string Kind, string Text)> _entries = [];
private List<(string Description, DateTimeOffset? Finished, string? Outcome)> _jobs = [];
private IReadOnlyList<UpcomingRun> _upcoming = [];
private DateTimeOffset _since;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
protected override async Task LoadAsync()
{
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
var services = Host.Services!;
(_entries, _jobs) = await services.Db.ReadAsync(async s =>
{
var entries = await s.QueryAsync("SELECT occurred_at, kind, message FROM journal ORDER BY occurred_at DESC LIMIT 200",
r => (r.Moment("occurred_at"), r.Text("kind"), r.Text("message")));
var jobs = await s.QueryAsync("SELECT description, last_finished_at, last_outcome FROM jobs ORDER BY last_finished_at DESC",
r => (r.Text("description"), r.MomentOrNull("last_finished_at"), r.TextOrNull("last_outcome")));
return (entries, jobs);
}, ct);
_upcoming = services.Scheduler.Upcoming(10);
_since = Host.Status.Since;
}
private static string Outcome(string? outcome) => outcome switch
{
"succeeded" => "fatto",
"failed" => "non riuscito",
"skipped" => "saltato, orario superato",
_ => "in attesa",
};
}
@@ -0,0 +1,230 @@
@inherits LoadedComponent
@page "/impostazioni"
@inject AnubisHost Host
@inject ShellData Shell
@inject SecondFactorDrafts Drafts
<PageTitle>Impostazioni · Anubis</PageTitle>
@* First part of SPEC 13.5: appearance, security, system. The other sections arrive with their phases. *@
@if (Ok is { } ok)
{
<p class="notice notice-gain" role="status"><Icon Name="check" Size="16" />@(ok switch
{
"password" => "Password cambiata. Le altre sessioni sono state chiuse.",
"due-fattori" => "Secondo fattore attivato.",
"due-fattori-tolti" => "Secondo fattore disattivato.",
"salvataggio" => "Salvataggio fatto.",
_ => "Fatto.",
})</p>
}
@if (ErrorText is { } error)
{
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@error</p>
}
<nav class="tabs" aria-label="Sezioni delle impostazioni">
<a href="#aspetto">Aspetto</a><a href="#sicurezza">Sicurezza</a><a href="#sistema">Sistema</a><a href="#modifiche">Modifiche</a>
</nav>
<section class="panel" id="aspetto">
<h2>Aspetto</h2>
@foreach (var setting in _appearance)
{
var definition = SettingsStore.Definition(setting.Key);
<form method="post" action="/azioni/impostazioni/@setting.Key" class="form-inline">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/impostazioni#aspetto" />
<label for="@setting.Key">@definition.Label</label>
<select id="@setting.Key" name="valore" disabled="@setting.ReadOnly" data-autosubmit>
@foreach (var value in definition.Allowed!)
{
<option value="@value" selected="@(value == setting.Value)">@Label(value)</option>
}
</select>
@if (setting.ReadOnly)
{
<span class="hint">Fissato da @setting.Source: si cambia lì.</span>
}
else
{
<button class="btn btn-small" type="submit">Salva</button>
}
</form>
}
<p class="hint">Gli importi in dollari usano il cambio del giorno, che arriva con i dati di mercato. Fino ad allora restano in euro.</p>
</section>
<section class="panel" id="sicurezza">
<h2>Sicurezza</h2>
@if (Shell.IsDemo)
{
<p class="hint">Nella modalità dimostrativa password e secondo fattore non si cambiano.</p>
}
else
{
<h3>Password</h3>
<form method="post" action="/azioni/password" class="form">
<AntiforgeryToken />
<label for="attuale">Password attuale</label>
<input id="attuale" name="attuale" type="password" autocomplete="current-password" required />
<label for="nuova">Nuova password</label>
<input id="nuova" name="nuova" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
<label for="conferma">Scrivila di nuovo</label>
<input id="conferma" name="conferma" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
<button class="btn" type="submit">Cambia password</button>
</form>
<h3>Secondo fattore</h3>
@if (_hasSecondFactor)
{
<p>Attivo: all'accesso chiedo anche il codice dell'app. Servirà anche per attivare i soldi veri.</p>
<form method="post" action="/azioni/due-fattori/disattiva" class="form">
<AntiforgeryToken />
<label for="password-2fa">Per disattivarlo: password</label>
<input id="password-2fa" name="password" type="password" autocomplete="current-password" required />
<label for="codice-2fa">Codice dell'app</label>
<input id="codice-2fa" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
<button class="btn" type="submit">Disattiva il secondo fattore</button>
</form>
}
else
{
<p>Facoltativo: un codice di sei cifre da un'app di autenticazione (per esempio quella del tuo gestore di password), oltre alla password.</p>
<ol class="steps">
<li>Nell'app scegli "aggiungi con chiave" e scrivi questa chiave: <code class="secret">@_draft</code></li>
<li>Oppure, se l'app accetta un indirizzo, usa: <code class="secret">@_draftUri</code></li>
<li>Scrivi qui il codice che l'app mostra.</li>
</ol>
<form method="post" action="/azioni/due-fattori/attiva" class="form">
<AntiforgeryToken />
<label for="codice">Codice</label>
<input id="codice" name="codice" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" required />
<button class="btn" type="submit">Attiva il secondo fattore</button>
</form>
}
<form method="post" action="/azioni/esci" class="form-inline"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="logout" Size="18" />Esci</button></form>
}
</section>
<section class="panel" id="sistema">
<h2>Sistema</h2>
<dl class="facts">
<dt>Piattaforma</dt><dd>@(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop (Windows)")</dd>
<dt>Database</dt><dd>@Host.Config.Db?.Describe()</dd>
<dt>Cartella dei dati</dt><dd>@Host.Config.Data.Root</dd>
<dt>Chiave dei segreti</dt><dd>@Host.Config.SecretKey.Description</dd>
<dt>Fuso orario</dt><dd>@Host.Config.TimeZone.Id</dd>
<dt>Versione</dt><dd>@AnubisInfo.Version</dd>
</dl>
<p class="hint">
@if (Host.Config.Platform == PlatformKind.Docker)
{
@:Motore e connessione del database si cambiano solo nella configurazione del container.
}
else
{
@:Motore e connessione del database stanno in config.toml, nella cartella dei dati. Lo spostamento su un altro database arriva con l'applicazione desktop.
}
</p>
<h3>Salvataggi</h3>
<p class="hint">Ogni notte alle 03:30 e prima di ogni aggiornamento dello schema. Tengo gli ultimi @Backups.Keep.</p>
<form method="post" action="/azioni/salvataggio" class="form-inline"><AntiforgeryToken /><button class="btn" type="submit"><Icon Name="database" Size="18" />Salva adesso</button></form>
@if (_backups.Count > 0)
{
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col">Quando</th><th scope="col">Perché</th><th scope="col">Cartella</th></tr></thead>
<tbody>
@foreach (var b in _backups)
{
<tr><td class="nowrap">@Format.ShortDate(b.TakenAt, Shell.Now, Shell.Zone)</td><td>@b.Reason</td><td><code>@b.Name</code></td></tr>
}
</tbody>
</table>
</div>
}
</section>
<section class="panel" id="modifiche">
<h2>Registro delle modifiche</h2>
@if (_history.Count == 0)
{
<p class="note">Nessuna modifica finora.</p>
}
else
{
<div class="table-wrap">
<table class="table">
<thead><tr><th scope="col">Quando</th><th scope="col">Voce</th><th scope="col">Prima</th><th scope="col">Dopo</th><th scope="col">Chi</th></tr></thead>
<tbody>
@foreach (var h in _history)
{
<tr><td class="nowrap">@Format.ShortDate(h.At, Shell.Now, Shell.Zone)</td><td>@h.Key</td><td>@Label(h.OldValue)</td><td>@Label(h.NewValue)</td><td>@h.ChangedBy</td></tr>
}
</tbody>
</table>
</div>
}
</section>
@code {
private readonly List<SettingValue> _appearance = [];
private List<SettingChange> _history = [];
private IReadOnlyList<BackupInfo> _backups = [];
private bool _hasSecondFactor;
private string? _draft;
private string? _draftUri;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
[SupplyParameterFromQuery(Name = "ok")]
public string? Ok { get; set; }
[SupplyParameterFromQuery(Name = "errore")]
public string? Errore { get; set; }
protected override async Task LoadAsync()
{
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
var services = Host.Services!;
_appearance.Add(await services.Settings.GetAsync(SettingsStore.Theme.Key, ct));
_appearance.Add(await services.Settings.GetAsync(SettingsStore.Currency.Key, ct));
_history = await services.Settings.HistoryAsync(null, 50, ct);
_backups = services.Backups.List();
var user = HttpContext!.User;
_hasSecondFactor = CurrentUser.HasSecondFactor(user);
if (!_hasSecondFactor && !Shell.IsDemo)
{
var secret = Drafts.For(CurrentUser.Session(user));
_draft = Base32.Encode(secret);
_draftUri = Totp.Uri("Anubis", AccessStore.AdminName, secret);
}
}
private string? ErrorText => Errore switch
{
"codice" => "Il codice non è giusto. Controlla l'ora del telefono e riprova con il codice che vedi adesso.",
"segreto" => "La chiave è scaduta: ricarica la pagina e aggiungi di nuovo Anubis nell'app.",
"salvataggio" => "Il salvataggio non è riuscito. Controlla lo spazio libero nella cartella dei dati.",
"impostazione" => "Questa impostazione non si può cambiare così.",
"bot" => "Comando non ammesso nello stato attuale del bot.",
_ => PasswordMessages.For(Errore),
};
private static string Label(string? value) => value switch
{
null => "—",
"auto" => "Come il sistema",
"light" => "Chiaro",
"dark" => "Scuro",
"EUR" => "Euro (EUR)",
"USD" => "Dollaro (USD)",
"active" => "Attivo",
"paused" => "In pausa",
"stopped" => "Fermo",
_ => value.Trim('"'),
};
}
@@ -0,0 +1,5 @@
@page "/laboratorio"
<PageTitle>Laboratorio · Anubis</PageTitle>
<Pending Title="Nessun test eseguito.">Il laboratorio dei test sul passato arriva con il motore dei backtest.</Pending>
@@ -0,0 +1,5 @@
@page "/notizie"
<PageTitle>Notizie e mercato · Anubis</PageTitle>
<Pending Title="Nessuna notizia letta finora.">La lettura delle notizie, l'umore del mercato e il calendario degli eventi arrivano in una fase successiva.</Pending>
@@ -0,0 +1,5 @@
@page "/operazioni"
<PageTitle>Operazioni · Anubis</PageTitle>
<Pending Title="Ancora nessuna operazione chiusa.">Quando il bot comincerà a lavorare, qui troverai ogni operazione con il suo risultato e il perché di ogni ingresso e uscita.</Pending>
@@ -0,0 +1,134 @@
@inherits LoadedComponent
@page "/"
@inject AnubisHost Host
@inject ShellData Shell
<PageTitle>Panoramica · Anubis</PageTitle>
@{
var o = _overview;
var c = _currency;
}
<section class="panel head-block" aria-label="Il punto della situazione">
<div class="half half-past">
<div class="half-head">
<h2><Icon Name="half" Size="18" />Finora</h2>
@if (o.HasData)
{
<nav class="segmented" aria-label="Periodo">
@foreach (var (key, label) in Overview.Periods)
{
<a href="@(key == "avvio" ? "/" : "/?periodo=" + key)" class="@(key == _period ? "on" : null)" aria-current="@(key == _period ? "true" : null)">@label</a>
}
</nav>
}
</div>
@if (!o.HasData)
{
<div class="empty">
<p class="empty-title">Ancora nessun risultato da mostrare.</p>
<p>Il patrimonio comincia a essere registrato quando colleghi un conto. Da quel giorno qui vedrai quanto stai guadagnando o perdendo, al netto dei costi, e il confronto con chi non usa il bot.</p>
</div>
}
else
{
var gain = o.Result.Amount >= 0;
<p class="lead">@(gain ? "Sei in profitto di" : "Sei in perdita di")</p>
<div class="big-result">
<span class="big-number">@Shell.Money(o.Result.Amount, c, withSign: true)</span>
<span class="badge @(gain ? "badge-gain" : "badge-loss")"><Arrow Up="gain" />@Format.Percent(o.Result.Percent, 2, withSign: true)</span>
</div>
<p class="note">Dal @Format.LongDate(o.From), partendo da @Shell.Money(o.FromEquity, c). Commissioni già tolte.</p>
<div class="cells">
@foreach (var (cell, i) in o.Cells.Select((x, i) => (x, i)))
{
var up = cell.Amount >= 0;
var label = cell.Label.StartsWith("Ultimi ", StringComparison.Ordinal) ? cell.Label["Ultimi ".Length..] : cell.Label;
<div class="cell @(i >= 3 ? "cell-extra" : null)">
<span class="cell-label">@if (label != cell.Label) {<span class="long">Ultimi </span>}@label</span>
<span class="cell-value">@Shell.Money(cell.Amount, c, withSign: true)</span>
<span class="cell-change @(up ? "gain" : "loss")"><Arrow Up="up" />@Format.Percent(cell.Percent, 2, withSign: true)</span>
</div>
}
</div>
<EquityChart Points="o.Series" Currency="c" />
}
</div>
<div class="half half-next">
<div class="half-head">
<h2><Icon Name="next" Size="18" />Adesso e dopo</h2>
@if (_runningDays is { } days)
{
<span class="note">Attivo da @days giorni senza interruzioni</span>
}
</div>
<p class="statement">@Statement(o)</p>
<h3 class="list-title">Prossime mosse</h3>
@if (o.Next.Count == 0)
{
<p class="note">Niente in programma.</p>
}
else
{
<ul class="moves">
@foreach (var move in o.Next)
{
<li><span class="move-time">@move.Time</span><span>@move.Text</span></li>
}
</ul>
}
<h3 class="list-title">Ultime azioni</h3>
@if (o.Last.Count == 0)
{
<p class="note">Ancora nessuna voce nel diario.</p>
}
else
{
<ul class="moves moves-past">
@foreach (var action in o.Last)
{
<li><span class="move-time">@action.When</span><span>@action.Text</span></li>
}
</ul>
<a class="more" href="/diario">Tutto il diario</a>
}
</div>
</section>
@code {
private Overview _overview = null!;
private string _currency = "EUR";
private string _period = "avvio";
private int? _runningDays;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
[SupplyParameterFromQuery(Name = "periodo")]
public string? Periodo { get; set; }
protected override async Task LoadAsync()
{
var ct = HttpContext?.RequestAborted ?? CancellationToken.None;
_period = Periodo is "30" or "7" or "oggi" ? Periodo : "avvio";
var services = Host.Services!;
_currency = Shell.Effective((await services.Settings.GetAsync(SettingsStore.Currency.Key, ct)).Value);
_overview = await Overview.LoadAsync(services, _period, Shell.Now, Shell.Zone, ct);
using var aggregates = Shell.Aggregates();
_runningDays = aggregates?.RootElement.GetProperty("giorno").GetInt32();
}
private static string Statement(Overview o)
{
var orders = o.OpenOrders == 0 ? "Nessun ordine in corso." : o.OpenOrders == 1 ? "Un ordine in corso." : $"{o.OpenOrders} ordini in corso.";
if (o.Positions == 0)
{
return "Nessuna posizione aperta. " + orders;
}
var stops = o.PositionsWithoutStop == 0
? (o.Positions == 1 ? "con il suo stop" : "ognuna con il suo stop")
: $"{o.PositionsWithoutStop} senza stop";
return o.Positions == 1 ? $"Sorveglio una posizione, {stops}. {orders}" : $"Sorveglio {o.Positions} posizioni, {stops}. {orders}";
}
}
@@ -0,0 +1,43 @@
@page "/primo-accesso"
@layout ServiceLayout
@inject AnubisHost Host
<PageTitle>Primo accesso · Anubis</PageTitle>
<h1>Benvenuto in Anubis</h1>
<p>Prima di cominciare, due cose.</p>
<section class="service-section">
<h2><Icon Name="database" Size="18" />Database</h2>
<p>Scelto nella configurazione del container: qui si vede soltanto. Per cambiarlo si modifica il container (manuale, capitolo Installazione).</p>
<dl class="facts">
<dt>Motore</dt><dd>@(Host.Config.Db?.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite")</dd>
<dt>Dove</dt><dd>@Host.Config.Db?.Describe()</dd>
</dl>
</section>
<section class="service-section">
<h2><Icon Name="lock" Size="18" />Scegli la tua password</h2>
<p>La password iniziale del container vale solo per questo primo accesso. Scegline una nuova, di almeno @Passwords.MinimumLength caratteri.</p>
@if (Message is { } message)
{
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
}
<form method="post" action="/azioni/primo-accesso" class="form">
<AntiforgeryToken />
<label for="attuale">Password iniziale</label>
<input id="attuale" name="attuale" type="password" autocomplete="current-password" required />
<label for="nuova">Nuova password</label>
<input id="nuova" name="nuova" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
<label for="conferma">Scrivila di nuovo</label>
<input id="conferma" name="conferma" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
<button class="btn btn-primary" type="submit">Salva e continua</button>
</form>
</section>
@code {
[SupplyParameterFromQuery(Name = "errore")]
public string? Errore { get; set; }
private string? Message => PasswordMessages.For(Errore);
}
@@ -0,0 +1,79 @@
@page "/primo-avvio"
@layout ServiceLayout
@attribute [AllowAnonymous]
@inject AnubisHost Host
<PageTitle>Primo avvio · Anubis</PageTitle>
<h1>Primo avvio</h1>
@if (!_local)
{
<p class="notice notice-attention" role="alert"><Icon Name="lock" Size="16" />La prima configurazione si fa solo dal computer su cui gira Anubis.</p>
}
else
{
<p>Due passi: dove tenere i dati e la password per entrare. Conti, capitale e Telegram si aggiungono dopo, dalle Impostazioni.</p>
@if (Message is { } message)
{
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@message</p>
}
<form method="post" action="/azioni/primo-avvio" class="form" data-wizard>
<AntiforgeryToken />
@if (!Host.Config.IsComplete)
{
<fieldset class="service-section">
<legend><span class="step">1</span>Database</legend>
<label class="choice">
<input type="radio" name="motore" value="sqlite" checked data-engine />
<span><strong>SQLite</strong> (consigliato): un file nella cartella dei dati, niente da installare.</span>
</label>
<label class="choice">
<input type="radio" name="motore" value="postgres" data-engine />
<span><strong>PostgreSQL</strong>: un server che hai già, con un database dedicato e vuoto.</span>
</label>
<div class="postgres-fields" data-postgres>
<label for="host">Indirizzo del server</label>
<input id="host" name="host" autocomplete="off" placeholder="192.168.1.10" />
<div class="row">
<div><label for="porta">Porta</label><input id="porta" name="porta" inputmode="numeric" value="5432" /></div>
<div><label for="nome">Nome del database</label><input id="nome" name="nome" value="anubis" /></div>
</div>
<div class="row">
<div><label for="utente">Utente</label><input id="utente" name="utente" value="anubis" autocomplete="off" /></div>
<div><label for="dbpassword">Password del database</label><input id="dbpassword" name="dbpassword" type="password" autocomplete="off" /></div>
</div>
<p class="hint">La password del database non va in <code>config.toml</code>: la custodisce Windows per il tuo utente.</p>
<button class="btn" type="submit" formaction="/azioni/primo-avvio/prova" data-test-connection>Prova la connessione</button>
<p class="test-result" data-test-result role="status"></p>
</div>
</fieldset>
}
<fieldset class="service-section">
<legend><span class="step">@(Host.Config.IsComplete ? "1" : "2")</span>Password</legend>
<p class="hint">Serve per entrare nell'interfaccia, anche da questo computer. Almeno @Passwords.MinimumLength caratteri.</p>
<label for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
<label for="conferma">Scrivila di nuovo</label>
<input id="conferma" name="conferma" type="password" autocomplete="new-password" minlength="@Passwords.MinimumLength" required />
</fieldset>
<p class="hint">Anubis lavora solo quando il computer è acceso. Dopo un'assenza ricostruisce cosa è successo prima di riprendere.</p>
<button class="btn btn-primary" type="submit">Crea l'installazione</button>
</form>
}
@code {
private bool _local;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
[SupplyParameterFromQuery(Name = "errore")]
public string? Errore { get; set; }
protected override void OnInitialized() => _local = HttpContext is not null && CurrentUser.IsLocal(HttpContext);
private string? Message => Errore == "database"
? "Non riesco a collegarmi al database con questi dati. Controlla indirizzo, porta, nome, utente e password, poi riprova."
: PasswordMessages.For(Errore);
}
@@ -0,0 +1,30 @@
@inherits LoadedComponent
@page "/rischio"
@inject AnubisHost Host
<PageTitle>Rischio · Anubis</PageTitle>
<section class="panel">
<h2><Icon Name="shield" Size="18" />Interruttore</h2>
@if (_bot == "stopped")
{
<p class="notice notice-attention" role="status"><Icon Name="alert" Size="16" />"Ferma tutto" è acceso: il bot non apre e non gestisce operazioni finché non lo riattivi.</p>
<form method="post" action="/azioni/bot/riattiva" class="form-inline">
<AntiforgeryToken />
<input type="hidden" name="ritorno" value="/rischio" />
<button class="btn" type="submit" data-confirm="Riattivare il bot?">Riattiva il bot</button>
</form>
}
else
{
<p>"Ferma tutto", in alto, blocca il bot. Dopo averlo usato il bot si riattiva solo da qui, mai da solo e mai da Telegram.</p>
}
</section>
<Pending Title="Limiti e scenari non sono ancora attivi.">Limiti di perdita, calo dal massimo, esposizione e scenari arrivano con le strategie e il controllo del rischio.</Pending>
@code {
private string _bot = "active";
protected override async Task LoadAsync() =>
_bot = (await Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value;
}
@@ -0,0 +1,117 @@
@page "/servizio"
@layout ServiceLayout
@attribute [AllowAnonymous]
@inject AnubisHost Host
@inject IClock Clock
@* The error page of SPEC 15.1: what is wrong, what to do, and the engine stays off. Never another database. *@
<PageTitle>@ServiceText.Title(_status.Mode) · Anubis</PageTitle>
@if (_refresh)
{
<HeadContent><meta http-equiv="refresh" content="5" /></HeadContent>
}
<h1>@ServiceText.Title(_status.Mode)</h1>
@switch (_status.Mode)
{
case HostMode.Starting:
<p>Controllo configurazione e database. Questa pagina si aggiorna da sola.</p>
break;
case HostMode.ConfigProblem:
<p>Il motore resta spento finché la configurazione non è completa. Non uso nessun altro database al posto di quello indicato.</p>
<table class="table problems">
<thead><tr><th scope="col">Voce</th><th scope="col">Cosa non va</th><th scope="col">Come rimediare</th></tr></thead>
<tbody>
@foreach (var problem in Host.Config.Problems)
{
<tr><td><code>@problem.Setting</code></td><td>@problem.What</td><td>@problem.Remedy</td></tr>
}
</tbody>
</table>
@if (Host.Config.Platform == PlatformKind.Docker)
{
<p class="hint">Le variabili si cambiano nella configurazione del container (su Unraid, nei campi del modello), poi si riavvia il container.</p>
}
else
{
<p class="hint">Il file è <code>@Host.Config.Data.ConfigFile</code>. Appena lo correggi riprovo da solo.</p>
}
break;
case HostMode.DatabaseUnavailable:
<p>Il motore è fermo e aspetta il database. Non apro un altro database al suo posto: riprovo da solo ogni pochi secondi e riparto appena risponde.</p>
<dl class="facts">
<dt>Database</dt><dd>@Host.Config.Db?.Describe()</dd>
<dt>Risposta</dt><dd>@(_status.Detail ?? "nessuna")</dd>
<dt>Tentativi</dt><dd>@_status.Attempts, dal @Format.ShortDate(_status.Since, Clock.UtcNow, Host.Config.TimeZone)</dd>
</dl>
<h2>Cosa controllare</h2>
<ul class="steps">
@if (Host.Config.Db?.Engine == DbEngine.Postgres)
{
<li>Che il server PostgreSQL sia acceso e raggiungibile da qui (indirizzo e porta).</li>
<li>Che nome del database, utente e password siano quelli giusti.</li>
<li>Che il database esista: lo crei tu una volta, Anubis non crea e non cancella database.</li>
}
else
{
<li>Che il file del database sia al suo posto e leggibile. Se l'hai spostato, rimettilo dov'era.</li>
<li>Che il disco della cartella dei dati sia collegato e abbia spazio libero.</li>
}
</ul>
break;
case HostMode.SchemaProblem:
<p>@_status.Detail</p>
<p>Per non rovinare i dati il motore resta spento. Aggiorna Anubis alla versione che ha creato questo database, oppure ripristina un salvataggio in un database vuoto.</p>
break;
case HostMode.IdentityProblem:
<IdentityChoices Status="_status" Local="_local" />
break;
case HostMode.FirstRun:
<p><a href="/primo-avvio">Apri la procedura di primo avvio</a>.</p>
break;
}
@if (Errore is { } errore)
{
<p class="notice notice-loss" role="alert"><Icon Name="alert" Size="16" />@(errore switch
{
"password" => "Password della configurazione d'avvio sbagliata, oppure scelta fatta da un altro computer.",
"importazione" => "Il ripristino non è riuscito e non ho cambiato nulla. Controlla l'archivio e riprova.",
"attesa" => "Troppi tentativi sbagliati. Riprova tra 15 minuti.",
_ => "Questa scelta non è disponibile adesso.",
})</p>
}
@code {
private HostStatus _status = null!;
private bool _refresh;
private bool _local;
[CascadingParameter]
public HttpContext? HttpContext { get; set; }
[SupplyParameterFromQuery(Name = "errore")]
public string? Errore { get; set; }
protected override void OnInitialized()
{
_status = Host.Status;
_refresh = _status.Mode is HostMode.Starting or HostMode.DatabaseUnavailable or HostMode.ConfigProblem;
if (HttpContext is not null)
{
_local = CurrentUser.IsLocal(HttpContext);
if (!HttpContext.Response.HasStarted)
{
HttpContext.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
HttpContext.Response.Headers.CacheControl = "no-store";
HttpContext.Response.Headers.RetryAfter = "5";
}
}
}
}
@@ -0,0 +1,5 @@
@page "/strategie"
<PageTitle>Strategie · Anubis</PageTitle>
<Pending Title="Le strategie non sono ancora attive.">Arrivano dopo il laboratorio: ognuna con la sua descrizione, i requisiti per passare allo stadio successivo e i risultati.</Pending>
@@ -0,0 +1,13 @@
@* A screen whose content arrives with a later phase: it says so plainly instead of showing invented numbers (SPEC 13.1). *@
<section class="panel empty">
<p class="empty-title">@Title</p>
<p>@ChildContent</p>
</section>
@code {
[Parameter, EditorRequired]
public string Title { get; set; } = "";
[Parameter]
public RenderFragment? ChildContent { get; set; }
}
@@ -0,0 +1,5 @@
<Router AppAssembly="typeof(App).Assembly">
<Found Context="routeData">
<RouteView RouteData="routeData" DefaultLayout="typeof(MainLayout)" />
</Found>
</Router>
@@ -0,0 +1,30 @@
namespace Anubis.Server;
/// <summary>Titles of the service page, also used in plain answers while the application is not ready.</summary>
internal static class ServiceText
{
public static string Title(HostMode mode) => mode switch
{
HostMode.Starting => "Anubis si sta avviando",
HostMode.ConfigProblem => "Manca qualcosa nella configurazione d'avvio",
HostMode.FirstRun => "Anubis va configurato",
HostMode.DatabaseUnavailable => "Il database non risponde",
HostMode.SchemaProblem => "Il database non è compatibile con questa versione",
HostMode.IdentityProblem => "Il database non è quello di questa installazione",
_ => "Anubis",
};
}
/// <summary>Messages of the password forms.</summary>
internal static class PasswordMessages
{
public static string? For(string? code) => code switch
{
"diverse" => "Le due password non coincidono. Scrivile di nuovo.",
"corta" => $"La password è troppo corta: servono almeno {Access.Passwords.MinimumLength} caratteri.",
"uguale" => "La nuova password deve essere diversa da quella iniziale.",
"attuale" => "La password attuale non è giusta.",
"demo" => "Nella modalità dimostrativa la password non si cambia.",
_ => null,
};
}
@@ -0,0 +1,14 @@
@using System.Globalization
@using Microsoft.AspNetCore.Authorization
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using Anubis
@using Anubis.Access
@using Anubis.Core
@using Anubis.Db
@using Anubis.Platform
@using Anubis.Server
@using Anubis.Server.Components
@using Anubis.Server.Components.Layout
+64
View File
@@ -0,0 +1,64 @@
using System.Collections;
using Anubis.Core;
using Anubis.Db;
using Anubis.Platform;
namespace Anubis.Server;
/// <summary>
/// Command line export and import (SPEC 5.4), the way to change engine: with the server stopped, export from the old
/// database, point the configuration to the new one, import. The import goes only into an empty database and renews
/// the installation fingerprint, so the old copy is no longer accepted (SPEC 15.1).
/// </summary>
internal static class DatabaseCommand
{
public static async Task<int> RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary<string, string?>? environment = null)
{
output ??= Console.Out;
if (args.Length < 2 || args[0] is not ("export" or "import"))
{
await output.WriteLineAsync("Uso: anubis db export <cartella> | anubis db import <cartella> [--platform docker|desktop] [--data-dir <cartella>]").ConfigureAwait(false);
return 2;
}
environment ??= Environment.GetEnvironmentVariables().Cast<DictionaryEntry>().ToDictionary(e => (string)e.Key, e => e.Value as string, StringComparer.Ordinal);
var options = ServerOptions.Parse(args[2..], environment);
var config = options.LoadConfig(environment);
if (!config.IsComplete)
{
await output.WriteLineAsync("La configurazione d'avvio non è completa:").ConfigureAwait(false);
foreach (var problem in config.Problems)
{
await output.WriteLineAsync($"- {problem.Setting}: {problem.What} {problem.Remedy}").ConfigureAwait(false);
}
return 1;
}
Redactor.Register(config.Db!.Password);
var clock = new SystemClock();
var folder = Path.GetFullPath(args[1]);
try
{
await using var db = Database.Open(config.Db!, allowCreate: args[0] == "import" && !File.Exists(config.Data.InstallationFile));
if (args[0] == "export")
{
var index = await Archive.ExportAsync(db, folder, clock).ConfigureAwait(false);
await output.WriteLineAsync($"Esportate {index.Tables.Sum(t => t.Count)} righe di {index.Tables.Count} tabelle in {folder}.").ConfigureAwait(false);
return 0;
}
config.Data.Ensure();
var imported = await Archive.ImportAsync(db, folder, clock).ConfigureAwait(false);
await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: !File.Exists(config.Data.InstallationFile)).ConfigureAwait(false);
await output.WriteLineAsync($"Importate {imported.Tables.Sum(t => t.Count)} righe di {imported.Tables.Count} tabelle: conteggi e totali coincidono. " +
"Al prossimo avvio il bot riparte protetto.").ConfigureAwait(false);
return 0;
}
catch (Exception ex) when (ex is IOException or InvalidOperationException or SchemaException or System.Text.Json.JsonException or System.Data.Common.DbException)
{
await output.WriteLineAsync("Non riuscito: " + Redactor.Redact(ex.Message)).ConfigureAwait(false);
return 1;
}
}
}
+324
View File
@@ -0,0 +1,324 @@
using System.Net.WebSockets;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Anubis.Access;
using Anubis.Core;
using Anubis.Db;
using Anubis.Platform;
using Microsoft.AspNetCore.Antiforgery;
namespace Anubis.Server;
/// <summary>Answer of <c>GET /health</c>.</summary>
internal sealed record HealthResponse(string Status, string Name, string Version, string? Mode = null, IReadOnlyDictionary<string, string>? Checks = null);
internal sealed record SettingBody(string Value);
/// <summary>
/// The REST and WebSocket skeleton (issue #12) and the form actions of the service pages. The API answers JSON with
/// Italian messages, needs a session, and every request that changes something carries the CSRF token in a header.
/// </summary>
internal static partial class Endpoints
{
public const string CsrfHeader = "X-Anubis-Csrf";
private static readonly JsonSerializerOptions _json = new(JsonSerializerDefaults.Web);
public static void Map(WebApplication app)
{
app.MapGet("/health", HealthAsync).AllowAnonymous();
app.MapGet("/brand/{file}", Brand).AllowAnonymous();
app.MapGet("/assets/{file}", Asset).AllowAnonymous();
app.MapGet("/favicon.ico", () => Brand("anubis.ico")).AllowAnonymous();
MapApi(app);
app.Map("/ws", StatusSocketAsync).RequireAuthorization();
Forms.Map(app);
}
// Healthy only when the database answers and the scheduler loop is alive (SPEC 15.2); the body says why not.
private static async Task<IResult> HealthAsync(AnubisHost host, CancellationToken cancellationToken)
{
var status = host.Status;
var checks = new Dictionary<string, string>(StringComparer.Ordinal) { ["mode"] = status.Mode.ToString() };
var healthy = status.Mode == HostMode.Ready;
if (host.Services is { } services)
{
try
{
using var timeout = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
timeout.CancelAfter(TimeSpan.FromSeconds(5));
await services.Db.PingAsync(timeout.Token).ConfigureAwait(false);
checks["database"] = "ok";
}
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
{
checks["database"] = "non risponde";
healthy = false;
}
checks["scheduler"] = host.SchedulerRunning ? "ok" : "fermo";
healthy &= host.SchedulerRunning;
}
var body = new HealthResponse(healthy ? "ok" : "unavailable", AnubisInfo.Name, AnubisInfo.Version, status.Mode.ToString(), checks);
return Results.Json(body, _json, statusCode: healthy ? StatusCodes.Status200OK : StatusCodes.Status503ServiceUnavailable);
}
// The logo comes only from docs/design/logo, embedded at build time (ADR 0005).
private static IResult Brand(string file) => Embedded("Anubis.Server.Brand." + file, file);
private static IResult Asset(string file) => Embedded("Anubis.Server.Assets." + file, file);
private static IResult Embedded(string resource, string file)
{
var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource);
if (stream is null)
{
return Results.NotFound();
}
var type = Path.GetExtension(file) switch
{
".svg" => "image/svg+xml",
".png" => "image/png",
".ico" => "image/x-icon",
".css" => "text/css; charset=utf-8",
".js" => "text/javascript; charset=utf-8",
_ => "application/octet-stream",
};
return Results.Stream(stream, type);
}
private static void MapApi(WebApplication app)
{
var api = app.MapGroup("/api").RequireAuthorization().AddEndpointFilter(CsrfFilterAsync);
api.MapGet("/antiforgery", (HttpContext context, IAntiforgery antiforgery) =>
{
var tokens = antiforgery.GetAndStoreTokens(context);
return Results.Json(new { header = CsrfHeader, token = tokens.RequestToken }, _json);
});
api.MapGet("/status", async (AnubisHost host, ShellData shell, CancellationToken ct) => Results.Json(await shell.SnapshotAsync(ct).ConfigureAwait(false), _json));
api.MapGet("/me", (HttpContext context) => Results.Json(new
{
username = context.User.Identity?.Name,
mustChangePassword = CurrentUser.MustChangePassword(context.User),
hasSecondFactor = CurrentUser.HasSecondFactor(context.User),
}, _json));
api.MapGet("/settings", async (AnubisHost host, CancellationToken ct) =>
{
var services = host.Services!;
var values = new List<SettingValue>();
foreach (var definition in SettingsStore.All)
{
values.Add(await services.Settings.GetAsync(definition.Key, ct).ConfigureAwait(false));
}
return Results.Json(values, _json);
});
api.MapPut("/settings/{key}", async (string key, SettingBody body, AnubisHost host, HttpContext context, CancellationToken ct) =>
{
if (key == SettingsStore.BotState.Key)
{
return Error(StatusCodes.Status400BadRequest, "usa_i_comandi", "Lo stato del bot si cambia con pausa, ripresa e Ferma tutto.");
}
return await SetSettingAsync(host, key, body.Value, context, ct).ConfigureAwait(false);
});
api.MapGet("/settings/history", async (AnubisHost host, CancellationToken ct) =>
Results.Json(await host.Services!.Settings.HistoryAsync(null, 100, ct).ConfigureAwait(false), _json));
// Only whether a secret is set and where it comes from: the value never leaves the server (SPEC 15.4).
api.MapGet("/secrets/{name}", async (string name, AnubisHost host, CancellationToken ct) =>
Results.Json(await host.Services!.Secrets.StatusAsync(name, ct).ConfigureAwait(false), _json));
api.MapPost("/bot/{command}", async (string command, AnubisHost host, HttpContext context, CancellationToken ct) =>
{
var (ok, message) = await BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
return ok ? Results.Json(new { state = message }, _json) : Error(StatusCodes.Status409Conflict, "comando_non_ammesso", message);
});
api.MapGet("/jobs", async (AnubisHost host, CancellationToken ct) =>
{
var services = host.Services!;
var last = await services.Db.ReadAsync(s => s.QueryAsync(
"SELECT name, description, last_due_at, last_finished_at, last_outcome, last_error FROM jobs ORDER BY name",
r => new
{
name = r.Text("name"),
description = r.Text("description"),
lastDue = r.MomentOrNull("last_due_at"),
lastFinished = r.MomentOrNull("last_finished_at"),
outcome = r.TextOrNull("last_outcome"),
error = r.TextOrNull("last_error")
}), ct).ConfigureAwait(false);
return Results.Json(new { upcoming = services.Scheduler.Upcoming(20), last }, _json);
});
}
internal static IResult Error(int status, string code, string message) => Results.Json(new ApiError(code, message), _json, statusCode: status);
private static async ValueTask<object?> CsrfFilterAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
{
var http = context.HttpContext;
if (!HttpMethods.IsGet(http.Request.Method) && !HttpMethods.IsHead(http.Request.Method))
{
var antiforgery = http.RequestServices.GetRequiredService<IAntiforgery>();
if (!await antiforgery.IsRequestValidAsync(http).ConfigureAwait(false))
{
return Error(StatusCodes.Status400BadRequest, "csrf", "Richiesta senza il gettone di sicurezza: ricarica la pagina e riprova.");
}
}
return await next(context).ConfigureAwait(false);
}
internal static async Task<IResult> SetSettingAsync(AnubisHost host, string key, string value, HttpContext context, CancellationToken ct)
{
try
{
await host.Services!.Settings.SetAsync(key, value, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return Results.NoContent();
}
catch (ReadOnlySettingException ex)
{
return Error(StatusCodes.Status409Conflict, "sola_lettura", ex.Message);
}
catch (ArgumentException ex)
{
return Error(StatusCodes.Status400BadRequest, "valore_non_valido", ex.Message);
}
}
/// <summary>
/// Pause blocks new entries and keeps stops and exits; "Ferma tutto" is the switch of SPEC 9.3 (its full effect
/// arrives with the engine). Resume works only from a pause, never after "Ferma tutto" (SPEC 14).
/// </summary>
internal static async Task<(bool Ok, string Message)> BotCommandAsync(AnubisHost host, string command, HttpContext context, CancellationToken ct)
{
var settings = host.Services!.Settings;
var current = (await settings.GetAsync(SettingsStore.BotState.Key, ct).ConfigureAwait(false)).Value;
var target = command switch
{
"pause" or "pausa" when current == "active" => "paused",
"resume" or "riprendi" when current == "paused" => "active",
"stop" or "ferma" => "stopped",
"restart" or "riattiva" when current == "stopped" => "active",
_ => null,
};
if (target is null)
{
return (false, current == "stopped"
? "Dopo \"Ferma tutto\" il bot non riprende da solo: riattivalo dalla pagina Rischio."
: "Comando non ammesso nello stato attuale del bot.");
}
await settings.SetAsync(SettingsStore.BotState.Key, target, context.User.Identity?.Name ?? "utente", ct).ConfigureAwait(false);
return (true, target);
}
// Live status (SPEC 13.4): one message on connect, one at every change and a heartbeat every few seconds, so the
// page can tell how old its data are and warn when the link drops.
private static async Task StatusSocketAsync(HttpContext context, AnubisHost host, ShellData shell, EventBus bus)
{
if (!context.WebSockets.IsWebSocketRequest)
{
context.Response.StatusCode = StatusCodes.Status400BadRequest;
return;
}
// Cross-site WebSocket hijacking: the page must come from this same server.
var origin = context.Request.Headers.Origin.ToString();
if (origin.Length > 0 && (!Uri.TryCreate(origin, UriKind.Absolute, out var originUri) ||
!string.Equals(originUri.Authority, context.Request.Host.Value, StringComparison.OrdinalIgnoreCase)))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return;
}
using var socket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false);
using var settings = bus.Subscribe<SettingChanged>(16);
using var modes = bus.Subscribe<HostChanged>(16);
var aborted = context.RequestAborted;
var receive = DrainAsync(socket, aborted);
try
{
while (socket.State == WebSocketState.Open && !aborted.IsCancellationRequested)
{
var snapshot = await shell.SnapshotAsync(aborted).ConfigureAwait(false);
var bytes = JsonSerializer.SerializeToUtf8Bytes(new { type = "status", status = snapshot }, _json);
await socket.SendAsync(bytes, WebSocketMessageType.Text, true, aborted).ConfigureAwait(false);
using var wait = CancellationTokenSource.CreateLinkedTokenSource(aborted);
wait.CancelAfter(TimeSpan.FromSeconds(5));
var changed = Task.WhenAny(Next(settings, wait.Token), Next(modes, wait.Token));
await Task.WhenAny(changed, receive, Task.Delay(Timeout.Infinite, wait.Token)).ConfigureAwait(false);
// Stop the reader that lost, or it would swallow the next event of its kind.
await wait.CancelAsync().ConfigureAwait(false);
if (receive.IsCompleted)
{
break;
}
}
}
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
{
}
// Answer the client's close, or start ours. Output only: the drain loop may still be receiving.
if (socket.State is WebSocketState.Open or WebSocketState.CloseReceived)
{
try
{
using var closing = new CancellationTokenSource(TimeSpan.FromSeconds(2));
await socket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, null, closing.Token).ConfigureAwait(false);
}
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
{
}
}
await Task.WhenAny(receive, Task.Delay(TimeSpan.FromSeconds(2), CancellationToken.None)).ConfigureAwait(false);
}
private static async Task Next<T>(EventSubscription<T> subscription, CancellationToken cancellationToken)
{
await foreach (var _ in subscription.ReadAllAsync(cancellationToken).ConfigureAwait(false))
{
return;
}
}
private static async Task DrainAsync(WebSocket socket, CancellationToken cancellationToken)
{
var buffer = new byte[1024];
try
{
while (socket.State == WebSocketState.Open)
{
var result = await socket.ReceiveAsync(buffer, cancellationToken).ConfigureAwait(false);
if (result.MessageType == WebSocketMessageType.Close)
{
return;
}
}
}
catch (Exception ex) when (ex is OperationCanceledException or WebSocketException)
{
}
}
/// <summary>Compares two secrets in constant time.</summary>
internal static bool SameSecret(string? given, string? expected) =>
given is not null && expected is not null &&
CryptographicOperations.FixedTimeEquals(SHA256.HashData(Encoding.UTF8.GetBytes(given)), SHA256.HashData(Encoding.UTF8.GetBytes(expected)));
}
+443
View File
@@ -0,0 +1,443 @@
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);
}
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");
if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key)
{
return Results.Redirect(With(back, "errore", "impostazione"));
}
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, _) = await Endpoints.BotCommandAsync(host, command, context, ct).ConfigureAwait(false);
return Results.Redirect(ok ? back : With(back, "errore", "bot"));
}
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);
exclusive.Dispose();
await host.ResetAsync().ConfigureAwait(false);
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();
}
+138
View File
@@ -0,0 +1,138 @@
using System.Collections.Concurrent;
using System.Globalization;
using System.Text;
using System.Text.Json;
using Anubis.Core;
namespace Anubis.Server;
/// <summary>
/// Structured logs (SPEC 2.2, issue #10): one JSON object per line on the console and in a daily file under
/// data/logs, every text passed through the <see cref="Redactor"/> so no secret reaches a log. The last 14 files are kept.
/// </summary>
internal sealed class JsonLogProvider : ILoggerProvider
{
public const int KeepFiles = 14;
private readonly string? _folder;
private readonly IClock _clock;
private readonly bool _console;
private readonly Lock _gate = new();
private readonly ConcurrentDictionary<string, JsonLogger> _loggers = new(StringComparer.Ordinal);
private StreamWriter? _file;
private string? _fileDay;
public JsonLogProvider(string? folder, IClock clock, bool console)
{
_folder = folder;
_clock = clock;
_console = console;
}
public ILogger CreateLogger(string categoryName) => _loggers.GetOrAdd(categoryName, name => new JsonLogger(name, this));
internal void Write(string category, LogLevel level, EventId eventId, string message, Exception? exception)
{
var now = _clock.UtcNow;
using var buffer = new MemoryStream();
using (var json = new Utf8JsonWriter(buffer))
{
json.WriteStartObject();
json.WriteString("at", now.ToString("yyyy-MM-ddTHH:mm:ss.fffZ", CultureInfo.InvariantCulture));
json.WriteString("level", level.ToString().ToLowerInvariant());
json.WriteString("category", category);
if (eventId.Id != 0)
{
json.WriteNumber("event", eventId.Id);
}
json.WriteString("message", Redactor.Redact(message));
if (exception is not null)
{
json.WriteString("error", Redactor.Redact(exception.GetType().Name + ": " + exception.Message));
json.WriteString("stack", Redactor.Redact(exception.StackTrace));
}
json.WriteEndObject();
}
var line = Encoding.UTF8.GetString(buffer.ToArray());
lock (_gate)
{
if (_console)
{
Console.Out.WriteLine(line);
}
WriteFile(now, line);
}
}
private void WriteFile(DateTimeOffset now, string line)
{
if (_folder is null)
{
return;
}
try
{
var day = now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
if (_file is null || _fileDay != day)
{
_file?.Dispose();
Directory.CreateDirectory(_folder);
_file = new StreamWriter(new FileStream(Path.Combine(_folder, "anubis-" + day + ".log"), FileMode.Append, FileAccess.Write, FileShare.ReadWrite | FileShare.Delete), new UTF8Encoding(false))
{
AutoFlush = true,
};
_fileDay = day;
Prune();
}
_file.WriteLine(line);
}
catch (IOException)
{
// A full or read-only disk must not stop the application: the console still has the line.
}
catch (UnauthorizedAccessException)
{
}
}
private void Prune()
{
foreach (var old in Directory.EnumerateFiles(_folder!, "anubis-*.log").OrderDescending(StringComparer.Ordinal).Skip(KeepFiles))
{
File.Delete(old);
}
}
public void Dispose()
{
lock (_gate)
{
_file?.Dispose();
_file = null;
}
}
private sealed class JsonLogger(string category, JsonLogProvider provider) : ILogger
{
public IDisposable? BeginScope<TState>(TState state)
where TState : notnull => null;
public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None;
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (!IsEnabled(logLevel))
{
return;
}
provider.Write(category, logLevel, eventId, formatter(state, exception), exception);
}
}
}
+85
View File
@@ -0,0 +1,85 @@
using Anubis.Core;
using Anubis.Db;
namespace Anubis.Server;
public sealed record EquityPoint(DateTimeOffset At, DateOnly Day, decimal Equity, decimal? Benchmark);
internal sealed record PeriodResult(string Label, decimal Amount, decimal Percent);
internal sealed record NextMove(string Time, string Text);
internal sealed record LastAction(string When, string Text);
/// <summary>The "Finora" and "Adesso e dopo" halves of the Panoramica (SPEC 13.2, 13.6), read from the database.</summary>
internal sealed record Overview(
IReadOnlyList<EquityPoint> Points,
IReadOnlyList<EquityPoint> Series,
PeriodResult Result,
DateOnly From,
decimal FromEquity,
IReadOnlyList<PeriodResult> Cells,
int Positions,
int PositionsWithoutStop,
int OpenOrders,
IReadOnlyList<NextMove> Next,
IReadOnlyList<LastAction> Last)
{
public static readonly IReadOnlyList<(string Key, string Label)> Periods = [("avvio", "Dall'avvio"), ("30", "30 giorni"), ("7", "7 giorni"), ("oggi", "Oggi")];
public bool HasData => Points.Count > 0;
public static async Task<Overview> LoadAsync(AppServices services, string period, DateTimeOffset now, TimeZoneInfo zone, CancellationToken cancellationToken)
{
var (points, positions, withoutStop, orders, journal) = await services.Db.ReadAsync(async s =>
{
var p = await s.QueryAsync(
"SELECT taken_at, equity, benchmark FROM equity_snapshots WHERE scope = 'total' ORDER BY taken_at",
r => (At: r.Moment("taken_at"), Equity: r.Money("equity"), Benchmark: r.MoneyOrNull("benchmark"))).ConfigureAwait(false);
var count = await s.CountAsync("SELECT COUNT(*) FROM positions").ConfigureAwait(false);
var noStop = await s.CountAsync("SELECT COUNT(*) FROM positions WHERE stop_price IS NULL").ConfigureAwait(false);
var open = await s.CountAsync("SELECT COUNT(*) FROM orders WHERE status IN ('new', 'submitted', 'accepted', 'partially_filled')").ConfigureAwait(false);
var j = await s.QueryAsync("SELECT occurred_at, message FROM journal ORDER BY occurred_at DESC LIMIT 4",
r => (At: r.Moment("occurred_at"), Text: r.Text("message"))).ConfigureAwait(false);
return (p, count, noStop, open, j);
}, cancellationToken).ConfigureAwait(false);
// One point per day: the last snapshot of each local day.
var daily = points
.Select(p => new EquityPoint(p.At, DateOnly.FromDateTime(TimeZoneInfo.ConvertTime(p.At, zone).DateTime), p.Equity, p.Benchmark))
.GroupBy(p => p.Day)
.Select(g => g.Last())
.ToList();
var next = services.Scheduler.Upcoming(5)
.Select(u => new NextMove(TimeZoneInfo.ConvertTime(u.DueUtc, zone).ToString("HH:mm", System.Globalization.CultureInfo.InvariantCulture), u.Description))
.ToList();
var last = journal.Select(j => new LastAction(Format.ShortDate(j.At, now, zone), j.Text)).ToList();
if (daily.Count == 0)
{
return new Overview([], [], new PeriodResult("", 0, 0), default, 0, [], (int)positions, (int)withoutStop, (int)orders, next, last);
}
var latest = daily[^1];
EquityPoint Since(int days) => daily.LastOrDefault(p => p.Day <= latest.Day.AddDays(-days)) ?? daily[0];
PeriodResult Between(string label, EquityPoint start) =>
new(label, latest.Equity - start.Equity, start.Equity == 0 ? 0 : (latest.Equity - start.Equity) / start.Equity * 100m);
var start = period switch
{
"30" => Since(30),
"7" => Since(7),
"oggi" => Since(1),
_ => daily[0],
};
var series = daily.Where(p => p.Day >= start.Day).ToList();
var cells = new List<PeriodResult> { Between("Oggi", Since(1)), Between("Ultimi 7 giorni", Since(7)), Between("Ultimi 30 giorni", Since(30)) };
if (daily[0].Benchmark is { } firstBenchmark && latest.Benchmark is { } lastBenchmark && firstBenchmark != 0)
{
cells.Add(new PeriodResult("Senza bot", lastBenchmark - firstBenchmark, (lastBenchmark - firstBenchmark) / firstBenchmark * 100m));
}
return new Overview(daily, series, Between("", start), start.Day, start.Equity, cells, (int)positions, (int)withoutStop, (int)orders, next, last);
}
}
+7
View File
@@ -1,4 +1,11 @@
using Anubis.Server;
// "anubis db export <folder>" and "anubis db import <folder>" (SPEC 5.4) run with the engine stopped; anything else starts the server.
if (args.Length >= 1 && args[0] == "db")
{
return await DatabaseCommand.RunAsync(args[1..]).ConfigureAwait(false);
}
var app = ServerApp.Build(args);
await app.RunAsync().ConfigureAwait(false);
return 0;
+233 -6
View File
@@ -1,18 +1,245 @@
using System.Collections;
using Anubis.Access;
using Anubis.Core;
using Anubis.Demo;
using Anubis.Platform;
using Anubis.Server.Components;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.DataProtection;
namespace Anubis.Server;
/// <summary>Builds the web application. Kept apart from Program so tests can host it.</summary>
internal static class ServerApp
{
public static WebApplication Build(string[] args)
public static WebApplication Build(string[] args, ServerOverrides? overrides = null)
{
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var environment = overrides?.Environment ?? ReadEnvironment();
var options = ServerOptions.Parse(args, environment);
IClock clock = overrides?.Clock ?? (options.Demo ? new ManualClock(DemoMode.Now) : new Anubis.Core.SystemClock());
app.MapGet("/health", () => Results.Ok(new HealthResponse("ok", AnubisInfo.Name, AnubisInfo.Version)));
// Demo mode never reads the configured database: it gets a brand-new folder of its own (trap 27).
var config = options.Demo ? DemoMode.Config(DemoMode.CreateFolder(new Anubis.Core.SystemClock())) : options.LoadConfig(environment);
RegisterSecrets(config);
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = options.AspNetArgs,
ApplicationName = typeof(ServerApp).Assembly.GetName().Name,
ContentRootPath = AppContext.BaseDirectory,
});
if (!options.AspNetArgs.Any(a => a.StartsWith("--urls", StringComparison.Ordinal)))
{
// Desktop and demo listen only on the computer itself unless the user allowed the home network (SPEC 15.6).
var local = options.Demo || (config.Platform == PlatformKind.Desktop && !config.AllowNetwork);
builder.WebHost.UseUrls((local ? "http://127.0.0.1:" : "http://0.0.0.0:") + config.Port.ToString(System.Globalization.CultureInfo.InvariantCulture));
}
builder.Logging.ClearProviders();
// Created by the container so it is disposed with the application and releases the log file.
builder.Services.AddSingleton<ILoggerProvider>(_ => new JsonLogProvider(config.Data.Logs, clock, console: true));
builder.Logging.SetMinimumLevel(LogLevel.Information);
builder.Logging.AddFilter("Microsoft", LogLevel.Warning);
builder.Logging.AddFilter("Microsoft.Hosting.Lifetime", LogLevel.Information);
// The form-token keys sit unencrypted in the data folder, which only the app's user can read (ADR 0007).
builder.Logging.AddFilter("Microsoft.AspNetCore.DataProtection", LogLevel.Error);
var services = builder.Services;
services.AddSingleton(options);
services.AddSingleton(config);
services.AddSingleton(environment);
services.AddSingleton(clock);
services.AddSingleton(overrides ?? new ServerOverrides());
services.AddSingleton<EventBus>();
services.AddSingleton(sp => new AnubisHost(options, config, environment, clock, sp.GetRequiredService<EventBus>(),
sp.GetRequiredService<ILogger<AnubisHost>>(), overrides));
services.AddHostedService(sp => sp.GetRequiredService<AnubisHost>());
services.AddSingleton(new LoginLimiter(clock));
services.AddSingleton<ShellData>();
services.AddSingleton<SecondFactorDrafts>();
services.AddAuthentication(SessionAuthentication.SchemeName)
.AddScheme<AuthenticationSchemeOptions, SessionAuthentication>(SessionAuthentication.SchemeName, null);
services.AddAuthorization();
services.AddAntiforgery(o =>
{
o.Cookie.Name = "anubis_csrf";
o.Cookie.SameSite = SameSiteMode.Strict;
o.Cookie.HttpOnly = true;
o.HeaderName = Endpoints.CsrfHeader;
o.FormFieldName = "__csrf";
});
// The keys behind the form tokens live in the data folder, so a restart or a new container keeps open pages working
// (otherwise ASP.NET would use a home folder that in Docker belongs to root, or keys lost at every start).
services.AddDataProtection()
.SetApplicationName("Anubis")
.PersistKeysToFileSystem(new DirectoryInfo(Path.Combine(config.Data.Root, "web-keys")));
services.AddRazorComponents();
// Pages in Italian stay readable: letters with accents and the euro sign are written as they are.
services.AddSingleton(System.Text.Encodings.Web.HtmlEncoder.Create(System.Text.Unicode.UnicodeRanges.All));
var app = builder.Build();
var host = app.Services.GetRequiredService<AnubisHost>();
app.Use(SecurityHeaders);
app.Use((context, next) => LocalOnly(context, next, options, config));
app.Use((context, next) => Gate.InvokeAsync(context, next, host));
app.UseWebSockets(new WebSocketOptions { KeepAliveInterval = TimeSpan.FromSeconds(20) });
app.UseRouting();
app.UseAuthentication();
app.Use(MustChangePassword);
app.UseAuthorization();
app.UseAntiforgery();
Endpoints.Map(app);
app.MapRazorComponents<App>().RequireAuthorization();
return app;
}
private static Dictionary<string, string?> ReadEnvironment()
{
var result = new Dictionary<string, string?>(StringComparer.Ordinal);
foreach (DictionaryEntry entry in Environment.GetEnvironmentVariables())
{
result[(string)entry.Key] = entry.Value as string;
}
return result;
}
// Every secret the startup configuration knows is masked in logs and messages from the first line on.
private static void RegisterSecrets(StartupConfig config)
{
Redactor.Register(config.Db?.Password);
Redactor.Register(config.AdminPassword);
foreach (var value in config.EnvironmentKeys.Values)
{
Redactor.Register(value);
}
}
private static Task SecurityHeaders(HttpContext context, Func<Task> next)
{
var headers = context.Response.Headers;
headers.XContentTypeOptions = "nosniff";
headers.XFrameOptions = "DENY";
headers["Referrer-Policy"] = "same-origin";
headers.ContentSecurityPolicy = "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; " +
"font-src 'self'; frame-ancestors 'none'; form-action 'self'; base-uri 'none'";
return next();
}
// Defence in depth: even if someone binds the server to every address, desktop and demo answer only the computer itself.
private static Task LocalOnly(HttpContext context, Func<Task> next, ServerOptions options, StartupConfig config)
{
var localOnly = options.Demo || (config.Platform == PlatformKind.Desktop && !config.AllowNetwork);
if (localOnly && !CurrentUser.IsLocal(context))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return context.Response.WriteAsync("Anubis risponde solo dal computer su cui gira.");
}
return next();
}
// Docker: the initial password works once, then the interface asks for a new one before anything else (SPEC 13.1).
private static Task MustChangePassword(HttpContext context, Func<Task> next)
{
if (context.User.Identity?.IsAuthenticated != true || !CurrentUser.MustChangePassword(context.User))
{
return next();
}
var path = context.Request.Path;
if (path.StartsWithSegments("/primo-accesso", StringComparison.Ordinal) || path.StartsWithSegments("/azioni/primo-accesso", StringComparison.Ordinal) ||
path.StartsWithSegments("/azioni/esci", StringComparison.Ordinal) || Gate.IsAlwaysOpen(path))
{
return next();
}
if (SessionAuthentication.IsApi(context.Request))
{
context.Response.StatusCode = StatusCodes.Status403Forbidden;
return context.Response.WriteAsJsonAsync(new ApiError("password_da_cambiare", "Scegli una nuova password prima di continuare."));
}
context.Response.Redirect("/primo-accesso");
return Task.CompletedTask;
}
}
/// <summary>Answer of <c>GET /health</c>.</summary>
internal sealed record HealthResponse(string Status, string Name, string Version);
/// <summary>
/// While the application is not ready, every page is the service page (error, first run): the engine does not start
/// and no other database is ever opened (SPEC 15.1). Health, logo and style always answer.
/// </summary>
internal static class Gate
{
public static bool IsAlwaysOpen(PathString path) =>
path.StartsWithSegments("/health", StringComparison.Ordinal) || path.StartsWithSegments("/assets", StringComparison.Ordinal) ||
path.StartsWithSegments("/brand", StringComparison.Ordinal) || path == "/favicon.ico";
public static async Task InvokeAsync(HttpContext context, Func<Task> next, AnubisHost host)
{
var path = context.Request.Path;
var mode = host.Status.Mode;
if (IsAlwaysOpen(path))
{
await next().ConfigureAwait(false);
return;
}
if (mode == HostMode.Ready)
{
if (path.StartsWithSegments("/servizio", StringComparison.Ordinal) || path.StartsWithSegments("/primo-avvio", StringComparison.Ordinal))
{
context.Response.Redirect("/");
return;
}
await next().ConfigureAwait(false);
return;
}
var api = SessionAuthentication.IsApi(context.Request);
if (mode == HostMode.FirstRun)
{
if (path.StartsWithSegments("/primo-avvio", StringComparison.Ordinal) || path.StartsWithSegments("/azioni/primo-avvio", StringComparison.Ordinal))
{
await next().ConfigureAwait(false);
return;
}
if (!api && HttpMethods.IsGet(context.Request.Method))
{
context.Response.Redirect("/primo-avvio");
return;
}
}
else if (path.StartsWithSegments("/azioni/servizio", StringComparison.Ordinal))
{
await next().ConfigureAwait(false);
return;
}
if (api)
{
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
await context.Response.WriteAsJsonAsync(new ApiError("non_pronto", ServiceText.Title(mode))).ConfigureAwait(false);
return;
}
if (!HttpMethods.IsGet(context.Request.Method) && !HttpMethods.IsHead(context.Request.Method))
{
context.Response.StatusCode = StatusCodes.Status503ServiceUnavailable;
await context.Response.WriteAsync(ServiceText.Title(mode)).ConfigureAwait(false);
return;
}
// The service page answers in place of whatever was asked, with 503 so nothing caches it.
context.Request.Path = "/servizio";
await next().ConfigureAwait(false);
}
}
+70
View File
@@ -0,0 +1,70 @@
using Anubis.Core;
using Anubis.Platform;
namespace Anubis.Server;
/// <summary>
/// What the server process was asked to be, from its arguments and environment: Docker or desktop, which data
/// folder, demo mode. Tests pass a fake environment and clock through <see cref="ServerOverrides"/>.
/// </summary>
internal sealed record ServerOptions(PlatformKind Platform, string? DataDir, bool Demo, string[] AspNetArgs)
{
public static ServerOptions Parse(string[] args, IReadOnlyDictionary<string, string?> environment)
{
var rest = new List<string>();
PlatformKind? platform = null;
string? dataDir = null;
var demo = false;
for (var i = 0; i < args.Length; i++)
{
switch (args[i])
{
case "--platform" when i + 1 < args.Length:
platform = args[++i].Equals("docker", StringComparison.OrdinalIgnoreCase) ? PlatformKind.Docker : PlatformKind.Desktop;
break;
case "--data-dir" when i + 1 < args.Length:
dataDir = Path.GetFullPath(args[++i]);
break;
case "--demo":
demo = true;
break;
default:
rest.Add(args[i]);
break;
}
}
platform ??= (environment.GetValueOrDefault("ANUBIS_PLATFORM") ?? "").ToLowerInvariant() switch
{
"docker" => PlatformKind.Docker,
"desktop" => PlatformKind.Desktop,
_ => environment.GetValueOrDefault("DOTNET_RUNNING_IN_CONTAINER") == "true" ? PlatformKind.Docker : PlatformKind.Desktop,
};
return new ServerOptions(platform.Value, dataDir, demo, [.. rest]);
}
/// <summary>Reads the startup configuration of the chosen platform.</summary>
public StartupConfig LoadConfig(IReadOnlyDictionary<string, string?> environment)
{
if (Platform == PlatformKind.Docker)
{
return DockerPlatform.Load(environment, DataDir ?? "/data");
}
var data = DataDir is null ? DataDirectory.ForCurrentUser() : new DataDirectory(DataDir);
return DesktopPlatform.Load(data, ProtectedSecretKey.DefaultStore(data));
}
}
/// <summary>Test hooks: a fake environment, a manual clock, a cheaper password hash.</summary>
internal sealed record ServerOverrides
{
public IReadOnlyDictionary<string, string?>? Environment { get; init; }
public IClock? Clock { get; init; }
public int? PasswordIterations { get; init; }
/// <summary>How often the database is checked while running and retried while it is missing.</summary>
public TimeSpan? DatabaseCheckInterval { get; init; }
}
+124
View File
@@ -0,0 +1,124 @@
using System.Globalization;
using System.Net;
using System.Security.Claims;
using System.Text.Encodings.Web;
using Anubis.Access;
using Microsoft.AspNetCore.Authentication;
using Microsoft.Extensions.Options;
namespace Anubis.Server;
/// <summary>
/// Sign-in by session cookie (SPEC 15.4): the cookie holds a random token, the database only its hash. HttpOnly,
/// SameSite=Strict, Secure when the request is HTTPS. In demo mode everyone on the computer itself is signed in.
/// </summary>
internal sealed class SessionAuthentication(
IOptionsMonitor<AuthenticationSchemeOptions> options,
ILoggerFactory logger,
UrlEncoder encoder,
AnubisHost host) : AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
public const string SchemeName = "anubis";
public const string Cookie = "anubis_session";
public const string SessionClaim = "anubis:session";
public const string MustChangeClaim = "anubis:must_change";
public const string SecondFactorClaim = "anubis:second_factor";
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
{
var services = host.Services;
if (services is null)
{
return AuthenticateResult.NoResult();
}
if (host.IsDemo)
{
var user = await services.Access.GetUserAsync(Context.RequestAborted).ConfigureAwait(false);
return user is null ? AuthenticateResult.NoResult() : Success(user, Guid.Empty);
}
if (!Request.Cookies.TryGetValue(Cookie, out var token) || string.IsNullOrEmpty(token))
{
return AuthenticateResult.NoResult();
}
var session = await services.Access.ValidateAsync(token, Context.RequestAborted).ConfigureAwait(false);
return session is null ? AuthenticateResult.Fail("Sessione scaduta") : Success(session.User, session.Id);
}
private static AuthenticateResult Success(User user, Guid session)
{
Claim[] claims =
[
new(ClaimTypes.NameIdentifier, user.Id.ToString("D")),
new(ClaimTypes.Name, user.Username),
new(SessionClaim, session.ToString("D")),
new(MustChangeClaim, user.MustChangePassword ? "1" : "0"),
new(SecondFactorClaim, user.HasSecondFactor ? "1" : "0"),
];
var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, SchemeName));
return AuthenticateResult.Success(new AuthenticationTicket(principal, SchemeName));
}
protected override Task HandleChallengeAsync(AuthenticationProperties properties)
{
if (IsApi(Request))
{
Response.StatusCode = StatusCodes.Status401Unauthorized;
return Response.WriteAsJsonAsync(new ApiError("non_autenticato", "Accedi di nuovo."));
}
var back = Request.Path + Request.QueryString;
Response.Redirect("/accesso" + (back == "/" ? "" : "?ritorno=" + Uri.EscapeDataString(back)));
return Task.CompletedTask;
}
protected override Task HandleForbiddenAsync(AuthenticationProperties properties)
{
Response.StatusCode = StatusCodes.Status403Forbidden;
return Task.CompletedTask;
}
internal static bool IsApi(HttpRequest request) =>
request.Path.StartsWithSegments("/api", StringComparison.Ordinal) || request.Path.StartsWithSegments("/ws", StringComparison.Ordinal);
public static void WriteCookie(HttpContext context, string token) =>
context.Response.Cookies.Append(Cookie, token, new CookieOptions
{
HttpOnly = true,
SameSite = SameSiteMode.Strict,
Secure = context.Request.IsHttps,
Path = "/",
MaxAge = AccessStore.MaxLifetime,
IsEssential = true,
});
public static void ClearCookie(HttpContext context) =>
context.Response.Cookies.Delete(Cookie, new CookieOptions { Path = "/", HttpOnly = true, SameSite = SameSiteMode.Strict, Secure = context.Request.IsHttps });
}
/// <summary>Who is signed in, read from the claims.</summary>
internal static class CurrentUser
{
public static Guid Id(ClaimsPrincipal user) => Guid.Parse(user.FindFirstValue(ClaimTypes.NameIdentifier)!, CultureInfo.InvariantCulture);
public static Guid Session(ClaimsPrincipal user) => Guid.Parse(user.FindFirstValue(SessionAuthentication.SessionClaim) ?? Guid.Empty.ToString(), CultureInfo.InvariantCulture);
public static bool MustChangePassword(ClaimsPrincipal user) => user.FindFirstValue(SessionAuthentication.MustChangeClaim) == "1";
public static bool HasSecondFactor(ClaimsPrincipal user) => user.FindFirstValue(SessionAuthentication.SecondFactorClaim) == "1";
/// <summary>
/// The request comes from the computer the server runs on, addressed to it by a local name. The name matters too:
/// a web page that points its own name at 127.0.0.1 (DNS rebinding) arrives from the loopback with a foreign Host.
/// </summary>
public static bool IsLocal(HttpContext context) =>
context.Connection.RemoteIpAddress is { } address && IPAddress.IsLoopback(address) && IsLocalName(context.Request.Host.Host);
internal static bool IsLocalName(string host) =>
host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || host is "127.0.0.1" or "[::1]" or "::1";
}
/// <summary>Error body of the API: a code for programs and a sentence for people.</summary>
internal sealed record ApiError(string Code, string Message);
+105
View File
@@ -0,0 +1,105 @@
using System.Globalization;
using System.Text.Json;
using Anubis.Core;
using Anubis.Demo;
using Anubis.Platform;
namespace Anubis.Server;
/// <summary>What the top bar shows and the WebSocket sends: state of the bot, mode, currency, how fresh the data are.</summary>
internal sealed record ShellSnapshot(
string Mode,
string Bot,
string BotLabel,
string BotShort,
bool RealMoney,
string Currency,
string Theme,
string Now,
int AgeSeconds,
bool Demo,
string Version);
/// <summary>Reads the shell state once per request; also the money formatter with the chosen display currency.</summary>
internal sealed class ShellData(AnubisHost host, IClock clock)
{
private decimal? _demoRate;
private int? _demoAge;
public bool IsDemo => host.IsDemo;
public TimeZoneInfo Zone => host.Config.TimeZone;
public DateTimeOffset Now => clock.UtcNow;
public async Task<ShellSnapshot> SnapshotAsync(CancellationToken cancellationToken)
{
var services = host.Services;
var bot = "active";
var currency = "EUR";
var theme = "auto";
if (services is not null)
{
bot = (await services.Settings.GetAsync(Core.SettingsStore.BotState.Key, cancellationToken).ConfigureAwait(false)).Value;
currency = (await services.Settings.GetAsync(Core.SettingsStore.Currency.Key, cancellationToken).ConfigureAwait(false)).Value;
theme = (await services.Settings.GetAsync(Core.SettingsStore.Theme.Key, cancellationToken).ConfigureAwait(false)).Value;
}
var (label, shortLabel) = bot switch
{
"paused" => ("Bot in pausa", "In pausa"),
"stopped" => ("Bot fermo", "Fermo"),
_ => ("Bot attivo", "Attivo"),
};
var age = DemoAge() ?? (host.LastCheckUtc is { } last ? (int)Math.Max(0, (clock.UtcNow - last).TotalSeconds) : 0);
return new ShellSnapshot(host.Status.Mode.ToString(), bot, label, shortLabel, RealMoney: false, currency, theme,
Format.LongDateTime(clock.UtcNow, Zone), age, host.IsDemo, AnubisInfo.Version);
}
/// <summary>
/// An amount in euro shown in the display currency. Exchange rates arrive with the market data (phase 2): until
/// then dollars appear only in demo mode, with the rate of appendix F, and otherwise amounts stay in euro.
/// </summary>
public string Money(decimal euro, string currency, bool withSign = false, int decimals = 2) =>
Format.Money(Convert(euro, currency), Effective(currency), withSign, decimals);
public decimal Convert(decimal euro, string currency) => currency == "USD" && DemoRate() is { } rate ? euro * rate : euro;
/// <summary>The display currency that <see cref="Money"/> can honour.</summary>
public string Effective(string currency) => currency == "USD" && DemoRate() is not null ? "USD" : "EUR";
private decimal? DemoRate()
{
if (!host.IsDemo)
{
return null;
}
if (_demoRate is null && Aggregates() is { } doc)
{
_demoRate = decimal.Parse(doc.RootElement.GetProperty("cambio_eur_usd").GetString()!, CultureInfo.InvariantCulture);
}
return _demoRate;
}
private int? DemoAge()
{
if (!host.IsDemo)
{
return null;
}
if (_demoAge is null && Aggregates() is { } doc)
{
_demoAge = doc.RootElement.GetProperty("dati_aggiornati_secondi").GetInt32();
}
return _demoAge;
}
/// <summary>The aggregates of appendix F; only in demo mode (SPEC 13.1).</summary>
public JsonDocument? Aggregates() => host.IsDemo ? DemoMode.ReadAggregates(host.Config.Data) : null;
public PlatformKind Platform => host.Config.Platform;
}
+77 -6
View File
@@ -58,6 +58,43 @@ public sealed class LoginLimiter(IClock clock)
}
}
/// <summary>
/// Starts an attempt: zero when it may go ahead, already counted as a failure, so parallel attempts cannot all slip
/// through before the first one fails. A success clears it with <see cref="Succeeded"/>, a correct password still
/// waiting for its code with <see cref="Forgive"/>.
/// </summary>
public TimeSpan Begin(string address)
{
lock (_gate)
{
var wait = Wait(address);
if (wait == TimeSpan.Zero)
{
Failed(address);
}
return wait;
}
}
/// <summary>Takes back the last attempt counted by <see cref="Begin"/>.</summary>
public void Forgive(string address)
{
lock (_gate)
{
if (_failures.TryGetValue(address, out var list) && list.Count > 0)
{
var last = list[^1];
list.RemoveAt(list.Count - 1);
var index = _all.LastIndexOf(last);
if (index >= 0)
{
_all.RemoveAt(index);
}
}
}
}
public void Failed(string address)
{
lock (_gate)
@@ -105,9 +142,37 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
public static readonly TimeSpan IdleTimeout = TimeSpan.FromHours(12);
public static readonly TimeSpan MaxLifetime = TimeSpan.FromDays(7);
// Each second-factor code works once (RFC 6238, 5.2): the last time step used, in memory.
private readonly Lock _stepGate = new();
private long _lastStep = long.MinValue;
private bool AcceptCode(ReadOnlySpan<byte> secret, string? code)
{
if (Totp.Match(secret, code, clock.UtcNow) is not { } step)
{
return false;
}
lock (_stepGate)
{
if (step <= _lastStep)
{
return false;
}
_lastStep = step;
return true;
}
}
public Task<bool> HasUserAsync(CancellationToken cancellationToken = default) =>
db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM users").ConfigureAwait(false) > 0, cancellationToken);
/// <summary>The single user, or null before the first run created it.</summary>
public Task<User?> GetUserAsync(CancellationToken cancellationToken = default) =>
db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT id, username, must_change_password, totp_secret FROM users WHERE username = @u",
r => new User(r.Id("id"), r.Text("username"), r.Bool("must_change_password"), !r.IsNull("totp_secret")), ("u", AdminName)), cancellationToken);
/// <summary>Creates the user when there is none. In Docker the initial password must be changed at first sign-in.</summary>
public async Task<bool> EnsureUserAsync(string password, bool mustChange, CancellationToken cancellationToken = default)
{
@@ -148,7 +213,7 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
}
var secret = Convert.FromBase64String(secrets.Open("totp:" + user.Id.ToString("D"), user.Totp));
if (!Totp.Verify(secret, code, clock.UtcNow))
if (!AcceptCode(secret, code))
{
return (LoginResult.WrongSecondFactor, null);
}
@@ -226,7 +291,7 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
public async Task<bool> EnableSecondFactorAsync(Guid userId, byte[] secret, string code, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(secret);
if (!Totp.Verify(secret, code, clock.UtcNow))
if (!AcceptCode(secret, code))
{
return false;
}
@@ -241,11 +306,17 @@ public sealed class AccessStore(Database db, IClock clock, SecretStore secrets,
return true;
}
public async Task<bool> DisableSecondFactorAsync(Guid userId, string password, CancellationToken cancellationToken = default)
/// <summary>Turning the second factor off asks for both: the password and a code from the app.</summary>
public async Task<bool> DisableSecondFactorAsync(Guid userId, string password, string? code, CancellationToken cancellationToken = default)
{
var hash = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash FROM users WHERE id = @id", r => r.Text("password_hash"), ("id", userId)), cancellationToken)
.ConfigureAwait(false);
if (hash is null || !Passwords.Verify(password, hash))
var user = await db.ReadAsync(s => s.FirstOrDefaultAsync("SELECT password_hash, totp_secret FROM users WHERE id = @id",
r => (Hash: r.Text("password_hash"), Totp: r.BytesOrNull("totp_secret")), ("id", userId)), cancellationToken).ConfigureAwait(false);
if (user == default || !Passwords.Verify(password, user.Hash))
{
return false;
}
if (user.Totp is not null && !AcceptCode(Convert.FromBase64String(secrets.Open("totp:" + userId.ToString("D"), user.Totp)), code))
{
return false;
}
+14 -7
View File
@@ -157,27 +157,34 @@ public static class Totp
}
/// <summary>Accepts the code of the current step and of one step before or after, for clocks a little apart.</summary>
public static bool Verify(ReadOnlySpan<byte> secret, string? code, DateTimeOffset now)
public static bool Verify(ReadOnlySpan<byte> secret, string? code, DateTimeOffset now) => Match(secret, code, now) is not null;
/// <summary>The time step the code belongs to (current, one before or one after), or null when it matches none.</summary>
public static long? Match(ReadOnlySpan<byte> secret, string? code, DateTimeOffset now)
{
if (code is null)
{
return false;
return null;
}
code = code.Replace(" ", "", StringComparison.Ordinal);
if (code.Length != 6 || !code.All(char.IsAsciiDigit))
{
return false;
return null;
}
var ok = false;
long? matched = null;
for (var step = -1; step <= 1; step++)
{
var expected = Compute(secret, now.AddSeconds(step * 30));
ok |= CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(expected), Encoding.ASCII.GetBytes(code));
var at = now.AddSeconds(step * 30);
var expected = Compute(secret, at);
if (CryptographicOperations.FixedTimeEquals(Encoding.ASCII.GetBytes(expected), Encoding.ASCII.GetBytes(code)))
{
matched = at.ToUnixTimeSeconds() / 30;
}
}
return ok;
return matched;
}
/// <summary>The address authenticator apps read (otpauth://), for manual entry or a QR code.</summary>
+1
View File
@@ -9,6 +9,7 @@
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Db\Migrations\*.sql" LogicalName="Anubis.Db.Migrations.%(Filename)%(Extension)" />
<EmbeddedResource Include="Demo\Data\*" LogicalName="Anubis.Demo.Data.%(Filename)%(Extension)" />
</ItemGroup>
<ItemGroup>
<InternalsVisibleTo Include="Anubis.Tests" />
+15 -2
View File
@@ -17,10 +17,12 @@ public sealed class Database : IAsyncDisposable
private readonly SemaphoreSlim _writer = new(1, 1);
private readonly string _connectionString;
private readonly NpgsqlDataSource? _postgres;
private volatile bool _sqliteSeen;
private Database(DbEngine engine, string connectionString, NpgsqlDataSource? postgres, string description)
private Database(DbEngine engine, string connectionString, NpgsqlDataSource? postgres, string description, string? sqlitePath = null)
{
Engine = engine;
SqlitePath = sqlitePath is null ? null : Path.GetFullPath(sqlitePath);
_connectionString = connectionString;
_postgres = postgres;
Description = description;
@@ -28,6 +30,9 @@ public sealed class Database : IAsyncDisposable
public DbEngine Engine { get; }
/// <summary>Full path of the SQLite file; null on PostgreSQL.</summary>
public string? SqlitePath { get; }
/// <summary>Engine and place, without the password.</summary>
public string Description { get; }
@@ -55,7 +60,7 @@ public sealed class Database : IAsyncDisposable
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path))!);
}
return new Database(DbEngine.Sqlite, builder.ToString(), null, settings.Describe());
return new Database(DbEngine.Sqlite, builder.ToString(), null, settings.Describe(), path);
}
var pg = settings.Url is { } url ? new NpgsqlConnectionStringBuilder(ToKeyValue(url)) : new NpgsqlConnectionStringBuilder
@@ -111,10 +116,18 @@ public sealed class Database : IAsyncDisposable
return await _postgres.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);
}
// Once the file existed it must stay where the configuration says: a pooled connection would keep answering
// from a deleted file (on Linux the inode lives on) and a new one would create an empty database (trap 20).
if (_sqliteSeen && !File.Exists(SqlitePath))
{
throw new FileNotFoundException("Il file del database SQLite non c'è più: " + SqlitePath);
}
var connection = new SqliteConnection(_connectionString);
try
{
await connection.OpenAsync(cancellationToken).ConfigureAwait(false);
_sqliteSeen = true;
await using var pragma = connection.CreateCommand();
pragma.CommandText = "PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000;";
await pragma.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);
+59
View File
@@ -0,0 +1,59 @@
{
"_nota": "Valori dell'appendice F di docs/SPEC.md che hanno solo un totale o una statistica. Letti solo dalla modalità dimostrativa (SPEC 13.1).",
"adesso": "2026-10-09T08:21:00+02:00",
"avvio": "2026-08-12",
"capitale_iniziale": "10000.00",
"giorno": 58,
"dati_aggiornati_secondi": 4,
"piattaforma": "Docker",
"database": "PostgreSQL",
"versione": "0.9.2",
"bot": "active",
"soldi_veri": false,
"cambio_eur_usd": "1.1601",
"totali": {
"patrimonio": "10412.46",
"risultato": "412.46",
"risultato_pct": "4.12",
"oggi": "18.40",
"oggi_pct": "0.18",
"sette_giorni": "96.10",
"sette_giorni_pct": "0.93",
"trenta_giorni": "251.70",
"trenta_giorni_pct": "2.48",
"senza_bot": "9974.00",
"senza_bot_risultato": "-26.00",
"senza_bot_pct": "-0.26",
"investito": "6671.13",
"investito_pct": "64.1",
"liquidita": "3741.33",
"liquidita_pct": "35.9",
"risultato_aperto": "173.18",
"calo_peggiore_pct": "-2.82",
"calo_peggiore_data": "2026-09-05"
},
"conti": [
{
"nome": "OKX Europe", "tipo": "Crypto", "ambiente": "simulatore interno", "capitale": "4000.00", "patrimonio": "4231.60",
"risultato": "231.60", "risultato_pct": "5.79", "liquidita": "1905.10", "investito": "2326.50", "incassati": "163.45",
"aperti": "68.15", "commissioni": "14.49", "trenta_giorni": "158.20", "risposta_ms": 84
},
{
"nome": "Alpaca", "tipo": "Azioni USA", "ambiente": "conto di prova", "capitale": "6000.00", "patrimonio": "6180.86", "patrimonio_usd": "7170.41",
"risultato": "180.86", "risultato_pct": "3.01", "liquidita": "1836.23", "investito": "4344.63", "incassati": "75.83",
"aperti": "105.03", "commissioni": "0.33", "trenta_giorni": "93.50", "risposta_ms": 61
}
],
"strategie": [
{ "nome": "crypto_trend", "etichetta": "Trend crypto", "conto": "OKX Europe", "giorno": 58, "di": 60, "quota_pct": 40, "capitale": "4000", "risultato": "231.60", "risultato_pct": "5.79", "calo_peggiore_pct": "-4.1", "chiuse": 9, "in_guadagno": 5 },
{ "nome": "equity_momentum", "etichetta": "Momentum azioni USA", "conto": "Alpaca", "giorno": 58, "di": 60, "quota_pct": 45, "capitale": "4500", "risultato": "169.50", "risultato_pct": "3.77", "calo_peggiore_pct": "-3.2", "chiuse": 11, "in_guadagno": 7 },
{ "nome": "equity_meanrev", "etichetta": "Mean reversion azioni USA", "conto": "Alpaca", "giorno": 58, "di": 60, "quota_pct": 15, "capitale": "1500", "risultato": "11.36", "risultato_pct": "0.76", "calo_peggiore_pct": "-1.1", "chiuse": 21, "in_guadagno": 10 }
],
"operazioni": { "chiuse": 41, "in_guadagno": 22, "guadagno_medio": "28.42", "perdita_media": "-20.31", "rapporto": "1.62", "incassati": "239.28", "commissioni": "14.82" },
"notizie": { "lette_24h": 312, "sulle_posizioni": 9, "con_effetto": 2, "spesa_oggi": "0.04", "tetto": "0.50" },
"apprendimento": { "stato": "observation", "segnali": 212, "necessari": 300, "precisione_pct": 56 },
"sistema": {
"controllo_secondi": 5, "notizie_fonti": 16, "database_gb": "1.8", "ultimo_salvataggio": "03:30", "telegram_ultimo": "08:00",
"cpu_pct": 6, "memoria_gb": "1.1", "memoria_totale_gb": 4, "disco_gb": "2.3", "disco_totale_gb": 50
}
}
+60
View File
@@ -0,0 +1,60 @@
data;patrimonio_eur;senza_bot_eur;calo_pct
2026-08-12;10000,00;10000,00;0,00
2026-08-13;10049,17;9898,01;0,00
2026-08-14;10087,89;9998,64;0,00
2026-08-15;10085,38;10046,35;-0,02
2026-08-16;10098,31;10048,96;0,00
2026-08-17;10143,92;10093,14;0,00
2026-08-18;10091,56;9979,39;-0,52
2026-08-19;10154,99;9904,91;0,00
2026-08-20;10186,43;9974,91;0,00
2026-08-21;10250,57;9947,97;0,00
2026-08-22;10257,92;9891,37;0,00
2026-08-23;10254,68;9903,32;-0,03
2026-08-24;10231,51;9844,47;-0,26
2026-08-25;10189,02;9746,55;-0,67
2026-08-26;10276,77;9716,33;0,00
2026-08-27;10269,26;9686,41;-0,07
2026-08-28;10220,22;9756,88;-0,55
2026-08-29;10162,96;9777,91;-1,11
2026-08-30;10154,80;9741,13;-1,19
2026-08-31;10102,80;9615,19;-1,69
2026-09-01;10077,13;9763,93;-1,94
2026-09-02;9992,93;9729,55;-2,76
2026-09-03;10006,93;9629,62;-2,63
2026-09-04;10045,33;9591,40;-2,25
2026-09-05;9987,08;9639,42;-2,82
2026-09-06;10047,74;9651,06;-2,23
2026-09-07;10095,79;9693,95;-1,76
2026-09-08;10132,43;9673,13;-1,40
2026-09-09;10160,76;9662,70;-1,13
2026-09-10;10167,99;9647,61;-1,06
2026-09-11;10142,45;9603,46;-1,31
2026-09-12;10129,43;9480,28;-1,43
2026-09-13;10149,62;9447,18;-1,24
2026-09-14;10146,01;9506,25;-1,27
2026-09-15;10121,86;9561,70;-1,51
2026-09-16;10142,77;9722,09;-1,30
2026-09-17;10208,79;9791,60;-0,66
2026-09-18;10205,70;9825,49;-0,69
2026-09-19;10174,28;9872,38;-1,00
2026-09-20;10203,45;9838,07;-0,71
2026-09-21;10206,21;9829,79;-0,69
2026-09-22;10255,00;9861,96;-0,21
2026-09-23;10282,67;10008,21;0,00
2026-09-24;10269,16;10083,10;-0,13
2026-09-25;10331,03;10100,31;0,00
2026-09-26;10322,66;10019,39;-0,08
2026-09-27;10314,46;10100,35;-0,16
2026-09-28;10388,02;10005,58;0,00
2026-09-29;10340,65;9980,52;-0,46
2026-09-30;10302,26;9985,59;-0,83
2026-10-01;10320,81;10002,01;-0,65
2026-10-02;10316,36;9943,23;-0,69
2026-10-03;10285,25;9937,24;-0,99
2026-10-04;10315,99;9896,36;-0,69
2026-10-05;10331,17;9982,05;-0,55
2026-10-06;10340,15;9998,34;-0,46
2026-10-07;10365,81;10012,27;-0,21
2026-10-08;10394,06;9941,64;0,00
2026-10-09;10412,46;9974,00;0,00
1 data patrimonio_eur senza_bot_eur calo_pct
2 2026-08-12 10000,00 10000,00 0,00
3 2026-08-13 10049,17 9898,01 0,00
4 2026-08-14 10087,89 9998,64 0,00
5 2026-08-15 10085,38 10046,35 -0,02
6 2026-08-16 10098,31 10048,96 0,00
7 2026-08-17 10143,92 10093,14 0,00
8 2026-08-18 10091,56 9979,39 -0,52
9 2026-08-19 10154,99 9904,91 0,00
10 2026-08-20 10186,43 9974,91 0,00
11 2026-08-21 10250,57 9947,97 0,00
12 2026-08-22 10257,92 9891,37 0,00
13 2026-08-23 10254,68 9903,32 -0,03
14 2026-08-24 10231,51 9844,47 -0,26
15 2026-08-25 10189,02 9746,55 -0,67
16 2026-08-26 10276,77 9716,33 0,00
17 2026-08-27 10269,26 9686,41 -0,07
18 2026-08-28 10220,22 9756,88 -0,55
19 2026-08-29 10162,96 9777,91 -1,11
20 2026-08-30 10154,80 9741,13 -1,19
21 2026-08-31 10102,80 9615,19 -1,69
22 2026-09-01 10077,13 9763,93 -1,94
23 2026-09-02 9992,93 9729,55 -2,76
24 2026-09-03 10006,93 9629,62 -2,63
25 2026-09-04 10045,33 9591,40 -2,25
26 2026-09-05 9987,08 9639,42 -2,82
27 2026-09-06 10047,74 9651,06 -2,23
28 2026-09-07 10095,79 9693,95 -1,76
29 2026-09-08 10132,43 9673,13 -1,40
30 2026-09-09 10160,76 9662,70 -1,13
31 2026-09-10 10167,99 9647,61 -1,06
32 2026-09-11 10142,45 9603,46 -1,31
33 2026-09-12 10129,43 9480,28 -1,43
34 2026-09-13 10149,62 9447,18 -1,24
35 2026-09-14 10146,01 9506,25 -1,27
36 2026-09-15 10121,86 9561,70 -1,51
37 2026-09-16 10142,77 9722,09 -1,30
38 2026-09-17 10208,79 9791,60 -0,66
39 2026-09-18 10205,70 9825,49 -0,69
40 2026-09-19 10174,28 9872,38 -1,00
41 2026-09-20 10203,45 9838,07 -0,71
42 2026-09-21 10206,21 9829,79 -0,69
43 2026-09-22 10255,00 9861,96 -0,21
44 2026-09-23 10282,67 10008,21 0,00
45 2026-09-24 10269,16 10083,10 -0,13
46 2026-09-25 10331,03 10100,31 0,00
47 2026-09-26 10322,66 10019,39 -0,08
48 2026-09-27 10314,46 10100,35 -0,16
49 2026-09-28 10388,02 10005,58 0,00
50 2026-09-29 10340,65 9980,52 -0,46
51 2026-09-30 10302,26 9985,59 -0,83
52 2026-10-01 10320,81 10002,01 -0,65
53 2026-10-02 10316,36 9943,23 -0,69
54 2026-10-03 10285,25 9937,24 -0,99
55 2026-10-04 10315,99 9896,36 -0,69
56 2026-10-05 10331,17 9982,05 -0,55
57 2026-10-06 10340,15 9998,34 -0,46
58 2026-10-07 10365,81 10012,27 -0,21
59 2026-10-08 10394,06 9941,64 0,00
60 2026-10-09 10412,46 9974,00 0,00
+16
View File
@@ -0,0 +1,16 @@
Giorno;Ora;Voce;Tipo
Oggi;08:20;Controllo periodico: registri in ordine, conto Alpaca allineato.;Sistema
Oggi;08:00;Inviato il riepilogo del mattino su Telegram.;Sistema
Oggi;07:52;Notizia sui verbali della banca centrale USA: nessun effetto.;Notizie
Oggi;06:10;Ho cambiato una regola per 24 ore: non aumento la posizione su SOL. Motivo: l'aggiornamento della rete Solana è stato rinviato di una settimana.;Notizie
Oggi;03:00;Controllo del modello: nessuna anomalia.;Apprendimento
Oggi;02:06;Alzato lo stop di BTC/EUR da 65.400 € a 66.180 €. Lo stop segue il prezzo quando sale.;Ordini
Oggi;02:05;Chiusura giornaliera crypto: nessun cambio. BTC, ETH e SOL restano in tendenza. Le altre 7 monete restano fuori: nessuna ha segnato nuovi massimi.;Decisioni
Ieri;22:41;Ho messo una restrizione fino a martedì: niente mean reversion su JPM. Motivo: JPMorgan pubblica i conti martedì prima dell'apertura.;Notizie
Ieri;22:21;Azioni: nessun nuovo acquisto. AAPL resta aperta: non è ancora tornata sopra la media a 5 giorni.;Decisioni
Ieri;21:58;Venduta 1 MSFT a 522,14 $: +9,84 $ in 3 giorni. (con il collegamento "Perché l'ho comprata e venduta");Ordini
Ieri;18:20;Ricontrollata la voce sui prelievi rallentati di un exchange: rientrata.;Notizie
Ieri;16:20;Voce non confermata su un exchange. Nessuna azione: ricontrollo tra 2 ore.;Notizie
Ieri;15:36;Comprate 2 AAPL a 259,80 $. Mean reversion: tre sedute di ribasso, titolo sopra la media a 200 giorni.;Ordini
Ieri;15:35;Rimessi 6 stop giornalieri sulle frazioni di azione.;Ordini
Ieri;14:31;Richieste di sussidi USA sotto le attese: impatto medio, nessun blocco.;Notizie
Can't render this file because it contains an unexpected character in line 11 and column 81.
+11
View File
@@ -0,0 +1,11 @@
Strumento;Nome;Conto;Strategia;Quantità;Prezzo medio;Prezzo ora;Valore €;Risultato €;Risultato %;Stop;Aperta da (giorni);Rischio all'ingresso %
BTC/EUR;Bitcoin;OKX Europe;Trend crypto;0,0182;68.950,00 €;71.420,00 €;1.299,84;+44,95;+3,58;66.180 €;23;0,95
ETH/EUR;Ether;OKX Europe;Trend crypto;0,262;2.488,00 €;2.611,00 €;684,08;+32,23;+4,94;2.395 €;19;0,62
AVGO;Broadcom;Alpaca;Momentum;2,1;352,10 $;367,90 $;665,97;+28,60;+4,49;338,50 $;18;0,48
NVDA;Nvidia;Alpaca;Momentum;4,2;171,30 $;182,45 $;660,54;+40,37;+6,51;166,00 $;25;0,52
LLY;Eli Lilly;Alpaca;Momentum;0,9;812,00 $;846,30 $;656,56;+26,61;+4,22;795,00 $;11;0,41
JPM;JPMorgan Chase;Alpaca;Momentum;2,6;291,40 $;287,15 $;643,56;−9,53;−1,46;276,90 $;4;0,36
XOM;Exxon Mobil;Alpaca;Momentum;6,1;118,90 $;121,35 $;638,08;+12,89;+2,06;115,20 $;11;0,33
COST;Costco;Alpaca;Momentum;0,75;968,20 $;981,60 $;634,60;+8,66;+1,38;941,00 $;4;0,30
AAPL;Apple;Alpaca;Mean reversion;2;259,80 $;258,31 $;445,32;−2,57;−0,57;249,40 $;1;0,17
SOL/EUR;Solana;OKX Europe;Trend crypto;2,68;131,20 €;127,83 €;342,58;−9,03;−2,57;118,40 €;6;0,38
1 Strumento Nome Conto Strategia Quantità Prezzo medio Prezzo ora Valore € Risultato € Risultato % Stop Aperta da (giorni) Rischio all'ingresso %
2 BTC/EUR Bitcoin OKX Europe Trend crypto 0,0182 68.950,00 € 71.420,00 € 1.299,84 +44,95 +3,58 66.180 € 23 0,95
3 ETH/EUR Ether OKX Europe Trend crypto 0,262 2.488,00 € 2.611,00 € 684,08 +32,23 +4,94 2.395 € 19 0,62
4 AVGO Broadcom Alpaca Momentum 2,1 352,10 $ 367,90 $ 665,97 +28,60 +4,49 338,50 $ 18 0,48
5 NVDA Nvidia Alpaca Momentum 4,2 171,30 $ 182,45 $ 660,54 +40,37 +6,51 166,00 $ 25 0,52
6 LLY Eli Lilly Alpaca Momentum 0,9 812,00 $ 846,30 $ 656,56 +26,61 +4,22 795,00 $ 11 0,41
7 JPM JPMorgan Chase Alpaca Momentum 2,6 291,40 $ 287,15 $ 643,56 −9,53 −1,46 276,90 $ 4 0,36
8 XOM Exxon Mobil Alpaca Momentum 6,1 118,90 $ 121,35 $ 638,08 +12,89 +2,06 115,20 $ 11 0,33
9 COST Costco Alpaca Momentum 0,75 968,20 $ 981,60 $ 634,60 +8,66 +1,38 941,00 $ 4 0,30
10 AAPL Apple Alpaca Mean reversion 2 259,80 $ 258,31 $ 445,32 −2,57 −0,57 249,40 $ 1 0,17
11 SOL/EUR Solana OKX Europe Trend crypto 2,68 131,20 € 127,83 € 342,58 −9,03 −2,57 118,40 € 6 0,38
+42
View File
@@ -0,0 +1,42 @@
n;strategia;risultato_eur;simbolo
1;crypto_trend;27,32;
2;equity_momentum;16,21;
3;equity_meanrev;-12,85;
4;equity_momentum;33,93;
5;equity_meanrev;7,61;
6;equity_momentum;-67,16;TSLA
7;equity_momentum;27,43;
8;equity_meanrev;-8,53;
9;equity_momentum;-51,17;
10;equity_meanrev;-11,58;
11;equity_meanrev;-7,31;
12;equity_momentum;40,39;
13;equity_meanrev;13,54;
14;equity_meanrev;-5,28;
15;equity_meanrev;15,14;
16;equity_momentum;44,26;
17;equity_meanrev;-12,63;
18;equity_meanrev;5,38;
19;crypto_trend;42,50;
20;equity_meanrev;8,74;
21;equity_meanrev;16,58;
22;equity_meanrev;5,28;
23;crypto_trend;-29,31;
24;crypto_trend;50,05;
25;equity_momentum;40,74;
26;equity_meanrev;-4,99;
27;crypto_trend;52,70;
28;equity_meanrev;-8,11;
29;crypto_trend;-29,03;
30;crypto_trend;-18,18;
31;equity_momentum;-54,77;
32;equity_meanrev;-4,90;
33;equity_meanrev;12,10;
34;equity_meanrev;-3,75;PG
35;crypto_trend;89,54;LINK/EUR
36;equity_meanrev;7,95;V
37;crypto_trend;-22,14;ADA/EUR
38;equity_momentum;59,35;AMD
39;equity_momentum;-27,31;UNH
40;equity_meanrev;-6,94;KO
41;equity_meanrev;8,48;MSFT
1 n strategia risultato_eur simbolo
2 1 crypto_trend 27,32
3 2 equity_momentum 16,21
4 3 equity_meanrev -12,85
5 4 equity_momentum 33,93
6 5 equity_meanrev 7,61
7 6 equity_momentum -67,16 TSLA
8 7 equity_momentum 27,43
9 8 equity_meanrev -8,53
10 9 equity_momentum -51,17
11 10 equity_meanrev -11,58
12 11 equity_meanrev -7,31
13 12 equity_momentum 40,39
14 13 equity_meanrev 13,54
15 14 equity_meanrev -5,28
16 15 equity_meanrev 15,14
17 16 equity_momentum 44,26
18 17 equity_meanrev -12,63
19 18 equity_meanrev 5,38
20 19 crypto_trend 42,50
21 20 equity_meanrev 8,74
22 21 equity_meanrev 16,58
23 22 equity_meanrev 5,28
24 23 crypto_trend -29,31
25 24 crypto_trend 50,05
26 25 equity_momentum 40,74
27 26 equity_meanrev -4,99
28 27 crypto_trend 52,70
29 28 equity_meanrev -8,11
30 29 crypto_trend -29,03
31 30 crypto_trend -18,18
32 31 equity_momentum -54,77
33 32 equity_meanrev -4,90
34 33 equity_meanrev 12,10
35 34 equity_meanrev -3,75 PG
36 35 crypto_trend 89,54 LINK/EUR
37 36 equity_meanrev 7,95 V
38 37 crypto_trend -22,14 ADA/EUR
39 38 equity_momentum 59,35 AMD
40 39 equity_momentum -27,31 UNH
41 40 equity_meanrev -6,94 KO
42 41 equity_meanrev 8,48 MSFT
+224
View File
@@ -0,0 +1,224 @@
using System.Globalization;
using System.Reflection;
using System.Text;
using System.Text.Json;
using Anubis.Core;
using Anubis.Db;
using Anubis.Platform;
namespace Anubis.Demo;
/// <summary>
/// Demo mode (SPEC 13.1, appendix F): a separate SQLite database in a new temporary folder, never the configured
/// one (trap 27), filled with the rows of appendix F; the clock frozen at Friday 9 October 2026, 08:21 Italian
/// time; no broker. Values that appendix F gives only as totals go to an aggregates file that only this mode reads.
/// Rows of tables that later phases create (closed trades, news, models) are loaded by those phases.
/// </summary>
public static class DemoMode
{
public const string AggregatesFile = "demo-aggregates.json";
/// <summary>"Adesso" in the demo: Friday 9 October 2026, 08:21 in Rome.</summary>
public static readonly DateTimeOffset Now = new(2026, 10, 9, 8, 21, 0, TimeSpan.FromHours(2));
private static readonly CultureInfo _it = CultureInfo.InvariantCulture;
/// <summary>Demo folders older than this are removed when a new demo starts.</summary>
public static readonly TimeSpan KeepFolders = TimeSpan.FromDays(7);
/// <summary>
/// A brand-new folder under the system temporary directory; it never reuses another folder. <paramref name="wallClock"/>
/// is the real clock (the demo's own clock stands still): it names the folder and clears demos older than a week.
/// </summary>
public static DataDirectory CreateFolder(IClock wallClock)
{
ArgumentNullException.ThrowIfNull(wallClock);
var now = wallClock.UtcNow;
var parent = Path.Combine(Path.GetTempPath(), "anubis-demo");
RemoveOldFolders(parent, now);
var root = Path.Combine(parent, now.ToString("yyyyMMdd-HHmmss", _it) + "-" + Guid.NewGuid().ToString("N")[..8]);
if (Directory.Exists(root))
{
throw new IOException("Demo folder already exists: " + root);
}
var data = new DataDirectory(root);
data.Ensure();
return data;
}
// Only folders named the way CreateFolder names them, and only by the date in the name: nothing else is touched.
private static void RemoveOldFolders(string parent, DateTimeOffset now)
{
if (!Directory.Exists(parent))
{
return;
}
foreach (var folder in Directory.EnumerateDirectories(parent))
{
var name = Path.GetFileName(folder);
if (name.Length != 24 || name[15] != '-' ||
!DateTimeOffset.TryParseExact(name[..15], "yyyyMMdd-HHmmss", _it, DateTimeStyles.AssumeUniversal, out var created) ||
now - created < KeepFolders)
{
continue;
}
try
{
Directory.Delete(folder, recursive: true);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// Still in use by another demo, or protected: left for next time.
}
}
}
public static StartupConfig Config(DataDirectory data) => new()
{
Platform = PlatformKind.Desktop,
Data = data,
Db = new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = data.SqliteFile },
TimeZone = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome"),
SecretKey = new ProtectedSecretKey(new RestrictedFileStore(Path.Combine(data.Root, "keys"))),
AllowLive = false,
};
/// <summary>Loads appendix F into an empty, migrated database and writes the aggregates file next to it.</summary>
public static async Task SeedAsync(Database db, DataDirectory data, IClock clock, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(db);
ArgumentNullException.ThrowIfNull(data);
ArgumentNullException.ThrowIfNull(clock);
if (db.SqlitePath is null || !db.SqlitePath.StartsWith(Path.GetFullPath(data.Root), StringComparison.Ordinal))
{
throw new InvalidOperationException("Demo data go only into the demo's own SQLite database.");
}
File.WriteAllText(Path.Combine(data.Root, AggregatesFile), Resource("aggregates.json"));
var rome = TimeZoneInfo.FindSystemTimeZoneById("Europe/Rome");
var now = clock.UtcNow;
var ids = new IdSource(now);
await db.WriteAsync(async s =>
{
var okx = ids.Next();
var alpaca = ids.Next();
await s.ExecuteAsync("INSERT INTO accounts (id, name, broker, environment, base_currency, created_at) VALUES (@id, 'OKX Europe', 'okx', 'simulation', 'EUR', @t), (@id2, 'Alpaca', 'alpaca', 'demo', 'USD', @t)",
cancellationToken, ("id", okx), ("id2", alpaca), ("t", now)).ConfigureAwait(false);
var strategies = new Dictionary<string, (string Name, Guid Account, decimal Capital)>
{
["Trend crypto"] = ("crypto_trend", okx, 4000m),
["Momentum"] = ("equity_momentum", alpaca, 4500m),
["Mean reversion"] = ("equity_meanrev", alpaca, 1500m),
};
foreach (var (name, account, capital) in strategies.Values)
{
await s.ExecuteAsync("INSERT INTO strategy_state (id, strategy, account_id, stage, capital, state, created_at, updated_at) VALUES (@id, @n, @a, 'simulation', @c, @st, @t, @t)",
cancellationToken, ("id", ids.Next()), ("n", name), ("a", account), ("c", capital), ("st", new DbJson("{\"day\":58,\"of\":60}")), ("t", now)).ConfigureAwait(false);
}
// F.4: the ten open positions.
foreach (var row in Csv("positions.csv").Skip(1))
{
var symbol = row[0];
var crypto = symbol.Contains('/', StringComparison.Ordinal);
var instrument = ids.Next();
var (strategy, account, _) = strategies[row[3]];
await s.ExecuteAsync("INSERT INTO instruments (id, venue, symbol, name, asset_class, quote_currency, created_at) VALUES (@id, @v, @s, @n, @c, @q, @t)",
cancellationToken, ("id", instrument), ("v", crypto ? "okx" : "alpaca"), ("s", symbol), ("n", row[1]), ("c", crypto ? "crypto" : "equity"),
("q", crypto ? "EUR" : "USD"), ("t", now)).ConfigureAwait(false);
await s.ExecuteAsync(
"INSERT INTO positions (id, account_id, instrument_id, strategy, quantity, average_price, last_price, stop_price, opened_at, created_at, updated_at) VALUES (@id, @a, @i, @s, @q, @p, @l, @st, @o, @t, @t)",
cancellationToken, ("id", ids.Next()), ("a", account), ("i", instrument), ("s", strategy), ("q", Number(row[4])), ("p", Number(row[5])), ("l", Number(row[6])),
("st", Number(row[10])), ("o", now.AddDays(-int.Parse(row[11], _it))), ("t", now)).ConfigureAwait(false);
}
// F.6: the daily series of the total; accounts and strategies are generated to end on their F.2 and F.3 results.
var daily = Csv("daily.csv").Skip(1).Select(r => (Day: DateOnly.ParseExact(r[0], "yyyy-MM-dd", _it), Equity: Number(r[1]), Benchmark: Number(r[2]), Drawdown: Number(r[3]))).ToList();
var total = daily[^1].Equity - 10000m;
(string Scope, Guid? Account, string? Strategy, decimal Start, decimal Result)[] series =
[
("account", okx, null, 4000m, 231.60m),
("account", alpaca, null, 6000m, 180.86m),
("strategy", null, "crypto_trend", 4000m, 231.60m),
("strategy", null, "equity_momentum", 4500m, 169.50m),
("strategy", null, "equity_meanrev", 1500m, 11.36m),
];
foreach (var (day, equity, benchmark, drawdown) in daily)
{
var at = day == DateOnly.FromDateTime(Now.DateTime) ? now : new DateTimeOffset(day.ToDateTime(new TimeOnly(22, 0)), rome.GetUtcOffset(day.ToDateTime(new TimeOnly(22, 0))));
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, equity, benchmark, drawdown_pct, created_at) VALUES (@id, @at, 'total', @e, @b, @d, @t)",
cancellationToken, ("id", ids.Next()), ("at", at), ("e", equity), ("b", benchmark), ("d", drawdown), ("t", now)).ConfigureAwait(false);
foreach (var (scope, account, strategy, start, result) in series)
{
var value = Math.Round(start + (equity - 10000m) * result / total, 2, MidpointRounding.AwayFromZero);
await s.ExecuteAsync("INSERT INTO equity_snapshots (id, taken_at, scope, account_id, strategy, equity, created_at) VALUES (@id, @at, @sc, @a, @st, @e, @t)",
cancellationToken, ("id", ids.Next()), ("at", at), ("sc", scope), ("a", account), ("st", strategy), ("e", value), ("t", now)).ConfigureAwait(false);
}
}
// F.10: the diary, newest first in the appendix.
var today = DateOnly.FromDateTime(Now.DateTime);
foreach (var row in Csv("journal.csv").Skip(1))
{
var day = row[0] == "Oggi" ? today : today.AddDays(-1);
var local = day.ToDateTime(TimeOnly.ParseExact(row[1], "HH:mm", _it));
await s.ExecuteAsync("INSERT INTO journal (id, occurred_at, kind, code, message, created_at) VALUES (@id, @at, @k, 'demo', @m, @t)",
cancellationToken, ("id", ids.Next()), ("at", new DateTimeOffset(local, rome.GetUtcOffset(local))), ("k", row[3]), ("m", row[2]), ("t", now)).ConfigureAwait(false);
}
await s.ExecuteAsync("INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, 'bot.state', @v, @t, @t)",
cancellationToken, ("id", ids.Next()), ("v", new DbJson(JsonSerializer.Serialize("active"))), ("t", now)).ConfigureAwait(false);
}, cancellationToken).ConfigureAwait(false);
}
/// <summary>Reads the aggregates file of a demo folder.</summary>
public static JsonDocument? ReadAggregates(DataDirectory data)
{
ArgumentNullException.ThrowIfNull(data);
var path = Path.Combine(data.Root, AggregatesFile);
return File.Exists(path) ? JsonDocument.Parse(File.ReadAllText(path)) : null;
}
// "68.950,00 €", "+3,58", "66.180 €", "0,0182" → decimal.
private static decimal Number(string text)
{
var clean = new StringBuilder();
foreach (var c in text)
{
if (char.IsAsciiDigit(c) || c == ',')
{
clean.Append(c == ',' ? '.' : c);
}
else if (c is '-' or '−')
{
clean.Append('-');
}
}
return decimal.Parse(clean.ToString(), NumberStyles.Number, _it);
}
private static IEnumerable<string[]> Csv(string name) =>
Resource(name).Split('\n', StringSplitOptions.RemoveEmptyEntries).Select(l => l.TrimEnd('\r').Split(';'));
private static string Resource(string name)
{
using var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("Anubis.Demo.Data." + name)
?? throw new InvalidOperationException("Missing demo resource " + name);
using var reader = new StreamReader(stream, Encoding.UTF8);
return reader.ReadToEnd();
}
/// <summary>UUIDv7 in insertion order, all at the demo's frozen time.</summary>
private sealed class IdSource(DateTimeOffset at)
{
private int _n;
public Guid Next() => Guid.CreateVersion7(at.AddMilliseconds(_n++));
}
}
+15
View File
@@ -141,6 +141,21 @@ public static class Installation
// Sessions of the old database do not survive: everyone signs in again.
await s.ExecuteAsync("DELETE FROM sessions", cancellationToken).ConfigureAwait(false);
// SPEC 15.1: after an import, a restore or a move the bot restarts with "Ferma tutto" on, whatever the archive said.
var key = Core.SettingsStore.BotState.Key;
var stopped = new DbJson(JsonSerializer.Serialize("stopped"));
var old = await s.FirstOrDefaultAsync("SELECT value FROM config WHERE key = @k", r => r.Json("value").Text, ("k", key)).ConfigureAwait(false);
if (old != stopped.Text)
{
await s.ExecuteAsync(old is null
? "INSERT INTO config (id, key, value, created_at, updated_at) VALUES (@id, @k, @v, @t, @t)"
: "UPDATE config SET value = @v, updated_at = @t WHERE key = @k",
cancellationToken, ("id", Ids.NewId(clock)), ("k", key), ("v", stopped), ("t", now)).ConfigureAwait(false);
await s.ExecuteAsync("INSERT INTO config_history (id, key, old_value, new_value, changed_by, created_at) VALUES (@id, @k, @o, @n, @by, @t)", cancellationToken,
("id", Ids.NewId(clock)), ("k", key), ("o", new DbJson(old ?? JsonSerializer.Serialize(Core.SettingsStore.BotState.Default))), ("n", stopped),
("by", "ripartenza protetta"), ("t", now)).ConfigureAwait(false);
}
}, cancellationToken).ConfigureAwait(false);
var renewed = new InstallationFile(id, fingerprint, engine, createdAt, now);
WriteFile(data, renewed);