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:
denis
2026-10-16 23:15:14 +02:00
parent fb3c539eee
commit a4df92a7c6
43 changed files with 2369 additions and 8 deletions
+44
View File
@@ -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.
+49
View File
@@ -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`.
+106
View File
@@ -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.
+225
View File
@@ -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.
+100
View File
@@ -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.
+32
View File
@@ -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.
+45
View File
@@ -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.
+65
View File
@@ -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.
+40
View File
@@ -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).
+47
View File
@@ -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.
+45
View File
@@ -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/`.
+59
View File
@@ -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.
+36
View File
@@ -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.