// 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)); }