mirror of
https://github.com/deunix-educ/PyQuest.git
synced 2026-11-25 08:19:44 +01:00
Prepare VPS handover: bootstrap, doctor, DB backup, systemd unit, backend deploy, operations guide; commit docs sources previously ignored
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
+1
-1
@@ -17,7 +17,7 @@ backend/staticfiles/
|
|||||||
backend/.venv/
|
backend/.venv/
|
||||||
.venv-voice/
|
.venv-voice/
|
||||||
.venv-docs/
|
.venv-docs/
|
||||||
site/
|
/site/
|
||||||
.cache/
|
.cache/
|
||||||
backend/venv/
|
backend/venv/
|
||||||
|
|
||||||
|
|||||||
@@ -76,9 +76,11 @@ Commandes : `make test` (JS `node:test`, Python `unittest`, backend Django, vali
|
|||||||
niveaux), `make test-e2e` (Chromium), `make typecheck` (pyright), `make dev`, `make build`.
|
niveaux), `make test-e2e` (Chromium), `make typecheck` (pyright), `make dev`, `make build`.
|
||||||
Pyodide épinglé 314.0.7 (Python 3.14.2) via `make vendor-pyodide`.
|
Pyodide épinglé 314.0.7 (Python 3.14.2) via `make vendor-pyodide`.
|
||||||
|
|
||||||
**À traiter en premier à la reprise** : le parcours est complet (niveaux 00 à 14, synchronisation, éditeur
|
**À traiter en premier à la reprise** : le parcours est complet (niveaux 00 à 14, synchronisation, éditeur auteur protégé
|
||||||
auteur, canvas de dessin). Restent : retour d'écoute sur les effets sonores, test Safari/iOS (Firefox validé par
|
par Django, administration des comptes, canvas de dessin, documentation bilingue). **Prochaine étape : le déploiement sur
|
||||||
l'utilisateur), audit lecteur d'écran, documentation MkDocs. Voir les priorités dans CONTEXT.md.
|
le VPS** (rien n'est encore en ligne, tout est préparé : voir « Déploiement sur le VPS — état et reprise » dans CONTEXT.md et
|
||||||
|
`docs/site/fr/host/operations.md`). Demander à l'utilisateur adresse SSH, domaine, version de MariaDB avant d'agir. Restent
|
||||||
|
aussi : retour d'écoute sur les effets sonores, test Safari/iOS (Firefox validé), audit lecteur d'écran.
|
||||||
|
|
||||||
## Règles de travail apprises
|
## Règles de travail apprises
|
||||||
|
|
||||||
|
|||||||
+26
@@ -42,6 +42,32 @@ vrai navigateur (Chromium) avec 4 niveaux jouables.
|
|||||||
| Accès éditeur | `backend/authors/` (login, `check` pour nginx `auth_request`, administration `/api/admin/` : groupe « Auteurs » / permission `use_editor`, `create_author`, anti force brute) ; nginx `pyquest.conf.example` ; prod = MariaDB |
|
| Accès éditeur | `backend/authors/` (login, `check` pour nginx `auth_request`, administration `/api/admin/` : groupe « Auteurs » / permission `use_editor`, `create_author`, anti force brute) ; nginx `pyquest.conf.example` ; prod = MariaDB |
|
||||||
| Synchronisation | `core/SyncClient.js` + section Réglages ; export/import fichier ; voir `docs/design/09-sync.md` ; `make dev-sync` |
|
| Synchronisation | `core/SyncClient.js` + section Réglages ; export/import fichier ; voir `docs/design/09-sync.md` ; `make dev-sync` |
|
||||||
|
|
||||||
|
## Déploiement sur le VPS — état et reprise (2026-10-16)
|
||||||
|
|
||||||
|
**État : rien n'est déployé.** Tout est préparé et testé sans serveur ; l'utilisateur a dit « Pas encore » au premier
|
||||||
|
déploiement. Décisions : site statique + backend Django (synchronisation, accès authentifié à l'éditeur, administration),
|
||||||
|
**MariaDB déjà en place** sur le VPS, nginx, Let's Encrypt, `nginx/pyquest.conf.example` (version complète).
|
||||||
|
|
||||||
|
**Inconnues à demander à l'utilisateur** : adresse SSH (`utilisateur@hote`) et si je dois exécuter les commandes moi-même
|
||||||
|
(sa préférence actuelle : il les lance lui-même), nom de domaine, version de MariaDB, version de nginx, e-mail Let's Encrypt.
|
||||||
|
|
||||||
|
**Feuille de route** (détail et dépannage : `docs/site/fr/host/operations.md`) : `make ci` → `make vps-bootstrap
|
||||||
|
DOMAIN=… ARGS=--dry-run` → `make vps-bootstrap DOMAIN=… ARGS="--certbot mail"` → base MariaDB
|
||||||
|
(`deploy/mariadb-setup.sql.example`) + mot de passe dans `/etc/pyquest/env` → `systemctl enable --now pyquest` →
|
||||||
|
`createsuperuser` → `make deploy` → `make check-deploy URL=…` → `make vps-doctor`.
|
||||||
|
|
||||||
|
| Outil | Rôle | Testé |
|
||||||
|
|---|---|---|
|
||||||
|
| `scripts/deploy.sh` (`--rollback`, `--backend`, `--dry-run`) | versions atomiques du site, code du backend | faux ssh (`tests/deploy/test_deploy.sh`) |
|
||||||
|
| `scripts/vps_bootstrap.sh` + `deploy/remote_setup.sh` | première installation root idempotente (`--dry-run`) | arguments et dry-run seulement |
|
||||||
|
| `scripts/vps_doctor.sh` | diagnostic en lecture seule du serveur | exécution locale |
|
||||||
|
| `scripts/backup_db.sh` | sauvegarde MariaDB vérifiée + rotation | faux `mariadb-dump` |
|
||||||
|
| `scripts/check_deploy.sh` | contrôle du site publié | serveur local, vrai nginx (`make dev-nginx`) |
|
||||||
|
| `deploy/pyquest.service.example`, `pyquest.env.example`, `mariadb-setup.sql.example` | unité systemd (migrate + collectstatic au démarrage), variables, base | syntaxe de l'unité (`systemd-analyze`) |
|
||||||
|
|
||||||
|
**Jamais éprouvé en réel** : `remote_setup.sh` sur un vrai serveur (apt, systemd, sudoers, certbot), MariaDB, HTTPS réel,
|
||||||
|
cookies `Secure`. Premier réflexe en reprenant : `make ci`, puis `make vps-doctor`, et lire les lignes ÉCHEC.
|
||||||
|
|
||||||
## Éditeur de niveaux (mode auteur) — fait le 2026-10-16
|
## Éditeur de niveaux (mode auteur) — fait le 2026-10-16
|
||||||
|
|
||||||
Décision de l'utilisateur : ouvrir à des contributeurs + éditeur en mode auteur (Django inchangé : sync
|
Décision de l'utilisateur : ouvrir à des contributeurs + éditeur en mode auteur (Django inchangé : sync
|
||||||
|
|||||||
@@ -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 fetch-nginx dev-nginx dev-admin dev-author 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
|
.PHONY: help install vendor-pyodide dev validate-levels build dev-sync fetch-nginx dev-nginx dev-admin dev-author docs docs-serve deploy deploy-backend vps-bootstrap vps-doctor 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}'
|
||||||
@@ -35,8 +35,18 @@ deploy: build ## Déploie dist/ sur le VPS (DEPLOY_HOST=utilisateur@hote ; voir
|
|||||||
check-deploy: ## Contrôle un site déployé (URL=https://domaine)
|
check-deploy: ## Contrôle un site déployé (URL=https://domaine)
|
||||||
./scripts/check_deploy.sh $(URL)
|
./scripts/check_deploy.sh $(URL)
|
||||||
|
|
||||||
test-deploy: ## Teste le script de déploiement avec un faux ssh local
|
deploy-backend: ## Envoie le code du backend Django au VPS et redémarre le service (DEPLOY_HOST=utilisateur@hote)
|
||||||
|
./scripts/deploy.sh --backend
|
||||||
|
|
||||||
|
vps-bootstrap: ## Première installation du VPS (DEPLOY_HOST=… DOMAIN=… ; ajouter ARGS=--dry-run pour simuler)
|
||||||
|
./scripts/vps_bootstrap.sh --domain $(DOMAIN) $(ARGS)
|
||||||
|
|
||||||
|
vps-doctor: ## Diagnostic en lecture seule du VPS (DEPLOY_HOST=utilisateur@hote)
|
||||||
|
ssh $(DEPLOY_HOST) 'bash -s' < scripts/vps_doctor.sh
|
||||||
|
|
||||||
|
test-deploy: ## Teste les scripts de déploiement et d'exploitation (faux ssh, faux mariadb-dump, --dry-run)
|
||||||
bash tests/deploy/test_deploy.sh
|
bash tests/deploy/test_deploy.sh
|
||||||
|
bash tests/deploy/test_server_scripts.sh
|
||||||
|
|
||||||
DOCS_VENV := .venv-docs
|
DOCS_VENV := .venv-docs
|
||||||
|
|
||||||
|
|||||||
@@ -60,6 +60,12 @@ backend is deployed on the same domain behind nginx (`/api/` → Django, see
|
|||||||
[nginx/pyquest.conf.example](nginx/pyquest.conf.example)). In development: `make dev-sync`.
|
[nginx/pyquest.conf.example](nginx/pyquest.conf.example)). In development: `make dev-sync`.
|
||||||
Details (in French): [docs/design/09-sync.md](docs/design/09-sync.md).
|
Details (in French): [docs/design/09-sync.md](docs/design/09-sync.md).
|
||||||
|
|
||||||
|
### Installing on a VPS
|
||||||
|
|
||||||
|
Tested scripts for installation, atomic-release deployment, diagnostics and backup: see
|
||||||
|
[docs/site/en/host/operations.md](docs/site/en/host/operations.md) (`make vps-bootstrap`, `make deploy`, `make vps-doctor`).
|
||||||
|
Production-faithful local test: `make dev-nginx`.
|
||||||
|
|
||||||
## Contributing
|
## Contributing
|
||||||
|
|
||||||
See [CONTRIBUTING.md](CONTRIBUTING.md) (contribution flow, adding a level with the editor) and [docs/MAINTAINERS.md](docs/MAINTAINERS.md) (review, release; in French). `make ci` runs the whole verification chain.
|
See [CONTRIBUTING.md](CONTRIBUTING.md) (contribution flow, adding a level with the editor) and [docs/MAINTAINERS.md](docs/MAINTAINERS.md) (review, release; in French). `make ci` runs the whole verification chain.
|
||||||
|
|||||||
@@ -60,6 +60,12 @@ secret (sans compte) si le backend Django est déployé sur le même domaine, de
|
|||||||
(`/api/` → Django, voir [nginx/pyquest.conf.example](nginx/pyquest.conf.example)). En développement :
|
(`/api/` → Django, voir [nginx/pyquest.conf.example](nginx/pyquest.conf.example)). En développement :
|
||||||
`make dev-sync`. Fonctionnement détaillé : [docs/design/09-sync.md](docs/design/09-sync.md).
|
`make dev-sync`. Fonctionnement détaillé : [docs/design/09-sync.md](docs/design/09-sync.md).
|
||||||
|
|
||||||
|
### Installer sur un VPS
|
||||||
|
|
||||||
|
Scripts testés d'installation, de déploiement par versions atomiques, de diagnostic et de sauvegarde : voir
|
||||||
|
[docs/site/fr/host/operations.md](docs/site/fr/host/operations.md) (`make vps-bootstrap`, `make deploy`, `make vps-doctor`).
|
||||||
|
Essai local fidèle à la production : `make dev-nginx`.
|
||||||
|
|
||||||
## Contribuer
|
## Contribuer
|
||||||
|
|
||||||
Voir [CONTRIBUTING.md](CONTRIBUTING.md) (flux de contribution, ajout d'un niveau avec l'éditeur) et [docs/MAINTAINERS.md](docs/MAINTAINERS.md) (relecture, publication). `make ci` lance toute la chaîne de vérification.
|
Voir [CONTRIBUTING.md](CONTRIBUTING.md) (flux de contribution, ajout d'un niveau avec l'éditeur) et [docs/MAINTAINERS.md](docs/MAINTAINERS.md) (relecture, publication). `make ci` lance toute la chaîne de vérification.
|
||||||
|
|||||||
@@ -0,0 +1,7 @@
|
|||||||
|
-- Base et utilisateur dédiés à PyQuest sur le MariaDB existant (MariaDB 10.5 ou plus).
|
||||||
|
-- À exécuter en administrateur : sudo mariadb < deploy/mariadb-setup.sql (après avoir remplacé le mot de passe).
|
||||||
|
-- Le mot de passe va ensuite dans /etc/pyquest/env (PYQUEST_DB_PASSWORD).
|
||||||
|
CREATE DATABASE IF NOT EXISTS pyquest CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
CREATE USER IF NOT EXISTS 'pyquest'@'localhost' IDENTIFIED BY 'REMPLACER-PAR-UN-MOT-DE-PASSE-LONG';
|
||||||
|
GRANT ALL PRIVILEGES ON pyquest.* TO 'pyquest'@'localhost';
|
||||||
|
FLUSH PRIVILEGES;
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# Variables d'environnement du backend. À copier en /etc/pyquest/env (droits 640, propriétaire root:pyquest).
|
||||||
|
# JAMAIS commité avec de vraies valeurs. scripts/vps_bootstrap.sh génère PYQUEST_SECRET_KEY automatiquement.
|
||||||
|
DJANGO_SETTINGS_MODULE=pyquest_api.settings.production
|
||||||
|
|
||||||
|
# Chaîne aléatoire longue et secrète (générée à l'installation).
|
||||||
|
PYQUEST_SECRET_KEY=__A_GENERER__
|
||||||
|
# Domaine public (sans schéma) et origine complète.
|
||||||
|
PYQUEST_ALLOWED_HOSTS=pyquest.example.org
|
||||||
|
PYQUEST_ORIGIN=https://pyquest.example.org
|
||||||
|
|
||||||
|
# MariaDB (existante) : voir deploy/mariadb-setup.sql.example pour créer la base et l'utilisateur.
|
||||||
|
PYQUEST_DB_NAME=pyquest
|
||||||
|
PYQUEST_DB_USER=pyquest
|
||||||
|
PYQUEST_DB_PASSWORD=__A_REMPLIR__
|
||||||
|
PYQUEST_DB_HOST=127.0.0.1
|
||||||
|
PYQUEST_DB_PORT=3306
|
||||||
|
|
||||||
|
# Fichiers statiques de l'administration (servis par nginx sous /api/static/).
|
||||||
|
PYQUEST_STATIC_ROOT=/var/www/pyquest/static
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
# Unité systemd du backend PyQuest (gunicorn, derrière nginx). À copier en /etc/systemd/system/pyquest.service.
|
||||||
|
# Au démarrage (et donc à chaque redémarrage après un déploiement), les migrations et les fichiers statiques de
|
||||||
|
# l'administration sont mis à jour avant de lancer le serveur.
|
||||||
|
#
|
||||||
|
# sudo systemctl daemon-reload && sudo systemctl enable --now pyquest
|
||||||
|
# sudo systemctl status pyquest ; journalctl -u pyquest -f
|
||||||
|
|
||||||
|
[Unit]
|
||||||
|
Description=PyQuest backend (synchronisation et accès à l'éditeur)
|
||||||
|
After=network.target mariadb.service
|
||||||
|
Wants=mariadb.service
|
||||||
|
|
||||||
|
[Service]
|
||||||
|
User=pyquest
|
||||||
|
Group=pyquest
|
||||||
|
WorkingDirectory=/opt/pyquest/backend
|
||||||
|
# Secrets et réglages : fichier lisible par root et le groupe pyquest seulement (voir deploy/pyquest.env.example).
|
||||||
|
EnvironmentFile=/etc/pyquest/env
|
||||||
|
ExecStartPre=/opt/pyquest/venv/bin/python manage.py migrate --noinput
|
||||||
|
ExecStartPre=/opt/pyquest/venv/bin/python manage.py collectstatic --noinput --verbosity 0
|
||||||
|
ExecStart=/opt/pyquest/venv/bin/gunicorn pyquest_api.wsgi --bind 127.0.0.1:8001 --workers 3 --access-logfile - --error-logfile -
|
||||||
|
Environment=PYTHONDONTWRITEBYTECODE=1
|
||||||
|
Restart=on-failure
|
||||||
|
RestartSec=3
|
||||||
|
|
||||||
|
# Durcissement : le service n'écrit que dans les statiques et n'a accès à rien d'autre.
|
||||||
|
NoNewPrivileges=true
|
||||||
|
PrivateTmp=true
|
||||||
|
ProtectSystem=strict
|
||||||
|
ProtectHome=true
|
||||||
|
ReadWritePaths=/var/www/pyquest/static
|
||||||
|
ProtectKernelTunables=true
|
||||||
|
ProtectControlGroups=true
|
||||||
|
RestrictSUIDSGID=true
|
||||||
|
LockPersonality=true
|
||||||
|
|
||||||
|
[Install]
|
||||||
|
WantedBy=multi-user.target
|
||||||
Executable
+154
@@ -0,0 +1,154 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Installation du serveur PyQuest, À EXÉCUTER SUR LE VPS en root (sudo). Normalement lancé par scripts/vps_bootstrap.sh,
|
||||||
|
# qui envoie d'abord ce dossier, nginx/ et le code du backend. Idempotent : peut être relancé sans danger ; ne remplace
|
||||||
|
# jamais un fichier de configuration ou un secret déjà présent.
|
||||||
|
#
|
||||||
|
# sudo bash remote_setup.sh --domain pyquest.example.org --deploy-user denis [--certbot adresse@mail] [--dry-run]
|
||||||
|
#
|
||||||
|
# Fait : paquets, utilisateur système, dossiers, environnement Python, fichier d'environnement (clé secrète générée),
|
||||||
|
# unité systemd, extraits et vhost nginx, certificat Let's Encrypt (si --certbot), droit de redémarrer le service.
|
||||||
|
# NE fait PAS : créer la base MariaDB, saisir son mot de passe, créer l'administrateur (étapes listées à la fin).
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
DOMAIN=""
|
||||||
|
DEPLOY_USER=""
|
||||||
|
CERTBOT_EMAIL=""
|
||||||
|
DRY_RUN=0
|
||||||
|
HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||||
|
NGINX_SRC="${HERE}/../nginx"
|
||||||
|
WEB_ROOT="/var/www/pyquest"
|
||||||
|
APP_ROOT="/opt/pyquest"
|
||||||
|
ENV_FILE="/etc/pyquest/env"
|
||||||
|
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case "$1" in
|
||||||
|
--domain) DOMAIN="${2:-}"; shift 2 ;;
|
||||||
|
--deploy-user) DEPLOY_USER="${2:-}"; shift 2 ;;
|
||||||
|
--certbot) CERTBOT_EMAIL="${2:-}"; shift 2 ;;
|
||||||
|
--dry-run) DRY_RUN=1; shift ;;
|
||||||
|
-h|--help) sed -n '2,11p' "${BASH_SOURCE[0]}"; exit 0 ;;
|
||||||
|
*) echo "Option inconnue : $1" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
|
||||||
|
[[ "${DOMAIN}" =~ ^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || { echo "--domain invalide (ex. pyquest.example.org)" >&2; exit 2; }
|
||||||
|
[[ "${DEPLOY_USER}" =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] || { echo "--deploy-user invalide" >&2; exit 2; }
|
||||||
|
[[ -z "${CERTBOT_EMAIL}" || "${CERTBOT_EMAIL}" =~ ^[^@[:space:]]+@[^@[:space:]]+\.[A-Za-z]{2,}$ ]] || { echo "--certbot : adresse e-mail invalide" >&2; exit 2; }
|
||||||
|
[[ "${DRY_RUN}" == 1 || "${EUID}" -eq 0 ]] || { echo "À lancer en root : sudo bash $0 …" >&2; exit 1; }
|
||||||
|
id "${DEPLOY_USER}" >/dev/null 2>&1 || { [[ "${DRY_RUN}" == 1 ]] || { echo "L'utilisateur ${DEPLOY_USER} n'existe pas." >&2; exit 1; }; }
|
||||||
|
|
||||||
|
step() { printf '\n==> %s\n' "$*"; }
|
||||||
|
run() {
|
||||||
|
if [[ "${DRY_RUN}" == 1 ]]; then printf '[dry-run] %s\n' "$*"; else "$@"; fi
|
||||||
|
}
|
||||||
|
# Écrit un fichier depuis l'entrée standard, sauf s'il existe déjà (jamais d'écrasement de ta configuration).
|
||||||
|
install_new() { # chemin mode propriétaire:groupe
|
||||||
|
if [[ -e "$1" ]]; then echo "déjà présent, conservé : $1"; cat >/dev/null; return; fi
|
||||||
|
if [[ "${DRY_RUN}" == 1 ]]; then echo "[dry-run] création de $1"; cat >/dev/null; return; fi
|
||||||
|
install -m "$2" -o "${3%%:*}" -g "${3##*:}" /dev/stdin "$1"
|
||||||
|
echo "créé : $1"
|
||||||
|
}
|
||||||
|
|
||||||
|
step "Paquets (nginx, rsync, Python, bibliothèque cliente MariaDB, certbot)"
|
||||||
|
run apt-get update -qq
|
||||||
|
run env DEBIAN_FRONTEND=noninteractive apt-get install -y -qq nginx rsync python3-venv python3-dev pkg-config libmariadb-dev build-essential certbot
|
||||||
|
|
||||||
|
step "Utilisateur système « pyquest » et dossiers"
|
||||||
|
getent passwd pyquest >/dev/null || run adduser --system --group --no-create-home --shell /usr/sbin/nologin pyquest
|
||||||
|
run mkdir -p "${WEB_ROOT}/releases" "${WEB_ROOT}/static" "${WEB_ROOT}/letsencrypt" "${APP_ROOT}/backend" /etc/pyquest
|
||||||
|
run chown -R "${DEPLOY_USER}:${DEPLOY_USER}" "${WEB_ROOT}/releases" "${APP_ROOT}/backend"
|
||||||
|
run chown pyquest:pyquest "${WEB_ROOT}/static"
|
||||||
|
run chown root:pyquest /etc/pyquest
|
||||||
|
run chmod 750 /etc/pyquest
|
||||||
|
|
||||||
|
step "Environnement Python du backend"
|
||||||
|
if [[ ! -d "${APP_ROOT}/venv" ]]; then run python3 -m venv "${APP_ROOT}/venv"; fi
|
||||||
|
if [[ -f "${APP_ROOT}/backend/requirements-prod.txt" || "${DRY_RUN}" == 1 ]]; then
|
||||||
|
run "${APP_ROOT}/venv/bin/pip" install --quiet --upgrade pip
|
||||||
|
run "${APP_ROOT}/venv/bin/pip" install --quiet -r "${APP_ROOT}/backend/requirements-prod.txt"
|
||||||
|
else
|
||||||
|
echo "Code du backend absent de ${APP_ROOT}/backend : lance d'abord « make deploy-backend » (ou scripts/vps_bootstrap.sh)." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
step "Fichier d'environnement ${ENV_FILE} (clé secrète générée, jamais écrasé)"
|
||||||
|
if [[ ! -e "${ENV_FILE}" ]]; then
|
||||||
|
SECRET="$(python3 -c 'import secrets; print(secrets.token_urlsafe(64))')"
|
||||||
|
sed -e "s#__A_GENERER__#${SECRET}#" -e "s#pyquest.example.org#${DOMAIN}#g" "${HERE}/pyquest.env.example" | install_new "${ENV_FILE}" 640 root:pyquest
|
||||||
|
else
|
||||||
|
echo "déjà présent, conservé : ${ENV_FILE}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
step "Unité systemd"
|
||||||
|
install_new /etc/systemd/system/pyquest.service 644 root:root < "${HERE}/pyquest.service.example"
|
||||||
|
run systemctl daemon-reload
|
||||||
|
|
||||||
|
step "Droit de redémarrer le service (seule commande autorisée sans mot de passe)"
|
||||||
|
if [[ "${DRY_RUN}" == 1 ]]; then
|
||||||
|
echo "[dry-run] /etc/sudoers.d/pyquest : ${DEPLOY_USER} peut lancer « systemctl restart|status pyquest »"
|
||||||
|
else
|
||||||
|
SUDOERS_TMP="$(mktemp)"
|
||||||
|
printf '%s ALL=(root) NOPASSWD: /usr/bin/systemctl restart pyquest, /usr/bin/systemctl status pyquest\n' "${DEPLOY_USER}" > "${SUDOERS_TMP}"
|
||||||
|
visudo -cf "${SUDOERS_TMP}" >/dev/null && install -m 440 -o root -g root "${SUDOERS_TMP}" /etc/sudoers.d/pyquest
|
||||||
|
rm -f "${SUDOERS_TMP}"
|
||||||
|
fi
|
||||||
|
|
||||||
|
step "Script de sauvegarde de la base (${APP_ROOT}/scripts/backup_db.sh)"
|
||||||
|
if [[ -f "${HERE}/../scripts/backup_db.sh" || "${DRY_RUN}" == 1 ]]; then
|
||||||
|
run install -d "${APP_ROOT}/scripts"
|
||||||
|
run install -m 750 -o root -g root "${HERE}/../scripts/backup_db.sh" "${APP_ROOT}/scripts/backup_db.sh"
|
||||||
|
fi
|
||||||
|
|
||||||
|
step "nginx : extraits partagés"
|
||||||
|
run install -d /etc/nginx/snippets
|
||||||
|
run install -m 644 "${NGINX_SRC}/pyquest-locations.conf.example" /etc/nginx/snippets/pyquest-locations.conf
|
||||||
|
run install -m 644 "${NGINX_SRC}/pyquest-author-headers.conf.example" /etc/nginx/snippets/pyquest-author-headers.conf
|
||||||
|
|
||||||
|
VHOST=/etc/nginx/sites-available/pyquest
|
||||||
|
CERT_DIR="/etc/letsencrypt/live/${DOMAIN}"
|
||||||
|
if [[ ! -e "${CERT_DIR}/fullchain.pem" && "${DRY_RUN}" == 0 ]]; then
|
||||||
|
step "nginx : vhost HTTP provisoire (le certificat n'existe pas encore)"
|
||||||
|
cat > "${VHOST}" <<CONF
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
listen [::]:80;
|
||||||
|
server_name ${DOMAIN};
|
||||||
|
location /.well-known/acme-challenge/ { root ${WEB_ROOT}/letsencrypt; }
|
||||||
|
location / { return 200 "PyQuest : installation en cours\n"; add_header Content-Type text/plain; }
|
||||||
|
}
|
||||||
|
CONF
|
||||||
|
ln -sfn "${VHOST}" /etc/nginx/sites-enabled/pyquest
|
||||||
|
rm -f /etc/nginx/sites-enabled/default
|
||||||
|
nginx -t && systemctl reload nginx
|
||||||
|
if [[ -n "${CERTBOT_EMAIL}" ]]; then
|
||||||
|
step "Certificat Let's Encrypt pour ${DOMAIN}"
|
||||||
|
certbot certonly --webroot -w "${WEB_ROOT}/letsencrypt" -d "${DOMAIN}" --non-interactive --agree-tos -m "${CERTBOT_EMAIL}"
|
||||||
|
fi
|
||||||
|
fi
|
||||||
|
if [[ -e "${CERT_DIR}/fullchain.pem" || "${DRY_RUN}" == 1 ]]; then
|
||||||
|
step "nginx : vhost complet (HTTPS, éditeur protégé, API, administration)"
|
||||||
|
if [[ "${DRY_RUN}" == 1 ]]; then
|
||||||
|
echo "[dry-run] vhost ${VHOST} pour ${DOMAIN}"
|
||||||
|
else
|
||||||
|
sed -e "s#pyquest.example.org#${DOMAIN}#g" -e "s#/var/www/pyquest/current#${WEB_ROOT}/current#" -e "s#/var/www/letsencrypt#${WEB_ROOT}/letsencrypt#" "${NGINX_SRC}/pyquest.conf.example" > "${VHOST}.new"
|
||||||
|
mv "${VHOST}.new" "${VHOST}"
|
||||||
|
ln -sfn "${VHOST}" /etc/nginx/sites-enabled/pyquest
|
||||||
|
rm -f /etc/nginx/sites-enabled/default
|
||||||
|
# Les zones limit_req_zone doivent être au niveau http : sites-enabled y est inclus, c'est bon.
|
||||||
|
nginx -t && systemctl reload nginx
|
||||||
|
fi
|
||||||
|
else
|
||||||
|
echo "Pas de certificat : relance avec --certbot adresse@mail, ou obtiens-le toi-même, puis relance ce script."
|
||||||
|
fi
|
||||||
|
|
||||||
|
cat <<NEXT
|
||||||
|
|
||||||
|
==> Installation du serveur terminée. Restent, dans l'ordre :
|
||||||
|
1. Base MariaDB : adapter puis exécuter deploy/mariadb-setup.sql.example (sudo mariadb < …), puis mettre le mot de
|
||||||
|
passe dans ${ENV_FILE} (PYQUEST_DB_PASSWORD) — fichier lisible par root et le groupe pyquest seulement.
|
||||||
|
2. Démarrer le service : sudo systemctl enable --now pyquest ; sudo systemctl status pyquest
|
||||||
|
(il applique les migrations et collecte les fichiers statiques au démarrage).
|
||||||
|
3. Premier administrateur : sudo -u pyquest env \$(grep -v '^#' ${ENV_FILE} | xargs) ${APP_ROOT}/venv/bin/python ${APP_ROOT}/backend/manage.py createsuperuser
|
||||||
|
4. Depuis ta machine : make deploy (le site), puis make check-deploy URL=https://${DOMAIN}
|
||||||
|
5. Sauvegarde quotidienne de la base : echo '30 3 * * * root ${APP_ROOT}/scripts/backup_db.sh' | sudo tee /etc/cron.d/pyquest-backup
|
||||||
|
NEXT
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# The level editor
|
||||||
|
|
||||||
|
A built-in tool to write a level **without hand-writing YAML**, and without a server.
|
||||||
|
|
||||||
|
## Opening it
|
||||||
|
|
||||||
|
1. Run `make dev` (or open your instance).
|
||||||
|
2. In **Settings**, turn on **Author mode**.
|
||||||
|
3. Click **Open the level editor** (page `/author.html`).
|
||||||
|
|
||||||
|
Learners do not see this link while author mode is off.
|
||||||
|
|
||||||
|
!!! note "On a protected server"
|
||||||
|
If the instance has the Django backend, opening `/author.html` requires signing in (an account authorised by an
|
||||||
|
administrator in the Django administration, see [Deployment](../host/deploy.md)). Once signed
|
||||||
|
in, the editor header shows your name and a **Sign out** button (the session lasts 8 hours). Locally (`make dev`) there
|
||||||
|
is no login and no button.
|
||||||
|
|
||||||
|
## What it does
|
||||||
|
|
||||||
|
- **Forms** for the level information, steps (explanation or code exercise), tests, hints, solutions and the
|
||||||
|
mission. Each text is entered in French **and** English, side by side.
|
||||||
|
- **Live checks**: schema conformity (targeted messages), missing translations, `requires`, missing solutions,
|
||||||
|
inconsistent tests, invalid regular expressions, a reminder to generate the narration. A button jumps to the
|
||||||
|
field concerned.
|
||||||
|
- **Run the exercises**: runs each solution with the browser's **real Python**, like `make test`. The solution
|
||||||
|
must pass its tests and the starter code must not.
|
||||||
|
- **Try it**: plays the level as a learner, in the real interface (progress is never saved).
|
||||||
|
- **Export**: downloads `level.yaml` in the project's style, shows the line to add to the manifest and the next
|
||||||
|
steps. You can also **import** a file or load an existing level to edit it.
|
||||||
|
- Your **draft** is saved in the browser.
|
||||||
|
|
||||||
|
## After exporting
|
||||||
|
|
||||||
|
1. Put `level.yaml` in `levels/NN-slug/` and add the manifest line.
|
||||||
|
2. `make validate-levels` and `make test`.
|
||||||
|
3. `make voice` for narrated steps.
|
||||||
|
4. Open your merge request ([contribution flow](flow.md)).
|
||||||
|
|
||||||
|
## Limits
|
||||||
|
|
||||||
|
- Narration cannot be generated in the browser: `make voice` is needed (the editor reminds you).
|
||||||
|
- Scripted inputs are entered one per line; an empty input in the middle is possible, not in last position.
|
||||||
|
- The editor helps but does not replace review: the `make` commands remain the reference.
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
# Contribution flow
|
||||||
|
|
||||||
|
You can propose a **level**, a **fix** or a **translation**. You do not need to know how the app works inside to
|
||||||
|
write a level.
|
||||||
|
|
||||||
|
## Steps
|
||||||
|
|
||||||
|
1. **Branch**: one branch per contribution (`level-08-functions`, `fix-hint-typo`…). One level per merge request is
|
||||||
|
easier to review.
|
||||||
|
2. **Prepare**: `make install` (tools and Python engine), then `make dev` to try it in the browser
|
||||||
|
(`http://127.0.0.1:8000/`).
|
||||||
|
3. **Write** your level, preferably with the [level editor](author-editor.md), or your fix.
|
||||||
|
4. **Check**: `make ci` runs the tests, the check of **all reference solutions** with real Python, type checking
|
||||||
|
and the build. With Chromium installed, `make ci-e2e` adds the real-browser journeys.
|
||||||
|
5. **Commits**: messages in English, short, imperative ("Add level 08 functions").
|
||||||
|
6. **Propose** your contribution (pull request or merge request); the description template is in
|
||||||
|
`docs/ci/pull_request_template.md`.
|
||||||
|
7. **Review** by a maintainer (see `docs/MAINTAINERS.md`: pedagogy, tone, correctness, English version, tests,
|
||||||
|
accessibility, security), then merge.
|
||||||
|
|
||||||
|
By contributing you agree that your contribution is published under the project licence (MIT).
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- Code, identifiers, file names and commit messages in **English**; comments in **French**.
|
||||||
|
- **4-space** indentation everywhere (tabs only for `make`).
|
||||||
|
- JavaScript: ES2022 classes and native modules, no framework without a written justification.
|
||||||
|
- Python: typed, `pyright`-clean (`make typecheck`).
|
||||||
|
- UI and teaching content **bilingual fr/en**.
|
||||||
|
- No dependency on a paid or proprietary service.
|
||||||
|
|
||||||
|
## Useful commands
|
||||||
|
|
||||||
|
| Command | Purpose |
|
||||||
|
|---|---|
|
||||||
|
| `make dev` | development server |
|
||||||
|
| `make dev-sync` | same, with the sync backend |
|
||||||
|
| `make validate-levels` | schema, manifest, translations, starter code compiles |
|
||||||
|
| `make test` | JS, Python, backend tests, level validation, narration up to date |
|
||||||
|
| `make test-e2e` | journeys in Chromium |
|
||||||
|
| `make voice` | generate the narration (Piper) |
|
||||||
|
| `make docs` | build this documentation |
|
||||||
|
| `make ci` / `make ci-e2e` | the whole verification chain |
|
||||||
|
|
||||||
|
## Voice narration
|
||||||
|
|
||||||
|
An `explain` step with `voice: true` needs its audio files (`make voice`, which downloads the voices and requires
|
||||||
|
`ffmpeg`). `make ci` fails if they are missing. If you cannot generate them, set `voice: false`: a maintainer will
|
||||||
|
enable narration before merging. Voices and licences: `levels/AUDIO-CREDITS.md`.
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
# Writing a level
|
||||||
|
|
||||||
|
A level is a **YAML** file: `levels/NN-slug/level.yaml`. The `id` must equal the folder name
|
||||||
|
(`^[0-9]{2}-[a-z0-9-]+$`). No application code to touch.
|
||||||
|
|
||||||
|
!!! tip "The easy way"
|
||||||
|
The [level editor](author-editor.md) fills this file for you, checks live and runs your solutions. This page
|
||||||
|
describes the format, to understand it or finish by hand.
|
||||||
|
|
||||||
|
## Structure
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
id: 05-decide
|
||||||
|
title:
|
||||||
|
fr: Prendre des décisions
|
||||||
|
en: Making decisions
|
||||||
|
difficulty: 3 # 0 to 10
|
||||||
|
xp: 70 # granted when the mission is completed
|
||||||
|
requires:
|
||||||
|
- 04-math
|
||||||
|
steps:
|
||||||
|
- type: explain
|
||||||
|
voice: true # "Listen" button (pre-generated narration)
|
||||||
|
text:
|
||||||
|
fr: "Avec `if`, le programme choisit ce qu'il fait."
|
||||||
|
en: "With `if`, the program chooses what to do."
|
||||||
|
- type: code
|
||||||
|
starter: |
|
||||||
|
age = 15
|
||||||
|
# Show "Majeur" if age is 18 or more
|
||||||
|
instruction:
|
||||||
|
fr: "Complète le programme."
|
||||||
|
en: "Complete the program."
|
||||||
|
tests:
|
||||||
|
- kind: stdout_equals
|
||||||
|
value: "Mineur\n"
|
||||||
|
hints:
|
||||||
|
fr: ["Utilise `if age >= 18:`.", "N'oublie pas `else:`."]
|
||||||
|
en: ["Use `if age >= 18:`.", "Don't forget `else:`."]
|
||||||
|
solution: |
|
||||||
|
age = 15
|
||||||
|
if age >= 18:
|
||||||
|
print("Majeur")
|
||||||
|
else:
|
||||||
|
print("Mineur")
|
||||||
|
mission:
|
||||||
|
title: {fr: Le portier, en: The doorman}
|
||||||
|
goal: {fr: "…", en: "…"}
|
||||||
|
starter: "…"
|
||||||
|
tests: []
|
||||||
|
solution: "…"
|
||||||
|
reward_sound: success_big # success_small | success_big | level_unlocked
|
||||||
|
```
|
||||||
|
|
||||||
|
The full schema is `levels/schema/level.schema.json`. A model to copy: `levels/01-hello/level.yaml`.
|
||||||
|
|
||||||
|
## Teaching rules
|
||||||
|
|
||||||
|
- **One new notion** per step, short sentences, encouraging tone, never guilt-inducing.
|
||||||
|
- Alternate `explain` and `code` steps.
|
||||||
|
- Each `code` step: a `starter` that runs as is, an `instruction`, `tests`, `hints` (from vaguest to most precise)
|
||||||
|
and a `solution`.
|
||||||
|
- A motivating final `mission`, with a `reward_sound`.
|
||||||
|
- **French and English** for every text. Python identifiers in the code stay in English.
|
||||||
|
- Texts may contain `code` between backticks.
|
||||||
|
|
||||||
|
## Reference solutions
|
||||||
|
|
||||||
|
Every `code` step and every mission with tests must have a `solution`. `make test` runs them with real Python: it
|
||||||
|
must **pass** its tests, and the starter code must **not** pass them. For random code, test the shape of the output
|
||||||
|
(regular expression) and the use of a function (`code_contains`), not a precise value.
|
||||||
|
|
||||||
|
## Scripted inputs (`inputs`)
|
||||||
|
|
||||||
|
For a program that calls `input()`, add `inputs` to the test: the code is **replayed** in isolation, each `input()`
|
||||||
|
receiving the next value in the list. Validation is deterministic, whatever the learner actually typed.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
tests:
|
||||||
|
- kind: stdout_equals
|
||||||
|
value: "Bonjour Ada\n"
|
||||||
|
inputs: ["Ada"]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Files and drawing
|
||||||
|
|
||||||
|
- Levels that read or write files must use the **`data/`** folder (the only one kept between sessions).
|
||||||
|
- Drawing levels use the `canvas` module (see [Writing and running code](../learn/code.md)) and the `drawing_*`
|
||||||
|
tests ([Validation tests](../reference/tests.md)).
|
||||||
|
|
||||||
|
## Add the level and validate
|
||||||
|
|
||||||
|
1. Add it to `levels/manifest.json` (order and `requires`).
|
||||||
|
2. `make validate-levels`, then `make test` (checks all solutions), then `make voice` if steps have `voice: true`
|
||||||
|
(commit the generated mp3 files in `levels/<id>/audio/`).
|
||||||
|
3. Propose your contribution: see the [contribution flow](flow.md).
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
A level **never contains code run by the application**, apart from the starter and solution shown to the learner.
|
||||||
|
Any new kind of validation is added to the engine, not to a level file.
|
||||||
|
|
||||||
|
## Accessibility
|
||||||
|
|
||||||
|
No information may be conveyed by colour or sound alone. A decorative image has an empty `alt`; a meaningful
|
||||||
|
illustration is described in the text.
|
||||||
@@ -0,0 +1,225 @@
|
|||||||
|
# Deployment
|
||||||
|
|
||||||
|
PyQuest is a **static application**: a web server is enough. A Django backend is **optional** (progress sync).
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
Python 3.12+, Node.js 20+, `make`, `curl`.
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make install # development tools + pinned Pyodide in vendor/pyodide
|
||||||
|
make build # produces dist/ (static application)
|
||||||
|
```
|
||||||
|
|
||||||
|
Serve the content of `dist/` at the **root of a domain**, over **HTTPS**.
|
||||||
|
|
||||||
|
## Required headers
|
||||||
|
|
||||||
|
To interrupt an infinite loop cleanly and allow `input()`, the site must be **isolated**:
|
||||||
|
|
||||||
|
```
|
||||||
|
Cross-Origin-Opener-Policy: same-origin
|
||||||
|
Cross-Origin-Embedder-Policy: require-corp
|
||||||
|
Cross-Origin-Resource-Policy: same-origin
|
||||||
|
```
|
||||||
|
|
||||||
|
Without them the app works but must restart its engine to stop a program, and `input()` is unavailable.
|
||||||
|
Consequence: **everything is served from the same domain**, including the Python engine (Pyodide, never from a
|
||||||
|
CDN) and the fonts.
|
||||||
|
|
||||||
|
A complete nginx configuration example (MIME types, headers, cache, API) is provided in
|
||||||
|
`nginx/pyquest.conf.example`.
|
||||||
|
|
||||||
|
## Deploying to a VPS, step by step
|
||||||
|
|
||||||
|
Assumptions: a Linux VPS with **nginx**, a **domain name** pointing to it, and **SSH key** access.
|
||||||
|
|
||||||
|
**1. On the VPS (once)**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo mkdir -p /var/www/pyquest /var/www/letsencrypt
|
||||||
|
sudo chown "$USER" /var/www/pyquest # the SSH user must be able to write here
|
||||||
|
sudo apt install nginx certbot rsync
|
||||||
|
```
|
||||||
|
|
||||||
|
Then install the vhost: copy `nginx/pyquest-static.conf.example` (no backend; with the Django backend, `nginx/pyquest.conf.example`, see below) to `/etc/nginx/sites-available/pyquest` and
|
||||||
|
replace `pyquest.example.org` with your domain. The certificate does not exist yet: **first comment out the second
|
||||||
|
`server` block** (the port 443 one), then:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo ln -s /etc/nginx/sites-available/pyquest /etc/nginx/sites-enabled/pyquest
|
||||||
|
sudo nginx -t && sudo systemctl reload nginx
|
||||||
|
sudo certbot certonly --webroot -w /var/www/letsencrypt -d your-domain.example # Let's Encrypt
|
||||||
|
```
|
||||||
|
|
||||||
|
Then uncomment the 443 block and reload nginx (`sudo nginx -t && sudo systemctl reload nginx`). Certificate renewal is
|
||||||
|
automatic (the `certbot` package timer); nginx must be reloaded after each renewal:
|
||||||
|
`sudo sh -c 'printf "#!/bin/sh\nsystemctl reload nginx\n" > /etc/letsencrypt/renewal-hooks/deploy/nginx && chmod +x /etc/letsencrypt/renewal-hooks/deploy/nginx'`.
|
||||||
|
|
||||||
|
**2. On your machine: deploy**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make install
|
||||||
|
DEPLOY_HOST=user@your-domain.example make deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
`make deploy` builds `dist/`, uploads the files to `releases/<date>-<commit>/` on the VPS (only changed files
|
||||||
|
travel), then switches the `current` link **in one atomic step**: the site is never half-updated. The last 3
|
||||||
|
versions are kept. Variables: `DEPLOY_PATH` (default `/var/www/pyquest`), `DEPLOY_KEEP`.
|
||||||
|
`./scripts/deploy.sh --dry-run` shows what would be sent without changing anything.
|
||||||
|
|
||||||
|
**3. Check**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make check-deploy URL=https://your-domain.example
|
||||||
|
```
|
||||||
|
|
||||||
|
The check verifies the isolation headers, MIME types, the Python engine, the service worker and the HTTPS
|
||||||
|
redirect. Then open the site: a level with `input()` (level 03) confirms isolation works.
|
||||||
|
|
||||||
|
**4. Update or roll back**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
DEPLOY_HOST=user@your-domain.example make deploy # new version
|
||||||
|
DEPLOY_HOST=user@your-domain.example ./scripts/deploy.sh --rollback # previous version
|
||||||
|
```
|
||||||
|
|
||||||
|
Browsers pick up the new version on reload (pages and scripts go network first).
|
||||||
|
|
||||||
|
!!! warning "If something goes wrong"
|
||||||
|
- **`input()` unavailable, or stopping a loop restarts the engine**: the COOP/COEP/CORP headers are missing.
|
||||||
|
`make check-deploy` reports it.
|
||||||
|
- **Blank page, scripts refused**: wrong MIME type (a `types` block forgotten or incomplete).
|
||||||
|
- **Old version shown**: check that `service-worker.js` is served with `Cache-Control: no-cache`.
|
||||||
|
- The script never uses `sudo` or a password: only your SSH key is used, and nothing secret is in the repository.
|
||||||
|
|
||||||
|
## Testing locally before deploying
|
||||||
|
|
||||||
|
Three levels of testing, from the simplest to the most faithful to production:
|
||||||
|
|
||||||
|
| Command | What it starts | What it lets you try |
|
||||||
|
|---|---|---|
|
||||||
|
| `make dev` | development server (`http://127.0.0.1:8000/`) | the app alone |
|
||||||
|
| `make dev-sync` | same + Django backend, `/api/` proxied | sync, the login page (`/api/auth/login/`); the editor is **not** protected there |
|
||||||
|
| `make dev-nginx` | **real nginx** + Django + `dist/` (`http://127.0.0.1:8080/`) | everything: isolation headers, MIME types, the login-protected editor, sync |
|
||||||
|
|
||||||
|
`make dev-nginx` uses **the same blocks as production** (`nginx/pyquest-locations.conf.example`): what you see locally
|
||||||
|
is what will be deployed. It builds `dist/`, creates a throwaway SQLite database in `.local/stack/`, offers to create
|
||||||
|
an author account, then starts nginx and Django. **There is no default account**: on first launch, in a terminal, it asks you
|
||||||
|
to create the **administrator** account (password of at least 12 characters). Otherwise: `make dev-admin`. Sign in at
|
||||||
|
`http://127.0.0.1:8080/api/admin/` to create authors and give them access to the editor; an administrator can also open
|
||||||
|
the editor. Shortcut bypassing the administration: `make dev-author NAME=ada` (`RESET=--reset` to change the password). Stop with `Ctrl + C`. Logs: `.local/stack/logs/`.
|
||||||
|
|
||||||
|
nginx does not need to be installed as a service: only the binary is used. The easiest way (Debian/Ubuntu, no administrator rights): `make fetch-nginx`, which extracts it into `.local/nginx/`; `make dev-nginx` then finds it by itself. By hand:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p /tmp/ngx && cd /tmp/ngx && apt-get download nginx && dpkg -x nginx_*.deb root
|
||||||
|
PYQUEST_NGINX=/tmp/ngx/root/usr/sbin/nginx make dev-nginx
|
||||||
|
```
|
||||||
|
|
||||||
|
(the variable is `PYQUEST_NGINX`: nginx itself reads a variable named `NGINX`, which does not work here.)
|
||||||
|
|
||||||
|
**Journey to try** on `http://127.0.0.1:8080/`:
|
||||||
|
|
||||||
|
1. The app opens; a level with `input()` (level 03) works: isolation is active.
|
||||||
|
2. `http://127.0.0.1:8080/author.html` **redirects to the login page**. A wrong password is refused; the right account
|
||||||
|
reaches the editor; "Sign out" (on the login page) closes access again.
|
||||||
|
3. **Settings → Sync → Turn on** works (the "Last sync" line appears).
|
||||||
|
4. Check a site (local or remote): `make check-deploy URL=http://127.0.0.1:8080`.
|
||||||
|
|
||||||
|
The automated tests do this journey: `make test-e2e` includes `tests/e2e/nginx.test.mjs` (skipped if no nginx binary is
|
||||||
|
found).
|
||||||
|
|
||||||
|
## Caching
|
||||||
|
|
||||||
|
A service worker makes the app usable offline: pages and scripts are **network first** (an update is seen on
|
||||||
|
reload), the Python engine is **cache first** (versioned, immutable files).
|
||||||
|
|
||||||
|
## Django backend (optional): sync and editor access
|
||||||
|
|
||||||
|
The Django backend does **two things**, both optional: sync progress between devices, and **protect access to the
|
||||||
|
level editor** (`author.html`) with a login. The learning application works entirely without it.
|
||||||
|
|
||||||
|
1. **Database: MariaDB** (or MySQL). Create a dedicated database and user (`utf8mb4` character set):
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE DATABASE pyquest CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
CREATE USER 'pyquest'@'localhost' IDENTIFIED BY '…a long password…';
|
||||||
|
GRANT ALL PRIVILEGES ON pyquest.* TO 'pyquest'@'localhost';
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Install** in a dedicated virtual environment (Django 5.2 requires MariaDB 10.5 or later):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo apt install pkg-config libmariadb-dev build-essential python3-dev # to build mysqlclient
|
||||||
|
python3 -m venv /opt/pyquest/venv
|
||||||
|
/opt/pyquest/venv/bin/pip install -r backend/requirements-prod.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Environment variables** (never committed; for example in a file read by the systemd unit, mode `600`):
|
||||||
|
`PYQUEST_SECRET_KEY` (long random string), `PYQUEST_ALLOWED_HOSTS` (your domain), `PYQUEST_ORIGIN`
|
||||||
|
(`https://your-domain.example`), `PYQUEST_DB_NAME`, `PYQUEST_DB_USER`, `PYQUEST_DB_PASSWORD`, and if needed
|
||||||
|
`PYQUEST_DB_HOST` (default `127.0.0.1`), `PYQUEST_DB_PORT` (default `3306`) and `PYQUEST_STATIC_ROOT` (default
|
||||||
|
`/var/www/pyquest/static`, the administration's static files). Settings:
|
||||||
|
`DJANGO_SETTINGS_MODULE=pyquest_api.settings.production`.
|
||||||
|
4. **Create the tables**: `python manage.py migrate` (in `backend/`).
|
||||||
|
5. **Run** with `gunicorn` on `127.0.0.1:8001` (`gunicorn pyquest_api.wsgi --bind 127.0.0.1:8001`), managed by
|
||||||
|
systemd. nginx proxies `/api/` to it, **on the same domain**: use `nginx/pyquest.conf.example`, and copy
|
||||||
|
`nginx/pyquest-locations.conf.example` and `nginx/pyquest-author-headers.conf.example` into `/etc/nginx/snippets/` as
|
||||||
|
`pyquest-locations.conf` and `pyquest-author-headers.conf`.
|
||||||
|
|
||||||
|
### Administration and author accounts
|
||||||
|
|
||||||
|
Two distinct notions:
|
||||||
|
|
||||||
|
- **administrators** (`is_staff`) open the **Django administration** at `/api/admin/`: they create accounts, deactivate
|
||||||
|
them, change passwords and decide **who may use the level editor**;
|
||||||
|
- **authors** (the "May use the level editor" permission, given by the **Auteurs** group) open the editor
|
||||||
|
(`author.html`) and nothing else: they have no access to the administration.
|
||||||
|
|
||||||
|
**First administrator** (on the server, once):
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend && python manage.py createsuperuser # password of at least 12 characters
|
||||||
|
python manage.py collectstatic --noinput # administration files, served by nginx
|
||||||
|
```
|
||||||
|
|
||||||
|
`collectstatic` writes into `PYQUEST_STATIC_ROOT` (default `/var/www/pyquest/static`), which nginx serves under
|
||||||
|
`/api/static/` (the `alias` in `pyquest-locations.conf`). Redo it after a Django upgrade.
|
||||||
|
|
||||||
|
**Managing authors**: open `https://your-domain.example/api/admin/`, sign in, then **Users**:
|
||||||
|
|
||||||
|
- tick accounts, choose the action **"Autoriser à utiliser l'éditeur de niveaux"** (or **"Retirer l'accès…"**), then
|
||||||
|
**Go**: the **Éditeur de niveaux** column shows the state;
|
||||||
|
- **Add user** creates an account (username, password); then add it to the **Auteurs** group, or use the action above;
|
||||||
|
- deactivating an account (the "Active" box) removes all access at the next check.
|
||||||
|
|
||||||
|
On the command line, `python manage.py create_author ada` creates an author account directly, bypassing the
|
||||||
|
administration; `--reset` changes its password, `--admin` makes it an administrator (access to `/api/admin/`).
|
||||||
|
|
||||||
|
An administrator can also use the editor (a superuser has every permission). The `is_staff` status alone is **not
|
||||||
|
enough** to open the editor.
|
||||||
|
|
||||||
|
**Security**:
|
||||||
|
|
||||||
|
- 8-hour session, `HttpOnly` and `Secure` cookie, CSRF-protected forms, pages that cannot be framed
|
||||||
|
(`X-Frame-Options`);
|
||||||
|
- **brute-force protection** shared by the editor login and the administration login: after 5 failures on an account
|
||||||
|
(or 20 from one address) within 15 minutes, logins are refused; nginx also rate-limits;
|
||||||
|
- to reduce the exposure of `/api/admin/` further, uncomment `allow` / `deny` in `pyquest-locations.conf` (restrict it to
|
||||||
|
your network) or only reach it through a VPN;
|
||||||
|
- no password recovery by email: an administrator changes it (administration or `create_author --reset`).
|
||||||
|
|
||||||
|
### Privacy
|
||||||
|
|
||||||
|
For sync, the server stores, for each token, the **token fingerprint** (SHA-256) and the **progress JSON** (completed
|
||||||
|
levels, badges, streak). No learner account, no email address, no analytics. Users can erase everything from the
|
||||||
|
settings (`DELETE` route). Accounts (authors, administrators) only hold a username and the (hashed) password.
|
||||||
|
|
||||||
|
## Without a backend
|
||||||
|
|
||||||
|
Serving `dist/` is enough (`nginx/pyquest-static.conf.example`). The "Sync" section of the settings then says no server
|
||||||
|
is available, and file backup remains usable. The level editor (`author.html`) is then **public**: to avoid exposing
|
||||||
|
it, use the backend above or delete it from `dist/` before uploading.
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# Going live and operations
|
||||||
|
|
||||||
|
This page is the **roadmap** for installing PyQuest on a VPS, then running it. It relies on scripts tested without a
|
||||||
|
server; what touches the VPS itself could not be tried for real before the first installation: always start with
|
||||||
|
`--dry-run` and `vps-doctor`.
|
||||||
|
|
||||||
|
## Have at hand
|
||||||
|
|
||||||
|
- the VPS SSH address and your key (`user@host`), the user having `sudo`;
|
||||||
|
- the **domain name**, already pointing to the VPS (A/AAAA record);
|
||||||
|
- an email address (Let's Encrypt expiry notices);
|
||||||
|
- the **MariaDB** version in place (10.5 or later) and administrator access to create a database there;
|
||||||
|
- nginx 1.25.1 or later preferably (otherwise see the `http2` comment in the examples).
|
||||||
|
|
||||||
|
## First installation (in order)
|
||||||
|
|
||||||
|
| # | Where | Command | Result |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | your machine | `make ci` | everything green before sending |
|
||||||
|
| 2 | your machine | `DEPLOY_HOST=u@h make vps-bootstrap DOMAIN=pyquest.example.org ARGS=--dry-run` | **simulation**: nothing is written to the VPS |
|
||||||
|
| 3 | your machine | `DEPLOY_HOST=u@h make vps-bootstrap DOMAIN=pyquest.example.org ARGS="--certbot you@mail"` | packages, `pyquest` user, folders, Python environment, environment file (secret key generated), systemd service, nginx, certificate |
|
||||||
|
| 4 | VPS | adapt then `sudo mariadb < deploy/mariadb-setup.sql.example` | `pyquest` database and its user |
|
||||||
|
| 5 | VPS | put the database password in `/etc/pyquest/env` (`PYQUEST_DB_PASSWORD`) | the service can connect |
|
||||||
|
| 6 | VPS | `sudo systemctl enable --now pyquest` | migrations and static files applied at startup |
|
||||||
|
| 7 | VPS | `createsuperuser` (command printed at the end of the installation) | first administrator |
|
||||||
|
| 8 | your machine | `DEPLOY_HOST=u@h make deploy` | the site is online |
|
||||||
|
| 9 | your machine | `make check-deploy URL=https://pyquest.example.org` | headers, MIME types, Python engine, HTTPS redirect |
|
||||||
|
| 10 | your machine | `DEPLOY_HOST=u@h make vps-doctor` | everything is "ok" |
|
||||||
|
|
||||||
|
Then, in a browser: level 03 (`input()`), `/author.html` (redirects to the login), `/api/admin/` (administration), and
|
||||||
|
**Settings → Sync → Turn on**.
|
||||||
|
|
||||||
|
The scripts are **idempotent**: you can rerun them after an error; they never replace a configuration file or a secret
|
||||||
|
that is already there.
|
||||||
|
|
||||||
|
## What the installation does, concretely
|
||||||
|
|
||||||
|
| Item | Location on the VPS |
|
||||||
|
|---|---|
|
||||||
|
| Static site (successive versions) | `/var/www/pyquest/releases/…`, `current` link |
|
||||||
|
| Administration static files | `/var/www/pyquest/static` |
|
||||||
|
| Backend code | `/opt/pyquest/backend` |
|
||||||
|
| Python environment | `/opt/pyquest/venv` |
|
||||||
|
| Secrets and settings | `/etc/pyquest/env` (mode 640, `root:pyquest`) |
|
||||||
|
| Service | `pyquest.service` (gunicorn, `127.0.0.1:8001`, `pyquest` system user) |
|
||||||
|
| nginx | `/etc/nginx/sites-available/pyquest`, snippets in `/etc/nginx/snippets/` |
|
||||||
|
| Backups | `/var/backups/pyquest` |
|
||||||
|
|
||||||
|
The only right given without a password to your user is `systemctl restart|status pyquest`
|
||||||
|
(`/etc/sudoers.d/pyquest`).
|
||||||
|
|
||||||
|
## Day-to-day operations
|
||||||
|
|
||||||
|
| I want to… | Command |
|
||||||
|
|---|---|
|
||||||
|
| publish a new site version | `DEPLOY_HOST=u@h make deploy` |
|
||||||
|
| go back to the previous site version | `DEPLOY_HOST=u@h ./scripts/deploy.sh --rollback` |
|
||||||
|
| publish a new backend version | `DEPLOY_HOST=u@h make deploy-backend` (restarts the service; automatic migrations) |
|
||||||
|
| see the server state | `DEPLOY_HOST=u@h make vps-doctor` |
|
||||||
|
| read the logs | `journalctl -u pyquest -f`; `/var/log/nginx/error.log` |
|
||||||
|
| manage authors | `https://domain/api/admin/` |
|
||||||
|
| check the published site | `make check-deploy URL=https://domain` |
|
||||||
|
|
||||||
|
### Database backup
|
||||||
|
|
||||||
|
It holds the synced progress and the accounts. `scripts/backup_db.sh` makes a compressed, verified export (an empty
|
||||||
|
backup is refused) in `/var/backups/pyquest`, and keeps the last 14. Credentials are read from `/etc/pyquest/env`,
|
||||||
|
never passed on the command line.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo ./scripts/backup_db.sh # by hand
|
||||||
|
echo '30 3 * * * root /opt/pyquest/scripts/backup_db.sh' | sudo tee /etc/cron.d/pyquest-backup # every night
|
||||||
|
gunzip < /var/backups/pyquest/pyquest-YYYYMMDD-HHMMSS.sql.gz | sudo mariadb pyquest # restore
|
||||||
|
```
|
||||||
|
|
||||||
|
(The installation puts the script in `/opt/pyquest/scripts/`.) Remember to move the backups off the VPS (copy to another machine).
|
||||||
|
|
||||||
|
### Security updates
|
||||||
|
|
||||||
|
`sudo apt update && sudo apt upgrade` regularly; after a Django upgrade (`pip install -r
|
||||||
|
backend/requirements-prod.txt`), rerun `make deploy-backend`. The certificate renews itself (`certbot` timer);
|
||||||
|
`vps-doctor` flags an approaching expiry.
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
| Symptom | Likely cause | What to do |
|
||||||
|
|---|---|---|
|
||||||
|
| `vps-doctor`: `pyquest` service inactive | database password missing or wrong | `journalctl -u pyquest -n 50`, fix `/etc/pyquest/env` |
|
||||||
|
| the API answers 500 | database unreachable | `systemctl status mariadb`, check `PYQUEST_DB_*` |
|
||||||
|
| login page: "Forbidden (CSRF)" | wrong `PYQUEST_ORIGIN` | must be exactly `https://domain` |
|
||||||
|
| administration without styles | static files missing | `sudo systemctl restart pyquest` (reruns `collectstatic`) |
|
||||||
|
| `input()` unavailable | COOP/COEP headers missing | `make check-deploy`; check the nginx snippets |
|
||||||
|
| 502 on `/api/` | service stopped | `sudo systemctl status pyquest` |
|
||||||
|
| 503 on the login | nginx rate limit exceeded | wait a minute |
|
||||||
|
| login refused "Too many attempts" | 5 failures in 15 minutes | wait 15 minutes |
|
||||||
|
|
||||||
|
## Resuming work later
|
||||||
|
|
||||||
|
The deployment progress and next steps are in `CONTEXT.md` (section "Déploiement sur le VPS"). To resume a session:
|
||||||
|
read it, run `make ci`, then `make vps-doctor` to see where the server stands.
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
# PyQuest
|
||||||
|
|
||||||
|
**Learn Python by doing, right in your browser.** No installation, no account: open the page, write code, see
|
||||||
|
the result. The app also works offline.
|
||||||
|
|
||||||
|
## What you get
|
||||||
|
|
||||||
|
- **Real Python.** Your code is run by CPython (through Pyodide) inside your browser. Errors are Python's real
|
||||||
|
errors, explained in plain language.
|
||||||
|
- **15 levels** (from "What is a program?" to classes and a small drawing project), each with short explanations,
|
||||||
|
guided exercises, progressive hints and a final mission.
|
||||||
|
- **Visible progress**: experience points (XP), badges, a day streak, a map of the path.
|
||||||
|
- **Accessible**: full keyboard use, light and dark themes, adjustable text size, sound and voice always
|
||||||
|
switchable off, interface in French and English.
|
||||||
|
|
||||||
|
## Where to start
|
||||||
|
|
||||||
|
| I want to… | Page |
|
||||||
|
|---|---|
|
||||||
|
| learn Python | [Getting started](learn/getting-started.md) |
|
||||||
|
| understand cells, errors and drawing | [Writing and running code](learn/code.md) |
|
||||||
|
| find my progress on another device | [Progress and backup](learn/progress.md) |
|
||||||
|
| adjust text and sound, use the keyboard or a screen reader | [Accessibility and settings](learn/accessibility.md) |
|
||||||
|
| propose a level or a fix | [Contribution flow](contribute/flow.md) |
|
||||||
|
| install PyQuest on my server | [Deployment](host/deploy.md) |
|
||||||
|
|
||||||
|
## Project principles
|
||||||
|
|
||||||
|
- **Self-contained**: everything happens in the browser. A server is only needed to host the files, and syncing
|
||||||
|
between devices is **optional**.
|
||||||
|
- **Privacy**: no analytics, no third-party service. Nothing leaves your device unless you turn on sync.
|
||||||
|
- **Open**: MIT licence, levels written in YAML, a built-in level editor to contribute without coding.
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Accessibility and settings
|
||||||
|
|
||||||
|
PyQuest aims at **WCAG 2.2 AA**. The **Settings** button opens the following panel.
|
||||||
|
|
||||||
|
## Settings
|
||||||
|
|
||||||
|
| Setting | Effect |
|
||||||
|
|---|---|
|
||||||
|
| Language | French or English; the current level restarts in the new language |
|
||||||
|
| Text size | from 80% to 200% |
|
||||||
|
| Theme | automatic (follows your system), light or dark |
|
||||||
|
| Guide character | shows or hides the encouragement bubbles |
|
||||||
|
| Sound effects / Volume | success and error sounds, can be turned off; "Test the sound" |
|
||||||
|
| Voice / Speed | the "Listen" button of explanations, can be turned off; "Test the voice" |
|
||||||
|
| Author mode | shows the link to the [level editor](../contribute/author-editor.md) |
|
||||||
|
|
||||||
|
Sound and voice **never** start on their own. No information is conveyed by sound or colour alone: every result is
|
||||||
|
also written ("Well done, that's correct!", "Not yet.").
|
||||||
|
|
||||||
|
## Keyboard
|
||||||
|
|
||||||
|
Everything works without a mouse.
|
||||||
|
|
||||||
|
| Key | Action |
|
||||||
|
|---|---|
|
||||||
|
| `Tab` / `Shift + Tab` | move between controls |
|
||||||
|
| `Ctrl + Enter` (`Cmd + Enter`) | run the cell |
|
||||||
|
| `Esc` | close the "Levels" or "Settings" panel (focus returns to the button that opened it) |
|
||||||
|
| `Tab` in the code editor | indent; `Esc` then `Tab` to leave the editor |
|
||||||
|
|
||||||
|
While a panel is open, the rest of the page is set aside and focus stays inside.
|
||||||
|
|
||||||
|
## Screen readers
|
||||||
|
|
||||||
|
Controls have explicit names, results and errors are announced (`role="status"` regions), the progress map and
|
||||||
|
badges have their states in text, and the canvas drawing has a description and a list of lines.
|
||||||
|
|
||||||
|
!!! note "Feedback welcome"
|
||||||
|
The app is tested automatically, but a try with a real screen reader (Orca, NVDA, VoiceOver) remains the best
|
||||||
|
check. If something is not announced or is confusing, report it: it is a defect to fix.
|
||||||
|
|
||||||
|
## Offline
|
||||||
|
|
||||||
|
PyQuest is an installable web app (PWA). After a first complete load it works without a connection; your browser
|
||||||
|
may offer to install it.
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# Writing and running code
|
||||||
|
|
||||||
|
## Cells
|
||||||
|
|
||||||
|
Each exercise has a **cell**: a code area, and below it the output and the validation result.
|
||||||
|
|
||||||
|
| Action | How |
|
||||||
|
|---|---|
|
||||||
|
| Run | **Run** button or `Ctrl + Enter` (`Cmd + Enter` on Mac) |
|
||||||
|
| Stop a running program | **Stop** button (useful against an infinite loop) |
|
||||||
|
| Start over | **Reset** button: restores the starting code |
|
||||||
|
| Hint | **Hint** button: one more hint at each click |
|
||||||
|
| Solution | "Show the solution", below the cell |
|
||||||
|
|
||||||
|
Between runs, **variables are kept** from one cell to the next within a level, like in a notebook.
|
||||||
|
|
||||||
|
## Indenting with the Tab key
|
||||||
|
|
||||||
|
Python is structured by indentation. In the editor:
|
||||||
|
|
||||||
|
- **Tab** inserts spaces (4, aligned to the next column); with several lines selected, it indents them all.
|
||||||
|
- **Shift + Tab** dedents.
|
||||||
|
- **Esc then Tab** **leaves** the code field, so keyboard navigation never gets stuck. As soon as you type in the
|
||||||
|
editor again, Tab indents again.
|
||||||
|
|
||||||
|
## Errors
|
||||||
|
|
||||||
|
When your code crashes, PyQuest shows:
|
||||||
|
|
||||||
|
- the translated error **type** ("Python does not know this name");
|
||||||
|
- a plain-language **explanation** and a **tip**;
|
||||||
|
- the **line** concerned;
|
||||||
|
- Python's real technical message, under "Technical details", so you learn to read it.
|
||||||
|
|
||||||
|
## Reading data with `input()`
|
||||||
|
|
||||||
|
When your program calls `input("Your name? ")`, an input field appears under the output: type your answer and
|
||||||
|
validate with **Enter** or the **Send** button. The question is shown as in a real terminal.
|
||||||
|
|
||||||
|
!!! note
|
||||||
|
Interactive input needs the page to be served with the isolation headers (see
|
||||||
|
[Deployment](../host/deploy.md)). Without them, `input()` raises `EOFError`: that is a hosting issue, not a
|
||||||
|
problem with your code.
|
||||||
|
|
||||||
|
## Files
|
||||||
|
|
||||||
|
Python can read and write files. In the browser, **only the `data/` folder is kept** when you close the page (for
|
||||||
|
example `open("data/agenda.txt", "w")`). Any file written elsewhere disappears on reload.
|
||||||
|
|
||||||
|
## Drawing with `canvas`
|
||||||
|
|
||||||
|
From level 13 you have a drawing sheet:
|
||||||
|
|
||||||
|
```python
|
||||||
|
import canvas
|
||||||
|
|
||||||
|
canvas.line(0, 0, 100, 0, "red") # a red line from (0, 0) to (100, 0)
|
||||||
|
canvas.line(0, 0, 0, 100, "blue")
|
||||||
|
```
|
||||||
|
|
||||||
|
- The point `(0, 0)` is at the **centre**; positive numbers go **right** and **up**, up to 200.
|
||||||
|
- Colours: `black`, `red`, `green`, `blue`, `orange`, `purple`, `gray`.
|
||||||
|
- `canvas.clear()` wipes the sheet. **Each run starts from a blank sheet.**
|
||||||
|
- The drawing appears under the cell with a **written description** and the **list of all lines** ("See the list
|
||||||
|
of lines"): nothing is conveyed by the image alone.
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
# Getting started
|
||||||
|
|
||||||
|
## Open PyQuest
|
||||||
|
|
||||||
|
Open your PyQuest instance in a recent browser (Firefox, Chrome, Edge). The Python engine loads on first start
|
||||||
|
(a few seconds); after that the app remembers everything and works **offline**.
|
||||||
|
|
||||||
|
You land on your **first unfinished level**. To open a specific level, use the **Levels** button (see below) or a
|
||||||
|
direct link like `https://…/#/levels/05-decide`.
|
||||||
|
|
||||||
|
## A level, step by step
|
||||||
|
|
||||||
|
A level is a series of steps shown one after the other:
|
||||||
|
|
||||||
|
1. **Explanation**: a short text. When a **Listen** button is present, a voice reads the text (never
|
||||||
|
automatically: you click).
|
||||||
|
2. **Code exercise**: an instruction and a pre-filled code cell. You edit, run, and see the result and the
|
||||||
|
validation.
|
||||||
|
3. **Final mission**: a small program that brings together what you just learned. Completing it finishes the level.
|
||||||
|
|
||||||
|
The **Continue** button moves to the next step. The **Previous level** and **Next level** buttons at the top
|
||||||
|
change level.
|
||||||
|
|
||||||
|
!!! tip "Don't panic"
|
||||||
|
Mistakes are normal: the error is explained, and you can ask for **hints** (from vague to precise) or, as a
|
||||||
|
last resort, show the **solution**.
|
||||||
|
|
||||||
|
## The "Levels" button
|
||||||
|
|
||||||
|
It opens a panel with:
|
||||||
|
|
||||||
|
- the **path map**: each level is a dot, with its state written out in words ("Done", "In progress", "To do");
|
||||||
|
- the **badge shelf**: badges you earned (with the date) and those still to unlock.
|
||||||
|
|
||||||
|
Choosing a level on the map opens it directly: nothing is locked.
|
||||||
|
|
||||||
|
## The guide character
|
||||||
|
|
||||||
|
A little character encourages you after a success, offers a hint when you are stuck, and welcomes you back after a
|
||||||
|
break. It never judges. You can hide it in the [settings](accessibility.md).
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# Progress and backup
|
||||||
|
|
||||||
|
## XP, badges, streak
|
||||||
|
|
||||||
|
- **XP (experience points)**: each level is worth some points, granted **only once**, when you complete its **final
|
||||||
|
mission**. Redoing a level earns nothing more.
|
||||||
|
- **Badges**: rewards for milestones (first level, three levels, 100 XP, 3-day and 7-day streaks).
|
||||||
|
- **Day streak**: the number of consecutive days you practised. Missing a day resets it to 1, without blame.
|
||||||
|
|
||||||
|
Nothing is locked: points and badges only measure your progress.
|
||||||
|
|
||||||
|
## Where is my progress saved?
|
||||||
|
|
||||||
|
**In your browser**, on your device (local storage). You do nothing. Beware: clearing the site's data, or switching
|
||||||
|
browser or device, makes it disappear. Two solutions below.
|
||||||
|
|
||||||
|
## Back up to a file (no server)
|
||||||
|
|
||||||
|
**Settings → Progress backup**
|
||||||
|
|
||||||
|
- **Export my progress** downloads a `pyquest-progress-YYYY-MM-DD.json` file.
|
||||||
|
- **Import progress** reads such a file and **merges** it with your current progress: all levels and badges are
|
||||||
|
kept, nothing is ever lost. The app tells you how many levels are new.
|
||||||
|
|
||||||
|
Keep the file or copy it to another device. An invalid file is refused without changing anything.
|
||||||
|
|
||||||
|
## Sync between devices (optional)
|
||||||
|
|
||||||
|
If your PyQuest instance offers sync (a server with the sync module), you can find your progress everywhere,
|
||||||
|
**without creating an account**.
|
||||||
|
|
||||||
|
**Settings → Sync between devices**
|
||||||
|
|
||||||
|
1. On the first device: **Turn on sync**. A **secret token** is created and shown.
|
||||||
|
2. On the second device: paste that token into "Or paste the token from another device", then **Link this device**.
|
||||||
|
The two progresses are merged.
|
||||||
|
3. After that it is automatic: at startup, when the network returns, and shortly after each completed level.
|
||||||
|
**Sync now** forces an exchange.
|
||||||
|
|
||||||
|
!!! warning "The token is like a password"
|
||||||
|
It gives access to your progress. Do not share it. **If lost, it cannot be recovered**: the server only keeps a
|
||||||
|
fingerprint of it. Also make a file backup.
|
||||||
|
|
||||||
|
- **Turn off (keep the server data)** stops syncing on this device.
|
||||||
|
- **Turn off and erase the server data** permanently deletes what is stored for this token.
|
||||||
|
- **Offline** or server unavailable: a message says so, your local progress stays intact and syncing resumes by
|
||||||
|
itself.
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
# Architecture
|
||||||
|
|
||||||
|
## Overview
|
||||||
|
|
||||||
|
```text
|
||||||
|
┌───────────────────────────── Browser ──────────────────────────────┐
|
||||||
|
│ Interface (ES modules) ──► Worker client ◄──► Web Worker │
|
||||||
|
│ │ Pyodide / CPython │
|
||||||
|
│ ▼ │ │
|
||||||
|
│ IndexedDB: progress, settings persistent data/ │
|
||||||
|
└────────┬───────────────────────────────────────────────────────────┘
|
||||||
|
│ reads (optional)
|
||||||
|
▼ ▼
|
||||||
|
levels/*.yaml + JSON schema Django backend /api/sync/
|
||||||
|
```
|
||||||
|
|
||||||
|
The application is **self-contained**: everything runs in the browser. The backend is only an optional store for
|
||||||
|
progress.
|
||||||
|
|
||||||
|
## Key decisions
|
||||||
|
|
||||||
|
- **Python engine: Pyodide** (real CPython in WebAssembly): faithful error messages, complete standard library. It
|
||||||
|
runs in a **Web Worker** so the interface never freezes.
|
||||||
|
- **Interruption** through a `SharedArrayBuffer` (Python's SIGINT): needs an isolated site (COOP/COEP), hence a
|
||||||
|
Pyodide served from the same domain. `input()` also uses a `SharedArrayBuffer`.
|
||||||
|
- **Declarative levels**: YAML validated by JSON Schema; validating an exercise goes through a **closed** list of
|
||||||
|
test types, never through code coming from the level.
|
||||||
|
- **JavaScript**: ES2022 classes and native modules, no framework.
|
||||||
|
- **Files**: only `data/` is mounted on IndexedDB (IDBFS) and survives sessions.
|
||||||
|
- **Drawing**: the `canvas` module records lines returned with the run result; the interface displays them and the
|
||||||
|
`drawing_*` tests examine them.
|
||||||
|
- **Narration**: pre-generated mp3 files (Piper, build tool only), falling back to the system voice.
|
||||||
|
|
||||||
|
## What lives where
|
||||||
|
|
||||||
|
| Folder | Content |
|
||||||
|
|---|---|
|
||||||
|
| `app/` | the application (HTML, CSS, `js/core`, `js/ui`, `js/author`, `js/workers`, `python/`) |
|
||||||
|
| `levels/` | levels, manifest, schema, narration |
|
||||||
|
| `backend/` | Django sync API |
|
||||||
|
| `scripts/` | dev server, validation, build, voices |
|
||||||
|
| `tests/` | `js/` (node:test), `python/`, `e2e/` (Chromium) |
|
||||||
|
| `docs/site/` | this documentation; `docs/design/`: design notes (in French) |
|
||||||
|
|
||||||
|
The detailed reasoning behind each choice is in the repository's `docs/design/`.
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# Sync API
|
||||||
|
|
||||||
|
Available only if the Django backend is deployed. It is always on the **same domain** as the application:
|
||||||
|
`/api/sync/`.
|
||||||
|
|
||||||
|
## Authentication
|
||||||
|
|
||||||
|
Each request carries a **token**: `Authorization: Bearer <token>`. The token is generated by the client (256 bits,
|
||||||
|
43 URL-safe characters; the server accepts 32 to 128 `A-Za-z0-9_-` characters). The server only keeps its
|
||||||
|
**SHA-256**. There is no account and no cookie (hence no CSRF).
|
||||||
|
|
||||||
|
## Calls
|
||||||
|
|
||||||
|
| Call | Response |
|
||||||
|
|---|---|
|
||||||
|
| `GET /api/sync/` | `200 {"payload": …, "updated_at": …}`; `404 {"error": …}` if nothing is stored |
|
||||||
|
| `PUT /api/sync/` with `{"payload": …, "base": …}` | `200 {"updated_at": …}`; `409` if `base` is stale; `400` invalid or too large payload |
|
||||||
|
| `DELETE /api/sync/` | `204`: permanently erases this token's data (idempotent) |
|
||||||
|
| any call without a valid token | `401 {"error": …}` |
|
||||||
|
|
||||||
|
- `payload`: the object exported by the application (`version`, `completedLevels`, `badges`, `streak`). Maximum
|
||||||
|
size: 256 KB.
|
||||||
|
- `base` (optional): the `updated_at` read by the client. If it no longer matches the server version (another
|
||||||
|
device wrote in between), the server answers **`409`** with the current state (`payload`, `updated_at`): the
|
||||||
|
client merges and retries. This is **optimistic concurrency**.
|
||||||
|
|
||||||
|
## Who merges?
|
||||||
|
|
||||||
|
**The client.** The server stores the last JSON received and merges nothing. Merging keeps the union of completed
|
||||||
|
levels and badges, the maximum best streak, and the current streak of the most recently active device.
|
||||||
|
|
||||||
|
## Client cycle
|
||||||
|
|
||||||
|
1. `GET` then local merge;
|
||||||
|
2. `PUT` of the merged state with `base`; on `409`, merge the received state and retry (4 at most);
|
||||||
|
3. triggered on activation, at startup, when the network returns, when the tab becomes visible again and 2 seconds
|
||||||
|
after a local change.
|
||||||
|
|
||||||
|
Errors are visible states (`offline`, `token refused`, `server unavailable`, `data refused`, `invalid data`) and
|
||||||
|
never block the application. A `404` that is not JSON (a static server without Django) is treated as "server
|
||||||
|
unavailable".
|
||||||
|
|
||||||
|
## Editor access (author accounts)
|
||||||
|
|
||||||
|
The same backend exposes, for nginx and for the login page:
|
||||||
|
|
||||||
|
| Call | Purpose |
|
||||||
|
|---|---|
|
||||||
|
| `GET /api/auth/check/` | `204` if the session belongs to an active account with the `authors.use_editor` permission (the "Auteurs" group), otherwise `401`; used by nginx `auth_request` (not reachable from outside) |
|
||||||
|
| `GET /api/auth/login/` | login form (French or English from `Accept-Language`) |
|
||||||
|
| `POST /api/auth/login/` | sign in (CSRF); `302` to `next` (local paths only), `200` with a message if refused, `429` when too many attempts |
|
||||||
|
| `GET /api/auth/me/` | `200 {username, csrf}` for a signed-in author (shows the name and carries the token of the editor's sign-out button), otherwise `401` |
|
||||||
|
| `POST /api/auth/logout/` | sign out (CSRF); redirects to the login page |
|
||||||
|
| `/api/admin/` | Django administration (accounts, "Auteurs" group); static files under `/api/static/` |
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
Any data received from the server or from a file is treated as untrusted and strictly validated before merging
|
||||||
|
(types, bounds, identifiers). The server enforces the maximum size; nginx rate-limits.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Validation tests
|
||||||
|
|
||||||
|
The list of test types (`tests[].kind`) is **closed**: adding a type goes through the engine.
|
||||||
|
|
||||||
|
| `kind` | Fields | Passes if… |
|
||||||
|
|---|---|---|
|
||||||
|
| `no_syntax_error` | — | the code has no syntax error |
|
||||||
|
| `stdout_equals` | `value` | the output is **exactly** equal (final newline included) |
|
||||||
|
| `stdout_contains` | `value` | the output contains this text |
|
||||||
|
| `stdout_matches_regex` | `value` | the whole output matches the regular expression |
|
||||||
|
| `var_equals` | `name`, `value` | the variable equals `value` (`10.0` is a `float`, `10` an `int`) |
|
||||||
|
| `var_type_is` | `name`, `value` | the variable has this type (`str`, `int`, `float`, `list`…) |
|
||||||
|
| `code_contains` | `value` | the learner's code contains this text (e.g. `random.choice`) |
|
||||||
|
| `drawing_segments` | `value` | the drawing has this number of lines: `"4"` (exactly) or `"4+"` (at least) |
|
||||||
|
| `drawing_has_line` | `value` | a line joins two points: `"0,0 100,0"` or with a colour `"0,0 100,0 red"` |
|
||||||
|
| `drawing_colors` | `value` | all these colours are used: `"red,blue"` |
|
||||||
|
|
||||||
|
Common fields: `message` (`fr`/`en` text shown when the test fails) and `inputs` (scripted inputs, see
|
||||||
|
[Writing a level](../contribute/write-level.md)).
|
||||||
|
|
||||||
|
## Details
|
||||||
|
|
||||||
|
- **Output**: the `input()` prompt is in the output (as in Python), not the answer.
|
||||||
|
- **`code_contains`** is not evaluated on a replay: useless with `inputs`.
|
||||||
|
- **Drawing**: a line counts as present if its ends are within 0.5 of the requested ones, **in either direction**.
|
||||||
|
Colours: `black`, `red`, `green`, `blue`, `orange`, `purple`, `gray`. The drawing comes from the cell's run (a
|
||||||
|
blank sheet at each run).
|
||||||
|
- **A runtime error** always fails the step.
|
||||||
|
|
||||||
|
## Adding a test type
|
||||||
|
|
||||||
|
1. `ValidationEngine`: interpret the type (and `supportedKinds`).
|
||||||
|
2. `levels/schema/level.schema.json`: add it to the enumeration.
|
||||||
|
3. `app/js/author/LevelDraft.js`: add it to `TEST_KINDS`.
|
||||||
|
4. Editor catalogues: `author.kind.<type>` and its help; the application's `reason.*` messages.
|
||||||
|
5. `LevelLinter` if consistency rules are needed, then unit tests.
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
# L'éditeur de niveaux
|
||||||
|
|
||||||
|
Un outil intégré pour écrire un niveau **sans écrire de YAML à la main**, et sans serveur.
|
||||||
|
|
||||||
|
## Y accéder
|
||||||
|
|
||||||
|
1. Lance `make dev` (ou ouvre ton instance).
|
||||||
|
2. Dans **Réglages**, active **Mode auteur**.
|
||||||
|
3. Clique sur **Ouvrir l'éditeur de niveaux** (page `/author.html`).
|
||||||
|
|
||||||
|
Les apprenants ne voient pas ce lien tant que le mode auteur est désactivé.
|
||||||
|
|
||||||
|
!!! note "Sur un serveur protégé"
|
||||||
|
Si l'instance a le backend Django, l'accès à `/author.html` demande une connexion (compte autorisé par un
|
||||||
|
administrateur dans l'administration Django, voir [Déploiement](../host/deploy.md)). Une fois
|
||||||
|
connecté, l'en-tête de l'éditeur affiche ton nom et un bouton **Se déconnecter** (la session dure 8 heures). En local
|
||||||
|
(`make dev`), pas de connexion ni de bouton.
|
||||||
|
|
||||||
|
## Ce qu'il fait
|
||||||
|
|
||||||
|
- **Formulaires** pour les informations du niveau, les étapes (explication ou exercice de code), les tests, les
|
||||||
|
indices, les solutions et la mission. Chaque texte est saisi en français **et** en anglais, côte à côte.
|
||||||
|
- **Vérifications en direct** : conformité au schéma (messages ciblés), traductions manquantes, `requires`,
|
||||||
|
solutions manquantes, tests incohérents, expressions régulières invalides, rappel de la narration à générer.
|
||||||
|
Un bouton mène au champ en cause.
|
||||||
|
- **Exécuter les exercices** : lance chaque solution avec le **vrai Python** du navigateur, comme `make test`. La
|
||||||
|
solution doit passer ses tests et le code de départ ne doit pas les passer.
|
||||||
|
- **Essayer** : joue le niveau comme un apprenant, dans la vraie interface (progression jamais enregistrée).
|
||||||
|
- **Exporter** : télécharge `level.yaml` au style du projet, indique la ligne à ajouter au manifeste et les
|
||||||
|
étapes suivantes. Tu peux aussi **importer** un fichier ou charger un niveau existant pour le modifier.
|
||||||
|
- Ton **brouillon** est enregistré dans le navigateur.
|
||||||
|
|
||||||
|
## Après l'export
|
||||||
|
|
||||||
|
1. Place `level.yaml` dans `levels/NN-slug/` et ajoute la ligne du manifeste.
|
||||||
|
2. `make validate-levels` et `make test`.
|
||||||
|
3. `make voice` pour les étapes narrées.
|
||||||
|
4. Ouvre ta demande de fusion ([flux de contribution](flow.md)).
|
||||||
|
|
||||||
|
## Limites
|
||||||
|
|
||||||
|
- La narration ne se génère pas dans le navigateur : `make voice` est nécessaire (l'éditeur te le rappelle).
|
||||||
|
- Les saisies scriptées sont saisies une par ligne ; une saisie vide au milieu est possible, pas en dernière position.
|
||||||
|
- L'éditeur aide mais ne remplace pas la relecture : les commandes `make` restent la référence.
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
# Flux de contribution
|
||||||
|
|
||||||
|
Tu peux proposer un **niveau**, un **correctif** ou une **traduction**. Tu n'as pas besoin de connaître le
|
||||||
|
fonctionnement interne de l'application pour écrire un niveau.
|
||||||
|
|
||||||
|
## Étapes
|
||||||
|
|
||||||
|
1. **Branche** : une branche par contribution (`level-08-functions`, `fix-hint-typo`…). Un niveau par demande de
|
||||||
|
fusion, c'est plus simple à relire.
|
||||||
|
2. **Prépare** : `make install` (outils et moteur Python), puis `make dev` pour essayer dans le navigateur
|
||||||
|
(`http://127.0.0.1:8000/`).
|
||||||
|
3. **Écris** ton niveau, de préférence avec l'[éditeur de niveaux](author-editor.md), ou ton correctif.
|
||||||
|
4. **Vérifie** : `make ci` lance les tests, la vérification de **toutes les solutions de référence** avec le vrai
|
||||||
|
Python, le typage et la construction du site. Avec Chromium installé : `make ci-e2e` ajoute les parcours dans
|
||||||
|
un vrai navigateur.
|
||||||
|
5. **Commits** : messages en anglais, courts, à l'impératif (« Add level 08 functions »).
|
||||||
|
6. **Propose** ta contribution (pull request ou merge request) ; le modèle de description est dans
|
||||||
|
`docs/ci/pull_request_template.md`.
|
||||||
|
7. **Relecture** par un mainteneur (voir `docs/MAINTAINERS.md` : pédagogie, ton, justesse, version anglaise,
|
||||||
|
tests, accessibilité, sécurité), puis fusion.
|
||||||
|
|
||||||
|
En contribuant, tu acceptes que ta contribution soit publiée sous la licence du projet (MIT).
|
||||||
|
|
||||||
|
## Conventions
|
||||||
|
|
||||||
|
- Code, identifiants, noms de fichiers et messages de commit en **anglais** ; commentaires en **français**.
|
||||||
|
- Indentation de **4 espaces** partout (tabulations seulement pour `make`).
|
||||||
|
- JavaScript : classes ES2022 et modules natifs, pas de framework sans justification écrite.
|
||||||
|
- Python : typé, compatible `pyright` (`make typecheck`).
|
||||||
|
- Interface et contenus pédagogiques **bilingues fr/en**.
|
||||||
|
- Pas de dépendance à un service payant ou propriétaire.
|
||||||
|
|
||||||
|
## Commandes utiles
|
||||||
|
|
||||||
|
| Commande | Rôle |
|
||||||
|
|---|---|
|
||||||
|
| `make dev` | serveur de développement |
|
||||||
|
| `make dev-sync` | idem, avec le backend de synchronisation |
|
||||||
|
| `make validate-levels` | schéma, manifeste, traductions, code de départ qui compile |
|
||||||
|
| `make test` | tests JS, Python, backend, validation des niveaux, narration à jour |
|
||||||
|
| `make test-e2e` | parcours dans Chromium |
|
||||||
|
| `make voice` | génère la narration (Piper) |
|
||||||
|
| `make docs` | génère cette documentation |
|
||||||
|
| `make ci` / `make ci-e2e` | toute la chaîne de vérification |
|
||||||
|
|
||||||
|
## Narration vocale
|
||||||
|
|
||||||
|
Une étape `explain` avec `voice: true` a besoin de ses fichiers audio (`make voice`, qui télécharge les voix et
|
||||||
|
demande `ffmpeg`). `make ci` échoue s'ils manquent. Si tu ne peux pas les générer, mets `voice: false` : un
|
||||||
|
mainteneur activera la narration avant la fusion. Voix et licences : `levels/AUDIO-CREDITS.md`.
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
# Écrire un niveau
|
||||||
|
|
||||||
|
Un niveau est un fichier **YAML** : `levels/NN-slug/level.yaml`. L'`id` doit être identique au nom du dossier
|
||||||
|
(`^[0-9]{2}-[a-z0-9-]+$`). Pas de code de l'application à toucher.
|
||||||
|
|
||||||
|
!!! tip "Le plus simple"
|
||||||
|
L'[éditeur de niveaux](author-editor.md) remplit ce fichier pour toi, vérifie en direct et exécute tes
|
||||||
|
solutions. Cette page décrit le format, pour comprendre ou finir à la main.
|
||||||
|
|
||||||
|
## Structure
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
id: 05-decide
|
||||||
|
title:
|
||||||
|
fr: Prendre des décisions
|
||||||
|
en: Making decisions
|
||||||
|
difficulty: 3 # 0 à 10
|
||||||
|
xp: 70 # accordés à la réussite de la mission
|
||||||
|
requires:
|
||||||
|
- 04-math
|
||||||
|
steps:
|
||||||
|
- type: explain
|
||||||
|
voice: true # bouton « Écouter » (narration pré-générée)
|
||||||
|
text:
|
||||||
|
fr: "Avec `if`, le programme choisit ce qu'il fait."
|
||||||
|
en: "With `if`, the program chooses what to do."
|
||||||
|
- type: code
|
||||||
|
starter: |
|
||||||
|
age = 15
|
||||||
|
# Affiche « Majeur » si age vaut 18 ou plus
|
||||||
|
instruction:
|
||||||
|
fr: "Complète le programme."
|
||||||
|
en: "Complete the program."
|
||||||
|
tests:
|
||||||
|
- kind: stdout_equals
|
||||||
|
value: "Mineur\n"
|
||||||
|
hints:
|
||||||
|
fr: ["Utilise `if age >= 18:`.", "N'oublie pas `else:`."]
|
||||||
|
en: ["Use `if age >= 18:`.", "Don't forget `else:`."]
|
||||||
|
solution: |
|
||||||
|
age = 15
|
||||||
|
if age >= 18:
|
||||||
|
print("Majeur")
|
||||||
|
else:
|
||||||
|
print("Mineur")
|
||||||
|
mission:
|
||||||
|
title: {fr: Le portier, en: The doorman}
|
||||||
|
goal: {fr: "…", en: "…"}
|
||||||
|
starter: "…"
|
||||||
|
tests: []
|
||||||
|
solution: "…"
|
||||||
|
reward_sound: success_big # success_small | success_big | level_unlocked
|
||||||
|
```
|
||||||
|
|
||||||
|
Le schéma complet est `levels/schema/level.schema.json`. Modèle à copier : `levels/01-hello/level.yaml`.
|
||||||
|
|
||||||
|
## Règles pédagogiques
|
||||||
|
|
||||||
|
- **Une seule notion nouvelle** par étape, phrases courtes, ton encourageant, jamais culpabilisant.
|
||||||
|
- Alterne étapes `explain` et `code`.
|
||||||
|
- Chaque étape `code` : un `starter` qui s'exécute tel quel, une `instruction`, des `tests`, des `hints`
|
||||||
|
(du plus vague au plus précis) et une `solution`.
|
||||||
|
- Une `mission` finale motivante, avec un `reward_sound`.
|
||||||
|
- **Français et anglais** pour chaque texte. Les identifiants du code Python restent en anglais.
|
||||||
|
- Les textes peuvent contenir du `code` entre accents graves.
|
||||||
|
|
||||||
|
## Solutions de référence
|
||||||
|
|
||||||
|
Chaque étape `code` et chaque mission avec tests doit avoir une `solution`. `make test` les exécute avec le vrai
|
||||||
|
Python : elle doit **passer** ses tests, et le code de départ ne doit **pas** les passer. Pour du code aléatoire,
|
||||||
|
teste la forme de la sortie (expression régulière) et l'usage d'une fonction (`code_contains`), pas une valeur
|
||||||
|
précise.
|
||||||
|
|
||||||
|
## Saisies scriptées (`inputs`)
|
||||||
|
|
||||||
|
Pour un programme qui appelle `input()`, ajoute `inputs` au test : le code est **rejoué** en isolation, chaque
|
||||||
|
`input()` recevant la valeur suivante de la liste. La validation est déterministe, quelle que soit la saisie
|
||||||
|
réelle de l'apprenant.
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
tests:
|
||||||
|
- kind: stdout_equals
|
||||||
|
value: "Bonjour Ada\n"
|
||||||
|
inputs: ["Ada"]
|
||||||
|
```
|
||||||
|
|
||||||
|
## Fichiers et dessin
|
||||||
|
|
||||||
|
- Les niveaux qui lisent ou écrivent des fichiers doivent utiliser le dossier **`data/`** (seul conservé entre les
|
||||||
|
sessions).
|
||||||
|
- Les niveaux de dessin utilisent le module `canvas` (voir [Écrire et exécuter du code](../learn/code.md)) et les
|
||||||
|
tests `drawing_*` ([Tests de validation](../reference/tests.md)).
|
||||||
|
|
||||||
|
## Ajouter le niveau et valider
|
||||||
|
|
||||||
|
1. Ajoute-le dans `levels/manifest.json` (ordre et `requires`).
|
||||||
|
2. `make validate-levels`, puis `make test` (vérifie toutes les solutions), puis `make voice` si des étapes ont
|
||||||
|
`voice: true` (commite les mp3 générés dans `levels/<id>/audio/`).
|
||||||
|
3. Propose ta contribution : voir le [flux de contribution](flow.md).
|
||||||
|
|
||||||
|
## Sécurité
|
||||||
|
|
||||||
|
Un niveau ne contient **jamais de code exécuté par l'application**, hormis le code de départ et la solution
|
||||||
|
montrés à l'apprenant. Toute nouvelle sorte de validation est ajoutée au moteur, pas à un fichier de niveau.
|
||||||
|
|
||||||
|
## Accessibilité
|
||||||
|
|
||||||
|
Aucune information ne doit passer uniquement par la couleur ou le son. Une image décorative a un `alt` vide ; une
|
||||||
|
illustration porteuse de sens est décrite dans le texte.
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
# Déploiement
|
||||||
|
|
||||||
|
PyQuest est une **application statique** : un serveur web suffit. Un backend Django est **facultatif** (synchronisation
|
||||||
|
de la progression).
|
||||||
|
|
||||||
|
## Prérequis
|
||||||
|
|
||||||
|
Python 3.12+, Node.js 20+, `make`, `curl`.
|
||||||
|
|
||||||
|
## Construire
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make install # outils de développement + Pyodide épinglé dans vendor/pyodide
|
||||||
|
make build # produit dist/ (application statique)
|
||||||
|
```
|
||||||
|
|
||||||
|
Servir le contenu de `dist/` à la **racine d'un domaine**, en **HTTPS**.
|
||||||
|
|
||||||
|
## En-têtes obligatoires
|
||||||
|
|
||||||
|
Pour interrompre proprement une boucle infinie et permettre la saisie `input()`, le site doit être **isolé** :
|
||||||
|
|
||||||
|
```
|
||||||
|
Cross-Origin-Opener-Policy: same-origin
|
||||||
|
Cross-Origin-Embedder-Policy: require-corp
|
||||||
|
Cross-Origin-Resource-Policy: same-origin
|
||||||
|
```
|
||||||
|
|
||||||
|
Sans eux, l'application fonctionne mais doit redémarrer son moteur pour arrêter un programme, et `input()` est
|
||||||
|
indisponible. Conséquence : **tout est servi depuis le même domaine**, y compris le moteur Python (Pyodide,
|
||||||
|
jamais depuis un CDN) et les polices.
|
||||||
|
|
||||||
|
Un exemple complet de configuration nginx (types MIME, en-têtes, cache, API) est fourni dans
|
||||||
|
`nginx/pyquest.conf.example`.
|
||||||
|
|
||||||
|
## Déployer sur un VPS, pas à pas
|
||||||
|
|
||||||
|
Hypothèses : un VPS Linux avec **nginx**, un **nom de domaine** qui pointe vers lui, et un accès **SSH par clé**.
|
||||||
|
|
||||||
|
**1. Sur le VPS (une seule fois)**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo mkdir -p /var/www/pyquest /var/www/letsencrypt
|
||||||
|
sudo chown "$USER" /var/www/pyquest # l'utilisateur SSH doit pouvoir écrire ici
|
||||||
|
sudo apt install nginx certbot rsync
|
||||||
|
```
|
||||||
|
|
||||||
|
Installe ensuite le vhost : copie `nginx/pyquest-static.conf.example` (sans backend ; avec le backend Django, `nginx/pyquest.conf.example`, voir plus bas) vers `/etc/nginx/sites-available/pyquest` et
|
||||||
|
remplace `pyquest.example.org` par ton domaine. Le certificat n'existe pas encore : **commente d'abord le second
|
||||||
|
bloc `server`** (celui du port 443), puis :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo ln -s /etc/nginx/sites-available/pyquest /etc/nginx/sites-enabled/pyquest
|
||||||
|
sudo nginx -t && sudo systemctl reload nginx
|
||||||
|
sudo certbot certonly --webroot -w /var/www/letsencrypt -d ton-domaine.example # Let's Encrypt
|
||||||
|
```
|
||||||
|
|
||||||
|
Décommente alors le bloc 443 et recharge nginx (`sudo nginx -t && sudo systemctl reload nginx`). Le renouvellement du
|
||||||
|
certificat est automatique (minuteur `certbot` du paquet) ; il reste à recharger nginx après renouvellement :
|
||||||
|
`sudo sh -c 'printf "#!/bin/sh\nsystemctl reload nginx\n" > /etc/letsencrypt/renewal-hooks/deploy/nginx && chmod +x /etc/letsencrypt/renewal-hooks/deploy/nginx'`.
|
||||||
|
|
||||||
|
**2. Sur ta machine : déployer**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make install
|
||||||
|
DEPLOY_HOST=utilisateur@ton-domaine.example make deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
`make deploy` construit `dist/`, envoie les fichiers dans `releases/<date>-<commit>/` sur le VPS (seuls les fichiers
|
||||||
|
modifiés voyagent), puis bascule le lien `current` **d'un seul coup** : le site n'est jamais à moitié à jour. Les
|
||||||
|
3 dernières versions sont conservées. Variables : `DEPLOY_PATH` (défaut `/var/www/pyquest`), `DEPLOY_KEEP`.
|
||||||
|
`./scripts/deploy.sh --dry-run` montre ce qui serait envoyé sans rien modifier.
|
||||||
|
|
||||||
|
**3. Vérifier**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
make check-deploy URL=https://ton-domaine.example
|
||||||
|
```
|
||||||
|
|
||||||
|
Le contrôle vérifie les en-têtes d'isolation, les types MIME, le moteur Python, le service worker et la
|
||||||
|
redirection HTTPS. Ouvre ensuite le site : un niveau avec `input()` (niveau 03) confirme que l'isolation fonctionne.
|
||||||
|
|
||||||
|
**4. Mettre à jour ou revenir en arrière**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
DEPLOY_HOST=utilisateur@ton-domaine.example make deploy # nouvelle version
|
||||||
|
DEPLOY_HOST=utilisateur@ton-domaine.example ./scripts/deploy.sh --rollback # version précédente
|
||||||
|
```
|
||||||
|
|
||||||
|
Les navigateurs récupèrent la nouvelle version au rechargement (pages et scripts passent par le réseau d'abord).
|
||||||
|
|
||||||
|
!!! warning "En cas de problème"
|
||||||
|
- **`input()` indisponible, ou arrêt d'une boucle qui redémarre le moteur** : les en-têtes COOP/COEP/CORP
|
||||||
|
manquent. `make check-deploy` le dit.
|
||||||
|
- **Page blanche, scripts refusés** : type MIME incorrect (un bloc `types` oublié ou incomplet).
|
||||||
|
- **Ancienne version affichée** : vérifie que `service-worker.js` est bien servi avec `Cache-Control: no-cache`.
|
||||||
|
- Le script n'utilise jamais `sudo` ni de mot de passe : seule ta clé SSH sert, et rien de secret n'est dans le dépôt.
|
||||||
|
|
||||||
|
## Tester en local avant de déployer
|
||||||
|
|
||||||
|
Trois niveaux d'essai, du plus simple au plus fidèle à la production :
|
||||||
|
|
||||||
|
| Commande | Ce qu'elle lance | Ce qu'elle permet d'essayer |
|
||||||
|
|---|---|---|
|
||||||
|
| `make dev` | serveur de développement (`http://127.0.0.1:8000/`) | l'application seule |
|
||||||
|
| `make dev-sync` | idem + backend Django, `/api/` relayé | synchronisation, page de connexion (`/api/auth/login/`) ; l'éditeur n'y est **pas** protégé |
|
||||||
|
| `make dev-nginx` | **nginx réel** + Django + `dist/` (`http://127.0.0.1:8080/`) | tout : en-têtes d'isolation, types MIME, éditeur protégé par connexion, synchronisation |
|
||||||
|
|
||||||
|
`make dev-nginx` utilise **les mêmes blocs que la production** (`nginx/pyquest-locations.conf.example`) : ce que tu
|
||||||
|
vois en local est ce qui sera déployé. Il construit `dist/`, crée une base SQLite jetable dans `.local/stack/`, propose
|
||||||
|
de créer un compte auteur, puis lance nginx et Django. **Il n'existe aucun compte par défaut** : au premier lancement, dans un terminal, il te
|
||||||
|
demande de créer le compte **administrateur** (mot de passe de 12 caractères minimum). Sinon : `make dev-admin`. Connecte-toi
|
||||||
|
sur `http://127.0.0.1:8080/api/admin/` pour créer des auteurs et leur donner l'accès à l'éditeur ; un administrateur peut
|
||||||
|
aussi ouvrir l'éditeur. Raccourci sans passer par l'administration : `make dev-author NAME=ada` (`RESET=--reset` pour
|
||||||
|
changer le mot de passe). Arrêt avec `Ctrl + C`. Journaux : `.local/stack/logs/`.
|
||||||
|
|
||||||
|
nginx n'a pas besoin d'être installé comme service : seul le binaire est utilisé. Le plus simple (Debian/Ubuntu, sans droits administrateur) : `make fetch-nginx`, qui l'extrait dans `.local/nginx/` ; `make dev-nginx` le trouve alors tout seul. À la main :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
mkdir -p /tmp/ngx && cd /tmp/ngx && apt-get download nginx && dpkg -x nginx_*.deb root
|
||||||
|
PYQUEST_NGINX=/tmp/ngx/root/usr/sbin/nginx make dev-nginx
|
||||||
|
```
|
||||||
|
|
||||||
|
(la variable est `PYQUEST_NGINX` : nginx lit lui-même une variable nommée `NGINX`, qui ne convient pas.)
|
||||||
|
|
||||||
|
**Parcours à essayer** sur `http://127.0.0.1:8080/` :
|
||||||
|
|
||||||
|
1. L'application s'ouvre ; un niveau avec `input()` (niveau 03) fonctionne : l'isolation est active.
|
||||||
|
2. `http://127.0.0.1:8080/author.html` **redirige vers la page de connexion**. Un mauvais mot de passe est refusé ; le
|
||||||
|
bon compte arrive sur l'éditeur ; « Se déconnecter » (sur la page de connexion) referme l'accès.
|
||||||
|
3. **Réglages → Synchronisation → Activer** fonctionne (la ligne « Dernière synchronisation » apparaît).
|
||||||
|
4. Vérifier un site (local ou distant) : `make check-deploy URL=http://127.0.0.1:8080`.
|
||||||
|
|
||||||
|
Les tests automatiques font ce parcours : `make test-e2e` inclut `tests/e2e/nginx.test.mjs` (ignoré si aucun binaire
|
||||||
|
nginx n'est trouvé).
|
||||||
|
|
||||||
|
## Mise en cache
|
||||||
|
|
||||||
|
Un service worker rend l'application utilisable hors ligne : pages et scripts en **réseau d'abord** (une mise à jour
|
||||||
|
est vue dès le rechargement), moteur Python en **cache d'abord** (fichiers versionnés et immuables).
|
||||||
|
|
||||||
|
## Backend Django (facultatif) : synchronisation et accès à l'éditeur
|
||||||
|
|
||||||
|
Le backend Django sert à **deux choses**, toutes deux facultatives : synchroniser la progression entre appareils, et
|
||||||
|
**protéger l'accès à l'éditeur de niveaux** (`author.html`) par une connexion, avec une **administration** pour gérer les
|
||||||
|
comptes. L'application d'apprentissage
|
||||||
|
fonctionne entièrement sans lui.
|
||||||
|
|
||||||
|
1. **Base de données : MariaDB** (ou MySQL). Crée une base et un utilisateur dédiés (jeu de caractères `utf8mb4`) :
|
||||||
|
|
||||||
|
```sql
|
||||||
|
CREATE DATABASE pyquest CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
|
||||||
|
CREATE USER 'pyquest'@'localhost' IDENTIFIED BY '…un mot de passe long…';
|
||||||
|
GRANT ALL PRIVILEGES ON pyquest.* TO 'pyquest'@'localhost';
|
||||||
|
```
|
||||||
|
|
||||||
|
2. **Installer** dans un environnement virtuel dédié (Django 5.2 exige MariaDB 10.5 ou plus) :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo apt install pkg-config libmariadb-dev build-essential python3-dev # pour compiler mysqlclient
|
||||||
|
python3 -m venv /opt/pyquest/venv
|
||||||
|
/opt/pyquest/venv/bin/pip install -r backend/requirements-prod.txt
|
||||||
|
```
|
||||||
|
|
||||||
|
3. **Variables d'environnement** (jamais commitées ; par exemple dans un fichier lu par l'unité systemd, droits `600`) :
|
||||||
|
`PYQUEST_SECRET_KEY` (longue chaîne aléatoire), `PYQUEST_ALLOWED_HOSTS` (ton domaine), `PYQUEST_ORIGIN`
|
||||||
|
(`https://ton-domaine.example`), `PYQUEST_DB_NAME`, `PYQUEST_DB_USER`, `PYQUEST_DB_PASSWORD`, et si besoin
|
||||||
|
`PYQUEST_DB_HOST` (défaut `127.0.0.1`), `PYQUEST_DB_PORT` (défaut `3306`) et `PYQUEST_STATIC_ROOT` (défaut
|
||||||
|
`/var/www/pyquest/static`, fichiers statiques de l'administration). Réglages :
|
||||||
|
`DJANGO_SETTINGS_MODULE=pyquest_api.settings.production`.
|
||||||
|
4. **Créer les tables** : `python manage.py migrate` (dossier `backend/`).
|
||||||
|
5. **Lancer** avec `gunicorn` sur `127.0.0.1:8001` (`gunicorn pyquest_api.wsgi --bind 127.0.0.1:8001`), géré par
|
||||||
|
systemd. nginx relaie `/api/` vers lui, **sur le même domaine** : utilise `nginx/pyquest.conf.example`, et copie
|
||||||
|
`nginx/pyquest-locations.conf.example` et `nginx/pyquest-author-headers.conf.example` dans `/etc/nginx/snippets/` sous les
|
||||||
|
noms `pyquest-locations.conf` et `pyquest-author-headers.conf`.
|
||||||
|
|
||||||
|
### Administration et comptes auteurs
|
||||||
|
|
||||||
|
Deux notions distinctes :
|
||||||
|
|
||||||
|
- les **administrateurs** (`is_staff`) ouvrent l'**administration Django** sur `/api/admin/` : ils créent les comptes,
|
||||||
|
les désactivent, changent les mots de passe et décident **qui peut utiliser l'éditeur de niveaux** ;
|
||||||
|
- les **auteurs** (permission « Peut utiliser l'éditeur de niveaux », donnée par le groupe **Auteurs**) ouvrent
|
||||||
|
l'éditeur (`author.html`) et rien d'autre : ils n'ont aucun accès à l'administration.
|
||||||
|
|
||||||
|
**Premier administrateur** (sur le serveur, une seule fois) :
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend && python manage.py createsuperuser # mot de passe de 12 caractères minimum
|
||||||
|
python manage.py collectstatic --noinput # fichiers de l'administration, servis par nginx
|
||||||
|
```
|
||||||
|
|
||||||
|
`collectstatic` écrit dans `PYQUEST_STATIC_ROOT` (défaut `/var/www/pyquest/static`), que nginx sert sous `/api/static/`
|
||||||
|
(`alias` du fichier `pyquest-locations.conf`). À refaire après une mise à jour de Django.
|
||||||
|
|
||||||
|
**Gérer les auteurs** : ouvre `https://ton-domaine.example/api/admin/`, connecte-toi, puis **Utilisateurs** :
|
||||||
|
|
||||||
|
- cocher des comptes, choisir l'action **« Autoriser à utiliser l'éditeur de niveaux »** (ou **« Retirer l'accès… »**),
|
||||||
|
puis **Envoyer** : la colonne **Éditeur de niveaux** indique l'état ;
|
||||||
|
- **Ajouter un utilisateur** crée un compte (identifiant, mot de passe) ; ajoute-le ensuite au groupe **Auteurs**, ou
|
||||||
|
utilise l'action ci-dessus ;
|
||||||
|
- désactiver un compte (case « Actif ») lui retire tout accès à la prochaine vérification.
|
||||||
|
|
||||||
|
En ligne de commande, `python manage.py create_author ada` crée directement un compte auteur sans passer par
|
||||||
|
l'administration ; `--reset` change son mot de passe, `--admin` en fait un administrateur (accès à `/api/admin/`).
|
||||||
|
|
||||||
|
Un administrateur peut aussi utiliser l'éditeur (un superutilisateur a toutes les permissions). Le simple statut
|
||||||
|
`is_staff` **ne suffit pas** à ouvrir l'éditeur.
|
||||||
|
|
||||||
|
**Sécurité** :
|
||||||
|
|
||||||
|
- session de 8 heures, cookie `HttpOnly` et `Secure`, formulaires protégés contre le CSRF, pages non intégrables dans
|
||||||
|
un cadre (`X-Frame-Options`) ;
|
||||||
|
- **anti force brute** commun à la connexion de l'éditeur et à celle de l'administration : après 5 échecs sur un compte
|
||||||
|
(ou 20 depuis une adresse) en 15 minutes, les connexions sont refusées ; nginx limite aussi le débit ;
|
||||||
|
- pour réduire encore l'exposition de `/api/admin/`, décommente `allow` / `deny` dans `pyquest-locations.conf` (limiter à
|
||||||
|
ton réseau) ou n'y accède que par VPN ;
|
||||||
|
- pas de récupération de mot de passe par e-mail : un administrateur le change (administration ou
|
||||||
|
`create_author --reset`).
|
||||||
|
|
||||||
|
### Vie privée
|
||||||
|
|
||||||
|
Pour la synchronisation, le serveur stocke, pour chaque jeton, **l'empreinte du jeton** (SHA-256) et le **JSON de
|
||||||
|
progression** (niveaux terminés, badges, série). Pas de compte apprenant, pas d'adresse e-mail, pas de statistiques.
|
||||||
|
L'utilisateur peut tout effacer depuis les réglages (route `DELETE`). Les comptes (auteurs, administrateurs) ne contiennent qu'un
|
||||||
|
identifiant et l'empreinte (hachée) du mot de passe.
|
||||||
|
|
||||||
|
## Sans backend
|
||||||
|
|
||||||
|
Servir `dist/` suffit (`nginx/pyquest-static.conf.example`). La section « Synchronisation » des réglages indique alors
|
||||||
|
qu'aucun serveur n'est disponible, et la sauvegarde par fichier reste utilisable. L'éditeur de niveaux (`author.html`)
|
||||||
|
est alors **public** : pour ne pas l'exposer, utilise le backend ci-dessus ou supprime-le de `dist/` avant l'envoi.
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
# Mise en service et exploitation
|
||||||
|
|
||||||
|
Cette page est la **feuille de route** pour installer PyQuest sur un VPS, puis l'exploiter. Elle s'appuie sur des
|
||||||
|
scripts testés (sans serveur) ; ce qui touche le VPS lui-même n'a pas pu être essayé en réel avant la première
|
||||||
|
installation : commence toujours par `--dry-run` et `vps-doctor`.
|
||||||
|
|
||||||
|
## À avoir sous la main
|
||||||
|
|
||||||
|
- l'adresse SSH du VPS et ta clé (`utilisateur@hote`), l'utilisateur ayant `sudo` ;
|
||||||
|
- le **nom de domaine**, qui pointe déjà vers le VPS (enregistrement A/AAAA) ;
|
||||||
|
- une adresse e-mail (avis d'expiration Let's Encrypt) ;
|
||||||
|
- la version de **MariaDB** en place (10.5 ou plus) et un accès administrateur pour y créer une base ;
|
||||||
|
- nginx 1.25.1 ou plus de préférence (sinon voir le commentaire `http2` dans les exemples).
|
||||||
|
|
||||||
|
## Première installation (dans l'ordre)
|
||||||
|
|
||||||
|
| # | Où | Commande | Résultat |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 1 | ta machine | `make ci` | tout est vert avant d'envoyer |
|
||||||
|
| 2 | ta machine | `DEPLOY_HOST=u@h make vps-bootstrap DOMAIN=pyquest.example.org ARGS=--dry-run` | **simulation** : rien n'est écrit sur le VPS |
|
||||||
|
| 3 | ta machine | `DEPLOY_HOST=u@h make vps-bootstrap DOMAIN=pyquest.example.org ARGS="--certbot toi@mail"` | paquets, utilisateur `pyquest`, dossiers, environnement Python, fichier d'environnement (clé secrète générée), service systemd, nginx, certificat |
|
||||||
|
| 4 | VPS | adapter puis `sudo mariadb < deploy/mariadb-setup.sql.example` | base `pyquest` et son utilisateur |
|
||||||
|
| 5 | VPS | mettre le mot de passe de la base dans `/etc/pyquest/env` (`PYQUEST_DB_PASSWORD`) | le service pourra se connecter |
|
||||||
|
| 6 | VPS | `sudo systemctl enable --now pyquest` | migrations et statiques appliqués au démarrage |
|
||||||
|
| 7 | VPS | `createsuperuser` (commande affichée à la fin de l'installation) | premier administrateur |
|
||||||
|
| 8 | ta machine | `DEPLOY_HOST=u@h make deploy` | le site est en ligne |
|
||||||
|
| 9 | ta machine | `make check-deploy URL=https://pyquest.example.org` | en-têtes, types MIME, moteur Python, redirection HTTPS |
|
||||||
|
| 10 | ta machine | `DEPLOY_HOST=u@h make vps-doctor` | tout est « ok » |
|
||||||
|
|
||||||
|
Puis, dans un navigateur : le niveau 03 (`input()`), `/author.html` (renvoie vers la connexion), `/api/admin/`
|
||||||
|
(administration), et **Réglages → Synchronisation → Activer**.
|
||||||
|
|
||||||
|
Les scripts sont **idempotents** : on peut les relancer après une erreur ; ils ne remplacent jamais un fichier de
|
||||||
|
configuration ou un secret déjà présent.
|
||||||
|
|
||||||
|
## Ce que fait l'installation, concrètement
|
||||||
|
|
||||||
|
| Élément | Emplacement sur le VPS |
|
||||||
|
|---|---|
|
||||||
|
| Site statique (versions successives) | `/var/www/pyquest/releases/…`, lien `current` |
|
||||||
|
| Fichiers statiques de l'administration | `/var/www/pyquest/static` |
|
||||||
|
| Code du backend | `/opt/pyquest/backend` |
|
||||||
|
| Environnement Python | `/opt/pyquest/venv` |
|
||||||
|
| Secrets et réglages | `/etc/pyquest/env` (droits 640, `root:pyquest`) |
|
||||||
|
| Service | `pyquest.service` (gunicorn, `127.0.0.1:8001`, utilisateur système `pyquest`) |
|
||||||
|
| nginx | `/etc/nginx/sites-available/pyquest`, extraits dans `/etc/nginx/snippets/` |
|
||||||
|
| Sauvegardes | `/var/backups/pyquest` |
|
||||||
|
|
||||||
|
Le seul droit donné sans mot de passe à ton utilisateur est `systemctl restart|status pyquest`
|
||||||
|
(`/etc/sudoers.d/pyquest`).
|
||||||
|
|
||||||
|
## Exploitation courante
|
||||||
|
|
||||||
|
| Je veux… | Commande |
|
||||||
|
|---|---|
|
||||||
|
| publier une nouvelle version du site | `DEPLOY_HOST=u@h make deploy` |
|
||||||
|
| revenir à la version précédente du site | `DEPLOY_HOST=u@h ./scripts/deploy.sh --rollback` |
|
||||||
|
| publier une nouvelle version du backend | `DEPLOY_HOST=u@h make deploy-backend` (redémarre le service ; migrations automatiques) |
|
||||||
|
| voir l'état du serveur | `DEPLOY_HOST=u@h make vps-doctor` |
|
||||||
|
| lire les journaux | `journalctl -u pyquest -f` ; `/var/log/nginx/error.log` |
|
||||||
|
| gérer les auteurs | `https://domaine/api/admin/` |
|
||||||
|
| contrôler le site publié | `make check-deploy URL=https://domaine` |
|
||||||
|
|
||||||
|
### Sauvegarde de la base
|
||||||
|
|
||||||
|
Elle contient les progressions synchronisées et les comptes. `scripts/backup_db.sh` fait un export compressé, vérifié
|
||||||
|
(une sauvegarde vide est refusée), dans `/var/backups/pyquest`, et garde les 14 dernières. Les identifiants sont lus
|
||||||
|
dans `/etc/pyquest/env`, jamais passés en ligne de commande.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
sudo ./scripts/backup_db.sh # à la main
|
||||||
|
echo '30 3 * * * root /opt/pyquest/scripts/backup_db.sh' | sudo tee /etc/cron.d/pyquest-backup # chaque nuit
|
||||||
|
gunzip < /var/backups/pyquest/pyquest-AAAAMMJJ-HHMMSS.sql.gz | sudo mariadb pyquest # restauration
|
||||||
|
```
|
||||||
|
|
||||||
|
(L'installation place le script dans `/opt/pyquest/scripts/`.) Pense à sortir les sauvegardes du VPS (copie vers une autre machine).
|
||||||
|
|
||||||
|
### Mises à jour de sécurité
|
||||||
|
|
||||||
|
`sudo apt update && sudo apt upgrade` régulièrement ; après une mise à jour de Django
|
||||||
|
(`pip install -r backend/requirements-prod.txt`), relance `make deploy-backend`. Le certificat se renouvelle seul
|
||||||
|
(minuteur `certbot`) ; `vps-doctor` signale une expiration proche.
|
||||||
|
|
||||||
|
## Dépannage
|
||||||
|
|
||||||
|
| Symptôme | Cause probable | Que faire |
|
||||||
|
|---|---|---|
|
||||||
|
| `vps-doctor` : service `pyquest` inactif | mot de passe de la base absent ou faux | `journalctl -u pyquest -n 50`, corriger `/etc/pyquest/env` |
|
||||||
|
| l'API répond 500 | base injoignable | `systemctl status mariadb`, vérifier `PYQUEST_DB_*` |
|
||||||
|
| page de connexion : « Forbidden (CSRF) » | `PYQUEST_ORIGIN` incorrect | doit valoir exactement `https://domaine` |
|
||||||
|
| administration sans style | statiques absents | `sudo systemctl restart pyquest` (relance `collectstatic`) |
|
||||||
|
| `input()` indisponible | en-têtes COOP/COEP absents | `make check-deploy` ; vérifier les extraits nginx |
|
||||||
|
| 502 sur `/api/` | service arrêté | `sudo systemctl status pyquest` |
|
||||||
|
| 503 sur la connexion | limite de débit nginx dépassée | attendre une minute |
|
||||||
|
| connexion refusée « Trop d'essais » | 5 échecs en 15 minutes | attendre 15 minutes |
|
||||||
|
|
||||||
|
## Reprendre le travail plus tard
|
||||||
|
|
||||||
|
L'état d'avancement du déploiement et les prochaines étapes sont dans `CONTEXT.md` (section « Déploiement sur le
|
||||||
|
VPS »). Pour reprendre une session : le lire, lancer `make ci`, puis `make vps-doctor` pour voir où en est le serveur.
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
# PyQuest
|
||||||
|
|
||||||
|
**Apprendre Python par la pratique, directement dans le navigateur.** Pas d'installation, pas de compte :
|
||||||
|
tu ouvres la page, tu écris du code, tu vois le résultat. L'application fonctionne aussi hors ligne.
|
||||||
|
|
||||||
|
## Ce que tu trouves dans PyQuest
|
||||||
|
|
||||||
|
- **Du vrai Python.** Ton code est exécuté par CPython (via Pyodide), dans ton navigateur. Les erreurs sont
|
||||||
|
les vraies erreurs de Python, expliquées en langage simple.
|
||||||
|
- **15 niveaux** (de « Qu'est-ce qu'un programme ? » aux classes et à un petit projet de dessin), chacun
|
||||||
|
avec des explications courtes, des exercices guidés, des indices progressifs et une mission finale.
|
||||||
|
- **Une progression visible** : points d'expérience (XP), badges, série de jours, carte du parcours.
|
||||||
|
- **Accessible** : clavier complet, thèmes clair et sombre, taille de texte réglable, son et voix toujours
|
||||||
|
désactivables, interface en français et en anglais.
|
||||||
|
|
||||||
|
## Par où commencer
|
||||||
|
|
||||||
|
| Je veux… | Page |
|
||||||
|
|---|---|
|
||||||
|
| apprendre Python | [Premiers pas](learn/getting-started.md) |
|
||||||
|
| comprendre les cellules, les erreurs, le dessin | [Écrire et exécuter du code](learn/code.md) |
|
||||||
|
| retrouver ma progression sur un autre appareil | [Progression et sauvegarde](learn/progress.md) |
|
||||||
|
| régler le texte, le son, utiliser le clavier ou un lecteur d'écran | [Accessibilité et réglages](learn/accessibility.md) |
|
||||||
|
| proposer un niveau ou un correctif | [Flux de contribution](contribute/flow.md) |
|
||||||
|
| installer PyQuest sur mon serveur | [Déploiement](host/deploy.md) |
|
||||||
|
|
||||||
|
## Principes du projet
|
||||||
|
|
||||||
|
- **Autonome** : tout se passe dans le navigateur. Un serveur n'est nécessaire que pour héberger les
|
||||||
|
fichiers, et une synchronisation entre appareils est **facultative**.
|
||||||
|
- **Respect de la vie privée** : aucune statistique, aucun service tiers. Rien ne quitte ton appareil sauf si
|
||||||
|
tu actives la synchronisation.
|
||||||
|
- **Ouvert** : licence MIT, niveaux écrits en YAML, éditeur de niveaux intégré pour contribuer sans coder.
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# Accessibilité et réglages
|
||||||
|
|
||||||
|
PyQuest vise le niveau **WCAG 2.2 AA**. Le bouton **Réglages** ouvre le panneau suivant.
|
||||||
|
|
||||||
|
## Réglages
|
||||||
|
|
||||||
|
| Réglage | Effet |
|
||||||
|
|---|---|
|
||||||
|
| Langue | français ou anglais ; le niveau en cours redémarre dans la nouvelle langue |
|
||||||
|
| Taille du texte | de 80 % à 200 % |
|
||||||
|
| Thème | automatique (suit ton système), clair ou sombre |
|
||||||
|
| Personnage-guide | affiche ou masque les bulles d'encouragement |
|
||||||
|
| Effets sonores / Volume | sons de réussite et d'erreur, désactivables ; « Tester le son » |
|
||||||
|
| Voix / Vitesse | bouton « Écouter » des explications, désactivable ; « Tester la voix » |
|
||||||
|
| Mode auteur | affiche le lien vers l'[éditeur de niveaux](../contribute/author-editor.md) |
|
||||||
|
|
||||||
|
Le son et la voix ne démarrent **jamais** tout seuls. Aucune information n'est transmise uniquement par le son ou
|
||||||
|
par la couleur : chaque résultat est aussi écrit (« Bravo, c'est correct ! », « Pas encore. »).
|
||||||
|
|
||||||
|
## Au clavier
|
||||||
|
|
||||||
|
Tout est utilisable sans souris.
|
||||||
|
|
||||||
|
| Touche | Action |
|
||||||
|
|---|---|
|
||||||
|
| `Tab` / `Maj + Tab` | passer d'un contrôle à l'autre |
|
||||||
|
| `Ctrl + Entrée` (`Cmd + Entrée`) | exécuter la cellule |
|
||||||
|
| `Échap` | fermer le panneau « Niveaux » ou « Réglages » (le focus revient au bouton d'origine) |
|
||||||
|
| `Tab` dans l'éditeur de code | indenter ; `Échap` puis `Tab` pour quitter l'éditeur |
|
||||||
|
|
||||||
|
Quand un panneau est ouvert, le reste de la page est mis de côté et le focus reste à l'intérieur.
|
||||||
|
|
||||||
|
## Lecteurs d'écran
|
||||||
|
|
||||||
|
Les contrôles ont des noms explicites, les résultats et erreurs sont annoncés (zones `role="status"`), la carte de
|
||||||
|
progression et les badges ont leurs états en texte, le dessin du canvas a une description et une liste de traits.
|
||||||
|
|
||||||
|
!!! note "Retours bienvenus"
|
||||||
|
L'application est testée automatiquement, mais un essai avec un lecteur d'écran réel (Orca, NVDA, VoiceOver)
|
||||||
|
reste la meilleure vérification. Si quelque chose n'est pas annoncé ou est confus, signale-le : c'est un
|
||||||
|
défaut à corriger.
|
||||||
|
|
||||||
|
## Hors ligne
|
||||||
|
|
||||||
|
PyQuest est une application web installable (PWA). Après un premier chargement complet, elle fonctionne sans
|
||||||
|
connexion ; le navigateur peut te proposer de l'installer.
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
# Écrire et exécuter du code
|
||||||
|
|
||||||
|
## Les cellules
|
||||||
|
|
||||||
|
Chaque exercice a une **cellule** : une zone de code, et dessous la sortie et le résultat de la validation.
|
||||||
|
|
||||||
|
| Action | Comment |
|
||||||
|
|---|---|
|
||||||
|
| Exécuter | bouton **Exécuter** ou `Ctrl + Entrée` (`Cmd + Entrée` sur Mac) |
|
||||||
|
| Arrêter un programme qui tourne | bouton **Arrêter** (utile contre une boucle infinie) |
|
||||||
|
| Réinitialiser | bouton **Réinitialiser** : remet le code de départ |
|
||||||
|
| Indice | bouton **Indice** : un indice de plus à chaque clic |
|
||||||
|
| Solution | « Voir la solution », sous la cellule |
|
||||||
|
|
||||||
|
Entre deux exécutions, **les variables sont conservées** d'une cellule à l'autre dans un même niveau, comme dans
|
||||||
|
un notebook.
|
||||||
|
|
||||||
|
## Indenter avec la touche Tab
|
||||||
|
|
||||||
|
Python se structure par l'indentation. Dans l'éditeur :
|
||||||
|
|
||||||
|
- **Tab** insère des espaces (4, alignés sur la colonne suivante) ; avec plusieurs lignes sélectionnées, il les
|
||||||
|
indente toutes.
|
||||||
|
- **Maj + Tab** désindente.
|
||||||
|
- **Échap puis Tab** fait **sortir** du champ de code, pour continuer à naviguer au clavier sans rester bloqué.
|
||||||
|
Dès que tu retapes dans l'éditeur, Tab indente de nouveau.
|
||||||
|
|
||||||
|
## Les erreurs
|
||||||
|
|
||||||
|
Quand ton code plante, PyQuest affiche :
|
||||||
|
|
||||||
|
- le **type** de l'erreur traduit (« Python ne connaît pas ce nom ») ;
|
||||||
|
- une **explication** en langage simple et un **conseil** ;
|
||||||
|
- la **ligne** concernée ;
|
||||||
|
- le message technique réel de Python, dans « Détail technique », pour apprendre à le lire.
|
||||||
|
|
||||||
|
## Saisir des données avec `input()`
|
||||||
|
|
||||||
|
Quand ton programme appelle `input("Ton prénom ? ")`, un champ de saisie apparaît sous la sortie : tape ta réponse
|
||||||
|
et valide avec **Entrée** ou le bouton **Envoyer**. La question est affichée comme dans un vrai terminal.
|
||||||
|
|
||||||
|
!!! note
|
||||||
|
La saisie interactive demande que la page soit servie avec les en-têtes d'isolation (voir
|
||||||
|
[Déploiement](../host/deploy.md)). Sans eux, `input()` lève une erreur `EOFError` : c'est un problème
|
||||||
|
d'hébergement, pas de ton code.
|
||||||
|
|
||||||
|
## Les fichiers
|
||||||
|
|
||||||
|
Python peut lire et écrire des fichiers. Dans le navigateur, **seul le dossier `data/` est conservé** quand tu
|
||||||
|
fermes la page (par exemple `open("data/agenda.txt", "w")`). Tout fichier écrit ailleurs disparaît au
|
||||||
|
rechargement.
|
||||||
|
|
||||||
|
## Dessiner avec `canvas`
|
||||||
|
|
||||||
|
À partir du niveau 13, tu disposes d'une feuille de dessin :
|
||||||
|
|
||||||
|
```python
|
||||||
|
import canvas
|
||||||
|
|
||||||
|
canvas.line(0, 0, 100, 0, "red") # un trait rouge de (0, 0) à (100, 0)
|
||||||
|
canvas.line(0, 0, 0, 100, "blue")
|
||||||
|
```
|
||||||
|
|
||||||
|
- Le point `(0, 0)` est au **centre** ; les nombres positifs vont vers la **droite** et vers le **haut**, jusqu'à 200.
|
||||||
|
- Couleurs : `black`, `red`, `green`, `blue`, `orange`, `purple`, `gray`.
|
||||||
|
- `canvas.clear()` efface la feuille. **Chaque exécution repart d'une feuille vierge.**
|
||||||
|
- Le dessin s'affiche sous la cellule, avec une **description écrite** et la **liste de tous les traits**
|
||||||
|
(« Voir la liste des traits ») : rien n'est transmis par la seule image.
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Premiers pas
|
||||||
|
|
||||||
|
## Ouvrir PyQuest
|
||||||
|
|
||||||
|
Ouvre l'adresse de ton instance PyQuest dans un navigateur récent (Firefox, Chrome, Edge). Le moteur Python se
|
||||||
|
charge au premier démarrage (quelques secondes) ; ensuite l'application se souvient de tout et fonctionne
|
||||||
|
**sans connexion**.
|
||||||
|
|
||||||
|
Tu arrives sur ton **premier niveau non terminé**. Pour ouvrir un niveau précis, utilise le bouton
|
||||||
|
**Niveaux** (voir plus bas) ou un lien direct de la forme `https://…/#/levels/05-decide`.
|
||||||
|
|
||||||
|
## Un niveau, étape par étape
|
||||||
|
|
||||||
|
Un niveau est une suite d'étapes qui s'affichent les unes après les autres :
|
||||||
|
|
||||||
|
1. **Explication** : un court texte. Quand le bouton **Écouter** est présent, une voix lit le texte (jamais
|
||||||
|
automatiquement : c'est toi qui cliques).
|
||||||
|
2. **Exercice de code** : une consigne et une cellule de code déjà remplie. Tu modifies, tu exécutes, tu vois le
|
||||||
|
résultat et la validation.
|
||||||
|
3. **Mission finale** : un petit programme qui réunit ce que tu viens d'apprendre. La réussir termine le niveau.
|
||||||
|
|
||||||
|
Le bouton **Continuer** passe à l'étape suivante. Les boutons **Niveau précédent** et **Niveau suivant**, en haut,
|
||||||
|
changent de niveau.
|
||||||
|
|
||||||
|
!!! tip "Pas de panique"
|
||||||
|
Se tromper est normal : l'erreur est expliquée, et tu peux demander des **indices** (du plus vague au plus
|
||||||
|
précis) ou, en dernier recours, afficher la **solution**.
|
||||||
|
|
||||||
|
## Le bouton « Niveaux »
|
||||||
|
|
||||||
|
Il ouvre un panneau avec :
|
||||||
|
|
||||||
|
- la **carte du parcours** : chaque niveau est un point, avec son état écrit en toutes lettres
|
||||||
|
(« Terminé », « En cours », « À faire ») ;
|
||||||
|
- l'**étagère de badges** : ceux que tu as obtenus (avec la date) et ceux qui restent à débloquer.
|
||||||
|
|
||||||
|
Choisir un niveau dans la carte l'ouvre directement : rien n'est verrouillé.
|
||||||
|
|
||||||
|
## Le personnage-guide
|
||||||
|
|
||||||
|
Un petit personnage t'encourage après une réussite, te propose un indice quand tu bloques, t'accueille quand tu
|
||||||
|
reviens après une pause. Il ne juge jamais. Tu peux le masquer dans les [réglages](accessibility.md).
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# Progression et sauvegarde
|
||||||
|
|
||||||
|
## XP, badges, série
|
||||||
|
|
||||||
|
- **XP (points d'expérience)** : chaque niveau vaut un certain nombre de points, accordés **une seule fois**, quand tu
|
||||||
|
réussis sa **mission finale**. Refaire un niveau ne rapporte rien de plus.
|
||||||
|
- **Badges** : récompenses pour des étapes (premier niveau, trois niveaux, 100 XP, séries de 3 et de 7 jours).
|
||||||
|
- **Série de jours** : nombre de jours consécutifs où tu as pratiqué. Manquer un jour la remet à 1, sans reproche.
|
||||||
|
|
||||||
|
Rien n'est verrouillé : les points et badges ne servent qu'à mesurer ton avancée.
|
||||||
|
|
||||||
|
## Où est enregistrée ma progression ?
|
||||||
|
|
||||||
|
**Dans ton navigateur**, sur ton appareil (stockage local). Tu n'as rien à faire. Attention : effacer les données
|
||||||
|
du site, ou changer de navigateur ou d'appareil, la fait disparaître. Deux solutions ci-dessous.
|
||||||
|
|
||||||
|
## Sauvegarder dans un fichier (sans serveur)
|
||||||
|
|
||||||
|
**Réglages → Sauvegarde de la progression**
|
||||||
|
|
||||||
|
- **Exporter ma progression** télécharge un fichier `pyquest-progress-AAAA-MM-JJ.json`.
|
||||||
|
- **Importer une progression** relit un tel fichier et le **fusionne** avec ta progression actuelle : on garde
|
||||||
|
tous les niveaux et badges, on ne perd jamais rien. L'application indique combien de niveaux sont nouveaux.
|
||||||
|
|
||||||
|
Garde le fichier ou copie-le sur un autre appareil. Un fichier invalide est refusé sans rien changer.
|
||||||
|
|
||||||
|
## Synchroniser entre appareils (facultatif)
|
||||||
|
|
||||||
|
Si ton instance PyQuest propose la synchronisation (un serveur avec le module de synchronisation), tu peux
|
||||||
|
retrouver ta progression partout, **sans créer de compte**.
|
||||||
|
|
||||||
|
**Réglages → Synchronisation entre appareils**
|
||||||
|
|
||||||
|
1. Sur le premier appareil : **Activer la synchronisation**. Un **jeton secret** est créé et affiché.
|
||||||
|
2. Sur le second appareil : colle ce jeton dans « colle le jeton d'un autre appareil » puis **Lier cet appareil**.
|
||||||
|
Les deux progressions sont fusionnées.
|
||||||
|
3. Ensuite, tout est automatique : au démarrage, au retour du réseau, et peu après chaque niveau terminé.
|
||||||
|
**Synchroniser maintenant** force un échange.
|
||||||
|
|
||||||
|
!!! warning "Le jeton est comme un mot de passe"
|
||||||
|
Il donne accès à ta progression. Ne le partage pas. **S'il est perdu, il ne peut pas être récupéré** : le
|
||||||
|
serveur n'en garde qu'une empreinte. Fais aussi une sauvegarde par fichier.
|
||||||
|
|
||||||
|
- **Désactiver (garder les données du serveur)** arrête la synchronisation sur cet appareil.
|
||||||
|
- **Désactiver et effacer les données du serveur** supprime définitivement ce qui est stocké pour ce jeton.
|
||||||
|
- **Hors ligne** ou serveur indisponible : un message l'indique, ta progression locale reste intacte et la
|
||||||
|
synchronisation reprendra seule.
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
# Architecture
|
||||||
|
|
||||||
|
## Vue d'ensemble
|
||||||
|
|
||||||
|
```text
|
||||||
|
┌──────────────────────────── Navigateur ────────────────────────────┐
|
||||||
|
│ Interface (modules ES) ──► Client du worker ◄──► Web Worker │
|
||||||
|
│ │ Pyodide/CPython │
|
||||||
|
│ ▼ │ │
|
||||||
|
│ IndexedDB : progression, réglages data/ persistant │
|
||||||
|
└────────┬───────────────────────────────────────────────────────────┘
|
||||||
|
│ lit (facultatif)
|
||||||
|
▼ ▼
|
||||||
|
levels/*.yaml + schéma JSON Backend Django /api/sync/
|
||||||
|
```
|
||||||
|
|
||||||
|
L'application est **autonome** : tout s'exécute dans le navigateur. Le backend n'est qu'un stockage optionnel de la
|
||||||
|
progression.
|
||||||
|
|
||||||
|
## Choix structurants
|
||||||
|
|
||||||
|
- **Moteur Python : Pyodide** (CPython réel en WebAssembly) : fidélité des messages d'erreur, bibliothèque standard
|
||||||
|
complète. Il tourne dans un **Web Worker** pour ne jamais figer l'interface.
|
||||||
|
- **Interruption** par un `SharedArrayBuffer` (signal SIGINT de Python) : demande un site isolé
|
||||||
|
(COOP/COEP), d'où un Pyodide servi par le même domaine. La saisie `input()` utilise aussi un
|
||||||
|
`SharedArrayBuffer`.
|
||||||
|
- **Niveaux déclaratifs** : YAML validé par JSON Schema ; la validation d'un exercice passe par une liste **fermée**
|
||||||
|
de types de tests, jamais par du code venant du niveau.
|
||||||
|
- **JavaScript** : classes ES2022 et modules natifs, sans framework.
|
||||||
|
- **Fichiers** : seul `data/` est monté sur IndexedDB (IDBFS) et survit aux sessions.
|
||||||
|
- **Dessin** : le module `canvas` enregistre des traits renvoyés avec le résultat de l'exécution ; l'interface les
|
||||||
|
affiche et les tests `drawing_*` les examinent.
|
||||||
|
- **Narration** : mp3 générés à l'avance (Piper, outil de build uniquement), repli sur la voix du système.
|
||||||
|
|
||||||
|
## Où est quoi
|
||||||
|
|
||||||
|
| Dossier | Contenu |
|
||||||
|
|---|---|
|
||||||
|
| `app/` | application (HTML, CSS, `js/core`, `js/ui`, `js/author`, `js/workers`, `python/`) |
|
||||||
|
| `levels/` | niveaux, manifeste, schéma, narration |
|
||||||
|
| `backend/` | API de synchronisation Django |
|
||||||
|
| `scripts/` | serveur de dev, validation, build, voix |
|
||||||
|
| `tests/` | `js/` (node:test), `python/`, `e2e/` (Chromium) |
|
||||||
|
| `docs/site/` | cette documentation ; `docs/design/` : notes de conception (en français) |
|
||||||
|
|
||||||
|
Le raisonnement détaillé de chaque choix est dans `docs/design/` du dépôt.
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
# API de synchronisation
|
||||||
|
|
||||||
|
Disponible seulement si le backend Django est déployé. Elle est toujours sur le **même domaine** que l'application :
|
||||||
|
`/api/sync/`.
|
||||||
|
|
||||||
|
## Authentification
|
||||||
|
|
||||||
|
Chaque requête porte un **jeton** : `Authorization: Bearer <jeton>`. Le jeton est généré par le client (256 bits,
|
||||||
|
43 caractères URL-safe ; le serveur accepte 32 à 128 caractères `A-Za-z0-9_-`). Le serveur n'en conserve que le
|
||||||
|
**SHA-256**. Il n'y a ni compte ni cookie (donc pas de CSRF).
|
||||||
|
|
||||||
|
## Appels
|
||||||
|
|
||||||
|
| Appel | Réponse |
|
||||||
|
|---|---|
|
||||||
|
| `GET /api/sync/` | `200 {"payload": …, "updated_at": …}` ; `404 {"error": …}` si rien n'est stocké |
|
||||||
|
| `PUT /api/sync/` avec `{"payload": …, "base": …}` | `200 {"updated_at": …}` ; `409` si `base` est périmée ; `400` payload invalide ou trop gros |
|
||||||
|
| `DELETE /api/sync/` | `204` : efface définitivement les données de ce jeton (idempotent) |
|
||||||
|
| tout appel sans jeton valide | `401 {"error": …}` |
|
||||||
|
|
||||||
|
- `payload` : l'objet exporté par l'application (`version`, `completedLevels`, `badges`, `streak`). Taille maximale :
|
||||||
|
256 Ko.
|
||||||
|
- `base` (facultatif) : le `updated_at` lu par le client. S'il ne correspond plus à la version du serveur
|
||||||
|
(un autre appareil a écrit entre-temps), le serveur répond **`409`** avec l'état courant
|
||||||
|
(`payload`, `updated_at`) : le client fusionne et réessaie. C'est une **concurrence optimiste**.
|
||||||
|
|
||||||
|
## Qui fusionne ?
|
||||||
|
|
||||||
|
**Le client.** Le serveur stocke le dernier JSON reçu et ne fusionne rien. La fusion garde l'union des niveaux
|
||||||
|
terminés et des badges, le maximum de la meilleure série, et la série courante de l'appareil le plus récemment actif.
|
||||||
|
|
||||||
|
## Cycle du client
|
||||||
|
|
||||||
|
1. `GET` puis fusion locale ;
|
||||||
|
2. `PUT` de l'état fusionné avec `base` ; sur `409`, fusion de l'état reçu et nouvel essai (4 au plus) ;
|
||||||
|
3. déclenché à l'activation, au démarrage, au retour du réseau, quand l'onglet redevient visible et 2 secondes après
|
||||||
|
un changement local.
|
||||||
|
|
||||||
|
Les erreurs sont des états visibles (`hors ligne`, `jeton refusé`, `serveur indisponible`, `données refusées`,
|
||||||
|
`données invalides`) et ne bloquent jamais l'application. Un `404` qui n'est pas du JSON (serveur statique sans
|
||||||
|
Django) est traité comme « serveur indisponible ».
|
||||||
|
|
||||||
|
## Accès à l'éditeur (comptes auteurs)
|
||||||
|
|
||||||
|
Le même backend expose, pour nginx et pour la page de connexion :
|
||||||
|
|
||||||
|
| Appel | Rôle |
|
||||||
|
|---|---|
|
||||||
|
| `GET /api/auth/check/` | `204` si la session appartient à un compte actif ayant la permission `authors.use_editor` (groupe « Auteurs »), sinon `401` ; utilisé par `auth_request` de nginx (non joignable de l'extérieur) |
|
||||||
|
| `GET /api/auth/login/` | formulaire de connexion (français ou anglais selon `Accept-Language`) |
|
||||||
|
| `POST /api/auth/login/` | connexion (CSRF) ; `302` vers `next` (chemin local uniquement), `200` avec message si refusé, `429` si trop d'essais |
|
||||||
|
| `GET /api/auth/me/` | `200 {username, csrf}` pour un auteur connecté (affichage du nom et jeton du bouton de déconnexion de l'éditeur), sinon `401` |
|
||||||
|
| `POST /api/auth/logout/` | déconnexion (CSRF) ; redirige vers la page de connexion |
|
||||||
|
| `/api/admin/` | administration Django (comptes, groupe « Auteurs ») ; fichiers statiques sous `/api/static/` |
|
||||||
|
|
||||||
|
## Sécurité
|
||||||
|
|
||||||
|
Toute donnée reçue du serveur ou d'un fichier est considérée comme non fiable et validée strictement avant fusion
|
||||||
|
(types, bornes, identifiants). Le serveur impose la taille maximale ; nginx limite le débit.
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
# Tests de validation
|
||||||
|
|
||||||
|
La liste des types de tests (`tests[].kind`) est **fermée** : ajouter un type passe par le moteur.
|
||||||
|
|
||||||
|
| `kind` | Champs | Réussit si… |
|
||||||
|
|---|---|---|
|
||||||
|
| `no_syntax_error` | — | le code ne contient pas d'erreur de syntaxe |
|
||||||
|
| `stdout_equals` | `value` | la sortie est **exactement** égale (retour à la ligne final compris) |
|
||||||
|
| `stdout_contains` | `value` | la sortie contient ce texte |
|
||||||
|
| `stdout_matches_regex` | `value` | la sortie complète correspond à l'expression régulière |
|
||||||
|
| `var_equals` | `name`, `value` | la variable vaut `value` (`10.0` est un `float`, `10` un `int`) |
|
||||||
|
| `var_type_is` | `name`, `value` | la variable a ce type (`str`, `int`, `float`, `list`…) |
|
||||||
|
| `code_contains` | `value` | le code de l'apprenant contient ce texte (ex. `random.choice`) |
|
||||||
|
| `drawing_segments` | `value` | le dessin a ce nombre de traits : `"4"` (exactement) ou `"4+"` (au moins) |
|
||||||
|
| `drawing_has_line` | `value` | un trait relie deux points : `"0,0 100,0"` ou avec couleur `"0,0 100,0 red"` |
|
||||||
|
| `drawing_colors` | `value` | toutes ces couleurs sont utilisées : `"red,blue"` |
|
||||||
|
|
||||||
|
Champs communs : `message` (texte `fr`/`en` affiché si le test échoue) et `inputs` (saisies scriptées, voir
|
||||||
|
[Écrire un niveau](../contribute/write-level.md)).
|
||||||
|
|
||||||
|
## Détails
|
||||||
|
|
||||||
|
- **Sortie** : l'invite de `input()` est dans la sortie (comme en Python), pas la réponse.
|
||||||
|
- **`code_contains`** ne s'évalue pas sur un rejeu : inutile avec `inputs`.
|
||||||
|
- **Dessin** : un trait compte comme présent si ses extrémités sont à moins de 0,5 de celles demandées, **dans un
|
||||||
|
sens ou dans l'autre**. Couleurs : `black`, `red`, `green`, `blue`, `orange`, `purple`, `gray`. Le dessin vient de
|
||||||
|
l'exécution de la cellule (une feuille vierge à chaque exécution).
|
||||||
|
- **Une erreur d'exécution** fait toujours échouer l'étape.
|
||||||
|
|
||||||
|
## Ajouter un type de test
|
||||||
|
|
||||||
|
1. `ValidationEngine` : interpréter le type (et `supportedKinds`).
|
||||||
|
2. `levels/schema/level.schema.json` : l'ajouter à l'énumération.
|
||||||
|
3. `app/js/author/LevelDraft.js` : l'ajouter à `TEST_KINDS`.
|
||||||
|
4. Catalogues de l'éditeur : `author.kind.<type>` et son aide ; messages `reason.*` de l'application.
|
||||||
|
5. `LevelLinter` si des règles de cohérence s'imposent, puis des tests unitaires.
|
||||||
@@ -68,6 +68,7 @@ plugins:
|
|||||||
Écrire un niveau: Writing a level
|
Écrire un niveau: Writing a level
|
||||||
L'éditeur de niveaux: The level editor
|
L'éditeur de niveaux: The level editor
|
||||||
Déploiement: Deployment
|
Déploiement: Deployment
|
||||||
|
Mise en service et exploitation: Going live and operations
|
||||||
Architecture: Architecture
|
Architecture: Architecture
|
||||||
Tests de validation: Validation tests
|
Tests de validation: Validation tests
|
||||||
API de synchronisation: Sync API
|
API de synchronisation: Sync API
|
||||||
@@ -85,6 +86,7 @@ nav:
|
|||||||
- L'éditeur de niveaux: contribute/author-editor.md
|
- L'éditeur de niveaux: contribute/author-editor.md
|
||||||
- Héberger:
|
- Héberger:
|
||||||
- Déploiement: host/deploy.md
|
- Déploiement: host/deploy.md
|
||||||
|
- Mise en service et exploitation: host/operations.md
|
||||||
- Référence:
|
- Référence:
|
||||||
- Architecture: reference/architecture.md
|
- Architecture: reference/architecture.md
|
||||||
- Tests de validation: reference/tests.md
|
- Tests de validation: reference/tests.md
|
||||||
|
|||||||
Executable
+45
@@ -0,0 +1,45 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Sauvegarde de la base MariaDB de PyQuest (progressions synchronisées et comptes). À lancer SUR LE VPS, en root ou en
|
||||||
|
# utilisateur pouvant lire /etc/pyquest/env : les identifiants viennent de ce fichier, jamais de la ligne de commande
|
||||||
|
# (donc invisibles dans la liste des processus).
|
||||||
|
#
|
||||||
|
# sudo ./scripts/backup_db.sh # sauvegarde dans /var/backups/pyquest, garde les 14 dernières
|
||||||
|
# Cron quotidien (/etc/cron.d/pyquest-backup) : 30 3 * * * root /opt/pyquest/backend/../scripts/backup_db.sh
|
||||||
|
# Restauration : gunzip < pyquest-AAAAMMJJ-HHMMSS.sql.gz | sudo mariadb pyquest
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ENV_FILE="${PYQUEST_ENV_FILE:-/etc/pyquest/env}"
|
||||||
|
DEST="${PYQUEST_BACKUP_DIR:-/var/backups/pyquest}"
|
||||||
|
KEEP="${PYQUEST_BACKUP_KEEP:-14}"
|
||||||
|
|
||||||
|
[[ -r "${ENV_FILE}" ]] || { echo "Impossible de lire ${ENV_FILE} (lancer avec sudo)." >&2; exit 1; }
|
||||||
|
[[ "${KEEP}" =~ ^[1-9][0-9]*$ ]] || { echo "PYQUEST_BACKUP_KEEP doit être un entier >= 1" >&2; exit 2; }
|
||||||
|
# Lecture sans « source » : le fichier est au format systemd (valeurs sans guillemets, éventuellement avec $ ou espaces).
|
||||||
|
envval() { grep -E "^$1=" "${ENV_FILE}" | tail -n1 | cut -d= -f2-; }
|
||||||
|
NAME="$(envval PYQUEST_DB_NAME)"; USER_DB="$(envval PYQUEST_DB_USER)"; PASS="$(envval PYQUEST_DB_PASSWORD)"
|
||||||
|
HOST="$(envval PYQUEST_DB_HOST)"; PORT="$(envval PYQUEST_DB_PORT)"
|
||||||
|
[[ -n "${NAME}" && -n "${USER_DB}" && -n "${PASS}" ]] || { echo "Variables PYQUEST_DB_* incomplètes dans ${ENV_FILE}." >&2; exit 1; }
|
||||||
|
DUMP="$(command -v mariadb-dump || command -v mysqldump || true)"
|
||||||
|
[[ -n "${DUMP}" ]] || { echo "mariadb-dump / mysqldump introuvable (sudo apt install mariadb-client)." >&2; exit 1; }
|
||||||
|
|
||||||
|
umask 077
|
||||||
|
mkdir -p "${DEST}"
|
||||||
|
chmod 700 "${DEST}"
|
||||||
|
CNF="$(mktemp)"
|
||||||
|
PART=""
|
||||||
|
trap 'rm -f "${CNF}" "${PART}"' EXIT
|
||||||
|
printf '[client]\nuser=%s\npassword=%s\nhost=%s\nport=%s\n' "${USER_DB}" "${PASS}" "${HOST:-127.0.0.1}" "${PORT:-3306}" > "${CNF}"
|
||||||
|
|
||||||
|
FILE="${DEST}/pyquest-$(date +%Y%m%d-%H%M%S).sql.gz"
|
||||||
|
# On écrit dans un fichier provisoire : une sauvegarde ratée n'écrase ni ne remplace jamais une bonne.
|
||||||
|
PART="${FILE}.part"
|
||||||
|
"${DUMP}" --defaults-extra-file="${CNF}" --single-transaction --routines --default-character-set=utf8mb4 "${NAME}" | gzip -9 > "${PART}"
|
||||||
|
# Une sauvegarde vide ou illisible ne doit jamais passer pour bonne.
|
||||||
|
if ! gzip -t "${PART}" || [[ "$(gunzip -c "${PART}" | wc -c)" -le 500 ]]; then
|
||||||
|
echo "Sauvegarde invalide, supprimée." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
mv "${PART}" "${FILE}"
|
||||||
|
PART=""
|
||||||
|
ls -1 "${DEST}"/pyquest-*.sql.gz | sort | head -n -"${KEEP}" | xargs -r rm -f --
|
||||||
|
echo "Sauvegarde : ${FILE} ($(du -h "${FILE}" | cut -f1)) ; conservées : $(ls -1 "${DEST}"/pyquest-*.sql.gz | wc -l)"
|
||||||
+28
-2
@@ -5,16 +5,23 @@
|
|||||||
#
|
#
|
||||||
# DEPLOY_HOST=utilisateur@vps.example.org ./scripts/deploy.sh [--dry-run]
|
# DEPLOY_HOST=utilisateur@vps.example.org ./scripts/deploy.sh [--dry-run]
|
||||||
# DEPLOY_HOST=utilisateur@vps.example.org ./scripts/deploy.sh --rollback
|
# DEPLOY_HOST=utilisateur@vps.example.org ./scripts/deploy.sh --rollback
|
||||||
|
# DEPLOY_HOST=utilisateur@vps.example.org ./scripts/deploy.sh --backend [--no-restart]
|
||||||
|
#
|
||||||
|
# --backend : envoie le code du backend Django (dossier backend/) dans DEPLOY_BACKEND_PATH puis redémarre le service
|
||||||
|
# (« sudo -n systemctl restart pyquest » : voir deploy/remote_setup.sh qui autorise cette seule commande). Au
|
||||||
|
# redémarrage, systemd applique les migrations et collecte les fichiers statiques.
|
||||||
#
|
#
|
||||||
# Variables : DEPLOY_HOST (obligatoire), DEPLOY_PATH (défaut /var/www/pyquest), DEPLOY_KEEP (défaut 3),
|
# Variables : DEPLOY_HOST (obligatoire), DEPLOY_PATH (défaut /var/www/pyquest), DEPLOY_KEEP (défaut 3),
|
||||||
# DEPLOY_SSH (défaut « ssh -o BatchMode=yes »).
|
# DEPLOY_BACKEND_PATH (défaut /opt/pyquest/backend), DEPLOY_SSH (défaut « ssh -o BatchMode=yes »).
|
||||||
set -euo pipefail
|
set -euo pipefail
|
||||||
|
|
||||||
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
HOST="${DEPLOY_HOST:-}"
|
HOST="${DEPLOY_HOST:-}"
|
||||||
REMOTE_PATH="${DEPLOY_PATH:-/var/www/pyquest}"
|
REMOTE_PATH="${DEPLOY_PATH:-/var/www/pyquest}"
|
||||||
KEEP="${DEPLOY_KEEP:-3}"
|
KEEP="${DEPLOY_KEEP:-3}"
|
||||||
|
BACKEND_PATH="${DEPLOY_BACKEND_PATH:-/opt/pyquest/backend}"
|
||||||
SSH="${DEPLOY_SSH:-ssh -o BatchMode=yes}"
|
SSH="${DEPLOY_SSH:-ssh -o BatchMode=yes}"
|
||||||
|
RESTART=1
|
||||||
MODE="deploy"
|
MODE="deploy"
|
||||||
DRY_RUN=0
|
DRY_RUN=0
|
||||||
|
|
||||||
@@ -22,7 +29,9 @@ for arg in "$@"; do
|
|||||||
case "${arg}" in
|
case "${arg}" in
|
||||||
--dry-run) DRY_RUN=1 ;;
|
--dry-run) DRY_RUN=1 ;;
|
||||||
--rollback) MODE="rollback" ;;
|
--rollback) MODE="rollback" ;;
|
||||||
-h|--help) sed -n '2,11p' "${BASH_SOURCE[0]}"; exit 0 ;;
|
--backend) MODE="backend" ;;
|
||||||
|
--no-restart) RESTART=0 ;;
|
||||||
|
-h|--help) sed -n '2,16p' "${BASH_SOURCE[0]}"; exit 0 ;;
|
||||||
*) echo "Option inconnue : ${arg}" >&2; exit 2 ;;
|
*) echo "Option inconnue : ${arg}" >&2; exit 2 ;;
|
||||||
esac
|
esac
|
||||||
done
|
done
|
||||||
@@ -30,6 +39,7 @@ done
|
|||||||
# Ces valeurs sont insérées dans des commandes distantes : on n'accepte que des caractères sûrs.
|
# 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; }
|
[[ "${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; }
|
[[ "${REMOTE_PATH}" =~ ^/[A-Za-z0-9_./-]{3,}$ ]] || { echo "DEPLOY_PATH doit être un chemin absolu simple (ex. /var/www/pyquest)" >&2; exit 2; }
|
||||||
|
[[ "${BACKEND_PATH}" =~ ^/[A-Za-z0-9_./-]{3,}$ ]] || { echo "DEPLOY_BACKEND_PATH doit être un chemin absolu simple" >&2; exit 2; }
|
||||||
[[ "${KEEP}" =~ ^[1-9][0-9]*$ ]] || { echo "DEPLOY_KEEP doit être un entier >= 1" >&2; exit 2; }
|
[[ "${KEEP}" =~ ^[1-9][0-9]*$ ]] || { echo "DEPLOY_KEEP doit être un entier >= 1" >&2; exit 2; }
|
||||||
|
|
||||||
remote() {
|
remote() {
|
||||||
@@ -50,6 +60,22 @@ ln -sfn \"releases/\$previous\" current.tmp && mv -Tf current.tmp current; echo
|
|||||||
exit 0
|
exit 0
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
if [[ "${MODE}" == "backend" ]]; then
|
||||||
|
[[ -f "${ROOT}/backend/manage.py" ]] || { echo "backend/manage.py introuvable." >&2; exit 1; }
|
||||||
|
echo "Envoi du backend vers ${HOST}:${BACKEND_PATH}"
|
||||||
|
remote "mkdir -p '${BACKEND_PATH}'"
|
||||||
|
BACK=(rsync -az --delete --chmod=D755,F644 -e "${SSH}"
|
||||||
|
--exclude='__pycache__/' --exclude='*.pyc' --exclude='db.sqlite3' --exclude='staticfiles/' --exclude='.venv/' --exclude='venv/' --exclude='*.mo')
|
||||||
|
[[ "${DRY_RUN}" == 1 ]] && BACK+=(--dry-run --itemize-changes)
|
||||||
|
"${BACK[@]}" "${ROOT}/backend/" "${HOST}:${BACKEND_PATH}/"
|
||||||
|
if [[ "${RESTART}" == 1 ]]; then
|
||||||
|
# Une seule commande sudo autorisée sans mot de passe (voir deploy/remote_setup.sh) ; sinon on le dit.
|
||||||
|
remote "sudo -n systemctl restart pyquest" || echo "Redémarrage impossible sans mot de passe : lance « sudo systemctl restart pyquest » sur le VPS." >&2
|
||||||
|
fi
|
||||||
|
echo "Backend envoyé. Migrations et statiques sont appliqués au démarrage du service."
|
||||||
|
exit 0
|
||||||
|
fi
|
||||||
|
|
||||||
[[ -f "${ROOT}/dist/index.html" ]] || { echo "dist/ est absent : lance d'abord « make build »." >&2; exit 1; }
|
[[ -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; }
|
[[ -f "${ROOT}/dist/vendor/pyodide/pyodide.asm.wasm" ]] || { echo "Pyodide manque dans dist/ : « make vendor-pyodide » puis « make build »." >&2; exit 1; }
|
||||||
|
|
||||||
|
|||||||
Executable
+45
@@ -0,0 +1,45 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Première installation sur un VPS, depuis ta machine : envoie le code du backend, les fichiers de déploiement et
|
||||||
|
# nginx/, puis exécute deploy/remote_setup.sh en root sur le VPS (sudo, mot de passe demandé si besoin).
|
||||||
|
#
|
||||||
|
# DEPLOY_HOST=utilisateur@vps.example.org ./scripts/vps_bootstrap.sh --domain pyquest.example.org [--certbot mail] [--dry-run]
|
||||||
|
#
|
||||||
|
# Recommandé : commencer par --dry-run (n'écrit rien sur le VPS, affiche ce qui serait fait).
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||||
|
HOST="${DEPLOY_HOST:-}"
|
||||||
|
SSH="${DEPLOY_SSH:-ssh}"
|
||||||
|
DOMAIN=""
|
||||||
|
EXTRA=()
|
||||||
|
|
||||||
|
while [[ $# -gt 0 ]]; do
|
||||||
|
case "$1" in
|
||||||
|
--domain) DOMAIN="${2:-}"; shift 2 ;;
|
||||||
|
--certbot) EXTRA+=(--certbot "${2:-}"); shift 2 ;;
|
||||||
|
--dry-run) EXTRA+=(--dry-run); shift ;;
|
||||||
|
-h|--help) sed -n '2,8p' "${BASH_SOURCE[0]}"; exit 0 ;;
|
||||||
|
*) echo "Option inconnue : $1" >&2; exit 2 ;;
|
||||||
|
esac
|
||||||
|
done
|
||||||
|
[[ "${HOST}" =~ ^[A-Za-z0-9_.@:-]+$ ]] || { echo "DEPLOY_HOST manquant ou invalide (ex. utilisateur@vps.example.org)" >&2; exit 2; }
|
||||||
|
[[ "${DOMAIN}" =~ ^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]] || { echo "--domain manquant ou invalide" >&2; exit 2; }
|
||||||
|
DEPLOY_USER="${HOST%%@*}"
|
||||||
|
[[ "${HOST}" == *@* ]] || { echo "DEPLOY_HOST doit contenir l'utilisateur (utilisateur@hote)" >&2; exit 2; }
|
||||||
|
|
||||||
|
echo "1/3 Envoi du code du backend"
|
||||||
|
"${ROOT}/scripts/deploy.sh" --backend --no-restart
|
||||||
|
|
||||||
|
echo "2/3 Envoi des fichiers d'installation"
|
||||||
|
STAGE="/tmp/pyquest-setup"
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
${SSH} "${HOST}" "rm -rf '${STAGE}' && mkdir -p '${STAGE}'"
|
||||||
|
rsync -az -e "${SSH}" "${ROOT}/deploy/" "${HOST}:${STAGE}/deploy/"
|
||||||
|
rsync -az -e "${SSH}" "${ROOT}/nginx/" "${HOST}:${STAGE}/nginx/"
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
${SSH} "${HOST}" "mkdir -p '${STAGE}/scripts'"
|
||||||
|
rsync -az -e "${SSH}" "${ROOT}/scripts/backup_db.sh" "${HOST}:${STAGE}/scripts/"
|
||||||
|
|
||||||
|
echo "3/3 Installation sur le VPS (sudo)"
|
||||||
|
# shellcheck disable=SC2086
|
||||||
|
${SSH} -t "${HOST}" "sudo bash '${STAGE}/deploy/remote_setup.sh' --domain '${DOMAIN}' --deploy-user '${DEPLOY_USER}' ${EXTRA[*]:-}"
|
||||||
Executable
+94
@@ -0,0 +1,94 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Diagnostic en LECTURE SEULE d'un serveur PyQuest, à lancer depuis ta machine :
|
||||||
|
# ssh utilisateur@vps.example.org 'bash -s' < scripts/vps_doctor.sh
|
||||||
|
# (ou directement sur le VPS). Ne modifie rien et n'affiche aucun secret. Utile pour reprendre un déploiement.
|
||||||
|
set -uo pipefail
|
||||||
|
|
||||||
|
FAILED=0
|
||||||
|
ok() { printf ' ok %s\n' "$1"; }
|
||||||
|
ko() { printf ' ÉCHEC %s\n' "$1"; FAILED=1; }
|
||||||
|
info() { printf ' info %s\n' "$1"; }
|
||||||
|
can_sudo() { sudo -n true 2>/dev/null; }
|
||||||
|
as_root() { if [[ "${EUID}" -eq 0 ]]; then "$@"; elif can_sudo; then sudo -n "$@"; else return 126; fi; }
|
||||||
|
|
||||||
|
echo "Système"
|
||||||
|
info "$(. /etc/os-release 2>/dev/null && echo "${PRETTY_NAME:-inconnu}") — $(uname -r)"
|
||||||
|
info "disque libre sur / : $(df -h / | awk 'NR==2 {print $4}')"
|
||||||
|
|
||||||
|
echo "nginx"
|
||||||
|
if command -v nginx >/dev/null; then
|
||||||
|
version="$(nginx -v 2>&1 | sed 's/.*nginx\///')"
|
||||||
|
ok "nginx ${version}"
|
||||||
|
major="${version%%.*}"; minor="$(echo "${version}" | cut -d. -f2)"
|
||||||
|
if (( major > 1 || (major == 1 && minor >= 25) )); then ok "http2 on; pris en charge"; else info "nginx < 1.25.1 : utiliser « listen 443 ssl http2; »"; fi
|
||||||
|
if as_root nginx -t >/dev/null 2>&1; then ok "configuration valide (nginx -t)"; else info "nginx -t non vérifiable ou en échec (droits root requis) : lance « sudo nginx -t »"; fi
|
||||||
|
systemctl is-active --quiet nginx && ok "service nginx actif" || ko "service nginx inactif"
|
||||||
|
else
|
||||||
|
ko "nginx n'est pas installé"
|
||||||
|
fi
|
||||||
|
[[ -f /etc/nginx/snippets/pyquest-locations.conf ]] && ok "extrait pyquest-locations.conf installé" || ko "extrait /etc/nginx/snippets/pyquest-locations.conf manquant"
|
||||||
|
[[ -f /etc/nginx/snippets/pyquest-author-headers.conf ]] && ok "extrait pyquest-author-headers.conf installé" || ko "extrait pyquest-author-headers.conf manquant"
|
||||||
|
|
||||||
|
echo "Site statique"
|
||||||
|
WEB=/var/www/pyquest
|
||||||
|
if [[ -L "${WEB}/current" ]]; then
|
||||||
|
ok "current -> $(readlink "${WEB}/current")"
|
||||||
|
[[ -f "${WEB}/current/index.html" ]] && ok "index.html présent" || ko "index.html absent dans current"
|
||||||
|
[[ -f "${WEB}/current/vendor/pyodide/pyodide.asm.wasm" ]] && ok "moteur Python (Pyodide) présent" || ko "Pyodide absent : make vendor-pyodide puis make deploy"
|
||||||
|
info "versions conservées : $(ls -1 "${WEB}/releases" 2>/dev/null | wc -l)"
|
||||||
|
else
|
||||||
|
ko "${WEB}/current absent : aucun déploiement du site (make deploy)"
|
||||||
|
fi
|
||||||
|
[[ -d "${WEB}/static/admin" ]] && ok "fichiers statiques de l'administration présents" || info "statiques de l'administration absents (créés au démarrage du service)"
|
||||||
|
|
||||||
|
echo "Backend Django"
|
||||||
|
[[ -x /opt/pyquest/venv/bin/gunicorn ]] && ok "environnement Python et gunicorn installés" || ko "/opt/pyquest/venv/bin/gunicorn manquant (deploy/remote_setup.sh)"
|
||||||
|
[[ -f /opt/pyquest/backend/manage.py ]] && ok "code du backend présent" || ko "code du backend absent (make deploy-backend)"
|
||||||
|
if [[ -f /etc/pyquest/env ]]; then
|
||||||
|
perms="$(stat -c '%a %U:%G' /etc/pyquest/env)"
|
||||||
|
ok "/etc/pyquest/env présent (${perms})"
|
||||||
|
case "${perms%% *}" in 600|640|400|440) ok "droits du fichier d'environnement stricts" ;; *) ko "droits trop larges sur /etc/pyquest/env (attendu 640 root:pyquest)" ;; esac
|
||||||
|
if as_root grep -q '__A_REMPLIR__\|__A_GENERER__' /etc/pyquest/env 2>/dev/null; then ko "valeurs à remplir dans /etc/pyquest/env (mot de passe de la base ?)"; fi
|
||||||
|
else
|
||||||
|
ko "/etc/pyquest/env absent"
|
||||||
|
fi
|
||||||
|
if systemctl is-active --quiet pyquest 2>/dev/null; then
|
||||||
|
ok "service pyquest actif"
|
||||||
|
# Un jeton au bon format interroge la base : 404 = base joignable, 500 = base en panne.
|
||||||
|
code="$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 -H 'Authorization: Bearer aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' http://127.0.0.1:8001/api/sync/)"
|
||||||
|
case "${code}" in
|
||||||
|
404) ok "API répond et la base de données est joignable (404 attendu)" ;;
|
||||||
|
500) ko "l'API répond 500 : base de données injoignable ? (journalctl -u pyquest)" ;;
|
||||||
|
*) info "API répond ${code}" ;;
|
||||||
|
esac
|
||||||
|
[[ "$(curl -s -o /dev/null -w '%{http_code}' --max-time 10 http://127.0.0.1:8001/api/auth/check/)" == 401 ]] && ok "contrôle d'accès de l'éditeur répond (401 sans session)" || ko "/api/auth/check/ ne répond pas 401"
|
||||||
|
else
|
||||||
|
ko "service pyquest inactif (sudo systemctl enable --now pyquest ; journalctl -u pyquest -n 50)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Base de données"
|
||||||
|
if command -v mariadb >/dev/null || command -v mysql >/dev/null; then
|
||||||
|
ok "client MariaDB/MySQL présent"
|
||||||
|
systemctl is-active --quiet mariadb 2>/dev/null && ok "service mariadb actif" || info "service mariadb non local ou inactif"
|
||||||
|
else
|
||||||
|
info "pas de client MariaDB/MySQL (base distante ?)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Certificat"
|
||||||
|
domain="$(ls /etc/letsencrypt/live 2>/dev/null | grep -v README | head -n1 || true)"
|
||||||
|
if [[ -n "${domain}" ]]; then
|
||||||
|
end="$(as_root openssl x509 -enddate -noout -in "/etc/letsencrypt/live/${domain}/fullchain.pem" 2>/dev/null | cut -d= -f2)"
|
||||||
|
if [[ -n "${end}" ]]; then
|
||||||
|
days=$(( ( $(date -d "${end}" +%s) - $(date +%s) ) / 86400 ))
|
||||||
|
(( days > 14 )) && ok "certificat ${domain} valide encore ${days} jours" || ko "certificat ${domain} expire dans ${days} jours"
|
||||||
|
else
|
||||||
|
info "certificat ${domain} non lisible sans root"
|
||||||
|
fi
|
||||||
|
systemctl list-timers 2>/dev/null | grep -q certbot && ok "renouvellement automatique (minuteur certbot)" || info "minuteur certbot non trouvé : vérifier le renouvellement"
|
||||||
|
else
|
||||||
|
info "aucun certificat Let's Encrypt trouvé"
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo
|
||||||
|
if [[ "${FAILED}" == 0 ]]; then echo "Aucun problème détecté."; else echo "Des points demandent une action (lignes ÉCHEC)." >&2; fi
|
||||||
|
exit "${FAILED}"
|
||||||
@@ -52,4 +52,20 @@ DEPLOY_HOST='x; rm -rf /' "${DEPLOY}" >/dev/null 2>&1 && fail "hôte dangereux a
|
|||||||
DEPLOY_PATH='/var/www/a b' "${DEPLOY}" >/dev/null 2>&1 && fail "chemin avec espace 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é"
|
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é"
|
rm "${FAKE_ROOT}/dist/index.html"; "${DEPLOY}" >/dev/null 2>&1 && fail "dist absent accepté"
|
||||||
|
# --backend : code envoyé sans les fichiers locaux (base, caches), puis redémarrage demandé via sudo (faux sudo ici).
|
||||||
|
mkdir -p "${FAKE_ROOT}/backend/app1/__pycache__" "${WORK}/bin"
|
||||||
|
echo "print('manage')" > "${FAKE_ROOT}/backend/manage.py"
|
||||||
|
echo "x = 1" > "${FAKE_ROOT}/backend/app1/models.py"
|
||||||
|
echo "cache" > "${FAKE_ROOT}/backend/app1/__pycache__/models.pyc"
|
||||||
|
echo "secret-db" > "${FAKE_ROOT}/backend/db.sqlite3"
|
||||||
|
printf '#!/usr/bin/env bash\necho "sudo $*" >> "%s/sudo.log"\n' "${WORK}" > "${WORK}/bin/sudo"
|
||||||
|
chmod +x "${WORK}/bin/sudo"
|
||||||
|
export DEPLOY_BACKEND_PATH="${WORK}/opt/pyquest/backend"
|
||||||
|
PATH="${WORK}/bin:${PATH}" "${DEPLOY}" --backend >/dev/null
|
||||||
|
[[ -f "${DEPLOY_BACKEND_PATH}/manage.py" && -f "${DEPLOY_BACKEND_PATH}/app1/models.py" ]] || fail "le code du backend n'est pas envoyé"
|
||||||
|
[[ ! -e "${DEPLOY_BACKEND_PATH}/db.sqlite3" && ! -e "${DEPLOY_BACKEND_PATH}/app1/__pycache__" ]] || fail "base locale ou caches envoyés"
|
||||||
|
grep -q "systemctl restart pyquest" "${WORK}/sudo.log" || fail "le redémarrage du service n'est pas demandé"
|
||||||
|
rm "${WORK}/sudo.log"
|
||||||
|
PATH="${WORK}/bin:${PATH}" "${DEPLOY}" --backend --no-restart >/dev/null
|
||||||
|
[[ ! -e "${WORK}/sudo.log" ]] || fail "--no-restart ne doit pas redémarrer"
|
||||||
echo "deploy.sh : ok"
|
echo "deploy.sh : ok"
|
||||||
|
|||||||
Executable
+60
@@ -0,0 +1,60 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
# Teste les scripts d'exploitation du VPS sans serveur : sauvegarde de la base (faux mariadb-dump), installation
|
||||||
|
# (--dry-run : n'écrit rien) et validation des arguments. Le diagnostic (vps_doctor.sh) est seulement vérifié en lecture.
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
|
||||||
|
WORK="$(mktemp -d)"
|
||||||
|
trap 'rm -rf "${WORK}"' EXIT
|
||||||
|
fail() { echo "ÉCHEC : $1" >&2; exit 1; }
|
||||||
|
|
||||||
|
# ---- backup_db.sh -----------------------------------------------------------------------------------------------
|
||||||
|
mkdir -p "${WORK}/bin" "${WORK}/backups"
|
||||||
|
cat > "${WORK}/env" <<'ENV'
|
||||||
|
PYQUEST_DB_NAME=pyquest
|
||||||
|
PYQUEST_DB_USER=pyquest
|
||||||
|
PYQUEST_DB_PASSWORD=mot de passe avec $ et espaces
|
||||||
|
PYQUEST_DB_HOST=127.0.0.1
|
||||||
|
PYQUEST_DB_PORT=3306
|
||||||
|
ENV
|
||||||
|
# Faux mariadb-dump : produit un export plausible et enregistre la configuration de connexion reçue (sans l'afficher).
|
||||||
|
cat > "${WORK}/bin/mariadb-dump" <<SH
|
||||||
|
#!/usr/bin/env bash
|
||||||
|
for arg in "\$@"; do case "\$arg" in --defaults-extra-file=*) cp "\${arg#*=}" "${WORK}/cnf.copy";; esac; done
|
||||||
|
if [[ "\${FAKE_DUMP_EMPTY:-0}" == 1 ]]; then exit 0; fi
|
||||||
|
for i in \$(seq 1 40); do echo "INSERT INTO sync_syncprofile VALUES (\$i, 'hash\$i');"; done
|
||||||
|
SH
|
||||||
|
chmod +x "${WORK}/bin/mariadb-dump"
|
||||||
|
export PATH="${WORK}/bin:${PATH}" PYQUEST_ENV_FILE="${WORK}/env" PYQUEST_BACKUP_DIR="${WORK}/backups" PYQUEST_BACKUP_KEEP=2
|
||||||
|
|
||||||
|
for _ in 1 2 3; do sleep 1; "${ROOT}/scripts/backup_db.sh" >/dev/null; done
|
||||||
|
[[ "$(ls "${WORK}/backups" | wc -l)" == 2 ]] || fail "la rotation doit garder 2 sauvegardes"
|
||||||
|
latest="$(ls "${WORK}/backups"/*.sql.gz | sort | tail -n1)"
|
||||||
|
gunzip -c "${latest}" | grep -q "INSERT INTO sync_syncprofile" || fail "la sauvegarde ne contient pas l'export"
|
||||||
|
grep -q '^password=mot de passe avec \$ et espaces$' "${WORK}/cnf.copy" || fail "le mot de passe n'est pas transmis tel quel (fichier de configuration)"
|
||||||
|
[[ "$(stat -c %a "${WORK}/backups")" == 700 ]] || fail "le dossier de sauvegarde doit être privé (700)"
|
||||||
|
# Une sauvegarde vide est refusée et supprimée.
|
||||||
|
before="$(ls "${WORK}/backups" | wc -l)"
|
||||||
|
FAKE_DUMP_EMPTY=1 "${ROOT}/scripts/backup_db.sh" >/dev/null 2>&1 && fail "une sauvegarde vide ne doit pas être acceptée"
|
||||||
|
[[ "$(ls "${WORK}/backups" | wc -l)" == "${before}" ]] || fail "la sauvegarde vide n'a pas été supprimée"
|
||||||
|
# Le mot de passe n'apparaît jamais dans la sortie.
|
||||||
|
"${ROOT}/scripts/backup_db.sh" 2>&1 | grep -q "mot de passe avec" && fail "le mot de passe a fuité dans la sortie"
|
||||||
|
# Variables manquantes : refus net.
|
||||||
|
echo "PYQUEST_DB_NAME=x" > "${WORK}/env-incomplete"
|
||||||
|
PYQUEST_ENV_FILE="${WORK}/env-incomplete" "${ROOT}/scripts/backup_db.sh" >/dev/null 2>&1 && fail "variables incomplètes acceptées"
|
||||||
|
|
||||||
|
# ---- remote_setup.sh : arguments et --dry-run ------------------------------------------------------------------
|
||||||
|
SETUP="${ROOT}/deploy/remote_setup.sh"
|
||||||
|
"${SETUP}" --domain "pas un domaine" --deploy-user denis --dry-run >/dev/null 2>&1 && fail "domaine invalide accepté"
|
||||||
|
"${SETUP}" --domain pyquest.example.org --deploy-user 'x; rm -rf /' --dry-run >/dev/null 2>&1 && fail "utilisateur dangereux accepté"
|
||||||
|
"${SETUP}" --domain pyquest.example.org --deploy-user denis --certbot pas-un-mail --dry-run >/dev/null 2>&1 && fail "e-mail invalide accepté"
|
||||||
|
"${SETUP}" --domain pyquest.example.org --deploy-user denis >/dev/null 2>&1 && fail "doit exiger root hors --dry-run" || true
|
||||||
|
out="$("${SETUP}" --domain pyquest.example.org --deploy-user "$(id -un)" --dry-run 2>&1)"
|
||||||
|
echo "${out}" | grep -q "\[dry-run\] .*apt-get install" || fail "le dry-run doit annoncer l'installation des paquets"
|
||||||
|
echo "${out}" | grep -q "mariadb-setup.sql" || fail "les étapes restantes (base de données) doivent être listées"
|
||||||
|
echo "${out}" | grep -q "Pas de certificat\|vhost complet" || fail "le dry-run doit traiter nginx"
|
||||||
|
|
||||||
|
# ---- vps_doctor.sh : s'exécute en lecture seule et signale ce qui manque -----------------------------------------
|
||||||
|
doctor="$("${ROOT}/scripts/vps_doctor.sh" 2>&1 || true)"
|
||||||
|
echo "${doctor}" | grep -q "^Système" || fail "le diagnostic doit s'exécuter"
|
||||||
|
echo "deploy/ et scripts d'exploitation : ok"
|
||||||
Reference in New Issue
Block a user