// Rôle : compresse et chiffre une toolbox envoyée, pour que le serveur n'en garde qu'une copie illisible. const MAGIC = new TextEncoder().encode("SKS1"); const IV_BYTES = 12; const KEY_BYTES = 32; // Un envoi de 50 Mo compressés ne doit pas pouvoir faire déborder la mémoire une fois décompressé. export const SHARE_MAX_DECOMPRESSED_BYTES = 256 * 1024 * 1024; export class ShareCryptoError extends Error { constructor(code, message) { super(message); this.name = "ShareCryptoError"; this.code = code; } } function toBase64Url(bytes) { let binary = ""; bytes.forEach((byte) => { binary += String.fromCharCode(byte); }); return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); } function fromBase64Url(text) { if (!/^[A-Za-z0-9_-]+$/.test(String(text || ""))) return null; try { const binary = atob(text.replace(/-/g, "+").replace(/_/g, "/")); return Uint8Array.from(binary, (char) => char.charCodeAt(0)); } catch { return null; } } function concat(...parts) { const result = new Uint8Array(parts.reduce((sum, part) => sum + part.length, 0)); let offset = 0; parts.forEach((part) => { result.set(part, offset); offset += part.length; }); return result; } async function readLimited(stream, limit) { const reader = stream.getReader(); const chunks = []; let size = 0; for (;;) { const { done, value } = await reader.read(); if (done) break; size += value.length; if (size > limit) { await reader.cancel(); throw new ShareCryptoError("SHARE_FORMAT", "Cette toolbox est trop volumineuse une fois décompressée."); } chunks.push(value); } return concat(...chunks); } async function gzip(bytes) { const stream = new Blob([bytes]).stream().pipeThrough(new CompressionStream("gzip")); return new Uint8Array(await new Response(stream).arrayBuffer()); } function gunzip(bytes) { return readLimited(new Blob([bytes]).stream().pipeThrough(new DecompressionStream("gzip")), SHARE_MAX_DECOMPRESSED_BYTES); } export function isShareKey(text) { return fromBase64Url(text)?.length === KEY_BYTES; } // Format : "SKS1", IV de 12 octets, puis le JSON compressé et chiffré en AES-GCM 256. L'en-tête est authentifié. export async function encryptSharePayload(value) { const plain = await gzip(new TextEncoder().encode(JSON.stringify(value))); const key = await crypto.subtle.generateKey({ name: "AES-GCM", length: 256 }, true, ["encrypt"]); const iv = crypto.getRandomValues(new Uint8Array(IV_BYTES)); const cipher = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv, additionalData: MAGIC }, key, plain)); const rawKey = new Uint8Array(await crypto.subtle.exportKey("raw", key)); return { bytes: concat(MAGIC, iv, cipher), key: toBase64Url(rawKey) }; } export async function decryptSharePayload(input, keyText) { const rawKey = fromBase64Url(keyText); if (rawKey?.length !== KEY_BYTES) throw new ShareCryptoError("SHARE_KEY_INVALID", "Ce lien est incomplet : la clé de déchiffrement manque ou a été modifiée."); const bytes = input instanceof Uint8Array ? input : new Uint8Array(input); if (bytes.length < MAGIC.length + IV_BYTES + 16 || MAGIC.some((byte, index) => bytes[index] !== byte)) { throw new ShareCryptoError("SHARE_FORMAT", "Le contenu reçu n'est pas une toolbox envoyée depuis Sokko G."); } const key = await crypto.subtle.importKey("raw", rawKey, { name: "AES-GCM" }, false, ["decrypt"]); let plain; try { plain = await crypto.subtle.decrypt({ name: "AES-GCM", iv: bytes.subarray(MAGIC.length, MAGIC.length + IV_BYTES), additionalData: MAGIC }, key, bytes.subarray(MAGIC.length + IV_BYTES)); } catch { throw new ShareCryptoError("SHARE_KEY_INVALID", "Ce lien est incomplet ou a été modifié : la toolbox ne peut pas être déchiffrée."); } try { return JSON.parse(new TextDecoder().decode(await gunzip(new Uint8Array(plain)))); } catch (error) { if (error instanceof ShareCryptoError) throw error; throw new ShareCryptoError("SHARE_FORMAT", "Le contenu reçu n'est pas une toolbox valide."); } }