diff --git a/.dockerignore b/.dockerignore index 619d996..cf448c2 100644 --- a/.dockerignore +++ b/.dockerignore @@ -6,6 +6,7 @@ artifacts/ TestResults/ docs/ +!docs/design/logo/ **/*.md .env .env.* diff --git a/CLAUDE.md b/CLAUDE.md index c64c51e..4ab29db 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -11,15 +11,17 @@ Bot di trading personale: azioni USA su Alpaca, crypto spot su OKX Europe, senza ## Comandi -Da `tools/Anubis.Tasks`, tramite `./tasks.ps1 ` (Windows) o `sh ./tasks.sh ` (Linux). Niente `make`. +Dalla radice del repository: `./tasks.ps1 ` (Windows) o `sh ./tasks.sh ` (Linux); il codice sta in `tools/Anubis.Tasks`. Niente `make`. - `check`: ripristino con `--locked-mode`, `dotnet format --verify-no-changes`, build Release con gli analizzatori, test. Va verde prima di ogni commit. - `test`: solo i test; il motore viene da `ANUBIS_TEST_DB` (`sqlite` o `postgres`). Esclude la categoria `LiveDemo`. -- `dev`: il server con `dotnet watch` su http://localhost:5000 (o `--urls`). +- `dev`: il server con `dotnet watch` su http://localhost:8787 (o `--urls`). Fuori da Docker usa la configurazione desktop e la cartella dei dati dell'utente (`%APPDATA%\Anubis`): per provare senza toccarla c'è `seed-demo`. - `build`: l'immagine Docker `gitea.encke-hake.ts.net/balbosoft/anubis:dev`. - `ci`: come la CI. Esegue `check`, poi i test su PostgreSQL (avvia `docker compose up -d --wait postgres`, porta 55432) e infine l'immagine. Richiede Docker. - `hooks`: attiva `.githooks/pre-commit`, che esegue `check` prima di ogni commit. Si fa una volta per copia del repository. -- `seed-demo` (Fase 1), `desktop-win` (Fase 10): non ancora disponibili. -- `docker compose up --build`: l'applicazione su http://localhost:8787, `/health` risponde `ok`. +- `seed-demo`: la modalità dimostrativa con i dati dell'appendice F, in una cartella e un database a parte, solo dal computer stesso. +- `screenshots`: fotografa Panoramica, Diario e Impostazioni a 1440 px (chiaro e scuro) e a 390 px in `artifacts/screenshots/`. Usa Edge o Chrome già installati. +- `desktop-win` (Fase 10): non ancora disponibile. +- `docker compose up --build`: l'applicazione su http://localhost:8787 con PostgreSQL, `/health` risponde `ok`. Primo accesso con `ANUBIS_ADMIN_PASSWORD` del compose. Un pacchetto nuovo rompe `DependencyPolicyTests` finché non è autorizzato (ADR 0004) e presente in `Directory.Packages.props` e nel file di blocco. Una sua dipendenza di terze parti va aggiunta all'elenco del test e a `docs/API-NOTES.md` (ADR 0006). @@ -42,6 +44,7 @@ Un pacchetto nuovo rompe `DependencyPolicyTests` finché non è autorizzato (ADR - `docs/SPEC.md` — specifica completa - `docs/adr/0003-csharp-dotnet.md` — stack, struttura del repository, strumenti - `docs/adr/0004-componenti-esterni.md` — pacchetti ammessi e come chiederne altri +- `docs/adr/0007-scelte-fase-1.md` — schema per i due motori, interfaccia statica, immagine Docker - `docs/design/` — screen di riferimento (SPEC 13.1); `docs/design/logo/` — logo - `docs/ROADMAP.md` — fasi, issue, criteri di accettazione - `docs/STATE.md` — stato corrente diff --git a/deploy/docker/Dockerfile b/deploy/docker/Dockerfile index ed70e0e..d0a17b6 100644 --- a/deploy/docker/Dockerfile +++ b/deploy/docker/Dockerfile @@ -1,5 +1,5 @@ -# Anubis image (ADR 0003). Phase 0: minimal server with /health. -# Phase 1 adds the entrypoint (PUID/PGID, data folder) and the HEALTHCHECK (issue #16). +# Anubis image (ADR 0003, SPEC 15.2). Build from the repository root: +# docker build -f deploy/docker/Dockerfile -t gitea.encke-hake.ts.net/balbosoft/anubis:dev . FROM mcr.microsoft.com/dotnet/sdk:10.0 AS build WORKDIR /src @@ -9,14 +9,24 @@ COPY src/Anubis.Server/Anubis.Server.csproj src/Anubis.Server/packages.lock.json RUN dotnet restore src/Anubis.Server/Anubis.Server.csproj --locked-mode COPY src/Anubis/ src/Anubis/ COPY src/Anubis.Server/ src/Anubis.Server/ +# The logo is embedded from docs/design/logo, its only source (ADR 0005). +COPY docs/design/logo/ docs/design/logo/ RUN dotnet publish src/Anubis.Server/Anubis.Server.csproj -c Release --no-restore -o /app FROM mcr.microsoft.com/dotnet/aspnet:10.0 WORKDIR /app COPY --from=build /app ./ -ENV ASPNETCORE_HTTP_PORTS=8787 \ - TZ=Europe/Rome +COPY --chmod=755 deploy/docker/entrypoint.sh /usr/local/bin/anubis-entrypoint +# The port comes from PORT (8787 by default), read by the app; the base image's own port setting is cleared. +ENV ANUBIS_PLATFORM=docker \ + ASPNETCORE_HTTP_PORTS= \ + TZ=Europe/Rome \ + PUID=99 \ + PGID=100 EXPOSE 8787 VOLUME /data -USER $APP_UID -ENTRYPOINT ["dotnet", "Anubis.Server.dll"] +# Starts as root only to give /data to PUID:PGID, then runs the app as that user (entrypoint.sh). +# Health through bash's /dev/tcp: no curl or wget in the image. 503 (database down) counts as unhealthy. +HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \ + CMD ["bash", "-c", "exec 3<>/dev/tcp/127.0.0.1/${PORT:-8787} && printf 'GET /health HTTP/1.0\r\nHost: localhost\r\n\r\n' >&3 && head -n 1 <&3 | grep -q ' 200 '"] +ENTRYPOINT ["anubis-entrypoint"] diff --git a/deploy/docker/entrypoint.sh b/deploy/docker/entrypoint.sh new file mode 100644 index 0000000..fb91c16 --- /dev/null +++ b/deploy/docker/entrypoint.sh @@ -0,0 +1,30 @@ +#!/bin/sh +# Container start (SPEC 15.2, issue #16). As root: prepare /data for PUID:PGID (99:100 on Unraid), then drop to that +# user with setpriv, which is part of the base image (no gosu). Started as another user (docker run --user): go straight on. +set -eu + +app="/app/Anubis.Server.dll" + +if [ "$(id -u)" != "0" ]; then + exec dotnet "$app" "$@" +fi + +uid="${PUID:-99}" +gid="${PGID:-100}" +case "$uid$gid" in + *[!0-9]*|"") + echo "PUID e PGID devono essere numeri (adesso: PUID=$uid PGID=$gid)." >&2 + exit 64 + ;; +esac + +mkdir -p /data +for folder in db models research import backups logs web-keys; do + mkdir -p "/data/$folder" +done +# Only what does not already belong to PUID:PGID, so a large data folder does not slow every start. +find /data -xdev \( ! -user "$uid" -o ! -group "$gid" \) -exec chown -h "$uid:$gid" {} + +chmod 700 /data + +export HOME=/tmp +exec setpriv --reuid="$uid" --regid="$gid" --clear-groups -- dotnet "$app" "$@" diff --git a/docker-compose.yml b/docker-compose.yml index 5cb6028..db8b85a 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,5 +1,6 @@ # Development only (SPEC 3): the app plus a local PostgreSQL. Never used in production. # Start: docker compose up --build Health: curl http://localhost:8787/health +# First access at http://localhost:8787 with ANUBIS_ADMIN_PASSWORD, then choose a new password. services: anubis: build: @@ -15,6 +16,9 @@ services: ANUBIS_DB_NAME: anubis ANUBIS_DB_USER: anubis ANUBIS_DB_PASSWORD: ${ANUBIS_DB_PASSWORD:-anubis-dev} + # Development values only: a real installation chooses its own (deploy/unraid/anubis.xml). + ANUBIS_SECRET_KEY: ${ANUBIS_SECRET_KEY:-dev-only-secret-key-change-me-0123456789} + ANUBIS_ADMIN_PASSWORD: ${ANUBIS_ADMIN_PASSWORD:-dev-only-change-me} ANUBIS_ALLOW_LIVE: "0" TZ: Europe/Rome volumes: diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index b2ab7f8..e5eb4d8 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -53,30 +53,30 @@ Le basi su cui si appoggia tutto: piattaforma, database, sicurezza, guscio dell' **Lavori** -- [ ] [#7](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/7) Strato di piattaforma: configurazione d'avvio Docker e desktop, cartella dei dati, identità dell'installazione -- [ ] [#8](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/8) Database portabile PostgreSQL/SQLite: tipi, accesso ADO.NET, migrazioni SQL -- [ ] [#9](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/9) Esportazione e importazione indipendenti dal motore; salvataggi notturni e prima delle migrazioni -- [ ] [#10](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/10) Nucleo: orologio iniettabile, bus degli eventi, pianificatore, impostazioni, segreti, registri strutturati -- [ ] [#11](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/11) Accesso e sicurezza: PBKDF2, sessioni, CSRF, limite tentativi, TOTP -- [ ] [#12](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/12) Scheletro delle API REST e del WebSocket -- [ ] [#13](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/13) Guscio dell'interfaccia: menu, barra superiore, temi, token grafici, formati italiani -- [ ] [#14](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/14) Schermate di servizio: accesso, primo avvio (Docker e desktop), pagina d'errore del database, prima parte di Impostazioni -- [ ] [#15](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/15) Modalità dimostrativa con i dati dell'appendice F (`tasks seed-demo`) -- [ ] [#16](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/16) Dockerfile definitivo con entrypoint (PUID/PGID, cartella dati, healthcheck) -- [ ] [#17](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/17) Chiusura della fase, revisione indipendente e tag `fase-1` +- [x] [#7](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/7) Strato di piattaforma: configurazione d'avvio Docker e desktop, cartella dei dati, identità dell'installazione +- [x] [#8](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/8) Database portabile PostgreSQL/SQLite: tipi, accesso ADO.NET, migrazioni SQL +- [x] [#9](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/9) Esportazione e importazione indipendenti dal motore; salvataggi notturni e prima delle migrazioni +- [x] [#10](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/10) Nucleo: orologio iniettabile, bus degli eventi, pianificatore, impostazioni, segreti, registri strutturati +- [x] [#11](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/11) Accesso e sicurezza: PBKDF2, sessioni, CSRF, limite tentativi, TOTP +- [x] [#12](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/12) Scheletro delle API REST e del WebSocket +- [x] [#13](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/13) Guscio dell'interfaccia: menu, barra superiore, temi, token grafici, formati italiani +- [x] [#14](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/14) Schermate di servizio: accesso, primo avvio (Docker e desktop), pagina d'errore del database, prima parte di Impostazioni +- [x] [#15](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/15) Modalità dimostrativa con i dati dell'appendice F (`tasks seed-demo`) +- [x] [#16](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/16) Dockerfile definitivo con entrypoint (PUID/PGID, cartella dati, healthcheck) +- [x] [#17](https://gitea.encke-hake.ts.net/BalboSoft/Anubis/issues/17) Chiusura della fase, revisione indipendente e tag `fase-1` **Criteri di accettazione** -- [ ] Accesso funzionante -- [ ] Il guscio corrisponde ai mockup per menu e barra superiore a 1440 px e per barra superiore e barra in basso a 390 px (screenshot allegati) -- [ ] I formati numerici superano i test -- [ ] L'immagine si costruisce e parte con `ANUBIS_DB_ENGINE=sqlite` e con `postgres` -- [ ] Con una configurazione mancante o sbagliata compare la pagina d'errore e non nasce alcun altro database -- [ ] Staccando il database compare la pagina d'errore e al ritorno l'applicazione riprende da sola -- [ ] La stessa batteria di test passa su entrambi i motori -- [ ] Un archivio esportato da un motore e importato nell'altro dà gli stessi conteggi -- [ ] Con la configurazione desktop il server parte da una cartella dei dati vuota e la chiave dei segreti non finisce in `config.toml` -- [ ] La modalità dimostrativa non tocca il database configurato (test) +- [x] Accesso funzionante +- [x] Il guscio corrisponde ai mockup per menu e barra superiore a 1440 px e per barra superiore e barra in basso a 390 px (screenshot allegati) +- [x] I formati numerici superano i test +- [x] L'immagine si costruisce e parte con `ANUBIS_DB_ENGINE=sqlite` e con `postgres` +- [x] Con una configurazione mancante o sbagliata compare la pagina d'errore e non nasce alcun altro database +- [x] Staccando il database compare la pagina d'errore e al ritorno l'applicazione riprende da sola +- [x] La stessa batteria di test passa su entrambi i motori +- [x] Un archivio esportato da un motore e importato nell'altro dà gli stessi conteggi +- [x] Con la configurazione desktop il server parte da una cartella dei dati vuota e la chiave dei segreti non finisce in `config.toml` +- [x] La modalità dimostrativa non tocca il database configurato (test) ## Fase 2 — Dati di mercato diff --git a/docs/STATE.md b/docs/STATE.md index 5eda458..adf296b 100644 --- a/docs/STATE.md +++ b/docs/STATE.md @@ -4,7 +4,7 @@ Aggiornato: 2026-11-10 ## Fase corrente -**Fase 0 — Preparazione: completata.** La prossima è la Fase 1 (Fondamenta), da iniziare con il via dell'utente. +**Fase 1 — Fondamenta: completata.** La prossima è la Fase 2 (Dati di mercato), da iniziare con il via dell'utente. ## Fatto @@ -34,6 +34,16 @@ Aggiornato: 2026-11-10 - `/health`. - Applicazione minima con `GET /health`, `Dockerfile` e `docker-compose.yml` con PostgreSQL 18. - CI in `.gitea/workflows/ci.yml`: test su SQLite e PostgreSQL, poi l'immagine. Solo passi `run:`. +- **Fase 1** (scelte nell'ADR 0007): + - Piattaforma: configurazione d'avvio Docker (variabili) e desktop (`config.toml`), cartella dei dati, identità dell'installazione con impronta del database, custodia della chiave dei segreti (DPAPI su Windows). + - Database portabile su PostgreSQL e SQLite con ADO.NET: un solo schema con tipi per motore, migrazioni SQL numerate con salvataggio prima, esportazione e importazione tra motori con controllo di conteggi e totali (`Anubis.Server db export|import`), salvataggi notturni (ne tiene 14). + - Nucleo: orologio iniettabile, bus degli eventi, pianificatore, impostazioni con registro delle modifiche, segreti cifrati AES-GCM, registri JSON con i segreti oscurati, formati italiani. + - Accesso: password PBKDF2, sessioni, CSRF, limite ai tentativi, secondo fattore TOTP facoltativo. + - Server: avvio a stati (configurazione, primo avvio, database assente, schema, identità, pronto), pagina d'errore con riprova automatica, API REST e WebSocket dello stato. + - Interfaccia: guscio di menu, barra superiore e barra in basso come nei mockup, temi chiaro e scuro, Panoramica, Diario, Rischio, Impostazioni (aspetto, sicurezza, sistema); le altre voci arrivano con le loro fasi. + - Modalità dimostrativa (`tasks seed-demo`) con i dati dell'appendice F, in un database a parte. + - Immagine Docker definitiva: `PUID`/`PGID`, controllo di salute, l'applicazione non gira come root. Provata con SQLite, PostgreSQL, configurazione sbagliata e database staccato. + - `tasks screenshots` per confrontare le schermate con i mockup. ## In corso @@ -41,11 +51,13 @@ Nulla. ## Prossimo passo -Fase 1, issue #7–#13: piattaforma, database portabile, salvataggi, nucleo, accesso, guscio dell'interfaccia. +Fase 2, dati di mercato: storico e dati dal vivo, controlli di qualità, cambi del giorno. Servono le chiavi del conto paper di Alpaca (vedi sotto); senza, la parte azionaria si prova su dati sintetici. ## Da sapere - Le immagini .NET 10 sono su Ubuntu 24.04, non Debian (ADR 0006). +- La modalità dimostrativa mostra solo le parti già costruite: conti, posizioni, strategie e notizie della Panoramica arrivano con le loro fasi. +- `tasks dev` fuori da Docker usa la cartella dei dati vera dell'utente: per prove usa `tasks seed-demo`. - Alpaca non ha più conti senza margine: il divieto di leva lo impone Anubis (API-NOTES A14). - OKX: WebSocket sulla porta 443, la 8443 è chiusa (API-NOTES O3). - Gitea ha un esecutore delle Actions attivo: la CI gira a ogni push (prima esecuzione: run 169 del branch `fase-0`, test verdi su SQLite e PostgreSQL). `tasks ci` resta per provarla in locale. @@ -55,7 +67,8 @@ Fase 1, issue #7–#13: piattaforma, database portabile, salvataggi, nucleo, acc | Cosa | Da quando serve | Senza | |---|---|---| -| Via libera per la Fase 1 | Subito | Non si parte | +| Via libera per la Fase 2 | Subito | Non si parte | +| Permesso di scaricare il carattere Instrument Sans (licenza SIL OFL, già ammesso dall'ADR 0004) | Quando vuoi | L'interfaccia usa i caratteri di sistema | | Chiavi del conto paper di Alpaca | Fase 2 (dati azionari) | La parte azionaria si prova su dati sintetici; criteri in attesa | | Chiavi demo di OKX Europe | Fase 3 (ordini sui conti di prova) | Batteria di conformità su risposte d'esempio; criteri in attesa | | Un token Gitea con permesso `write:package` come segreto `REGISTRY_TOKEN` | Fase 9 (pubblicazione dell'immagine) | Pubblicazione a mano | diff --git a/docs/adr/0004-componenti-esterni.md b/docs/adr/0004-componenti-esterni.md index 7e6b6e5..1667079 100644 --- a/docs/adr/0004-componenti-esterni.md +++ b/docs/adr/0004-componenti-esterni.md @@ -1,6 +1,6 @@ # 0004 — Nessun SDK o componente esterno senza il permesso dell'utente -Data: 2026-11-09 · Stato: accettata · Precisata dall'ADR 0006 (MSTest tramite i suoi pacchetti di base; `libgomp1` nella Fase 8) +Data: 2026-11-09 · Stato: accettata · Precisata dagli ADR 0006 (MSTest tramite i suoi pacchetti di base; `libgomp1` nella Fase 8) e 0007 (`ProtectedData` dalla Fase 1; carattere di sistema finché Instrument Sans non è scaricato) ## Contesto diff --git a/docs/adr/0007-scelte-fase-1.md b/docs/adr/0007-scelte-fase-1.md new file mode 100644 index 0000000..ec63751 --- /dev/null +++ b/docs/adr/0007-scelte-fase-1.md @@ -0,0 +1,101 @@ +# 0007 — Scelte della Fase 1: database portabile, interfaccia, immagine Docker + +Data: 2026-11-10 · Stato: accettata · Precisa gli ADR 0003, 0004 e 0006, senza aggiungere componenti esterni + +## Contesto + +La Fase 1 costruisce le fondamenta: piattaforma, database su due motori, accesso, guscio dell'interfaccia, modalità dimostrativa e immagine Docker. Alcune scelte non sono scritte nella specifica, o la precisano. Le raccolgo qui. + +## Decisione + +**1. Un solo schema per i due motori.** +- Le migrazioni sono file SQL numerati (`src/Anubis/Db/Migrations`). Lo stesso testo gira su PostgreSQL e SQLite. Le parole tra graffe diventano i tipi del motore: + +| Segno | PostgreSQL | SQLite | +|---|---|---| +| `{money}` | `NUMERIC(38,18)` | `TEXT` in forma canonica, arrotondato a 18 decimali | +| `{timestamp}` | `TIMESTAMPTZ` | `TEXT` ISO 8601 in UTC | +| `{uuid}` | `UUID` | `TEXT` | +| `{bool}`, `{bytes}`, `{json}`, `{float}` | `BOOLEAN`, `BYTEA`, `JSON`, `DOUBLE PRECISION` | `INTEGER`, `BLOB`, `TEXT`, `REAL` | + +- Su SQLite le tabelle sono `STRICT` e il database lavora con WAL, `synchronous=FULL` e chiavi esterne attive. +- Il denaro passa sempre come `decimal` e non è mai `REAL`. `{float}` serve solo a misure che non sono importi. +- Lo schema 1 contiene le tabelle che servono adesso e quelle contabili che la modalità dimostrativa riempie (conti, ordini, eseguiti, lotti, liquidità, posizioni, patrimonio, diario, rischio). Le tabelle delle fasi successive (barre, notizie, modelli, prove storiche, segnali) arrivano ciascuna con la propria migrazione. +- Prima di ogni migrazione si fa un salvataggio. +- I limiti di SQLite restano quelli della specifica: un solo processo scrive, e il file deve stare su un disco locale. + +**2. Il database non si ricrea da solo.** +- Un file SQLite già visto che sparisce, mentre l'applicazione gira, è un errore. Non si crea un database nuovo e vuoto al suo posto: compare la pagina d'errore finché il file non torna. +- All'avvio il file si crea solo se nella cartella dei dati manca `installation.json`, cioè alla prima installazione. + +**3. Password con PBKDF2, secondo fattore senza codice QR.** +- Le password si cifrano con PBKDF2-SHA512 (ADR 0003). +- Per il secondo fattore l'interfaccia mostra la chiave in base32 e l'indirizzo `otpauth://`. Non disegna un codice QR, che richiederebbe una libreria esterna o un generatore scritto in casa. Le app di autenticazione accettano la chiave scritta a mano. +- La chiave in prova resta sul server, legata alla sessione, per 15 minuti. Non passa mai nell'indirizzo della pagina. + +**4. Interfaccia con rendering statico.** +- Le pagine Blazor sono generate sul server e arrivano come HTML semplice. Niente modalità interattiva e niente `blazor.web.js`: per questo il progetto del server imposta `RequiresAspNetWebAssets=false`, e il pacchetto `Microsoft.AspNetCore.App.Internal.Assets` non entra. +- I pulsanti sono moduli HTML che inviano ad `/azioni/*`, con il gettone CSRF. La risposta riporta alla pagina (post/redirect/get). Gli errori tornano come codici brevi, mai con i valori scritti dall'utente. +- Lo stato dal vivo (bot, freschezza dei dati) arriva da un WebSocket su `/ws`, letto da un piccolo `app.js`. +- Fogli di stile, script e logo sono risorse incluse nella DLL. Il logo arriva solo da `docs/design/logo` (ADR 0005). +- Le chiavi dei gettoni dei moduli stanno in `web-keys/`, nella cartella dei dati, così un riavvio non rompe le pagine aperte. Sono salvate senza cifratura, ma la cartella dei dati è leggibile solo dall'utente dell'applicazione. + +**5. Carattere di sistema, per ora.** L'ADR 0004 ammette Instrument Sans incluso nell'applicazione. Scaricarlo richiede il permesso dell'utente. Finché non arriva, il foglio di stile lo nomina per primo e ripiega sui caratteri di sistema (Segoe UI su Windows, il sans-serif di sistema altrove). + +**6. Modalità dimostrativa.** +- `--demo` crea una cartella dei dati nuova in quella temporanea, con un database SQLite proprio, e non legge mai la configurazione vera. +- La modalità dimostrativa: + - usa un orologio fermo al 9 ottobre 2026, 08:21; + - risponde solo dal computer stesso; + - accede da sola; + - tiene la chiave dei segreti in un file della propria cartella, per non toccare il portachiavi di Windows. +- Carica i dati dell'appendice F solo nelle tabelle che esistono già. Strategie, notizie e apprendimento compaiono quando arrivano le loro fasi. +- Gli importi in dollari si mostrano solo qui, con il cambio dei dati d'esempio. Nell'uso vero restano in euro finché la Fase 2 non porta i cambi del giorno. + +**7. Custodia della chiave su desktop dalla Fase 1.** `System.Security.Cryptography.ProtectedData` (già nell'ADR 0004) entra adesso e non nella Fase 10: la chiave dei segreti va custodita da quando nasce lo strato di piattaforma. + +**8. Immagine Docker.** +- Il container parte come root solo per preparare `/data` e darla a `PUID:PGID` (99:100 su Unraid). Poi l'applicazione gira con quell'utente tramite `setpriv`, che è già nell'immagine di base. Niente `gosu`. +- Il controllo di salute usa `/dev/tcp` di bash su `/health`, perché nell'immagine non ci sono `curl` né `wget`. Un 503 (database che non risponde) conta come container non sano. +- `libgomp1` resta rimandata alla Fase 8 (ADR 0006). + +**9. Fotografie con il browser già installato.** +- `tasks screenshots` usa Edge o Chrome già presenti sul computer e li guida con il protocollo DevTools, attraverso il `ClientWebSocket` di .NET. Niente Playwright (ADR 0004). +- Il protocollo serve per fissare la larghezza esatta: una finestra senza schermo non scende sotto i 500 pixel circa, troppi per il telefono a 390. + +**10. Correzioni della revisione indipendente.** +- **Indirizzo di ritorno.** Dopo l'accesso si torna solo a un percorso del sito. Sono esclusi i percorsi con barre rovesciate o caratteri di controllo, perché il browser li toglie e `/␉/altro.sito` diventerebbe `//altro.sito`. +- **Solo dal computer.** Desktop e modalità dimostrativa controllano due cose: l'indirizzo di chi chiama e il nome con cui chiama. Sono ammessi solo `localhost`, `127.0.0.1` e `[::1]`. Così una pagina web che fa puntare il proprio nome a 127.0.0.1 (DNS rebinding) non arriva alla procedura guidata né alle scelte della pagina d'errore. +- **Limite ai tentativi.** + - Ogni tentativo si conta prima di controllare la password, così tentativi in parallelo non passano tutti. + - Lo stesso limite vale per la password della configurazione d'avvio chiesta dalla pagina d'errore. +- **Secondo fattore.** + - Ogni codice vale una volta sola. Il registro sta in memoria: un riavvio lo azzera, ma il codice scade comunque entro 90 secondi. + - Per disattivare il secondo fattore servono la password e un codice. +- **Pagina d'errore e ciclo d'avvio.** + - Una scelta (ripristina, importa, comincia da capo, usa questo) tiene fermo il ciclo d'avvio finché non ha finito, rinnovo dell'identità compreso. + - L'identità si controlla prima di migrare. Un database che appartiene a un'altra installazione non viene toccato. Uno vuoto resta vuoto, quindi accoglie anche un salvataggio con uno schema più vecchio. + - Dopo un ripristino, un'importazione o "usa questo database", il bot riparte con "Ferma tutto" acceso (SPEC 15.1), qualunque cosa dicesse l'archivio. + - Un archivio rovinato dà un messaggio sulla pagina, non un errore del server. +- **Pagine che leggono prima di disegnare.** + - Con il rendering statico Blazor disegna una prima volta mentre `OnInitializedAsync` aspetta ancora. + - Con SQLite le letture finiscono subito e il difetto non si vede. Con PostgreSQL la pagina si rompe. + - I componenti che leggono dati ereditano da `LoadedComponent` (o `LoadedLayout`): prima leggono, poi disegnano una volta sola. + - I test del server ora girano anche su PostgreSQL. +- **Docker con SQLite e `/data` non collegata.** + - Docker crea un volume anonimo senza `installation.json`, quindi parte un'installazione nuova e vuota. Non si può distinguere da una prima installazione vera. + - Il manuale (Fase 9) dirà di controllare la riga "Cartella dei dati" in Impostazioni. + +## Alternative scartate + +- **Tipi diversi per motore scritti a mano in due serie di migrazioni.** Raddoppia il lavoro e lascia divergere i due schemi. +- **Blazor interattivo sul server (SignalR).** Una connessione sempre aperta per ogni pagina, più JavaScript del framework, e pagine che smettono di funzionare quando la connessione cade. I moduli semplici funzionano anche senza script. +- **Un generatore di codici QR scritto in casa.** È molto codice per un passo che si fa una volta sola. +- **Chiedere il pacchetto Playwright.** Il browser già installato fa lo stesso lavoro. + +## Conseguenze + +- Ogni fase che aggiunge tabelle scrive una nuova migrazione con gli stessi segni, e la prova su entrambi i motori. +- Quando l'utente dà il permesso di scaricare Instrument Sans, i file vanno in `src/Anubis.Server/Assets/` e nel foglio di stile. +- Chi apre la modalità dimostrativa vede solo le parti costruite fino a quella fase. +- Il WebSocket dello stato non si chiude quando si esce: manda solo lo stato del bot e la freschezza dei dati, e si chiude alla prima riconnessione. Da rivedere quando porterà dati più ricchi. diff --git a/src/Anubis.Server/Anubis.Server.csproj b/src/Anubis.Server/Anubis.Server.csproj index 890fc6d..3f11b0c 100644 --- a/src/Anubis.Server/Anubis.Server.csproj +++ b/src/Anubis.Server/Anubis.Server.csproj @@ -2,6 +2,8 @@ Anubis.Server false + + false @@ -9,4 +11,10 @@ + + + + + + diff --git a/src/Anubis.Server/AnubisHost.cs b/src/Anubis.Server/AnubisHost.cs new file mode 100644 index 0000000..ada7fda --- /dev/null +++ b/src/Anubis.Server/AnubisHost.cs @@ -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, + + /// The startup configuration is missing or wrong: the error page lists what to fix. + ConfigProblem, + + /// Desktop without config.toml, or without a user yet: the first-run wizard. + FirstRun, + + /// The configured database does not answer: error page, retry, never another database (trap 20). + DatabaseUnavailable, + + /// The database schema is newer than this version or was altered. + SchemaProblem, + + /// Database and data folder do not belong together (SPEC 15.1): the user chooses. + IdentityProblem, + + Ready, +} + +public sealed record HostStatus(HostMode Mode, string? Detail, IdentityCheck? Identity, DateTimeOffset Since, int Attempts); + +/// Published on the bus whenever the host changes mode. +internal sealed record HostChanged(HostMode Mode); + +/// Everything that needs the database, built once it is reachable and the installation checks out. +internal sealed record AppServices(Database Db, SettingsStore Settings, SecretStore Secrets, AccessStore Access, Backups Backups, Scheduler Scheduler); + +/// +/// 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. +/// +internal sealed partial class AnubisHost( + ServerOptions options, + StartupConfig initialConfig, + IReadOnlyDictionary environment, + IClock clock, + EventBus bus, + ILogger 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; + + /// The running services; null until the first successful start. + public AppServices? Services => _status.Mode == HostMode.Ready ? _services : null; + + /// Desktop first run: the password chosen in the wizard, used once the database is ready. + public string? PendingPassword { get; set; } + + public int PasswordIterations => overrides?.PasswordIterations ?? Passwords.DefaultIterations; + + /// Asks the loop to check again now (after the wizard or an error-page choice). + public void Wake() + { + lock (_gate) + { + _wake.TrySetResult(); + } + } + + /// Waits until the host reaches ; for tests and the CLI. + 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); + } + } + + /// Last time the database answered: the "Dati aggiornati" of the top bar. + public DateTimeOffset? LastCheckUtc { get; private set; } + + /// The scheduler loop is alive (health check). + public bool SchedulerRunning => _schedulerLoop is { IsCompleted: false }; + + /// The database even when not ready (error-page choices need it to restore or import). + internal Database? Database => _db; + + /// Holds the loop still while an error-page choice works on the database. + internal async Task 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 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); + } + + /// After an error-page choice changed the database: forget the services so the next step starts over. + 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(); + 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 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 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); +} diff --git a/src/Anubis.Server/Assets/app.css b/src/Anubis.Server/Assets/app.css new file mode 100644 index 0000000..8fa9166 --- /dev/null +++ b/src/Anubis.Server/Assets/app.css @@ -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; } +} diff --git a/src/Anubis.Server/Assets/app.js b/src/Anubis.Server/Assets/app.js new file mode 100644 index 0000000..8915f31 --- /dev/null +++ b/src/Anubis.Server/Assets/app.js @@ -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); +})(); diff --git a/src/Anubis.Server/Assets/early.js b/src/Anubis.Server/Assets/early.js new file mode 100644 index 0000000..7a271ac --- /dev/null +++ b/src/Anubis.Server/Assets/early.js @@ -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. + } +})(); diff --git a/src/Anubis.Server/Components/AdminPassword.razor b/src/Anubis.Server/Components/AdminPassword.razor new file mode 100644 index 0000000..0cabc9f --- /dev/null +++ b/src/Anubis.Server/Components/AdminPassword.razor @@ -0,0 +1,12 @@ +@if (Docker) +{ + + +} + +@code { + private readonly string _id = "admin-" + Guid.NewGuid().ToString("N")[..6]; + + [Parameter] + public bool Docker { get; set; } +} diff --git a/src/Anubis.Server/Components/App.razor b/src/Anubis.Server/Components/App.razor new file mode 100644 index 0000000..42066d3 --- /dev/null +++ b/src/Anubis.Server/Components/App.razor @@ -0,0 +1,28 @@ +@inherits LoadedComponent +@inject ShellData Shell + + + + + + + + + + + + + + + + + +@code { + private string? _theme; + + protected override async Task LoadAsync() + { + var snapshot = await Shell.SnapshotAsync(CancellationToken.None); + _theme = snapshot.Theme == "auto" ? null : snapshot.Theme; + } +} diff --git a/src/Anubis.Server/Components/Arrow.razor b/src/Anubis.Server/Components/Arrow.razor new file mode 100644 index 0000000..5fb807c --- /dev/null +++ b/src/Anubis.Server/Components/Arrow.razor @@ -0,0 +1,16 @@ +@* A small filled triangle: the direction is never told by colour alone (SPEC 13.2). *@ + + +@code { + [Parameter] + public bool Up { get; set; } +} diff --git a/src/Anubis.Server/Components/EquityChart.razor b/src/Anubis.Server/Components/EquityChart.razor new file mode 100644 index 0000000..7d32e9c --- /dev/null +++ b/src/Anubis.Server/Components/EquityChart.razor @@ -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()).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]; +
+
+ +
+ + @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; + + @Shell.Money(Points[^1].Benchmark!.Value, Currency, decimals: 0) + } + + @Shell.Money(Points[^1].Equity, Currency, decimals: 0) +
+
+
+ Con Anubis + @if (benchLine.Length > 0) + { + Senza bot: Bitcoin e S&P 500 comprati e tenuti + } +
+
+ Vedi i numeri in una tabella +
+ + + + @foreach (var p in Points.AsEnumerable().Reverse()) + { + + } + +
GiornoCon il botSenza bot
@Format.LongDate(p.Day)@Shell.Money(p.Equity, Currency)@(p.Benchmark is { } b ? Shell.Money(b, Currency) : "—")
+
+
+
+} + +@code { + [Parameter, EditorRequired] + public IReadOnlyList 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); + } +} diff --git a/src/Anubis.Server/Components/Icon.razor b/src/Anubis.Server/Components/Icon.razor new file mode 100644 index 0000000..6217352 --- /dev/null +++ b/src/Anubis.Server/Components/Icon.razor @@ -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. *@ + + +@code { + [Parameter, EditorRequired] + public string Name { get; set; } = ""; + + [Parameter] + public int Size { get; set; } = 20; + + [Parameter] + public string? Class { get; set; } +} diff --git a/src/Anubis.Server/Components/IdentityChoices.razor b/src/Anubis.Server/Components/IdentityChoices.razor new file mode 100644 index 0000000..10f9076 --- /dev/null +++ b/src/Anubis.Server/Components/IdentityChoices.razor @@ -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: +

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.

+ break; + case IdentityVerdict.DifferentInstallation: +

Il database appartiene a un'altra installazione di Anubis. Il motore resta spento: due registri sugli stessi conti produrrebbero ordini doppi.

+ break; + case IdentityVerdict.StaleDatabase: +

È 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.

+ break; +} + +
+
Database
@Host.Config.Db?.Describe()
+
Cartella dei dati
@data.Root
+ @if (Status.Identity.File is { } file) + { +
Installazione della cartella
@file.InstallationId.ToString("D")[..8], nata il @Format.ShortDate(file.CreatedAt, Clock.UtcNow, Host.Config.TimeZone, withTime: false)
+ } + @if (Status.Identity.Row is { } row) + { +
Installazione del database
@row.Id.ToString("D")[..8], nata il @Format.ShortDate(row.CreatedAt, Clock.UtcNow, Host.Config.TimeZone, withTime: false)
+ } +
+ +

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.

+ +@if (!canChoose) +{ +

Queste scelte si fanno solo dal computer su cui gira Anubis.

+} +else +{ + @if (verdict == IdentityVerdict.EmptyDatabase) + { + var backups = new Backups(data, Clock).List(); + var imports = ServiceChoices.ImportFolders(data); +
+

Ripristina un salvataggio

+ @if (backups.Count == 0) + { +

Nessun salvataggio nella cartella @data.Backups.

+ } + else + { +
+ + + + + + + } +
+
+

Importa un archivio

+ @if (imports.Count == 0) + { +

Metti la cartella di un archivio esportato (con il suo index.json) dentro @data.Import e ricarica la pagina.

+ } + else + { +
+ + + + + + + } +
+
+

Comincia da capo

+

Una nuova installazione in questo database vuoto. Il file d'identità della cartella viene messo da parte, non cancellato.

+
+ + + + +
+ } + else + { +
+

Usa comunque questo database

+

Diventa il database di questa installazione con una nuova impronta. Ogni altra copia non verrà più accettata. Il bot riparte protetto.

+
+ + + + +
+ } +} + +@code { + [Parameter, EditorRequired] + public HostStatus Status { get; set; } = null!; + + [Parameter] + public bool Local { get; set; } +} diff --git a/src/Anubis.Server/Components/Layout/MainLayout.razor b/src/Anubis.Server/Components/Layout/MainLayout.razor new file mode 100644 index 0000000..1ee222a --- /dev/null +++ b/src/Anubis.Server/Components/Layout/MainLayout.razor @@ -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. *@ +
+ + +
+
+
+ + + + Anubis + + @_shell.BotShort +

@Menu.Title(_path)

+

+ @_shell.Now. Dati aggiornati @Format.Ago(TimeSpan.FromSeconds(_shell.AgeSeconds)). +

+
+
+ @_shell.BotLabel + Simulazione: nessun soldo reale +
+ + + + + + + + @if (_shell.Bot == "paused") + { +
+ } + else if (_shell.Bot == "active") + { +
+ } +
+
+
+
Simulazione: nessun soldo reale
+ + +
+ @Body +
+ @if (Shell.IsDemo) + { +

Modalità dimostrativa. Numeri, titoli e notizie sono dati di esempio.

+ } + else + { +

Anubis @AnubisInfo.Version

+ } +
+
+
+ + +
+ +@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); +} diff --git a/src/Anubis.Server/Components/Layout/ServiceLayout.razor b/src/Anubis.Server/Components/Layout/ServiceLayout.razor new file mode 100644 index 0000000..ce72231 --- /dev/null +++ b/src/Anubis.Server/Components/Layout/ServiceLayout.razor @@ -0,0 +1,15 @@ +@inherits LayoutComponentBase +@inject ShellData Shell + +@* Pages outside the shell: sign-in, first run, first access, error page. *@ +
+
+
+ + + Anubis +
+ @Body +

Anubis @AnubisInfo.Version@(Shell.IsDemo ? " · modalità dimostrativa" : "")

+
+
diff --git a/src/Anubis.Server/Components/Loaded.cs b/src/Anubis.Server/Components/Loaded.cs new file mode 100644 index 0000000..b5d9a6d --- /dev/null +++ b/src/Anubis.Server/Components/Loaded.cs @@ -0,0 +1,49 @@ +using Microsoft.AspNetCore.Components; + +namespace Anubis.Server.Components; + +/// +/// A component that reads its data before drawing anything. With static rendering, a plain OnInitializedAsync +/// 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. +/// +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); + } + + /// Reads what the component shows. Parameters, cascading values and query values are already set. + protected abstract Task LoadAsync(); +} + +/// The same for the layout. +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); + } + + /// + protected abstract Task LoadAsync(); +} diff --git a/src/Anubis.Server/Components/Menu.cs b/src/Anubis.Server/Components/Menu.cs new file mode 100644 index 0000000..e55febf --- /dev/null +++ b/src/Anubis.Server/Components/Menu.cs @@ -0,0 +1,39 @@ +namespace Anubis.Server.Components; + +internal sealed record MenuItem(string Path, string Label, string Icon, string Title); + +/// The screens of SPEC 13.6 in the order of the mockups. +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> Groups = + [ + [Overview, Accounts, Trades], + [Strategies, News, Learning], + [Risk, Journal, Lab, Settings], + ]; + + /// The bottom bar of the phone (SPEC 13.4). + public static readonly IReadOnlyList 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"; +} diff --git a/src/Anubis.Server/Components/Pages/Accesso.razor b/src/Anubis.Server/Components/Pages/Accesso.razor new file mode 100644 index 0000000..d628729 --- /dev/null +++ b/src/Anubis.Server/Components/Pages/Accesso.razor @@ -0,0 +1,46 @@ +@page "/accesso" +@layout ServiceLayout +@attribute [AllowAnonymous] + +Accesso · Anubis + +

Accedi

+@if (Message is { } message) +{ + +} +
+ + + + + @if (Fattore == "1") + { + + +

Sei cifre, cambiano ogni 30 secondi. Scrivi di nuovo anche la password.

+ } + + + +@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, + }; +} diff --git a/src/Anubis.Server/Components/Pages/Altro.razor b/src/Anubis.Server/Components/Pages/Altro.razor new file mode 100644 index 0000000..77c9198 --- /dev/null +++ b/src/Anubis.Server/Components/Pages/Altro.razor @@ -0,0 +1,44 @@ +@inherits LoadedComponent +@page "/altro" +@inject ShellData Shell + +Altro · Anubis + +@* On the phone: the screens that do not fit the bottom bar, the pause and the currency (SPEC 13.4). *@ +
+
    + @foreach (var item in Menu.Groups.SelectMany(g => g).Where(i => !Menu.Phone.Any(p => p.Path == i.Path))) + { +
  • @item.Label
  • + } +
+
+
+

Comandi

+
+ @if (_shell.Bot == "active") + { +
+ } + else if (_shell.Bot == "paused") + { +
+ } +
+ + + + + + @if (!Shell.IsDemo) + { +
+ } +
+
+ +@code { + private ShellSnapshot _shell = null!; + + protected override async Task LoadAsync() => _shell = await Shell.SnapshotAsync(CancellationToken.None); +} diff --git a/src/Anubis.Server/Components/Pages/Apprendimento.razor b/src/Anubis.Server/Components/Pages/Apprendimento.razor new file mode 100644 index 0000000..7dd9820 --- /dev/null +++ b/src/Anubis.Server/Components/Pages/Apprendimento.razor @@ -0,0 +1,5 @@ +@page "/apprendimento" + +Apprendimento · Anubis + +Comincia a imparare quando ci sono abbastanza segnali: qui vedrai quanti ne mancano e quanto è preciso su casi mai visti. diff --git a/src/Anubis.Server/Components/Pages/Conti.razor b/src/Anubis.Server/Components/Pages/Conti.razor new file mode 100644 index 0000000..e171572 --- /dev/null +++ b/src/Anubis.Server/Components/Pages/Conti.razor @@ -0,0 +1,5 @@ +@page "/conti" + +Conti e posizioni · Anubis + +Conti, posizioni e ordini arrivano con la contabilità: lì aggiungerai le chiavi dei conti di prova e vedrai patrimonio, liquidità e commissioni di ciascuno. diff --git a/src/Anubis.Server/Components/Pages/Diario.razor b/src/Anubis.Server/Components/Pages/Diario.razor new file mode 100644 index 0000000..280efa1 --- /dev/null +++ b/src/Anubis.Server/Components/Pages/Diario.razor @@ -0,0 +1,90 @@ +@inherits LoadedComponent +@page "/diario" +@inject AnubisHost Host +@inject ShellData Shell + +Diario e sistema · Anubis + +
+
+

Diario

+ @if (_entries.Count == 0) + { +

Ancora nessuna voce.

+ } + else + { +
+ + + + @foreach (var e in _entries) + { + + } + +
QuandoTipoVoce
@Format.ShortDate(e.At, Shell.Now, Shell.Zone)@e.Kind@e.Text
+
+ } +
+
+

Sistema

+
+
Versione
@AnubisInfo.Version
+
Piattaforma
@(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop")
+
Database
@(Host.Config.Db?.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite") · risponde
+
In funzione da
@Format.Ago(Shell.Now - _since).Replace(" fa", "", StringComparison.Ordinal)
+
+

Lavori in programma

+
    + @foreach (var job in _upcoming) + { +
  • @Format.ShortDate(job.DueUtc, Shell.Now, Shell.Zone)@job.Description
  • + } +
+ @if (_jobs.Count > 0) + { +

Ultimi lavori

+
    + @foreach (var job in _jobs) + { +
  • @(job.Finished is { } f ? Format.ShortDate(f, Shell.Now, Shell.Zone) : "—")@job.Description: @Outcome(job.Outcome)
  • + } +
+ } +
+
+ +@code { + private List<(DateTimeOffset At, string Kind, string Text)> _entries = []; + private List<(string Description, DateTimeOffset? Finished, string? Outcome)> _jobs = []; + private IReadOnlyList _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", + }; +} diff --git a/src/Anubis.Server/Components/Pages/Impostazioni.razor b/src/Anubis.Server/Components/Pages/Impostazioni.razor new file mode 100644 index 0000000..99ce779 --- /dev/null +++ b/src/Anubis.Server/Components/Pages/Impostazioni.razor @@ -0,0 +1,230 @@ +@inherits LoadedComponent +@page "/impostazioni" +@inject AnubisHost Host +@inject ShellData Shell +@inject SecondFactorDrafts Drafts + +Impostazioni · Anubis + +@* First part of SPEC 13.5: appearance, security, system. The other sections arrive with their phases. *@ +@if (Ok is { } ok) +{ +

@(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.", + })

+} +@if (ErrorText is { } error) +{ + +} + + + +
+

Aspetto

+ @foreach (var setting in _appearance) + { + var definition = SettingsStore.Definition(setting.Key); +
+ + + + + @if (setting.ReadOnly) + { + Fissato da @setting.Source: si cambia lì. + } + else + { + + } + + } +

Gli importi in dollari usano il cambio del giorno, che arriva con i dati di mercato. Fino ad allora restano in euro.

+
+ +
+

Sicurezza

+ @if (Shell.IsDemo) + { +

Nella modalità dimostrativa password e secondo fattore non si cambiano.

+ } + else + { +

Password

+
+ + + + + + + + + + +

Secondo fattore

+ @if (_hasSecondFactor) + { +

Attivo: all'accesso chiedo anche il codice dell'app. Servirà anche per attivare i soldi veri.

+
+ + + + + + + + } + else + { +

Facoltativo: un codice di sei cifre da un'app di autenticazione (per esempio quella del tuo gestore di password), oltre alla password.

+
    +
  1. Nell'app scegli "aggiungi con chiave" e scrivi questa chiave: @_draft
  2. +
  3. Oppure, se l'app accetta un indirizzo, usa: @_draftUri
  4. +
  5. Scrivi qui il codice che l'app mostra.
  6. +
+
+ + + + + + } +
+ } +
+ +
+

Sistema

+
+
Piattaforma
@(Host.Config.Platform == PlatformKind.Docker ? "Docker" : "Desktop (Windows)")
+
Database
@Host.Config.Db?.Describe()
+
Cartella dei dati
@Host.Config.Data.Root
+
Chiave dei segreti
@Host.Config.SecretKey.Description
+
Fuso orario
@Host.Config.TimeZone.Id
+
Versione
@AnubisInfo.Version
+
+

+ @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. + } +

+ +

Salvataggi

+

Ogni notte alle 03:30 e prima di ogni aggiornamento dello schema. Tengo gli ultimi @Backups.Keep.

+
+ @if (_backups.Count > 0) + { +
+ + + + @foreach (var b in _backups) + { + + } + +
QuandoPerchéCartella
@Format.ShortDate(b.TakenAt, Shell.Now, Shell.Zone)@b.Reason@b.Name
+
+ } +
+ +
+

Registro delle modifiche

+ @if (_history.Count == 0) + { +

Nessuna modifica finora.

+ } + else + { +
+ + + + @foreach (var h in _history) + { + + } + +
QuandoVocePrimaDopoChi
@Format.ShortDate(h.At, Shell.Now, Shell.Zone)@h.Key@Label(h.OldValue)@Label(h.NewValue)@h.ChangedBy
+
+ } +
+ +@code { + private readonly List _appearance = []; + private List _history = []; + private IReadOnlyList _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('"'), + }; +} diff --git a/src/Anubis.Server/Components/Pages/Laboratorio.razor b/src/Anubis.Server/Components/Pages/Laboratorio.razor new file mode 100644 index 0000000..de56aad --- /dev/null +++ b/src/Anubis.Server/Components/Pages/Laboratorio.razor @@ -0,0 +1,5 @@ +@page "/laboratorio" + +Laboratorio · Anubis + +Il laboratorio dei test sul passato arriva con il motore dei backtest. diff --git a/src/Anubis.Server/Components/Pages/Notizie.razor b/src/Anubis.Server/Components/Pages/Notizie.razor new file mode 100644 index 0000000..30189c8 --- /dev/null +++ b/src/Anubis.Server/Components/Pages/Notizie.razor @@ -0,0 +1,5 @@ +@page "/notizie" + +Notizie e mercato · Anubis + +La lettura delle notizie, l'umore del mercato e il calendario degli eventi arrivano in una fase successiva. diff --git a/src/Anubis.Server/Components/Pages/Operazioni.razor b/src/Anubis.Server/Components/Pages/Operazioni.razor new file mode 100644 index 0000000..12359a1 --- /dev/null +++ b/src/Anubis.Server/Components/Pages/Operazioni.razor @@ -0,0 +1,5 @@ +@page "/operazioni" + +Operazioni · Anubis + +Quando il bot comincerà a lavorare, qui troverai ogni operazione con il suo risultato e il perché di ogni ingresso e uscita. diff --git a/src/Anubis.Server/Components/Pages/Panoramica.razor b/src/Anubis.Server/Components/Pages/Panoramica.razor new file mode 100644 index 0000000..b6cf335 --- /dev/null +++ b/src/Anubis.Server/Components/Pages/Panoramica.razor @@ -0,0 +1,134 @@ +@inherits LoadedComponent +@page "/" +@inject AnubisHost Host +@inject ShellData Shell + +Panoramica · Anubis + +@{ + var o = _overview; + var c = _currency; +} +
+
+
+

Finora

+ @if (o.HasData) + { + + } +
+ @if (!o.HasData) + { +
+

Ancora nessun risultato da mostrare.

+

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.

+
+ } + else + { + var gain = o.Result.Amount >= 0; +

@(gain ? "Sei in profitto di" : "Sei in perdita di")

+
+ @Shell.Money(o.Result.Amount, c, withSign: true) + @Format.Percent(o.Result.Percent, 2, withSign: true) +
+

Dal @Format.LongDate(o.From), partendo da @Shell.Money(o.FromEquity, c). Commissioni già tolte.

+
+ @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; +
+ @if (label != cell.Label) {Ultimi }@label + @Shell.Money(cell.Amount, c, withSign: true) + @Format.Percent(cell.Percent, 2, withSign: true) +
+ } +
+ + } +
+
+
+

Adesso e dopo

+ @if (_runningDays is { } days) + { + Attivo da @days giorni senza interruzioni + } +
+

@Statement(o)

+

Prossime mosse

+ @if (o.Next.Count == 0) + { +

Niente in programma.

+ } + else + { +
    + @foreach (var move in o.Next) + { +
  • @move.Time@move.Text
  • + } +
+ } +

Ultime azioni

+ @if (o.Last.Count == 0) + { +

Ancora nessuna voce nel diario.

+ } + else + { +
    + @foreach (var action in o.Last) + { +
  • @action.When@action.Text
  • + } +
+ Tutto il diario + } +
+
+ +@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}"; + } +} diff --git a/src/Anubis.Server/Components/Pages/PrimoAccesso.razor b/src/Anubis.Server/Components/Pages/PrimoAccesso.razor new file mode 100644 index 0000000..b8e433b --- /dev/null +++ b/src/Anubis.Server/Components/Pages/PrimoAccesso.razor @@ -0,0 +1,43 @@ +@page "/primo-accesso" +@layout ServiceLayout +@inject AnubisHost Host + +Primo accesso · Anubis + +

Benvenuto in Anubis

+

Prima di cominciare, due cose.

+ +
+

Database

+

Scelto nella configurazione del container: qui si vede soltanto. Per cambiarlo si modifica il container (manuale, capitolo Installazione).

+
+
Motore
@(Host.Config.Db?.Engine == DbEngine.Postgres ? "PostgreSQL" : "SQLite")
+
Dove
@Host.Config.Db?.Describe()
+
+
+ +
+

Scegli la tua password

+

La password iniziale del container vale solo per questo primo accesso. Scegline una nuova, di almeno @Passwords.MinimumLength caratteri.

+ @if (Message is { } message) + { + + } +
+ + + + + + + + + +
+ +@code { + [SupplyParameterFromQuery(Name = "errore")] + public string? Errore { get; set; } + + private string? Message => PasswordMessages.For(Errore); +} diff --git a/src/Anubis.Server/Components/Pages/PrimoAvvio.razor b/src/Anubis.Server/Components/Pages/PrimoAvvio.razor new file mode 100644 index 0000000..7e94b7a --- /dev/null +++ b/src/Anubis.Server/Components/Pages/PrimoAvvio.razor @@ -0,0 +1,79 @@ +@page "/primo-avvio" +@layout ServiceLayout +@attribute [AllowAnonymous] +@inject AnubisHost Host + +Primo avvio · Anubis + +

Primo avvio

+@if (!_local) +{ + +} +else +{ +

Due passi: dove tenere i dati e la password per entrare. Conti, capitale e Telegram si aggiungono dopo, dalle Impostazioni.

+ @if (Message is { } message) + { + + } + +
+ + @if (!Host.Config.IsComplete) + { +
+ 1Database + + +
+ + +
+
+
+
+
+
+
+
+

La password del database non va in config.toml: la custodisce Windows per il tuo utente.

+ +

+
+
+ } +
+ @(Host.Config.IsComplete ? "1" : "2")Password +

Serve per entrare nell'interfaccia, anche da questo computer. Almeno @Passwords.MinimumLength caratteri.

+ + + + +
+

Anubis lavora solo quando il computer è acceso. Dopo un'assenza ricostruisce cosa è successo prima di riprendere.

+ + +} + +@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); +} diff --git a/src/Anubis.Server/Components/Pages/Rischio.razor b/src/Anubis.Server/Components/Pages/Rischio.razor new file mode 100644 index 0000000..26eefce --- /dev/null +++ b/src/Anubis.Server/Components/Pages/Rischio.razor @@ -0,0 +1,30 @@ +@inherits LoadedComponent +@page "/rischio" +@inject AnubisHost Host + +Rischio · Anubis + +
+

Interruttore

+ @if (_bot == "stopped") + { +

"Ferma tutto" è acceso: il bot non apre e non gestisce operazioni finché non lo riattivi.

+
+ + + + + } + else + { +

"Ferma tutto", in alto, blocca il bot. Dopo averlo usato il bot si riattiva solo da qui, mai da solo e mai da Telegram.

+ } +
+Limiti di perdita, calo dal massimo, esposizione e scenari arrivano con le strategie e il controllo del rischio. + +@code { + private string _bot = "active"; + + protected override async Task LoadAsync() => + _bot = (await Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key)).Value; +} diff --git a/src/Anubis.Server/Components/Pages/Servizio.razor b/src/Anubis.Server/Components/Pages/Servizio.razor new file mode 100644 index 0000000..ce8803f --- /dev/null +++ b/src/Anubis.Server/Components/Pages/Servizio.razor @@ -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. *@ +@ServiceText.Title(_status.Mode) · Anubis +@if (_refresh) +{ + +} + +

@ServiceText.Title(_status.Mode)

+ +@switch (_status.Mode) +{ + case HostMode.Starting: +

Controllo configurazione e database. Questa pagina si aggiorna da sola.

+ break; + + case HostMode.ConfigProblem: +

Il motore resta spento finché la configurazione non è completa. Non uso nessun altro database al posto di quello indicato.

+ + + + @foreach (var problem in Host.Config.Problems) + { + + } + +
VoceCosa non vaCome rimediare
@problem.Setting@problem.What@problem.Remedy
+ @if (Host.Config.Platform == PlatformKind.Docker) + { +

Le variabili si cambiano nella configurazione del container (su Unraid, nei campi del modello), poi si riavvia il container.

+ } + else + { +

Il file è @Host.Config.Data.ConfigFile. Appena lo correggi riprovo da solo.

+ } + break; + + case HostMode.DatabaseUnavailable: +

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.

+
+
Database
@Host.Config.Db?.Describe()
+
Risposta
@(_status.Detail ?? "nessuna")
+
Tentativi
@_status.Attempts, dal @Format.ShortDate(_status.Since, Clock.UtcNow, Host.Config.TimeZone)
+
+

Cosa controllare

+
    + @if (Host.Config.Db?.Engine == DbEngine.Postgres) + { +
  • Che il server PostgreSQL sia acceso e raggiungibile da qui (indirizzo e porta).
  • +
  • Che nome del database, utente e password siano quelli giusti.
  • +
  • Che il database esista: lo crei tu una volta, Anubis non crea e non cancella database.
  • + } + else + { +
  • Che il file del database sia al suo posto e leggibile. Se l'hai spostato, rimettilo dov'era.
  • +
  • Che il disco della cartella dei dati sia collegato e abbia spazio libero.
  • + } +
+ break; + + case HostMode.SchemaProblem: +

@_status.Detail

+

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.

+ break; + + case HostMode.IdentityProblem: + + break; + + case HostMode.FirstRun: +

Apri la procedura di primo avvio.

+ break; +} + +@if (Errore is { } errore) +{ + +} + +@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"; + } + } + } +} diff --git a/src/Anubis.Server/Components/Pages/Strategie.razor b/src/Anubis.Server/Components/Pages/Strategie.razor new file mode 100644 index 0000000..08c50f0 --- /dev/null +++ b/src/Anubis.Server/Components/Pages/Strategie.razor @@ -0,0 +1,5 @@ +@page "/strategie" + +Strategie · Anubis + +Arrivano dopo il laboratorio: ognuna con la sua descrizione, i requisiti per passare allo stadio successivo e i risultati. diff --git a/src/Anubis.Server/Components/Pending.razor b/src/Anubis.Server/Components/Pending.razor new file mode 100644 index 0000000..54ebc39 --- /dev/null +++ b/src/Anubis.Server/Components/Pending.razor @@ -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). *@ +
+

@Title

+

@ChildContent

+
+ +@code { + [Parameter, EditorRequired] + public string Title { get; set; } = ""; + + [Parameter] + public RenderFragment? ChildContent { get; set; } +} diff --git a/src/Anubis.Server/Components/Routes.razor b/src/Anubis.Server/Components/Routes.razor new file mode 100644 index 0000000..13a1af8 --- /dev/null +++ b/src/Anubis.Server/Components/Routes.razor @@ -0,0 +1,5 @@ + + + + + diff --git a/src/Anubis.Server/Components/ServiceText.cs b/src/Anubis.Server/Components/ServiceText.cs new file mode 100644 index 0000000..7969f86 --- /dev/null +++ b/src/Anubis.Server/Components/ServiceText.cs @@ -0,0 +1,30 @@ +namespace Anubis.Server; + +/// Titles of the service page, also used in plain answers while the application is not ready. +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", + }; +} + +/// Messages of the password forms. +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, + }; +} diff --git a/src/Anubis.Server/Components/_Imports.razor b/src/Anubis.Server/Components/_Imports.razor new file mode 100644 index 0000000..fbd24b1 --- /dev/null +++ b/src/Anubis.Server/Components/_Imports.razor @@ -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 diff --git a/src/Anubis.Server/DatabaseCommand.cs b/src/Anubis.Server/DatabaseCommand.cs new file mode 100644 index 0000000..9ec3798 --- /dev/null +++ b/src/Anubis.Server/DatabaseCommand.cs @@ -0,0 +1,64 @@ +using System.Collections; +using Anubis.Core; +using Anubis.Db; +using Anubis.Platform; + +namespace Anubis.Server; + +/// +/// 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). +/// +internal static class DatabaseCommand +{ + public static async Task RunAsync(string[] args, TextWriter? output = null, IReadOnlyDictionary? environment = null) + { + output ??= Console.Out; + if (args.Length < 2 || args[0] is not ("export" or "import")) + { + await output.WriteLineAsync("Uso: anubis db export | anubis db import [--platform docker|desktop] [--data-dir ]").ConfigureAwait(false); + return 2; + } + + environment ??= Environment.GetEnvironmentVariables().Cast().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; + } + } +} diff --git a/src/Anubis.Server/Endpoints.cs b/src/Anubis.Server/Endpoints.cs new file mode 100644 index 0000000..0c9ce1f --- /dev/null +++ b/src/Anubis.Server/Endpoints.cs @@ -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; + +/// Answer of GET /health. +internal sealed record HealthResponse(string Status, string Name, string Version, string? Mode = null, IReadOnlyDictionary? Checks = null); + +internal sealed record SettingBody(string Value); + +/// +/// 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. +/// +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 HealthAsync(AnubisHost host, CancellationToken cancellationToken) + { + var status = host.Status; + var checks = new Dictionary(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(); + 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 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(); + 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 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); + } + } + + /// + /// 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). + /// + 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(16); + using var modes = bus.Subscribe(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(EventSubscription 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) + { + } + } + + /// Compares two secrets in constant time. + 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))); +} diff --git a/src/Anubis.Server/Forms.cs b/src/Anubis.Server/Forms.cs new file mode 100644 index 0000000..6bdd4a5 --- /dev/null +++ b/src/Anubis.Server/Forms.cs @@ -0,0 +1,443 @@ +using Anubis.Access; +using Anubis.Core; +using Anubis.Db; +using Anubis.Platform; + +namespace Anubis.Server; + +/// +/// Form actions of the pages: plain HTML forms with the CSRF field, answered with a redirect (post, redirect, get). +/// Errors travel back as a short code in the address, never with the values typed in. +/// +internal static partial class Forms +{ + public static void Map(WebApplication app) + { + var open = app.MapGroup("/azioni").AllowAnonymous(); + open.MapPost("/accesso", SignInAsync); + open.MapPost("/primo-avvio/prova", TestDatabaseAsync); + open.MapPost("/primo-avvio", FirstRunAsync); + open.MapPost("/servizio/{choice}", ServiceChoiceAsync); + + var signed = app.MapGroup("/azioni").RequireAuthorization(); + signed.MapPost("/esci", SignOutAsync); + signed.MapPost("/primo-accesso", (IFormCollection form, AnubisHost host, StartupConfig config, HttpContext context, CancellationToken ct) => + ChangePasswordAsync(form, host, context, config.AdminPassword, "/primo-accesso", "/", ct)); + signed.MapPost("/password", (IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) => + ChangePasswordAsync(form, host, context, null, "/impostazioni", "/impostazioni", ct)); + signed.MapPost("/due-fattori/attiva", EnableSecondFactorAsync); + signed.MapPost("/due-fattori/disattiva", DisableSecondFactorAsync); + signed.MapPost("/impostazioni/{key}", SetSettingAsync); + signed.MapPost("/bot/{command}", BotAsync); + signed.MapPost("/salvataggio", BackupAsync); + } + + private static string Back(IFormCollection form, string fallback) + { + var back = form["ritorno"].ToString(); + + return IsLocalPath(back) ? back : fallback; + } + + /// + /// Only paths of this site: "/x" yes; "//other.site", "https://..." no; no backslash and no control characters, + /// which browsers drop or turn into "/" while reading an address ("/\t/other.site" becomes "//other.site"). + /// + internal static bool IsLocalPath(string path) => + path.StartsWith('/') && !path.StartsWith("//", StringComparison.Ordinal) && !path.Any(c => char.IsControl(c) || c == '\\'); + + private static string With(string path, string key, string value) + { + var hash = path.IndexOf('#', StringComparison.Ordinal); + var anchor = hash >= 0 ? path[hash..] : ""; + var bare = hash >= 0 ? path[..hash] : path; + return bare + (bare.Contains('?', StringComparison.Ordinal) ? "&" : "?") + key + "=" + Uri.EscapeDataString(value) + anchor; + } + + private static async Task SignInAsync(IFormCollection form, AnubisHost host, LoginLimiter limiter, HttpContext context, CancellationToken ct) + { + var services = host.Services; + if (services is null) + { + return Results.Redirect("/"); + } + + var address = context.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto"; + var back = Back(form, "/"); + var wait = limiter.Begin(address); + if (wait > TimeSpan.Zero) + { + var minutes = Math.Max(1, (int)Math.Ceiling(wait.TotalMinutes)); + return Results.Redirect(With(With("/accesso", "errore", "attesa"), "minuti", minutes.ToString(System.Globalization.CultureInfo.InvariantCulture))); + } + + var code = form["codice"].ToString(); + var (result, token) = await services.Access.SignInAsync(form["password"].ToString(), code, context.Request.Headers.UserAgent.ToString(), address, ct) + .ConfigureAwait(false); + switch (result) + { + case LoginResult.Ok: + limiter.Succeeded(address); + SessionAuthentication.WriteCookie(context, token!); + return Results.Redirect(back); + case LoginResult.SecondFactorNeeded: + limiter.Forgive(address); + return Results.Redirect(With(With("/accesso", "fattore", "1"), "ritorno", back)); + case LoginResult.WrongSecondFactor: + return Results.Redirect(With(With(With("/accesso", "fattore", "1"), "errore", "codice"), "ritorno", back)); + default: + return Results.Redirect(With(With("/accesso", "errore", "password"), "ritorno", back)); + } + } + + private static async Task SignOutAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + { + if (context.Request.Cookies.TryGetValue(SessionAuthentication.Cookie, out var token) && host.Services is { } services) + { + await services.Access.SignOutAsync(token, ct).ConfigureAwait(false); + } + + SessionAuthentication.ClearCookie(context); + return Results.Redirect("/accesso"); + } + + private static async Task ChangePasswordAsync(IFormCollection form, AnubisHost host, HttpContext context, string? initial, string page, string done, CancellationToken ct) + { + if (host.IsDemo) + { + return Results.Redirect(With(page, "errore", "demo")); + } + + var replacement = form["nuova"].ToString(); + if (replacement != form["conferma"].ToString()) + { + return Results.Redirect(With(page, "errore", "diverse")); + } + + if (Passwords.Problem(replacement, initial) is not null) + { + return Results.Redirect(With(page, "errore", replacement.Length < Passwords.MinimumLength ? "corta" : "uguale")); + } + + var ok = await host.Services!.Access.ChangePasswordAsync(CurrentUser.Id(context.User), form["attuale"].ToString(), replacement, CurrentUser.Session(context.User), ct) + .ConfigureAwait(false); + return Results.Redirect(ok ? With(done, "ok", "password") : With(page, "errore", "attuale")); + } + + private static async Task EnableSecondFactorAsync(IFormCollection form, AnubisHost host, SecondFactorDrafts drafts, HttpContext context, CancellationToken ct) + { + // The secret shown on the page stays on the server, tied to this session: it never travels in a form or an address. + var session = CurrentUser.Session(context.User); + if (host.IsDemo || drafts.Peek(session) is not { } secret) + { + return Results.Redirect("/impostazioni?errore=segreto#sicurezza"); + } + + var ok = await host.Services!.Access.EnableSecondFactorAsync(CurrentUser.Id(context.User), secret, form["codice"].ToString(), ct).ConfigureAwait(false); + if (ok) + { + drafts.Remove(session); + } + + return Results.Redirect(ok ? "/impostazioni?ok=due-fattori#sicurezza" : "/impostazioni?errore=codice#sicurezza"); + } + + private static async Task DisableSecondFactorAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + { + var ok = !host.IsDemo && await host.Services!.Access.DisableSecondFactorAsync(CurrentUser.Id(context.User), form["password"].ToString(), form["codice"].ToString(), ct).ConfigureAwait(false); + return Results.Redirect(ok ? "/impostazioni?ok=due-fattori-tolti#sicurezza" : "/impostazioni?errore=attuale#sicurezza"); + } + + private static async Task SetSettingAsync(string key, IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + { + var back = Back(form, "/impostazioni"); + if (key != SettingsStore.Theme.Key && key != SettingsStore.Currency.Key) + { + 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 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 BackupAsync(IFormCollection form, AnubisHost host, ILogger logger, CancellationToken ct) + { + var services = host.Services!; + try + { + await services.Backups.TakeAsync(services.Db, "a-mano", ct).ConfigureAwait(false); + return Results.Redirect("/impostazioni?ok=salvataggio#sistema"); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException) + { + LogBackupFailed(logger, ex); + return Results.Redirect("/impostazioni?errore=salvataggio#sistema"); + } + } + + // ---- Desktop first run (SPEC 15.6): only from the computer itself, only while the wizard is due. ---- + + private static DbSettings ReadDatabase(IFormCollection form, StartupConfig config) + { + if (form["motore"].ToString() != "postgres") + { + return new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = config.Data.SqliteFile }; + } + + return new DbSettings + { + Engine = DbEngine.Postgres, + Host = form["host"].ToString().Trim(), + Port = int.TryParse(form["porta"].ToString(), out var port) && port is > 0 and < 65536 ? port : 5432, + Database = string.IsNullOrWhiteSpace(form["nome"]) ? "anubis" : form["nome"].ToString().Trim(), + User = string.IsNullOrWhiteSpace(form["utente"]) ? "anubis" : form["utente"].ToString().Trim(), + Password = form["dbpassword"].ToString(), + }; + } + + /// Opens the database without creating anything and asks it one question. + private static async Task TryConnectAsync(DbSettings settings, CancellationToken ct) + { + if (settings.Engine == DbEngine.Postgres && string.IsNullOrWhiteSpace(settings.Host)) + { + return "Manca l'indirizzo del server PostgreSQL."; + } + + Redactor.Register(settings.Password); + try + { + await using var db = Database.Open(settings, allowCreate: settings.Engine == DbEngine.Sqlite); + using var timeout = CancellationTokenSource.CreateLinkedTokenSource(ct); + timeout.CancelAfter(TimeSpan.FromSeconds(8)); + await db.PingAsync(timeout.Token).ConfigureAwait(false); + return null; + } + catch (Exception ex) when (!ct.IsCancellationRequested) + { + return Redactor.Redact(ex.Message); + } + } + + private static bool WizardAllowed(AnubisHost host, HttpContext context) => + host.Status.Mode == HostMode.FirstRun && host.Config.Platform == PlatformKind.Desktop && CurrentUser.IsLocal(context); + + private static async Task TestDatabaseAsync(IFormCollection form, AnubisHost host, HttpContext context, CancellationToken ct) + { + if (!WizardAllowed(host, context)) + { + return Endpoints.Error(StatusCodes.Status403Forbidden, "non_ammesso", "La procedura guidata si usa solo dal computer su cui gira Anubis, al primo avvio."); + } + + var problem = await TryConnectAsync(ReadDatabase(form, host.Config), ct).ConfigureAwait(false); + return Results.Json(new { ok = problem is null, message = problem ?? "Connessione riuscita." }); + } + + private static async Task FirstRunAsync(IFormCollection form, AnubisHost host, HttpContext context, ILogger logger, CancellationToken ct) + { + if (!WizardAllowed(host, context)) + { + return Results.Redirect("/"); + } + + var password = form["password"].ToString(); + if (password != form["conferma"].ToString()) + { + return Results.Redirect("/primo-avvio?errore=diverse"); + } + + if (Passwords.Problem(password) is not null) + { + return Results.Redirect("/primo-avvio?errore=corta"); + } + + var config = host.Config; + if (!config.IsComplete) + { + var settings = ReadDatabase(form, config); + if (await TryConnectAsync(settings, ct).ConfigureAwait(false) is not null) + { + return Results.Redirect("/primo-avvio?errore=database"); + } + + // config.toml without the database password: that goes to the protected store (SPEC 15.6). + DesktopPlatform.WriteConfig(config.Data, ProtectedSecretKey.DefaultStore(config.Data), settings, config.Port, allowNetwork: false); + } + + host.PendingPassword = password; + host.Wake(); + try + { + await host.WaitForAsync(HostMode.Ready, TimeSpan.FromSeconds(60)).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + LogFirstRunSlow(logger); + return Results.Redirect("/"); + } + + var (result, token) = await host.Services!.Access.SignInAsync(password, null, context.Request.Headers.UserAgent.ToString(), + context.Connection.RemoteIpAddress?.ToString(), ct).ConfigureAwait(false); + if (result == LoginResult.Ok) + { + SessionAuthentication.WriteCookie(context, token!); + } + + return Results.Redirect("/"); + } + + // ---- Choices of the error page (SPEC 15.1): Docker asks the startup password, desktop only the computer itself. ---- + + private static async Task ServiceChoiceAsync(string choice, IFormCollection form, AnubisHost host, IClock clock, LoginLimiter limiter, + HttpContext context, ILogger logger, CancellationToken ct) + { + var config = host.Config; + if (config.Platform == PlatformKind.Docker) + { + // The startup password, asked by a page anyone on the network can open: same attempt limit as the sign-in. + var address = context.Connection.RemoteIpAddress?.ToString() ?? "sconosciuto"; + if (limiter.Begin(address) > TimeSpan.Zero) + { + return Results.Redirect("/?errore=attesa"); + } + + if (!Endpoints.SameSecret(form["password"].ToString(), config.AdminPassword)) + { + LogChoiceRefused(logger, choice); + return Results.Redirect("/?errore=password"); + } + + limiter.Succeeded(address); + } + else if (!CurrentUser.IsLocal(context)) + { + return Results.Redirect("/?errore=password"); + } + + // The startup loop stays still until the choice is done and the installation renewed. + using var exclusive = await host.ExclusiveAsync(ct).ConfigureAwait(false); + var status = host.Status; + var db = host.Database; + if (status.Mode != HostMode.IdentityProblem || status.Identity is null || db is null) + { + return Results.Redirect("/"); + } + + var verdict = status.Identity.Verdict; + try + { + switch (choice) + { + case "ripristina" when verdict == IdentityVerdict.EmptyDatabase: + var backup = new Backups(config.Data, clock).List().FirstOrDefault(b => b.Name == form["salvataggio"].ToString()); + if (backup is null) + { + return Results.Redirect("/?errore=scelta"); + } + + await Archive.ImportAsync(db, Path.Combine(backup.Folder, Backups.ArchiveFolder), clock, ct).ConfigureAwait(false); + await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false); + break; + case "importa" when verdict == IdentityVerdict.EmptyDatabase: + var folder = ServiceChoices.ImportFolders(config.Data).FirstOrDefault(f => Path.GetFileName(f) == form["archivio"].ToString()); + if (folder is null) + { + return Results.Redirect("/?errore=scelta"); + } + + await Archive.ImportAsync(db, folder, clock, ct).ConfigureAwait(false); + await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: false, ct).ConfigureAwait(false); + break; + case "da-capo" when verdict == IdentityVerdict.EmptyDatabase: + Installation.StartOver(config.Data, clock); + break; + case "usa-questo" when verdict is IdentityVerdict.DifferentInstallation or IdentityVerdict.StaleDatabase: + await Installation.RenewAsync(db, config.Data, clock, adoptDatabaseIdentity: true, ct).ConfigureAwait(false); + break; + default: + return Results.Redirect("/?errore=scelta"); + } + } + catch (Exception ex) when (IsArchiveProblem(ex)) + { + LogChoiceFailed(logger, ex, choice); + return Results.Redirect("/?errore=importazione"); + } + + LogChoice(logger, choice); + exclusive.Dispose(); + await host.ResetAsync().ConfigureAwait(false); + await WaitBrieflyAsync(host).ConfigureAwait(false); + return Results.Redirect("/"); + } + + /// What a damaged or unsuitable archive throws: reported on the page, not as a crash. + internal static bool IsArchiveProblem(Exception ex) => + ex is IOException or UnauthorizedAccessException or InvalidOperationException or InvalidDataException or FormatException or OverflowException + or SchemaException or System.Text.Json.JsonException or System.Data.Common.DbException; + + private static async Task WaitBrieflyAsync(AnubisHost host) + { + try + { + await host.WaitForAsync(HostMode.Ready, TimeSpan.FromSeconds(10)).ConfigureAwait(false); + } + catch (OperationCanceledException) + { + } + } + + [LoggerMessage(Level = LogLevel.Error, Message = "Backup on request failed")] + private static partial void LogBackupFailed(ILogger logger, Exception exception); + + [LoggerMessage(Level = LogLevel.Warning, Message = "First run: the application is not ready after 60 seconds")] + private static partial void LogFirstRunSlow(ILogger logger); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Error page choice {Choice} confirmed")] + private static partial void LogChoice(ILogger logger, string choice); + + [LoggerMessage(Level = LogLevel.Warning, Message = "Error page choice {Choice} refused: wrong startup password")] + private static partial void LogChoiceRefused(ILogger logger, string choice); + + [LoggerMessage(Level = LogLevel.Error, Message = "Error page choice {Choice} failed")] + private static partial void LogChoiceFailed(ILogger logger, Exception exception, string choice); +} + +/// Second-factor secrets being set up, one per session, kept for 15 minutes. +internal sealed class SecondFactorDrafts(IClock clock) +{ + private static readonly TimeSpan _life = TimeSpan.FromMinutes(15); + private readonly System.Collections.Concurrent.ConcurrentDictionary _drafts = new(); + + /// The draft of this session, or a new one. + public byte[] For(Guid session) + { + var now = clock.UtcNow; + foreach (var expired in _drafts.Where(d => d.Value.Until <= now).Select(d => d.Key).ToList()) + { + _drafts.TryRemove(expired, out _); + } + + return _drafts.AddOrUpdate(session, _ => (Totp.NewSecret(), now + _life), (_, d) => d.Until > now ? d : (Totp.NewSecret(), now + _life)).Secret; + } + + public byte[]? Peek(Guid session) => _drafts.TryGetValue(session, out var d) && d.Until > clock.UtcNow ? d.Secret : null; + + public void Remove(Guid session) => _drafts.TryRemove(session, out _); +} + +/// What the error page can offer. +internal static class ServiceChoices +{ + /// Archives under data/import, one folder each with its index.json. + public static IReadOnlyList ImportFolders(DataDirectory data) => + !Directory.Exists(data.Import) + ? [] + : Directory.EnumerateDirectories(data.Import).Where(d => File.Exists(Path.Combine(d, Archive.IndexFile))).Order(StringComparer.Ordinal).ToList(); +} diff --git a/src/Anubis.Server/JsonLog.cs b/src/Anubis.Server/JsonLog.cs new file mode 100644 index 0000000..3bdc1ad --- /dev/null +++ b/src/Anubis.Server/JsonLog.cs @@ -0,0 +1,138 @@ +using System.Collections.Concurrent; +using System.Globalization; +using System.Text; +using System.Text.Json; +using Anubis.Core; + +namespace Anubis.Server; + +/// +/// 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 so no secret reaches a log. The last 14 files are kept. +/// +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 _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 state) + where TState : notnull => null; + + public bool IsEnabled(LogLevel logLevel) => logLevel != LogLevel.None; + + public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) + { + if (!IsEnabled(logLevel)) + { + return; + } + + provider.Write(category, logLevel, eventId, formatter(state, exception), exception); + } + } +} diff --git a/src/Anubis.Server/Overview.cs b/src/Anubis.Server/Overview.cs new file mode 100644 index 0000000..b1e0ad1 --- /dev/null +++ b/src/Anubis.Server/Overview.cs @@ -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); + +/// The "Finora" and "Adesso e dopo" halves of the Panoramica (SPEC 13.2, 13.6), read from the database. +internal sealed record Overview( + IReadOnlyList Points, + IReadOnlyList Series, + PeriodResult Result, + DateOnly From, + decimal FromEquity, + IReadOnlyList Cells, + int Positions, + int PositionsWithoutStop, + int OpenOrders, + IReadOnlyList Next, + IReadOnlyList 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 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 { 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); + } +} diff --git a/src/Anubis.Server/Program.cs b/src/Anubis.Server/Program.cs index 1f0ed79..a9595bc 100644 --- a/src/Anubis.Server/Program.cs +++ b/src/Anubis.Server/Program.cs @@ -1,4 +1,11 @@ using Anubis.Server; +// "anubis db export " and "anubis db import " (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; diff --git a/src/Anubis.Server/ServerApp.cs b/src/Anubis.Server/ServerApp.cs index 5aca06a..413755f 100644 --- a/src/Anubis.Server/ServerApp.cs +++ b/src/Anubis.Server/ServerApp.cs @@ -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; /// Builds the web application. Kept apart from Program so tests can host it. 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(_ => 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(); + services.AddSingleton(sp => new AnubisHost(options, config, environment, clock, sp.GetRequiredService(), + sp.GetRequiredService>(), overrides)); + services.AddHostedService(sp => sp.GetRequiredService()); + services.AddSingleton(new LoginLimiter(clock)); + services.AddSingleton(); + services.AddSingleton(); + + services.AddAuthentication(SessionAuthentication.SchemeName) + .AddScheme(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(); + + 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().RequireAuthorization(); return app; } + + private static Dictionary ReadEnvironment() + { + var result = new Dictionary(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 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 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 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; + } } -/// Answer of GET /health. -internal sealed record HealthResponse(string Status, string Name, string Version); +/// +/// 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. +/// +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 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); + } +} diff --git a/src/Anubis.Server/ServerOptions.cs b/src/Anubis.Server/ServerOptions.cs new file mode 100644 index 0000000..a872996 --- /dev/null +++ b/src/Anubis.Server/ServerOptions.cs @@ -0,0 +1,70 @@ +using Anubis.Core; +using Anubis.Platform; + +namespace Anubis.Server; + +/// +/// 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 . +/// +internal sealed record ServerOptions(PlatformKind Platform, string? DataDir, bool Demo, string[] AspNetArgs) +{ + public static ServerOptions Parse(string[] args, IReadOnlyDictionary environment) + { + var rest = new List(); + 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]); + } + + /// Reads the startup configuration of the chosen platform. + public StartupConfig LoadConfig(IReadOnlyDictionary 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)); + } +} + +/// Test hooks: a fake environment, a manual clock, a cheaper password hash. +internal sealed record ServerOverrides +{ + public IReadOnlyDictionary? Environment { get; init; } + + public IClock? Clock { get; init; } + + public int? PasswordIterations { get; init; } + + /// How often the database is checked while running and retried while it is missing. + public TimeSpan? DatabaseCheckInterval { get; init; } +} diff --git a/src/Anubis.Server/SessionAuthentication.cs b/src/Anubis.Server/SessionAuthentication.cs new file mode 100644 index 0000000..de619fd --- /dev/null +++ b/src/Anubis.Server/SessionAuthentication.cs @@ -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; + +/// +/// 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. +/// +internal sealed class SessionAuthentication( + IOptionsMonitor options, + ILoggerFactory logger, + UrlEncoder encoder, + AnubisHost host) : AuthenticationHandler(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 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 }); +} + +/// Who is signed in, read from the claims. +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"; + + /// + /// 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. + /// + 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"; +} + +/// Error body of the API: a code for programs and a sentence for people. +internal sealed record ApiError(string Code, string Message); diff --git a/src/Anubis.Server/ShellData.cs b/src/Anubis.Server/ShellData.cs new file mode 100644 index 0000000..b893990 --- /dev/null +++ b/src/Anubis.Server/ShellData.cs @@ -0,0 +1,105 @@ +using System.Globalization; +using System.Text.Json; +using Anubis.Core; +using Anubis.Demo; +using Anubis.Platform; + +namespace Anubis.Server; + +/// What the top bar shows and the WebSocket sends: state of the bot, mode, currency, how fresh the data are. +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); + +/// Reads the shell state once per request; also the money formatter with the chosen display currency. +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 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); + } + + /// + /// 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. + /// + 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; + + /// The display currency that can honour. + 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; + } + + /// The aggregates of appendix F; only in demo mode (SPEC 13.1). + public JsonDocument? Aggregates() => host.IsDemo ? DemoMode.ReadAggregates(host.Config.Data) : null; + + public PlatformKind Platform => host.Config.Platform; +} diff --git a/src/Anubis/Access/AccessStore.cs b/src/Anubis/Access/AccessStore.cs index 2c5dba5..6559b0f 100644 --- a/src/Anubis/Access/AccessStore.cs +++ b/src/Anubis/Access/AccessStore.cs @@ -58,6 +58,43 @@ public sealed class LoginLimiter(IClock clock) } } + /// + /// 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 , a correct password still + /// waiting for its code with . + /// + public TimeSpan Begin(string address) + { + lock (_gate) + { + var wait = Wait(address); + if (wait == TimeSpan.Zero) + { + Failed(address); + } + + return wait; + } + } + + /// Takes back the last attempt counted by . + 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 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 HasUserAsync(CancellationToken cancellationToken = default) => db.ReadAsync(async s => await s.CountAsync("SELECT COUNT(*) FROM users").ConfigureAwait(false) > 0, cancellationToken); + /// The single user, or null before the first run created it. + public Task 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); + /// Creates the user when there is none. In Docker the initial password must be changed at first sign-in. public async Task 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 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 DisableSecondFactorAsync(Guid userId, string password, CancellationToken cancellationToken = default) + /// Turning the second factor off asks for both: the password and a code from the app. + public async Task 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; } diff --git a/src/Anubis/Access/Passwords.cs b/src/Anubis/Access/Passwords.cs index 91c9c4d..38f4f14 100644 --- a/src/Anubis/Access/Passwords.cs +++ b/src/Anubis/Access/Passwords.cs @@ -157,27 +157,34 @@ public static class Totp } /// Accepts the code of the current step and of one step before or after, for clocks a little apart. - public static bool Verify(ReadOnlySpan secret, string? code, DateTimeOffset now) + public static bool Verify(ReadOnlySpan secret, string? code, DateTimeOffset now) => Match(secret, code, now) is not null; + + /// The time step the code belongs to (current, one before or one after), or null when it matches none. + public static long? Match(ReadOnlySpan 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; } /// The address authenticator apps read (otpauth://), for manual entry or a QR code. diff --git a/src/Anubis/Anubis.csproj b/src/Anubis/Anubis.csproj index c75e33c..7cc3c05 100644 --- a/src/Anubis/Anubis.csproj +++ b/src/Anubis/Anubis.csproj @@ -9,6 +9,7 @@
+ diff --git a/src/Anubis/Db/Database.cs b/src/Anubis/Db/Database.cs index f6d358b..1131647 100644 --- a/src/Anubis/Db/Database.cs +++ b/src/Anubis/Db/Database.cs @@ -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; } + /// Full path of the SQLite file; null on PostgreSQL. + public string? SqlitePath { get; } + /// Engine and place, without the password. 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); diff --git a/src/Anubis/Demo/Data/aggregates.json b/src/Anubis/Demo/Data/aggregates.json new file mode 100644 index 0000000..9e0650b --- /dev/null +++ b/src/Anubis/Demo/Data/aggregates.json @@ -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 + } +} diff --git a/src/Anubis/Demo/Data/daily.csv b/src/Anubis/Demo/Data/daily.csv new file mode 100644 index 0000000..ea33b29 --- /dev/null +++ b/src/Anubis/Demo/Data/daily.csv @@ -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 diff --git a/src/Anubis/Demo/Data/journal.csv b/src/Anubis/Demo/Data/journal.csv new file mode 100644 index 0000000..825406a --- /dev/null +++ b/src/Anubis/Demo/Data/journal.csv @@ -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 diff --git a/src/Anubis/Demo/Data/positions.csv b/src/Anubis/Demo/Data/positions.csv new file mode 100644 index 0000000..18a7231 --- /dev/null +++ b/src/Anubis/Demo/Data/positions.csv @@ -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 diff --git a/src/Anubis/Demo/Data/trades.csv b/src/Anubis/Demo/Data/trades.csv new file mode 100644 index 0000000..a3d0183 --- /dev/null +++ b/src/Anubis/Demo/Data/trades.csv @@ -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 diff --git a/src/Anubis/Demo/DemoMode.cs b/src/Anubis/Demo/DemoMode.cs new file mode 100644 index 0000000..567542b --- /dev/null +++ b/src/Anubis/Demo/DemoMode.cs @@ -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; + +/// +/// 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. +/// +public static class DemoMode +{ + public const string AggregatesFile = "demo-aggregates.json"; + + /// "Adesso" in the demo: Friday 9 October 2026, 08:21 in Rome. + public static readonly DateTimeOffset Now = new(2026, 10, 9, 8, 21, 0, TimeSpan.FromHours(2)); + + private static readonly CultureInfo _it = CultureInfo.InvariantCulture; + + /// Demo folders older than this are removed when a new demo starts. + public static readonly TimeSpan KeepFolders = TimeSpan.FromDays(7); + + /// + /// A brand-new folder under the system temporary directory; it never reuses another folder. + /// is the real clock (the demo's own clock stands still): it names the folder and clears demos older than a week. + /// + 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, + }; + + /// Loads appendix F into an empty, migrated database and writes the aggregates file next to it. + 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 + { + ["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); + } + + /// Reads the aggregates file of a demo folder. + 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 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(); + } + + /// UUIDv7 in insertion order, all at the demo's frozen time. + private sealed class IdSource(DateTimeOffset at) + { + private int _n; + + public Guid Next() => Guid.CreateVersion7(at.AddMilliseconds(_n++)); + } +} diff --git a/src/Anubis/Platform/Installation.cs b/src/Anubis/Platform/Installation.cs index 7b23b0b..21b8346 100644 --- a/src/Anubis/Platform/Installation.cs +++ b/src/Anubis/Platform/Installation.cs @@ -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); diff --git a/tests/Anubis.Tests/ContrastTests.cs b/tests/Anubis.Tests/ContrastTests.cs new file mode 100644 index 0000000..e1e0364 --- /dev/null +++ b/tests/Anubis.Tests/ContrastTests.cs @@ -0,0 +1,88 @@ +using System.Globalization; +using System.Text.RegularExpressions; + +namespace Anubis.Tests; + +/// +/// SPEC 13.4: the seven text colours reach 4.5:1 on the page and on the panels, the control border 3:1 on the panels, +/// in both themes; and the style uses no colour outside appendix C. +/// +[TestClass] +[TestCategory(Category.Unit)] +public sealed partial class ContrastTests +{ + private static readonly string[] _texts = ["--text", "--text-2", "--text-3", "--link", "--gain", "--loss", "--attention"]; + + private static string Css() => File.ReadAllText(Path.Combine(Repo.Root.FullName, "src", "Anubis.Server", "Assets", "app.css")); + + private static Dictionary Block(string css, string selector) + { + var start = css.IndexOf(selector + " {", StringComparison.Ordinal); + Assert.IsGreaterThanOrEqualTo(0, start, "Missing block " + selector); + var end = css.IndexOf('}', start); + return Token().Matches(css[start..end]).ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value.ToLowerInvariant(), StringComparer.Ordinal); + } + + public static IEnumerable Themes() => [[":root"], [":root[data-theme=\"dark\"]"], [":root:not([data-theme=\"light\"])"]]; + + [TestMethod] + [DynamicData(nameof(Themes))] + public void TextAndControlsAreReadable(string selector) + { + var tokens = Block(Css(), selector); + foreach (var text in _texts) + { + foreach (var background in new[] { "--page", "--surface" }) + { + var ratio = Ratio(tokens[text], tokens[background]); + Assert.IsGreaterThanOrEqualTo(4.5, ratio, $"{selector} {text} on {background}: {ratio:0.00}"); + } + } + + Assert.IsGreaterThanOrEqualTo(3.0, Ratio(tokens["--control"], tokens["--surface"]), selector + " control border"); + } + + [TestMethod] + public void DarkThemeIsTheSameForTheSystemAndTheSetting() + { + var css = Css(); + CollectionAssert.AreEquivalent(Block(css, ":root[data-theme=\"dark\"]").ToList(), Block(css, ":root:not([data-theme=\"light\"])").ToList()); + } + + [TestMethod] + public void OnlyColoursOfAppendixC() + { + var spec = File.ReadAllText(Path.Combine(Repo.Root.FullName, "docs", "SPEC.md")); + var appendix = spec[spec.IndexOf("## Appendice C", StringComparison.Ordinal)..spec.IndexOf("## Appendice D", StringComparison.Ordinal)]; + var allowed = Hex().Matches(appendix).Select(m => m.Value.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal); + var used = Hex().Matches(Css()).Select(m => m.Value.ToLowerInvariant()).Distinct().ToList(); + Assert.IsNotEmpty(used); + foreach (var colour in used) + { + Assert.Contains(colour, allowed, colour + " is not in appendix C"); + } + } + + private static double Ratio(string a, string b) + { + var (la, lb) = (Luminance(a), Luminance(b)); + return (Math.Max(la, lb) + 0.05) / (Math.Min(la, lb) + 0.05); + } + + private static double Luminance(string hex) + { + double Channel(int i) + { + var c = int.Parse(hex.AsSpan(1 + (2 * i), 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture) / 255.0; + return c <= 0.03928 ? c / 12.92 : Math.Pow((c + 0.055) / 1.055, 2.4); + } + + return (0.2126 * Channel(0)) + (0.7152 * Channel(1)) + (0.0722 * Channel(2)); + } + + [GeneratedRegex(@"(--[a-z0-9-]+):\s*(#[0-9a-fA-F]{6})")] + private static partial Regex Token(); + + [GeneratedRegex(@"#[0-9a-fA-F]{6}(?![0-9a-fA-F])")] + private static partial Regex Hex(); +} diff --git a/tests/Anubis.Tests/HealthEndpointTests.cs b/tests/Anubis.Tests/HealthEndpointTests.cs index 540d7f3..c3dda93 100644 --- a/tests/Anubis.Tests/HealthEndpointTests.cs +++ b/tests/Anubis.Tests/HealthEndpointTests.cs @@ -11,27 +11,16 @@ public sealed class HealthEndpointTests [TestCategory(Category.Integration)] public async Task HealthAnswersOkWithNameAndVersion() { - // The real server on a free local port: no test host package needed (ADR 0004). - var app = ServerApp.Build(["--urls", "http://127.0.0.1:0"]); - await app.StartAsync().ConfigureAwait(false); - try - { - var address = app.Urls.Single(); - using var http = new HttpClient { BaseAddress = new Uri(address) }; + // The real server on a free local port with its own data folder: no test host package needed (ADR 0004). + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); - using var response = await http.GetAsync(new Uri("/health", UriKind.Relative)).ConfigureAwait(false); - var body = await response.Content.ReadFromJsonAsync().ConfigureAwait(false); + using var response = await server.GetAsync("/health"); + var body = await response.Content.ReadFromJsonAsync(); - Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); - Assert.IsNotNull(body); - Assert.AreEqual("ok", body.Status); - Assert.AreEqual(AnubisInfo.Name, body.Name); - Assert.AreEqual(AnubisInfo.Version, body.Version); - } - finally - { - await app.StopAsync().ConfigureAwait(false); - await app.DisposeAsync().ConfigureAwait(false); - } + Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); + Assert.IsNotNull(body); + Assert.AreEqual("ok", body.Status); + Assert.AreEqual(AnubisInfo.Name, body.Name); + Assert.AreEqual(AnubisInfo.Version, body.Version); } } diff --git a/tests/Anubis.Tests/ServerHarness.cs b/tests/Anubis.Tests/ServerHarness.cs new file mode 100644 index 0000000..84cc2a4 --- /dev/null +++ b/tests/Anubis.Tests/ServerHarness.cs @@ -0,0 +1,166 @@ +using System.Net; +using System.Text.RegularExpressions; +using Anubis.Server; +using Microsoft.AspNetCore.Builder; +using Microsoft.Extensions.DependencyInjection; + +namespace Anubis.Tests; + +/// +/// The real server on a free local port, with a fake environment and its own data folder: never %APPDATA%, never +/// the developer's database. A cookie-keeping client that does not follow redirects, so tests see each step. +/// +internal sealed partial class ServerHarness : IAsyncDisposable +{ + public const string AdminPassword = "fake-initial-pass-1"; + public const string SecretKey = "fake-secret-key-0123456789-abcdefghij"; + + private readonly WebApplication _app; + + private bool _ownsData; + + private ServerHarness(WebApplication app, string dataDir, CookieContainer cookies, HttpClient http) + { + _app = app; + DataDir = dataDir; + Cookies = cookies; + Http = http; + } + + public string DataDir { get; } + + public CookieContainer Cookies { get; } + + public HttpClient Http { get; } + + public Uri BaseAddress => Http.BaseAddress!; + + internal AnubisHost Host => _app.Services.GetRequiredService(); + + /// Docker configuration with SQLite in the data folder: what most tests need. + public static Dictionary DockerSqlite() => new(StringComparer.Ordinal) + { + ["ANUBIS_DB_ENGINE"] = "sqlite", + ["ANUBIS_SECRET_KEY"] = SecretKey, + ["ANUBIS_ADMIN_PASSWORD"] = AdminPassword, + ["TZ"] = "Europe/Rome", + }; + + /// + /// Docker configuration on the engine of this run (ANUBIS_TEST_DB): SQLite in the data folder, or a new PostgreSQL + /// database that the caller disposes. + /// + public static async Task<(Dictionary Env, TestDb? Postgres)> DockerOnEngineAsync() + { + var env = DockerSqlite(); + if (TestDatabase.Engine != "postgres") + { + return (env, null); + } + + var db = await TestDb.CreateAsync(Anubis.Platform.DbEngine.Postgres).ConfigureAwait(false); + UsePostgres(env, db); + return (env, db); + } + + public static void UsePostgres(Dictionary env, TestDb db) + { + ArgumentNullException.ThrowIfNull(env); + ArgumentNullException.ThrowIfNull(db); + env["ANUBIS_DB_ENGINE"] = "postgres"; + env["ANUBIS_DB_HOST"] = db.Settings.Host; + env["ANUBIS_DB_PORT"] = db.Settings.Port.ToString(System.Globalization.CultureInfo.InvariantCulture); + env["ANUBIS_DB_NAME"] = db.Settings.Database; + env["ANUBIS_DB_USER"] = db.Settings.User; + env["ANUBIS_DB_PASSWORD"] = db.Settings.Password; + } + + public static async Task StartAsync(string platform, IReadOnlyDictionary environment, string? dataDir = null, + string[]? extraArgs = null, bool waitReady = true) + { + var owns = dataDir is null; + dataDir ??= TempFolder.Create("server"); + string[] args = ["--platform", platform, "--data-dir", dataDir, "--urls", "http://127.0.0.1:0", .. extraArgs ?? []]; + var app = ServerApp.Build(args, new ServerOverrides + { + Environment = environment, + PasswordIterations = 1000, + DatabaseCheckInterval = TimeSpan.FromMilliseconds(100), + }); + await app.StartAsync().ConfigureAwait(false); + var cookies = new CookieContainer(); +#pragma warning disable CA2000 // The handler belongs to the client, disposed with the harness. + var http = new HttpClient(new HttpClientHandler { CookieContainer = cookies, AllowAutoRedirect = false }) +#pragma warning restore CA2000 + { + BaseAddress = new Uri(app.Urls.Single()), + Timeout = TimeSpan.FromSeconds(60), + }; + var harness = new ServerHarness(app, dataDir, cookies, http) { _ownsData = owns }; + if (waitReady) + { + await harness.Host.WaitForAsync(HostMode.Ready, TimeSpan.FromSeconds(30)).ConfigureAwait(false); + } + + return harness; + } + + public async Task WaitForAsync(HostMode mode) => await Host.WaitForAsync(mode, TimeSpan.FromSeconds(30)).ConfigureAwait(false); + + public Task GetAsync(string path) => Http.GetAsync(new Uri(path, UriKind.Relative)); + + public async Task TextAsync(string path) + { + using var response = await GetAsync(path).ConfigureAwait(false); + return WebUtility.HtmlDecode(await response.Content.ReadAsStringAsync().ConfigureAwait(false)); + } + + /// The CSRF field of a page's forms. + public async Task CsrfAsync(string page) + { + using var response = await GetAsync(page).ConfigureAwait(false); + var html = await response.Content.ReadAsStringAsync().ConfigureAwait(false); + var match = CsrfField().Match(html); + Assert.IsTrue(match.Success, "No CSRF field on " + page); + return WebUtility.HtmlDecode(match.Groups[1].Value); + } + + /// Posts a form the way the browser does, with the CSRF field of . + public async Task PostFormAsync(string page, string action, params (string Name, string Value)[] fields) + { + var token = await CsrfAsync(page).ConfigureAwait(false); + using var content = new FormUrlEncodedContent([new("__csrf", token), .. fields.Select(f => new KeyValuePair(f.Name, f.Value))]); + return await Http.PostAsync(new Uri(action, UriKind.Relative), content).ConfigureAwait(false); + } + + /// Signs in with the initial password and replaces it, as the first access in Docker requires. + public async Task SignInFirstTimeAsync() + { + using (var login = await PostFormAsync("/accesso", "/azioni/accesso", ("password", AdminPassword)).ConfigureAwait(false)) + { + Assert.AreEqual(HttpStatusCode.Redirect, login.StatusCode); + } + + const string chosen = "chosen-test-pass-2"; + using var change = await PostFormAsync("/primo-accesso", "/azioni/primo-accesso", ("attuale", AdminPassword), ("nuova", chosen), ("conferma", chosen)) + .ConfigureAwait(false); + Assert.AreEqual("/?ok=password", change.Headers.Location?.OriginalString); + return chosen; + } + + public static string Location(HttpResponseMessage response) => response.Headers.Location?.OriginalString ?? ""; + + public async ValueTask DisposeAsync() + { + Http.Dispose(); + await _app.StopAsync().ConfigureAwait(false); + await _app.DisposeAsync().ConfigureAwait(false); + if (_ownsData) + { + TempFolder.Delete(DataDir); + } + } + + [GeneratedRegex("name=\"__csrf\" value=\"([^\"]+)\"")] + private static partial Regex CsrfField(); +} diff --git a/tests/Anubis.Tests/ServerTests.cs b/tests/Anubis.Tests/ServerTests.cs new file mode 100644 index 0000000..103d021 --- /dev/null +++ b/tests/Anubis.Tests/ServerTests.cs @@ -0,0 +1,453 @@ +using System.Net; +using System.Net.Http.Json; +using System.Net.WebSockets; +using System.Text; +using Anubis.Core; +using Anubis.Db; +using Anubis.Demo; +using Anubis.Platform; +using Anubis.Server; + +namespace Anubis.Tests; + +[TestClass] +[TestCategory(Category.Integration)] +public sealed class ServerTests +{ + [TestMethod] + public async Task SignInFirstAccessAndApi() + { + var (env, postgres) = await ServerHarness.DockerOnEngineAsync(); + await using var engine = postgres; + await using var server = await ServerHarness.StartAsync("docker", env); + + // A return address that leaves the site never reaches the form. + StringAssert.Contains(await server.TextAsync("/accesso?ritorno=%2F%09%2Fevil.example"), "name=\"ritorno\" value=\"/\""); + + // Without a session: pages go to sign-in, the API answers 401. + using (var page = await server.GetAsync("/")) + { + Assert.AreEqual(HttpStatusCode.Redirect, page.StatusCode); + StringAssert.StartsWith(ServerHarness.Location(page), "/accesso"); + } + + using (var api = await server.GetAsync("/api/status")) + { + Assert.AreEqual(HttpStatusCode.Unauthorized, api.StatusCode); + } + + // Wrong password: back to the form with the reason. + using (var wrong = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", "not-the-password"))) + { + StringAssert.Contains(ServerHarness.Location(wrong), "errore=password"); + } + + // A form without the CSRF field is refused. + using (var noCsrf = await server.Http.PostAsync(new Uri("/azioni/accesso", UriKind.Relative), + new FormUrlEncodedContent([new("password", ServerHarness.AdminPassword)]))) + { + Assert.AreEqual(HttpStatusCode.BadRequest, noCsrf.StatusCode); + } + + // The initial password lets in only to change it. + using (var login = await server.PostFormAsync("/accesso", "/azioni/accesso", ("password", ServerHarness.AdminPassword))) + { + Assert.AreEqual("/", ServerHarness.Location(login)); + var cookie = login.Headers.GetValues("Set-Cookie").Single(c => c.StartsWith("anubis_session=", StringComparison.Ordinal)); + StringAssert.Contains(cookie, "httponly"); + StringAssert.Contains(cookie, "samesite=strict"); + } + + using (var forced = await server.GetAsync("/")) + { + Assert.AreEqual("/primo-accesso", ServerHarness.Location(forced)); + } + + using (var same = await server.PostFormAsync("/primo-accesso", "/azioni/primo-accesso", + ("attuale", ServerHarness.AdminPassword), ("nuova", ServerHarness.AdminPassword), ("conferma", ServerHarness.AdminPassword))) + { + StringAssert.Contains(ServerHarness.Location(same), "errore=uguale"); + } + + const string chosen = "chosen-test-pass-2"; + using (var change = await server.PostFormAsync("/primo-accesso", "/azioni/primo-accesso", + ("attuale", ServerHarness.AdminPassword), ("nuova", chosen), ("conferma", chosen))) + { + Assert.AreEqual("/?ok=password", ServerHarness.Location(change)); + } + + var home = await server.TextAsync("/"); + StringAssert.Contains(home, "Panoramica"); + StringAssert.Contains(home, "Simulazione: nessun soldo reale"); + StringAssert.Contains(home, "Ancora nessun risultato", "Production never shows invented numbers."); + + // API: reading works, writing needs the CSRF header. + var status = await server.Http.GetFromJsonAsync>(new Uri("/api/status", UriKind.Relative)); + Assert.AreEqual("Ready", status!["mode"].ToString()); + using (var noHeader = await server.Http.PutAsJsonAsync(new Uri("/api/settings/appearance.theme", UriKind.Relative), new { value = "dark" })) + { + Assert.AreEqual(HttpStatusCode.BadRequest, noHeader.StatusCode); + } + + var csrf = await server.Http.GetFromJsonAsync>(new Uri("/api/antiforgery", UriKind.Relative)); + using (var request = new HttpRequestMessage(HttpMethod.Put, new Uri("/api/settings/appearance.theme", UriKind.Relative)) { Content = JsonContent.Create(new { value = "dark" }) }) + { + request.Headers.Add(csrf!["header"], csrf["token"]); + using var put = await server.Http.SendAsync(request); + Assert.AreEqual(HttpStatusCode.NoContent, put.StatusCode); + } + + StringAssert.Contains(await server.TextAsync("/"), "data-theme=\"dark\""); + + // Secrets: status only, never the value. + var secret = await server.TextAsync("/api/secrets/ALPACA_API_KEY"); + StringAssert.Contains(secret, "\"isSet\":false"); + + // Pause, resume, stop; resume never undoes "Ferma tutto". + Assert.AreEqual("paused", await BotAsync(server, csrf, "pause")); + Assert.AreEqual("active", await BotAsync(server, csrf, "resume")); + Assert.AreEqual("stopped", await BotAsync(server, csrf, "stop")); + Assert.IsNull(await BotAsync(server, csrf, "resume")); + + // Sign out ends the session. + using (var bye = await server.PostFormAsync("/impostazioni", "/azioni/esci")) + { + Assert.AreEqual("/accesso", ServerHarness.Location(bye)); + } + + using var after = await server.GetAsync("/api/status"); + Assert.AreEqual(HttpStatusCode.Unauthorized, after.StatusCode); + } + + private static async Task BotAsync(ServerHarness server, Dictionary csrf, string command) + { + using var request = new HttpRequestMessage(HttpMethod.Post, new Uri("/api/bot/" + command, UriKind.Relative)); + request.Headers.Add(csrf["header"], csrf["token"]); + using var response = await server.Http.SendAsync(request); + if (!response.IsSuccessStatusCode) + { + return null; + } + + var body = await response.Content.ReadFromJsonAsync>(); + return body!["state"]; + } + + [TestMethod] + [DataRow("/impostazioni#aspetto", true)] + [DataRow("/?periodo=30", true)] + [DataRow("//evil.example", false)] + [DataRow("/\\evil.example", false)] + [DataRow("/\t/evil.example", false)] + [DataRow("/a\nb", false)] + [DataRow("https://evil.example", false)] + [DataRow("", false)] + public void ReturnAddressesStayOnTheSite(string path, bool local) => Assert.AreEqual(local, Forms.IsLocalPath(path)); + + [TestMethod] + public async Task ComputerOnlyModesRefuseForeignHostNames() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), extraArgs: ["--demo"]); + var demoRoot = server.Host.Config.Data.Root; + using (var mine = await server.GetAsync("/api/me")) + { + Assert.AreEqual(HttpStatusCode.OK, mine.StatusCode); + } + + // DNS rebinding: a page whose name now points at 127.0.0.1 arrives from the loopback with its own Host. + using var request = new HttpRequestMessage(HttpMethod.Get, new Uri("/api/me", UriKind.Relative)); + request.Headers.Host = "evil.example:" + server.BaseAddress.Port.ToString(System.Globalization.CultureInfo.InvariantCulture); + using var foreign = await server.Http.SendAsync(request); + Assert.AreEqual(HttpStatusCode.Forbidden, foreign.StatusCode); + TempFolder.Delete(demoRoot); + } + + [TestMethod] + public async Task RestoreFromTheErrorPageRestartsWithEverythingStopped() + { + var (env, postgres) = await ServerHarness.DockerOnEngineAsync(); + await using var engine = postgres; + var data = TempFolder.Create("restore"); + await using (var first = await ServerHarness.StartAsync("docker", env, dataDir: data)) + { + await first.SignInFirstTimeAsync(); + using var saved = await first.PostFormAsync("/impostazioni", "/azioni/salvataggio"); + Assert.AreEqual("/impostazioni?ok=salvataggio#sistema", ServerHarness.Location(saved)); + } + + var backup = new Backups(new DataDirectory(data), new ManualClock(DemoMode.Now)).List().Single(b => b.Reason == "a-mano"); + + // An empty database takes the place of the real one; the data folder still belongs to the installation. + await using var empty = postgres is null ? null : await TestDb.CreateAsync(DbEngine.Postgres); + if (empty is null) + { + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + var file = new DataDirectory(data).SqliteFile; + foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!)) + { + File.Delete(f); + } + + await File.WriteAllBytesAsync(file, []); + } + else + { + ServerHarness.UsePostgres(env, empty); + } + + await using var server = await ServerHarness.StartAsync("docker", env, dataDir: data, waitReady: false); + await server.WaitForAsync(HostMode.IdentityProblem); + Assert.AreEqual(IdentityVerdict.EmptyDatabase, server.Host.Status.Identity!.Verdict); + using (var restore = await server.PostFormAsync("/", "/azioni/servizio/ripristina", ("password", ServerHarness.AdminPassword), ("salvataggio", backup.Name))) + { + Assert.AreEqual("/", ServerHarness.Location(restore)); + } + + await server.WaitForAsync(HostMode.Ready); + + // SPEC 15.1: back with "Ferma tutto" on, a new fingerprint, and nobody signed in. + var state = await server.Host.Services!.Settings.GetAsync(SettingsStore.BotState.Key); + Assert.AreEqual("stopped", state.Value); + var row = await Installation.ReadRowAsync(server.Host.Services.Db); + Assert.IsTrue(row!.ProtectedRestart); + Assert.AreEqual(row.Fingerprint, Installation.ReadFile(new DataDirectory(data))!.Fingerprint); + Assert.AreEqual(0, await server.Host.Services.Db.ReadAsync(s => s.CountAsync("SELECT COUNT(*) FROM sessions"))); + TempFolder.Delete(data); + } + + [TestMethod] + public async Task MissingConfigurationShowsTheErrorPageAndCreatesNoDatabase() + { + var env = ServerHarness.DockerSqlite(); + env.Remove("ANUBIS_DB_ENGINE"); + await using var server = await ServerHarness.StartAsync("docker", env, waitReady: false); + await server.WaitForAsync(HostMode.ConfigProblem); + + using var page = await server.GetAsync("/qualsiasi/pagina"); + var html = WebUtility.HtmlDecode(await page.Content.ReadAsStringAsync()); + Assert.AreEqual(HttpStatusCode.ServiceUnavailable, page.StatusCode); + StringAssert.Contains(html, "Manca qualcosa nella configurazione d'avvio"); + StringAssert.Contains(html, "ANUBIS_DB_ENGINE"); + + using var health = await server.GetAsync("/health"); + Assert.AreEqual(HttpStatusCode.ServiceUnavailable, health.StatusCode); + + // Trap 20: no database appears anywhere in the data folder. + Assert.IsEmpty(Directory.EnumerateFiles(server.DataDir, "*.sqlite3*", SearchOption.AllDirectories).ToList()); + } + + [TestMethod] + public async Task DetachedDatabaseShowsTheErrorPageAndTheAppResumesAlone() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); + await server.SignInFirstTimeAsync(); + var file = new DataDirectory(server.DataDir).SqliteFile; + var away = file + ".altrove"; + + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + File.Move(file, away); + await server.WaitForAsync(HostMode.DatabaseUnavailable); + + using (var page = await server.GetAsync("/")) + { + Assert.AreEqual(HttpStatusCode.ServiceUnavailable, page.StatusCode); + StringAssert.Contains(WebUtility.HtmlDecode(await page.Content.ReadAsStringAsync()), "Il database non risponde"); + } + + Assert.IsFalse(File.Exists(file), "No new empty database while the real one is away."); + + File.Move(away, file); + await server.WaitForAsync(HostMode.Ready); + using var back = await server.GetAsync("/"); + Assert.AreEqual(HttpStatusCode.OK, back.StatusCode, "Same session, no restart."); + } + + [TestMethod] + public async Task EmptyDatabaseOfAKnownInstallationAsksTheUser() + { + var data = TempFolder.Create("identity"); + await using (var first = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: data)) + { + await first.Http.GetAsync(new Uri("/health", UriKind.Relative)); + } + + // The database is replaced by an empty one; the data folder still belongs to the installation. + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + var file = new DataDirectory(data).SqliteFile; + foreach (var f in Directory.EnumerateFiles(Path.GetDirectoryName(file)!)) + { + File.Delete(f); + } + + await File.WriteAllBytesAsync(file, []); + + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: data, waitReady: false); + await server.WaitForAsync(HostMode.IdentityProblem); + var html = await server.TextAsync("/"); + StringAssert.Contains(html, "Il database è vuoto"); + StringAssert.Contains(html, "Comincia da capo"); + + using (var wrong = await server.PostFormAsync("/", "/azioni/servizio/da-capo", ("password", "wrong-password-123"))) + { + StringAssert.Contains(ServerHarness.Location(wrong), "errore=password"); + } + + Assert.AreEqual(HostMode.IdentityProblem, server.Host.Status.Mode); + using (var ok = await server.PostFormAsync("/", "/azioni/servizio/da-capo", ("password", ServerHarness.AdminPassword))) + { + Assert.AreEqual("/", ServerHarness.Location(ok)); + } + + await server.WaitForAsync(HostMode.Ready); + Assert.IsNotEmpty(Directory.EnumerateFiles(data, "installation.json.precedente-*").ToList(), "The old identity is set aside, not deleted."); + } + + [TestMethod] + public async Task DesktopStartsFromAnEmptyFolderAndKeepsTheKeyOutOfConfig() + { + await using var server = await ServerHarness.StartAsync("desktop", new Dictionary(), waitReady: false); + await server.WaitForAsync(HostMode.FirstRun); + + using (var redirect = await server.GetAsync("/")) + { + Assert.AreEqual("/primo-avvio", ServerHarness.Location(redirect)); + } + + const string password = "fake-desktop-pass-3"; + using (var done = await server.PostFormAsync("/primo-avvio", "/azioni/primo-avvio", ("motore", "sqlite"), ("password", password), ("conferma", password))) + { + Assert.AreEqual("/", ServerHarness.Location(done)); + } + + Assert.AreEqual(HostMode.Ready, server.Host.Status.Mode); + using (var home = await server.GetAsync("/")) + { + Assert.AreEqual(HttpStatusCode.OK, home.StatusCode, "Signed in by the wizard."); + } + + var data = new DataDirectory(server.DataDir); + Assert.IsTrue(File.Exists(data.SqliteFile)); + var config = await File.ReadAllTextAsync(data.ConfigFile); + StringAssert.Contains(config, "engine = \"sqlite\""); + StringAssert.Contains(config, "allow_live = false"); + Assert.IsFalse(System.Text.RegularExpressions.Regex.IsMatch(config, @"^\s*\w*(secret|key|password)\w*\s*=", System.Text.RegularExpressions.RegexOptions.Multiline), + "Neither the secret key nor a password goes into config.toml."); + Assert.IsNotEmpty(Directory.EnumerateFiles(Path.Combine(data.Root, "keys")).ToList()); + } + + [TestMethod] + public async Task DemoModeNeverTouchesTheConfiguredDatabase() + { + // A real installation with its database, then the demo started with the same configuration. + var configured = TempFolder.Create("configured"); + await using (var real = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: configured)) + { + await real.SignInFirstTimeAsync(); + } + + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + var before = Snapshot(configured); + Assert.IsTrue(before.Keys.Any(k => k.EndsWith(".sqlite3", StringComparison.Ordinal))); + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite(), dataDir: configured, extraArgs: ["--demo"]); + + // Its own folder under the temporary directory, the configured one untouched. + var demoRoot = server.Host.Config.Data.Root; + StringAssert.StartsWith(demoRoot, Path.Combine(Path.GetTempPath(), "anubis-demo")); + + // Appendix F on screen, frozen clock, signed in by itself, the footer says it. + var html = await server.TextAsync("/"); + StringAssert.Contains(html, "+412,46 €"); + StringAssert.Contains(html, "Venerdì 9 ottobre 2026, ore 08:21"); + StringAssert.Contains(html, "Sorveglio 10 posizioni, ognuna con il suo stop."); + StringAssert.Contains(html, "Modalità dimostrativa. Numeri, titoli e notizie sono dati di esempio."); + + // The live status arrives over the WebSocket. + using var socket = new ClientWebSocket(); + await socket.ConnectAsync(new Uri(server.BaseAddress.ToString().Replace("http", "ws", StringComparison.Ordinal) + "ws"), CancellationToken.None); + var buffer = new byte[4096]; + var received = await socket.ReceiveAsync(buffer, CancellationToken.None); + var message = Encoding.UTF8.GetString(buffer, 0, received.Count); + StringAssert.Contains(message, "\"type\":\"status\""); + StringAssert.Contains(message, "\"bot\":\"active\""); + await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None); + + var after = Snapshot(configured); + CollectionAssert.AreEquivalent(before.Keys.ToList(), after.Keys.ToList(), "No file added or removed in the configured data folder."); + foreach (var (name, hash) in before) + { + Assert.AreEqual(hash, after[name], name + " changed"); + } + + TempFolder.Delete(demoRoot); + TempFolder.Delete(configured); + } + + private static Dictionary Snapshot(string folder) => + Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories).ToDictionary( + f => Path.GetRelativePath(folder, f), + f => Convert.ToHexString(System.Security.Cryptography.SHA256.HashData(File.ReadAllBytes(f))), + StringComparer.Ordinal); + + [TestMethod] + public async Task DemoSeedRefusesAnyOtherDatabase() + { + var demo = DemoMode.CreateFolder(new Anubis.Core.SystemClock()); + var elsewhere = TempFolder.Create("elsewhere"); + await using var db = Database.Open(new DbSettings { Engine = DbEngine.Sqlite, SqlitePath = Path.Combine(elsewhere, "x.sqlite3") }); + await Migrations.MigrateAsync(db, new ManualClock(DemoMode.Now), null, CancellationToken.None); + await Assert.ThrowsExactlyAsync(() => DemoMode.SeedAsync(db, demo, new ManualClock(DemoMode.Now))); + TempFolder.Delete(elsewhere); + TempFolder.Delete(demo.Root); + } + + [TestMethod] + public async Task HealthChecksDatabaseAndScheduler() + { + var (env, postgres) = await ServerHarness.DockerOnEngineAsync(); + await using var engine = postgres; + await using var server = await ServerHarness.StartAsync("docker", env); + var health = await server.Http.GetFromJsonAsync(new Uri("/health", UriKind.Relative)); + Assert.AreEqual("ok", health!.Status); + Assert.AreEqual("ok", health.Checks!["database"]); + Assert.AreEqual("ok", health.Checks["scheduler"]); + } + + [TestMethod] + public async Task SecurityHeadersAndLogoFromTheDesignFolder() + { + await using var server = await ServerHarness.StartAsync("docker", ServerHarness.DockerSqlite()); + using var logo = await server.GetAsync("/brand/anubis.svg"); + Assert.AreEqual(HttpStatusCode.OK, logo.StatusCode); + var served = await logo.Content.ReadAsByteArrayAsync(); + CollectionAssert.AreEqual(await File.ReadAllBytesAsync(Path.Combine(Repo.Root.FullName, "docs", "design", "logo", "anubis.svg")), served); + Assert.Contains("frame-ancestors 'none'", logo.Headers.GetValues("Content-Security-Policy").Single()); + Assert.AreEqual("nosniff", logo.Headers.GetValues("X-Content-Type-Options").Single()); + } + + [TestMethod] + public async Task DatabaseCommandExportsAndImports() + { + var data = TempFolder.Create("cli"); + var env = ServerHarness.DockerSqlite(); + await using (var server = await ServerHarness.StartAsync("docker", env, dataDir: data)) + { + await server.SignInFirstTimeAsync(); + } + + Microsoft.Data.Sqlite.SqliteConnection.ClearAllPools(); + var archive = Path.Combine(TempFolder.Create("cli-archive"), "archivio"); + using var output = new StringWriter(); + Assert.AreEqual(0, await DatabaseCommand.RunAsync(["export", archive, "--platform", "docker", "--data-dir", data], output, env), output.ToString()); + + var target = TempFolder.Create("cli-target"); + Assert.AreEqual(0, await DatabaseCommand.RunAsync(["import", archive, "--platform", "docker", "--data-dir", target], output, env), output.ToString()); + StringAssert.Contains(output.ToString(), "conteggi e totali coincidono"); + Assert.IsTrue(File.Exists(new DataDirectory(target).InstallationFile)); + + // Import only into an empty database. + Assert.AreEqual(1, await DatabaseCommand.RunAsync(["import", archive, "--platform", "docker", "--data-dir", target], output, env)); + TempFolder.Delete(data); + TempFolder.Delete(target); + TempFolder.Delete(Path.GetDirectoryName(archive)!); + } +} diff --git a/tests/Anubis.Tests/StoresTests.cs b/tests/Anubis.Tests/StoresTests.cs index bcf5b5a..df08b99 100644 --- a/tests/Anubis.Tests/StoresTests.cs +++ b/tests/Anubis.Tests/StoresTests.cs @@ -215,6 +215,28 @@ public sealed class AccessTests Assert.IsGreaterThan(TimeSpan.Zero, limiter.Wait("10.0.0.9"), "troppi errori in tutto: aspettano tutti"); } + [TestMethod] + [TestCategory(Category.Unit)] + public void LoginLimiterCountsAnAttemptBeforeItsCheckEnds() + { + var clock = new ManualClock(DateTimeOffset.UnixEpoch); + var limiter = new LoginLimiter(clock); + + // Five attempts started together, none finished yet: the sixth already waits. + for (var i = 0; i < LoginLimiter.PerAddress; i++) + { + Assert.AreEqual(TimeSpan.Zero, limiter.Begin("10.0.0.2")); + } + + Assert.IsGreaterThan(TimeSpan.Zero, limiter.Begin("10.0.0.2")); + + // A correct password still waiting for its code is taken back; a success clears the address. + limiter.Forgive("10.0.0.2"); + Assert.AreEqual(TimeSpan.Zero, limiter.Begin("10.0.0.2")); + limiter.Succeeded("10.0.0.2"); + Assert.AreEqual(TimeSpan.Zero, limiter.Wait("10.0.0.2")); + } + [TestMethod] [TestCategory(Category.Integration)] public async Task SignInSessionsSecondFactorAndPasswordChange() @@ -251,8 +273,18 @@ public sealed class AccessTests Assert.AreEqual(LoginResult.SecondFactorNeeded, (await access.SignInAsync("una password nuova", null, null, null).ConfigureAwait(false)).Result); var badCode = Totp.Compute(secret, clock.UtcNow.AddMinutes(10)); Assert.AreEqual(LoginResult.WrongSecondFactor, (await access.SignInAsync("una password nuova", badCode, null, null).ConfigureAwait(false)).Result); - Assert.AreEqual(LoginResult.Ok, (await access.SignInAsync("una password nuova", Totp.Compute(secret, clock.UtcNow), null, null).ConfigureAwait(false)).Result); - Assert.IsTrue(await access.DisableSecondFactorAsync(session.User.Id, "una password nuova").ConfigureAwait(false)); + + // Each code works once: the one used to switch it on does not sign in, the next one does, and only once. + Assert.AreEqual(LoginResult.WrongSecondFactor, (await access.SignInAsync("una password nuova", Totp.Compute(secret, clock.UtcNow), null, null).ConfigureAwait(false)).Result); + clock.Advance(TimeSpan.FromSeconds(30)); + var code = Totp.Compute(secret, clock.UtcNow); + Assert.AreEqual(LoginResult.Ok, (await access.SignInAsync("una password nuova", code, null, null).ConfigureAwait(false)).Result); + Assert.AreEqual(LoginResult.WrongSecondFactor, (await access.SignInAsync("una password nuova", code, null, null).ConfigureAwait(false)).Result); + + // Switching it off asks for the password and a fresh code. + clock.Advance(TimeSpan.FromSeconds(30)); + Assert.IsFalse(await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", null).ConfigureAwait(false)); + Assert.IsTrue(await access.DisableSecondFactorAsync(session.User.Id, "una password nuova", Totp.Compute(secret, clock.UtcNow)).ConfigureAwait(false)); // Idle and absolute timeouts. clock.Advance(AccessStore.IdleTimeout); diff --git a/tools/Anubis.Tasks/Program.cs b/tools/Anubis.Tasks/Program.cs index 08129e3..38e2ace 100644 --- a/tools/Anubis.Tasks/Program.cs +++ b/tools/Anubis.Tasks/Program.cs @@ -16,7 +16,8 @@ return command switch "build" => BuildImage("dev"), "ci" => Ci(), "hooks" => Step("Attivazione dell'hook pre-commit (.githooks)", "git", ["config", "core.hooksPath", ".githooks"]) ?? 0, - "seed-demo" => NotYet("seed-demo", 1), + "seed-demo" => Run("dotnet", ["run", "--project", "src/Anubis.Server", "-c", "Release", "--", "--demo", .. rest]), + "screenshots" => Screenshots(rest), "desktop-win" => NotYet("desktop-win", 10), _ => Help(), }; @@ -76,6 +77,106 @@ int BuildImage(string tag) => Step("Costruzione dell'immagine Docker", "docker", ["build", "-f", "deploy/docker/Dockerfile", "-t", $"gitea.encke-hake.ts.net/balbosoft/anubis:{tag}", "."]) ?? 0; +// Demo data photographed at 1440 and 390 pixels, light and dark, to compare with docs/design (SPEC 13.1). Uses the +// Edge or Chrome already on the computer, driven through its DevTools protocol: nothing to install (ADR 0007). +int Screenshots(string[] pages) +{ + var browser = FindBrowser(); + if (browser is null) + { + Console.Error.WriteLine("Serve Microsoft Edge o Google Chrome installato per le fotografie."); + return 2; + } + + var failed = Step("Compilazione del server", "dotnet", ["build", "src/Anubis.Server", "-c", "Release"]); + if (failed is not null) + { + return failed.Value; + } + + var port = FreePort(); + var url = "http://127.0.0.1:" + port.ToString(CultureInfo.InvariantCulture); + var server = new ProcessStartInfo("dotnet") { WorkingDirectory = root, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; + foreach (var argument in new[] { Path.Combine("src", "Anubis.Server", "bin", "Release", "net10.0", "Anubis.Server.dll"), "--demo", "--urls", url }) + { + server.ArgumentList.Add(argument); + } + + using var process = Process.Start(server)!; + process.OutputDataReceived += (_, _) => { }; + process.ErrorDataReceived += (_, _) => { }; + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + try + { + using var http = new System.Net.Http.HttpClient(); + var ready = false; + for (var i = 0; i < 60 && !ready; i++) + { + try + { + ready = http.GetAsync(new Uri(url + "/health")).GetAwaiter().GetResult().IsSuccessStatusCode; + } + catch (System.Net.Http.HttpRequestException) + { + } + + if (!ready) + { + Thread.Sleep(500); + } + } + + if (!ready) + { + Console.Error.WriteLine("Il server dimostrativo non risponde."); + return 1; + } + + var folder = Path.Combine(root, "artifacts", "screenshots"); + Directory.CreateDirectory(folder); + var targets = pages.Length > 0 ? pages : ["/", "/diario", "/impostazioni"]; + using var shots = Shots.Start(browser); + foreach (var page in targets) + { + var name = page == "/" ? "panoramica" : page.Trim('/').Replace('/', '-'); + foreach (var (width, height, dark) in new[] { (1440, 1400, false), (390, 2200, false), (1440, 1400, true) }) + { + var file = Path.Combine(folder, $"{name}-{width.ToString(CultureInfo.InvariantCulture)}{(dark ? "-scuro" : "")}.png"); + shots.Take(url + page, width, height, dark, file); + Console.WriteLine($" {file}"); + } + } + + return 0; + } + finally + { + process.Kill(entireProcessTree: true); + } +} + +static string? FindBrowser() +{ + string[] candidates = + [ + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86), "Microsoft", "Edge", "Application", "msedge.exe"), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Microsoft", "Edge", "Application", "msedge.exe"), + Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles), "Google", "Chrome", "Application", "chrome.exe"), + "/usr/bin/chromium", "/usr/bin/chromium-browser", "/usr/bin/google-chrome", "/usr/bin/microsoft-edge", + ]; + return candidates.FirstOrDefault(File.Exists); +} + +static int FreePort() +{ + var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0); + listener.Start(); + var port = ((System.Net.IPEndPoint)listener.LocalEndpoint).Port; + listener.Stop(); + return port; +} + int NotYet(string name, int phase) { Console.Error.WriteLine($"'tasks {name}' arriva nella Fase {phase.ToString(CultureInfo.InvariantCulture)}."); @@ -92,7 +193,8 @@ int Help() tasks build costruisce l'immagine Docker tasks ci come la CI: check, test su PostgreSQL, immagine tasks hooks attiva l'hook che esegue check prima di ogni commit - tasks seed-demo dati dimostrativi (Fase 1) + tasks seed-demo avvia la modalità dimostrativa (dati dell'appendice F, database a parte) + tasks screenshots fotografa le schermate dimostrative a 1440 e 390 pixel tasks desktop-win installatore Windows (Fase 10) """); return command == "help" ? 0 : 1; diff --git a/tools/Anubis.Tasks/Shots.cs b/tools/Anubis.Tasks/Shots.cs new file mode 100644 index 0000000..f119c64 --- /dev/null +++ b/tools/Anubis.Tasks/Shots.cs @@ -0,0 +1,177 @@ +using System.Diagnostics; +using System.Net.WebSockets; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +/// +/// Screenshots through the DevTools protocol of the Edge or Chrome already installed (ADR 0007). The protocol sets the +/// exact width: a headless window cannot be narrower than about 500 pixels, too wide for the 390-pixel phone. +/// +internal sealed class Shots : IDisposable +{ + private readonly Process _browser; + private readonly ClientWebSocket _socket = new(); + private readonly string _profile; + private int _id; + + private Shots(Process browser, string profile) + { + _browser = browser; + _profile = profile; + } + + public static Shots Start(string browserPath) + { + var profile = Path.Combine(Path.GetTempPath(), "anubis-shots-" + Guid.NewGuid().ToString("N")); + var info = new ProcessStartInfo(browserPath) + { + UseShellExecute = false, + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (var argument in new[] { "--headless=new", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check", + "--remote-debugging-port=0", "--user-data-dir=" + profile, "about:blank" }) + { + info.ArgumentList.Add(argument); + } + + var process = Process.Start(info)!; + process.OutputDataReceived += (_, _) => { }; + process.ErrorDataReceived += (_, _) => { }; + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + var shots = new Shots(process, profile); + try + { + shots.Connect(); + return shots; + } + catch + { + shots.Dispose(); + throw; + } + } + + // The browser writes its port into DevToolsActivePort; the page target is found through /json/list. + private void Connect() + { + var portFile = Path.Combine(_profile, "DevToolsActivePort"); + for (var i = 0; i < 60 && !File.Exists(portFile); i++) + { + Thread.Sleep(250); + } + + var port = File.ReadAllLines(portFile)[0].Trim(); + using var http = new HttpClient(); + string? target = null; + for (var i = 0; i < 40 && target is null; i++) + { + var list = JsonNode.Parse(http.GetStringAsync(new Uri($"http://127.0.0.1:{port}/json/list")).GetAwaiter().GetResult())!.AsArray(); + target = list.FirstOrDefault(t => (string?)t!["type"] == "page")?["webSocketDebuggerUrl"]?.GetValue(); + if (target is null) + { + Thread.Sleep(250); + } + } + + _socket.ConnectAsync(new Uri(target ?? throw new InvalidOperationException("Nessuna pagina nel browser.")), CancellationToken.None).GetAwaiter().GetResult(); + Send("Page.enable", new JsonObject()); + } + + /// Opens at the given size and theme and saves the visible part as PNG. + public void Take(string url, int width, int height, bool dark, string file) + { + Send("Emulation.setDeviceMetricsOverride", new JsonObject + { + ["width"] = width, + ["height"] = height, + ["deviceScaleFactor"] = 2, + ["mobile"] = width < 768, + }); + Send("Emulation.setEmulatedMedia", new JsonObject + { + ["features"] = new JsonArray(new JsonObject { ["name"] = "prefers-color-scheme", ["value"] = dark ? "dark" : "light" }), + }); + Send("Page.navigate", new JsonObject { ["url"] = url }, waitForEvent: "Page.loadEventFired"); + Thread.Sleep(500); + var result = Send("Page.captureScreenshot", new JsonObject { ["format"] = "png" }); + File.WriteAllBytes(file, Convert.FromBase64String(result["data"]!.GetValue())); + } + + // Sends one command and waits for its answer (and, if asked, for an event), skipping everything else. + private JsonNode Send(string method, JsonObject parameters, string? waitForEvent = null) + { + var id = ++_id; + var message = new JsonObject { ["id"] = id, ["method"] = method, ["params"] = parameters }; + _socket.SendAsync(Encoding.UTF8.GetBytes(message.ToJsonString()), WebSocketMessageType.Text, true, CancellationToken.None).GetAwaiter().GetResult(); + JsonNode? answer = null; + var eventSeen = waitForEvent is null; + using var limit = new CancellationTokenSource(TimeSpan.FromSeconds(30)); + while (answer is null || !eventSeen) + { + var received = Receive(limit.Token); + if ((int?)received["id"] == id) + { + if (received["error"] is { } error) + { + throw new InvalidOperationException(method + ": " + error.ToJsonString()); + } + + answer = received["result"] ?? new JsonObject(); + } + else if ((string?)received["method"] == waitForEvent) + { + eventSeen = true; + } + } + + return answer; + } + + private JsonNode Receive(CancellationToken cancellationToken) + { + var buffer = new byte[64 * 1024]; + using var all = new MemoryStream(); + WebSocketReceiveResult result; + do + { + result = _socket.ReceiveAsync(buffer, cancellationToken).GetAwaiter().GetResult(); + all.Write(buffer, 0, result.Count); + } + while (!result.EndOfMessage); + + return JsonNode.Parse(all.ToArray(), documentOptions: new JsonDocumentOptions { MaxDepth = 64 })!; + } + + public void Dispose() + { + _socket.Dispose(); + try + { + _browser.Kill(entireProcessTree: true); + _browser.WaitForExit(5000); + } + catch (InvalidOperationException) + { + } + + _browser.Dispose(); + for (var i = 0; i < 10 && Directory.Exists(_profile); i++) + { + try + { + Directory.Delete(_profile, recursive: true); + } + catch (IOException) + { + Thread.Sleep(300); + } + catch (UnauthorizedAccessException) + { + Thread.Sleep(300); + } + } + } +}