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

+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)));
}