// Rôle : vérifie que le chiffrement d'un envoi de toolbox est réversible avec la bonne clé seulement. import assert from "node:assert/strict"; import { test } from "node:test"; import { decryptSharePayload, encryptSharePayload, isShareKey, ShareCryptoError } from "../website/src/features/toolboxes/sharing/shareCrypto.js"; const sample = { version: 2, toolbox: { id: "tbx1", name: "Monster Hunter Wilds — été", modules: [{ id: "mod1", type: "checklist", title: "Quêtes" }] }, modules: { mod1: { sections: [{ id: "sec1", title: "Rang élevé", items: [] }] } } }; async function rejectsWith(promise, code) { await assert.rejects(promise, (error) => error instanceof ShareCryptoError && error.code === code); } test("an encrypted share decrypts back to the same payload", async () => { const { bytes, key } = await encryptSharePayload(sample); assert.ok(isShareKey(key)); assert.equal(new TextDecoder().decode(bytes.subarray(0, 4)), "SKS1"); assert.equal(new TextDecoder().decode(bytes).includes("Monster"), false); assert.deepEqual(await decryptSharePayload(bytes, key), sample); assert.deepEqual(await decryptSharePayload(bytes.buffer, key), sample); }); test("each share uses its own key and IV", async () => { const first = await encryptSharePayload(sample); const second = await encryptSharePayload(sample); assert.notEqual(first.key, second.key); assert.notDeepEqual(first.bytes.subarray(4, 16), second.bytes.subarray(4, 16)); }); test("a wrong, missing or malformed key is refused", async () => { const { bytes } = await encryptSharePayload(sample); const other = await encryptSharePayload(sample); await rejectsWith(decryptSharePayload(bytes, other.key), "SHARE_KEY_INVALID"); await rejectsWith(decryptSharePayload(bytes, ""), "SHARE_KEY_INVALID"); await rejectsWith(decryptSharePayload(bytes, "abc"), "SHARE_KEY_INVALID"); await rejectsWith(decryptSharePayload(bytes, "not+base64url/"), "SHARE_KEY_INVALID"); assert.equal(isShareKey(other.key.slice(1)), false); }); test("tampered content or an unknown format is refused", async () => { const { bytes, key } = await encryptSharePayload(sample); const tampered = bytes.slice(); tampered[tampered.length - 1] ^= 1; await rejectsWith(decryptSharePayload(tampered, key), "SHARE_KEY_INVALID"); const header = bytes.slice(); header[0] = 0; await rejectsWith(decryptSharePayload(header, key), "SHARE_FORMAT"); await rejectsWith(decryptSharePayload(new Uint8Array(10), key), "SHARE_FORMAT"); });