From e10745b0613e74205135edb9e3ee13a8963526e2 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 15 Oct 2026 23:05:12 +0000 Subject: [PATCH] ci: workflow Forgejo, pacchetto di rilascio e file di deploy - .forgejo/workflows/ci.yml: npm run verify nel container Playwright a ogni push su main e pull request, report come artifact, link esterni non bloccanti - .forgejo/workflows/release.yml: ai tag vX.Y.Z verifica, pacchetto e pubblicazione nella sezione Release con forgejo-release (token FORGEJO_TOKEN) - scripts/package.mjs: zip e tar.gz riproducibili, SHA256SUMS.txt, BUILD-INFO.txt - scripts/check-package.mjs: confronto 1:1 con dist/, impronte, sha256sum -c - scripts/changelog-notes.mjs e release-upload.sh (API REST di Forgejo) - deploy/: nginx.conf.example, gestore PHP del modulo, esempio di deploy automatico (rsync, FTPS, rclone) non attivo Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016zJ9ZWGKvoKoxYwbmnRKdJ --- .forgejo/workflows/ci.yml | 92 ++++++++++++ .forgejo/workflows/release.yml | 104 +++++++++++++ DECISIONS.md | 24 +++ deploy/forgejo-deploy.yml.example | 100 +++++++++++++ deploy/nginx.conf.example | 112 ++++++++++++++ deploy/optional-php-form/contact.php | 189 +++++++++++++++++++++++ scripts/changelog-notes.mjs | 41 ++++- scripts/check-package.mjs | 215 ++++++++++++++++++++++++++- scripts/lib/release.mjs | 74 +++++++++ scripts/package.mjs | 109 +++++++++++++- scripts/release-upload.sh | 64 +++++++- 11 files changed, 1116 insertions(+), 8 deletions(-) create mode 100644 .forgejo/workflows/ci.yml create mode 100644 .forgejo/workflows/release.yml create mode 100644 deploy/forgejo-deploy.yml.example create mode 100644 deploy/nginx.conf.example create mode 100644 deploy/optional-php-form/contact.php create mode 100644 scripts/lib/release.mjs diff --git a/.forgejo/workflows/ci.yml b/.forgejo/workflows/ci.yml new file mode 100644 index 0000000..4d0c80f --- /dev/null +++ b/.forgejo/workflows/ci.yml @@ -0,0 +1,92 @@ +# ============================================================================= +# CI — verifica completa a ogni push su main e a ogni pull request. +# +# RUNNER: `runs-on: docker` è il label più comune di forgejo-runner. Se il runner +# dell'istanza usa un altro label (es. `ubuntu-latest`, `self-hosted`), sostituirlo +# in tutti i job: Impostazioni del repository → Actions → Runner mostra i label disponibili. +# +# CONTAINER: l'immagine Playwright DEVE avere la stessa versione di @playwright/test +# in package.json (oggi 1.56.1). Aggiornando Playwright, aggiornare anche qui e in release.yml. +# +# AZIONI: referenziate con URL completo su code.forgejo.org, così il workflow non dipende +# dall'impostazione DEFAULT_ACTIONS_URL dell'istanza. +# +# SEGRETI: questo workflow non ne usa. Il segreto facoltativo FORGEJO_TOKEN serve solo a +# release.yml (vedi il commento in quel file e il README). +# ============================================================================= +name: CI + +on: + push: + branches: [main] + pull_request: + workflow_dispatch: + +env: + ASTRO_TELEMETRY_DISABLED: '1' + CI: 'true' + +jobs: + verify: + name: Verifica (lint, build, test, Lighthouse) + runs-on: docker # label del runner: adattare (es. ubuntu-latest) + container: + image: mcr.microsoft.com/playwright:v1.56.1-noble # = versione di @playwright/test + timeout-minutes: 30 + steps: + - uses: https://code.forgejo.org/actions/checkout@v4 + + - uses: https://code.forgejo.org/actions/setup-node@v4 + with: + node-version-file: .nvmrc + cache: npm + + - name: Dipendenze + run: npm ci + + - name: npm run verify + run: npm run verify + + - name: Report Playwright (solo in caso di errore) + if: failure() + uses: https://code.forgejo.org/actions/upload-artifact@v3 # usare @v4 se l'istanza Forgejo lo supporta + with: + name: playwright-report + path: playwright-report + retention-days: 14 + + - name: Report Lighthouse + if: always() + uses: https://code.forgejo.org/actions/upload-artifact@v3 + with: + name: lighthouse + path: .lighthouseci + retention-days: 14 + + - name: Artifact dist + uses: https://code.forgejo.org/actions/upload-artifact@v3 + with: + name: dist + path: dist + retention-days: 7 + + external-links: + name: Link esterni (non bloccante) + runs-on: docker # label del runner: adattare (es. ubuntu-latest) + container: + image: node:24 + continue-on-error: true # dipende dalla rete del runner e dai siti esterni + timeout-minutes: 15 + steps: + - uses: https://code.forgejo.org/actions/checkout@v4 + + - name: Dipendenze + run: npm ci + env: + PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD: '1' + + - name: Build + run: npm run build + + - name: Controllo dei link esterni + run: npm run test:links -- --external diff --git a/.forgejo/workflows/release.yml b/.forgejo/workflows/release.yml new file mode 100644 index 0000000..2f412cf --- /dev/null +++ b/.forgejo/workflows/release.yml @@ -0,0 +1,104 @@ +# ============================================================================= +# Release — a ogni tag vX.Y.Z: verifica completa, pacchetto (zip, tar.gz, SHA256SUMS.txt, +# BUILD-INFO.txt) e pubblicazione nella sezione «Release» del repository Forgejo. +# +# Come rilasciare (dettagli nel README): +# 1. aggiornare "version" in package.json e la sezione ## [X.Y.Z] di CHANGELOG.md; +# 2. commit su main; 3. git tag vX.Y.Z && git push origin vX.Y.Z +# Il workflow si ferma se il tag non coincide con la versione di package.json o se manca +# la sezione del CHANGELOG. +# +# RUNNER: `runs-on: docker` è il label più comune di forgejo-runner; sostituirlo se il +# runner dell'istanza ne usa un altro (es. `ubuntu-latest`). +# +# TOKEN: su alcune istanze il token automatico del workflow non può creare release. +# In tal caso creare un access token (Impostazioni utente → Applicazioni → Genera token, +# permesso «write:repository») e salvarlo come segreto del repository con nome +# FORGEJO_TOKEN (Impostazioni del repository → Actions → Segreti). Se il segreto esiste +# viene usato al posto del token automatico. +# ============================================================================= +name: Release + +on: + push: + tags: ['v*.*.*'] + +env: + ASTRO_TELEMETRY_DISABLED: '1' + CI: 'true' + +jobs: + release: + name: Pacchetto e pubblicazione + runs-on: docker # label del runner: adattare (es. ubuntu-latest) + container: + image: mcr.microsoft.com/playwright:v1.56.1-noble # = versione di @playwright/test + timeout-minutes: 40 + steps: + - uses: https://code.forgejo.org/actions/checkout@v4 + with: + fetch-depth: 0 + + - uses: https://code.forgejo.org/actions/setup-node@v4 + with: + node-version-file: .nvmrc + cache: npm + + - name: Data riproducibile (data del commit) + run: echo "SOURCE_DATE_EPOCH=$(git log -1 --format=%ct)" >> "$GITHUB_ENV" + + - name: Dipendenze + run: npm ci + + - name: Controlli preliminari (tag, versione, CHANGELOG) + env: + RELEASE_VERSION: ${{ github.ref_name }} + run: | + node -e 'const v=require("./package.json").version; const t=process.env.RELEASE_VERSION.replace(/^v/,""); if (v!==t) { console.error(`Il tag ${process.env.RELEASE_VERSION} non corrisponde a package.json (${v})`); process.exit(1); }' + node scripts/changelog-notes.mjs "$RELEASE_VERSION" > /dev/null + + - name: npm run verify # nessuna release senza test verdi + run: npm run verify + + - name: npm run package # crea release/ e ne verifica il contenuto + run: npm run package + env: + RELEASE_VERSION: ${{ github.ref_name }} + + - name: Note di rilascio dal CHANGELOG + id: notes + run: | + { + echo 'notes<> "$GITHUB_OUTPUT" + + - name: Pubblica la release su Forgejo + uses: https://code.forgejo.org/actions/forgejo-release@v2 + with: + direction: upload + url: ${{ github.server_url }} + repo: ${{ github.repository }} + tag: ${{ github.ref_name }} + token: ${{ secrets.FORGEJO_TOKEN || secrets.GITHUB_TOKEN }} + release-dir: release # contiene SOLO zip, tar.gz, SHA256SUMS.txt, BUILD-INFO.txt + release-notes: ${{ steps.notes.outputs.notes }} + prerelease: ${{ contains(github.ref_name, '-') }} + verbose: true + + # Alternativa all'action (es. istanze in cui l'action non è disponibile): + # - name: Pubblica la release (API REST) + # env: + # FORGEJO_URL: ${{ github.server_url }} + # FORGEJO_REPO: ${{ github.repository }} + # FORGEJO_TOKEN: ${{ secrets.FORGEJO_TOKEN || secrets.GITHUB_TOKEN }} + # run: scripts/release-upload.sh "${{ github.ref_name }}" release + + - name: Report Playwright (solo in caso di errore) + if: failure() + uses: https://code.forgejo.org/actions/upload-artifact@v3 # usare @v4 se l'istanza Forgejo lo supporta + with: + name: playwright-report + path: playwright-report + retention-days: 14 diff --git a/DECISIONS.md b/DECISIONS.md index 1fb8a5b..c1cec6b 100644 --- a/DECISIONS.md +++ b/DECISIONS.md @@ -262,3 +262,27 @@ Ogni scelta non banale presa durante lo sviluppo (brief §0.4). Formato: data · - **Scelta:** la variabile d'ambiente `CONTACT_FORM_MODE` (`off`, `php`, `endpoint`) ha la precedenza su `studio.ts`; i test del modulo sono stati eseguiti con `CONTACT_FORM_MODE=php npm run build` seguito da Playwright (tutti verdi, insieme a html-validate, axe e conformità). Il README spiega come ripeterli. L'invio a `/contact.php` è simulato nei test (nessun PHP in `astro preview`). - **Alternative scartate:** attivare il modulo per impostazione predefinita (moduli rotti su hosting senza PHP, §10.1). - **Motivazione:** il modulo resta verificato anche se disattivato. + +## D-033 — Pacchetto di rilascio riproducibile e verificato senza dipendenze aggiuntive + +- **Data:** 2026-10-15 +- **Contesto:** §12.4 chiede archivi zip e tar.gz deterministici; §11.7 chiede di estrarli e confrontarli 1:1 con `dist/`. L'immagine CI potrebbe non avere `unzip`. +- **Scelta:** `scripts/package.mjs` usa `archiver` (ZipArchive/TarArchive) con voci ordinate, permessi 0644, fuso orario UTC e data fissa = `SOURCE_DATE_EPOCH` o data dell'ultimo commit (il workflow di release la imposta dal commit del tag). `check-package.mjs` legge lo zip con un lettore minimale in Node (directory centrale, store/deflate, controllo CRC32) ed estrae il tar.gz con `tar` di sistema; confronta percorsi, dimensioni e impronte con `dist/` e verifica `SHA256SUMS.txt` sia in Node sia con `sha256sum -c`. Due esecuzioni consecutive producono archivi identici (verificato). Il pacchetto fallisce se il tag non coincide con `package.json`. +- **Alternative scartate:** `unzip`/`zip` di sistema (non garantiti nel container); librerie di estrazione aggiuntive. +- **Motivazione:** integrità verificabile ovunque, nessuna dipendenza in più. + +## D-034 — Verifica reale di `.htaccess`, configurazione nginx e `contact.php` + +- **Data:** 2026-10-15 +- **Contesto:** l'hosting non è noto; un errore in `.htaccess` o nel gestore PHP si scoprirebbe solo in produzione. +- **Scelta:** durante lo sviluppo sono stati installati localmente Apache 2.4.58, nginx 1.24 e PHP 8.3: il `.htaccess` (con `AllowOverride All`) e `deploy/nginx.conf.example` (con `nginx -t`) sono stati provati servendo `dist/` (redirect HTTPS e /privacy, barra finale, 404, file nascosti, header, cache, compressione); `contact.php` è stato provato con il server integrato di PHP (405, honeypot, validazione, header injection, tempo minimo, limite di 5 invii/ora, e-mail UTF-8 con Reply-To). +- **Alternative scartate:** nessuna verifica (solo revisione del codice). +- **Motivazione:** ridurre il rischio al primo deploy. Le prove non fanno parte di `npm run verify` (richiedono server non presenti nel container CI). + +## D-035 — Workflow Forgejo + +- **Data:** 2026-10-15 +- **Contesto:** §12.2–12.3. +- **Scelta:** `ci.yml` (push su main, pull request, avvio manuale) con `npm run verify` nel container Playwright 1.56.1 e Node da `.nvmrc`, report Playwright e Lighthouse come artifact, job dei link esterni non bloccante; `release.yml` sui tag `v*.*.*` con controllo preliminare tag/versione/CHANGELOG, `SOURCE_DATE_EPOCH` dal commit, `verify`, `package`, note dal CHANGELOG e `forgejo-release@v2` (token `FORGEJO_TOKEN` se presente, altrimenti quello automatico); alternativa via API REST (`scripts/release-upload.sh`) commentata. Telemetria di Astro disattivata (`ASTRO_TELEMETRY_DISABLED`). Il deploy automatico resta un esempio non attivo (`deploy/forgejo-deploy.yml.example`, evento `release: published`, varianti rsync/FTPS/rclone). +- **Alternative scartate:** `workflow_run` per il deploy (non supportato da Forgejo Actions). +- **Motivazione:** nessuna release senza test verdi; workflow indipendenti dalla configurazione dell'istanza. diff --git a/deploy/forgejo-deploy.yml.example b/deploy/forgejo-deploy.yml.example new file mode 100644 index 0000000..0d26858 --- /dev/null +++ b/deploy/forgejo-deploy.yml.example @@ -0,0 +1,100 @@ +# ============================================================================= +# DEPLOY AUTOMATICO (DISATTIVATO) — esempio per Forgejo Actions. +# +# Per attivarlo: copiare questo file in .forgejo/workflows/deploy.yml, scegliere UNA delle +# varianti qui sotto (rsync su SSH, FTPS con lftp, object storage con rclone), decommentarla +# e creare i segreti del repository indicati (Impostazioni → Actions → Segreti). +# Istruzioni complete in docs/DEPLOY.md, sezione «Deploy automatico». +# +# Si avvia quando una release viene pubblicata (dal workflow release.yml) oppure a mano +# (workflow_dispatch, indicando il tag). Pubblica il pacchetto della release, già verificato. +# RUNNER: `runs-on: docker`, adattare il label come negli altri workflow. +# ============================================================================= +name: Deploy + +on: + release: + types: [published] + workflow_dispatch: + inputs: + tag: + description: 'Tag della release da pubblicare (es. v1.0.0)' + required: true + +jobs: + deploy: + runs-on: docker # label del runner: adattare (es. ubuntu-latest) + container: + image: debian:stable-slim + environment: produzione + steps: + - name: Strumenti + run: apt-get update && apt-get install -y --no-install-recommends ca-certificates curl unzip + # aggiungere: rsync openssh-client (variante A) · lftp (variante B) · rclone (variante C) + + - name: Scarica il pacchetto della release + env: + TAG: ${{ github.event.release.tag_name || inputs.tag }} + TOKEN: ${{ secrets.FORGEJO_TOKEN || secrets.GITHUB_TOKEN }} + run: | + set -eu + VERSION="${TAG#v}" + BASE="${{ github.server_url }}/${{ github.repository }}/releases/download/${TAG}" + curl -fsSL -H "Authorization: token ${TOKEN}" -o pacchetto.zip "${BASE}/sito-studio-grasso-v${VERSION}.zip" + curl -fsSL -H "Authorization: token ${TOKEN}" -o SHA256SUMS.txt "${BASE}/SHA256SUMS.txt" + grep " sito-studio-grasso-v${VERSION}.zip$" SHA256SUMS.txt | sed "s/sito-studio-grasso-v${VERSION}.zip/pacchetto.zip/" | sha256sum -c - + mkdir sito && unzip -q pacchetto.zip -d sito + + # --------------------------------------------------------------------------- + # Variante A — rsync su SSH (VPS o hosting con accesso SSH) + # Segreti: DEPLOY_HOST, DEPLOY_USER, DEPLOY_PATH, DEPLOY_SSH_KEY (chiave privata) + # --------------------------------------------------------------------------- + # - name: Pubblica con rsync + # env: + # DEPLOY_HOST: ${{ secrets.DEPLOY_HOST }} + # DEPLOY_USER: ${{ secrets.DEPLOY_USER }} + # DEPLOY_PATH: ${{ secrets.DEPLOY_PATH }} + # DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }} + # run: | + # set -eu + # mkdir -p ~/.ssh && chmod 700 ~/.ssh + # printf '%s\n' "$DEPLOY_SSH_KEY" > ~/.ssh/id_deploy && chmod 600 ~/.ssh/id_deploy + # ssh-keyscan -H "$DEPLOY_HOST" >> ~/.ssh/known_hosts + # rsync -az --delete --exclude 'contact.php' -e "ssh -i ~/.ssh/id_deploy" sito/ "$DEPLOY_USER@$DEPLOY_HOST:$DEPLOY_PATH/" + + # --------------------------------------------------------------------------- + # Variante B — FTPS con lftp (hosting condivisi: cPanel, Plesk, Aruba, Register…) + # Segreti: FTP_HOST, FTP_USER, FTP_PASSWORD, FTP_PATH (es. /public_html) + # --------------------------------------------------------------------------- + # - name: Pubblica via FTPS + # env: + # FTP_HOST: ${{ secrets.FTP_HOST }} + # FTP_USER: ${{ secrets.FTP_USER }} + # FTP_PASSWORD: ${{ secrets.FTP_PASSWORD }} + # FTP_PATH: ${{ secrets.FTP_PATH }} + # run: | + # lftp -u "$FTP_USER","$FTP_PASSWORD" -e "set ftp:ssl-force true; set ssl:verify-certificate yes; \ + # mirror -R --delete --verbose --exclude-glob contact.php sito/ $FTP_PATH; quit" "$FTP_HOST" + + # --------------------------------------------------------------------------- + # Variante C — object storage S3 compatibile con rclone + # Segreti: RCLONE_CONFIG (contenuto di rclone.conf con il remote «sito»), RCLONE_DEST (es. sito:bucket) + # --------------------------------------------------------------------------- + # - name: Pubblica su object storage + # env: + # RCLONE_CONFIG_CONTENT: ${{ secrets.RCLONE_CONFIG }} + # RCLONE_DEST: ${{ secrets.RCLONE_DEST }} + # run: | + # mkdir -p ~/.config/rclone && printf '%s\n' "$RCLONE_CONFIG_CONTENT" > ~/.config/rclone/rclone.conf + # rclone sync sito/ "$RCLONE_DEST" --checksum --exclude '.htaccess' + + - name: Controllo dopo la pubblicazione + env: + SITE_URL: ${{ vars.SITE_URL || 'https://www.grassoezio.it' }} + run: | + set -eu + for p in / /servizi/ /contatti/ /sitemap-index.xml /robots.txt; do + code=$(curl -s -o /dev/null -w '%{http_code}' "${SITE_URL}${p}") + echo "${p} → ${code}"; [ "$code" = 200 ] + done + code=$(curl -s -o /dev/null -w '%{http_code}' "${SITE_URL}/pagina-inesistente/"); echo "404 → ${code}"; [ "$code" = 404 ] diff --git a/deploy/nginx.conf.example b/deploy/nginx.conf.example new file mode 100644 index 0000000..5b6ab67 --- /dev/null +++ b/deploy/nginx.conf.example @@ -0,0 +1,112 @@ +# ============================================================================= +# Studio Grasso — configurazione nginx di esempio (equivalente a public/.htaccess) +# ----------------------------------------------------------------------------- +# 1. Estrarre il pacchetto sito-studio-grasso-vX.Y.Z.tar.gz in /var/www/studio-grasso +# 2. Copiare questo file in /etc/nginx/sites-available/studio-grasso, adattare +# server_name e certificati, attivarlo e ricaricare: nginx -t && systemctl reload nginx +# 3. Il file .htaccess incluso nel pacchetto è ignorato da nginx (ed è bloccato qui sotto). +# Richiede nginx ≥ 1.25.1 per la direttiva «http2 on;»; con versioni precedenti eliminarla e +# scrivere «listen 443 ssl http2;». Configurazione verificata con `nginx -t`. +# ============================================================================= + +# HTTP → HTTPS +server { + listen 80; + listen [::]:80; + server_name www.grassoezio.it grassoezio.it; + return 301 https://www.grassoezio.it$request_uri; +} + +# Dominio senza «www» → con «www» (coerente con SITE_URL; invertire se si usa il dominio senza www) +server { + listen 443 ssl; + listen [::]:443 ssl; + http2 on; + server_name grassoezio.it; + ssl_certificate /etc/letsencrypt/live/grassoezio.it/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/grassoezio.it/privkey.pem; + return 301 https://www.grassoezio.it$request_uri; +} + +server { + listen 443 ssl; + listen [::]:443 ssl; + http2 on; + server_name www.grassoezio.it; + + ssl_certificate /etc/letsencrypt/live/grassoezio.it/fullchain.pem; + ssl_certificate_key /etc/letsencrypt/live/grassoezio.it/privkey.pem; + + root /var/www/studio-grasso; + index index.html; + charset utf-8; + server_tokens off; + + # --- header di sicurezza (come .htaccess, brief §9.4) --- + add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; font-src 'self'; frame-src https://www.google.com; form-action 'self'; base-uri 'self'; frame-ancestors 'self'" always; + add_header X-Content-Type-Options "nosniff" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header Permissions-Policy "accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), usb=(), browsing-topics=()" always; + add_header Cross-Origin-Opener-Policy "same-origin" always; + # HSTS: attivare solo quando HTTPS è certo su tutto il dominio. + # add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + + # --- compressione --- + gzip on; + gzip_vary on; + gzip_comp_level 6; + gzip_types text/css text/plain text/xml application/xml application/javascript image/svg+xml application/ld+json; + + # --- pagine e 404 --- + # /studio → /studio/ è automatico (try_files su una cartella con index.html). + location / { + try_files $uri $uri/ =404; + add_header Cache-Control "no-cache"; + # ripetuti perché add_header in un blocco location sostituisce quelli del server + add_header Content-Security-Policy "default-src 'self'; img-src 'self' data:; style-src 'self' 'unsafe-inline'; script-src 'self'; font-src 'self'; frame-src https://www.google.com; form-action 'self'; base-uri 'self'; frame-ancestors 'self'" always; + add_header X-Content-Type-Options "nosniff" always; + add_header Referrer-Policy "strict-origin-when-cross-origin" always; + add_header X-Frame-Options "SAMEORIGIN" always; + add_header Permissions-Policy "accelerometer=(), autoplay=(), camera=(), display-capture=(), geolocation=(), gyroscope=(), magnetometer=(), microphone=(), midi=(), payment=(), usb=(), browsing-topics=()" always; + add_header Cross-Origin-Opener-Policy "same-origin" always; + } + error_page 404 /404.html; + location = /404.html { + internal; + } + + # vecchio indirizzo della privacy policy + location = /privacy { + return 301 /privacy-policy/; + } + + # file con impronta nel nome (cartella /_astro/): cache di un anno + location /_astro/ { + add_header Cache-Control "public, max-age=31536000, immutable"; + add_header X-Content-Type-Options "nosniff" always; + try_files $uri =404; + } + + # icone, immagine di condivisione, sitemap, robots.txt: una settimana + location ~* ^/(favicon\.(ico|svg)|apple-touch-icon\.png|og-default\.png|robots\.txt|sitemap.*\.xml)$ { + add_header Cache-Control "public, max-age=604800"; + add_header X-Content-Type-Options "nosniff" always; + } + + # file nascosti (tranne /.well-known/ per i certificati) e mappe dei sorgenti + location ~ /\.(?!well-known/) { + deny all; + return 404; + } + location ~* \.map$ { + deny all; + return 404; + } + + # Modulo di contatto in PHP (solo con contactForm.mode = "php", vedi docs/DEPLOY.md): + # location = /contact.php { + # include snippets/fastcgi-php.conf; + # fastcgi_pass unix:/run/php/php8.3-fpm.sock; + # } +} diff --git a/deploy/optional-php-form/contact.php b/deploy/optional-php-form/contact.php new file mode 100644 index 0000000..e2f6e64 --- /dev/null +++ b/deploy/optional-php-form/contact.php @@ -0,0 +1,189 @@ + 120, 'email' => 160, 'telefono' => 25, 'oggetto' => 160, 'messaggio' => 5000]; + +// ---------------------------------------------------------------- funzioni +function campo(string $nome): string +{ + $valore = $_POST[$nome] ?? ''; + return is_string($valore) ? trim($valore) : ''; +} + +function h(string $testo): string +{ + return htmlspecialchars($testo, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'); +} + +/** Pagina d'errore semplice, in italiano, con link per tornare al modulo. */ +function errore(string $messaggio, int $stato = 400): void +{ + http_response_code($stato); + header('Content-Type: text/html; charset=utf-8'); + header('Cache-Control: no-store'); + header('X-Robots-Tag: noindex'); + echo '' + . '' + . 'Richiesta non inviata — Studio Grasso' + . '' + . '

