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:
@@ -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.
|
||||
Reference in New Issue
Block a user