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(); + } +});