Richiesta non inviata

' . h($messaggio) . '

' + . '

Torna alla pagina Contatti oppure scrivi a ' + . '' . h(DESTINATARIO) . '.

'; + exit; +} + +function vai(string $percorso): void +{ + header('Location: ' . $percorso, true, 303); + exit; +} + +/** Limite di invii per IP: file temporaneo con l'impronta (non reversibile) dell'indirizzo. */ +function limiteSuperato(string $ip): bool +{ + $file = sys_get_temp_dir() . '/studio-grasso-form-' . hash('sha256', $ip . '|' . __FILE__); + $adesso = time(); + $invii = []; + $fp = @fopen($file, 'c+'); + if ($fp === false) { + return false; // se il file non è scrivibile non si blocca l'utente + } + flock($fp, LOCK_EX); + $dati = stream_get_contents($fp); + if (is_string($dati) && $dati !== '') { + $decodificati = json_decode($dati, true); + if (is_array($decodificati)) { + $invii = array_values(array_filter($decodificati, static function ($t) use ($adesso) { + return is_int($t) && $t > $adesso - 3600; + })); + } + } + $superato = count($invii) >= MAX_INVII_ORA; + if (!$superato) { + $invii[] = $adesso; + } + ftruncate($fp, 0); + rewind($fp); + fwrite($fp, (string) json_encode($invii)); + fflush($fp); + flock($fp, LOCK_UN); + fclose($fp); + return $superato; +} + +/** Oggetto codificato secondo RFC 2047 (lettere accentate). */ +function oggettoMime(string $oggetto): string +{ + return '=?UTF-8?B?' . base64_encode($oggetto) . '?='; +} + +// ---------------------------------------------------------------- richiesta +if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'POST') { + header('Allow: POST'); + errore('Il modulo va inviato dalla pagina Contatti.', 405); +} + +// 1) campo trappola: compilato solo dai programmi automatici → si finge l'invio riuscito +if (campo('sito_web') !== '') { + vai(PAGINA_GRAZIE); +} + +// 2) tempo minimo di compilazione (il campo ts è valorizzato via JavaScript all'apertura della +// pagina; senza JavaScript manca e il controllo non si applica) +$ts = campo('ts'); +if ($ts !== '' && ctype_digit($ts)) { + $trascorsi = (int) floor(microtime(true) * 1000) - (int) $ts; + if ($trascorsi >= 0 && $trascorsi < TEMPO_MINIMO_MS) { + errore('Il modulo è stato inviato troppo rapidamente. Attendi qualche secondo e riprova.', 429); + } +} + +// 3) validazione +$dati = []; +foreach (LUNGHEZZE as $nome => $max) { + $valore = campo($nome); + if ($valore === '') { + errore('Compila tutti i campi obbligatori del modulo.'); + } + if (mb_strlen($valore, 'UTF-8') > $max) { + errore('Uno dei campi supera la lunghezza consentita.'); + } + $dati[$nome] = $valore; +} +foreach (['nome', 'email', 'telefono', 'oggetto'] as $nome) { + if (preg_match('/[\r\n]/', $dati[$nome])) { + errore('Uno dei campi contiene caratteri non consentiti.'); + } +} +if (filter_var($dati['email'], FILTER_VALIDATE_EMAIL) === false) { + errore("L'indirizzo e-mail non è valido."); +} +if (!preg_match('/^[0-9 +().\/-]{6,25}$/', $dati['telefono'])) { + errore('Il numero di telefono non è valido.'); +} +if (mb_strlen($dati['messaggio'], 'UTF-8') < 10) { + errore('Il messaggio è troppo breve.'); +} +if (campo('privacy') !== '1') { + errore("Per inviare la richiesta è necessario accettare l'informativa sulla privacy."); +} + +// 4) limite di invii per IP +if (limiteSuperato((string) ($_SERVER['REMOTE_ADDR'] ?? ''))) { + errore('Hai inviato troppe richieste in poco tempo. Riprova più tardi o scrivici per e-mail.', 429); +} + +// 5) invio +$corpo = "Nuova richiesta dal modulo di contatto del sito.\n\n" + . 'Nome e cognome: ' . $dati['nome'] . "\n" + . 'E-mail: ' . $dati['email'] . "\n" + . 'Telefono: ' . $dati['telefono'] . "\n" + . 'Oggetto: ' . $dati['oggetto'] . "\n\n" + . "Messaggio:\n" . $dati['messaggio'] . "\n\n" + . "--\nConsenso all'informativa sulla privacy: sì\n" + . 'Data: ' . date('d/m/Y H:i') . "\n"; + +$intestazioni = [ + 'From' => oggettoMime(NOME_MITTENTE) . ' <' . MITTENTE . '>', + 'Reply-To' => $dati['email'], + 'MIME-Version' => '1.0', + 'Content-Type' => 'text/plain; charset=UTF-8', + 'Content-Transfer-Encoding' => '8bit', + 'X-Mailer' => 'studio-grasso-form', +]; + +$inviato = mail(DESTINATARIO, oggettoMime(PREFISSO_OGGETTO . $dati['oggetto']), $corpo, $intestazioni); +if (!$inviato) { + errore('Non è stato possibile inviare la richiesta per un problema tecnico.', 500); +} + +vai(PAGINA_GRAZIE); diff --git a/scripts/changelog-notes.mjs b/scripts/changelog-notes.mjs index 2f65bb5..282332e 100644 --- a/scripts/changelog-notes.mjs +++ b/scripts/changelog-notes.mjs @@ -1,2 +1,39 @@ -// Segnaposto della fase 0: l'implementazione completa arriva nelle fasi successive (vedi DECISIONS.md). -console.log('scripts/changelog-notes.mjs: non ancora implementato (fase 0).'); +#!/usr/bin/env node +/** + * Stampa la sezione di CHANGELOG.md relativa a una versione: diventa il testo della release. + * Uso: `node scripts/changelog-notes.mjs v1.0.0` (oppure 1.0.0). Esce con codice 1 se la + * sezione non esiste, così non si pubblica una release senza note. + */ +import { readFileSync } from 'node:fs'; +import { resolve } from 'node:path'; + +const arg = (process.argv[2] ?? process.env.RELEASE_VERSION ?? '').replace(/^refs\/tags\//, ''); +const version = arg.replace(/^v/, ''); +if (!/^\d+\.\d+\.\d+/.test(version)) { + console.error('Uso: node scripts/changelog-notes.mjs vX.Y.Z'); + process.exit(1); +} + +const changelog = readFileSync(resolve(import.meta.dirname, '..', 'CHANGELOG.md'), 'utf8'); +const lines = changelog.split(/\r?\n/); +const escaped = version.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +const start = lines.findIndex((l) => new RegExp(`^## \\[${escaped}\\]`).test(l)); +if (start < 0) { + console.error( + `Nessuna sezione «## [${version}]» in CHANGELOG.md: aggiungerla prima del rilascio.`, + ); + process.exit(1); +} +let end = lines.findIndex((l, i) => i > start && /^## \[/.test(l)); +if (end < 0) end = lines.length; +// i riferimenti in fondo al file ([1.0.0]: https://…) non fanno parte delle note +const body = lines + .slice(start + 1, end) + .filter((l) => !/^\[[^\]]+\]:\s*\S+/.test(l)) + .join('\n') + .trim(); +if (!body) { + console.error(`La sezione ${version} di CHANGELOG.md è vuota.`); + process.exit(1); +} +process.stdout.write(`${body}\n`); diff --git a/scripts/check-package.mjs b/scripts/check-package.mjs index 4d57af8..4357122 100644 --- a/scripts/check-package.mjs +++ b/scripts/check-package.mjs @@ -1,2 +1,213 @@ -// Segnaposto della fase 0: l'implementazione completa arriva nelle fasi successive (vedi DECISIONS.md). -console.log('scripts/check-package.mjs: non ancora implementato (fase 0).'); +#!/usr/bin/env node +/** + * Integrità del pacchetto di rilascio (brief §11.7), da eseguire dopo scripts/package.mjs: + * + * - in release/ ci sono solo zip, tar.gz, SHA256SUMS.txt e BUILD-INFO.txt, con i nomi attesi; + * - le impronte di SHA256SUMS.txt sono corrette (anche con `sha256sum -c`, se disponibile); + * - zip e tar.gz, estratti in una cartella temporanea, contengono esattamente i file di dist/ + * (stessi percorsi, dimensioni e contenuto), alla radice, con .htaccess e tutte le pagine; + * - lo zip non supera 5 MB; BUILD-INFO.txt riporta versione, commit e data. + */ +import { execFileSync, spawnSync } from 'node:child_process'; +import { createHash } from 'node:crypto'; +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { crc32, inflateRawSync } from 'node:zlib'; +import { readSitemapPaths } from './lib/pages.mjs'; +import { archiveNames, distDir, listFiles, releaseDir, resolveVersion } from './lib/release.mjs'; + +const MAX_ZIP = 5 * 1024 * 1024; +const errors = []; +const fail = (msg) => errors.push(msg); +const sha256 = (buf) => createHash('sha256').update(buf).digest('hex'); + +/** Lettore ZIP minimale (directory centrale + store/deflate), senza dipendenze esterne. */ +function readZip(file) { + const buf = readFileSync(file); + let eocd = -1; + for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 65535); i--) { + if (buf.readUInt32LE(i) === 0x06054b50) { + eocd = i; + break; + } + } + if (eocd < 0) throw new Error('fine della directory centrale non trovata (zip danneggiato)'); + const count = buf.readUInt16LE(eocd + 10); + let p = buf.readUInt32LE(eocd + 16); + const entries = new Map(); + for (let i = 0; i < count; i++) { + if (buf.readUInt32LE(p) !== 0x02014b50) + throw new Error('voce della directory centrale non valida'); + const method = buf.readUInt16LE(p + 10); + const crc = buf.readUInt32LE(p + 16); + const compSize = buf.readUInt32LE(p + 20); + const size = buf.readUInt32LE(p + 24); + const nameLen = buf.readUInt16LE(p + 28); + const extraLen = buf.readUInt16LE(p + 30); + const commentLen = buf.readUInt16LE(p + 32); + const localOffset = buf.readUInt32LE(p + 42); + const name = buf.toString('utf8', p + 46, p + 46 + nameLen); + p += 46 + nameLen + extraLen + commentLen; + if (name.endsWith('/')) continue; // cartella + const lNameLen = buf.readUInt16LE(localOffset + 26); + const lExtraLen = buf.readUInt16LE(localOffset + 28); + const start = localOffset + 30 + lNameLen + lExtraLen; + const raw = buf.subarray(start, start + compSize); + const data = method === 0 ? raw : method === 8 ? inflateRawSync(raw) : null; + if (!data) throw new Error(`metodo di compressione ${method} non supportato (${name})`); + if (data.length !== size) throw new Error(`dimensione errata per ${name}`); + if (crc32(data) !== crc) throw new Error(`CRC errato per ${name}`); + entries.set(name, data); + } + return entries; +} + +/** Estrazione del tar.gz con `tar` di sistema in una cartella temporanea. */ +function readTarGz(file) { + const dir = mkdtempSync(join(tmpdir(), 'sito-studio-grasso-')); + try { + execFileSync('tar', ['-xzf', file, '-C', dir]); + const entries = new Map(); + for (const rel of listAll(dir)) entries.set(rel, readFileSync(join(dir, rel))); + return entries; + } finally { + rmSync(dir, { recursive: true, force: true }); + } +} + +function listAll(dir, base = '') { + const out = []; + for (const e of readdirSync(join(dir, base), { withFileTypes: true })) { + const rel = base ? `${base}/${e.name}` : e.name; + if (e.isDirectory()) out.push(...listAll(dir, rel)); + else out.push(rel); + } + return out.sort(); +} + +function compareWithDist(label, entries, expected) { + const names = [...entries.keys()].sort(); + const missing = expected.filter((f) => !entries.has(f)); + const extra = names.filter((f) => !expected.includes(f)); + if (missing.length) fail(`${label}: file di dist/ mancanti nell'archivio: ${missing.join(', ')}`); + if (extra.length) fail(`${label}: file in più rispetto a dist/: ${extra.join(', ')}`); + for (const f of expected) { + const data = entries.get(f); + if (!data) continue; + const original = readFileSync(join(distDir, f)); + if (data.length !== original.length) fail(`${label}: dimensione diversa per ${f}`); + else if (sha256(data) !== sha256(original)) fail(`${label}: contenuto diverso per ${f}`); + } + if ([...entries.keys()].some((f) => f.startsWith('dist/'))) { + fail(`${label}: i file devono stare alla radice dell'archivio, non in una cartella dist/`); + } + const required = [ + 'index.html', + '404.html', + '.htaccess', + 'robots.txt', + 'sitemap-index.xml', + 'favicon.svg', + ]; + for (const f of required) if (!entries.has(f)) fail(`${label}: manca ${f} alla radice`); + for (const p of readSitemapPaths(distDir)) { + const f = p === '/' ? 'index.html' : `${p.replace(/^\//, '')}index.html`; + if (!entries.has(f)) fail(`${label}: manca la pagina ${p} (${f})`); + } + if ([...entries.keys()].some((f) => f.endsWith('.map'))) fail(`${label}: contiene file .map`); +} + +/* ------------------------------------------------------------------ verifica */ + +let version; +try { + version = resolveVersion(); +} catch (e) { + console.error(`✘ ${e.message}`); + process.exit(1); +} +const names = archiveNames(version); +const expectedRelease = [names.zip, names.tgz, 'SHA256SUMS.txt', 'BUILD-INFO.txt'].sort(); + +if (!existsSync(releaseDir)) { + console.error('✘ release/ assente: eseguire `npm run package`.'); + process.exit(1); +} +const present = readdirSync(releaseDir).sort(); +for (const f of expectedRelease) if (!present.includes(f)) fail(`release/: manca ${f}`); +for (const f of present) + if (!expectedRelease.includes(f)) + fail(`release/: file inatteso ${f} (la cartella deve contenere solo il pacchetto)`); + +// impronte +const sumsFile = join(releaseDir, 'SHA256SUMS.txt'); +if (existsSync(sumsFile)) { + const lines = readFileSync(sumsFile, 'utf8').trim().split('\n'); + const listed = new Set(); + for (const line of lines) { + const m = line.match(/^([0-9a-f]{64}) {2}(.+)$/); + if (!m) { + fail(`SHA256SUMS.txt: riga non valida «${line}»`); + continue; + } + listed.add(m[2]); + const target = join(releaseDir, m[2]); + if (!existsSync(target)) fail(`SHA256SUMS.txt: il file ${m[2]} non esiste`); + else if (sha256(readFileSync(target)) !== m[1]) + fail(`SHA256SUMS.txt: impronta errata per ${m[2]}`); + } + for (const f of [names.zip, names.tgz]) if (!listed.has(f)) fail(`SHA256SUMS.txt: manca ${f}`); + const tool = spawnSync('sha256sum', ['-c', 'SHA256SUMS.txt'], { + cwd: releaseDir, + encoding: 'utf8', + }); + if (tool.error) + console.log(' (sha256sum non disponibile: impronte verificate solo con Node.js)'); + else if (tool.status !== 0) fail(`sha256sum -c non superato:\n${tool.stdout}${tool.stderr}`); + else console.log(` sha256sum -c: ${tool.stdout.trim().split('\n').join(' · ')}`); +} + +// contenuto degli archivi +const expected = listFiles(distDir); +const zipPath = join(releaseDir, names.zip); +const tgzPath = join(releaseDir, names.tgz); +if (existsSync(zipPath)) { + const size = statSync(zipPath).size; + if (size > MAX_ZIP) + fail(`${names.zip}: ${(size / 1048576).toFixed(2)} MB oltre il limite di 5 MB`); + try { + compareWithDist(names.zip, readZip(zipPath), expected); + } catch (e) { + fail(`${names.zip}: ${e.message}`); + } +} +if (existsSync(tgzPath)) { + try { + compareWithDist(names.tgz, readTarGz(tgzPath), expected); + } catch (e) { + fail(`${names.tgz}: ${e.message}`); + } +} + +// BUILD-INFO +const infoFile = join(releaseDir, 'BUILD-INFO.txt'); +if (existsSync(infoFile)) { + const info = readFileSync(infoFile, 'utf8'); + if (!info.includes(`Versione: ${version}`)) fail('BUILD-INFO.txt: manca «Versione»'); + if (!/^Commit: [0-9a-f]{7,40}$/m.test(info)) fail('BUILD-INFO.txt: manca l’hash del commit'); + if (!/^Data: \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/m.test(info)) + fail('BUILD-INFO.txt: manca la data ISO'); + if (!/^Node\.js: v\d+/m.test(info) || !/^Astro: \d+/m.test(info)) + fail('BUILD-INFO.txt: mancano le versioni di Node.js e Astro'); +} + +if (errors.length) { + console.error(`✘ Pacchetto v${version}: ${errors.length} errori`); + for (const e of errors) console.error(` - ${e}`); + process.exit(1); +} +const zipKb = (statSync(zipPath).size / 1024).toFixed(1); +console.log( + `✔ Pacchetto v${version} verificato: ${expected.length} file identici a dist/ in zip (${zipKb} KB) e tar.gz, impronte corrette.`, +); diff --git a/scripts/lib/release.mjs b/scripts/lib/release.mjs new file mode 100644 index 0000000..9889d5f --- /dev/null +++ b/scripts/lib/release.mjs @@ -0,0 +1,74 @@ +/** + * Utilità condivise da package.mjs e check-package.mjs. + */ +import { execFileSync } from 'node:child_process'; +import { readFileSync, readdirSync } from 'node:fs'; +import { join, resolve } from 'node:path'; + +export const root = resolve(import.meta.dirname, '..', '..'); +export const distDir = resolve(root, 'dist'); +export const releaseDir = resolve(root, 'release'); +export const ARCHIVE_PREFIX = 'sito-studio-grasso'; + +/** File esclusi dal pacchetto: mappe dei sorgenti e file di sistema. */ +const EXCLUDED = [/\.map$/, /(^|\/)\.DS_Store$/, /(^|\/)Thumbs\.db$/i, /(^|\/)desktop\.ini$/i]; +export const isExcluded = (rel) => EXCLUDED.some((re) => re.test(rel)); + +/** Versione da RELEASE_VERSION (es. «v1.0.0», dal tag) oppure da package.json. */ +export function resolveVersion() { + const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8')); + const fromEnv = (process.env.RELEASE_VERSION ?? '').trim().replace(/^refs\/tags\//, ''); + const version = (fromEnv || pkg.version).replace(/^v/, ''); + if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(version)) { + throw new Error(`Versione non valida «${version}»: atteso X.Y.Z (tag vX.Y.Z).`); + } + if (fromEnv && version !== pkg.version) { + throw new Error( + `Il tag (${fromEnv}) non corrisponde alla versione di package.json (${pkg.version}): ` + + 'aggiornare package.json e CHANGELOG.md prima di creare il tag.', + ); + } + return version; +} + +export const archiveNames = (version) => ({ + zip: `${ARCHIVE_PREFIX}-v${version}.zip`, + tgz: `${ARCHIVE_PREFIX}-v${version}.tar.gz`, +}); + +/** Elenco ordinato dei file di una cartella (percorsi relativi con «/»), esclusioni applicate. */ +export function listFiles(dir, base = '') { + const out = []; + for (const entry of readdirSync(join(dir, base), { withFileTypes: true })) { + const rel = base ? `${base}/${entry.name}` : entry.name; + if (entry.isDirectory()) out.push(...listFiles(dir, rel)); + else if (entry.isFile() && !isExcluded(rel)) out.push(rel); + } + return out.sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)); +} + +export function gitCommit() { + if (process.env.GITHUB_SHA) return process.env.GITHUB_SHA; + try { + return execFileSync('git', ['rev-parse', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim(); + } catch { + return 'sconosciuto'; + } +} + +/** + * Istante fisso per le date dei file negli archivi (archivi riproducibili): SOURCE_DATE_EPOCH, + * altrimenti la data dell'ultimo commit, altrimenti il 1° gennaio 1980. + */ +export function archiveEpoch() { + const fromEnv = Number(process.env.SOURCE_DATE_EPOCH); + if (Number.isFinite(fromEnv) && fromEnv > 0) return fromEnv; + try { + const ct = execFileSync('git', ['log', '-1', '--format=%ct'], { cwd: root, encoding: 'utf8' }); + const n = Number(ct.trim()); + if (Number.isFinite(n) && n > 0) return n; + } catch { + // non è un repository git + } + return 315532800; +} diff --git a/scripts/package.mjs b/scripts/package.mjs index a91b848..e5c2325 100644 --- a/scripts/package.mjs +++ b/scripts/package.mjs @@ -1,2 +1,107 @@ -// Segnaposto della fase 0: l'implementazione completa arriva nelle fasi successive (vedi DECISIONS.md). -console.log('scripts/package.mjs: non ancora implementato (fase 0).'); +#!/usr/bin/env node +/** + * Pacchetto di rilascio (brief §12.4). Da `dist/` crea in `release/`: + * + * sito-studio-grasso-v.zip per i pannelli di hosting (cPanel, Plesk, …) + * sito-studio-grasso-v.tar.gz per server Linux/SSH, nginx, object storage + * SHA256SUMS.txt impronte SHA-256 (verificabili con `sha256sum -c`) + * BUILD-INFO.txt versione, commit, data, Node, Astro + * + * Il contenuto di dist/ è alla radice degli archivi (nessuna cartella di primo livello), con + * `.htaccess`. Voci ordinate e date fisse: a parità di dist/ gli archivi sono identici. + * Versione: variabile RELEASE_VERSION (tag vX.Y.Z) oppure package.json. + */ +process.env.TZ = 'UTC'; + +import { createHash } from 'node:crypto'; +import { createReadStream, createWriteStream, existsSync, readFileSync, statSync } from 'node:fs'; +import { mkdir, rm, writeFile } from 'node:fs/promises'; +import { join, resolve } from 'node:path'; +import { pipeline } from 'node:stream/promises'; +import { TarArchive, ZipArchive } from 'archiver'; +import { + archiveEpoch, + archiveNames, + distDir, + gitCommit, + listFiles, + releaseDir, + resolveVersion, + root, +} from './lib/release.mjs'; + +if (!existsSync(join(distDir, 'index.html'))) { + console.error('✘ dist/ assente o incompleta: eseguire prima `npm run build`.'); + process.exit(1); +} + +let version; +try { + version = resolveVersion(); +} catch (e) { + console.error(`✘ ${e.message}`); + process.exit(1); +} +const names = archiveNames(version); +const files = listFiles(distDir); +const date = new Date(archiveEpoch() * 1000); + +await rm(releaseDir, { recursive: true, force: true }); +await mkdir(releaseDir, { recursive: true }); + +async function build(archive, target) { + const output = createWriteStream(target); + const done = pipeline(archive, output); + archive.on('warning', (err) => { + throw err; + }); + for (const rel of files) { + // contenuto letto in memoria: l'ordine delle voci resta quello dell'elenco ordinato + archive.append(readFileSync(join(distDir, rel)), { name: rel, date, mode: 0o644 }); + } + await archive.finalize(); + await done; +} + +await build(new ZipArchive({ zlib: { level: 9 } }), join(releaseDir, names.zip)); +await build(new TarArchive({ gzip: true, gzipOptions: { level: 9 } }), join(releaseDir, names.tgz)); + +const sha256 = (file) => + new Promise((ok, ko) => { + const hash = createHash('sha256'); + createReadStream(file) + .on('data', (d) => hash.update(d)) + .on('end', () => ok(hash.digest('hex'))) + .on('error', ko); + }); + +const pkgLock = JSON.parse(readFileSync(resolve(root, 'package-lock.json'), 'utf8')); +const astroVersion = pkgLock.packages?.['node_modules/astro']?.version ?? 'sconosciuta'; +const info = [ + 'Sito web dello Studio Grasso — Studio Tributario e Societario', + `Versione: ${version}`, + `Commit: ${gitCommit()}`, + `Data: ${new Date().toISOString()}`, + `Data dei file negli archivi: ${date.toISOString()}`, + `Node.js: ${process.version}`, + `Astro: ${astroVersion}`, + `SITE_URL: ${process.env.SITE_URL || 'https://www.grassoezio.it'}`, + `File: ${files.length}`, + '', + 'Pubblicazione: estrarre il contenuto dell’archivio nella cartella pubblica del sito', + '(es. public_html o httpdocs), includendo il file nascosto .htaccess. Vedi docs/DEPLOY.md.', + '', +].join('\n'); +await writeFile(join(releaseDir, 'BUILD-INFO.txt'), info); + +const sums = []; +for (const name of [names.zip, names.tgz, 'BUILD-INFO.txt']) { + sums.push(`${await sha256(join(releaseDir, name))} ${name}`); +} +await writeFile(join(releaseDir, 'SHA256SUMS.txt'), sums.join('\n') + '\n'); + +const kb = (f) => `${(statSync(join(releaseDir, f)).size / 1024).toFixed(1)} KB`; +console.log(`✔ Pacchetto v${version} creato in release/ (${files.length} file da dist/):`); +for (const f of [names.zip, names.tgz, 'SHA256SUMS.txt', 'BUILD-INFO.txt']) { + console.log(` ${f.padEnd(40)} ${kb(f)}`); +} diff --git a/scripts/release-upload.sh b/scripts/release-upload.sh index f938a1b..98683bb 100755 --- a/scripts/release-upload.sh +++ b/scripts/release-upload.sh @@ -1,3 +1,63 @@ #!/usr/bin/env bash -# Segnaposto della fase 0: l'implementazione completa arriva nella fase 7. -echo "scripts/release-upload.sh: non ancora implementato (fase 0)." +# ============================================================================= +# Pubblica una release su Forgejo tramite API REST e carica i file di release/. +# Alternativa manuale (o step di riserva) all'action forgejo-release del workflow. +# +# Uso: +# FORGEJO_URL=https://forgejo.example.it \ +# FORGEJO_REPO=proprietario/repository \ +# FORGEJO_TOKEN= \ +# scripts/release-upload.sh v1.0.0 [cartella] # cartella predefinita: release +# +# Prima eseguire `npm run package` con RELEASE_VERSION=v1.0.0. Il tag deve già esistere +# sul server (git push origin v1.0.0). Le note della release sono prese da CHANGELOG.md. +# Se la release esiste già, i file con lo stesso nome vengono sostituiti. +# ============================================================================= +set -euo pipefail + +TAG="${1:-${RELEASE_VERSION:-}}" +DIR="${2:-release}" + +die() { echo "✘ $*" >&2; exit 1; } + +[ -n "$TAG" ] || die "indicare il tag, es.: scripts/release-upload.sh v1.0.0" +[ -n "${FORGEJO_URL:-}" ] || die "variabile FORGEJO_URL mancante (es. https://forgejo.example.it)" +[ -n "${FORGEJO_REPO:-}" ] || die "variabile FORGEJO_REPO mancante (es. proprietario/repository)" +[ -n "${FORGEJO_TOKEN:-}" ] || die "variabile FORGEJO_TOKEN mancante" +[ -d "$DIR" ] || die "cartella $DIR assente: eseguire prima npm run package" +command -v curl >/dev/null || die "curl non installato" +command -v node >/dev/null || die "node non installato" + +API="${FORGEJO_URL%/}/api/v1/repos/${FORGEJO_REPO}" +AUTH="Authorization: token ${FORGEJO_TOKEN}" + +json_field() { node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const v=JSON.parse(s)[process.argv[1]];if(v===undefined)process.exit(1);console.log(typeof v==="object"?JSON.stringify(v):v)})' "$1"; } + +NOTES="$(node scripts/changelog-notes.mjs "$TAG")" +PAYLOAD="$(node -e 'console.log(JSON.stringify({tag_name:process.argv[1],name:process.argv[1],body:process.argv[2],draft:false,prerelease:/-/.test(process.argv[1])}))' "$TAG" "$NOTES")" + +echo "→ Release $TAG su $FORGEJO_REPO" +if EXISTING="$(curl -fsS -H "$AUTH" "$API/releases/tags/$TAG" 2>/dev/null)"; then + RELEASE_ID="$(printf '%s' "$EXISTING" | json_field id)" + echo " release già esistente (id $RELEASE_ID): aggiornamento dei file" +else + CREATED="$(curl -fsS -X POST -H "$AUTH" -H 'Content-Type: application/json' -d "$PAYLOAD" "$API/releases")" \ + || die "creazione della release non riuscita (permessi del token? il tag esiste sul server?)" + RELEASE_ID="$(printf '%s' "$CREATED" | json_field id)" + echo " release creata (id $RELEASE_ID)" +fi + +ASSETS="$(curl -fsS -H "$AUTH" "$API/releases/$RELEASE_ID/assets")" +for FILE in "$DIR"/*; do + [ -f "$FILE" ] || continue + NAME="$(basename "$FILE")" + OLD_ID="$(printf '%s' "$ASSETS" | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const a=JSON.parse(s).find(x=>x.name===process.argv[1]);if(a)console.log(a.id)})' "$NAME")" + if [ -n "$OLD_ID" ]; then + curl -fsS -X DELETE -H "$AUTH" "$API/releases/$RELEASE_ID/assets/$OLD_ID" >/dev/null + fi + curl -fsS -X POST -H "$AUTH" -F "attachment=@${FILE}" \ + "$API/releases/$RELEASE_ID/assets?name=$(node -e 'console.log(encodeURIComponent(process.argv[1]))' "$NAME")" >/dev/null \ + || die "caricamento di $NAME non riuscito" + echo " ✔ $NAME" +done +echo "✔ Release $TAG pubblicata: ${FORGEJO_URL%/}/${FORGEJO_REPO}/releases/tag/$TAG"