diff --git a/CONTEXT.md b/CONTEXT.md index 6fe633a..5eb77c6 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -37,7 +37,8 @@ vrai navigateur (Chromium) avec 4 niveaux jouables. | Shell PWA | `app/index.html`, `app/js/main.js`, `app/service-worker.js`, `app/manifest.webmanifest` | | Tooling | `Makefile`, `scripts/{dev_server,validate_levels,build}.py`, `scripts/vendor_pyodide.sh` | | Tests | `tests/js/*.test.mjs` (node:test), `tests/python/`, `backend/sync/tests.py`, `tests/e2e/` (Chromium) | -| Backend | `backend/` Django : `GET/PUT /api/sync/` avec jeton Bearer (haché côté serveur) | +| Backend | `backend/` Django : `GET/PUT/DELETE /api/sync/` avec jeton Bearer (haché côté serveur), concurrence optimiste (`base` → 409) | +| Synchronisation | `core/SyncClient.js` + section Réglages ; export/import fichier ; voir `docs/design/09-sync.md` ; `make dev-sync` | ## Éditeur de niveaux (mode auteur) — fait le 2026-10-16 @@ -116,7 +117,7 @@ Flux de contribution documenté (`CONTRIBUTING.md`, `docs/MAINTAINERS.md`, `docs 3. **Navigateurs** : validé dans Chromium 155 seulement. Reste Firefox, Safari desktop et surtout **iOS Safari** (mémoire WASM, autoplay audio, `SharedArrayBuffer` + `Atomics.wait`). 4. Icônes PNG (iOS) en plus de `app/icons/icon.svg`. -5. Client de synchronisation (jeton + export/import) et son UI ; le backend existe. +5. ~~Client de synchronisation~~ fait (export/import fichier + sync complète, e2e avec vrai Django). Reste : QR code du jeton (dépendance), URL serveur configurable (CORS). 6. Documentation MkDocs bilingue (`docs/mkdocs/`) ; compilation des traductions Django (`compilemessages`, gettext absent du poste actuel). 7. Audit accessibilité réel (lecteur d'écran, axe) ; le champ de saisie `input()` en particulier. diff --git a/Makefile b/Makefile index 3494cef..e8525d1 100644 --- a/Makefile +++ b/Makefile @@ -5,7 +5,7 @@ VENV := .venv VENV_PY := $(VENV)/bin/python PORT ?= 8000 -.PHONY: help install vendor-pyodide dev validate-levels build test test-js test-python test-backend test-e2e typecheck icons voice check-voice ci ci-e2e clean +.PHONY: help install vendor-pyodide dev validate-levels build dev-sync test test-js test-python test-backend test-e2e typecheck icons voice check-voice ci ci-e2e clean help: ## Affiche cette aide @grep -E '^[a-z-]+:.*##' $(MAKEFILE_LIST) | awk -F':.*## ' '{printf " %-16s %s\n", $$1, $$2}' @@ -23,6 +23,12 @@ vendor-pyodide: ## Télécharge Pyodide (version épinglée) dans vendor/pyodide dev: ## Serveur de développement avec en-têtes COOP/COEP (PORT=8000) $(PYTHON) scripts/dev_server.py --port $(PORT) +dev-sync: $(VENV)/.installed ## Serveur de dev + backend Django relayé sur /api/ (synchronisation) + cd backend && DJANGO_SETTINGS_MODULE=pyquest_api.settings.dev ../$(VENV_PY) manage.py migrate --noinput + @set -e; (cd backend && DJANGO_SETTINGS_MODULE=pyquest_api.settings.dev ../$(VENV_PY) manage.py runserver 8001 --noreload) & \ + pid=$$!; trap "kill $$pid" EXIT INT TERM; \ + $(PYTHON) scripts/dev_server.py --port $(PORT) --api-upstream http://127.0.0.1:8001 + validate-levels: $(VENV)/.installed ## Valide les niveaux (schéma, manifeste, traductions) $(VENV_PY) scripts/validate_levels.py diff --git a/README-EN.md b/README-EN.md index 8a791f7..5789a22 100644 --- a/README-EN.md +++ b/README-EN.md @@ -47,6 +47,14 @@ a cell. Pyodide is served from the same domain (never from a CDN): this is a COEP requirement. +### Backup and sync (optional) + +The app is self-contained: progress is stored in the browser. In **Settings** you can export/import it +as a JSON file (no server), or sync it across devices with a secret token (no account) when the Django +backend is deployed on the same domain behind nginx (`/api/` → Django, see +[nginx/pyquest.conf.example](nginx/pyquest.conf.example)). In development: `make dev-sync`. +Details (in French): [docs/design/09-sync.md](docs/design/09-sync.md). + ## Contributing See [CONTRIBUTING.md](CONTRIBUTING.md) (contribution flow, adding a level with the editor) and [docs/MAINTAINERS.md](docs/MAINTAINERS.md) (review, release; in French). `make ci` runs the whole verification chain. diff --git a/README.md b/README.md index 77031ce..882f8f6 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,14 @@ Python pour arrêter une cellule. Pyodide est servi depuis le même domaine (jamais depuis un CDN) : c'est une contrainte de COEP. +### Sauvegarde et synchronisation (facultatives) + +L'application est autonome : la progression est stockée dans le navigateur. Dans **Réglages**, on peut +l'exporter/importer en fichier JSON (sans serveur), ou la synchroniser entre appareils avec un jeton +secret (sans compte) si le backend Django est déployé sur le même domaine, derrière nginx +(`/api/` → Django, voir [nginx/pyquest.conf.example](nginx/pyquest.conf.example)). En développement : +`make dev-sync`. Fonctionnement détaillé : [docs/design/09-sync.md](docs/design/09-sync.md). + ## Contribuer Voir [CONTRIBUTING.md](CONTRIBUTING.md) (flux de contribution, ajout d'un niveau avec l'éditeur) et [docs/MAINTAINERS.md](docs/MAINTAINERS.md) (relecture, publication). `make ci` lance toute la chaîne de vérification. diff --git a/app/css/base.css b/app/css/base.css index 4e4a02d..47f7a74 100644 --- a/app/css/base.css +++ b/app/css/base.css @@ -307,6 +307,22 @@ pre { margin: 0.25rem 0.5rem 0.25rem 0; } +.setting.stacked { + grid-template-columns: 1fr; + gap: 0.25rem; +} + +.token-input { + width: 100%; + min-height: 2.5rem; + font-family: var(--font-code); + font-size: 0.85rem; +} + +.sync-message:empty { + display: none; +} + .author-link { display: inline-flex; align-items: center; diff --git a/app/js/core/SyncClient.js b/app/js/core/SyncClient.js new file mode 100644 index 0000000..a94ab6a --- /dev/null +++ b/app/js/core/SyncClient.js @@ -0,0 +1,268 @@ +// Client de synchronisation optionnelle de la progression avec le backend Django (même domaine). +// Aucun compte : un jeton secret généré ici identifie le profil (le serveur n'en garde que le hash). +// Cycle : GET (fusion locale) puis PUT de l'état fusionné ; la fusion se fait toujours côté client +// (ProgressStore.import), le serveur ne fait que stocker. Concurrence optimiste : si un autre +// appareil a écrit entre-temps, le serveur répond 409 avec son état, on fusionne et on réessaie. +// L'application ne dépend jamais de ce module pour fonctionner : toute erreur est un état, pas une exception. + +const STORAGE_KEY = 'sync'; +const TOKEN_PATTERN = /^[A-Za-z0-9_-]{32,128}$/; +const MAX_ATTEMPTS = 4; +const REQUEST_TIMEOUT_MS = 10000; + +export class SyncClient extends EventTarget { + #store; + #progress; + #fetch; + #endpoint; + #debounceMs; + #now; + #token = null; + #lastSync = null; + #status = 'off'; // 'off' | 'idle' | 'syncing' | 'error' + #error = null; // 'offline' | 'unauthorized' | 'unavailable' | 'rejected' | 'invalid' + #running = null; + #rerun = false; + #timer = null; + #applying = false; + + /** + * @param {object} options + * @param {{get: Function, set: Function}} options.store Magasin clé/valeur du jeton. + * @param {import('./ProgressStore.js').ProgressStore} options.progress + * @param {string} options.endpoint URL de l'API (même domaine que l'application). + */ + constructor({ store, progress, endpoint, fetchFn = (...args) => globalThis.fetch(...args), debounceMs = 2000, now = () => new Date() }) { + super(); + this.#store = store; + this.#progress = progress; + this.#endpoint = endpoint; + this.#fetch = fetchFn; + this.#debounceMs = debounceMs; + this.#now = now; + progress.addEventListener('change', () => this.#onProgressChange()); + } + + /** Jeton aléatoire de 256 bits, base64url (43 caractères) ; jamais dérivé d'une donnée personnelle. */ + static generateToken(cryptoApi = globalThis.crypto) { + const bytes = cryptoApi.getRandomValues(new Uint8Array(32)); + return btoa(String.fromCharCode(...bytes)) + .replaceAll('+', '-') + .replaceAll('/', '_') + .replaceAll('=', ''); + } + + static isValidToken(token) { + return typeof token === 'string' && TOKEN_PATTERN.test(token); + } + + get state() { + return { enabled: this.#token !== null, token: this.#token, status: this.#status, error: this.#error, lastSync: this.#lastSync }; + } + + async load() { + const saved = await this.#store.get(STORAGE_KEY); + if (saved && SyncClient.isValidToken(saved.token)) { + this.#token = saved.token; + this.#lastSync = typeof saved.lastSync === 'string' ? saved.lastSync : null; + this.#status = 'idle'; + } + return this.state; + } + + /** Au démarrage : si la synchronisation est active, un cycle immédiat. */ + start() { + return this.#token ? this.sync() : Promise.resolve({ ok: false, code: 'disabled' }); + } + + /** Active la synchronisation avec un nouveau profil, puis envoie la progression locale. */ + async enable() { + await this.#setToken(SyncClient.generateToken()); + return this.sync(); + } + + /** Rejoint un profil existant (jeton copié depuis un autre appareil) : les progressions sont fusionnées. */ + async link(token) { + const clean = String(token ?? '').trim(); + if (!SyncClient.isValidToken(clean)) { + throw new Error('Invalid sync token'); + } + await this.#setToken(clean); + return this.sync(); + } + + /** + * Désactive localement ; avec `eraseRemote`, supprime d'abord les données du serveur + * (si l'effacement échoue, on reste actif pour pouvoir réessayer). + */ + async disable({ eraseRemote = false } = {}) { + if (this.#timer !== null) { + clearTimeout(this.#timer); + this.#timer = null; + } + if (eraseRemote && this.#token) { + const outcome = await this.#call('DELETE'); + if (outcome.code || outcome.status !== 204) { + return { ok: false, code: outcome.code ?? (outcome.status === 401 ? 'unauthorized' : 'unavailable') }; + } + } + this.#token = null; + this.#lastSync = null; + this.#status = 'off'; + this.#error = null; + await this.#store.set(STORAGE_KEY, { token: null, lastSync: null }); + this.#emitChange(); + return { ok: true }; + } + + /** Un cycle complet ; les appels simultanés sont regroupés (un cycle de plus au plus). Ne lève jamais. */ + sync() { + if (!this.#token) { + return Promise.resolve({ ok: false, code: 'disabled' }); + } + if (this.#running) { + this.#rerun = true; + return this.#running; + } + this.#running = (async () => { + let result; + do { + this.#rerun = false; + result = await this.#cycle(); + } while (this.#rerun && result.ok); + return result; + })().finally(() => { + this.#running = null; + }); + return this.#running; + } + + async #setToken(token) { + this.#token = token; + this.#lastSync = null; + this.#status = 'idle'; + this.#error = null; + await this.#persist(); + this.#emitChange(); + } + + #onProgressChange() { + // Les changements dus à une fusion venant du serveur ne repartent pas vers le serveur. + if (!this.#token || this.#applying) { + return; + } + clearTimeout(this.#timer); + this.#timer = setTimeout(() => { + this.#timer = null; + this.sync(); + }, this.#debounceMs); + } + + async #cycle() { + this.#status = 'syncing'; + this.#error = null; + this.#emitChange(); + + let base = null; + const first = await this.#call('GET'); + if (first.code) { + return this.#fail(first.code); + } + if (first.status === 200) { + base = first.body.updated_at ?? null; + if (!(await this.#merge(first.body.payload))) { + return this.#fail('invalid'); + } + } else if (first.status !== 404 || !first.fromApi) { + // 404 d'un serveur statique (sans Django) : la synchronisation n'est pas disponible ici. + return this.#fail(first.status === 401 ? 'unauthorized' : 'unavailable'); + } + + for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt += 1) { + const put = await this.#call('PUT', { payload: JSON.parse(this.#progress.export()), base }); + if (put.code) { + return this.#fail(put.code); + } + if (put.status === 200) { + this.#lastSync = this.#now().toISOString(); + this.#status = 'idle'; + await this.#persist(); + this.#emitChange(); + return { ok: true }; + } + if (put.status === 409) { + // Un autre appareil a écrit entre notre lecture et notre envoi : on fusionne son état. + base = put.body.updated_at ?? null; + if (!(await this.#merge(put.body.payload))) { + return this.#fail('invalid'); + } + continue; + } + return this.#fail(put.status === 401 ? 'unauthorized' : put.status === 400 || put.status === 413 ? 'rejected' : 'unavailable'); + } + return this.#fail('unavailable'); + } + + /** Fusionne un état venant du serveur (donnée non fiable : ProgressStore la valide). */ + async #merge(payload) { + const before = this.#progress.export(); + this.#applying = true; + try { + await this.#progress.import(JSON.stringify(payload)); + } catch { + return false; + } finally { + this.#applying = false; + } + if (this.#progress.export() !== before) { + this.dispatchEvent(new CustomEvent('merged')); + } + return true; + } + + /** @returns {Promise<{status?: number, body?: any, fromApi?: boolean, code?: string}>} `code` seulement si la requête n'a pas abouti. */ + async #call(method, body) { + const options = { + method, + headers: { Authorization: `Bearer ${this.#token}`, 'Content-Type': 'application/json', Accept: 'application/json' }, + cache: 'no-store', + }; + if (body !== undefined) { + options.body = JSON.stringify(body); + } + if (typeof AbortSignal?.timeout === 'function') { + options.signal = AbortSignal.timeout(REQUEST_TIMEOUT_MS); + } + let response; + try { + response = await this.#fetch(this.#endpoint, options); + } catch { + return { code: 'offline' }; + } + const fromApi = (response.headers.get('content-type') ?? '').includes('application/json'); + let parsed = null; + if (fromApi && response.status !== 204) { + try { + parsed = await response.json(); + } catch { + parsed = null; + } + } + return { status: response.status, body: parsed ?? {}, fromApi }; + } + + #fail(code) { + this.#status = 'error'; + this.#error = code; + this.#emitChange(); + return { ok: false, code }; + } + + async #persist() { + await this.#store.set(STORAGE_KEY, { token: this.#token, lastSync: this.#lastSync }); + } + + #emitChange() { + this.dispatchEvent(new CustomEvent('change', { detail: this.state })); + } +} diff --git a/app/js/i18n/en.json b/app/js/i18n/en.json index df59cbc..4d43b9a 100644 --- a/app/js/i18n/en.json +++ b/app/js/i18n/en.json @@ -93,5 +93,31 @@ "backup.import": "Import progress", "backup.imported": "Progress imported: {n} new level(s).", "backup.importFailed": "This file is not a valid PyQuest progress file.", - "backup.exported": "Progress exported." + "backup.exported": "Progress exported.", + "sync.title": "Sync between devices (optional)", + "sync.help": "Find your progress on another device. No account: a secret token is enough. Needs a PyQuest server with sync; the app works fine without it.", + "sync.enable": "Turn on sync", + "sync.linkLabel": "Or paste the token from another device", + "sync.link": "Link this device", + "sync.tokenLabel": "Your secret token", + "sync.tokenHelp": "Keep it like a password: it gives access to your progress. If lost, it cannot be recovered (also use the file export).", + "sync.copy": "Copy the token", + "sync.copied": "Token copied.", + "sync.copyFailed": "Could not copy: select the token and copy it by hand.", + "sync.now": "Sync now", + "sync.disable": "Turn off (keep the server data)", + "sync.erase": "Turn off and erase the server data", + "sync.erased": "Sync turned off, server data erased.", + "sync.disabled": "Sync turned off.", + "sync.enabled": "Sync turned on.", + "sync.linked": "Device linked: progress merged.", + "sync.invalidToken": "This token is not valid (at least 32 characters: letters, digits, - and _).", + "sync.status.syncing": "Syncing…", + "sync.status.last": "Last sync: {when}.", + "sync.status.never": "Not synced yet.", + "sync.error.offline": "Offline: will retry when the connection is back. Your local progress is safe.", + "sync.error.unauthorized": "The server refuses this token.", + "sync.error.unavailable": "No sync server available here. Your local progress is safe.", + "sync.error.rejected": "The server rejected the data sent.", + "sync.error.invalid": "The data received from the server is invalid and was ignored." } diff --git a/app/js/i18n/fr.json b/app/js/i18n/fr.json index e4182ca..034c210 100644 --- a/app/js/i18n/fr.json +++ b/app/js/i18n/fr.json @@ -93,5 +93,31 @@ "backup.import": "Importer une progression", "backup.imported": "Progression importée : {n} nouveau(x) niveau(x).", "backup.importFailed": "Ce fichier n'est pas une progression PyQuest valide.", - "backup.exported": "Progression exportée." + "backup.exported": "Progression exportée.", + "sync.title": "Synchronisation entre appareils (facultatif)", + "sync.help": "Retrouve ta progression sur un autre appareil. Pas de compte : un jeton secret suffit. Nécessite un serveur PyQuest avec synchronisation ; l'application fonctionne très bien sans.", + "sync.enable": "Activer la synchronisation", + "sync.linkLabel": "Ou colle le jeton d'un autre appareil", + "sync.link": "Lier cet appareil", + "sync.tokenLabel": "Ton jeton secret", + "sync.tokenHelp": "Garde-le comme un mot de passe : il donne accès à ta progression. S'il est perdu, il ne peut pas être récupéré (utilise aussi l'export en fichier).", + "sync.copy": "Copier le jeton", + "sync.copied": "Jeton copié.", + "sync.copyFailed": "Copie impossible : sélectionne le jeton et copie-le à la main.", + "sync.now": "Synchroniser maintenant", + "sync.disable": "Désactiver (garder les données du serveur)", + "sync.erase": "Désactiver et effacer les données du serveur", + "sync.erased": "Synchronisation désactivée, données du serveur effacées.", + "sync.disabled": "Synchronisation désactivée.", + "sync.enabled": "Synchronisation activée.", + "sync.linked": "Appareil lié : progressions fusionnées.", + "sync.invalidToken": "Ce jeton n'est pas valide (au moins 32 caractères : lettres, chiffres, - et _).", + "sync.status.syncing": "Synchronisation en cours…", + "sync.status.last": "Dernière synchronisation : {when}.", + "sync.status.never": "Pas encore synchronisé.", + "sync.error.offline": "Hors ligne : nouvel essai dès que la connexion revient. Ta progression locale est intacte.", + "sync.error.unauthorized": "Le serveur refuse ce jeton.", + "sync.error.unavailable": "Pas de serveur de synchronisation disponible ici. Ta progression locale est intacte.", + "sync.error.rejected": "Le serveur a refusé les données envoyées.", + "sync.error.invalid": "Les données reçues du serveur sont invalides et ont été ignorées." } diff --git a/app/js/main.js b/app/js/main.js index 2fa0458..4c8e259 100644 --- a/app/js/main.js +++ b/app/js/main.js @@ -8,6 +8,7 @@ import { IndexedDbKeyValueStore, MemoryKeyValueStore } from './core/KeyValueStor import { ProgressStore } from './core/ProgressStore.js'; import { PyodideWorkerClient } from './core/PyodideWorkerClient.js'; import { SettingsStore } from './core/SettingsStore.js'; +import { SyncClient } from './core/SyncClient.js'; import { ValidationEngine } from './core/ValidationEngine.js'; import { VoiceEngine } from './core/VoiceEngine.js'; import { I18n } from './i18n/i18n.js'; @@ -58,6 +59,7 @@ class App { #i18n; #settings; #progress; + #sync; #lessons; #audio; #voice; @@ -88,6 +90,9 @@ class App { this.#progress = new ProgressStore(store); await this.#progress.load(); + // Synchronisation facultative : l'API est sur le même domaine (nginx), sinon l'état « indisponible » s'affiche. + this.#sync = new SyncClient({ store, progress: this.#progress, endpoint: new URL('api/sync/', document.baseURI).href }); + await this.#sync.load(); this.#lessons = new LessonEngine({ levelsUrl: new URL('/levels/', location.href).href }); this.#audio = new AudioEngine({ enabled: settings.soundEnabled, volume: settings.volume }); this.#voice = new VoiceEngine({ enabled: settings.voiceEnabled, rate: settings.voiceRate }); @@ -120,8 +125,12 @@ class App { this.#goTo(event.detail.id); }); this.#panel = new SettingsPanel(this.#i18n); + this.#panel.setSync(this.#sync.state); this.#panel.addEventListener('change', (event) => this.#onSettingChange(event.detail)); this.#panel.addEventListener('test', (event) => this.#onTest(event.detail.kind)); + this.#panel.addEventListener('sync', (event) => this.#onSync(event.detail)); + this.#sync.addEventListener('change', (event) => this.#panel.setSync(event.detail)); + this.#sync.addEventListener('merged', () => this.#renderMap()); this.#panel.addEventListener('export', () => this.#exportProgress()); this.#panel.addEventListener('import', (event) => this.#importProgress(event.detail.file)); @@ -142,6 +151,14 @@ class App { // Retour après une pause (2 jours ou plus sans activité) : accueil bienveillant, sans reproche. await this.#openLevel(next, { greeting: this.#isReturning() ? 'welcome_back' : 'level_start' }); this.#registerServiceWorker(); + // Synchronisation (si activée) : au démarrage, au retour du réseau et quand l'onglet redevient visible. + this.#sync.start(); + window.addEventListener('online', () => this.#sync.sync()); + document.addEventListener('visibilitychange', () => { + if (!document.hidden) { + this.#sync.sync(); + } + }); } /** Vrai si l'apprenant a déjà de l'activité mais pas depuis au moins deux jours. */ @@ -269,6 +286,40 @@ class App { } } + async #onSync({ action, token }) { + const t = (key) => this.#i18n.t(key); + const say = (key) => this.#panel.setSync(this.#sync.state, key ? t(key) : ''); + if (action === 'enable') { + const result = await this.#sync.enable(); + say(result.ok ? 'sync.enabled' : ''); + } else if (action === 'link') { + try { + const result = await this.#sync.link(token); + say(result.ok ? 'sync.linked' : ''); + } catch { + say('sync.invalidToken'); + } + } else if (action === 'now') { + await this.#sync.sync(); + say(''); + } else if (action === 'disable' || action === 'erase') { + const result = await this.#sync.disable({ eraseRemote: action === 'erase' }); + if (result.ok) { + say(action === 'erase' ? 'sync.erased' : 'sync.disabled'); + } else { + this.#panel.setSync(this.#sync.state, t(`sync.error.${result.code}`)); + } + } else if (action === 'copy') { + try { + await navigator.clipboard.writeText(this.#sync.state.token); + say('sync.copied'); + } catch { + // Pas d'API presse-papiers (http, autorisation refusée) : la copie manuelle reste possible. + say('sync.copyFailed'); + } + } + } + /** Télécharge la progression en JSON (Blob + lien temporaire : API standard, sans serveur). */ #exportProgress() { const blob = new Blob([this.#progress.export()], { type: 'application/json' }); diff --git a/app/js/ui/SettingsPanel.js b/app/js/ui/SettingsPanel.js index f43384e..f1a35e0 100644 --- a/app/js/ui/SettingsPanel.js +++ b/app/js/ui/SettingsPanel.js @@ -7,6 +7,9 @@ import { el, uniqueId } from './dom.js'; export class SettingsPanel extends EventTarget { #i18n; #root; + #syncRoot = el('fieldset', { class: 'setting-group sync-group' }); + #syncState = { enabled: false, token: null, status: 'off', error: null, lastSync: null }; + #syncMessage = ''; /** @param {import('../i18n/i18n.js').I18n} i18n */ constructor(i18n) { @@ -43,8 +46,17 @@ export class SettingsPanel extends EventTarget { this.#field('settings.voiceRate', 'range', { value: settings.voiceRate, min: 0.5, max: 2, step: 0.1, key: 'voiceRate', number: true }), this.#field('settings.author', 'checkbox', { value: settings.authorMode, key: 'authorMode' }), this.#backupSection(), + this.#syncRoot, settings.authorMode ? el('a', { class: 'btn author-link', href: 'author.html', text: t('settings.authorOpen') }) : null, ); + this.#renderSync(); + } + + /** Met à jour la section de synchronisation (état du SyncClient ; `message` : résultat d'une action). */ + setSync(state, message = this.#syncMessage) { + this.#syncState = state; + this.#syncMessage = message; + this.#renderSync(); } /** Redonne le focus à un réglage après un nouveau rendu (ex. changement de langue). */ @@ -80,6 +92,52 @@ export class SettingsPanel extends EventTarget { ); } + #renderSync() { + const t = (key, params) => this.#i18n.t(key, params); + const state = this.#syncState; + const emit = (action, extra = {}) => this.dispatchEvent(new CustomEvent('sync', { detail: { action, ...extra } })); + const button = (key, action, extra) => el('button', { type: 'button', class: 'btn', 'data-action': action, text: t(key), onclick: () => emit(action, extra) }); + const activeAction = this.#syncRoot.contains(document.activeElement) ? (document.activeElement.dataset.action ?? 'token') : null; + const children = [el('legend', { text: t('sync.title') }), el('p', { class: 'hint', text: t('sync.help') })]; + + if (!state.enabled) { + const id = uniqueId('sync-token'); + const input = el('input', { id, type: 'text', autocomplete: 'off', spellcheck: 'false', class: 'token-input' }); + children.push( + button('sync.enable', 'enable'), + el('div', { class: 'setting stacked' }, el('label', { for: id, text: t('sync.linkLabel') }), input), + el('button', { type: 'button', class: 'btn', 'data-action': 'link', text: t('sync.link'), onclick: () => emit('link', { token: input.value }) }), + ); + } else { + const id = uniqueId('sync-mytoken'); + const when = state.lastSync ? new Date(state.lastSync).toLocaleString(this.#i18n.lang) : null; + const status = + state.status === 'syncing' + ? t('sync.status.syncing') + : state.status === 'error' + ? t(`sync.error.${state.error}`) + : when + ? t('sync.status.last', { when }) + : t('sync.status.never'); + children.push( + el('p', { class: 'sync-status', role: 'status', 'data-status': state.status, text: status }), + el('div', { class: 'setting stacked' }, el('label', { for: id, text: t('sync.tokenLabel') }), el('input', { id, type: 'text', readonly: true, class: 'token-input', value: state.token })), + el('p', { class: 'hint', text: t('sync.tokenHelp') }), + button('sync.copy', 'copy'), + button('sync.now', 'now'), + button('sync.disable', 'disable'), + button('sync.erase', 'erase'), + ); + } + // Résultat de la dernière action (copie, jeton invalide…) : annoncé aux lecteurs d'écran. + children.push(el('p', { class: 'sync-message', role: 'status', text: this.#syncMessage })); + this.#syncRoot.replaceChildren(...children); + // Le rendu remplace les boutons : on redonne le focus à l'équivalent (ou au jeton) pour le clavier. + if (activeAction) { + (this.#syncRoot.querySelector(`[data-action="${activeAction}"]`) ?? this.#syncRoot.querySelector('.token-input'))?.focus(); + } + } + #testButton(labelKey, kind) { const button = el('button', { type: 'button', diff --git a/backend/locale/en/LC_MESSAGES/django.po b/backend/locale/en/LC_MESSAGES/django.po index e860bef..c88bc12 100644 --- a/backend/locale/en/LC_MESSAGES/django.po +++ b/backend/locale/en/LC_MESSAGES/django.po @@ -27,3 +27,7 @@ msgstr "" #: sync/views.py msgid "Invalid request." msgstr "" + +#: sync/views.py +msgid "Progress changed on the server." +msgstr "" diff --git a/backend/locale/fr/LC_MESSAGES/django.po b/backend/locale/fr/LC_MESSAGES/django.po index 3ef021e..6831e0a 100644 --- a/backend/locale/fr/LC_MESSAGES/django.po +++ b/backend/locale/fr/LC_MESSAGES/django.po @@ -27,3 +27,7 @@ msgstr "Aucune progression enregistrée pour ce jeton." #: sync/views.py msgid "Invalid request." msgstr "Requête invalide." + +#: sync/views.py +msgid "Progress changed on the server." +msgstr "La progression a changé sur le serveur." diff --git a/backend/pyquest_api/settings/dev.py b/backend/pyquest_api/settings/dev.py index f1c8ab9..414e724 100644 --- a/backend/pyquest_api/settings/dev.py +++ b/backend/pyquest_api/settings/dev.py @@ -1,5 +1,7 @@ """Réglages de développement : SQLite locale, DEBUG actif, clé non secrète.""" +import os + from .base import * # noqa: F401,F403 from .base import BASE_DIR @@ -10,6 +12,7 @@ ALLOWED_HOSTS = ["127.0.0.1", "localhost"] DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", - "NAME": BASE_DIR / "db.sqlite3", + # PYQUEST_DB_PATH : base jetable (tests de bout en bout), sans toucher à la base de dev. + "NAME": os.environ.get("PYQUEST_DB_PATH", BASE_DIR / "db.sqlite3"), } } diff --git a/backend/sync/tests.py b/backend/sync/tests.py index 4359eb5..7bab432 100644 --- a/backend/sync/tests.py +++ b/backend/sync/tests.py @@ -46,3 +46,22 @@ class SyncApiTest(TestCase): def test_rejects_oversized_payload(self) -> None: big = {"payload": {"version": 1, "blob": "x" * (300 * 1024)}} self.assertEqual(self.put(big).status_code, 400) + + def test_optimistic_concurrency(self) -> None: + first = self.put({"payload": PAYLOAD}).json()["updated_at"] + # Mise à jour avec la bonne base : acceptée. + second = self.put({"payload": PAYLOAD, "base": first}).json()["updated_at"] + # Base périmée (un autre appareil est passé entre-temps) : 409 avec l'état courant. + stale = self.put({"payload": {**PAYLOAD, "badges": {"x": "y"}}, "base": first}) + self.assertEqual(stale.status_code, 409) + self.assertEqual(stale.json()["updated_at"], second) + self.assertEqual(stale.json()["payload"], PAYLOAD) + self.assertEqual(self.put({"payload": PAYLOAD, "base": 12}).status_code, 400) + + def test_delete_erases_data(self) -> None: + self.put({"payload": PAYLOAD}) + self.assertEqual(self.client.delete(URL, headers=bearer(TOKEN)).status_code, 204) + self.assertEqual(self.client.get(URL, headers=bearer(TOKEN)).status_code, 404) + # Idempotent, et exige toujours un jeton valide. + self.assertEqual(self.client.delete(URL, headers=bearer(TOKEN)).status_code, 204) + self.assertEqual(self.client.delete(URL).status_code, 401) diff --git a/backend/sync/views.py b/backend/sync/views.py index b8f8686..f5ebccb 100644 --- a/backend/sync/views.py +++ b/backend/sync/views.py @@ -2,6 +2,9 @@ Le serveur ne fait que stocker le dernier JSON exporté par `ProgressStore` ; la fusion entre appareils reste côté client (ProgressStore.import, mode `merge`). + +Concurrence optimiste : le client envoie `base` (le `updated_at` qu'il a lu). Si le profil a changé +depuis (autre appareil), la réponse est 409 avec l'état courant : le client fusionne et réessaie. """ from __future__ import annotations @@ -12,7 +15,8 @@ import re from typing import Any from django.conf import settings -from django.http import HttpRequest, JsonResponse +from django.db import transaction +from django.http import HttpRequest, HttpResponse, JsonResponse from django.utils.translation import gettext as _ from django.views.decorators.csrf import csrf_exempt from django.views.decorators.http import require_http_methods @@ -35,23 +39,27 @@ def _token_hash(request: HttpRequest) -> str | None: return hashlib.sha256(token.encode("ascii")).hexdigest() -def _parse_payload(request: HttpRequest) -> tuple[dict[str, Any] | None, str | None]: +def _parse_payload(request: HttpRequest) -> tuple[dict[str, Any] | None, str | None, str | None]: + """Renvoie (payload, base, problème) ; `base` est le updated_at connu du client, ou None.""" if len(request.body) > settings.SYNC_MAX_PAYLOAD_BYTES: - return None, _("Payload too large.") + return None, None, _("Payload too large.") try: data = json.loads(request.body) except json.JSONDecodeError: - return None, _("Invalid JSON.") + return None, None, _("Invalid JSON.") payload = data.get("payload") if isinstance(data, dict) else None if not isinstance(payload, dict) or not isinstance(payload.get("version"), int): - return None, _("Invalid progress payload.") - return payload, None + return None, None, _("Invalid progress payload.") + base = data.get("base") + if base is not None and not isinstance(base, str): + return None, None, _("Invalid progress payload.") + return payload, base, None # Pas de cookie ni de session : l'authentification est le jeton Bearer, donc pas de CSRF. @csrf_exempt -@require_http_methods(["GET", "PUT"]) -def progress(request: HttpRequest) -> JsonResponse: +@require_http_methods(["GET", "PUT", "DELETE"]) +def progress(request: HttpRequest) -> HttpResponse: token_hash = _token_hash(request) if token_hash is None: return _error(_("Missing or malformed token."), 401) @@ -62,8 +70,21 @@ def progress(request: HttpRequest) -> JsonResponse: return _error(_("No progress stored for this token."), 404) return JsonResponse({"payload": profile.payload, "updated_at": profile.updated_at.isoformat()}) - payload, problem = _parse_payload(request) + if request.method == "DELETE": + # Droit à l'effacement : supprime définitivement les données liées à ce jeton. + SyncProfile.objects.filter(token_hash=token_hash).delete() + return HttpResponse(status=204) + + payload, base, problem = _parse_payload(request) if payload is None: return _error(problem or _("Invalid request."), 400) - profile, _created = SyncProfile.objects.update_or_create(token_hash=token_hash, defaults={"payload": payload}) + with transaction.atomic(): + profile = SyncProfile.objects.select_for_update().filter(token_hash=token_hash).first() + if profile is None: + profile = SyncProfile.objects.create(token_hash=token_hash, payload=payload) + else: + if base is not None and base != profile.updated_at.isoformat(): + return JsonResponse({"error": _("Progress changed on the server."), "payload": profile.payload, "updated_at": profile.updated_at.isoformat()}, status=409) + profile.payload = payload + profile.save() return JsonResponse({"updated_at": profile.updated_at.isoformat()}) diff --git a/docs/design/09-sync.md b/docs/design/09-sync.md new file mode 100644 index 0000000..aabd262 --- /dev/null +++ b/docs/design/09-sync.md @@ -0,0 +1,53 @@ +# Synchronisation entre appareils (facultative) + +L'application est autonome : la progression vit dans l'IndexedDB du navigateur. La synchronisation ne +sert qu'à retrouver sa progression sur un autre appareil. Rien n'en dépend. + +## Deux niveaux, indépendants + +1. **Sauvegarde par fichier** (aucun serveur) : Réglages → « Exporter ma progression » télécharge un + JSON ; « Importer une progression » le fusionne (union, rien n'est jamais perdu). +2. **Synchronisation** (serveur PyQuest avec le backend Django, même domaine via nginx). + +## Principe + +- Pas de compte. Au clic sur « Activer », le navigateur génère un **jeton** de 256 bits (43 caractères + URL-safe). Le jeton est l'identifiant *et* le secret ; le serveur n'en stocke que le **SHA-256**. +- Un second appareil rejoint le profil en collant le jeton (« Lier cet appareil »). +- Le jeton reste dans l'IndexedDB (clé `sync`) ; il n'est jamais inclus dans l'export de progression. +- **Perte du jeton = pas de récupération possible** (conséquence voulue de « pas de compte »). L'export + fichier reste le filet de sécurité. + +## Protocole (`/api/sync/`, en-tête `Authorization: Bearer `) + +| Appel | Réponse | +|---|---| +| `GET` | `200 {payload, updated_at}` ou `404 {error}` (rien de stocké) | +| `PUT {payload, base}` | `200 {updated_at}` ; `409 {payload, updated_at}` si `base` ≠ version serveur ; `400` payload invalide ou trop gros (256 Ko) | +| `DELETE` | `204` : efface définitivement les données liées au jeton (droit à l'effacement) | +| (tout) | `401` sans jeton valide | + +`base` est le `updated_at` lu par le client : **concurrence optimiste**. Le serveur ne fusionne jamais. + +## Cycle client (`app/js/core/SyncClient.js`) + +1. `GET` → fusion locale (`ProgressStore.import`, mode merge : union des niveaux et badges, meilleur streak). +2. `PUT` de l'état fusionné avec `base`. Sur `409` : fusion de l'état renvoyé, nouvel essai (4 au plus). +3. Déclencheurs : activation, démarrage, retour du réseau (`online`), onglet de nouveau visible, + et 2 s après un changement local (debounce). Une fusion venant du serveur ne repart pas vers le serveur. + +Les erreurs sont des **états** (`offline`, `unauthorized`, `unavailable`, `rejected`, `invalid`), jamais +des exceptions : l'application continue de fonctionner, la progression locale est intacte. Un `404` +non JSON (serveur statique sans Django) donne `unavailable`. + +## Sécurité + +- Toute donnée venant du serveur ou d'un fichier est **non fiable** : `ProgressStore` la valide + strictement (types, bornes, identifiants `[A-Za-z0-9_-]{1,64}` hors `__proto__`) avant fusion. +- Même origine uniquement : pas de CORS, pas d'exception COEP. En dev : `make dev-sync`. +- nginx : limite de débit et taille de corps (voir `nginx/pyquest.conf.example`). + +## Non fait (volontairement) + +- QR code du jeton (aurait demandé une dépendance) : copier/coller suffit pour l'instant. +- URL de serveur configurable (implique CORS) : l'API est toujours `api/sync/` sur le domaine de l'app. diff --git a/nginx/pyquest.conf.example b/nginx/pyquest.conf.example index 97c7575..21aa41b 100644 --- a/nginx/pyquest.conf.example +++ b/nginx/pyquest.conf.example @@ -3,6 +3,9 @@ # (SharedArrayBuffer). HTTPS obligatoire (service worker + isolation cross-origin). # Voir docs/design/01-pyodide-choice.md. +# Limite de débit de l'API de synchronisation (hors bloc server, contexte http) : 30 requêtes/min par IP. +limit_req_zone $binary_remote_addr zone=pyquest_sync:10m rate=30r/m; + server { listen 443 ssl http2; server_name pyquest.example.org; @@ -47,6 +50,8 @@ server { # API de synchronisation Django (optionnelle), sur le même domaine. location /api/ { + limit_req zone=pyquest_sync burst=20 nodelay; + client_max_body_size 300k; proxy_pass http://127.0.0.1:8001; proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; diff --git a/scripts/dev_server.py b/scripts/dev_server.py index 7fbf866..bad1f04 100644 --- a/scripts/dev_server.py +++ b/scripts/dev_server.py @@ -9,6 +9,8 @@ from __future__ import annotations import argparse import mimetypes import os +import urllib.error +import urllib.request from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from typing import Any @@ -22,7 +24,47 @@ mimetypes.add_type("application/manifest+json", ".webmanifest") mimetypes.add_type("application/wasm", ".wasm") +# Amont Django optionnel (--api-upstream) : /api/ est relayé comme le ferait nginx en production. +API_UPSTREAM: str | None = None +FORWARDED_HEADERS = ("Authorization", "Content-Type", "Accept", "Accept-Language") + + class DevHandler(SimpleHTTPRequestHandler): + def _proxy_api(self) -> None: + assert API_UPSTREAM is not None + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length) if length else None + headers = {name: value for name in FORWARDED_HEADERS if (value := self.headers.get(name))} + request = urllib.request.Request(API_UPSTREAM + self.path, data=body, headers=headers, method=self.command) + try: + with urllib.request.urlopen(request, timeout=10) as response: + status, payload, content_type = response.status, response.read(), response.headers.get("Content-Type") + except urllib.error.HTTPError as error: + status, payload, content_type = error.code, error.read(), error.headers.get("Content-Type") + except OSError: + status, payload, content_type = 502, b"Bad gateway", "text/plain" + self.send_response(status) + if content_type: + self.send_header("Content-Type", content_type) + self.send_header("Content-Length", str(len(payload))) + self.end_headers() + self.wfile.write(payload) + + def _is_api(self) -> bool: + return API_UPSTREAM is not None and self.path.startswith("/api/") + + def do_GET(self) -> None: + self._proxy_api() if self._is_api() else super().do_GET() + + def do_HEAD(self) -> None: + self._proxy_api() if self._is_api() else super().do_HEAD() + + def do_PUT(self) -> None: + self._proxy_api() if self._is_api() else self.send_error(405) + + def do_DELETE(self) -> None: + self._proxy_api() if self._is_api() else self.send_error(405) + def translate_path(self, path: str) -> str: clean = path.split("?", 1)[0].split("#", 1)[0] base, relative = APP_DIR, clean.lstrip("/") @@ -52,7 +94,10 @@ def main() -> None: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--port", type=int, default=8000) parser.add_argument("--host", default="127.0.0.1") + parser.add_argument("--api-upstream", help="URL d'un backend Django à relayer sur /api/ (ex. http://127.0.0.1:8001)") args = parser.parse_args() + global API_UPSTREAM + API_UPSTREAM = args.api_upstream.rstrip("/") if args.api_upstream else None server = ThreadingHTTPServer((args.host, args.port), DevHandler) print(f"PyQuest dev server: http://{args.host}:{args.port}/") server.serve_forever() diff --git a/tests/e2e/sync.test.mjs b/tests/e2e/sync.test.mjs new file mode 100644 index 0000000..50b2856 --- /dev/null +++ b/tests/e2e/sync.test.mjs @@ -0,0 +1,132 @@ +// Synchronisation entre appareils, de bout en bout : deux contextes Chromium indépendants, le vrai +// backend Django (base jetable) relayé sur /api/ par le serveur de dev, comme nginx en production. +import { spawn, spawnSync } from 'node:child_process'; +import { existsSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { after, before, test } from 'node:test'; +import assert from 'node:assert'; +import { chromium } from 'playwright-core'; + +const root = new URL('../../', import.meta.url).pathname; +const executablePath = process.env.CHROMIUM ?? '/usr/bin/chromium'; +const venvPython = `${root}.venv/bin/python`; +const [webPort, apiPort, staticPort] = [8131, 8132, 8133]; +const web = `http://127.0.0.1:${webPort}/`; +const staticOnly = `http://127.0.0.1:${staticPort}/`; +const skip = !existsSync(`${root}vendor/pyodide/pyodide.mjs`) + ? 'vendor/pyodide absent' + : !existsSync(executablePath) + ? `navigateur absent (${executablePath})` + : !existsSync(venvPython) + ? 'make install requis (Django)' + : false; + +const servers = []; +let browser; +let tmp; + +before(async () => { + if (skip) return; + tmp = mkdtempSync(join(tmpdir(), 'pyquest-sync-')); + const env = { ...process.env, DJANGO_SETTINGS_MODULE: 'pyquest_api.settings.dev', PYQUEST_DB_PATH: join(tmp, 'db.sqlite3'), PYQUEST_QUIET: '1' }; + const migrate = spawnSync(venvPython, ['manage.py', 'migrate', '--noinput'], { cwd: `${root}backend`, env, stdio: 'ignore' }); + assert.equal(migrate.status, 0, 'migrate'); + servers.push(spawn(venvPython, ['manage.py', 'runserver', String(apiPort), '--noreload'], { cwd: `${root}backend`, env, stdio: 'ignore' })); + servers.push(spawn('python3', [`${root}scripts/dev_server.py`, '--port', String(webPort), '--api-upstream', `http://127.0.0.1:${apiPort}`], { env, stdio: 'ignore' })); + servers.push(spawn('python3', [`${root}scripts/dev_server.py`, '--port', String(staticPort)], { env, stdio: 'ignore' })); + await new Promise((resolve) => setTimeout(resolve, 2500)); + browser = await chromium.launch({ executablePath, args: ['--no-sandbox'] }); +}); + +after(async () => { + await browser?.close(); + servers.forEach((server) => server.kill()); + if (tmp) rmSync(tmp, { recursive: true, force: true }); +}); + +const errors = []; +async function openDevice(url = web) { + const context = await browser.newContext(); + await context.grantPermissions(['clipboard-read', 'clipboard-write'], { origin: new URL(url).origin }).catch(() => {}); + const page = await context.newPage(); + page.on('pageerror', (error) => errors.push(error.message)); + await page.goto(url); + await page.waitForSelector('.explain', { timeout: 60000 }); + return page; +} + +const settings = (page) => page.locator('.settings .sync-group'); + +async function finishLevelZero(page) { + for (let i = 0; i < 5; i++) await page.locator('.notebook-action button').last().click(); + await page.waitForSelector('.toast'); +} + +async function doneCount(page) { + await page.locator('#levels-toggle').click(); + const count = await page.locator('.level-button.is-done').count(); + await page.keyboard.press('Escape'); + return count; +} + +test('synchronisation : activer sur A, lier B, recharger, effacer côté serveur', { skip, timeout: 180000 }, async () => { + // Appareil A : progression locale, puis activation. + const a = await openDevice(); + await finishLevelZero(a); + await a.locator('#settings-toggle').click(); + await settings(a).getByRole('button', { name: 'Activer la synchronisation' }).click(); + await settings(a).getByText(/Dernière synchronisation/).waitFor({ timeout: 15000 }); + const token = await settings(a).getByLabel('Ton jeton secret').inputValue(); + assert.match(token, /^[A-Za-z0-9_-]{43}$/); + + // Le focus clavier reste dans la section après le re-rendu. + assert.ok(await a.evaluate(() => document.activeElement?.closest('.sync-group') !== null)); + + // Un jeton invalide est refusé sans appel réseau ni changement d'état. + const b = await openDevice(); + assert.equal(await doneCount(b), 0); + await b.locator('#settings-toggle').click(); + await settings(b).getByLabel(/colle le jeton/).fill('trop-court'); + await settings(b).getByRole('button', { name: 'Lier cet appareil' }).click(); + await settings(b).getByText(/n'est pas valide/).waitFor(); + + // Appareil B : lien avec le vrai jeton → la progression de A apparaît. + await settings(b).getByLabel(/colle le jeton/).fill(token); + await settings(b).getByRole('button', { name: 'Lier cet appareil' }).click(); + await settings(b).getByText(/Appareil lié/).waitFor({ timeout: 15000 }); + await b.keyboard.press('Escape'); + assert.equal(await doneCount(b), 1, 'le niveau terminé sur A est visible sur B'); + + // B recharge la page : la synchronisation reste active (jeton conservé). + await b.reload(); + await b.waitForSelector('.explain', { timeout: 60000 }); + await b.locator('#settings-toggle').click(); + assert.equal(await settings(b).getByLabel('Ton jeton secret').inputValue(), token); + await b.keyboard.press('Escape'); + + // A efface ses données serveur ; un appareil C lié ensuite ne retrouve rien. + await settings(a).getByRole('button', { name: 'Désactiver et effacer les données du serveur' }).click(); + await settings(a).getByText(/données du serveur effacées/).waitFor({ timeout: 15000 }); + await settings(a).getByRole('button', { name: 'Activer la synchronisation' }).waitFor(); + + const c = await openDevice(); + await c.locator('#settings-toggle').click(); + await settings(c).getByLabel(/colle le jeton/).fill(token); + await settings(c).getByRole('button', { name: 'Lier cet appareil' }).click(); + await settings(c).getByText(/Appareil lié/).waitFor({ timeout: 15000 }); + await c.keyboard.press('Escape'); + assert.equal(await doneCount(c), 0, 'les données effacées du serveur ne reviennent pas'); + assert.deepEqual(errors, []); +}); + +test('synchronisation : sans backend, message clair et l\'application reste utilisable', { skip, timeout: 120000 }, async () => { + const page = await openDevice(staticOnly); + await page.locator('#settings-toggle').click(); + await settings(page).getByRole('button', { name: 'Activer la synchronisation' }).click(); + await settings(page).getByText(/Pas de serveur de synchronisation disponible/).waitFor({ timeout: 15000 }); + await page.keyboard.press('Escape'); + await finishLevelZero(page); + assert.equal(await doneCount(page), 1); + assert.deepEqual(errors, []); +}); diff --git a/tests/js/sync-client.test.mjs b/tests/js/sync-client.test.mjs new file mode 100644 index 0000000..72d073f --- /dev/null +++ b/tests/js/sync-client.test.mjs @@ -0,0 +1,179 @@ +// SyncClient contre un faux serveur en mémoire qui reproduit le contrat de l'API Django +// (GET 200/404 JSON, PUT avec concurrence optimiste 200/409, DELETE 204, 401). +import { test } from 'node:test'; +import assert from 'node:assert'; +import { SyncClient } from '../../app/js/core/SyncClient.js'; +import { ProgressStore } from '../../app/js/core/ProgressStore.js'; +import { MemoryKeyValueStore } from '../../app/js/core/KeyValueStores.js'; + +const day = (s) => new Date(`${s}T10:00:00`); +const json = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } }); + +class FakeServer { + profiles = new Map(); // token -> { payload, version } + calls = []; + offline = false; + onBeforePut = null; // pour simuler un autre appareil qui écrit entre le GET et le PUT + + fetch = async (url, options) => { + this.calls.push(options.method); + if (this.offline) throw new TypeError('network down'); + const token = (options.headers.Authorization ?? '').replace('Bearer ', ''); + if (!/^[A-Za-z0-9_-]{32,128}$/.test(token)) return json(401, { error: 'token' }); + const profile = this.profiles.get(token); + if (options.method === 'GET') { + return profile ? json(200, { payload: profile.payload, updated_at: `v${profile.version}` }) : json(404, { error: 'none' }); + } + if (options.method === 'DELETE') { + this.profiles.delete(token); + return new Response(null, { status: 204 }); + } + if (this.onBeforePut) { + const hook = this.onBeforePut; + this.onBeforePut = null; + hook(token); + } + const { payload, base } = JSON.parse(options.body); + const current = this.profiles.get(token); + if (current && base !== null && base !== `v${current.version}`) { + return json(409, { error: 'changed', payload: current.payload, updated_at: `v${current.version}` }); + } + this.profiles.set(token, { payload, version: (current?.version ?? 0) + 1 }); + return json(200, { updated_at: `v${this.profiles.get(token).version}` }); + }; +} + +async function device(server, { debounceMs = 5 } = {}) { + const progress = new ProgressStore(new MemoryKeyValueStore()); + await progress.load(); + const sync = new SyncClient({ store: new MemoryKeyValueStore(), progress, endpoint: '/api/sync/', fetchFn: server.fetch, debounceMs }); + await sync.load(); + return { progress, sync }; +} + +test('jeton : 43 caractères URL-safe, tous différents', () => { + const tokens = new Set(Array.from({ length: 50 }, () => SyncClient.generateToken())); + assert.equal(tokens.size, 50); + for (const token of tokens) assert.match(token, /^[A-Za-z0-9_-]{43}$/); + assert.ok(SyncClient.isValidToken([...tokens][0])); + assert.ok(!SyncClient.isValidToken('court')); + assert.ok(!SyncClient.isValidToken('a'.repeat(40) + '!')); +}); + +test('activer envoie la progression, un second appareil lié la récupère et les deux convergent', async () => { + const server = new FakeServer(); + const a = await device(server); + await a.progress.completeLevel('00-intro', 10, day('2026-10-14')); + assert.deepEqual(await a.sync.enable(), { ok: true }); + assert.equal(a.sync.state.status, 'idle'); + assert.ok(a.sync.state.lastSync); + + const b = await device(server); + await b.progress.completeLevel('01-hello', 20, day('2026-10-15')); + let merged = 0; + b.sync.addEventListener('merged', () => (merged += 1)); + assert.deepEqual(await b.sync.link(a.sync.state.token), { ok: true }); + assert.equal(merged, 1); + assert.deepEqual(Object.keys(b.progress.snapshot().completedLevels).sort(), ['00-intro', '01-hello']); + + await a.sync.sync(); + assert.deepEqual(Object.keys(a.progress.snapshot().completedLevels).sort(), ['00-intro', '01-hello']); + assert.equal(a.progress.snapshot().xp, 30); +}); + +test('un changement local est poussé automatiquement (debounce), sans boucle', async () => { + const server = new FakeServer(); + const a = await device(server); + await a.sync.enable(); + server.calls.length = 0; + await a.progress.completeLevel('00-intro', 10, day('2026-10-14')); + await a.progress.completeLevel('01-hello', 20, day('2026-10-14')); + await new Promise((resolve) => setTimeout(resolve, 100)); + assert.deepEqual(server.calls, ['GET', 'PUT'], 'un seul cycle pour deux changements rapprochés'); + const stored = [...server.profiles.values()][0].payload; + assert.equal(Object.keys(stored.completedLevels).length, 2); +}); + +test('conflit 409 : l\'écriture concurrente d\'un autre appareil est fusionnée, rien n\'est perdu', async () => { + const server = new FakeServer(); + const a = await device(server); + const b = await device(server); + await a.sync.enable(); + await b.sync.link(a.sync.state.token); + await a.progress.completeLevel('00-intro', 10, day('2026-10-14')); + await b.progress.completeLevel('05-decide', 40, day('2026-10-14')); + // B écrit entre le GET et le PUT de A. + server.onBeforePut = async (token) => { + const profile = server.profiles.get(token); + const merged = JSON.parse(b.progress.export()); + server.profiles.set(token, { payload: { ...merged, completedLevels: { ...profile.payload.completedLevels, ...merged.completedLevels } }, version: profile.version + 1 }); + }; + assert.deepEqual(await a.sync.sync(), { ok: true }); + assert.deepEqual(Object.keys(a.progress.snapshot().completedLevels).sort(), ['00-intro', '05-decide']); + const stored = [...server.profiles.values()][0].payload; + assert.deepEqual(Object.keys(stored.completedLevels).sort(), ['00-intro', '05-decide']); +}); + +test('hors ligne : état d\'erreur, aucune exception, et le cycle suivant réussit', async () => { + const server = new FakeServer(); + const a = await device(server); + await a.progress.completeLevel('00-intro', 10, day('2026-10-14')); + server.offline = true; + assert.deepEqual(await a.sync.enable(), { ok: false, code: 'offline' }); + assert.deepEqual([a.sync.state.status, a.sync.state.error], ['error', 'offline']); + server.offline = false; + assert.deepEqual(await a.sync.sync(), { ok: true }); + assert.equal(a.sync.state.error, null); + assert.equal([...server.profiles.values()].length, 1); +}); + +test('serveur sans API (404 non JSON) et réponses invalides : états explicites', async () => { + const a = await device({ fetch: async () => new Response('Not found', { status: 404, headers: { 'content-type': 'text/html' } }) }); + assert.deepEqual(await a.sync.enable(), { ok: false, code: 'unavailable' }); + + const hostile = await device({ fetch: async () => json(200, { payload: { version: 1, completedLevels: { x: { xp: 'a' } }, badges: {}, streak: {} }, updated_at: 'v1' }) }); + assert.deepEqual(await hostile.sync.enable(), { ok: false, code: 'invalid' }); + assert.equal(hostile.progress.snapshot().xp, 0); + + const refused = await device({ fetch: async () => json(401, { error: 'token' }) }); + assert.deepEqual(await refused.sync.enable(), { ok: false, code: 'unauthorized' }); +}); + +test('lier avec un jeton invalide lève une erreur ; l\'état reste désactivé', async () => { + const a = await device(new FakeServer()); + await assert.rejects(a.sync.link('trop-court')); + assert.equal(a.sync.state.enabled, false); + assert.deepEqual(await a.sync.sync(), { ok: false, code: 'disabled' }); +}); + +test('désactiver : local seul, ou avec effacement serveur ; échec d\'effacement = on reste actif', async () => { + const server = new FakeServer(); + const a = await device(server); + await a.sync.enable(); + const token = a.sync.state.token; + server.offline = true; + assert.deepEqual(await a.sync.disable({ eraseRemote: true }), { ok: false, code: 'offline' }); + assert.equal(a.sync.state.enabled, true); + server.offline = false; + assert.deepEqual(await a.sync.disable({ eraseRemote: true }), { ok: true }); + assert.equal(a.sync.state.enabled, false); + assert.equal(server.profiles.has(token), false); + + const b = await device(server); + await b.sync.enable(); + await b.sync.disable(); + assert.equal(server.profiles.size, 1, 'sans effacement, les données du serveur restent'); +}); + +test('le jeton survit au rechargement (magasin), pas la progression de la session précédente', async () => { + const server = new FakeServer(); + const kv = new MemoryKeyValueStore(); + const progress = new ProgressStore(new MemoryKeyValueStore()); + await progress.load(); + const first = new SyncClient({ store: kv, progress, endpoint: '/x', fetchFn: server.fetch }); + await first.enable(); + const second = new SyncClient({ store: kv, progress, endpoint: '/x', fetchFn: server.fetch }); + await second.load(); + assert.equal(second.state.token, first.state.token); + assert.equal(second.state.enabled, true); +});