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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016zJ9ZWGKvoKoxYwbmnRKdJ
This commit is contained in:
Claude committed 2026-10-15 23:05:12 +00:00
1 parent 601d13cfaf
commit e10745b061
11 files changed
+1116 -8

No files matched your search

+92
View File
@@ -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
+104
View File
@@ -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<<NOTES_EOF'
node scripts/changelog-notes.mjs "${{ github.ref_name }}"
echo 'NOTES_EOF'
} >> "$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
+24
View File
@@ -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.
+100
View File
@@ -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 ]
+112
View File
@@ -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;
# }
}
+189
View File
@@ -0,0 +1,189 @@
<?php
/**
* Studio Grasso — gestore del modulo di contatto (modalità "php", brief §10.1).
*
* Installazione: impostare `contactForm.mode = 'php'` in src/data/studio.ts, copiare questo
* file in public/contact.php, eseguire `npm run verify` e pubblicare (vedi docs/DEPLOY.md).
* Requisiti: PHP 7.4 o successivo con la funzione mail() abilitata dall'hosting.
*
* Cosa fa:
* - accetta solo POST e valida tutti i campi (obbligatori, lunghezze, e-mail, telefono, consenso);
* - anti-spam senza cookie né servizi esterni: campo trappola `sito_web` (se compilato la
* richiesta viene scartata in silenzio), tempo minimo di compilazione (campo `ts`) e massimo
* 5 invii all'ora per indirizzo IP (contatore in un file temporaneo con l'impronta dell'IP,
* mai l'IP in chiaro);
* - invia un'e-mail in testo semplice al destinatario configurato con mail();
* - NON salva né registra il contenuto dei messaggi;
* - risponde con redirect a /contatti/grazie/ oppure con una pagina d'errore leggibile.
*/
declare(strict_types=1);
// ---------------------------------------------------------------- configurazione
const DESTINATARIO = 'info@studiograssoezio.it';
// Mittente tecnico: una casella del dominio del sito (necessario per SPF/DMARC su molti hosting).
const MITTENTE = 'noreply@studiograssoezio.it';
const NOME_MITTENTE = 'Sito Studio Grasso';
const PREFISSO_OGGETTO = '[Sito] ';
const PAGINA_GRAZIE = '/contatti/grazie/';
const PAGINA_CONTATTI = '/contatti/';
const MAX_INVII_ORA = 5;
const TEMPO_MINIMO_MS = 3000;
const LUNGHEZZE = ['nome' => 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 '<!doctype html><html lang="it"><head><meta charset="utf-8">'
. '<meta name="viewport" content="width=device-width, initial-scale=1">'
. '<meta name="robots" content="noindex"><title>Richiesta non inviata — Studio Grasso</title>'
. '<style>body{font-family:system-ui,sans-serif;max-width:40rem;margin:4rem auto;padding:0 1rem;'
. 'color:#16202a;line-height:1.6}h1{color:#0b1f33}a{color:#163a5c}</style></head><body>'
. '<h1>Richiesta non inviata</h1><p>' . h($messaggio) . '</p>'
. '<p><a href="' . h(PAGINA_CONTATTI) . '">Torna alla pagina Contatti</a> oppure scrivi a '
. '<a href="mailto:' . h(DESTINATARIO) . '">' . h(DESTINATARIO) . '</a>.</p></body></html>';
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);
+39 -2
View File
@@ -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`);
+213 -2
View File
@@ -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.`,
);
+74
View File
@@ -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;
}
+107 -2
View File
@@ -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<versione>.zip per i pannelli di hosting (cPanel, Plesk, …)
* sito-studio-grasso-v<versione>.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)}`);
}
+62 -2
View File
@@ -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=<token con permesso write:repository> \
# 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"