From c29e7c639043ae0a2d32f4afc15e2ce9271c2bf9 Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Wed, 18 Nov 2026 01:11:32 +0100 Subject: [PATCH 01/10] =?UTF-8?q?Plan=20du=20lot=202=20c=C3=B4t=C3=A9=20se?= =?UTF-8?q?rveur=20et=20cryptographie?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- docs/plans/2026-11-18-lot-2-serveur.md | 76 ++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 docs/plans/2026-11-18-lot-2-serveur.md diff --git a/docs/plans/2026-11-18-lot-2-serveur.md b/docs/plans/2026-11-18-lot-2-serveur.md new file mode 100644 index 0000000..81ea908 --- /dev/null +++ b/docs/plans/2026-11-18-lot-2-serveur.md @@ -0,0 +1,76 @@ +# Lot 2 : serveur (relais, OAuth, MCP) et cryptographie + +- **Date** : 2026-11-18 +- **Lot** : 2a et 2c (sans l'interface) +- **Statut** : en cours +- **Exécutant** : sous-agent general-purpose (worktree isolé, branche `lot-2-serveur`) + +## Objectif + +Livrer la partie serveur et cryptographique du lot 2 (ADR 0005, points 2, 3, 5 et 6) : +la clé de synchro et ses dérivations, le relais chiffré, l'OAuth 2.1 sans état, le +serveur MCP, le module de synchro du navigateur, et la publication par un serveur +Node qui remplace Caddy. L'interface (page `/#/connecter-ia`, écran Synchro) est +écrite par ailleurs. + +## Consignes + +**Fichiers possédés** : `server/` (nouveau), `app/domain/sync-crypto.js`, +`app/infra/sync.js`, `tests/server/`, `tests/domain/sync-crypto.test.js`, `deploy/`, +`scripts/deploy.sh`, `tests/test_site.sh`, le `Makefile` (ajouts et adaptations), +`tsconfig.json`, `docs/deploiement.md`, `docs/mcp.md` (nouveau), ce plan. Ne pas +toucher `app/ui/`, `app/index.html`, `app/main.js`, `app/styles/` ni les autres +modules du domaine. + +1. **`app/domain/sync-crypto.js`** (navigateur et Node : `crypto.subtle`, + `TextEncoder` seulement) : + - `generateSyncKey()` : 128 bits aléatoires, en base32 Crockford par groupes de 4 ; + `normalizeSyncKey(text)` (espaces, tirets, minuscules, O/0, I/1, L/1) et + validation ; + - `deriveKeys(syncKey)` → `{journalId, authToken, encKey}` par HKDF-SHA-256, sel + `ia-fit`, info `ia-fit/id`, `ia-fit/auth`, `ia-fit/enc` ; + - `encryptEvent(encKey, event)` → texte (IV aléatoire 96 bits + chiffré, + base64url) ; `decryptEvent(encKey, blob)` → événement ou erreur claire. + - Tests : vecteurs déterministes, aller-retour, clé fausse refusée, + normalisation. +2. **`server/`**, Node sans dépendance : + - site statique avec exactement les en-têtes et types MIME du Caddyfile (CSP, + nosniff, no-referrer, no-cache, `text/markdown`, compression des textes) ; + - relais : `POST` et `GET /api/journals/:journalId/events`, empreinte SHA-256 de + l'authToken retenue au premier dépôt puis exigée (temps constant), un fichier + JSON Lines par journal dans `DATA_DIR`, écritures sérialisées par journal, + `fsync` ; aucun journal d'accès ; quotas (blob 64 Ko, journal 20 Mo, blobs par + requête, requêtes par IP en mémoire avec `x-real-ip` ou le dernier élément de + `x-forwarded-for`), effacement des journaux inactifs depuis 400 jours ; + - OAuth 2.1 sans état : métadonnées, enregistrement dynamique où le `client_id` + porte ses redirect_uris signées (HMAC, secret persistant `DATA_DIR/.server-secret`), + `GET /oauth/authorize` → `/#/connecter-ia?`, `POST /oauth/authorize` en + JSON (PKCE S256 obligatoire, clé vérifiée contre un journal existant), code et + jetons chiffrés par une clé serveur (code 5 min à usage unique, accès 1 h, + rafraîchissement 90 jours), `/oauth/token` ; la clé de synchro n'apparaît + jamais dans un journal ni une erreur ; + - MCP sur `/mcp` (JSON-RPC 2.0, protocole 2025-06-18, 401 avec + `WWW-Authenticate`) ; à chaque requête : jeton → clé → journal déchiffré → + `foldEvents` → réponse. Outils `get_overview`, `get_program`, + `get_training_history`, `get_exercise_progress`, `get_body_weight`, + `propose_program`, `propose_session_change`, `propose_profile` ; + - variables `PORT`, `DATA_DIR`, `SITE_DIR`, `PUBLIC_URL` ; refus de démarrer si + `DATA_DIR` n'est pas inscriptible. +3. **`app/infra/sync.js`** : `createSync({store, syncKey, baseUrl})` → + `{push, pull, sync}`, état gardé dans le magasin `meta` ; événements invalides + ignorés et comptés ; mode d'emploi pour l'interface. +4. **Publication** : image `node:24-alpine` (version précise), non root, port 3000, + `/data` ; `make serve` ; `tests/test_site.sh` adapté et étendu (relais, OAuth, + MCP de bout en bout) ; `tests/server/*.test.js` ; `docs/mcp.md` ; + `docs/deploiement.md` (réglages CapRover). Ne rien publier. + +## Critères de réussite + +- `make setup`, `make lint` et `make test` passent (dont `make test-site`). +- Le parcours de bout en bout (dépôt, lecture, OAuth PKCE, MCP, proposition qui + ajoute un bloc) passe contre l'image de production. +- Commits petits, en français ; rien de poussé. + +## Résultat + +(à compléter) From ff2b22f5fd094e91bef2249bbbf5212744ccc5ff Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Wed, 18 Nov 2026 01:14:44 +0100 Subject: [PATCH 02/10] =?UTF-8?q?Cl=C3=A9=20de=20synchro,=20d=C3=A9rivatio?= =?UTF-8?q?ns=20HKDF=20et=20chiffrement=20des=20=C3=A9v=C3=A9nements?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- app/domain/sync-crypto.js | 183 +++++++++++++++++++++++++++++++ tests/domain/sync-crypto.test.js | 77 +++++++++++++ 2 files changed, 260 insertions(+) create mode 100644 app/domain/sync-crypto.js create mode 100644 tests/domain/sync-crypto.test.js diff --git a/app/domain/sync-crypto.js b/app/domain/sync-crypto.js new file mode 100644 index 0000000..f7bc728 --- /dev/null +++ b/app/domain/sync-crypto.js @@ -0,0 +1,183 @@ +// Clé de synchro et chiffrement des événements (ADR 0005, points 2 et 3). +// Glossaire : docs/glossaire/cle-de-synchro.md, docs/glossaire/relais.md +// +// Module partagé par le navigateur et le serveur : il n'utilise que +// crypto.subtle, crypto.getRandomValues, TextEncoder et TextDecoder, présents +// dans les deux. +// +// FORMAT DURABLE (le changer rend illisibles les journaux déjà déposés) : +// - clé de synchro : 128 bits aléatoires, écrits en base32 Crockford +// (alphabet 0-9 A-Z sans I, L, O, U), bits de poids fort d'abord, complétés +// par deux bits nuls : 26 caractères, affichés par groupes de 4 séparés par +// des tirets (« K7Q2-…-XY ») ; +// - dérivations HKDF-SHA-256 à partir des 16 octets de la clé, sel « ia-fit » : +// - info « ia-fit/id » → 16 octets, identifiant du journal (base64url) ; +// - info « ia-fit/auth » → 32 octets, clé d'accès au relais (base64url) ; +// - info « ia-fit/enc » → clé AES-256-GCM ; +// - bloc chiffré : base64url( IV aléatoire de 12 octets ‖ chiffré AES-GCM du +// JSON de l'événement, étiquette de 16 octets comprise ). + +const ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; +const KEY_BYTES = 16; +const KEY_CHARS = 26; +const IV_BYTES = 12; +const TAG_BYTES = 16; + +/** Erreur de clé ou de bloc, au message lisible (jamais la clé elle-même). */ +export class SyncCryptoError extends Error { + /** @param {string} message */ + constructor(message) { + super(message); + this.name = "SyncCryptoError"; + } +} + +/** + * @typedef {object} SyncKeys + * @property {string} journalId identifiant du journal sur le relais (base64url, 22 caractères) + * @property {string} authToken clé d'accès au relais (base64url, 43 caractères) + * @property {CryptoKey} encKey clé AES-256-GCM des événements, non exportable + */ + +/** @param {Uint8Array} bytes */ +function toBase32(bytes) { + let bits = 0, value = 0, out = ""; + for (const b of bytes) { + value = (value << 8) | b; + bits += 8; + while (bits >= 5) { + out += ALPHABET[(value >>> (bits - 5)) & 31]; + bits -= 5; + } + value &= (1 << bits) - 1; + } + if (bits > 0) out += ALPHABET[(value << (5 - bits)) & 31]; + return out; +} + +/** @param {string} text 26 caractères de l'alphabet @returns {Uint8Array|null} */ +function fromBase32(text) { + const out = new Uint8Array(KEY_BYTES); + let bits = 0, value = 0, i = 0; + for (const c of text) { + const v = ALPHABET.indexOf(c); + if (v < 0) return null; + value = (value << 5) | v; + bits += 5; + if (bits >= 8) { + if (i < KEY_BYTES) out[i++] = (value >>> (bits - 8)) & 255; + bits -= 8; + } + value &= (1 << bits) - 1; + } + // Les deux bits de complément doivent être nuls : une faute de frappe sur le + // dernier caractère est ainsi souvent détectée. + return i === KEY_BYTES && value === 0 ? out : null; +} + +/** @param {string} raw 26 caractères */ +const group = (raw) => raw.match(/.{1,4}/g)?.join("-") ?? raw; + +/** Tire une nouvelle clé de synchro au hasard, au format affiché. */ +export function generateSyncKey() { + return group(toBase32(crypto.getRandomValues(new Uint8Array(KEY_BYTES)))); +} + +/** + * Remet une clé saisie à la main au format affiché : espaces et tirets ignorés, + * minuscules acceptées, O lu comme 0, I et L lus comme 1. + * @param {string} text + * @returns {string|null} la clé au format « XXXX-…-XX », ou null si elle est invalide + */ +export function normalizeSyncKey(text) { + if (typeof text !== "string") return null; + const raw = text.toUpperCase().replace(/[\s-]/g, "").replace(/O/g, "0").replace(/[IL]/g, "1"); + if (raw.length !== KEY_CHARS || !fromBase32(raw)) return null; + return group(raw); +} + +/** @param {string} text */ +export function isValidSyncKey(text) { + return normalizeSyncKey(text) !== null; +} + +/** @param {string} syncKey */ +function keyBytes(syncKey) { + const normalized = normalizeSyncKey(syncKey); + const bytes = normalized && fromBase32(normalized.replace(/-/g, "")); + if (!bytes) throw new SyncCryptoError("Clé de synchro invalide : 26 caractères attendus (chiffres et lettres, sans I, L, O ni U)."); + return bytes; +} + +const encoder = new TextEncoder(); +const SALT = encoder.encode("ia-fit"); + +/** + * Dérive l'identifiant du journal, la clé d'accès au relais et la clé de + * chiffrement. Déterministe : une même clé donne toujours les mêmes valeurs. + * @param {string} syncKey clé au format affiché ou saisie à la main + * @returns {Promise} + */ +export async function deriveKeys(syncKey) { + const master = await crypto.subtle.importKey("raw", keyBytes(syncKey), "HKDF", false, ["deriveBits", "deriveKey"]); + /** @param {string} info */ + const params = (info) => ({ name: "HKDF", hash: "SHA-256", salt: SALT, info: encoder.encode(info) }); + const id = await crypto.subtle.deriveBits(params("ia-fit/id"), master, 128); + const auth = await crypto.subtle.deriveBits(params("ia-fit/auth"), master, 256); + const encKey = await crypto.subtle.deriveKey(params("ia-fit/enc"), master, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]); + return { journalId: toBase64url(new Uint8Array(id)), authToken: toBase64url(new Uint8Array(auth)), encKey }; +} + +/** + * Chiffre un événement : un IV aléatoire par bloc (ADR 0005, point 3). + * @param {CryptoKey} encKey + * @param {unknown} event + * @returns {Promise} bloc base64url + */ +export async function encryptEvent(encKey, event) { + const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES)); + const sealed = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, encKey, encoder.encode(JSON.stringify(event)))); + const out = new Uint8Array(IV_BYTES + sealed.length); + out.set(iv); + out.set(sealed, IV_BYTES); + return toBase64url(out); +} + +/** + * Déchiffre un bloc. Lève une SyncCryptoError si le bloc est mal formé, ou s'il + * a été chiffré avec une autre clé (ou modifié). + * @param {CryptoKey} encKey + * @param {string} blob + * @returns {Promise} l'événement, à valider par l'appelant (validateEvent) + */ +export async function decryptEvent(encKey, blob) { + const bytes = typeof blob === "string" ? fromBase64url(blob) : null; + if (!bytes || bytes.length < IV_BYTES + TAG_BYTES) throw new SyncCryptoError("Bloc chiffré mal formé."); + let plain; + try { + plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.subarray(0, IV_BYTES) }, encKey, bytes.subarray(IV_BYTES)); + } catch { + throw new SyncCryptoError("Bloc chiffré illisible : autre clé de synchro, ou bloc altéré."); + } + try { + return JSON.parse(new TextDecoder().decode(plain)); + } catch { + throw new SyncCryptoError("Bloc déchiffré, mais son contenu n'est pas du JSON."); + } +} + +/** @param {Uint8Array} bytes */ +export function toBase64url(bytes) { + let binary = ""; + for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000)); + return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +} + +/** @param {string} text @returns {Uint8Array|null} */ +export function fromBase64url(text) { + if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return null; + const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (text.length % 4)) % 4)); + const out = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i); + return out; +} diff --git a/tests/domain/sync-crypto.test.js b/tests/domain/sync-crypto.test.js new file mode 100644 index 0000000..a2d16d4 --- /dev/null +++ b/tests/domain/sync-crypto.test.js @@ -0,0 +1,77 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { hkdfSync } from "node:crypto"; +import { + generateSyncKey, normalizeSyncKey, isValidSyncKey, deriveKeys, encryptEvent, decryptEvent, + SyncCryptoError, fromBase64url, +} from "../../app/domain/sync-crypto.js"; + +// Clé dont les 16 octets valent 0, 1, …, 15. +const KEY = "000G-40R4-0M30-E209-185G-R38E-1W"; +const BYTES = Uint8Array.from({ length: 16 }, (_, i) => i); + +test("une clé tirée au hasard : 26 caractères Crockford par groupes de 4, et toujours différente", () => { + const a = generateSyncKey(); + assert.match(a, /^([0-9A-HJKMNP-TV-Z]{4}-){6}[0-9A-HJKMNP-TV-Z]{2}$/); + assert.equal(normalizeSyncKey(a), a); + assert.notEqual(generateSyncKey(), a); +}); + +test("normalisation : espaces, tirets, minuscules et lettres ambiguës", () => { + assert.equal(normalizeSyncKey("000g 40r4 0m30 e209 185g r38e 1w"), KEY); + assert.equal(normalizeSyncKey("OOOG40R4OM3OE2O9185GR38EIW"), KEY); + assert.equal(normalizeSyncKey(" ooog-40r4-om3o-e2o9-l85g-r38e-lw "), KEY); + assert.equal(normalizeSyncKey(KEY.replace(/-/g, "")), KEY); +}); + +test("validation : longueur, alphabet et bits de complément", () => { + assert.equal(normalizeSyncKey(KEY.slice(0, -1)), null, "trop courte"); + assert.equal(normalizeSyncKey(KEY + "0"), null, "trop longue"); + assert.equal(normalizeSyncKey(KEY.replace("G", "U")), null, "U hors de l'alphabet"); + assert.equal(normalizeSyncKey(KEY.slice(0, -1) + "X"), null, "bits de complément non nuls"); + assert.equal(normalizeSyncKey(/** @type {any} */ (42)), null); + assert.equal(isValidSyncKey(KEY), true); + assert.equal(isValidSyncKey("bonjour"), false); +}); + +test("dérivations : vecteurs fixes, conformes à HKDF-SHA-256 (sel ia-fit)", async () => { + const k = await deriveKeys(KEY); + assert.equal(k.journalId, "ZgJsF_SV8W3E27y5p0AhMg"); + assert.equal(k.authToken, "_NaCNrXbQlORkPj77TOhUThrbXoF740wNVYw9Djg8Z0"); + // Recalcul indépendant avec l'implémentation de Node. + const hkdf = (/** @type {string} */ info, /** @type {number} */ n) => + Buffer.from(hkdfSync("sha256", BYTES, "ia-fit", info, n)).toString("base64url"); + assert.equal(k.journalId, hkdf("ia-fit/id", 16)); + assert.equal(k.authToken, hkdf("ia-fit/auth", 32)); + assert.equal(k.encKey.algorithm.name, "AES-GCM"); + assert.equal(k.encKey.extractable, false); + // Même clé, saisie autrement : mêmes dérivations. + const again = await deriveKeys(KEY.toLowerCase().replace(/-/g, " ")); + assert.equal(again.journalId, k.journalId); + assert.equal(again.authToken, k.authToken); +}); + +test("une clé invalide est refusée sans être recopiée dans le message", async () => { + await assert.rejects(deriveKeys("ABCD-EFGH-SECRET"), (err) => { + assert.ok(err instanceof SyncCryptoError); + assert.doesNotMatch(String(err.message), /SECRET|ABCD/); + return true; + }); +}); + +test("chiffrement : aller-retour, IV aléatoire, autre clé refusée, bloc altéré refusé", async () => { + const { encKey } = await deriveKeys(KEY); + const event = { id: "e1", at: "2026-11-18T10:00:00.000Z", device: "pc", v: 1, type: "WeightRecorded", data: { date: "2026-11-18", kg: 80.5 } }; + const blob = await encryptEvent(encKey, event); + assert.match(blob, /^[A-Za-z0-9_-]+$/); + assert.equal(fromBase64url(blob)?.length, 12 + JSON.stringify(event).length + 16); + assert.deepEqual(await decryptEvent(encKey, blob), event); + assert.notEqual(await encryptEvent(encKey, event), blob, "deux chiffrements diffèrent (IV aléatoire)"); + + const other = await deriveKeys(generateSyncKey()); + await assert.rejects(decryptEvent(other.encKey, blob), /autre clé de synchro/); + const flipped = blob.slice(0, 20) + (blob[20] === "A" ? "B" : "A") + blob.slice(21); + await assert.rejects(decryptEvent(encKey, flipped), SyncCryptoError); + await assert.rejects(decryptEvent(encKey, "court"), /mal formé/); + await assert.rejects(decryptEvent(encKey, "pas du base64 !"), /mal formé/); +}); From 508bab9a8ebbc8db331a7b5b605dbe2ec4d91d44 Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Wed, 18 Nov 2026 05:07:21 +0100 Subject: [PATCH 03/10] =?UTF-8?q?Serveur=20Node=20:=20site=20statique,=20r?= =?UTF-8?q?elais=20chiffr=C3=A9,=20OAuth=20sans=20=C3=A9tat,=20MCP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- server/app.js | 241 +++++++++++++++++++++++++++++++++ server/http.js | 118 ++++++++++++++++ server/main.js | 55 ++++++++ server/mcp.js | 313 +++++++++++++++++++++++++++++++++++++++++++ server/oauth.js | 305 +++++++++++++++++++++++++++++++++++++++++ server/rate-limit.js | 49 +++++++ server/relay.js | 259 +++++++++++++++++++++++++++++++++++ server/static.js | 140 +++++++++++++++++++ 8 files changed, 1480 insertions(+) create mode 100644 server/app.js create mode 100644 server/http.js create mode 100644 server/main.js create mode 100644 server/mcp.js create mode 100644 server/oauth.js create mode 100644 server/rate-limit.js create mode 100644 server/relay.js create mode 100644 server/static.js diff --git a/server/app.js b/server/app.js new file mode 100644 index 0000000..cb55d90 --- /dev/null +++ b/server/app.js @@ -0,0 +1,241 @@ +// Routage du serveur d'IA-Fit : site statique, relais, OAuth et MCP sur la même +// origine (ADR 0005). Aucun journal d'accès : ni adresse IP, ni identifiant de +// journal, ni jeton ne sont écrits nulle part. + +import { createStaticHandler } from "./static.js"; +import { createRelay } from "./relay.js"; +import { createOAuth, loadServerSecret, OAuthError } from "./oauth.js"; +import { createMcp } from "./mcp.js"; +import { clientIp, createRateLimiter } from "./rate-limit.js"; +import { HttpError, bearer, readBody, readJson, sendJson, sendText, BodyTooLarge, SECURITY_HEADERS } from "./http.js"; +import { deriveKeys, normalizeSyncKey } from "../app/domain/sync-crypto.js"; + +/** Corps maximal d'un dépôt sur le relais. */ +const RELAY_BODY_BYTES = 4 * 1024 * 1024; +const SMALL_BODY_BYTES = 64 * 1024; +const MCP_BODY_BYTES = 1024 * 1024; + +const CORS = { + "access-control-allow-origin": "*", + "access-control-allow-methods": "GET, POST, OPTIONS", + "access-control-allow-headers": "authorization, content-type, mcp-protocol-version, mcp-session-id", + "access-control-expose-headers": "www-authenticate, mcp-protocol-version", + "access-control-max-age": "86400", +}; + +/** + * @typedef {object} AppOptions + * @property {string} dataDir + * @property {string} siteDir + * @property {string} publicUrl adresse publique, sans « / » final + * @property {() => number} [now] + * @property {Partial} [limits] + * @property {{max: number, windowMs: number}} [rate] toutes les routes dynamiques + * @property {{max: number, windowMs: number}} [authorizeRate] POST /oauth/authorize + */ + +/** @param {AppOptions} options */ +export function createApp(options) { + const now = options.now ?? Date.now; + const publicUrl = options.publicUrl.replace(/\/+$/, ""); + const relay = createRelay(options.dataDir, { limits: options.limits, now }); + const oauth = createOAuth({ secret: loadServerSecret(options.dataDir), now }); + const mcp = createMcp({ relay, publicUrl, now: () => new Date(now()) }); + const serveStatic = createStaticHandler(options.siteDir); + const limiter = createRateLimiter({ ...(options.rate ?? { max: 300, windowMs: 60e3 }), now }); + const authorizeLimiter = createRateLimiter({ ...(options.authorizeRate ?? { max: 20, windowMs: 60e3 }), now }); + const resourceMetadata = `${publicUrl}/.well-known/oauth-protected-resource/mcp`; + + /** + * @param {import("node:http").IncomingMessage} req + * @param {import("node:http").ServerResponse} res + */ + async function route(req, res) { + const url = new URL(req.url ?? "/", "http://localhost"); + const p = url.pathname; + const dynamic = p.startsWith("/api/") || p.startsWith("/oauth/") || p === "/mcp" || p.startsWith("/.well-known/"); + if (!dynamic) return serveStatic(req, res, p); + + const ip = clientIp(req); + const wait = limiter.hit(ip); + if (wait) throw new HttpError(429, "rate_limited", `Trop de requêtes : réessaie dans ${wait} s.`); + if (req.method === "OPTIONS") return sendJson(res, 204, undefined, CORS); + + if (p === "/.well-known/oauth-protected-resource" || p === "/.well-known/oauth-protected-resource/mcp") + return sendJson(res, 200, { + resource: `${publicUrl}/mcp`, + authorization_servers: [publicUrl], + bearer_methods_supported: ["header"], + scopes_supported: ["ia-fit"], + resource_name: "IA-Fit", + resource_documentation: `${publicUrl}/ia.md`, + }, CORS); + if (p === "/.well-known/oauth-authorization-server" || p === "/.well-known/oauth-authorization-server/mcp") + return sendJson(res, 200, { + issuer: publicUrl, + authorization_endpoint: `${publicUrl}/oauth/authorize`, + token_endpoint: `${publicUrl}/oauth/token`, + registration_endpoint: `${publicUrl}/oauth/register`, + response_types_supported: ["code"], + grant_types_supported: ["authorization_code", "refresh_token"], + code_challenge_methods_supported: ["S256"], + token_endpoint_auth_methods_supported: ["none"], + scopes_supported: ["ia-fit"], + }, CORS); + + if (p === "/oauth/register") { + if (req.method !== "POST") throw new HttpError(405, "method_not_allowed"); + return sendJson(res, 201, oauth.register(await readJson(req, SMALL_BODY_BYTES)), CORS); + } + + if (p === "/oauth/authorize") { + if (req.method === "GET") return authorizeGet(url, res); + if (req.method === "POST") { + const wait2 = authorizeLimiter.hit(ip); + if (wait2) throw new HttpError(429, "rate_limited", `Trop de tentatives : réessaie dans ${wait2} s.`); + return authorizePost(await readJson(req, SMALL_BODY_BYTES), res); + } + throw new HttpError(405, "method_not_allowed"); + } + + if (p === "/oauth/token") { + if (req.method !== "POST") throw new HttpError(405, "method_not_allowed"); + return sendJson(res, 200, oauth.token(await readForm(req)), CORS); + } + + if (p === "/mcp") return handleMcp(req, res); + + const m = /^\/api\/journals\/([^/]+)\/events$/.exec(p); + if (m) { + const id = m[1]; + const token = bearer(req); + if (req.method === "GET") { + const after = Number(url.searchParams.get("after") ?? 0); + if (!Number.isInteger(after) || after < 0) throw new HttpError(400, "invalid_request", "'after' doit être un entier positif."); + return sendJson(res, 200, await relay.read(id, token, after)); + } + if (req.method === "POST") { + // La clé d'accès est vérifiée avant de lire un gros corps. + if (!token) throw new HttpError(401, "unauthorized", "Clé d'accès manquante."); + const body = await readJson(req, RELAY_BODY_BYTES); + return sendJson(res, 200, await relay.append(id, token, body)); + } + throw new HttpError(405, "method_not_allowed"); + } + throw new HttpError(404, "not_found", "Adresse inconnue."); + } + + /** + * Première étape de l'autorisation : on vérifie le client, puis on passe la + * main à la page de l'app, qui retrouve la clé de synchro du navigateur. + * @param {URL} url + * @param {import("node:http").ServerResponse} res + */ + function authorizeGet(url, res) { + const params = Object.fromEntries(url.searchParams); + let request; + try { + request = oauth.checkAuthorization(params); + } catch (e) { + if (e instanceof OAuthError && e.redirect && typeof params.redirect_uri === "string") { + res.writeHead(302, { ...SECURITY_HEADERS, "cache-control": "no-store", + location: oauth.redirectTo(params.redirect_uri, { error: e.error, error_description: e.message, state: params.state ?? null }) }); + return res.end(); + } + if (e instanceof OAuthError) return sendText(res, 400, `Autorisation impossible : ${e.message}`); + throw e; + } + const forward = new URLSearchParams(url.searchParams); + forward.set("client_name", request.client.name); + res.writeHead(302, { ...SECURITY_HEADERS, "cache-control": "no-store", location: `/#/connecter-ia?${forward}` }); + res.end(); + } + + /** + * Seconde étape, appelée par la page de l'app avec la clé de synchro. + * @param {any} body + * @param {import("node:http").ServerResponse} res + */ + async function authorizePost(body, res) { + if (typeof body !== "object" || body === null) throw new OAuthError("invalid_request", "Corps JSON attendu."); + const request = oauth.checkAuthorization(body); + const syncKey = normalizeSyncKey(body.sync_key); + if (!syncKey) throw new OAuthError("invalid_sync_key", "Clé de synchro invalide."); + const keys = await deriveKeys(syncKey); + if (!(await relay.owns(keys.journalId, keys.authToken))) + throw new OAuthError("unknown_journal", "Aucun journal synchronisé pour cette clé : active d'abord la synchro dans l'app."); + return sendJson(res, 200, { redirect: oauth.authorize(request, body.client_id, syncKey) }); + } + + /** + * @param {import("node:http").IncomingMessage} req + * @param {import("node:http").ServerResponse} res + */ + async function handleMcp(req, res) { + const token = bearer(req); + const syncKey = token ? oauth.verifyAccess(token) : null; + if (!syncKey) { + const challenge = `Bearer resource_metadata="${resourceMetadata}"` + (token ? `, error="invalid_token"` : ""); + return sendJson(res, 401, { error: token ? "invalid_token" : "unauthorized" }, { ...CORS, "www-authenticate": challenge }); + } + if (req.method !== "POST") return sendJson(res, 405, { error: "method_not_allowed" }, { ...CORS, allow: "POST" }); + let msg; + try { + msg = JSON.parse(await readBody(req, MCP_BODY_BYTES)); + } catch (e) { + if (e instanceof BodyTooLarge) throw new HttpError(413, "payload_too_large"); + return sendJson(res, 400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "JSON invalide." } }, CORS); + } + if (Array.isArray(msg)) { + const out = []; + for (const m of msg) { + const r = await mcp.handle(m, syncKey); + if (r) out.push(r); + } + return out.length ? sendJson(res, 200, out, CORS) : sendJson(res, 202, undefined, CORS); + } + const r = await mcp.handle(msg, syncKey); + return r ? sendJson(res, 200, r, CORS) : sendJson(res, 202, undefined, CORS); + } + + /** + * Corps d'une requête /oauth/token : formulaire (la norme) ou JSON. + * @param {import("node:http").IncomingMessage} req + * @returns {Promise>} + */ + async function readForm(req) { + if ((req.headers["content-type"] ?? "").includes("application/json")) { + const body = await readJson(req, SMALL_BODY_BYTES); + return typeof body === "object" && body !== null ? body : {}; + } + let text; + try { + text = await readBody(req, SMALL_BODY_BYTES); + } catch (e) { + if (e instanceof BodyTooLarge) throw new HttpError(413, "payload_too_large"); + throw e; + } + return Object.fromEntries(new URLSearchParams(text)); + } + + /** + * @param {import("node:http").IncomingMessage} req + * @param {import("node:http").ServerResponse} res + */ + async function handler(req, res) { + try { + await route(req, res); + } catch (e) { + if (res.headersSent) return res.destroy(); + if (e instanceof HttpError) { + const cors = req.url?.startsWith("/oauth/") || req.url?.startsWith("/mcp") ? CORS : {}; + return sendJson(res, e.status, { error: e.error, ...(e.description ? { error_description: e.description } : {}) }, cors); + } + // Message seul : ni adresse, ni requête, ni jeton. + console.error("Erreur interne :", e instanceof Error ? e.message : e); + sendJson(res, 500, { error: "server_error" }); + } + } + + return { handler, relay, oauth, mcp }; +} diff --git a/server/http.js b/server/http.js new file mode 100644 index 0000000..1796ddc --- /dev/null +++ b/server/http.js @@ -0,0 +1,118 @@ +// Petits outils HTTP partagés par les routes du serveur. + +/** En-têtes de sécurité de toutes les réponses, repris du Caddyfile du lot 1. */ +export const CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; worker-src 'self'; manifest-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'"; + +export const SECURITY_HEADERS = { + "x-content-type-options": "nosniff", + "referrer-policy": "no-referrer", + "content-security-policy": CSP, +}; + +/** Corps trop gros : le client reçoit 413. */ +export class BodyTooLarge extends Error {} + +/** Erreur à renvoyer telle quelle au client (code HTTP, corps JSON). */ +export class HttpError extends Error { + /** @param {number} status @param {string} error @param {string} [description] */ + constructor(status, error, description) { + super(description ?? error); + this.status = status; + this.error = error; + this.description = description; + } +} + +/** + * Lit le corps d'une requête, en refusant au-delà de `limit` octets. + * @param {import("node:http").IncomingMessage} req + * @param {number} limit + * @returns {Promise} + */ +export function readBody(req, limit) { + return new Promise((resolve, reject) => { + const declared = Number(req.headers["content-length"]); + if (declared > limit) { + req.resume(); + return reject(new BodyTooLarge()); + } + /** @type {Buffer[]} */ + const chunks = []; + let size = 0; + let failed = false; + req.on("data", (/** @type {Buffer} */ chunk) => { + if (failed) return; + size += chunk.length; + if (size > limit) { + failed = true; + reject(new BodyTooLarge()); + return; + } + chunks.push(chunk); + }); + req.on("end", () => failed || resolve(Buffer.concat(chunks).toString("utf8"))); + req.on("error", reject); + }); +} + +/** + * Lit un corps JSON ; lève une HttpError 400 s'il est illisible. + * @param {import("node:http").IncomingMessage} req + * @param {number} limit + * @returns {Promise} + */ +export async function readJson(req, limit) { + let text; + try { + text = await readBody(req, limit); + } catch (e) { + if (e instanceof BodyTooLarge) throw new HttpError(413, "payload_too_large", "Requête trop volumineuse."); + throw e; + } + try { + return JSON.parse(text || "null"); + } catch { + throw new HttpError(400, "invalid_request", "Corps JSON illisible."); + } +} + +/** + * Envoie une réponse JSON (ou vide pour 202 et 204), jamais mise en cache. + * @param {import("node:http").ServerResponse} res + * @param {number} status + * @param {unknown} body + * @param {Record} [headers] + */ +export function sendJson(res, status, body, headers = {}) { + const text = body === undefined ? "" : JSON.stringify(body); + res.writeHead(status, { + ...SECURITY_HEADERS, + "cache-control": "no-store", + ...(text ? { "content-type": "application/json; charset=utf-8", "content-length": Buffer.byteLength(text) } : {}), + ...headers, + }); + res.end(text); +} + +/** + * @param {import("node:http").ServerResponse} res + * @param {number} status + * @param {string} text + * @param {Record} [headers] + */ +export function sendText(res, status, text, headers = {}) { + res.writeHead(status, { + ...SECURITY_HEADERS, + "cache-control": "no-store", + "content-type": "text/plain; charset=utf-8", + "content-length": Buffer.byteLength(text), + ...headers, + }); + res.end(text); +} + +/** Jeton porteur de l'en-tête Authorization, ou "" s'il n'y en a pas. @param {import("node:http").IncomingMessage} req */ +export function bearer(req) { + const m = /^Bearer\s+(\S+)\s*$/i.exec(req.headers.authorization ?? ""); + return m ? m[1] : ""; +} diff --git a/server/main.js b/server/main.js new file mode 100644 index 0000000..4eb8a79 --- /dev/null +++ b/server/main.js @@ -0,0 +1,55 @@ +#!/usr/bin/env node +// Point d'entrée du serveur d'IA-Fit (lot 2, ADR 0005 et 0007) : Node seul, +// sans dépendance. +// +// Variables : +// PORT port d'écoute (3000) +// DATA_DIR journaux chiffrés et secret du serveur (/data en production) +// SITE_DIR site assemblé par make site (/srv/site en production) +// PUBLIC_URL adresse publique (https://ia-fit.sans.pub), pour OAuth et MCP + +import http from "node:http"; +import fs from "node:fs"; +import path from "node:path"; +import { createApp } from "./app.js"; + +const PORT = Number(process.env.PORT ?? 3000); +const DATA_DIR = path.resolve(process.env.DATA_DIR ?? "data"); +const SITE_DIR = path.resolve(process.env.SITE_DIR ?? "build/site"); +const PUBLIC_URL = (process.env.PUBLIC_URL ?? "https://ia-fit.sans.pub").replace(/\/+$/, ""); + +/** @param {string} message */ +function fail(message) { + console.error("IA-Fit ne démarre pas : " + message); + process.exit(1); +} + +// Refus de démarrer sans dossier de données inscriptible : sinon le premier +// dépôt échouerait, et le secret OAuth ne pourrait pas être gardé. +try { + fs.mkdirSync(DATA_DIR, { recursive: true }); + const probe = path.join(DATA_DIR, `.ecriture-${process.pid}`); + fs.writeFileSync(probe, ""); + fs.unlinkSync(probe); +} catch (e) { + fail(`DATA_DIR (${DATA_DIR}) n'est pas inscriptible : ${e instanceof Error ? e.message : e}`); +} +if (!fs.existsSync(path.join(SITE_DIR, "index.html"))) fail(`SITE_DIR (${SITE_DIR}) ne contient pas index.html (make site).`); +if (!/^https?:\/\/[^/]+$/.test(PUBLIC_URL)) fail(`PUBLIC_URL (${PUBLIC_URL}) doit être de la forme https://domaine, sans chemin.`); + +const app = createApp({ dataDir: DATA_DIR, siteDir: SITE_DIR, publicUrl: PUBLIC_URL }); +const server = http.createServer(app.handler); +server.headersTimeout = 20e3; +server.requestTimeout = 60e3; + +// Effacement des journaux inactifs : au démarrage, puis chaque jour. +const purge = () => app.relay.purgeInactive() + .then((n) => n && console.log(`Journaux inactifs effacés : ${n}`)) + .catch((e) => console.error("Effacement des journaux inactifs :", e instanceof Error ? e.message : e)); +purge(); +setInterval(purge, 864e5).unref(); + +server.listen(PORT, () => console.log(`IA-Fit : port ${PORT}, site ${SITE_DIR}, données ${DATA_DIR}, adresse ${PUBLIC_URL}`)); + +for (const signal of /** @type {const} */ (["SIGTERM", "SIGINT"])) + process.on(signal, () => server.close(() => process.exit(0))); diff --git a/server/mcp.js b/server/mcp.js new file mode 100644 index 0000000..00d2b38 --- /dev/null +++ b/server/mcp.js @@ -0,0 +1,313 @@ +// Serveur MCP (ADR 0005, points 5 et 6) : JSON-RPC 2.0 sur HTTP POST. +// +// À chaque appel d'outil : la clé de synchro (tirée du jeton) donne les clés du +// journal ; on lit et déchiffre tous ses blocs en mémoire, on replie l'état avec +// le même code que l'app (foldEvents), on répond, puis tout est oublié. Les +// outils qui modifient n'écrivent qu'une proposition (ProgramProposed, source +// « ai »), que l'utilisateur adopte ou refuse dans l'app. + +import { createEvent, validateEvent } from "../app/domain/events.js"; +import { foldEvents } from "../app/domain/state.js"; +import { validateProgram } from "../app/domain/program.js"; +import { validateProfile } from "../app/domain/profile.js"; +import { exerciseHistory, attendance } from "../app/domain/analysis.js"; +import { weightTrend, weightMilestones } from "../app/domain/weight.js"; +import { addDays, localISO } from "../app/domain/dates.js"; +import { deriveKeys, decryptEvent, encryptEvent } from "../app/domain/sync-crypto.js"; + +/** Versions du protocole comprises ; la première est celle d'Atelier. */ +export const PROTOCOL_VERSIONS = ["2025-06-18", "2025-03-26"]; + +export const PROPOSAL_SAVED = "Proposition enregistrée : l'utilisateur la validera dans l'app."; + +/** Erreur d'outil : renvoyée à l'IA comme résultat en erreur, pour qu'elle corrige. */ +class ToolError extends Error { + /** @param {string} message @param {string[]} [problems] */ + constructor(message, problems = []) { + super(problems.length ? message + "\n- " + problems.join("\n- ") : message); + } +} + +/** @param {string} publicUrl */ +function instructions(publicUrl) { + return `IA-Fit suit le programme de musculation de l'utilisateur. Commence toujours par get_overview : programme, profil (objectif, matériel, contraintes de sécurité à respecter absolument), mode, propositions en attente et assiduité. Tu ne modifies jamais rien directement : propose_program, propose_session_change et propose_profile enregistrent une proposition, avec ta raison, que l'utilisateur voit avec un aperçu des changements et valide (ou refuse) dans l'app. Explique-lui ce que tu proposes avant de l'enregistrer. Le format du programme et du profil, ses règles et la bibliothèque d'exercices (champ 'ref') sont décrits dans ${publicUrl}/ia.md : lis-le avant ta première proposition. Une proposition invalide est refusée avec la liste des problèmes : corrige-les et recommence.`; +} + +const DAYS = { type: "integer", minimum: 1, maximum: 3650 }; + +const TOOLS = [ + { + name: "get_overview", + description: "Vue d'ensemble, à lire en premier : programme courant (séances et exercices), profil (objectif, matériel, contraintes de sécurité), mode (progression, maintien, récupération), propositions en attente de validation, assiduité des 4 dernières semaines, dernière séance et dernière pesée.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + }, + { + name: "get_program", + description: "Programme courant complet (JSON au format IA-Fit, celui à reprendre pour une proposition), avec les charges de travail actuelles par clé « séance-exercice » et l'historique des versions du programme.", + inputSchema: { type: "object", properties: {}, additionalProperties: false }, + }, + { + name: "get_training_history", + description: "Séances réellement faites sur les derniers jours (28 par défaut) : date, séance, exercices, charge, répétitions et ressenti de chaque série (easy, ok, hard, failure), ainsi que les jours prévus marqués non faits.", + inputSchema: { type: "object", properties: { days: { ...DAYS, description: "Nombre de jours en arrière (28 par défaut)." } }, additionalProperties: false }, + }, + { + name: "get_exercise_progress", + description: "Évolution d'un exercice, séance après séance : charge, durée, séries, meilleure série, répétitions totales, volume et ressenti dominant. exercise_id est la 'ref' de l'exercice dans le programme (par exemple « squat »), ou son nom s'il n'a pas de ref.", + inputSchema: { type: "object", properties: { exercise_id: { type: "string", description: "ref de l'exercice, sinon son nom." } }, required: ["exercise_id"], additionalProperties: false }, + }, + { + name: "get_body_weight", + description: "Pesées des derniers jours (90 par défaut), tendance en kg par semaine sur les 8 dernières semaines mesurées et repères (minimum, dernière fois sous le poids actuel).", + inputSchema: { type: "object", properties: { days: { ...DAYS, description: "Nombre de jours en arrière (90 par défaut)." } }, additionalProperties: false }, + }, + { + name: "propose_program", + description: "Propose un nouveau programme complet (et, si besoin, un nouveau profil complet). Rien n'est appliqué : l'utilisateur voit l'aperçu des changements et valide dans l'app. Format : voir ia.md. Refusé avec la liste des problèmes si le programme ou le profil est invalide.", + inputSchema: { + type: "object", + properties: { + program: { type: "object", description: "Programme complet au format IA-Fit : {name, sessions: [{key, name, exercises: [{ref|name, sets, reps, rest, …}]}], activities?, cardio?, rules?}." }, + profile: { type: "object", description: "Profil complet, facultatif : {goal, context, equipment[], constraints[], heightCm, sessionMinutes}." }, + reason: { type: "string", description: "Pourquoi ce changement, en une ou deux phrases adressées à l'utilisateur." }, + }, + required: ["program", "reason"], + additionalProperties: false, + }, + }, + { + name: "propose_session_change", + description: "Propose de remplacer une séance du programme courant (ou d'en ajouter une si la clé n'existe pas), le reste du programme étant gardé tel quel. Rien n'est appliqué sans la validation de l'utilisateur.", + inputSchema: { + type: "object", + properties: { + key: { type: "string", description: "Clé de la séance (« A », « B »…)." }, + session: { type: "object", description: "Séance complète : {key?, name, subtitle?, exercises: [...]} ; sa clé, si elle est donnée, doit être 'key'." }, + reason: { type: "string", description: "Pourquoi ce changement." }, + }, + required: ["key", "session", "reason"], + additionalProperties: false, + }, + }, + { + name: "propose_profile", + description: "Propose un nouveau profil complet (objectif, contexte, matériel, contraintes, taille, durée de séance), le programme courant restant le même. Rien n'est appliqué sans la validation de l'utilisateur.", + inputSchema: { + type: "object", + properties: { + profile: { type: "object", description: "Profil complet : {goal, context, equipment[], constraints[], heightCm, sessionMinutes}." }, + reason: { type: "string", description: "Pourquoi ce changement." }, + }, + required: ["profile", "reason"], + additionalProperties: false, + }, + }, +]; + +/** + * @param {{relay: import("./relay.js").Relay, publicUrl: string, now?: () => Date}} options + */ +export function createMcp({ relay, publicUrl, now = () => new Date() }) { + /** + * Ouvre le journal en mémoire, le temps d'une requête. + * @param {string} syncKey + */ + async function openJournal(syncKey) { + const keys = await deriveKeys(syncKey); + /** @type {import("../app/domain/events.js").DomainEvent[]} */ + const events = []; + let unreadable = 0; + let after = 0; + for (;;) { + const page = await relay.read(keys.journalId, keys.authToken, after); + for (const { blob } of page.events) { + try { + const e = await decryptEvent(keys.encKey, blob); + if (validateEvent(e) === null) events.push(/** @type {any} */ (e)); + else unreadable++; + } catch { + unreadable++; + } + } + after = page.events.length ? page.events[page.events.length - 1].seq : page.last; + if (!page.more) break; + } + const byId = new Map(events.map((e) => [e.id, e])); + const state = foldEvents([...byId.values()]); + return { + state, + unreadable, + /** + * Enregistre une proposition de l'IA. + * @param {{program: unknown, profile?: unknown, reason: string}} data + */ + async propose(data) { + const event = createEvent("ProgramProposed", /** @type {any} */ ({ ...data, source: "ai" }), { device: "mcp", at: now().toISOString() }); + await relay.append(keys.journalId, keys.authToken, [await encryptEvent(keys.encKey, event)]); + return event; + }, + }; + } + + const today = () => localISO(now()); + + /** @param {unknown} reason */ + function checkReason(reason) { + if (typeof reason !== "string" || !reason.trim()) throw new ToolError("'reason' manquant : explique en une phrase pourquoi tu proposes ce changement."); + return reason.trim(); + } + + /** @param {unknown} days @param {number} fallback */ + const daysArg = (days, fallback) => (Number.isInteger(days) && /** @type {number} */ (days) > 0 ? Math.min(/** @type {number} */ (days), 3650) : fallback); + + /** @param {Awaited>} j @param {{program: unknown, profile?: unknown, reason: string}} data */ + async function propose(j, data) { + const problems = validateProgram(data.program).map((x) => "programme : " + x); + if (data.profile !== undefined) problems.push(...validateProfile(data.profile).map((x) => "profil : " + x)); + if (problems.length) throw new ToolError("Proposition refusée, rien n'a été enregistré. Corrige :", problems); + const event = await j.propose(data); + return { message: PROPOSAL_SAVED, proposalId: event.id }; + } + + /** @type {Record>, args: Record) => Promise|unknown>} */ + const run = { + get_overview(j) { + const s = j.state; + const day = today(); + const att = attendance(s, addDays(day, -27), day); + const last = s.sessions.at(-1); + return { + today: day, + program: s.program && { + name: s.program.name, + subtitle: s.program.subtitle ?? null, + sessions: s.program.sessions.map((x) => ({ + key: x.key, name: x.name, + exercises: x.exercises.map((e) => `${e.ref ?? e.name} ${e.sets} × ${e.reps}`), + })), + activities: (s.program.activities ?? []).map((a) => a.name), + versions: s.programVersions.length, + }, + profile: s.profile, + mode: s.mode, + pendingProposals: s.proposals.map((p) => ({ id: p.id, at: p.at, source: p.source, reason: p.reason, programName: p.program.name, withProfile: !!p.profile })), + attendanceLast4Weeks: att, + lastSession: last ? { date: last.date, kind: last.kind, ref: last.ref, name: last.name } : null, + lastWeight: s.weights.at(-1) ?? null, + planSettings: s.planSettings, + notes: [ + ...(s.program ? [] : ["Aucun programme adopté : construis-en un avec propose_program (format : ia.md)."]), + ...(s.proposals.length ? ["Des propositions attendent la décision de l'utilisateur : une nouvelle proposition s'ajoute à la liste."] : []), + ...(j.unreadable ? [`${j.unreadable} événement(s) illisibles ignorés.`] : []), + ], + }; + }, + get_program(j) { + const s = j.state; + if (!s.program) return { program: null, note: "Aucun programme adopté : propose_program pour en construire un." }; + return { program: s.program, workingLoads: s.workingLoads, trackingOverrides: s.trackingOverrides, versions: s.programVersions }; + }, + get_training_history(j, args) { + const day = today(); + const since = addDays(day, -daysArg(args.days, 28)); + return { + from: since, to: day, + sessions: j.state.sessions.filter((x) => x.date >= since && x.date <= day).map(({ loggedAt, ...rest }) => rest), + skippedDays: j.state.skippedDays.filter((d) => d >= since && d <= day), + }; + }, + get_exercise_progress(j, args) { + if (typeof args.exercise_id !== "string" || !args.exercise_id.trim()) throw new ToolError("'exercise_id' manquant."); + const points = exerciseHistory(j.state, args.exercise_id); + if (points.length) return { exercise_id: args.exercise_id, points }; + const known = [...new Set(j.state.sessions.flatMap((x) => x.exercises.map((e) => e.id)))].sort(); + return { exercise_id: args.exercise_id, points: [], note: "Aucune séance avec cet exercice.", knownExerciseIds: known }; + }, + get_body_weight(j, args) { + const day = today(); + const since = addDays(day, -daysArg(args.days, 90)); + const weights = j.state.weights; + return { + from: since, to: day, + weights: weights.filter((w) => w.date >= since && w.date <= day), + trend: weightTrend(weights, { today: day }), + milestones: weightMilestones(weights), + heightCm: j.state.profile.heightCm, + }; + }, + propose_program(j, args) { + const data = { program: args.program, reason: checkReason(args.reason) }; + if (args.profile !== undefined) Object.assign(data, { profile: args.profile }); + return propose(j, data); + }, + propose_session_change(j, args) { + const reason = checkReason(args.reason); + const program = j.state.program; + if (!program) throw new ToolError("Aucun programme courant à modifier : utilise propose_program avec un programme complet."); + if (typeof args.key !== "string" || !args.key.trim()) throw new ToolError("'key' manquant : la clé de la séance (« A »)."); + const session = args.session; + if (typeof session !== "object" || session === null || Array.isArray(session)) throw new ToolError("'session' doit être un objet séance."); + if (session.key !== undefined && session.key !== args.key) throw new ToolError(`La séance porte la clé « ${session.key} », différente de 'key' (« ${args.key} »).`); + const copy = structuredClone(program); + const merged = { ...session, key: args.key }; + const i = copy.sessions.findIndex((x) => x.key === args.key); + if (i >= 0) copy.sessions[i] = merged; + else copy.sessions.push(merged); + return propose(j, { program: copy, reason }); + }, + propose_profile(j, args) { + const reason = checkReason(args.reason); + if (!j.state.program) throw new ToolError("Aucun programme courant : une proposition porte toujours un programme. Utilise propose_program avec le programme et le profil."); + return propose(j, { program: structuredClone(j.state.program), profile: args.profile, reason }); + }, + }; + + /** + * Traite un message JSON-RPC. Renvoie null pour une notification. + * @param {any} msg + * @param {string} syncKey + */ + async function handle(msg, syncKey) { + const id = msg && typeof msg === "object" && "id" in msg ? msg.id : null; + const result = (/** @type {unknown} */ r) => ({ jsonrpc: "2.0", id, result: r }); + const error = (/** @type {number} */ code, /** @type {string} */ message) => ({ jsonrpc: "2.0", id, error: { code, message } }); + if (!msg || typeof msg !== "object" || msg.jsonrpc !== "2.0" || typeof msg.method !== "string") + return error(-32600, "Requête JSON-RPC invalide."); + const isNotification = !("id" in msg); + const params = msg.params ?? {}; + switch (msg.method) { + case "initialize": { + const asked = params.protocolVersion; + return result({ + protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0], + capabilities: { tools: { listChanged: false } }, + serverInfo: { name: "ia-fit", title: "IA-Fit", version: "2.0.0" }, + instructions: instructions(publicUrl), + }); + } + case "ping": + return isNotification ? null : result({}); + case "tools/list": + return result({ tools: TOOLS }); + case "tools/call": { + const tool = run[params.name]; + if (!tool) return error(-32602, `Outil inconnu : ${params.name}`); + try { + const j = await openJournal(syncKey); + const out = await tool(j, params.arguments ?? {}); + return result({ content: [{ type: "text", text: JSON.stringify(out, null, 1) }] }); + } catch (e) { + // Jamais la clé de synchro dans un message : les erreurs viennent des + // outils (textes fixes) ou du relais (HttpError, textes fixes). + const message = e instanceof Error ? e.message : String(e); + return result({ content: [{ type: "text", text: "Erreur : " + message }], isError: true }); + } + } + default: + if (isNotification) return null; + return error(-32601, `Méthode inconnue : ${msg.method}`); + } + } + + return { handle, tools: TOOLS }; +} diff --git a/server/oauth.js b/server/oauth.js new file mode 100644 index 0000000..2b46678 --- /dev/null +++ b/server/oauth.js @@ -0,0 +1,305 @@ +// OAuth 2.1 sans état (ADR 0005, point 5) : le serveur ne garde ni client, ni +// code, ni jeton. Tout ce qu'il doit retrouver voyage dans ce qu'il a émis : +// - l'identifiant d'un client porte ses adresses de retour, signées (HMAC) : les +// connecteurs survivent à un redémarrage ; +// - le code et les jetons sont chiffrés (AES-256-GCM) par une clé du serveur et +// portent la clé de synchro et leur expiration. +// Seule exception, en mémoire : la liste des codes déjà échangés, jusqu'à leur +// expiration (usage unique). PKCE S256 est obligatoire. +// +// La clé de synchro n'apparaît jamais dans un message d'erreur ni dans un journal. + +import crypto from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { HttpError } from "./http.js"; + +export const TTL = { + codeMs: 5 * 60e3, + accessMs: 3600e3, + refreshMs: 90 * 864e5, +}; + +export const SCOPE = "ia-fit"; + +/** + * Secret du serveur, créé au premier lancement dans DATA_DIR/.server-secret + * (32 octets aléatoires, en hexadécimal, lisible par le seul propriétaire). Le + * perdre ou le changer déconnecte toutes les IA (clients et jetons), sans + * toucher aux journaux. + * @param {string} dataDir + * @returns {Buffer} + */ +export function loadServerSecret(dataDir) { + const file = path.join(dataDir, ".server-secret"); + try { + fs.writeFileSync(file, crypto.randomBytes(32).toString("hex") + "\n", { flag: "wx", mode: 0o600 }); + } catch (e) { + if (/** @type {NodeJS.ErrnoException} */ (e).code !== "EEXIST") throw e; + } + const secret = Buffer.from(fs.readFileSync(file, "utf8").trim(), "hex"); + if (secret.length !== 32) throw new Error(`${file} est illisible : 64 caractères hexadécimaux attendus.`); + return secret; +} + +/** Erreur OAuth : renvoyée au client (en JSON, ou vers son adresse de retour). */ +export class OAuthError extends HttpError { + /** + * @param {string} error code OAuth (invalid_request, invalid_grant…) + * @param {string} description + * @param {{status?: number, redirect?: boolean}} [options] redirect : l'erreur peut être renvoyée à l'adresse de retour + */ + constructor(error, description, { status = 400, redirect = false } = {}) { + super(status, error, description); + this.redirect = redirect; + } +} + +/** @param {string} uri */ +function isLoopback(uri) { + try { + const u = new URL(uri); + return u.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(u.hostname); + } catch { + return false; + } +} + +/** + * Adresse de retour acceptable : https, http en boucle locale (outils en ligne + * de commande), ou schéma privé d'application (« com.exemple.app: »). + * @param {unknown} uri + */ +export function isAcceptableRedirect(uri) { + if (typeof uri !== "string" || uri.length > 512) return false; + let u; + try { + u = new URL(uri); + } catch { + return false; + } + if (u.hash) return false; + if (u.protocol === "https:") return !!u.hostname; + if (u.protocol === "http:") return isLoopback(uri); + return /^[a-z][a-z0-9+-]*(\.[a-z0-9+-]+)+:$/.test(u.protocol); +} + +/** + * L'adresse demandée correspond-elle à une adresse enregistrée ? Égalité + * exacte, sauf le port en boucle locale (RFC 8252, point 7.3). + * @param {string[]} registered + * @param {string} uri + */ +function redirectMatches(registered, uri) { + if (registered.includes(uri)) return true; + if (!isLoopback(uri)) return false; + const strip = (/** @type {string} */ x) => { const u = new URL(x); u.port = ""; return u.toString(); }; + return registered.some((r) => isLoopback(r) && strip(r) === strip(uri)); +} + +/** + * @param {{secret: Buffer, now?: () => number}} options + */ +export function createOAuth({ secret, now = Date.now }) { + const sub = (/** @type {string} */ label) => crypto.createHmac("sha256", secret).update(label).digest(); + const clientKey = sub("ia-fit/oauth-clients"); + const tokenKey = sub("ia-fit/oauth-tokens"); + /** Codes déjà échangés : identifiant → expiration. */ + /** @type {Map} */ + const usedCodes = new Map(); + + /** @param {string} payload */ + const sign = (payload) => crypto.createHmac("sha256", clientKey).update(payload).digest("base64url"); + /** Empreinte courte d'un client, portée par ses jetons. @param {string} clientId */ + const clientTag = (clientId) => crypto.createHash("sha256").update(clientId).digest("base64url").slice(0, 16); + + /** @param {object} payload */ + function seal(payload) { + const iv = crypto.randomBytes(12); + const cipher = crypto.createCipheriv("aes-256-gcm", tokenKey, iv); + const body = Buffer.concat([cipher.update(JSON.stringify(payload), "utf8"), cipher.final()]); + return Buffer.concat([iv, body, cipher.getAuthTag()]).toString("base64url"); + } + + /** + * @param {unknown} token + * @param {string} type + * @returns {Record|null} null si illisible, d'un autre type ou expiré + */ + function open(token, type) { + if (typeof token !== "string" || token.length > 4096 || !/^[A-Za-z0-9_-]+$/.test(token)) return null; + const raw = Buffer.from(token, "base64url"); + if (raw.length < 12 + 16 + 2) return null; + try { + const decipher = crypto.createDecipheriv("aes-256-gcm", tokenKey, raw.subarray(0, 12)); + decipher.setAuthTag(raw.subarray(raw.length - 16)); + const p = JSON.parse(Buffer.concat([decipher.update(raw.subarray(12, raw.length - 16)), decipher.final()]).toString("utf8")); + return p.t === type && typeof p.exp === "number" && p.exp > now() ? p : null; + } catch { + return null; + } + } + + /** + * @param {unknown} clientId + * @returns {{redirectUris: string[], name: string}|null} + */ + function readClient(clientId) { + if (typeof clientId !== "string" || clientId.length > 8192) return null; + const [payload, mac, extra] = clientId.split("."); + if (!payload || !mac || extra !== undefined) return null; + const expected = Buffer.from(sign(payload)); + if (expected.length !== Buffer.byteLength(mac) || !crypto.timingSafeEqual(expected, Buffer.from(mac))) return null; + try { + const c = JSON.parse(Buffer.from(payload, "base64url").toString("utf8")); + return Array.isArray(c.r) ? { redirectUris: c.r, name: typeof c.n === "string" ? c.n : "" } : null; + } catch { + return null; + } + } + + /** + * Vérifie une demande d'autorisation (GET ou POST /oauth/authorize). + * Erreurs : sans `redirect` si le client ou l'adresse de retour sont en cause + * (on ne renvoie rien vers une adresse inconnue), avec sinon. + * @param {Record} p + */ + function checkAuthorization(p) { + const client = readClient(p.client_id); + if (!client) throw new OAuthError("invalid_client", "Client inconnu : l'enregistrement du connecteur n'est pas reconnu par ce serveur. Supprime puis rajoute le connecteur."); + const redirectUri = p.redirect_uri; + if (typeof redirectUri !== "string" || !redirectMatches(client.redirectUris, redirectUri)) + throw new OAuthError("invalid_request", "Adresse de retour non enregistrée pour ce client."); + if (p.response_type !== undefined && p.response_type !== "code") + throw new OAuthError("unsupported_response_type", "Seul response_type=code est accepté.", { redirect: true }); + if (typeof p.code_challenge !== "string" || !/^[A-Za-z0-9_-]{43,128}$/.test(p.code_challenge)) + throw new OAuthError("invalid_request", "PKCE obligatoire : code_challenge manquant ou mal formé.", { redirect: true }); + if (p.code_challenge_method !== "S256") + throw new OAuthError("invalid_request", "PKCE : seule la méthode S256 est acceptée.", { redirect: true }); + return { client, redirectUri, challenge: p.code_challenge, state: typeof p.state === "string" ? p.state : null }; + } + + /** + * @param {string} redirectUri + * @param {Record} params + */ + function redirectTo(redirectUri, params) { + const u = new URL(redirectUri); + for (const [k, v] of Object.entries(params)) if (v !== null) u.searchParams.set(k, v); + return u.toString(); + } + + /** @param {string} syncKey @param {string} cid empreinte du client */ + function issueTokens(syncKey, cid) { + return { + access_token: seal({ t: "access", k: syncKey, cid, exp: now() + TTL.accessMs }), + token_type: "Bearer", + expires_in: TTL.accessMs / 1000, + refresh_token: seal({ t: "refresh", k: syncKey, cid, exp: now() + TTL.refreshMs }), + scope: SCOPE, + }; + } + + return { + readClient, + checkAuthorization, + + /** + * Enregistrement dynamique (RFC 7591), sans stockage. + * @param {any} body + */ + register(body) { + if (typeof body !== "object" || body === null) throw new OAuthError("invalid_client_metadata", "Corps JSON attendu."); + const uris = body.redirect_uris; + if (!Array.isArray(uris) || uris.length === 0 || uris.length > 10) + throw new OAuthError("invalid_redirect_uri", "redirect_uris : une à dix adresses attendues."); + for (const u of uris) + if (!isAcceptableRedirect(u)) throw new OAuthError("invalid_redirect_uri", "Adresse de retour refusée : https, http://localhost ou schéma d'application attendu, sans fragment."); + const name = typeof body.client_name === "string" ? body.client_name.slice(0, 80) : ""; + const payload = Buffer.from(JSON.stringify({ r: uris, n: name })).toString("base64url"); + const clientId = payload + "." + sign(payload); + return { + client_id: clientId, + client_id_issued_at: Math.floor(now() / 1000), + client_name: name, + redirect_uris: uris, + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + scope: SCOPE, + }; + }, + + /** + * Émet un code pour une demande vérifiée, avec la clé de synchro (déjà + * vérifiée contre le relais par l'appelant). + * @param {ReturnType} request + * @param {string} clientId + * @param {string} syncKey au format normalisé + * @returns {string} adresse de retour, avec le code et l'état + */ + authorize(request, clientId, syncKey) { + const code = seal({ + t: "code", k: syncKey, cid: clientTag(clientId), r: request.redirectUri, ch: request.challenge, + j: crypto.randomBytes(12).toString("base64url"), exp: now() + TTL.codeMs, + }); + return redirectTo(request.redirectUri, { code, state: request.state }); + }, + + redirectTo, + + /** + * Point d'échange (/oauth/token). + * @param {Record} p + */ + token(p) { + if (p.grant_type === "authorization_code") { + const c = open(p.code, "code"); + if (!c) throw new OAuthError("invalid_grant", "Code inconnu ou expiré."); + if (p.client_id !== undefined && clientTag(p.client_id) !== c.cid) + throw new OAuthError("invalid_grant", "Ce code a été émis pour un autre client."); + if (p.redirect_uri !== undefined && p.redirect_uri !== c.r) + throw new OAuthError("invalid_grant", "redirect_uri différente de celle de la demande."); + const verifier = p.code_verifier; + if (typeof verifier !== "string" || !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) + throw new OAuthError("invalid_grant", "PKCE obligatoire : code_verifier manquant ou mal formé."); + const computed = Buffer.from(crypto.createHash("sha256").update(verifier).digest("base64url")); + const expected = Buffer.from(c.ch); + if (computed.length !== expected.length || !crypto.timingSafeEqual(computed, expected)) + throw new OAuthError("invalid_grant", "PKCE : code_verifier ne correspond pas."); + const t = now(); + for (const [j, exp] of usedCodes) if (exp <= t) usedCodes.delete(j); + if (usedCodes.has(c.j)) throw new OAuthError("invalid_grant", "Code déjà utilisé."); + usedCodes.set(c.j, c.exp); + return issueTokens(c.k, c.cid); + } + if (p.grant_type === "refresh_token") { + const r = open(p.refresh_token, "refresh"); + if (!r) throw new OAuthError("invalid_grant", "Jeton de rafraîchissement inconnu ou expiré."); + if (p.client_id !== undefined && clientTag(p.client_id) !== r.cid) + throw new OAuthError("invalid_grant", "Ce jeton a été émis pour un autre client."); + // Rotation sans révocation (sans état) : l'ancien jeton reste valable + // jusqu'à son expiration. + return issueTokens(r.k, r.cid); + } + throw new OAuthError("unsupported_grant_type", "grant_type : authorization_code ou refresh_token."); + }, + + /** + * Clé de synchro portée par un jeton d'accès valide, sinon null. + * @param {string} token + * @returns {string|null} + */ + verifyAccess(token) { + const a = open(token, "access"); + return a && typeof a.k === "string" ? a.k : null; + }, + + /** Codes échangés gardés en mémoire (tests). */ + get usedCodes() { + return usedCodes.size; + }, + }; +} + +/** @typedef {ReturnType} OAuth */ diff --git a/server/rate-limit.js b/server/rate-limit.js new file mode 100644 index 0000000..fed35ba --- /dev/null +++ b/server/rate-limit.js @@ -0,0 +1,49 @@ +// Limite de requêtes par adresse IP, en mémoire seulement : rien n'est écrit, +// et tout est oublié au redémarrage (ADR 0005 : aucune adresse conservée). + +/** + * Adresse du client telle que vue par le proxy de CapRover (nginx), qui écrit + * `X-Real-IP` et AJOUTE l'adresse vue à la fin de `X-Forwarded-For`. Le début de + * `X-Forwarded-For` vient du client et peut être inventé (défaut d'Atelier) : + * on ne le lit jamais. + * @param {import("node:http").IncomingMessage} req + */ +export function clientIp(req) { + const real = req.headers["x-real-ip"]; + if (typeof real === "string" && real.trim()) return real.trim(); + const forwarded = req.headers["x-forwarded-for"]; + const list = (Array.isArray(forwarded) ? forwarded.join(",") : forwarded ?? "").split(",").map((s) => s.trim()).filter(Boolean); + if (list.length) return list[list.length - 1]; + return req.socket.remoteAddress ?? "inconnue"; +} + +/** + * Fenêtre fixe : au plus `max` requêtes par `windowMs` et par clé. + * @param {{max: number, windowMs: number, now?: () => number}} options + */ +export function createRateLimiter({ max, windowMs, now = Date.now }) { + /** @type {Map} */ + const windows = new Map(); + return { + /** + * Compte une requête ; renvoie le nombre de secondes à attendre si la limite + * est dépassée, sinon 0. + * @param {string} key + */ + hit(key) { + const t = now(); + if (windows.size > 50_000) for (const [k, w] of windows) if (t - w.start >= windowMs) windows.delete(k); + let w = windows.get(key); + if (!w || t - w.start >= windowMs) { + w = { start: t, count: 0 }; + windows.set(key, w); + } + w.count++; + return w.count > max ? Math.ceil((w.start + windowMs - t) / 1000) : 0; + }, + /** Nombre d'adresses suivies (tests). */ + get size() { + return windows.size; + }, + }; +} diff --git a/server/relay.js b/server/relay.js new file mode 100644 index 0000000..7e1de43 --- /dev/null +++ b/server/relay.js @@ -0,0 +1,259 @@ +// Le relais (ADR 0005, point 3) : il range des blocs chiffrés par journal, sans +// pouvoir les lire. Glossaire : docs/glossaire/relais.md +// +// FORMAT DURABLE sur disque, un fichier JSON Lines par journal : +// /journals/.jsonl +// ligne 1 : {"v":1,"auth":""} +// puis : {"seq":1,"blob":""}, {"seq":2,…}, … +// Le fichier ne fait que grandir (ajout seulement). Aucune date, aucune adresse : +// la date de modification du fichier sert seule à repérer l'inactivité. + +import fs from "node:fs/promises"; +import path from "node:path"; +import crypto from "node:crypto"; +import { HttpError } from "./http.js"; + +export const LIMITS = { + /** Taille maximale d'un bloc chiffré (caractères base64url, donc octets). */ + blobBytes: 64 * 1024, + /** Taille maximale d'un journal sur disque. */ + journalBytes: 20 * 1024 * 1024, + /** Blocs par dépôt. */ + blobsPerRequest: 500, + /** Blocs par réponse de lecture : au-delà, `more` vaut true. */ + blobsPerRead: 2000, + /** Inactivité au bout de laquelle un journal est effacé. */ + inactiveDays: 400, +}; + +/** Identifiant de journal : 16 octets en base64url (22 caractères) ; tolérance jusqu'à 64. */ +export const JOURNAL_ID = /^[A-Za-z0-9_-]{16,64}$/; +const BLOB = /^[A-Za-z0-9_-]{38,}$/; + +/** @param {string} token */ +const hashToken = (token) => crypto.createHash("sha256").update(token).digest(); + +/** + * @typedef {object} JournalMeta + * @property {Buffer} auth empreinte SHA-256 de la clé d'accès + * @property {number} last dernier numéro d'ordre + * @property {number} size taille du fichier + * @property {number} touched dernière mise à jour de la date du fichier (lecture), en ms + */ + +/** + * @param {string} dataDir + * @param {{limits?: Partial, now?: () => number}} [options] + */ +export function createRelay(dataDir, options = {}) { + const limits = { ...LIMITS, ...options.limits }; + const now = options.now ?? Date.now; + const dir = path.join(dataDir, "journals"); + /** @type {Map} */ + const metas = new Map(); + /** File d'attente par journal : les écritures (et le chargement) sont sérialisées. */ + /** @type {Map>} */ + const queues = new Map(); + + /** @param {string} id */ + const fileOf = (id) => path.join(dir, id + ".jsonl"); + + /** + * @template T + * @param {string} id + * @param {() => Promise} task + * @returns {Promise} + */ + function serialized(id, task) { + const previous = queues.get(id) ?? Promise.resolve(); + const run = previous.then(task, task); + const tail = run.catch(() => {}); + queues.set(id, tail); + tail.then(() => { if (queues.get(id) === tail) queues.delete(id); }); + return run; + } + + /** + * Lit l'en-tête et compte les blocs. Une dernière ligne incomplète (arrêt + * brutal pendant une écriture) est retirée. + * @param {string} id + * @returns {Promise} + */ + async function load(id) { + const cached = metas.get(id); + if (cached) return cached; + let text; + try { + text = await fs.readFile(fileOf(id), "utf8"); + } catch (e) { + if (/** @type {NodeJS.ErrnoException} */ (e).code === "ENOENT") return null; + throw e; + } + if (!text.endsWith("\n")) { + const cut = text.lastIndexOf("\n") + 1; + await fs.truncate(fileOf(id), Buffer.byteLength(text.slice(0, cut))); + text = text.slice(0, cut); + if (!text) { + await fs.unlink(fileOf(id)); + return null; + } + } + const lines = text.split("\n"); + const header = JSON.parse(lines[0]); + const meta = { + auth: Buffer.from(header.auth, "hex"), + last: lines.length - 2, + size: Buffer.byteLength(text), + touched: 0, + }; + if (metas.size > 10_000) metas.clear(); + metas.set(id, meta); + return meta; + } + + /** + * Vérifie la clé d'accès, à temps constant. + * @param {JournalMeta} meta + * @param {string} token + */ + function checkToken(meta, token) { + if (!token || !crypto.timingSafeEqual(meta.auth, hashToken(token))) + throw new HttpError(403, "forbidden", "Clé d'accès refusée pour ce journal."); + } + + /** @param {string} id */ + function checkId(id) { + if (!JOURNAL_ID.test(id)) throw new HttpError(404, "unknown_journal", "Journal inconnu."); + } + + /** + * Garde le journal en vie : une lecture compte comme une activité (au plus + * une mise à jour de la date du fichier par jour). + * @param {string} id + * @param {JournalMeta} meta + */ + async function touch(id, meta) { + if (now() - meta.touched < 864e5) return; + meta.touched = now(); + const t = new Date(now()); + await fs.utimes(fileOf(id), t, t).catch(() => {}); + } + + return { + limits, + + /** + * Dépose des blocs. Le premier dépôt crée le journal et retient l'empreinte + * de la clé d'accès ; les suivants l'exigent. + * @param {string} id + * @param {string} token + * @param {unknown} blobs + * @returns {Promise<{last: number, accepted: number}>} + */ + append(id, token, blobs) { + checkId(id); + if (!token) throw new HttpError(401, "unauthorized", "Clé d'accès manquante."); + if (!Array.isArray(blobs) || blobs.length === 0) + throw new HttpError(400, "invalid_request", "Le corps doit être une liste non vide de blocs chiffrés."); + if (blobs.length > limits.blobsPerRequest) + throw new HttpError(413, "too_many_blobs", `Au plus ${limits.blobsPerRequest} blocs par dépôt.`); + for (const b of blobs) { + if (typeof b !== "string" || !BLOB.test(b)) throw new HttpError(400, "invalid_blob", "Bloc chiffré mal formé (base64url attendu)."); + if (b.length > limits.blobBytes) throw new HttpError(413, "blob_too_large", `Un bloc dépasse ${limits.blobBytes} octets.`); + } + return serialized(id, async () => { + let meta = await load(id); + let header = ""; + if (meta) checkToken(meta, token); + else { + await fs.mkdir(dir, { recursive: true }); + header = JSON.stringify({ v: 1, auth: hashToken(token).toString("hex") }) + "\n"; + } + const start = meta?.last ?? 0; + const lines = header + blobs.map((blob, i) => JSON.stringify({ seq: start + i + 1, blob })).join("\n") + "\n"; + const bytes = Buffer.byteLength(lines); + if ((meta?.size ?? 0) + bytes > limits.journalBytes) + throw new HttpError(413, "journal_full", `Le journal dépasserait ${Math.round(limits.journalBytes / 1048576)} Mo.`); + const handle = await fs.open(fileOf(id), meta ? "a" : "wx"); + try { + await handle.write(lines); + await handle.datasync(); + } finally { + await handle.close(); + } + if (!meta) { + meta = { auth: hashToken(token), last: 0, size: 0, touched: now() }; + metas.set(id, meta); + } + meta.last = start + blobs.length; + meta.size += bytes; + meta.touched = now(); + return { last: meta.last, accepted: blobs.length }; + }); + }, + + /** + * Blocs dont le numéro d'ordre suit `after`. + * @param {string} id + * @param {string} token + * @param {number} [after] + * @returns {Promise<{events: {seq: number, blob: string}[], last: number, more: boolean}>} + */ + read(id, token, after = 0) { + checkId(id); + if (!token) throw new HttpError(401, "unauthorized", "Clé d'accès manquante."); + return serialized(id, async () => { + const meta = await load(id); + if (!meta) throw new HttpError(404, "unknown_journal", "Journal inconnu : aucun dépôt n'a encore été fait avec cette clé."); + checkToken(meta, token); + await touch(id, meta); + /** @type {{seq: number, blob: string}[]} */ + const events = []; + if (after < meta.last) { + const lines = (await fs.readFile(fileOf(id), "utf8")).split("\n"); + // Ligne n (à partir de 1) = bloc n. + for (let seq = Math.max(1, after + 1); seq <= meta.last && events.length < limits.blobsPerRead; seq++) + events.push({ seq, blob: JSON.parse(lines[seq]).blob }); + } + const lastSent = events.length ? events[events.length - 1].seq : Math.max(after, 0); + return { events, last: meta.last, more: lastSent < meta.last }; + }); + }, + + /** + * Le journal existe-t-il, et cette clé d'accès est-elle la sienne ? + * @param {string} id + * @param {string} token + */ + async owns(id, token) { + if (!JOURNAL_ID.test(id) || !token) return false; + const meta = await serialized(id, () => load(id)); + return !!meta && crypto.timingSafeEqual(meta.auth, hashToken(token)); + }, + + /** + * Efface les journaux inactifs depuis `inactiveDays` jours. + * @returns {Promise} nombre de journaux effacés + */ + async purgeInactive() { + const limit = now() - limits.inactiveDays * 864e5; + let removed = 0; + const names = await fs.readdir(dir).catch(() => /** @type {string[]} */ ([])); + for (const name of names) { + if (!name.endsWith(".jsonl")) continue; + const id = name.slice(0, -6); + await serialized(id, async () => { + const stat = await fs.stat(fileOf(id)).catch(() => null); + if (stat && stat.mtimeMs < limit) { + await fs.unlink(fileOf(id)); + metas.delete(id); + removed++; + } + }); + } + return removed; + }, + }; +} + +/** @typedef {ReturnType} Relay */ diff --git a/server/static.js b/server/static.js new file mode 100644 index 0000000..25691ec --- /dev/null +++ b/server/static.js @@ -0,0 +1,140 @@ +// Site statique : les mêmes réponses que le Caddyfile du lot 1 (types MIME fixés, +// en-têtes de sécurité, revalidation à chaque visite, compression des textes). + +import fs from "node:fs/promises"; +import path from "node:path"; +import zlib from "node:zlib"; +import { SECURITY_HEADERS, sendText } from "./http.js"; + +/** + * Types MIME fixés ici plutôt que devinés : avec nosniff, un module ES servi + * sous un autre type ne se charge pas. + * @type {Record} + */ +export const MIME_TYPES = { + ".html": "text/html; charset=utf-8", + ".js": "text/javascript; charset=utf-8", + ".mjs": "text/javascript; charset=utf-8", + ".css": "text/css; charset=utf-8", + ".json": "application/json", + ".webmanifest": "application/manifest+json", + ".md": "text/markdown; charset=utf-8", + ".txt": "text/plain; charset=utf-8", + ".svg": "image/svg+xml", + ".png": "image/png", + ".jpg": "image/jpeg", + ".jpeg": "image/jpeg", + ".webp": "image/webp", + ".ico": "image/x-icon", + ".woff2": "font/woff2", +}; + +/** Types compressés : les textes. Les polices woff2 et les images le sont déjà. */ +const COMPRESSIBLE = /^(text\/|application\/json|application\/manifest\+json|image\/svg\+xml)/; +/** Comme Caddy : en dessous, la compression ne fait rien gagner. */ +const MIN_COMPRESS = 512; + +/** + * Encodage choisi d'après Accept-Encoding : zstd, sinon gzip, sinon aucun. + * @param {string|undefined} header + * @returns {"zstd"|"gzip"|null} + */ +export function pickEncoding(header) { + /** @type {Map} */ + const accepted = new Map(); + for (const part of (header ?? "").split(",")) { + const [name, ...params] = part.trim().toLowerCase().split(";"); + if (!name) continue; + const q = params.map((p) => /^\s*q=([0-9.]+)\s*$/.exec(p)).find(Boolean); + accepted.set(name, q ? Number(q[1]) : 1); + } + const ok = (/** @type {string} */ name) => (accepted.get(name) ?? accepted.get("*") ?? 0) > 0; + if (ok("zstd")) return "zstd"; + if (ok("gzip")) return "gzip"; + return null; +} + +/** + * @param {string} siteDir dossier du site assemblé (make site) + */ +export function createStaticHandler(siteDir) { + const root = path.resolve(siteDir); + /** Versions compressées, gardées en mémoire tant que le fichier ne change pas. */ + /** @type {Map} */ + const compressed = new Map(); + + /** + * @param {import("node:http").IncomingMessage} req + * @param {import("node:http").ServerResponse} res + * @param {string} pathname chemin de l'URL, non décodé + */ + return async function serveStatic(req, res, pathname) { + if (req.method !== "GET" && req.method !== "HEAD") + return sendText(res, 405, "Méthode non permise.", { allow: "GET, HEAD" }); + let rel; + try { + rel = decodeURIComponent(pathname); + } catch { + return sendText(res, 400, "Adresse invalide."); + } + // Ni remontée, ni fichier caché, ni caractère nul. + if (rel.includes("\0") || rel.split("/").some((seg) => seg === ".." || seg.startsWith("."))) + return notFound(res); + let file = path.join(root, rel); + if (file !== root && !file.startsWith(root + path.sep)) return notFound(res); + let stat = await fs.stat(file).catch(() => null); + if (stat?.isDirectory()) { + if (!rel.endsWith("/")) { + const index = await fs.stat(path.join(file, "index.html")).catch(() => null); + if (!index) return notFound(res); + res.writeHead(308, { ...SECURITY_HEADERS, location: pathname + "/", "cache-control": "no-cache" }); + return res.end(); + } + file = path.join(file, "index.html"); + stat = await fs.stat(file).catch(() => null); + } + if (!stat?.isFile()) return notFound(res); + + const type = MIME_TYPES[path.extname(file).toLowerCase()] ?? "application/octet-stream"; + const encoding = COMPRESSIBLE.test(type) && stat.size >= MIN_COMPRESS ? pickEncoding(req.headers["accept-encoding"]) : null; + const baseTag = `${Math.floor(stat.mtimeMs).toString(36)}${stat.size.toString(36)}`; + const etag = `"${baseTag}${encoding ? "-" + encoding : ""}"`; + /** @type {Record} */ + const headers = { + ...SECURITY_HEADERS, + // Les noms de fichiers ne changent pas d'une version à l'autre : le + // navigateur revalide chaque fichier (ETag). sw.js porte la version. + "cache-control": "no-cache", + "content-type": type, + etag, + "last-modified": stat.mtime.toUTCString(), + }; + if (COMPRESSIBLE.test(type)) headers.vary = "Accept-Encoding"; + const inm = req.headers["if-none-match"]; + if (inm && inm.split(",").some((t) => t.trim().replace(/^W\//, "") === etag)) { + res.writeHead(304, headers); + return res.end(); + } + let body = await fs.readFile(file); + if (encoding) { + const key = `${file}|${baseTag}|${encoding}`; + let packed = compressed.get(key); + if (!packed) { + packed = encoding === "zstd" ? zlib.zstdCompressSync(body) : zlib.gzipSync(body); + if (compressed.size > 2000) compressed.clear(); + compressed.set(key, packed); + } + body = packed; + headers["content-encoding"] = encoding; + } + headers["content-length"] = body.length; + res.writeHead(200, headers); + res.end(req.method === "HEAD" ? undefined : body); + }; +} + +/** @param {import("node:http").ServerResponse} res */ +function notFound(res) { + res.writeHead(404, { ...SECURITY_HEADERS, "cache-control": "no-cache", "content-type": "text/plain; charset=utf-8" }); + res.end("Introuvable."); +} From 91ee787ba0d1459f76992019dce08b35061b86e1 Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Wed, 18 Nov 2026 05:10:31 +0100 Subject: [PATCH 04/10] =?UTF-8?q?Tests=20du=20serveur=20:=20relais,=20quot?= =?UTF-8?q?as,=20IP=20r=C3=A9elle,=20OAuth=20sans=20=C3=A9tat,=20MCP,=20si?= =?UTF-8?q?te?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- tests/server/helpers.js | 100 +++++++++++++++ tests/server/mcp.test.js | 196 ++++++++++++++++++++++++++++++ tests/server/oauth.test.js | 235 ++++++++++++++++++++++++++++++++++++ tests/server/relay.test.js | 146 ++++++++++++++++++++++ tests/server/static.test.js | 71 +++++++++++ 5 files changed, 748 insertions(+) create mode 100644 tests/server/helpers.js create mode 100644 tests/server/mcp.test.js create mode 100644 tests/server/oauth.test.js create mode 100644 tests/server/relay.test.js create mode 100644 tests/server/static.test.js diff --git a/tests/server/helpers.js b/tests/server/helpers.js new file mode 100644 index 0000000..7617ebc --- /dev/null +++ b/tests/server/helpers.js @@ -0,0 +1,100 @@ +// Outils communs aux tests du serveur : un serveur lancé sur un port libre, avec +// des dossiers temporaires, et un client OAuth complet (PKCE). +import http from "node:http"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import crypto from "node:crypto"; +import { createApp } from "../../server/app.js"; + +/** + * @param {Partial} [options] + */ +export async function startServer(options = {}) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "ia-fit-server-")); + const siteDir = path.join(root, "site"); + const dataDir = path.join(root, "data"); + fs.mkdirSync(siteDir); + fs.mkdirSync(dataDir); + fs.writeFileSync(path.join(siteDir, "index.html"), "IA-Fit"); + fs.writeFileSync(path.join(siteDir, "ia.md"), "# Format\n" + "texte ".repeat(200)); + fs.writeFileSync(path.join(siteDir, "app.js"), "export const x = 1;\n".repeat(100)); + fs.writeFileSync(path.join(siteDir, "police.woff2"), "wOF2" + "x".repeat(2000)); + const publicUrl = "https://ia-fit.test"; + const app = createApp({ dataDir, siteDir, publicUrl, ...options }); + const server = http.createServer(app.handler); + await new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(undefined))); + const address = /** @type {import("node:net").AddressInfo} */ (server.address()); + const base = `http://127.0.0.1:${address.port}`; + return { + app, base, dataDir, siteDir, publicUrl, + /** + * @param {string} p + * @param {RequestInit} [init] + */ + fetch: (p, init) => fetch(base + p, { redirect: "manual", ...init }), + async close() { + await new Promise((resolve) => server.close(() => resolve(undefined))); + fs.rmSync(root, { recursive: true, force: true }); + }, + }; +} + +export function pkce() { + const verifier = crypto.randomBytes(32).toString("base64url"); + const challenge = crypto.createHash("sha256").update(verifier).digest("base64url"); + return { verifier, challenge }; +} + +/** @param {string} token */ +export const auth = (token) => ({ authorization: "Bearer " + token }); + +/** + * @param {Awaited>} s + * @param {string} journalId + * @param {string} token + * @param {string[]} blobs + */ +export function push(s, journalId, token, blobs) { + return s.fetch(`/api/journals/${journalId}/events`, { + method: "POST", headers: { ...auth(token), "content-type": "application/json" }, body: JSON.stringify(blobs), + }); +} + +/** + * Parcours OAuth complet jusqu'aux jetons. + * @param {Awaited>} s + * @param {string} syncKey + */ +export async function connect(s, syncKey) { + const redirectUri = "https://claude.ai/api/mcp/auth_callback"; + const reg = await (await s.fetch("/oauth/register", { + method: "POST", headers: { "content-type": "application/json" }, + body: JSON.stringify({ client_name: "Claude", redirect_uris: [redirectUri] }), + })).json(); + const { verifier, challenge } = pkce(); + const body = { client_id: reg.client_id, redirect_uri: redirectUri, state: "s1", code_challenge: challenge, code_challenge_method: "S256", sync_key: syncKey }; + const r = await s.fetch("/oauth/authorize", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const { redirect } = await r.json(); + const code = new URL(redirect).searchParams.get("code") ?? ""; + const tokens = await (await s.fetch("/oauth/token", { + method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ grant_type: "authorization_code", code, code_verifier: verifier, client_id: reg.client_id, redirect_uri: redirectUri }), + })).json(); + return { clientId: reg.client_id, redirectUri, tokens }; +} + +/** + * Appel JSON-RPC sur /mcp. + * @param {Awaited>} s + * @param {string} token + * @param {string} method + * @param {unknown} [params] + */ +export async function rpc(s, token, method, params) { + const r = await s.fetch("/mcp", { + method: "POST", headers: { ...auth(token), "content-type": "application/json" }, + body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), + }); + return r.json(); +} diff --git a/tests/server/mcp.test.js b/tests/server/mcp.test.js new file mode 100644 index 0000000..fd5ca71 --- /dev/null +++ b/tests/server/mcp.test.js @@ -0,0 +1,196 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { createMcp, PROPOSAL_SAVED } from "../../server/mcp.js"; +import { createRelay } from "../../server/relay.js"; +import { createEvent } from "../../app/domain/events.js"; +import { foldEvents } from "../../app/domain/state.js"; +import { EXAMPLE_PROGRAM } from "../../app/domain/example-program.js"; +import { deriveKeys, encryptEvent, decryptEvent, generateSyncKey } from "../../app/domain/sync-crypto.js"; +import { startServer, push, connect, rpc } from "./helpers.js"; + +const NOW = new Date("2026-11-18T12:00:00"); +const device = "pc"; +const PROFILE = { goal: "Force", context: "Maison", equipment: ["barre"], constraints: ["Pas de pareur"], heightCm: 180, sessionMinutes: 50 }; +const squat = { id: "squat", name: "Squat", target: "4 × 8", tracking: /** @type {const} */ ("load"), loadKg: 60, seconds: null, plannedSets: 4, sets: [{ reps: 8, effort: /** @type {const} */ ("ok") }] }; + +function history() { + return [ + createEvent("ProgramAdopted", { program: EXAMPLE_PROGRAM, source: "example" }, { device, at: "2026-11-01T10:00:00.000Z" }), + createEvent("ProfileUpdated", { profile: PROFILE }, { device, at: "2026-11-01T10:01:00.000Z" }), + createEvent("SessionLogged", { date: "2026-11-10", kind: "strength", ref: "A", name: "Séance A", warmup: null, exercises: [squat] }, { device, at: "2026-11-10T19:00:00.000Z" }), + createEvent("SessionLogged", { date: "2026-11-14", kind: "strength", ref: "A", name: "Séance A", warmup: null, exercises: [{ ...squat, loadKg: 62.5 }] }, { device, at: "2026-11-14T19:00:00.000Z" }), + createEvent("SessionLogged", { date: "2025-01-01", kind: "cardio", ref: "Vélo", name: "Vélo", warmup: null, exercises: [] }, { device, at: "2025-01-01T19:00:00.000Z" }), + createEvent("WeightRecorded", { date: "2026-11-01", kg: 82 }, { device, at: "2026-11-01T07:00:00.000Z" }), + createEvent("WeightRecorded", { date: "2026-11-15", kg: 81 }, { device, at: "2026-11-15T07:00:00.000Z" }), + ]; +} + +/** Journal en mémoire (dossier temporaire), servi par un MCP sans HTTP. */ +async function setup(events = history()) { + const relay = createRelay(fs.mkdtempSync(path.join(os.tmpdir(), "ia-fit-mcp-"))); + const syncKey = generateSyncKey(); + const keys = await deriveKeys(syncKey); + const blobs = await Promise.all(events.map((e) => encryptEvent(keys.encKey, e))); + // Un bloc d'une autre clé et un événement invalide : ignorés. + blobs.push(await encryptEvent((await deriveKeys(generateSyncKey())).encKey, events[0])); + blobs.push(await encryptEvent(keys.encKey, { id: "x", type: "Inconnu" })); + await relay.append(keys.journalId, keys.authToken, blobs); + const mcp = createMcp({ relay, publicUrl: "https://ia-fit.test", now: () => NOW }); + /** @param {string} name @param {object} [args] */ + const call = async (name, args = {}) => { + const r = /** @type {any} */ (await mcp.handle({ jsonrpc: "2.0", id: 7, method: "tools/call", params: { name, arguments: args } }, syncKey)); + assert.equal(r.id, 7); + const text = r.result.content[0].text; + return { isError: !!r.result.isError, text, json: r.result.isError ? null : JSON.parse(text) }; + }; + /** Le journal tel que l'app le relirait. */ + const journal = async () => { + const { events: stored } = await relay.read(keys.journalId, keys.authToken, 0); + const out = []; + for (const { blob } of stored) out.push(await decryptEvent(keys.encKey, blob).catch(() => null)); + return out.filter(Boolean); + }; + return { mcp, call, journal, syncKey }; +} + +test("initialize, tools/list, notifications et méthodes inconnues", async () => { + const { mcp, syncKey } = await setup(); + const init = /** @type {any} */ (await mcp.handle({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } }, syncKey)); + assert.equal(init.result.protocolVersion, "2025-06-18"); + assert.match(init.result.instructions, /get_overview/); + assert.match(init.result.instructions, /https:\/\/ia-fit\.test\/ia\.md/); + assert.match(init.result.instructions, /proposition/); + const old = /** @type {any} */ (await mcp.handle({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2024-11-05" } }, syncKey)); + assert.equal(old.result.protocolVersion, "2025-06-18"); + assert.equal(await mcp.handle({ jsonrpc: "2.0", method: "notifications/initialized" }, syncKey), null); + const list = /** @type {any} */ (await mcp.handle({ jsonrpc: "2.0", id: 2, method: "tools/list" }, syncKey)); + assert.deepEqual(list.result.tools.map((/** @type {any} */ t) => t.name), [ + "get_overview", "get_program", "get_training_history", "get_exercise_progress", "get_body_weight", + "propose_program", "propose_session_change", "propose_profile", + ]); + assert.equal((/** @type {any} */ (await mcp.handle({ jsonrpc: "2.0", id: 3, method: "resources/list" }, syncKey))).error.code, -32601); + assert.equal((/** @type {any} */ (await mcp.handle({ jsonrpc: "2.0", id: 4, method: "tools/call", params: { name: "rm" } }, syncKey))).error.code, -32602); +}); + +test("lecture : vue d'ensemble, programme, historique, progression, poids", async () => { + const { call } = await setup(); + const o = (await call("get_overview")).json; + assert.equal(o.today, "2026-11-18"); + assert.equal(o.program.name, EXAMPLE_PROGRAM.name); + assert.deepEqual(o.profile, PROFILE); + assert.equal(o.mode, "progression"); + assert.deepEqual(o.pendingProposals, []); + assert.equal(o.attendanceLast4Weeks.totals.strength, 2); + assert.equal(o.lastSession.date, "2026-11-14"); + assert.deepEqual(o.lastWeight, { date: "2026-11-15", kg: 81 }); + assert.ok(o.notes.some((/** @type {string} */ n) => /2 événement\(s\) illisibles/.test(n))); + + assert.deepEqual((await call("get_program")).json.program, EXAMPLE_PROGRAM); + assert.equal((await call("get_training_history")).json.sessions.length, 2, "28 jours par défaut"); + assert.equal((await call("get_training_history", { days: 1000 })).json.sessions.length, 3); + + const progress = (await call("get_exercise_progress", { exercise_id: "squat" })).json; + assert.deepEqual(progress.points.map((/** @type {any} */ p) => p.loadKg), [60, 62.5]); + const none = (await call("get_exercise_progress", { exercise_id: "curl" })).json; + assert.deepEqual([none.points, none.knownExerciseIds], [[], ["squat"]]); + assert.equal((await call("get_exercise_progress", {})).isError, true); + + const w = (await call("get_body_weight")).json; + assert.equal(w.weights.length, 2); + assert.ok(w.trend.kgPerWeek < 0); +}); + +test("propose_program : une proposition « ai » chiffrée dans le journal, que l'app relit", async () => { + const { call, journal } = await setup(); + const before = (await journal()).length; + const program = { ...EXAMPLE_PROGRAM, name: "Programme revu" }; + const r = await call("propose_program", { program, profile: { ...PROFILE, sessionMinutes: 40 }, reason: "Séances plus courtes" }); + assert.equal(r.isError, false); + assert.equal(r.json.message, PROPOSAL_SAVED); + const events = /** @type {any[]} */ (await journal()); + assert.equal(events.length, before + 1); + const proposed = events.at(-1); + assert.equal(proposed.type, "ProgramProposed"); + assert.equal(proposed.device, "mcp"); + assert.equal(proposed.data.source, "ai"); + assert.equal(proposed.id, r.json.proposalId); + const state = foldEvents(events.filter((e) => e.v === 1 && e.device)); + assert.equal(state.proposals[0].program.name, "Programme revu"); + assert.equal(state.proposals[0].profile?.sessionMinutes, 40); + assert.equal(state.program?.name, EXAMPLE_PROGRAM.name, "le programme courant ne change pas"); + // La vue d'ensemble la montre en attente. + assert.equal((await call("get_overview")).json.pendingProposals[0].reason, "Séances plus courtes"); +}); + +test("propose_program invalide : refusé avec la liste des problèmes, rien n'est écrit", async () => { + const { call, journal } = await setup(); + const before = (await journal()).length; + const r = await call("propose_program", { program: { name: "", sessions: [{ key: "A", name: "A", exercises: [{ ref: "inconnu", sets: 0, reps: "8", rest: 60 }] }] }, reason: "Essai" }); + assert.equal(r.isError, true); + assert.match(r.text, /Proposition refusée/); + assert.match(r.text, /- programme : Le programme n'a pas de nom/); + assert.match(r.text, /référence inconnue « inconnu »/); + assert.match(r.text, /'sets' doit être un entier/); + assert.equal((await call("propose_program", { program: EXAMPLE_PROGRAM, reason: "" })).isError, true, "raison obligatoire"); + assert.match((await call("propose_program", { program: EXAMPLE_PROGRAM, profile: { goal: 3 }, reason: "x" })).text, /profil :/); + assert.equal((await journal()).length, before); +}); + +test("propose_session_change : fusion dans une copie du programme courant", async () => { + const { call, journal } = await setup(); + const session = { name: "Séance A allégée", exercises: [{ ref: "squat", sets: 3, reps: "8", rest: 90 }] }; + const r = await call("propose_session_change", { key: "A", session, reason: "Genou" }); + assert.equal(r.isError, false); + const proposed = /** @type {any} */ ((await journal()).at(-1)); + const sessions = proposed.data.program.sessions; + assert.equal(sessions.length, EXAMPLE_PROGRAM.sessions.length); + assert.deepEqual(sessions.find((/** @type {any} */ s) => s.key === "A"), { ...session, key: "A" }); + assert.deepEqual(sessions.filter((/** @type {any} */ s) => s.key !== "A"), EXAMPLE_PROGRAM.sessions.filter((s) => s.key !== "A")); + // Nouvelle clé : séance ajoutée. + await call("propose_session_change", { key: "Z", session, reason: "Une de plus" }); + assert.equal(/** @type {any} */ ((await journal()).at(-1)).data.program.sessions.length, EXAMPLE_PROGRAM.sessions.length + 1); + assert.equal((await call("propose_session_change", { key: "A", session: { ...session, key: "B" }, reason: "x" })).isError, true); + assert.equal((await call("propose_session_change", { key: "A", session: { name: "vide", exercises: [] }, reason: "x" })).isError, true); +}); + +test("propose_profile : le programme courant accompagné du nouveau profil ; sans programme, refusé", async () => { + const { call, journal } = await setup(); + const r = await call("propose_profile", { profile: { ...PROFILE, constraints: ["Épaule droite"] }, reason: "Blessure" }); + assert.equal(r.isError, false); + const proposed = /** @type {any} */ ((await journal()).at(-1)); + assert.deepEqual(proposed.data.program, EXAMPLE_PROGRAM); + assert.deepEqual(proposed.data.profile.constraints, ["Épaule droite"]); + + const empty = await setup([createEvent("WeightRecorded", { date: "2026-11-01", kg: 80 }, { device })]); + assert.match((await empty.call("propose_profile", { profile: PROFILE, reason: "x" })).text, /Aucun programme courant/); + assert.match((await empty.call("propose_session_change", { key: "A", session: {}, reason: "x" })).text, /Aucun programme courant/); + assert.equal((await empty.call("get_overview")).json.program, null); +}); + +test("de bout en bout en HTTP : jeton OAuth, outils, proposition déposée sur le relais", async () => { + const s = await startServer(); + try { + const syncKey = generateSyncKey(); + const keys = await deriveKeys(syncKey); + await push(s, keys.journalId, keys.authToken, await Promise.all(history().map((e) => encryptEvent(keys.encKey, e)))); + const { tokens } = await connect(s, syncKey); + assert.equal((await rpc(s, "faux", "tools/list")).error, "invalid_token"); + const overview = await rpc(s, tokens.access_token, "tools/call", { name: "get_overview", arguments: {} }); + assert.equal(JSON.parse(overview.result.content[0].text).program.name, EXAMPLE_PROGRAM.name); + const proposed = await rpc(s, tokens.access_token, "tools/call", { name: "propose_program", arguments: { program: EXAMPLE_PROGRAM, reason: "Test" } }); + assert.equal(proposed.result.isError, undefined); + const r = await s.fetch(`/api/journals/${keys.journalId}/events?after=${history().length}`, { headers: { authorization: "Bearer " + keys.authToken } }); + const { events } = await r.json(); + assert.equal(events.length, 1); + assert.equal(/** @type {any} */ (await decryptEvent(keys.encKey, events[0].blob)).type, "ProgramProposed"); + // Notification : 202 sans corps. + const n = await s.fetch("/mcp", { method: "POST", headers: { authorization: "Bearer " + tokens.access_token }, body: JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" }) }); + assert.equal(n.status, 202); + assert.equal((await s.fetch("/mcp", { headers: { authorization: "Bearer " + tokens.access_token } })).status, 405); + } finally { + await s.close(); + } +}); diff --git a/tests/server/oauth.test.js b/tests/server/oauth.test.js new file mode 100644 index 0000000..213dfbd --- /dev/null +++ b/tests/server/oauth.test.js @@ -0,0 +1,235 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { createOAuth, loadServerSecret, isAcceptableRedirect, TTL } from "../../server/oauth.js"; +import { deriveKeys, encryptEvent, generateSyncKey } from "../../app/domain/sync-crypto.js"; +import { startServer, push, pkce, connect, rpc } from "./helpers.js"; +import crypto from "node:crypto"; + +const REDIRECT = "https://claude.ai/api/mcp/auth_callback"; + +/** Un journal existant sur le relais, pour une clé neuve. @param {Awaited>} s */ +async function journal(s) { + const syncKey = generateSyncKey(); + const k = await deriveKeys(syncKey); + const event = { id: "w1", at: "2026-11-18T08:00:00.000Z", device: "pc", v: 1, type: "WeightRecorded", data: { date: "2026-11-18", kg: 80 } }; + assert.equal((await push(s, k.journalId, k.authToken, [await encryptEvent(k.encKey, event)])).status, 200); + return syncKey; +} + +/** @param {Awaited>} s @param {object} body */ +const authorize = (s, body) => s.fetch("/oauth/authorize", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + +/** @param {Awaited>} s @param {Record} form */ +const token = (s, form) => s.fetch("/oauth/token", { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" }, body: new URLSearchParams(form) }); + +/** @param {Awaited>} s */ +async function register(s, uris = [REDIRECT]) { + const r = await s.fetch("/oauth/register", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ client_name: "Claude", redirect_uris: uris }) }); + return { status: r.status, body: await r.json() }; +} + +test("métadonnées OAuth et ressource protégée, sur l'adresse publique", async () => { + const s = await startServer(); + try { + const as = await (await s.fetch("/.well-known/oauth-authorization-server")).json(); + assert.equal(as.issuer, s.publicUrl); + assert.equal(as.token_endpoint, s.publicUrl + "/oauth/token"); + assert.deepEqual(as.code_challenge_methods_supported, ["S256"]); + for (const p of ["/.well-known/oauth-protected-resource", "/.well-known/oauth-protected-resource/mcp"]) { + const pr = await (await s.fetch(p)).json(); + assert.equal(pr.resource, s.publicUrl + "/mcp"); + assert.deepEqual(pr.authorization_servers, [s.publicUrl]); + } + const r = await s.fetch("/mcp", { method: "POST" }); + assert.equal(r.status, 401); + assert.equal(r.headers.get("www-authenticate"), `Bearer resource_metadata="${s.publicUrl}/.well-known/oauth-protected-resource/mcp"`); + } finally { + await s.close(); + } +}); + +test("enregistrement sans état : le client survit à un redémarrage (même secret), un client falsifié est refusé", async () => { + const s = await startServer(); + try { + const { status, body } = await register(s); + assert.equal(status, 201); + assert.deepEqual(body.redirect_uris, [REDIRECT]); + assert.equal(body.token_endpoint_auth_method, "none"); + assert.equal(fs.readdirSync(s.dataDir).join(","), ".server-secret", "rien d'autre n'est écrit"); + assert.equal((fs.statSync(path.join(s.dataDir, ".server-secret")).mode & 0o777), 0o600); + + // « Redémarrage » : une nouvelle instance relit le même secret. + const again = createOAuth({ secret: loadServerSecret(s.dataDir) }); + assert.deepEqual(again.readClient(body.client_id)?.redirectUris, [REDIRECT]); + // Autre secret : inconnu. + assert.equal(createOAuth({ secret: crypto.randomBytes(32) }).readClient(body.client_id), null); + + // Client falsifié : adresses de retour changées sans la signature. + const [, mac] = body.client_id.split("."); + const forged = Buffer.from(JSON.stringify({ r: ["https://pirate.example/cb"], n: "Claude" })).toString("base64url") + "." + mac; + const { challenge } = pkce(); + const base = { redirect_uri: "https://pirate.example/cb", code_challenge: challenge, code_challenge_method: "S256", response_type: "code" }; + let r = await s.fetch("/oauth/authorize?" + new URLSearchParams({ ...base, client_id: forged })); + assert.equal(r.status, 400); + assert.match(await r.text(), /Client inconnu/); + // Vrai client, adresse non enregistrée : refus sans redirection. + r = await s.fetch("/oauth/authorize?" + new URLSearchParams({ ...base, client_id: body.client_id })); + assert.equal(r.status, 400); + assert.equal(r.headers.get("location"), null); + + assert.equal((await register(s, ["http://pirate.example/cb"])).status, 400, "http hors boucle locale refusé"); + assert.equal((await register(s, [])).status, 400); + } finally { + await s.close(); + } +}); + +test("adresses de retour acceptées : https, boucle locale, schéma d'application", () => { + assert.ok(isAcceptableRedirect("https://chatgpt.com/connector_platform_oauth_redirect")); + assert.ok(isAcceptableRedirect("http://localhost:33418/callback")); + assert.ok(isAcceptableRedirect("http://127.0.0.1/cb")); + assert.ok(isAcceptableRedirect("com.example.app:/cb")); + assert.ok(!isAcceptableRedirect("javascript:alert(1)")); + assert.ok(!isAcceptableRedirect("https://a.example/cb#x")); + assert.ok(!isAcceptableRedirect("http://a.example/cb")); +}); + +test("GET /oauth/authorize : vers la page de l'app ; sans PKCE S256, erreur renvoyée au client", async () => { + const s = await startServer(); + try { + const { body } = await register(s); + const { challenge } = pkce(); + const params = { client_id: body.client_id, redirect_uri: REDIRECT, response_type: "code", state: "xyz", code_challenge: challenge, code_challenge_method: "S256" }; + let r = await s.fetch("/oauth/authorize?" + new URLSearchParams(params)); + assert.equal(r.status, 302); + const location = r.headers.get("location") ?? ""; + assert.match(location, /^\/#\/connecter-ia\?/); + const forwarded = new URLSearchParams(location.split("?")[1]); + assert.equal(forwarded.get("client_id"), body.client_id); + assert.equal(forwarded.get("state"), "xyz"); + assert.equal(forwarded.get("client_name"), "Claude"); + + for (const changed of [{ code_challenge_method: "plain" }, { code_challenge: "" }]) { + r = await s.fetch("/oauth/authorize?" + new URLSearchParams({ ...params, ...changed })); + assert.equal(r.status, 302); + const back = new URL(r.headers.get("location") ?? ""); + assert.equal(back.origin + back.pathname, REDIRECT); + assert.equal(back.searchParams.get("error"), "invalid_request"); + assert.equal(back.searchParams.get("state"), "xyz"); + } + } finally { + await s.close(); + } +}); + +test("POST /oauth/authorize : PKCE obligatoire, clé valide et journal existant exigés, clé jamais renvoyée", async () => { + const s = await startServer(); + try { + const syncKey = await journal(s); + const { body: client } = await register(s); + const { challenge } = pkce(); + const ok = { client_id: client.client_id, redirect_uri: REDIRECT, state: "s", code_challenge: challenge, code_challenge_method: "S256", sync_key: syncKey }; + + const fails = [ + [{ code_challenge: undefined }, "invalid_request"], + [{ code_challenge_method: "plain" }, "invalid_request"], + [{ sync_key: "pas une clé" }, "invalid_sync_key"], + [{ sync_key: generateSyncKey() }, "unknown_journal"], + [{ redirect_uri: "https://ailleurs.example/cb" }, "invalid_request"], + ]; + for (const [change, error] of fails) { + const r = await authorize(s, { ...ok, ...change }); + const text = await r.text(); + assert.equal(r.status, 400, JSON.stringify(change)); + assert.equal(JSON.parse(text).error, error); + assert.ok(!text.includes(syncKey.slice(0, 9)), "la clé n'apparaît pas dans l'erreur"); + } + const r = await authorize(s, { ...ok, sync_key: syncKey.toLowerCase().replace(/-/g, " ") }); + assert.equal(r.status, 200); + const { redirect } = await r.json(); + const u = new URL(redirect); + assert.equal(u.origin + u.pathname, REDIRECT); + assert.equal(u.searchParams.get("state"), "s"); + assert.ok(!redirect.includes(syncKey.replace(/-/g, "").slice(0, 8)), "la clé est chiffrée dans le code"); + } finally { + await s.close(); + } +}); + +test("échange : code à usage unique, vérificateur PKCE exigé, rafraîchissement, jetons vers le MCP", async () => { + const s = await startServer(); + try { + const syncKey = await journal(s); + const { body: client } = await register(s); + const { verifier, challenge } = pkce(); + const r = await authorize(s, { client_id: client.client_id, redirect_uri: REDIRECT, code_challenge: challenge, code_challenge_method: "S256", sync_key: syncKey }); + const code = new URL((await r.json()).redirect).searchParams.get("code") ?? ""; + const form = { grant_type: "authorization_code", code, client_id: client.client_id, redirect_uri: REDIRECT }; + + let t = await token(s, form); + assert.equal(t.status, 400, "sans code_verifier"); + assert.equal((await t.json()).error, "invalid_grant"); + t = await token(s, { ...form, code_verifier: pkce().verifier }); + assert.equal(t.status, 400, "mauvais code_verifier"); + t = await token(s, { ...form, code_verifier: verifier, redirect_uri: "https://claude.ai/autre" }); + assert.equal(t.status, 400, "autre redirect_uri"); + t = await token(s, { ...form, code_verifier: verifier }); + assert.equal(t.status, 200); + const tokens = await t.json(); + assert.equal(tokens.token_type, "Bearer"); + assert.equal(tokens.expires_in, 3600); + t = await token(s, { ...form, code_verifier: verifier }); + assert.equal(t.status, 400, "code déjà utilisé"); + assert.match((await t.json()).error_description, /déjà utilisé/); + + // Le jeton d'accès ouvre le MCP ; un jeton de rafraîchissement, non. + assert.equal((await rpc(s, tokens.access_token, "ping")).result !== undefined, true); + assert.equal((await s.fetch("/mcp", { method: "POST", headers: { authorization: "Bearer " + tokens.refresh_token } })).status, 401); + + const refreshed = await token(s, { grant_type: "refresh_token", refresh_token: tokens.refresh_token, client_id: client.client_id }); + assert.equal(refreshed.status, 200); + const next = await refreshed.json(); + assert.ok((await rpc(s, next.access_token, "tools/list")).result.tools.length > 0); + // Rafraîchissement par un autre client : refusé. + const { body: other } = await register(s, ["https://chatgpt.com/connector_platform_oauth_redirect"]); + assert.equal((await token(s, { grant_type: "refresh_token", refresh_token: tokens.refresh_token, client_id: other.client_id })).status, 400); + assert.equal((await token(s, { grant_type: "password" })).status, 400); + } finally { + await s.close(); + } +}); + +test("jetons expirés : code après 5 min, accès après 1 h, rafraîchissement après 90 jours", () => { + let t = Date.parse("2026-11-18T10:00:00Z"); + const oauth = createOAuth({ secret: crypto.randomBytes(32), now: () => t }); + const { client_id } = oauth.register({ redirect_uris: [REDIRECT] }); + const { verifier, challenge } = pkce(); + const request = oauth.checkAuthorization({ client_id, redirect_uri: REDIRECT, code_challenge: challenge, code_challenge_method: "S256" }); + const key = generateSyncKey(); + const code = new URL(oauth.authorize(request, client_id, key)).searchParams.get("code") ?? ""; + t += TTL.codeMs + 1; + assert.throws(() => oauth.token({ grant_type: "authorization_code", code, code_verifier: verifier }), /expiré/); + t -= 2; + const tokens = oauth.token({ grant_type: "authorization_code", code, code_verifier: verifier }); + assert.equal(oauth.verifyAccess(tokens.access_token), key); + t += TTL.accessMs + 1; + assert.equal(oauth.verifyAccess(tokens.access_token), null); + assert.ok(oauth.token({ grant_type: "refresh_token", refresh_token: tokens.refresh_token }).access_token); + t += TTL.refreshMs; + assert.throws(() => oauth.token({ grant_type: "refresh_token", refresh_token: tokens.refresh_token }), /expiré/); + // Un jeton altéré ou d'une autre nature n'ouvre rien. + assert.equal(oauth.verifyAccess(tokens.refresh_token), null); + assert.equal(oauth.verifyAccess("abc"), null); +}); + +test("parcours complet en une fonction (helpers) : sert aux tests MCP", async () => { + const s = await startServer(); + try { + const { tokens } = await connect(s, await journal(s)); + assert.ok(tokens.access_token); + } finally { + await s.close(); + } +}); diff --git a/tests/server/relay.test.js b/tests/server/relay.test.js new file mode 100644 index 0000000..70bcc65 --- /dev/null +++ b/tests/server/relay.test.js @@ -0,0 +1,146 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { createRelay } from "../../server/relay.js"; +import { clientIp, createRateLimiter } from "../../server/rate-limit.js"; +import { startServer, push, auth } from "./helpers.js"; + +const ID = "ZgJsF_SV8W3E27y5p0AhMg"; +const TOKEN = "_NaCNrXbQlORkPj77TOhUThrbXoF740wNVYw9Djg8Z0"; +const blob = (/** @type {number} */ n) => "B".repeat(40) + String(n).padStart(4, "0").replace(/\d/g, (d) => "abcdefghij"[Number(d)]); + +const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "ia-fit-relay-")); + +test("relais : premier dépôt, lecture après un numéro, clé d'accès exigée ensuite", async () => { + const s = await startServer(); + try { + let r = await s.fetch(`/api/journals/${ID}/events`, { headers: auth(TOKEN) }); + assert.equal(r.status, 404, "journal inconnu avant le premier dépôt"); + r = await push(s, ID, TOKEN, [blob(1), blob(2)]); + assert.equal(r.status, 200); + assert.deepEqual(await r.json(), { last: 2, accepted: 2 }); + r = await push(s, ID, TOKEN, [blob(3)]); + assert.deepEqual(await r.json(), { last: 3, accepted: 1 }); + + r = await s.fetch(`/api/journals/${ID}/events?after=1`, { headers: auth(TOKEN) }); + assert.deepEqual(await r.json(), { events: [{ seq: 2, blob: blob(2) }, { seq: 3, blob: blob(3) }], last: 3, more: false }); + r = await s.fetch(`/api/journals/${ID}/events?after=3`, { headers: auth(TOKEN) }); + assert.deepEqual(await r.json(), { events: [], last: 3, more: false }); + + // Sans clé, avec une autre clé : refusé, en lecture comme en écriture. + assert.equal((await s.fetch(`/api/journals/${ID}/events`)).status, 401); + assert.equal((await s.fetch(`/api/journals/${ID}/events`, { headers: auth("autre-cle") })).status, 403); + assert.equal((await push(s, ID, "autre-cle", [blob(4)])).status, 403); + assert.equal((await s.fetch(`/api/journals/${ID}/events?after=-1`, { headers: auth(TOKEN) })).status, 400); + + // Sur disque : un en-tête (empreinte, jamais la clé) puis une ligne par bloc. + const text = fs.readFileSync(path.join(s.dataDir, "journals", ID + ".jsonl"), "utf8"); + const lines = text.trim().split("\n").map((l) => JSON.parse(l)); + assert.equal(lines.length, 4); + assert.match(lines[0].auth, /^[0-9a-f]{64}$/); + assert.ok(!text.includes(TOKEN)); + assert.deepEqual(lines[3], { seq: 3, blob: blob(3) }); + } finally { + await s.close(); + } +}); + +test("relais : quotas (bloc, nombre de blocs, taille du journal) et blocs mal formés", async () => { + const s = await startServer({ limits: { blobBytes: 100, blobsPerRequest: 3, journalBytes: 400 } }); + try { + const bad = async (/** @type {unknown} */ body, /** @type {number} */ status, /** @type {string} */ error) => { + const r = await s.fetch(`/api/journals/${ID}/events`, { method: "POST", headers: auth(TOKEN), body: JSON.stringify(body) }); + assert.equal(r.status, status, error); + assert.equal((await r.json()).error, error); + }; + await bad(["x".repeat(101)], 413, "blob_too_large"); + await bad([blob(1), blob(2), blob(3), blob(4)], 413, "too_many_blobs"); + await bad([], 400, "invalid_request"); + await bad(["pas du base64 !"], 400, "invalid_blob"); + await bad({ blob: blob(1) }, 400, "invalid_request"); + assert.equal((await push(s, ID, TOKEN, [blob(1), blob(2), blob(3)])).status, 200); + await bad([blob(4), blob(5), blob(6)], 413, "journal_full"); + assert.equal((await s.fetch("/api/journals/court/events", { headers: auth(TOKEN) })).status, 404); + } finally { + await s.close(); + } +}); + +test("relais : écritures concurrentes sérialisées, numéros continus", async () => { + const relay = createRelay(tmp()); + await Promise.all(Array.from({ length: 20 }, (_, i) => relay.append(ID, TOKEN, [blob(i), blob(100 + i)]))); + const { events, last } = await relay.read(ID, TOKEN, 0); + assert.equal(last, 40); + assert.deepEqual(events.map((e) => e.seq), Array.from({ length: 40 }, (_, i) => i + 1)); +}); + +test("relais : lecture par pages, ligne incomplète réparée au chargement", async () => { + const dir = tmp(); + const relay = createRelay(dir, { limits: { blobsPerRead: 2 } }); + await relay.append(ID, TOKEN, [blob(1), blob(2), blob(3)]); + let page = await relay.read(ID, TOKEN, 0); + assert.deepEqual([page.events.map((e) => e.seq), page.more], [[1, 2], true]); + page = await relay.read(ID, TOKEN, 2); + assert.deepEqual([page.events.map((e) => e.seq), page.more], [[3], false]); + + // Arrêt brutal au milieu d'une écriture : la ligne coupée est retirée. + fs.appendFileSync(path.join(dir, "journals", ID + ".jsonl"), '{"seq":4,"bl'); + const reopened = createRelay(dir); + assert.equal((await reopened.read(ID, TOKEN, 0)).last, 3); + assert.deepEqual(await reopened.append(ID, TOKEN, [blob(4)]), { last: 4, accepted: 1 }); + assert.equal((await createRelay(dir).read(ID, TOKEN, 3)).events[0].blob, blob(4)); +}); + +test("relais : effacement des journaux inactifs depuis 400 jours, une lecture compte comme activité", async () => { + const dir = tmp(); + let t = Date.parse("2026-01-01T00:00:00Z"); + const relay = createRelay(dir, { now: () => t }); + const other = "AAAAAAAAAAAAAAAAAAAAAA"; + await relay.append(ID, TOKEN, [blob(1)]); + await relay.append(other, TOKEN, [blob(1)]); + const file = (/** @type {string} */ id) => path.join(dir, "journals", id + ".jsonl"); + const old = new Date(t - 401 * 864e5); + fs.utimesSync(file(ID), old, old); + fs.utimesSync(file(other), old, old); + t += 2 * 864e5; + await relay.read(other, TOKEN, 0); // lu : redevient actif + assert.equal(await relay.purgeInactive(), 1); + assert.equal(fs.existsSync(file(ID)), false); + assert.equal(fs.existsSync(file(other)), true); + assert.equal(await relay.owns(ID, TOKEN), false); +}); + +test("adresse du client : X-Real-IP, sinon le DERNIER élément de X-Forwarded-For", () => { + const req = (/** @type {Record} */ headers) => /** @type {any} */ ({ headers, socket: { remoteAddress: "10.0.0.1" } }); + assert.equal(clientIp(req({ "x-real-ip": "203.0.113.7", "x-forwarded-for": "1.1.1.1, 203.0.113.7" })), "203.0.113.7"); + assert.equal(clientIp(req({ "x-forwarded-for": "1.1.1.1, 2.2.2.2, 203.0.113.7" })), "203.0.113.7", "le début est inventé par le client"); + assert.equal(clientIp(req({})), "10.0.0.1"); +}); + +test("limite de requêtes : par adresse, en fenêtre, et non contournable par un faux X-Forwarded-For", async () => { + let t = 0; + const limiter = createRateLimiter({ max: 2, windowMs: 1000, now: () => t }); + assert.equal(limiter.hit("a"), 0); + assert.equal(limiter.hit("a"), 0); + assert.equal(limiter.hit("a"), 1); + assert.equal(limiter.hit("b"), 0); + t = 1000; + assert.equal(limiter.hit("a"), 0); + + const s = await startServer({ rate: { max: 3, windowMs: 60e3 } }); + try { + const statuses = []; + for (let i = 0; i < 5; i++) { + // Le client change le début de X-Forwarded-For ; le proxy ajoute sa vraie adresse à la fin. + const r = await s.fetch("/.well-known/oauth-authorization-server", { headers: { "x-forwarded-for": `9.9.9.${i}, 203.0.113.7` } }); + statuses.push(r.status); + } + assert.deepEqual(statuses, [200, 200, 200, 429, 429]); + // Le site statique n'est pas limité. + assert.equal((await s.fetch("/", { headers: { "x-forwarded-for": "203.0.113.7" } })).status, 200); + } finally { + await s.close(); + } +}); diff --git a/tests/server/static.test.js b/tests/server/static.test.js new file mode 100644 index 0000000..35e3e6c --- /dev/null +++ b/tests/server/static.test.js @@ -0,0 +1,71 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import zlib from "node:zlib"; +import { CSP } from "../../server/http.js"; +import { pickEncoding } from "../../server/static.js"; +import { startServer } from "./helpers.js"; + +test("site : types MIME, en-têtes du lot 1, revalidation", async () => { + const s = await startServer(); + try { + for (const [p, type] of [["/", "text/html; charset=utf-8"], ["/app.js", "text/javascript; charset=utf-8"], ["/ia.md", "text/markdown; charset=utf-8"], ["/police.woff2", "font/woff2"]]) { + const r = await s.fetch(p); + assert.equal(r.status, 200, p); + assert.equal(r.headers.get("content-type"), type, p); + assert.equal(r.headers.get("content-security-policy"), CSP); + assert.equal(r.headers.get("x-content-type-options"), "nosniff"); + assert.equal(r.headers.get("referrer-policy"), "no-referrer"); + assert.equal(r.headers.get("cache-control"), "no-cache"); + } + const first = await s.fetch("/app.js", { headers: { "accept-encoding": "identity" } }); + const etag = first.headers.get("etag") ?? ""; + assert.equal((await s.fetch("/app.js", { headers: { "if-none-match": etag, "accept-encoding": "identity" } })).status, 304); + // Les API ne sont jamais mises en cache. + assert.equal((await s.fetch("/.well-known/oauth-authorization-server")).headers.get("cache-control"), "no-store"); + } finally { + await s.close(); + } +}); + +test("site : compression zstd ou gzip des textes, pas des polices", async () => { + const s = await startServer(); + try { + const raw = fs.readFileSync(path.join(s.siteDir, "app.js")); + // fetch décompresse de lui-même : on lit donc les en-têtes, puis le contenu par node:http. + const http = await import("node:http"); + /** @param {string} p @param {string} enc */ + const get = (p, enc) => new Promise((resolve) => http.get(s.base + p, { headers: { "accept-encoding": enc } }, (res) => { + /** @type {Buffer[]} */ const chunks = []; + res.on("data", (c) => chunks.push(c)); + res.on("end", () => resolve({ headers: res.headers, body: Buffer.concat(chunks) })); + })); + const z = /** @type {any} */ (await get("/app.js", "gzip, deflate, br, zstd")); + assert.equal(z.headers["content-encoding"], "zstd"); + assert.deepEqual(zlib.zstdDecompressSync(z.body), raw); + const g = /** @type {any} */ (await get("/app.js", "gzip")); + assert.equal(g.headers["content-encoding"], "gzip"); + assert.deepEqual(zlib.gunzipSync(g.body), raw); + const f = /** @type {any} */ (await get("/police.woff2", "gzip")); + assert.equal(f.headers["content-encoding"], undefined); + assert.equal(pickEncoding("gzip;q=0, zstd;q=0"), null); + assert.equal(pickEncoding("*"), "zstd"); + assert.equal(pickEncoding(undefined), null); + } finally { + await s.close(); + } +}); + +test("site : 404 pour l'absent, les fichiers cachés et les remontées ; méthodes limitées", async () => { + const s = await startServer(); + try { + fs.writeFileSync(path.join(s.siteDir, ".cache"), "secret"); + for (const p of ["/absent.html", "/.cache", "/%2e%2e/data/.server-secret", "/..%2fdata%2f.server-secret"]) + assert.equal((await s.fetch(p)).status, 404, p); + assert.equal((await s.fetch("/", { method: "POST" })).status, 405); + assert.equal((await s.fetch("/app.js", { method: "HEAD" })).status, 200); + } finally { + await s.close(); + } +}); From 86bf709da3aba103929f6bfd5af31a79055281f0 Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Wed, 18 Nov 2026 05:12:06 +0100 Subject: [PATCH 05/10] Synchro du navigateur avec le relais (app/infra/sync.js) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ajoute getMeta et setMeta au magasin IndexedDB pour garder l'état de la synchro. Co-Authored-By: Claude Opus 5.5 --- app/infra/event-store.js | 21 +++++ app/infra/sync.js | 184 ++++++++++++++++++++++++++++++++++++++ tests/server/sync.test.js | 106 ++++++++++++++++++++++ 3 files changed, 311 insertions(+) create mode 100644 app/infra/sync.js create mode 100644 tests/server/sync.test.js diff --git a/app/infra/event-store.js b/app/infra/event-store.js index 30df68c..1dca54c 100644 --- a/app/infra/event-store.js +++ b/app/infra/event-store.js @@ -9,6 +9,7 @@ // relit en entier et se replie en mémoire. // - Magasin `meta` : réglages de l'appareil, clés explicites (sans keyPath). // « deviceId » : identifiant aléatoire de l'appareil (UUID v4), créé une fois. +// « sync: » : état de la synchro avec le relais (app/infra/sync.js). // // Ce module ne valide pas les événements : l'appelant le fait (createEvent, // readImport). Les événements invalides déjà stockés sont gardés (foldEvents les @@ -109,6 +110,26 @@ export async function openEventStore(dbName = "ia-fit") { return id; }, + /** + * Lit un réglage de l'appareil (magasin `meta`), ou undefined. + * @param {string} key + * @returns {Promise} + */ + async getMeta(key) { + return done(db.transaction("meta").objectStore("meta").get(key)); + }, + + /** + * Écrit un réglage de l'appareil (magasin `meta`). + * @param {string} key + * @param {unknown} value clonable (structuredClone) + */ + async setMeta(key, value) { + const tx = db.transaction("meta", "readwrite"); + tx.objectStore("meta").put(value, key); + await committed(tx); + }, + /** Ferme la base (tests, changement de clé). */ close() { db.close(); diff --git a/app/infra/sync.js b/app/infra/sync.js new file mode 100644 index 0000000..28a649e --- /dev/null +++ b/app/infra/sync.js @@ -0,0 +1,184 @@ +// Synchro avec le relais chiffré (ADR 0005, point 3), côté navigateur. +// +// Chaque événement est chiffré un par un avec la clé tirée de la clé de synchro, +// envoyé au relais, et les événements des autres appareils (et de l'IA) sont +// récupérés puis fusionnés par union (ADR 0006). Le relais ne voit que des blocs. +// +// État gardé dans le magasin `meta` (clé « sync: ») : +// - `lastSeq` : dernier numéro d'ordre lu sur le relais ; +// - `known` : identifiants des événements que le relais a déjà (lus, ou +// envoyés avec succès). Un événement local absent de cette liste est à envoyer. +// Un envoi dont la réponse se perd est refait : le relais reçoit alors deux blocs +// du même événement, que la fusion par union dédoublonne. +// +// MODE D'EMPLOI POUR L'INTERFACE +// const sync = createSync({ store, syncKey }); // store : openEventStore() +// const { pushed, pulled, ignored } = await sync.sync(); +// - à l'ouverture de l'app (si une clé de synchro est enregistrée) ; +// - après chaque événement local, avec un délai (2 à 5 s, regroupé : plusieurs +// saisies rapprochées donnent une seule synchro) ; +// - au retour du réseau (événement `online`) et au retour sur l'onglet +// (`visibilitychange` vers visible). +// Après un `pulled > 0`, recharger l'état depuis store.list(). sync() n'en +// lance jamais deux à la fois : un appel pendant une synchro attend la même. +// Erreurs : SyncError, avec `code` : +// - "offline" (réseau absent : réessayer plus tard, sans alerte) ; +// - "forbidden" (le relais refuse la clé d'accès : journal pris par une autre +// clé, cas anormal) ; "journal_full", "rate_limited", "server". +// Appariement d'un nouvel appareil : `await sync.pull()` d'abord ; `exists` +// false signale une clé qui ne correspond à aucun journal (faute de frappe ?) +// avant que le premier envoi ne crée un journal neuf. + +import { validateEvent } from "../domain/events.js"; +import { deriveKeys, decryptEvent, encryptEvent } from "../domain/sync-crypto.js"; + +/** @typedef {import("../domain/events.js").DomainEvent} DomainEvent */ + +/** Événements par envoi (le relais en accepte 500, et 4 Mo par requête). */ +const PUSH_BATCH = 100; +const PUSH_BATCH_BYTES = 2 * 1024 * 1024; + +export class SyncError extends Error { + /** @param {string} code @param {string} message @param {number} [status] */ + constructor(code, message, status) { + super(message); + this.name = "SyncError"; + this.code = code; + this.status = status; + } +} + +/** + * @typedef {object} SyncStore ce que la synchro utilise de openEventStore() + * @property {() => Promise} list + * @property {(events: readonly DomainEvent[]) => Promise} add + * @property {(key: string) => Promise} getMeta + * @property {(key: string, value: unknown) => Promise} setMeta + */ + +/** + * @param {{store: SyncStore, syncKey: string, baseUrl?: string, fetch?: typeof fetch}} options + * baseUrl : adresse du serveur, vide pour la même origine + */ +export function createSync({ store, syncKey, baseUrl = "", fetch: doFetch = globalThis.fetch.bind(globalThis) }) { + const keysPromise = deriveKeys(syncKey); + /** @type {Promise<{pushed: number, pulled: number, ignored: number}>|null} */ + let running = null; + + async function context() { + const keys = await keysPromise; + const metaKey = "sync:" + keys.journalId; + const saved = /** @type {{lastSeq?: number, known?: string[]}|undefined} */ (await store.getMeta(metaKey)); + const state = { lastSeq: saved?.lastSeq ?? 0, known: new Set(saved?.known ?? []) }; + const save = () => store.setMeta(metaKey, { lastSeq: state.lastSeq, known: [...state.known] }); + const url = `${baseUrl.replace(/\/+$/, "")}/api/journals/${keys.journalId}/events`; + return { keys, state, save, url }; + } + + /** + * @param {string} url + * @param {RequestInit} init + */ + async function request(url, init) { + let res; + try { + res = await doFetch(url, init); + } catch { + throw new SyncError("offline", "Relais injoignable : la synchro reprendra au retour du réseau."); + } + if (res.ok || res.status === 404) return res; + const body = await res.json().catch(() => ({})); + const code = res.status === 403 ? "forbidden" : res.status === 429 ? "rate_limited" : body.error === "journal_full" ? "journal_full" : "server"; + throw new SyncError(code, body.error_description ?? `Relais : erreur ${res.status}.`, res.status); + } + + /** + * Envoie les événements que le relais n'a pas encore. + * @param {readonly DomainEvent[]} events + * @returns {Promise} nombre d'événements envoyés + */ + async function push(events) { + const { keys, state, save, url } = await context(); + const todo = events.filter((e) => !state.known.has(e.id)); + let sent = 0; + while (sent < todo.length) { + const batch = []; + const blobs = []; + let bytes = 0; + for (const e of todo.slice(sent, sent + PUSH_BATCH)) { + const blob = await encryptEvent(keys.encKey, e); + if (blobs.length && bytes + blob.length > PUSH_BATCH_BYTES) break; + batch.push(e); + blobs.push(blob); + bytes += blob.length; + } + await request(url, { + method: "POST", + headers: { authorization: "Bearer " + keys.authToken, "content-type": "application/json" }, + body: JSON.stringify(blobs), + }); + for (const e of batch) state.known.add(e.id); + await save(); + sent += batch.length; + } + return sent; + } + + /** + * Récupère les événements déposés depuis la dernière lecture, les déchiffre, + * les valide et ajoute les valides au magasin. + * @returns {Promise<{events: DomainEvent[], added: number, ignored: number, exists: boolean}>} + * events : événements valides lus ; added : ceux qui manquaient au magasin ; + * ignored : blocs illisibles ou invalides ; + * exists : false si aucun journal ne correspond encore à cette clé + */ + async function pull() { + const { keys, state, save, url } = await context(); + /** @type {DomainEvent[]} */ + const events = []; + let ignored = 0; + let added = 0; + for (;;) { + const res = await request(`${url}?after=${state.lastSeq}`, { headers: { authorization: "Bearer " + keys.authToken } }); + if (res.status === 404) return { events, added, ignored, exists: false }; + const page = /** @type {{events: {seq: number, blob: string}[], last: number, more: boolean}} */ (await res.json()); + /** @type {DomainEvent[]} */ + const valid = []; + for (const { blob } of page.events) { + try { + const e = await decryptEvent(keys.encKey, blob); + if (validateEvent(e) === null) valid.push(/** @type {DomainEvent} */ (e)); + else ignored++; + } catch { + ignored++; + } + } + if (valid.length) added += await store.add(valid); + for (const e of valid) state.known.add(e.id); + events.push(...valid); + if (page.events.length) state.lastSeq = page.events[page.events.length - 1].seq; + await save(); + if (!page.more || !page.events.length) break; + } + return { events, added, ignored, exists: true }; + } + + /** + * Lit d'abord (ce que le relais a déjà n'est pas renvoyé), puis envoie. + * @returns {Promise<{pushed: number, pulled: number, ignored: number}>} + */ + function sync() { + running ??= (async () => { + try { + const { added, ignored } = await pull(); + const pushed = await push(await store.list()); + return { pushed, pulled: added, ignored }; + } finally { + running = null; + } + })(); + return running; + } + + return { push, pull, sync }; +} diff --git a/tests/server/sync.test.js b/tests/server/sync.test.js new file mode 100644 index 0000000..da3cb31 --- /dev/null +++ b/tests/server/sync.test.js @@ -0,0 +1,106 @@ +// app/infra/sync.js contre le vrai serveur, avec un magasin en mémoire qui +// imite openEventStore() (list, add, getMeta, setMeta). +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { createSync, SyncError } from "../../app/infra/sync.js"; +import { createEvent, compareEvents } from "../../app/domain/events.js"; +import { deriveKeys, encryptEvent, generateSyncKey } from "../../app/domain/sync-crypto.js"; +import { startServer, push } from "./helpers.js"; + +function memoryStore() { + /** @type {Map} */ + const events = new Map(); + /** @type {Map} */ + const meta = new Map(); + return { + async list() { return [...events.values()].sort(compareEvents); }, + /** @param {readonly any[]} list */ + async add(list) { + let n = 0; + for (const e of list) if (!events.has(e.id)) { events.set(e.id, e); n++; } + return n; + }, + /** @param {string} k */ + async getMeta(k) { return structuredClone(meta.get(k)); }, + /** @param {string} k @param {unknown} v */ + async setMeta(k, v) { meta.set(k, structuredClone(v)); }, + meta, + }; +} + +/** @param {string} device @param {string} date @param {number} kg */ +const weight = (device, date, kg) => createEvent("WeightRecorded", { date, kg }, { device, at: date + "T07:00:00.000Z" }); + +test("deux appareils : chacun envoie les siens et reçoit ceux de l'autre, sans doublon", async () => { + const s = await startServer(); + try { + const syncKey = generateSyncKey(); + const pc = memoryStore(); + const phone = memoryStore(); + await pc.add([weight("pc", "2026-11-01", 80), weight("pc", "2026-11-02", 79.8)]); + const syncPc = createSync({ store: pc, syncKey, baseUrl: s.base }); + const syncPhone = createSync({ store: phone, syncKey, baseUrl: s.base }); + + // Le téléphone, avant tout dépôt : la clé ne correspond à aucun journal. + assert.equal((await syncPhone.pull()).exists, false); + assert.deepEqual(await syncPc.sync(), { pushed: 2, pulled: 0, ignored: 0 }); + assert.deepEqual(await syncPc.sync(), { pushed: 0, pulled: 0, ignored: 0 }, "rien de nouveau"); + + await phone.add([weight("phone", "2026-11-03", 79.5)]); + assert.deepEqual(await syncPhone.sync(), { pushed: 1, pulled: 2, ignored: 0 }); + assert.deepEqual(await syncPc.sync(), { pushed: 0, pulled: 1, ignored: 0 }); + assert.deepEqual((await pc.list()).map((e) => e.id), (await phone.list()).map((e) => e.id)); + assert.equal((await pc.list()).length, 3); + + // L'état est gardé dans meta, par journal. + const { journalId } = await deriveKeys(syncKey); + const saved = /** @type {any} */ (pc.meta.get("sync:" + journalId)); + assert.equal(saved.lastSeq, 3); + assert.equal(saved.known.length, 3); + + // Une nouvelle instance (rechargement de la page) reprend où elle en était. + assert.deepEqual(await createSync({ store: pc, syncKey, baseUrl: s.base }).sync(), { pushed: 0, pulled: 0, ignored: 0 }); + } finally { + await s.close(); + } +}); + +test("blocs illisibles ou événements invalides : ignorés et comptés", async () => { + const s = await startServer(); + try { + const syncKey = generateSyncKey(); + const k = await deriveKeys(syncKey); + const intruder = await deriveKeys(generateSyncKey()); + await push(s, k.journalId, k.authToken, [ + await encryptEvent(k.encKey, weight("pc", "2026-11-01", 80)), + await encryptEvent(k.encKey, { id: "x", type: "WeightRecorded", data: {} }), + await encryptEvent(intruder.encKey, weight("pc", "2026-11-02", 80)), + ]); + const store = memoryStore(); + const r = await createSync({ store, syncKey, baseUrl: s.base }).pull(); + assert.deepEqual([r.events.length, r.added, r.ignored, r.exists], [1, 1, 2, true]); + assert.equal((await store.list()).length, 1); + } finally { + await s.close(); + } +}); + +test("erreurs : réseau absent, clé d'accès refusée ; un seul sync() à la fois", async () => { + const store = memoryStore(); + await store.add([weight("pc", "2026-11-01", 80)]); + const offline = createSync({ store, syncKey: generateSyncKey(), fetch: async () => { throw new TypeError("Failed to fetch"); } }); + await assert.rejects(offline.sync(), (e) => e instanceof SyncError && e.code === "offline"); + + const forbidden = createSync({ store, syncKey: generateSyncKey(), fetch: async () => new Response(JSON.stringify({ error: "forbidden" }), { status: 403 }) }); + await assert.rejects(forbidden.pull(), (e) => e instanceof SyncError && e.code === "forbidden"); + + let calls = 0; + const slow = createSync({ + store, syncKey: generateSyncKey(), + fetch: async () => { calls++; return new Response(JSON.stringify({ last: 1, accepted: 1, events: [], more: false }), { status: 200 }); }, + }); + const [a, b] = [slow.sync(), slow.sync()]; + assert.equal(a, b, "le même appel en cours est rendu"); + await a; + assert.equal(calls, 2, "une lecture, un envoi"); +}); From 237fa8b8e48f02cf0aa8f08cb78dc24ca8cb03e9 Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Wed, 18 Nov 2026 05:13:59 +0100 Subject: [PATCH 06/10] =?UTF-8?q?Image=20Node=20=C3=A0=20la=20place=20de?= =?UTF-8?q?=20Caddy,=20make=20serve,=20types=20de=20Node=20pour=20le=20lin?= =?UTF-8?q?t=20du=20serveur?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- Makefile | 34 +++++++++++++++++++------ app/domain/sync-crypto.js | 4 +-- deploy/Caddyfile | 51 -------------------------------------- deploy/Dockerfile | 31 +++++++++++++++++------ server/static.js | 1 + tests/server/oauth.test.js | 1 + tsconfig.server.json | 9 +++++++ 7 files changed, 63 insertions(+), 68 deletions(-) delete mode 100644 deploy/Caddyfile create mode 100644 tsconfig.server.json diff --git a/Makefile b/Makefile index df8ffd2..db66f83 100644 --- a/Makefile +++ b/Makefile @@ -8,9 +8,16 @@ SHELL := bash TYPESCRIPT_VERSION := 5.9.2 TOOLS := build/tools TSC := $(TOOLS)/node_modules/.bin/tsc +# Types de Node pour vérifier server/ (même version majeure que Node 24 de +# l'image de production). Outil de développement seulement. MIT. +TYPES_NODE_VERSION := 24.10.1 +TYPES_NODE := $(TOOLS)/node_modules/@types/node/package.json # Analyse des scripts shell, dans Docker pour ne rien installer sur le PC. SHELLCHECK_IMAGE := koalaman/shellcheck:v0.10.0 DEV_PORT := 8080 +# make serve : le serveur de production (server/) sur le site assemblé. +SERVE_PORT := 3000 +SERVE_DATA := build/data # Publication (lot 1f, docs/deploiement.md). APP_DIR et SITE_BUILD peuvent être # changés à l'appel : tests/test_site.sh assemble ainsi son site d'essai hors de @@ -22,22 +29,26 @@ SITE := $(SITE_BUILD)/site # d'éditeur. SITE_EXCLUDE := .[!./]* *.test.js *~ *.swp *.orig -.PHONY: help setup dev test test-docs test-unit test-site lint site package deploy-prod +.PHONY: help setup dev serve test test-docs test-unit test-site lint site package deploy-prod help: ## Liste les commandes disponibles @echo "IA-Fit : commandes disponibles" @grep -E '^[a-zA-Z0-9_-]+:.*## ' $(MAKEFILE_LIST) \ | awk 'BEGIN { FS = ":.*## " } { printf " make %-14s %s\n", $$1, $$2 }' -setup: $(TSC) ## Installe les outils de développement (idempotent) +setup: $(TSC) $(TYPES_NODE) ## Installe les outils de développement (idempotent) -$(TSC): - npm install --silent --no-audit --no-fund --prefix $(TOOLS) typescript@$(TYPESCRIPT_VERSION) +$(TSC) $(TYPES_NODE) &: + npm install --silent --no-audit --no-fund --prefix $(TOOLS) typescript@$(TYPESCRIPT_VERSION) @types/node@$(TYPES_NODE_VERSION) dev: ## Sert l'app en local sur le port 8080 (Ctrl+C pour arrêter) @echo "App : http://localhost:$(DEV_PORT)/" @python3 -m http.server $(DEV_PORT) --directory app +serve: site ## Lance le serveur de production (relais, OAuth, MCP) sur build/site, port 3000 + @echo "Serveur : http://localhost:$(SERVE_PORT)/ (données dans $(SERVE_DATA))" + @PORT=$(SERVE_PORT) SITE_DIR=$(SITE) DATA_DIR=$(SERVE_DATA) PUBLIC_URL=http://localhost:$(SERVE_PORT) node server/main.js + test: test-docs test-unit ## Lance tous les tests (dont test-site si Docker répond) @if docker info >/dev/null 2>&1; then $(MAKE) --no-print-directory test-site; \ else echo "test-site sauté : Docker indisponible, l'image de production n'est pas vérifiée."; fi @@ -48,9 +59,10 @@ test-docs: ## Vérifie la forme des ADR et du glossaire test-unit: ## Tests du domaine et de l'architecture (node --test) @node --test 'tests/**/*.test.js' -lint: $(TSC) ## Vérifie les types (JSDoc), la syntaxe et les scripts shell +lint: $(TSC) $(TYPES_NODE) ## Vérifie les types (JSDoc), la syntaxe et les scripts shell @$(TSC) -p tsconfig.json - @for f in $$(find app tests -name '*.js'); do node --check "$$f" || exit 1; done + @$(TSC) -p tsconfig.server.json + @for f in $$(find app server tests -name '*.js'); do node --check "$$f" || exit 1; done @if command -v shellcheck >/dev/null; then shellcheck scripts/*.sh tests/*.sh; \ else docker run --rm -v "$(CURDIR):/mnt:ro" -w /mnt $(SHELLCHECK_IMAGE) scripts/*.sh tests/*.sh; fi @echo "Lint : OK" @@ -73,12 +85,18 @@ site: ## Assemble le site publié dans build/site/ @scripts/service-worker.sh "$(SITE)" @echo "Site assemblé : $(SITE)/ ($$(find "$(SITE)" -type f | wc -l) fichiers)" -# L'archive envoyée à CapRover : captain-definition, Dockerfile, Caddyfile et -# le site. CapRover construit l'image (une simple copie) sur le serveur. +# L'archive envoyée à CapRover : captain-definition, Dockerfile, le site, le +# serveur (server/), le domaine dont il dépend (app/domain/) et package.json +# (modules ES), sans les fichiers exclus du site. CapRover construit l'image +# (une simple copie) sur le serveur. package: site ## Prépare l'archive de déploiement build/ia-fit.tar @rm -rf -- "$(SITE_BUILD)/deploy" @cp -r deploy "$(SITE_BUILD)/deploy" @cp -r "$(SITE)" "$(SITE_BUILD)/deploy/site" + @mkdir -p "$(SITE_BUILD)/deploy/server" "$(SITE_BUILD)/deploy/app/domain" + @tar -C server $(foreach p,$(SITE_EXCLUDE),--exclude='$(p)') -cf - . | tar -C "$(SITE_BUILD)/deploy/server" -xf - + @tar -C "$(APP_DIR)/domain" $(foreach p,$(SITE_EXCLUDE),--exclude='$(p)') -cf - . | tar -C "$(SITE_BUILD)/deploy/app/domain" -xf - + @cp package.json "$(SITE_BUILD)/deploy/package.json" @tar -cf "$(SITE_BUILD)/ia-fit.tar" -C "$(SITE_BUILD)/deploy" . @echo "Archive prête : $(SITE_BUILD)/ia-fit.tar" diff --git a/app/domain/sync-crypto.js b/app/domain/sync-crypto.js index f7bc728..9802c54 100644 --- a/app/domain/sync-crypto.js +++ b/app/domain/sync-crypto.js @@ -55,7 +55,7 @@ function toBase32(bytes) { return out; } -/** @param {string} text 26 caractères de l'alphabet @returns {Uint8Array|null} */ +/** @param {string} text 26 caractères de l'alphabet @returns {Uint8Array|null} */ function fromBase32(text) { const out = new Uint8Array(KEY_BYTES); let bits = 0, value = 0, i = 0; @@ -173,7 +173,7 @@ export function toBase64url(bytes) { return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } -/** @param {string} text @returns {Uint8Array|null} */ +/** @param {string} text @returns {Uint8Array|null} */ export function fromBase64url(text) { if (!/^[A-Za-z0-9_-]*$/.test(text) || text.length % 4 === 1) return null; const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/") + "=".repeat((4 - (text.length % 4)) % 4)); diff --git a/deploy/Caddyfile b/deploy/Caddyfile deleted file mode 100644 index d217aba..0000000 --- a/deploy/Caddyfile +++ /dev/null @@ -1,51 +0,0 @@ -# Serveur statique d'IA-Fit. CapRover fournit le HTTPS devant ; ici on écoute -# en HTTP sur le port 80 du conteneur. -{ - admin off - auto_https off -} - -:80 { - root * /srv - # Types compressés : les textes (HTML, CSS, JavaScript, JSON, manifeste, - # SVG). Les polices woff2 et les images PNG le sont déjà. - encode { - zstd - gzip - match { - header Content-Type text/* - header Content-Type application/json* - header Content-Type application/manifest+json* - header Content-Type image/svg+xml* - } - } - - # Les noms de fichiers ne changent pas d'une version à l'autre : le - # navigateur revalide chaque fichier (ETag) au lieu de garder une copie - # périmée. Le service worker (sw.js) porte la version du site. - header Cache-Control "no-cache" - header X-Content-Type-Options "nosniff" - header Referrer-Policy "no-referrer" - - # Politique de sécurité du contenu : tout vient du site lui-même, aucun - # script ni style en ligne, ni eval, ni WebAssembly ; les images data: - # sont permises (QR code généré dans le navigateur, lot 2). L'en-tête - # s'applique aussi au service worker. - header Content-Security-Policy "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; worker-src 'self'; manifest-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" - - # Types MIME fixés ici plutôt que devinés d'après la table du système de - # l'image : avec nosniff, un module ES servi sous un autre type ne se - # charge pas. - @javascript path *.js *.mjs - header @javascript Content-Type "text/javascript; charset=utf-8" - @manifest path *.webmanifest - header @manifest Content-Type "application/manifest+json" - @woff2 path *.woff2 - header @woff2 Content-Type "font/woff2" - # Textes lus par une IA qui navigue (ia.md, prompt d'accueil) : du - # Markdown en UTF-8, affiché tel quel par un navigateur. - @markdown path *.md - header @markdown Content-Type "text/markdown; charset=utf-8" - - file_server -} diff --git a/deploy/Dockerfile b/deploy/Dockerfile index 2e35336..0a7523b 100644 --- a/deploy/Dockerfile +++ b/deploy/Dockerfile @@ -1,9 +1,26 @@ -# Image de production d'IA-Fit : un serveur statique (Caddy) et le site déjà -# assemblé et testé sur le PC (make site). Rien n'est construit sur le -# serveur : voir docs/deploiement.md. Même version de Caddy qu'Ustagammon. -FROM caddy:2.8.4-alpine +# Image de production d'IA-Fit (lot 2) : Node seul, sans dépendance (ADR 0007). +# Le serveur (server/) sert le site déjà assemblé et testé sur le PC (make +# site), le relais chiffré, OAuth et MCP (ADR 0005). Rien n'est construit sur le +# serveur : voir docs/deploiement.md. +FROM node:24.11.1-alpine3.22 -COPY Caddyfile /etc/caddy/Caddyfile -COPY site/ /srv/ +ENV NODE_ENV=production \ + PORT=3000 \ + DATA_DIR=/data \ + SITE_DIR=/srv/site \ + PUBLIC_URL=https://ia-fit.sans.pub -EXPOSE 80 +WORKDIR /srv +COPY package.json /srv/package.json +COPY app/domain/ /srv/app/domain/ +COPY server/ /srv/server/ +COPY site/ /srv/site/ + +# Les journaux chiffrés et le secret du serveur : volume persistant de CapRover. +# Utilisateur non root (node, uid 1000), propriétaire de /data. +RUN mkdir -p /data && chown node:node /data +VOLUME /data +USER node + +EXPOSE 3000 +CMD ["node", "server/main.js"] diff --git a/server/static.js b/server/static.js index 25691ec..8a4ff34 100644 --- a/server/static.js +++ b/server/static.js @@ -115,6 +115,7 @@ export function createStaticHandler(siteDir) { res.writeHead(304, headers); return res.end(); } + /** @type {Buffer} */ let body = await fs.readFile(file); if (encoding) { const key = `${file}|${baseTag}|${encoding}`; diff --git a/tests/server/oauth.test.js b/tests/server/oauth.test.js index 213dfbd..d8a8a00 100644 --- a/tests/server/oauth.test.js +++ b/tests/server/oauth.test.js @@ -132,6 +132,7 @@ test("POST /oauth/authorize : PKCE obligatoire, clé valide et journal existant const { challenge } = pkce(); const ok = { client_id: client.client_id, redirect_uri: REDIRECT, state: "s", code_challenge: challenge, code_challenge_method: "S256", sync_key: syncKey }; + /** @type {[object, string][]} */ const fails = [ [{ code_challenge: undefined }, "invalid_request"], [{ code_challenge_method: "plain" }, "invalid_request"], diff --git a/tsconfig.server.json b/tsconfig.server.json new file mode 100644 index 0000000..8e468de --- /dev/null +++ b/tsconfig.server.json @@ -0,0 +1,9 @@ +{ + "//": "Vérification des types JSDoc du serveur et de ses tests (make lint), avec les types de Node installés dans build/tools. Séparé de tsconfig.json : le code de l'app ne doit pas voir les API de Node.", + "extends": "./tsconfig.json", + "compilerOptions": { + "typeRoots": ["build/tools/node_modules/@types"], + "types": ["node"] + }, + "include": ["server/**/*.js", "tests/server/**/*.js", "tests/domain/sync-crypto.test.js"] +} From d6cd47dbd715584734ada6230186189e6016da52 Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Wed, 18 Nov 2026 05:21:25 +0100 Subject: [PATCH 07/10] test-site : serveur Node, relais, OAuth et MCP de bout en bout Co-Authored-By: Claude Opus 5.5 --- scripts/deploy.sh | 10 ++-- server/main.js | 4 +- tests/server/cli.js | 36 ++++++++++++++ tests/test_site.sh | 118 +++++++++++++++++++++++++++++++++++++++++--- 4 files changed, 156 insertions(+), 12 deletions(-) create mode 100644 tests/server/cli.js diff --git a/scripts/deploy.sh b/scripts/deploy.sh index 42e0040..b8be02d 100755 --- a/scripts/deploy.sh +++ b/scripts/deploy.sh @@ -2,7 +2,7 @@ # Publie la branche main sur CapRover (voir docs/deploiement.md). # # Le site est assemblé et testé sur le PC, puis envoyé sous forme d'archive : -# le serveur ne fait que copier les fichiers dans une image Caddy. Circuit +# le serveur ne fait que copier les fichiers dans une image Node. Circuit # repris d'Ustagammon. # # Prérequis : CLI caprover (via fnm) connecté à la machine CapRover @@ -31,10 +31,10 @@ command -v caprover >/dev/null || die "CLI caprover introuvable (voir docs/deplo # On ne publie que main, propre et identique à origin/main. [ "$(git branch --show-current)" = "main" ] || die "lancer le déploiement depuis la branche main" git diff --quiet HEAD || die "des modifications ne sont pas commitées" -# make site publie tout app/ : un fichier inconnu de git (même ignoré) serait -# publié sans avoir été relu ni commité. -[ -z "$(git ls-files --others -- app)" ] \ - || die "fichiers non suivis par git dans app/ (git ls-files --others app) : ils seraient publiés" +# make site publie tout app/ (et make package tout server/) : un fichier +# inconnu de git (même ignoré) serait publié sans avoir été relu ni commité. +[ -z "$(git ls-files --others -- app server)" ] \ + || die "fichiers non suivis par git dans app/ ou server/ (git ls-files --others app server) : ils seraient publiés" git fetch -q origin main [ "$(git rev-parse main)" = "$(git rev-parse origin/main)" ] \ || die "main diffère d'origin/main : git pull (ou fusionner la MR) d'abord" diff --git a/server/main.js b/server/main.js index 4eb8a79..8e31d73 100644 --- a/server/main.js +++ b/server/main.js @@ -27,7 +27,9 @@ function fail(message) { // Refus de démarrer sans dossier de données inscriptible : sinon le premier // dépôt échouerait, et le secret OAuth ne pourrait pas être gardé. try { - fs.mkdirSync(DATA_DIR, { recursive: true }); + // Sans `recursive` : le parent doit exister (sous /proc, Node 24 boucle sur + // un mkdir récursif). + if (!fs.existsSync(DATA_DIR)) fs.mkdirSync(DATA_DIR); const probe = path.join(DATA_DIR, `.ecriture-${process.pid}`); fs.writeFileSync(probe, ""); fs.unlinkSync(probe); diff --git a/tests/server/cli.js b/tests/server/cli.js new file mode 100644 index 0000000..f23a892 --- /dev/null +++ b/tests/server/cli.js @@ -0,0 +1,36 @@ +#!/usr/bin/env node +// Petit outil en ligne de commande pour tests/test_site.sh : la cryptographie +// d'un appareil (app/domain/sync-crypto.js) et de PKCE, appelée depuis bash. +// node tests/server/cli.js generate → une clé de synchro +// node tests/server/cli.js keys → journalId authToken +// node tests/server/cli.js encrypt → bloc chiffré +// node tests/server/cli.js decrypt → JSON de l'événement +// node tests/server/cli.js pkce → code_verifier code_challenge +import crypto from "node:crypto"; +import { generateSyncKey, deriveKeys, encryptEvent, decryptEvent } from "../../app/domain/sync-crypto.js"; + +const [command, key, value] = process.argv.slice(2); +switch (command) { + case "generate": + console.log(generateSyncKey()); + break; + case "keys": { + const k = await deriveKeys(key); + console.log(k.journalId, k.authToken); + break; + } + case "encrypt": + console.log(await encryptEvent((await deriveKeys(key)).encKey, JSON.parse(value))); + break; + case "decrypt": + console.log(JSON.stringify(await decryptEvent((await deriveKeys(key)).encKey, value))); + break; + case "pkce": { + const verifier = crypto.randomBytes(32).toString("base64url"); + console.log(verifier, crypto.createHash("sha256").update(verifier).digest("base64url")); + break; + } + default: + console.error("commande inconnue"); + process.exit(2); +} diff --git a/tests/test_site.sh b/tests/test_site.sh index 4cccf85..5f1dd2c 100755 --- a/tests/test_site.sh +++ b/tests/test_site.sh @@ -3,7 +3,11 @@ # construit l'image en local, la lance, et contrôle par curl ce que reçoit un # navigateur : page, modules ES (type MIME), version.json, manifeste, service # worker et sa liste de fichiers, en-têtes (CSP, nosniff, cache, referrer), -# compression, fichiers exclus de la publication. +# compression, fichiers exclus de la publication. Puis, de bout en bout contre +# le serveur Node (lot 2) : relais (dépôt, lecture, clé d'accès), OAuth (client, +# autorisation PKCE avec une vraie clé de synchro, échange du code) et MCP +# (tools/list, get_overview, propose_program qui ajoute un bloc au journal). +# La cryptographie d'appareil vient de tests/server/cli.js. # # Le site d'essai est assemblé par les vraies cibles make, mais depuis une # copie de app/ dans un dossier temporaire (rien n'est écrit dans app/ ni dans @@ -64,11 +68,12 @@ make -s package APP_DIR="$work/app" SITE_BUILD="$work/build" >/dev/null site="$work/build/site" docker build -q -t "$image" "$work/build/deploy" >/dev/null -container="$(docker run -d --rm -p 127.0.0.1::80 "$image")" -port="$(docker port "$container" 80/tcp | head -n1 | sed 's/.*://')" +public_url="https://ia-fit.test" +container="$(docker run -d --rm -p 127.0.0.1::3000 -e PUBLIC_URL="$public_url" "$image")" +port="$(docker port "$container" 3000/tcp | head -n1 | sed 's/.*://')" base="http://127.0.0.1:$port" -# Caddy démarre en une fraction de seconde : on attend qu'il réponde. +# Le serveur démarre en une fraction de seconde : on attend qu'il réponde. for _ in $(seq 1 50); do curl -sf -o /dev/null "$base/" && break sleep 0.1 @@ -163,7 +168,7 @@ for path in "" sw-register.js sw.js; do grep -qiE "unsafe-inline|unsafe-eval|wasm-unsafe-eval" <<<"$headers" && report "/$path : CSP trop permissive" done -# Compression : le plus gros module JavaScript (au-dessus du seuil de Caddy). +# Compression : le plus gros module JavaScript (au-dessus du seuil de 512 octets). biggest="$(cd "$site" && find . -name '*.js' -printf '%s %P\n' | sort -n | tail -1 | cut -d' ' -f2)" for encoding in gzip zstd; do curl -s -H "Accept-Encoding: $encoding" -D - -o /dev/null "$base/$biggest" \ @@ -172,8 +177,109 @@ done curl -s -H "Accept-Encoding: gzip" -D - -o /dev/null "$base/__essai__/police.woff2" \ | grep -qi "^Content-Encoding" && report "police woff2 recompressée inutilement" +# --------------------------------------------------------------------------- +# Serveur Node : conteneur, relais, OAuth, MCP, de bout en bout. +# --------------------------------------------------------------------------- +cli() { node tests/server/cli.js "$@"; } +# jsonget : lit du JSON sur l'entrée standard. +jsonget() { + node -e 'let s="";process.stdin.on("data",(d)=>s+=d).on("end",()=>{let r;try{r=new Function("v","return "+process.argv[1])(JSON.parse(s))}catch{r=""}console.log(typeof r==="string"?r:JSON.stringify(r))})' "$1" +} +# status [arguments de curl…] : code HTTP seul. +status() { + local method="$1" path="$2" + shift 2 + curl -s -o /dev/null -w "%{http_code}" -X "$method" "$base$path" "$@" +} + +[ "$(docker exec "$container" id -u)" != "0" ] || report "le serveur tourne en root" +docker exec "$container" test -s /data/.server-secret || report "/data/.server-secret absent : secret OAuth non créé" +if timeout 20 docker run --rm -e DATA_DIR=/srv/site "$image" >"$work/refus.log" 2>&1; then + report "le serveur démarre avec un DATA_DIR non inscriptible" +else + grep -q "DATA_DIR" "$work/refus.log" || report "refus de démarrer sans message sur DATA_DIR" +fi + +# Relais : un appareil dépose deux événements chiffrés, puis les relit. +key="$(cli generate)" +read -r journal token < <(cli keys "$key") +api="/api/journals/$journal/events" +blob1="$(cli encrypt "$key" '{"id":"e2e-1","at":"2026-11-01T10:00:00.000Z","device":"pc","v":1,"type":"WeightRecorded","data":{"date":"2026-11-01","kg":80}}')" +blob2="$(cli encrypt "$key" '{"id":"e2e-2","at":"2026-11-02T10:00:00.000Z","device":"pc","v":1,"type":"ModeChanged","data":{"mode":"maintenance"}}')" +[ "$(status GET "$api" -H "Authorization: Bearer $token")" = 404 ] || report "relais : journal inconnu attendu (404) avant le premier dépôt" +deposit="$(curl -s -X POST "$base$api" -H "Authorization: Bearer $token" -H "Content-Type: application/json" -d "[\"$blob1\",\"$blob2\"]")" +[ "$(jsonget v.last <<<"$deposit")" = 2 ] || report "relais : dépôt de deux blocs refusé ($deposit)" +read_back="$(curl -s "$base$api?after=0" -H "Authorization: Bearer $token")" +[ "$(jsonget 'v.events.map((e) => e.seq).join(",")' <<<"$read_back")" = "1,2" ] || report "relais : lecture incomplète" +[ "$(cli decrypt "$key" "$(jsonget 'v.events[1].blob' <<<"$read_back")" | jsonget v.type)" = ModeChanged ] \ + || report "relais : bloc relu indéchiffrable" +[ "$(jsonget 'v.events.length' < <(curl -s "$base$api?after=1" -H "Authorization: Bearer $token"))" = 1 ] || report "relais : after=1 mal appliqué" +[ "$(status GET "$api")" = 401 ] || report "relais : lecture sans clé d'accès acceptée" +read -r _ other_token < <(cli keys "$(cli generate)") +[ "$(status GET "$api" -H "Authorization: Bearer $other_token")" = 403 ] || report "relais : lecture avec une fausse clé d'accès acceptée" +[ "$(status POST "$api" -H "Authorization: Bearer $other_token" -d "[\"$blob1\"]")" = 403 ] || report "relais : dépôt avec une fausse clé d'accès accepté" +big="$(head -c 70000 /dev/zero | tr '\0' A)" +[ "$(status POST "$api" -H "Authorization: Bearer $token" -d "[\"$big\"]")" = 413 ] || report "relais : bloc de plus de 64 Ko accepté" +# Aucun journal d'accès : la sortie du conteneur ne contient ni l'identifiant ni la clé d'accès. +docker logs "$container" 2>&1 | grep -qE "$journal|$token" && report "les journaux du conteneur contiennent un identifiant ou une clé d'accès" + +# OAuth : métadonnées, enregistrement, autorisation PKCE, échange du code. +[ "$(curl -s "$base/.well-known/oauth-authorization-server" | jsonget v.token_endpoint)" = "$public_url/oauth/token" ] \ + || report "OAuth : métadonnées du serveur d'autorisation" +[ "$(curl -s "$base/.well-known/oauth-protected-resource/mcp" | jsonget v.resource)" = "$public_url/mcp" ] \ + || report "OAuth : métadonnées de la ressource protégée" +mcp_401="$(curl -s -D - -o /dev/null -X POST "$base/mcp" | tr -d '\r')" +grep -q "^HTTP/1.1 401" <<<"$mcp_401" || report "MCP : 401 attendu sans jeton" +grep -qiF "www-authenticate: Bearer resource_metadata=\"$public_url/.well-known/oauth-protected-resource/mcp\"" <<<"$mcp_401" \ + || report "MCP : en-tête WWW-Authenticate absent ou différent" +redirect_uri="https://claude.ai/api/mcp/auth_callback" +client_id="$(curl -s -X POST "$base/oauth/register" -H "Content-Type: application/json" \ + -d "{\"client_name\":\"Essai\",\"redirect_uris\":[\"$redirect_uri\"]}" | jsonget v.client_id)" +[ -n "$client_id" ] || report "OAuth : enregistrement du client refusé" +read -r verifier challenge < <(cli pkce) +location="$(curl -s -o /dev/null -w "%{redirect_url}" -G "$base/oauth/authorize" --data-urlencode "client_id=$client_id" \ + --data-urlencode "redirect_uri=$redirect_uri" -d response_type=code -d state=e2e \ + -d "code_challenge=$challenge" -d code_challenge_method=S256)" +grep -qF "/#/connecter-ia?" <<<"$location" || report "OAuth : GET /oauth/authorize ne renvoie pas vers /#/connecter-ia ($location)" +authorize() { + curl -s -X POST "$base/oauth/authorize" -H "Content-Type: application/json" \ + -d "{\"client_id\":\"$client_id\",\"redirect_uri\":\"$redirect_uri\",\"state\":\"e2e\",\"code_challenge\":\"$challenge\",\"code_challenge_method\":\"S256\",\"sync_key\":\"$1\"}" +} +[ "$(authorize "$(cli generate)" | jsonget v.error)" = unknown_journal ] || report "OAuth : clé sans journal acceptée" +redirect="$(authorize "$key" | jsonget v.redirect)" +grep -q "^$redirect_uri?code=.*state=e2e" <<<"$redirect" || report "OAuth : autorisation refusée avec la bonne clé ($redirect)" +grep -qF "${key:0:9}" <<<"$redirect" && report "OAuth : la clé de synchro apparaît en clair dans le code" +code="$(node -e 'console.log(new URL(process.argv[1]).searchParams.get("code") ?? "")' "$redirect")" +exchange() { + curl -s -X POST "$base/oauth/token" --data-urlencode grant_type=authorization_code --data-urlencode "code=$code" \ + --data-urlencode "code_verifier=$1" --data-urlencode "client_id=$client_id" --data-urlencode "redirect_uri=$redirect_uri" +} +[ "$(exchange "$(cli pkce | cut -d' ' -f1)" | jsonget v.error)" = invalid_grant ] || report "OAuth : mauvais code_verifier accepté" +access="$(exchange "$verifier" | jsonget v.access_token)" +[ -n "$access" ] || report "OAuth : échange du code refusé" +[ "$(exchange "$verifier" | jsonget v.error)" = invalid_grant ] || report "OAuth : code utilisable deux fois" + +# MCP : liste des outils, vue d'ensemble, proposition déposée sur le relais. +mcp() { + curl -s -X POST "$base/mcp" -H "Authorization: Bearer $access" -H "Content-Type: application/json" -d "$1" +} +tools="$(mcp '{"jsonrpc":"2.0","id":1,"method":"tools/list"}' | jsonget 'v.result.tools.map((t) => t.name).join(",")')" +{ grep -q "get_overview" <<<"$tools" && grep -q "propose_program" <<<"$tools"; } || report "MCP : tools/list incomplet ($tools)" +[ "$(mcp '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"get_overview","arguments":{}}}' \ + | jsonget 'JSON.parse(v.result.content[0].text).mode')" = maintenance ] || report "MCP : get_overview ne lit pas le journal" +program='{"name":"Essai","sessions":[{"key":"A","name":"Séance A","exercises":[{"ref":"squat","sets":3,"reps":"8","rest":90}]}]}' +proposed="$(mcp "{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"tools/call\",\"params\":{\"name\":\"propose_program\",\"arguments\":{\"program\":$program,\"reason\":\"Essai de bout en bout\"}}}")" +[ "$(jsonget 'v.result.isError ?? false' <<<"$proposed")" = false ] || report "MCP : propose_program refusé ($proposed)" +after="$(curl -s "$base$api?after=2" -H "Authorization: Bearer $token")" +[ "$(jsonget 'v.events.length' <<<"$after")" = 1 ] || report "MCP : la proposition n'a pas ajouté un bloc au journal" +[ "$(cli decrypt "$key" "$(jsonget 'v.events[0].blob' <<<"$after")" | jsonget '[v.type, v.device, v.data.source].join(",")')" = "ProgramProposed,mcp,ai" ] \ + || report "MCP : le bloc ajouté n'est pas une proposition de l'IA" +invalid="$(mcp '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"propose_program","arguments":{"program":{"name":""},"reason":"x"}}}')" +[ "$(jsonget 'v.result.isError' <<<"$invalid")" = true ] || report "MCP : programme invalide accepté" +[ "$(jsonget 'v.last' < <(curl -s "$base$api?after=3" -H "Authorization: Bearer $token"))" = 3 ] || report "MCP : un programme invalide a été écrit" + if [ "$errors" -eq 0 ]; then - echo "test-site : OK ($present fichiers servis, image $image)" + echo "test-site : OK ($present fichiers servis, relais, OAuth et MCP de bout en bout, image $image)" else echo "test-site : $errors erreur(s)" >&2 exit 1 From 7e10934b8d50db390acad38c68e7d882ad82a08b Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Wed, 18 Nov 2026 05:21:25 +0100 Subject: [PATCH 08/10] =?UTF-8?q?Docs=20:=20d=C3=A9ploiement=20du=20serveu?= =?UTF-8?q?r=20Node=20(r=C3=A9glages=20CapRover)=20et=20branchement=20MCP?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- docs/deploiement.md | 141 ++++++++++++++++++++++++++++++-------------- docs/mcp.md | 90 ++++++++++++++++++++++++++++ 2 files changed, 187 insertions(+), 44 deletions(-) create mode 100644 docs/mcp.md diff --git a/docs/deploiement.md b/docs/deploiement.md index cf417f2..8132b4a 100644 --- a/docs/deploiement.md +++ b/docs/deploiement.md @@ -1,15 +1,21 @@ # Déploiement -Au lot 1, IA-Fit est un site statique : des modules ES servis tels quels (ADR 0007), -qui marchent hors ligne grâce à un service worker (ADR 0005). Il est publié sur -CapRover, machine `sans-pub` (https://captain.cloud.sans.pub), app `ia-fit`, sur -https://ia-fit.sans.pub. Le circuit est repris d'Ustagammon. +IA-Fit est publié sur CapRover, machine `sans-pub` (https://captain.cloud.sans.pub), +app `ia-fit`, sur https://ia-fit.sans.pub. Le circuit est repris d'Ustagammon. + +Depuis le lot 2, l'image est un **serveur Node sans dépendance** (`server/`, +ADR 0007), qui sert sur la même origine : +- le site statique (modules ES servis tels quels, hors ligne grâce au service + worker), avec les mêmes en-têtes que le Caddyfile du lot 1 ; +- le relais chiffré `/api/journals/…` (ADR 0005, point 3) ; +- OAuth 2.1 sans état (`/.well-known/…`, `/oauth/…`) et le MCP `/mcp` (point 5, + `docs/mcp.md`). **Le site est assemblé et testé sur le PC, pas sur le serveur.** `make deploy-prod` -envoie à CapRover une archive qui contient le site prêt, un `Dockerfile` et un -`Caddyfile` (`deploy/`). Le serveur ne fait que copier les fichiers dans une image -Caddy (`caddy:2.8.4-alpine`, même version qu'Ustagammon), qui les sert en HTTP sur -le port 80 du conteneur, derrière le HTTPS de CapRover. +envoie à CapRover une archive qui contient le site prêt, le serveur, le domaine dont +il dépend et un `Dockerfile` (`deploy/`). Le serveur ne fait que copier les fichiers +dans une image `node:24.11.1-alpine3.22`, qui écoute en HTTP sur le port **3000** du +conteneur, derrière le HTTPS de CapRover, sous l'utilisateur `node` (non root). ## Prérequis @@ -23,10 +29,33 @@ le port 80 du conteneur, derrière le HTTPS de CapRover. caprover api -n sans-pub -t /user/system/info -m GET -d '{}' -o false ``` En cas de `not valid anymore` : `caprover login` dans un vrai terminal. -- **L'app `ia-fit` existe dans CapRover** : créée par le porteur du projet - (https://captain.cloud.sans.pub/#/apps/details/ia-fit). À vérifier avant la - première publication : port du conteneur 80, domaine `ia-fit.sans.pub` avec HTTPS - activé et forcé. **Aucun volume** au lot 1 : rien n'est stocké côté serveur. +- **L'app `ia-fit` existe dans CapRover** + (https://captain.cloud.sans.pub/#/apps/details/ia-fit), domaine `ia-fit.sans.pub` + avec HTTPS activé et forcé. + +### Réglages CapRover à faire avant la première publication du lot 2 + +À faire à la main par le porteur du projet (ou la session principale), dans l'app +`ia-fit` : +1. **HTTP Settings → Container HTTP Port : `3000`** (au lot 1 : 80). Sans ce + changement, CapRover répond 502 après la publication. +2. **App Configs → Persistent Directories** (l'app a déjà « Has Persistent Data » + activé) : ajouter le chemin dans l'app `/data`, avec un nom de volume + (par exemple `ia-fit-data`). On y trouve les journaux chiffrés + (`/data/journals/*.jsonl`) et le secret du serveur (`/data/.server-secret`). + Le dossier doit être inscriptible par l'uid 1000 (`node`) : le volume Docker + nommé hérite des droits de l'image (`/data` appartient à `node`). Si le serveur + journalise « DATA_DIR (/data) n'est pas inscriptible », corriger les droits du + volume sur l'hôte (`chown 1000:1000`). +3. **Variables d'environnement** : aucune n'est nécessaire (valeurs par défaut de + l'image : `PORT=3000`, `DATA_DIR=/data`, `SITE_DIR=/srv/site`, + `PUBLIC_URL=https://ia-fit.sans.pub`). Pour une autre adresse publique, régler + `PUBLIC_URL` : les métadonnées OAuth et le MCP l'annoncent aux IA. +4. **Sauvegardes** : inclure le volume `/data` dans les sauvegardes restic de + sans.pub (**à vérifier** : la liste des volumes sauvegardés). Perdre + `.server-secret` déconnecte les IA (il suffit de les rebrancher) ; perdre les + journaux coupe la synchro, mais les données restent sur les appareils, qui les + redéposent à la synchro suivante sous la même clé. ## Publier @@ -39,8 +68,8 @@ make deploy-prod Le script (`scripts/deploy.sh`) refuse de publier : - si l'on n'est pas sur `main`, si l'arbre n'est pas propre, ou si `main` diffère d'`origin/main` ; -- si `app/` contient un fichier inconnu de git (il serait publié sans avoir été - commité) ; +- si `app/` ou `server/` contient un fichier inconnu de git (il serait publié sans + avoir été commité) ; - si la session CapRover a expiré, ou si Docker ne répond pas (l'image doit être vérifiée). @@ -52,6 +81,13 @@ commit publié : la CLI peut rendre 0 sans avoir rien publié. Pour une autre machine ou une autre app : `CAPROVER_MACHINE=… CAPROVER_APP=… SITE_URL=… make deploy-prod`. +## En local + +- `make dev` : les fichiers de `app/` tels quels (Python, port 8080), sans relais ni + MCP. +- `make serve` : le serveur de production sur `build/site` (assemblé à l'appel), + port 3000, données dans `build/data`, `PUBLIC_URL=http://localhost:3000`. + ## Ce qui est publié - `make site` assemble `build/site/` : @@ -63,7 +99,10 @@ SITE_URL=… make deploy-prod`. - enfin, `scripts/service-worker.sh` remplace dans `sw.js` le bloc entre `// ` et `// ` par la liste de tous ces fichiers et une empreinte de leur contenu. -- `make package` ajoute `deploy/` et produit `build/ia-fit.tar`. +- `make package` ajoute `deploy/`, `server/`, `app/domain/` (dont le serveur + importe le repli de l'état, la validation et la cryptographie) et `package.json`, + puis produit `build/ia-fit.tar`. Dans l'image : `/srv/site`, `/srv/server`, + `/srv/app/domain`, `/srv/package.json`. - `make test-site` (dans `make test` si Docker répond, sinon un message le dit) assemble un site d'essai depuis une copie de `app/` dans un dossier temporaire, construit l'image de production, la lance et vérifie par `curl` : @@ -75,7 +114,15 @@ SITE_URL=… make deploy-prod`. listé) ; - les en-têtes (CSP exacte, `nosniff`, `Referrer-Policy`, `Cache-Control`) sur la page, un module et le service worker ; la compression gzip et zstd ; - - l'absence des fichiers exclus. + - l'absence des fichiers exclus ; + - le serveur : utilisateur non root, secret créé dans `/data`, refus de démarrer + sans `DATA_DIR` inscriptible ; + - de bout en bout, avec une vraie clé de synchro (`tests/server/cli.js`) : dépôt + et lecture sur le relais, refus sans clé d'accès ou avec une fausse, bloc trop + gros ; métadonnées OAuth, `401` du MCP avec `WWW-Authenticate`, enregistrement + d'un client, autorisation PKCE, échange du code (une seule fois) ; + `tools/list`, `get_overview`, `propose_program` qui ajoute un bloc chiffré + (`ProgramProposed`, source `ai`) au journal, programme invalide refusé. Tant que `app/` n'a pas de `index.html` ou de `manifest.webmanifest`, le test en ajoute une version d'essai à sa copie, et le signale. @@ -96,24 +143,38 @@ Une page ouverte garde ainsi tous ses modules, de la même version. Une publicat sans changement de fichier garde le même `sw.js` : rien n'est retéléchargé. Le service worker exige https (ou `localhost`). Sous `make dev`, `sw.js` est servi tel quel, avec une liste vide : il ne met rien en cache et laisse tout passer vers le -réseau. +réseau. Les routes du serveur (`/api/`, `/oauth/`, `/mcp`, `/.well-known/`) ne sont +pas des fichiers du site : le service worker ne les met pas en cache. -**Réglages du serveur** (`deploy/Caddyfile`) : -- compression zstd ou gzip des textes (HTML, CSS, JavaScript, JSON, manifeste, SVG) ; -- `Cache-Control: no-cache` : les noms de fichiers ne changent pas d'une version à - l'autre, le navigateur revalide chaque fichier ; +**Réglages du site** (`server/static.js`, repris du Caddyfile du lot 1) : +- compression zstd ou gzip des textes (HTML, CSS, JavaScript, JSON, manifeste, SVG, + Markdown) au-dessus de 512 octets ; +- `Cache-Control: no-cache` et `ETag` : les noms de fichiers ne changent pas d'une + version à l'autre, le navigateur revalide chaque fichier ; les routes dynamiques + répondent `no-store` ; - `X-Content-Type-Options: nosniff` et `Referrer-Policy: no-referrer` ; -- types MIME fixés pour `.js` (`text/javascript`), `.webmanifest`, `.woff2` et `.md` - (`text/markdown; charset=utf-8`, pour `ia.md`, le prompt d'accueil lu par une IA - qui navigue ; mis en cache par le service worker comme tout fichier du site) ; -- une politique de sécurité du contenu stricte, « tout vient du site lui-même » : +- types MIME fixés (`.js` en `text/javascript`, `.webmanifest`, `.woff2`, `.md` en + `text/markdown; charset=utf-8`…) ; +- fichiers cachés et remontées (`..`) refusés (404) ; +- une politique de sécurité du contenu stricte, « tout vient du site lui-même », + sur toutes les réponses : ``` default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; worker-src 'self'; manifest-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none' ``` - Ni script ni style en ligne (pas d'attribut `style=` ni de `onclick=` dans le - HTML), ni `eval`, ni WebAssembly ; polices auto-hébergées (ADR 0007). + Ni script ni style en ligne, ni `eval`, ni WebAssembly ; polices auto-hébergées + (ADR 0007). Relais et MCP sont sur la même origine : `connect-src 'self'` suffit. + +**Réglages du relais** (`server/relay.js`) : un fichier JSON Lines par journal +(ajout seulement, `fdatasync` à chaque dépôt, écritures sérialisées par journal) ; +bloc de 64 Ko au plus, 500 blocs et 4 Mo par dépôt, 20 Mo par journal ; journaux +inactifs depuis 400 jours effacés (au démarrage puis chaque jour) ; 300 requêtes +par minute et par adresse sur les routes dynamiques, 20 autorisations par minute, +en mémoire seulement. L'adresse est celle qu'écrit le proxy de CapRover +(`X-Real-IP`, sinon le dernier élément de `X-Forwarded-For`) : le conteneur ne doit +être joignable que par ce proxy, ce qui est le cas dans CapRover. Aucun journal +d'accès n'est écrit. ## Vérifier @@ -122,31 +183,23 @@ curl -s https://ia-fit.sans.pub/version.json # commit pub curl -sI https://ia-fit.sans.pub/sw-register.js | grep -i content-type # text/javascript curl -sI https://ia-fit.sans.pub/ | grep -i content-security # CSP curl -s https://ia-fit.sans.pub/sw.js | sed -n '/^const VERSION/p' # version du cache +curl -s https://ia-fit.sans.pub/.well-known/oauth-authorization-server # métadonnées OAuth +curl -si -X POST https://ia-fit.sans.pub/mcp | grep -i www-authenticate # 401 du MCP ssh sans.pub 'sudo docker service ps srv-captain--ia-fit --format "{{.Image}} {{.CurrentState}}" | head -2' ``` Puis ouvrir le site sur le téléphone, attendre le premier affichage, passer en mode -avion et recharger : l'app doit s'ouvrir sans réseau. +avion et recharger : l'app doit s'ouvrir sans réseau. Pour le MCP, brancher un +connecteur (`docs/mcp.md`) et appeler `get_overview`. ## Retour arrière Dans CapRover, onglet *Deployment* de l'app `ia-fit` : redéployer une image -précédente (`img-captain-ia-fit:N`). Rien n'est stocké côté serveur : aucun risque -pour des données. Les navigateurs qui ont déjà la version fautive en cache -reçoivent la version redéployée à l'ouverture suivante, puisque son `sw.js` -diffère. - -## Au lot 2 : relais et MCP - -Le relais chiffré et le serveur MCP (ADR 0005) changeront la nature de l'app -CapRover `ia-fit` : -- un **serveur Node** (sans dépendance, ADR 0007) remplacera ou complétera Caddy : - il servira les mêmes fichiers statiques, avec les mêmes en-têtes, plus les routes - du relais, d'OAuth et du MCP ; -- un **volume persistant** sera nécessaire pour les journaux chiffrés du relais - (à déclarer dans CapRover avant la première publication du lot 2, et à inclure - dans les sauvegardes du serveur) ; -- la CSP restera « tout du site lui-même » : relais et MCP sont sur la même origine. +précédente (`img-captain-ia-fit:N`). Revenir à une image Caddy du lot 1 demande +aussi de remettre le port du conteneur à 80 ; le volume `/data` est alors ignoré, +et retrouvé intact au retour du lot 2. Les navigateurs qui ont déjà la version +fautive en cache reçoivent la version redéployée à l'ouverture suivante, puisque +son `sw.js` diffère. ## Incidents connus diff --git a/docs/mcp.md b/docs/mcp.md new file mode 100644 index 0000000..9f1c8e6 --- /dev/null +++ b/docs/mcp.md @@ -0,0 +1,90 @@ +# Brancher une IA par MCP + +IA-Fit expose un serveur MCP à l'adresse **https://ia-fit.sans.pub/mcp** (ADR 0005, +point 5). Une IA branchée lit le programme, les séances, le poids et le profil, puis +**propose** ses changements : rien n'est appliqué sans la validation de +l'utilisateur dans l'app (point 6). + +Prérequis : la synchro est activée dans l'app (une clé de synchro existe et le +journal a été déposé au moins une fois sur le relais). Sans journal sur le relais, +l'autorisation est refusée (« Aucun journal synchronisé pour cette clé »). + +## Brancher + +**Claude (claude.ai, applications)** : Réglages → Connecteurs → Ajouter un connecteur +personnalisé → URL `https://ia-fit.sans.pub/mcp`. Claude ouvre la page +d'autorisation d'IA-Fit : sur un appareil déjà apparié, la clé est retrouvée et un +clic sur « Autoriser » suffit ; ailleurs, on colle la clé de synchro. + +**ChatGPT** : Réglages → Applications et connecteurs → Paramètres avancés → activer +le mode développeur, puis « Créer » un connecteur : URL +`https://ia-fit.sans.pub/mcp`, authentification OAuth. ChatGPT s'enregistre seul +(enregistrement dynamique) et ouvre la même page d'autorisation. + +**Claude Code** : +```bash +claude mcp add --transport http ia-fit https://ia-fit.sans.pub/mcp +``` +puis `/mcp` dans Claude Code pour lancer l'autorisation dans le navigateur. + +Pour le développement local (`make serve`), l'adresse est `http://localhost:3000/mcp`. + +## Ce que voit le serveur + +- **Au repos**, le relais ne garde que des blocs chiffrés (AES-256-GCM, clé tirée de + la clé de synchro), rangés sous un identifiant aléatoire. Il ne connaît ni nom, ni + e-mail, ni adresse IP (la limite de requêtes par adresse reste en mémoire). +- **Le jeton OAuth** transporte la clé de synchro, chiffrée par une clé propre au + serveur. Le serveur ne la conserve pas. +- **Pendant une requête MCP**, le serveur déchiffre le jeton, dérive les clés, + déchiffre tout le journal **en mémoire**, calcule l'état avec le même code que + l'app, répond, puis oublie tout. Il voit donc les données en clair le temps de la + requête ; l'IA (Claude, ChatGPT…) les voit aussi, et son fournisseur les garde + selon ses propres règles. +- Révoquer un accès : supprimer le connecteur dans l'IA. Le jeton de + rafraîchissement reste toutefois valable jusqu'à son expiration (90 jours) : pour + couper tout de suite, changer de clé de synchro (nouveau journal). + +## Durées + +| Élément | Durée | Remarque | +| --- | --- | --- | +| Code d'autorisation | 5 min | usage unique ; PKCE S256 obligatoire | +| Jeton d'accès | 1 h | | +| Jeton de rafraîchissement | 90 jours | renouvelé à chaque rafraîchissement | +| Client enregistré | sans limite | son identifiant porte ses adresses de retour, signées : il survit aux redémarrages | + +Changer le secret du serveur (`/data/.server-secret`) déconnecte toutes les IA, sans +toucher aux journaux. + +## Outils + +| Outil | Arguments | Rôle | +| --- | --- | --- | +| `get_overview` | — | À lire en premier : programme (résumé), profil, mode, propositions en attente, assiduité sur 4 semaines, dernière séance, dernière pesée | +| `get_program` | — | Programme courant complet, charges de travail, versions du programme | +| `get_training_history` | `days?` (28) | Séances faites, série par série, et jours marqués non faits | +| `get_exercise_progress` | `exercise_id` | Évolution d'un exercice (charge, répétitions, volume, ressenti) | +| `get_body_weight` | `days?` (90) | Pesées, tendance, repères | +| `propose_program` | `program`, `profile?`, `reason` | Propose un programme complet (et un profil) | +| `propose_session_change` | `key`, `session`, `reason` | Remplace (ou ajoute) une séance dans une copie du programme courant, puis la propose | +| `propose_profile` | `profile`, `reason` | Propose le programme courant avec un nouveau profil | + +Les propositions sont des événements `ProgramProposed` (appareil `mcp`, source `ai`, +`docs/evenements.md`) ajoutés au journal chiffré. Un programme ou un profil invalide +est refusé avec la liste des problèmes (la même validation que l'app, +`app/domain/program.js` et `profile.js`), et rien n'est écrit. Le format est décrit +dans https://ia-fit.sans.pub/ia.md, que les `instructions` du serveur demandent de +lire. + +## Protocole + +JSON-RPC 2.0 sur HTTP POST, sans session ni flux SSE (`GET /mcp` répond 405). +Version du protocole `2025-06-18` (ou `2025-03-26` si le client la demande). Sans +jeton valide : `401` avec +`WWW-Authenticate: Bearer resource_metadata="https://ia-fit.sans.pub/.well-known/oauth-protected-resource/mcp"`. + +Routes OAuth : `/.well-known/oauth-protected-resource[/mcp]`, +`/.well-known/oauth-authorization-server`, `POST /oauth/register`, +`GET|POST /oauth/authorize`, `POST /oauth/token`. Code : `server/oauth.js`, +`server/mcp.js`. From 6ac2061f513b9eb6f288c5e7c95bcda34590f924 Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Wed, 18 Nov 2026 05:22:39 +0100 Subject: [PATCH 09/10] =?UTF-8?q?Plan=20du=20lot=202=20serveur=20:=20r?= =?UTF-8?q?=C3=A9sultat,=20termin=C3=A9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- docs/plans/2026-11-18-lot-2-serveur.md | 37 ++++++++++++++++++++++++-- 1 file changed, 35 insertions(+), 2 deletions(-) diff --git a/docs/plans/2026-11-18-lot-2-serveur.md b/docs/plans/2026-11-18-lot-2-serveur.md index 81ea908..62e0012 100644 --- a/docs/plans/2026-11-18-lot-2-serveur.md +++ b/docs/plans/2026-11-18-lot-2-serveur.md @@ -2,7 +2,7 @@ - **Date** : 2026-11-18 - **Lot** : 2a et 2c (sans l'interface) -- **Statut** : en cours +- **Statut** : terminé - **Exécutant** : sous-agent general-purpose (worktree isolé, branche `lot-2-serveur`) ## Objectif @@ -73,4 +73,37 @@ modules du domaine. ## Résultat -(à compléter) +Livré sur la branche `lot-2-serveur` (main fusionné deux fois, sans conflit) : + +- `app/domain/sync-crypto.js` : `generateSyncKey`, `normalizeSyncKey`, + `isValidSyncKey`, `deriveKeys` → `{journalId, authToken, encKey}`, + `encryptEvent`, `decryptEvent`, `SyncCryptoError`. Clé de 26 caractères Crockford + (128 bits + 2 bits nuls de complément), affichée en 7 groupes. Vecteurs fixes + vérifiés contre `hkdfSync` de Node. +- `server/` (Node sans dépendance) : `main.js` (variables, refus sans `DATA_DIR` + inscriptible, effacement quotidien), `app.js` (routage), `static.js` (en-têtes et + types du Caddyfile, zstd/gzip, ETag), `relay.js` (JSON Lines, `fdatasync`, file + d'attente par journal, réparation d'une ligne coupée, quotas), `rate-limit.js` + (`X-Real-IP`, sinon dernier `X-Forwarded-For`), `oauth.js` (clients signés, + code et jetons AES-GCM, PKCE S256 obligatoire, codes à usage unique en + mémoire), `mcp.js` (8 outils, propositions `ProgramProposed` source `ai`). +- `app/infra/sync.js` : `createSync({store, syncKey, baseUrl})` → `push`, `pull`, + `sync` ; état dans `meta` (`sync:` : `lastSeq`, `known`). Ajout de + `getMeta`/`setMeta` à `app/infra/event-store.js` (hors périmètre initial, purement + additif). +- Publication : image `node:24.11.1-alpine3.22`, utilisateur `node`, port 3000, + `/data` ; `deploy/Caddyfile` retiré ; `make serve` ; `make package` embarque + `server/`, `app/domain/` et `package.json` ; `tsconfig.server.json` avec + `@types/node@24.10.1` (outil de dev, MIT) ; `scripts/deploy.sh` refuse aussi les + fichiers non suivis dans `server/`. +- Tests : `tests/domain/sync-crypto.test.js`, `tests/server/*.test.js` (relais, + quotas, IP, limite, OAuth, MCP, site, synchro à deux appareils) ; + `tests/test_site.sh` contre l'image, avec parcours de bout en bout par curl + (`tests/server/cli.js` pour la cryptographie). +- Docs : `docs/deploiement.md` (réglages CapRover), `docs/mcp.md`. + +Points ouverts : réglages CapRover (port 3000, volume `/data`, sauvegarde restic) +à faire et vérifier avant publication ; interface (`/#/connecter-ia`, écran Synchro, +appels de `sync.js`) à écrire ; outil MCP de changement de mode non prévu +(`ProgramProposed` ne porte pas de mode) ; un jeton de rafraîchissement ne peut pas +être révoqué avant 90 jours (sans état). From 006f0332c620a08ce253fcebd9577f823d2003cb Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Wed, 18 Nov 2026 05:23:28 +0100 Subject: [PATCH 10/10] =?UTF-8?q?Cl=C3=B4ture=20du=20plan=20du=20lot=202?= =?UTF-8?q?=20serveur?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus 5.5 --- docs/plans/2026-11-18-lot-2-serveur.md | 109 ------------------------- 1 file changed, 109 deletions(-) delete mode 100644 docs/plans/2026-11-18-lot-2-serveur.md diff --git a/docs/plans/2026-11-18-lot-2-serveur.md b/docs/plans/2026-11-18-lot-2-serveur.md deleted file mode 100644 index 62e0012..0000000 --- a/docs/plans/2026-11-18-lot-2-serveur.md +++ /dev/null @@ -1,109 +0,0 @@ -# Lot 2 : serveur (relais, OAuth, MCP) et cryptographie - -- **Date** : 2026-11-18 -- **Lot** : 2a et 2c (sans l'interface) -- **Statut** : terminé -- **Exécutant** : sous-agent general-purpose (worktree isolé, branche `lot-2-serveur`) - -## Objectif - -Livrer la partie serveur et cryptographique du lot 2 (ADR 0005, points 2, 3, 5 et 6) : -la clé de synchro et ses dérivations, le relais chiffré, l'OAuth 2.1 sans état, le -serveur MCP, le module de synchro du navigateur, et la publication par un serveur -Node qui remplace Caddy. L'interface (page `/#/connecter-ia`, écran Synchro) est -écrite par ailleurs. - -## Consignes - -**Fichiers possédés** : `server/` (nouveau), `app/domain/sync-crypto.js`, -`app/infra/sync.js`, `tests/server/`, `tests/domain/sync-crypto.test.js`, `deploy/`, -`scripts/deploy.sh`, `tests/test_site.sh`, le `Makefile` (ajouts et adaptations), -`tsconfig.json`, `docs/deploiement.md`, `docs/mcp.md` (nouveau), ce plan. Ne pas -toucher `app/ui/`, `app/index.html`, `app/main.js`, `app/styles/` ni les autres -modules du domaine. - -1. **`app/domain/sync-crypto.js`** (navigateur et Node : `crypto.subtle`, - `TextEncoder` seulement) : - - `generateSyncKey()` : 128 bits aléatoires, en base32 Crockford par groupes de 4 ; - `normalizeSyncKey(text)` (espaces, tirets, minuscules, O/0, I/1, L/1) et - validation ; - - `deriveKeys(syncKey)` → `{journalId, authToken, encKey}` par HKDF-SHA-256, sel - `ia-fit`, info `ia-fit/id`, `ia-fit/auth`, `ia-fit/enc` ; - - `encryptEvent(encKey, event)` → texte (IV aléatoire 96 bits + chiffré, - base64url) ; `decryptEvent(encKey, blob)` → événement ou erreur claire. - - Tests : vecteurs déterministes, aller-retour, clé fausse refusée, - normalisation. -2. **`server/`**, Node sans dépendance : - - site statique avec exactement les en-têtes et types MIME du Caddyfile (CSP, - nosniff, no-referrer, no-cache, `text/markdown`, compression des textes) ; - - relais : `POST` et `GET /api/journals/:journalId/events`, empreinte SHA-256 de - l'authToken retenue au premier dépôt puis exigée (temps constant), un fichier - JSON Lines par journal dans `DATA_DIR`, écritures sérialisées par journal, - `fsync` ; aucun journal d'accès ; quotas (blob 64 Ko, journal 20 Mo, blobs par - requête, requêtes par IP en mémoire avec `x-real-ip` ou le dernier élément de - `x-forwarded-for`), effacement des journaux inactifs depuis 400 jours ; - - OAuth 2.1 sans état : métadonnées, enregistrement dynamique où le `client_id` - porte ses redirect_uris signées (HMAC, secret persistant `DATA_DIR/.server-secret`), - `GET /oauth/authorize` → `/#/connecter-ia?`, `POST /oauth/authorize` en - JSON (PKCE S256 obligatoire, clé vérifiée contre un journal existant), code et - jetons chiffrés par une clé serveur (code 5 min à usage unique, accès 1 h, - rafraîchissement 90 jours), `/oauth/token` ; la clé de synchro n'apparaît - jamais dans un journal ni une erreur ; - - MCP sur `/mcp` (JSON-RPC 2.0, protocole 2025-06-18, 401 avec - `WWW-Authenticate`) ; à chaque requête : jeton → clé → journal déchiffré → - `foldEvents` → réponse. Outils `get_overview`, `get_program`, - `get_training_history`, `get_exercise_progress`, `get_body_weight`, - `propose_program`, `propose_session_change`, `propose_profile` ; - - variables `PORT`, `DATA_DIR`, `SITE_DIR`, `PUBLIC_URL` ; refus de démarrer si - `DATA_DIR` n'est pas inscriptible. -3. **`app/infra/sync.js`** : `createSync({store, syncKey, baseUrl})` → - `{push, pull, sync}`, état gardé dans le magasin `meta` ; événements invalides - ignorés et comptés ; mode d'emploi pour l'interface. -4. **Publication** : image `node:24-alpine` (version précise), non root, port 3000, - `/data` ; `make serve` ; `tests/test_site.sh` adapté et étendu (relais, OAuth, - MCP de bout en bout) ; `tests/server/*.test.js` ; `docs/mcp.md` ; - `docs/deploiement.md` (réglages CapRover). Ne rien publier. - -## Critères de réussite - -- `make setup`, `make lint` et `make test` passent (dont `make test-site`). -- Le parcours de bout en bout (dépôt, lecture, OAuth PKCE, MCP, proposition qui - ajoute un bloc) passe contre l'image de production. -- Commits petits, en français ; rien de poussé. - -## Résultat - -Livré sur la branche `lot-2-serveur` (main fusionné deux fois, sans conflit) : - -- `app/domain/sync-crypto.js` : `generateSyncKey`, `normalizeSyncKey`, - `isValidSyncKey`, `deriveKeys` → `{journalId, authToken, encKey}`, - `encryptEvent`, `decryptEvent`, `SyncCryptoError`. Clé de 26 caractères Crockford - (128 bits + 2 bits nuls de complément), affichée en 7 groupes. Vecteurs fixes - vérifiés contre `hkdfSync` de Node. -- `server/` (Node sans dépendance) : `main.js` (variables, refus sans `DATA_DIR` - inscriptible, effacement quotidien), `app.js` (routage), `static.js` (en-têtes et - types du Caddyfile, zstd/gzip, ETag), `relay.js` (JSON Lines, `fdatasync`, file - d'attente par journal, réparation d'une ligne coupée, quotas), `rate-limit.js` - (`X-Real-IP`, sinon dernier `X-Forwarded-For`), `oauth.js` (clients signés, - code et jetons AES-GCM, PKCE S256 obligatoire, codes à usage unique en - mémoire), `mcp.js` (8 outils, propositions `ProgramProposed` source `ai`). -- `app/infra/sync.js` : `createSync({store, syncKey, baseUrl})` → `push`, `pull`, - `sync` ; état dans `meta` (`sync:` : `lastSeq`, `known`). Ajout de - `getMeta`/`setMeta` à `app/infra/event-store.js` (hors périmètre initial, purement - additif). -- Publication : image `node:24.11.1-alpine3.22`, utilisateur `node`, port 3000, - `/data` ; `deploy/Caddyfile` retiré ; `make serve` ; `make package` embarque - `server/`, `app/domain/` et `package.json` ; `tsconfig.server.json` avec - `@types/node@24.10.1` (outil de dev, MIT) ; `scripts/deploy.sh` refuse aussi les - fichiers non suivis dans `server/`. -- Tests : `tests/domain/sync-crypto.test.js`, `tests/server/*.test.js` (relais, - quotas, IP, limite, OAuth, MCP, site, synchro à deux appareils) ; - `tests/test_site.sh` contre l'image, avec parcours de bout en bout par curl - (`tests/server/cli.js` pour la cryptographie). -- Docs : `docs/deploiement.md` (réglages CapRover), `docs/mcp.md`. - -Points ouverts : réglages CapRover (port 3000, volume `/data`, sauvegarde restic) -à faire et vérifier avant publication ; interface (`/#/connecter-ia`, écran Synchro, -appels de `sync.js`) à écrire ; outil MCP de changement de mode non prévu -(`ProgramProposed` ne porte pas de mode) ; un jeton de rafraîchissement ne peut pas -être révoqué avant 90 jours (sans état).