From ec37dd6d3c8a1838cecd3fbaaa6e9e8ff7ff4a75 Mon Sep 17 00:00:00 2001 From: Pierre MARTIN Date: Wed, 18 Nov 2026 01:00:01 +0100 Subject: [PATCH] =?UTF-8?q?Liens=20d'=C3=A9change=20:=20#import=20(compres?= =?UTF-8?q?s=C3=A9)=20et=20#import-json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Proposition {program, profile?, reason} validée, erreurs en français. Co-Authored-By: Claude Opus 5.5 --- app/domain/atelier.js | 2 +- app/domain/link.js | 159 ++++++++++++++++++++++++++++++++++++++ tests/domain/link.test.js | 76 ++++++++++++++++++ 3 files changed, 236 insertions(+), 1 deletion(-) create mode 100644 app/domain/link.js create mode 100644 tests/domain/link.test.js diff --git a/app/domain/atelier.js b/app/domain/atelier.js index f932877..d32bdbc 100644 --- a/app/domain/atelier.js +++ b/app/domain/atelier.js @@ -116,7 +116,7 @@ export function convertAtelier(input, { device, now = new Date() }) { * @param {string} [when] */ const add = (type, data, key, when = at) => - events.push(createEvent(type, data, { device, at: when, id: stableId("atelier", type + "|" + key) })); + events.push(createEvent(type, /** @type {any} */ (data), { device, at: when, id: stableId("atelier", type + "|" + key) })); const isExport = "instructions" in obj || "charges_courantes" in obj || "planning" in obj; const isProgramOnly = !isObject(obj.program) && Array.isArray(obj.sessions); diff --git a/app/domain/link.js b/app/domain/link.js new file mode 100644 index 0000000..42bfa5f --- /dev/null +++ b/app/domain/link.js @@ -0,0 +1,159 @@ +// Circuit d'échange par lien (ADR 0005, point 7) : une proposition de programme +// voyage dans la partie « # » d'une adresse, que le navigateur n'envoie jamais au +// serveur. Deux variantes : +// - `#import=` : JSON compressé (deflate-raw), produit par l'app ; +// - `#import-json=` : non compressé, pour une IA qui ne sait pas +// compresser (voir ai-brief.js). +// Le contenu est {program, profile?, reason} ; il devient un ProgramProposed que +// l'utilisateur adopte ou refuse après en avoir vu l'aperçu. + +import { createEvent } from "./events.js"; +import { stableId } from "./ids.js"; +import { validateProgram } from "./program.js"; +import { validateProfile } from "./profile.js"; + +/** Taille maximale acceptée une fois décompressé : protège d'une « bombe ». */ +const MAX_BYTES = 1_000_000; + +/** + * Contenu d'une proposition échangée. + * @typedef {object} ProposalPayload + * @property {import("./program.js").Program} program + * @property {import("./profile.js").Profile} [profile] profil complet, s'il change + * @property {string} reason + */ + +/** Erreur lisible, avec la liste des problèmes à montrer (ou à renvoyer à l'IA). */ +export class ProposalError extends Error { + /** @param {string} message @param {string[]} [problems] */ + constructor(message, problems = []) { + super(problems.length ? message + "\n- " + problems.join("\n- ") : message); + this.name = "ProposalError"; + this.problems = problems; + } +} + +/** + * Vérifie un contenu {program, profile?, reason} (ou un programme nu) et en fait + * une proposition. L'identifiant est tiré du contenu : rouvrir le même lien ne + * crée pas une deuxième proposition. + * @param {unknown} payload + * @param {"link"|"import"} source + * @param {{device: string, now?: Date}} options + * @returns {Extract} + */ +export function createProposal(payload, source, { device, now = new Date() }) { + if (typeof payload !== "object" || payload === null || Array.isArray(payload)) + throw new ProposalError("La proposition doit être un objet JSON {program, profile, reason}."); + const p = /** @type {Record} */ (payload); + const wrapped = "program" in p; + const program = wrapped ? p.program : p; + const problems = validateProgram(program).map((x) => "programme : " + x); + if (wrapped && p.profile !== undefined) problems.push(...validateProfile(p.profile).map((x) => "profil : " + x)); + if (wrapped && p.reason !== undefined && typeof p.reason !== "string") problems.push("'reason' doit être un texte."); + if (problems.length) throw new ProposalError("Proposition invalide :", problems); + const data = { program, source, reason: wrapped && typeof p.reason === "string" ? p.reason : "" }; + if (wrapped && p.profile !== undefined) Object.assign(data, { profile: p.profile }); + // `profile` est un champ facultatif de ProgramProposed (cadrage du 2026-11-18). + return /** @type {any} */ (createEvent("ProgramProposed", /** @type {any} */ (data), { + device, at: now.toISOString(), id: stableId(source, JSON.stringify(data)), + })); +} + +/** + * Lien de proposition : `#import=`. + * @param {string} baseUrl adresse de l'app ; une éventuelle partie « # » est retirée + * @param {ProposalPayload} payload + * @returns {Promise} + */ +export async function encodeProposalLink(baseUrl, { program, profile, reason }) { + const problems = validateProgram(program); + if (profile !== undefined) problems.push(...validateProfile(profile)); + if (problems.length) throw new ProposalError("Proposition invalide :", problems); + const json = JSON.stringify(profile === undefined ? { program, reason } : { program, profile, reason }); + const packed = await transform(new TextEncoder().encode(json), new CompressionStream("deflate-raw")); + return baseUrl.split("#")[0] + "#import=" + toBase64Url(packed); +} + +/** + * Lit la partie « # » d'une adresse (ou l'adresse entière) et en fait une proposition. + * @param {string} hash « #import=… », « #import-json=… » ou une adresse complète + * @param {{device: string, now?: Date}} options + * @returns {Promise>} + */ +export async function decodeProposalFragment(hash, options) { + const fragment = hash.includes("#") ? hash.slice(hash.indexOf("#") + 1) : hash; + let json; + if (fragment.startsWith("import=")) { + let bytes; + try { + bytes = fromBase64Url(fragment.slice("import=".length)); + bytes = await transform(bytes, new DecompressionStream("deflate-raw")); + } catch (e) { + if (e instanceof ProposalError) throw e; + throw new ProposalError("Lien abîmé ou incomplet : les données compressées sont illisibles. Recopie le lien en entier."); + } + json = new TextDecoder().decode(bytes); + } else if (fragment.startsWith("import-json=")) { + const raw = fragment.slice("import-json=".length); + try { + json = decodeURIComponent(raw); + } catch { + json = raw; // un « % » isolé : on tente le texte tel quel + } + if (json.length > MAX_BYTES) throw new ProposalError("Proposition trop volumineuse."); + } else { + throw new ProposalError("Ce lien ne contient pas de proposition (« #import=… » ou « #import-json=… » attendu)."); + } + let payload; + try { + payload = JSON.parse(json); + } catch (e) { + throw new ProposalError("Le contenu du lien n'est pas du JSON valide (lien tronqué ?) : " + /** @type {Error} */ (e).message); + } + return createProposal(payload, "link", options); +} + +/** + * Passe des octets dans un flux de (dé)compression, en plafonnant la sortie. + * @param {Uint8Array} bytes + * @param {CompressionStream|DecompressionStream} stream + */ +async function transform(bytes, stream) { + const writer = stream.writable.getWriter(); + // Écriture non attendue : le flux ne se vide qu'au fil de la lecture. + writer.write(/** @type {Uint8Array} */ (bytes)).catch(() => {}); + writer.close().catch(() => {}); + const reader = stream.readable.getReader(); + /** @type {Uint8Array[]} */ + const chunks = []; + let size = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + size += value.length; + if (size > MAX_BYTES) { + await reader.cancel(); + throw new ProposalError("Proposition trop volumineuse."); + } + chunks.push(value); + } + const out = new Uint8Array(size); + let offset = 0; + for (const c of chunks) out.set(c, (offset += c.length) - c.length); + return out; +} + +/** @param {Uint8Array} bytes */ +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 */ +function fromBase64Url(text) { + if (text.length > MAX_BYTES) throw new ProposalError("Proposition trop volumineuse."); + const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/")); + return Uint8Array.from(binary, (c) => c.charCodeAt(0)); +} diff --git a/tests/domain/link.test.js b/tests/domain/link.test.js new file mode 100644 index 0000000..86fd844 --- /dev/null +++ b/tests/domain/link.test.js @@ -0,0 +1,76 @@ +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { encodeProposalLink, decodeProposalFragment, createProposal } from "../../app/domain/link.js"; +import { validateEvent } from "../../app/domain/events.js"; +import { DEFAULT_PROGRAM } from "../../app/domain/default-program.js"; + +const base = "https://ia-fit.sans.pub/"; +const opts = { device: "phone", now: new Date("2026-11-18T10:00:00Z") }; +const profile = { + goal: "Prendre de la force", context: "Débutant, à la maison", equipment: ["haltères"], + constraints: ["Genou gauche fragile"], heightCm: 180, sessionMinutes: 45, +}; + +test("aller-retour d'un lien compressé : une proposition « link » valide", async () => { + const url = await encodeProposalLink(base + "#ancien", { program: DEFAULT_PROGRAM, reason: "Plus de volume" }); + assert.match(url, /^https:\/\/ia-fit\.sans\.pub\/#import=[A-Za-z0-9_-]+$/); + const e = await decodeProposalFragment(new URL(url).hash, opts); + assert.equal(validateEvent(e), null); + assert.equal(e.type, "ProgramProposed"); + assert.equal(e.data.source, "link"); + assert.equal(e.data.reason, "Plus de volume"); + assert.deepEqual(e.data.program, DEFAULT_PROGRAM); + assert.equal(e.at, "2026-11-18T10:00:00.000Z"); + // l'adresse complète est acceptée aussi, et le même lien donne la même proposition + assert.equal((await decodeProposalFragment(url, opts)).id, e.id); + // taille du lien pour le programme de départ (rapportée dans le plan) + const json = JSON.stringify({ program: DEFAULT_PROGRAM, reason: "Plus de volume" }); + const plain = base + "#import-json=" + encodeURIComponent(json); + console.log(`# programme de départ : lien compressé ${url.length} caractères, non compressé ${plain.length}, JSON ${json.length}`); + assert.ok(url.length < 2000, "un lien compressé tient sous 2 000 caractères"); + assert.ok(url.length < plain.length / 2); +}); + +test("le profil voyage avec le programme et il est validé", async () => { + const url = await encodeProposalLink(base, { program: DEFAULT_PROGRAM, profile, reason: "Premier programme" }); + const e = await decodeProposalFragment(url, opts); + assert.deepEqual(/** @type {any} */ (e.data).profile, profile); + await assert.rejects(encodeProposalLink(base, { program: DEFAULT_PROGRAM, profile: { ...profile, sessionMinutes: 2 }, reason: "" }), + /sessionMinutes/); +}); + +test("variante non compressée #import-json, telle qu'une IA l'écrit", async () => { + const payload = { program: DEFAULT_PROGRAM, profile, reason: "Proposé par l'IA" }; + const e = await decodeProposalFragment("#import-json=" + encodeURIComponent(JSON.stringify(payload)), opts); + assert.equal(e.data.reason, "Proposé par l'IA"); + assert.deepEqual(e.data.program, DEFAULT_PROGRAM); + // un programme nu, et un JSON non encodé, passent aussi + const bare = await decodeProposalFragment("#import-json=" + JSON.stringify(DEFAULT_PROGRAM), opts); + assert.equal(bare.data.reason, ""); +}); + +test("erreurs en français : programme invalide, lien abîmé, pas de proposition", async () => { + const bad = structuredClone(DEFAULT_PROGRAM); + bad.sessions[0].exercises[0].ref = "pompes"; + bad.sessions[1].exercises[0].sets = 0; + await assert.rejects(decodeProposalFragment("#import-json=" + encodeURIComponent(JSON.stringify({ program: bad, reason: "" })), opts), + (/** @type {any} */ err) => { + assert.match(err.message, /^Proposition invalide :/); + assert.equal(err.problems.length, 2); + assert.match(err.problems[0], /référence inconnue « pompes »/); + return true; + }); + const url = await encodeProposalLink(base, { program: DEFAULT_PROGRAM, reason: "" }); + await assert.rejects(decodeProposalFragment(url.slice(0, -40), opts), /Lien abîmé ou incomplet/); + await assert.rejects(decodeProposalFragment("#import=@@@", opts), /Lien abîmé/); + await assert.rejects(decodeProposalFragment("#pair=abc", opts), /ne contient pas de proposition/); + await assert.rejects(decodeProposalFragment("#import-json={program:", opts), /pas du JSON valide/); +}); + +test("createProposal : source « import », identifiant tiré du contenu", () => { + const a = createProposal({ program: DEFAULT_PROGRAM, reason: "x" }, "import", opts); + const b = createProposal({ program: DEFAULT_PROGRAM, reason: "x" }, "import", { device: "pc" }); + assert.equal(a.data.source, "import"); + assert.equal(a.id, b.id); + assert.notEqual(a.id, createProposal({ program: DEFAULT_PROGRAM, reason: "y" }, "import", opts).id); +});