diff --git a/.gitattributes b/.gitattributes index ccd596d..18ab574 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,7 +1,7 @@ # Gli script di shell restano con le righe Unix anche su un Windows con core.autocrlf: bash non regge il CR. *.sh text eol=lf -# Il programma di installazione si costruisce anche da Linux con makensis. -*.nsi text eol=lf +# Anche i programmi awk della CI (json.awk e quelli che lo usano), che girano con bash. +*.awk text eol=lf # Binari: mai conversioni. *.ico binary *.png binary diff --git a/.gitea/scripts/ambiente-prove.sh b/.gitea/scripts/ambiente-prove.sh index d7c0f47..ee56ff6 100755 --- a/.gitea/scripts/ambiente-prove.sh +++ b/.gitea/scripts/ambiente-prove.sh @@ -1,9 +1,10 @@ #!/usr/bin/env bash -# Prepara il contenitore Debian del lavoro «prove» (node:24-trixie: Debian 13 con Node, che serve alle azioni) perché -# nessuna prova si salti: Chromium vero della distribuzione (su Ubuntu è uno snap, che nei contenitori non va) con le -# sue lingue, Xvfb, makensis (NSIS) e zip, la lingua it_IT.UTF-8, fusi orari, ICU e gli stessi -# caratteri dell'immagine di Febe. Node c'è già (prova della pagina di accesso); setpriv, getent e l'utente nobody -# (65534) vengono con Debian (prove dell'avvio del contenitore). +# Prepara il contenitore Debian del lavoro «prove» (debian:trixie, Debian 13 senza nient'altro: nessuna azione +# JavaScript, quindi niente Node) perché nessuna prova si salti: Chromium vero della distribuzione (su Ubuntu è uno +# snap, che nei contenitori non va) con le sue lingue, Xvfb, la lingua it_IT.UTF-8, fusi orari e gli stessi caratteri +# dell'immagine di Febe; ICU, OpenSSL, zlib e libstdc++ per l'SDK .NET (dotnet.sh). git, curl e i certificati li +# installa il passo prima dei sorgenti. setpriv, getent e l'utente nobody (65534) vengono con Debian (prove +# dell'avvio del contenitore). # # .gitea/scripts/ambiente-prove.sh set -euo pipefail @@ -16,9 +17,8 @@ $sudo apt-get update -qq $sudo apt-get install -y -qq --no-install-recommends \ chromium chromium-l10n \ xvfb \ - nsis zip \ - locales tzdata libicu76 ca-certificates \ - fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \ + locales tzdata libicu76 libssl3t64 zlib1g libstdc++6 ca-certificates curl git \ + fonts-noto-color-emoji fonts-dejavu-core \ util-linux procps > /dev/null $sudo sed -i 's/^# *\(it_IT.UTF-8 UTF-8\)/\1/' /etc/locale.gen $sudo locale-gen > /dev/null @@ -26,8 +26,10 @@ $sudo locale-gen > /dev/null echo "== Strumenti delle prove" chromium --version command -v Xvfb -echo "makensis $(makensis -VERSION)" -echo "node $(node --version)" locale -a | grep -i '^it_IT\.utf8$' -for strumento in setpriv getent stat chown sh; do command -v "$strumento" > /dev/null || { echo "Manca $strumento." >&2; exit 1; }; done +for strumento in setpriv getent stat chown sh awk sort; do command -v "$strumento" > /dev/null || { echo "Manca $strumento." >&2; exit 1; }; done +if command -v node > /dev/null; then + echo "C'è node in questo contenitore: la CI non deve usarlo (nessuna azione JavaScript, nessuno script Node)." >&2 + exit 1 +fi getent passwd 65534 > /dev/null && getent group 65534 > /dev/null || { echo "Mancano l'utente o il gruppo 65534 (nobody)." >&2; exit 1; } diff --git a/.gitea/scripts/artefatti.sh b/.gitea/scripts/artefatti.sh new file mode 100644 index 0000000..c3a2274 --- /dev/null +++ b/.gitea/scripts/artefatti.sh @@ -0,0 +1,67 @@ +#!/usr/bin/env bash +# Artefatti della CI, al posto di actions/upload-artifact (un'azione JavaScript, che vuole Node): i file vanno nel +# registro dei pacchetti di Gitea, pacchetto generico febe-ci, una versione per esecuzione: +# +# -ci. dal flusso verifica (come Febe-Setup--ci..exe) +# -rilascio. dal flusso rilascio +# +# con da Directory.Build.props e il numero dell'esecuzione (NUMERO). Si scaricano dalla pagina del +# pacchetto su Gitea (proprietario ▸ Pacchetti ▸ febe-ci). La pulizia del lunedì (pulizia-docker.sh completa) toglie le +# versioni create più di 14 giorni prima, come faceva la scadenza degli artefatti. +# +# .gitea/scripts/artefatti.sh verifica|rilascio ... +# +# Variabili: REGISTRY_TOKEN (token con «package: read and write», solo nell'intestazione di curl, mai stampato), GITEA_URL +# (l'indirizzo del server, gitea.server_url), PROPRIETARIO, NUMERO. Senza REGISTRY_TOKEN un avviso e nessun file +# caricato: il lavoro resta verde, come per l'immagine. Un file che manca o un rifiuto del registro fanno fallire il +# passo. Un file con lo stesso nome già caricato (un nuovo tentativo della stessa esecuzione) si sostituisce. +set -euo pipefail + +flusso="${1:-}" +case "$flusso" in + verifica) suffisso=ci ;; + rilascio) suffisso=rilascio ;; + *) echo "Uso: artefatti.sh verifica|rilascio ..." >&2; exit 2 ;; +esac +shift +(($# > 0)) || { echo "Indica almeno un file da caricare." >&2; exit 2; } +cd "$(git rev-parse --show-toplevel)" + +numero="${NUMERO:-}" +[[ "$numero" =~ ^[0-9]+$ ]] || { echo "Manca NUMERO, il numero dell'esecuzione, o non è un numero: «$numero»." >&2; exit 2; } +v=$(sed -n 's:.*\(.*\).*:\1:p' Directory.Build.props | head -n 1) +versione="$v-$suffisso.$numero" +[[ "$versione" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?-(ci|rilascio)\.[0-9]+$ ]] || { echo "Versione degli artefatti non valida: «$versione»." >&2; exit 2; } + +for file in "$@"; do + [[ -f "$file" ]] || { echo "Manca l'artefatto $file." >&2; exit 1; } + [[ "$(basename "$file")" =~ ^[0-9A-Za-z._-]+$ ]] || { echo "Nome di file non adatto a un pacchetto: «$(basename "$file")»." >&2; exit 2; } +done + +if [[ -z "${REGISTRY_TOKEN:-}" ]]; then + echo "::warning::Manca il segreto REGISTRY_TOKEN: gli artefatti ($*) non vanno sul registro dei pacchetti. Aggiungilo (token con package: read and write) per averli per 14 giorni." + exit 0 +fi +proprietario="${PROPRIETARIO:?Manca PROPRIETARIO.}" +base="${GITEA_URL:?Manca GITEA_URL.}" +base="${base%/}/api/packages/$proprietario/generic/febe-ci/$versione" + +# Una chiamata al registro: il codice HTTP, 000 se Gitea non risponde. Il token sta solo nell'intestazione di curl. +chiedi() { + local codice + codice=$(curl -sS --max-time 900 -H "Authorization: token $REGISTRY_TOKEN" -o /dev/null -w '%{http_code}' "$@") || true + echo "${codice:-000}" +} + +for file in "$@"; do + nome="$(basename "$file")" + codice=$(chiedi -X PUT --upload-file "$file" "$base/$nome") + if [[ "$codice" == 409 ]]; then + codice=$(chiedi -X DELETE "$base/$nome") + [[ "$codice" == 204 ]] || { echo "Il registro non toglie la copia precedente di $nome: risponde $codice." >&2; exit 1; } + codice=$(chiedi -X PUT --upload-file "$file" "$base/$nome") + fi + [[ "$codice" == 201 ]] || { echo "Il registro non accetta $nome: risponde $codice." >&2; exit 1; } + echo "$nome caricato ($(du -h "$file" | cut -f1))" +done +echo "Artefatti: ${GITEA_URL%/}/$proprietario/-/packages/generic/febe-ci/$versione" diff --git a/.gitea/scripts/controlli.sh b/.gitea/scripts/controlli.sh index 023a0de..10de5cd 100755 --- a/.gitea/scripts/controlli.sh +++ b/.gitea/scripts/controlli.sh @@ -4,18 +4,21 @@ # # bash .gitea/scripts/controlli.sh # -# 1. ogni script di shell del repository è sintassi valida (bash -n; sh -n per quelli in sh) e ha le righe Unix; gli -# script Node della CI (.gitea/scripts/*.js) sono JavaScript valido (node --check); -# 2. i flussi della CI non hanno tabulazioni (YAML non le accetta come rientro); +# 1. ogni script di shell del repository è sintassi valida (bash -n; sh -n per quelli in sh) e ha le righe Unix, come +# i programmi awk della CI; +# 2. i flussi della CI si leggono come YAML a blocchi: niente tabulazioni né righe Windows, rientri di due spazi fuori +# dai blocchi di testo, «on:» e «jobs:» presenti; e sono fatti solo di comandi: nessun «uses:», cioè nessuna +# azione (le azioni JavaScript vogliono Node, e la CI di Febe è scritta in casa: decisione del 18 novembre 2026); # 3. nessun file contiene segni di conflitto rimasti da un'unione; # 4. la versione di Directory.Build.props è nella forma x.y.z[-qualcosa], quella che installer/costruisci.sh accetta; # 5. ogni progetto elencato in Febe.slnx esiste; -# 6. ogni file JSON del repository si legge (configurazioni, campioni ripuliti, criteri di Chromium). +# 6. ogni file JSON del repository si legge (configurazioni, campioni ripuliti, criteri di Chromium), con json.awk. set -uo pipefail radice="$(git rev-parse --show-toplevel)" || exit 2 cd "$radice" || exit 2 errori=0 +export LC_ALL=C errore() { echo "ERRORE: $*" >&2 @@ -35,25 +38,48 @@ while IFS= read -r -d '' script; do fi done < <(git ls-files -z -- '*.sh') echo " $quanti script controllati" - -echo "== Script Node della CI" -if command -v node > /dev/null; then - quanti=0 - while IFS= read -r -d '' script; do - quanti=$((quanti + 1)) - node --check "$script" || errore "$script: JavaScript non valido." - done < <(git ls-files -z -- '.gitea/scripts/*.js') - echo " $quanti script controllati" -else - errore "manca node: gli script Node della CI non si possono controllare." -fi +while IFS= read -r -d '' programma; do + if grep -q $'\r' "$programma"; then + errore "$programma ha righe Windows (CR) (.gitattributes chiede eol=lf)." + fi +done < <(git ls-files -z -- '*.awk') echo "== Flussi della CI" +quanti=0 while IFS= read -r -d '' flusso; do + quanti=$((quanti + 1)) if grep -n $'\t' "$flusso" > /dev/null; then errore "$flusso contiene tabulazioni: in YAML il rientro si fa con gli spazi." fi + # Un blocco di testo («run: |», «>-») tiene tutte le righe più rientrate della sua chiave; fuori, i rientri sono di + # due spazi in due e nessuna riga chiama un'azione. + if rilievi=$(awk ' + FNR == 1 { blocco = -1; on = 0; jobs = 0 } + { + riga = $0 + if (riga ~ /\r$/) { print FNR ": riga Windows (CR)"; next } + match(riga, /^ */) + rientro = RLENGTH + vuota = riga ~ /^ *$/ + if (blocco >= 0) { + if (vuota || rientro > blocco) next + blocco = -1 + } + if (vuota || riga ~ /^ *#/) next + if (rientro % 2 == 1) print FNR ": rientro dispari" + if (riga ~ /^ *(- +)?uses *:/) print FNR ": «uses:» (nessuna azione: solo comandi)" + if (riga ~ /^on:/) on = 1 + if (riga ~ /^jobs:/) jobs = 1 + if (riga ~ /: *[|>][-+]?[0-9]? *(#.*)?$/) blocco = rientro + } + END { + if (!on) print "manca «on:»" + if (!jobs) print "manca «jobs:»" + }' "$flusso") && [[ -n "$rilievi" ]]; then + errore "$flusso:"$'\n'"$(sed 's/^/ riga /; s/^ riga manca/ manca/' <<< "$rilievi")" + fi done < <(git ls-files -z -- '.gitea/workflows/*.yml' '.gitea/workflows/*.yaml') +echo " $quanti flussi controllati" echo "== Segni di conflitto" if conflitti=$(git grep -n -I -E '^(<{7}|>{7})( |$)' -- . ':!*.png' ':!*.jpg'); then @@ -78,21 +104,13 @@ done < <(sed -n 's:.* 0)); then + if ! guasti=$(awk -f .gitea/scripts/json.awk -f .gitea/scripts/json-valido.awk "${json[@]}"); then errore "JSON non valido:" - echo "$guasti" >&2 + echo "${guasti:-(nessun dettaglio)}" >&2 fi -else - errore "manca node: i file JSON non si possono controllare." fi if ((errori > 0)); then diff --git a/.gitea/scripts/costruisci-immagine.sh b/.gitea/scripts/costruisci-immagine.sh index 9a5e9b1..4c71e0e 100755 --- a/.gitea/scripts/costruisci-immagine.sh +++ b/.gitea/scripts/costruisci-immagine.sh @@ -3,9 +3,15 @@ # stessi argomenti e le stesse etichette: la costruzione che si pubblica esce intera dalla cache di quella che si è # provata e scansionata, quindi gli strati sono gli stessi. # +# costruisci-immagine.sh builder il builder buildx dell'esecuzione (BUILDER), con il +# driver docker-container e la configurazione di +# buildkit che dice che il registro di casa risponde in +# HTTP (al posto di docker/setup-buildx-action, un'azione +# JavaScript); lo toglie pulizia-docker.sh esecuzione # costruisci-immagine.sh archivio archivio dell'immagine, per docker load e per Trivy -# costruisci-immagine.sh pubblica ... spinta sul registro da buildx: le credenziali sono -# già nella configurazione del client, il demone non +# costruisci-immagine.sh pubblica ... spinta sul registro REGISTRY da buildx, con +# REGISTRO_UTENTE e REGISTRO_TOKEN in una configurazione +# del client solo sua, tolta alla fine; il demone non # parla mai con il registro (proverebbe HTTPS) # # L'immagine è un manifest semplice, senza attestazioni (--provenance=false --sbom=false). Con le attestazioni, che @@ -20,10 +26,26 @@ # lo controlla PipelineTests. set -euo pipefail -modo="${1:?Indica il modo: archivio o pubblica.}" +modo="${1:?Indica il modo: builder, archivio o pubblica.}" shift cd "$(git rev-parse --show-toplevel)" +if [[ "$modo" == builder ]]; then + registro="${1:?Indica il registro, per esempio 192.168.30.23:3000.}" + # Solo un nome di host (o un indirizzo) con la porta: il valore finisce in un file TOML. + [[ "$registro" =~ ^[A-Za-z0-9.-]+(:[0-9]+)?$ ]] || { echo "Registro non valido: «$registro»." >&2; exit 2; } + configurazione="${RUNNER_TEMP:-/tmp}/buildkitd-${BUILDER:?}.toml" + printf '[registry."%s"]\n http = true\n insecure = true\n' "$registro" > "$configurazione" + # --buildkitd-config da buildx 0.13; prima si chiamava --config. + opzione=--buildkitd-config + aiuto=$(docker buildx create --help 2> /dev/null) || true + [[ "$aiuto" == *--buildkitd-config* ]] || opzione=--config + docker buildx create --name "$BUILDER" --driver docker-container "$opzione" "$configurazione" --bootstrap + rm -f "$configurazione" + docker buildx inspect "$BUILDER" + exit 0 +fi + comuni=(--builder "${BUILDER:?}" -f docker/Dockerfile --provenance=false --sbom=false --build-arg "VERSION=${VERSIONE:?}" --build-arg "GIT_COMMIT=${GIT_COMMIT:?}" --label "febe.ci.workflow=${FLUSSO:?}" --label "febe.ci.run=${ESECUZIONE:?}" @@ -39,15 +61,47 @@ case "$modo" in ;; pubblica) (($# > 0)) || { echo "Indica almeno un nome:etichetta da pubblicare." >&2; exit 2; } + registro="${REGISTRY:?Manca REGISTRY, il registro su cui pubblicare.}" + [[ "$registro" =~ ^[A-Za-z0-9.-]+(:[0-9]+)?$ ]] || { echo "Registro non valido: «$registro»." >&2; exit 2; } + [[ -n "${REGISTRO_UTENTE:-}" && -n "${REGISTRO_TOKEN:-}" ]] || { echo "Mancano REGISTRO_UTENTE e REGISTRO_TOKEN." >&2; exit 2; } etichette=() for nome in "$@"; do etichette+=(-t "$nome") done - docker buildx build "${comuni[@]}" "${etichette[@]}" --push . + + # Le credenziali in una configurazione del client tutta nostra, solo per questa spinta e poi tolta: quella del + # runner non si tocca mai (niente jq per modificarla, nessuna credenziale che resti nella sua cartella). buildx le + # passa al builder; il demone non c'entra (proverebbe HTTPS). Del client originale restano i plugin, i contesti e + # il contesto corrente; i builder buildx li trova con BUILDX_CONFIG. Il nome è fisso per l'esecuzione, così il passo + # «Pulizia (sempre)» la toglie anche dopo un'interruzione che salta la trap. + originale="${DOCKER_CONFIG:-$HOME/.docker}" + configurazione="${RUNNER_TEMP:-/tmp}/febe-docker-${ESECUZIONE}" + rm -rf "$configurazione" + trap 'rm -rf "$configurazione"' EXIT + (umask 077 && mkdir -p "$configurazione") + for parte in cli-plugins contexts; do + if [[ -e "$originale/$parte" ]]; then ln -s "$originale/$parte" "$configurazione/$parte"; fi + done + contesto="" + if [[ -s "$originale/config.json" ]]; then + contesto=$(bash .gitea/scripts/json.sh campi "" currentContext "$originale/config.json" 2> /dev/null) || contesto="" + [[ "$contesto" =~ ^[A-Za-z0-9][A-Za-z0-9_.+-]*$ ]] || contesto="" + fi + credenziali=$(printf '%s:%s' "$REGISTRO_UTENTE" "$REGISTRO_TOKEN" | base64 -w0) + # Solo caratteri di base64, e il registro controllato sopra: il JSON si scrive senza bisogno di escape. + [[ "$credenziali" =~ ^[A-Za-z0-9+/]+=*$ ]] || { echo "Credenziali del registro non codificabili." >&2; exit 2; } + ( + umask 077 + printf '{"auths":{"%s":{"auth":"%s"}}%s}\n' "$registro" "$credenziali" "${contesto:+,\"currentContext\":\"$contesto\"}" \ + > "$configurazione/config.json" + ) + unset credenziali + DOCKER_CONFIG="$configurazione" BUILDX_CONFIG="${BUILDX_CONFIG:-$originale/buildx}" \ + docker buildx build "${comuni[@]}" "${etichette[@]}" --push . printf 'Pubblicata: %s\n' "$@" ;; *) - echo "Modo sconosciuto: «$modo» (archivio o pubblica)." >&2 + echo "Modo sconosciuto: «$modo» (builder, archivio o pubblica)." >&2 exit 2 ;; esac diff --git a/.gitea/scripts/dotnet-sdk.awk b/.gitea/scripts/dotnet-sdk.awk new file mode 100644 index 0000000..20245fc --- /dev/null +++ b/.gitea/scripts/dotnet-sdk.awk @@ -0,0 +1,56 @@ +# For dotnet.sh, with json.awk: in the release metadata of a .NET channel (releases.json of +# builds.dotnet.microsoft.com/dotnet/release-metadata//), the newest SDK («latest-sdk») and the address and +# SHA-512 of its archive for the rid asked: +# +# LC_ALL=C awk -v rid=linux-x64 -f json.awk -f dotnet-sdk.awk releases.json +# +# Prints «
» and exits with 0, or says why on stderr and exits with 1. The archive +# is the file object with that address: https, on one of Microsoft's two hosts of .NET builds, named +# dotnet-sdk--.tar.gz, with a hash of 128 hexadecimal digits. + +function json_begin(file) {} + +function json_open(kind) { + if (kind == "o") { + address[json_depth] = "" + hash[json_depth] = "" + } +} + +function json_scalar(kind, value) { + if (kind != "s" || json_depth == 0 || json_stack[json_depth] != "o") return + if (json_depth == 1 && json_at[1] == "latest-sdk") latest = value + if (json_at[json_depth] == "url") address[json_depth] = value + if (json_at[json_depth] == "hash") hash[json_depth] = value +} + +function json_close(kind) { + if (kind == "o" && address[json_depth] != "") sha512[address[json_depth]] = hash[json_depth] +} + +function json_end(file, error) { + problem = error +} + +END { + if (problem != "") { + print "metadati dei rilasci .NET non validi: " problem > "/dev/stderr" + exit 1 + } + if (latest !~ /^[0-9]+[.][0-9]+[.][0-9]+(-[0-9A-Za-z.]+)?$/) { + print "nei metadati dei rilasci .NET manca «latest-sdk» o non è una versione: «" substr(latest, 1, 40) "»" > "/dev/stderr" + exit 1 + } + name = "dotnet-sdk-" latest "-" rid ".tar.gz" + for (candidate in sha512) { + if (substr(candidate, length(candidate) - length(name)) != "/" name) continue + if (candidate !~ /^https:[/][/](builds[.]dotnet[.]microsoft[.]com|dotnetcli[.]blob[.]core[.]windows[.]net)[/]/) continue + if (sha512[candidate] !~ /^[0-9a-fA-F]+$/ || length(sha512[candidate]) != 128) continue + found = candidate + } + if (found == "") { + print "nei metadati dei rilasci .NET non c'è l'archivio " name " con la sua impronta" > "/dev/stderr" + exit 1 + } + print latest "\t" found "\t" tolower(sha512[found]) +} diff --git a/.gitea/scripts/dotnet.sh b/.gitea/scripts/dotnet.sh new file mode 100644 index 0000000..5f46e48 --- /dev/null +++ b/.gitea/scripts/dotnet.sh @@ -0,0 +1,71 @@ +#!/usr/bin/env bash +# Installa l'SDK .NET per un lavoro della CI, al posto di actions/setup-dotnet (un'azione JavaScript, che vuole Node). +# Come quella prende l'ultimo SDK del canale (predefinito 10.0, come «10.0.x»), ma lo verifica: la versione e +# l'impronta SHA-512 dell'archivio vengono dai metadati dei rilasci di Microsoft (letti con json.awk e dotnet-sdk.awk, +# awk POSIX), l'archivio da builds.dotnet.microsoft.com, e si installa solo se l'impronta coincide. Mai uno script di +# installazione scaricato al volo. +# +# .gitea/scripts/dotnet.sh [canale] +# +# Dove: nella cache degli strumenti del runner (RUNNER_TOOL_CACHE, il volume act-toolcache che act_runner monta in ogni +# lavoro, anche nei contenitori), in febe-dotnet/; senza, nella cartella temporanea del lavoro. Una versione +# già installata e verificata non si riscarica; le versioni più vecchie di febe-dotnet si tolgono. Aggiunge dotnet al +# PATH dei passi seguenti (GITHUB_PATH) e scrive DOTNET_ROOT (GITHUB_ENV); fuori dalla CI stampa solo la cartella. +# Serve curl, tar, sha512sum e awk. Nel contenitore Debian delle prove le librerie di sistema dell'SDK (ICU, OpenSSL) +# le installa ambiente-prove.sh; sull'immagine del runner ICU non è garantito, e i lavori che ci girano (installatore, +# windows, release) usano DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true. +set -euo pipefail + +canale="${1:-10.0}" +[[ "$canale" =~ ^[0-9]+\.[0-9]+$ ]] || { echo "Canale .NET non valido: «$canale» (per esempio 10.0)." >&2; exit 2; } +qui="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +case "$(uname -s)-$(uname -m)" in + Linux-x86_64) rid=linux-x64 ;; + Linux-aarch64) rid=linux-arm64 ;; + *) echo "Piattaforma non prevista per l'SDK .NET della CI: $(uname -s)-$(uname -m)." >&2; exit 2 ;; +esac + +radice="${RUNNER_TOOL_CACHE:-${RUNNER_TEMP:-/tmp}}/febe-dotnet" +mkdir -p "$radice" +temporanea="$(mktemp -d "$radice/.scarico-XXXXXX")" +trap 'rm -rf "$temporanea"' EXIT + +echo "== SDK .NET $canale" +curl -fsSL --retry 3 --retry-delay 5 --max-time 120 -o "$temporanea/releases.json" \ + "https://builds.dotnet.microsoft.com/dotnet/release-metadata/$canale/releases.json" +scelta=$(LC_ALL=C awk -v rid="$rid" -f "$qui/json.awk" -f "$qui/dotnet-sdk.awk" "$temporanea/releases.json") +IFS=$'\t' read -r versione indirizzo sha512 <<< "$scelta" +[[ "$versione" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.]+)?$ ]] || { echo "Versione dell'SDK non valida: «$versione»." >&2; exit 1; } +[[ "$versione" == "$canale".* ]] || { echo "L'SDK $versione non è del canale $canale." >&2; exit 1; } + +cartella="$radice/$versione" +if [[ -x "$cartella/dotnet" && -f "$cartella/.febe-sha512" && "$(cat "$cartella/.febe-sha512")" == "$sha512" ]]; then + echo " $versione già installato in $cartella" +else + echo " $versione da $indirizzo" + curl -fsSL --retry 3 --retry-delay 5 --max-time 900 -o "$temporanea/sdk.tar.gz" "$indirizzo" + if ! echo "$sha512 $temporanea/sdk.tar.gz" | sha512sum -c --quiet -; then + echo "L'impronta SHA-512 dell'SDK $versione non è quella dei metadati di Microsoft: non si installa." >&2 + exit 1 + fi + mkdir "$temporanea/sdk" + tar -xzf "$temporanea/sdk.tar.gz" -C "$temporanea/sdk" + echo "$sha512" > "$temporanea/sdk/.febe-sha512" + rm -rf "$cartella" + mv "$temporanea/sdk" "$cartella" +fi + +# Le versioni precedenti, che nessun lavoro userà più (la CI fa un lavoro alla volta), e gli scarichi interrotti. +for vecchia in "$radice"/* "$radice"/.scarico-*; do + [[ -d "$vecchia" && "$vecchia" != "$cartella" && "$vecchia" != "$temporanea" ]] || continue + rm -rf "$vecchia" +done + +"$cartella/dotnet" --version +if [[ -n "${GITHUB_PATH:-}" ]]; then + echo "$cartella" >> "$GITHUB_PATH" + echo "DOTNET_ROOT=$cartella" >> "$GITHUB_ENV" +else + echo "$cartella" +fi diff --git a/.gitea/scripts/json-campi.awk b/.gitea/scripts/json-campi.awk new file mode 100644 index 0000000..2506b20 --- /dev/null +++ b/.gitea/scripts/json-campi.awk @@ -0,0 +1,60 @@ +# For json.sh campi, with json.awk: the plain fields of the objects found at one place of a JSON text. +# +# LC_ALL=C awk -v percorso= -v campi= -f json.awk -f json-campi.awk ... +# +# percorso is the way from the root to the objects: keys and indexes separated by «/», «*» for any key or index, empty +# for the root object itself. «*» is every object of a root list; «Results/*/Vulnerabilities/*» every vulnerability of +# every result of Trivy. For each object found there, in the order of the text, one line with the values of campi in +# the order asked, separated by a TAB: a string decoded (TAB, CR and LF inside become spaces, so a line stays a line), a +# number as written, true, false and null as words; a field that is missing, or holds a list or an object, is empty. +# +# A file that is not a valid JSON text prints nothing at all (not even the lines found before the error): the reason +# goes to stderr and the exit status is 2. A valid text with no object at that place prints nothing and exits with 0. + +BEGIN { + steps = percorso == "" ? 0 : split(percorso, step, "/") + wanted = split(campi, field, ",") + for (i = 1; i <= wanted; i++) column[field[i]] = i + broken = 0 +} + +function json_begin(file) { + inside = 0 + rows = "" +} + +function json_open(kind, d) { + if (inside || kind != "o" || json_depth != steps + 1) return + for (d = 1; d <= steps; d++) { + if (step[d] != "*" && (json_at[d] "") != step[d]) return + } + inside = 1 + split("", value) +} + +function json_scalar(kind, text) { + if (!inside || json_depth != steps + 1 || !((json_at[json_depth] "") in column)) return + if (kind == "s") gsub(/[\t\r\n]/, " ", text) + value[column[json_at[json_depth] ""]] = text +} + +function json_close(kind, line, i) { + if (!inside || json_depth != steps + 1) return + inside = 0 + line = "" + for (i = 1; i <= wanted; i++) line = line (i > 1 ? "\t" : "") ((i in value) ? value[i] : "") + rows = rows line "\n" +} + +function json_end(file, error) { + if (error != "") { + print file ": " error > "/dev/stderr" + broken = 1 + } else { + printf "%s", rows + } +} + +END { + exit (broken ? 2 : 0) +} diff --git a/.gitea/scripts/json-stringa.awk b/.gitea/scripts/json-stringa.awk new file mode 100644 index 0000000..c93c964 --- /dev/null +++ b/.gitea/scripts/json-stringa.awk @@ -0,0 +1,33 @@ +# For json.sh stringa: the text read on standard input as one JSON string (RFC 8259), quotes included, on one line. +# +# printf '%s' "$testo" | LC_ALL=C awk -f json-stringa.awk +# +# The lines are joined by a line feed («\n»); a line feed at the very end of the input is not kept. The quote, the +# backslash and every control character below 0x20 are escaped; every other byte passes as it is (UTF-8 stays UTF-8, +# which JSON allows). The text is read byte by byte under LC_ALL=C: fine for the notes of a release, a name, a tag. + +BEGIN { + for (i = 1; i < 32; i++) escaped[sprintf("%c", i)] = sprintf("\\u%04x", i) + escaped["\b"] = "\\b" + escaped["\f"] = "\\f" + escaped["\n"] = "\\n" + escaped["\r"] = "\\r" + escaped["\t"] = "\\t" + escaped["\""] = "\\\"" + escaped["\\"] = "\\\\" + text = "" +} + +{ + text = (NR > 1 ? text "\n" : "") $0 +} + +END { + out = "" + n = length(text) + for (i = 1; i <= n; i++) { + c = substr(text, i, 1) + out = out ((c in escaped) ? escaped[c] : c) + } + printf "\"%s\"\n", out +} diff --git a/.gitea/scripts/json-valido.awk b/.gitea/scripts/json-valido.awk new file mode 100644 index 0000000..036c8cb --- /dev/null +++ b/.gitea/scripts/json-valido.awk @@ -0,0 +1,22 @@ +# Checks that every file named is a valid JSON text (controlli.sh), with json.awk: +# +# LC_ALL=C awk -f json.awk -f json-valido.awk ... +# +# Prints «file: reason» for each file that is not, and on stderr how many were checked; exits with 1 if one is not. +function json_begin(file) {} +function json_open(kind) {} +function json_close(kind) {} +function json_scalar(kind, value) {} + +function json_end(file, error) { + checked++ + if (error != "") { + print file ": " error + broken++ + } +} + +END { + printf " %d file controllati\n", checked > "/dev/stderr" + exit (broken > 0 ? 1 : 0) +} diff --git a/.gitea/scripts/json.awk b/.gitea/scripts/json.awk new file mode 100644 index 0000000..ff149d5 --- /dev/null +++ b/.gitea/scripts/json.awk @@ -0,0 +1,226 @@ +# Reader of JSON texts (RFC 8259) for the scripts of the CI, in plain POSIX awk (mawk, gawk, busybox awk): no jq, no +# Node. Every file named on the command line is one JSON text. The program that includes this file (awk -f json.awk +# -f .awk) defines five hooks, called while a file is read: +# +# json_begin(file) before the first value of the file +# json_open(kind) a container opens: kind "a" (array) or "o" (object); json_depth is now its level (the +# root is level 1) and json_stack[d] the kind of the container at level d +# json_close(kind) the container at level json_depth closes (json_depth drops after the call) +# json_scalar(kind, value) a value that is not a container: kind "s" string (decoded), "n" number (its text), "t" +# true, "f" false, "z" null +# json_end(file, error) after the file: error is "" for a valid JSON text, otherwise the reason (with the line) +# +# Where a value is: inside the container at level d it is at json_at[d], its key (object, decoded) or its index from 0 +# (array). A scalar inside the container at level json_depth is at json_at[json_depth]; at the root json_depth is 0. +# After an error the rest of that file is skipped and only json_end follows; an empty file is an error, as for every +# JSON parser. The hooks must not call exit: the program records what it needs and decides in its own END, which runs +# after the END of this file (it comes first on the command line). +# +# Run with LC_ALL=C: the text is read as bytes, a leading BOM is skipped and a string may hold any byte from 0x20 on +# (UTF-8 is not checked). \uXXXX escapes below 0x80 are decoded; the others stay as they are written, which is enough +# for the names, versions, dates and addresses the CI compares. Tokens never span lines in JSON (a string cannot hold a +# raw line break), so each line is cut once at the quotes and once at the punctuation: the work grows with the size of +# the text, never with its square. + +BEGIN { + json_file = "" + json_control = "[" sprintf("%c", 1) "-" sprintf("%c", 31) "]" + json_escape = "\\\\([\"\\\\/bfnrt]|u[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f])" + json_number = "^-?(0|[1-9][0-9]*)([.][0-9]+)?([eE][-+]?[0-9]+)?$" +} + +FNR == 1 { + if (json_file != "") json_finish() + json_start(FILENAME) + if (substr($0, 1, 3) == "\357\273\277") $0 = substr($0, 4) +} + +{ + if (json_error == "") json_line($0) +} + +END { + if (json_file != "") json_finish() + for (json_i = 1; json_i < ARGC; json_i++) { + json_f = ARGV[json_i] + if (json_f == "" || (json_f in json_seen) || json_f ~ /^[A-Za-z_][A-Za-z0-9_]*=/) continue + json_start(json_f) + json_fail("file vuoto") + json_finish() + } +} + +function json_start(file) { + json_file = file + json_seen[file] = 1 + json_depth = 0 + json_state = "V" + json_error = "" + json_instring = 0 + json_buffer = "" + json_lineno = 0 + json_begin(file) +} + +function json_finish() { + if (json_error == "") { + if (json_instring) json_fail("stringa non chiusa") + else if (json_state != "E") json_fail(json_depth > 0 || json_state != "V" ? "testo interrotto" : "file vuoto") + } + json_end(json_file, json_error) + json_file = "" +} + +function json_fail(message) { + if (json_error == "") json_error = (json_lineno > 0 ? "riga " json_lineno ": " : "") message + return 0 +} + +# One line: the parts between quotes alternate between text outside and inside strings, except where a quote is +# escaped (an odd number of backslashes before it), which stays in the string. +function json_line(line, n, parts, i) { + json_lineno = FNR + n = split(line, parts, "\"") + for (i = 1; i <= n; i++) { + if (json_instring) { + json_buffer = json_buffer parts[i] + if (i == n) return json_fail("stringa non chiusa a fine riga") + if (json_escaped(json_buffer)) { + json_buffer = json_buffer "\"" + continue + } + json_instring = 0 + json_string(json_buffer) + } else { + json_plain(parts[i]) + if (i < n && json_error == "") { + json_instring = 1 + json_buffer = "" + } + } + if (json_error != "") return 0 + } + return 1 +} + +function json_escaped(text) { + return match(text, /[\\]+$/) && RLENGTH % 2 == 1 +} + +# Text outside strings: punctuation, numbers, true, false, null and the four blanks of JSON. +function json_plain(text, n, tokens, i) { + gsub(/\{/, " { ", text) + gsub(/\}/, " } ", text) + gsub(/\[/, " [ ", text) + gsub(/\]/, " ] ", text) + gsub(/,/, " , ", text) + gsub(/:/, " : ", text) + gsub(/\r/, " ", text) + n = split(text, tokens, " ") + for (i = 1; i <= n; i++) { + json_token(tokens[i]) + if (json_error != "") return 0 + } + return 1 +} + +function json_token(token, kind) { + if (token == "{" || token == "[") { + if (json_state != "V" && json_state != "VA") return json_fail("«" token "» inatteso") + json_enter() + json_depth++ + json_stack[json_depth] = token == "{" ? "o" : "a" + json_index[json_depth] = 0 + json_at[json_depth] = "" + json_state = token == "{" ? "KO" : "VA" + json_open(json_stack[json_depth]) + return 1 + } + if (token == "}" || token == "]") { + kind = token == "}" ? "o" : "a" + if (json_depth == 0 || json_stack[json_depth] != kind) return json_fail("«" token "» inatteso") + if (json_state != "N" && !(kind == "o" && json_state == "KO") && !(kind == "a" && json_state == "VA")) return json_fail("«" token "» inatteso") + json_close(kind) + json_depth-- + json_state = json_depth > 0 ? "N" : "E" + return 1 + } + if (token == ",") { + if (json_state != "N") return json_fail("«,» inattesa") + if (json_stack[json_depth] == "o") { + json_state = "K" + } else { + json_index[json_depth]++ + json_state = "V" + } + return 1 + } + if (token == ":") { + if (json_state != ":") return json_fail("«:» inattesi") + json_state = "V" + return 1 + } + if (token == "true") kind = "t" + else if (token == "false") kind = "f" + else if (token == "null") kind = "z" + else if (token ~ json_number) kind = "n" + else return json_fail("«" substr(token, 1, 20) "» non è un valore JSON") + if (json_state != "V" && json_state != "VA") return json_fail("«" substr(token, 1, 20) "» inatteso") + json_enter() + json_scalar(kind, token) + json_state = json_depth > 0 ? "N" : "E" + return 1 +} + +# A whole string, without its quotes: a key or a value. +function json_string(raw, rest, value) { + if (raw ~ json_control) return json_fail("carattere di controllo in una stringa") + rest = raw + gsub(json_escape, "", rest) + if (index(rest, "\\") > 0) return json_fail("sequenza «\\» non valida in una stringa") + value = json_unescape(raw) + if (json_state == "K" || json_state == "KO") { + json_at[json_depth] = value + json_state = ":" + return 1 + } + if (json_state != "V" && json_state != "VA") return json_fail("stringa inattesa") + json_enter() + json_scalar("s", value) + json_state = json_depth > 0 ? "N" : "E" + return 1 +} + +# A value starts inside the current container: in an array its place is the running index. +function json_enter() { + if (json_depth > 0 && json_stack[json_depth] == "a") json_at[json_depth] = json_index[json_depth] +} + +function json_unescape(text, out, i, c, code) { + if (index(text, "\\") == 0) return text + out = "" + while ((i = index(text, "\\")) > 0) { + out = out substr(text, 1, i - 1) + c = substr(text, i + 1, 1) + if (c == "u") { + code = json_hex(substr(text, i + 2, 4)) + out = out (code > 0 && code < 128 ? sprintf("%c", code) : "\\u" substr(text, i + 2, 4)) + text = substr(text, i + 6) + } else { + if (c == "b") c = "\b" + else if (c == "f") c = "\f" + else if (c == "n") c = "\n" + else if (c == "r") c = "\r" + else if (c == "t") c = "\t" + out = out c + text = substr(text, i + 2) + } + } + return out text +} + +function json_hex(digits, value, i) { + value = 0 + for (i = 1; i <= length(digits); i++) value = value * 16 + index("0123456789abcdef", tolower(substr(digits, i, 1))) - 1 + return value +} diff --git a/.gitea/scripts/json.sh b/.gitea/scripts/json.sh new file mode 100644 index 0000000..5676018 --- /dev/null +++ b/.gitea/scripts/json.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +# JSON per i passi della CI, senza programmi di terzi (niente jq, niente Node; decisione di Alberto del 18 novembre +# 2026): legge con json.awk e json-campi.awk, scrive le stringhe con json-stringa.awk. awk POSIX, niente rete. +# +# json.sh campi ... per ogni oggetto a quel posto, una riga con i campi +# separati da un TAB (json-campi.awk): percorso vuoto +# per l'oggetto radice, «*» per ogni elemento di un +# elenco, per esempio «Results/*/Vulnerabilities/*» +# json.sh stringa il testo come stringa JSON, virgolette comprese +# +# Un file che non è JSON valido: niente in uscita, il motivo su stderr, uscita 2. Lo provano le PipelineTests. +set -euo pipefail + +qui="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +export LC_ALL=C +uso() { + echo "Uso: json.sh campi ... | stringa " >&2 + exit 2 +} + +modo="${1:-}" +(($# > 0)) && shift +case "$modo" in + campi) + (($# >= 3)) || uso + percorso="$1" campi="$2" + shift 2 + nome='[A-Za-z_][A-Za-z0-9_.-]*' + passo='([A-Za-z0-9_.-]+|[*])' + [[ "$campi" =~ ^$nome(,$nome)*$ ]] || uso + [[ -z "$percorso" || "$percorso" =~ ^$passo(/$passo)*$ ]] || uso + for file in "$@"; do + [[ -f "$file" ]] || { echo "json.sh: manca il file $file" >&2; exit 2; } + done + exec awk -v percorso="$percorso" -v campi="$campi" -f "$qui/json.awk" -f "$qui/json-campi.awk" "$@" + ;; + stringa) + (($# == 1)) || uso + printf '%s' "$1" | awk -f "$qui/json-stringa.awk" + ;; + *) + uso + ;; +esac diff --git a/.gitea/scripts/prova-immagine.sh b/.gitea/scripts/prova-immagine.sh index 87e3214..e6752d3 100755 --- a/.gitea/scripts/prova-immagine.sh +++ b/.gitea/scripts/prova-immagine.sh @@ -13,7 +13,8 @@ # 2. la lingua it_IT.UTF-8 è generata; # 3. il contenitore parte come dice la guida (profilo seccomp di Febe, password dell'interfaccia, PUID/PGID # predefiniti), il controllo di salute dell'immagine diventa «healthy» e «febe --controllo-salute» risponde; -# 4. allo stop si ferma da solo, entro i 30 secondi che la guida concede. +# 4. il processo 1 è Febe (niente tini) e nel contenitore non restano processi orfani da raccogliere; +# 5. allo stop si ferma da solo, entro i 30 secondi che la guida concede. # La password è casuale, vive solo nell'ambiente del client Docker e non si stampa mai. set -euo pipefail @@ -75,6 +76,36 @@ if ! docker exec "$nome" /app/febe --controllo-salute > /dev/null; then fi echo "salute: healthy, e febe --controllo-salute risponde" +echo "== Processo 1 e processi orfani" +# Senza tini il processo 1 è Febe, e il runtime .NET da processo 1 raccoglie anche i figli di Chromium rimasti orfani. +# Un processo appena finito può restare «zombie» per un istante: conta solo uno che resta tale per 10 secondi. +primo="$(docker exec "$nome" cat /proc/1/comm)" +if [[ "$primo" != "febe" ]]; then + echo "Il processo 1 del contenitore è «$primo» invece di febe. Registro:" >&2 + docker logs --tail 80 "$nome" >&2 || true + exit 1 +fi +# I numeri dei processi zombie figli del processo 1, ordinati: quelli che tocca a lui raccogliere (gli orfani finiscono +# lì). Uno sparito durante la lettura non conta. +orfani_zombie='for f in /proc/[0-9]*/status; do + awk '\''$1 == "State:" { z = $2 } $1 == "Pid:" { p = $2 } $1 == "PPid:" { q = $2 } END { if (z == "Z" && q == 1) print p }'\'' "$f" 2> /dev/null +done' +zombie() { + { docker exec "$nome" sh -c "$orfani_zombie" || true; } | sort +} +rimasti="$(zombie)" +for _ in 1 2 3 4 5; do + [[ -z "$rimasti" ]] && break + sleep 2 + rimasti="$(comm -12 <(printf '%s\n' "$rimasti") <(zombie))" +done +if [[ -n "$rimasti" ]]; then + echo "Processi zombie che nessuno raccoglie (numeri: $(tr '\n' ' ' <<< "$rimasti")). Registro:" >&2 + docker logs --tail 80 "$nome" >&2 || true + exit 1 +fi +echo "processo 1: febe, nessun processo orfano da raccogliere" + inizio=$(date +%s) docker stop -t 30 "$nome" > /dev/null durata=$(($(date +%s) - inizio)) diff --git a/.gitea/scripts/pulizia-docker.sh b/.gitea/scripts/pulizia-docker.sh index 8f20e85..29c8612 100755 --- a/.gitea/scripts/pulizia-docker.sh +++ b/.gitea/scripts/pulizia-docker.sh @@ -36,8 +36,9 @@ # stretta di prima del 21 ottobre 2026, ora solo a mano # pulizia-docker.sh completa residui, febe:ci, resti di act_runner, le immagini che nessun contenitore # usa create più di 24 ore fa, la cache di costruzione non usata da 24 ore e, -# con REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti -# (flusso «pulizia», ogni lunedì e a mano) +# con REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti e +# gli artefatti della CI (febe-ci) di più di 14 giorni (flusso «pulizia», ogni +# lunedì e a mano) # pulizia-docker.sh --prova elenca che cosa toglierebbe e non toglie nulla: solo comandi che leggono # (sul registro solo GET) # @@ -49,7 +50,8 @@ # il filtro delle 24 ore; mai un contenitore, un volume o una rete che non sia della CI. Le immagini le toglie Docker # stesso (image prune), che non toglie mai un'immagine usata da un contenitore, nemmeno fermo; con -a, però, le toglie i # nomi in più, e lo script li scrive (nella prova li stima, secondo lo store). Sul registro mai main, latest o una -# versione X.Y.Z: solo le etichette sha- della verifica. +# versione X.Y.Z: solo le etichette sha- della verifica e gli artefatti -ci. e +# -rilascio. del pacchetto generico febe-ci. # # Nei modi «residui», «settimanale» e «completa» un contenitore di prova si toglie solo se è fermo. Uno ancora acceso # dopo 90 minuti (il suo lavoro è stato ucciso proprio durante la prova del contenitore) resta dov'è: lo si segnala, con @@ -63,7 +65,7 @@ # # Variabili per il registro (modo «completa»): REGISTRY_TOKEN (token con «package: read and write», mai stampato), # GITEA_API (l'API del server, per esempio https://gitea.example/api/v1) e PROPRIETARIO (il proprietario del pacchetto -# febe). La scelta delle versioni da togliere sta in versioni-registro.js, accanto a questo script. +# febe). La scelta delle versioni da togliere sta in versioni-registro.sh, accanto a questo script. set -uo pipefail uso() { @@ -103,9 +105,9 @@ tipi=() note=() # La cache di costruzione che si pota è quella del builder del demone, «default». docker builder è un alias di docker -# buildx quando c'è il plugin, e buildx lavora sul builder corrente: nel lavoro «immagine» è quello dell'esecuzione -# (setup-buildx-action lo crea con --use), che il modo «esecuzione» ha appena tolto. Gli altri comandi buildx di questo -# script indicano il builder per nome. +# buildx quando c'è il plugin, e buildx lavora sul builder corrente: se qualcuno avesse reso corrente il builder +# dell'esecuzione (costruisci-immagine.sh builder non lo fa), il modo «esecuzione» l'avrebbe appena tolto. Gli altri +# comandi buildx di questo script indicano il builder per nome. export BUILDX_BUILDER=default avviso() { @@ -693,11 +695,16 @@ spiega() { # ne arriva una vuota (il server può darne # meno di 50 per pagina) # DELETE /api/v1/packages/{proprietario}/container/febe/{versione} una versione (risponde 204) -# Quali togliere lo sceglie versioni-registro.js; qui si ricontrolla la forma sha- prima di ogni DELETE. -# Ogni rifiuto dell'API è un avviso che non fa diventare rosso il lavoro. Le versioni sha256:… senza etichetta (i +# Quali togliere lo sceglie versioni-registro.sh (awk POSIX con json.awk: niente Node, niente jq); qui si ricontrolla +# la forma sha- prima di ogni DELETE. Ogni rifiuto dell'API è un avviso che non fa diventare rosso il +# lavoro, e dopo un rifiuto il registro non si tocca più (il token è lo stesso). Le versioni sha256:… senza etichetta (i # manifest figli di un indice, con gli strati) non si toccano mai: l'API non dice se un'etichetta le usa ancora. Si # dice solo quante sono; la CI pubblica manifest semplici (costruisci-immagine.sh), quindi non dovrebbero essercene, e # quelle che nessuna etichetta usa le toglie una regola di pulizia di Gitea (docs/processo.md, «Registro dei container»). +# Poi gli artefatti della CI (artefatti.sh): le versioni del pacchetto generico febe-ci create più di 14 giorni fa, +# GET /api/v1/packages/{proprietario}/generic/febe-ci?page=N&limit=50 +# DELETE /api/v1/packages/{proprietario}/generic/febe-ci/{versione} la versione con i suoi file (204) +# solo con la forma -ci. o -rilascio., ricontrollata prima di ogni DELETE. registro() { local tenere=10 echo "== Registro: le etichette sha- del pacchetto febe oltre le $tenere più recenti" @@ -710,40 +717,58 @@ registro() { return 0 fi local programma - for programma in curl node; do + for programma in curl awk sort; do command -v "$programma" > /dev/null || { segnala "Manca $programma: il registro non si tocca."; return 0; } done - local base="${GITEA_API%/}/packages/$PROPRIETARIO/container/febe" cartella pagina codice scelte + local base="${GITEA_API%/}/packages/$PROPRIETARIO/container/febe" cartella codice scelte esito cartella=$(mktemp -d) || { segnala "Non riesco a creare una cartella temporanea: il registro non si tocca."; return 0; } - for ((pagina = 1; ; pagina++)); do - if ((pagina > 200)); then - segnala "Più di 200 pagine di versioni sul registro: il registro non si tocca." - rm -rf "$cartella" - return 0 - fi - codice=$(chiedi GET "$base?page=$pagina&limit=50" "$cartella/pagina-$pagina.json") - if [[ "$codice" == 404 && "$pagina" == 1 ]]; then - echo " Il pacchetto febe non è ancora sul registro: niente da togliere." - rm -rf "$cartella" - return 0 - fi - if [[ "$codice" != 200 ]]; then - segnala "L'API dei pacchetti di Gitea risponde $(spiega "$codice") alla pagina $pagina delle versioni: il registro non si tocca." - rm -rf "$cartella" - return 0 - fi - case "$(tr -d '[:space:]' < "$cartella/pagina-$pagina.json")" in - "[]" | null) break ;; - esac - done - local senza_etichetta quante - if ! scelte=$(node "$cartella_script/versioni-registro.js" "$tenere" "$cartella"/pagina-*.json) \ - || ! senza_etichetta=$(node "$cartella_script/versioni-registro.js" senza-etichetta "$cartella"/pagina-*.json); then - segnala "Non riesco a leggere le versioni del pacchetto febe: il registro non si tocca." + esito=0 + pagine "$base" "$cartella" febe || esito=$? + if ((esito == 2)); then rm -rf "$cartella" return 0 fi + if ((esito == 1)); then + echo " Il pacchetto febe non è ancora sul registro: niente da togliere." + else + contenitore "$base" "$cartella" + fi rm -rf "$cartella" + artefatti_della_ci +} + +# Le pagine delle versioni di un pacchetto nella cartella, pagina-.json, fino alla prima vuota (il server può darne +# meno di 50 per pagina). Esce con 0 se le ha lette, 1 se il pacchetto non c'è (404 alla prima pagina), 2 se l'API +# rifiuta (e lo segnala). +pagine() { + local base="$1" cartella="$2" nome="$3" pagina codice + for ((pagina = 1; ; pagina++)); do + if ((pagina > 200)); then + segnala "Più di 200 pagine di versioni di $nome sul registro: il registro non si tocca." + return 2 + fi + codice=$(chiedi GET "$base?page=$pagina&limit=50" "$cartella/pagina-$pagina.json") + if [[ "$codice" == 404 && "$pagina" == 1 ]]; then + return 1 + fi + if [[ "$codice" != 200 ]]; then + segnala "L'API dei pacchetti di Gitea risponde $(spiega "$codice") alla pagina $pagina delle versioni di $nome: il registro non si tocca." + return 2 + fi + case "$(tr -d '[:space:]' < "$cartella/pagina-$pagina.json")" in + "[]" | null) return 0 ;; + esac + done +} + +# Le etichette sha- del contenitore febe, dalle pagine già lette. +contenitore() { + local base="$1" cartella="$2" scelte senza_etichetta quante codice + if ! scelte=$(bash "$cartella_script/versioni-registro.sh" "$tenere" "$cartella"/pagina-*.json) \ + || ! senza_etichetta=$(bash "$cartella_script/versioni-registro.sh" senza-etichetta "$cartella"/pagina-*.json); then + segnala "Non riesco a leggere le versioni del pacchetto febe: il registro non si tocca." + return 0 + fi quante=$(grep -c . <<< "$senza_etichetta") if ((quante > 0)); then echo " $quante versioni senza etichetta (sha256:…, i manifest di un indice con i loro strati): restano, questa pulizia non le tocca mai (docs/processo.md, «Registro dei container»)" @@ -775,6 +800,47 @@ registro() { done <<< "$scelte" } +# Gli artefatti della CI (artefatti.sh): le versioni del pacchetto generico febe-ci create più di 14 giorni fa, come la +# scadenza degli artefatti di una volta. +artefatti_della_ci() { + local giorni=14 base="${GITEA_API%/}/packages/$PROPRIETARIO/generic/febe-ci" cartella esito scelte versione creata codice + echo "== Registro: gli artefatti della CI (pacchetto febe-ci) creati più di $giorni giorni fa" + cartella=$(mktemp -d) || { segnala "Non riesco a creare una cartella temporanea: gli artefatti restano."; return 0; } + esito=0 + pagine "$base" "$cartella" febe-ci || esito=$? + if ((esito == 1)); then + echo " Il pacchetto febe-ci non è ancora sul registro: niente da togliere." + elif ((esito == 0)) && ! scelte=$(bash "$cartella_script/versioni-registro.sh" scadute "$giorni" "$(date +%s)" "$cartella"/pagina-*.json); then + segnala "Non riesco a leggere le versioni del pacchetto febe-ci: gli artefatti restano." + esito=3 + fi + rm -rf "$cartella" + ((esito == 0)) || return 0 + if [[ -z "${scelte:-}" ]]; then + echo " niente da togliere" + return 0 + fi + while IFS=$'\t' read -r versione creata; do + [[ -n "${versione:-}" ]] || continue + if [[ ! "$versione" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[0-9A-Za-z.-]+)?-(ci|rilascio)\.[0-9]+$ ]]; then + segnala "Versione inattesa «$versione» fra gli artefatti da togliere: resta." + continue + fi + if ((prova)); then + echo " toglierei febe-ci $versione (caricata il $creata)" + conta "artefatti della CI sul registro" + continue + fi + codice=$(chiedi DELETE "$base/$versione" /dev/null) + if [[ "$codice" == 204 ]]; then + echo " febe-ci $versione tolta (caricata il $creata)" + conta "artefatti della CI sul registro" + else + segnala "Non riesco a togliere febe-ci $versione dal registro: l'API risponde $(spiega "$codice")." + fi + done <<< "$scelte" +} + # La cache con lo stesso limite del lunedì: senza, a ogni push di ogni ramo se ne andrebbero gli strati intermedi e le # cache montate (RUN --mount=type=cache) che le costruzioni degli altri progetti hanno appena usato. penzolanti() { diff --git a/.gitea/scripts/riepilogo-prove.sh b/.gitea/scripts/riepilogo-prove.sh index f7be7e3..e81589f 100755 --- a/.gitea/scripts/riepilogo-prove.sh +++ b/.gitea/scripts/riepilogo-prove.sh @@ -6,8 +6,8 @@ # .gitea/scripts/riepilogo-prove.sh [saltate ammesse] # # Esce con 1 se una prova è fallita, se le saltate sono più di quelle ammesse (predefinito 0: nella CI ci sono -# Chromium, Xvfb, NSIS e Node, quindi nessuna prova ha motivo di saltarsi) o se non c'è nessun risultato. Fa eccezione -# solo la categoria «da fare»: le inconclusive di FeaturesStillToDo (flussi di conformità H.264 delle parti che il +# Chromium e Xvfb, quindi nessuna prova ha motivo di saltarsi) o se non c'è nessun risultato. Fa eccezione solo la +# categoria «da fare»: le inconclusive di FeaturesStillToDo (flussi di conformità H.264 delle parti che il # decodificatore non gestisce ancora) il cui motivo comincia con «da fare: » si elencano e non contano fra le saltate. # Qualunque altra inconclusiva, anche con «da fare: » nel messaggio, è una saltata. set -euo pipefail @@ -113,7 +113,7 @@ if (( fallite_totali > 0 )); then esito=1 fi if (( saltate_totali > ammesse )); then - echo "Prove saltate: $saltate_totali, più delle $ammesse ammesse. Qui ci sono Chromium, Xvfb, NSIS e Node: una prova che si salta segnala un ambiente rotto, non una prova superata." >&2 + echo "Prove saltate: $saltate_totali, più delle $ammesse ammesse. Qui ci sono Chromium e Xvfb: una prova che si salta segnala un ambiente rotto, non una prova superata." >&2 esito=1 fi diff --git a/.gitea/scripts/scansione-immagine.sh b/.gitea/scripts/scansione-immagine.sh index 43d37c8..fd6f038 100755 --- a/.gitea/scripts/scansione-immagine.sh +++ b/.gitea/scripts/scansione-immagine.sh @@ -35,13 +35,19 @@ echo "== Vulnerabilità HIGH e CRITICAL (rapporto: non fermano il lavoro)" "$strumenti/trivy" "${comuni[@]}" --severity HIGH,CRITICAL --format json --output "$rapporti/trivy.json" --exit-code 0 "$strumenti/trivy" convert --format table "$rapporti/trivy.json" -if command -v jq > /dev/null; then - conteggio=$(jq -r '[.Results[]?.Vulnerabilities[]?] as $v - | "HIGH \([$v[] | select(.Severity == "HIGH")] | length) · CRITICAL \([$v[] | select(.Severity == "CRITICAL")] | length), di cui correggibili \([$v[] | select(.Severity == "CRITICAL" and ((.FixedVersion // "") != ""))] | length)"' "$rapporti/trivy.json") +# Il conteggio con il lettore JSON nostro (json.sh, awk): niente jq. Una riga per vulnerabilità, gravità e versione +# che la corregge (vuota o null se non c'è). Un rapporto illeggibile non ferma nulla: lo dice e basta. +if vulnerabilita=$(bash "$radice/.gitea/scripts/json.sh" campi "Results/*/Vulnerabilities/*" Severity,FixedVersion "$rapporti/trivy.json"); then + conteggio=$(awk -F '\t' ' + $1 == "HIGH" { alte++ } + $1 == "CRITICAL" { critiche++; if ($2 != "" && $2 != "null") correggibili++ } + END { printf "HIGH %d · CRITICAL %d, di cui correggibili %d", alte, critiche, correggibili }' <<< "$vulnerabilita") echo "Trovate: $conteggio." if [[ -n "${GITHUB_STEP_SUMMARY:-}" ]]; then printf "### Sicurezza dell'immagine (Trivy)\n\n%s.\n" "$conteggio" >> "$GITHUB_STEP_SUMMARY" || true fi +else + echo "::warning::Il rapporto di Trivy non si legge come JSON: niente conteggio (la scansione che ferma il lavoro segue)." fi echo "== CRITICAL con una correzione disponibile (fermano il lavoro)" diff --git a/.gitea/scripts/segreti.sh b/.gitea/scripts/segreti.sh index f4df3f4..6d672c2 100755 --- a/.gitea/scripts/segreti.sh +++ b/.gitea/scripts/segreti.sh @@ -37,10 +37,13 @@ if ((stato == 0)); then exit 0 fi -if [[ -s "$rapporto" ]] && command -v jq > /dev/null; then - quanti=$(jq 'length' "$rapporto") - echo "Possibili segreti: $quanti (in $commit commit). Regola, file:riga, commit, impronta per .gitleaksignore:" >&2 - jq -r '.[] | " \(.RuleID) \(.File):\(.StartLine) commit \(.Commit[0:12]) impronta \(.Fingerprint)"' "$rapporto" >&2 +# Il riassunto con il lettore JSON nostro (json.sh, awk): niente jq. +if [[ -s "$rapporto" ]] \ + && rilievi=$(bash "$radice/.gitea/scripts/json.sh" campi "*" RuleID,File,StartLine,Commit,Fingerprint "$rapporto"); then + quanti=0 + [[ -z "$rilievi" ]] || quanti=$(wc -l <<< "$rilievi") + echo "Possibili segreti: $((quanti)) (in $commit commit). Regola, file:riga, commit, impronta per .gitleaksignore:" >&2 + [[ -z "$rilievi" ]] || awk -F '\t' '{ printf " %s %s:%s commit %s impronta %s\n", $1, $2, $3, substr($4, 1, 12), $5 }' <<< "$rilievi" >&2 else echo "gitleaks è uscito con $stato: vedi il registro qui sopra e il rapporto $rapporto." >&2 fi diff --git a/.gitea/scripts/versioni-registro.awk b/.gitea/scripts/versioni-registro.awk new file mode 100644 index 0000000..d0440f4 --- /dev/null +++ b/.gitea/scripts/versioni-registro.awk @@ -0,0 +1,148 @@ +# For versioni-registro.sh, with json.awk: the versions of one package of Gitea's registry in the pages of +# GET /api/v1/packages/{owner}/{type}/{name} of Gitea 28, given as files: +# +# LC_ALL=C awk -v tipo=container -v nome=febe -f json.awk -f versioni-registro.awk ... +# +# A page is a list of versions with «type», «name», «version», «created_at» and «id»; an empty page may be «[]» or +# «null». Only the versions whose type and name are those asked count, and a version found in two pages counts once +# (the last one read wins, in the place of the first). For each it prints, in the order first met: +# +# +# +# +# created_at is read as ISO 8601 / RFC 3339 like JavaScript's Date.parse: a date, or a date and time with «Z» or an +# offset (+02:00), seconds and fractions optional. A time without a zone is local time for JavaScript and would depend +# on the machine: here it is not a date, and in doubt nothing is removed. If a file is not JSON, or not a list (nor +# null), it prints nothing, says why on stderr and exits with 2. + +function json_begin(file) { + root = "" + inside = 0 +} + +function json_open(kind) { + if (json_depth == 1) { + root = kind + } else if (json_depth == 2 && root == "a" && kind == "o") { + inside = 1 + split("", field) + split("", seen) + } +} + +function json_scalar(kind, value) { + if (json_depth == 0) { + root = kind == "z" ? "null" : "valore" + } else if (json_depth == 2 && inside) { + field[json_at[2]] = value + seen[json_at[2]] = kind + } +} + +function json_close(kind) { + if (json_depth == 2 && inside) { + inside = 0 + keep() + } +} + +function json_end(file, error) { + if (error != "") { + problems = problems file ": " error "\n" + } else if (root != "a" && root != "null") { + problems = problems file ": non è un elenco di versioni\n" + } +} + +function keep( version, created, id) { + if (seen["type"] != "s" || field["type"] != tipo || seen["name"] != "s" || field["name"] != nome) return + if (seen["version"] != "s") return + version = field["version"] + if (version ~ control) return + if (!("created_at" in seen)) created = "undefined" + else if (seen["created_at"] == "z") created = "null" + else if (seen["created_at"] == "t") created = "true" + else if (seen["created_at"] == "f") created = "false" + else created = field["created_at"] + gsub(control, "?", created) + id = 0 + if (seen["id"] == "n" || (seen["id"] == "s" && field["id"] ~ /^[0-9]+$/)) id = field["id"] + 0 + if (!(version in order)) order[version] = ++count + when[version] = seen["created_at"] == "s" ? milliseconds(field["created_at"]) : "" + number[version] = id + written[version] = created +} + +# Milliseconds since 1970 UTC of an ISO 8601 date as Date.parse reads it, or "" if it is not one. +function milliseconds(text, y, mo, d, h, mi, s, ms, rest, offset, fraction) { + if (text !~ /^[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]/) return "" + y = substr(text, 1, 4) + 0 + mo = substr(text, 6, 2) + 0 + d = substr(text, 9, 2) + 0 + h = mi = s = ms = offset = 0 + rest = substr(text, 11) + if (rest != "") { + if (rest !~ /^T[0-9][0-9]:[0-9][0-9]/) return "" + h = substr(rest, 2, 2) + 0 + mi = substr(rest, 5, 2) + 0 + rest = substr(rest, 7) + if (rest ~ /^:[0-9][0-9]/) { + s = substr(rest, 2, 2) + 0 + rest = substr(rest, 4) + if (match(rest, /^[.][0-9]+/)) { + fraction = substr(rest, 2, RLENGTH - 1) "00" + ms = substr(fraction, 1, 3) + 0 + rest = substr(rest, RLENGTH + 1) + } + } + if (rest == "Z") offset = 0 + else if (rest ~ /^[-+][0-9][0-9]:[0-9][0-9]$/) { + offset = substr(rest, 2, 2) * 60 + substr(rest, 5, 2) + if (substr(rest, 2, 2) + 0 > 23 || substr(rest, 5, 2) + 0 > 59) return "" + if (substr(rest, 1, 1) == "-") offset = -offset + } else return "" + } + if (mo < 1 || mo > 12 || d < 1 || d > days_in_month(y, mo)) return "" + if (h > 24 || mi > 59 || s > 59 || (h == 24 && (mi > 0 || s > 0 || ms > 0))) return "" + return ((days_from_civil(y, mo, d) * 86400 + h * 3600 + mi * 60 + s - offset * 60) * 1000 + ms) +} + +function leap(y) { + return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 +} + +function days_in_month(y, m) { + if (m == 2) return leap(y) ? 29 : 28 + return (m == 4 || m == 6 || m == 9 || m == 11) ? 30 : 31 +} + +# Days from 1970-01-01 to a date of the proleptic Gregorian calendar (years 0 to 9999 here). +function days_from_civil(y, m, d, era, yoe, doy, doe) { + if (m <= 2) y-- + era = int(y / 400) + if (y < 0 && y % 400 != 0) era-- + yoe = y - era * 400 + doy = int((153 * (m > 2 ? m - 3 : m + 9) + 2) / 5) + d - 1 + doe = yoe * 365 + int(yoe / 4) - int(yoe / 100) + doy + return era * 146097 + doe - 719468 +} + +BEGIN { + control = "[" sprintf("%c", 1) "-" sprintf("%c", 31) "]" + if (tipo == "" || nome == "") { + print "versioni-registro.awk: servono -v tipo=… -v nome=…" > "/dev/stderr" + failed = 1 + exit 2 + } +} + +END { + if (failed) exit 2 + if (problems != "") { + printf "%s", problems > "/dev/stderr" + exit 2 + } + for (version in order) { + printf "%s\t%.0f\t%d\t%s\t%s\n", when[version] == "" ? "-" : sprintf("%.0f", when[version]), number[version], order[version], version, written[version] + } +} diff --git a/.gitea/scripts/versioni-registro.js b/.gitea/scripts/versioni-registro.js deleted file mode 100644 index d50c651..0000000 --- a/.gitea/scripts/versioni-registro.js +++ /dev/null @@ -1,82 +0,0 @@ -"use strict"; -// Chooses the tags to remove from Gitea's container registry (pulizia-docker.sh, mode «completa»). It only reads the -// files it is given: no network, no writes, so it is tested with a JSON file. -// -// node versioni-registro.js ... -// node versioni-registro.js senza-etichetta ... -// -// Each file is a page of the answer of GET /api/v1/packages/{owner}/container/febe of Gitea 28: a list of versions with -// «type», «name», «version» and «created_at» (an empty page may be «[]» or «null»). Only the versions of the container -// package «febe» count, and a version found in two pages counts once. Both forms print, oldest first and one per line, -// «versioncreated». -// -// With a number N: the sha-<7 to 40 hex digits> tags beyond the N newest by creation date. Everything else always -// stays: main, latest, the X.Y.Z releases (X.Y.Z-rc.N too), the digests (sha256:…), any other tag and a sha- tag -// without a date that can be read. -// -// With «senza-etichetta»: the untagged versions, sha256:<64 hex digits>. They are the manifests of an image index, -// which Gitea keeps as versions of their own with the configuration and the layers; nothing here removes them (Gitea -// cannot be asked through this API whether a tag still uses one), the cleanup only says how many there are. -// -// If a file is not a JSON list it exits with 2 and prints nothing: when in doubt nothing is removed. -// Messages are in Italian, like every message of the CI. -const fs = require("fs"); - -const [mode, ...pages] = process.argv.slice(2); -const untagged = mode === "senza-etichetta"; -if (!(untagged || /^[0-9]+$/.test(mode || "")) || pages.length === 0) { - console.error("Uso: node versioni-registro.js | senza-etichetta ..."); - process.exit(2); -} - -const shaTag = /^sha-[0-9a-f]{7,40}$/; -const digest = /^sha256:[0-9a-f]{64}$/; -const versions = new Map(); -for (const file of pages) { - let page; - try { - page = JSON.parse(fs.readFileSync(file, "utf8").replace(/^/, "")); - } catch (error) { - console.error(`${file}: ${error.message}`); - process.exit(2); - } - if (page === null) { - continue; - } - if (!Array.isArray(page)) { - console.error(`${file}: non è un elenco di versioni`); - process.exit(2); - } - for (const version of page) { - if (version && version.type === "container" && version.name === "febe" && typeof version.version === "string") { - versions.set(version.version, version); - } - } -} - -const dated = (version) => ({ - name: version.version, - created: String(version.created_at), - time: Date.parse(version.created_at), - id: Number(version.id) || 0, -}); - -let chosen; -if (untagged) { - chosen = [...versions.values()] - .filter((version) => digest.test(version.version)) - .map(dated) - .sort((a, b) => (Number.isFinite(a.time) ? a.time : 0) - (Number.isFinite(b.time) ? b.time : 0) || a.id - b.id); -} else { - chosen = [...versions.values()] - .filter((version) => shaTag.test(version.version)) - .map(dated) - .filter((version) => Number.isFinite(version.time)) - .sort((a, b) => b.time - a.time || b.id - a.id) - .slice(Number(mode)) - .reverse(); -} - -for (const version of chosen) { - process.stdout.write(`${version.name}\t${version.created}\n`); -} diff --git a/.gitea/scripts/versioni-registro.sh b/.gitea/scripts/versioni-registro.sh new file mode 100644 index 0000000..1dbbe1d --- /dev/null +++ b/.gitea/scripts/versioni-registro.sh @@ -0,0 +1,68 @@ +#!/usr/bin/env bash +# Sceglie le versioni da togliere dal registro dei pacchetti di Gitea (pulizia-docker.sh, modo «completa»). Legge solo +# i file che riceve, con json.awk e versioni-registro.awk (awk POSIX: niente jq, niente Node): niente rete, niente +# scritture, quindi si prova con un file JSON (PipelineTests). +# +# versioni-registro.sh ... le etichette sha- +# del contenitore febe oltre le N più recenti +# versioni-registro.sh senza-etichetta ... le versioni sha256:<64 cifre> del contenitore +# febe (i manifest di un indice: solo da contare) +# versioni-registro.sh scadute ... le versioni -ci. e +# -rilascio. del pacchetto generico +# febe-ci (gli artefatti della CI, artefatti.sh) +# create più di giorni prima di , +# in secondi dal 1970 +# +# Ogni pagina è una risposta di GET /api/v1/packages/{proprietario}/{tipo}/{nome} di Gitea 28. Stampa, dalla più +# vecchia e una per riga, «versionecreata». Tutto il resto resta sempre: main, latest, le versioni X.Y.Z (anche +# X.Y.Z-rc.N), i digest, ogni altra etichetta, una sha- o un artefatto senza una data che si legga. Fra le sha- contano +# le date, non il testo; a parità di data l'identificativo. Se un file non è un elenco JSON esce con 2 e non stampa +# nulla: nel dubbio non si toglie niente. +set -euo pipefail + +qui="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +uso() { + echo "Uso: versioni-registro.sh | senza-etichetta | scadute ..." >&2 + exit 2 +} + +modo="${1:-}" +(($# > 0)) && shift +case "$modo" in + senza-etichetta) tipo=container nome=febe ;; + scadute) + (($# >= 2)) || uso + giorni="$1" adesso="$2" + shift 2 + [[ "$giorni" =~ ^[0-9]{1,5}$ && "$adesso" =~ ^[0-9]{1,12}$ ]] || uso + tipo=generic nome=febe-ci + ;; + *) + [[ "$modo" =~ ^[0-9]{1,6}$ ]] || uso + tipo=container nome=febe + ;; +esac +(($# > 0)) || uso + +export LC_ALL=C +tab=$'\t' +versioni=$(awk -v tipo="$tipo" -v nome="$nome" -f "$qui/json.awk" -f "$qui/versioni-registro.awk" "$@") || exit 2 + +# Righe: millisecondi (o «-»), identificativo, ordine, versione, data come scritta. +case "$modo" in + senza-etichetta) + awk -F "$tab" -v OFS="$tab" '$4 ~ /^sha256:[0-9a-f]+$/ && length($4) == 71 { if ($1 == "-") $1 = 0; print }' <<< "$versioni" \ + | sort -t "$tab" -k1,1n -k2,2n -k3,3n | cut -f4,5 + ;; + scadute) + awk -F "$tab" -v limite="$(((adesso - giorni * 86400) * 1000))" \ + '$1 != "-" && $1 + 0 < limite + 0 && $4 ~ /^[0-9]+[.][0-9]+[.][0-9]+(-[0-9A-Za-z.-]+)?-(ci|rilascio)[.][0-9]+$/' <<< "$versioni" \ + | sort -t "$tab" -k1,1n -k2,2n -k3,3n | cut -f4,5 + ;; + *) + # Le più recenti prima (data, poi identificativo), si saltano le prime N, il resto dalla più vecchia. + awk -F "$tab" '$1 != "-" && $4 ~ /^sha-[0-9a-f]+$/ && length($4) >= 11 && length($4) <= 44' <<< "$versioni" \ + | sort -t "$tab" -k1,1nr -k2,2nr -k3,3n | tail -n "+$((modo + 1))" \ + | awk '{ righe[NR] = $0 } END { for (i = NR; i > 0; i--) print righe[i] }' | cut -f4,5 + ;; +esac diff --git a/.gitea/workflows/pulizia.yml b/.gitea/workflows/pulizia.yml index 47a2ebf..e10f128 100644 --- a/.gitea/workflows/pulizia.yml +++ b/.gitea/workflows/pulizia.yml @@ -11,8 +11,9 @@ # vecchi di 90 minuti; # - le immagini che nessun contenitore usa, né acceso né fermo, create più di 24 ore fa (di un'immagine in uso Docker # toglie i nomi in più), e la cache di costruzione del demone non usata da 24 ore. Le immagini di base -# (node:24-trixie, moby/buildkit, …) si riscaricano alla prima esecuzione che le chiede; -# - con il segreto REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti; mai main, latest o X.Y.Z. +# (debian:trixie, moby/buildkit, …) si riscaricano alla prima esecuzione che le chiede; +# - con il segreto REGISTRY_TOKEN, le etichette sha- del registro oltre le 10 più recenti, mai main, latest o X.Y.Z, +# e gli artefatti della CI (pacchetto generico febe-ci, artefatti.sh) creati più di 14 giorni fa. # Mai system prune, container prune, volume prune o network prune; mai un contenitore, un volume o una rete che non sia # della CI. Un contenitore di prova ancora acceso si segnala e il lavoro diventa rosso; un rifiuto dell'API del # registro è solo un avviso. Dettagli in .gitea/scripts/pulizia-docker.sh e in docs/processo.md, «Pulizia». @@ -45,7 +46,26 @@ jobs: runs-on: ubuntu-latest timeout-minutes: 30 steps: - - uses: actions/checkout@v4 + - name: Sorgenti + env: + TOKEN: ${{ gitea.token }} + SERVER: ${{ gitea.server_url }} + REPOSITORY: ${{ gitea.repository }} + PROFONDITA: "1" + run: | + git config --global --add safe.directory "$PWD" + git init -q . + git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git" + GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" + export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0 + profondita=() + [ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA") + if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then + echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia." + git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro" + fi + git checkout -q --force --detach "$GITHUB_SHA" + git log -1 --format='Commit %h: %s' # Gitea 28 mette nell'evento la casella «prova» come testo, "true" o "false"; il lunedì l'evento non ha input e # la pulizia è quella vera. Un avvio con l'API passa il valore così com'è: qualunque altro («True», «1») ferma il diff --git a/.gitea/workflows/rilascio.yml b/.gitea/workflows/rilascio.yml index e80825a..a35fe9c 100644 --- a/.gitea/workflows/rilascio.yml +++ b/.gitea/workflows/rilascio.yml @@ -1,17 +1,24 @@ # Rilascio a ogni tag vX.Y.Z (anche vX.Y.Z-qualcosa per un'anteprima): # 1. prove: il tag coincide con di Directory.Build.props, la soluzione si compila con gli avvisi come errori -# e tutte le prove passano. Senza prove verdi non si costruisce né si rilascia nulla; -# 2. windows: Febe.exe in un file solo, il programma di installazione NSIS e lo zip portabile (installer/costruisci.sh, -# gira su Linux); +# e tutte le prove passano, nello stesso contenitore Debian 13 della verifica (Chromium e Xvfb veri) e +# senza nessuna prova saltata. Senza prove verdi non si costruisce né si rilascia nulla; +# 2. windows: Febe.exe in un file solo, il programma di installazione nostro (src/Febe.Installer) e lo zip portabile +# (installer/costruisci.sh, gira su Linux con il solo .NET SDK): il cancello prima dell'immagine; # 3. immagine: dopo l'installatore, l'immagine Docker (le prove girano anche dentro la build), provata senza rete e # scansionata con Trivy come nella verifica (una CRITICAL con correzione ferma tutto), poi pubblicata sul registro # dei container di Gitea come //febe:X.Y.Z e :latest (solo per le versioni senza # trattino). Il lavoro dice se l'ha pubblicata, e alla fine toglie sempre immagini, contenitori, cache e builder # dell'esecuzione, poi le immagini senza nome e la cache di costruzione penzolante non usata da 24 ore di tutti i # progetti del demone; -# 4. release: solo dopo le prove, l'installatore e l'immagine. Crea la release (o la completa, se esiste già) con -# installatore, zip portabile, modello Unraid e l'archivio per Docker Compose (compose.yml con il profilo seccomp -# accanto); le note dicono dove sta l'immagine, o che non è stata pubblicata. +# 4. release: solo dopo le prove, l'installatore e l'immagine. Ricostruisce installatore e zip dallo stesso commit con +# lo stesso script (senza azioni non c'è un passaggio di artefatti fra i lavori che non dipenda da REGISTRY_TOKEN, +# e la release deve uscire anche senza), poi crea la release (o la completa, se esiste già) con installatore, zip +# portabile, modello Unraid e l'archivio per Docker Compose (compose.yml con il profilo seccomp accanto); le note +# dicono dove sta l'immagine, o che non è stata pubblicata. +# +# Niente azioni, come nella verifica (decisione del 18 novembre 2026): sorgenti con git e il gettone del lavoro, SDK con +# .gitea/scripts/dotnet.sh, builder buildx con costruisci-immagine.sh builder, risultati delle prove e rapporto di Trivy +# nel pacchetto generico febe-ci (versione -rilascio., con REGISTRY_TOKEN; artefatti.sh). # # Segreto del repository (Impostazioni ▸ Actions ▸ Segreti): REGISTRY_TOKEN, un token dell'utente con i permessi # «package: read and write». Senza, l'immagine si costruisce e si prova ma non si pubblica: la release esce lo stesso, @@ -29,21 +36,69 @@ on: push: tags: ["v*"] +# Come la verifica e la pulizia: ogni passo con «bash -e -o pipefail», qualunque sia la shell predefinita del runner +# o del contenitore (i Sorgenti usano gli array di bash; in un contenitore Debian la predefinita sarebbe dash). +defaults: + run: + shell: bash + +env: + DOTNET_NOLOGO: "1" + DOTNET_CLI_TELEMETRY_OPTOUT: "1" + DOTNET_SKIP_FIRST_TIME_EXPERIENCE: "1" + jobs: prove: runs-on: ubuntu-latest timeout-minutes: 60 + # Lo stesso ambiente delle prove della verifica: Debian 13 con Chromium e Xvfb veri e il riepilogo che non + # ammette prove saltate. Su ubuntu-latest le prove nel browser (fra cui il ritorno dopo l'accesso, return-path.js) + # sarebbero inconcludenti e un rilascio uscirebbe senza averle fatte. + container: + image: debian:trixie + options: --shm-size=1g + env: + FEBE_CHROMIUM: /usr/bin/chromium + NUMERO: ${{ gitea.run_number }} steps: - - uses: actions/checkout@v4 + - name: Git e curl per i sorgenti + run: | + export DEBIAN_FRONTEND=noninteractive + apt-get update -qq + apt-get install -y -qq --no-install-recommends git curl ca-certificates > /dev/null + git --version + + - name: Sorgenti + env: + TOKEN: ${{ gitea.token }} + SERVER: ${{ gitea.server_url }} + REPOSITORY: ${{ gitea.repository }} + PROFONDITA: "1" + run: | + git config --global --add safe.directory "$PWD" + git init -q . + git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git" + GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" + export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0 + profondita=() + [ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA") + if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then + echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia." + git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro" + fi + git checkout -q --force --detach "$GITHUB_SHA" + git log -1 --format='Commit %h: %s' - name: Versione coerente con il tag run: | V=$(sed -n 's:.*\(.*\).*:\1:p' Directory.Build.props | head -n 1) [ "v$V" = "${GITHUB_REF_NAME}" ] || { echo "Il tag ${GITHUB_REF_NAME} non coincide con $V"; exit 1; } - - uses: actions/setup-dotnet@v4 - with: - dotnet-version: "10.0.x" + - name: Chromium, Xvfb e lingua italiana + run: bash .gitea/scripts/ambiente-prove.sh + + - name: SDK .NET 10 + run: bash .gitea/scripts/dotnet.sh 10.0 - name: Compilazione (avvisi = errori) run: dotnet build Febe.slnx -c Release -nologo -warnaserror @@ -53,13 +108,20 @@ jobs: dotnet test tests/Febe.Tests -c Release --no-build --nologo --logger "trx;LogFileName=prove.trx" --results-directory out/prove - - name: Risultati + # Nessuna prova saltata: una prova inconcludente (per esempio senza Chromium) ferma il rilascio. + - name: Riepilogo delle prove + if: ${{ !cancelled() }} + run: bash .gitea/scripts/riepilogo-prove.sh out/prove 0 + + - name: Risultati (pacchetto febe-ci) if: always() - uses: actions/upload-artifact@v3 - with: - name: risultati-prove - path: out/prove/*.trx - if-no-files-found: ignore + env: + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + GITEA_URL: ${{ gitea.server_url }} + PROPRIETARIO: ${{ gitea.repository_owner }} + run: | + [ -f out/prove/prove.trx ] || { echo "Nessun risultato delle prove."; exit 0; } + bash .gitea/scripts/artefatti.sh rilascio out/prove/prove.trx windows: runs-on: ubuntu-latest @@ -69,32 +131,36 @@ jobs: # Come l'installatore di verifica.yml: l'immagine del runner non garantisce ICU, e qui non serve. DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: "true" steps: - - uses: actions/checkout@v4 + - name: Sorgenti + env: + TOKEN: ${{ gitea.token }} + SERVER: ${{ gitea.server_url }} + REPOSITORY: ${{ gitea.repository }} + PROFONDITA: "1" + run: | + git config --global --add safe.directory "$PWD" + git init -q . + git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git" + GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" + export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0 + profondita=() + [ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA") + if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then + echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia." + git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro" + fi + git checkout -q --force --detach "$GITHUB_SHA" + git log -1 --format='Commit %h: %s' - name: Versione run: echo "VERSION=${GITHUB_REF_NAME#v}" >> "$GITHUB_ENV" - - uses: actions/setup-dotnet@v4 - with: - dotnet-version: "10.0.x" - - - name: NSIS e zip - run: | - SUDO=""; [ "$(id -u)" = 0 ] || SUDO=sudo - $SUDO apt-get update -qq - $SUDO apt-get install -y -qq nsis zip > /dev/null + - name: SDK .NET 10 + run: bash .gitea/scripts/dotnet.sh 10.0 - name: Febe.exe, programma di installazione e zip portabile run: bash installer/costruisci.sh "$VERSION" - - uses: actions/upload-artifact@v3 - with: - name: windows - path: | - out/Febe-Setup-*.exe - out/Febe-*-portabile.zip - if-no-files-found: error - immagine: runs-on: ubuntu-latest # Dopo l'installatore: :X.Y.Z e :latest escono solo se anche la release potrà uscire. @@ -103,6 +169,7 @@ jobs: env: FLUSSO: rilascio ESECUZIONE: ${{ gitea.run_id }} + NUMERO: ${{ gitea.run_number }} BUILDER: febe-ci-${{ gitea.run_id }} PROVA: febe-ci:${{ gitea.run_id }} outputs: @@ -110,7 +177,26 @@ jobs: pubblicata: ${{ steps.pubblicazione.outputs.pubblicata }} motivo: ${{ steps.segreto.outputs.motivo }} steps: - - uses: actions/checkout@v4 + - name: Sorgenti + env: + TOKEN: ${{ gitea.token }} + SERVER: ${{ gitea.server_url }} + REPOSITORY: ${{ gitea.repository }} + PROFONDITA: "1" + run: | + git config --global --add safe.directory "$PWD" + git init -q . + git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git" + GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" + export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0 + profondita=() + [ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA") + if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then + echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia." + git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro" + fi + git checkout -q --force --detach "$GITHUB_SHA" + git log -1 --format='Commit %h: %s' # Ciò che un'esecuzione interrotta non ha potuto togliere, e un tentativo precedente di questa stessa esecuzione. - name: Resti di esecuzioni interrotte @@ -131,18 +217,11 @@ jobs: echo "ARCHIVIO=${RUNNER_TEMP:-/tmp}/febe-$ESECUZIONE.tar" >> "$GITHUB_ENV" echo "REGISTRY=$REGISTRY" >> "$GITHUB_ENV" echo "IMAGE=$REGISTRY/$OWNER/febe" >> "$GITHUB_ENV" - echo "registro=$REGISTRY" >> "$GITHUB_OUTPUT" echo "immagine=$REGISTRY/$OWNER/febe" >> "$GITHUB_OUTPUT" # Un builder buildx proprio, che sa che il registro di casa risponde in HTTP. - - uses: docker/setup-buildx-action@v3 - with: - name: febe-ci-${{ gitea.run_id }} - driver: docker-container - buildkitd-config-inline: | - [registry."${{ steps.nome.outputs.registro }}"] - http = true - insecure = true + - name: Builder buildx dell'esecuzione + run: bash .gitea/scripts/costruisci-immagine.sh builder "$REGISTRY" # Gli stessi argomenti ed etichette della pubblicazione (costruisci-immagine.sh): quella esce dalla cache di questa. - name: Costruzione dell'immagine (le prove girano dentro la build) @@ -156,13 +235,15 @@ jobs: - name: Vulnerabilità dell'immagine (Trivy) run: bash .gitea/scripts/scansione-immagine.sh "$ARCHIVIO" out/sicurezza - - name: Rapporto di Trivy + - name: Rapporto di Trivy (pacchetto febe-ci) if: ${{ !cancelled() }} - uses: actions/upload-artifact@v3 - with: - name: sicurezza-immagine - path: out/sicurezza/trivy.json - if-no-files-found: ignore + env: + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + GITEA_URL: ${{ gitea.server_url }} + PROPRIETARIO: ${{ gitea.repository_owner }} + run: | + [ -f out/sicurezza/trivy.json ] || { echo "Nessun rapporto di Trivy."; exit 0; } + bash .gitea/scripts/artefatti.sh rilascio out/sicurezza/trivy.json - name: Segreto per il registro id: segreto @@ -182,17 +263,12 @@ jobs: id: pubblicazione if: steps.segreto.outputs.presente == 'si' env: - TOKEN: ${{ secrets.REGISTRY_TOKEN }} - UTENTE: ${{ gitea.actor }} + REGISTRO_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + REGISTRO_UTENTE: ${{ gitea.actor }} run: | set -eu - # Le credenziali nella configurazione del client: buildx le passa al builder, il demone non c'entra. - CONFIG="${DOCKER_CONFIG:-$HOME/.docker}" - mkdir -p "$CONFIG" - [ -s "$CONFIG/config.json" ] || echo '{}' > "$CONFIG/config.json" - AUTH=$(printf '%s:%s' "$UTENTE" "$TOKEN" | base64 -w0) - jq --arg r "$REGISTRY" --arg a "$AUTH" '.auths[$r].auth = $a' "$CONFIG/config.json" > "$CONFIG/config.json.nuovo" - mv "$CONFIG/config.json.nuovo" "$CONFIG/config.json" + # Le credenziali le mette costruisci-immagine.sh pubblica in una configurazione del client solo sua, tolta + # alla fine: buildx le passa al builder, il demone non c'entra. NOMI="$IMAGE:$VERSION" case "$VERSION" in *-*) echo "Versione di anteprima: :latest non si sposta." ;; @@ -202,17 +278,11 @@ jobs: bash .gitea/scripts/costruisci-immagine.sh pubblica $NOMI echo "pubblicata=si" >> "$GITHUB_OUTPUT" - - name: Credenziali tolte - if: always() - run: | - CONFIG="${DOCKER_CONFIG:-$HOME/.docker}/config.json" - if [ -s "$CONFIG" ] && [ -n "${REGISTRY:-}" ]; then - jq --arg r "$REGISTRY" 'if .auths then .auths |= del(.[$r]) else . end' "$CONFIG" > "$CONFIG.nuovo" && mv "$CONFIG.nuovo" "$CONFIG" - fi - - name: Pulizia (sempre) if: always() run: | + # La configurazione del client con le credenziali, se un'interruzione ha saltato la trap di chi l'ha scritta. + rm -rf "${RUNNER_TEMP:-/tmp}/febe-docker-$ESECUZIONE" if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE" # Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione @@ -225,14 +295,38 @@ jobs: # mancanza del segreto (il lavoro «immagine» lo dice e le note lo riportano). Se la costruzione, la prova del # contenitore, la scansione o la spinta sul registro falliscono, non esce nessuna release. needs: [prove, windows, immagine] - timeout-minutes: 15 + timeout-minutes: 40 + env: + # Come «windows»: l'immagine del runner non garantisce ICU, e per costruire l'installatore non serve. + DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: "true" steps: - - uses: actions/checkout@v4 + - name: Sorgenti + env: + TOKEN: ${{ gitea.token }} + SERVER: ${{ gitea.server_url }} + REPOSITORY: ${{ gitea.repository }} + PROFONDITA: "1" + run: | + git config --global --add safe.directory "$PWD" + git init -q . + git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git" + GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" + export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0 + profondita=() + [ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA") + if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then + echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia." + git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro" + fi + git checkout -q --force --detach "$GITHUB_SHA" + git log -1 --format='Commit %h: %s' - - uses: actions/download-artifact@v3 - with: - name: windows - path: out + - name: SDK .NET 10 + run: bash .gitea/scripts/dotnet.sh 10.0 + + # Lo stesso commit e lo stesso script del lavoro «windows», che ha già fatto da cancello prima dell'immagine. + - name: Febe.exe, programma di installazione e zip portabile per la release + run: bash installer/costruisci.sh "${GITHUB_REF_NAME#v}" - name: Release con installatore, zip portabile, modello Unraid e archivio per Compose env: @@ -259,16 +353,26 @@ jobs: fi NOTE=$(printf '%s\n\n### Immagine Docker\n\n%s\n' "$NOTE" "$IMMAGINE_NOTA") - ID=$(curl -sf -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" | jq -r '.id // empty' || true) + # JSON letto e scritto con .gitea/scripts/json.sh (awk), niente jq. Le risposte di Gitea in un file: il + # lettore legge file, non un flusso. + RISPOSTA="${RUNNER_TEMP:-/tmp}/febe-release-${GITHUB_RUN_ID:-0}.json" + ID="" + if curl -sf -H "Authorization: token $TOKEN" "$API/releases/tags/$TAG" -o "$RISPOSTA"; then + ID=$(bash .gitea/scripts/json.sh campi "" id "$RISPOSTA") || ID="" + fi if [ -z "$ID" ]; then - ID=$(jq -n --arg t "$TAG" --arg n "Febe $VERSION" --arg b "$NOTE" --argjson p "$PRE" \ - '{tag_name:$t, name:$n, body:$b, draft:false, prerelease:$p}' \ - | curl -sf -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \ - --data-binary @- "$API/releases" | jq -r .id) + printf '{"tag_name":%s,"name":%s,"body":%s,"draft":false,"prerelease":%s}' \ + "$(bash .gitea/scripts/json.sh stringa "$TAG")" "$(bash .gitea/scripts/json.sh stringa "Febe $VERSION")" \ + "$(bash .gitea/scripts/json.sh stringa "$NOTE")" "$PRE" \ + | curl -sf -X POST -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \ + --data-binary @- "$API/releases" -o "$RISPOSTA" + ID=$(bash .gitea/scripts/json.sh campi "" id "$RISPOSTA") + [[ "$ID" =~ ^[0-9]+$ ]] || { echo "Gitea non ha dato l'identificativo della release creata." >&2; exit 1; } echo "Release $TAG creata (id $ID)" else + [[ "$ID" =~ ^[0-9]+$ ]] || { echo "Identificativo della release inatteso: «$ID»." >&2; exit 1; } # Le note dicono come è andata questa volta (per esempio: l'immagine ora è pubblicata). - jq -n --arg b "$NOTE" '{body:$b}' \ + printf '{"body":%s}' "$(bash .gitea/scripts/json.sh stringa "$NOTE")" \ | curl -sf -X PATCH -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \ --data-binary @- "$API/releases/$ID" > /dev/null echo "Release $TAG già presente (id $ID): note aggiornate, aggiungo gli allegati mancanti" @@ -283,7 +387,9 @@ jobs: cp docker/chromium/seccomp.json "$COMPOSE/chromium/seccomp.json" tar -czf "$COMPOSE.tar.gz" -C out "febe-compose-$VERSION" - ESISTENTI=$(curl -sf -H "Authorization: token $TOKEN" "$API/releases/$ID/assets" | jq -r '.[].name') + curl -sf -H "Authorization: token $TOKEN" "$API/releases/$ID/assets" -o "$RISPOSTA" + ESISTENTI=$(bash .gitea/scripts/json.sh campi "*" name "$RISPOSTA") + rm -f "$RISPOSTA" for f in out/Febe-Setup-*.exe out/Febe-*-portabile.zip "out/febe-unraid-$VERSION.xml" "$COMPOSE.tar.gz"; do n=$(basename "$f") if echo "$ESISTENTI" | grep -qx "$n"; then echo "$n già allegato"; continue; fi diff --git a/.gitea/workflows/verifica.yml b/.gitea/workflows/verifica.yml index aa9821a..857c50b 100644 --- a/.gitea/workflows/verifica.yml +++ b/.gitea/workflows/verifica.yml @@ -1,26 +1,34 @@ # Verifica: a ogni push su qualunque ramo (i tag li prende rilascio.yml) e a mano (Actions ▸ verifica ▸ Esegui). # I suoi quattro lavori sono i controlli richiesti per unire in main (docs/processo.md): -# controlli sintassi degli script, flussi senza tabulazioni, segni di conflitto, versione, progetti della -# soluzione, JSON; segreti in tutta la storia con gitleaks (versione e impronta fissate); +# controlli sintassi degli script, flussi in YAML a blocchi e senza azioni, segni di conflitto, versione, +# progetti della soluzione, JSON; segreti in tutta la storia con gitleaks (versione e impronta fissate); # prove compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di tests/Febe.Tests # (mai «dotnet test» sulla soluzione intera: tests/Febe.Tests.Windows gira solo su Windows) con -# Chromium, Xvfb, NSIS e Node veri in un contenitore Debian 13: nessuna prova deve saltarsi, tranne -# le «da fare» di H264ConformanceTests.FeaturesStillToDo (riepilogo-prove.sh le conta a parte). +# Chromium e Xvfb veri in un contenitore Debian 13: nessuna prova deve saltarsi, tranne le «da fare» +# di H264ConformanceTests.FeaturesStillToDo (riepilogo-prove.sh le conta a parte). # Il mondo sintetico del sito di prova ha il seme 13 e, per la categoria SitoDiProva, anche il seme di # questa esecuzione, scritto nel registro per rifare un errore; -# installatore Febe-Setup--ci..exe e lo zip portabile, artefatti per 14 giorni; +# installatore Febe-Setup--ci..exe (il programma di installazione nostro, src/Febe.Installer) e +# lo zip portabile; serve solo il .NET SDK; # immagine dopo l'installatore: l'immagine Docker costruita con buildx, provata senza rete (parte, salute, # Chromium, it_IT) e scansionata con Trivy (si ferma per una CRITICAL con correzione); solo dopo un push # su main la pubblica come :main e :sha-<7 caratteri> (:latest resta al rilascio). Alla fine, sempre, # toglie immagini, contenitori, cache e builder di questa esecuzione, poi le immagini senza nome e la # cache di costruzione penzolante non usata da 24 ore di tutti i progetti del demone. # +# Niente azioni (decisione di Alberto del 18 novembre 2026: niente componenti esterni): ogni passo è un comando. I +# sorgenti arrivano con git e il gettone del lavoro, l'SDK .NET con .gitea/scripts/dotnet.sh (verificato con l'impronta +# dei metadati di Microsoft), il builder buildx con costruisci-immagine.sh builder. Gli artefatti (risultati delle +# prove, installatore e zip, rapporti di gitleaks e di Trivy) vanno nel registro dei pacchetti di Gitea, pacchetto +# generico febe-ci, versione -ci., con REGISTRY_TOKEN (.gitea/scripts/artefatti.sh); la pulizia del +# lunedì toglie quelli di più di 14 giorni. Senza il segreto un avviso, e il lavoro resta verde. Nessun passo usa Node. +# # Niente «pull_request»: in Gitea una richiesta di unione mostra lo stato del suo ultimo commit, che il push del ramo # ha già verificato; pull_request rifarebbe tutto sullo stesso commit (refs/pull/N/head) sull'unico runner. # Runner: act_runner con l'etichetta ubuntu-latest, un lavoro alla volta. I lavori parlano con il demone Docker del # server, lo stesso di Encelado, Mimante e degli altri progetti: niente montaggi della cartella del lavoro in altri # contenitori (sul server i percorsi sono diversi); le immagini passano come archivi e contesti di costruzione. -# Che cosa di Gitea 28 si usa e perché: docs/decisioni.md (20 ottobre 2026) e docs/processo.md. +# Che cosa di Gitea 28 si usa e perché: docs/decisioni.md (20 ottobre e 18 novembre 2026) e docs/processo.md. name: verifica on: @@ -57,11 +65,32 @@ jobs: controlli: runs-on: ubuntu-latest timeout-minutes: 10 + env: + NUMERO: ${{ gitea.run_number }} steps: - # Tutta la storia: gitleaks legge ogni commit da cui discende quello verificato. - - uses: actions/checkout@v4 - with: - fetch-depth: 0 + # I sorgenti del commit con git e il gettone del lavoro, che vale solo finché il lavoro gira e non resta nella + # configurazione del repository. Qui tutta la storia (PROFONDITA 0): gitleaks legge ogni commit da cui discende + # quello verificato. Lo stesso passo, lettera per lettera, apre ogni lavoro (lo controlla PipelineTests). + - name: Sorgenti + env: + TOKEN: ${{ gitea.token }} + SERVER: ${{ gitea.server_url }} + REPOSITORY: ${{ gitea.repository }} + PROFONDITA: "0" + run: | + git config --global --add safe.directory "$PWD" + git init -q . + git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git" + GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" + export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0 + profondita=() + [ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA") + if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then + echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia." + git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro" + fi + git checkout -q --force --detach "$GITHUB_SHA" + git log -1 --format='Commit %h: %s' - name: Script, flussi, conflitti, versione, soluzione e JSON run: bash .gitea/scripts/controlli.sh @@ -69,33 +98,60 @@ jobs: - name: Segreti in tutta la storia (gitleaks) run: bash .gitea/scripts/segreti.sh out/sicurezza - - name: Rapporto di gitleaks (segreti oscurati) + - name: Rapporto di gitleaks (segreti oscurati, pacchetto febe-ci) if: failure() - uses: actions/upload-artifact@v3 - with: - name: rapporto-gitleaks - path: out/sicurezza/gitleaks.json - retention-days: 14 - if-no-files-found: ignore + env: + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + GITEA_URL: ${{ gitea.server_url }} + PROPRIETARIO: ${{ gitea.repository_owner }} + run: | + [ -f out/sicurezza/gitleaks.json ] || { echo "Nessun rapporto di gitleaks."; exit 0; } + bash .gitea/scripts/artefatti.sh verifica out/sicurezza/gitleaks.json prove: needs: controlli runs-on: ubuntu-latest timeout-minutes: 60 - # Debian 13 con Node 24: Chromium vero della distribuzione, come nell'immagine di Febe (su Ubuntu è uno snap), e - # Node per le azioni e per la prova della pagina di accesso. + # Debian 13, nient'altro: Chromium vero della distribuzione, come nell'immagine di Febe (su Ubuntu è uno snap). Senza + # azioni non serve Node: git e curl prima dei sorgenti, il resto da ambiente-prove.sh, l'SDK da dotnet.sh. # Memoria condivisa più ampia dei 64 MB predefiniti: le prove dell'interfaccia usano un Chromium senza finestra. container: - image: node:24-trixie + image: debian:trixie options: --shm-size=1g env: FEBE_CHROMIUM: /usr/bin/chromium SEME_RICHIESTO: ${{ gitea.event.inputs.seme }} NUMERO: ${{ gitea.run_number }} steps: - - uses: actions/checkout@v4 + - name: Git e curl per i sorgenti + run: | + export DEBIAN_FRONTEND=noninteractive + apt-get update -qq + apt-get install -y -qq --no-install-recommends git curl ca-certificates > /dev/null + git --version - # Prima di tutto, così un seme chiesto a mano e sbagliato ferma subito il lavoro. + - name: Sorgenti + env: + TOKEN: ${{ gitea.token }} + SERVER: ${{ gitea.server_url }} + REPOSITORY: ${{ gitea.repository }} + PROFONDITA: "1" + run: | + git config --global --add safe.directory "$PWD" + git init -q . + git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git" + GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" + export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0 + profondita=() + [ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA") + if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then + echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia." + git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro" + fi + git checkout -q --force --detach "$GITHUB_SHA" + git log -1 --format='Commit %h: %s' + + # Prima di tutto il resto, così un seme chiesto a mano e sbagliato ferma subito il lavoro. - name: Semi del mondo sintetico id: semi run: | @@ -109,12 +165,11 @@ jobs: echo "Mondo sintetico: seme 13 per tutte le prove, seme $seme per la seconda passata (categoria SitoDiProva)." echo "Per rifarla: FEBE_SEME_PROVA=$seme dotnet test tests/Febe.Tests --filter \"TestCategory=SitoDiProva\"" - - name: Chromium, Xvfb, NSIS e lingua italiana + - name: Chromium, Xvfb e lingua italiana run: bash .gitea/scripts/ambiente-prove.sh - - uses: actions/setup-dotnet@v4 - with: - dotnet-version: "10.0.x" + - name: SDK .NET 10 + run: bash .gitea/scripts/dotnet.sh 10.0 - name: Compilazione di tutta la soluzione (avvisi = errori) run: dotnet build Febe.slnx -c Release -nologo -warnaserror @@ -136,14 +191,17 @@ jobs: if: ${{ !cancelled() }} run: bash .gitea/scripts/riepilogo-prove.sh out/prove 0 - - name: Risultati delle prove + - name: Risultati delle prove (pacchetto febe-ci) if: ${{ !cancelled() }} - uses: actions/upload-artifact@v3 - with: - name: risultati-prove - path: out/prove/*.trx - retention-days: 14 - if-no-files-found: warn + env: + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + GITEA_URL: ${{ gitea.server_url }} + PROPRIETARIO: ${{ gitea.repository_owner }} + run: | + shopt -s nullglob + risultati=(out/prove/*.trx) + ((${#risultati[@]} > 0)) || { echo "::warning::Nessun risultato delle prove da conservare."; exit 0; } + bash .gitea/scripts/artefatti.sh verifica "${risultati[@]}" installatore: needs: prove @@ -155,17 +213,29 @@ jobs: # bisogno, quindi .NET va in globalizzazione invariante invece di fermarsi («Couldn't find a valid ICU package»). DOTNET_SYSTEM_GLOBALIZATION_INVARIANT: "true" steps: - - uses: actions/checkout@v4 - - - uses: actions/setup-dotnet@v4 - with: - dotnet-version: "10.0.x" - - - name: NSIS e zip + - name: Sorgenti + env: + TOKEN: ${{ gitea.token }} + SERVER: ${{ gitea.server_url }} + REPOSITORY: ${{ gitea.repository }} + PROFONDITA: "1" run: | - SUDO=""; [ "$(id -u)" = 0 ] || SUDO=sudo - $SUDO apt-get update -qq - $SUDO apt-get install -y -qq nsis zip > /dev/null + git config --global --add safe.directory "$PWD" + git init -q . + git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git" + GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" + export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0 + profondita=() + [ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA") + if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then + echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia." + git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro" + fi + git checkout -q --force --detach "$GITHUB_SHA" + git log -1 --format='Commit %h: %s' + + - name: SDK .NET 10 + run: bash .gitea/scripts/dotnet.sh 10.0 - name: Febe.exe, programma di installazione e zip portabile (versione di prova) run: | @@ -173,15 +243,16 @@ jobs: echo "Versione di questa esecuzione: $V-ci.$NUMERO" bash installer/costruisci.sh "$V-ci.$NUMERO" - - name: Artefatti per Windows - uses: actions/upload-artifact@v3 - with: - name: windows - path: | - out/Febe-Setup-*.exe - out/Febe-*-portabile.zip - retention-days: 14 - if-no-files-found: error + - name: Artefatti per Windows (pacchetto febe-ci) + env: + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + GITEA_URL: ${{ gitea.server_url }} + PROPRIETARIO: ${{ gitea.repository_owner }} + run: | + shopt -s nullglob + artefatti=(out/Febe-Setup-*.exe out/Febe-*-portabile.zip) + ((${#artefatti[@]} == 2)) || { echo "Servono il programma di installazione e lo zip portabile, non: ${artefatti[*]:-niente}." >&2; exit 1; } + bash .gitea/scripts/artefatti.sh verifica "${artefatti[@]}" # Dopo l'installatore, non solo dopo le prove: :main e :sha- escono solo da un commit con tutta la verifica verde. # Sull'unico runner i lavori vanno comunque uno alla volta, quindi la durata non cambia. @@ -196,7 +267,26 @@ jobs: BUILDER: febe-ci-${{ gitea.run_id }} PROVA: febe-ci:${{ gitea.run_id }} steps: - - uses: actions/checkout@v4 + - name: Sorgenti + env: + TOKEN: ${{ gitea.token }} + SERVER: ${{ gitea.server_url }} + REPOSITORY: ${{ gitea.repository }} + PROFONDITA: "1" + run: | + git config --global --add safe.directory "$PWD" + git init -q . + git remote add origin "$SERVER/$REPOSITORY.git" 2> /dev/null || git remote set-url origin "$SERVER/$REPOSITORY.git" + GIT_CONFIG_VALUE_0="Authorization: basic $(printf 'x-access-token:%s' "$TOKEN" | base64 -w0)" + export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0 + profondita=() + [ "$PROFONDITA" = 0 ] || profondita=(--depth "$PROFONDITA") + if ! git fetch -q --no-tags "${profondita[@]}" origin "$GITHUB_SHA"; then + echo "Il server non dà il commit per identificativo: prendo $GITHUB_REF con tutta la storia." + git fetch -q --no-tags origin "+$GITHUB_REF:refs/remotes/origin/lavoro" + fi + git checkout -q --force --detach "$GITHUB_SHA" + git log -1 --format='Commit %h: %s' # Ciò che un'esecuzione interrotta (annullata, scaduta) non ha potuto togliere, e un tentativo precedente di # questa stessa esecuzione. @@ -207,7 +297,6 @@ jobs: # Registro: la variabile REGISTRY delle Actions, se c'è, altrimenti l'host dell'indirizzo del server (ROOT_URL). - name: Versione, registro e nomi - id: nome env: REGISTRO_SCELTO: ${{ vars.REGISTRY }} SERVER: ${{ gitea.server_url }} @@ -224,19 +313,11 @@ jobs: echo "IMAGE=$REGISTRY/$OWNER/febe" echo "ARCHIVIO=${RUNNER_TEMP:-/tmp}/febe-$ESECUZIONE.tar" } >> "$GITHUB_ENV" - echo "registro=$REGISTRY" >> "$GITHUB_OUTPUT" echo "Immagine $V-ci.$NUMERO del commit ${GITHUB_SHA::12}, provata come $PROVA; registro $REGISTRY/$OWNER/febe" # Un builder buildx di questa esecuzione (con la sua cache), che sa che il registro di casa risponde in HTTP. - name: Builder buildx dell'esecuzione - uses: docker/setup-buildx-action@v3 - with: - name: febe-ci-${{ gitea.run_id }} - driver: docker-container - buildkitd-config-inline: | - [registry."${{ steps.nome.outputs.registro }}"] - http = true - insecure = true + run: bash .gitea/scripts/costruisci-immagine.sh builder "$REGISTRY" - name: Costruzione dell'immagine (dentro girano compilazione e prove) run: | @@ -249,14 +330,15 @@ jobs: - name: Vulnerabilità dell'immagine (Trivy) run: bash .gitea/scripts/scansione-immagine.sh "$ARCHIVIO" out/sicurezza - - name: Rapporto di Trivy + - name: Rapporto di Trivy (pacchetto febe-ci) if: ${{ !cancelled() }} - uses: actions/upload-artifact@v3 - with: - name: sicurezza-immagine - path: out/sicurezza/trivy.json - retention-days: 14 - if-no-files-found: ignore + env: + REGISTRY_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + GITEA_URL: ${{ gitea.server_url }} + PROPRIETARIO: ${{ gitea.repository_owner }} + run: | + [ -f out/sicurezza/trivy.json ] || { echo "Nessun rapporto di Trivy."; exit 0; } + bash .gitea/scripts/artefatti.sh verifica out/sicurezza/trivy.json - name: Pubblicare? id: segreto @@ -278,22 +360,20 @@ jobs: - name: Pubblicazione come :main e :sha- if: steps.segreto.outputs.presente == 'si' env: - TOKEN: ${{ secrets.REGISTRY_TOKEN }} - UTENTE: ${{ gitea.actor }} + REGISTRO_TOKEN: ${{ secrets.REGISTRY_TOKEN }} + REGISTRO_UTENTE: ${{ gitea.actor }} + GITEA_TOKEN: ${{ gitea.token }} run: | - # Le credenziali vanno nella configurazione del client: buildx le passa al builder, il demone non c'entra (e - # proverebbe HTTPS). Non si stampano mai. - CONFIG="${DOCKER_CONFIG:-$HOME/.docker}" - mkdir -p "$CONFIG" - [ -s "$CONFIG/config.json" ] || echo '{}' > "$CONFIG/config.json" - AUTH=$(printf '%s:%s' "$UTENTE" "$TOKEN" | base64 -w0) - jq --arg r "$REGISTRY" --arg a "$AUTH" '.auths[$r].auth = $a' "$CONFIG/config.json" > "$CONFIG/config.json.nuovo" - mv "$CONFIG/config.json.nuovo" "$CONFIG/config.json" + # Le credenziali le mette costruisci-immagine.sh pubblica in una configurazione del client solo sua, tolta + # alla fine: buildx le passa al builder, il demone non c'entra (e proverebbe HTTPS). Non si stampano mai. NOMI=("$IMAGE:sha-${GITHUB_SHA::7}") # :main solo se main è ancora a questo commit: un'esecuzione arrivata in ritardo non lo riporta indietro. - # Il passo gira con «bash -e -o pipefail»: senza «|| CIMA=""» un errore di ls-remote chiuderebbe il passo - # prima dell'avviso, e non uscirebbe nemmeno la :sha-. - CIMA=$(git ls-remote origin refs/heads/main 2> /dev/null | cut -f1) || CIMA="" + # Il gettone del lavoro solo nell'ambiente di git, come per i sorgenti. Il passo gira con «bash -e -o + # pipefail»: senza «|| CIMA=""» un errore di ls-remote chiuderebbe il passo prima dell'avviso, e non + # uscirebbe nemmeno la :sha-. + INTESTAZIONE="Authorization: basic $(printf 'x-access-token:%s' "$GITEA_TOKEN" | base64 -w0)" + CIMA=$(GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0=http.extraHeader GIT_CONFIG_VALUE_0="$INTESTAZIONE" \ + git ls-remote origin refs/heads/main 2> /dev/null | cut -f1) || CIMA="" if [ "$CIMA" = "$GITHUB_SHA" ]; then NOMI+=("$IMAGE:main") elif [ -z "$CIMA" ]; then @@ -306,11 +386,8 @@ jobs: - name: Pulizia (sempre) if: always() run: | - CONFIG="${DOCKER_CONFIG:-$HOME/.docker}/config.json" - if [ -s "$CONFIG" ] && [ -n "${REGISTRY:-}" ]; then - jq --arg r "$REGISTRY" 'if .auths then .auths |= del(.[$r]) else . end' "$CONFIG" > "$CONFIG.nuovo" \ - && mv "$CONFIG.nuovo" "$CONFIG" || echo "::warning::Non riesco a togliere le credenziali da $CONFIG." - fi + # La configurazione del client con le credenziali, se un'interruzione ha saltato la trap di chi l'ha scritta. + rm -rf "${RUNNER_TEMP:-/tmp}/febe-docker-$ESECUZIONE" if [ -n "${ARCHIVIO:-}" ]; then rm -f "$ARCHIVIO"; fi bash .gitea/scripts/pulizia-docker.sh esecuzione "$ESECUZIONE" # Poi, per tutti i progetti del demone, ciò che nessuno usa: immagini senza nome e cache di costruzione diff --git a/CLAUDE.md b/CLAUDE.md index bbb52b8..825ef61 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -24,7 +24,7 @@ All'inizio di ogni sessione leggi docs/stato.md. 9. I lettori si scrivono solo su campioni reali ripuliti. Il formato delle risposte non si inventa. 10. Mai password, cookie, gettoni, tasti, variabili o corpi di richieste e risposte nei log. Il client CDP registra solo nomi di comandi; il client del sito solo operazione o forma del percorso e stato. 11. La libreria non cancella e non sostituisce file da sola. -12. Niente componenti esterni: niente ffmpeg, programmi, librerie o file di dati di terzi (caratteri, icone); tutto il codice in casa, i formati dalle loro specifiche pubbliche. Ammessi solo .NET/BCL con ASP.NET Core, Microsoft.Data.Sqlite, il browser (Chromium o WebView2 con Microsoft.Web.WebView2, regola 4) e MSTest; nella sola CI gitleaks e Trivy (docs/processo.md); nell'immagine Docker solo Chromium, i pacchetti Debian che gli servono e Xvfb (mai headless). Escono con la loro tappa della 0.3.0 (specifica §2 regola 13, §15): SkiaSharp con C1, ffmpeg con C3; NSIS, Node, il carattere Archivo e le icone Lucide con C6. Prima di aggiungere qualunque cosa, chiedi. +12. Niente componenti esterni: niente ffmpeg, programmi, librerie o file di dati di terzi (caratteri, icone); tutto il codice in casa, i formati dalle loro specifiche pubbliche. Ammessi solo .NET/BCL con ASP.NET Core, Microsoft.Data.Sqlite, il browser (Chromium o WebView2 con Microsoft.Web.WebView2, regola 4) e MSTest; nella sola CI gitleaks e Trivy (docs/processo.md); nell'immagine Docker solo Chromium, i pacchetti Debian che gli servono e Xvfb (mai headless). Sono già usciti con la loro tappa della 0.3.0 (specifica §2 regola 13, §15): SkiaSharp con C1, ffmpeg con C3; NSIS, Node, il carattere Archivo e le icone Lucide con C6. Prima di aggiungere qualunque cosa, chiedi. ## Convenzioni - Codice e commenti in inglese; interfaccia, documenti e messaggi in italiano (glossario: appendice D). @@ -41,9 +41,9 @@ Conserva: tappa in corso, file modificati, controlli ancora da eseguire, domande - Repository: Gitea di casa, https://gitea.encke-hake.ts.net/Alby96/Febe (ramo main). Non è GitHub: niente strumenti GitHub. - Processo (rami `/`, commit piccoli, una richiesta di unione per ramo, verifica verde per unire in main, commit di unione, rilasci, correzioni urgenti): docs/processo.md. - CI in `.gitea/workflows/`, script comuni in `.gitea/scripts/`: - - `verifica.yml` a ogni push su qualunque ramo (non sui tag) e a mano, niente pull_request: controlli e gitleaks; compilazione di tutta la soluzione e tutte le prove di `tests/Febe.Tests` con Chromium e Xvfb veri in Debian (più ffmpeg fino alla tappa C3, NSIS e Node fino alla tappa C6 della 0.3.0: regola 12), nessuna saltata, anche con il seme dell'esecuzione (`FEBE_SEME_PROVA`); installatore e zip `-ci.`; immagine provata senza rete e scansionata con Trivy. Dopo un push su main pubblica `:main` e `:sha-` (con il segreto `REGISTRY_TOKEN`; senza, un avviso). - - `rilascio.yml` a ogni tag `vX.Y.Z`: immagine `:X.Y.Z` (e `:latest`) sul registro di Gitea, installatore Windows e release. - - `pulizia.yml` ogni lunedì e a mano (con «Solo prova» elenca e non toglie nulla): resti della CI di Febe e di act_runner, immagini che nessun contenitore usa e cache di costruzione più vecchie di 24 ore, di tutti i progetti; con `REGISTRY_TOKEN` le `:sha-` oltre le 10 più recenti, mai `main`, `latest` o `X.Y.Z`. Mai contenitori, volumi o reti che non siano della CI, mai `system prune`. Ogni lavoro «immagine» toglie alla fine anche le immagini senza nome e la cache penzolante non usata da 24 ore. + - `verifica.yml` a ogni push su qualunque ramo (non sui tag) e a mano, niente pull_request: solo comandi, nessuna azione (`uses:`) e niente Node (sorgenti con git e il gettone del lavoro, SDK con `.gitea/scripts/dotnet.sh`, JSON con `.gitea/scripts/json.sh`, niente jq); controlli e gitleaks; compilazione di tutta la soluzione e tutte le prove di `tests/Febe.Tests` con Chromium e Xvfb veri in Debian (`debian:trixie`), nessuna saltata, anche con il seme dell'esecuzione (`FEBE_SEME_PROVA`); installatore (nostro, `src/Febe.Installer`, solo .NET SDK) e zip `-ci.`, con i risultati e i rapporti nel pacchetto generico `febe-ci` del registro (con `REGISTRY_TOKEN`; senza, un avviso); immagine provata senza rete e scansionata con Trivy. Dopo un push su main pubblica `:main` e `:sha-` (con il segreto `REGISTRY_TOKEN`; senza, un avviso). + - `rilascio.yml` a ogni tag `vX.Y.Z`: le prove come nella verifica (`debian:trixie` con Chromium, nessuna saltata), poi immagine `:X.Y.Z` (e `:latest`) sul registro di Gitea, installatore Windows e release; le credenziali del registro solo in un `DOCKER_CONFIG` della pubblicazione, tolto alla fine. + - `pulizia.yml` ogni lunedì e a mano (con «Solo prova» elenca e non toglie nulla): resti della CI di Febe e di act_runner, immagini che nessun contenitore usa e cache di costruzione più vecchie di 24 ore, di tutti i progetti; con `REGISTRY_TOKEN` le `:sha-` oltre le 10 più recenti e le versioni del pacchetto `febe-ci` di più di 14 giorni, mai `main`, `latest` o `X.Y.Z`. Mai contenitori, volumi o reti che non siano della CI, mai `system prune`. Ogni lavoro «immagine» toglie alla fine anche le immagini senza nome e la cache penzolante non usata da 24 ore. - Le prove nella CI passano solo da `tests/Febe.Tests`, mai `dotnet test` sulla soluzione intera. - La versione sta solo in `Directory.Build.props` (``); il tag deve coincidere. - Guida per l'uso: wiki del repository (sorgenti in `docs/guida/`). diff --git a/Febe.slnx b/Febe.slnx index 38a7235..bdb4442 100644 --- a/Febe.slnx +++ b/Febe.slnx @@ -8,6 +8,7 @@ + @@ -15,6 +16,7 @@ + diff --git a/docker/Dockerfile b/docker/Dockerfile index 02ec824..4e3b896 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -14,8 +14,8 @@ # test tutte le prove: un'immagine con prove rosse non esiste. Qui non ci sono Chromium né Xvfb, quindi le prove # con il browser vero risultano «inconcludenti» (saltate) e girano solo dove ci sono (CI, sviluppo); # publish Febe.Server autosufficiente per linux-x64: nell'immagine non serve il runtime .NET; -# runtime Debian stabile ridotta (trixie-slim) con Chromium della distribuzione, Xvfb, ICU, caratteri -# (anche emoji), certificati, fusi orari, lingua italiana; tini come processo 1; setpriv per PUID/PGID. +# runtime Debian stabile ridotta (trixie-slim) con Chromium della distribuzione, Xvfb, ICU, un carattere e le +# emoji, certificati, fusi orari, lingua italiana; Febe come processo 1; setpriv per PUID/PGID. # # Vedi docs/docker.md per volumi, variabili, porte, sandbox, salute e aggiornamento. @@ -74,9 +74,38 @@ LABEL org.opencontainers.image.title="Febe" \ org.opencontainers.image.source="https://gitea.encke-hake.ts.net/Alby96/Febe" \ org.opencontainers.image.url="https://gitea.encke-hake.ts.net/Alby96/Febe" -# Chromium della distribuzione con le sue lingue, il display virtuale, ICU e -# le librerie del runtime .NET autosufficiente, caratteri di sistema con le emoji, certificati, fusi orari, la lingua -# italiana generata, tini come processo 1 (raccoglie i processi di Chromium), setpriv (util-linux) per PUID/PGID. +# Chromium della distribuzione con le sue lingue, il display virtuale, ICU e le librerie del runtime .NET +# autosufficiente, il carattere che fontconfig chiede e quello delle emoji, certificati, fusi orari, la lingua italiana +# generata. +# Decisione di Alberto del 18 novembre 2026: nell'immagine solo Chromium con i pacchetti di Debian che gli servono, +# Xvfb e ciò che serve al runtime .NET; nient'altro. L'interfaccia di Febe la disegna il browser di chi la apre, con i +# suoi caratteri: quelli qui sotto servono al Chromium del contenitore, che mostra il sito e la vista remota. Ogni +# pacchetto della lista, e perché c'è (le dipendenze le porta apt da solo): +# chromium il browser di Febe (specifica §6.1), quello della distribuzione; +# chromium-l10n le lingue di Chromium: con LANG=it_IT.UTF-8 menu e Accept-Language sono in italiano come +# nel browser di Alberto (senza, Chromium ha solo l'inglese); +# xvfb il display virtuale: Chromium non è mai headless; +# libicu76 ICU per il runtime .NET (globalizzazione non invariante: date, ordinamenti e testi in +# italiano); Chromium ha la sua; +# libssl3t64 OpenSSL per il runtime .NET: TLS del client del sito e del CDN, AES-GCM della sessione +# salvata; Chromium ha la sua; +# libstdc++6 chiesta dal runtime .NET (libcoreclr, libclrjit, libhostfxr la caricano); +# libgcc-s1 chiesta dal runtime .NET e da Chromium; +# zlib1g chiesta da Chromium; il runtime .NET 10 non la usa più (zlib-ng è dentro +# libSystem.IO.Compression.Native); +# fonts-dejavu-core il carattere che fontconfig, la libreria dei caratteri di Chromium, chiede per primo +# (fontconfig-config lo porta comunque): senza un carattere Chromium non disegna il testo; +# fonts-noto-color-emoji le emoji a colori: Chromium ne ha bisogno per mostrare le pagine del sito, piene di emoji, +# nella vista remota; senza, diventano quadratini (risposta di Alberto del 25 novembre +# 2026). Nessun altro carattere: quelli che servono solo all'aspetto restano fuori; +# ca-certificates le autorità di certificazione per il TLS del runtime .NET (Chromium ha le sue); +# tzdata i fusi orari: TZ per il motore (.NET) e per Chromium; +# locales genera it_IT.UTF-8: Chromium (GTK, Xlib) gira con la lingua della libreria C, che deve +# esistere. +# Niente tini: Febe è il processo 1 e il runtime .NET, da processo 1, raccoglie anche i processi rimasti orfani. +# setpriv, groupadd, useradd e getent per l'avvio sono già nell'immagine di base (util-linux è essenziale in Debian, +# passwd e libc-bin sono fra i pacchetti richiesti): la costruzione si ferma se uno manca. Niente curl: la sonda di +# salute è Febe stesso. # Prima gli aggiornamenti di sicurezza della distribuzione già pubblicati, anche quelli arrivati dopo l'immagine di # base: la scansione della CI non deve trovare correzioni disponibili e non applicate. ENV DEBIAN_FRONTEND=noninteractive @@ -86,11 +115,13 @@ RUN apt-get update \ chromium chromium-l10n \ xvfb \ libicu76 libssl3t64 libstdc++6 libgcc-s1 zlib1g \ - fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \ + fonts-dejavu-core fonts-noto-color-emoji \ ca-certificates tzdata locales \ - tini util-linux passwd \ && sed -i 's/^# *\(it_IT.UTF-8 UTF-8\)/\1/' /etc/locale.gen \ && locale-gen \ + && for comando in setpriv groupadd useradd getent; do \ + command -v "$comando" > /dev/null || { echo "Manca $comando nell'immagine di base." >&2; exit 1; }; \ + done \ && rm -rf /var/lib/apt/lists/* # Criteri di Chromium: niente salvataggio delle password né compilazione automatica (nel profilo resta solo la sessione). @@ -127,8 +158,9 @@ EXPOSE 8480 HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \ CMD ["/app/febe", "--controllo-salute"] -# tini è il processo 1: inoltra SIGTERM a Febe (che ferma il motore, poi Chromium con SIGINT, poi Xvfb) e raccoglie i -# processi figli di Chromium rimasti orfani. +# Il processo 1 è Febe: l'avvio fa exec di setpriv, che fa exec del server, e il numero di processo resta 1. SIGTERM +# arriva a Febe (che ferma il motore, poi Chromium con SIGINT, poi Xvfb), e il runtime .NET, quando è il processo 1, +# raccoglie anche i processi figli di Chromium rimasti orfani (System.Native, «reapAll» con il processo 1). STOPSIGNAL SIGTERM -ENTRYPOINT ["/usr/bin/tini", "--", "/usr/local/bin/febe-avvio"] +ENTRYPOINT ["/usr/local/bin/febe-avvio"] CMD ["/app/febe"] diff --git a/docker/compose.yml b/docker/compose.yml index c74b49e..c1c4c9d 100644 --- a/docker/compose.yml +++ b/docker/compose.yml @@ -23,7 +23,7 @@ services: # VERSION: ${VERSION:-dev} # GIT_COMMIT: ${GIT_COMMIT:-n/d} container_name: febe - # tini è già nell'immagine come processo 1: «init: true» non serve. + # Il processo 1 è Febe, e il runtime .NET da processo 1 raccoglie i processi orfani: «init: true» non serve. restart: unless-stopped # Febe ferma il motore, poi Chromium con SIGINT (la sessione resta nel profilo), poi Xvfb. stop_grace_period: 30s diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index aa6cd63..7142152 100755 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -5,6 +5,8 @@ # 1. crea, se mancano, il gruppo PGID e l'utente PUID (su Unraid 99 e 100, «nobody:users»); # 2. rende /dati di quell'utente (la prima volta, o se PUID/PGID sono cambiati) e gli fa preparare /dati/home; # 3. exec del server con setpriv, come quell'utente: il server avvia e sorveglia da sé Xvfb e Chromium. +# Sempre exec, mai un processo figlio: il server prende il posto di questo script come processo 1 del contenitore +# (niente tini), riceve SIGTERM da «docker stop» e, con il runtime .NET, raccoglie i processi rimasti orfani. # Nessun ciclo di sorveglianza qui: è il lavoro di Febe.Server (niente script di shell che facciano da supervisore). # /libreria non si cambia mai ricorsivamente (sono le foto di Alberto); /importa è in sola lettura e non si tocca. # Se /dati non si può sistemare (disco di rete, permessi) si parte lo stesso: è Febe a spiegare il problema nella sua diff --git a/docs/SPECIFICA.md b/docs/SPECIFICA.md index 49f4db5..cff7dbc 100644 --- a/docs/SPECIFICA.md +++ b/docs/SPECIFICA.md @@ -90,7 +90,7 @@ Queste regole prevalgono su qualunque altra indicazione del documento e su qualu 10. **Il formato delle risposte di Instagram non si inventa.** I lettori si scrivono soltanto su campioni reali raccolti nella tappa M0. Se un campione manca, chiedilo. 11. **Segreti fuori dai registri e fuori da git.** Mai password, cookie, gettoni (`fb_dtsg`, `lsd`, `csrftoken`, `x-ig-www-claim`), tasti premuti, corpi di richieste e di risposte, variabili delle interrogazioni né indirizzi con i loro parametri nei log, nei messaggi di errore e nel rapporto di diagnostica. La sessione salvata non va mai in git, nelle copie del database né nell'interfaccia: la pagina Collegamento ne mostra solo la data della copia, i conteggi e i nomi dei valori che mancano, mai un valore (§6.0, §13.2). I campioni grezzi stanno fuori dal repository. 12. **La libreria non cancella e non sostituisce da sola.** Se un contenuto sparisce da Instagram, il file resta. Un file della libreria si elimina o si sostituisce solo per una scelta esplicita di Alberto. Anche la conversione del formato della libreria (§4.10) aggiunge il file convertito accanto all'originale, che resta; e nelle cartelle di esportazione Febe non cancella né sovrascrive mai nulla, salvo i propri file temporanei `.part`. -13. **Niente componenti esterni** (§3, decisioni di Alberto del 18 novembre 2026). Niente ffmpeg o ffprobe, nessun altro programma, nessuna libreria di terzi, nessun file di dati di terzi (caratteri, icone) e nessun codice copiato da altri progetti: tutto il codice si scrive in casa sulla libreria di base di .NET, i formati dalle loro specifiche pubbliche. Ammessi solo la libreria di base di .NET con ASP.NET Core, `Microsoft.Data.Sqlite`, il browser (regola 2: Chromium in Docker, WebView2 su Windows con `Microsoft.Web.WebView2`) e MSTest per le prove; nella sola CI gitleaks e Trivy, approvati da Alberto (`docs/processo.md`); nell'immagine Docker e nel contenitore delle prove solo Chromium, i pacchetti Debian che gli servono e Xvfb, perché Chromium ha sempre una finestra e non è mai headless (§11). Gli altri componenti ancora in uso escono con la loro tappa del traguardo 0.3.0 (§15), e finché la tappa non è unita il codice di prima li usa: SkiaSharp con C1, ffprobe con C2, ffmpeg con C3; NSIS (al suo posto un installatore scritto in casa), Node (la CI con passi di shell, git e curl verso l'API di Gitea), il carattere Archivo (i caratteri di sistema, `system-ui`) e le icone Lucide (icone SVG disegnate in casa) con C6. Prima di aggiungere qualunque cosa chiedi, spiegando perché non basta ciò che c'è. +13. **Niente componenti esterni** (§3, decisioni di Alberto del 18 novembre 2026). Niente ffmpeg o ffprobe, nessun altro programma, nessuna libreria di terzi, nessun file di dati di terzi (caratteri, icone) e nessun codice copiato da altri progetti: tutto il codice si scrive in casa sulla libreria di base di .NET, i formati dalle loro specifiche pubbliche. Ammessi solo la libreria di base di .NET con ASP.NET Core, `Microsoft.Data.Sqlite`, il browser (regola 2: Chromium in Docker, WebView2 su Windows con `Microsoft.Web.WebView2`) e MSTest per le prove; nella sola CI gitleaks e Trivy, approvati da Alberto (`docs/processo.md`); nell'immagine Docker e nel contenitore delle prove solo Chromium, i pacchetti Debian che gli servono e Xvfb, perché Chromium ha sempre una finestra e non è mai headless (§11). Gli altri componenti che il progetto usava sono già usciti, ciascuno con la sua tappa del traguardo 0.3.0 (§15), e non si rimettono: SkiaSharp con C1, ffprobe con C2, ffmpeg con C3; NSIS (al suo posto un installatore scritto in casa), Node (la CI con passi di shell, git e curl verso l'API di Gitea), il carattere Archivo (i caratteri di sistema, `system-ui`) e le icone Lucide (icone SVG disegnate in casa) con C6. Prima di aggiungere qualunque cosa chiedi, spiegando perché non basta ciò che c'è. 14. **Resoconti onesti.** Se una cosa non funziona, o non l'hai potuta verificare, scrivilo così. Un «fatto» senza il risultato del controllo non vale. --- @@ -112,31 +112,31 @@ Sono scelte fatte al posto di Alberto per poter scrivere una specifica coerente. | **Profilo «Prudente» come predefinito** | §7.5 | Impostazione | | **Le storie si leggono con una richiesta per account e non risultano viste** | Decisione di Alberto del 16 novembre 2026 (#36, domanda 11 di §16): segnarle come viste sarebbe una scrittura, vietata dalla regola 5. Fino al 15 novembre valeva il contrario: solo dal visualizzatore, con Alberto fra gli spettatori | Domande 5 e 11 di §16 | | **Due percorsi generali: Libreria e Dati** | La richiesta originale era troncata su questo punto | Domanda 3 di §16 | -| **Caratteri di sistema** (`system-ui`) **e icone SVG disegnate in casa** | Decisione di Alberto del 18 novembre 2026 (regola 13): nessun file di dati di terzi, nessun caricamento da rete. Fino alla tappa C6 della 0.3.0 restano il carattere Archivo (OFL) e le icone Lucide (ISC), copiati nel programma (appendici B e C) | — | +| **Caratteri di sistema** (`system-ui`) **e icone SVG disegnate in casa** | Decisione di Alberto del 18 novembre 2026 (regola 13): nessun file di dati di terzi, nessun caricamento da rete. Fino alla tappa C6 della 0.3.0 c'erano il carattere Archivo (OFL) e le icone Lucide (ISC), copiati nel programma: sono usciti con C6 (appendici B e C) | — | **Dipendenze ammesse** (decisioni di Alberto del 18 novembre 2026, regola 13). Niente componenti esterni: niente ffmpeg o ffprobe, nessun altro programma, nessuna libreria di terzi, nessun file di dati di terzi, nessun codice copiato da altri progetti. In esecuzione si usano solo la libreria di base di .NET con ASP.NET Core (framework condiviso: `System.Text.Json`, `HttpClient`, `ClientWebSocket`, `System.Security.Cryptography`, `System.IO.Compression`…), `Microsoft.Data.Sqlite` e il browser: Chromium della distribuzione in Docker, WebView2 su Windows con il suo pacchetto `Microsoft.Web.WebView2`. Per le prove: MSTest. Nella sola CI: gitleaks e Trivy. Nell'immagine Docker e nel contenitore delle prove: Chromium, i pacchetti Debian che gli servono e Xvfb (§11), più ciò che la piattaforma .NET chiede al sistema (ICU, certificati). Nell'interfaccia: nessun pacchetto npm e nessun file di terzi: dalla tappa C6 i caratteri di sistema (`system-ui`, `-apple-system`, `"Segoe UI"`, `Roboto`, `sans-serif`) e icone SVG disegnate in casa. Tutto il resto si scrive in casa, dalle specifiche pubbliche dei formati e mai copiando codice di altri, con `Span` e senza allocazioni nei cicli che lavorano sui pixel (librerie di 200.000 elementi, processori di un server Unraid): -- decodificatori di immagini: JPEG (ITU-T T.81 con codifica di Huffman a 8 bit: di base, sequenziale esteso e progressivo; scala di grigi, YCbCr, e CMYK o YCCK con il segmento APP14 di Adobe; restano fuori la codifica aritmetica, la precisione a 12 bit, il modo senza perdita e il gerarchico, e un file così è uno che non si decodifica), PNG, WEBP con e senza perdita (contenitore RFC 9649; il flusso con perdita VP8 è quello di RFC 6386), GIF (GIF89a, primo fotogramma), BMP. Delle immagini animate (GIF con più di un fotogramma, WEBP con `ANIM`/`ANMF`, PNG animato con `acTL`) si decodifica solo il primo fotogramma, per miniatura e impronta visiva: non si convertono mai (§4.10). Un'immagine troncata o rovinata (un PNG o un JPEG che finisce prima del suo marcatore di fine, un blocco che non torna) non si decodifica a metà: si rifiuta, con la tessera neutra e «File danneggiato o incompleto» (§8.4; risposta di Alberto del 25 novembre 2026); +- decodificatori di immagini: JPEG (ITU-T T.81: di base, sequenziale esteso, progressivo e senza perdita, con codifica di Huffman o con codifica aritmetica, a 8 bit e con la precisione a 12 bit, da 2 a 16 bit il senza perdita; scala di grigi, YCbCr, RGB, e CMYK o YCCK con il segmento APP14 di Adobe; resta fuori il gerarchico, con i file a due componenti, e un file così è uno che non si decodifica; si è scritto più di quanto chiedeva la decisione del 18 novembre 2026, `docs/decisioni.md`), PNG, WEBP con e senza perdita (contenitore RFC 9649; il flusso con perdita VP8 è quello di RFC 6386), GIF (GIF89a, primo fotogramma), BMP, HEIC/HEIF (ISO/IEC 23008-12) con immagini HEVC, singole o a griglia di riquadri, sopra il decodificatore H.265 qui sotto: dimensioni, miniatura e impronta visiva. Un HEIF che non si decodifica (AVIF o JPEG dentro HEIF, immagini derivate diverse dalle griglie, sequenze, una proprietà essenziale sconosciuta, o un file rovinato) ha solo la tessera neutra e non si dice mai «File danneggiato o incompleto», perché il decodificatore non distingue un file rovinato da uno che non gestisce. Delle immagini animate (GIF con più di un fotogramma, WEBP con `ANIM`/`ANMF`, PNG animato con `acTL`) si decodifica solo il primo fotogramma, per miniatura e impronta visiva: non si convertono mai (§4.10). Un'immagine troncata o rovinata (un PNG o un JPEG che finisce prima del suo marcatore di fine, `IEND` o `EOI`, anche quando dati e scansioni sembrano completi; un blocco che non torna) non si decodifica a metà: si rifiuta, con la tessera neutra e «File danneggiato o incompleto» (§8.4; risposta di Alberto del 25 novembre 2026). La sola lettura delle dimensioni dalle intestazioni resta tollerante, così il file ha comunque le sue misure; - codificatori di immagini: JPEG, PNG, WEBP senza perdita; - metadati delle immagini: lettura e scrittura di EXIF (orientamento compreso), profilo ICC e XMP, per copiarli da un formato all'altro (§4.10); - lettori dei contenitori video ISO BMFF (MP4, MOV) e Matroska (MKV, WebM): durata, dimensioni, rotazione, tracce, codec e metadati del contenitore, al posto di ffprobe; -- lettori dei contenitori ASF (WMV, WMA), FLV e MPEG-PS (flusso di programma di ISO/IEC 13818-1, `.mpg`, `.vob`): durata, dimensioni, codec e data dove il contenitore la porta (risposta di Alberto del 18 novembre 2026, tappa C5). Solo lettura dei metadati: i loro video non si rimuxano e non si decodificano, salvo una traccia H.264 o H.265 dentro MPEG-PS, che i decodificatori qui sotto leggono come le altre; +- lettori dei contenitori ASF (WMV, WMA), FLV e MPEG-PS (flusso di programma di ISO/IEC 13818-1, `.mpg`, `.vob`): durata, dimensioni, codec e data dove il contenitore la porta (risposta di Alberto del 18 novembre 2026, tappa C5). Solo lettura dei metadati: i loro video non si rimuxano. Di un MPEG-PS codec e dimensioni vengono dall'intestazione di sequenza MPEG-1 o MPEG-2, o dall'SPS di una traccia H.264 o H.265 (questa solo con il tipo di flusso 0x24 nella mappa del flusso di programma); i suoi campioni, spezzati nei pacchetti PES, non si elencano, quindi nemmeno una traccia H.264 o H.265 dà un fotogramma e la miniatura è la tessera neutra. Fra questi contenitori la miniatura viene solo da un FLV con H.264; - rimuxaggio in MP4, senza ricodifica; - decodificatore H.264 (ITU-T H.264), per i fotogrammi, le miniature dei video importati e i video fermi (§4.10). **Tutto lo standard** (risposta di Alberto del 18 novembre 2026, «Tutto»): profili Baseline (anche non vincolato), Constrained Baseline, Main, Extended (FMO, ASO, fette ridondanti, partizione dei dati, fette SP e SI), High, High 10, High 4:2:2 e High 4:4:4 (Predictive e Intra, con i piani di colore separati e il modo senza perdita), CAVLC 4:4:4 Intra, monocromatico (4:0:0), con la profondità di bit che ogni profilo prevede (fino a 14 bit); video interlacciati (campi, PAFF, MBAFF); CAVLC e CABAC, trasformata 8×8 e matrici di quantizzazione; SVC (allegato G) e MVC (allegato H), di cui per fotogrammi e miniature si usano lo strato con la risoluzione più alta e la vista di base. Un fotogramma con più di 8 bit si porta a 8 bit solo all'uscita, per JPG, PNG e WEBP. Solo un flusso rovinato dice «Fotogramma non disponibile per questo video»; - decodificatore H.265/HEVC (ITU-T H.265; risposta di Alberto del 18 novembre 2026, dentro la 0.3.0, tappa C4), per gli stessi usi: tutti i profili della serie di conformità ITU-T H.265.1 scelta per Febe (cartelle `HEVC_v1` e `RExt`, §16 domanda 18, risposta di Alberto del 25 novembre 2026), cioè Main, Main 10, Main Still Picture e le **estensioni di formato (RExt)** dei flussi della serie, che **restano**: 4:0:0, 4:2:2 e 4:4:4 fino a 12 bit, con i loro strumenti (predizione fra componenti, RDPCM, adattamento di Rice, `chroma_qp_offset_list`). Un fotogramma con più di 8 bit si porta a 8 bit solo all'uscita, come per H.264. Non hanno flussi in quella serie e restano fuori la precisione estesa dei profili a 16 bit, l'allineamento del CABAC, lo scalabile (SHVC), il multivista (MV-HEVC), il 3D e i contenuti dello schermo (SCC): un video così dice «Fotogramma non disponibile per questo video»; - VP9, AV1 e gli altri codec video non si decodificano (non richiesti): miniatura con la tessera neutra e «Fotogramma non disponibile per questo video»; - miniature e impronta visiva (§8.4) sopra questi decodificatori; -- ridimensionamento (filtro cubico di Mitchell–Netravali, quello usato oggi con SkiaSharp) e un piccolo disegnatore 2D: riempimento e contorno con antialias di rettangoli anche arrotondati, cerchi, ovali, linee e tracciati, sfumature lineari, rotazioni, composizione di un'immagine su un'altra. Servono all'icona (`BrandIcon`, Febe.Desktop.Core), alle immagini della modalità dimostrativa (`DemoImages`, `DemoPart2`), all'anteprima dell'importazione (`ImportPreview`), alle immagini del sito di prova (`MediaFactory`) e ai generatori delle prove (`LibraryTestSupport`, `ImportTestFiles`: le varianti ridimensionate, ricompresse e ritagliate di §14.1). Non deve dare gli stessi pixel di SkiaSharp: basta che le prove dei doppioni passino con le soglie di §8.4 invariate; +- ridimensionamento (filtro cubico di Mitchell–Netravali, quello che si usava con SkiaSharp) e un piccolo disegnatore 2D: riempimento e contorno con antialias di rettangoli anche arrotondati, cerchi, ovali, linee e tracciati, sfumature lineari, rotazioni, composizione di un'immagine su un'altra. Servono all'icona (`BrandIcon`, Febe.Desktop.Core), alle immagini della modalità dimostrativa (`DemoImages`, `DemoPart2`), all'anteprima dell'importazione (`ImportPreview`), alle immagini del sito di prova (`MediaFactory`) e ai generatori delle prove (`LibraryTestSupport`, `ImportTestFiles`: le varianti ridimensionate, ricompresse e ritagliate di §14.1). Non deve dare gli stessi pixel di SkiaSharp: basta che le prove dei doppioni passino con le soglie di §8.4 invariate; - l'installatore di Windows (§12), al posto di NSIS: un eseguibile .NET scritto in casa che porta Febe compresso con `System.IO.Compression`, lo installa per l'utente, crea i collegamenti e la voce di disinstallazione, e si costruisce con `dotnet publish` (tappa C6); - i passi della CI (`docs/processo.md`), al posto delle azioni che vogliono Node: script di shell con git (scaricare il commit) e curl verso l'API di Gitea (artefatti, stati, rilasci) (tappa C6); - le icone dell'interfaccia: SVG disegnati in casa, tratto 1,75, con gli stessi nomi d'uso dell'appendice C (tappa C6). -**Il passaggio avviene a tappe nella 0.3.0** (§15): C1 codec delle immagini (esce SkiaSharp con `SkiaSharp.NativeAssets.Linux.NoDependencies`), C2 contenitori e metadati senza ffprobe, C3 tutto H.264 (esce ffmpeg, dall'immagine Docker, dalla CI e dalle prove; fatto sul ramo `funzione/decoder-h264`, non ancora unito), C4 HEVC, C5 lettori ASF, FLV e MPEG-PS, C6 CI senza Node, installatore senza NSIS, caratteri di sistema e icone nostre. **Finché una tappa non è unita, il codice di prima li usa ancora**: SkiaSharp per miniature, impronta visiva, icona, immagini della modalità dimostrativa e del sito di prova, anteprima dell'importazione e generatori delle prove; ffmpeg e ffprobe dal PATH per i video importati; NSIS e Node nella CI; Archivo e Lucide nell'interfaccia. Dati di prova per questi lavori (risposte di Alberto del 18 novembre 2026, §16 domande 15 e 16): +**Il passaggio è avvenuto a tappe nella 0.3.0** (§15), e sono tutte costruite: C1 codec delle immagini (è uscito SkiaSharp, con `SkiaSharp.NativeAssets.Linux.NoDependencies`), C2 contenitori e metadati senza ffprobe, C3 tutto H.264 (è uscito ffmpeg, dall'immagine Docker, dalla CI e dalle prove), C4 HEVC, C5 lettori ASF, FLV e MPEG-PS, C6 CI senza Node, installatore senza NSIS, caratteri di sistema e icone nostre. Miniature, impronta visiva, icona, immagini della modalità dimostrativa e del sito di prova, anteprima dell'importazione e generatori delle prove usano i codec e il disegnatore di Febe; i video importati i suoi lettori dei contenitori e i suoi decodificatori, senza nulla dal PATH; la CI solo comandi di shell; l'interfaccia i caratteri del sistema e le icone disegnate per Febe. Dati di prova per questi lavori (risposte di Alberto del 18 novembre 2026, §16 domande 15 e 16): -- Le serie di conformità ITU-T: H.264.1 per C3 (12 flussi già scaricati e messi nel repository sul ramo `funzione/decoder-h264`, con il permesso di Alberto; si scaricano anche quelli dei profili che mancano, ora che il decodificatore copre tutto lo standard) e H.265.1 per C4, in `tests/Febe.Tests/Media/H264/Conformita` e `tests/Febe.Tests/Media/H265/Conformita`. Nel repository **solo i flussi e l'MD5 dell'uscita di riferimento**, mai le uscite decodificate, con un `LEGGIMI.md` che dice la fonte (indirizzo dell'ITU-T, data dello scaricamento, condizioni d'uso) e l'elenco (nome, profilo, MD5 del flusso e dell'uscita). -- Le immagini di riferimento dei codec, generate una sola volta con SkiaSharp prima che esca (permesso di Alberto, già fatto), tenute come file di prova della tappa C1. +- Le serie di conformità ITU-T: H.264.1 per C3 (scaricati con il permesso di Alberto i primi 12 flussi e poi quelli dei profili che mancavano, perché il decodificatore copre tutto lo standard) e H.265.1 per C4 (cartelle `HEVC_v1` e `RExt`), in `tests/Febe.Tests/Media/H264/Conformita` e `tests/Febe.Tests/Media/H265/Conformita`. Nel repository **solo i flussi e l'MD5 dell'uscita di riferimento**, mai le uscite decodificate, con un `LEGGIMI.md` che dice la fonte (indirizzo dell'ITU-T, data dello scaricamento, condizioni d'uso) e l'elenco (nome, profilo, MD5 del flusso e dell'uscita). +- Le immagini di riferimento dei codec, generate una sola volta con SkiaSharp prima che uscisse (permesso di Alberto), tenute come file di prova della tappa C1 in `tests/Febe.Tests/Imaging/Riferimenti`. **Lingua del codice.** Identificatori e commenti in inglese; interfaccia, documentazione e messaggi per l'utente in italiano. Il glossario dell'appendice D lega i due vocabolari. @@ -218,7 +218,7 @@ A destra un riquadro «Con queste impostazioni» traduce le scelte in conseguenz - Mosaico di tutti gli elementi in ordine di pubblicazione, raggruppati per giorno (mockup 01). Filtri per tipo, account, periodo, provenienza (scaricati o importati). Ricerca per nome dell'account e testo della didascalia. - Deve restare fluida con 200.000 elementi: caricamento a finestre, miniature generate una volta e conservate. - **«Raggruppa i post» o «Tutte le foto»** (issue #59, tappa D1 del traguardo 0.3.0; decisione di Alberto del 25 novembre 2026): un interruttore a due voci nella riga di strumenti della Libreria e della vista dei contenuti della scheda account. «Raggruppa i post», il predefinito, è il mosaico di oggi: una tessera per elemento, con il numero dei file in alto a destra. «Tutte le foto» mette una tessera per file, video compresi, nello stesso ordine (data dell'elemento, poi posizione nella serie): utile quando un post ha più foto. In quel modo la tessera di un file di una serie dice la sua posizione («2/4»), il conteggio della riga del giorno conta i file, il visualizzatore si apre su quel file e le frecce vanno di file in file. La selezione è di file: «Copia in…» e «Fotogrammi…» lavorano sui file scelti; l'elenco CSV ed «Elimina» lavorano sugli elementi a cui appartengono, e la conferma lo dice («3 file scelti appartengono a 2 post: elimino i 2 post, 9 file»). La scelta si ricorda per pagina, una per la Libreria e una per le viste degli account, nel browser di chi guarda come il tema (memoria locale del browser, letta e scritta dentro un `try`); se manca o non si legge vale «Raggruppa i post». Filtri, ricerca e caricamento a finestre funzionano uguali nei due modi, anche con 200.000 elementi e i loro file. -- **File danneggiato o incompleto** (risposta di Alberto del 25 novembre 2026). Un'immagine troncata o rovinata, scaricata o importata (§3, §8.4), si rifiuta e lo dice: tessera neutra nel mosaico e «File danneggiato o incompleto» nel visualizzatore al posto dell'immagine, con le azioni sul file (mostra nella cartella o scarica, elimina) che restano. Il file **resta in libreria** (regola 12): Febe non lo cancella, non lo sostituisce e non lo riscarica da sé. +- **File danneggiato o incompleto** (risposta di Alberto del 25 novembre 2026). Un'immagine troncata o rovinata, scaricata o importata (§3, §8.4), si rifiuta e lo dice: tessera neutra nel mosaico e «File danneggiato o incompleto» nel visualizzatore al posto dell'immagine, con le azioni sul file (mostra nella cartella o scarica, elimina) che restano. Il file **resta in libreria** (regola 12): Febe non lo cancella, non lo sostituisce e non lo riscarica da sé. Un HEIC che non si decodifica ha solo la tessera neutra, senza questa scritta (§3). - Visualizzatore (mockup 02): elemento a tutta altezza, frecce, file della serie, scheda con dati, file e provenienza. Azioni: mostra nella cartella (Windows) o scarica il file (browser), apri su Instagram, elimina dalla libreria. Con l'esportazione (§4.10, traguardo 0.3.0): «Copia in…», «Fotogramma» per i video, «È un video fermo?» a richiesta, e nel pannello File le righe delle copie esterne («Copiato in … · intero», «· fotogramma»). - Eliminare chiede conferma e, per impostazione predefinita, ricorda la scelta: l'elemento resta nel database senza file, nello stato «eliminato», così non viene riscaricato. La conferma offre anche «Eliminalo e lascia che torni». Le copie esterne di un elemento eliminato restano dove sono (§4.10). - Scheda dell'account con gli elementi divisi in Post, Storie, In evidenza, Taggati (mockup 12), con lo stesso interruttore «Raggruppa i post» / «Tutte le foto», le impostazioni e la cronologia dei controlli. @@ -407,7 +407,7 @@ User agent e valori della pagina si leggono con **una sola** `Runtime.evaluate` La copia si fa solo da una pagina del sito che non sia un percorso di accesso o di verifica delle regole di arresto (§7.6), dentro i comandi del collegamento, dopo il controllo del cookie di sessione e prima del riposo. Si fa solo dentro il permesso di guida di Alberto («Accedi a Instagram», «Usa il browser»): Febe tiene il permesso e il turno della pagina per tutta la copia, a «Ho finito» come alla chiusura della finestra e alla fine del permesso, e in Docker lasciando la pagina del browser («Quando si copia»), e se il permesso finisce comunque prima del salvataggio la copia si butta. In ogni caso la copia dura al più 10 secondi; oltre, è un errore del browser e la copia si butta. -**Quando si copia** (decisione di Alberto del 18 novembre 2026, tappa S4b di #36). In tre momenti, sempre **prima che la pagina torni al motore**: a «Ho finito»; quando Alberto chiude la finestra «Browser di Febe» su Windows (anche quando resta ridotta a icona troppo a lungo); quando il permesso di guida finisce da solo. In Docker, al posto della finestra, conta **lasciare la pagina del browser** (risposta di Alberto del 25 novembre 2026): mentre Alberto guida, passare dalla pagina «Browser» o dalla vista remota della pagina Collegamento a un'altra pagina di Febe, chiudere la scheda o la finestra del browser in cui la guarda, o perderne il collegamento. Febe lo riconosce dal server: si chiude l'ultima vista remota aperta durante il permesso (la pagina che si lascia lo dice subito; una scheda chiusa o un collegamento perso chiudono la sua connessione) e per 5 secondi non se ne apre un'altra, così ricaricare la pagina non è lasciarla. Da lì vale ciò che vale per la finestra di Windows: la copia, se la pagina è sul sito e non è di accesso o di verifica, poi il permesso finisce e la pagina torna al motore. Finché questo non è costruito, in Docker si copia solo a «Ho finito» e alla fine del permesso. Alla chiusura della finestra, lasciando la pagina in Docker e alla fine del permesso la copia ha le stesse garanzie di «Ho finito»: i comandi del collegamento, la presa del permesso di guida e il turno della pagina, che Febe rilascia solo quando la copia è salvata o buttata (la finestra tiene una presa del permesso finché la copia non è finita; la fine del permesso copia prima di rilasciarlo); il motore intanto è fermo e aspetta (regola 4: la pagina non è mai di due). Si copia solo con il cookie di sessione nel browser e solo da una pagina del sito che non sia di accesso o di verifica (né il riposo). Alla chiusura della finestra e lasciando la pagina in Docker Febe aspetta al più 30 secondi che finisca un altro comando del collegamento in corso, perché il motore non resti trattenuto; poi vale il limite di 10 secondi della copia. Un errore imprevisto (database, disco) si scrive nel registro con il solo tipo d'errore e il permesso si rilascia lo stesso. Lì non c'è un messaggio: l'esito è una riga del registro con soli conteggi e lo stato nel riquadro della pagina Collegamento. La fine del permesso non copia di nuovo se la finestra (o la pagina lasciata) ha appena copiato, e un «Ho finito» tardivo dopo una copia fatta lasciando il browser non rilegge nulla e dice che la sessione era già stata copiata. +**Quando si copia** (decisione di Alberto del 18 novembre 2026, tappa S4b di #36). In tre momenti, sempre **prima che la pagina torni al motore**: a «Ho finito»; quando Alberto chiude la finestra «Browser di Febe» su Windows (anche quando resta ridotta a icona troppo a lungo); quando il permesso di guida finisce da solo. In Docker, al posto della finestra, conta **lasciare la pagina del browser** (risposta di Alberto del 25 novembre 2026): mentre Alberto guida, passare dalla pagina «Browser» o dalla vista remota della pagina Collegamento a un'altra pagina di Febe, chiudere la scheda o la finestra del browser in cui la guarda, o perderne il collegamento. Febe lo riconosce dal server: si chiude l'ultima vista remota aperta durante il permesso (la pagina che si lascia lo dice subito; una scheda chiusa o un collegamento perso chiudono la sua connessione) e per 5 secondi non se ne apre un'altra, così ricaricare la pagina non è lasciarla. Da lì vale ciò che vale per la finestra di Windows: la copia, se la pagina è sul sito e non è di accesso o di verifica, poi il permesso finisce e la pagina torna al motore, che rimette il browser a riposo. L'interfaccia lo dice al server con `cancel` e `pageLeft` (`IConnectionService.LeavePageAsync`); su Windows, dove il browser è una finestra a parte, lasciare la pagina rilascia solo il permesso tenuto da quella pagina e la finestra resta com'è. Una vista chiusa perché il browser si è fermato non conta come pagina lasciata. Dove la sessione si copia, solo il pulsante «Annulla» restituisce il browser senza copiare. Senza la raccolta `richieste` non c'è una sessione salvata: lasciare la pagina fa solo finire il permesso, senza copia; dove Febe non ha un collegamento che copi la sessione (la modalità dimostrativa, un avvio fermato da un problema di configurazione, il browser non disponibile) lasciare la pagina vale «Annulla». Alla chiusura della finestra, lasciando la pagina in Docker e alla fine del permesso la copia ha le stesse garanzie di «Ho finito»: i comandi del collegamento, la presa del permesso di guida e il turno della pagina, che Febe rilascia solo quando la copia è salvata o buttata (la finestra tiene una presa del permesso finché la copia non è finita; la fine del permesso copia prima di rilasciarlo); il motore intanto è fermo e aspetta (regola 4: la pagina non è mai di due). Si copia solo con il cookie di sessione nel browser e solo da una pagina del sito che non sia di accesso o di verifica (né il riposo). Alla chiusura della finestra e lasciando la pagina in Docker Febe aspetta al più 30 secondi che finisca un altro comando del collegamento in corso, perché il motore non resti trattenuto (se non finisce, il permesso finisce senza copia, e il registro lo dice); poi vale il limite di 10 secondi della copia. Un errore imprevisto (database, disco) si scrive nel registro con il solo tipo d'errore e il permesso si rilascia lo stesso. Lì non c'è un messaggio: l'esito è una riga del registro con soli conteggi e lo stato nel riquadro della pagina Collegamento. La fine del permesso non copia di nuovo se la finestra (o la pagina lasciata) ha appena copiato, e un «Ho finito» tardivo dopo una copia fatta lasciando il browser non rilegge nulla e dice che la sessione era già stata copiata. **Copia incompleta** (impostazione `sessione.copia-incompleta`, tappa S4b di #36, letta a ogni copia). Una copia a cui manca qualche valore o `doc_id` che un'operazione configurata manda segue l'opzione «Copia incompleta» della pagina Collegamento: **«Sostituisci comunque»** (predefinita), perché tenere una copia più vecchia potrebbe tenere i cookie di un altro accesso; oppure **«Tieni la copia completa di prima»**, che lascia la sessione salvata com'era se quella era completa, e lo dice («Ho tenuto la copia del 17 novembre: in quella nuova mancavano …»). Una copia completa sostituisce sempre. Il messaggio di «Ho finito» conta solo i valori e i `doc_id` che un'operazione configurata manda, e dice com'è secondo ciò che è successo. Se la copia nuova ha sostituito quella di prima («Sostituisci comunque», o «Tieni la copia completa di prima» quando quella di prima era già incompleta): le richieste che li usano non partono e, alla prima, Febe si ferma come disconnessione e chiede un nuovo accesso (mai un ritorno alle pagine) finché un nuovo «Ho finito» non li trova. Se Febe ha tenuto la copia completa di prima: la sessione salvata resta quella di quella data, le richieste continuano a usarla e nulla si ferma per quei valori; la copia nuova non si tiene. Dopo «Ho finito» il permesso di guida è finito: per rifare la copia Alberto riapre il browser dalla pagina Collegamento («Usa il browser» o «Pagina iniziale») e preme di nuovo «Ho finito», ed è ciò che il messaggio di una copia rifiutata gli dice. Una copia rifiutata (pagina fuori dal sito, pagina di accesso o verifica, browser che non risponde, nessun user agent) la lascia com'era. Con il sito di prova e `--accesso-di-prova` la copia si fa anche dopo l'accesso automatico, come la farebbe Alberto. @@ -791,10 +791,10 @@ Vincoli che contano: ### 8.4 Miniature e impronte -- Miniatura di 480 pixel sul lato lungo per ogni immagine; per i video si usa la copertina che arriva dalla pagina e, per quelli importati, un fotogramma estratto con i decodificatori H.264 e H.265 di Febe (§3), altrimenti (VP9, AV1 e gli altri codec) una tessera neutra. Fino alla tappa C3 del traguardo 0.3.0 il fotogramma lo estrae ffmpeg, se presente; fra C3 e C4 un video HEVC ha la tessera neutra. +- Miniatura di 480 pixel sul lato lungo per ogni immagine; per i video si usa la copertina che arriva dalla pagina e, per quelli importati, un fotogramma estratto con i decodificatori H.264 e H.265 di Febe (§3), altrimenti (VP9, AV1 e gli altri codec, e i contenitori di cui Febe legge solo i metadati, §3) una tessera neutra. Le foto HEIC hanno miniatura e impronta dal decodificatore HEIF di Febe (§3). - SHA-256 del file per i doppioni esatti. - Impronta visiva a 64 bit per le immagini, per riconoscere la stessa foto salvata a risoluzione o compressione diversa. Le impronte stanno in memoria: il confronto di una foto con 200.000 è questione di millisecondi. -- **Immagini troncate o rovinate** (PNG, JPEG e gli altri formati di §3; risposta di Alberto del 25 novembre 2026): si rifiutano e lo si dice, «File danneggiato o incompleto». Niente miniatura (la tessera neutra) e **nessuna impronta visiva**: un file così non risulta mai doppione probabile per impronta, né dallo scaricamento né dall'importazione (§9.3). Lo SHA-256 sì, perché dice solo se due file sono identici. Il file **resta in libreria** (regola 12): Febe non lo cancella, non lo sostituisce e non lo riscarica da sé. +- **Immagini troncate o rovinate** (PNG, JPEG e gli altri formati di §3; risposta di Alberto del 25 novembre 2026): si rifiutano e lo si dice, «File danneggiato o incompleto». Niente miniatura (la tessera neutra) e **nessuna impronta visiva**: un file così non risulta mai doppione probabile per impronta, né dallo scaricamento né dall'importazione (§9.3). Lo SHA-256 sì, perché dice solo se due file sono identici. Il file **resta in libreria** (regola 12): Febe non lo cancella, non lo sostituisce e non lo riscarica da sé. Un PNG o un JPEG senza il suo marcatore di fine (`IEND`, `EOI`) è troncato anche se il resto c'è; un HEIC che non si decodifica non si dice mai danneggiato: ha la tessera neutra, nessuna impronta e nessuna scritta (§3). ### 8.5 Copie e ricostruzione @@ -819,7 +819,7 @@ Quattro passi, mostrati in alto nella pagina (mockup 09): ### 9.2 Analisi -Per ogni file: tipo dal contenuto e non solo dall'estensione; byte; SHA-256; dimensioni; impronta visiva per le immagini che si decodificano per intero (non per quelle troncate o rovinate, §8.4); data, cercata nell'ordine nel nome del file, nei metadati del file (data di scatto delle foto, data di creazione dei video), nella data di modifica; identificativo o codice Instagram, se il nome lo contiene; account probabile, dal nome della cartella; tipo probabile (storia, evidenza, taggato) dalle sottocartelle. La lettura dei metadati si scrive a mano per i pochi campi che servono: per i video con i lettori dei contenitori di Febe (§3: ISO BMFF, Matroska e, dalla tappa C5, ASF/WMV, FLV e MPEG-PS); fino alla tappa C2 del traguardo 0.3.0 si usa ancora ffprobe dove è presente, e fra C2 e C5 un file ASF, FLV o MPEG-PS ha il tipo dal contenuto ma durata, dimensioni e codec vuoti. +Per ogni file: tipo dal contenuto e non solo dall'estensione; byte; SHA-256; dimensioni; impronta visiva per le immagini che si decodificano per intero (non per quelle troncate o rovinate, §8.4); data, cercata nell'ordine nel nome del file, nei metadati del file (data di scatto delle foto, data di creazione dei video), nella data di modifica; identificativo o codice Instagram, se il nome lo contiene; account probabile, dal nome della cartella; tipo probabile (storia, evidenza, taggato) dalle sottocartelle. La lettura dei metadati si scrive a mano per i pochi campi che servono: per le foto con i decodificatori di Febe (HEIC compreso, §3), per i video con i suoi lettori dei contenitori (§3: ISO BMFF, Matroska, ASF/WMV, FLV e MPEG-PS, dove codec e dimensioni di una traccia H.264 o HEVC vengono dal suo SPS). Nessun programma esterno. ### 9.3 Confronto con la libreria @@ -830,7 +830,7 @@ Per ogni file: tipo dal contenuto e non solo dall'estensione; byte; SHA-256; dim | **Nuovo** | Nessuna corrispondenza | Verrà copiato | | **Non riconosciuto** | Né foto né video | Ignorato ed elencato | -I doppioni si cercano anche dentro la sorgente stessa. Un'immagine troncata o rovinata (§8.4) ha il tipo dal contenuto e lo SHA-256, ma nessuna impronta: può essere «Già in libreria» o «Nuovo», mai «Doppione probabile» per impronta; si importa come le altre e revisione e resoconto la segnano «File danneggiato o incompleto». Le soglie dell'impronta si tarano con le prove di §14.1 su varianti costruite apposta: ridimensionata e ricompressa deve risultare doppione, ritagliata no. Per i video vale solo lo SHA-256. «Tenere il più grande», quando il più grande è quello importato, sostituisce un file della libreria: è una scelta esplicita di Alberto, come chiede la regola 12. +I doppioni si cercano anche dentro la sorgente stessa. Un'immagine troncata o rovinata (§8.4) ha il tipo dal contenuto e lo SHA-256, ma nessuna impronta: può essere «Già in libreria» o «Nuovo», mai «Doppione probabile» per impronta; si importa come le altre e la revisione (un avviso), il resoconto (sotto «File danneggiato o incompleto») e l'elenco CSV (colonna «Nota») la segnano «File danneggiato o incompleto». Le soglie dell'impronta si tarano con le prove di §14.1 su varianti costruite apposta: ridimensionata e ricompressa deve risultare doppione, ritagliata no. Per i video vale solo lo SHA-256. «Tenere il più grande», quando il più grande è quello importato, sostituisce un file della libreria: è una scelta esplicita di Alberto, come chiede la regola 12. ### 9.4 Associazione e copia @@ -863,7 +863,7 @@ Semplice e moderna, con una ragione dietro ogni scelta: - **Le foto portano il colore, l'interfaccia resta in grigio neutro.** Come nei programmi di fotoritocco, i grigi non hanno dominante, così i colori delle immagini non vengono falsati. Niente sfumature decorative, niente richiami alla grafica di Instagram. - **Un solo accento**, un blu cianotipo, per l'azione principale, la selezione e le sessioni del motore. Verde, ambra e rosso servono solo a dire uno stato, sempre accompagnati da testo o numero. -- **Un solo carattere**, quello di sistema (`system-ui`, regola 13: dalla tappa C6 della 0.3.0; fino ad allora Archivo), con cifre tabellari per i dati (date, numeri, nomi di file). La larghezza più stretta dei dati c'era con Archivo; con i caratteri di sistema si ottiene solo dove il carattere la offre, e i mockup si confrontano tenendone conto (§10.7). +- **Un solo carattere**, quello di sistema (`system-ui`, regola 13: dalla tappa C6 della 0.3.0, che ha tolto Archivo), con cifre tabellari per i dati (date, numeri, nomi di file). La larghezza più stretta dei dati c'era con Archivo; con i caratteri di sistema si ottiene solo dove il carattere la offre, e i mockup si confrontano tenendone conto (§10.7). - **Raggi che crescono con l'importanza**: 3 per le tessere, 7 per i controlli, 10 per i pannelli, 14 per le finestre di dialogo. Ombre solo su menu e dialoghi; il resto si separa con linee sottili. - **Elenchi e tabelle, non mosaici di riquadri uguali.** Un pannello si usa quando raggruppa davvero qualcosa. - **La striscia della giornata** è l'elemento che distingue Febe: una barra di 24 ore con le sessioni come tratti irregolari. Il resto le sta intorno in silenzio. @@ -964,8 +964,8 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I ## 11. Docker e Unraid -- **Immagine.** Base Debian stabile in versione ridotta. Su Ubuntu il pacchetto Chromium è uno snap e nei contenitori non funziona. Febe si pubblica autosufficiente per `linux-x64`, quindi nell'immagine non serve il runtime .NET. Pacchetti (regola 13: solo Chromium, ciò che gli serve e Xvfb, più ciò che la piattaforma .NET chiede al sistema): `chromium`, `chromium-l10n` (le lingue del browser sono a parte), `xvfb`, i caratteri per il browser, cioè `fonts-noto-color-emoji`, che **resta** perché a Chromium serve per mostrare le pagine, e `fonts-dejavu-core` come carattere di base (`fonts-liberation` **esce**: risposta di Alberto del 25 novembre 2026), `tzdata` e `locales` con la lingua italiana generata (fuso e lingua veri del browser, §6.1), la libreria ICU e i certificati (per .NET); `ffmpeg` solo fino alla tappa C3 del traguardo 0.3.0, poi esce dall'immagine. Nient'altro. -- **Processi.** `Febe.Server` è il processo principale: avvia Xvfb, poi Chromium, e li riavvia se cadono. Niente script di shell che facciano da supervisore. +- **Immagine.** Base Debian stabile in versione ridotta. Su Ubuntu il pacchetto Chromium è uno snap e nei contenitori non funziona. Febe si pubblica autosufficiente per `linux-x64`, quindi nell'immagine non serve il runtime .NET. Pacchetti (regola 13: solo Chromium, ciò che gli serve e Xvfb, più ciò che la piattaforma .NET chiede al sistema): `chromium`, `chromium-l10n` (le lingue del browser sono a parte), `xvfb`, i caratteri per il browser, cioè `fonts-noto-color-emoji`, che **resta** perché a Chromium serve per mostrare le pagine, e `fonts-dejavu-core` come carattere di base, quello che fontconfig chiede per primo (`fonts-liberation` **è uscito**: risposta di Alberto del 25 novembre 2026), `tzdata` e `locales` con la lingua italiana generata (fuso e lingua veri del browser, §6.1), e per il runtime .NET autosufficiente la libreria ICU (`libicu76`), OpenSSL (`libssl3t64`), `libstdc++6`, `libgcc-s1` e i certificati (`ca-certificates`); `zlib1g` per Chromium. Ogni pacchetto ha il suo motivo accanto, nel `Dockerfile` e in `docs/docker.md`. ffmpeg è uscito con la tappa C3, e con lui ogni programma per i video. Nient'altro: `setpriv`, `groupadd`, `useradd` e `getent`, che servono all'avvio, sono già nell'immagine di base (`util-linux` è essenziale in Debian, `passwd` e `libc-bin` sono fra i pacchetti richiesti) e non si installano a parte. +- **Processi.** `Febe.Server` è il processo principale e, in Docker, il **processo 1** (niente `tini` né altri programmi di avvio): l'avvio fa `exec` di `setpriv`, che fa `exec` di Febe, che riceve `SIGTERM` da `docker stop` e, con il runtime .NET da processo 1, raccoglie anche i processi rimasti orfani. Avvia Xvfb, poi Chromium, e li riavvia se cadono. Niente script di shell che facciano da supervisore. - **Utente.** Non root, con `PUID` e `PGID` configurabili (su Unraid 99 e 100). - **Avvio di Chromium.** Come un browser normale, con finestra, sul display virtuale, con: porta di debug fissa su `127.0.0.1` (§6.1), cartella del profilo, nessuna procedura di primo avvio, dimensione della finestra, archivio delle password di base, uso di `/tmp` al posto della memoria condivisa. La lingua viene da `LANG`. Mai `--headless`, `--enable-automation`, opzioni che cambiano lo user agent o che intervengono su ciò che il browser dichiara. - **Password del browser.** Un file di criteri nell'immagine disattiva il salvataggio delle password e la compilazione automatica di Chromium: con l'archivio di base finirebbero in chiaro nel profilo. @@ -1002,11 +1002,11 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I - La finestra principale è un WebView2 che mostra l'interfaccia servita in locale su `127.0.0.1`, porta scelta all'avvio, e si apre sulla Dashboard (§7.9, dalla tappa D1). - Il browser di Instagram è un secondo WebView2, con una sua cartella dati, in una finestra separata «Browser di Febe». Alberto la apre da Collegamento e dalla Dashboard; quando non serve resta fuori vista ma attiva (S2). Salvataggio delle password e compilazione automatica sono disattivati nelle impostazioni del controllo. - Funzioni native offerte all'interfaccia: scelta di una cartella (anche per le destinazioni di esportazione di §4.10, con percorsi di rete e UNC), «Mostra nella cartella», apertura di un indirizzo nel browser predefinito, notifiche di Windows, avvio con il sistema. -- **Niente ffmpeg** (regola 13): fotogrammi, conversioni, miniature dei video importati e video fermi li fa il codice di Febe (§3), e non c'è nulla da installare a parte né un «Percorso di ffmpeg» da impostare. Fino alla tappa C3 del traguardo 0.3.0 un ffmpeg nel PATH serve ancora alle miniature dei video importati; senza, una tessera neutra. +- **Niente ffmpeg** (regola 13): fotogrammi, conversioni, miniature dei video importati e video fermi li fa il codice di Febe (§3), e non c'è nulla da installare a parte né un «Percorso di ffmpeg» da impostare. Un ffmpeg nel PATH non si usa: è uscito con la tappa C3 del traguardo 0.3.0. - Chiudendo la finestra Febe resta nell'area di notifica e continua a lavorare; dal menu dell'icona: apri, metti in pausa, esci. - Cartelle predefinite: dati in `%LOCALAPPDATA%\Febe`, libreria in `Immagini\Febe`. - **Verificato**: il runtime WebView2 è già presente in Windows 11 e in quasi tutti i Windows 10. Se manca, Febe lo dice con il collegamento per installarlo. -- Pubblicazione autosufficiente in un unico eseguibile; programma di installazione (domanda 6 di §16) scritto in casa dalla tappa C6 della 0.3.0 (§3, regola 13); fino ad allora lo costruisce NSIS nella sola CI. +- Pubblicazione autosufficiente in un unico eseguibile; programma di installazione (domanda 6 di §16) scritto in casa dalla tappa C6 della 0.3.0 (`src/Febe.Installer`, §3, regola 13), costruito con il solo .NET SDK, al posto di NSIS. --- @@ -1026,7 +1026,7 @@ Il divieto di modalità headless della regola 2 riguarda il browser che visita I Su Unix la cartella `Dati/sessione` è 0700 e i suoi file 0600 dalla creazione (`File.SetUnixFileMode`); un `chiave.bin` più aperto si restringe e il registro lo dice. Si scrive in modo atomico: un file `.part` nella stessa cartella, scritto fino al disco, poi rinominato sul vecchio. Sostituire, aggiornare e cancellare passano da un solo semaforo; un aggiornamento ricontrolla sessione e copia dopo averlo preso, così una risposta tardiva non riporta in vita una sessione cancellata né tocca quella di un accesso nuovo. Una scrittura che il disco rifiuta tiene i valori nuovi in memoria (il sito ha già cambiato i cookie), scrive nel registro una riga con il solo tipo d'errore e si riprova alla scrittura dopo. Un file che non si legge (altra chiave o altro utente, rovinato, altro formato) è nessuna sessione, detto nel registro e lasciato com'è finché una copia nuova non lo sostituisce: mai un arresto del programma. Non va nel database, nelle copie giornaliere, nel rapporto di diagnostica né nell'interfaccia, dove la pagina Collegamento ne mostra solo data della copia, conteggi e nomi mancanti; Febe non lo esporta e non accetta sessioni incollate da fuori. **«Scollega»** cancella la sessione salvata prima del profilo del browser: prima in memoria, poi il file (e i `.part` rimasti), senza annullamento; con `pagine` cancella comunque un `sessione.json` lasciato da un avvio con `richieste`. `chiave.bin` resta. Un file che non si cancella è un fallimento parziale detto ad Alberto: Febe non lo usa più finché resta acceso, ma al prossimo avvio con `richieste` lo rileggerebbe, quindi il messaggio chiede di riprovare «Scollega» o di cancellare a mano la cartella `sessione` prima di riavviare. Chi ha accesso alla cartella dei dati e alla chiave (in Docker), o all'utente di Windows, ha accesso alla sessione. -- `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` si tolgono dall'ambiente di ogni processo che Febe avvia (Chromium o Edge, Xvfb e, finché ci sono, ffmpeg e ffprobe): un figlio eredita l'ambiente del padre, e Chromium esegue il codice del sito. La password e la chiave non si passano mai sulla riga di comando e non compaiono in nessun testo di Febe (registri, problemi, descrizione delle opzioni: solo «impostata», «assente» o «non valida»). +- `FEBE_PASSWORD` e `FEBE_CHIAVE_SESSIONE` si tolgono dall'ambiente di ogni processo che Febe avvia (Chromium o Edge e Xvfb, gli unici dopo l'uscita di ffmpeg e ffprobe con la 0.3.0): un figlio eredita l'ambiente del padre, e Chromium esegue il codice del sito. La password e la chiave non si passano mai sulla riga di comando e non compaiono in nessun testo di Febe (registri, problemi, descrizione delle opzioni: solo «impostata», «assente» o «non valida»). - Password e codici non entrano mai nei registri. Nella vista remota i tasti vanno al browser e non si conservano. - I registri contengono azioni ed esiti, non contenuti: nomi utente sì, didascalie e corpi delle risposte no. Il client CDP registra solo nomi di comandi (§6.1); il client del sito solo operazione o forma del percorso e stato (§6.0). Il rapporto di diagnostica (§7.9) è più severo dei registri: nemmeno i nomi utente, né indirizzi interi, solo forme, conteggi e codici di elenchi chiusi, perché è fatto per uscire dalla macchina di Alberto. Per le richieste verso Telegram e verso il CDN non si registrano gli indirizzi: contengono il gettone del bot e le firme dei file. - I campioni grezzi della sonda stanno fuori dal repository e si cancellano a fine M0 (§14.5). @@ -1048,11 +1048,11 @@ Eventi che meritano un avviso: verifica richiesta, disconnessione, fermo per ral - **Libreria**: nomi ripuliti, percorsi lunghi, scrittura con nome temporaneo, eliminazione che non torna, ricostruzione del database dai file. - **Doppioni**: immagini di prova generate e le loro varianti ridimensionate, ricompresse e ritagliate. - **Importazione**: interruzione e ripresa; «Sposta» non elimina mai un originale non verificato. -- **Codec e video** (traguardo 0.3.0, §3): decodificatori e codificatori sulle immagini di riferimento generate una volta con SkiaSharp (permesso di Alberto, §16 domanda 16), andata e ritorno senza perdita per PNG e WEBP senza perdita, metadati conservati. Pixel uguali esattamente per PNG, WEBP senza perdita, GIF e BMP; per JPEG e WEBP con perdita una tolleranza, perché la IDCT (ITU-T T.81 e T.83 ne fissano solo la precisione) e il ricampionamento della crominanza non danno gli stessi pixel in due decodificatori: proposta, PSNR di almeno 40 dB su ogni canale e al più lo 0,1 % dei pixel con un canale più lontano di 16 dal riferimento, da scrivere in `docs/decisioni.md` con C1. Decodificatore H.264 su tutti i flussi di conformità ITU-T H.264.1 di §3, di ogni profilo (interlacciati, Extended, High 10, 4:2:2, 4:4:4, monocromatici, SVC e MVC compresi), e decodificatore H.265 sui flussi di ITU-T H.265.1 dei profili di §3: uscita uguale bit per bit all'MD5 dell'uscita di riferimento, nessun flusso saltato. Lettori ISO BMFF, Matroska, ASF, FLV e MPEG-PS su file costruiti dalle prove stesse (durata, dimensioni, codec, data, file troncati e rovinati che non fanno cadere nulla); mai campioni veri. +- **Codec e video** (traguardo 0.3.0, §3): decodificatori e codificatori sulle immagini di riferimento generate una volta con SkiaSharp (permesso di Alberto, §16 domanda 16), andata e ritorno senza perdita per PNG e WEBP senza perdita, metadati conservati. Pixel uguali esattamente per PNG, WEBP senza perdita, GIF e BMP; per JPEG e WEBP con perdita una tolleranza, perché la IDCT (ITU-T T.81 e T.83 ne fissano solo la precisione) e il ricampionamento della crominanza non danno gli stessi pixel in due decodificatori: PSNR di almeno 40 dB su ogni canale e al più lo 0,1 % dei pixel con un canale più lontano di 16 dal riferimento, scritta in `docs/decisioni.md` con C1. HEIC su file HEIF costruiti dalle prove con le immagini dei flussi di ITU-T H.265.1 (singole, a griglia, con trasparenza, ruotate), uguali all'immagine decodificata dal flusso. Decodificatore H.264 su tutti i flussi di conformità ITU-T H.264.1 di §3, di ogni profilo (interlacciati, Extended, High 10, 4:2:2, 4:4:4, monocromatici, SVC e MVC compresi), e decodificatore H.265 sui flussi di ITU-T H.265.1 dei profili di §3: uscita uguale bit per bit all'MD5 dell'uscita di riferimento, nessun flusso saltato. Lettori ISO BMFF, Matroska, ASF, FLV e MPEG-PS su file costruiti dalle prove stesse (durata, dimensioni, codec, data, file troncati e rovinati che non fanno cadere nulla); mai campioni veri. - **Installatore e CI** (tappa C6, §3): l'installatore scritto in casa installa, aggiorna e disinstalla in una cartella di prova senza toccare i dati; l'interfaccia non carica file di caratteri né icone di terzi (nessun `@font-face`, nessun file di Archivo o Lucide in `wwwroot`). - **Esportazione** (§4.10): nessuna sovrascrittura né cancellazione, radice della destinazione mai creata, stati «Tolto» e «Superato» mai ricopiati da soli, filtro «Copie» nei tempi della prova di scala. - **Cosa scaricare prima** (tappa D1, §7.2): con orologio virtuale e seme fisso, il giro resta primo, l'ordine pesa senza diventare fisso, un tipo senza lavoro dovuto non si visita, tetti, pause, frequenze e composizione delle sessioni non cambiano; la coda dei file segue l'ordine dell'account. -- **Immagini danneggiate** (§8.4): PNG e JPEG troncati costruiti dalle prove danno «File danneggiato o incompleto», nessuna impronta, nessun doppione probabile, e il file resta. +- **Immagini danneggiate** (§8.4): PNG e JPEG troncati costruiti dalle prove, anche solo senza `IEND` o `EOI`, danno «File danneggiato o incompleto», nessuna impronta, nessun doppione probabile, e il file resta; le loro dimensioni si leggono lo stesso; un HEIC che non si decodifica non è mai detto danneggiato; nell'importazione revisione, resoconto e CSV li segnano (§9.3). - **Ripulitura dei campioni**: nessun valore dei campioni grezzi sopravvive in quelli ripuliti (§14.5). ### 14.2 Sito di prova @@ -1160,7 +1160,7 @@ Falle quando arrivi al punto indicato, una per volta, proponendo la risposta del | 15 | **Risposte di Alberto del 18 novembre 2026: sì** (§3, §14.1). Domanda di allora: si scarica il sottoinsieme delle serie di conformità ITU-T H.264.1 dei profili di §3, e dove stanno i flussi se superano 50 MB? | C3, prima di cominciare | Risposte: scaricamento permesso, fatto (12 flussi nel repository sul ramo `funzione/decoder-h264`); poi sì anche agli altri flussi di conformità ITU-T, i profili di H.264.1 che mancano e H.265.1: nel repository solo i flussi e l'MD5 dell'uscita di riferimento, con un `LEGGIMI.md` che dice la fonte | | 16 | **Risposta di Alberto del 18 novembre 2026: sì** (§3, §14.1). Domanda di allora: le immagini di riferimento dei codec si generano una sola volta con SkiaSharp prima che esca? | C1, prima di cominciare | Risposta: SkiaSharp permesso un'ultima volta per generarle, fatto; per JPEG e WEBP con perdita le tolleranze di §14.1 | | 17 | **Risposta di Alberto del 18 novembre 2026: si tolgono** (regola 13, §3, §15 tappa C6). Domanda di allora: componenti in uso oltre a quelli ammessi dalla regola 13 (Xvfb e gli altri pacchetti Debian di §11, il carattere Archivo e le icone Lucide come file, NSIS e Node nella CI): restano come eccezioni per nome o si tolgono? | E0 | Risposta: escono anche questi; installatore senza NSIS (scritto in casa), CI senza Node (passi di shell con git e curl verso l'API di Gitea), caratteri di sistema (`system-ui`) al posto di Archivo, icone SVG disegnate in casa al posto di Lucide. Restano solo Xvfb e i pacchetti Debian che servono a Chromium, e gitleaks e Trivy nella sola CI. Inoltre: lo stesso post in due account si copia con «Una copia per account» come predefinito (§4.10) | -| 18 | **Risposta di Alberto del 25 novembre 2026: le estensioni di formato (RExt) restano** (§3, §15 tappa C4). Domanda di allora: decodificatore H.265, oltre a Main, Main 10 e Main Still Picture, quali profili? Estensioni di formato (4:2:2, 4:4:4, 12 e 16 bit, senza perdita), scalabile (SHVC), multivista (MV-HEVC), 3D, contenuti dello schermo (SCC) | C4, prima di cominciare | Risposta: tutti i profili della serie di ITU-T H.265.1 scelta per Febe (cartelle `HEVC_v1` e `RExt`): Main, Main 10, Main Still Picture e RExt fino a 12 bit. Ciò che non ha flussi in quella serie (precisione estesa a 16 bit, SHVC, MV-HEVC, 3D, SCC) dice «Fotogramma non disponibile per questo video». Inoltre, lo stesso giorno: in Docker lasciare la pagina del browser copia la sessione (§6.0); nell'immagine Docker `fonts-noto-color-emoji` resta e `fonts-liberation` esce (§11); le immagini troncate si rifiutano con «File danneggiato o incompleto», senza impronta, e restano in libreria (§8.4) | +| 18 | **Risposta di Alberto del 25 novembre 2026: le estensioni di formato (RExt) restano** (§3, §15 tappa C4). Domanda di allora: decodificatore H.265, oltre a Main, Main 10 e Main Still Picture, quali profili? Estensioni di formato (4:2:2, 4:4:4, 12 e 16 bit, senza perdita), scalabile (SHVC), multivista (MV-HEVC), 3D, contenuti dello schermo (SCC) | C4, prima di cominciare | Risposta: tutti i profili della serie di ITU-T H.265.1 scelta per Febe (cartelle `HEVC_v1` e `RExt`): Main, Main 10, Main Still Picture e RExt fino a 12 bit. Ciò che non ha flussi in quella serie (precisione estesa a 16 bit, SHVC, MV-HEVC, 3D, SCC) dice «Fotogramma non disponibile per questo video». Inoltre, lo stesso giorno: in Docker lasciare la pagina del browser copia la sessione (§6.0); nell'immagine Docker `fonts-noto-color-emoji` resta e `fonts-liberation` è uscito (§11); le immagini troncate si rifiutano con «File danneggiato o incompleto», senza impronta, e restano in libreria (§8.4) | | 19 | «Cosa scaricare prima»: le raccolte in evidenza vanno subito dopo le storie? Alberto ha detto storie, post, reel, taggati, senza nominarle | D1, prima di cominciare | Sì: storie, evidenza, post, reel, taggati, perché sono storie anche loro; si possono comunque spostare trascinandole | --- @@ -1195,7 +1195,7 @@ All'inizio di ogni sessione leggi docs/stato.md. 9. I lettori si scrivono solo su campioni reali ripuliti. Il formato delle risposte non si inventa. 10. Mai password, cookie, gettoni, tasti, variabili o corpi di richieste e risposte nei log. Il client CDP registra solo nomi di comandi; il client del sito solo operazione o forma del percorso e stato. 11. La libreria non cancella e non sostituisce file da sola. -12. Niente componenti esterni: niente ffmpeg, programmi, librerie o file di dati di terzi (caratteri, icone); tutto il codice in casa, i formati dalle loro specifiche pubbliche. Ammessi solo .NET/BCL con ASP.NET Core, Microsoft.Data.Sqlite, il browser (Chromium o WebView2 con Microsoft.Web.WebView2, regola 4) e MSTest; nella sola CI gitleaks e Trivy (docs/processo.md); nell'immagine Docker solo Chromium, i pacchetti Debian che gli servono e Xvfb (mai headless). Escono con la loro tappa della 0.3.0 (specifica §2 regola 13, §15): SkiaSharp con C1, ffmpeg con C3; NSIS, Node, il carattere Archivo e le icone Lucide con C6. Prima di aggiungere qualunque cosa, chiedi. +12. Niente componenti esterni: niente ffmpeg, programmi, librerie o file di dati di terzi (caratteri, icone); tutto il codice in casa, i formati dalle loro specifiche pubbliche. Ammessi solo .NET/BCL con ASP.NET Core, Microsoft.Data.Sqlite, il browser (Chromium o WebView2 con Microsoft.Web.WebView2, regola 4) e MSTest; nella sola CI gitleaks e Trivy (docs/processo.md); nell'immagine Docker solo Chromium, i pacchetti Debian che gli servono e Xvfb (mai headless). Sono già usciti con la loro tappa della 0.3.0 (specifica §2 regola 13, §15): SkiaSharp con C1, ffmpeg con C3; NSIS, Node, il carattere Archivo e le icone Lucide con C6. Prima di aggiungere qualunque cosa, chiedi. ## Convenzioni - Codice e commenti in inglese; interfaccia, documenti e messaggi in italiano (glossario: appendice D). @@ -1215,21 +1215,11 @@ Conserva: tappa in corso, file modificati, controlli ancora da eseguire, domande È il foglio che ha generato i mockup, con una sola differenza: qui il contenuto della pagina scorre (`.corpo` ha `overflow:auto`), mentre nelle immagini è tagliato al bordo. Usalo come base di `src/Febe.Web/wwwroot/css/febe.css` e completalo; i nomi delle classi puoi tenerli. Il tema scuro si attiva con `data-tema="scuro"` sull'elemento radice. -Il carattere Archivo variabile (licenza OFL) si prende dal pacchetto npm `@fontsource-variable/archivo`, cartella `files`: servono `archivo-latin-standard-normal.woff2` e `archivo-latin-ext-standard-normal.woff2`. Copiali in `wwwroot/caratteri/` con il file della licenza: il pacchetto non diventa una dipendenza. **Con la tappa C6 della 0.3.0 Archivo esce** (regola 13, decisione di Alberto del 18 novembre 2026): le due regole `@font-face` e i file in `wwwroot/caratteri/` si tolgono, e `font-family` di `body` diventa la pila dei caratteri di sistema `system-ui,-apple-system,"Segoe UI",Roboto,sans-serif`. +I mockup sono stati disegnati con il carattere Archivo (licenza OFL), copiato nel programma fino alla tappa C6 della 0.3.0. **Con C6 Archivo è uscito** (regola 13, decisione di Alberto del 18 novembre 2026): niente regole `@font-face`, niente file di caratteri in `wwwroot`, e `font-family` di `body` è il token `--carattere`, la pila dei caratteri di sistema `system-ui,-apple-system,"Segoe UI",Roboto,sans-serif`. Il foglio qui sotto è già quello di dopo C6. ```css /* Febe — token e componenti di base */ -@font-face{ - font-family:"Archivo"; - src:url(../caratteri/archivo-latin-standard-normal.woff2) format("woff2"); - font-weight:100 900; font-stretch:62% 125%; font-display:block; -} -@font-face{ - font-family:"Archivo"; - src:url(../caratteri/archivo-latin-ext-standard-normal.woff2) format("woff2"); - font-weight:100 900; font-stretch:62% 125%; font-display:block; - unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF; -} +/* The system's own font (--carattere): no font file ships with Febe (decision of 18 November 2026). */ :root{ --fondo:#F4F4F4; @@ -1261,6 +1251,7 @@ Il carattere Archivo variabile (licenza OFL) si prende dal pacchetto npm `@fonts --r-pannello:10px; --r-dialogo:14px; --tratteggio:rgba(0,0,0,.075); + --carattere:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif; } [data-tema="scuro"]{ --fondo:#1B1B1B; @@ -1293,7 +1284,7 @@ Il carattere Archivo variabile (licenza OFL) si prende dal pacchetto npm `@fonts *{box-sizing:border-box} html,body{margin:0;height:100%} body{ - font-family:"Archivo",system-ui,sans-serif; font-stretch:100%; + font-family:var(--carattere); font-stretch:100%; font-size:14px; line-height:1.45; color:var(--testo); background:var(--fondo); -webkit-font-smoothing:antialiased; text-rendering:optimizeLegibility; } @@ -1504,7 +1495,7 @@ Marchio: quadrato arrotondato nel colore d'accento con un anello e un punto, cio ``` -Icone: fino alla tappa C6 della 0.3.0 Lucide (licenza ISC), dal pacchetto npm `lucide-static`, cartella `icons`, solo quelle usate, come SVG in linea con tratto 1,75. **Con C6 Lucide esce** (regola 13, decisione di Alberto del 18 novembre 2026): ogni icona si ridisegna in casa, SVG in linea su una griglia di 24, tratto 1,75, con lo stesso nome d'uso, così l'interfaccia non cambia i suoi riferimenti. Elenco di partenza: +Icone: fino alla tappa C6 della 0.3.0 erano quelle di Lucide (licenza ISC), con cui sono disegnati i mockup. **Con C6 Lucide è uscito** (regola 13, decisione di Alberto del 18 novembre 2026): ogni icona è ridisegnata in casa (`src/Febe.Web/wwwroot/icone`), SVG in linea su una griglia di 24, tratto 1,75, con lo stesso nome d'uso, così l'interfaccia non ha cambiato i suoi riferimenti. Elenco di partenza: | Uso | Icone | |---|---| diff --git a/docs/decisioni.md b/docs/decisioni.md index 99b9c8d..7fc84b1 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -512,4 +512,35 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 2026-11-18 | Restano componenti esterni che la regola del 18 novembre non ammette e che questo ramo non toglie: NSIS per l'installatore (`ambiente-prove.sh`, `makensis`), Node nella CI (lavoro su `node:24-trixie`, `node --check` in `controlli.sh`), tini come processo 1 dell'immagine Docker (con `passwd` e `util-linux`). Alberto ha già detto: installatore senza NSIS, CI senza Node (passi in shell con git e curl). Piano, in una tappa sua: un costruttore dell'installatore scritto in casa; i passi della CI in shell e un controllo della sintassi dei file JavaScript scritto in casa; per il processo 1, Febe che raccoglie da sé i processi figli (Chromium, Xvfb) e inoltra i segnali, da decidere con Alberto perché `docker run --init` userebbe di nuovo tini | Revisione del ramo: le regole di oggi valgono anche per ciò che c'era prima, ma sostituire installatore, CI e processo 1 non è lavoro del decodificatore HEVC e va provato a parte (installatore su Windows, immagine nella CI) | | 2026-11-25 | Unione della catena della 0.3.0 nel ramo HEVC: le foto HEIC passano dalla facciata dei codec di casa (`ImageDecoder`, `HeifImageDecoder`): l'`HeifImage` diventa un `RgbaImage` senza copia e `irot`/`imir` l'orientamento dei metadati, così `ImageDecoding`, miniature e impronte le trattano come JPEG e PNG; la misura di un HEIC più grande dei primi 256 KB si legge dai soli box (`HeifDecoder.ReadInfo`). Un HEIC senza immagine non si dice «File danneggiato o incompleto»: il decodificatore HEIF non distingue un file rovinato da un HEIF che non gestisce (AV1, JPEG, una proprietà essenziale sconosciuta). I fotogrammi H.264 sopra gli 8 bit passano dal convertitore comune `YuvToRgb` come quelli HEVC, copiati una volta in valori a 16 bit; dell'MVC solo la vista di base | Una sola immagine RGBA per tutti i codec, come voleva il ramo HEVC; dire danneggiato un HEIC di un tipo non gestito sarebbe falso, e i fotogrammi decodificati per una miniatura sono pochi | | 2026-11-25 | Flusso di programma MPEG con HEVC: con il tipo 0x24 nella mappa del flusso, codec e dimensioni (dopo la finestra di conformità) vengono dall'SPS dell'HEVC (`H265StreamInfo`), come per l'H.264. Senza mappa un HEVC non si riconosce (niente dimensioni). Come per l'H.264, i campioni non si elencano e non c'è miniatura | Il lettore MPEG del ramo H.264 lo rendeva facile; distinguere un HEVC senza mappa dall'H.264 o da altro video vorrebbe un'euristica sui byte che nessun campione chiede | +| 2026-11-18 | Il carattere è quello del sistema (token `--carattere`: `system-ui`, "Segoe UI", Roboto, Cantarell, "Noto Sans", "Liberation Sans", `sans-serif`); tolti i file di Archivo, la sua licenza e il precaricamento; `font-src 'none'` nella CSP e `/caratteri/` non è più fra i percorsi pubblici | Decisione di Alberto del 18 novembre 2026: niente componenti esterni, nemmeno caratteri o icone di terzi. Le larghezze di `font-stretch` restano: valgono dove il sistema ha una variante più stretta o più larga, altrimenti non cambiano nulla | +| 2026-11-18 | Le 70 icone sono disegnate per Febe: un SVG per icona in `wwwroot/icone`, griglia di 24, solo tratti (linee, cerchi, rettangoli, poligoni, archi semplici), spessore 1,75 dal foglio di stile; stessi nomi e stesso significato di prima, così `icon('nome')` non cambia; tolte le icone Lucide e la loro licenza | Stessa decisione; i nomi restano identificativi interni. Una prova fallisce se nei file del programma ricompare un riferimento al carattere o alle icone di prima | +| 2026-11-18 | Il programma di installazione per Windows è nostro: `src/Febe.Installer`, un programma .NET pubblicato per win-x64 autosufficiente, in un file solo, ridotto con il trimming e compresso, a cui lo stesso progetto (compilato per il sistema che costruisce: `--impacchetta`, `--verifica`, `--zip`) appende `Febe.exe` compresso con Brotli (qualità 5, finestra di 16 MB), la versione e un piè di pagina di 80 byte con lunghezze e SHA-256. Fa ciò che faceva lo script di prima: per utente in `%LOCALAPPDATA%\Programs\Febe`, collegamenti con l'oggetto ShellLink di Windows (interop COM generata da .NET), voce in App installate sotto HKCU, controllo di WebView2, rifiuto con Febe aperto, disinstallazione che non tocca dati né libreria; pagine con la finestra di dialogo delle attività di Windows (TaskDialog); `/S`, `/D=` e, per le prove, `/PROVA=`. Tolti `installer/febe.nsi`, NSIS e `zip` dalla CI e dai documenti; lo zip portabile lo scrive `ZipArchive` | Decisione di Alberto del 18 novembre 2026: niente componenti esterni. Il trimming e il pacchetto del runtime vengono dallo SDK di .NET (come i runtime per win-x64 che `Febe.exe` già usa), non sono codice di terzi; senza trimming il programma con il suo runtime supererebbe con `Febe.exe` i 100 MB degli allegati di Gitea (oggi 91,4 MB in tutto). Brotli 5 invece di 11: 80,8 MB invece di 79,7, in 3 secondi invece di 6 minuti | +| 2026-11-18 | La disinstallazione si copia in `%TEMP%` (`Febe-disinstalla-.exe`), avvia la copia con la cartella del programma e il proprio numero di processo e finisce; la copia aspetta che finisca, fa il lavoro e resta in `%TEMP%` finché un avvio successivo dell'installazione o della disinstallazione non la toglie | Un eseguibile in esecuzione non può cancellare il proprio file; senza permessi di amministratore Windows non cancella un file al riavvio. `/S` della disinstallazione esce quindi subito con 0 | +| 2026-11-18 | I flussi della CI sono fatti solo di comandi: nessun `uses:` (né `actions/checkout`, `setup-dotnet`, `upload-artifact`, `download-artifact`, né `docker/setup-buildx-action`) e nessun Node, né nei lavori né negli script; `controlli.sh` rifiuta un flusso con `uses:` e `PipelineTests` un comando `node`, `npm` o `npx` | Decisione di Alberto del 18 novembre 2026: niente componenti esterni. Le azioni sono programmi JavaScript di terzi che vogliono Node. Restano gli unici strumenti esterni approvati, gitleaks e Trivy, scaricati e verificati da `strumento.sh` come prima | +| 2026-11-18 | Sorgenti: in ogni lavoro lo stesso passo «Sorgenti», `git init`, `git fetch` del commit (`GITHUB_SHA`; se Gitea non lo dà per identificativo, il riferimento `GITHUB_REF` con tutta la storia) e `checkout --detach`, con il gettone del lavoro (`gitea.token`) in un'intestazione `Authorization: basic` passata a git solo con `GIT_CONFIG_COUNT`/`KEY_0`/`VALUE_0` nell'ambiente del passo; tutta la storia in `controlli`, profondità 1 altrove. Allo stesso modo `git ls-remote` della cima di `main` prima di pubblicare `:main` | Il gettone non finisce in `.git/config` né nel registro del lavoro (`PipelineTests` controlla che non vada in `echo`/`printf`); gitleaks ha bisogno di tutta la storia, come con `fetch-depth: 0` | +| 2026-11-18 | SDK .NET: `.gitea/scripts/dotnet.sh ` prende da `builds.dotnet.microsoft.com/dotnet/release-metadata//releases.json` l'ultimo SDK (`latest-sdk`), ne scarica l'archivio per `linux-x64` o `linux-arm64` solo dagli host di Microsoft e lo installa solo se l'SHA-512 coincide con quello dei metadati; lo tiene in `RUNNER_TOOL_CACHE/febe-dotnet/` (il volume `act-toolcache`) e toglie le versioni precedenti | Lo stesso di `setup-dotnet` con `10.0.x`, ma verificato; mai uno script di installazione scaricato al volo. La scelta la fa `dotnet-sdk.awk`, provato su metadati scritti nella prova | +| 2026-11-18 | Builder buildx: `costruisci-immagine.sh builder ` scrive la configurazione di BuildKit (`[registry.""]` con `http` e `insecure`), crea il builder `febe-ci-` con il driver `docker-container` (`--buildkitd-config`, o `--config` per un buildx più vecchio di 0.13) e lo avvia | Ciò che faceva `docker/setup-buildx-action`; la pulizia lo toglie per nome come prima | +| 2026-11-18 | Artefatti della CI nel registro dei pacchetti di Gitea, pacchetto generico `febe-ci`, una versione per esecuzione (`-ci.` dalla verifica, `-rilascio.` dal rilascio), con `.gitea/scripts/artefatti.sh` e `REGISTRY_TOKEN` (PUT su `/api/packages//generic/febe-ci//`; un file già caricato da un tentativo precedente si toglie e si ricarica). Senza il segreto un avviso e nessun artefatto. La pulizia del lunedì toglie le versioni di quella forma create più di 14 giorni prima (`versioni-registro.sh scadute 14`). Il lavoro `release` ricostruisce `Febe.exe`, installatore e zip invece di riceverli dal lavoro `windows` | I 14 giorni di `retention-days` di prima. Senza azioni non c'è un deposito di artefatti fra i lavori: il registro dei pacchetti è di Gitea, già usato per l'immagine. Ricostruire nella release costa qualche minuto a ogni tag, ma non la fa dipendere dal segreto | +| 2026-11-18 | JSON nella CI letto con `.gitea/scripts/json.awk`, un lettore in awk POSIX con funzioni di richiamo (`json-valido.awk` per il controllo di ogni file JSON del repository, `versioni-registro.awk` per la scelta delle versioni del registro); tolti `versioni-registro.js` e il controllo `node --check`. Prende il posto del motivo «Node e non jq» della riga del 21 ottobre sul registro e della riga sul controllo degli script Node | Niente Node nella CI. awk c'è nell'immagine dei lavori, in Debian e in Git Bash; il lettore dà gli stessi esiti di `JSON.parse` sui casi difficili provati (gawk normale e `--posix`) e sui 46 file JSON del repository, e la scelta delle versioni coincide con quella dello script Node sul file di prova | +| 2026-11-18 | Lavoro «prove» nel contenitore `debian:trixie` invece di `node:24-trixie`: git, curl e certificati nel primo passo, il resto da `ambiente-prove.sh` (anche le librerie di sistema dell'SDK), che si ferma se nel contenitore c'è `node`. La prova della pagina di accesso (`return-path.js`) gira in Chromium con il protocollo DevTools, come le altre prove dell'interfaccia, invece che in Node | Prende il posto della riga del 20 ottobre sul contenitore: le azioni, che volevano Node lì dentro, non ci sono più. Chromium è già fra ciò che Febe usa, ed è il motore che esegue davvero quel modulo | +| 2026-11-18 | Immagine Docker: si installano solo `chromium`, `chromium-l10n`, `xvfb`, `libicu76`, `libssl3t64`, `libstdc++6`, `libgcc-s1`, `zlib1g`, `fonts-dejavu-core`, `fonts-liberation`, `fonts-noto-color-emoji`, `ca-certificates`, `tzdata` e `locales` (più `ffmpeg` finché non arriva C2–C3), ciascuno con il suo motivo accanto alla lista nel `Dockerfile` e in `docs/docker.md`; tolti dalla lista `tini`, `util-linux` e `passwd`. `setpriv`, `groupadd`, `useradd` e `getent` vengono dall'immagine di base e la costruzione si ferma se uno manca. `ImageContentsTests` rifiuta un pacchetto fuori elenco o senza motivo | Decisione di Alberto del 18 novembre 2026: nell'immagine solo Chromium con i pacchetti di Debian che gli servono, Xvfb e ciò che serve al runtime .NET. Controllato: le librerie native del runtime .NET 10 per linux-x64 chiedono solo libc, libstdc++ e libgcc_s, e caricano ICU e OpenSSL a richiesta; zlib non la chiedono più (zlib-ng è dentro `libSystem.IO.Compression.Native`), ma `zlib1g` è una dipendenza diretta di `chromium` in trixie e resta. I caratteri restano perché servono al Chromium del contenitore: senza un carattere non scrive nulla, DejaVu è il primo che fontconfig chiede, Liberation tiene le misure di Arial e Helvetica, Noto le emoji. L'interfaccia di Febe non li usa: la disegna il browser di chi la apre. `util-linux` è essenziale in Debian e `passwd` è fra i pacchetti richiesti, quindi c'erano già | +| 2026-11-18 | Niente `tini`: il processo 1 del contenitore è Febe (`ENTRYPOINT ["/usr/local/bin/febe-avvio"]`, che con `exec setpriv … "$@"` cede il proprio numero di processo al server). Il runtime .NET, quando è il processo 1, raccoglie anche i processi orfani (`System.Native`, `reapAll` se il processo è il numero 1, nel ramo `release/10.0`) e riceve SIGTERM. La prova dell'immagine controlla che il processo 1 sia `febe` e che nessuno zombie suo figlio resti più di 10 secondi. Prende il posto della riga del 13 ottobre su tini | Stessa decisione: tini è un programma di terzi che non serve a Chromium. Il runtime .NET faceva già le due cose per cui c'era: SIGTERM lo gestiva Febe anche prima, e i processi del browser rimasti orfani li raccoglie il processo 1 | +| 2026-11-18 | jq tolto dalla CI: il riepilogo di gitleaks, i conti di Trivy, la configurazione del registro e le chiamate della release leggono e scrivono JSON con `.gitea/scripts/json.sh` (`campi` sul lettore `json.awk` con `json-campi.awk`, `stringa` con `json-stringa.awk`); un file che non si legge ferma il passo invece di dare campi vuoti | jq è un programma di terzi (in `debian:trixie` non c'è): con la regola «niente componenti esterni» il JSON della CI si tratta in casa, con lo stesso lettore già usato per i controlli | +| 2026-11-18 | Credenziali del registro solo in una configurazione del client Docker fatta per la pubblicazione (`DOCKER_CONFIG` temporaneo in `${RUNNER_TEMP}`, permessi 600, con i plugin, i contesti e il contesto corrente di quella del runner e `BUILDX_CONFIG` che resta quello di prima), tolta alla fine del passo e dalla pulizia | Prima `docker login` scriveva nella configurazione del runner, condivisa fra lavori e progetti, e la pulizia doveva toglierle con jq; così il gettone non esce mai dalla cartella dell'esecuzione | +| 2026-11-18 | `rilascio.yml`: le prove girano come nella verifica, nel contenitore `debian:trixie` con Chromium, Xvfb e ffmpeg di `ambiente-prove.sh` e il riepilogo che fa rosso il lavoro se una prova si salta; tutti i passi di ogni flusso con `defaults: run: shell: bash` | Il rilascio provava su un runner senza Chromium, dove le prove del browser risultano saltate: una release non deve passare con meno prove della verifica; senza `shell: bash` i passi in un contenitore partono con `sh` e `set -o pipefail` si rompe | +| 2026-11-18 | Caratteri: nell'immagine e nell'ambiente delle prove solo `fonts-dejavu-core`; tolti `fonts-liberation` e `fonts-noto-color-emoji` (sostituisce il motivo della riga del 18 novembre sull'elenco dei pacchetti dell'immagine) | Chromium non li chiede (Liberation è solo consigliato, le emoji nulla): servivano all'aspetto, non al funzionamento, e la regola ammette solo ciò che serve a Chromium. Da confermare con Alberto: senza emoji a colori il Chromium del contenitore mostra le emoji delle pagine come caratteri semplici o quadratini | +| 2026-11-18 | Programma di installazione: un aggiornamento senza `/D=` va nella cartella dell'installazione che c'è (`InstallLocation` della chiave di disinstallazione, solo se è un percorso assoluto e non una radice); la dimensione in «App installate» conta solo i due file dell'installatore; i file in sola lettura si sostituiscono e si tolgono; «Febe» in Esegui all'avvio si toglie solo se avvia il Febe di quella cartella; Febe parte alla fine solo con «Fine» e la casella spuntata; `/PROVA=` rifiuta la radice di un disco | Correzioni della revisione di C6: prima un aggiornamento da una cartella scelta a mano finiva nella cartella predefinita lasciando la vecchia copia, una cartella senza permessi sembrava «Febe aperto», e la disinstallazione toglieva l'avvio di un Febe portatile | +| 2026-11-18 | Schermate dell'interfaccia con `tools/Febe.Schermate`, un programma C# (`ClientWebSocket` e `System.Text.Json`, nessun pacchetto) che sostituisce `tools/schermate` (sostituisce la riga del 2026-10-13); resta il Chromium senza finestra, come le prove dell'interfaccia (`UiBrowser`), solo verso 127.0.0.1, localhost o [::1] | Lo strumento di prima voleva Node; la regola «Chromium mai headless» riguarda il browser di Febe verso il sito, non le schermate dell'interfaccia di Febe stessa | +| 2026-11-25 | Unione della catena della 0.3.0 in `funzione/senza-terzi`: la CI, l'immagine e le guide di C6 restano (solo comandi, niente Node, installatore `src/Febe.Installer`, carattere del sistema e icone di Febe, Febe processo 1) senza più ffmpeg e con la categoria «da fare» di `riepilogo-prove.sh`; la guida (`docs/guida/Sviluppo.md`) dice che Node, il programma di installazione, il carattere e le icone di terzi sono usciti con la tappa C6 senza nominare gli ultimi tre, e `SpecificationConsistencyTests` lo ammette solo per la guida; `InstallerTests` ammette NSIS solo nella regola 12 di `CLAUDE.md`, copia dell'appendice A della specifica | Le prove di C6 vietano NSIS, Archivo e Lucide in `docs/guida` e in `CLAUDE.md`, quelle dei documenti chiedevano che la regola li nominasse con la loro tappa: con C6 fatta i nomi possono uscire dalla guida, mentre la regola 12 di `CLAUDE.md` e la specifica sono del lavoro sui documenti | +| 2026-11-25 | Immagine Docker e contenitore delle prove: `fonts-noto-color-emoji` torna accanto a `fonts-dejavu-core`, con il suo motivo nel `Dockerfile` e nella tabella di `docs/docker.md`; `fonts-liberation` resta fuori. `ImageContentsTests` lo ammette e chiede gli stessi due caratteri in `ambiente-prove.sh` (sostituisce, per le emoji, la riga del 18 novembre che toglieva i due caratteri) | Risposta di Alberto del 25 novembre 2026: a Chromium le emoji servono per mostrare le pagine (senza, quadratini nella vista remota); Liberation non serve | +| 2026-11-25 | Revisione della catena su `funzione/senza-terzi`: `ImageFormatSniffer.Detect` dice HEIF per ogni file che `HeifDecoder.Looks` accetta (mif2, MiHE, o una marca HEIF solo fra le compatibili), dopo il controllo di AVIF | La facciata delle immagini sceglie il decodificatore con `Detect`: con un elenco più stretto un HEIC di quelle marche restava senza miniatura, impronta e dimensioni, mentre `MediaSniffer` lo archiviava come foto HEIC | +| 2026-11-25 | Docker, lasciare la pagina del browser: una vista che si riapre cancella un abbandono annunciato prima (il `pageLeft` tardivo di una pagina ricaricata, la vecchia vista chiusa da «Riprova»), e l'attesa di un altro comando del collegamento prima della copia dura al più `LetGoWait` (30 s), come alla chiusura della finestra su Windows; poi il permesso finisce senza copia | §6.0: il browser spento non vale come abbandono, quindi una vista chiusa dal server deve aspettare `DrivingGrace`; e il motore non deve restare trattenuto da un comando lungo | +| 2026-11-25 | JPEG e PNG che finiscono prima del loro marcatore di fine (EOI, IEND) non si decodificano più, anche con le scansioni o i dati completi: sono «File danneggiato o incompleto»; `Identify` ne legge ancora le dimensioni | §3 lo chiede alla lettera; un JPEG progressivo tagliato fra due scansioni dava un'immagine di qualità minore, con miniatura e impronta, senza dirlo | +| 2026-11-25 | Visualizzatore: il controllo «danneggiato» guarda prima l'intestazione (formati che Febe non decodifica, HEIC, PNG/GIF/BMP/WebP oltre i 100 megapixel dall'intestazione: mai danneggiati, senza leggere il resto), legge con I/O asincrono e tiene la risposta per percorso, lunghezza e data di modifica (al più 512) | Ogni apertura del visualizzatore rileggeva tutto il file, fino a 512 MB, per arrivare al limite già scritto nell'intestazione | +| 2026-11-25 | Importazione (§9.3): l'analisi segna le immagini danneggiate o troncate; la revisione lo dice in un avviso, il resoconto le elenca sotto «File danneggiato o incompleto» e l'elenco CSV lo scrive nella colonna «Nota». Gli identificativi stanno nell'impostazione `importazione..danneggiati` della singola importazione, come le altre sue impostazioni, senza una colonna nuova in `import_file` | La migrazione `0002` è riservata alla tappa E1 (§8.3): un'impostazione dell'importazione evita una migrazione fuori piano; i file danneggiati sono pochi | +| 2026-11-25 | Moduli dell'interfaccia: una prova senza browser (`ScriptSyntaxTests`, lettore di simboli in casa) cerca le parentesi che non tornano, `let`/`const`/`class` dichiarati due volte nello stesso blocco o col nome di un parametro o di un'importazione, e le importazioni statiche di nomi che l'altro modulo non esporta | `let saved` in `savedSessionBox(saved, …)` era un errore di sintassi che fermava `connection.js` e con lui le pagine Browser e Collegamento; le prove con Chromium girano solo nella CI. Niente Node (regola 12) | +| 2026-11-25 | Le sei prove di `PipelineTests.Pulizia` con il limite di 5 minuti girano una per volta, dopo le altre (`[DoNotParallelize]`), senza alzare il limite | In un giro completo in locale, accanto alle suite di conformità H.264/H.265, superavano i 5 minuti; da sole ne prendono circa uno | +| 2026-11-25 | Carattere: il token `--carattere` è esattamente la pila dell'appendice B (`system-ui,-apple-system,"Segoe UI",Roboto,sans-serif`), che `InHouseAssetsTests` confronta con la specifica; sostituisce la pila del 18 novembre con Cantarell, "Noto Sans" e "Liberation Sans" | La specifica fissa la pila; Liberation è fuori anche dall'immagine. Resta per i documenti: l'appendice B non elenca il token `--carattere` | +| 2026-11-25 | Il commit di unione 537517b ha nel messaggio, dopo `Co-Authored-By`, le righe `# Conflicts:` lasciate da git: si accetta così, sapendolo | Rifarlo vorrebbe dire riscrivere la storia di cinque rami locali costruiti sopra; `git interpret-trailers` legge lo stesso il `Co-Authored-By` | +| 2026-11-25 | Documenti allineati alla catena della 0.3.0 costruita su `funzione/senza-terzi` (C1–C6, S4b): la regola 12 di `CLAUDE.md` e la sua copia nell'appendice A, e la regola 13 della specifica, dicono che SkiaSharp, ffprobe, ffmpeg, NSIS, Node, Archivo e Lucide **sono già usciti**; §6.0 toglie «finché questo non è costruito» e dice `LeavePageAsync` e il ripiego su «Annulla» dove non si copia; §3, §4.6, §8.4, §9.2, §9.3 e §14.1 dicono HEIC decodificato in casa (mai «danneggiato»), JPEG e PNG senza `EOI`/`IEND` troncati, HEVC negli MPEG-PS dall'SPS con il tipo 0x24 e senza fotogramma, i danneggiati segnati in revisione, resoconto e CSV, e il JPEG con codifica aritmetica, 12 bit e senza perdita; §11 l'immagine com'è (Febe processo 1, `fonts-dejavu-core` e `fonts-noto-color-emoji`, i pacchetti per il runtime .NET, `setpriv` dall'immagine di base); appendici B e C senza Archivo e Lucide, con il token `--carattere`. `SpecificationConsistencyTests` vuole il passato nella frase che nomina ogni componente, cerca le frasi che lo davano ancora in uso e ammette in `Directory.Packages.props` solo i pacchetti della regola; `InstallerTests` ammette NSIS nella regola 12 solo se dice che è uscito | Le tappe sono costruite e i documenti le davano ancora per future: le prove dei documenti chiedevano «esce con», e avrebbero lasciato passare un documento che desse un componente ancora in uso | | 2026-11-25 | I lavori «installatore» di `verifica.yml` e «windows» di `rilascio.yml` girano con `DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=true` | L'immagine `ubuntu-latest` del runner non ha più ICU: il 25 novembre `dotnet publish` si fermava con «Couldn't find a valid ICU package» (esecuzione 431). Pubblicare Febe.exe e impacchettare l'installatore non usano le culture, e così il lavoro non dipende più da cosa l'immagine installa; le prove restano nel contenitore Debian con ICU e la lingua italiana | diff --git a/docs/docker.md b/docs/docker.md index 005f214..b61d1f4 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -11,12 +11,12 @@ display virtuale (Xvfb) e la libreria su disco. Si usa dal browser di casa; il b - Debian stabile ridotta (`debian:trixie-slim`). Su Ubuntu il pacchetto Chromium è uno snap e nei contenitori non funziona. - Febe pubblicato **autosufficiente** per `linux-x64`: nell'immagine non c'è il runtime .NET. -- `chromium` e `chromium-l10n`, `xvfb`, ICU, caratteri di sistema con le emoji (`fonts-noto-color-emoji`, - `fonts-liberation`, `fonts-dejavu-core`, per Chromium), certificati, `tzdata`, la lingua `it_IT.UTF-8` generata. +- `chromium` e `chromium-l10n`, `xvfb`, ICU, un carattere di sistema (`fonts-dejavu-core`) e le emoji + (`fonts-noto-color-emoji`), per Chromium, certificati, `tzdata`, la lingua `it_IT.UTF-8` generata. - Nessuna libreria per le immagini: miniature, impronte e disegni li fanno i codec di Febe scritti in C# (`src/Febe.Core/Codecs/Images`, `src/Febe.Core/Drawing`). -- `tini` come processo 1 (inoltra lo stop a Febe e raccoglie i processi di Chromium rimasti orfani) e `setpriv` per - scendere all'utente `PUID`/`PGID`. Nessuno script fa da supervisore: è Febe ad avviare e riavviare Xvfb e Chromium. +- Febe come processo 1 (niente `tini`: riceve lo stop e raccoglie i processi di Chromium rimasti orfani) e `setpriv` + per scendere all'utente `PUID`/`PGID`. Nessuno script fa da supervisore: è Febe ad avviare e riavviare Xvfb e Chromium. - Un file di criteri di Chromium (`/etc/chromium/policies/managed/febe.json`) che spegne il salvataggio delle password e la compilazione automatica: con l'archivio di base finirebbero in chiaro nel profilo. Nel profilo resta solo la sessione. - L'immagine si costruisce solo con le prove verdi: la compilazione e tutte le prove girano dentro la costruzione @@ -27,6 +27,39 @@ display virtuale (Xvfb) e la libreria su disco. Si usa dal browser di casa; il b scansiona con Trivy: una vulnerabilità CRITICAL con correzione disponibile ferma la pubblicazione (`docs/processo.md`, «Rilievi di sicurezza»). +### Perché c'è ogni pacchetto + +Dal 18 novembre 2026 (decisione di Alberto, niente componenti esterni) nell'immagine si installano solo Chromium con i +pacchetti di Debian che gli servono, Xvfb e ciò che serve al runtime .NET. Le dipendenze di ciascuno le porta apt da +solo; la lista del `Dockerfile` ha accanto lo stesso motivo, e una prova (`ImageContentsTests`) si ferma se un +pacchetto entra senza motivo o fuori da questo elenco. + +| Pacchetto | Perché | +|---|---| +| `chromium` | il browser di Febe, quello della distribuzione | +| `chromium-l10n` | le lingue di Chromium: con `LANG=it_IT.UTF-8` menu e `Accept-Language` sono in italiano come nel browser di Alberto; senza, Chromium ha solo l'inglese | +| `xvfb` | il display virtuale: Chromium non è mai headless | +| `libicu76` | ICU per il runtime .NET (date, ordinamenti e testi in italiano); Chromium ha la sua | +| `libssl3t64` | OpenSSL per il runtime .NET: TLS del client del sito e del CDN, cifratura della sessione salvata; Chromium ha la sua | +| `libstdc++6`, `libgcc-s1` | librerie che il runtime .NET carica (la seconda serve anche a Chromium) | +| `zlib1g` | chiesta da Chromium; il runtime .NET 10 non la usa più (ha zlib-ng al suo interno) | +| `fonts-dejavu-core` | il carattere che fontconfig, la libreria dei caratteri di Chromium, chiede per primo (fontconfig-config lo porta comunque): senza un carattere Chromium non scrive nulla | +| `fonts-noto-color-emoji` | le emoji a colori: Chromium ne ha bisogno per mostrare le pagine del sito nella vista remota; senza, le emoji diventano quadratini (risposta di Alberto del 25 novembre 2026) | +| `ca-certificates` | le autorità di certificazione per il TLS del runtime .NET (Chromium ha le sue) | +| `tzdata` | i fusi orari, per il motore e per Chromium | +| `locales` | genera `it_IT.UTF-8`: Chromium gira con la lingua della libreria C, che deve esistere | + +I due caratteri servono al Chromium del contenitore, che mostra il sito e la vista remota. L'interfaccia di Febe no: la +disegna il browser di chi la apre, con i caratteri del suo sistema. Dal 25 novembre 2026 (risposta di Alberto) le emoji +a colori restano, perché a Chromium servono per mostrare le pagine; nessun altro carattere entra per il solo aspetto. +Nella vista remota le pagine che chiedono Arial o Helvetica si vedono con DejaVu, con misure un po' diverse. + +Non ci sono più `tini`, `util-linux` e `passwd` fra i pacchetti installati. Il processo 1 è Febe: l'avvio fa `exec` +di `setpriv`, che fa `exec` del server, e il runtime .NET, quando è il processo 1, raccoglie da sé anche i processi +orfani. `setpriv`, `groupadd`, `useradd` e `getent`, che servono all'avvio, sono già nell'immagine di base +(`util-linux` è essenziale in Debian, `passwd` e `libc-bin` sono fra i pacchetti richiesti); la costruzione si ferma +se uno manca. Nell'immagine non c'è curl: il controllo di salute lo fa Febe stesso. + ## Etichette dell'immagine Sul registro di Gitea, `192.168.30.23:3000/alby96/febe`: @@ -170,7 +203,7 @@ Febe non sceglie da solo: se Chromium non parte, il registro dice perché e rima `docker/compose.yml` è un esempio pronto: immagine, porta, volumi (con `/importa` in sola lettura), variabili, profilo seccomp con percorso relativo al file (`chromium/seccomp.json`, fuori da `/dati`), `restart: unless-stopped`, 30 -secondi per fermarsi. `init: true` non serve (c'è già `tini`) e nemmeno `shm_size` (Chromium usa `/tmp` al posto della +secondi per fermarsi. `init: true` non serve (il processo 1 è Febe) e nemmeno `shm_size` (Chromium usa `/tmp` al posto della memoria condivisa). Anche qui il registro `192.168.30.23:3000` deve stare fra gli `insecure-registries` del Docker. ```sh diff --git a/docs/guida/Installazione-Windows.md b/docs/guida/Installazione-Windows.md index 18f8b76..2ede7f2 100644 --- a/docs/guida/Installazione-Windows.md +++ b/docs/guida/Installazione-Windows.md @@ -46,10 +46,17 @@ , e aprilo. 2. Windows può avvisare che il programma non è firmato (SmartScreen): «Ulteriori informazioni» ▸ «Esegui comunque». 3. Il programma di installazione mette `Febe.exe` in `%LOCALAPPDATA%\Programs\Febe`, crea il collegamento nel menu - Start e, se lasci la scelta «Collegamento sul desktop», uno sul desktop. Febe compare in Impostazioni di Windows ▸ - App installate. + Start e, se lasci la scelta «Crea un collegamento a Febe sul desktop», uno sul desktop. Febe compare in + Impostazioni di Windows ▸ App installate. 4. Alla fine, «Apri Febe adesso» lo avvia. +**Aggiornare.** Esci da Febe (menu dell'icona ▸ Esci) e apri il programma di installazione della versione nuova: la +prima pagina dice «Aggiornamento di Febe alla versione …», sostituisce il programma e lascia dove sono i dati, la +libreria e le impostazioni. Con Febe aperto si ferma e chiede di chiuderlo. + +**Senza domande.** `Febe-Setup-.exe /S` installa (o aggiorna) senza finestre, con il collegamento sul +desktop e senza avviare Febe; `/D=`, ultima opzione, sceglie un'altra cartella. + Non serve installare .NET: `Febe.exe` (circa 86 MB) contiene il runtime, l'interfaccia e le librerie native. Al primo avvio Windows estrae le librerie native in `%TEMP%\.net\Febe`: è normale. diff --git a/docs/guida/Problemi-comuni.md b/docs/guida/Problemi-comuni.md index 6f032a5..1c781d8 100644 --- a/docs/guida/Problemi-comuni.md +++ b/docs/guida/Problemi-comuni.md @@ -32,7 +32,7 @@ dati. | La vista remota dice «Nessuna immagine dal browser» | La vista è aperta ma la pagina non arriva. Febe riavvia da solo l'invio delle immagini quando si fermano; premi «Riprova». Se resta così, guarda il registro (categoria «vista»: avvii, riavvii e silenzi) e riferisci il caso | | Il browser è bianco, o la barra dice «Il browser è a riposo su una pagina vuota» | È la pagina vuota su cui Febe lascia il browser quando non lo usa: premi «Pagina iniziale» (la home di Instagram se sei collegato, altrimenti la pagina di accesso) | | «Ho finito» dice che l'accesso non è riuscito | Nella pagina deve comparire la tua pagina iniziale di Instagram, non il modulo di accesso: completa l'accesso, poi di nuovo «Ho finito» | -| «La sessione per le richieste non è stata copiata» | Solo con la raccolta «richieste». Il messaggio dice perché: se il browser non era su una pagina del sito o era sulla pagina di accesso o di verifica, apri la tua pagina iniziale e premi di nuovo «Ho finito»; se nel frattempo il browser era tornato al motore, rifai l'accesso dalla pagina Collegamento. La sessione salvata di prima resta com'era. Se invece il messaggio dice che la sessione «era già stata copiata quando il browser è tornato al motore», Febe l'ha copiata quando hai lasciato il browser (su Windows chiudendo la finestra, o alla fine della guida) e il browser era già tornato al motore: se il messaggio non dice che mancano valori, non serve fare nulla. In Docker lasciare la pagina senza «Ho finito» non copia: premi «Ho finito» prima di uscire | +| «La sessione per le richieste non è stata copiata» | Solo con la raccolta «richieste». Il messaggio dice perché: se il browser non era su una pagina del sito o era sulla pagina di accesso o di verifica, apri la tua pagina iniziale e premi di nuovo «Ho finito»; se nel frattempo il browser era tornato al motore, rifai l'accesso dalla pagina Collegamento. La sessione salvata di prima resta com'era. Se invece il messaggio dice che la sessione «era già stata copiata quando il browser è tornato al motore», Febe l'ha copiata quando hai lasciato il browser (su Windows chiudendo la finestra, in Docker lasciando la pagina del browser, o alla fine della guida) e il browser era già tornato al motore: se il messaggio non dice che mancano valori, non serve fare nulla. In Docker, se lasci la pagina del browser (o ne chiudi la scheda) senza «Ho finito», Febe aspetta 5 secondi: se nessuna vista del browser si riapre copia la sessione e restituisce il browser al motore; solo «Annulla» lo restituisce senza copiare | | «Serve «Ho finito»» (barra laterale o pagina Collegamento) | Solo con la raccolta «richieste»: il browser ha la sessione, ma Febe non ha una copia leggibile per le richieste (dopo «Annulla», o con un file che non si legge più). Il motore aspetta: dalla pagina Collegamento apri la tua pagina iniziale nel browser e premi «Ho finito» | | «Alla pagina mancavano … Febe tiene la copia completa salvata prima e non usa quella nuova» | Hai scelto «Tieni la copia completa» nella pagina Collegamento e alla pagina mancava un valore che le richieste usano. Se hai rifatto l'accesso o cambiato account, scegli «Sostituisci comunque» e premi di nuovo «Ho finito» | | «Sessione copiata…, ma non ancora scritta su disco» | Il disco ha rifiutato la scrittura (spazio, permessi di `/dati/sessione`): Febe usa la copia in memoria e riprova alla prossima scrittura. Controlla lo spazio e i permessi; il registro dice il tipo d'errore | diff --git a/docs/guida/Sicurezza-e-riservatezza.md b/docs/guida/Sicurezza-e-riservatezza.md index fbc29db..2206a50 100644 --- a/docs/guida/Sicurezza-e-riservatezza.md +++ b/docs/guida/Sicurezza-e-riservatezza.md @@ -18,7 +18,8 @@ copia altrove. Con la raccolta «richieste» (`FEBE_RACCOLTA`, `--raccolta`) «Ho finito» copia la sessione del browser in `sessione/sessione.json`, nella cartella dei dati, per le richieste dirette di Febe; la copia si fa anche quando chiudi -la finestra del browser su Windows e quando la guida del browser finisce da sola (vedi +la finestra del browser su Windows, in Docker quando lasci la pagina del browser senza «Ho finito», e quando la guida +del browser finisce da sola (vedi [Primo collegamento](Primo-collegamento)). Con Instagram, per ora, non succede: la copia si accende solo quando ci sono richieste configurate. diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index 42a8d31..c415960 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -13,12 +13,14 @@ framework né fase di build. La specifica è `docs/SPECIFICA.md`; le scelte pres programmi, librerie o file di dati di terzi (caratteri, icone); tutto il codice in casa, i formati dalle loro specifiche pubbliche. Ammessi solo .NET, Microsoft.Data.Sqlite, il browser (Microsoft.Web.WebView2 su Windows) e MSTest (`Directory.Packages.props`); nella sola CI gitleaks e Trivy; nell'immagine Docker solo Chromium, i pacchetti - Debian che gli servono e Xvfb. Ciò che è ancora in uso esce con la sua tappa del traguardo 0.3.0, e intanto lo usa il - codice di prima: NSIS, Node, il carattere Archivo e le icone Lucide con C6. SkiaSharp è già uscito, - con la tappa C1: le immagini (PNG, JPEG, GIF, BMP, WebP) le leggono e scrivono codec di Febe + Debian che gli servono e Xvfb. Ciò che era ancora in uso è uscito con la sua tappa del traguardo 0.3.0. SkiaSharp è + uscito con la tappa C1: le immagini (PNG, JPEG, GIF, BMP, WebP, HEIC) le leggono e scrivono codec di Febe (`src/Febe.Core/Codecs/Images`), e icona, immagini dimostrative e riquadri li disegna `src/Febe.Core/Drawing`. - Anche ffmpeg è già uscito, con la tappa C3: contenitori e H.264 li legge codice di Febe (`src/Febe.Core/Codecs/Containers`, - `src/Febe.Core/Codecs/H264`). Prima di aggiungere qualunque cosa, si chiede. + ffmpeg è uscito con la tappa C3: contenitori, H.264 e HEVC li legge codice di Febe (`src/Febe.Core/Codecs/Containers`, + `src/Febe.Core/Codecs/H264`, `src/Febe.Core/Codecs/H265`). Node, il programma di installazione, il carattere e le + icone di terzi sono usciti con la tappa C6: la CI è fatta solo di comandi, l'installatore è `src/Febe.Installer`, il + carattere è quello del sistema e le icone sono disegnate per Febe (`src/Febe.Web/wwwroot/icone`). Prima di aggiungere + qualunque cosa, si chiede. ## Com'è fatto il repository @@ -33,7 +35,7 @@ framework né fase di build. La specifica è `docs/SPECIFICA.md`; le scelte pres | `tests/Febe.Tests` | Le prove (MSTest), con i campioni ripuliti in `tests/campioni/` | | `tools/Febe.SitoDiProva` | Il sito locale per le prove senza Instagram | | `tools/Febe.Sonda` | La sonda passiva per raccogliere i campioni | -| `tools/schermate` | Le schermate dell'interfaccia per il confronto con i mockup | +| `tools/Febe.Schermate` | Le schermate dell'interfaccia per il confronto con i mockup (C#, nessun programma di terzi), con i passi in `passi/` | | `docker/` | `Dockerfile`, `compose.yml`, `entrypoint.sh`, file di Chromium (criteri, profilo seccomp), modello di Unraid | | `docs/` | Specifica, decisioni, stato, Docker, prove dal vivo, esiti della sonda, mockup, schermate, e questa guida (`docs/guida/`) | @@ -182,9 +184,10 @@ si cancellano dopo l'uso; nel repository entrano solo i campioni ripuliti. La pr ## Schermate -`bash tools/schermate/tutte.sh 8490` rifà le schermate di `docs/schermate/` da una dimostrazione avviata su quella -porta, per il confronto con i mockup (§10.7 della specifica); le differenze rimaste sono in -`docs/schermate/differenze.md`. Lo strumento accetta solo indirizzi di questo computer. +`dotnet run --project tools/Febe.Schermate -- 8490` rifà le schermate di `docs/schermate/` da una dimostrazione avviata su +quella porta, una alla volta, per il confronto con i mockup (§10.7 della specifica); le differenze rimaste sono in +`docs/schermate/differenze.md`. Lo strumento accetta solo indirizzi di questo computer e cerca Chromium come Febe +(`FEBE_CHROMIUM`, poi `chromium` di Debian, poi Edge su Windows). ## Immagine Docker @@ -200,17 +203,19 @@ da sole). Vedi [Installazione con Docker e Unraid](Installazione-Docker-e-Unraid Il repository è sul Gitea di casa (); la CI usa Gitea Actions in `.gitea/workflows/`, con il codice comune in `.gitea/scripts/`. Il processo completo (nomi dei rami, commit, richieste di unione, protezione di `main`, rilievi di sicurezza, rilasci, correzioni urgenti) è in `docs/processo.md`. +I flussi sono fatti solo di comandi: nessuna azione (`uses:`) e niente Node; i sorgenti si prendono con git, l'SDK +.NET con `.gitea/scripts/dotnet.sh` e gli artefatti vanno nel pacchetto generico `febe-ci` del registro di Gitea +(proprietario ▸ Pacchetti), con il segreto `REGISTRY_TOKEN`. - `verifica.yml`, a ogni push su qualunque ramo e a mano (non sui tag, non sulle richieste di unione, che mostrano lo stato del loro ultimo commit). Quattro lavori, che sono i controlli richiesti per unire in `main`: - `controlli`: sintassi degli script, file di testo, versione, progetti della soluzione, JSON, e nessun segreto in tutta la storia (gitleaks); - `prove`: compilazione di tutta la soluzione con gli avvisi come errori e tutte le prove di `tests/Febe.Tests` in - un contenitore Debian con Chromium e Xvfb veri, più NSIS e Node (fino alla tappa C6 del traguardo 0.3.0): - nessuna prova si salta. Fa eccezione solo la categoria «da fare»: le inconclusive di - `H264ConformanceTests.FeaturesStillToDo` il cui motivo comincia con «da fare: » (flussi di conformità delle parti - del decodificatore H.264 non ancora scritte), elencate a parte nel riepilogo; - - `installatore`: `Febe-Setup--ci..exe` e lo zip portabile, fra gli artefatti per 14 giorni; + un contenitore Debian con Chromium e Xvfb veri, senza Node: nessuna prova si salta. Fa eccezione solo la categoria + «da fare»: le inconclusive di `H264ConformanceTests.FeaturesStillToDo` il cui motivo comincia con «da fare: » + (flussi di conformità delle parti del decodificatore H.264 non ancora scritte), elencate a parte nel riepilogo; + - `installatore`: `Febe-Setup--ci..exe` e lo zip portabile, nel pacchetto `febe-ci` per 14 giorni; - `immagine`, dopo l'installatore: l'immagine Docker, provata senza rete (parte, diventa «healthy», si ferma) e scansionata con Trivy; dopo un push su `main` va sul registro come `:main` e `:sha-`. Alla fine si toglie tutto ciò che l'esecuzione ha creato sul demone Docker, che è condiviso con gli altri progetti, e poi, di tutti, le @@ -219,7 +224,7 @@ richieste di unione, protezione di `main`, rilievi di sicurezza, rilasci, correz `:X.Y.Z` e `:latest` (solo per le versioni senza trattino), poi la release; - `pulizia.yml`, ogni lunedì e a mano: i resti delle esecuzioni interrotte e dei lavori di act_runner, le immagini che nessun contenitore usa e la cache di costruzione più vecchie di 24 ore, di tutti i progetti, e sul registro le - `:sha-` oltre le 10 più recenti; mai un contenitore, un volume o una rete che non sia della CI. A mano, con «Solo + `:sha-` oltre le 10 più recenti e gli artefatti di `febe-ci` di più di 14 giorni; mai un contenitore, un volume o una rete che non sia della CI. A mano, con «Solo prova», elenca che cosa toglierebbe e non toglie nulla (`docs/processo.md`, «Pulizia»). Nella CI le prove del sito di prova (categoria `SitoDiProva`) girano due volte: con il seme 13 e con un seme diverso diff --git a/docs/processo.md b/docs/processo.md index 9abf0a0..9a74f2b 100644 --- a/docs/processo.md +++ b/docs/processo.md @@ -84,11 +84,30 @@ Gitea Actions su un solo act_runner (etichetta `ubuntu-latest`, un lavoro alla v Docker del server, lo stesso che costruisce Encelado, Mimante e gli altri progetti di Alberto. I flussi stanno in `.gitea/workflows/`, il codice comune in `.gitea/scripts/` (si lancia anche a mano). +Dal 18 novembre 2026 i flussi sono fatti **solo di comandi**: nessuna azione (`uses:`), perché quelle di GitHub e di +Gitea sono programmi JavaScript che vogliono Node, e nella CI di Febe non gira Node in nessuna forma (decisione di +Alberto, nessun componente esterno). Al posto delle azioni: + +| Prima | Ora | +|---|---| +| `actions/checkout` | il passo «Sorgenti», uguale lettera per lettera in ogni lavoro: `git init` e `git fetch` del commit con il gettone del lavoro (`gitea.token`), passato a git solo nell'ambiente di quel passo (`GIT_CONFIG_*`), mai scritto nella configurazione del repository; tutta la storia in `controlli` (gitleaks), un solo commit altrove | +| `actions/setup-dotnet` | `.gitea/scripts/dotnet.sh 10.0`: l'ultimo SDK del canale dai metadati dei rilasci di Microsoft, scaricato da `builds.dotnet.microsoft.com` e installato solo se l'impronta SHA-512 coincide con quella dei metadati; resta nella cache degli strumenti del runner (`act-toolcache`) e non si riscarica finché non esce un SDK nuovo | +| `docker/setup-buildx-action` | `costruisci-immagine.sh builder `: `docker buildx create` con il driver `docker-container` e il registro di casa in HTTP | +| `actions/upload-artifact` | `.gitea/scripts/artefatti.sh`: i file vanno nel registro dei pacchetti di Gitea, pacchetto generico `febe-ci`, una versione per esecuzione (`-ci.` dalla verifica, `-rilascio.` dal rilascio), con `REGISTRY_TOKEN`; si scaricano da proprietario ▸ Pacchetti ▸ `febe-ci`, e la pulizia del lunedì toglie quelle di più di 14 giorni | +| `actions/download-artifact` (rilascio) | nessun passaggio di file fra lavori: il lavoro `release` ricostruisce `Febe.exe`, installatore e zip dallo stesso commit | +| Node per i JSON (`controlli`, pulizia del registro) | `.gitea/scripts/json.awk`, un lettore JSON in awk POSIX (con `json-valido.awk` per i controlli, `versioni-registro.awk` per il registro) | +| jq (riepilogo di gitleaks, conti di Trivy, credenziali del registro, release) | `.gitea/scripts/json.sh`: `json.sh campi ` legge i campi degli oggetti di un percorso (`json-campi.awk`, sullo stesso lettore), `json.sh stringa ` scrive un testo come stringa JSON (`json-stringa.awk`); nessun flusso né script chiama jq | + +Il contenitore del lavoro `prove` è `debian:trixie` (prima `node:24-trixie`): git e curl si installano nel primo passo, +tutto il resto da `ambiente-prove.sh`, che si ferma se trova `node`. La regola della pagina di accesso +(`return-path.js`) si prova in Chromium, come tutte le prove dell'interfaccia. `PipelineTests` controlla che nessun +flusso usi `uses:` e che nessuno script chiami `node`, `npm` o `npx`. + | Lavoro | Quando | Che cosa garantisce | |---|---|---| -| `controlli` | ogni push | sintassi di tutti gli script di shell (`bash -n`, `sh -n`) e righe Unix; flussi senza tabulazioni; nessun segno di conflitto; versione in `Directory.Build.props` valida; ogni progetto di `Febe.slnx` esiste; ogni JSON si legge; nessun segreto in tutta la storia (gitleaks 8.30.1, `--redact`) | -| `prove` | dopo `controlli` | in un contenitore Debian 13 (`node:24-trixie` fino alla tappa C6 del traguardo 0.3.0, poi un'immagine Debian senza Node) con Chromium della distribuzione, Xvfb e la lingua italiana, più NSIS e Node (fino alla tappa C6, regola 13): tutta la soluzione compila con gli avvisi come errori e **tutte** le prove di `tests/Febe.Tests` passano senza saltarsi (unica eccezione la categoria «da fare»: le inconclusive di `H264ConformanceTests.FeaturesStillToDo` il cui motivo comincia con «da fare: », cioè i flussi di conformità delle parti del decodificatore non ancora scritte, che `riepilogo-prove.sh` elenca a parte e non conta fra le saltate); quelle della categoria `SitoDiProva` passano anche con il seme dell'esecuzione. Risultati `.trx` fra gli artefatti (14 giorni) | -| `installatore` | dopo `prove` | `Febe.exe` in un file solo, `Febe-Setup--ci..exe` (con NSIS fino alla tappa C6, poi con l'installatore scritto in casa) e lo zip portabile si costruiscono, ciascuno sotto i 100 MB; artefatti per 14 giorni | +| `controlli` | ogni push | sintassi di tutti gli script di shell (`bash -n`, `sh -n`) e righe Unix, anche dei programmi awk; flussi senza tabulazioni né righe Windows, con i rientri di due spazi, `on:` e `jobs:`, e senza `uses:`; nessun segno di conflitto; versione in `Directory.Build.props` valida; ogni progetto di `Febe.slnx` esiste; ogni JSON si legge (`json.awk`); nessun segreto in tutta la storia (gitleaks 8.30.1, `--redact`; il rapporto, se trova qualcosa, nel pacchetto `febe-ci`) | +| `prove` | dopo `controlli` | in un contenitore Debian 13 (`debian:trixie`) con Chromium della distribuzione, Xvfb e la lingua italiana, senza Node, e l'SDK di `dotnet.sh`: tutta la soluzione compila con gli avvisi come errori e **tutte** le prove di `tests/Febe.Tests` passano senza saltarsi (unica eccezione la categoria «da fare»: le inconclusive di `H264ConformanceTests.FeaturesStillToDo` il cui motivo comincia con «da fare: », cioè i flussi di conformità delle parti del decodificatore non ancora scritte, che `riepilogo-prove.sh` elenca a parte e non conta fra le saltate); quelle della categoria `SitoDiProva` passano anche con il seme dell'esecuzione. Risultati `.trx` nel pacchetto `febe-ci` (14 giorni, con `REGISTRY_TOKEN`) | +| `installatore` | dopo `prove` | `Febe.exe` in un file solo, `Febe-Setup--ci..exe` (con l'installatore scritto in casa, `src/Febe.Installer`) e lo zip portabile si costruiscono, ciascuno sotto i 100 MB; installatore e zip nel pacchetto `febe-ci` per 14 giorni | | `immagine` | dopo `installatore` (così `:main` e `:sha-` escono solo da un commit con tutta la verifica verde) | l'immagine si costruisce con buildx (dentro girano compilazione e prove), il contenitore parte **senza rete** come dice la guida e diventa «healthy», Chromium e la lingua italiana ci sono, si ferma entro 30 secondi; Trivy 0.75.0 non trova vulnerabilità CRITICAL con correzione disponibile. Solo dopo un push su `main`: pubblicazione `:main` e `:sha-` | La verifica gira a ogni push su qualunque ramo e a mano (Actions ▸ verifica ▸ Esegui, con un seme facoltativo). Su un @@ -114,10 +133,17 @@ FEBE_SEME_PROVA= dotnet test tests/Febe.Tests --filter "TestCategory=SitoD ### Segreti e variabili - `REGISTRY_TOKEN` (segreto del repository): token di Alberto con «package: read and write». Senza, `verifica` e - `rilascio` costruiscono, provano e scansionano l'immagine ma non la pubblicano, con un avviso, e restano verdi. + `rilascio` costruiscono, provano e scansionano l'immagine ma non la pubblicano, con un avviso, e restano verdi. Lo + stesso token carica gli artefatti nel pacchetto `febe-ci`: senza, un avviso per ogni passo che li caricherebbe, e + nessun artefatto (il lavoro resta verde). +- `gitea.token` (il gettone del lavoro, di Gitea): solo per leggere i sorgenti e la cima di `main`, nell'ambiente di git + e mai su disco. - `REGISTRY` (variabile, facoltativa): il registro come lo raggiunge il runner (`192.168.30.23:3000`); se manca si usa l'host dell'indirizzo del server Gitea. -- Le credenziali vanno nella configurazione del client Docker del lavoro, mai nel demone, e si tolgono alla fine. +- Le credenziali del registro vivono solo in una configurazione del client Docker fatta per la pubblicazione + (`DOCKER_CONFIG` in `${RUNNER_TEMP}/febe-docker-`, con i plugin, i contesti e il contesto corrente di + quella del runner), scritta da `costruisci-immagine.sh pubblica` con permessi 600 e tolta alla fine del passo e + dalla pulizia del lavoro; mai nel demone, mai nella configurazione del runner. Nessun flusso stampa segreti; `PipelineTests` lo controlla a ogni esecuzione. - I segreti sono leggibili da qualunque flusso di questo repository, su qualunque ramo: chi può fare push può leggerli. Per questo il permesso di scrittura sul repository resta ad Alberto e agli account di cui si fida. @@ -186,12 +212,12 @@ quell'immagine ha più nomi, `image prune -a` le toglie quelli in più (vedi «C |---|---| | alla fine di ogni lavoro «immagine» (verifica e rilascio), sempre | il contenitore di prova con i suoi volumi anonimi, l'immagine provata, il builder buildx dell'esecuzione con la sua cache, l'archivio dell'immagine, le credenziali del registro; poi, di tutti i progetti, le immagini senza nome che nessun contenitore usa e la cache di costruzione penzolante del demone, cioè quella che nessuna immagine condivide, non usata da 24 ore (`pulizia-docker.sh penzolanti`). Un errore qui è solo un avviso: il lavoro non diventa rosso | | all'inizio di ogni lavoro «immagine» | i resti di esecuzioni interrotte più vecchi di 90 minuti (un lavoro dura al massimo 60 minuti): contenitori di prova **fermi**, immagini `febe-ci:`, builder; e ciò che ha lasciato un tentativo precedente della stessa esecuzione | -| ogni lunedì alle 4:17 e a mano (`pulizia.yml`, `pulizia-docker.sh completa`) | gli stessi resti e l'immagine `febe:ci` del vecchio flusso; i resti di act_runner; **le immagini che nessun contenitore usa create più di 24 ore fa**, di tutti i progetti, anche col nome del registro; la cache di costruzione del demone non usata da più di 24 ore; con il segreto `REGISTRY_TOKEN`, sul registro le `:sha-` oltre le 10 più recenti. Prima e dopo `docker system df`, alla fine un riepilogo di che cosa è andato via | -| mai | `docker system prune`, `container prune`, `volume prune`, `network prune`; un contenitore, un volume o una rete che non sia della CI: un Febe vero, anche se porta le etichette `febe.ci.*`, le applicazioni di Unraid, i volumi con i dati, `act-toolcache`; un contenitore di prova ancora acceso di un'altra esecuzione (si segnala con un avviso e il comando per toglierlo: il flusso del lunedì diventa rosso); un'immagine usata da un contenitore, anche fermo (i suoi nomi in più sì: vedi sotto); `image prune -a` e `builder prune -a` senza il filtro delle 24 ore; sul registro `:main`, `:latest` e le versioni `X.Y.Z` | +| ogni lunedì alle 4:17 e a mano (`pulizia.yml`, `pulizia-docker.sh completa`) | gli stessi resti e l'immagine `febe:ci` del vecchio flusso; i resti di act_runner; **le immagini che nessun contenitore usa create più di 24 ore fa**, di tutti i progetti, anche col nome del registro; la cache di costruzione del demone non usata da più di 24 ore; con il segreto `REGISTRY_TOKEN`, sul registro le `:sha-` oltre le 10 più recenti e, del pacchetto generico `febe-ci`, le versioni `-ci.` e `-rilascio.` create più di 14 giorni prima (gli artefatti scaduti). Prima e dopo `docker system df`, alla fine un riepilogo di che cosa è andato via | +| mai | `docker system prune`, `container prune`, `volume prune`, `network prune`; un contenitore, un volume o una rete che non sia della CI: un Febe vero, anche se porta le etichette `febe.ci.*`, le applicazioni di Unraid, i volumi con i dati, `act-toolcache`; un contenitore di prova ancora acceso di un'altra esecuzione (si segnala con un avviso e il comando per toglierlo: il flusso del lunedì diventa rosso); un'immagine usata da un contenitore, anche fermo (i suoi nomi in più sì: vedi sotto); `image prune -a` e `builder prune -a` senza il filtro delle 24 ore; sul registro `:main`, `:latest` e le versioni `X.Y.Z`, e ogni pacchetto che non sia `febe` o `febe-ci`; in `febe-ci` una versione di un'altra forma o senza una data leggibile con il fuso | Che cosa costa: -- le immagini di base che fra un lavoro e l'altro nessun contenitore usa (`node:24-trixie` del lavoro «prove», +- le immagini di base che fra un lavoro e l'altro nessun contenitore usa (`debian:trixie` del lavoro «prove», `moby/buildkit` dei builder, quelle dei lavori degli altri progetti) si riscaricano alla prima esecuzione che le chiede dopo il lunedì: qualche minuto e qualche centinaio di MB in più, una volta. L'immagine dei lavori (`ubuntu-latest`) resta, perché durante la pulizia la usa il lavoro stesso; @@ -220,7 +246,7 @@ Che cosa costa: **Prova senza togliere nulla.** Actions ▸ pulizia ▸ Esegui, con «Solo prova» spuntato: il registro del lavoro elenca che cosa toglierebbe (le immagini con dimensione ed età, i nomi in più delle immagini in uso, la cache di costruzione, i -resti della CI di Febe e di act_runner, le `:sha-` del registro) e non toglie nulla: solo comandi che leggono, e sul +resti della CI di Febe e di act_runner, le `:sha-` e gli artefatti scaduti del registro) e non toglie nulla: solo comandi che leggono, e sul registro solo GET. Si lancia prima della prima pulizia vera e dopo ogni cambio dello script. Dal server, nella cartella del repository: `bash .gitea/scripts/pulizia-docker.sh completa --prova` (il registro solo con `REGISTRY_TOKEN`, `GITEA_API` e @@ -243,21 +269,21 @@ lavoro. Gitea dalle impostazioni dell'utente) e se ne crea uno nuovo: toglierlo dalla storia non basta, perché qualcuno può averlo già. Solo dopo, se serve, si riscrive la storia, d'accordo con Alberto. Un falso allarme (un dato di prova finto, già controllato) si toglie aggiungendo la sua impronta («Fingerprint», nel registro del lavoro o nel - rapporto `rapporto-gitleaks`) a `.gitleaksignore`, con un commento sulla riga sopra: che cos'è, chi l'ha + rapporto `gitleaks.json` del pacchetto `febe-ci`) a `.gitleaksignore`, con un commento sulla riga sopra: che cos'è, chi l'ha controllato, quando. Mai disattivare una regola. - **Trivy** (lavoro `immagine`, anche nel rilascio). Una vulnerabilità CRITICAL con correzione disponibile ferma il lavoro e l'immagine non si pubblica. Che cosa fare: per un pacchetto di Debian di solito basta rilanciare (il Dockerfile applica gli aggiornamenti della distribuzione); per una dipendenza .NET si aggiorna la sua versione in `Directory.Packages.props` (una dipendenza nuova va chiesta ad Alberto); per il runtime .NET si ricostruisce con l'SDK aggiornato. Le HIGH, e le CRITICAL ancora senza correzione, non fermano nulla ma si guardano nel rapporto - `sicurezza-immagine` (`trivy.json`) e, se riguardano ciò che Febe usa, diventano una segnalazione. Un'eccezione si + `trivy.json` del pacchetto `febe-ci` e, se riguardano ciò che Febe usa, diventano una segnalazione. Un'eccezione si scrive solo in `.trivyignore`, alla radice: l'identificativo con una scadenza (`CVE-AAAA-NNNN exp:AAAA-MM-GG`, al massimo 90 giorni) e, sulla riga sopra, il motivo e chi l'ha deciso. - Strumenti: gitleaks e Trivy sono gli unici strumenti esterni ammessi nella CI, approvati da Alberto, e girano solo lì (regola 13 della specifica, decisioni del 18 novembre 2026). Nel contenitore delle prove restano solo Chromium, i - pacchetti Debian che gli servono e Xvfb. ffmpeg è già uscito, con la tappa C3; NSIS (al suo posto l'installatore scritto in - casa) e Node (al posto delle azioni che lo vogliono, passi di shell con git e curl verso l'API di Gitea) escono con - la tappa C6. Si aggiornano cambiando versione e impronta SHA-256 in `.gitea/scripts/strumento.sh`, in una richiesta di + pacchetti Debian che gli servono e Xvfb. ffmpeg è già uscito, con la tappa C3; con la tappa C6 sono usciti anche il + programma di installazione di terzi (al suo posto quello scritto in casa, `src/Febe.Installer`) e Node (al posto + delle azioni che lo vogliono, passi di shell con git e curl verso l'API di Gitea). Si aggiornano cambiando versione e impronta SHA-256 in `.gitea/scripts/strumento.sh`, in una richiesta di unione con una riga in `docs/decisioni.md`, preferendo versioni uscite da almeno due settimane. ## Rilasci @@ -265,7 +291,8 @@ lavoro. 1. In un ramo `rilascio/X.Y.Z`: `` in `Directory.Build.props`, la sezione `## X.Y.Z` di `CHANGELOG.md` (è il testo delle note della release), `docs/stato.md`. Richiesta di unione, verifica verde, unione. 2. Sul commit di unione in `main`: `git tag -a vX.Y.Z -m "Febe X.Y.Z"` e `git push origin vX.Y.Z`. -3. `rilascio.yml` controlla che il tag coincida con ``, rifà le prove, costruisce installatore e zip, +3. `rilascio.yml` controlla che il tag coincida con ``, rifà le prove come la verifica (in `debian:trixie`, con + Chromium e Xvfb veri, nessuna saltata), costruisce installatore e zip, costruisce, prova e scansiona l'immagine, la pubblica come `:X.Y.Z` (e `:latest` se la versione non ha trattini) e crea la release con installatore, zip, modello di Unraid e archivio per Compose. 4. Un'anteprima è `vX.Y.Z-rc.N`: stessa strada, `:latest` non si sposta e la release è segnata come anteprima (come @@ -285,10 +312,19 @@ lavoro. Qui non ci sono runner né demone Docker: i flussi sono stati controllati come testo (struttura, espressioni, `bash -n` di ogni blocco `run`), gli script con un client Docker finto. Restano da vedere alla prima esecuzione: il contenitore -`node:24-trixie` con le azioni dentro (fino alla tappa C6); le prove con il browser nel contenitore (nessuna saltata); `upload-artifact@v3` -con `retention-days`; la concorrenza; il builder buildx con il nome dell'esecuzione; la prova del contenitore senza -rete fino a «healthy»; il download e la scansione di Trivy (e se trova CRITICAL da correggere); gitleaks sulla storia; -la pubblicazione su `main` con il segreto. +`debian:trixie` con git e curl installati nel primo passo; le prove con il browser nel contenitore (nessuna saltata); la +concorrenza; il builder buildx con il nome dell'esecuzione; la prova del contenitore senza rete fino a «healthy»; il +download e la scansione di Trivy (e se trova CRITICAL da correggere); gitleaks sulla storia; la pubblicazione su `main` +con il segreto. + +Della CI senza azioni del 18 novembre 2026 (script provati con file di prova e un curl finto, mai contro la rete) +restano da vedere: che Gitea accetti il gettone del lavoro come password di base per `git fetch` e dia il commit per +identificativo (se no, il passo «Sorgenti» lo dice e prende il ramo con tutta la storia); che act_runner monti +`act-toolcache` anche nel contenitore delle prove (`RUNNER_TOOL_CACHE`; senza, l'SDK si riscarica a ogni lavoro); +il formato vero di `releases.json` di Microsoft per `dotnet-sdk.awk` (provato solo su metadati scritti nella prova); +`docker buildx create` con `--buildkitd-config` sul client Docker del runner; il caricamento nel pacchetto generico +`febe-ci` (PUT con risposta 201, 409 per un file già caricato) e la sua pulizia dopo 14 giorni; `mawk` (le prove e i +controlli locali usano gawk, anche in modo `--posix`). Della pulizia del 21 ottobre 2026 (script e API provati con un client Docker e un curl finti) restano da vedere: la casella «Solo prova» di Gitea che arriva al lavoro come «true»; i nomi che questo act_runner dà ai suoi contenitori, diff --git a/docs/schermate/differenze.md b/docs/schermate/differenze.md index 7b91d8a..17e4174 100644 --- a/docs/schermate/differenze.md +++ b/docs/schermate/differenze.md @@ -138,3 +138,20 @@ schermata del motore fermo si prende per prima, perché «Riprendi» resta spent - **Finestra stretta e telefono.** A 860 px il menu delle impostazioni diventa una fila di schede sopra il contenuto e le colonne laterali (passi del collegamento, doppioni dell'importazione) vanno sotto. Al telefono la tabella delle cartelle dell'importazione diventa un elenco di schede e «Esporta l'elenco in CSV» resta solo come icona. + +### Carattere e icone (dal 18 novembre 2026) + +Mockup e schermate di questa cartella sono stati presi con il carattere Archivo e le icone Lucide, che dal 18 novembre +2026 non sono più nel programma (niente componenti di terzi, `docs/decisioni.md`). Restano il riferimento per +disposizione, misure e colori, non più per la forma delle lettere e dei segni: + +- **Carattere.** L'interfaccia usa il carattere del sistema, con la pila del token `--carattere` + (`system-ui,-apple-system,"Segoe UI",Roboto,sans-serif`, appendice B della specifica): San Francisco su Apple, Segoe + UI su Windows, Roboto su Android, e su Linux il carattere del desktop o il `sans-serif` che sceglie fontconfig. + Lettere, larghezze delle + righe e a capo possono differire un poco da quelli disegnati; i dati (date, numeri, nomi di file) sono più stretti + solo dove il sistema ha una variante stretta, ma restano con cifre tabellari. +- **Icone.** Le icone sono disegnate per Febe sulla stessa griglia di 24 con lo stesso spessore: stesso posto, stessa + misura e stesso significato, ma il disegno è diverso da quello dei mockup (per esempio l'ingranaggio, la stella, le + frecce circolari). +- Le schermate non sono state rifatte: si rifanno alla prossima tornata (`dotnet run --project tools/Febe.Schermate`). diff --git a/docs/windows.md b/docs/windows.md index aa298d1..85dd089 100644 --- a/docs/windows.md +++ b/docs/windows.md @@ -46,7 +46,7 @@ un'applicazione per Windows 10 e 11. La finestra di Febe mostra l'interfaccia; i dove si vuole e si apre, senza installazione. Anche la versione portabile tiene i dati in `%LOCALAPPDATA%\Febe` e la libreria in `Immagini\Febe`, finché non scegli altre cartelle. -`Febe.exe` è un file solo (circa 86 MB, misurato di nuovo senza SkiaSharp): contiene il runtime .NET, l'interfaccia +`Febe.exe` è un file solo (circa 86 MB, misurato di nuovo con i codec di casa): contiene il runtime .NET, l'interfaccia e le librerie native (SQLite, WebView2Loader). Le immagini le leggono, le scrivono e le disegnano codec di Febe scritti in C#. Al primo avvio Windows estrae le librerie native in `%TEMP%\.net\Febe`: è normale. @@ -217,7 +217,7 @@ servono più, cancellale tu — la cartella dei dati contiene la sessione di Ins ## Costruire il programma di installazione -Da Linux (CI, rilascio) o da Windows con bash, con il .NET SDK 10 e NSIS 3 (`apt-get install nsis`): +Da Linux (CI, rilascio) o da Windows con bash, con il solo .NET SDK 10: nessun altro programma. ```sh installer/costruisci.sh # versione di Directory.Build.props @@ -225,10 +225,33 @@ installer/costruisci.sh 0.2.0 # oppure una versione esplicita ``` Il risultato è in `out/`: `Febe-Setup-.exe` e `Febe--portabile.zip`, ognuno sotto i 100 MB -(limite degli allegati di Gitea; con la versione 0.1.0: Febe.exe 86 MB, installazione 80 MB, zip 81 MB; senza -SkiaSharp, il 18 novembre 2026, Febe.exe 85,6 MB). Lo script controlla che la pubblicazione abbia prodotto un solo -file e che nulla superi il limite. Lo script NSIS è -`installer/febe.nsi` (Unicode, testi in italiano, versione passata con `/DVERSION=…`). +(limite degli allegati di Gitea; con la versione 0.1.2: Febe.exe 86,5 MB, installazione 91,4 MB, zip 80,8 MB). Lo +script controlla che le pubblicazioni abbiano prodotto un solo file ciascuna e che nulla superi il limite. + +Il programma di installazione è nostro, dal 18 novembre 2026: `src/Febe.Installer`, solo la libreria di base di .NET. + +- **Com'è fatto.** `Febe.Installer.exe` è pubblicato per win-x64 autosufficiente, in un file solo, ridotto con il + trimming e compresso (circa 11 MB). Lo stesso progetto, compilato per il sistema che costruisce, è lo strumento del + pacchetto: `--impacchetta` gli appende `Febe.exe` compresso con Brotli, la versione e un piè di pagina di 80 byte con + la lunghezza e lo SHA-256 di `Febe.exe`; `--verifica` lo rilegge come farà l'installazione e confronta il risultato + con `Febe.exe` byte per byte; `--zip` scrive lo zip portabile. Il programma di un file solo trova le sue parti da un + indirizzo scritto dentro di sé, non dalla fine del file: ciò che segue non lo disturba. +- **Che cosa fa** (come prima): installazione per l'utente, senza permessi di amministratore (il manifesto dice + `asInvoker`: Windows non chiede di elevare un programma con «Setup» nel nome), in `%LOCALAPPDATA%\Programs\Febe`; + `Febe.exe` scritto accanto e poi rinominato, e controllato con lo SHA-256 (un pacchetto rovinato non installa nulla); + «Disinstalla Febe.exe» (lo stesso programma, senza `Febe.exe`); collegamento nel menu Start e, se scelto, sul + desktop, scritti con l'oggetto ShellLink di Windows; la voce in App installate sotto `HKEY_CURRENT_USER`; il + controllo di WebView2; un'installazione sopra un'altra sostituisce il programma e lascia tutto il resto. Con Febe + aperto si ferma e chiede di chiuderlo. Le pagine sono le finestre di dialogo di Windows (TaskDialog). +- **Disinstallazione.** «Disinstalla Febe.exe» si copia in `%TEMP%` (un programma non può cancellare il proprio file), + avvia la copia e finisce; la copia toglie il programma, i collegamenti, la voce, l'avvio con il computer e le + librerie estratte in `%TEMP%\.net\Febe`, **mai** la cartella dei dati né la libreria, e dice dove sono. La copia + resta in `%TEMP%` fino al prossimo avvio dell'installazione o della disinstallazione, che la toglie. +- **Senza domande**: `Febe-Setup-.exe /S` (collegamento sul desktop sì, Febe non si avvia, con Febe aperto + esce con il codice 2), `/D=` per un'altra cartella (ultima opzione, anche con spazi); + `"Disinstalla Febe.exe" /S` (esce subito con 0: il lavoro lo fa la sua copia in `%TEMP%`). Codici d'uscita: 0 fatto, 1 annullato, 2 non riuscito (con `/S` il motivo va + sull'errore standard). `/PROVA=` serve alle prove: menu Start, desktop, `%TEMP%` e chiavi del registro + (sotto `HKEY_CURRENT_USER\Software\FebeProve\`) stanno tutti lì dentro. L'icona `src/Febe.Desktop/Febe.ico` (16, 24, 32, 48, 64, 128 e 256 pixel) è disegnata dal marchio dell'appendice C con il disegnatore di casa (`Febe.Core.Drawing`) e scritta a mano: per rigenerarla dopo un cambio del marchio, @@ -258,6 +281,7 @@ farlo ripartire. Tutte insieme durano due o tre minuti, quasi tutti della sessio | `WebView2LifecycleTests` | Un avvio che fallisce davvero si riprova e poi va; primo piano e fuori vista con il permesso di guida; «Scollega»; «Scollega» mentre il primo avvio aspetta di riprovare (un solo browser nella finestra, il «Scollega» dopo riesce subito); «Esci» mentre l'avvio non si completa (non lo aspetta); ripartenza dopo l'arresto del processo; «composizione» di S2 | | `WebView2CdpTests` | S1: i comandi dell'elenco su WebView2 contro il sito di prova, con la finestra fuori vista, e i comandi vietati rifiutati | | `WebView2CollectionTests` | Una sessione vera della composizione (`FebeApp` con `DesktopPlatform`) su WebView2: i file arrivano nella libreria | +| `InstallerTests` | Il programma di installazione pubblicato come nella CI (un file solo, ridotto) e impacchettato con un finto `Febe.exe`: manifesto e risorsa di versione; installazione senza domande in una cartella della prova (`/PROVA=`), collegamenti riletti con ShellLink, voce in App installate; seconda installazione sopra la prima con i dati intatti; rifiuto con Febe aperto; disinstallazione con la `QuietUninstallString`, che toglie solo ciò che è suo. La prima pagina si apre e «Annulla» non installa nulla. Non avvia mai Febe | | `WebView2ConnectionTests` | Il collegamento dal servizio vero della composizione: «Accedi a Instagram» porta in primo piano la finestra con la pagina di accesso (del sito di prova), «Ho finito» trova la sessione e la rimette fuori vista, «Scollega» cancella il profilo e il motore riparte | Quello che di `WebView2CdpSession` non chiede Windows (per esempio: un errore di chi ascolta la ripartenza non disfa diff --git a/installer/costruisci.sh b/installer/costruisci.sh index 673014b..f83faa9 100755 --- a/installer/costruisci.sh +++ b/installer/costruisci.sh @@ -3,8 +3,10 @@ # # installer/costruisci.sh [versione] # -# Gira su Linux (CI e rilascio) come su Windows con bash: servono il .NET SDK 10 e makensis (NSIS 3, «apt-get install -# nsis»). La versione, se non la si passa, è quella di Directory.Build.props (il tag deve coincidere). +# Gira su Linux (CI e rilascio) come su Windows con bash: serve solo il .NET SDK 10. Nessun altro programma: il +# programma di installazione è nostro (src/Febe.Installer) e lo stesso progetto, compilato per il sistema che lo +# costruisce, fa il pacchetto, lo controlla e scrive lo zip. La versione, se non la si passa, è quella di +# Directory.Build.props (il tag deve coincidere). # Risultato in out/: # Febe-Setup-.exe installazione per l'utente, senza permessi di amministratore # Febe--portabile.zip Febe.exe e LEGGIMI.txt, da copiare dove si vuole @@ -20,16 +22,13 @@ if [[ ! "$versione" =~ ^[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$ ]]; then exit 2 fi -# La versione dei file di Windows vuole quattro numeri. -numeri="${versione%%[-+]*}" -versione_file="${numeri}.0" - command -v dotnet >/dev/null || { echo "Manca il .NET SDK (dotnet)." >&2; exit 2; } -command -v makensis >/dev/null || { echo "Manca makensis: installa NSIS (apt-get install nsis)." >&2; exit 2; } uscita="$radice/out" pubblicazione="$uscita/pubblicazione" -rm -rf "$pubblicazione" +installatore="$uscita/installatore" +strumento="$uscita/strumento-installatore" +rm -rf "$pubblicazione" "$installatore" "$strumento" mkdir -p "$pubblicazione" echo "== Pubblicazione di Febe.exe $versione (win-x64, un file solo)" @@ -38,19 +37,31 @@ dotnet publish src/Febe.Desktop/Febe.Desktop.csproj -c Release -r win-x64 --self -p:Version="$versione" -nologo -o "$pubblicazione" # Un file solo: niente accanto all'eseguibile. -altri="$(find "$pubblicazione" -mindepth 1 ! -name Febe.exe)" -if [[ -n "$altri" ]]; then - echo "La pubblicazione ha prodotto altri file oltre a Febe.exe:" >&2 - echo "$altri" >&2 - exit 1 -fi +solo_un_file() { + local cartella="$1" nome="$2" altri + altri="$(find "$cartella" -mindepth 1 ! -name "$nome")" + if [[ -n "$altri" ]]; then + echo "La pubblicazione ha prodotto altri file oltre a $nome:" >&2 + echo "$altri" >&2 + exit 1 + fi +} +solo_un_file "$pubblicazione" Febe.exe + +echo "== Programma di installazione (win-x64, un file solo, ridotto)" +# Le proprietà della pubblicazione (autosufficiente, un file solo, trimming, compressione) sono nel progetto. +dotnet publish src/Febe.Installer/Febe.Installer.csproj -c Release -r win-x64 \ + -p:Version="$versione" -nologo -o "$installatore" +solo_un_file "$installatore" Febe.Installer.exe + +echo "== Strumento del pacchetto (per questo sistema)" +dotnet build src/Febe.Installer/Febe.Installer.csproj -c Release -p:Version="$versione" -nologo -o "$strumento" +pacchetto() { dotnet "$strumento/Febe.Installer.dll" "$@"; } -echo "== Programma di installazione" setup="$uscita/Febe-Setup-$versione.exe" rm -f "$setup" -(cd installer && makensis -V2 -INPUTCHARSET UTF8 \ - -DVERSION="$versione" -DVERSIONE_FILE="$versione_file" \ - -DSORGENTE="$pubblicazione" -DUSCITA="$setup" febe.nsi) +pacchetto --impacchetta "$installatore/Febe.Installer.exe" "$pubblicazione/Febe.exe" "$versione" "$setup" +pacchetto --verifica "$setup" "$pubblicazione/Febe.exe" echo "== Zip portabile" zip_portabile="$uscita/Febe-$versione-portabile.zip" @@ -73,17 +84,7 @@ Non usare insieme Febe per Windows e il contenitore Docker con lo stesso account Guida: https://gitea.encke-hake.ts.net/Alby96/Febe/wiki TESTO sed -i 's/$/\r/' "$leggimi" -if command -v zip >/dev/null; then - (cd "$pubblicazione" && zip -q -9 "$zip_portabile" Febe.exe LEGGIMI.txt) -else - python3 - "$zip_portabile" "$pubblicazione" <<'PY' -import os, sys, zipfile -target, folder = sys.argv[1], sys.argv[2] -with zipfile.ZipFile(target, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as archive: - for name in ("Febe.exe", "LEGGIMI.txt"): - archive.write(os.path.join(folder, name), name) -PY -fi +pacchetto --zip "$zip_portabile" "$pubblicazione/Febe.exe" "$leggimi" rm -f "$leggimi" limite=$((100 * 1024 * 1024)) diff --git a/installer/febe.nsi b/installer/febe.nsi deleted file mode 100644 index b9e0d2a..0000000 --- a/installer/febe.nsi +++ /dev/null @@ -1,232 +0,0 @@ -; Febe — programma di installazione per Windows (specifica §12, domanda 6 di §16). -; -; makensis -INPUTCHARSET UTF8 -DVERSION=0.1.0 -DVERSIONE_FILE=0.1.0.0 \ -; -DSORGENTE=out/pubblicazione -DUSCITA=out/Febe-Setup-0.1.0.exe installer/febe.nsi -; -; Di solito lo lancia installer/costruisci.sh, che prima pubblica Febe.exe in un file solo. -; -; - Installazione per l'utente, senza permessi di amministratore, in %LOCALAPPDATA%\Programs\Febe. -; - Collegamento nel menu Start; collegamento sul desktop facoltativo. -; - Disinstallazione registrata in HKCU (Programmi e funzionalità / App installate). -; - La disinstallazione non tocca MAI la cartella dei dati né la libreria e non chiede nulla su di loro: dice dove sono. -; - Controllo del runtime WebView2 di Microsoft, con il collegamento alla pagina ufficiale se manca. - -Unicode true -ManifestDPIAware true -RequestExecutionLevel user -SetCompressor /SOLID lzma - -!ifndef VERSION - !error "Manca la versione: passala con /DVERSION=x.y.z (installer/costruisci.sh la legge da Directory.Build.props)." -!endif -!ifndef SORGENTE - !define SORGENTE "../out/pubblicazione" -!endif -!ifndef USCITA - !define USCITA "../out/Febe-Setup-${VERSION}.exe" -!endif - -!define NOME "Febe" -!define EDITORE "Alberto Balbo" -!define ESEGUIBILE "Febe.exe" -!define DISINSTALLA "Disinstalla Febe.exe" -!define CHIAVE_DISINSTALLA "Software\Microsoft\Windows\CurrentVersion\Uninstall\Febe" -!define CHIAVE_FEBE "Software\Febe" -!define CHIAVE_AVVIO "Software\Microsoft\Windows\CurrentVersion\Run" -!define WEBVIEW2_GUID "{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}" -!define WEBVIEW2_PAGINA "https://developer.microsoft.com/microsoft-edge/webview2/" -!define SITO "https://gitea.encke-hake.ts.net/Alby96/Febe" - -Name "${NOME}" -OutFile "${USCITA}" -InstallDir "$LOCALAPPDATA\Programs\Febe" -BrandingText "${NOME} ${VERSION}" -ShowInstDetails show -ShowUninstDetails show - -!ifdef VERSIONE_FILE - VIProductVersion "${VERSIONE_FILE}" - VIAddVersionKey /LANG=1040 "ProductName" "${NOME}" - VIAddVersionKey /LANG=1040 "ProductVersion" "${VERSION}" - VIAddVersionKey /LANG=1040 "CompanyName" "${EDITORE}" - VIAddVersionKey /LANG=1040 "LegalCopyright" "${EDITORE}" - VIAddVersionKey /LANG=1040 "FileDescription" "Installazione di ${NOME}" - VIAddVersionKey /LANG=1040 "FileVersion" "${VERSION}" -!endif - -!include "MUI2.nsh" -!include "LogicLib.nsh" -!include "FileFunc.nsh" - -!define MUI_ICON "../src/Febe.Desktop/Febe.ico" -!define MUI_UNICON "../src/Febe.Desktop/Febe.ico" -!define MUI_ABORTWARNING - -; ------------------------------------------------------------------------------------------------ pagine -!define MUI_WELCOMEPAGE_TITLE "Installazione di Febe ${VERSION}" -!define MUI_WELCOMEPAGE_TEXT "Febe è l'archivio personale di foto, video e storie da Instagram.$\r$\n$\r$\nVerrà installato solo per te, in $LOCALAPPDATA\Programs\Febe: non servono permessi di amministratore.$\r$\n$\r$\nI dati di Febe (database e sessione del browser) andranno in $LOCALAPPDATA\Febe, le foto e i video nella cartella Immagini\Febe; le cartelle si possono cambiare dalle Impostazioni." -!insertmacro MUI_PAGE_WELCOME -!insertmacro MUI_PAGE_COMPONENTS -!insertmacro MUI_PAGE_INSTFILES -!define MUI_FINISHPAGE_TITLE "Febe è installato" -!define MUI_FINISHPAGE_TEXT "Febe si apre in una sua finestra e resta attivo nell'area di notifica, accanto all'orologio.$\r$\n$\r$\nPer collegarlo a Instagram: Impostazioni ▸ Collegamento. Non usare insieme Febe per Windows e il contenitore Docker con lo stesso account." -!define MUI_FINISHPAGE_RUN "$INSTDIR\${ESEGUIBILE}" -!define MUI_FINISHPAGE_RUN_TEXT "Apri Febe adesso" -!insertmacro MUI_PAGE_FINISH - -!define MUI_UNCONFIRMPAGE_TEXT_TOP "Il programma Febe verrà tolto da questo computer. I tuoi dati restano dove sono: la disinstallazione non cancella né la cartella dei dati né la libreria con le foto e i video." -!insertmacro MUI_UNPAGE_CONFIRM -!insertmacro MUI_UNPAGE_INSTFILES -!define MUI_FINISHPAGE_TITLE "Febe è stato disinstallato" -!define MUI_FINISHPAGE_TEXT "I dati di Febe non sono stati toccati:$\r$\n$\r$\n- cartella dei dati: $R8$\r$\n- libreria: $R9, o la cartella scelta nelle Impostazioni.$\r$\n$\r$\nLa cartella dei dati contiene la sessione di Instagram: se non ti serve più, cancellala tu." -!insertmacro MUI_UNPAGE_FINISH - -!insertmacro MUI_LANGUAGE "Italian" - -LangString DESC_Programma ${LANG_ITALIAN} "Febe.exe, il menu Start e la voce in App installate." -LangString DESC_Desktop ${LANG_ITALIAN} "Un collegamento a Febe sul desktop." - -; ------------------------------------------------------------------------------------------------ funzioni -; Febe in esecuzione tiene aperto Febe.exe: non si può sovrascrivere né cancellare. -!macro FebeChiuso UN -Function ${UN}FebeChiuso - IfFileExists "$INSTDIR\${ESEGUIBILE}" 0 fatto - riprova: - ClearErrors - FileOpen $0 "$INSTDIR\${ESEGUIBILE}" a - ${If} ${Errors} - MessageBox MB_RETRYCANCEL|MB_ICONEXCLAMATION "Febe è aperto. Chiudilo dall'area di notifica (clic destro sull'icona ▸ Esci), poi premi Riprova." /SD IDCANCEL IDRETRY riprova - Abort - ${EndIf} - FileClose $0 - fatto: -FunctionEnd -!macroend -!insertmacro FebeChiuso "" -!insertmacro FebeChiuso "un." - -; Il runtime WebView2 (Evergreen) è installato per tutto il computer o solo per l'utente: «pv» è la sua versione. -Function WebView2Presente - StrCpy $1 "" - ReadRegStr $1 HKLM "SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\${WEBVIEW2_GUID}" "pv" - ${If} $1 == "" - ${OrIf} $1 == "0.0.0.0" - ReadRegStr $1 HKLM "SOFTWARE\Microsoft\EdgeUpdate\Clients\${WEBVIEW2_GUID}" "pv" - ${EndIf} - ${If} $1 == "" - ${OrIf} $1 == "0.0.0.0" - ReadRegStr $1 HKCU "Software\Microsoft\EdgeUpdate\Clients\${WEBVIEW2_GUID}" "pv" - ${EndIf} - ${If} $1 == "0.0.0.0" - StrCpy $1 "" - ${EndIf} - Push $1 -FunctionEnd - -; ------------------------------------------------------------------------------------------------ installazione -Section "Febe" SEC_PROGRAMMA - SectionIn RO - Call FebeChiuso - SetOutPath "$INSTDIR" - File "${SORGENTE}/${ESEGUIBILE}" - WriteUninstaller "$INSTDIR\${DISINSTALLA}" - - ; Menu Start (dell'utente). - SetShellVarContext current - CreateShortCut "$SMPROGRAMS\Febe.lnk" "$INSTDIR\${ESEGUIBILE}" "" "$INSTDIR\${ESEGUIBILE}" 0 SW_SHOWNORMAL "" "Archivio personale di foto, video e storie da Instagram" - - ; App installate (Programmi e funzionalità), per l'utente. - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "DisplayName" "${NOME}" - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "DisplayVersion" "${VERSION}" - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "Publisher" "${EDITORE}" - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "DisplayIcon" "$INSTDIR\${ESEGUIBILE},0" - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "InstallLocation" "$INSTDIR" - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "UninstallString" '"$INSTDIR\${DISINSTALLA}"' - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "QuietUninstallString" '"$INSTDIR\${DISINSTALLA}" /S' - WriteRegStr HKCU "${CHIAVE_DISINSTALLA}" "URLInfoAbout" "${SITO}" - WriteRegDWORD HKCU "${CHIAVE_DISINSTALLA}" "NoModify" 1 - WriteRegDWORD HKCU "${CHIAVE_DISINSTALLA}" "NoRepair" 1 - ${GetSize} "$INSTDIR" "/S=0K" $0 $1 $2 - WriteRegDWORD HKCU "${CHIAVE_DISINSTALLA}" "EstimatedSize" "$0" - - ; WebView2: senza, Febe non può mostrare nulla. Lo dice anche Febe al primo avvio. - Call WebView2Presente - Pop $1 - ${If} $1 == "" - DetailPrint "Runtime WebView2 di Microsoft: non trovato." - MessageBox MB_YESNO|MB_ICONINFORMATION "Febe ha bisogno del runtime WebView2 di Microsoft, che su questo computer non c'è (Windows 11 e quasi tutti i Windows 10 lo hanno già).$\r$\n$\r$\nSi installa gratis dalla pagina ufficiale di Microsoft, senza permessi di amministratore. Vuoi aprirla adesso?" /SD IDNO IDNO fine_webview2 - ExecShell "open" "${WEBVIEW2_PAGINA}" - fine_webview2: - ${Else} - DetailPrint "Runtime WebView2 di Microsoft: $1." - ${EndIf} -SectionEnd - -Section "Collegamento sul desktop" SEC_DESKTOP - SetShellVarContext current - CreateShortCut "$DESKTOP\Febe.lnk" "$INSTDIR\${ESEGUIBILE}" "" "$INSTDIR\${ESEGUIBILE}" 0 SW_SHOWNORMAL "" "Archivio personale di foto, video e storie da Instagram" -SectionEnd - -!insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN - !insertmacro MUI_DESCRIPTION_TEXT ${SEC_PROGRAMMA} $(DESC_Programma) - !insertmacro MUI_DESCRIPTION_TEXT ${SEC_DESKTOP} $(DESC_Desktop) -!insertmacro MUI_FUNCTION_DESCRIPTION_END - -; ------------------------------------------------------------------------------------------------ disinstallazione -Function un.onInit - ; Dove sono i dati, per dirlo alla fine: la cartella scelta nelle Impostazioni o quella predefinita. - ReadRegStr $R8 HKCU "${CHIAVE_FEBE}" "CartellaDati" - ${If} $R8 == "" - StrCpy $R8 "$LOCALAPPDATA\Febe" - ${EndIf} - StrCpy $R9 "$PICTURES\Febe" -FunctionEnd - -; «Avvia con il computer» dei Febe avviati con --dati (un secondo account): valori «Febe-…» che avviano questo Febe.exe. -Function un.TogliAvviiConDati - StrCpy $3 '"$INSTDIR\${ESEGUIBILE}"' - StrLen $4 $3 - StrCpy $0 0 - ciclo: - ClearErrors - EnumRegValue $1 HKCU "${CHIAVE_AVVIO}" $0 - IfErrors fine - StrCmp $1 "" fine - StrCpy $2 $1 5 - ${If} $2 == "Febe-" - ReadRegStr $5 HKCU "${CHIAVE_AVVIO}" $1 - StrCpy $6 $5 $4 - ${If} $6 == $3 - DeleteRegValue HKCU "${CHIAVE_AVVIO}" $1 - ; Il valore successivo prende il posto di quello tolto: stesso indice. - Goto ciclo - ${EndIf} - ${EndIf} - IntOp $0 $0 + 1 - Goto ciclo - fine: -FunctionEnd - -Section "Uninstall" - Call un.FebeChiuso - SetShellVarContext current - - ; Solo i file del programma. MAI la cartella dei dati, MAI la libreria: non si chiede nulla su di loro. - Delete "$INSTDIR\${ESEGUIBILE}" - Delete "$INSTDIR\${DISINSTALLA}" - RMDir "$INSTDIR" - Delete "$SMPROGRAMS\Febe.lnk" - Delete "$DESKTOP\Febe.lnk" - - ; «Avvia Febe all'accensione del computer» punterebbe a un programma che non c'è più: il valore «Febe» e quelli - ; «Febe-…» dei Febe avviati con --dati. - DeleteRegValue HKCU "${CHIAVE_AVVIO}" "Febe" - Call un.TogliAvviiConDati - DeleteRegKey HKCU "${CHIAVE_DISINSTALLA}" - - ; Le librerie native che Febe.exe estrae da sé al primo avvio (non sono dati). - RMDir /r "$TEMP\.net\Febe" - - DetailPrint "I dati restano: cartella dei dati $R8; libreria $R9 (o quella scelta nelle Impostazioni)." - DetailPrint "La cartella dei dati contiene la sessione di Instagram: se non ti serve più, cancellala tu." -SectionEnd diff --git a/src/Febe.App/BrowserConnectionService.cs b/src/Febe.App/BrowserConnectionService.cs index 4e63058..ab14d3d 100644 --- a/src/Febe.App/BrowserConnectionService.cs +++ b/src/Febe.App/BrowserConnectionService.cs @@ -794,10 +794,14 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa return; } - // Besides this lease: the remote view, the browser window in front, «Scollega» in progress. + // Besides this lease: the remote view, the browser window in front, «Scollega» in progress. A view open + // again also cancels an earlier leave (a late «pageLeft» of a reloaded page, the old view that + // «Riprova» closed): only a view closing after this counts as leaving, so that a view ended later by + // the server (the browser stopped) waits for DrivingGrace, as a browser that is down is not leaving. if (_browser.UserDriving.Leases > 1) { _lastDrivingSign = _clock.Now; + _leftAt = null; } lastSign = _lastDrivingSign; @@ -867,10 +871,24 @@ public sealed class BrowserConnectionService : IConnectionService, IAsyncDisposa } } - // Cancelled when «Ho finito», «Annulla» or «Scollega» end the lease meanwhile: then they decide. + // Cancelled when «Ho finito», «Annulla» or «Scollega» end the lease meanwhile: then they decide. Leaving the page + // in Docker waits at most LetGoWait for another command of the connection, as closing the window does (§6.0), so + // that the engine is not held still: then the lease ends without the copy. + using var limit = CancellationTokenSource.CreateLinkedTokenSource(ct); + if (what == PageLeftText) + { + limit.CancelAfter(LetGoWait); + } + try { - await _commands.WaitAsync(ct).ConfigureAwait(false); + await _commands.WaitAsync(limit.Token).ConfigureAwait(false); + } + catch (OperationCanceledException) when (!ct.IsCancellationRequested && limit.IsCancellationRequested) + { + ForgetLetGoCopy(); + _log.Info("collegamento", $"{what}: sessione non copiata, un altro comando del collegamento era ancora in corso."); + return true; } catch (ObjectDisposedException) { diff --git a/src/Febe.Core/Codecs/Images/ImageFormat.cs b/src/Febe.Core/Codecs/Images/ImageFormat.cs index 1a8f2d2..feac852 100644 --- a/src/Febe.Core/Codecs/Images/ImageFormat.cs +++ b/src/Febe.Core/Codecs/Images/ImageFormat.cs @@ -23,7 +23,10 @@ public enum ImageFormat /// Recognises an image format from the first bytes of a file. public static class ImageFormatSniffer { - /// Bytes needs to tell every format apart; fewer are fine for most formats. + /// + /// Bytes needs to tell every format apart; fewer are fine for most formats. A HEIF whose brand + /// is only among the compatible brands needs the whole ftyp box. + /// public const int HeaderLength = 32; /// The format the bytes start with, or . @@ -72,6 +75,13 @@ public static class ImageFormatSniffer { return ImageFormat.Heif; } + + // Every file the HEIF decoder takes (mif2, MiHE, or a HEIF brand among the compatible ones) is a HEIF: + // the decoder is chosen from this answer, so a narrower list would leave such a HEIC without a picture. + if (Heif.HeifDecoder.Looks(header)) + { + return ImageFormat.Heif; + } } return ImageFormat.Unknown; diff --git a/src/Febe.Core/Codecs/Images/JpegDecoder.cs b/src/Febe.Core/Codecs/Images/JpegDecoder.cs index 31109a9..c6ea169 100644 --- a/src/Febe.Core/Codecs/Images/JpegDecoder.cs +++ b/src/Febe.Core/Codecs/Images/JpegDecoder.cs @@ -10,8 +10,10 @@ namespace Febe.Core.Codecs.Images; /// /// /// Strictness: a file whose entropy-coded data ends before the last MCU of a scan is damaged -/// (), as is a Huffman code the table does not have; a missing EOI after complete -/// scans, bytes after EOI and stray restart markers are accepted. Hierarchical files (SOF5-7, SOF13-15) are refused +/// (), as is a Huffman code the table does not have, and a file that ends before its +/// EOI is incomplete even after complete scans (spec §3: a progressive file cut between two scans is refused, not shown +/// at a lower quality); still reads the size of such a file. Bytes after EOI and stray restart +/// markers are accepted. Hierarchical files (SOF5-7, SOF13-15) are refused /// with . /// public static class JpegDecoder diff --git a/src/Febe.Core/Codecs/Images/JpegFile.cs b/src/Febe.Core/Codecs/Images/JpegFile.cs index 3f6e51d..a9d5698 100644 --- a/src/Febe.Core/Codecs/Images/JpegFile.cs +++ b/src/Febe.Core/Codecs/Images/JpegFile.cs @@ -288,6 +288,13 @@ internal sealed partial class JpegFile : IDisposable return; } + // Spec §3, §8.4: a JPEG that ends before its end marker is incomplete, even when its scans so far are complete + // (a progressive file cut between two scans would otherwise give a picture of lower quality). + if (!sawEoi) + { + throw new ImageDecodeException("JPEG troncato: manca il marcatore di fine (EOI)."); + } + if (_scanCount == 0) { throw new ImageDecodeException("JPEG senza dati d'immagine."); diff --git a/src/Febe.Core/Codecs/Images/PngDecoder.cs b/src/Febe.Core/Codecs/Images/PngDecoder.cs index 7a92baa..2fe7f0d 100644 --- a/src/Febe.Core/Codecs/Images/PngDecoder.cs +++ b/src/Febe.Core/Codecs/Images/PngDecoder.cs @@ -48,6 +48,7 @@ public static class PngDecoder { limits ??= ImageLimits.Default; var file = Parse(data, limits, readMetadata: false); + RequireEnd(file); return DecodePixels(data, file, limits, pooled); } @@ -56,13 +57,27 @@ public static class PngDecoder { limits ??= ImageLimits.Default; var file = Parse(data, limits, readMetadata: true); + RequireEnd(file); var image = DecodePixels(data, file, limits, pooled); info = file.ToInfo(); return image; } + /// + /// Spec §3, §8.4: a PNG that ends before its end marker is incomplete, even when its image data is complete, and is + /// not decoded; still reads its size. + /// + private static void RequireEnd(PngFile file) + { + if (!file.SeenEnd) + { + throw new ImageDecodeException("PNG troncato: manca il blocco di fine (IEND)."); + } + } + private sealed class PngFile { + public bool SeenEnd; public int Width; public int Height; public int BitDepth; @@ -129,6 +144,7 @@ public static class PngDecoder var seenPalette = false; var seenTransparency = false; var idatState = 0; // 0 none yet, 1 inside the IDAT run, 2 after it + var seenEnd = false; var metadataBudget = limits.MaxMetadataBytes; var pos = 8; while (pos < data.Length) @@ -227,6 +243,7 @@ public static class PngDecoder break; case "IEND": + seenEnd = true; pos = data.Length; break; @@ -275,6 +292,7 @@ public static class PngDecoder throw new ImageDecodeException("PNG senza dati dell'immagine (IDAT)."); } + file.SeenEnd = seenEnd; return file; } diff --git a/src/Febe.Core/Import/ContentAnalysis.cs b/src/Febe.Core/Import/ContentAnalysis.cs index bb5cd49..0c44621 100644 --- a/src/Febe.Core/Import/ContentAnalysis.cs +++ b/src/Febe.Core/Import/ContentAnalysis.cs @@ -14,7 +14,8 @@ internal sealed record ContentFacts( TimeSpan? Duration, ulong? PerceptualHash, DateTimeOffset? MetadataDate, - string? Error); + string? Error, + bool Damaged = false); /// /// Reads one source file, read-only (spec §9.2): type from the content, size, SHA-256, dimensions, perceptual hash for @@ -58,6 +59,7 @@ internal static class ContentAnalysis string sha; int? width = null, height = null; ulong? hash = null; + var damaged = false; if (length <= InMemoryLimit) { var bytes = new byte[length]; @@ -69,16 +71,18 @@ internal static class ContentAnalysis sha = Convert.ToHexStringLower(SHA256.HashData(bytes)); ct.ThrowIfCancellationRequested(); (width, height, hash) = Decode(bytes); + damaged = hash is null && ImageDecoding.IsDamaged(bytes); } else { sha = await env.FileSystem.ComputeSha256Async(fullPath, ct).ConfigureAwait(false); ct.ThrowIfCancellationRequested(); - (width, height, hash) = Decode(() => env.FileSystem.OpenRead(fullPath)); + (width, height, hash, damaged) = Decode(() => env.FileSystem.OpenRead(fullPath)); } + // Spec §9.3: a truncated or damaged image is imported like the others, and the review and the report say so. var date = ExifDateReader.Read(head, env.Clock.LocalZone); - return new ContentFacts(type, length, sha, width, height, null, hash, date, null); + return new ContentFacts(type, length, sha, width, height, null, hash, date, null, damaged); } /// Size as shown and perceptual hash of a photo in memory; nulls for what Febe cannot decode (e.g. AVIF). @@ -101,7 +105,7 @@ internal static class ContentAnalysis /// more, whole (up to ; the codecs need the bytes in memory), and decoded /// once for both hash and size. /// - private static (int? Width, int? Height, ulong? Hash) Decode(Func open) + private static (int? Width, int? Height, ulong? Hash, bool Damaged) Decode(Func open) { try { @@ -113,15 +117,15 @@ internal static class ContentAnalysis if (data is null) { - return (null, null, null); + return (null, null, null, false); } var (hash, size) = PerceptualHash.ComputeWithSize(data); - return (size?.Width, size?.Height, hash); + return (size?.Width, size?.Height, hash, hash is null && ImageDecoding.IsDamaged(data)); } catch (Exception ex) when (ex is OutOfMemoryException or ArgumentException or InvalidOperationException or IndexOutOfRangeException) { - return (null, null, null); // a format no decoder reads (e.g. AVIF): no size, no hash + return (null, null, null, false); // a format no decoder reads (e.g. AVIF): no size, no hash } } diff --git a/src/Febe.Core/Import/ImportAnalyzer.cs b/src/Febe.Core/Import/ImportAnalyzer.cs index 322f87c..89a502e 100644 --- a/src/Febe.Core/Import/ImportAnalyzer.cs +++ b/src/Febe.Core/Import/ImportAnalyzer.cs @@ -265,6 +265,7 @@ public sealed class ImportAnalyzer(ImportEnvironment env) .ConfigureAwait(false); var updates = new List(batch.Count); + var damaged = new List(); for (var i = 0; i < batch.Count; i++) { var file = batch[i]; @@ -275,6 +276,11 @@ public sealed class ImportAnalyzer(ImportEnvironment env) continue; } + if (fact.Damaged) + { + damaged.Add(file.Id); + } + var hints = recognizers.Recognize(new ImportFileContext(layout, file.RelativePath)); var (takenAt, source) = ResolveDate(hints, fact.MetadataDate, file.ModifiedAt); var analysed = file with @@ -318,6 +324,7 @@ public sealed class ImportAnalyzer(ImportEnvironment env) } await env.Storage.Imports.UpdateFilesAsync(updates, ct).ConfigureAwait(false); + await ImportRunSettings.AddDamagedAsync(env.Storage.Settings, run.Id, damaged, ct).ConfigureAwait(false); foreach (var update in updates) { done++; diff --git a/src/Febe.Core/Import/ImportEnvironment.cs b/src/Febe.Core/Import/ImportEnvironment.cs index d8afc19..25e8e00 100644 --- a/src/Febe.Core/Import/ImportEnvironment.cs +++ b/src/Febe.Core/Import/ImportEnvironment.cs @@ -115,6 +115,67 @@ internal static class ImportRunSettings public static string NewAccountsKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"importazione.{runId}.nuovi-account"); + /// + /// The files of the run the analysis found «File danneggiato o incompleto» (spec §9.3), as a JSON array of their ids: + /// a setting of the run like the others, so that the schema (and the numbering of its migrations) stays as it is. + /// + public static string DamagedKey(long runId) => string.Create(CultureInfo.InvariantCulture, $"importazione.{runId}.danneggiati"); + + /// The ids of the files of the run that the analysis found damaged or truncated (spec §9.3). + public static async Task> GetDamagedAsync(ISettingsStore store, long runId, CancellationToken ct) + { + var text = await store.GetAsync(DamagedKey(runId), ct).ConfigureAwait(false); + var result = new HashSet(); + if (string.IsNullOrWhiteSpace(text)) + { + return result; + } + + try + { + if (JsonNode.Parse(text) is JsonArray ids) + { + foreach (var id in ids) + { + if (id is JsonValue value && value.TryGetValue(out var fileId)) + { + result.Add(fileId); + } + } + } + } + catch (Exception ex) when (ex is System.Text.Json.JsonException or InvalidOperationException or FormatException) + { + // An unreadable value: no file is marked. + } + + return result; + } + + /// Adds to the damaged files of the run (an analysis that starts again adds nothing twice). + public static async Task AddDamagedAsync(ISettingsStore store, long runId, IReadOnlyCollection fileIds, CancellationToken ct) + { + if (fileIds.Count == 0) + { + return; + } + + var all = await GetDamagedAsync(store, runId, ct).ConfigureAwait(false); + if (all.IsSupersetOf(fileIds)) + { + return; + } + + all.UnionWith(fileIds); + var json = new JsonArray(); + foreach (var id in all.Order()) + { + json.Add(id); + } + + await store.SetAsync(DamagedKey(runId), json.ToJsonString(), ct).ConfigureAwait(false); + } + public static Task GetStogramAsync(ISettingsStore store, long runId, CancellationToken ct) => store.GetBoolAsync(StogramKey(runId), false, ct); @@ -169,5 +230,5 @@ internal static class ImportRunSettings } public static Task ClearAsync(ISettingsStore store, long runId, CancellationToken ct) => - store.SetManyAsync(new Dictionary { [StogramKey(runId)] = null, [NewAccountsKey(runId)] = null }, ct); + store.SetManyAsync(new Dictionary { [StogramKey(runId)] = null, [NewAccountsKey(runId)] = null, [DamagedKey(runId)] = null }, ct); } diff --git a/src/Febe.Core/Import/ImportModels.cs b/src/Febe.Core/Import/ImportModels.cs index 3010b95..c1f6d18 100644 --- a/src/Febe.Core/Import/ImportModels.cs +++ b/src/Febe.Core/Import/ImportModels.cs @@ -124,6 +124,7 @@ public sealed record ImportFolderReview( /// From the start of the import to the end of the analysis. /// The 4K Stogram hypothesis recognizer was used. /// Files already copied or moved by this import. +/// Images the analysis found «File danneggiato o incompleto» (spec §9.3): imported like the others. public sealed record ImportReviewSummary( ImportRun Run, string DisplayPath, @@ -135,7 +136,8 @@ public sealed record ImportReviewSummary( IReadOnlyList Folders, TimeSpan? AnalysisDuration, bool StogramHypothesis, - int Copied) + int Copied, + int Damaged = 0) { /// «Sposta» is offered only for writable sources. public bool CanMove => !Run.SourceReadOnly; diff --git a/src/Febe.Core/Import/ImportReports.cs b/src/Febe.Core/Import/ImportReports.cs index 6b2cac9..12d816f 100644 --- a/src/Febe.Core/Import/ImportReports.cs +++ b/src/Febe.Core/Import/ImportReports.cs @@ -29,6 +29,8 @@ public sealed record ReportNote(string Path, string Note); /// Where the «Già in libreria» files already are. /// The files that are neither photos nor videos (at most ). /// Files that failed or need attention, with the reason (at most ). +/// Images found «File danneggiato o incompleto» by the analysis (spec §9.3). +/// Their paths (at most ). public sealed record ImportReport( ImportRun Run, string DisplayPath, @@ -46,7 +48,9 @@ public sealed record ImportReport( IReadOnlyList ImportedByAccount, IReadOnlyList AlreadyInLibraryByAccount, IReadOnlyList Unrecognized, - IReadOnlyList Problems); + IReadOnlyList Problems, + int DamagedCount = 0, + IReadOnlyList? Damaged = null); /// /// The report of an import and its CSV export (spec §9.4, §4.8): one row per file, ';' as separator, UTF-8 with BOM, so @@ -74,9 +78,16 @@ public sealed class ImportReports(ImportEnvironment env) var already = new Dictionary(StringComparer.OrdinalIgnoreCase); var unrecognized = new List(); var problems = new List(); + var damagedIds = await ImportRunSettings.GetDamagedAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false); + var damaged = new List(); await foreach (var row in RowsAsync(runId, ct).ConfigureAwait(false)) { var file = row.File; + if (damagedIds.Contains(file.Id) && damaged.Count < MaxListed) + { + damaged.Add(file.RelativePath); + } + if (file.State is ImportFileState.Copied or ImportFileState.Moved) { bytesCopied += file.Bytes; @@ -120,7 +131,9 @@ public sealed class ImportReports(ImportEnvironment env) Sorted(imported), Sorted(already), unrecognized, - problems); + problems, + damagedIds.Count, + damaged); } /// Suggested name of the CSV file: «importazione-2026-10-13-12.csv». @@ -138,9 +151,13 @@ public sealed class ImportReports(ImportEnvironment env) var zone = env.Clock.LocalZone; await using var writer = new StreamWriter(destination, new UTF8Encoding(encoderShouldEmitUTF8Identifier: true), 64 * 1024, leaveOpen: true) { NewLine = "\r\n" }; await writer.WriteLineAsync(Line(Header)).ConfigureAwait(false); + var damaged = await ImportRunSettings.GetDamagedAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false); await foreach (var row in RowsAsync(runId, ct).ConfigureAwait(false)) { var f = row.File; + var note = damaged.Contains(f.Id) + ? f.LastError is { Length: > 0 } other ? $"{ImportText.NoteDamaged}. {other}" : ImportText.NoteDamaged + : f.LastError ?? string.Empty; var replaced = f.LastError?.StartsWith(ImportText.NoteReplaced, StringComparison.Ordinal) == true; var destinationUser = replaced ? row.MatchedUsername : row.TargetUsername; await writer.WriteLineAsync(Line( @@ -163,7 +180,7 @@ public sealed class ImportReports(ImportEnvironment env) f.InstagramId ?? string.Empty, row.MatchedUsername is { } user ? $"{user}/{row.MatchedPath}" : string.Empty, f.DestinationPath is { } path && destinationUser is { } to ? $"{to}/{path}" : f.DestinationPath ?? string.Empty, - f.LastError ?? string.Empty, + note, ])).ConfigureAwait(false); } diff --git a/src/Febe.Core/Import/ImportReview.cs b/src/Febe.Core/Import/ImportReview.cs index b7bb3ad..b36dfab 100644 --- a/src/Febe.Core/Import/ImportReview.cs +++ b/src/Febe.Core/Import/ImportReview.cs @@ -20,6 +20,7 @@ public sealed class ImportReview(ImportEnvironment env) var folders = await ListFoldersAsync(run, ct).ConfigureAwait(false); var pending = await env.Storage.Imports.CountPairsAsync(runId, pendingOnly: true, ct).ConfigureAwait(false); var stogram = await ImportRunSettings.GetStogramAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false); + var damaged = await ImportRunSettings.GetDamagedAsync(env.Storage.Settings, runId, ct).ConfigureAwait(false); return new ImportReviewSummary( run, env.CreateSources().DisplayPath(run.SourcePath), @@ -31,7 +32,8 @@ public sealed class ImportReview(ImportEnvironment env) folders, run.AnalyzedAt is { } analyzed ? analyzed - run.StartedAt : null, stogram, - summary.ByState[ImportFileState.Copied] + summary.ByState[ImportFileState.Moved]); + summary.ByState[ImportFileState.Copied] + summary.ByState[ImportFileState.Moved], + damaged.Count); } /// The rows of «Cartelle e account». diff --git a/src/Febe.Core/Import/ImportText.cs b/src/Febe.Core/Import/ImportText.cs index e16f137..50f13fb 100644 --- a/src/Febe.Core/Import/ImportText.cs +++ b/src/Febe.Core/Import/ImportText.cs @@ -145,4 +145,7 @@ public static class ImportText internal const string NoteOriginalKept = "Copiato; l'originale non si è potuto eliminare e resta al suo posto."; internal const string NoteMovePending = "Copiato; l'originale si elimina dopo la verifica della copia."; internal const string NoteOldNotDeleted = "Il file sostituito non si è potuto eliminare dalla libreria: resta accanto al nuovo."; + + /// Spec §9.3, §8.4: an image truncated or damaged, imported like the others, without visual fingerprint. + internal const string NoteDamaged = "File danneggiato o incompleto"; } diff --git a/src/Febe.Core/Library/DamagedImage.cs b/src/Febe.Core/Library/DamagedImage.cs index b095e89..888fb05 100644 --- a/src/Febe.Core/Library/DamagedImage.cs +++ b/src/Febe.Core/Library/DamagedImage.cs @@ -1,3 +1,5 @@ +using System.Collections.Concurrent; + namespace Febe.Core.Library; /// @@ -7,11 +9,18 @@ namespace Febe.Core.Library; /// class only looks, it never deletes, replaces or downloads again. /// /// -/// The check decodes the picture, so it is meant for a single file at a time (the viewer) and only for photos that -/// have no thumbnail: a photo with a thumbnail was decoded when it was stored. +/// The check decodes the picture, so it is meant for a single file at a time (the viewer, the import of one file) and +/// only for photos that have no thumbnail: a photo with a thumbnail was decoded when it was stored. The first bytes are +/// looked at before the rest is read: a format Febe does not decode, a HEIC and a picture over the decoding limit are +/// never damaged, so their file is not read whole for nothing. /// public static class DamagedImage { + /// How many answers keeps; the whole memory is dropped when it is full. + private const int RememberedAnswers = 512; + + private static readonly ConcurrentDictionary<(string Path, long Length, DateTime Written), bool> Answers = new(); + /// /// True when the bytes are a photo in a format Febe reads that cannot be decoded because it is damaged or /// truncated; false for a photo that decodes, for a format Febe does not read (AVIF, an unknown one), for HEIC (see ImageDecoding.IsDamaged) and for a @@ -20,23 +29,120 @@ public static class DamagedImage public static bool IsDamaged(ReadOnlyMemory data) => ImageDecoding.IsDamaged(data); /// - /// for a file on disk, read once; false when it cannot be read or is - /// larger than . + /// for a file on disk; false when it cannot be read or is larger than + /// . Reads the first bytes and, only when the picture may be damaged, the rest. /// public static bool IsFileDamaged(string path) { ArgumentException.ThrowIfNullOrEmpty(path); - byte[]? data; try { using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete); - data = ImageDecoding.ReadAll(stream); + var length = stream.Length; + if (length <= 0 || length > ImageDecoding.MaxFileBytes) + { + return false; + } + + var head = (int)Math.Min(length, ImageDecoding.HeaderBytes); + var data = new byte[head]; + stream.ReadExactly(data); + if (!ImageDecoding.MayBeDamaged(data)) + { + return false; + } + + if (length > head) + { + var whole = new byte[length]; + data.CopyTo(whole, 0); + stream.ReadExactly(whole.AsSpan(head)); + data = whole; + } + + return ImageDecoding.IsDamaged(data); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return false; + } + } + + /// + /// with asynchronous reads, for a request: the answer is kept for the same file (path, + /// length and time of the last write), so stepping back and forth in the viewer does not read and decode it again. + /// + public static async Task IsFileDamagedAsync(string path, CancellationToken ct) + { + ArgumentException.ThrowIfNullOrEmpty(path); + (string, long, DateTime) key; + try + { + var info = new FileInfo(path); + if (!info.Exists) + { + return false; + } + + key = (info.FullName, info.Length, info.LastWriteTimeUtc); } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { return false; } - return data is not null && ImageDecoding.IsDamaged(data); + if (Answers.TryGetValue(key, out var known)) + { + return known; + } + + var answer = await ReadAndCheckAsync(path, ct).ConfigureAwait(false); + if (answer is not { } damaged) + { + return false; // not readable now: not remembered + } + + if (Answers.Count >= RememberedAnswers) + { + Answers.Clear(); + } + + Answers[key] = damaged; + return damaged; + } + + private static async Task ReadAndCheckAsync(string path, CancellationToken ct) + { + try + { + await using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite | FileShare.Delete, 81920, FileOptions.Asynchronous | FileOptions.SequentialScan); + var length = stream.Length; + if (length <= 0 || length > ImageDecoding.MaxFileBytes) + { + return false; + } + + var head = (int)Math.Min(length, ImageDecoding.HeaderBytes); + var data = new byte[head]; + await stream.ReadExactlyAsync(data, ct).ConfigureAwait(false); + if (!ImageDecoding.MayBeDamaged(data)) + { + return false; + } + + if (length > head) + { + var whole = new byte[length]; + data.CopyTo(whole, 0); + await stream.ReadExactlyAsync(whole.AsMemory(head), ct).ConfigureAwait(false); + data = whole; + } + + return ImageDecoding.IsDamaged(data); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + return null; + } } } diff --git a/src/Febe.Core/Library/ImageDecoding.cs b/src/Febe.Core/Library/ImageDecoding.cs index 21d35d1..f6aad5e 100644 --- a/src/Febe.Core/Library/ImageDecoding.cs +++ b/src/Febe.Core/Library/ImageDecoding.cs @@ -1,3 +1,4 @@ +using System.Buffers.Binary; using Febe.Core.Codecs.Heif; using Febe.Core.Codecs.Images; @@ -112,6 +113,54 @@ internal static class ImageDecoding } } + /// + /// From the first bytes of a file (at least the header of its format): false when would + /// say false whatever follows — a format Febe does not decode, a HEIC, a PNG, GIF, BMP or WebP whose header gives + /// more pixels than — so that such a file is not read whole only to be refused. + /// JPEG decodes at a reduced size, so its header alone never rules it out. + /// + internal static bool MayBeDamaged(ReadOnlySpan head) + { + var format = head.IsEmpty ? ImageFormat.Unknown : ImageFormatSniffer.Detect(head); + if (format == ImageFormat.Heif || !ImageDecoder.CanDecode(format)) + { + return false; + } + + return HeaderPixels(format, head) is not { } pixels || pixels <= MaxDecodedPixels; + } + + /// + /// Width × height as the header of a PNG (IHDR), GIF (logical screen), BMP (information header) or WebP (VP8X, + /// VP8L or VP8 frame header) states it, from their public specifications; null when it is not there. + /// + internal static long? HeaderPixels(ImageFormat format, ReadOnlySpan h) + { + switch (format) + { + case ImageFormat.Png when h.Length >= 24 && h[12..16].SequenceEqual("IHDR"u8): + return (long)BinaryPrimitives.ReadUInt32BigEndian(h[16..]) * BinaryPrimitives.ReadUInt32BigEndian(h[20..]); + case ImageFormat.Gif when h.Length >= 10: + return (long)BinaryPrimitives.ReadUInt16LittleEndian(h[6..]) * BinaryPrimitives.ReadUInt16LittleEndian(h[8..]); + case ImageFormat.Bmp when h.Length >= 22 && BinaryPrimitives.ReadUInt32LittleEndian(h[14..]) == 12: + return (long)BinaryPrimitives.ReadUInt16LittleEndian(h[18..]) * BinaryPrimitives.ReadUInt16LittleEndian(h[20..]); + case ImageFormat.Bmp when h.Length >= 26: + return Math.Abs((long)BinaryPrimitives.ReadInt32LittleEndian(h[18..])) * Math.Abs((long)BinaryPrimitives.ReadInt32LittleEndian(h[22..])); + case ImageFormat.WebP when h.Length >= 30 && h[12..16].SequenceEqual("VP8X"u8): + return (1L + (h[24] | (h[25] << 8) | (h[26] << 16))) * (1L + (h[27] | (h[28] << 8) | (h[29] << 16))); + case ImageFormat.WebP when h.Length >= 25 && h[12..16].SequenceEqual("VP8L"u8) && h[20] == 0x2F: + { + var bits = BinaryPrimitives.ReadUInt32LittleEndian(h[21..]); + return (1L + (bits & 0x3FFF)) * (1L + ((bits >> 14) & 0x3FFF)); + } + + case ImageFormat.WebP when h.Length >= 30 && h[12..16].SequenceEqual("VP8 "u8) && h[23] == 0x9D && h[24] == 0x01 && h[25] == 0x2A: + return (long)(BinaryPrimitives.ReadUInt16LittleEndian(h[26..]) & 0x3FFF) * (BinaryPrimitives.ReadUInt16LittleEndian(h[28..]) & 0x3FFF); + default: + return null; + } + } + /// The smallest long side lets a JPEG be decoded at: the cheapest reduction. private const int DamageCheckSide = 1; diff --git a/src/Febe.Core/Library/VideoFrameDecoder.cs b/src/Febe.Core/Library/VideoFrameDecoder.cs index 5496967..261bfcf 100644 --- a/src/Febe.Core/Library/VideoFrameDecoder.cs +++ b/src/Febe.Core/Library/VideoFrameDecoder.cs @@ -64,7 +64,7 @@ public sealed class VideoFrameDecoder public const double StillThreshold = 3.0; /// - /// The longest a frame or a stillness analysis may take: what the ffmpeg extractor it replaces was given. A damaged + /// The longest a frame or a stillness analysis may take: what the external extractor used before C3 was given. A damaged /// file never holds an import or a rebuild for longer. /// public static readonly TimeSpan DefaultBudget = TimeSpan.FromSeconds(30); diff --git a/src/Febe.Desktop.Core/BrandIcon.cs b/src/Febe.Desktop.Core/BrandIcon.cs index 45b6eec..8661726 100644 --- a/src/Febe.Desktop.Core/BrandIcon.cs +++ b/src/Febe.Desktop.Core/BrandIcon.cs @@ -50,7 +50,7 @@ public static class BrandMark /// /// Writes Windows .ico files by hand (no package for it, spec §3): the 256-pixel image as PNG, the smaller ones as /// 32-bit DIBs (BGRA with alpha, bottom-up, plus the 1-bit AND mask), which every part of Windows reads — window icons, -/// the notification area, Explorer, NSIS. +/// the notification area, Explorer, the installer. /// public static class IcoWriter { diff --git a/src/Febe.Desktop/LEGGIMI.md b/src/Febe.Desktop/LEGGIMI.md index 7868c2f..062927d 100644 --- a/src/Febe.Desktop/LEGGIMI.md +++ b/src/Febe.Desktop/LEGGIMI.md @@ -44,4 +44,5 @@ Regole che valgono anche qui: ## Pubblicazione `installer/costruisci.sh` pubblica un solo `Febe.exe` (autosufficiente, compresso, librerie native incluse) e ne fa -`out/Febe-Setup-.exe` (NSIS, `installer/febe.nsi`) e `out/Febe--portabile.zip`. +`out/Febe-Setup-.exe` (il programma di installazione nostro, `src/Febe.Installer`) e +`out/Febe--portabile.zip`. diff --git a/src/Febe.Installer/CommandLine.cs b/src/Febe.Installer/CommandLine.cs new file mode 100644 index 0000000..847105f --- /dev/null +++ b/src/Febe.Installer/CommandLine.cs @@ -0,0 +1,151 @@ +namespace Febe.Installer; + +/// What the build asks of the tool (never on Windows of Alberto: in the CI and in installer/costruisci.sh). +internal enum ToolCommand +{ + None, + + /// --impacchetta <installer> <Febe.exe> <version> <output> + Pack, + + /// --verifica <package> <Febe.exe> + Verify, + + /// --zip <output> <file>... + Zip, +} + +/// +/// The command line of the installer and of the uninstaller, the same options as the installer before 18 November 2026: +/// +/// /S: silent, no dialog; the desktop shortcut is created, Febe is not started, an open Febe is an error. +/// /D=<folder>: the program folder (only the installer); last, it takes the rest of the line even +/// with spaces, as before. +/// /PROVA=<folder>: for the tests, every folder and key under that one (). +/// +/// Internal to the uninstaller, which starts a copy of itself from %TEMP% so it can delete its own file: +/// /_?=<program folder> and /ATTENDI=<process>. +/// +internal sealed record CommandLine +{ + public bool Silent { get; init; } + + public string? InstallFolder { get; init; } + + public string? TestRoot { get; init; } + + public string? UninstallFolder { get; init; } + + public int? WaitFor { get; init; } + + public ToolCommand Tool { get; init; } + + public IReadOnlyList ToolArguments { get; init; } = []; + + /// The options again, for the copy of the uninstaller (all but the internal ones). + public IReadOnlyList PassOn() + { + var arguments = new List(); + if (Silent) + { + arguments.Add("/S"); + } + + if (TestRoot is not null) + { + arguments.Add("/PROVA=" + TestRoot); + } + + return arguments; + } + + /// Reads ; an unknown option is an error with its text. + /// An option that does not exist or lacks its value. + public static CommandLine Parse(IReadOnlyList arguments) + { + if (arguments.Count > 0 && arguments[0].StartsWith("--", StringComparison.Ordinal)) + { + var tool = arguments[0] switch + { + "--impacchetta" => ToolCommand.Pack, + "--verifica" => ToolCommand.Verify, + "--zip" => ToolCommand.Zip, + _ => throw new ArgumentException($"Opzione sconosciuta: «{arguments[0]}»."), + }; + var rest = arguments.Skip(1).ToArray(); + var valid = tool switch + { + ToolCommand.Pack => rest.Length == 4, + ToolCommand.Verify => rest.Length == 2, + _ => rest.Length >= 2, + }; + if (!valid) + { + throw new ArgumentException(tool switch + { + ToolCommand.Pack => "Uso: --impacchetta ", + ToolCommand.Verify => "Uso: --verifica ", + _ => "Uso: --zip ...", + }); + } + + return new CommandLine { Tool = tool, ToolArguments = rest }; + } + + var line = new CommandLine(); + for (var i = 0; i < arguments.Count; i++) + { + var argument = arguments[i]; + if (string.Equals(argument, "/S", StringComparison.OrdinalIgnoreCase)) + { + line = line with { Silent = true }; + } + else if (argument.StartsWith("/D=", StringComparison.OrdinalIgnoreCase)) + { + // The last option: the rest of the line is the folder even when unquoted. + var folder = string.Join(' ', [argument[3..], .. arguments.Skip(i + 1)]); + line = line with { InstallFolder = Folder(folder, "/D=") }; + break; + } + else if (argument.StartsWith("/PROVA=", StringComparison.OrdinalIgnoreCase)) + { + // A folder of its own: its name becomes the registry key of the test (Locations.ForTest), and a root + // has no name. + var root = Folder(argument[7..], "/PROVA="); + if (Path.GetFileName(root).Length == 0) + { + throw new ArgumentException("/PROVA= vuole una cartella, non la radice di un disco."); + } + + line = line with { TestRoot = root }; + } + else if (argument.StartsWith("/_?=", StringComparison.Ordinal)) + { + line = line with { UninstallFolder = Folder(argument[4..], "/_?=") }; + } + else if (argument.StartsWith("/ATTENDI=", StringComparison.OrdinalIgnoreCase) + && int.TryParse(argument.AsSpan(9), System.Globalization.NumberStyles.None, System.Globalization.CultureInfo.InvariantCulture, out var process) + && process > 0) + { + line = line with { WaitFor = process }; + } + else + { + throw new ArgumentException($"Opzione sconosciuta: «{argument}». Le opzioni sono /S e /D=."); + } + } + + return line; + } + + private static string Folder(string value, string option) + { + var folder = value.Trim().Trim('"'); + if (folder.Length == 0 || !Path.IsPathFullyQualified(folder)) + { + throw new ArgumentException($"{option} vuole un percorso completo, per esempio {option}D:\\Programmi\\Febe."); + } + + return Path.TrimEndingDirectorySeparator(folder); + } +} diff --git a/src/Febe.Installer/Febe.Installer.csproj b/src/Febe.Installer/Febe.Installer.csproj new file mode 100644 index 0000000..87e8a17 --- /dev/null +++ b/src/Febe.Installer/Febe.Installer.csproj @@ -0,0 +1,42 @@ + + + + WinExe + Febe.Installer + Febe.Installer + Installazione di Febe + Installazione di Febe + ..\Febe.Desktop\Febe.ico + app.manifest + true + true + true + true + + + + true + true + true + true + none + false + false + false + false + + + + + + diff --git a/src/Febe.Installer/ISystemAccess.cs b/src/Febe.Installer/ISystemAccess.cs new file mode 100644 index 0000000..476ccd6 --- /dev/null +++ b/src/Febe.Installer/ISystemAccess.cs @@ -0,0 +1,48 @@ +namespace Febe.Installer; + +/// A shortcut (.lnk) to write. +internal sealed record Shortcut(string Path, string Target, string WorkingDirectory, string Description, string IconPath, int IconIndex); + +/// +/// What the installation asks of Windows besides files: the registry of the current user (and only reading that of +/// the machine), shortcuts, opening an address, starting a process. The real one is WindowsSystem; the tests use +/// a fake, so the logic of and runs on Linux too. Writing for every +/// user is not even possible through this interface: nothing of the installation needs administrator rights. +/// +internal interface ISystemAccess +{ + /// A string value under HKEY_CURRENT_USER; null when the key or the value is missing or not a string. + string? ReadUserString(string key, string name); + + /// A DWORD value under HKEY_CURRENT_USER; null when missing. + int? ReadUserDword(string key, string name); + + void WriteUserString(string key, string name, string value); + + void WriteUserDword(string key, string name, int value); + + /// The names of the values of a key of HKEY_CURRENT_USER, empty when the key is missing. + IReadOnlyList UserValueNames(string key); + + void DeleteUserValue(string key, string name); + + /// Deletes a key of HKEY_CURRENT_USER with everything under it; nothing when it is missing. + void DeleteUserKeyTree(string key); + + /// A string value under HKEY_LOCAL_MACHINE (64-bit view), only read. + string? ReadMachineString(string key, string name); + + void CreateShortcut(Shortcut shortcut); + + /// Opens an address in the default browser. + void OpenAddress(string address); + + /// Starts a program and does not wait for it. + void Start(string executable, IReadOnlyList arguments, string workingDirectory); + + /// Waits until the process has ended, at most . + void WaitForExit(int processId, TimeSpan timeout); + + /// Waits a little before trying again (a file still held by a process that is ending). + void Pause(TimeSpan delay); +} diff --git a/src/Febe.Installer/Locations.cs b/src/Febe.Installer/Locations.cs new file mode 100644 index 0000000..0a5e5bc --- /dev/null +++ b/src/Febe.Installer/Locations.cs @@ -0,0 +1,86 @@ +namespace Febe.Installer; + +/// +/// Where the installation writes: the folders of the user and the root of the registry keys of Febe. For the user +/// these are the folders of Windows (); for the tests everything moves under one folder and one +/// registry key of its own (, option /PROVA=), so a test never touches the real Start menu, +/// the real desktop or the real entries of an installed Febe. +/// +internal sealed record Locations +{ + /// %LOCALAPPDATA%: the default program folder is under it, and the default Data folder. + public required string LocalAppData { get; init; } + + /// The Programs folder of the user's Start menu. + public required string StartMenuPrograms { get; init; } + + public required string Desktop { get; init; } + + public required string Pictures { get; init; } + + public required string Temp { get; init; } + + /// Empty for the user; for a test, the key under which every key of Febe is written. + public string RegistryRoot { get; init; } = string.Empty; + + /// The folder given with /PROVA=, null for the user. + public string? TestRoot { get; init; } + + public string DefaultInstallFolder => Path.Combine(LocalAppData, "Programs", Product.Name); + + public string StartMenuShortcut => Path.Combine(StartMenuPrograms, Product.ShortcutName); + + public string DesktopShortcut => Path.Combine(Desktop, Product.ShortcutName); + + public string DefaultDataFolder => Path.Combine(LocalAppData, Product.Name); + + public string Library => Path.Combine(Pictures, Product.Name); + + /// Where Febe.exe, a single file, extracts its native libraries on the first start (not data). + public string ExtractionFolder => Path.Combine(Temp, ".net", Product.Name); + + public string UninstallKey => RegistryRoot + Product.UninstallKey; + + public string FebeKey => RegistryRoot + Product.FebeKey; + + public string RunKey => RegistryRoot + Product.RunKey; + + /// The folders of Windows for the current user. + public static Locations ForUser() => new() + { + LocalAppData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), + StartMenuPrograms = Environment.GetFolderPath(Environment.SpecialFolder.Programs), + Desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), + Pictures = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), + Temp = Path.TrimEndingDirectorySeparator(Path.GetTempPath()), + }; + + /// + /// Everything under : AppData, Menu, Desktop, Immagini and Temp inside it, and the keys under + /// HKCU\Software\FebeProve\<name of the folder>. + /// + public static Locations ForTest(string root) + { + var full = Path.TrimEndingDirectorySeparator(Path.GetFullPath(root)); + var name = Path.GetFileName(full); + if (name.Length == 0 || name.Contains('\\', StringComparison.Ordinal)) + { + throw new ArgumentException("Cartella di prova non valida.", nameof(root)); + } + + return new() + { + LocalAppData = Path.Combine(full, "AppData"), + StartMenuPrograms = Path.Combine(full, "Menu"), + Desktop = Path.Combine(full, "Desktop"), + Pictures = Path.Combine(full, "Immagini"), + Temp = Path.Combine(full, "Temp"), + RegistryRoot = TestRegistryRoot(full), + TestRoot = full, + }; + } + + /// The registry key under which a test installation in writes. + public static string TestRegistryRoot(string root) => + @"Software\FebeProve\" + Path.GetFileName(Path.TrimEndingDirectorySeparator(Path.GetFullPath(root))) + @"\"; +} diff --git a/src/Febe.Installer/Package.cs b/src/Febe.Installer/Package.cs new file mode 100644 index 0000000..d92bd61 --- /dev/null +++ b/src/Febe.Installer/Package.cs @@ -0,0 +1,405 @@ +using System.Buffers; +using System.Buffers.Binary; +using System.IO.Compression; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; + +namespace Febe.Installer; + +/// What a package is: the installer with Febe.exe inside, or the uninstaller left in the program folder. +internal enum PackageKind +{ + Installer = 1, + Uninstaller = 2, +} + +/// The footer of a package, read back. +internal sealed record PackageInfo( + PackageKind Kind, + long ProgramStart, + long DataLength, + long ProgramLength, + byte[] ProgramHash, + string Version) +{ + /// The length of the program itself (the published installer), before the data: where the data start. + public long StubLength => ProgramStart; +} + +/// +/// The package: the published installer (a .NET single file) followed by Febe.exe compressed with Brotli, the version +/// and a fixed footer of bytes at the very end. The host of a single file finds its bundle +/// through an offset written inside the executable, not from the end of the file, so what follows does not disturb it. +/// The uninstaller is the same program with a footer of its own and no data. +/// +/// [installer][Febe.exe, Brotli][version, UTF-8][footer] +/// footer, little-endian: «FEBE-PKG» · format 1 (int32) · kind (int32) · length of the installer (int64) +/// · length of the data (int64) · length of Febe.exe (int64) · length of the version (int32) +/// · SHA-256 of Febe.exe (32 bytes) · 0 (int32) +/// +/// +internal static partial class Package +{ + public const int FooterLength = 80; + + private const int FormatVersion = 1; + + private const int MaxVersionLength = 64; + + /// Brotli: quality 5 and a 16 MB window, a few seconds for Febe.exe and within 1% of the best. + private const int Quality = 5; + + private const int Window = 24; + + private const int BufferSize = 1 << 20; + + private static ReadOnlySpan Magic => "FEBE-PKG"u8; + + /// The footer of ; null when the file is not a package (no footer at the end). + /// The footer is there but does not describe the file. + public static PackageInfo? Read(string path) + { + using var file = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); + return Read(file); + } + + /// + public static PackageInfo? Read(FileStream file) + { + var length = file.Length; + if (length < FooterLength) + { + return null; + } + + Span footer = stackalloc byte[FooterLength]; + file.Position = length - FooterLength; + file.ReadExactly(footer); + if (!footer[..8].SequenceEqual(Magic)) + { + return null; + } + + var format = BinaryPrimitives.ReadInt32LittleEndian(footer[8..]); + var kind = (PackageKind)BinaryPrimitives.ReadInt32LittleEndian(footer[12..]); + var programStart = BinaryPrimitives.ReadInt64LittleEndian(footer[16..]); + var dataLength = BinaryPrimitives.ReadInt64LittleEndian(footer[24..]); + var programLength = BinaryPrimitives.ReadInt64LittleEndian(footer[32..]); + var versionLength = BinaryPrimitives.ReadInt32LittleEndian(footer[40..]); + var hash = footer.Slice(44, 32).ToArray(); + if (format != FormatVersion + || kind is not (PackageKind.Installer or PackageKind.Uninstaller) + || programStart <= 0 || dataLength < 0 || programLength < 0 + || versionLength <= 0 || versionLength > MaxVersionLength + || programStart + dataLength + versionLength + FooterLength != length + || (kind == PackageKind.Uninstaller && (dataLength != 0 || programLength != 0)) + || (kind == PackageKind.Installer && (dataLength == 0 || programLength == 0))) + { + throw new InvalidDataException(Texts.Damaged); + } + + Span versionBytes = stackalloc byte[versionLength]; + file.Position = programStart + dataLength; + file.ReadExactly(versionBytes); + var version = Encoding.UTF8.GetString(versionBytes); + if (!IsVersion(version)) + { + throw new InvalidDataException(Texts.Damaged); + } + + return new PackageInfo(kind, programStart, dataLength, programLength, hash, version); + } + + /// A version as the build writes it: x.y.z, optionally followed by -something or +something. + public static bool IsVersion(string? version) => + version is { Length: > 0 and <= MaxVersionLength } && VersionPattern().IsMatch(version); + + /// + /// Writes the package : the published installer , then + /// (Febe.exe) compressed, the version and the footer. Written beside and renamed at the + /// end, so a failure never leaves half a package. + /// + public static PackageInfo Write(string installer, string program, string version, string output) + { + if (!IsVersion(version)) + { + throw new ArgumentException($"Versione non valida: «{version}» (serve x.y.z).", nameof(version)); + } + + if (Read(installer) is not null) + { + throw new ArgumentException("Il programma di installazione contiene già un pacchetto: serve quello appena pubblicato.", nameof(installer)); + } + + var partial = output + ".part"; + try + { + PackageInfo info; + using (var target = new FileStream(partial, FileMode.Create, FileAccess.Write, FileShare.None)) + { + using (var source = File.OpenRead(installer)) + { + source.CopyTo(target, BufferSize); + } + + var programStart = target.Position; + if (programStart == 0) + { + throw new ArgumentException("Il programma di installazione è vuoto.", nameof(installer)); + } + + byte[] hash; + long programLength; + using (var source = File.OpenRead(program)) + { + (programLength, hash) = Compress(source, target); + } + + if (programLength == 0) + { + throw new ArgumentException("Il programma da installare è vuoto.", nameof(program)); + } + + var dataLength = target.Position - programStart; + info = new PackageInfo(PackageKind.Installer, programStart, dataLength, programLength, hash, version); + WriteTail(target, info); + target.Flush(flushToDisk: true); + } + + File.Move(partial, output, overwrite: true); + return info; + } + catch + { + TryDelete(partial); + throw; + } + } + + /// + /// Decompresses Febe.exe from the package into , checking + /// its length and SHA-256; gets the share written, from 0 to 1. + /// + /// The data are not the program the footer describes. + public static void ExtractProgram(string package, PackageInfo info, string destination, Action? progress = null) + { + if (info.Kind != PackageKind.Installer) + { + throw new InvalidOperationException("Il pacchetto non contiene Febe."); + } + + var buffer = ArrayPool.Shared.Rent(BufferSize); + try + { + using var file = new FileStream(package, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, 1, FileOptions.SequentialScan); + using var slice = new SliceStream(file, info.ProgramStart, info.DataLength); + using var brotli = new BrotliStream(slice, CompressionMode.Decompress); + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + using var target = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.None, 1, FileOptions.SequentialScan); + target.SetLength(info.ProgramLength); + long written = 0; + while (true) + { + int read; + try + { + read = brotli.Read(buffer, 0, BufferSize); + } + catch (Exception ex) when (ex is InvalidDataException or InvalidOperationException or EndOfStreamException) + { + // Brotli refuses the data, or they end before the footer says. + throw new InvalidDataException(Texts.Damaged, ex); + } + + if (read == 0) + { + break; + } + + written += read; + if (written > info.ProgramLength) + { + throw new InvalidDataException(Texts.Damaged); + } + + hash.AppendData(buffer, 0, read); + target.Write(buffer, 0, read); + progress?.Invoke((double)written / info.ProgramLength); + } + + Span actual = stackalloc byte[32]; + hash.GetHashAndReset(actual); + if (written != info.ProgramLength || !actual.SequenceEqual(info.ProgramHash)) + { + throw new InvalidDataException(Texts.Damaged); + } + + target.Flush(flushToDisk: true); + } + finally + { + ArrayPool.Shared.Return(buffer); + } + } + + /// + /// Writes the uninstaller into : the program of without + /// Febe.exe, with a footer of kind and the same version. + /// + public static void WriteUninstaller(string package, PackageInfo info, string destination) + { + using var source = new FileStream(package, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete); + using var target = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.None); + using (var program = new SliceStream(source, 0, info.StubLength)) + { + program.CopyTo(target, BufferSize); + } + + WriteTail(target, new PackageInfo(PackageKind.Uninstaller, info.StubLength, 0, 0, new byte[32], info.Version)); + target.Flush(flushToDisk: true); + } + + private static (long Length, byte[] Hash) Compress(Stream source, Stream target) + { + var input = ArrayPool.Shared.Rent(BufferSize); + var output = ArrayPool.Shared.Rent(BufferSize); + try + { + using var encoder = new BrotliEncoder(Quality, Window); + using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256); + long length = 0; + while (true) + { + var read = source.Read(input, 0, BufferSize); + var final = read == 0; + length += read; + hash.AppendData(input, 0, read); + var pending = input.AsSpan(0, read); + while (true) + { + var status = encoder.Compress(pending, output, out var consumed, out var produced, final); + target.Write(output, 0, produced); + pending = pending[consumed..]; + if (status is OperationStatus.Done or OperationStatus.NeedMoreData) + { + break; + } + + if (status == OperationStatus.InvalidData) + { + throw new InvalidDataException("Compressione non riuscita."); + } + } + + if (final) + { + return (length, hash.GetHashAndReset()); + } + } + } + finally + { + ArrayPool.Shared.Return(input); + ArrayPool.Shared.Return(output); + } + } + + private static void WriteTail(Stream target, PackageInfo info) + { + var version = Encoding.UTF8.GetBytes(info.Version); + target.Write(version); + Span footer = stackalloc byte[FooterLength]; + footer.Clear(); + Magic.CopyTo(footer); + BinaryPrimitives.WriteInt32LittleEndian(footer[8..], FormatVersion); + BinaryPrimitives.WriteInt32LittleEndian(footer[12..], (int)info.Kind); + BinaryPrimitives.WriteInt64LittleEndian(footer[16..], info.ProgramStart); + BinaryPrimitives.WriteInt64LittleEndian(footer[24..], info.DataLength); + BinaryPrimitives.WriteInt64LittleEndian(footer[32..], info.ProgramLength); + BinaryPrimitives.WriteInt32LittleEndian(footer[40..], version.Length); + info.ProgramHash.CopyTo(footer[44..]); + target.Write(footer); + } + + internal static void TryDelete(string path) + { + try + { + File.Delete(path); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Our own temporary file: left behind, it is overwritten next time. + } + } + + [GeneratedRegex(@"^[0-9]+\.[0-9]+\.[0-9]+([-+][0-9A-Za-z.-]+)?$", RegexOptions.CultureInvariant)] + private static partial Regex VersionPattern(); +} + +/// A read-only window on a part of a stream, which it never closes. +internal sealed class SliceStream : Stream +{ + private readonly Stream _inner; + private readonly long _start; + private readonly long _length; + private long _position; + + public SliceStream(Stream inner, long start, long length) + { + _inner = inner; + _start = start; + _length = length; + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => false; + + public override long Length => _length; + + public override long Position + { + get => _position; + set => throw new NotSupportedException(); + } + + public override int Read(byte[] buffer, int offset, int count) => Read(buffer.AsSpan(offset, count)); + + public override int Read(Span buffer) + { + var left = _length - _position; + if (left <= 0 || buffer.IsEmpty) + { + return 0; + } + + if (buffer.Length > left) + { + buffer = buffer[..(int)left]; + } + + _inner.Position = _start + _position; + var read = _inner.Read(buffer); + if (read == 0) + { + throw new EndOfStreamException(); + } + + _position += read; + return read; + } + + public override void Flush() + { + } + + public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException(); + + public override void SetLength(long value) => throw new NotSupportedException(); + + public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException(); +} diff --git a/src/Febe.Installer/Product.cs b/src/Febe.Installer/Product.cs new file mode 100644 index 0000000..7c9aa3f --- /dev/null +++ b/src/Febe.Installer/Product.cs @@ -0,0 +1,46 @@ +namespace Febe.Installer; + +/// +/// The fixed facts of the installation (spec §12, question 6 of §16): names, registry keys and addresses. The keys +/// , and the values under them are those Febe for Windows writes itself +/// (RegistryLocationStore and Autostart in the desktop projects); a test checks they agree. +/// +internal static class Product +{ + public const string Name = "Febe"; + + public const string Publisher = "Alberto Balbo"; + + public const string Executable = "Febe.exe"; + + public const string Uninstaller = "Disinstalla Febe.exe"; + + public const string ShortcutName = "Febe.lnk"; + + public const string ShortcutDescription = "Archivio personale di foto, video e storie da Instagram"; + + /// Apps installed (Programs and Features), per user, under HKEY_CURRENT_USER. + public const string UninstallKey = @"Software\Microsoft\Windows\CurrentVersion\Uninstall\Febe"; + + /// Febe's own key: «CartellaDati» says where the data are after a move (spec §12). + public const string FebeKey = @"Software\Febe"; + + public const string DataFolderValue = "CartellaDati"; + + /// «Start Febe with the computer»: the value «Febe» and, for a Febe started with --dati, «Febe-…». + public const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run"; + + public const string AutostartValue = "Febe"; + + public const string AutostartPrefix = "Febe-"; + + /// The Evergreen runtime of WebView2: «pv» under this client of EdgeUpdate is its version. + public const string EdgeUpdateClient = @"Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"; + + public const string WebView2Page = "https://developer.microsoft.com/microsoft-edge/webview2/"; + + public const string Site = "https://gitea.encke-hake.ts.net/Alby96/Febe"; + + /// The prefix of the copies of the uninstaller that run from the temporary folder. + public const string UninstallerCopyPrefix = "Febe-disinstalla-"; +} diff --git a/src/Febe.Installer/Program.cs b/src/Febe.Installer/Program.cs new file mode 100644 index 0000000..eb72f2a --- /dev/null +++ b/src/Febe.Installer/Program.cs @@ -0,0 +1,197 @@ +using System.IO.Compression; +using System.Security.Cryptography; +using Febe.Installer.Windows; + +namespace Febe.Installer; + +/// +/// The entry point. With a package footer at the end of its own file it is the installer (Febe.exe inside) or the +/// uninstaller; with --impacchetta, --verifica or --zip it is the build tool, on any system. +/// +internal static class Program +{ + [STAThread] + public static int Main(string[] args) + { + CommandLine line; + try + { + line = CommandLine.Parse(args); + } + catch (ArgumentException ex) + { + return Report(ex.Message, args); + } + + if (line.Tool != ToolCommand.None) + { + return RunTool(line); + } + + if (!OperatingSystem.IsWindows()) + { + Console.Error.WriteLine(Texts.WindowsOnly); + return ExitCodes.Failed; + } + + return RunOnWindows(line); + } + + [System.Runtime.Versioning.SupportedOSPlatform("windows")] + private static int RunOnWindows(CommandLine line) + { + var self = Environment.ProcessPath; + Locations locations; + try + { + locations = line.TestRoot is { } root ? Locations.ForTest(root) : Locations.ForUser(); + } + catch (ArgumentException ex) + { + // CommandLine.Parse already refuses what ForTest refuses: this is the last net, said like a wrong line. + return Report(ex.Message, line.Silent ? ["/S"] : []); + } + + // With /S the reason of a failure goes to the standard error, in UTF-8 whatever the code page of the console. + ISetupInterface ui = line.Silent + ? new SilentInterface(new StreamWriter(Console.OpenStandardError(), new System.Text.UTF8Encoding(false)) { AutoFlush = true }) + : new DialogInterface(locations); + PackageInfo? package; + try + { + package = self is null ? null : Package.Read(self); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException) + { + ui.Failed(uninstalling: false, Texts.Failure(ex)); + return ExitCodes.Failed; + } + + if (package is null || self is null) + { + ui.Failed(uninstalling: false, Texts.NoPackage); + return ExitCodes.Failed; + } + + SetupFlow.RemoveOldUninstallerCopies(locations, self); + var flow = new SetupFlow(new WindowsSystem(), locations, ui); + try + { + return package.Kind == PackageKind.Installer ? flow.Install(self, package, line) : flow.Uninstall(self, line); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or System.ComponentModel.Win32Exception or System.Runtime.InteropServices.COMException) + { + ui.Failed(package.Kind == PackageKind.Uninstaller, Texts.Failure(ex)); + return ExitCodes.Failed; + } + } + + /// A wrong command line: said in a dialog, or on the standard error with /S or for the build tool. + private static int Report(string message, string[] args) + { + var silent = args.Any(a => string.Equals(a, "/S", StringComparison.OrdinalIgnoreCase)); + if (OperatingSystem.IsWindows() && !silent && !(args.Length > 0 && args[0].StartsWith("--", StringComparison.Ordinal))) + { + new DialogInterface(Locations.ForUser()).Failed(uninstalling: false, message); + } + else + { + Console.Error.WriteLine(message); + } + + return ExitCodes.Failed; + } + + private static int RunTool(CommandLine line) + { + var a = line.ToolArguments; + try + { + switch (line.Tool) + { + case ToolCommand.Pack: + { + var info = Package.Write(a[0], a[1], a[2], a[3]); + Console.WriteLine($"Pacchetto {Path.GetFileName(a[3])}: programma {info.StubLength / 1048576.0:F1} MB, Febe.exe {info.ProgramLength / 1048576.0:F1} MB compresso in {info.DataLength / 1048576.0:F1} MB, versione {info.Version}."); + return ExitCodes.Done; + } + + case ToolCommand.Verify: + return Verify(a[0], a[1]); + + default: + Zip(a[0], a.Skip(1).ToArray()); + Console.WriteLine($"Zip {Path.GetFileName(a[0])}: {a.Count - 1} file."); + return ExitCodes.Done; + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or ArgumentException) + { + Console.Error.WriteLine(ex.Message); + return ExitCodes.Failed; + } + } + + /// + /// Checks a package as the installer will read it: a footer of an installer, and inside exactly + /// , decompressed to a file beside and compared byte for byte (then deleted). + /// + private static int Verify(string packagePath, string program) + { + var info = Package.Read(packagePath); + if (info is not { Kind: PackageKind.Installer }) + { + Console.Error.WriteLine($"{packagePath} non è un programma di installazione di Febe."); + return ExitCodes.Failed; + } + + var extracted = packagePath + ".verifica"; + try + { + Package.ExtractProgram(packagePath, info, extracted); + if (!SameContent(extracted, program)) + { + Console.Error.WriteLine($"Il Febe.exe dentro {Path.GetFileName(packagePath)} non è {program}."); + return ExitCodes.Failed; + } + } + finally + { + Package.TryDelete(extracted); + } + + Console.WriteLine($"{Path.GetFileName(packagePath)}: Febe {info.Version}, Febe.exe integro ({info.ProgramLength} byte)."); + return ExitCodes.Done; + } + + private static bool SameContent(string a, string b) + { + using var first = File.OpenRead(a); + using var second = File.OpenRead(b); + return first.Length == second.Length && SHA256.HashData(first).AsSpan().SequenceEqual(SHA256.HashData(second)); + } + + /// The portable zip: each file at the top, by its name, at the strongest compression of Deflate. + internal static void Zip(string output, IReadOnlyList files) + { + var partial = output + ".part"; + try + { + using (var stream = new FileStream(partial, FileMode.Create, FileAccess.Write, FileShare.None)) + using (var archive = new ZipArchive(stream, ZipArchiveMode.Create)) + { + foreach (var file in files) + { + archive.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.SmallestSize); + } + } + + File.Move(partial, output, overwrite: true); + } + catch + { + Package.TryDelete(partial); + throw; + } + } +} diff --git a/src/Febe.Installer/SetupActions.cs b/src/Febe.Installer/SetupActions.cs new file mode 100644 index 0000000..8018905 --- /dev/null +++ b/src/Febe.Installer/SetupActions.cs @@ -0,0 +1,282 @@ +namespace Febe.Installer; + +/// What an installation asks for: from which package, into which folder, with or without the desktop shortcut. +internal sealed record InstallRequest(string PackagePath, PackageInfo Package, string InstallFolder, bool DesktopShortcut); + +/// +/// The work of the installer and of the uninstaller, without dialogs (spec §12, question 6 of §16): exactly what the +/// installer built with a third-party tool did until 18 November 2026. +/// +/// Per user, without administrator rights, by default in %LOCALAPPDATA%\Programs\Febe. +/// Febe.exe and «Disinstalla Febe.exe»; the shortcut in the Start menu, the one on the desktop if chosen. +/// The uninstall entry under HKCU (Apps installed). +/// An installation over an existing one replaces the program and keeps everything else. +/// The uninstallation removes only the program, its shortcuts, its registry entries and the libraries Febe.exe +/// extracts by itself: NEVER the Data folder or the library, and it asks nothing about them. +/// +/// +internal sealed class SetupActions(ISystemAccess system, Locations locations) +{ + private const string NewSuffix = ".nuovo"; + + public Locations Locations => locations; + + /// + /// True when Febe.exe in is running: Windows refuses to open a running program + /// for writing with a sharing violation (an ), so it could be neither replaced nor deleted. + /// A refusal of the permissions (read-only file, an access list) is not an open Febe: «Riprova» could never help, + /// so it is not reported here; the installation clears the read-only attribute of its own files, and what is still + /// refused comes out of the copy as «Windows non permette di scrivere qui». + /// + public static bool IsFebeOpen(string installFolder) + { + var executable = Path.Combine(installFolder, Product.Executable); + if (!File.Exists(executable)) + { + return false; + } + + try + { + using var stream = new FileStream(executable, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete); + return false; + } + catch (UnauthorizedAccessException) + { + return false; + } + catch (IOException) + { + return true; + } + } + + /// The version recorded by an earlier installation, null for none. + public string? InstalledVersion() => system.ReadUserString(locations.UninstallKey, "DisplayVersion"); + + /// + /// The program folder recorded by an earlier installation (InstallLocation of the uninstall entry), null when + /// there is none or it is not a full path: an installation without /D= goes where Febe already is, so an + /// update replaces that program instead of leaving it behind with no entry in Apps installed. + /// + public string? InstalledFolder() + { + var folder = system.ReadUserString(locations.UninstallKey, "InstallLocation")?.Trim(); + return folder is { Length: > 0 } && Path.IsPathFullyQualified(folder) && Path.GetFileName(Path.TrimEndingDirectorySeparator(folder)).Length > 0 + ? Path.TrimEndingDirectorySeparator(folder) + : null; + } + + /// + /// The version of the WebView2 runtime of Microsoft, null when it is missing. The Evergreen runtime is installed for + /// the whole computer (32-bit node of the registry on 64-bit Windows) or for the user only; «0.0.0.0» means removed. + /// + public string? WebView2Version() + { + foreach (var value in new[] + { + system.ReadMachineString(@"SOFTWARE\WOW6432Node\" + Product.EdgeUpdateClient, "pv"), + system.ReadMachineString(@"SOFTWARE\" + Product.EdgeUpdateClient, "pv"), + system.ReadUserString(@"Software\" + Product.EdgeUpdateClient, "pv"), + }) + { + if (!string.IsNullOrWhiteSpace(value) && value != "0.0.0.0") + { + return value; + } + } + + return null; + } + + /// Where the data are: the folder chosen in Impostazioni (recorded by Febe) or the default one. + public string DataFolder() => + system.ReadUserString(locations.FebeKey, Product.DataFolderValue) is { Length: > 0 } folder ? folder : locations.DefaultDataFolder; + + /// The command line of the uninstaller, as the uninstall entry records it. + public string UninstallCommand(string installFolder, bool silent) + { + var command = $"\"{Path.Combine(installFolder, Product.Uninstaller)}\""; + if (silent) + { + command += " /S"; + } + + if (locations.TestRoot is { } root) + { + command += $" \"/PROVA={root}\""; + } + + return command; + } + + /// + /// Installs: Febe.exe (written beside and renamed, so an interrupted copy never leaves half a program), the + /// uninstaller, the shortcuts and the uninstall entry. gets the share done, 0 to 1. + /// + public void Install(InstallRequest request, Action? progress = null) + { + var folder = request.InstallFolder; + Directory.CreateDirectory(folder); + var executable = Path.Combine(folder, Product.Executable); + Replace(executable, partial => Package.ExtractProgram(request.PackagePath, request.Package, partial, share => progress?.Invoke(share * 0.95))); + Replace(Path.Combine(folder, Product.Uninstaller), partial => Package.WriteUninstaller(request.PackagePath, request.Package, partial)); + progress?.Invoke(0.97); + + system.CreateShortcut(ShortcutTo(locations.StartMenuShortcut, folder)); + + var key = locations.UninstallKey; + system.WriteUserString(key, "DisplayName", Product.Name); + system.WriteUserString(key, "DisplayVersion", request.Package.Version); + system.WriteUserString(key, "Publisher", Product.Publisher); + system.WriteUserString(key, "DisplayIcon", executable + ",0"); + system.WriteUserString(key, "InstallLocation", folder); + system.WriteUserString(key, "UninstallString", UninstallCommand(folder, silent: false)); + system.WriteUserString(key, "QuietUninstallString", UninstallCommand(folder, silent: true)); + system.WriteUserString(key, "URLInfoAbout", Product.Site); + system.WriteUserDword(key, "NoModify", 1); + system.WriteUserDword(key, "NoRepair", 1); + system.WriteUserDword(key, "EstimatedSize", EstimatedSizeInKb(folder)); + + if (request.DesktopShortcut) + { + system.CreateShortcut(ShortcutTo(locations.DesktopShortcut, folder)); + } + + progress?.Invoke(1); + } + + /// + /// Uninstalls the Febe of : the program files (the folder itself only if nothing + /// else is left in it), the two shortcuts, «Start with the computer» («Febe» and the «Febe-…» values that start + /// this Febe.exe), the uninstall entry and the libraries extracted under %TEMP%. Nothing else. + /// + public void Uninstall(string installFolder) + { + var executable = Path.Combine(installFolder, Product.Executable); + DeleteFile(executable); + DeleteFile(executable + NewSuffix); + DeleteUninstaller(Path.Combine(installFolder, Product.Uninstaller)); + DeleteFile(Path.Combine(installFolder, Product.Uninstaller) + NewSuffix); + try + { + // Only when empty: whatever else is there is not ours to delete. + Directory.Delete(installFolder, recursive: false); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + + DeleteFile(locations.StartMenuShortcut); + DeleteFile(locations.DesktopShortcut); + + // «Start Febe with the computer» would point to a program that is no longer there. Only the values that start + // this Febe.exe, «Febe» included: a portable Febe with the default Data folder writes «Febe» for itself. + var command = $"\"{executable}\""; + foreach (var name in system.UserValueNames(locations.RunKey)) + { + if ((name.Equals(Product.AutostartValue, StringComparison.OrdinalIgnoreCase) || name.StartsWith(Product.AutostartPrefix, StringComparison.OrdinalIgnoreCase)) + && system.ReadUserString(locations.RunKey, name) is { } value + && value.StartsWith(command, StringComparison.OrdinalIgnoreCase)) + { + system.DeleteUserValue(locations.RunKey, name); + } + } + + system.DeleteUserKeyTree(locations.UninstallKey); + + // The native libraries Febe.exe extracts by itself on the first start: not data. + try + { + if (Directory.Exists(locations.ExtractionFolder)) + { + Directory.Delete(locations.ExtractionFolder, recursive: true); + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // A portable Febe still running holds them: they stay, Windows cleans %TEMP%. + } + } + + private static Shortcut ShortcutTo(string path, string installFolder) + { + var executable = Path.Combine(installFolder, Product.Executable); + return new Shortcut(path, executable, installFolder, Product.ShortcutDescription, executable, 0); + } + + private static void Replace(string path, Action write) + { + var partial = path + NewSuffix; + try + { + write(partial); + ClearReadOnly(path); + File.Move(partial, path, overwrite: true); + } + catch + { + Package.TryDelete(partial); + throw; + } + } + + private static void DeleteFile(string path) + { + if (File.Exists(path)) + { + ClearReadOnly(path); + File.Delete(path); + } + } + + /// + /// A file of the program left read-only (by a copy, a restore, an archive): Windows refuses to replace or delete + /// it while the attribute is there. Only the attribute: an access list that says no stays a refusal. + /// + private static void ClearReadOnly(string path) + { + var file = new FileInfo(path); + if (file.Exists && file.IsReadOnly) + { + file.IsReadOnly = false; + } + } + + /// The uninstaller that started this one may take a moment to end and release its file. + private void DeleteUninstaller(string path) + { + for (var attempt = 0; ; attempt++) + { + try + { + DeleteFile(path); + return; + } + catch (Exception ex) when ((ex is IOException or UnauthorizedAccessException) && attempt < 20) + { + system.Pause(TimeSpan.FromMilliseconds(250)); + } + } + } + + /// + /// The size for Apps installed: only the two files the installation writes. Never a walk of the folder, which may + /// be large or a drive root (/D=D:\) with folders nobody may read, and would fail after the program has + /// already been replaced. + /// + private static int EstimatedSizeInKb(string folder) + { + long bytes = 0; + foreach (var name in new[] { Product.Executable, Product.Uninstaller }) + { + var file = new FileInfo(Path.Combine(folder, name)); + if (file.Exists) + { + bytes += file.Length; + } + } + + return (int)Math.Min(int.MaxValue, bytes / 1024); + } +} diff --git a/src/Febe.Installer/SetupFlow.cs b/src/Febe.Installer/SetupFlow.cs new file mode 100644 index 0000000..afe0257 --- /dev/null +++ b/src/Febe.Installer/SetupFlow.cs @@ -0,0 +1,230 @@ +namespace Febe.Installer; + +/// The exit codes of the installer and of the uninstaller. +internal static class ExitCodes +{ + public const int Done = 0; + + /// Alberto said no: «Annulla». + public const int Cancelled = 1; + + /// Something went wrong, or Febe is open in silent mode: nothing was changed, or only the part said. + public const int Failed = 2; +} + +/// +/// The dialogs of the installation: the windows of Windows (DialogInterface) or, with /S, none +/// (). The tests use a fake that answers as told. +/// +internal interface ISetupInterface +{ + /// The first page; null for «Annulla», otherwise whether the desktop shortcut is wanted. + bool? Welcome(string version, string? installedVersion, string installFolder); + + /// Febe is open: true to try again (after closing it), false to give up. + bool RetryWhenFebeIsOpen(bool uninstalling); + + /// Runs showing its progress (0 to 1); its exception comes out of here. + void RunWithProgress(string version, string installFolder, Action> work); + + /// WebView2 is missing: true to open the page of Microsoft. + bool OfferWebView2Page(); + + /// The last page of the installation: true to start Febe now. + bool Installed(); + + bool ConfirmUninstall(); + + void Uninstalled(string dataFolder, string library); + + void Failed(bool uninstalling, string message); +} + +/// +/// /S: no dialog, the answers of the silent mode before: the desktop shortcut yes, Febe open means stop, the page +/// of WebView2 no, Febe not started. A failure goes to the standard error, for whoever started the installer. +/// +internal sealed class SilentInterface(TextWriter errors) : ISetupInterface +{ + public bool? Welcome(string version, string? installedVersion, string installFolder) => true; + + public bool RetryWhenFebeIsOpen(bool uninstalling) => false; + + public void RunWithProgress(string version, string installFolder, Action> work) => work(_ => { }); + + public bool OfferWebView2Page() => false; + + public bool Installed() => false; + + public bool ConfirmUninstall() => true; + + public void Uninstalled(string dataFolder, string library) + { + } + + public void Failed(bool uninstalling, string message) + { + try + { + errors.WriteLine((uninstalling ? Texts.UninstallFailed : Texts.InstallFailed) + ": " + message); + errors.Flush(); + } + catch (IOException) + { + // No one is reading: the exit code says it. + } + } +} + +/// +/// The steps of the installer and of the uninstaller, in the order they always had: first page, Febe closed, copy, +/// WebView2, last page; for the uninstaller: a copy of itself in %TEMP% (an executable cannot delete itself), +/// confirmation, Febe closed, removal, where the data stayed. +/// +internal sealed class SetupFlow(ISystemAccess system, Locations locations, ISetupInterface ui) +{ + private readonly SetupActions _actions = new(system, locations); + + /// The installer: is this program, with Febe.exe inside. + public int Install(string packagePath, PackageInfo package, CommandLine line) + { + // Without /D= an update goes where Febe already is, not to the default folder: otherwise the old program would + // stay there, orphaned, while the entry and the shortcuts moved to a second copy. + var folder = line.InstallFolder ?? _actions.InstalledFolder() ?? locations.DefaultInstallFolder; + var desktop = ui.Welcome(package.Version, _actions.InstalledVersion(), folder); + if (desktop is null) + { + return ExitCodes.Cancelled; + } + + if (!WaitUntilFebeIsClosed(folder, uninstalling: false, line.Silent)) + { + return line.Silent ? ExitCodes.Failed : ExitCodes.Cancelled; + } + + try + { + ui.RunWithProgress(package.Version, folder, progress => + _actions.Install(new InstallRequest(packagePath, package, folder, desktop.Value), progress)); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException or InvalidOperationException) + { + ui.Failed(uninstalling: false, Texts.Failure(ex)); + return ExitCodes.Failed; + } + + // WebView2: without it Febe cannot show anything. Febe says it too on its first start. + if (_actions.WebView2Version() is null && ui.OfferWebView2Page()) + { + system.OpenAddress(Product.WebView2Page); + } + + if (ui.Installed()) + { + try + { + system.Start(Path.Combine(folder, Product.Executable), [], folder); + } + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException or IOException) + { + // Febe is installed all the same; it opens from the Start menu. + } + } + + return ExitCodes.Done; + } + + /// + /// The uninstaller. Started from the program folder ( is «Disinstalla Febe.exe» there), it + /// copies itself into %TEMP%, starts the copy and ends; the copy waits for it, then does the work and can delete + /// the original. + /// + public int Uninstall(string selfPath, CommandLine line) + { + if (line.UninstallFolder is null) + { + var installFolder = Path.GetDirectoryName(Path.GetFullPath(selfPath))!; + Directory.CreateDirectory(locations.Temp); + var copy = Path.Combine(locations.Temp, $"{Product.UninstallerCopyPrefix}{Environment.ProcessId}.exe"); + File.Copy(selfPath, copy, overwrite: true); + system.Start(copy, [.. line.PassOn(), "/_?=" + installFolder, $"/ATTENDI={Environment.ProcessId}"], locations.Temp); + return ExitCodes.Done; + } + + if (line.WaitFor is { } parent) + { + system.WaitForExit(parent, TimeSpan.FromSeconds(30)); + } + + var folder = line.UninstallFolder; + if (!ui.ConfirmUninstall()) + { + return ExitCodes.Cancelled; + } + + if (!WaitUntilFebeIsClosed(folder, uninstalling: true, line.Silent)) + { + return line.Silent ? ExitCodes.Failed : ExitCodes.Cancelled; + } + + // Read before anything is removed, to say at the end where the data stayed. + var dataFolder = _actions.DataFolder(); + try + { + _actions.Uninstall(folder); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + ui.Failed(uninstalling: true, Texts.Failure(ex)); + return ExitCodes.Failed; + } + + ui.Uninstalled(dataFolder, locations.Library); + return ExitCodes.Done; + } + + /// + /// Copies of the uninstaller left in %TEMP% by earlier uninstallations (a running program cannot delete itself): + /// removed when they are no longer running. Never anything else. + /// + public static void RemoveOldUninstallerCopies(Locations locations, string? selfPath) + { + try + { + if (!Directory.Exists(locations.Temp)) + { + return; + } + + foreach (var copy in Directory.EnumerateFiles(locations.Temp, Product.UninstallerCopyPrefix + "*.exe")) + { + if (selfPath is null || !string.Equals(Path.GetFullPath(copy), Path.GetFullPath(selfPath), StringComparison.OrdinalIgnoreCase)) + { + Package.TryDelete(copy); + } + } + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + } + + private bool WaitUntilFebeIsClosed(string folder, bool uninstalling, bool silent) + { + while (SetupActions.IsFebeOpen(folder)) + { + if (silent) + { + ui.Failed(uninstalling, Texts.FebeOpenSilent); + return false; + } + + if (!ui.RetryWhenFebeIsOpen(uninstalling)) + { + return false; + } + } + + return true; + } +} diff --git a/src/Febe.Installer/Texts.cs b/src/Febe.Installer/Texts.cs new file mode 100644 index 0000000..9347804 --- /dev/null +++ b/src/Febe.Installer/Texts.cs @@ -0,0 +1,99 @@ +namespace Febe.Installer; + +/// What the installer and the uninstaller say, in Italian (glossary: appendix D of the spec). +internal static class Texts +{ + public const string InstallTitle = "Installazione di Febe"; + + public const string UninstallTitle = "Disinstallazione di Febe"; + + public const string Damaged = "Il programma di installazione è rovinato o incompleto: scaricalo di nuovo."; + + public const string NoPackage = "Questo programma non contiene Febe: usa Febe-Setup-.exe dalla pagina delle release."; + + public const string WindowsOnly = "Il programma di installazione di Febe gira solo su Windows."; + + public const string Install = "Installa"; + + public const string Cancel = "Annulla"; + + public const string Retry = "Riprova"; + + public const string Finish = "Fine"; + + public const string Wait = "Attendi"; + + public const string Uninstall = "Disinstalla"; + + public const string OpenPage = "Apri la pagina"; + + public const string NotNow = "Non ora"; + + public const string DesktopShortcut = "Crea un collegamento a Febe sul desktop"; + + public const string RunFebe = "Apri Febe adesso"; + + public static string Welcome(string version, string? installedVersion) => + installedVersion is null ? $"Installazione di Febe {version}" : $"Aggiornamento di Febe alla versione {version}"; + + public static string WelcomeText(Locations locations, string installFolder, string? installedVersion) + { + var text = + "Febe è l'archivio personale di foto, video e storie da Instagram.\n\n" + + $"Verrà installato solo per te, in {installFolder}: non servono permessi di amministratore.\n\n" + + $"I dati di Febe (database e sessione del browser) andranno in {locations.DefaultDataFolder}, le foto e i video " + + "nella cartella Immagini\\Febe; le cartelle si possono cambiare dalle Impostazioni."; + return installedVersion is null + ? text + : $"Febe {installedVersion} è già installato: il programma si sostituisce, i dati, la libreria e le impostazioni restano dove sono.\n\n" + text; + } + + public const string FebeOpen = "Febe è aperto"; + + public const string FebeOpenText = "Chiudilo dall'area di notifica (clic destro sull'icona ▸ Esci), poi premi Riprova."; + + public const string FebeOpenSilent = "Febe è aperto: chiudilo dall'area di notifica (clic destro sull'icona ▸ Esci) e riprova."; + + public static string Installing(string version) => $"Installazione di Febe {version} in corso"; + + public static string InstallingText(string installFolder) => $"Copia di Febe.exe in {installFolder}…"; + + public const string WebView2Missing = "Manca il runtime WebView2 di Microsoft"; + + public const string WebView2MissingText = + "Febe ha bisogno del runtime WebView2 di Microsoft, che su questo computer non c'è (Windows 11 e quasi tutti i " + + "Windows 10 lo hanno già).\n\nSi installa gratis dalla pagina ufficiale di Microsoft, senza permessi di " + + "amministratore. Vuoi aprirla adesso?"; + + public const string Installed = "Febe è installato"; + + public const string InstalledText = + "Febe si apre in una sua finestra e resta attivo nell'area di notifica, accanto all'orologio.\n\n" + + "Per collegarlo a Instagram: Impostazioni ▸ Collegamento. Non usare insieme Febe per Windows e il contenitore " + + "Docker con lo stesso account."; + + public const string InstallFailed = "L'installazione non è riuscita"; + + public const string ConfirmUninstall = "Disinstallare Febe?"; + + public const string ConfirmUninstallText = + "Il programma Febe verrà tolto da questo computer. I tuoi dati restano dove sono: la disinstallazione non " + + "cancella né la cartella dei dati né la libreria con le foto e i video."; + + public const string Uninstalled = "Febe è stato disinstallato"; + + public static string UninstalledText(string dataFolder, string library) => + "I dati di Febe non sono stati toccati:\n\n" + + $"- cartella dei dati: {dataFolder}\n" + + $"- libreria: {library}, o la cartella scelta nelle Impostazioni.\n\n" + + "La cartella dei dati contiene la sessione di Instagram: se non ti serve più, cancellala tu."; + + public const string UninstallFailed = "La disinstallazione non è riuscita"; + + public static string Failure(Exception ex) => ex switch + { + InvalidDataException => ex.Message, + UnauthorizedAccessException => $"Windows non permette di scrivere qui: {ex.Message}", + _ => ex.Message, + }; +} diff --git a/src/Febe.Installer/Windows/DialogInterface.cs b/src/Febe.Installer/Windows/DialogInterface.cs new file mode 100644 index 0000000..0cedb49 --- /dev/null +++ b/src/Febe.Installer/Windows/DialogInterface.cs @@ -0,0 +1,103 @@ +using System.Runtime.Versioning; + +namespace Febe.Installer.Windows; + +/// The pages of the installer and of the uninstaller, as dialogs of Windows (texts: ). +[SupportedOSPlatform("windows")] +internal sealed class DialogInterface(Locations locations) : ISetupInterface +{ + internal const int Yes = 100; + + private const int Cancel = TaskDialog.CancelId; + + public bool? Welcome(string version, string? installedVersion, string installFolder) + { + var (button, desktop) = TaskDialog.Show(Texts.InstallTitle, new DialogPage( + Texts.Welcome(version, installedVersion), + Texts.WelcomeText(locations, installFolder, installedVersion), + [(Yes, Texts.Install), (Cancel, Texts.Cancel)]) + { + Verification = Texts.DesktopShortcut, + VerificationChecked = true, + }); + return button == Yes ? desktop : null; + } + + public bool RetryWhenFebeIsOpen(bool uninstalling) + { + var (button, _) = TaskDialog.Show(Title(uninstalling), new DialogPage( + Texts.FebeOpen, + Texts.FebeOpenText, + [(Yes, Texts.Retry), (Cancel, Texts.Cancel)]) + { + Icon = DialogIcon.Warning, + }); + return button == Yes; + } + + public void RunWithProgress(string version, string installFolder, Action> work) => + TaskDialog.ShowProgress(Texts.InstallTitle, new DialogPage( + Texts.Installing(version), + Texts.InstallingText(installFolder), + [(Yes, Texts.Wait)]), work); + + public bool OfferWebView2Page() + { + var (button, _) = TaskDialog.Show(Texts.InstallTitle, new DialogPage( + Texts.WebView2Missing, + Texts.WebView2MissingText, + [(Yes, Texts.OpenPage), (Cancel, Texts.NotNow)]) + { + Icon = DialogIcon.Information, + }); + return button == Yes; + } + + public bool Installed() + { + var (button, run) = TaskDialog.Show(Texts.InstallTitle, new DialogPage( + Texts.Installed, + Texts.InstalledText, + [(Yes, Texts.Finish)]) + { + Verification = Texts.RunFebe, + VerificationChecked = true, + }); + return StartsFebe(button, run); + } + + /// + /// «Apri Febe adesso» counts only with «Fine»: Esc or the close button dismiss the page and start nothing, even + /// with the box ticked (Windows gives back its state on a cancel too). + /// + internal static bool StartsFebe(int button, bool runChecked) => button == Yes && runChecked; + + public bool ConfirmUninstall() + { + var (button, _) = TaskDialog.Show(Texts.UninstallTitle, new DialogPage( + Texts.ConfirmUninstall, + Texts.ConfirmUninstallText, + [(Yes, Texts.Uninstall), (Cancel, Texts.Cancel)])); + return button == Yes; + } + + public void Uninstalled(string dataFolder, string library) => + TaskDialog.Show(Texts.UninstallTitle, new DialogPage( + Texts.Uninstalled, + Texts.UninstalledText(dataFolder, library), + [(Yes, Texts.Finish)]) + { + Icon = DialogIcon.Information, + }); + + public void Failed(bool uninstalling, string message) => + TaskDialog.Show(Title(uninstalling), new DialogPage( + uninstalling ? Texts.UninstallFailed : Texts.InstallFailed, + message, + [(Yes, Texts.Finish)]) + { + Icon = DialogIcon.Error, + }); + + private static string Title(bool uninstalling) => uninstalling ? Texts.UninstallTitle : Texts.InstallTitle; +} diff --git a/src/Febe.Installer/Windows/ShellLinks.cs b/src/Febe.Installer/Windows/ShellLinks.cs new file mode 100644 index 0000000..215f765 --- /dev/null +++ b/src/Febe.Installer/Windows/ShellLinks.cs @@ -0,0 +1,129 @@ +using System.Runtime.InteropServices; +using System.Runtime.InteropServices.Marshalling; +using System.Runtime.Versioning; + +namespace Febe.Installer.Windows; + +/// +/// Shortcuts (.lnk) through the ShellLink object of Windows (IShellLinkW and IPersistFile), with the +/// COM interop that .NET generates at compile time: it survives trimming and needs no package. +/// +[SupportedOSPlatform("windows")] +internal static unsafe partial class ShellLinks +{ + private const uint ClassContextInprocServer = 1; + + private const int ShowNormal = 1; + + private const uint ReadMode = 0; + + private const uint RawPath = 4; + + private static readonly Guid ShellLinkClass = new(0x00021401, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46); + + private static readonly Guid ShellLinkInterface = new(0x000214F9, 0, 0, 0xC0, 0, 0, 0, 0, 0, 0, 0x46); + + private static readonly StrategyBasedComWrappers Wrappers = new(); + + /// Writes , replacing a shortcut already there. + public static void Create(Shortcut shortcut) + { + var link = New(); + link.SetPath(shortcut.Target); + link.SetWorkingDirectory(shortcut.WorkingDirectory); + link.SetDescription(shortcut.Description); + link.SetIconLocation(shortcut.IconPath, shortcut.IconIndex); + link.SetShowCmd(ShowNormal); + Directory.CreateDirectory(Path.GetDirectoryName(shortcut.Path)!); + ((IPersistFile)link).Save(shortcut.Path, true); + } + + /// Reads back a shortcut: target, working folder and description (for the tests). + public static (string Target, string WorkingDirectory, string Description) Read(string path) + { + var link = New(); + ((IPersistFile)link).Load(path, ReadMode); + var buffer = stackalloc char[1024]; + link.GetPath(buffer, 1024, 0, RawPath); + var target = new string(buffer); + link.GetWorkingDirectory(buffer, 1024); + var folder = new string(buffer); + link.GetDescription(buffer, 1024); + return (target, folder, new string(buffer)); + } + + private static IShellLinkW New() + { + Marshal.ThrowExceptionForHR(CoCreateInstance(in ShellLinkClass, 0, ClassContextInprocServer, in ShellLinkInterface, out var pointer)); + try + { + return (IShellLinkW)Wrappers.GetOrCreateObjectForComInstance(pointer, CreateObjectFlags.None); + } + finally + { + Marshal.Release(pointer); + } + } + + [LibraryImport("ole32.dll")] + private static partial int CoCreateInstance(in Guid classId, nint outer, uint context, in Guid interfaceId, out nint instance); +} + +[GeneratedComInterface(StringMarshalling = StringMarshalling.Utf16)] +[Guid("000214F9-0000-0000-C000-000000000046")] +internal unsafe partial interface IShellLinkW +{ + void GetPath(char* file, int length, nint findData, uint flags); + + void GetIDList(out nint list); + + void SetIDList(nint list); + + void GetDescription(char* name, int length); + + void SetDescription(string name); + + void GetWorkingDirectory(char* directory, int length); + + void SetWorkingDirectory(string directory); + + void GetArguments(char* arguments, int length); + + void SetArguments(string arguments); + + void GetHotkey(out ushort hotkey); + + void SetHotkey(ushort hotkey); + + void GetShowCmd(out int show); + + void SetShowCmd(int show); + + void GetIconLocation(char* iconPath, int length, out int icon); + + void SetIconLocation(string iconPath, int icon); + + void SetRelativePath(string relativePath, uint reserved); + + void Resolve(nint window, uint flags); + + void SetPath(string file); +} + +[GeneratedComInterface(StringMarshalling = StringMarshalling.Utf16)] +[Guid("0000010b-0000-0000-C000-000000000046")] +internal partial interface IPersistFile +{ + void GetClassID(out Guid classId); + + [PreserveSig] + int IsDirty(); + + void Load(string fileName, uint mode); + + void Save(string? fileName, [MarshalAs(UnmanagedType.Bool)] bool remember); + + void SaveCompleted(string fileName); + + void GetCurFile(out nint fileName); +} diff --git a/src/Febe.Installer/Windows/TaskDialog.cs b/src/Febe.Installer/Windows/TaskDialog.cs new file mode 100644 index 0000000..db68570 --- /dev/null +++ b/src/Febe.Installer/Windows/TaskDialog.cs @@ -0,0 +1,253 @@ +using System.Runtime.CompilerServices; +using System.Runtime.ExceptionServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +namespace Febe.Installer.Windows; + +/// The standard icons of the dialog of Windows. +internal enum DialogIcon +{ + None = 0, + Warning = 0xFFFF, + Error = 0xFFFE, + Information = 0xFFFD, +} + +/// One page of a dialog: texts, buttons (the first is the default) and the check box at the bottom. +internal sealed record DialogPage(string Instruction, string Content, IReadOnlyList<(int Id, string Text)> Buttons) +{ + public DialogIcon Icon { get; init; } + + /// The text of the check box at the bottom, null for none. + public string? Verification { get; init; } + + public bool VerificationChecked { get; init; } + + /// Esc and the close button answer . + public bool AllowCancel { get; init; } = true; +} + +/// +/// The dialog of Windows (TaskDialogIndirect of the common controls, version 6 through the manifest): the +/// pages of the installer without a window framework, so the installer can be trimmed and stays small. +/// +[SupportedOSPlatform("windows")] +internal static unsafe partial class TaskDialog +{ + public const int CancelId = 2; + + private const int AllowDialogCancellation = 0x0008; + private const int VerificationFlagChecked = 0x0100; + private const int ShowProgressBar = 0x0200; + private const int CallbackTimer = 0x0800; + private const int SizeToContent = 0x01000000; + + private const uint Created = 0; + private const uint ButtonClicked = 2; + private const uint Timer = 4; + + private const uint UserMessage = 0x0400; + private const uint ClickButton = UserMessage + 102; + private const uint SetProgressBarPosition = UserMessage + 106; + private const uint EnableButton = UserMessage + 111; + + private const int Ok = 0; + private const int False = 1; + + /// Shows and waits: the button pressed and the state of the check box. + public static (int Button, bool Checked) Show(string title, DialogPage page) => Run(title, page, 0, 0); + + /// + /// Shows with a progress bar while runs on another thread; its + /// only button stays disabled and the dialog closes by itself at the end. The exception of the work comes out of here. + /// + public static void ShowProgress(string title, DialogPage page, Action> work) + { + var state = new ProgressState(work, page.Buttons[0].Id); + var handle = GCHandle.Alloc(state); + try + { + Run(title, page with { AllowCancel = false }, ShowProgressBar | CallbackTimer, GCHandle.ToIntPtr(handle)); + } + finally + { + handle.Free(); + } + + state.Error?.Throw(); + } + + private static (int Button, bool Checked) Run(string title, DialogPage page, int extraFlags, nint callbackData) + { + var strings = new List(); + nint Text(string? value) + { + if (value is null) + { + return 0; + } + + var pointer = Marshal.StringToHGlobalUni(value); + strings.Add(pointer); + return pointer; + } + + var buttons = (Button*)NativeMemory.Alloc((nuint)page.Buttons.Count, (nuint)sizeof(Button)); + try + { + for (var i = 0; i < page.Buttons.Count; i++) + { + buttons[i] = new Button { Id = page.Buttons[i].Id, Text = (char*)Text(page.Buttons[i].Text) }; + } + + var flags = SizeToContent | extraFlags; + if (page.AllowCancel) + { + flags |= AllowDialogCancellation; + } + + if (page.VerificationChecked) + { + flags |= VerificationFlagChecked; + } + + var config = new Config + { + Size = (uint)sizeof(Config), + Flags = flags, + WindowTitle = (char*)Text(title), + MainIcon = (nint)page.Icon, + MainInstruction = (char*)Text(page.Instruction), + Content = (char*)Text(page.Content), + ButtonCount = (uint)page.Buttons.Count, + Buttons = buttons, + DefaultButton = page.Buttons[0].Id, + VerificationText = (char*)Text(page.Verification), + Callback = callbackData == 0 ? null : &ProgressCallback, + CallbackData = callbackData, + }; + int pressed; + int verified; + Marshal.ThrowExceptionForHR(TaskDialogIndirect(&config, &pressed, null, &verified)); + return (pressed, verified != 0); + } + finally + { + NativeMemory.Free(buttons); + foreach (var pointer in strings) + { + Marshal.FreeHGlobal(pointer); + } + } + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] + private static int ProgressCallback(nint window, uint message, nint wParam, nint lParam, nint data) + { + try + { + var state = (ProgressState)GCHandle.FromIntPtr(data).Target!; + switch (message) + { + case Created: + SendMessageW(window, EnableButton, state.ButtonId, 0); + state.Start(); + break; + case Timer: + SendMessageW(window, SetProgressBarPosition, state.Percent, 0); + if (state.Finished && !state.Closing) + { + state.Closing = true; + SendMessageW(window, EnableButton, state.ButtonId, 1); + SendMessageW(window, ClickButton, state.ButtonId, 0); + } + + break; + case ButtonClicked: + return state.Finished ? Ok : False; + } + } + catch (Exception) + { + // Nothing may escape into Windows; the work keeps its own error. + } + + return Ok; + } + + private sealed class ProgressState(Action> work, int buttonId) + { + private volatile bool _finished; + private volatile int _percent; + + public int ButtonId => buttonId; + + public int Percent => _percent; + + public bool Finished => _finished; + + public bool Closing { get; set; } + + public ExceptionDispatchInfo? Error { get; private set; } + + public void Start() => _ = Task.Run(() => + { + try + { + work(share => _percent = (int)Math.Clamp(share * 100, 0, 100)); + } + catch (Exception ex) + { + Error = ExceptionDispatchInfo.Capture(ex); + } + finally + { + _finished = true; + } + }); + } + + [StructLayout(LayoutKind.Sequential, Pack = 1)] + private struct Button + { + public int Id; + public char* Text; + } + + /// TASKDIALOGCONFIG of commctrl.h, packed to 1 byte as there. + [StructLayout(LayoutKind.Sequential, Pack = 1)] + private struct Config + { + public uint Size; + public nint Parent; + public nint Instance; + public int Flags; + public int CommonButtons; + public char* WindowTitle; + public nint MainIcon; + public char* MainInstruction; + public char* Content; + public uint ButtonCount; + public Button* Buttons; + public int DefaultButton; + public uint RadioButtonCount; + public Button* RadioButtons; + public int DefaultRadioButton; + public char* VerificationText; + public char* ExpandedInformation; + public char* ExpandedControlText; + public char* CollapsedControlText; + public nint FooterIcon; + public char* Footer; + public delegate* unmanaged[Stdcall] Callback; + public nint CallbackData; + public uint Width; + } + + [LibraryImport("comctl32.dll")] + private static partial int TaskDialogIndirect(Config* config, int* button, int* radioButton, int* verificationChecked); + + [LibraryImport("user32.dll")] + private static partial nint SendMessageW(nint window, uint message, nint wParam, nint lParam); +} diff --git a/src/Febe.Installer/Windows/WindowsSystem.cs b/src/Febe.Installer/Windows/WindowsSystem.cs new file mode 100644 index 0000000..1d9396e --- /dev/null +++ b/src/Febe.Installer/Windows/WindowsSystem.cs @@ -0,0 +1,95 @@ +using System.Diagnostics; +using System.Runtime.Versioning; +using Microsoft.Win32; + +namespace Febe.Installer.Windows; + +/// +/// on Windows: the registry of .NET (HKEY_CURRENT_USER for writing, HKEY_LOCAL_MACHINE only +/// read), the Shell for the shortcuts, for the rest. +/// +[SupportedOSPlatform("windows")] +internal sealed class WindowsSystem : ISystemAccess +{ + public string? ReadUserString(string key, string name) + { + using var opened = Registry.CurrentUser.OpenSubKey(key, writable: false); + return opened?.GetValue(name) as string; + } + + public int? ReadUserDword(string key, string name) + { + using var opened = Registry.CurrentUser.OpenSubKey(key, writable: false); + return opened?.GetValue(name) is int value ? value : null; + } + + public void WriteUserString(string key, string name, string value) + { + using var opened = Registry.CurrentUser.CreateSubKey(key, writable: true); + opened.SetValue(name, value, RegistryValueKind.String); + } + + public void WriteUserDword(string key, string name, int value) + { + using var opened = Registry.CurrentUser.CreateSubKey(key, writable: true); + opened.SetValue(name, value, RegistryValueKind.DWord); + } + + public IReadOnlyList UserValueNames(string key) + { + using var opened = Registry.CurrentUser.OpenSubKey(key, writable: false); + return opened?.GetValueNames() ?? []; + } + + public void DeleteUserValue(string key, string name) + { + using var opened = Registry.CurrentUser.OpenSubKey(key, writable: true); + opened?.DeleteValue(name, throwOnMissingValue: false); + } + + public void DeleteUserKeyTree(string key) => Registry.CurrentUser.DeleteSubKeyTree(key, throwOnMissingSubKey: false); + + public string? ReadMachineString(string key, string name) + { + using var machine = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); + using var opened = machine.OpenSubKey(key, writable: false); + return opened?.GetValue(name) as string; + } + + public void CreateShortcut(Shortcut shortcut) => ShellLinks.Create(shortcut); + + public void OpenAddress(string address) + { + using var process = Process.Start(new ProcessStartInfo(address) { UseShellExecute = true }); + } + + public void Start(string executable, IReadOnlyList arguments, string workingDirectory) + { + var start = new ProcessStartInfo(executable) { WorkingDirectory = workingDirectory, UseShellExecute = false }; + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start); + } + + public void WaitForExit(int processId, TimeSpan timeout) + { + try + { + using var process = Process.GetProcessById(processId); + process.WaitForExit(timeout); + } + catch (ArgumentException) + { + // Already ended. + } + catch (InvalidOperationException) + { + // Ended while looking at it. + } + } + + public void Pause(TimeSpan delay) => Thread.Sleep(delay); +} diff --git a/src/Febe.Installer/app.manifest b/src/Febe.Installer/app.manifest new file mode 100644 index 0000000..849d344 --- /dev/null +++ b/src/Febe.Installer/app.manifest @@ -0,0 +1,32 @@ + + + + + + + + + + + + + + + + + + + + true/pm + PerMonitorV2 + true + + + + + + + + diff --git a/src/Febe.Web/Api/ImportApi.cs b/src/Febe.Web/Api/ImportApi.cs index 7427833..01573d1 100644 --- a/src/Febe.Web/Api/ImportApi.cs +++ b/src/Febe.Web/Api/ImportApi.cs @@ -322,7 +322,8 @@ public static class ImportApi review.CanMove, review.StogramHypothesis, review.Copied, - [.. accounts.OrderBy(a => a.Username, StringComparer.Ordinal).Select(a => new AccountChoiceDto(a.Id, a.Username, ApiMapping.State(a.State)))]); + [.. accounts.OrderBy(a => a.Username, StringComparer.Ordinal).Select(a => new AccountChoiceDto(a.Id, a.Username, ApiMapping.State(a.State)))], + review.Damaged); } public static DuplicateCaseDto Case(DuplicateCase item, IClock clock) @@ -373,7 +374,9 @@ public static class ImportApi [.. report.ImportedByAccount.Select(a => new ImportCountDto(a.Username, a.Files))], [.. report.AlreadyInLibraryByAccount.Select(a => new ImportCountDto(a.Username, a.Files))], report.Unrecognized, - [.. report.Problems.Select(p => new ImportNoteDto(p.Path, p.Note))]); + [.. report.Problems.Select(p => new ImportNoteDto(p.Path, p.Note))], + report.DamagedCount, + report.Damaged ?? []); } private static ImportMode ParseMode(string? text) => text?.ToLowerInvariant() switch diff --git a/src/Febe.Web/Api/LibraryApi.cs b/src/Febe.Web/Api/LibraryApi.cs index 6b73f75..2fb98cb 100644 --- a/src/Febe.Web/Api/LibraryApi.cs +++ b/src/Febe.Web/Api/LibraryApi.cs @@ -227,7 +227,8 @@ public static class LibraryApi var local = LocalCalendar.ToLocal(entry.PublishedAt, zone); var accountFolder = Path.GetFileName(Path.TrimEndingDirectorySeparator(library.Layout.AccountFolder(account))); var avatar = await AccountsApi.AvatarAsync(storage, account.Id, ct).ConfigureAwait(false); - var media = stored.Media.Select(m => + var media = new List(stored.Media.Count); + foreach (var m in stored.Media) { var relative = m.RelativePath; string? folder = null; @@ -238,7 +239,8 @@ public static class LibraryApi } var path = files.Resolve(account, m); - return new MediaDto( + var damaged = await IsDamagedAsync(m, path, ct).ConfigureAwait(false); + media.Add(new MediaDto( m.Id, m.Position, ApiMapping.Media(m.Kind), @@ -251,8 +253,8 @@ public static class LibraryApi m.HasThumbnail && m.Sha256 is not null ? m.Sha256 : m.Kind == MediaKind.Video ? "video" : null, path is not null, ApiMapping.State(m.State), - IsDamaged(m, path)); - }).ToList(); + damaged)); + } return new EntryDto( entry.Id, @@ -277,10 +279,12 @@ public static class LibraryApi /// /// «File danneggiato o incompleto» (spec §4.6, §8.4): a photo on disk with no thumbnail whose bytes are damaged or /// truncated. A photo with a thumbnail was decoded when it was stored, so only those without one are looked at, - /// one file each time the viewer opens it; the file is only read, never touched (rule 12). + /// one file each time the viewer opens it, with asynchronous reads and the answer kept for the same file; a format + /// Febe does not decode, a HEIC or a picture over the limit is told from its first bytes, without reading it whole. + /// The file is only read, never touched (rule 12). /// - private static bool IsDamaged(Media media, string? path) => - media.Kind == MediaKind.Photo && !media.HasThumbnail && path is not null && DamagedImage.IsFileDamaged(path); + private static async Task IsDamagedAsync(Media media, string? path, CancellationToken ct) => + media.Kind == MediaKind.Photo && !media.HasThumbnail && path is not null && await DamagedImage.IsFileDamagedAsync(path, ct).ConfigureAwait(false); private static async Task<(Account Account, Media Media)> MediaAsync(IFebeStorage storage, long mediaId, CancellationToken ct) { diff --git a/src/Febe.Web/Api/Part2Dtos.cs b/src/Febe.Web/Api/Part2Dtos.cs index 6bdc318..b9e03aa 100644 --- a/src/Febe.Web/Api/Part2Dtos.cs +++ b/src/Febe.Web/Api/Part2Dtos.cs @@ -311,7 +311,8 @@ public sealed record ImportReviewDto( bool CanMove, bool StogramHypothesis, int Copied, - IReadOnlyList Accounts); + IReadOnlyList Accounts, + int Damaged); /// Sets where a folder goes. : none, existing (with ), newArchiveAccount (with ). public sealed record FolderTargetRequest(string Folder, string Kind, long? AccountId, string? Username); @@ -340,4 +341,6 @@ public sealed record ImportReportDto( IReadOnlyList ImportedByAccount, IReadOnlyList AlreadyInLibraryByAccount, IReadOnlyList Unrecognized, - IReadOnlyList Problems); + IReadOnlyList Problems, + int DamagedCount, + IReadOnlyList Damaged); diff --git a/src/Febe.Web/Api/SystemApi.cs b/src/Febe.Web/Api/SystemApi.cs index 4c1128a..319e87c 100644 --- a/src/Febe.Web/Api/SystemApi.cs +++ b/src/Febe.Web/Api/SystemApi.cs @@ -83,7 +83,7 @@ public static class SystemApi context.RequestServices.GetService()?.Current ?? []); } - /// The sprite: each Lucide file's drawing inside a symbol; stroke and fill come from the CSS of svg.ic. + /// The sprite: each icon file's drawing (drawn for Febe on a 24 grid) inside a symbol; stroke and fill come from the CSS of svg.ic. public static string BuildSprite(EmbeddedWwwroot files) { ArgumentNullException.ThrowIfNull(files); diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md index 69050f6..2b09937 100644 --- a/src/Febe.Web/LEGGIMI.md +++ b/src/Febe.Web/LEGGIMI.md @@ -133,7 +133,7 @@ sono anche `day` (`aaaa-mm-gg`) e `clock` calcolati sul fuso di Febe. | `GET /api/import/{id}/progress`, `POST /{id}/interrupt`, `/resume` | Passi 2 e 4: avanzamento, interruzione e ripresa | | `GET /api/import/{id}/review`, `PUT /{id}/folders`, `PUT /{id}/mode`, `GET /{id}/duplicates?after=&all=`, `POST /{id}/duplicates/{pairId}`, `GET /api/import/files/{fileId}/preview` | Passo 3: contatori, cartelle → account, Copia/Sposta, doppioni con anteprime | | `POST /api/import/{id}/copy`, `GET /{id}/report`, `GET /{id}/report.csv`, `POST /{id}/discard` | Copia, resoconto, CSV (UTF-8 con BOM, `;`), abbandono di un'importazione non copiata | -| `GET /icone/tutte.svg` | Tutte le icone Lucide di `wwwroot/icone` in un solo sprite (``) | +| `GET /icone/tutte.svg` | Tutte le icone di `wwwroot/icone` (disegnate per Febe) in un solo sprite (``) | Ogni altro indirizzo senza estensione risponde con `index.html`; `/api/…` sconosciuto risponde 404 in JSON. @@ -221,7 +221,11 @@ virtualizzazione, selezione, nuovi elementi in cima senza spostare la vista), `p finestra stretta (≤1000 px: barra a icone; ≤560 px: una colonna e navigazione in basso). Colori solo dai token, mai informazione affidata al solo colore, focus sempre visibile, animazioni solo su gesto e spente con `prefers-reduced-motion`. -- Icone: file Lucide in `icone/`, usati con `icon('nome')` (lo sprite si costruisce da sé). +- Icone: disegnate per Febe, un file SVG per icona in `icone/` (griglia di 24, solo tratti; spessore, colore e + riempimento dal foglio di stile), usate con `icon('nome')` (lo sprite si costruisce da sé). Nessuna icona copiata da + raccolte di terzi. +- Carattere: quello del sistema (token `--carattere`: `system-ui,-apple-system,"Segoe UI",Roboto,sans-serif`, + la pila dell'appendice B della specifica); nessun file di caratteri nel programma. ## Dimostrazione @@ -244,9 +248,9 @@ scrive mai nella libreria vera e non usa la rete. ## Schermate (§10.7) -`bash tools/schermate/tutte.sh 8490` rifà le schermate di `docs/schermate/` da una dimostrazione avviata su quella -porta; `node tools/schermate/schermata.mjs [larghezza] [altezza] [attesa] [passo.js]` ne fa -una (scala 1,25, passi in `tools/schermate/passi/`). Accetta solo indirizzi di questo computer. Le differenze +`dotnet run --project tools/Febe.Schermate -- 8490` rifà le schermate di `docs/schermate/` da una dimostrazione avviata +su quella porta; `dotnet run --project tools/Febe.Schermate -- una [larghezza] [altezza] [attesa] +[passo.js]` ne fa una (scala 1,25, passi in `tools/Febe.Schermate/passi/`). Accetta solo indirizzi di questo computer. Le differenze rimaste dai mockup sono in `docs/schermate/differenze.md`. ## Prove diff --git a/src/Febe.Web/Security/SecurityMiddleware.cs b/src/Febe.Web/Security/SecurityMiddleware.cs index 980d603..d2c8b12 100644 --- a/src/Febe.Web/Security/SecurityMiddleware.cs +++ b/src/Febe.Web/Security/SecurityMiddleware.cs @@ -12,7 +12,7 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti { /// Paths reachable without a session in password mode: the login page and what it needs. public static readonly IReadOnlyList PublicPrefixes = - ["/accesso", "/api/accesso", "/css/", "/caratteri/", "/img/", "/testi/", "/js/", "/favicon.ico"]; + ["/accesso", "/api/accesso", "/css/", "/img/", "/testi/", "/js/", "/favicon.ico"]; /// /// Without a password (FEBE_PASSWORD missing) only these answer, so that the interface can show the page that @@ -206,6 +206,6 @@ public sealed class SecurityMiddleware(RequestDelegate next, FebeWebOptions opti headers["Cross-Origin-Opener-Policy"] = "same-origin"; headers["Content-Security-Policy"] = "default-src 'self'; img-src 'self' data: blob:; media-src 'self' blob:; style-src 'self' 'unsafe-inline'; " - + "script-src 'self'; connect-src 'self'; font-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"; + + "script-src 'self'; connect-src 'self'; font-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'"; } } diff --git a/src/Febe.Web/wwwroot/caratteri/LICENZA-OFL.txt b/src/Febe.Web/wwwroot/caratteri/LICENZA-OFL.txt deleted file mode 100644 index 78b7453..0000000 --- a/src/Febe.Web/wwwroot/caratteri/LICENZA-OFL.txt +++ /dev/null @@ -1,93 +0,0 @@ -Copyright 2020 The Archivo Project Authors (https://github.com/Omnibus-Type/Archivo) Archivo-Italic[wdth,wght].ttf: Copyright 2020 The Archivo Project Authors (https://github.com/Omnibus-Type/Archivo) - -This Font Software is licensed under the SIL Open Font License, Version 1.1. -This license is copied below, and is also available with a FAQ at: -http://scripts.sil.org/OFL - - ------------------------------------------------------------ -SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 ------------------------------------------------------------ - -PREAMBLE -The goals of the Open Font License (OFL) are to stimulate worldwide -development of collaborative font projects, to support the font creation -efforts of academic and linguistic communities, and to provide a free and -open framework in which fonts may be shared and improved in partnership -with others. - -The OFL allows the licensed fonts to be used, studied, modified and -redistributed freely as long as they are not sold by themselves. The -fonts, including any derivative works, can be bundled, embedded, -redistributed and/or sold with any software provided that any reserved -names are not used by derivative works. The fonts and derivatives, -however, cannot be released under any other type of license. The -requirement for fonts to remain under this license does not apply -to any document created using the fonts or their derivatives. - -DEFINITIONS -"Font Software" refers to the set of files released by the Copyright -Holder(s) under this license and clearly marked as such. This may -include source files, build scripts and documentation. - -"Reserved Font Name" refers to any names specified as such after the -copyright statement(s). - -"Original Version" refers to the collection of Font Software components as -distributed by the Copyright Holder(s). - -"Modified Version" refers to any derivative made by adding to, deleting, -or substituting -- in part or in whole -- any of the components of the -Original Version, by changing formats or by porting the Font Software to a -new environment. - -"Author" refers to any designer, engineer, programmer, technical -writer or other person who contributed to the Font Software. - -PERMISSION & CONDITIONS -Permission is hereby granted, free of charge, to any person obtaining -a copy of the Font Software, to use, study, copy, merge, embed, modify, -redistribute, and sell modified and unmodified copies of the Font -Software, subject to the following conditions: - -1) Neither the Font Software nor any of its individual components, -in Original or Modified Versions, may be sold by itself. - -2) Original or Modified Versions of the Font Software may be bundled, -redistributed and/or sold with any software, provided that each copy -contains the above copyright notice and this license. These can be -included either as stand-alone text files, human-readable headers or -in the appropriate machine-readable metadata fields within text or -binary files as long as those fields can be easily viewed by the user. - -3) No Modified Version of the Font Software may use the Reserved Font -Name(s) unless explicit written permission is granted by the corresponding -Copyright Holder. This restriction only applies to the primary font name as -presented to the users. - -4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font -Software shall not be used to promote, endorse or advertise any -Modified Version, except to acknowledge the contribution(s) of the -Copyright Holder(s) and the Author(s) or with their explicit written -permission. - -5) The Font Software, modified or unmodified, in part or in whole, -must be distributed entirely under this license, and must not be -distributed under any other license. The requirement for fonts to -remain under this license does not apply to any document created -using the Font Software. - -TERMINATION -This license becomes null and void if any of the above conditions are -not met. - -DISCLAIMER -THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT -OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE -COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, -INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL -DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM -OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/src/Febe.Web/wwwroot/caratteri/archivo-latin-ext-standard-normal.woff2 b/src/Febe.Web/wwwroot/caratteri/archivo-latin-ext-standard-normal.woff2 deleted file mode 100644 index c0dbc07..0000000 Binary files a/src/Febe.Web/wwwroot/caratteri/archivo-latin-ext-standard-normal.woff2 and /dev/null differ diff --git a/src/Febe.Web/wwwroot/caratteri/archivo-latin-standard-normal.woff2 b/src/Febe.Web/wwwroot/caratteri/archivo-latin-standard-normal.woff2 deleted file mode 100644 index e2448d0..0000000 Binary files a/src/Febe.Web/wwwroot/caratteri/archivo-latin-standard-normal.woff2 and /dev/null differ diff --git a/src/Febe.Web/wwwroot/css/febe.css b/src/Febe.Web/wwwroot/css/febe.css index 7a5e494..29b12cf 100644 --- a/src/Febe.Web/wwwroot/css/febe.css +++ b/src/Febe.Web/wwwroot/css/febe.css @@ -1,15 +1,5 @@ /* Febe — token e componenti di base */ -@font-face{ - font-family:"Archivo"; - src:url(../caratteri/archivo-latin-standard-normal.woff2) format("woff2"); - font-weight:100 900; font-stretch:62% 125%; font-display:block; -} -@font-face{ - font-family:"Archivo"; - src:url(../caratteri/archivo-latin-ext-standard-normal.woff2) format("woff2"); - font-weight:100 900; font-stretch:62% 125%; font-display:block; - unicode-range:U+0100-02BA,U+02BD-02C5,U+02C7-02CC,U+02CE-02D7,U+02DD-02FF,U+0304,U+0308,U+0329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF; -} +/* The system's own font (--carattere): no font file ships with Febe (decision of 18 November 2026). */ :root{ --fondo:#F4F4F4; @@ -41,6 +31,7 @@ --r-pannello:10px; --r-dialogo:14px; --tratteggio:rgba(0,0,0,.075); + --carattere:system-ui,-apple-system,"Segoe UI",Roboto,sans-serif; } [data-tema="scuro"]{ --fondo:#1B1B1B; @@ -73,7 +64,7 @@ *{box-sizing:border-box} html,body{margin:0;height:100%} body{ - font-family:"Archivo",system-ui,sans-serif; font-stretch:100%; + font-family:var(--carattere); font-stretch:100%; font-size:14px; line-height:1.45; color:var(--testo); background:var(--fondo); -webkit-font-smoothing:antialiased; text-rendering:optimizeLegibility; } diff --git a/src/Febe.Web/wwwroot/icone/LICENZA-ISC.txt b/src/Febe.Web/wwwroot/icone/LICENZA-ISC.txt deleted file mode 100644 index 718bb3f..0000000 --- a/src/Febe.Web/wwwroot/icone/LICENZA-ISC.txt +++ /dev/null @@ -1,43 +0,0 @@ -ISC License - -Copyright (c) 2026 Lucide Icons and Contributors - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted, provided that the above -copyright notice and this permission notice appear in all copies. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES -WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF -MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR -ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES -WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN -ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF -OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - ---- - -The following Lucide icons are derived from the Feather project: - -airplay, alert-circle, alert-octagon, alert-triangle, aperture, arrow-down-circle, arrow-down-left, arrow-down-right, arrow-down, arrow-left-circle, arrow-left, arrow-right-circle, arrow-right, arrow-up-circle, arrow-up-left, arrow-up-right, arrow-up, at-sign, calendar, cast, check, chevron-down, chevron-left, chevron-right, chevron-up, chevrons-down, chevrons-left, chevrons-right, chevrons-up, circle, clipboard, clock, code, columns, command, compass, corner-down-left, corner-down-right, corner-left-down, corner-left-up, corner-right-down, corner-right-up, corner-up-left, corner-up-right, crosshair, database, divide-circle, divide-square, dollar-sign, download, external-link, feather, frown, hash, headphones, help-circle, info, italic, key, layout, life-buoy, link-2, link, loader, lock, log-in, log-out, maximize, meh, minimize, minimize-2, minus-circle, minus-square, minus, monitor, moon, more-horizontal, more-vertical, move, music, navigation-2, navigation, octagon, pause-circle, percent, plus-circle, plus-square, plus, power, radio, rss, search, server, share, shopping-bag, sidebar, smartphone, smile, square, table-2, tablet, target, terminal, trash-2, trash, triangle, tv, type, upload, x-circle, x-octagon, x-square, x, zoom-in, zoom-out - -The MIT License (MIT) (for the icons listed above) - -Copyright (c) 2013-present Cole Bemis - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/src/Febe.Web/wwwroot/icone/activity.svg b/src/Febe.Web/wwwroot/icone/activity.svg index 7839633..0ce6185 100644 --- a/src/Febe.Web/wwwroot/icone/activity.svg +++ b/src/Febe.Web/wwwroot/icone/activity.svg @@ -1,15 +1,3 @@ - - - + + diff --git a/src/Febe.Web/wwwroot/icone/app-window.svg b/src/Febe.Web/wwwroot/icone/app-window.svg index fea2156..ffe713b 100644 --- a/src/Febe.Web/wwwroot/icone/app-window.svg +++ b/src/Febe.Web/wwwroot/icone/app-window.svg @@ -1,18 +1,5 @@ - - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/archive.svg b/src/Febe.Web/wwwroot/icone/archive.svg index 247154a..1ecd64e 100644 --- a/src/Febe.Web/wwwroot/icone/archive.svg +++ b/src/Febe.Web/wwwroot/icone/archive.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/arrow-left.svg b/src/Febe.Web/wwwroot/icone/arrow-left.svg index 8ff06a7..b3ae75b 100644 --- a/src/Febe.Web/wwwroot/icone/arrow-left.svg +++ b/src/Febe.Web/wwwroot/icone/arrow-left.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/at-sign.svg b/src/Febe.Web/wwwroot/icone/at-sign.svg index 011398e..c9637bc 100644 --- a/src/Febe.Web/wwwroot/icone/at-sign.svg +++ b/src/Febe.Web/wwwroot/icone/at-sign.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/bell.svg b/src/Febe.Web/wwwroot/icone/bell.svg index da0ec5a..9300436 100644 --- a/src/Febe.Web/wwwroot/icone/bell.svg +++ b/src/Febe.Web/wwwroot/icone/bell.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/calendar.svg b/src/Febe.Web/wwwroot/icone/calendar.svg index a8af7a7..4a38304 100644 --- a/src/Febe.Web/wwwroot/icone/calendar.svg +++ b/src/Febe.Web/wwwroot/icone/calendar.svg @@ -1,18 +1,6 @@ - - - - - - + + + + + diff --git a/src/Febe.Web/wwwroot/icone/check.svg b/src/Febe.Web/wwwroot/icone/check.svg index 4c9a401..b61c536 100644 --- a/src/Febe.Web/wwwroot/icone/check.svg +++ b/src/Febe.Web/wwwroot/icone/check.svg @@ -1,15 +1,3 @@ - - - + + diff --git a/src/Febe.Web/wwwroot/icone/chevron-down.svg b/src/Febe.Web/wwwroot/icone/chevron-down.svg index 50da053..da68b1e 100644 --- a/src/Febe.Web/wwwroot/icone/chevron-down.svg +++ b/src/Febe.Web/wwwroot/icone/chevron-down.svg @@ -1,15 +1,3 @@ - - - + + diff --git a/src/Febe.Web/wwwroot/icone/chevron-left.svg b/src/Febe.Web/wwwroot/icone/chevron-left.svg index 685d734..5370b5e 100644 --- a/src/Febe.Web/wwwroot/icone/chevron-left.svg +++ b/src/Febe.Web/wwwroot/icone/chevron-left.svg @@ -1,15 +1,3 @@ - - - + + diff --git a/src/Febe.Web/wwwroot/icone/chevron-right.svg b/src/Febe.Web/wwwroot/icone/chevron-right.svg index 28828c5..3c4c87c 100644 --- a/src/Febe.Web/wwwroot/icone/chevron-right.svg +++ b/src/Febe.Web/wwwroot/icone/chevron-right.svg @@ -1,15 +1,3 @@ - - - + + diff --git a/src/Febe.Web/wwwroot/icone/circle-check.svg b/src/Febe.Web/wwwroot/icone/circle-check.svg index 435da70..823edac 100644 --- a/src/Febe.Web/wwwroot/icone/circle-check.svg +++ b/src/Febe.Web/wwwroot/icone/circle-check.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/circle-dashed.svg b/src/Febe.Web/wwwroot/icone/circle-dashed.svg index 64be9b4..f5502d0 100644 --- a/src/Febe.Web/wwwroot/icone/circle-dashed.svg +++ b/src/Febe.Web/wwwroot/icone/circle-dashed.svg @@ -1,22 +1,3 @@ - - - - - - - - - - + + diff --git a/src/Febe.Web/wwwroot/icone/circle-user.svg b/src/Febe.Web/wwwroot/icone/circle-user.svg index d46ebc0..b48da9d 100644 --- a/src/Febe.Web/wwwroot/icone/circle-user.svg +++ b/src/Febe.Web/wwwroot/icone/circle-user.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/clapperboard.svg b/src/Febe.Web/wwwroot/icone/clapperboard.svg index 98830cf..15f5e27 100644 --- a/src/Febe.Web/wwwroot/icone/clapperboard.svg +++ b/src/Febe.Web/wwwroot/icone/clapperboard.svg @@ -1,18 +1,7 @@ - - - - - - + + + + + + diff --git a/src/Febe.Web/wwwroot/icone/clock.svg b/src/Febe.Web/wwwroot/icone/clock.svg index 79ddbe6..2358a62 100644 --- a/src/Febe.Web/wwwroot/icone/clock.svg +++ b/src/Febe.Web/wwwroot/icone/clock.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/copy.svg b/src/Febe.Web/wwwroot/icone/copy.svg index 882bd3b..bfa9fce 100644 --- a/src/Febe.Web/wwwroot/icone/copy.svg +++ b/src/Febe.Web/wwwroot/icone/copy.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/database.svg b/src/Febe.Web/wwwroot/icone/database.svg index fd6289b..6b16123 100644 --- a/src/Febe.Web/wwwroot/icone/database.svg +++ b/src/Febe.Web/wwwroot/icone/database.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/download.svg b/src/Febe.Web/wwwroot/icone/download.svg index 5679644..03dfa07 100644 --- a/src/Febe.Web/wwwroot/icone/download.svg +++ b/src/Febe.Web/wwwroot/icone/download.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/ellipsis.svg b/src/Febe.Web/wwwroot/icone/ellipsis.svg index 09ea4d1..56483bb 100644 --- a/src/Febe.Web/wwwroot/icone/ellipsis.svg +++ b/src/Febe.Web/wwwroot/icone/ellipsis.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/external-link.svg b/src/Febe.Web/wwwroot/icone/external-link.svg index acb5229..247e3b9 100644 --- a/src/Febe.Web/wwwroot/icone/external-link.svg +++ b/src/Febe.Web/wwwroot/icone/external-link.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/eye.svg b/src/Febe.Web/wwwroot/icone/eye.svg index d74ca6b..ba4e10c 100644 --- a/src/Febe.Web/wwwroot/icone/eye.svg +++ b/src/Febe.Web/wwwroot/icone/eye.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/file-down.svg b/src/Febe.Web/wwwroot/icone/file-down.svg index 027c22a..2745c2d 100644 --- a/src/Febe.Web/wwwroot/icone/file-down.svg +++ b/src/Febe.Web/wwwroot/icone/file-down.svg @@ -1,18 +1,6 @@ - - - - - - + + + + + diff --git a/src/Febe.Web/wwwroot/icone/folder-input.svg b/src/Febe.Web/wwwroot/icone/folder-input.svg index ed9ece2..8fdd39a 100644 --- a/src/Febe.Web/wwwroot/icone/folder-input.svg +++ b/src/Febe.Web/wwwroot/icone/folder-input.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/folder-open.svg b/src/Febe.Web/wwwroot/icone/folder-open.svg index 9d21ad7..3328aac 100644 --- a/src/Febe.Web/wwwroot/icone/folder-open.svg +++ b/src/Febe.Web/wwwroot/icone/folder-open.svg @@ -1,15 +1,4 @@ - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/folder.svg b/src/Febe.Web/wwwroot/icone/folder.svg index 2aece89..7bb3793 100644 --- a/src/Febe.Web/wwwroot/icone/folder.svg +++ b/src/Febe.Web/wwwroot/icone/folder.svg @@ -1,15 +1,3 @@ - - - + + diff --git a/src/Febe.Web/wwwroot/icone/gauge.svg b/src/Febe.Web/wwwroot/icone/gauge.svg index 2dd4b1f..b138559 100644 --- a/src/Febe.Web/wwwroot/icone/gauge.svg +++ b/src/Febe.Web/wwwroot/icone/gauge.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/grid-3x3.svg b/src/Febe.Web/wwwroot/icone/grid-3x3.svg index 38b39f8..3798471 100644 --- a/src/Febe.Web/wwwroot/icone/grid-3x3.svg +++ b/src/Febe.Web/wwwroot/icone/grid-3x3.svg @@ -1,19 +1,7 @@ - - - - - - - + + + + + + diff --git a/src/Febe.Web/wwwroot/icone/hard-drive.svg b/src/Febe.Web/wwwroot/icone/hard-drive.svg index 27e3044..6186cad 100644 --- a/src/Febe.Web/wwwroot/icone/hard-drive.svg +++ b/src/Febe.Web/wwwroot/icone/hard-drive.svg @@ -1,18 +1,5 @@ - - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/history.svg b/src/Febe.Web/wwwroot/icone/history.svg index 6cc5cd2..f24a109 100644 --- a/src/Febe.Web/wwwroot/icone/history.svg +++ b/src/Febe.Web/wwwroot/icone/history.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/hourglass.svg b/src/Febe.Web/wwwroot/icone/hourglass.svg index 7ca7a2c..f0aa66d 100644 --- a/src/Febe.Web/wwwroot/icone/hourglass.svg +++ b/src/Febe.Web/wwwroot/icone/hourglass.svg @@ -1,18 +1,6 @@ - - - - - - + + + + + diff --git a/src/Febe.Web/wwwroot/icone/house.svg b/src/Febe.Web/wwwroot/icone/house.svg index 12d0c4e..794f4ec 100644 --- a/src/Febe.Web/wwwroot/icone/house.svg +++ b/src/Febe.Web/wwwroot/icone/house.svg @@ -1,16 +1,5 @@ - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/image.svg b/src/Febe.Web/wwwroot/icone/image.svg index 17d6539..06bfa1a 100644 --- a/src/Febe.Web/wwwroot/icone/image.svg +++ b/src/Febe.Web/wwwroot/icone/image.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/info.svg b/src/Febe.Web/wwwroot/icone/info.svg index cdfff0c..37a9cb8 100644 --- a/src/Febe.Web/wwwroot/icone/info.svg +++ b/src/Febe.Web/wwwroot/icone/info.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/key-round.svg b/src/Febe.Web/wwwroot/icone/key-round.svg index c1a1cdf..a3c3f5a 100644 --- a/src/Febe.Web/wwwroot/icone/key-round.svg +++ b/src/Febe.Web/wwwroot/icone/key-round.svg @@ -1,16 +1,6 @@ - - - - + + + + + diff --git a/src/Febe.Web/wwwroot/icone/layers.svg b/src/Febe.Web/wwwroot/icone/layers.svg index dd0d5bb..c58603b 100644 --- a/src/Febe.Web/wwwroot/icone/layers.svg +++ b/src/Febe.Web/wwwroot/icone/layers.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/layout-grid.svg b/src/Febe.Web/wwwroot/icone/layout-grid.svg index 6bf6dd8..3822544 100644 --- a/src/Febe.Web/wwwroot/icone/layout-grid.svg +++ b/src/Febe.Web/wwwroot/icone/layout-grid.svg @@ -1,18 +1,6 @@ - - - - - - + + + + + diff --git a/src/Febe.Web/wwwroot/icone/list-filter.svg b/src/Febe.Web/wwwroot/icone/list-filter.svg index 00c72f0..a4376e1 100644 --- a/src/Febe.Web/wwwroot/icone/list-filter.svg +++ b/src/Febe.Web/wwwroot/icone/list-filter.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/lock.svg b/src/Febe.Web/wwwroot/icone/lock.svg index 505a2b2..51875b6 100644 --- a/src/Febe.Web/wwwroot/icone/lock.svg +++ b/src/Febe.Web/wwwroot/icone/lock.svg @@ -1,16 +1,5 @@ - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/log-out.svg b/src/Febe.Web/wwwroot/icone/log-out.svg index 697eb8e..380a395 100644 --- a/src/Febe.Web/wwwroot/icone/log-out.svg +++ b/src/Febe.Web/wwwroot/icone/log-out.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/maximize.svg b/src/Febe.Web/wwwroot/icone/maximize.svg index 1f90810..ec92618 100644 --- a/src/Febe.Web/wwwroot/icone/maximize.svg +++ b/src/Febe.Web/wwwroot/icone/maximize.svg @@ -1,18 +1,6 @@ - - - - - - + + + + + diff --git a/src/Febe.Web/wwwroot/icone/monitor.svg b/src/Febe.Web/wwwroot/icone/monitor.svg index 1b2b73f..9efaf2b 100644 --- a/src/Febe.Web/wwwroot/icone/monitor.svg +++ b/src/Febe.Web/wwwroot/icone/monitor.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/moon.svg b/src/Febe.Web/wwwroot/icone/moon.svg index 27cc7bc..f23e7d4 100644 --- a/src/Febe.Web/wwwroot/icone/moon.svg +++ b/src/Febe.Web/wwwroot/icone/moon.svg @@ -1,15 +1,3 @@ - - - + + diff --git a/src/Febe.Web/wwwroot/icone/octagon-alert.svg b/src/Febe.Web/wwwroot/icone/octagon-alert.svg index a7654db..884dc3a 100644 --- a/src/Febe.Web/wwwroot/icone/octagon-alert.svg +++ b/src/Febe.Web/wwwroot/icone/octagon-alert.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/pause.svg b/src/Febe.Web/wwwroot/icone/pause.svg index 3d09490..61775cd 100644 --- a/src/Febe.Web/wwwroot/icone/pause.svg +++ b/src/Febe.Web/wwwroot/icone/pause.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/play-circle.svg b/src/Febe.Web/wwwroot/icone/play-circle.svg index b92ad61..4ee811a 100644 --- a/src/Febe.Web/wwwroot/icone/play-circle.svg +++ b/src/Febe.Web/wwwroot/icone/play-circle.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/play.svg b/src/Febe.Web/wwwroot/icone/play.svg index 485a439..6ab85a7 100644 --- a/src/Febe.Web/wwwroot/icone/play.svg +++ b/src/Febe.Web/wwwroot/icone/play.svg @@ -1,15 +1,3 @@ - - - + + diff --git a/src/Febe.Web/wwwroot/icone/plus.svg b/src/Febe.Web/wwwroot/icone/plus.svg index 37e9160..2de9792 100644 --- a/src/Febe.Web/wwwroot/icone/plus.svg +++ b/src/Febe.Web/wwwroot/icone/plus.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/refresh-cw.svg b/src/Febe.Web/wwwroot/icone/refresh-cw.svg index 2f46dd5..61484e4 100644 --- a/src/Febe.Web/wwwroot/icone/refresh-cw.svg +++ b/src/Febe.Web/wwwroot/icone/refresh-cw.svg @@ -1,18 +1,6 @@ - - - - - - + + + + + diff --git a/src/Febe.Web/wwwroot/icone/rotate-ccw.svg b/src/Febe.Web/wwwroot/icone/rotate-ccw.svg index d236e73..c269f55 100644 --- a/src/Febe.Web/wwwroot/icone/rotate-ccw.svg +++ b/src/Febe.Web/wwwroot/icone/rotate-ccw.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/rotate-cw.svg b/src/Febe.Web/wwwroot/icone/rotate-cw.svg index 5fbb43f..873b0dc 100644 --- a/src/Febe.Web/wwwroot/icone/rotate-cw.svg +++ b/src/Febe.Web/wwwroot/icone/rotate-cw.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/search.svg b/src/Febe.Web/wwwroot/icone/search.svg index b8ffb2a..461703a 100644 --- a/src/Febe.Web/wwwroot/icone/search.svg +++ b/src/Febe.Web/wwwroot/icone/search.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/settings.svg b/src/Febe.Web/wwwroot/icone/settings.svg index e78308d..dc3d36e 100644 --- a/src/Febe.Web/wwwroot/icone/settings.svg +++ b/src/Febe.Web/wwwroot/icone/settings.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/shield-alert.svg b/src/Febe.Web/wwwroot/icone/shield-alert.svg index 7c9b11c..99e9d85 100644 --- a/src/Febe.Web/wwwroot/icone/shield-alert.svg +++ b/src/Febe.Web/wwwroot/icone/shield-alert.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/shield-check.svg b/src/Febe.Web/wwwroot/icone/shield-check.svg index e3265bd..ab90bfa 100644 --- a/src/Febe.Web/wwwroot/icone/shield-check.svg +++ b/src/Febe.Web/wwwroot/icone/shield-check.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/sliders-horizontal.svg b/src/Febe.Web/wwwroot/icone/sliders-horizontal.svg index ddbf08f..8db467d 100644 --- a/src/Febe.Web/wwwroot/icone/sliders-horizontal.svg +++ b/src/Febe.Web/wwwroot/icone/sliders-horizontal.svg @@ -1,23 +1,11 @@ - - - - - - - - - - - + + + + + + + + + + diff --git a/src/Febe.Web/wwwroot/icone/square-user.svg b/src/Febe.Web/wwwroot/icone/square-user.svg index 2f1a853..2a16d02 100644 --- a/src/Febe.Web/wwwroot/icone/square-user.svg +++ b/src/Febe.Web/wwwroot/icone/square-user.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/square.svg b/src/Febe.Web/wwwroot/icone/square.svg index 13d00d3..82f8d53 100644 --- a/src/Febe.Web/wwwroot/icone/square.svg +++ b/src/Febe.Web/wwwroot/icone/square.svg @@ -1,15 +1,3 @@ - - - + + diff --git a/src/Febe.Web/wwwroot/icone/star.svg b/src/Febe.Web/wwwroot/icone/star.svg index 3a2eb96..7af850c 100644 --- a/src/Febe.Web/wwwroot/icone/star.svg +++ b/src/Febe.Web/wwwroot/icone/star.svg @@ -1,15 +1,3 @@ - - - + + diff --git a/src/Febe.Web/wwwroot/icone/sun.svg b/src/Febe.Web/wwwroot/icone/sun.svg index e0bb4d2..2482502 100644 --- a/src/Febe.Web/wwwroot/icone/sun.svg +++ b/src/Febe.Web/wwwroot/icone/sun.svg @@ -1,23 +1,11 @@ - - - - - - - - - - - + + + + + + + + + + diff --git a/src/Febe.Web/wwwroot/icone/trash-2.svg b/src/Febe.Web/wwwroot/icone/trash-2.svg index becfb8d..a82290e 100644 --- a/src/Febe.Web/wwwroot/icone/trash-2.svg +++ b/src/Febe.Web/wwwroot/icone/trash-2.svg @@ -1,19 +1,7 @@ - - - - - - - + + + + + + diff --git a/src/Febe.Web/wwwroot/icone/triangle-alert.svg b/src/Febe.Web/wwwroot/icone/triangle-alert.svg index 9ea01aa..6f65ec2 100644 --- a/src/Febe.Web/wwwroot/icone/triangle-alert.svg +++ b/src/Febe.Web/wwwroot/icone/triangle-alert.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/upload.svg b/src/Febe.Web/wwwroot/icone/upload.svg index fd744a5..5686563 100644 --- a/src/Febe.Web/wwwroot/icone/upload.svg +++ b/src/Febe.Web/wwwroot/icone/upload.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/user-check.svg b/src/Febe.Web/wwwroot/icone/user-check.svg index 44f26e8..c4f1033 100644 --- a/src/Febe.Web/wwwroot/icone/user-check.svg +++ b/src/Febe.Web/wwwroot/icone/user-check.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/user.svg b/src/Febe.Web/wwwroot/icone/user.svg index 3404512..f896950 100644 --- a/src/Febe.Web/wwwroot/icone/user.svg +++ b/src/Febe.Web/wwwroot/icone/user.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/users.svg b/src/Febe.Web/wwwroot/icone/users.svg index a4597e2..597ce7f 100644 --- a/src/Febe.Web/wwwroot/icone/users.svg +++ b/src/Febe.Web/wwwroot/icone/users.svg @@ -1,18 +1,6 @@ - - - - - - + + + + + diff --git a/src/Febe.Web/wwwroot/icone/volume-2.svg b/src/Febe.Web/wwwroot/icone/volume-2.svg index 97c4dc3..5ca3efa 100644 --- a/src/Febe.Web/wwwroot/icone/volume-2.svg +++ b/src/Febe.Web/wwwroot/icone/volume-2.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/volume-x.svg b/src/Febe.Web/wwwroot/icone/volume-x.svg index 83db576..dbf8e55 100644 --- a/src/Febe.Web/wwwroot/icone/volume-x.svg +++ b/src/Febe.Web/wwwroot/icone/volume-x.svg @@ -1,17 +1,5 @@ - - - - - + + + + diff --git a/src/Febe.Web/wwwroot/icone/x.svg b/src/Febe.Web/wwwroot/icone/x.svg index eadaa1b..c7c431e 100644 --- a/src/Febe.Web/wwwroot/icone/x.svg +++ b/src/Febe.Web/wwwroot/icone/x.svg @@ -1,16 +1,4 @@ - - - - + + + diff --git a/src/Febe.Web/wwwroot/icone/zoom-in.svg b/src/Febe.Web/wwwroot/icone/zoom-in.svg index c18ba37..351f8af 100644 --- a/src/Febe.Web/wwwroot/icone/zoom-in.svg +++ b/src/Febe.Web/wwwroot/icone/zoom-in.svg @@ -1,18 +1,6 @@ - - - - - - + + + + + diff --git a/src/Febe.Web/wwwroot/index.html b/src/Febe.Web/wwwroot/index.html index 39eeb39..9e3b351 100644 --- a/src/Febe.Web/wwwroot/index.html +++ b/src/Febe.Web/wwwroot/index.html @@ -6,7 +6,6 @@ Febe - diff --git a/src/Febe.Web/wwwroot/js/core/dom.js b/src/Febe.Web/wwwroot/js/core/dom.js index 6e00b38..9e6d355 100644 --- a/src/Febe.Web/wwwroot/js/core/dom.js +++ b/src/Febe.Web/wwwroot/js/core/dom.js @@ -44,7 +44,7 @@ export function fill(el, ...children) { return append(el, children); } -/** An icon from the sprite (wwwroot/icone, Lucide, stroke 1.75): . */ +/** An icon from the sprite (wwwroot/icone, drawn for Febe on a 24 grid, stroke 1.75): . */ export function icon(name, size = '') { const svg = document.createElementNS(SVG, 'svg'); svg.setAttribute('class', `ic${size ? ' ' + size : ''}`); diff --git a/src/Febe.Web/wwwroot/js/pages/import.js b/src/Febe.Web/wwwroot/js/pages/import.js index 2c6be5f..58cc154 100644 --- a/src/Febe.Web/wwwroot/js/pages/import.js +++ b/src/Febe.Web/wwwroot/js/pages/import.js @@ -351,7 +351,8 @@ async function reviewStep(ctx, run) { function drawNotes() { fill(notes, review.recognized > 0 ? h('div.avviso', icon('info', 's'), h('span', t('importa.revisione.riconosciuti', { n: number(review.recognized) }))) : null, - review.stogramHypothesis ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('importa.revisione.stogram'))) : null); + review.stogramHypothesis ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('importa.revisione.stogram'))) : null, + review.damaged > 0 ? h('div.avviso.ambra', icon('triangle-alert', 's'), h('span', t('importa.revisione.danneggiati', { n: number(review.damaged) }))) : null); } // The fixed bar: Copia/Sposta, what stays out, CSV, «Importa N file». @@ -482,6 +483,9 @@ async function reportStep(ctx, run) { h('section', h('h2', t('importa.resoconto.giaPerAccount')), h('div.pannello', accounts(report.alreadyInLibraryByAccount)))), report.unrecognized.length ? h('section.blocco', h('h2', t('importa.resoconto.nonRiconosciuti')), h('div.pannello', h('ul.elenco-semplice', report.unrecognized.map((u) => h('li.dati', u))))) : null, + report.damaged.length ? h('section.blocco', h('h2', t('importa.resoconto.danneggiati')), + h('div.pannello', h('ul.elenco-semplice', report.damaged.map((u) => h('li.dati', u))), + report.damagedCount > report.damaged.length ? h('p.aiuto', t('importa.resoconto.danneggiatiAltri', { n: number(report.damagedCount - report.damaged.length) })) : null)) : null, report.problems.length ? h('section.blocco', h('h2', t('importa.resoconto.problemi')), h('div.pannello', h('ul.elenco-semplice', report.problems.map((p) => h('li', h('span.dati', p.path), h('span.muto', p.note)))))) : null, h('div.riga-azione', diff --git a/src/Febe.Web/wwwroot/js/pages/settings-about.js b/src/Febe.Web/wwwroot/js/pages/settings-about.js index e311a41..ad91084 100644 --- a/src/Febe.Web/wwwroot/js/pages/settings-about.js +++ b/src/Febe.Web/wwwroot/js/pages/settings-about.js @@ -1,6 +1,7 @@ // Impostazioni, Informazioni: version and shell, where the guide is (the wiki of the repository), the folders, the // statement on the risk for the account (spec §1, §15 «che cosa la guida deve dire»), the licenses of what Febe -// carries inside (Archivo OFL, Lucide ISC, SQLite, .NET, WebView2). Images (codecs, thumbnails, drawing) are Febe's own code. +// carries inside (SQLite, .NET, WebView2) and a line saying that font, icons and images (codecs, thumbnails, drawing) +// are Febe's own code, not third-party. import { api } from '../core/api.js'; import { h, icon, fill, brand } from '../core/dom.js'; @@ -28,5 +29,6 @@ export default async function about(page, box) { heading(t('impostazioni.informazioni.licenze'), t('impostazioni.informazioni.licenzeAiuto')), h('ul.licenze', (Array.isArray(components) ? components : []).map((c) => h('li', h('b', c.nome), h('span.muto', ` — ${c.testo}`), - c.file ? h('a', { href: c.file, target: '_blank', rel: 'noopener' }, t('impostazioni.informazioni.leggiLicenza')) : null))))); + c.file ? h('a', { href: c.file, target: '_blank', rel: 'noopener' }, t('impostazioni.informazioni.leggiLicenza')) : null))), + h('p.muto', t('impostazioni.informazioni.fattoInCasa')))); } diff --git a/src/Febe.Web/wwwroot/testi/it.json b/src/Febe.Web/wwwroot/testi/it.json index 1727851..c6c9a69 100644 --- a/src/Febe.Web/wwwroot/testi/it.json +++ b/src/Febe.Web/wwwroot/testi/it.json @@ -840,13 +840,12 @@ "licenze": "Licenze", "licenzeAiuto": "Febe usa questi componenti, copiati nel programma con le loro licenze:", "componenti": [ - { "nome": "Archivo", "testo": "carattere, SIL Open Font License 1.1", "file": "/caratteri/LICENZA-OFL.txt" }, - { "nome": "Lucide", "testo": "icone, licenza ISC", "file": "/icone/LICENZA-ISC.txt" }, { "nome": "SQLite e Microsoft.Data.Sqlite", "testo": "database, pubblico dominio e licenza MIT" }, { "nome": ".NET e ASP.NET Core", "testo": "licenza MIT" }, { "nome": "WebView2", "testo": "solo versione Windows, licenza Microsoft" } ], - "leggiLicenza": "Leggi la licenza" + "leggiLicenza": "Leggi la licenza", + "fattoInCasa": "Il carattere è quello del tuo sistema e le icone sono disegnate per Febe; le immagini (miniature, impronte visive, fotogrammi dei video) le legge e le disegna il codice di Febe: nessun carattere, icona o componente di terzi." } }, "browser": { @@ -937,7 +936,8 @@ "nessunNome": "Nessun nome di account riconosciuto", "esistenti": "Account in Febe", "riconosciuti": "Dai nomi dei file Febe ha ricavato data e codice di {n} elementi: quando terrà aggiornati questi account non li riscaricherà.", - "stogram": "I nomi sono stati letti con l'ipotesi su 4K Stogram, non ancora verificata: controlla date e codici prima di importare." + "stogram": "I nomi sono stati letti con l'ipotesi su 4K Stogram, non ancora verificata: controlla date e codici prima di importare.", + "danneggiati": "File danneggiato o incompleto: 1 immagine troncata o rovinata. Si importa come le altre, ma senza miniatura né impronta visiva.|File danneggiato o incompleto: {n} immagini troncate o rovinate. Si importano come le altre, ma senza miniatura né impronta visiva." }, "doppioni": { "titolo": "Doppioni probabili", @@ -998,6 +998,8 @@ "perAccount": "Importati per account", "giaPerAccount": "Già in libreria, per account", "nonRiconosciuti": "Non riconosciuti", + "danneggiati": "File danneggiato o incompleto", + "danneggiatiAltri": "e altri {n}: sono tutti nell'elenco CSV.", "problemi": "Da guardare", "nessuno": "Nessuno", "nuova": "Nuova importazione", diff --git a/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj b/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj index 404c8cf..c29d1cb 100644 --- a/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj +++ b/tests/Febe.Tests.Windows/Febe.Tests.Windows.csproj @@ -26,6 +26,7 @@ + diff --git a/tests/Febe.Tests.Windows/InstallerTests.cs b/tests/Febe.Tests.Windows/InstallerTests.cs new file mode 100644 index 0000000..66ca2e2 --- /dev/null +++ b/tests/Febe.Tests.Windows/InstallerTests.cs @@ -0,0 +1,348 @@ +using System.Diagnostics; +using System.Runtime.InteropServices; +using System.Text; +using Febe.Installer; +using Febe.Installer.Windows; +using Febe.Tests.Windows.Support; +using Microsoft.Win32; + +namespace Febe.Tests.Windows; + +/// +/// The installer on a real Windows: published for win-x64 as installer/costruisci.sh does it (self-contained, single +/// file, trimmed), packed with a stand-in Febe.exe, then installed in silent mode into a folder of the test +/// (/PROVA=: Start menu, desktop, %TEMP% and registry keys of the test, never those of an installed Febe), +/// installed again over itself, refused while Febe is open, and uninstalled with the command recorded in Apps +/// installed. The first page of the dialogs opens and «Annulla» closes it. Nothing here starts Febe. +/// +[TestClass] +public sealed class InstallerTests +{ + private static string? s_publishedInstaller; + private static TestFolder? s_build; + + public TestContext TestContext { get; set; } = null!; + + [ClassInitialize] + public static void PublishTheInstaller(TestContext context) + { + var project = Path.Combine(RepositoryRoot(), "src", "Febe.Installer", "Febe.Installer.csproj"); + s_build = new TestFolder("installatore-pubblicato"); + var output = s_build.Combine("uscita"); + var start = new ProcessStartInfo("dotnet") + { + RedirectStandardOutput = true, + RedirectStandardError = true, + }; + foreach (var argument in new[] { "publish", project, "-c", "Release", "-r", "win-x64", "-p:Version=0.0.1", "-nologo", "-o", output, "--artifacts-path", s_build.Combine("artefatti") }) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start)!; + var stdout = process.StandardOutput.ReadToEndAsync(context.CancellationToken); + var stderr = process.StandardError.ReadToEndAsync(context.CancellationToken); + process.WaitForExit(); + Assert.AreEqual(0, process.ExitCode, $"dotnet publish:\n{stdout.Result}\n{stderr.Result}"); + CollectionAssert.AreEqual(new[] { "Febe.Installer.exe" }, Directory.GetFiles(output).Select(Path.GetFileName).ToArray(), "a single file"); + s_publishedInstaller = Path.Combine(output, "Febe.Installer.exe"); + } + + [ClassCleanup] + public static void RemoveTheBuild() => s_build?.Dispose(); + + [TestMethod] + [Timeout(300_000, CooperativeCancellation = true)] + public async Task InstalledSilentlyIntoATestFolderUpdatedRefusedWhileOpenAndUninstalled() + { + using var folder = new TestFolder("installazione"); + var root = folder.Combine("utente"); + Directory.CreateDirectory(root); + var locations = Locations.ForTest(root); + var registryRoot = Locations.TestRegistryRoot(root).TrimEnd('\\'); + try + { + // The program and its version resource: not elevated (it would not even start here), version and names. + var first = Pack(folder, "0.0.1", seed: 1); + Assert.IsGreaterThan(1_000_000L, new FileInfo(s_publishedInstaller!).Length); + Assert.IsLessThan(20_000_000L, new FileInfo(s_publishedInstaller!).Length, "trimmed: a few MB beside Febe.exe"); + var version = FileVersionInfo.GetVersionInfo(first.Setup); + Assert.AreEqual("Febe", version.ProductName); + Assert.AreEqual("Installazione di Febe", version.FileDescription); + Assert.AreEqual("Alberto Balbo", version.CompanyName); + StringAssert.StartsWith(version.ProductVersion, "0.0.1"); + var bytes = await File.ReadAllBytesAsync(s_publishedInstaller!, TestContext.CancellationToken); + Assert.IsTrue(Contains(bytes, "asInvoker"u8), "the manifest is inside: no administrator rights"); + Assert.IsTrue(Contains(bytes, "Microsoft.Windows.Common-Controls"u8), "the manifest asks for the common controls 6"); + + // Installation, silent, default folder of the test user. + Assert.AreEqual(0, await Run(first.Setup, ["/S", "/PROVA=" + root])); + var program = locations.DefaultInstallFolder; + CollectionAssert.AreEqual(first.Program, await File.ReadAllBytesAsync(Path.Combine(program, "Febe.exe"), TestContext.CancellationToken)); + Assert.AreEqual(PackageKind.Uninstaller, Package.Read(Path.Combine(program, "Disinstalla Febe.exe"))!.Kind); + foreach (var shortcut in new[] { locations.StartMenuShortcut, locations.DesktopShortcut }) + { + var (target, workingDirectory, description) = ShellLinks.Read(shortcut); + Assert.AreEqual(Path.Combine(program, "Febe.exe"), target, shortcut); + Assert.AreEqual(program, workingDirectory); + Assert.AreEqual("Archivio personale di foto, video e storie da Instagram", description); + } + + using (var key = Registry.CurrentUser.OpenSubKey(locations.UninstallKey)!) + { + Assert.AreEqual("Febe", key.GetValue("DisplayName")); + Assert.AreEqual("0.0.1", key.GetValue("DisplayVersion")); + Assert.AreEqual("Alberto Balbo", key.GetValue("Publisher")); + Assert.AreEqual(program, key.GetValue("InstallLocation")); + Assert.AreEqual(1, key.GetValue("NoModify")); + Assert.AreEqual(RegistryValueKind.DWord, key.GetValueKind("EstimatedSize")); + } + + // The data of Febe and «Start with the computer». + var data = Path.Combine(locations.DefaultDataFolder, "febe.sqlite"); + Directory.CreateDirectory(locations.DefaultDataFolder); + await File.WriteAllTextAsync(data, "dati", TestContext.CancellationToken); + using (var run = Registry.CurrentUser.CreateSubKey(locations.RunKey)) + { + run.SetValue("Febe", $"\"{Path.Combine(program, "Febe.exe")}\" --nascosto"); + run.SetValue("Febe-Altro", "\"C:\\Altrove\\Febe.exe\" --nascosto --dati \"D:\\Altro\""); + } + + // Again, a newer version over it: the program changes, the data stay. + var second = Pack(folder, "0.0.2", seed: 2); + Assert.AreEqual(0, await Run(second.Setup, ["/S", "/PROVA=" + root])); + CollectionAssert.AreEqual(second.Program, await File.ReadAllBytesAsync(Path.Combine(program, "Febe.exe"), TestContext.CancellationToken)); + Assert.AreEqual("0.0.2", Registry.GetValue(@"HKEY_CURRENT_USER\" + locations.UninstallKey, "DisplayVersion", null)); + Assert.AreEqual("dati", await File.ReadAllTextAsync(data, TestContext.CancellationToken)); + + // Febe open: the installer stops (exit 2), says why on the standard error, changes nothing. + using (new FileStream(Path.Combine(program, "Febe.exe"), FileMode.Open, FileAccess.Read, FileShare.Read)) + { + var errors = new StringBuilder(); + Assert.AreEqual(2, await Run(first.Setup, ["/S", "/PROVA=" + root], errors)); + StringAssert.Contains(errors.ToString(), "Febe è aperto"); + } + + CollectionAssert.AreEqual(second.Program, await File.ReadAllBytesAsync(Path.Combine(program, "Febe.exe"), TestContext.CancellationToken)); + + // Uninstallation with the command Apps installed would use in silent mode: it hands over to a copy of + // itself in %TEMP% and ends; the copy does the work. + var quiet = (string)Registry.GetValue(@"HKEY_CURRENT_USER\" + locations.UninstallKey, "QuietUninstallString", null)!; + var (uninstaller, arguments) = Split(quiet); + Assert.AreEqual(Path.Combine(program, "Disinstalla Febe.exe"), uninstaller); + Assert.AreEqual(0, await Run(uninstaller, arguments)); + await WaitUntil(() => !Directory.Exists(program) && Registry.CurrentUser.OpenSubKey(locations.UninstallKey) is null, TimeSpan.FromSeconds(60)); + + Assert.IsFalse(File.Exists(locations.StartMenuShortcut)); + Assert.IsFalse(File.Exists(locations.DesktopShortcut)); + Assert.AreEqual("dati", await File.ReadAllTextAsync(data, TestContext.CancellationToken), "never the Data folder"); + using (var run = Registry.CurrentUser.OpenSubKey(locations.RunKey)!) + { + CollectionAssert.AreEqual(new[] { "Febe-Altro" }, run.GetValueNames(), "only the value of another Febe stays"); + } + + // The copy that did the work ends by itself; the next run of the installer removes it. + await WaitUntil(() => !Process.GetProcesses().Any(p => p.ProcessName.StartsWith("Febe-disinstalla-", StringComparison.Ordinal) && SafePath(p)?.StartsWith(root, StringComparison.OrdinalIgnoreCase) == true), TimeSpan.FromSeconds(30)); + } + finally + { + Registry.CurrentUser.DeleteSubKeyTree(registryRoot, throwOnMissingSubKey: false); + DeleteEmptyTestKey(); + } + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task TheFirstPageOpensAsADialogOfWindowsAndAnnullaInstallsNothing() + { + using var folder = new TestFolder("dialogo"); + var root = folder.Combine("utente"); + Directory.CreateDirectory(root); + var locations = Locations.ForTest(root); + try + { + var package = Pack(folder, "0.0.1", seed: 3); + using var process = Process.Start(new ProcessStartInfo(package.Setup, ["/PROVA=" + root]))!; + var window = IntPtr.Zero; + await WaitUntil(() => (window = VisibleWindowOf(process.Id)) != IntPtr.Zero, TimeSpan.FromSeconds(30)); + Assert.AreEqual("Installazione di Febe", WindowTitle(window)); + + // Close: with «Annulla» allowed, it answers as «Annulla». + PostMessage(window, 0x0010, IntPtr.Zero, IntPtr.Zero); + Assert.IsTrue(process.WaitForExit(30_000)); + Assert.AreEqual(1, process.ExitCode, "cancelled"); + Assert.IsFalse(Directory.Exists(locations.DefaultInstallFolder)); + Assert.IsNull(Registry.CurrentUser.OpenSubKey(locations.UninstallKey)); + } + finally + { + Registry.CurrentUser.DeleteSubKeyTree(Locations.TestRegistryRoot(root).TrimEnd('\\'), throwOnMissingSubKey: false); + DeleteEmptyTestKey(); + } + } + + [TestMethod] + public void TheLastPageStartsFebeOnlyWithFine() + { + // Windows gives back the state of the box on a cancel too: Esc or the close button must not start Febe. + Assert.IsTrue(DialogInterface.StartsFebe(DialogInterface.Yes, runChecked: true)); + Assert.IsFalse(DialogInterface.StartsFebe(DialogInterface.Yes, runChecked: false)); + Assert.IsFalse(DialogInterface.StartsFebe(TaskDialog.CancelId, runChecked: true), "Esc or ✕ with «Apri Febe adesso» ticked"); + Assert.IsFalse(DialogInterface.StartsFebe(TaskDialog.CancelId, runChecked: false)); + } + + private static (string Setup, byte[] Program) Pack(TestFolder folder, string version, int seed) + { + // Not an executable: if anything tried to start it, Windows would refuse it at once. + var program = new byte[300_000 + seed]; + new Random(seed).NextBytes(program); + program[0] = (byte)'F'; + program[1] = (byte)'B'; + var source = folder.Combine($"Febe-{seed}.exe"); + File.WriteAllBytes(source, program); + var setup = folder.Combine($"Febe-Setup-{version}-{seed}.exe"); + Package.Write(s_publishedInstaller!, source, version, setup); + return (setup, program); + } + + private async Task Run(string executable, IReadOnlyList arguments, StringBuilder? errors = null) + { + var start = new ProcessStartInfo(executable) { UseShellExecute = false, RedirectStandardError = true, StandardErrorEncoding = Encoding.UTF8 }; + foreach (var argument in arguments) + { + start.ArgumentList.Add(argument); + } + + using var process = Process.Start(start)!; + var text = await process.StandardError.ReadToEndAsync(TestContext.CancellationToken); + await process.WaitForExitAsync(TestContext.CancellationToken); + errors?.Append(text); + return process.ExitCode; + } + + private async Task WaitUntil(Func condition, TimeSpan timeout) + { + var deadline = Stopwatch.StartNew(); + while (!condition()) + { + Assert.IsLessThan(timeout, deadline.Elapsed, "timed out"); + await Task.Delay(200, TestContext.CancellationToken); + } + } + + /// The program and the arguments of a command line as Windows reads it (quotes group). + private static (string Program, string[] Arguments) Split(string commandLine) + { + var words = new List(); + var word = new StringBuilder(); + var quoted = false; + foreach (var c in commandLine) + { + if (c == '"') + { + quoted = !quoted; + } + else if (c == ' ' && !quoted) + { + if (word.Length > 0) + { + words.Add(word.ToString()); + word.Clear(); + } + } + else + { + word.Append(c); + } + } + + if (word.Length > 0) + { + words.Add(word.ToString()); + } + + return (words[0], words.Skip(1).ToArray()); + } + + private static string? SafePath(Process process) + { + try + { + return process.MainModule?.FileName; + } + catch (Exception ex) when (ex is System.ComponentModel.Win32Exception or InvalidOperationException) + { + return null; + } + } + + private static bool Contains(byte[] haystack, ReadOnlySpan needle) => haystack.AsSpan().IndexOf(needle) >= 0; + + private static void DeleteEmptyTestKey() + { + using var tests = Registry.CurrentUser.OpenSubKey(@"Software\FebeProve"); + if (tests is not null && tests.SubKeyCount == 0 && tests.ValueCount == 0) + { + Registry.CurrentUser.DeleteSubKey(@"Software\FebeProve", throwOnMissingSubKey: false); + } + } + + private static string RepositoryRoot() + { + for (var folder = new DirectoryInfo(AppContext.BaseDirectory); folder is not null; folder = folder.Parent) + { + if (File.Exists(Path.Combine(folder.FullName, "Febe.slnx"))) + { + return folder.FullName; + } + } + + Assert.Inconclusive("Il repository non è accanto alle prove."); + return string.Empty; + } + + /// The first visible top-level window of the process, zero for none. + private static IntPtr VisibleWindowOf(int processId) + { + var found = IntPtr.Zero; + EnumWindows((window, data) => + { + GetWindowThreadProcessId(window, out var owner); + if (owner == (uint)processId && IsWindowVisible(window)) + { + found = window; + return false; + } + + return true; + }, IntPtr.Zero); + return found; + } + + private static string WindowTitle(IntPtr window) + { + var buffer = new char[256]; + var length = GetWindowText(window, buffer, buffer.Length); + return new string(buffer, 0, Math.Max(length, 0)); + } + + private delegate bool WindowVisitor(IntPtr window, IntPtr data); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool EnumWindows(WindowVisitor visitor, IntPtr data); + + [DllImport("user32.dll")] + private static extern uint GetWindowThreadProcessId(IntPtr window, out uint processId); + + [DllImport("user32.dll")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool IsWindowVisible(IntPtr window); + + [DllImport("user32.dll", EntryPoint = "GetWindowTextW", CharSet = CharSet.Unicode)] + private static extern int GetWindowText(IntPtr window, [Out] char[] text, int maxCount); + + [DllImport("user32.dll", EntryPoint = "PostMessageW")] + [return: MarshalAs(UnmanagedType.Bool)] + private static extern bool PostMessage(IntPtr window, uint message, IntPtr wParam, IntPtr lParam); +} diff --git a/tests/Febe.Tests/Desktop/InstallerTests.cs b/tests/Febe.Tests/Desktop/InstallerTests.cs index f884dea..42e00a3 100644 --- a/tests/Febe.Tests/Desktop/InstallerTests.cs +++ b/tests/Febe.Tests/Desktop/InstallerTests.cs @@ -1,14 +1,21 @@ using System.Diagnostics; +using System.IO.Compression; +using System.Text; using System.Text.RegularExpressions; +using Febe.Desktop.Core; +using Febe.Installer; using Febe.Tests.Desktop.Support; using Febe.Tests.Support; namespace Febe.Tests.Desktop; /// -/// The installer of Windows (spec §12, question 6 of §16): installer/febe.nsi compiles with makensis (a dry -/// compile with a stand-in Febe.exe; skipped where NSIS is not installed), installs per user without administrator -/// rights, registers its uninstaller in HKCU, and its uninstaller never deletes the Data folder or the library. +/// The installer of Windows (spec §12, question 6 of §16), written in house in src/Febe.Installer since 18 November +/// 2026 instead of NSIS: the package (Febe.exe compressed after the program, with its SHA-256), the command line, and +/// the installation and uninstallation against a fake Windows (registry and shortcuts) and real files in a temporary +/// folder, on any system. Per user without administrator rights; an installation over another replaces the program +/// and keeps the data; the uninstaller never touches the Data folder or the library. The real Windows, with the +/// published installer, is in tests/Febe.Tests.Windows (InstallerTests). /// [TestClass] public sealed partial class InstallerTests @@ -16,101 +23,542 @@ public sealed partial class InstallerTests public TestContext TestContext { get; set; } = null!; [TestMethod] - [Timeout(120_000, CooperativeCancellation = true)] - public async Task TheScriptCompilesWithMakensisWithoutWarnings() + public void ThePackageCarriesFebeAfterTheProgramAndGivesItBackIdentical() { - var makensis = FindOnPath("makensis"); - if (makensis is null) - { - Assert.Inconclusive("makensis non è installato (apt-get install nsis): la prova del programma di installazione si salta."); - } + using var temp = new TempFolder("pacchetto"); + var stub = WriteBytes(temp.Combine("Febe.Installer.exe"), Bytes(200_000, seed: 1, compressible: false)); + var program = WriteBytes(temp.Combine("Febe.exe"), Bytes(3_000_000, seed: 2, compressible: true)); + var setup = temp.Combine("Febe-Setup-1.2.3-ci.4.exe"); - var script = Repository.PathOf("installer", "febe.nsi"); - using var temp = new TempFolder("nsis"); - await File.WriteAllTextAsync(temp.Combine("Febe.exe"), "MZ finto per la prova", TestContext.CancellationToken); - var output = temp.Combine("Febe-Setup-0.0.1.exe"); - var start = new ProcessStartInfo(makensis) - { - WorkingDirectory = Path.GetDirectoryName(script)!, - RedirectStandardOutput = true, - RedirectStandardError = true, - }; - foreach (var argument in new[] { "-V2", "-WX", "-INPUTCHARSET", "UTF8", "-DVERSION=0.0.1", "-DVERSIONE_FILE=0.0.1.0", $"-DSORGENTE={temp.Path}", $"-DUSCITA={output}", "febe.nsi" }) - { - start.ArgumentList.Add(argument); - } + var written = Package.Write(stub, program, "1.2.3-ci.4", setup); + var info = Package.Read(setup); - using var process = Process.Start(start)!; - var stdout = process.StandardOutput.ReadToEndAsync(TestContext.CancellationToken); - var stderr = process.StandardError.ReadToEndAsync(TestContext.CancellationToken); - await process.WaitForExitAsync(TestContext.CancellationToken); - Assert.AreEqual(0, process.ExitCode, $"makensis (avvisi = errori):\n{await stdout}\n{await stderr}"); - Assert.IsTrue(File.Exists(output)); - Assert.IsGreaterThan(100_000L, new FileInfo(output).Length); + Assert.IsNotNull(info); + Assert.AreEqual(PackageKind.Installer, info.Kind); + Assert.AreEqual("1.2.3-ci.4", info.Version); + Assert.AreEqual(200_000L, info.StubLength); + Assert.AreEqual(3_000_000L, info.ProgramLength); + Assert.AreEqual(written.DataLength, info.DataLength); + Assert.IsLessThan(3_000_000L, info.DataLength, "compressed"); + CollectionAssert.AreEqual(File.ReadAllBytes(stub), File.ReadAllBytes(setup)[..200_000], "the program comes first, untouched: its single-file bundle still works"); + Assert.IsFalse(File.Exists(setup + ".part")); - // Without the version the script refuses to compile: it always comes from the build. - using var noVersion = Process.Start(new ProcessStartInfo(makensis, ["-V1", $"-DSORGENTE={temp.Path}", $"-DUSCITA={temp.Combine("x.exe")}", "febe.nsi"]) - { - WorkingDirectory = Path.GetDirectoryName(script)!, - RedirectStandardOutput = true, - RedirectStandardError = true, - })!; - await noVersion.WaitForExitAsync(TestContext.CancellationToken); - Assert.AreNotEqual(0, noVersion.ExitCode); + var shares = new List(); + Package.ExtractProgram(setup, info, temp.Combine("estratto.exe"), shares.Add); + CollectionAssert.AreEqual(File.ReadAllBytes(program), File.ReadAllBytes(temp.Combine("estratto.exe"))); + Assert.AreEqual(1.0, shares[^1], 1e-9); + + // The uninstaller: the same program, no Febe.exe, a footer of its own. + Package.WriteUninstaller(setup, info, temp.Combine("Disinstalla Febe.exe")); + var uninstaller = Package.Read(temp.Combine("Disinstalla Febe.exe")); + Assert.IsNotNull(uninstaller); + Assert.AreEqual(PackageKind.Uninstaller, uninstaller.Kind); + Assert.AreEqual("1.2.3-ci.4", uninstaller.Version); + Assert.AreEqual(200_000L + "1.2.3-ci.4".Length + Package.FooterLength, new FileInfo(temp.Combine("Disinstalla Febe.exe")).Length); + CollectionAssert.AreEqual(File.ReadAllBytes(stub), File.ReadAllBytes(temp.Combine("Disinstalla Febe.exe"))[..200_000]); } [TestMethod] - public void TheScriptInstallsPerUserAndItsUninstallerNeverTouchesTheData() + public void ADamagedPackageIsRefusedAndNeverInstalled() { - var text = File.ReadAllText(Repository.PathOf("installer", "febe.nsi")); - StringAssert.Contains(text, "Unicode true"); - StringAssert.Contains(text, "RequestExecutionLevel user"); - StringAssert.Contains(text, "InstallDir \"$LOCALAPPDATA\\Programs\\Febe\""); - StringAssert.Contains(text, "MUI_LANGUAGE \"Italian\""); - StringAssert.Contains(text, "$SMPROGRAMS\\Febe.lnk"); - StringAssert.Contains(text, "Section \"Collegamento sul desktop\""); - foreach (var value in new[] { "DisplayName", "DisplayVersion", "Publisher", "DisplayIcon", "UninstallString" }) - { - StringAssert.Contains(text, $"WriteRegStr HKCU \"${{CHIAVE_DISINSTALLA}}\" \"{value}\""); - } + using var temp = new TempFolder("pacchetto"); + var stub = WriteBytes(temp.Combine("Febe.Installer.exe"), Bytes(50_000, seed: 3, compressible: false)); + var program = WriteBytes(temp.Combine("Febe.exe"), Bytes(500_000, seed: 4, compressible: true)); + var setup = temp.Combine("Febe-Setup.exe"); + var info = Package.Write(stub, program, "0.0.1", setup); - StringAssert.Contains(text, "\"DisplayVersion\" \"${VERSION}\""); - StringAssert.Contains(text, "\"Publisher\" \"${EDITORE}\""); - StringAssert.Contains(text, "!define EDITORE \"Alberto Balbo\""); - StringAssert.Contains(text, "EdgeUpdate\\Clients\\${WEBVIEW2_GUID}"); - StringAssert.Contains(text, "https://developer.microsoft.com/microsoft-edge/webview2/"); - Assert.DoesNotContain("HKLM\" \"${CHIAVE", text, "nothing written for every user"); - Assert.IsFalse(Regex.IsMatch(text, @"Write\w*\s+HKLM"), "no machine-wide registry"); + // Not a package at all: the bare program, or anything with bytes after the footer. + Assert.IsNull(Package.Read(stub)); + var longer = WriteBytes(temp.Combine("piu-lungo.exe"), [.. File.ReadAllBytes(setup), 0]); + Assert.IsNull(Package.Read(longer)); - // The uninstall section deletes only the program, its shortcuts and its registry entries. - var uninstall = text[text.IndexOf("Section \"Uninstall\"", StringComparison.Ordinal)..]; - uninstall = uninstall[..uninstall.IndexOf("SectionEnd", StringComparison.Ordinal)]; - foreach (Match removal in Removals().Matches(uninstall)) - { - var target = removal.Groups["target"].Value; - Assert.IsTrue( - target.StartsWith("$INSTDIR\\", StringComparison.Ordinal) || target == "$INSTDIR" - || target is "$SMPROGRAMS\\Febe.lnk" or "$DESKTOP\\Febe.lnk" or "$TEMP\\.net\\Febe", - $"the uninstaller removes «{target}»: only the program may go"); - } + // A byte of Febe.exe changed: the SHA-256 (or Brotli itself) says no. + var bytes = File.ReadAllBytes(setup); + bytes[info.ProgramStart + (info.DataLength / 2)] ^= 0x5A; + var damaged = WriteBytes(temp.Combine("rovinato.exe"), bytes); + var damagedInfo = Package.Read(damaged)!; + var error = Assert.ThrowsExactly(() => Package.ExtractProgram(damaged, damagedInfo, temp.Combine("x.exe"))); + Assert.AreEqual(Texts.Damaged, error.Message); - Assert.DoesNotContain("$LOCALAPPDATA\\Febe", uninstall.Replace("StrCpy $R8 \"$LOCALAPPDATA\\Febe\"", string.Empty, StringComparison.Ordinal), "never the Data folder"); - Assert.DoesNotContain("$PICTURES", uninstall, "never the library"); - Assert.DoesNotContain("MB_YESNO", uninstall, "it asks nothing about the data"); - StringAssert.Contains(uninstall, "DeleteRegValue HKCU \"${CHIAVE_AVVIO}\" \"Febe\"", "the start with the computer goes with the program"); + // A footer that does not describe the file: an error, not a guess. + bytes = File.ReadAllBytes(setup); + bytes[bytes.Length - Package.FooterLength + 16] ^= 1; + Assert.ThrowsExactly(() => Package.Read(WriteBytes(temp.Combine("piede.exe"), bytes))); + + // The tool never packs a package again, nor without a version of the build. + Assert.ThrowsExactly(() => Package.Write(setup, program, "0.0.1", temp.Combine("doppio.exe"))); + Assert.ThrowsExactly(() => Package.Write(stub, program, "1.0", temp.Combine("v.exe"))); + Assert.IsFalse(File.Exists(temp.Combine("doppio.exe")) || File.Exists(temp.Combine("doppio.exe.part"))); } [TestMethod] - public void TheBuildScriptIsValidBashAndProducesTheTwoFilesUnder100Mb() + public void TheCommandLineHasTheOptionsOfNsis() + { + var root = Root("Prove"); + Assert.AreEqual(new CommandLine(), CommandLine.Parse([])); + Assert.IsTrue(CommandLine.Parse(["/S"]).Silent); + Assert.IsTrue(CommandLine.Parse(["/s"]).Silent); + + // /D= is the last and takes the rest of the line, spaces included, as with NSIS. + var folder = Path.Combine(root, "Programmi personali", "Febe"); + var line = CommandLine.Parse(["/S", "/D=" + Path.Combine(root, "Programmi"), "personali" + Path.DirectorySeparatorChar + "Febe"]); + Assert.IsTrue(line.Silent); + Assert.AreEqual(folder, line.InstallFolder); + + line = CommandLine.Parse(["/PROVA=" + root, $"/_?={folder}", "/ATTENDI=4242"]); + Assert.AreEqual(root, line.TestRoot); + Assert.AreEqual(folder, line.UninstallFolder); + Assert.AreEqual(4242, line.WaitFor); + CollectionAssert.AreEqual(new[] { "/PROVA=" + root }, line.PassOn().ToArray(), "the internal options are not passed on"); + CollectionAssert.AreEqual(new[] { "/S" }, CommandLine.Parse(["/S"]).PassOn().ToArray()); + + Assert.ThrowsExactly(() => CommandLine.Parse(["/X"])); + Assert.ThrowsExactly(() => CommandLine.Parse(["/D=relativa"])); + Assert.ThrowsExactly(() => CommandLine.Parse(["/D="])); + + // /PROVA= at the root of a drive: refused here, with its message, not later as an unhandled crash (the name of + // the folder is the registry key of the test, and a root has none). + var driveRoot = Path.GetPathRoot(Path.GetTempPath())!; + var refused = Assert.ThrowsExactly(() => CommandLine.Parse(["/S", "/PROVA=" + driveRoot])); + StringAssert.Contains(refused.Message, "/PROVA="); + Assert.ThrowsExactly(() => Locations.ForTest(driveRoot), "what Parse refuses is what ForTest would refuse"); + + // The build tool. + Assert.AreEqual(ToolCommand.Pack, CommandLine.Parse(["--impacchetta", "a", "b", "1.0.0", "c"]).Tool); + Assert.AreEqual(ToolCommand.Verify, CommandLine.Parse(["--verifica", "a", "b"]).Tool); + Assert.AreEqual(ToolCommand.Zip, CommandLine.Parse(["--zip", "a.zip", "b"]).Tool); + Assert.ThrowsExactly(() => CommandLine.Parse(["--impacchetta", "a"])); + Assert.ThrowsExactly(() => CommandLine.Parse(["--altro"])); + } + + [TestMethod] + public void AnInstallationIsPerUserWithTheShortcutsAndTheEntryInAppsInstalled() + { + using var bed = new SetupBed("installa"); + var setup = bed.Package("0.1.2", seed: 5); + var ui = new ScriptedInterface { DesktopShortcut = true, StartFebe = true }; + + Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(setup, Package.Read(setup)!, new CommandLine())); + + var folder = bed.Locations.DefaultInstallFolder; + Assert.AreEqual(Path.Combine(bed.Root, "AppData", "Programs", "Febe"), folder, "%LOCALAPPDATA%\\Programs\\Febe"); + CollectionAssert.AreEqual(bed.Program(5), File.ReadAllBytes(Path.Combine(folder, "Febe.exe"))); + Assert.AreEqual(PackageKind.Uninstaller, Package.Read(Path.Combine(folder, "Disinstalla Febe.exe"))!.Kind); + CollectionAssert.AreEquivalent(new[] { "Febe.exe", "Disinstalla Febe.exe" }, Directory.GetFiles(folder).Select(Path.GetFileName).ToArray(), "nothing else, no .nuovo left"); + + // The shortcuts: Start menu always, desktop as chosen; both to Febe.exe, from its folder, with its icon. + Assert.HasCount(2, bed.System.Shortcuts); + foreach (var (shortcut, path) in bed.System.Shortcuts.Zip([bed.Locations.StartMenuShortcut, bed.Locations.DesktopShortcut])) + { + Assert.AreEqual(path, shortcut.Path); + Assert.AreEqual(Path.Combine(folder, "Febe.exe"), shortcut.Target); + Assert.AreEqual(folder, shortcut.WorkingDirectory); + Assert.AreEqual(Path.Combine(folder, "Febe.exe"), shortcut.IconPath); + Assert.AreEqual(0, shortcut.IconIndex); + Assert.AreEqual("Archivio personale di foto, video e storie da Instagram", shortcut.Description); + } + + // Apps installed: under HKEY_CURRENT_USER only (the fake has nothing else to write to). + var key = bed.Locations.UninstallKey; + Assert.AreEqual(Locations.TestRegistryRoot(bed.Root) + @"Software\Microsoft\Windows\CurrentVersion\Uninstall\Febe", key); + Assert.AreEqual("Febe", bed.System.String(key, "DisplayName")); + Assert.AreEqual("0.1.2", bed.System.String(key, "DisplayVersion")); + Assert.AreEqual("Alberto Balbo", bed.System.String(key, "Publisher")); + Assert.AreEqual(Path.Combine(folder, "Febe.exe") + ",0", bed.System.String(key, "DisplayIcon")); + Assert.AreEqual(folder, bed.System.String(key, "InstallLocation")); + var uninstaller = $"\"{Path.Combine(folder, "Disinstalla Febe.exe")}\""; + Assert.AreEqual($"{uninstaller} \"/PROVA={bed.Root}\"", bed.System.String(key, "UninstallString")); + Assert.AreEqual($"{uninstaller} /S \"/PROVA={bed.Root}\"", bed.System.String(key, "QuietUninstallString")); + Assert.AreEqual("https://gitea.encke-hake.ts.net/Alby96/Febe", bed.System.String(key, "URLInfoAbout")); + Assert.AreEqual(1, bed.System.ReadUserDword(key, "NoModify")); + Assert.AreEqual(1, bed.System.ReadUserDword(key, "NoRepair")); + var size = new DirectoryInfo(folder).EnumerateFiles().Sum(f => f.Length) / 1024; + Assert.AreEqual((int)size, bed.System.ReadUserDword(key, "EstimatedSize")); + + // WebView2 is there (in the fake): no question. Febe starts, from its folder. + CollectionAssert.DoesNotContain(ui.Calls, "webview2"); + Assert.HasCount(1, bed.System.Started); + Assert.AreEqual(Path.Combine(folder, "Febe.exe"), bed.System.Started[0].Executable); + Assert.AreEqual(folder, bed.System.Started[0].WorkingDirectory); + CollectionAssert.AreEqual(new[] { "benvenuto", "avanzamento", "installato" }, ui.Calls); + Assert.IsNull(ui.Version, "a fresh installation: nothing installed before"); + } + + [TestMethod] + public void WithoutTheDesktopShortcutAndInAnotherFolderOnlyTheStartMenuHasFebe() + { + using var bed = new SetupBed("cartella"); + var setup = bed.Package("0.1.2", seed: 6); + var folder = Path.Combine(bed.Root, "Altrove", "Febe"); + var ui = new ScriptedInterface { DesktopShortcut = false }; + + Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(setup, Package.Read(setup)!, CommandLine.Parse(["/D=" + folder]))); + + Assert.IsTrue(File.Exists(Path.Combine(folder, "Febe.exe"))); + Assert.IsFalse(Directory.Exists(bed.Locations.DefaultInstallFolder)); + Assert.AreEqual(bed.Locations.StartMenuShortcut, bed.System.Shortcuts.Single().Path); + Assert.AreEqual(folder, ui.Folder); + Assert.IsEmpty(bed.System.Started, "«Apri Febe adesso» unchecked"); + } + + [TestMethod] + public void AnUpdateWithoutAFolderGoesWhereFebeIsAlreadyInstalled() + { + using var bed = new SetupBed("dove-era"); + var folder = Path.Combine(bed.Root, "Altrove", "Febe"); + var first = bed.Package("0.1.1", seed: 20); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(first, Package.Read(first)!, CommandLine.Parse(["/D=" + folder]))); + + // With the dialogs: the first page names the folder where Febe is, and the update replaces that program. + var second = bed.Package("0.2.0", seed: 21); + var ui = new ScriptedInterface(); + Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(second, Package.Read(second)!, new CommandLine())); + Assert.AreEqual(folder, ui.Folder); + Assert.AreEqual("0.1.1", ui.Version); + CollectionAssert.AreEqual(bed.Program(21), File.ReadAllBytes(Path.Combine(folder, "Febe.exe"))); + Assert.IsFalse(Directory.Exists(bed.Locations.DefaultInstallFolder), "no second Febe in the default folder"); + Assert.AreEqual(folder, bed.System.String(bed.Locations.UninstallKey, "InstallLocation")); + Assert.IsTrue(bed.System.Shortcuts.All(s => s.Target == Path.Combine(folder, "Febe.exe"))); + + // Silent too; and a Febe open there is seen there. + var third = bed.Package("0.3.0", seed: 22); + using (new FileStream(Path.Combine(folder, "Febe.exe"), FileMode.Open, FileAccess.Read, FileShare.None)) + { + var errors = new StringWriter(); + Assert.AreEqual(ExitCodes.Failed, bed.Flow(new SilentInterface(errors)).Install(third, Package.Read(third)!, CommandLine.Parse(["/S"]))); + StringAssert.Contains(errors.ToString(), "Febe è aperto"); + } + + Assert.AreEqual(ExitCodes.Done, bed.Flow(new SilentInterface(TextWriter.Null)).Install(third, Package.Read(third)!, CommandLine.Parse(["/S"]))); + CollectionAssert.AreEqual(bed.Program(22), File.ReadAllBytes(Path.Combine(folder, "Febe.exe"))); + Assert.IsFalse(Directory.Exists(bed.Locations.DefaultInstallFolder)); + + // /D= still decides when given; an entry whose folder is not a full path counts as none. + var actions = new SetupActions(bed.System, bed.Locations); + Assert.AreEqual(folder, actions.InstalledFolder()); + bed.System.WriteUserString(bed.Locations.UninstallKey, "InstallLocation", "Programs\\Febe"); + Assert.IsNull(actions.InstalledFolder()); + bed.System.WriteUserString(bed.Locations.UninstallKey, "InstallLocation", folder + Path.DirectorySeparatorChar); + Assert.AreEqual(folder, actions.InstalledFolder()); + } + + [TestMethod] + public void TheSizeInAppsInstalledCountsOnlyTheFilesOfTheInstaller() + { + using var bed = new SetupBed("dimensione"); + var folder = Path.Combine(bed.Root, "Disco", "Febe"); + + // A folder with something else in it, and below it: never walked (a drive root would have folders nobody may read). + Directory.CreateDirectory(Path.Combine(folder, "altro", "dentro")); + File.WriteAllBytes(Path.Combine(folder, "altro", "dentro", "grande.bin"), new byte[3 * 1024 * 1024]); + File.WriteAllBytes(Path.Combine(folder, "accanto.bin"), new byte[1024 * 1024]); + var setup = bed.Package("0.1.2", seed: 23); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(setup, Package.Read(setup)!, CommandLine.Parse(["/D=" + folder]))); + + var ours = new FileInfo(Path.Combine(folder, "Febe.exe")).Length + new FileInfo(Path.Combine(folder, "Disinstalla Febe.exe")).Length; + Assert.AreEqual((int)(ours / 1024), bed.System.ReadUserDword(bed.Locations.UninstallKey, "EstimatedSize")); + } + + [TestMethod] + public void AReadOnlyFebeIsNotAnOpenFebeAndIsReplacedAndRemoved() + { + using var bed = new SetupBed("sola-lettura"); + var first = bed.Package("0.1.1", seed: 24); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(first, Package.Read(first)!, new CommandLine())); + var folder = bed.Locations.DefaultInstallFolder; + var executable = Path.Combine(folder, "Febe.exe"); + var uninstaller = Path.Combine(folder, "Disinstalla Febe.exe"); + try + { + // Left read-only by a copy or a restore: Windows refuses to open it for writing, but nothing is running. + File.SetAttributes(executable, File.GetAttributes(executable) | FileAttributes.ReadOnly); + File.SetAttributes(uninstaller, File.GetAttributes(uninstaller) | FileAttributes.ReadOnly); + Assert.IsFalse(SetupActions.IsFebeOpen(folder), "«Riprova» could never help: not «Febe è aperto»"); + + var second = bed.Package("0.2.0", seed: 25); + var ui = new ScriptedInterface { Retries = new Queue([true, true, false]) }; + Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(second, Package.Read(second)!, new CommandLine())); + CollectionAssert.AreEqual(new[] { "benvenuto", "avanzamento", "installato" }, ui.Calls); + CollectionAssert.AreEqual(bed.Program(25), File.ReadAllBytes(executable)); + + File.SetAttributes(executable, File.GetAttributes(executable) | FileAttributes.ReadOnly); + File.SetAttributes(uninstaller, File.GetAttributes(uninstaller) | FileAttributes.ReadOnly); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Uninstall(Path.Combine(bed.Locations.Temp, "copia.exe"), CommandLine.Parse(["/_?=" + folder]))); + Assert.IsFalse(File.Exists(executable)); + Assert.IsFalse(File.Exists(uninstaller)); + } + finally + { + foreach (var file in new[] { executable, uninstaller }) + { + if (File.Exists(file)) + { + File.SetAttributes(file, FileAttributes.Normal); + } + } + } + } + + [TestMethod] + public void AnInstallationOverAnotherReplacesTheProgramAndKeepsTheData() + { + using var bed = new SetupBed("aggiorna"); + var first = bed.Package("0.1.1", seed: 7); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(first, Package.Read(first)!, new CommandLine())); + + // Febe has been used: data, a library, a Data folder moved elsewhere, start with the computer. + var data = bed.FillData(); + var folder = bed.Locations.DefaultInstallFolder; + + var second = bed.Package("0.2.0", seed: 8); + var ui = new ScriptedInterface(); + Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Install(second, Package.Read(second)!, new CommandLine())); + + Assert.AreEqual("0.1.1", ui.Version, "the first page says it is an update"); + CollectionAssert.AreEqual(bed.Program(8), File.ReadAllBytes(Path.Combine(folder, "Febe.exe"))); + Assert.AreEqual("0.2.0", Package.Read(Path.Combine(folder, "Disinstalla Febe.exe"))!.Version); + Assert.AreEqual("0.2.0", bed.System.String(bed.Locations.UninstallKey, "DisplayVersion")); + CollectionAssert.AreEquivalent(new[] { "Febe.exe", "Disinstalla Febe.exe" }, Directory.GetFiles(folder).Select(Path.GetFileName).ToArray()); + data.AssertUntouched(); + } + + [TestMethod] + public void AnOpenFebeStopsTheInstallationUntilItIsClosed() + { + using var bed = new SetupBed("aperto"); + var first = bed.Package("0.1.1", seed: 9); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(first, Package.Read(first)!, new CommandLine())); + var executable = Path.Combine(bed.Locations.DefaultInstallFolder, "Febe.exe"); + var second = bed.Package("0.2.0", seed: 10); + + using (new FileStream(executable, FileMode.Open, FileAccess.Read, FileShare.None)) + { + Assert.IsTrue(SetupActions.IsFebeOpen(bed.Locations.DefaultInstallFolder)); + + // Silent: an error on the standard error, nothing replaced. + var errors = new StringWriter(); + Assert.AreEqual(ExitCodes.Failed, bed.Flow(new SilentInterface(errors)).Install(second, Package.Read(second)!, CommandLine.Parse(["/S"]))); + StringAssert.Contains(errors.ToString(), "Febe è aperto"); + + // With dialogs: «Annulla» gives up. + var ui = new ScriptedInterface { Retries = new Queue([false]) }; + Assert.AreEqual(ExitCodes.Cancelled, bed.Flow(ui).Install(second, Package.Read(second)!, new CommandLine())); + CollectionAssert.AreEqual(new[] { "benvenuto", "aperto" }, ui.Calls); + } + + CollectionAssert.AreEqual(bed.Program(9), File.ReadAllBytes(executable)); + Assert.AreEqual("0.1.1", bed.System.String(bed.Locations.UninstallKey, "DisplayVersion")); + + // Closed now: «Riprova» goes on. + Assert.IsFalse(SetupActions.IsFebeOpen(bed.Locations.DefaultInstallFolder)); + var retry = new ScriptedInterface(); + Assert.AreEqual(ExitCodes.Done, bed.Flow(retry).Install(second, Package.Read(second)!, new CommandLine())); + CollectionAssert.AreEqual(bed.Program(10), File.ReadAllBytes(executable)); + } + + [TestMethod] + public void TheUninstallerRemovesOnlyTheProgramItsShortcutsAndItsEntriesAndSaysWhereTheDataAre() + { + using var bed = new SetupBed("disinstalla"); + var setup = bed.Package("0.1.2", seed: 11); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(setup, Package.Read(setup)!, new CommandLine())); + var folder = bed.Locations.DefaultInstallFolder; + var data = bed.FillData(); + + // Something of Alberto's in the program folder, and the libraries Febe.exe extracted by itself. + File.WriteAllText(Path.Combine(folder, "appunti.txt"), "miei"); + Directory.CreateDirectory(Path.Combine(bed.Locations.ExtractionFolder, "abc")); + File.WriteAllText(Path.Combine(bed.Locations.ExtractionFolder, "abc", "e_sqlite3.dll"), "x"); + + // Start with the computer: this Febe, this Febe with --dati, a portable Febe with --dati, something else. + var run = bed.Locations.RunKey; + var executable = Path.Combine(folder, "Febe.exe"); + bed.System.WriteUserString(run, "Febe", Autostart.Command(executable)); + bed.System.WriteUserString(run, "Febe-AbC", Autostart.Command(executable.ToUpperInvariant(), Path.Combine(bed.Root, "Secondo"))); + bed.System.WriteUserString(run, "Febe-Portabile", Autostart.Command(Path.Combine(bed.Root, "Portabile", "Febe.exe"), Path.Combine(bed.Root, "Terzo"))); + bed.System.WriteUserString(run, "Altro", Autostart.Command(executable)); + + var ui = new ScriptedInterface(); + Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Uninstall(Path.Combine(bed.Locations.Temp, "copia.exe"), CommandLine.Parse(["/_?=" + folder]))); + + Assert.IsFalse(File.Exists(executable)); + Assert.IsFalse(File.Exists(Path.Combine(folder, "Disinstalla Febe.exe"))); + Assert.IsTrue(File.Exists(Path.Combine(folder, "appunti.txt")), "not ours: it stays, and so does the folder"); + Assert.IsFalse(File.Exists(bed.Locations.StartMenuShortcut)); + Assert.IsFalse(File.Exists(bed.Locations.DesktopShortcut)); + Assert.IsFalse(Directory.Exists(bed.Locations.ExtractionFolder)); + Assert.IsFalse(bed.System.HasKey(bed.Locations.UninstallKey)); + CollectionAssert.AreEquivalent(new[] { "Febe-Portabile", "Altro" }, bed.System.UserValueNames(run).ToArray()); + data.AssertUntouched(); + + // It asked nothing about the data and said where they are: the folder chosen in Impostazioni. + CollectionAssert.AreEqual(new[] { "conferma", "disinstallato" }, ui.Calls); + Assert.AreEqual((data.MovedDataFolder, bed.Locations.Library), ui.UninstalledWith); + + // A second time, with the program folder now empty: the folder goes too. Meanwhile a portable Febe with the + // default Data folder took «Febe» for itself: it starts another Febe.exe, so it stays. + File.Delete(Path.Combine(folder, "appunti.txt")); + var portable = Autostart.Command(Path.Combine(bed.Root, "Portabile", "Febe.exe")); + bed.System.WriteUserString(run, "Febe", portable); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Uninstall(Path.Combine(bed.Locations.Temp, "copia.exe"), CommandLine.Parse(["/_?=" + folder]))); + Assert.IsFalse(Directory.Exists(folder)); + Assert.AreEqual(portable, bed.System.String(run, "Febe"), "«Febe» of another Febe.exe is not ours to remove"); + } + + [TestMethod] + public void TheUninstallerAsksAndAnOpenFebeOrANoStopsItBeforeAnything() + { + using var bed = new SetupBed("rifiuto"); + var setup = bed.Package("0.1.2", seed: 12); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(setup, Package.Read(setup)!, new CommandLine())); + var folder = bed.Locations.DefaultInstallFolder; + var line = CommandLine.Parse(["/_?=" + folder]); + + var no = new ScriptedInterface { Confirm = false }; + Assert.AreEqual(ExitCodes.Cancelled, bed.Flow(no).Uninstall("copia.exe", line)); + using (new FileStream(Path.Combine(folder, "Febe.exe"), FileMode.Open, FileAccess.Read, FileShare.None)) + { + Assert.AreEqual(ExitCodes.Cancelled, bed.Flow(new ScriptedInterface { Retries = new Queue([false]) }).Uninstall("copia.exe", line)); + var errors = new StringWriter(); + Assert.AreEqual(ExitCodes.Failed, bed.Flow(new SilentInterface(errors)).Uninstall("copia.exe", CommandLine.Parse(["/S", "/_?=" + folder]))); + StringAssert.Contains(errors.ToString(), "La disinstallazione non è riuscita: Febe è aperto"); + } + + Assert.IsTrue(File.Exists(Path.Combine(folder, "Febe.exe"))); + Assert.IsTrue(File.Exists(bed.Locations.StartMenuShortcut)); + Assert.IsTrue(bed.System.HasKey(bed.Locations.UninstallKey)); + } + + [TestMethod] + public void StartedFromTheProgramFolderTheUninstallerRunsACopyOfItselfFromTemp() + { + using var bed = new SetupBed("copia"); + var setup = bed.Package("0.1.2", seed: 13); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new ScriptedInterface()).Install(setup, Package.Read(setup)!, new CommandLine())); + var folder = bed.Locations.DefaultInstallFolder; + var uninstaller = Path.Combine(folder, "Disinstalla Febe.exe"); + + // An old copy left by an earlier uninstallation goes; nothing else in %TEMP% does. + Directory.CreateDirectory(bed.Locations.Temp); + File.WriteAllText(Path.Combine(bed.Locations.Temp, "Febe-disinstalla-1.exe"), "vecchia"); + File.WriteAllText(Path.Combine(bed.Locations.Temp, "altro.exe"), "non nostro"); + SetupFlow.RemoveOldUninstallerCopies(bed.Locations, selfPath: uninstaller); + Assert.IsFalse(File.Exists(Path.Combine(bed.Locations.Temp, "Febe-disinstalla-1.exe"))); + Assert.IsTrue(File.Exists(Path.Combine(bed.Locations.Temp, "altro.exe"))); + + var ui = new ScriptedInterface(); + Assert.AreEqual(ExitCodes.Done, bed.Flow(ui).Uninstall(uninstaller, CommandLine.Parse(["/S", "/PROVA=" + bed.Root]))); + + Assert.IsEmpty(ui.Calls, "the copy asks, not this one"); + Assert.IsTrue(File.Exists(uninstaller), "nothing removed yet"); + var (copy, arguments, workingDirectory) = bed.System.Started.Single(); + Assert.AreEqual(Path.Combine(bed.Locations.Temp, $"Febe-disinstalla-{Environment.ProcessId}.exe"), copy); + CollectionAssert.AreEqual(File.ReadAllBytes(uninstaller), File.ReadAllBytes(copy)); + CollectionAssert.AreEqual(new[] { "/S", "/PROVA=" + bed.Root, "/_?=" + folder, $"/ATTENDI={Environment.ProcessId}" }, arguments.ToArray()); + Assert.AreEqual(bed.Locations.Temp, workingDirectory); + + // The copy waits for the first one to end, then does the work. + var copyLine = CommandLine.Parse(arguments.ToArray()); + Assert.AreEqual(ExitCodes.Done, bed.Flow(new SilentInterface(TextWriter.Null)).Uninstall(copy, copyLine)); + Assert.AreEqual(Environment.ProcessId, bed.System.WaitedFor.Single()); + Assert.IsFalse(Directory.Exists(folder)); + } + + [TestMethod] + public void WebView2IsLookedForWhereMicrosoftPutsItAndItsPageOfferedWhenMissing() + { + using var bed = new SetupBed("webview2"); + var actions = new SetupActions(bed.System, bed.Locations); + const string Client = @"Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}"; + bed.System.Machine.Clear(); + Assert.IsNull(actions.WebView2Version()); + + bed.System.Machine[(@"SOFTWARE\WOW6432Node\" + Client, "pv")] = "0.0.0.0"; + Assert.IsNull(actions.WebView2Version(), "0.0.0.0: removed"); + bed.System.Machine[(@"SOFTWARE\" + Client, "pv")] = "131.0.2903.70"; + Assert.AreEqual("131.0.2903.70", actions.WebView2Version()); + bed.System.Machine.Clear(); + bed.System.WriteUserString(@"Software\" + Client, "pv", "130.0.1.2"); + Assert.AreEqual("130.0.1.2", actions.WebView2Version(), "installed for the user only; never under the test key"); + bed.System.DeleteUserKeyTree(@"Software\" + Client); + + // Missing: the question, and the page of Microsoft only on «Apri la pagina»; never in silent mode. + var setup = bed.Package("0.1.2", seed: 14); + var yes = new ScriptedInterface { OpenWebView2Page = true }; + Assert.AreEqual(ExitCodes.Done, bed.Flow(yes).Install(setup, Package.Read(setup)!, new CommandLine())); + CollectionAssert.AreEqual(new[] { "benvenuto", "avanzamento", "webview2", "installato" }, yes.Calls); + CollectionAssert.AreEqual(new[] { "https://developer.microsoft.com/microsoft-edge/webview2/" }, bed.System.Opened); + + Assert.AreEqual(ExitCodes.Done, bed.Flow(new SilentInterface(TextWriter.Null)).Install(setup, Package.Read(setup)!, CommandLine.Parse(["/S"]))); + Assert.HasCount(1, bed.System.Opened); + Assert.IsEmpty(bed.System.Started, "silent: Febe is not started"); + Assert.IsTrue(File.Exists(bed.Locations.DesktopShortcut), "silent: the desktop shortcut, as the NSIS sections chosen by default"); + } + + [TestMethod] + public void TheKeysAreThoseFebeForWindowsWritesItself() + { + string[] desktop = [Autostart.RunKey, Autostart.ValueName]; + string[] installer = [Product.RunKey, Product.AutostartValue]; + CollectionAssert.AreEqual(desktop, installer); + StringAssert.StartsWith(Autostart.ValueNameFor(Path.Combine(Root("x"), "Secondo")), Product.AutostartPrefix); + StringAssert.StartsWith(Autostart.Command(@"C:\Febe\Febe.exe", @"D:\Dati"), "\"C:\\Febe\\Febe.exe\"", "the uninstaller recognizes the values by the quoted program"); + + var shell = File.ReadAllText(Repository.PathOf("src", "Febe.Desktop", "WindowsShell.cs")); + StringAssert.Contains(shell, $"public const string Key = @\"{Product.FebeKey}\";"); + StringAssert.Contains(shell, $"Read(\"{Product.DataFolderValue}\")"); + } + + [TestMethod] + public void TheToolWritesThePortableZipWithEachFileAtTheTop() + { + using var temp = new TempFolder("zip"); + var program = WriteBytes(temp.Combine("Febe.exe"), Bytes(300_000, seed: 15, compressible: true)); + File.WriteAllText(temp.Combine("LEGGIMI.txt"), "Febe portabile\r\n"); + var zip = temp.Combine("Febe-0.1.2-portabile.zip"); + + Febe.Installer.Program.Zip(zip, [program, temp.Combine("LEGGIMI.txt")]); + + using var archive = ZipFile.OpenRead(zip); + CollectionAssert.AreEqual(new[] { "Febe.exe", "LEGGIMI.txt" }, archive.Entries.Select(e => e.FullName).ToArray()); + using var entry = archive.GetEntry("Febe.exe")!.Open(); + using var copy = new MemoryStream(); + entry.CopyTo(copy); + CollectionAssert.AreEqual(File.ReadAllBytes(program), copy.ToArray()); + Assert.IsFalse(File.Exists(zip + ".part")); + } + + [TestMethod] + public void TheBuildScriptIsValidBashUsesOnlyDotnetAndProducesTheTwoFilesUnder100Mb() { var script = Repository.PathOf("installer", "costruisci.sh"); var text = File.ReadAllText(script); StringAssert.Contains(text, "set -euo pipefail"); StringAssert.Contains(text, "-p:PublishSingleFile=true -p:IncludeNativeLibrariesForSelfExtract=true -p:EnableCompressionInSingleFile=true"); + StringAssert.Contains(text, "dotnet publish src/Febe.Installer/Febe.Installer.csproj -c Release -r win-x64"); + StringAssert.Contains(text, "pacchetto --impacchetta \"$installatore/Febe.Installer.exe\" \"$pubblicazione/Febe.exe\" \"$versione\" \"$setup\""); + StringAssert.Contains(text, "pacchetto --verifica \"$setup\" \"$pubblicazione/Febe.exe\""); + StringAssert.Contains(text, "pacchetto --zip \"$zip_portabile\""); StringAssert.Contains(text, "Febe-Setup-$versione.exe"); StringAssert.Contains(text, "Febe-$versione-portabile.zip"); StringAssert.Contains(text, "100 * 1024 * 1024"); Assert.DoesNotContain("\r\n", text, "Unix line ends: bash would choke on CR"); + foreach (var program in new[] { "makensis", "python3", "command -v zip", "zip -q" }) + { + Assert.DoesNotContain(program, text, "only the .NET SDK"); + } + + // The publication of the installer: self-contained, single file, trimmed, compressed; no package of others. + var project = File.ReadAllText(Repository.PathOf("src", "Febe.Installer", "Febe.Installer.csproj")); + foreach (var property in new[] { "true", "true", "true", "true", "app.manifest" }) + { + StringAssert.Contains(project, property); + } + + Assert.DoesNotContain("PackageReference", project); + var manifest = File.ReadAllText(Repository.PathOf("src", "Febe.Installer", "app.manifest")); + StringAssert.Contains(manifest, "", "never administrator rights, even with «Setup» in the name"); + StringAssert.Contains(manifest, "name=\"Microsoft.Windows.Common-Controls\" version=\"6.0.0.0\"", "the dialogs of Windows need the common controls 6"); var bash = FindBash(); if (bash is null) @@ -124,7 +572,76 @@ public sealed partial class InstallerTests Assert.AreEqual(0, process.ExitCode, errors); } - private static string? FindOnPath(string name) => OnPath(name).FirstOrDefault(); + [TestMethod] + public void NsisIsGoneFromTheProgramTheBuildAndTheGuide() + { + var root = Repository.Root(); + if (root is null) + { + Assert.Inconclusive("Il repository non è accanto alle prove."); + } + + Assert.IsFalse(File.Exists(Path.Combine(root, "installer", "febe.nsi"))); + var offending = new List(); + var files = new[] { "src", "tools", "installer", "docker", ".gitea", Path.Combine("docs", "guida") } + .Select(folder => Path.Combine(root, folder)) + .Where(Directory.Exists) + .SelectMany(folder => Directory.EnumerateFiles(folder, "*", SearchOption.AllDirectories)) + .Concat(new[] { "CLAUDE.md", ".gitattributes", Path.Combine("docs", "windows.md"), Path.Combine("docs", "processo.md") }.Select(file => Path.Combine(root, file))) + .Where(file => File.Exists(file) && !IsBuildOutput(root, file) && IsText(file)); + foreach (var file in files) + { + var text = File.ReadAllText(file); + if (string.Equals(Path.GetFileName(file), "CLAUDE.md", StringComparison.Ordinal)) + { + // Rule 12 is the copy of spec appendix A, which says with which stage NSIS left + // (SpecificationConsistencyTests wants it there): only that line may name it, and only to say it is gone. + text = string.Join('\n', text.Split('\n').Where(line => !(line.StartsWith("12. Niente componenti esterni", StringComparison.Ordinal) && line.Contains("Sono già usciti", StringComparison.Ordinal)))); + } + + if (NsisWord().IsMatch(text)) + { + offending.Add(Path.GetRelativePath(root, file)); + } + } + + Assert.IsEmpty(offending, "NSIS is still named in: " + string.Join(", ", offending)); + } + + private static bool IsBuildOutput(string root, string file) + { + var relative = Path.GetRelativePath(root, file).Replace('\\', '/'); + return relative.Contains("/bin/", StringComparison.Ordinal) || relative.Contains("/obj/", StringComparison.Ordinal) || relative.Contains("/node_modules/", StringComparison.Ordinal); + } + + private static bool IsText(string file) => + Path.GetExtension(file).ToLowerInvariant() is ".cs" or ".csproj" or ".md" or ".sh" or ".yml" or ".yaml" or ".json" or ".xml" or ".js" or ".css" or ".html" or ".txt" or ".props" or ".manifest" or "" or ".gitattributes" or ".nsi"; + + private static string Root(string name) => + Path.Combine(Path.GetTempPath(), name); + + private static byte[] Bytes(int length, int seed, bool compressible) + { + var random = new Random(seed); + var bytes = new byte[length]; + random.NextBytes(bytes); + if (compressible) + { + // Long runs, as in an executable: Brotli has something to do. + for (var i = 0; i < length; i += 4096) + { + bytes.AsSpan(i, Math.Min(2048, length - i)).Fill((byte)(i / 4096)); + } + } + + return bytes; + } + + private static string WriteBytes(string path, byte[] bytes) + { + File.WriteAllBytes(path, bytes); + return path; + } /// /// A bash that checks the script on this system. Elsewhere than Windows, the first on PATH. On Windows Git Bash @@ -136,11 +653,11 @@ public sealed partial class InstallerTests { if (!OperatingSystem.IsWindows()) { - return FindOnPath("bash"); + return OnPath("bash").FirstOrDefault(); } var roots = new List(); - if (FindOnPath("git") is { } git) + if (OnPath("git").FirstOrDefault() is { } git) { // git.exe sits in \cmd, \bin or \mingw64\bin. for (var folder = Path.GetDirectoryName(git); folder is not null && roots.Count < 3; folder = Path.GetDirectoryName(folder)) @@ -189,6 +706,227 @@ public sealed partial class InstallerTests } } - [GeneratedRegex(@"^\s*(?:Delete|RMDir)(?:\s+/\w+)*\s+""(?[^""]+)""", RegexOptions.Multiline)] - private static partial Regex Removals(); + [GeneratedRegex(@"\b(?:nsis|makensis)\b|\.nsi\b", RegexOptions.IgnoreCase)] + private static partial Regex NsisWord(); + + /// A test installation: a folder of its own (Locations.ForTest), a fake Windows, packages made on the spot. + private sealed class SetupBed : IDisposable + { + private readonly TempFolder _temp; + private readonly Dictionary _programs = []; + + public SetupBed(string name) + { + _temp = new TempFolder("installatore-" + name); + Root = _temp.Path; + Locations = Locations.ForTest(Root); + System.Machine[(@"SOFTWARE\WOW6432Node\Microsoft\EdgeUpdate\Clients\{F3017226-FE2A-4295-8BDF-00C3A9A7E4C5}", "pv")] = "131.0.2903.70"; + } + + public string Root { get; } + + public Locations Locations { get; } + + public FakeSystem System { get; } = new(); + + public SetupFlow Flow(ISetupInterface ui) => new(System, Locations, ui); + + public byte[] Program(int seed) => _programs[seed]; + + /// A package of version with a Febe.exe of its own (by ). + public string Package(string version, int seed) + { + var folder = Directory.CreateDirectory(Path.Combine(Root, "pacchetti", seed.ToString(global::System.Globalization.CultureInfo.InvariantCulture))).FullName; + var stub = WriteBytes(Path.Combine(folder, "Febe.Installer.exe"), Bytes(20_000, seed: 1000 + seed, compressible: false)); + _programs[seed] = Bytes(400_000 + seed, seed, compressible: true); + var program = WriteBytes(Path.Combine(folder, "Febe.exe"), _programs[seed]); + var setup = Path.Combine(folder, $"Febe-Setup-{version}.exe"); + Febe.Installer.Package.Write(stub, program, version, setup); + return setup; + } + + /// Febe used for a while: a Data folder (moved by Impostazioni), the default one, a library. + public UsedData FillData() + { + var moved = Path.Combine(Root, "DatiSpostati"); + System.WriteUserString(Locations.FebeKey, "CartellaDati", moved); + var files = new[] + { + Path.Combine(moved, "febe.sqlite"), + Path.Combine(moved, "sessione", "sessione.json"), + Path.Combine(Locations.DefaultDataFolder, "febe.sqlite"), + Path.Combine(Locations.DefaultDataFolder, "browser", "Default", "Cookies"), + Path.Combine(Locations.Library, "alberto", "2026-11-18_post.jpg"), + }; + foreach (var file in files) + { + Directory.CreateDirectory(Path.GetDirectoryName(file)!); + File.WriteAllText(file, file); + } + + return new UsedData(this, moved, files); + } + + public void Dispose() => _temp.Dispose(); + } + + private sealed record UsedData(SetupBed Bed, string MovedDataFolder, string[] Files) + { + public void AssertUntouched() + { + foreach (var file in Files) + { + Assert.IsTrue(File.Exists(file), file); + Assert.AreEqual(file, File.ReadAllText(file)); + } + + Assert.AreEqual(MovedDataFolder, Bed.System.String(Bed.Locations.FebeKey, "CartellaDati"), "Febe's key is not the installer's"); + } + } + + /// Windows for the tests: a registry of HKEY_CURRENT_USER in memory, HKLM read from a table, shortcuts as small files. + private sealed class FakeSystem : ISystemAccess + { + private readonly Dictionary> _user = new(StringComparer.OrdinalIgnoreCase); + + public Dictionary<(string Key, string Name), string> Machine { get; } = []; + + public List Shortcuts { get; } = []; + + public List Opened { get; } = []; + + public List<(string Executable, IReadOnlyList Arguments, string WorkingDirectory)> Started { get; } = []; + + public List WaitedFor { get; } = []; + + public string? String(string key, string name) => ReadUserString(key, name); + + public bool HasKey(string key) => _user.Keys.Any(k => k.Equals(key, StringComparison.OrdinalIgnoreCase) || k.StartsWith(key + "\\", StringComparison.OrdinalIgnoreCase)); + + public string? ReadUserString(string key, string name) => + _user.TryGetValue(key, out var values) && values.TryGetValue(name, out var value) ? value as string : null; + + public int? ReadUserDword(string key, string name) => + _user.TryGetValue(key, out var values) && values.TryGetValue(name, out var value) && value is int number ? number : null; + + public void WriteUserString(string key, string name, string value) => Values(key)[name] = value; + + public void WriteUserDword(string key, string name, int value) => Values(key)[name] = value; + + public IReadOnlyList UserValueNames(string key) => _user.TryGetValue(key, out var values) ? [.. values.Keys] : []; + + public void DeleteUserValue(string key, string name) + { + if (_user.TryGetValue(key, out var values)) + { + values.Remove(name); + } + } + + public void DeleteUserKeyTree(string key) + { + foreach (var existing in _user.Keys.Where(k => k.Equals(key, StringComparison.OrdinalIgnoreCase) || k.StartsWith(key + "\\", StringComparison.OrdinalIgnoreCase)).ToList()) + { + _user.Remove(existing); + } + } + + public string? ReadMachineString(string key, string name) => Machine.GetValueOrDefault((key, name)); + + public void CreateShortcut(Shortcut shortcut) + { + Shortcuts.Add(shortcut); + Directory.CreateDirectory(Path.GetDirectoryName(shortcut.Path)!); + File.WriteAllText(shortcut.Path, shortcut.Target, Encoding.UTF8); + } + + public void OpenAddress(string address) => Opened.Add(address); + + public void Start(string executable, IReadOnlyList arguments, string workingDirectory) => Started.Add((executable, arguments, workingDirectory)); + + public void WaitForExit(int processId, TimeSpan timeout) => WaitedFor.Add(processId); + + public void Pause(TimeSpan delay) + { + } + + private Dictionary Values(string key) + { + if (!_user.TryGetValue(key, out var values)) + { + values = new Dictionary(StringComparer.OrdinalIgnoreCase); + _user[key] = values; + } + + return values; + } + } + + /// The pages, answered as told; each records its name in . + private sealed class ScriptedInterface : ISetupInterface + { + public bool DesktopShortcut { get; init; } = true; + + public bool StartFebe { get; init; } + + public bool OpenWebView2Page { get; init; } + + public bool Confirm { get; init; } = true; + + public Queue Retries { get; init; } = new([true]); + + public List Calls { get; } = []; + + public string? Version { get; private set; } + + public string? Folder { get; private set; } + + public (string DataFolder, string Library)? UninstalledWith { get; private set; } + + public bool? Welcome(string version, string? installedVersion, string installFolder) + { + Calls.Add("benvenuto"); + Version = installedVersion; + Folder = installFolder; + return DesktopShortcut; + } + + public bool RetryWhenFebeIsOpen(bool uninstalling) + { + Calls.Add("aperto"); + return Retries.Count > 0 && Retries.Dequeue(); + } + + public void RunWithProgress(string version, string installFolder, Action> work) + { + Calls.Add("avanzamento"); + work(_ => { }); + } + + public bool OfferWebView2Page() + { + Calls.Add("webview2"); + return OpenWebView2Page; + } + + public bool Installed() + { + Calls.Add("installato"); + return StartFebe; + } + + public bool ConfirmUninstall() + { + Calls.Add("conferma"); + return Confirm; + } + + public void Uninstalled(string dataFolder, string library) + { + Calls.Add("disinstallato"); + UninstalledWith = (dataFolder, library); + } + + public void Failed(bool uninstalling, string message) => Calls.Add("errore: " + message); + } } diff --git a/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs b/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs index 1f5b879..8ab72d9 100644 --- a/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs +++ b/tests/Febe.Tests/Desktop/SessionCopyOnLetGoTests.cs @@ -369,6 +369,104 @@ public sealed class SessionCopyOnLetGoTests Assert.IsNull(bed.App.SavedSession!.Read()); } + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task ABeginOfAReloadedPageCancelsTheLeaveEvenBeforeItsViewOpens() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + connection.PageLeaveGrace = TimeSpan.FromSeconds(1); + var view = await DockerBeginAsync(bed); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + + // A reload where the new page's «begin» arrives but its view does not open within the moment: «begin» alone says + // Alberto is back. Waited past PageLeaveGrace and well below DrivingGrace. + await connection.LeavePageAsync(ct); + view.Dispose(); + connection.RemoteViewClosed(); + await BeginAsync(bed, openLogin: false); + await browser.HideFromUserAsync(ct); + await Task.Delay(TimeSpan.FromSeconds(2.5), ct); + Assert.IsTrue(browser.UserIsDriving, "begin cancels the leave"); + Assert.AreEqual(0, browser.FakeCdp.CaptureReads); + Assert.DoesNotContain("Pagina del browser lasciata: nessuna vista", ReadLog(bed)); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + [DataRow(false, DisplayName = "«pageLeft» tardivo della pagina ricaricata")] + [DataRow(true, DisplayName = "vecchia vista chiusa da «Riprova»")] + public async Task ALeaveFollowedByAViewOpenAgainIsForgottenWhenThatViewEndsFromTheServer(bool oldViewClosed) + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + connection.PageLeaveGrace = TimeSpan.FromSeconds(1); + var view = await DockerBeginAsync(bed); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + + // The leave arrives while a view is open: the keepalive «pageLeft» of a reloaded page after the new page's + // «begin», or the old socket closed by «Riprova» while the new view opens without «begin». + if (oldViewClosed) + { + connection.RemoteViewClosed(); + } + else + { + await connection.LeavePageAsync(ct); + } + + await Task.Delay(TimeSpan.FromMilliseconds(600), ct); + + // That view then ends from the server (the browser stopped): it is not told to the connection. A browser that is + // down is not leaving it, so the lease waits for DrivingGrace, not for PageLeaveGrace. + view.Dispose(); + await Task.Delay(TimeSpan.FromSeconds(2.5), ct); + Assert.IsTrue(browser.UserIsDriving, "the earlier leave was forgotten once a view was open again"); + Assert.AreEqual(0, browser.FakeCdp.CaptureReads); + Assert.DoesNotContain("Pagina del browser lasciata: nessuna vista", ReadLog(bed)); + } + + [TestMethod] + [Timeout(60_000, CooperativeCancellation = true)] + public async Task LeavingTheBrowserPageWaitsForAnotherCommandOnlyForLetGoWait() + { + var ct = TestContext.CancellationToken; + await using var bed = await StartAsync(); + var browser = bed.Browser!; + var connection = bed.App.Connection!; + connection.PageLeaveGrace = TimeSpan.FromMilliseconds(300); + connection.LetGoWait = TimeSpan.FromMilliseconds(500); + connection.PageTurnWait = TimeSpan.FromSeconds(30); + var view = await DockerBeginAsync(bed); + browser.FakeCdp.LoggedIn = true; + browser.FakeCdp.Navigated(Site + "/"); + + // «Pagina iniziale» holds the commands of the connection while it waits for the page's turn, which a step of the + // profile search keeps for longer than leaving the page may wait. + using var press = CancellationTokenSource.CreateLinkedTokenSource(ct); + Task startPage; + using (await bed.App.Engine!.Services.PageTurns.TakeAsync(Febe.Core.Engine.PageUser.Search, ct)) + { + startPage = connection.OpenStartPageAsync(press.Token); + await Task.Delay(TimeSpan.FromMilliseconds(200), ct); + view.Dispose(); + connection.RemoteViewClosed(); + await DesktopTestBed.WaitUntilAsync(() => !browser.UserIsDriving, TimeSpan.FromSeconds(10), "la fine della guida dopo l'attesa massima"); + press.Cancel(); + } + + await startPage; + Assert.AreEqual(0, browser.FakeCdp.CaptureReads); + StringAssert.Contains(ReadLog(bed), "Pagina del browser lasciata: sessione non copiata, un altro comando del collegamento era ancora in corso."); + Assert.IsNull(bed.App.SavedSession!.Read()); + } + [TestMethod] [Timeout(60_000, CooperativeCancellation = true)] public async Task LeavingTheBrowserPageOnTheLoginPageCopiesNothingButGivesThePageBack() diff --git a/tests/Febe.Tests/Desktop/Support/Repository.cs b/tests/Febe.Tests/Desktop/Support/Repository.cs index 069f95c..21502a6 100644 --- a/tests/Febe.Tests/Desktop/Support/Repository.cs +++ b/tests/Febe.Tests/Desktop/Support/Repository.cs @@ -1,6 +1,6 @@ namespace Febe.Tests.Desktop.Support; -/// Files of the repository the desktop tests look at (the committed icon, the NSIS script). +/// Files of the repository the desktop tests look at (the committed icon, the build script of the installer). internal static class Repository { /// The folder with Febe.slnx, found from the test binaries upward; null outside a checkout. @@ -28,4 +28,22 @@ internal static class Repository return Path.Combine([root, .. parts]); } + + /// + /// A file or folder under docs/. The build of the Docker image copies the sources without docs/ (.dockerignore) and + /// without .git: there the test is inconclusive. In a checkout docs/ is always there, so the test goes on and a + /// missing path fails it. + /// + public static string Docs(params string[] parts) + { + var path = PathOf(["docs", .. parts]); + var root = Root()!; + var isCheckout = Directory.Exists(Path.Combine(root, ".git")) || File.Exists(Path.Combine(root, ".git")); + if (!Directory.Exists(Path.Combine(root, "docs")) && !isCheckout) + { + Assert.Inconclusive("Questa copia del repository non ha docs/ (costruzione dell'immagine Docker)."); + } + + return path; + } } diff --git a/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs b/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs index f1afa4b..bc9c508 100644 --- a/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs +++ b/tests/Febe.Tests/Docs/SpecificationConsistencyTests.cs @@ -5,31 +5,76 @@ namespace Febe.Tests.Docs; /// /// The documents agree with each other where a review of the 18 November 2026 changes found them apart: the rule on /// external components allows only gitleaks, Trivy, Xvfb and the Debian packages Chromium needs, and every other -/// component the project still uses says in which stage of 0.3.0 it leaves; no hypothesis of spec §6.6 is called -/// verified without an outcome in docs/sonda/esito.md; the questions Alberto answered are not open any more; and the -/// paragraphs of §2, §3, §4.10, §6.0, §6.1, §6.6, §13.2, §14.1 and §15 that were contradictory or unbounded say what -/// settles them. Since 25 November 2026 also Alberto's answers of that day (the session copied when the browser page is -/// left in Docker, the fonts of the Docker image, damaged images refused without a perceptual hash, HEVC RExt kept) -/// and the features of issue #59 (download order, Dashboard, grouped or per-file mosaic, stage D1). +/// component the project used says with which stage of 0.3.0 it left (all of them are built: since 25 November 2026 the +/// rule says so in the past tense, and no document may say that one of them is still in use); no hypothesis of spec +/// §6.6 is called verified without an outcome in docs/sonda/esito.md; the questions Alberto answered are not open any +/// more; and the paragraphs of §2, §3, §4.10, §6.0, §6.1, §6.6, §13.2, §14.1 and §15 that were contradictory or +/// unbounded say what settles them. Since 25 November 2026 also Alberto's answers of that day (the session copied when +/// the browser page is left in Docker, the fonts of the Docker image, damaged images refused without a perceptual hash, +/// HEVC RExt kept) and the features of issue #59 (download order, Dashboard, grouped or per-file mosaic, stage D1). /// [TestClass] public sealed partial class SpecificationConsistencyTests { - /// Packages that rule 13 allows for good; any other one must say in which stage it leaves. + /// Packages that rule 13 allows; since stage C1 no other package may be in Directory.Packages.props. private static readonly string[] AllowedPackages = ["Microsoft.Data.Sqlite", "Microsoft.Web.WebView2", "MSTest"]; /// The only exceptions the rule allows besides .NET, Microsoft.Data.Sqlite, the browser and MSTest. private static readonly string[] Exceptions = ["gitleaks e Trivy", "Xvfb", "pacchetti Debian che gli servono"]; /// - /// Components still in use that the rule must name, each with the stage of 0.3.0 it leaves with: the first stage - /// named after the last mention of the component. + /// Components the project used that the rule must name, each with the stage of 0.3.0 it left with: the first stage + /// named after the last mention of the component, in a sentence that says they left («uscito», «usciti»). /// private static readonly (string Component, string Stage)[] Leaving = [ ("SkiaSharp", "C1"), ("ffmpeg", "C3"), ("NSIS", "C6"), ("Node", "C6"), ("Archivo", "C6"), ("Lucide", "C6"), ]; + /// Words that put the leaving of a component in the future: none may be in the sentence that names it. + private static readonly string[] FutureLeaving = ["esce con", "escono con", "uscirà", "usciranno", "finché la tappa", "finché una tappa", "il codice di prima li usa"]; + + /// + /// Phrases that said a component that left with 0.3.0, or a part of it not built yet, is still in use (the stages + /// C1–C6 and S4b are built); none may be left in the documents (normalized like ). + /// + private static readonly string[] StillInUse = + [ + "escono con la loro tappa", + "il codice di prima li usa", + "non ancora unito", + "fino alla tappa c3 del traguardo 0.3.0 il fotogramma lo estrae ffmpeg", + "fra c3 e c4 un video hevc", + "fino alla tappa c2 del traguardo 0.3.0 si usa ancora ffprobe", + "fra c2 e c5 un file asf", + "un ffmpeg nel path serve ancora", + "`ffmpeg` solo fino alla tappa c3", + "finché ci sono, ffmpeg e ffprobe", + "fino ad allora archivo", + "fino ad allora lo costruisce nsis", + "fino alla tappa c6 della 0.3.0 restano il carattere archivo", + "font-family:\"archivo\"", + "quello usato oggi con skiasharp", + "quando skiasharp sarà tolto", + "finché questo non è costruito", + "in docker si copia solo a «ho finito» e alla fine del permesso", + "liberation sans", + "`fonts-liberation` esce", + ]; + + /// The documents looks at, besides docs/guida. + private static readonly string[] CurrentDocuments = + [ + "CLAUDE.md", "docs/SPECIFICA.md", "docs/docker.md", "docs/processo.md", "docs/windows.md", "docs/schermate/differenze.md", + "src/Febe.Web/LEGGIMI.md", "tests/Febe.Tests/Imaging/Riferimenti/LEGGIMI.md", + ]; + + /// + /// Since stage C6 the guide must not name these any more (InstallerTests and InHouseAssetsTests look for them in + /// docs/guida): there the rule may leave them unnamed, and if it names one, it still says the stage it left with. + /// + private static readonly string[] NotNamedInTheGuide = ["NSIS", "Archivo", "Lucide"]; + /// Questions of spec §16 that Alberto answered, with the day of the answer: their row must say so. private static readonly (string Number, string Day)[] AnsweredQuestions = [ @@ -78,15 +123,18 @@ public sealed partial class SpecificationConsistencyTests ["l'adozione non si fida della sola dimensione", "- **Adozione per percorso**", new[] { "rifà la conversione", "la sola dimensione non basta mai", "nome libero" }], ["le immagini animate si copiano come originali", "| Foto |", new[] { "immagini animate", "`acTL`", "`anim`/`anmf`" }], ["il file di prova delle cartelle rifiutate è un .part nella sola candidata", "- Cartelle rifiutate", new[] { "`.febe-prova-*.part`", "solo nella cartella candidata", "mai in dati, libreria, cartelle degli account o `/importa`" }], - ["i decodificatori dicono il loro sottoinsieme", "- decodificatori di immagini:", new[] { "rfc 6386", "codifica aritmetica", "precisione a 12 bit" }], + ["i decodificatori dicono il loro sottoinsieme", "- decodificatori di immagini:", new[] { "rfc 6386", "codifica aritmetica", "precisione a 12 bit", "resta fuori il gerarchico" }], + ["HEIC si decodifica in casa e non si dice mai danneggiato", "- decodificatori di immagini:", new[] { "heic/heif (iso/iec 23008-12)", "a griglia di riquadri", "dimensioni, miniatura e impronta visiva", "non si dice mai «file danneggiato o incompleto»", "non distingue un file rovinato da uno che non gestisce" }], + ["JPEG e PNG senza marcatore di fine sono troncati, le misure restano", "- decodificatori di immagini:", new[] { "`iend` o `eoi`", "anche quando dati e scansioni sembrano completi", "la sola lettura delle dimensioni dalle intestazioni resta tollerante" }], ["il decodificatore H.264 copre tutto lo standard", "- decodificatore H.264", new[] { "tutto lo standard", "extended", "high 10", "high 4:4:4", "piani di colore separati", "senza perdita", "monocromatico", "paff", "mbaff", "svc", "mvc", "cabac" }], ["il decodificatore H.265 è dentro la 0.3.0 e tiene RExt", "- decodificatore H.265/HEVC", new[] { "tappa c4", "main 10", "domanda 18", "risposta di alberto del 25 novembre 2026", "estensioni di formato (rext)", "che restano", "fino a 12 bit", "fotogramma non disponibile per questo video" }], ["VP9 e AV1 hanno la tessera neutra", "- VP9, AV1", new[] { "tessera neutra", "fotogramma non disponibile per questo video" }], ["i lettori dei contenitori comprendono ASF, FLV e MPEG-PS", "- lettori dei contenitori ASF", new[] { "flv", "mpeg-ps", "13818-1", "durata, dimensioni, codec e data", "tappa c5" }], + ["MPEG-PS ha codec e dimensioni dall'SPS, HEVC con il tipo 0x24, ma nessun fotogramma", "- lettori dei contenitori ASF", new[] { "dall'sps di una traccia h.264 o h.265", "tipo di flusso 0x24", "non si elencano", "la miniatura è la tessera neutra" }], ["l'installatore si scrive in casa", "- l'installatore di Windows", new[] { "al posto di nsis", "tappa c6" }], ["la CI non vuole Node", "- i passi della CI", new[] { "node", "git", "curl verso l'api di gitea", "tappa c6" }], ["le serie di conformità stanno nel repository con la loro fonte", "- Le serie di conformità ITU-T", new[] { "h.264.1", "h.265.1", "solo i flussi e l'md5 dell'uscita di riferimento", "`leggimi.md` che dice la fonte" }], - ["SkiaSharp esce anche dal disegno", "- ridimensionamento", new[] { "brandicon", "demoimages", "importpreview", "mediafactory", "librarytestsupport", "importtestfiles" }], + ["SkiaSharp è uscito anche dal disegno", "- ridimensionamento", new[] { "brandicon", "demoimages", "importpreview", "mediafactory", "librarytestsupport", "importtestfiles" }], ["le prove dei codec con perdita hanno una tolleranza", "- **Codec e video**", new[] { "psnr", "esattamente per png" }], ["C1 comprende disegno e tolleranze", "| **C1 Codec delle immagini** |", new[] { "disegnatore 2d", "tolleranze di §14.1" }], ["C3 copre tutto H.264 e tutti i flussi", "| **C3 Decodificatore H.264** |", new[] { "tutto lo standard", "tutti i flussi di itu-t h.264.1", "nessuno saltato", "permesso di alberto", "`leggimi.md`" }], @@ -95,8 +143,10 @@ public sealed partial class SpecificationConsistencyTests ["C6 toglie Node, NSIS, Archivo e Lucide", "| **C6 Niente terzi nella CI e nell'interfaccia** |", new[] { "senza node", "al posto di nsis", "al posto di archivo", "al posto di lucide", "gitleaks e trivy" }], ["le tappe C4–C6 e D1 hanno le loro dipendenze", "Dipendenze: C1", new[] { "c3 → c4", "c5 dopo c2", "c6 indipendente", "d1 indipendente" }], ["in Docker lasciare la pagina del browser copia la sessione", "**Quando si copia**", new[] { "lasciare la pagina del browser", "risposta di alberto del 25 novembre 2026", "pagina «browser»", "vista remota della pagina collegamento", "chiudere la scheda", "per 5 secondi", "ricaricare la pagina non è lasciarla", "lasciando la pagina in docker e alla fine del permesso la copia ha le stesse garanzie" }], + ["lasciare la pagina passa da LeavePageAsync e vale «Annulla» solo dove non si copia", "**Quando si copia**", new[] { "`cancel` e `pageleft` (`iconnectionservice.leavepageasync`)", "una vista chiusa perché il browser si è fermato non conta", "dove la sessione si copia, solo il pulsante «annulla» restituisce il browser senza copiare", "senza la raccolta `richieste` non c'è una sessione salvata", "lasciare la pagina vale «annulla»", "il permesso finisce senza copia" }], ["il comando CDP della copia comprende la pagina lasciata in Docker", "| Copiare la sessione", new[] { "25 novembre 2026", "in docker lasciando la pagina del browser o chiudendone la scheda" }], - ["l'immagine Docker tiene le emoji e non Liberation", "- **Immagine.**", new[] { "`fonts-noto-color-emoji`, che resta", "`fonts-liberation` esce", "25 novembre 2026" }], + ["l'immagine Docker tiene le emoji e non Liberation", "- **Immagine.**", new[] { "`fonts-noto-color-emoji`, che resta", "`fonts-liberation` è uscito", "25 novembre 2026", "`fonts-dejavu-core`", "`libicu76`", "`libssl3t64`", "`ca-certificates`", "ffmpeg è uscito con la tappa c3", "`util-linux` è essenziale in debian" }], + ["in Docker Febe è il processo 1, senza tini", "- **Processi.**", new[] { "processo 1", "niente `tini`", "`exec` di `setpriv`", "raccoglie anche i processi rimasti orfani" }], ["un'immagine troncata non ha impronta e resta", "- **Immagini troncate o rovinate**", new[] { "«file danneggiato o incompleto»", "nessuna impronta visiva", "mai doppione probabile per impronta", "resta in libreria", "25 novembre 2026" }], ["il visualizzatore dice «File danneggiato o incompleto»", "- **File danneggiato o incompleto**", new[] { "tessera neutra", "visualizzatore", "resta in libreria", "non lo riscarica" }], ["l'importazione non fa doppioni per impronta di un'immagine troncata", "I doppioni si cercano anche dentro la sorgente stessa", new[] { "mai «doppione probabile» per impronta", "«file danneggiato o incompleto»" }], @@ -134,7 +184,7 @@ public sealed partial class SpecificationConsistencyTests } [TestMethod] - public void TheRuleOnExternalComponentsIsTheSameEverywhereAndSaysWhenEachComponentLeaves() + public void TheRuleOnExternalComponentsIsTheSameEverywhereAndSaysWithWhichStageEachComponentLeft() { var claude = RuleLine(Read("CLAUDE.md"), "12. Niente componenti esterni"); var appendix = RuleLine(Read("docs", "SPECIFICA.md")[Read("docs", "SPECIFICA.md").IndexOf("## Appendice A", StringComparison.Ordinal)..], "12. Niente componenti esterni"); @@ -144,10 +194,14 @@ public sealed partial class SpecificationConsistencyTests var rule13 = RuleLine(spec, "13. **Niente componenti esterni**"); var guide = Read("docs", "guida", "Sviluppo.md"); var guideRule = guide[guide.IndexOf("- **Niente componenti esterni**", StringComparison.Ordinal)..]; - guideRule = guideRule[..guideRule.IndexOf("\n-", StringComparison.Ordinal)]; + // The bullet ends at the next bullet or at the blank line after it, never in the sections that follow. + guideRule = guideRule.Replace("\r\n", "\n", StringComparison.Ordinal); + var bulletEnds = new[] { guideRule.IndexOf("\n-", StringComparison.Ordinal), guideRule.IndexOf("\n\n", StringComparison.Ordinal) }.Where(i => i >= 0).ToList(); + guideRule = bulletEnds.Count == 0 ? guideRule : guideRule[..bulletEnds.Min()]; var problems = new List(); foreach (var (name, raw) in new[] { ("CLAUDE.md, regola 12", claude), ("SPECIFICA §2, regola 13", rule13), ("guida/Sviluppo.md", guideRule) }) { + var isGuide = name.StartsWith("guida/", StringComparison.Ordinal); var text = GuideTests.Normalize(raw); problems.AddRange(Exceptions.Where(e => !text.Contains(GuideTests.Normalize(e), StringComparison.Ordinal)).Select(e => $"{name} non ammette per nome «{e}»")); if (text.Contains("da confermare", StringComparison.Ordinal)) @@ -160,15 +214,30 @@ public sealed partial class SpecificationConsistencyTests var last = text.LastIndexOf(component.ToLowerInvariant(), StringComparison.Ordinal); if (last < 0) { - problems.Add($"{name} non nomina {component}"); + if (!(isGuide && NotNamedInTheGuide.Contains(component, StringComparer.Ordinal))) + { + problems.Add($"{name} non nomina {component}"); + } + continue; } var next = Stage().Match(text, last); if (!next.Success || !string.Equals(next.Value, stage.ToLowerInvariant(), StringComparison.Ordinal)) { - problems.Add($"{name}: {component} esce con la tappa {stage}, il testo dice «{(next.Success ? next.Value : "nessuna tappa")}»"); + problems.Add($"{name}: {component} è uscito con la tappa {stage}, il testo dice «{(next.Success ? next.Value : "nessuna tappa")}»"); + continue; } + + // The sentence that names the component and its stage says that it left, never that it will. + var start = text.LastIndexOf(". ", last, StringComparison.Ordinal) + 1; + var sentence = text[start..(next.Index + next.Length)]; + if (!sentence.Contains("uscit", StringComparison.Ordinal)) + { + problems.Add($"{name}: la frase che nomina {component} non dice che è uscito («{sentence.Trim()}»)"); + } + + problems.AddRange(FutureLeaving.Where(f => sentence.Contains(f, StringComparison.Ordinal)).Select(f => $"{name}: {component} è già uscito, la frase dice ancora «{f}»")); } } @@ -205,7 +274,7 @@ public sealed partial class SpecificationConsistencyTests } [TestMethod] - public void EveryMentionOfFfmpegSaysThatItLeavesWithStageC3() + public void EveryMentionOfFfmpegSaysThatItLeftWithStageC3() { var problems = new List(); foreach (var file in new[] { "CLAUDE.md", "docs/docker.md", "docs/processo.md", "docs/guida/Sviluppo.md" }) @@ -221,13 +290,21 @@ public sealed partial class SpecificationConsistencyTests if (!line.Contains("C3", StringComparison.Ordinal)) { - problems.Add($"{file}:{i + 1}: ffmpeg senza la tappa C3 in cui esce"); + problems.Add($"{file}:{i + 1}: ffmpeg senza la tappa C3 con cui è uscito"); } if (line.Contains("C2–C3", StringComparison.Ordinal) || line.Contains("C2-C3", StringComparison.Ordinal)) { - problems.Add($"{file}:{i + 1}: ffmpeg esce con la tappa C3, non con C2–C3"); + problems.Add($"{file}:{i + 1}: ffmpeg è uscito con la tappa C3, non con C2–C3"); } + + var text = GuideTests.Normalize(line); + if (!text.Contains("uscit", StringComparison.Ordinal)) + { + problems.Add($"{file}:{i + 1}: ffmpeg senza dire che è uscito"); + } + + problems.AddRange(FutureLeaving.Append("fino alla tappa").Where(f => text.Contains(f, StringComparison.Ordinal)).Select(f => $"{file}:{i + 1}: ffmpeg è già uscito, la riga dice ancora «{f}»")); } } @@ -235,32 +312,35 @@ public sealed partial class SpecificationConsistencyTests } [TestMethod] - public void EveryPackageIsAllowedOrSaysInWhichStageItLeaves() + public void NoDocumentSaysThatAComponentThatLeftIsStillInUse() + { + var root = Root(); + var files = CurrentDocuments.Select(f => Path.Combine([root, .. f.Split('/')])) + .Concat(Directory.EnumerateFiles(GuideTests.GuideFolder(), "*.md")) + .ToList(); + var problems = new List(); + foreach (var file in files) + { + Assert.IsTrue(File.Exists(file), $"manca {Path.GetRelativePath(root, file)}"); + var text = GuideTests.Normalize(File.ReadAllText(file)); + problems.AddRange(StillInUse.Where(p => text.Contains(p, StringComparison.Ordinal)).Select(p => $"{Path.GetRelativePath(root, file)} dice ancora «{p}»")); + } + + Assert.IsEmpty(problems, string.Join("\n", problems)); + } + + [TestMethod] + public void EveryPackageIsAllowedByTheRule() { var lines = Read("Directory.Packages.props").Split('\n'); Assert.IsTrue(lines.Any(l => l.Contains(" + + Exe + febe-schermate + Febe.Schermate + + + + + + + + + + + + diff --git a/tools/Febe.Schermate/Program.cs b/tools/Febe.Schermate/Program.cs new file mode 100644 index 0000000..b51c906 --- /dev/null +++ b/tools/Febe.Schermate/Program.cs @@ -0,0 +1,170 @@ +using System.Globalization; + +namespace Febe.Schermate; + +/// +/// Retakes the screenshots of docs/schermate from a running demo (spec §10.7): +/// +/// dotnet run --project src/Febe.Server -- --demo --porta 8490 (in another terminal) +/// dotnet run --project tools/Febe.Schermate -- [porta] [cartella] (all of them) +/// dotnet run --project tools/Febe.Schermate -- una <indirizzo> <file.png> [larghezza] [altezza] [attesa-ms] [passo.js] +/// +/// One screenshot at a time, each in its own Chromium: the browser and the demo share the computer. +/// +internal static class Program +{ + internal const string Usage = + "Uso: febe-schermate [porta] [cartella]\n" + + " febe-schermate una [larghezza] [altezza] [attesa-ms] [passo.js]"; + + private static readonly TimeSpan PerShot = TimeSpan.FromSeconds(90); + + public static async Task Main(string[] args) + { + Request request; + try + { + request = Request.Parse(args, Directory.GetCurrentDirectory()); + } + catch (ArgumentException ex) + { + await Console.Error.WriteLineAsync(ex.Message); + await Console.Error.WriteLineAsync(Usage); + return 2; + } + + if (Screenshotter.FindChromium() is not { } chromium) + { + await Console.Error.WriteLineAsync("Chromium non trovato: indica il percorso in FEBE_CHROMIUM."); + return 2; + } + + Directory.CreateDirectory(request.Folder); + var failed = 0; + foreach (var shot in request.Shots) + { + Console.WriteLine($"== {shot.File}"); + try + { + await TakeAsync(chromium, request, shot); + } + catch (Exception ex) when (ex is OperationCanceledException or InvalidOperationException or TimeoutException + or IOException or System.Net.WebSockets.WebSocketException or ArgumentException) + { + failed++; + Console.WriteLine($"non riuscita: {ex.Message}"); + } + } + + return failed == 0 ? 0 : 1; + } + + private static async Task TakeAsync(string chromium, Request request, Shot shot) + { + using var timeout = new CancellationTokenSource(PerShot); + var step = shot.Step is null ? null : await File.ReadAllTextAsync(request.StepPath(shot.Step), timeout.Token); + await using var browser = await Screenshotter.StartAsync(chromium, shot.Width, shot.Height, Console.Out, timeout.Token); + var png = await browser.TakeAsync(request.AddressOf(shot), shot.Width, shot.Height, TimeSpan.FromMilliseconds(shot.WaitMs), step, timeout.Token); + var file = Path.Combine(request.Folder, shot.File); + await File.WriteAllBytesAsync(file, png, timeout.Token); + Console.WriteLine($"salvata {file}"); + } +} + +/// What the command line asks: the shots, where they go, and against which address. +/// The demo («http://127.0.0.1:8480»); for a single shot, its whole address. +/// Where the PNG files go. +/// The shots, in order. +/// The folder of the steps named by the list; a single shot names its step by path. +internal sealed record Request(Uri Base, string Folder, IReadOnlyList Shots, string Steps) +{ + public const int DefaultPort = 8480; + + public Uri AddressOf(Shot shot) => shot.Page.Length == 0 ? Base : new Uri(Base, shot.Page); + + public string StepPath(string step) => Path.IsPathFullyQualified(step) ? step : Path.Combine(Steps, step); + + public static Request Parse(IReadOnlyList args, string currentDirectory) + { + if (args.Count > 0 && args[0] == "una") + { + return One(args, currentDirectory); + } + + if (args.Count > 2) + { + throw new ArgumentException("Troppi argomenti."); + } + + var port = args.Count > 0 ? Port(args[0]) : DefaultPort; + var folder = args.Count > 1 + ? Path.GetFullPath(args[1], currentDirectory) + : Path.Combine(RepositoryRoot(currentDirectory) + ?? throw new ArgumentException("Fuori dal repository di Febe: indica la cartella delle schermate."), "docs", "schermate"); + return new Request(new Uri($"http://127.0.0.1:{port.ToString(CultureInfo.InvariantCulture)}"), folder, Schermate.Shots.All, StepsFolder()); + } + + private static Request One(IReadOnlyList args, string currentDirectory) + { + if (args.Count is < 3 or > 7) + { + throw new ArgumentException("«una» vuole l'indirizzo e il file, poi a scelta larghezza, altezza, attesa e passo."); + } + + if (!Uri.TryCreate(args[1], UriKind.Absolute, out var address) || !Schermate.Shots.IsOnThisComputer(address)) + { + throw new ArgumentException("Solo l'interfaccia di Febe su questo computer (127.0.0.1, localhost o [::1])."); + } + + var file = Path.GetFullPath(args[2], currentDirectory); + if (!file.EndsWith(".png", StringComparison.OrdinalIgnoreCase)) + { + throw new ArgumentException("Il file della schermata è un .png."); + } + + var shot = new Shot( + string.Empty, + Path.GetFileName(file), + args.Count > 3 ? Size(args[3], "larghezza") : 1440, + args.Count > 4 ? Size(args[4], "altezza") : 900, + args.Count > 5 ? Wait(args[5]) : 3000, + args.Count > 6 ? Path.GetFullPath(args[6], currentDirectory) : null); + return new Request(address, Path.GetDirectoryName(file)!, [shot], StepsFolder()); + } + + private static int Port(string text) => + int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var port) && port is >= 1 and <= 65535 + ? port + : throw new ArgumentException($"Porta non valida: {text}."); + + private static int Size(string text, string what) => + int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var size) && size is >= 200 and <= 8000 + ? size + : throw new ArgumentException($"{what} non valida: {text} (da 200 a 8000 punti)."); + + private static int Wait(string text) => + int.TryParse(text, NumberStyles.None, CultureInfo.InvariantCulture, out var wait) && wait <= 60_000 + ? wait + : throw new ArgumentException($"Attesa non valida: {text} (millisecondi, al massimo 60000)."); + + /// The steps next to the program (copied at build), else in the sources. + private static string StepsFolder() + { + var beside = Path.Combine(AppContext.BaseDirectory, "passi"); + return Directory.Exists(beside) ? beside : Path.Combine(RepositoryRoot(AppContext.BaseDirectory) ?? AppContext.BaseDirectory, "tools", "Febe.Schermate", "passi"); + } + + /// The nearest folder, from up, that holds Febe.slnx. + internal static string? RepositoryRoot(string start) + { + for (var folder = new DirectoryInfo(start); folder is not null; folder = folder.Parent) + { + if (File.Exists(Path.Combine(folder.FullName, "Febe.slnx"))) + { + return folder.FullName; + } + } + + return null; + } +} diff --git a/tools/Febe.Schermate/Screenshotter.cs b/tools/Febe.Schermate/Screenshotter.cs new file mode 100644 index 0000000..a12dfc7 --- /dev/null +++ b/tools/Febe.Schermate/Screenshotter.cs @@ -0,0 +1,384 @@ +using System.Collections.Concurrent; +using System.Diagnostics; +using System.Globalization; +using System.Net.WebSockets; +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; +using Febe.Browser.Hosting; + +namespace Febe.Schermate; + +/// +/// One screenshot of Febe's own interface through the DevTools protocol of a Chromium without window: exact viewport at +/// scale 1.25 (like the mockups), console errors printed, an optional step (a script evaluated in the page and awaited; +/// when it returns { hover: [x, y] } the pointer is moved there, so :hover styles show). A fresh profile every +/// time, deleted at the end. Only addresses on this computer (). +/// +internal sealed class Screenshotter : IAsyncDisposable +{ + /// The scale of the mockups. + public const double Scale = 1.25; + + private static readonly TimeSpan StartPatience = TimeSpan.FromSeconds(20); + + private readonly Process _process; + private readonly string _profile; + private readonly ClientWebSocket _socket; + private readonly ConcurrentDictionary> _pending = new(); + private readonly CancellationTokenSource _stop = new(); + private readonly Task _receiving; + private readonly TextWriter _log; + private int _id; + + private Screenshotter(Process process, string profile, ClientWebSocket socket, TextWriter log) + { + _process = process; + _profile = profile; + _socket = socket; + _log = log; + _receiving = Task.Run(ReceiveAsync); + } + + /// Chromium: FEBE_CHROMIUM, then PATH and the usual places (Debian's «chromium», Edge on Windows). + public static string? FindChromium() => ChromiumCommandLine.FindExecutable(); + + /// The command line of the screenshot browser: no window, a private profile, the debug port only on 127.0.0.1. + internal static List Arguments(string profile, int width, int height, bool noSandbox) + { + // Port 0: Chromium picks a free port and writes it in DevToolsActivePort, so no other process can take it. + List arguments = + [ + "--headless", "--disable-gpu", "--hide-scrollbars", "--no-first-run", "--no-default-browser-check", + "--disable-extensions", "--disable-background-networking", "--disable-component-update", "--no-proxy-server", + "--mute-audio", string.Create(CultureInfo.InvariantCulture, $"--window-size={width},{height}"), + $"--user-data-dir={profile}", "--remote-debugging-port=0", "--remote-debugging-address=127.0.0.1", + ]; + if (noSandbox) + { + arguments.Add("--no-sandbox"); + } + + arguments.Add("about:blank"); + return arguments; + } + + public static async Task StartAsync(string chromium, int width, int height, TextWriter log, CancellationToken ct) + { + var profile = Path.Combine(Path.GetTempPath(), "febe-schermata-" + Guid.NewGuid().ToString("N")); + var info = new ProcessStartInfo(chromium) { UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; + foreach (var argument in Arguments(profile, width, height, OperatingSystem.IsLinux() && Environment.UserName == "root")) + { + info.ArgumentList.Add(argument); + } + + var process = Process.Start(info) ?? throw new InvalidOperationException("Chromium non parte."); + process.OutputDataReceived += (_, _) => { }; + process.ErrorDataReceived += (_, _) => { }; + process.BeginOutputReadLine(); + process.BeginErrorReadLine(); + try + { + using var http = new HttpClient(new HttpClientHandler { UseProxy = false }) { Timeout = TimeSpan.FromSeconds(5) }; + var watch = Stopwatch.StartNew(); + string? debugger = null; + while (debugger is null) + { + if (process.HasExited) + { + throw new InvalidOperationException($"Chromium si è chiuso all'avvio (codice {process.ExitCode})."); + } + + if (watch.Elapsed > StartPatience) + { + throw new TimeoutException("Chromium non risponde sulla porta di debug."); + } + + if (ActivePort(profile) is > 0 and var port) + { + try + { + debugger = PageDebugger(await http.GetStringAsync(new Uri($"http://127.0.0.1:{port}/json/list"), ct)); + } + catch (Exception ex) when (ex is HttpRequestException or TaskCanceledException or JsonException) + { + // Chromium is still starting. + } + } + + if (debugger is null) + { + await Task.Delay(100, ct); + } + } + + var socket = new ClientWebSocket(); + socket.Options.Proxy = null; + await socket.ConnectAsync(new Uri(debugger), ct); + return new Screenshotter(process, profile, socket, log); + } + catch + { + Kill(process); + TryDelete(profile); + throw; + } + } + + /// Navigates, waits, runs the step, and returns the PNG. + public async Task TakeAsync(Uri address, int width, int height, TimeSpan wait, string? stepCode, CancellationToken ct) + { + if (!Shots.IsOnThisComputer(address)) + { + throw new ArgumentException("Solo l'interfaccia di Febe su questo computer (127.0.0.1, localhost o [::1]).", nameof(address)); + } + + await SendAsync("Runtime.enable", null, ct); + await SendAsync("Log.enable", null, ct); + await SendAsync("Page.enable", null, ct); + await SendAsync("Emulation.setDeviceMetricsOverride", new JsonObject + { + ["width"] = width, ["height"] = height, ["deviceScaleFactor"] = Scale, ["mobile"] = false, + }, ct); + await SendAsync("Page.navigate", new JsonObject { ["url"] = address.AbsoluteUri }, ct); + await Task.Delay(wait, ct); + if (stepCode is not null) + { + var evaluated = await SendAsync("Runtime.evaluate", new JsonObject + { + ["expression"] = $"(async () => {{ {stepCode}\n}})()", ["awaitPromise"] = true, ["returnByValue"] = true, + }, ct); + if (evaluated.TryGetProperty("exceptionDetails", out var failure)) + { + _log.WriteLine($"errore nel passo: {Description(failure)}"); + } + else if (evaluated.TryGetProperty("result", out var result) && result.TryGetProperty("value", out var value)) + { + _log.WriteLine($"passo: {value.GetRawText()}"); + if (HoverPoint(value) is { } point) + { + await SendAsync("Input.dispatchMouseEvent", new JsonObject + { + ["type"] = "mouseMoved", ["x"] = point.X, ["y"] = point.Y, + }, ct); + } + } + + await Task.Delay(800, ct); + } + + var shot = await SendAsync("Page.captureScreenshot", new JsonObject { ["format"] = "png" }, ct); + return Convert.FromBase64String(shot.GetProperty("data").GetString() ?? string.Empty); + } + + /// The point of { hover: [x, y] }, or null. + internal static (double X, double Y)? HoverPoint(JsonElement value) => + value.ValueKind == JsonValueKind.Object + && value.TryGetProperty("hover", out var hover) + && hover.ValueKind == JsonValueKind.Array + && hover.GetArrayLength() == 2 + && hover[0].ValueKind == JsonValueKind.Number + && hover[1].ValueKind == JsonValueKind.Number + ? (hover[0].GetDouble(), hover[1].GetDouble()) + : null; + + /// The debugger address of the first page target of /json/list, or null. + internal static string? PageDebugger(string list) + { + using var document = JsonDocument.Parse(list); + foreach (var target in document.RootElement.EnumerateArray()) + { + if (target.TryGetProperty("type", out var type) && type.GetString() == "page" + && target.TryGetProperty("webSocketDebuggerUrl", out var url) && url.GetString() is { } address + && Uri.TryCreate(address, UriKind.Absolute, out var parsed) && parsed.Host == "127.0.0.1") + { + return address; + } + } + + return null; + } + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync(); + try + { + await _receiving; + } + catch (OperationCanceledException) + { + // Stopped on purpose. + } + + _socket.Dispose(); + Kill(_process); + _process.Dispose(); + _stop.Dispose(); + TryDelete(_profile); + } + + private async Task SendAsync(string method, JsonObject? parameters, CancellationToken ct) + { + var id = Interlocked.Increment(ref _id); + var answer = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + _pending[id] = answer; + var message = new JsonObject { ["id"] = id, ["method"] = method, ["params"] = parameters ?? new JsonObject() }; + await _socket.SendAsync(Encoding.UTF8.GetBytes(message.ToJsonString()), WebSocketMessageType.Text, endOfMessage: true, ct); + using var registration = ct.Register(() => answer.TrySetCanceled(ct)); + return await answer.Task; + } + + private async Task ReceiveAsync() + { + var buffer = new byte[64 * 1024]; + using var message = new MemoryStream(); + while (!_stop.IsCancellationRequested && _socket.State == WebSocketState.Open) + { + ValueWebSocketReceiveResult result; + try + { + result = await _socket.ReceiveAsync(buffer.AsMemory(), _stop.Token); + } + catch (WebSocketException) + { + break; + } + + if (result.MessageType == WebSocketMessageType.Close) + { + break; + } + + message.Write(buffer, 0, result.Count); + if (!result.EndOfMessage) + { + continue; + } + + Dispatch(message.GetBuffer().AsSpan(0, (int)message.Length)); + message.SetLength(0); + } + + foreach (var pending in _pending.Values) + { + pending.TrySetException(new InvalidOperationException("Chromium ha chiuso il collegamento.")); + } + } + + private void Dispatch(ReadOnlySpan text) + { + var reader = new Utf8JsonReader(text); + using var document = JsonDocument.ParseValue(ref reader); + var root = document.RootElement; + if (root.TryGetProperty("id", out var id) && _pending.TryRemove(id.GetInt32(), out var answer)) + { + if (root.TryGetProperty("error", out var error)) + { + answer.TrySetException(new InvalidOperationException($"DevTools: {error.GetRawText()}")); + } + else + { + answer.TrySetResult(root.GetProperty("result").Clone()); + } + + return; + } + + if (!root.TryGetProperty("method", out var method) || !root.TryGetProperty("params", out var parameters)) + { + return; + } + + // Only Febe's own pages: what they print in their console is Febe's own interface talking. + switch (method.GetString()) + { + case "Runtime.consoleAPICalled" when parameters.GetProperty("type").GetString() is "error" or "warning": + var words = new List(); + foreach (var argument in parameters.GetProperty("args").EnumerateArray()) + { + words.Add(argument.TryGetProperty("value", out var value) ? value.ToString() : Description(argument)); + } + + _log.WriteLine($"console.{parameters.GetProperty("type").GetString()}: {string.Join(' ', words)}"); + break; + case "Runtime.exceptionThrown": + _log.WriteLine($"eccezione: {Description(parameters.GetProperty("exceptionDetails"))}"); + break; + case "Log.entryAdded" when parameters.GetProperty("entry").GetProperty("level").GetString() == "error": + var entry = parameters.GetProperty("entry"); + _log.WriteLine($"errore: {entry.GetProperty("text").GetString()} {(entry.TryGetProperty("url", out var url) ? url.GetString() : string.Empty)}"); + break; + } + } + + private static string Description(JsonElement element) + { + if (element.TryGetProperty("exception", out var exception) && exception.TryGetProperty("description", out var described)) + { + return described.GetString() ?? string.Empty; + } + + if (element.TryGetProperty("description", out var description)) + { + return description.GetString() ?? string.Empty; + } + + return element.TryGetProperty("text", out var text) ? text.GetString() ?? string.Empty : string.Empty; + } + + /// The port Chromium wrote in DevToolsActivePort (first line), or 0 while it has not. + private static int ActivePort(string profile) + { + try + { + using var reader = new StreamReader(Path.Combine(profile, "DevToolsActivePort")); + return int.TryParse(reader.ReadLine(), NumberStyles.None, CultureInfo.InvariantCulture, out var port) ? port : 0; + } + catch (IOException) + { + return 0; + } + catch (UnauthorizedAccessException) + { + return 0; + } + } + + private static void Kill(Process process) + { + try + { + if (!process.HasExited) + { + process.Kill(entireProcessTree: true); + process.WaitForExit(5000); + } + } + catch (InvalidOperationException) + { + // Already gone. + } + } + + private static void TryDelete(string profile) + { + // Chromium may hold its files for a moment after it exits. + for (var attempt = 0; attempt < 10; attempt++) + { + try + { + if (Directory.Exists(profile)) + { + Directory.Delete(profile, recursive: true); + } + + return; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + Thread.Sleep(200); + } + } + } +} diff --git a/tools/Febe.Schermate/Shots.cs b/tools/Febe.Schermate/Shots.cs new file mode 100644 index 0000000..6a7e919 --- /dev/null +++ b/tools/Febe.Schermate/Shots.cs @@ -0,0 +1,62 @@ +namespace Febe.Schermate; + +/// One screenshot: the page (path and query on the demo), the file, the viewport, the wait and an optional step. +internal sealed record Shot(string Page, string File, int Width = 1440, int Height = 900, int WaitMs = 3000, string? Step = null); + +/// The screenshots of docs/schermate (spec §10.7), in the order they are taken. +internal static class Shots +{ + /// + /// One at a time: Chromium and the demo share the computer. The stopped scenes come first where it matters: + /// «Riprendi» stays off until the browser has been used (spec §7.6). + /// + public static IReadOnlyList All { get; } = + [ + new("/libreria?tema=chiaro", "01-libreria.png", Step: "puntatore.js"), + new("/libreria?tema=chiaro", "02-visualizzatore.png", Step: "visualizzatore.js"), + new("/account?tema=chiaro", "03-account.png"), + new("/account?tema=chiaro", "03-account-telefono.png", 390, 844), + new("/account?dialogo=aggiungi&tema=chiaro", "04-aggiungi-account.png", Step: "aggiungi.js"), + new("/account/3/impostazioni?tema=chiaro", "05-account-impostazioni.png"), + new("/libreria?scena=fermo&tema=scuro", "11-libreria-fermo-tema-scuro.png"), + new("/account/2?tema=scuro&tipo=storie", "12-account-storie-tema-scuro.png"), + new("/libreria?tema=chiaro", "14-finestra-stretta.png", 860, 900), + new("/libreria?tema=chiaro", "14-telefono.png", 390, 844), + new("/account/2/cronologia?tema=chiaro", "account-cronologia.png"), + + // Part 2: Attività, Impostazioni, Collegamento, Importa, doppioni, primo avvio, errore di configurazione. + new("/attivita?scena=fermo&tema=scuro", "11-attivita-fermo-tema-scuro.png"), + new("/attivita?scena=sessione&tema=chiaro", "06-attivita.png"), + new("/attivita?scena=sessione&tema=chiaro", "06-attivita-tutti-i-tetti.png", Step: "tutti-tetti.js"), + new("/attivita?scena=sessione&tema=chiaro", "14-attivita-finestra-stretta.png", 860, 900), + new("/attivita?scena=sessione&tema=chiaro", "14-attivita-telefono.png", 390, 844), + new("/attivita?scena=normale&tema=chiaro", "14-attivita-finestra-stretta-normale.png", 860, 900), + new("/attivita?scena=normale&tema=chiaro", "14-attivita-telefono-normale.png", 390, 844), + new("/impostazioni/limiti?tema=chiaro", "07-limiti-e-comportamento.png", 1440, 1470), + new("/impostazioni/limiti?tema=chiaro", "07-limiti-su-misura.png", Step: "su-misura.js"), + new("/impostazioni/generali?tema=chiaro", "08-impostazioni-generali.png"), + new("/impostazioni/notifiche?tema=chiaro", "impostazioni-notifiche.png"), + new("/impostazioni/dati?tema=chiaro", "impostazioni-dati.png"), + new("/impostazioni/informazioni?tema=chiaro", "impostazioni-informazioni.png"), + new("/importa?passo=1&tema=chiaro&veste=docker", "09-importa-sorgente.png"), + new("/importa?passo=3&tema=chiaro", "09-importa-revisione.png", Step: "doppione-scelto.js"), + new("/importa?passo=3&tema=chiaro", "09-importa-telefono.png", 390, 844), + new("/impostazioni/collegamento?scena=scollegato&tema=chiaro&veste=docker", "10-collegamento-instagram.png"), + new("/impostazioni/collegamento?scena=scollegato&tema=chiaro&veste=windows", "10-collegamento-windows.png"), + new("/impostazioni/collegamento?scena=normale&tema=chiaro&veste=docker", "10-collegamento-collegato.png"), + new("/browser?scena=fermo&tema=chiaro&veste=docker", "10-browser.png"), + new("/doppioni?tema=chiaro", "doppioni-download.png"), + new("/libreria?scena=scollegato&tema=chiaro", "primo-avvio.png", Step: "benvenuto.js"), + new("/libreria?scena=errore&tema=chiaro", "errore-configurazione.png"), + ]; + + /// + /// Only Febe's own interface on this computer: http or https to 127.0.0.1, localhost or [::1]. Instagram is never + /// opened this way (spec §2, rule 4). + /// + public static bool IsOnThisComputer(Uri address) => + address.IsAbsoluteUri + && (address.Scheme == Uri.UriSchemeHttp || address.Scheme == Uri.UriSchemeHttps) + && string.IsNullOrEmpty(address.UserInfo) + && address.Host is "127.0.0.1" or "localhost" or "[::1]"; +} diff --git a/tools/schermate/passi/aggiungi.js b/tools/Febe.Schermate/passi/aggiungi.js similarity index 100% rename from tools/schermate/passi/aggiungi.js rename to tools/Febe.Schermate/passi/aggiungi.js diff --git a/tools/schermate/passi/benvenuto.js b/tools/Febe.Schermate/passi/benvenuto.js similarity index 100% rename from tools/schermate/passi/benvenuto.js rename to tools/Febe.Schermate/passi/benvenuto.js diff --git a/tools/schermate/passi/doppione-scelto.js b/tools/Febe.Schermate/passi/doppione-scelto.js similarity index 100% rename from tools/schermate/passi/doppione-scelto.js rename to tools/Febe.Schermate/passi/doppione-scelto.js diff --git a/tools/schermate/passi/misure.js b/tools/Febe.Schermate/passi/misure.js similarity index 100% rename from tools/schermate/passi/misure.js rename to tools/Febe.Schermate/passi/misure.js diff --git a/tools/schermate/passi/puntatore.js b/tools/Febe.Schermate/passi/puntatore.js similarity index 100% rename from tools/schermate/passi/puntatore.js rename to tools/Febe.Schermate/passi/puntatore.js diff --git a/tools/schermate/passi/su-misura.js b/tools/Febe.Schermate/passi/su-misura.js similarity index 100% rename from tools/schermate/passi/su-misura.js rename to tools/Febe.Schermate/passi/su-misura.js diff --git a/tools/schermate/passi/tutti-tetti.js b/tools/Febe.Schermate/passi/tutti-tetti.js similarity index 100% rename from tools/schermate/passi/tutti-tetti.js rename to tools/Febe.Schermate/passi/tutti-tetti.js diff --git a/tools/schermate/passi/visualizzatore.js b/tools/Febe.Schermate/passi/visualizzatore.js similarity index 100% rename from tools/schermate/passi/visualizzatore.js rename to tools/Febe.Schermate/passi/visualizzatore.js diff --git a/tools/schermate/schermata.mjs b/tools/schermate/schermata.mjs deleted file mode 100644 index 039e964..0000000 --- a/tools/schermate/schermata.mjs +++ /dev/null @@ -1,119 +0,0 @@ -// node tools/schermate/schermata.mjs [larghezza] [altezza] [attesa-ms] [passo.js] -// -// Screenshot of Febe's own interface (spec §10.7) through the DevTools protocol of a Chromium without window: -// exact viewport at scale 1.25 (like the mockups), console errors printed, an optional step (a JS file evaluated in -// the page and awaited; when it returns { hover: [x, y] } the pointer is moved there, so :hover styles show). -// -// Only for Febe's own interface: the address must be on this computer (127.0.0.1 or localhost). Instagram is never -// opened this way (spec §2, rule 4). Needs Node 22 or later (global WebSocket) and a Chromium: set FEBE_CHROMIUM, or -// the Playwright build under /opt/pw-browsers is used. -import { spawn } from 'node:child_process'; -import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; - -const [address, out, width = '1440', height = '900', wait = '3000', step] = process.argv.slice(2); -if (!address || !out) { - console.error('Uso: node tools/schermate/schermata.mjs [larghezza] [altezza] [attesa-ms] [passo.js]'); - process.exit(2); -} - -const target = new URL(address); -if (!['127.0.0.1', 'localhost', '[::1]'].includes(target.hostname)) { - console.error('Solo l\'interfaccia di Febe su questo computer (127.0.0.1 o localhost).'); - process.exit(2); -} - -function findChromium() { - if (process.env.FEBE_CHROMIUM) return process.env.FEBE_CHROMIUM; - const root = '/opt/pw-browsers'; - if (existsSync(root)) { - for (const name of readdirSync(root).filter((n) => /^chromium-\d+$/.test(n)).sort().reverse()) { - const candidate = join(root, name, 'chrome-linux', 'chrome'); - if (existsSync(candidate)) return candidate; - } - } - console.error('Chromium non trovato: indica il percorso in FEBE_CHROMIUM.'); - process.exit(2); -} - -const profile = mkdtempSync(join(tmpdir(), 'febe-schermata-')); -const port = 9300 + Math.floor(Math.random() * 500); -const chrome = spawn(findChromium(), [ - '--headless', '--no-sandbox', '--disable-gpu', '--hide-scrollbars', '--disable-background-networking', - '--disable-component-update', '--no-first-run', '--no-default-browser-check', '--disable-extensions', - `--user-data-dir=${profile}`, `--remote-debugging-port=${port}`, '--remote-debugging-address=127.0.0.1', 'about:blank', -], { stdio: 'ignore' }); -const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); - -function finish(code) { - chrome.kill('SIGKILL'); - setTimeout(() => { - try { - rmSync(profile, { recursive: true, force: true }); - } catch { - // the profile stays in the temporary folder - } - process.exit(code); - }, 300); -} - -let ws; -for (let i = 0; i < 50 && !ws; i++) { - try { - const list = await (await fetch(`http://127.0.0.1:${port}/json/list`)).json(); - const page = list.find((t) => t.type === 'page'); - if (page) ws = new WebSocket(page.webSocketDebuggerUrl); - } catch { - // Chromium is still starting - } - if (!ws) await sleep(200); -} -if (!ws) { - console.error('Chromium non risponde.'); - finish(1); -} else { - await new Promise((r) => ws.addEventListener('open', r)); - let id = 0; - const pending = new Map(); - ws.addEventListener('message', (e) => { - const msg = JSON.parse(e.data); - if (msg.id && pending.has(msg.id)) { - pending.get(msg.id)(msg); - pending.delete(msg.id); - } else if (msg.method === 'Runtime.consoleAPICalled' && ['error', 'warning'].includes(msg.params.type)) { - console.log(`console.${msg.params.type}:`, msg.params.args.map((a) => a.value ?? a.description).join(' ')); - } else if (msg.method === 'Runtime.exceptionThrown') { - console.log('eccezione:', msg.params.exceptionDetails.exception?.description || msg.params.exceptionDetails.text); - } else if (msg.method === 'Log.entryAdded' && msg.params.entry.level === 'error') { - console.log('errore:', msg.params.entry.text, msg.params.entry.url || ''); - } - }); - const send = (method, params = {}) => new Promise((resolve) => { - const n = ++id; - pending.set(n, resolve); - ws.send(JSON.stringify({ id: n, method, params })); - }); - await send('Runtime.enable'); - await send('Log.enable'); - await send('Page.enable'); - await send('Emulation.setDeviceMetricsOverride', { width: Number(width), height: Number(height), deviceScaleFactor: 1.25, mobile: false }); - await send('Page.navigate', { url: target.href }); - await sleep(Number(wait)); - if (step) { - const code = readFileSync(step, 'utf8'); - const r = await send('Runtime.evaluate', { expression: `(async () => { ${code} })()`, awaitPromise: true, returnByValue: true }); - const value = r.result?.result?.value; - if (r.result?.exceptionDetails) console.log('errore nel passo:', r.result.exceptionDetails.exception?.description); - else if (value !== undefined) console.log('passo:', JSON.stringify(value)); - if (value && typeof value === 'object' && Array.isArray(value.hover)) { - await send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: value.hover[0], y: value.hover[1] }); - } - await sleep(800); - } - const shot = await send('Page.captureScreenshot', { format: 'png' }); - writeFileSync(out, Buffer.from(shot.result.data, 'base64')); - console.log('salvata', out); - ws.close(); - finish(0); -} diff --git a/tools/schermate/tutte.sh b/tools/schermate/tutte.sh deleted file mode 100644 index 89f8ddf..0000000 --- a/tools/schermate/tutte.sh +++ /dev/null @@ -1,48 +0,0 @@ -#!/bin/bash -# Retakes the screenshots of docs/schermate from a running demo (spec §10.7): -# dotnet run --project src/Febe.Server -- --demo --porta 8490 (in another terminal) -# bash tools/schermate/tutte.sh [porta] [cartella] -# One screenshot at a time: Chromium and the demo share the computer. -set -u -here="$(cd "$(dirname "$0")" && pwd)" -port="${1:-8480}" -out="${2:-$here/../../docs/schermate}" -b="http://127.0.0.1:$port" -mkdir -p "$out" -shot() { echo "== $2"; timeout 90 node "$here/schermata.mjs" "$1" "$out/$2" "${3:-1440}" "${4:-900}" "${5:-3000}" ${6:-}; } -shot "$b/libreria?tema=chiaro" 01-libreria.png 1440 900 3000 "$here/passi/puntatore.js" -shot "$b/libreria?tema=chiaro" 02-visualizzatore.png 1440 900 3000 "$here/passi/visualizzatore.js" -shot "$b/account?tema=chiaro" 03-account.png -shot "$b/account?tema=chiaro" 03-account-telefono.png 390 844 -shot "$b/account?dialogo=aggiungi&tema=chiaro" 04-aggiungi-account.png 1440 900 3000 "$here/passi/aggiungi.js" -shot "$b/account/3/impostazioni?tema=chiaro" 05-account-impostazioni.png -shot "$b/libreria?scena=fermo&tema=scuro" 11-libreria-fermo-tema-scuro.png -shot "$b/account/2?tema=scuro&tipo=storie" 12-account-storie-tema-scuro.png -shot "$b/libreria?tema=chiaro" 14-finestra-stretta.png 860 900 -shot "$b/libreria?tema=chiaro" 14-telefono.png 390 844 -shot "$b/account/2/cronologia?tema=chiaro" account-cronologia.png -# Part 2: Attività, Impostazioni, Collegamento, Importa, doppioni, primo avvio, errore di configurazione. -# The stopped scene first: «Riprendi» stays off until the browser has been used (spec §7.6). -shot "$b/attivita?scena=fermo&tema=scuro" 11-attivita-fermo-tema-scuro.png -shot "$b/attivita?scena=sessione&tema=chiaro" 06-attivita.png -shot "$b/attivita?scena=sessione&tema=chiaro" 06-attivita-tutti-i-tetti.png 1440 900 3000 "$here/passi/tutti-tetti.js" -shot "$b/attivita?scena=sessione&tema=chiaro" 14-attivita-finestra-stretta.png 860 900 -shot "$b/attivita?scena=sessione&tema=chiaro" 14-attivita-telefono.png 390 844 -shot "$b/attivita?scena=normale&tema=chiaro" 14-attivita-finestra-stretta-normale.png 860 900 -shot "$b/attivita?scena=normale&tema=chiaro" 14-attivita-telefono-normale.png 390 844 -shot "$b/impostazioni/limiti?tema=chiaro" 07-limiti-e-comportamento.png 1440 1470 -shot "$b/impostazioni/limiti?tema=chiaro" 07-limiti-su-misura.png 1440 900 3000 "$here/passi/su-misura.js" -shot "$b/impostazioni/generali?tema=chiaro" 08-impostazioni-generali.png -shot "$b/impostazioni/notifiche?tema=chiaro" impostazioni-notifiche.png -shot "$b/impostazioni/dati?tema=chiaro" impostazioni-dati.png -shot "$b/impostazioni/informazioni?tema=chiaro" impostazioni-informazioni.png -shot "$b/importa?passo=1&tema=chiaro&veste=docker" 09-importa-sorgente.png -shot "$b/importa?passo=3&tema=chiaro" 09-importa-revisione.png 1440 900 3000 "$here/passi/doppione-scelto.js" -shot "$b/importa?passo=3&tema=chiaro" 09-importa-telefono.png 390 844 -shot "$b/impostazioni/collegamento?scena=scollegato&tema=chiaro&veste=docker" 10-collegamento-instagram.png -shot "$b/impostazioni/collegamento?scena=scollegato&tema=chiaro&veste=windows" 10-collegamento-windows.png -shot "$b/impostazioni/collegamento?scena=normale&tema=chiaro&veste=docker" 10-collegamento-collegato.png -shot "$b/browser?scena=fermo&tema=chiaro&veste=docker" 10-browser.png -shot "$b/doppioni?tema=chiaro" doppioni-download.png -shot "$b/libreria?scena=scollegato&tema=chiaro" primo-avvio.png 1440 900 3000 "$here/passi/benvenuto.js" -shot "$b/libreria?scena=errore&tema=chiaro" errore-configurazione.png