diff --git a/.gitea/scripts/ambiente-prove.sh b/.gitea/scripts/ambiente-prove.sh index 81e2a7d..0338210 100755 --- a/.gitea/scripts/ambiente-prove.sh +++ b/.gitea/scripts/ambiente-prove.sh @@ -19,7 +19,7 @@ $sudo apt-get install -y -qq --no-install-recommends \ xvfb \ ffmpeg \ locales tzdata libicu76 libssl3t64 zlib1g libstdc++6 ca-certificates curl git \ - fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \ + 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 diff --git a/.gitea/scripts/costruisci-immagine.sh b/.gitea/scripts/costruisci-immagine.sh index d60ad53..4c71e0e 100755 --- a/.gitea/scripts/costruisci-immagine.sh +++ b/.gitea/scripts/costruisci-immagine.sh @@ -9,8 +9,9 @@ # 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 @@ -60,11 +61,43 @@ 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' "$@" ;; *) 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.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/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/workflows/rilascio.yml b/.gitea/workflows/rilascio.yml index afc680c..12c25e3 100644 --- a/.gitea/workflows/rilascio.yml +++ b/.gitea/workflows/rilascio.yml @@ -1,6 +1,7 @@ # 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; +# e tutte le prove passano, nello stesso contenitore Debian 13 della verifica (Chromium, Xvfb, ffmpeg 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 @@ -35,6 +36,12 @@ 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" @@ -44,9 +51,23 @@ jobs: prove: runs-on: ubuntu-latest timeout-minutes: 60 + # Lo stesso ambiente delle prove della verifica: Debian 13 con Chromium, Xvfb e ffmpeg 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: + - 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 }} @@ -73,6 +94,9 @@ jobs: 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; } + - name: Chromium, Xvfb, ffmpeg e lingua italiana + run: bash .gitea/scripts/ambiente-prove.sh + - name: SDK .NET 10 run: bash .gitea/scripts/dotnet.sh 10.0 @@ -84,6 +108,11 @@ jobs: dotnet test tests/Febe.Tests -c Release --no-build --nologo --logger "trx;LogFileName=prove.trx" --results-directory out/prove + # 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() env: @@ -231,17 +260,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." ;; @@ -251,17 +275,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 @@ -329,16 +347,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" @@ -353,7 +381,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 69d8cd2..1176569 100644 --- a/.gitea/workflows/verifica.yml +++ b/.gitea/workflows/verifica.yml @@ -356,18 +356,12 @@ 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 gettone del lavoro solo nell'ambiente di git, come per i sorgenti. Il passo gira con «bash -e -o @@ -388,11 +382,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 2084d06..f3ba7d7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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, Xvfb e ffmpeg veri in Debian, nessuna saltata, anche con il seme dell'esecuzione (`FEBE_SEME_PROVA`); installatore (nostro, `src/Febe.Installer`, solo .NET SDK) 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, Xvfb e ffmpeg 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 e587a79..bdb4442 100644 --- a/Febe.slnx +++ b/Febe.slnx @@ -16,6 +16,7 @@ + diff --git a/docker/Dockerfile b/docker/Dockerfile index de60e9a..b20ba91 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, ffmpeg, ICU, caratteri -# (anche emoji), certificati, fusi orari, lingua italiana; Febe come processo 1; setpriv per PUID/PGID. +# runtime Debian stabile ridotta (trixie-slim) con Chromium della distribuzione, Xvfb, ffmpeg, ICU, un +# carattere, 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. @@ -75,11 +75,11 @@ LABEL org.opencontainers.image.title="Febe" \ org.opencontainers.image.url="https://gitea.encke-hake.ts.net/Alby96/Febe" # Chromium della distribuzione con le sue lingue, il display virtuale, ffmpeg (miniature dei video importati), ICU e -# le librerie del runtime .NET autosufficiente, caratteri di sistema con le emoji, certificati, fusi orari, la lingua +# le librerie del runtime .NET autosufficiente, il carattere che fontconfig chiede, 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 +# suoi caratteri: quello qui sotto serve 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 @@ -93,11 +93,10 @@ LABEL org.opencontainers.image.title="Febe" \ # 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: -# senza un carattere Chromium non disegna il testo; -# fonts-liberation Arial, Helvetica e Times con le stesse misure: le pagine che li chiedono restano -# impaginate come altrove (il pacchetto di Google Chrome per Debian lo pretende); -# fonts-noto-color-emoji le emoji di nomi e didascalie nella vista remota, invece di quadratini vuoti; +# 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. +# È l'unico: niente caratteri in più per l'aspetto (Liberation, emoji), che Chromium non +# chiede; # 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 @@ -116,7 +115,7 @@ RUN apt-get update \ xvfb \ ffmpeg \ libicu76 libssl3t64 libstdc++6 libgcc-s1 zlib1g \ - fonts-noto-color-emoji fonts-liberation fonts-dejavu-core \ + fonts-dejavu-core \ ca-certificates tzdata locales \ && sed -i 's/^# *\(it_IT.UTF-8 UTF-8\)/\1/' /etc/locale.gen \ && locale-gen \ diff --git a/docs/decisioni.md b/docs/decisioni.md index eab4631..61863d5 100644 --- a/docs/decisioni.md +++ b/docs/decisioni.md @@ -433,3 +433,9 @@ Ogni scelta tecnica presa strada facendo, con data e motivo (specifica §15). | 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 | diff --git a/docs/docker.md b/docs/docker.md index 7a15411..6c62bb1 100644 --- a/docs/docker.md +++ b/docs/docker.md @@ -11,8 +11,8 @@ 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`, `ffmpeg` (miniature dei video importati), ICU, caratteri di sistema con le emoji - (`fonts-noto-color-emoji`, `fonts-liberation`, `fonts-dejavu-core`), certificati, `tzdata`, la lingua `it_IT.UTF-8` generata. +- `chromium` e `chromium-l10n`, `xvfb`, `ffmpeg` (miniature dei video importati), ICU, un solo carattere di sistema + (`fonts-dejavu-core`), certificati, `tzdata`, la lingua `it_IT.UTF-8` generata. - 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 @@ -41,15 +41,16 @@ pacchetto entra senza motivo o fuori da questo elenco. | `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: senza un carattere Chromium non scrive nulla | -| `fonts-liberation` | Arial, Helvetica e Times con le stesse misure: le pagine che li chiedono restano impaginate come altrove | -| `fonts-noto-color-emoji` | le emoji di nomi e didascalie nella vista remota, invece di quadratini vuoti | +| `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 | | `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 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. +Il carattere serve 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 18 novembre 2026 non ci sono più +`fonts-liberation` e `fonts-noto-color-emoji`: Chromium non li chiede (il primo è solo una raccomandazione, il secondo +nemmeno quella), servivano solo all'aspetto. Nella vista remota le pagine che chiedono Arial o Helvetica si vedono con +DejaVu, con misure un po' diverse, e le emoji a colori possono comparire come quadratini. 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 diff --git a/docs/guida/Sviluppo.md b/docs/guida/Sviluppo.md index 70285dd..1d34b99 100644 --- a/docs/guida/Sviluppo.md +++ b/docs/guida/Sviluppo.md @@ -25,7 +25,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#, senza Node), 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/`) | @@ -174,9 +174,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 diff --git a/docs/processo.md b/docs/processo.md index fdaf6b7..18f5e2b 100644 --- a/docs/processo.md +++ b/docs/processo.md @@ -96,6 +96,7 @@ Alberto, nessun componente esterno). Al posto delle azioni: | `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 @@ -139,7 +140,10 @@ FEBE_SEME_PROVA= dotnet test tests/Febe.Tests --filter "TestCategory=SitoD 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. @@ -284,7 +288,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, Xvfb e ffmpeg 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 diff --git a/docs/schermate/differenze.md b/docs/schermate/differenze.md index 48efb22..125a038 100644 --- a/docs/schermate/differenze.md +++ b/docs/schermate/differenze.md @@ -152,4 +152,4 @@ disposizione, misure e colori, non più per la forma delle lettere e dei segni: - **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 (`bash tools/schermate/tutte.sh`). +- Le schermate non sono state rifatte: si rifanno alla prossima tornata (`dotnet run --project tools/Febe.Schermate`). diff --git a/src/Febe.Installer/CommandLine.cs b/src/Febe.Installer/CommandLine.cs index 7ab3073..847105f 100644 --- a/src/Febe.Installer/CommandLine.cs +++ b/src/Febe.Installer/CommandLine.cs @@ -109,7 +109,15 @@ internal sealed record CommandLine } else if (argument.StartsWith("/PROVA=", StringComparison.OrdinalIgnoreCase)) { - line = line with { TestRoot = Folder(argument[7..], "/PROVA=") }; + // 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)) { diff --git a/src/Febe.Installer/Program.cs b/src/Febe.Installer/Program.cs index dedfc5f..eb72f2a 100644 --- a/src/Febe.Installer/Program.cs +++ b/src/Febe.Installer/Program.cs @@ -41,7 +41,17 @@ internal static class Program private static int RunOnWindows(CommandLine line) { var self = Environment.ProcessPath; - var locations = line.TestRoot is { } root ? Locations.ForTest(root) : Locations.ForUser(); + 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 }) diff --git a/src/Febe.Installer/SetupActions.cs b/src/Febe.Installer/SetupActions.cs index 2436d9c..8018905 100644 --- a/src/Febe.Installer/SetupActions.cs +++ b/src/Febe.Installer/SetupActions.cs @@ -22,8 +22,11 @@ internal sealed class SetupActions(ISystemAccess system, Locations locations) public Locations Locations => locations; /// - /// True when Febe.exe in is running: a running program cannot be opened for - /// writing, so it could be neither replaced nor deleted. + /// 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) { @@ -38,11 +41,11 @@ internal sealed class SetupActions(ISystemAccess system, Locations locations) using var stream = new FileStream(executable, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite | FileShare.Delete); return false; } - catch (IOException) - { - return true; - } catch (UnauthorizedAccessException) + { + return false; + } + catch (IOException) { return true; } @@ -51,6 +54,19 @@ internal sealed class SetupActions(ISystemAccess system, Locations locations) /// 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. @@ -154,12 +170,12 @@ internal sealed class SetupActions(ISystemAccess system, Locations locations) DeleteFile(locations.StartMenuShortcut); DeleteFile(locations.DesktopShortcut); - // «Start Febe with the computer» would point to a program that is no longer there. - system.DeleteUserValue(locations.RunKey, Product.AutostartValue); + // «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.StartsWith(Product.AutostartPrefix, StringComparison.OrdinalIgnoreCase) + 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)) { @@ -195,6 +211,7 @@ internal sealed class SetupActions(ISystemAccess system, Locations locations) try { write(partial); + ClearReadOnly(path); File.Move(partial, path, overwrite: true); } catch @@ -208,10 +225,24 @@ internal sealed class SetupActions(ISystemAccess system, Locations locations) { 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) { @@ -229,12 +260,21 @@ internal sealed class SetupActions(ISystemAccess system, Locations locations) } } + /// + /// 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 file in new DirectoryInfo(folder).EnumerateFiles("*", SearchOption.AllDirectories)) + foreach (var name in new[] { Product.Executable, Product.Uninstaller }) { - bytes += file.Length; + 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 index 1688a2e..afe0257 100644 --- a/src/Febe.Installer/SetupFlow.cs +++ b/src/Febe.Installer/SetupFlow.cs @@ -88,7 +88,9 @@ internal sealed class SetupFlow(ISystemAccess system, Locations locations, ISetu /// The installer: is this program, with Febe.exe inside. public int Install(string packagePath, PackageInfo package, CommandLine line) { - var folder = line.InstallFolder ?? locations.DefaultInstallFolder; + // 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) { diff --git a/src/Febe.Installer/Windows/DialogInterface.cs b/src/Febe.Installer/Windows/DialogInterface.cs index d6e7c60..0cedb49 100644 --- a/src/Febe.Installer/Windows/DialogInterface.cs +++ b/src/Febe.Installer/Windows/DialogInterface.cs @@ -6,7 +6,7 @@ namespace Febe.Installer.Windows; [SupportedOSPlatform("windows")] internal sealed class DialogInterface(Locations locations) : ISetupInterface { - private const int Yes = 100; + internal const int Yes = 100; private const int Cancel = TaskDialog.CancelId; @@ -55,7 +55,7 @@ internal sealed class DialogInterface(Locations locations) : ISetupInterface public bool Installed() { - var (_, run) = TaskDialog.Show(Texts.InstallTitle, new DialogPage( + var (button, run) = TaskDialog.Show(Texts.InstallTitle, new DialogPage( Texts.Installed, Texts.InstalledText, [(Yes, Texts.Finish)]) @@ -63,9 +63,15 @@ internal sealed class DialogInterface(Locations locations) : ISetupInterface Verification = Texts.RunFebe, VerificationChecked = true, }); - return run; + 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( diff --git a/src/Febe.Web/LEGGIMI.md b/src/Febe.Web/LEGGIMI.md index 68012b6..f0ca533 100644 --- a/src/Febe.Web/LEGGIMI.md +++ b/src/Febe.Web/LEGGIMI.md @@ -248,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/tests/Febe.Tests.Windows/InstallerTests.cs b/tests/Febe.Tests.Windows/InstallerTests.cs index bb791b7..66ca2e2 100644 --- a/tests/Febe.Tests.Windows/InstallerTests.cs +++ b/tests/Febe.Tests.Windows/InstallerTests.cs @@ -181,6 +181,16 @@ public sealed class InstallerTests } } + [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. diff --git a/tests/Febe.Tests/Desktop/InstallerTests.cs b/tests/Febe.Tests/Desktop/InstallerTests.cs index d405910..cdb0a8e 100644 --- a/tests/Febe.Tests/Desktop/InstallerTests.cs +++ b/tests/Febe.Tests/Desktop/InstallerTests.cs @@ -116,6 +116,13 @@ public sealed partial class InstallerTests 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); @@ -194,6 +201,104 @@ public sealed partial class InstallerTests 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() { @@ -290,10 +395,14 @@ public sealed partial class InstallerTests 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. + // 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] diff --git a/tests/Febe.Tests/Febe.Tests.csproj b/tests/Febe.Tests/Febe.Tests.csproj index 807ef63..8b27707 100644 --- a/tests/Febe.Tests/Febe.Tests.csproj +++ b/tests/Febe.Tests/Febe.Tests.csproj @@ -16,6 +16,7 @@ + diff --git a/tests/Febe.Tests/Packaging/ImageContentsTests.cs b/tests/Febe.Tests/Packaging/ImageContentsTests.cs index 6fc537a..b4c9c0d 100644 --- a/tests/Febe.Tests/Packaging/ImageContentsTests.cs +++ b/tests/Febe.Tests/Packaging/ImageContentsTests.cs @@ -22,9 +22,7 @@ public sealed partial class ImageContentsTests ["libstdc++6"] = "loaded by libcoreclr, libclrjit and libhostfxr", ["libgcc-s1"] = ".NET and Chromium", ["zlib1g"] = "a direct dependency of Chromium", - ["fonts-dejavu-core"] = "the first font fontconfig asks for", - ["fonts-liberation"] = "Arial, Helvetica and Times with the same metrics", - ["fonts-noto-color-emoji"] = "emoji in the remote view", + ["fonts-dejavu-core"] = "the first font fontconfig asks for: without a font Chromium draws no text", ["ca-certificates"] = "certificate authorities for .NET TLS", ["tzdata"] = "time zones for the engine and Chromium", ["locales"] = "generates it_IT.UTF-8 for the C library Chromium runs with", @@ -40,7 +38,10 @@ public sealed partial class ImageContentsTests private static readonly string[] Required = ["chromium", "chromium-l10n", "xvfb", "libicu76", "libssl3t64", "ca-certificates", "tzdata", "locales"]; /// Programs that must not come back: an init of others, privilege tools, downloaders, other runtimes. - private static readonly string[] Forbidden = ["tini", "dumb-init", "gosu", "su-exec", "sudo", "curl", "wget", "nodejs", "npm", "python3"]; + private static readonly string[] Forbidden = + ["tini", "dumb-init", "gosu", "su-exec", "sudo", "curl", "wget", "nodejs", "npm", "python3", "jq", + // Fonts for looks only: Chromium does not ask for them (Liberation is a Recommends, the emoji font nothing). + "fonts-liberation", "fonts-liberation2", "fonts-noto-color-emoji", "fonts-noto-core", "fonts-noto"]; [TestMethod] public void TheImageInstallsOnlyChromiumWhatItNeedsXvfbAndWhatTheDotNetRuntimeNeeds() @@ -67,6 +68,21 @@ public sealed partial class ImageContentsTests Assert.AreEqual(1, Regex.Matches(Code(dockerfile), @"apt-get install").Count, "a single apt-get install, in the runtime stage"); } + [TestMethod] + public void TheTestsOfTheCiDrawWithTheSameFontsAsTheImage() + { + var environment = Repository.PathOf(".gitea", "scripts", "ambiente-prove.sh"); + if (!File.Exists(environment)) + { + Assert.Inconclusive("Questa copia del repository non ha .gitea/ (costruzione dell'immagine Docker)."); + } + + static string[] Fonts(string text) => [.. Regex.Matches(text, @"\bfonts-[a-z0-9-]+").Select(m => m.Value).Distinct().Order(StringComparer.Ordinal)]; + var image = Fonts(string.Join('\n', InstalledPackages(RuntimeStage()))); + CollectionAssert.AreEqual(new[] { "fonts-dejavu-core" }, image, "one font, the one fontconfig asks for"); + CollectionAssert.AreEqual(image, Fonts(Code(File.ReadAllText(environment))), "ambiente-prove.sh installs the fonts of the image, no more"); + } + [TestMethod] public void EveryInstalledPackageHasItsReasonNextToTheList() { diff --git a/tests/Febe.Tests/Packaging/PipelineTests.Json.cs b/tests/Febe.Tests/Packaging/PipelineTests.Json.cs new file mode 100644 index 0000000..4d870bd --- /dev/null +++ b/tests/Febe.Tests/Packaging/PipelineTests.Json.cs @@ -0,0 +1,297 @@ +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Febe.Tests.Desktop.Support; +using Febe.Tests.Support; + +namespace Febe.Tests.Packaging; + +/// +/// JSON in the CI without third-party programs (decision of 18 November 2026: only gitleaks and Trivy come from +/// outside): .gitea/scripts/json.sh reads with json.awk and json-campi.awk and writes strings with json-stringa.awk, in +/// place of jq for the release, the summaries of gitleaks and Trivy and the credentials of the registry. The credentials +/// go into a client configuration of the publication only, never into the runner's. Every workflow runs its steps with +/// bash, and the release tests run like those of the verification, in Debian with Chromium and no test skipped. +/// +public sealed partial class PipelineTests +{ + [TestMethod] + public void NoJqAnywhereInTheCiNorInTheBuild() + { + var files = AllCiFiles(); + foreach (var path in new[] { Repository.PathOf("installer", "costruisci.sh"), Repository.PathOf("docker", "entrypoint.sh") }) + { + if (File.Exists(path)) + { + files.Add((Path.GetFileName(path), Read(path))); + } + } + + foreach (var (name, text) in files) + { + foreach (var line in Code(text).Split('\n')) + { + Assert.IsFalse(JqWord().IsMatch(line), $"{name}: «{line.Trim()}» uses jq, a program of others"); + } + } + + // What took its place is ours: the reader and the writer of json.sh, and nothing edits the client configuration + // of the runner any more. + StringAssert.Contains(Script("json.sh"), "-f \"$qui/json.awk\" -f \"$qui/json-campi.awk\""); + StringAssert.Contains(Script("json.sh"), "awk -f \"$qui/json-stringa.awk\""); + var release = Step(Job(Workflow("rilascio.yml"), "release"), "Release con installatore"); + StringAssert.Contains(release, "bash .gitea/scripts/json.sh campi \"\" id \"$RISPOSTA\""); + StringAssert.Contains(release, "bash .gitea/scripts/json.sh campi \"*\" name \"$RISPOSTA\""); + StringAssert.Contains(release, "bash .gitea/scripts/json.sh stringa \"$NOTE\""); + StringAssert.Contains(Script("segreti.sh"), "json.sh\" campi \"*\" RuleID,File,StartLine,Commit,Fingerprint"); + StringAssert.Contains(Script("scansione-immagine.sh"), "json.sh\" campi \"Results/*/Vulnerabilities/*\" Severity,FixedVersion"); + } + + [TestMethod] + public void EveryWorkflowRunsItsStepsWithBash() + { + foreach (var name in Workflows) + { + var code = Code(Workflow(name)); + StringAssert.Contains(code, "\ndefaults:\n run:\n shell: bash\n", $"{name}: bash -e -o pipefail whatever the default shell of the runner or of the container"); + foreach (Match shell in Regex.Matches(code, @"^\s+shell:[ \t]*(?\S*)", RegexOptions.Multiline)) + { + Assert.AreEqual("bash", shell.Groups["shell"].Value, $"{name}: no step with another shell"); + } + } + } + + [TestMethod] + public void TheReleaseRunsTheTestsLikeTheVerificationWithTheBrowserAndNoneSkipped() + { + var verification = Job(Workflow("verifica.yml"), "prove"); + var release = Job(Workflow("rilascio.yml"), "prove"); + foreach (var rule in new[] + { + "container:\n image: debian:trixie\n options: --shm-size=1g", + "FEBE_CHROMIUM: /usr/bin/chromium", + "- name: Git e curl per i sorgenti", + "bash .gitea/scripts/ambiente-prove.sh", + "bash .gitea/scripts/riepilogo-prove.sh out/prove 0", + }) + { + StringAssert.Contains(verification, rule, "verifica.yml: prove"); + StringAssert.Contains(release, rule, "rilascio.yml: prove: the release gate exercises what the verification does (the login return among them)"); + } + + var environment = release.IndexOf("bash .gitea/scripts/ambiente-prove.sh", StringComparison.Ordinal); + var tests = release.IndexOf("dotnet test tests/Febe.Tests", StringComparison.Ordinal); + var summary = release.IndexOf("riepilogo-prove.sh out/prove 0", StringComparison.Ordinal); + Assert.IsTrue(environment < tests && tests < summary, "Chromium before the tests, the summary after them"); + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task TheJsonOfTheCiIsReadAndWrittenInHouse() + { + var bash = RequireBash(); + CiPath("scripts", "json.sh"); + using var folder = new TempFolder("febe-json"); + + async Task FileAsync(string name, string text) + { + var path = Path.Combine(folder.Path, name); + await File.WriteAllTextAsync(path, text, new UTF8Encoding(false), TestContext.CancellationToken); + return path.Replace('\\', '/'); + } + + // The arguments through the environment: Git Bash started from Windows would expand an unquoted «*» itself. + async Task<(int Code, string Output, string Errors)> JsonAsync(params string[] arguments) => + await RunProcessAsync(bash, ["-c", "args=(); for ((i = 0; i < ARGOMENTI; i++)); do v=\"ARGOMENTO_$i\"; args+=(\"${!v}\"); done; exec bash .gitea/scripts/json.sh \"${args[@]}\""], start => + { + start.Environment["ARGOMENTI"] = arguments.Length.ToString(System.Globalization.CultureInfo.InvariantCulture); + for (var i = 0; i < arguments.Length; i++) + { + start.Environment[$"ARGOMENTO_{i}"] = arguments[i]; + } + }); + + // A release of Gitea: the id at the root, a list inside it that is not read. + var release = await FileAsync("release.json", """{"id": 4242, "tag_name": "v0.1.2", "assets": [{"id": 7, "name": "dentro.exe"}], "author": {"id": 3}}"""); + var read = await JsonAsync("campi", "", "id", release); + Assert.AreEqual(0, read.Code, read.Errors); + Assert.AreEqual("4242\n", read.Output); + + // The assets of a release: one name per line, in order, with spaces; a tab or a line break in a value stays on + // its line. A field missing or holding a container is empty; a scalar of the list is not an object. + var assets = await FileAsync("assets.json", """[{"name": "Febe-Setup-0.1.2.exe", "size": 9}, {"name": "febe compose.tar.gz", "x": {"name": "no"}}, {"name": "a\tb\nc"}, {"size": [1]}, 3]"""); + read = await JsonAsync("campi", "*", "name,size", assets); + Assert.AreEqual(0, read.Code, read.Errors); + Assert.AreEqual("Febe-Setup-0.1.2.exe\t9\nfebe compose.tar.gz\t\na b c\t\n\t\n", read.Output); + + // Trivy: every vulnerability of every result, with its fix (empty, null or missing when there is none). + var trivy = await FileAsync("trivy.json", """ + {"SchemaVersion": 2, "Results": [ + {"Target": "debian", "Vulnerabilities": [{"VulnerabilityID": "CVE-1", "Severity": "HIGH", "FixedVersion": ""}, + {"VulnerabilityID": "CVE-2", "Severity": "CRITICAL", "FixedVersion": "1.2-3"}]}, + {"Target": "Febe.deps.json"}, + {"Target": "altro", "Vulnerabilities": [{"Severity": "CRITICAL", "FixedVersion": null}, {"Severity": "CRITICAL"}]}]} + """); + read = await JsonAsync("campi", "Results/*/Vulnerabilities/*", "Severity,FixedVersion", trivy); + Assert.AreEqual(0, read.Code, read.Errors); + Assert.AreEqual("HIGH\t\nCRITICAL\t1.2-3\nCRITICAL\tnull\nCRITICAL\t\n", read.Output); + + // gitleaks: an empty report is an empty list, no line. + read = await JsonAsync("campi", "*", "RuleID,File", await FileAsync("vuoto.json", "[]")); + Assert.AreEqual((0, string.Empty), (read.Code, read.Output), read.Errors); + + // Broken JSON: nothing at all on the output (not even what came before the error), the reason, exit 2. A wrong + // command line or a missing file too. + read = await JsonAsync("campi", "*", "name", await FileAsync("rotto.json", """[{"name": "primo"}, {"name": """)); + Assert.AreEqual(2, read.Code); + Assert.IsEmpty(read.Output); + StringAssert.Contains(read.Errors, "rotto.json"); + foreach (var arguments in new[] { new[] { "campi", "*", "na me", release }, ["campi", "/x", "id", release], ["campi", "", "id", release + ".manca"], ["altro"] }) + { + read = await JsonAsync(arguments); + Assert.AreEqual(2, read.Code, string.Join(' ', arguments)); + Assert.IsEmpty(read.Output, string.Join(' ', arguments)); + } + + // Writing: any text, as the notes of a release are, comes back identical from a JSON parser. + var notes = "## 0.1.2\n\n- «Novità» con \"virgolette\", \\barre\\ e\ttabulazioni, un ritorno\r da solo\n- controllo \u0001 e \u001f, emoji 🙂, ünïcödé\n- fine"; + var notesFile = await FileAsync("note.txt", notes); + var written = await RunProcessAsync(bash, ["-c", "bash .gitea/scripts/json.sh stringa \"$(cat \"$1\")\"", "bash", notesFile]); + Assert.AreEqual(0, written.Code, written.Errors); + var literal = written.Output.TrimEnd('\n'); + Assert.DoesNotContain("\n", literal, "one line"); + Assert.AreEqual(notes, JsonDocument.Parse(literal).RootElement.GetString()); + written = await JsonAsync("stringa", ""); + Assert.AreEqual("\"\"\n", written.Output, written.Errors); + + // The body of a release as the step builds it is valid JSON with those values. + var body = await RunProcessAsync(bash, ["-c", """ + NOTE="$(cat "$1")" + printf '{"tag_name":%s,"name":%s,"body":%s,"draft":false,"prerelease":%s}' \ + "$(bash .gitea/scripts/json.sh stringa "v0.1.2")" "$(bash .gitea/scripts/json.sh stringa "Febe 0.1.2")" \ + "$(bash .gitea/scripts/json.sh stringa "$NOTE")" true + """, "bash", notesFile]); + Assert.AreEqual(0, body.Code, body.Errors); + using var parsed = JsonDocument.Parse(body.Output); + Assert.AreEqual("v0.1.2", parsed.RootElement.GetProperty("tag_name").GetString()); + Assert.AreEqual(notes, parsed.RootElement.GetProperty("body").GetString()); + Assert.IsTrue(parsed.RootElement.GetProperty("prerelease").GetBoolean()); + } + + [TestMethod] + [Timeout(120_000, CooperativeCancellation = true)] + public async Task TheCredentialsOfTheRegistryLiveOnlyInAConfigurationOfThePublicationAndGoAway() + { + var bash = RequireBash(); + CiPath("scripts", "costruisci-immagine.sh"); + using var folder = new TempFolder("febe-credenziali"); + var bin = folder.Combine("bin"); + var world = folder.Combine("mondo"); + var temp = folder.Combine("temp"); + var client = folder.Combine("client"); + foreach (var made in new[] { bin, world, temp, Path.Combine(client, "cli-plugins"), Path.Combine(client, "buildx") }) + { + Directory.CreateDirectory(made); + } + + // The runner's own client configuration: another registry, a context; it must come out byte for byte the same. + var original = "{\"currentContext\": \"casa\", \"auths\": {\"altro.invalid\": {\"auth\": \"" + Convert.ToBase64String(Encoding.UTF8.GetBytes("altro:altro")) + "\"}}}\n"; + await File.WriteAllTextAsync(Path.Combine(client, "config.json"), original, TestContext.CancellationToken); + + // A docker that records the configuration it is given while it runs. + var docker = Path.Combine(bin, "docker"); + await File.WriteAllTextAsync(docker, """ + #!/usr/bin/env bash + world="$FAKE_WORLD" + printf 'docker %s\n' "$*" >> "$world/calls" + printf '%s\n' "${DOCKER_CONFIG:-}" > "$world/config-dir" + printf '%s\n' "${BUILDX_CONFIG:-}" > "$world/buildx-config" + if [[ -f "${DOCKER_CONFIG:-/nessuna}/config.json" ]]; then cp "$DOCKER_CONFIG/config.json" "$world/config.json"; fi + if [[ -e "${DOCKER_CONFIG:-/nessuna}/cli-plugins" ]]; then echo si > "$world/plugins"; fi + exit "${FAKE_EXIT:-0}" + """.Replace("\r\n", "\n", StringComparison.Ordinal), TestContext.CancellationToken); + if (!OperatingSystem.IsWindows()) + { + File.SetUnixFileMode(docker, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + } + + async Task<(int Code, string Output, string Errors)> PublishAsync(string? token, string exit = "0") + { + foreach (var file in Directory.EnumerateFiles(world)) + { + File.Delete(file); + } + + string[] script = ["-c", "bin=\"$FAKE_BIN\"; if command -v cygpath > /dev/null; then bin=\"$(cygpath -u \"$bin\")\"; fi; PATH=\"$bin:$PATH\"; exec bash \"$@\"", "bash", ".gitea/scripts/costruisci-immagine.sh", "pubblica", "registro.invalid:3000/alby96/febe:0.1.2"]; + var run = await RunProcessAsync(bash, script, start => + { + start.Environment["FAKE_BIN"] = bin; + start.Environment["FAKE_WORLD"] = world.Replace('\\', '/'); + start.Environment["FAKE_EXIT"] = exit; + start.Environment["RUNNER_TEMP"] = temp.Replace('\\', '/'); + start.Environment["DOCKER_CONFIG"] = client.Replace('\\', '/'); + start.Environment.Remove("BUILDX_CONFIG"); + start.Environment["REGISTRY"] = "registro.invalid:3000"; + start.Environment["REGISTRO_UTENTE"] = "Alby96"; + start.Environment.Remove("REGISTRO_TOKEN"); + if (token is not null) + { + start.Environment["REGISTRO_TOKEN"] = token; + } + + foreach (var (key, value) in new[] { ("BUILDER", "febe-ci-7"), ("VERSIONE", "0.1.2"), ("GIT_COMMIT", "abc"), ("FLUSSO", "rilascio"), ("ESECUZIONE", "7") }) + { + start.Environment[key] = value; + } + }); + Assert.DoesNotContain(RegistryToken, run.Output + run.Errors, "the token never reaches the log"); + return run; + } + + var published = await PublishAsync(RegistryToken); + Assert.AreEqual(0, published.Code, published.Output + published.Errors); + var calls = await ReadLinesAsync(Path.Combine(world, "calls")); + Assert.HasCount(1, calls); + StringAssert.Contains(calls[0], "docker buildx build --builder febe-ci-7 "); + StringAssert.Contains(calls[0], "-t registro.invalid:3000/alby96/febe:0.1.2 --push ."); + + // While buildx ran: a configuration of its own, with only this registry and the context of the runner kept. + var directory = (await File.ReadAllTextAsync(Path.Combine(world, "config-dir"), TestContext.CancellationToken)).Trim(); + Assert.AreEqual(temp.Replace('\\', '/') + "/febe-docker-7", directory); + Assert.AreEqual(client.Replace('\\', '/') + "/buildx", (await File.ReadAllTextAsync(Path.Combine(world, "buildx-config"), TestContext.CancellationToken)).Trim(), "the builders of the run are still found"); + Assert.IsTrue(File.Exists(Path.Combine(world, "plugins")), "the plugins of the client (buildx) are still there"); + using (var used = JsonDocument.Parse(await File.ReadAllTextAsync(Path.Combine(world, "config.json"), TestContext.CancellationToken))) + { + var auths = used.RootElement.GetProperty("auths"); + Assert.AreEqual(1, auths.EnumerateObject().Count(), "only the registry of Febe"); + Assert.AreEqual(Convert.ToBase64String(Encoding.UTF8.GetBytes("Alby96:" + RegistryToken)), auths.GetProperty("registro.invalid:3000").GetProperty("auth").GetString()); + Assert.AreEqual("casa", used.RootElement.GetProperty("currentContext").GetString()); + } + + // After it: gone, and the runner's configuration untouched. + Assert.IsFalse(Directory.Exists(Path.Combine(temp, "febe-docker-7"))); + Assert.AreEqual(original, await File.ReadAllTextAsync(Path.Combine(client, "config.json"), TestContext.CancellationToken)); + + // A failed push leaves nothing behind either; without the token nothing is attempted. + var failed = await PublishAsync(RegistryToken, exit: "1"); + Assert.AreNotEqual(0, failed.Code); + Assert.IsFalse(Directory.Exists(Path.Combine(temp, "febe-docker-7"))); + var refused = await PublishAsync(token: null); + Assert.AreEqual(2, refused.Code, refused.Output); + Assert.IsFalse(File.Exists(Path.Combine(world, "calls"))); + Assert.AreEqual(original, await File.ReadAllTextAsync(Path.Combine(client, "config.json"), TestContext.CancellationToken)); + + // The steps leave the credentials to the script, and the cleanup that always runs removes its folder. + foreach (var (name, job, step) in new[] { ("verifica.yml", "immagine", "Pubblicazione come :main e :sha-"), ("rilascio.yml", "immagine", "Pubblicazione sul registro di Gitea") }) + { + var text = Job(Workflow(name), job); + var publish = Step(text, step); + StringAssert.Contains(publish, "REGISTRO_TOKEN: ${{ secrets.REGISTRY_TOKEN }}", name); + Assert.DoesNotContain("config.json", Code(publish), $"{name}: the runner's client configuration is never edited"); + StringAssert.Contains(Step(text, "Pulizia (sempre)"), "rm -rf \"${RUNNER_TEMP:-/tmp}/febe-docker-$ESECUZIONE\"", name); + } + } + + [GeneratedRegex(@"\bjq\b")] + private static partial Regex JqWord(); +} diff --git a/tests/Febe.Tests/Packaging/PipelineTests.cs b/tests/Febe.Tests/Packaging/PipelineTests.cs index 23e49ac..59060e2 100644 --- a/tests/Febe.Tests/Packaging/PipelineTests.cs +++ b/tests/Febe.Tests/Packaging/PipelineTests.cs @@ -129,7 +129,7 @@ public sealed partial class PipelineTests var cleanup = Step(image, "Pulizia (sempre)"); StringAssert.Contains(cleanup, "if: always()"); StringAssert.Contains(cleanup, "bash .gitea/scripts/pulizia-docker.sh esecuzione \"$ESECUZIONE\""); - StringAssert.Contains(cleanup, ".auths |= del(.[$r])", "the credentials leave the client configuration"); + StringAssert.Contains(cleanup, "rm -rf \"${RUNNER_TEMP:-/tmp}/febe-docker-$ESECUZIONE\"", "the client configuration with the credentials goes, even after an interruption"); } [TestMethod] diff --git a/tests/Febe.Tests/Web/InHouseAssetsTests.cs b/tests/Febe.Tests/Web/InHouseAssetsTests.cs index 2bd053b..3b9deae 100644 --- a/tests/Febe.Tests/Web/InHouseAssetsTests.cs +++ b/tests/Febe.Tests/Web/InHouseAssetsTests.cs @@ -92,34 +92,491 @@ public sealed partial class InHouseAssetsTests Assert.IsFalse(shape.HasElements, $"{path}: forme annidate"); foreach (var attribute in shape.Attributes()) { - Assert.IsTrue(Geometry.Contains(attribute.Name.LocalName), $"{path}: attributo «{attribute.Name.LocalName}» (spessore, colore e riempimento vengono dal foglio di stile)"); - if (attribute.Name.LocalName is not ("d" or "points" or "stroke-dasharray" or "stroke-dashoffset")) + var name = attribute.Name.LocalName; + Assert.IsTrue(Geometry.Contains(name), $"{path}: attributo «{name}» (spessore, colore e riempimento vengono dal foglio di stile)"); + var where = $"{path}: <{shape.Name.LocalName} {name}=\"{attribute.Value}\">"; + switch (name) { - var value = double.Parse(attribute.Value, System.Globalization.CultureInfo.InvariantCulture); - Assert.IsTrue(value is >= 0 and <= 24, $"{path}: {attribute.Name.LocalName}={attribute.Value} fuori dalla griglia"); + case "d": + foreach (var (x, y) in PathPoints(attribute.Value, where)!) + { + AssertOnGrid(x, where); + AssertOnGrid(y, where); + } + + break; + case "points": + var numbers = Numbers(attribute.Value, where); + Assert.IsTrue(numbers.Count >= 4 && numbers.Count % 2 == 0, $"{where}: coppie di coordinate, almeno due punti"); + numbers.ForEach(value => AssertOnGrid(value, where)); + break; + case "stroke-dasharray" or "stroke-dashoffset": + Numbers(attribute.Value, where).ForEach(value => Assert.IsTrue(value is >= 0 and <= 100, where)); + break; + default: + AssertOnGrid(Number(attribute.Value, where), where); + break; } } } } } + [TestMethod] + public void TheGridCheckReadsPathsAndPointsAndFindsWhatIsOffTheGrid() + { + // Absolute and relative commands, repeated arguments, arcs with packed flags, curves, closing. + var points = PathPoints("M4.5 12a7.5 7.5 0 0 1 13-5.1l2 2.1M3 3h18v18H3zM6 9c0-2 1-3 3-3s3 1 3 3q2 2 4 0t4 0", "prova"); + Assert.IsNotNull(points); + Assert.IsTrue(points.Any(p => Math.Abs(p.X - 19.5) < 1e-9 && Math.Abs(p.Y - 9) < 1e-9), "a relative line after a relative arc"); + Assert.IsTrue(points.Any(p => p == (21.0, 21.0)), "h and v, then H"); + Assert.IsTrue(points.Any(p => p == (20.0, 9.0)), "c, s, q and t"); + Assert.IsTrue(points.All(p => p.X is >= 0 and <= 24 && p.Y is >= 0 and <= 24)); + Assert.IsTrue(PathPoints("M2 12a10 10 0 1012 0", "prova")!.Any(p => p.Y > 12 + 5), "the arc is followed, not only its ends"); + + // What the test must refuse: off the grid by an end, by a curve or by an arc that bulges, broken numbers. + foreach (var bad in new[] { "M30 30L-5 40", "M2 2l30 0", "M2 12C2 -10 22 -10 22 12", "M2 2a20 20 0 0 1 20 0", "M2 2L3", "M2,x 3", "L2 2", "M2 2a1 1 0 2 1 3 3" }) + { + var off = PathPoints(bad, bad, failQuietly: true); + Assert.IsTrue(off is null || off.Any(p => p.X is < 0 or > 24 || p.Y is < 0 or > 24), $"«{bad}» passerebbe"); + } + + Assert.ThrowsExactly(() => Numbers("0,0 99,x", "prova", failQuietly: true)); + CollectionAssert.AreEqual(new[] { 0.5, 0.5, -3.0, 1e-1 }, Numbers("0.5.5-3,1e-1", "prova")); + } + + private static void AssertOnGrid(double value, string where) => + Assert.IsTrue(value is >= -1e-6 and <= 24 + 1e-6, $"{where}: {value.ToString(System.Globalization.CultureInfo.InvariantCulture)} fuori dalla griglia 0–24"); + + private static double Number(string text, string where) + { + Assert.IsTrue(double.TryParse(text, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out var value), $"{where}: «{text}» non è un numero"); + return value; + } + + private static List Numbers(string text, string where, bool failQuietly = false) + { + var numbers = new List(); + var at = 0; + while (SkipSeparators(text, ref at) < text.Length) + { + if (ReadNumber(text, ref at) is not { } value) + { + if (failQuietly) + { + throw new FormatException(where); + } + + Assert.Fail($"{where}: «{text[at..]}» non è un numero"); + } + else + { + numbers.Add(value); + } + } + + return numbers; + } + + /// + /// Every point the outline of an SVG path goes through (SVG 1.1 §8.3): the ends of each segment, the control points + /// of the curves and points along each curve and arc, all made absolute. A path that does not start with a move, + /// a command with too few numbers or a number that does not parse fails the test (or gives null with + /// ). + /// + private static List<(double X, double Y)>? PathPoints(string d, string where, bool failQuietly = false) + { + var points = new List<(double X, double Y)>(); + double x = 0, y = 0, startX = 0, startY = 0; + var at = 0; + var command = '\0'; + void Refuse(string why) + { + if (!failQuietly) + { + Assert.Fail($"{where}: {why}"); + } + } + + while (SkipSeparators(d, ref at) < d.Length) + { + if (char.IsAsciiLetter(d[at])) + { + command = d[at++]; + if (points.Count == 0 && command is not ('M' or 'm')) + { + Refuse("il percorso deve cominciare con M"); + return null; + } + + if (command is 'Z' or 'z') + { + (x, y) = (startX, startY); + points.Add((x, y)); + continue; + } + } + else if (command is '\0' or 'Z' or 'z') + { + Refuse($"numero senza comando: «{d[at..]}»"); + return null; + } + + var relative = char.IsAsciiLetterLower(command); + var arguments = char.ToUpperInvariant(command) switch + { + 'M' or 'L' or 'T' => 2, + 'H' or 'V' => 1, + 'C' => 6, + 'S' or 'Q' => 4, + 'A' => 7, + _ => -1, + }; + if (arguments < 0) + { + Refuse($"comando «{command}» sconosciuto"); + return null; + } + + var values = new double[arguments]; + for (var i = 0; i < arguments; i++) + { + SkipSeparators(d, ref at); + double? value = char.ToUpperInvariant(command) == 'A' && i is 3 or 4 ? ReadFlag(d, ref at) : ReadNumber(d, ref at); + if (value is null) + { + Refuse($"comando «{command}» con argomenti mancanti o non validi: «{d[at..]}»"); + return null; + } + + values[i] = value.Value; + } + + (double X, double Y) Absolute(int index) => relative ? (x + values[index], y + values[index + 1]) : (values[index], values[index + 1]); + var from = (X: x, Y: y); + switch (char.ToUpperInvariant(command)) + { + case 'M': + (x, y) = Absolute(0); + (startX, startY) = (x, y); + points.Add((x, y)); + command = relative ? 'l' : 'L'; + break; + case 'L' or 'T': + (x, y) = Absolute(0); + points.Add((x, y)); + break; + case 'H': + x = relative ? x + values[0] : values[0]; + points.Add((x, y)); + break; + case 'V': + y = relative ? y + values[0] : values[0]; + points.Add((x, y)); + break; + case 'C': + { + var (c1, c2, end) = (Absolute(0), Absolute(2), Absolute(4)); + points.AddRange([c1, c2, end]); + for (var t = 0.0625; t < 1; t += 0.0625) + { + var u = 1 - t; + points.Add(((u * u * u * from.X) + (3 * u * u * t * c1.X) + (3 * u * t * t * c2.X) + (t * t * t * end.X), + (u * u * u * from.Y) + (3 * u * u * t * c1.Y) + (3 * u * t * t * c2.Y) + (t * t * t * end.Y))); + } + + (x, y) = end; + break; + } + + case 'S' or 'Q': + { + var (control, end) = (Absolute(0), Absolute(2)); + points.AddRange([control, end]); + (x, y) = end; + break; + } + + case 'A': + { + var end = Absolute(5); + points.Add(end); + points.AddRange(ArcPoints(from, values[0], values[1], values[2], values[3] != 0, values[4] != 0, end)); + (x, y) = end; + break; + } + } + } + + if (points.Count == 0) + { + Refuse("percorso vuoto"); + return null; + } + + return points; + } + + /// Points along an elliptical arc, from its end points to its centre as in SVG 1.1 appendix F.6.5. + private static IEnumerable<(double X, double Y)> ArcPoints((double X, double Y) from, double rx, double ry, double rotation, bool large, bool sweep, (double X, double Y) to) + { + rx = Math.Abs(rx); + ry = Math.Abs(ry); + if (rx == 0 || ry == 0 || from == to) + { + yield break; + } + + var phi = rotation * Math.PI / 180; + var (cos, sin) = (Math.Cos(phi), Math.Sin(phi)); + var dx = (from.X - to.X) / 2; + var dy = (from.Y - to.Y) / 2; + var x1 = (cos * dx) + (sin * dy); + var y1 = (-sin * dx) + (cos * dy); + var lambda = (x1 * x1 / (rx * rx)) + (y1 * y1 / (ry * ry)); + if (lambda > 1) + { + rx *= Math.Sqrt(lambda); + ry *= Math.Sqrt(lambda); + } + + var numerator = (rx * rx * ry * ry) - (rx * rx * y1 * y1) - (ry * ry * x1 * x1); + var factor = Math.Sqrt(Math.Max(0, numerator / ((rx * rx * y1 * y1) + (ry * ry * x1 * x1)))) * (large == sweep ? -1 : 1); + var cx1 = factor * rx * y1 / ry; + var cy1 = -factor * ry * x1 / rx; + var cx = (cos * cx1) - (sin * cy1) + ((from.X + to.X) / 2); + var cy = (sin * cx1) + (cos * cy1) + ((from.Y + to.Y) / 2); + static double Angle(double ux, double uy, double vx, double vy) => Math.Atan2((ux * vy) - (uy * vx), (ux * vx) + (uy * vy)); + var start = Angle(1, 0, (x1 - cx1) / rx, (y1 - cy1) / ry); + var delta = Angle((x1 - cx1) / rx, (y1 - cy1) / ry, (-x1 - cx1) / rx, (-y1 - cy1) / ry); + if (!sweep && delta > 0) + { + delta -= 2 * Math.PI; + } + else if (sweep && delta < 0) + { + delta += 2 * Math.PI; + } + + for (var step = 1; step < 32; step++) + { + var angle = start + (delta * step / 32); + var (ex, ey) = (rx * Math.Cos(angle), ry * Math.Sin(angle)); + yield return ((cos * ex) - (sin * ey) + cx, (sin * ex) + (cos * ey) + cy); + } + } + + private static int SkipSeparators(string text, ref int at) + { + while (at < text.Length && (char.IsWhiteSpace(text[at]) || text[at] == ',')) + { + at++; + } + + return at; + } + + private static double? ReadNumber(string text, ref int at) + { + var match = SvgNumber().Match(text, at); + if (!match.Success || match.Index != at) + { + return null; + } + + at += match.Length; + return double.Parse(match.Value, System.Globalization.CultureInfo.InvariantCulture); + } + + /// An arc flag: one digit, 0 or 1, which may touch the next number («0 01 3 3»). + private static double? ReadFlag(string text, ref int at) + { + if (at < text.Length && text[at] is '0' or '1') + { + return text[at++] - '0'; + } + + return null; + } + [TestMethod] public void EveryIconThePagesAskForIsDrawn() { var files = new EmbeddedWwwroot(); var drawn = files.Files.Where(f => f.StartsWith("icone/", StringComparison.Ordinal)) .Select(f => f["icone/".Length..^".svg".Length]).ToHashSet(StringComparer.Ordinal); - var asked = 0; + var asked = new Dictionary(StringComparer.Ordinal); foreach (var path in files.Files.Where(f => f.EndsWith(".js", StringComparison.Ordinal))) { - foreach (Match match in IconCall().Matches(files.ReadText(path)!)) + foreach (var name in IconNamesAskedIn(files.ReadText(path)!)) { - asked++; - Assert.Contains(match.Groups[1].Value, drawn, $"{path} chiede l'icona «{match.Groups[1].Value}»"); + asked.TryAdd(name, path); } } - Assert.IsGreaterThan(20, asked, "le pagine usano le icone"); + foreach (var (name, path) in asked) + { + Assert.Contains(name, drawn, $"{path} chiede l'icona «{name}»"); + } + + // Every form the pages use is read, not only icon('…'): names held in data (icon: '…', a map of icons, the + // third argument of label), chosen with a condition, or taken from a list a function returns. One name for each + // form, as the pages have them today. + foreach (var (name, form) in new[] + { + ("layout-grid", "icon: '…' (shell.js)"), ("sun", "icon: '…' (settings-general.js)"), ("gauge", "PLAN_ICONS e icon: '…'"), + ("trash-2", "icon: '…' (accounts.js)"), ("circle-check", "icon(on ? '…' : '…')"), ("at-sign", "icon(cond ? '…' : '…')"), + ("octagon-alert", "[colore, '…'] in outcome"), ("shield-alert", "return ['…', …] di placeholderFor"), + ("user-check", "label(testo, '', '…')"), ("hourglass", "icon(a ? '…' : b ? '…' : '…')"), + }) + { + Assert.IsTrue(asked.ContainsKey(name), $"la prova non legge più la forma {form}: manca «{name}»"); + } + + Assert.IsGreaterThan(50, asked.Count, "le pagine usano le icone"); + } + + [TestMethod] + public void TheReadingOfTheIconNamesSeesEveryFormAndNotTheConditions() + { + const string script = """ + const MENU = [{ path: '/', icon: 'uno' }, { icon: x ? 'due' : 'tre', label: 'non-icona' }]; + const STATE_ICONS = { a: 'quattro', b: 'cinque' }; + h('b', icon(s.kind === 'video' ? 'sei' : 'sette', 's'), icon('otto'), label(t('x'), 'ambra', 'nove')); + const outcome = { ok: ['verde', 'dieci'], ko: ['rosso', 'undici'] }[k] || ['', 'dodici']; + h('td', icon(outcome[1])); + function placeholderFor(m) { + if (m === 'Off') return ['tredici', t('a'), null]; + return ['quattordici', t('b'), 'about:blank']; + } + const [name, text] = placeholderFor(mode); + fill(icon(name, 'l')); + """; + CollectionAssert.AreEquivalent( + new[] { "uno", "due", "tre", "quattro", "cinque", "sei", "sette", "otto", "nove", "dieci", "undici", "dodici", "tredici", "quattordici" }, + IconNamesAskedIn(script).Distinct().ToArray(), + "not «video» (a condition), not «non-icona», «verde» or «about:blank»"); + } + + /// + /// The icon names a script asks for: the literals that reach icon(…) directly or through data. + /// + /// the first argument of icon(…), the value of icon: … and the third argument of label(…), + /// with the literals of a condition left out (those before a ? or after ===); + /// the values of an object assigned to a name with ICON in it (PLAN_ICONS); + /// icon(v[n]): element n of the lists in const v = …; + /// icon(v) with const [.., v, ..] = f(…): that element of the lists f returns. + /// + /// + private static IEnumerable IconNamesAskedIn(string script) + { + foreach (Match call in IconArgument().Matches(script)) + { + foreach (var name in NamesIn(FirstArgument(script, call.Index + call.Length))) + { + yield return name; + } + } + + foreach (Match property in IconProperty().Matches(script)) + { + foreach (var name in NamesIn(FirstArgument(script, property.Index + property.Length))) + { + yield return name; + } + } + + foreach (Match label in LabelIcon().Matches(script)) + { + yield return label.Groups[1].Value; + } + + foreach (Match map in IconMap().Matches(script)) + { + foreach (Match value in QuotedValue().Matches(map.Groups["body"].Value)) + { + yield return value.Groups[1].Value; + } + } + + foreach (Match indexed in IndexedIcon().Matches(script)) + { + var definition = Regex.Match(script, $@"const {Regex.Escape(indexed.Groups["list"].Value)} = (?[^;\n]+)"); + var index = int.Parse(indexed.Groups["index"].Value, System.Globalization.CultureInfo.InvariantCulture); + foreach (Match list in ListLiteral().Matches(definition.Groups["value"].Value)) + { + var items = list.Groups["items"].Value.Split(',', StringSplitOptions.TrimEntries); + if (index < items.Length && Quoted().Match(items[index]) is { Success: true } item) + { + yield return item.Groups[1].Value; + } + } + } + + foreach (Match variable in VariableIcon().Matches(script)) + { + var name = variable.Groups["name"].Value; + foreach (Match destructured in Regex.Matches(script, @"const \[(?[^\]]+)\] = (?\w+)\(")) + { + var names = destructured.Groups["names"].Value.Split(',', StringSplitOptions.TrimEntries); + var position = Array.IndexOf(names, name); + if (position < 0) + { + continue; + } + + var body = Regex.Match(script, $@"function {Regex.Escape(destructured.Groups["function"].Value)}\([^)]*\) \{{(?.*?)\n\s*\}}", RegexOptions.Singleline); + foreach (Match returned in Regex.Matches(body.Groups["body"].Value, @"return \[(?[^\]]*)\]")) + { + var items = returned.Groups["items"].Value.Split(',', StringSplitOptions.TrimEntries); + if (position < items.Length && Quoted().Match(items[position]) is { Success: true } item) + { + yield return item.Groups[1].Value; + } + } + } + } + } + + /// The text of an argument or a value from to the comma, parenthesis or brace that ends it. + private static string FirstArgument(string script, int start) + { + var depth = 0; + for (var i = start; i < script.Length; i++) + { + var c = script[i]; + if (c is '(' or '[' or '{') + { + depth++; + } + else if (c is ')' or ']' or '}' || (c is ',' or ';' or '\n' && depth == 0)) + { + if (depth == 0) + { + return script[start..i]; + } + + depth--; + } + } + + return script[start..]; + } + + /// The quoted names of an expression, without the operands of a condition. + private static IEnumerable NamesIn(string expression) + { + foreach (Match literal in Quoted().Matches(expression)) + { + var after = expression[(literal.Index + literal.Length)..].TrimStart(); + var before = expression[..literal.Index].TrimEnd(); + if (after.StartsWith('?') || before.EndsWith("===", StringComparison.Ordinal) || before.EndsWith("!==", StringComparison.Ordinal)) + { + continue; + } + + yield return literal.Groups[1].Value; + } } [TestMethod] @@ -167,8 +624,35 @@ public sealed partial class InHouseAssetsTests [GeneratedRegex(@"--carattere:([^;]+);")] private static partial Regex CharacterToken(); - [GeneratedRegex(@"\bicon\('([a-z0-9-]+)'")] - private static partial Regex IconCall(); + [GeneratedRegex(@"[-+]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?")] + private static partial Regex SvgNumber(); + + [GeneratedRegex(@"(?[^}]*)\}", RegexOptions.IgnoreCase)] + private static partial Regex IconMap(); + + [GeneratedRegex(@":\s*'([a-z0-9-]+)'")] + private static partial Regex QuotedValue(); + + [GeneratedRegex(@"\bicon\((?\w+)\[(?\d)\]\)")] + private static partial Regex IndexedIcon(); + + [GeneratedRegex(@"\bicon\((?[A-Za-z_]\w*)[,)]")] + private static partial Regex VariableIcon(); + + [GeneratedRegex(@"\[(?[^\[\]]*)\]")] + private static partial Regex ListLiteral(); + + [GeneratedRegex(@"'([a-z0-9]+(?:-[a-z0-9]+)*)'")] + private static partial Regex Quoted(); // The font and the icon set Febe carried until 18 November 2026. [GeneratedRegex(@"\b(archivo|lucide)\b", RegexOptions.IgnoreCase)] diff --git a/tests/Febe.Tests/Web/ScreenshotToolTests.cs b/tests/Febe.Tests/Web/ScreenshotToolTests.cs new file mode 100644 index 0000000..6deabf1 --- /dev/null +++ b/tests/Febe.Tests/Web/ScreenshotToolTests.cs @@ -0,0 +1,144 @@ +using System.Text.Json; +using System.Text.RegularExpressions; +using Febe.Schermate; +using Febe.Tests.Desktop.Support; + +namespace Febe.Tests.Web; + +/// +/// The screenshot tool of spec §10.7 (tools/Febe.Schermate), written in C# like the rest (Alberto's decision of +/// 18 November 2026: no Node, no third-party programs): only Febe's own interface on this computer, every screenshot of +/// docs/schermate and nothing else. +/// +[TestClass] +public sealed partial class ScreenshotToolTests +{ + [TestMethod] + public void OnlyFebeOnThisComputerIsPhotographed() + { + foreach (var address in new[] { "http://127.0.0.1:8490/libreria", "http://localhost:8480/", "http://[::1]:8480/account", "https://127.0.0.1:8443/" }) + { + Assert.IsTrue(Shots.IsOnThisComputer(new Uri(address)), address); + } + + foreach (var address in new[] + { + "https://www.instagram.com/", "http://127.0.0.2:8480/", "http://localhost.example.com/", "file:///etc/passwd", + "http://user:pw@127.0.0.1:8480/", "http://192.168.1.10:8480/", "ws://127.0.0.1:8480/", + }) + { + Assert.IsFalse(Shots.IsOnThisComputer(new Uri(address)), address); + } + + var ex = Assert.ThrowsExactly(() => Request.Parse(["una", "https://www.instagram.com/", "x.png"], Path.GetTempPath())); + StringAssert.Contains(ex.Message, "questo computer"); + } + + [TestMethod] + public void TheListTakesEveryScreenshotOfTheFolderOnceWithItsStep() + { + var folder = Repository.PathOf("docs", "schermate"); + var steps = Repository.PathOf("tools", "Febe.Schermate", "passi"); + var files = Shots.All.Select(s => s.File).ToList(); + CollectionAssert.AllItemsAreUnique(files); + CollectionAssert.AreEquivalent(Directory.GetFiles(folder, "*.png").Select(Path.GetFileName).ToList(), files, "every screenshot of docs/schermate, no other"); + foreach (var shot in Shots.All) + { + Assert.IsTrue(shot.Page.StartsWith('/'), shot.File); + Assert.IsTrue(shot.Width is >= 390 and <= 1440 && shot.Height is >= 844 and <= 1470, shot.File); + if (shot.Step is not null) + { + Assert.IsTrue(File.Exists(Path.Combine(steps, shot.Step)), $"manca il passo {shot.Step}"); + } + } + + // The steps go next to the program, where it looks for them. + var project = File.ReadAllText(Repository.PathOf("tools", "Febe.Schermate", "Febe.Schermate.csproj")); + StringAssert.Contains(project, ""); + } + + [TestMethod] + public void TheCommandLineGivesTheDemoTheFolderAndASingleShot() + { + var root = Repository.PathOf(); + var all = Request.Parse([], Path.Combine(root, "src")); + Assert.AreEqual(new Uri("http://127.0.0.1:8480/"), all.Base); + Assert.AreEqual(Path.Combine(root, "docs", "schermate"), all.Folder); + Assert.HasCount(Shots.All.Count, all.Shots); + Assert.AreEqual(new Uri("http://127.0.0.1:8480/libreria?tema=chiaro"), all.AddressOf(all.Shots[0])); + + var other = Request.Parse(["8490", "uscita"], root); + Assert.AreEqual(8490, other.Base.Port); + Assert.AreEqual(Path.Combine(root, "uscita"), other.Folder); + + var one = Request.Parse(["una", "http://localhost:8490/attivita?scena=fermo", "prova.png", "390", "844", "500", "passo.js"], root); + var shot = one.Shots.Single(); + Assert.AreEqual(new Uri("http://localhost:8490/attivita?scena=fermo"), one.AddressOf(shot)); + Assert.AreEqual(root, one.Folder); + Assert.AreEqual(new Shot(string.Empty, "prova.png", 390, 844, 500, Path.Combine(root, "passo.js")), shot); + Assert.AreEqual(Path.Combine(root, "passo.js"), one.StepPath(shot.Step!)); + + foreach (var wrong in new[] { new[] { "porta" }, ["0"], ["70000"], ["8480", "a", "b"], ["una", "http://127.0.0.1/"], ["una", "http://127.0.0.1/", "x.jpg"], + ["una", "http://127.0.0.1/", "x.png", "10"], ["una", "http://127.0.0.1/", "x.png", "800", "600", "-1"] }) + { + Assert.ThrowsExactly(() => Request.Parse(wrong, root), string.Join(' ', wrong)); + } + + Assert.IsNull(Request.RepositoryRoot(Path.GetPathRoot(Path.GetTempPath())!)); + } + + [TestMethod] + public void TheBrowserHasNoWindowAPrivateProfileAndTheDebugPortOnlyHere() + { + var arguments = Screenshotter.Arguments("profilo", 390, 844, noSandbox: false); + CollectionAssert.Contains(arguments, "--headless"); + CollectionAssert.Contains(arguments, "--user-data-dir=profilo"); + CollectionAssert.Contains(arguments, "--remote-debugging-port=0"); + CollectionAssert.Contains(arguments, "--remote-debugging-address=127.0.0.1"); + CollectionAssert.Contains(arguments, "--no-proxy-server"); + CollectionAssert.Contains(arguments, "--window-size=390,844"); + CollectionAssert.DoesNotContain(arguments, "--no-sandbox"); + Assert.AreEqual("about:blank", arguments[^1]); + CollectionAssert.Contains(Screenshotter.Arguments("profilo", 1440, 900, noSandbox: true), "--no-sandbox"); + + // Only a page target on 127.0.0.1 is driven. + Assert.AreEqual( + "ws://127.0.0.1:9333/devtools/page/A", + Screenshotter.PageDebugger("""[{"type":"service_worker","webSocketDebuggerUrl":"ws://127.0.0.1:9333/devtools/page/W"},{"type":"page","webSocketDebuggerUrl":"ws://127.0.0.1:9333/devtools/page/A"}]""")); + Assert.IsNull(Screenshotter.PageDebugger("""[{"type":"page","webSocketDebuggerUrl":"ws://10.0.0.5:9333/devtools/page/A"}]""")); + Assert.IsNull(Screenshotter.PageDebugger("[]")); + + using var hover = JsonDocument.Parse("""{"hover":[640,212.5],"label":"x"}"""); + Assert.AreEqual((640d, 212.5d), Screenshotter.HoverPoint(hover.RootElement)); + using var none = JsonDocument.Parse("""{"hover":[1]}"""); + Assert.IsNull(Screenshotter.HoverPoint(none.RootElement)); + } + + [TestMethod] + public void NoToolNeedsNode() + { + var tools = Repository.PathOf("tools"); + foreach (var file in Directory.EnumerateFiles(tools, "*", SearchOption.AllDirectories)) + { + var relative = Path.GetRelativePath(tools, file); + if (relative.Split(Path.DirectorySeparatorChar).Any(part => part is "bin" or "obj")) + { + continue; + } + + Assert.IsFalse(Path.GetExtension(file) is ".mjs" or ".cjs" or ".ts", $"script Node: {relative}"); + Assert.AreNotEqual("package.json", Path.GetFileName(file), relative); + if (Path.GetExtension(file) is ".sh" or ".ps1" or ".cmd" or ".bat" or ".cs" or ".csproj") + { + Assert.IsFalse(NodeCommand().IsMatch(File.ReadAllText(file)), $"comando node in {relative}"); + } + } + + Assert.IsFalse(Directory.Exists(Path.Combine(tools, "schermate")), "tools/schermate became tools/Febe.Schermate"); + StringAssert.Contains(File.ReadAllText(Repository.PathOf("Febe.slnx")), ""); + } + + /// «node» or «npx» run as a command (at the start of a line or after a separator), not inside a word. + [GeneratedRegex(@"(?m)(?:^|[;&|(`]\s*|\bexec\s+|\btimeout\s+\d+\s+)(?:node|npx|npm)\s")] + private static partial Regex NodeCommand(); +} diff --git a/tests/Febe.Tests/Web/Support/UiBrowser.cs b/tests/Febe.Tests/Web/Support/UiBrowser.cs index dc7eb1e..ad49027 100644 --- a/tests/Febe.Tests/Web/Support/UiBrowser.cs +++ b/tests/Febe.Tests/Web/Support/UiBrowser.cs @@ -9,7 +9,7 @@ using Febe.Tests.Browser.TestSupport; namespace Febe.Tests.Web.Support; /// -/// A headless Chromium that drives Febe's own interface, like tools/schermate: only addresses on 127.0.0.1, never +/// A headless Chromium that drives Febe's own interface, like tools/Febe.Schermate: only addresses on 127.0.0.1, never /// Instagram (spec §2). It speaks the DevTools protocol directly, without the command policy of Febe's own client, /// because here the tests click, type and run scripts in Febe's pages. Inconclusive when Chromium is missing. /// diff --git a/tools/Febe.Schermate/Febe.Schermate.csproj b/tools/Febe.Schermate/Febe.Schermate.csproj new file mode 100644 index 0000000..0afaf7b --- /dev/null +++ b/tools/Febe.Schermate/Febe.Schermate.csproj @@ -0,0 +1,19 @@ + + + + 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