Add VPS deployment: atomic release script with rollback, deploy checker, static nginx vhost, guide

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
denis
2026-10-16 19:03:55 +02:00
parent 9bdcc4f31a
commit 7eb508380a
6 changed files with 309 additions and 6 deletions
+11 -2
View File
@@ -5,7 +5,7 @@ VENV := .venv
VENV_PY := $(VENV)/bin/python VENV_PY := $(VENV)/bin/python
PORT ?= 8000 PORT ?= 8000
.PHONY: help install vendor-pyodide dev validate-levels build dev-sync docs docs-serve test test-js test-python test-backend test-e2e typecheck icons voice check-voice ci ci-e2e clean .PHONY: help install vendor-pyodide dev validate-levels build dev-sync docs docs-serve deploy check-deploy test-deploy test test-js test-python test-backend test-e2e typecheck icons voice check-voice ci ci-e2e clean
help: ## Affiche cette aide help: ## Affiche cette aide
@grep -E '^[a-z-]+:.*##' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf " %-16s %s\n", $$1, $$2}' @grep -E '^[a-z-]+:.*##' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf " %-16s %s\n", $$1, $$2}'
@@ -29,6 +29,15 @@ dev-sync: $(VENV)/.installed ## Serveur de dev + backend Django relayé sur /api
pid=$$!; trap "kill $$pid" EXIT INT TERM; \ pid=$$!; trap "kill $$pid" EXIT INT TERM; \
$(PYTHON) scripts/dev_server.py --port $(PORT) --api-upstream http://127.0.0.1:8001 $(PYTHON) scripts/dev_server.py --port $(PORT) --api-upstream http://127.0.0.1:8001
deploy: build ## Déploie dist/ sur le VPS (DEPLOY_HOST=utilisateur@hote ; voir scripts/deploy.sh)
./scripts/deploy.sh
check-deploy: ## Contrôle un site déployé (URL=https://domaine)
./scripts/check_deploy.sh $(URL)
test-deploy: ## Teste le script de déploiement avec un faux ssh local
bash tests/deploy/test_deploy.sh
DOCS_VENV := .venv-docs DOCS_VENV := .venv-docs
$(DOCS_VENV)/.installed: requirements-docs.txt $(DOCS_VENV)/.installed: requirements-docs.txt
@@ -48,7 +57,7 @@ validate-levels: $(VENV)/.installed ## Valide les niveaux (schéma, manifeste, t
build: $(VENV)/.installed ## Construit dist/ pour la production build: $(VENV)/.installed ## Construit dist/ pour la production
$(VENV_PY) scripts/build.py $(VENV_PY) scripts/build.py
test: test-js test-python test-backend validate-levels check-voice ## Lance tous les tests test: test-js test-python test-backend test-deploy validate-levels check-voice ## Lance tous les tests
test-js: ## Tests JavaScript (node:test, aucune dépendance) test-js: ## Tests JavaScript (node:test, aucune dépendance)
node --test tests/js/*.test.mjs node --test tests/js/*.test.mjs
+92
View File
@@ -0,0 +1,92 @@
# Vhost PyQuest, version statique (sans synchronisation) : à adapter (domaine, chemins, certificat).
# Contenu servi : le dossier « current » créé par scripts/deploy.sh (lien vers la dernière version).
# Les en-têtes COOP/COEP/CORP sont indispensables à l'interruption des boucles infinies et à input()
# (SharedArrayBuffer). Tout est servi depuis ce domaine, y compris Pyodide (COEP interdit les CDN).
# Pour la synchronisation, voir pyquest.conf.example (bloc /api/ et limite de débit).
#
# Installation type (Debian/Ubuntu) : voir la documentation « Déploiement » (docs/site/fr/host/deploy.md).
# 1. éditer server_name et les chemins ; commenter le second bloc server (443) tant qu'il n'y a pas de certificat
# 2. sudo ln -s /etc/nginx/sites-available/pyquest /etc/nginx/sites-enabled/pyquest && sudo nginx -t && sudo systemctl reload nginx
# 3. sudo certbot certonly --webroot -w /var/www/letsencrypt -d pyquest.example.org
# 4. décommenter le bloc 443 puis sudo nginx -t && sudo systemctl reload nginx
server {
listen 80;
listen [::]:80;
server_name pyquest.example.org;
# Défi HTTP de Let's Encrypt, puis tout le reste passe en HTTPS.
location /.well-known/acme-challenge/ {
root /var/www/letsencrypt;
}
location / {
return 301 https://$host$request_uri;
}
}
server {
listen 443 ssl;
listen [::]:443 ssl;
http2 on; # nginx >= 1.25.1 ; avant : « listen 443 ssl http2; » ci-dessus
server_name pyquest.example.org;
ssl_certificate /etc/letsencrypt/live/pyquest.example.org/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/pyquest.example.org/privkey.pem;
# Dossier créé par scripts/deploy.sh (lien « current » basculé à chaque déploiement).
root /var/www/pyquest/current;
index index.html;
# Types MIME explicites : un bloc « types » dans server remplace la table par défaut, donc on
# liste tout ce que l'application sert. Les scripts-modules exigent text/javascript.
types {
text/html html;
text/css css;
text/javascript js mjs;
application/json json;
application/manifest+json webmanifest;
application/wasm wasm;
image/svg+xml svg;
image/png png;
image/x-icon ico;
audio/mpeg mp3;
font/woff2 woff2;
text/plain txt py yaml;
}
default_type application/octet-stream;
# Compression : le moteur Python (wasm) et les scripts gagnent beaucoup.
gzip on;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_types text/css text/javascript application/json application/wasm image/svg+xml text/plain application/manifest+json;
# add_header n'est hérité que si le bloc location n'en déclare aucun : chaque location qui ajoute
# un en-tête (cache) doit donc répéter ceux d'isolation. On les regroupe dans ce fichier-ci.
add_header Cross-Origin-Opener-Policy "same-origin" always;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Resource-Policy "same-origin" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Strict-Transport-Security "max-age=31536000" always;
location / {
try_files $uri $uri/ =404;
# Pages et scripts : revalidés à chaque chargement (le service worker passe par le réseau d'abord).
add_header Cache-Control "no-cache" always;
add_header Cross-Origin-Opener-Policy "same-origin" always;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Resource-Policy "same-origin" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Strict-Transport-Security "max-age=31536000" always;
}
# Pyodide est versionné et immuable : cache long.
location /vendor/pyodide/ {
add_header Cache-Control "public, max-age=31536000, immutable" always;
add_header Cross-Origin-Opener-Policy "same-origin" always;
add_header Cross-Origin-Embedder-Policy "require-corp" always;
add_header Cross-Origin-Resource-Policy "same-origin" always;
add_header X-Content-Type-Options "nosniff" always;
add_header Strict-Transport-Security "max-age=31536000" always;
}
}
+17 -4
View File
@@ -7,7 +7,8 @@
limit_req_zone $binary_remote_addr zone=pyquest_sync:10m rate=30r/m; limit_req_zone $binary_remote_addr zone=pyquest_sync:10m rate=30r/m;
server { server {
listen 443 ssl http2; listen 443 ssl;
http2 on; # nginx >= 1.25.1 ; avant : « listen 443 ssl http2; »
server_name pyquest.example.org; server_name pyquest.example.org;
ssl_certificate /etc/letsencrypt/live/pyquest.example.org/fullchain.pem; ssl_certificate /etc/letsencrypt/live/pyquest.example.org/fullchain.pem;
@@ -22,11 +23,23 @@ server {
add_header Cross-Origin-Resource-Policy "same-origin" always; add_header Cross-Origin-Resource-Policy "same-origin" always;
add_header X-Content-Type-Options "nosniff" always; add_header X-Content-Type-Options "nosniff" always;
# Types MIME explicites : un bloc « types » dans server remplace la table par défaut, donc on liste
# tout ce que l'application sert (voir pyquest-static.conf.example pour la version complète et la compression).
types { types {
text/javascript mjs; text/html html;
application/manifest+json webmanifest; text/css css;
application/wasm wasm; text/javascript js mjs;
application/json json;
application/manifest+json webmanifest;
application/wasm wasm;
image/svg+xml svg;
image/png png;
image/x-icon ico;
audio/mpeg mp3;
font/woff2 woff2;
text/plain txt py yaml;
} }
default_type application/octet-stream;
location / { location / {
try_files $uri $uri/ =404; try_files $uri $uri/ =404;
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env bash
# Vérifie un site PyQuest déployé : en-têtes d'isolation (COOP/COEP/CORP), types MIME, moteur Python,
# service worker, redirection HTTPS. Quitte avec un code non nul au premier défaut.
#
# ./scripts/check_deploy.sh https://pyquest.example.org
set -uo pipefail
BASE="${1:-}"
[[ "${BASE}" =~ ^https?://[A-Za-z0-9._:-]+/?$ ]] || { echo "Usage : $0 https://domaine" >&2; exit 2; }
BASE="${BASE%/}"
FAILED=0
# header <url> <nom> : valeur de l'en-tête (minuscules), vide s'il est absent.
header() {
curl -sI --max-time 20 "$1" | tr -d '\r' | awk -v name="$(echo "$2" | tr 'A-Z' 'a-z'):" 'tolower($1) == name { sub(/^[^:]*: */, ""); print tolower($0) }'
}
status() { curl -s -o /dev/null -w '%{http_code}' --max-time 20 "$1"; }
ok() { printf ' ok %s\n' "$1"; }
ko() { printf ' ÉCHEC %s\n' "$1"; FAILED=1; }
expect_header() { # url nom attendu
local got
got="$(header "$1" "$2")"
if [[ "${got}" == *"$3"* ]]; then ok "$2 = $3 ($1)"; else ko "$2 attendu « $3 », reçu « ${got} » ($1)"; fi
}
expect_status() {
local got
got="$(status "$1")"
if [[ "${got}" == "$2" ]]; then ok "$2 $1"; else ko "$1 : code $2 attendu, reçu ${got}"; fi
}
echo "Contrôle de ${BASE}"
for path in / /service-worker.js /vendor/pyodide/pyodide.asm.wasm /js/workers/python-worker.js; do
expect_status "${BASE}${path}" 200
expect_header "${BASE}${path}" Cross-Origin-Opener-Policy same-origin
expect_header "${BASE}${path}" Cross-Origin-Embedder-Policy require-corp
expect_header "${BASE}${path}" Cross-Origin-Resource-Policy same-origin
done
expect_header "${BASE}/vendor/pyodide/pyodide.asm.wasm" Content-Type application/wasm
expect_header "${BASE}/js/workers/python-worker.js" Content-Type javascript
expect_header "${BASE}/service-worker.js" Cache-Control no-cache
expect_header "${BASE}/css/base.css" Content-Type text/css
expect_header "${BASE}/manifest.webmanifest" Content-Type manifest+json
expect_status "${BASE}/levels/manifest.json" 200
expect_status "${BASE}/author.html" 200
if [[ "${BASE}" == https://* ]]; then
redirect="$(curl -s -o /dev/null -w '%{http_code}' --max-time 20 "http://${BASE#https://}/")"
if [[ "${redirect}" == 301 || "${redirect}" == 308 ]]; then ok "HTTP redirige vers HTTPS (${redirect})"; else ko "HTTP devrait rediriger vers HTTPS, code ${redirect}"; fi
fi
# Information seulement : la synchronisation est facultative.
api="$(status "${BASE}/api/sync/")"
echo " info /api/sync/ répond ${api} (401 = backend actif, 404 = pas de synchronisation)"
if [[ "${FAILED}" == 0 ]]; then echo "Tout est correct."; else echo "Des contrôles ont échoué." >&2; fi
exit "${FAILED}"
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env bash
# Déploie dist/ sur un VPS : envoi dans un dossier de version (releases/<date>-<commit>), puis bascule
# atomique du lien « current » vers cette version. Le site reste servi sans coupure ; on peut revenir en
# arrière (--rollback). Aucun secret ici : l'hôte vient de l'environnement, l'authentification de ta clé SSH.
#
# DEPLOY_HOST=utilisateur@vps.example.org ./scripts/deploy.sh [--dry-run]
# DEPLOY_HOST=utilisateur@vps.example.org ./scripts/deploy.sh --rollback
#
# Variables : DEPLOY_HOST (obligatoire), DEPLOY_PATH (défaut /var/www/pyquest), DEPLOY_KEEP (défaut 3),
# DEPLOY_SSH (défaut « ssh -o BatchMode=yes »).
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
HOST="${DEPLOY_HOST:-}"
REMOTE_PATH="${DEPLOY_PATH:-/var/www/pyquest}"
KEEP="${DEPLOY_KEEP:-3}"
SSH="${DEPLOY_SSH:-ssh -o BatchMode=yes}"
MODE="deploy"
DRY_RUN=0
for arg in "$@"; do
case "${arg}" in
--dry-run) DRY_RUN=1 ;;
--rollback) MODE="rollback" ;;
-h|--help) sed -n '2,11p' "${BASH_SOURCE[0]}"; exit 0 ;;
*) echo "Option inconnue : ${arg}" >&2; exit 2 ;;
esac
done
# Ces valeurs sont insérées dans des commandes distantes : on n'accepte que des caractères sûrs.
[[ "${HOST}" =~ ^[A-Za-z0-9_.@:-]+$ ]] || { echo "DEPLOY_HOST manquant ou invalide (ex. utilisateur@vps.example.org)" >&2; exit 2; }
[[ "${REMOTE_PATH}" =~ ^/[A-Za-z0-9_./-]{3,}$ ]] || { echo "DEPLOY_PATH doit être un chemin absolu simple (ex. /var/www/pyquest)" >&2; exit 2; }
[[ "${KEEP}" =~ ^[1-9][0-9]*$ ]] || { echo "DEPLOY_KEEP doit être un entier >= 1" >&2; exit 2; }
remote() {
if [[ "${DRY_RUN}" == 1 ]]; then
echo "[dry-run] ssh ${HOST} $*"
else
# shellcheck disable=SC2086 # ${SSH} contient volontairement plusieurs mots
${SSH} "${HOST}" "$@"
fi
}
if [[ "${MODE}" == "rollback" ]]; then
# Bascule vers la version précédente (la plus récente avant celle qui est en ligne).
remote "set -e; cd '${REMOTE_PATH}'; current=\$(basename \"\$(readlink current)\"); \
previous=\$(ls -1 releases | sort | grep -B1 -x \"\$current\" | head -n1); \
[ -n \"\$previous\" ] && [ \"\$previous\" != \"\$current\" ] || { echo 'Aucune version précédente.' >&2; exit 1; }; \
ln -sfn \"releases/\$previous\" current.tmp && mv -Tf current.tmp current; echo \"Retour à \$previous\""
exit 0
fi
[[ -f "${ROOT}/dist/index.html" ]] || { echo "dist/ est absent : lance d'abord « make build »." >&2; exit 1; }
[[ -f "${ROOT}/dist/vendor/pyodide/pyodide.asm.wasm" ]] || { echo "Pyodide manque dans dist/ : « make vendor-pyodide » puis « make build »." >&2; exit 1; }
COMMIT="$(git -C "${ROOT}" rev-parse --short HEAD 2>/dev/null || echo nogit)"
git -C "${ROOT}" diff --quiet HEAD 2>/dev/null || COMMIT="${COMMIT}-dirty"
RELEASE="$(date +%Y%m%d%H%M%S)-${COMMIT}"
TARGET="${REMOTE_PATH}/releases/${RELEASE}"
echo "Déploiement de dist/ ($(du -sh "${ROOT}/dist" | cut -f1)) vers ${HOST}:${TARGET}"
remote "mkdir -p '${REMOTE_PATH}/releases'"
RSYNC=(rsync -az --delete --chmod=D755,F644 -e "${SSH}")
# Réutilise (liens physiques) les fichiers inchangés de la version en ligne : envoi plus rapide, moins de disque.
# shellcheck disable=SC2086
if ${SSH} "${HOST}" "test -d '${REMOTE_PATH}/current'" 2>/dev/null; then
RSYNC+=(--link-dest="${REMOTE_PATH}/current/")
fi
[[ "${DRY_RUN}" == 1 ]] && RSYNC+=(--dry-run --itemize-changes)
"${RSYNC[@]}" "${ROOT}/dist/" "${HOST}:${TARGET}/"
# Bascule atomique : création d'un lien temporaire puis renommage (jamais de lien cassé).
remote "set -e; cd '${REMOTE_PATH}'; ln -sfn 'releases/${RELEASE}' current.tmp && mv -Tf current.tmp current"
# Ne garde que les KEEP dernières versions (la version en ligne est toujours la plus récente).
remote "cd '${REMOTE_PATH}/releases' && ls -1 | sort | head -n -${KEEP} | xargs -r rm -rf --"
echo "En ligne : ${RELEASE} (retour arrière : DEPLOY_HOST=${HOST} $0 --rollback)"
+55
View File
@@ -0,0 +1,55 @@
#!/usr/bin/env bash
# Teste scripts/deploy.sh sans serveur : un faux « ssh » exécute les commandes en local (dans un dossier
# temporaire), ce qui permet de vérifier les versions, la bascule atomique, le nettoyage et le retour arrière.
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
command -v rsync >/dev/null || { echo "rsync absent : test de déploiement ignoré"; exit 0; }
WORK="$(mktemp -d)"
trap 'rm -rf "${WORK}"' EXIT
FAKE="${WORK}/fake-ssh"
# Même interface que ssh : [options] hôte commande... ; rsync l'appelle avec « hôte rsync --server … ».
cat > "${FAKE}" <<'SH'
#!/usr/bin/env bash
[[ "${1:-}" == "-l" ]] && shift 2 # rsync passe « -l utilisateur hôte »
shift # hôte
exec bash -c "$*"
SH
chmod +x "${FAKE}"
export DEPLOY_HOST="tester@example.invalid" DEPLOY_PATH="${WORK}/www/pyquest" DEPLOY_KEEP=2 DEPLOY_SSH="${FAKE}"
fail() { echo "ÉCHEC : $1" >&2; exit 1; }
# dist/ minimal factice (le vrai peut manquer en CI avant le build).
FAKE_ROOT="${WORK}/repo"
mkdir -p "${FAKE_ROOT}/scripts" "${FAKE_ROOT}/dist/vendor/pyodide"
cp "${ROOT}/scripts/deploy.sh" "${FAKE_ROOT}/scripts/"
echo "v1" > "${FAKE_ROOT}/dist/index.html"
touch "${FAKE_ROOT}/dist/vendor/pyodide/pyodide.asm.wasm"
DEPLOY="${FAKE_ROOT}/scripts/deploy.sh"
"${DEPLOY}" >/dev/null
[[ "$(cat "${DEPLOY_PATH}/current/index.html")" == v1 ]] || fail "la première version n'est pas en ligne"
sleep 1; echo "v2" > "${FAKE_ROOT}/dist/index.html"; "${DEPLOY}" >/dev/null
[[ "$(cat "${DEPLOY_PATH}/current/index.html")" == v2 ]] || fail "la seconde version n'est pas en ligne"
sleep 1; echo "v3" > "${FAKE_ROOT}/dist/index.html"; "${DEPLOY}" >/dev/null
[[ "$(ls "${DEPLOY_PATH}/releases" | wc -l)" == 2 ]] || fail "le nettoyage doit garder 2 versions"
[[ -L "${DEPLOY_PATH}/current" ]] || fail "current doit être un lien"
"${DEPLOY}" --rollback >/dev/null
[[ "$(cat "${DEPLOY_PATH}/current/index.html")" == v2 ]] || fail "le retour arrière doit remettre v2"
"${DEPLOY}" --rollback >/dev/null 2>&1 && fail "pas de version plus ancienne : le retour arrière doit échouer" || true
[[ "$(cat "${DEPLOY_PATH}/current/index.html")" == v2 ]] || fail "un retour arrière impossible ne doit rien changer"
# --dry-run ne modifie rien.
before="$(ls "${DEPLOY_PATH}/releases")"
echo "v4" > "${FAKE_ROOT}/dist/index.html"; "${DEPLOY}" --dry-run >/dev/null
[[ "$(ls "${DEPLOY_PATH}/releases")" == "${before}" ]] || fail "--dry-run ne doit rien envoyer"
# Valeurs dangereuses refusées avant toute connexion.
DEPLOY_HOST='x; rm -rf /' "${DEPLOY}" >/dev/null 2>&1 && fail "hôte dangereux accepté"
DEPLOY_PATH='/var/www/a b' "${DEPLOY}" >/dev/null 2>&1 && fail "chemin avec espace accepté"
DEPLOY_PATH='/' "${DEPLOY}" >/dev/null 2>&1 && fail "chemin racine accepté"
rm "${FAKE_ROOT}/dist/index.html"; "${DEPLOY}" >/dev/null 2>&1 && fail "dist absent accepté"
echo "deploy.sh : ok"