/** * Deterministic sealing, for cross-language test vectors only. * * Production sealing takes its nonce from the `CryptoProvider`, which is the * point: a nonce reused under one content key breaks AES-GCM outright. A * vector, though, has to pin every byte so a Kotlin port can reproduce the * same wire bytes — so this takes the nonce from the caller. * * Lives behind its own export (`@shade/vault/testing`) and is not re-exported * from the package root, so it cannot be picked up by accident from an * autocomplete list next to `sealObject`. */ import { entryLocator, objectHash, packEntry, vaultObjectAad, type EntryLocator, type PackOptions, type PackedEntry, type SealedObject, } from './crypto.js'; const NONCE_LEN = 12; /** `sealObject` with a caller-chosen nonce. Never use outside vectors and tests. */ export async function sealObjectWithNonce( contentKey: Uint8Array, vaultId: string, plaintext: Uint8Array, nonce: Uint8Array, ): Promise { if (nonce.length !== NONCE_LEN) throw new Error(`nonce must be ${NONCE_LEN} bytes`); const subtle = globalThis.crypto.subtle; const key = await subtle.importKey( 'raw', contentKey as unknown as ArrayBuffer, 'AES-GCM', false, ['encrypt'], ); const ct = new Uint8Array( await subtle.encrypt( { name: 'AES-GCM', iv: nonce as unknown as ArrayBuffer, additionalData: vaultObjectAad(vaultId) as unknown as ArrayBuffer, }, key, plaintext as unknown as ArrayBuffer, ), ); const bytes = new Uint8Array(NONCE_LEN + ct.length); bytes.set(nonce, 0); bytes.set(ct, NONCE_LEN); return { hash: objectHash(bytes), bytes }; } /** * `sealEntry` with one caller-chosen nonce per part — the same `packEntry` * the real writer uses, so a vector pins the production format, not a copy. */ export async function sealEntryWithNonces( contentKey: Uint8Array, vaultId: string, plaintext: Uint8Array, nonceFor: (partIndex: number) => Uint8Array, opts: PackOptions = {}, ): Promise<{ packed: PackedEntry; locator: EntryLocator; objects: SealedObject[] }> { const packed = await packEntry(plaintext, opts); const objects: SealedObject[] = []; for (let i = 0; i < packed.chunks.length; i++) { objects.push(await sealObjectWithNonce(contentKey, vaultId, packed.chunks[i]!, nonceFor(i))); } return { packed, locator: entryLocator(packed, objects), objects }; }