/** * Metadata encryption (R-11). Labels the server used to read in the clear — capsule titles, * recipient and guardian names, vault item titles — are sealed on the device: * * - names, relationships and vault item titles: AES-GCM under the owner's Vault Key; * - capsule titles: under the capsule's own Content Key, so a recipient can read the title with * the same wrap that opens the message, and the owner recovers it through ownerWrap. * * Rows from before this still carry plaintext ("legacy"); every reader here accepts both, and the * MetadataUpgradeRunner in the app shell seals the legacy rows once the vault is unlocked. */ import * as mb from './crypto'; import type { CipherBlobDto } from './types'; export const SEALED = '(sealed)'; export async function sealText(key: CryptoKey, text: string): Promise { return mb.aesEncrypt(key, mb.utf8(text)); } export async function openText(key: CryptoKey, blob: CipherBlobDto): Promise { return mb.fromUtf8(await mb.aesDecrypt(key, blob)); } /** A label that may be sealed (new rows) or still plaintext (legacy rows). */ export async function label(key: CryptoKey | null, cipher?: CipherBlobDto | null, plain?: string | null, fallback = SEALED): Promise { if (cipher) { if (!key) return fallback; try { return await openText(key, cipher); } catch { return fallback; } } return plain ?? fallback; } /** Owner side: a capsule title sealed under the capsule's Content Key, recovered through ownerWrap. */ export async function capsuleTitle( vaultKey: CryptoKey | null, c: { title?: string | null; titleCipher?: CipherBlobDto | null; ownerWrap?: CipherBlobDto | null }, fallback = '(sealed title)', ): Promise { if (c.titleCipher) { if (!vaultKey || !c.ownerWrap) return fallback; try { const raw = await mb.unwrapContentKeyAsOwner(c.ownerWrap, vaultKey); return await openText(await mb.importAesKey(raw), c.titleCipher); } catch { return fallback; } } return c.title ?? fallback; } /** Recipient side: the same title, opened with the recipient's own key through their wrap. */ export async function capsuleTitleAsRecipient( recipientPrivateKey: string | null, c: { capsuleTitle?: string | null; titleCipher?: CipherBlobDto | null; accountWrap?: { ephemeralPublicJwk: string; wrap: CipherBlobDto } | null }, fallback = 'A message', ): Promise { if (c.titleCipher) { if (!recipientPrivateKey || !c.accountWrap) return fallback; try { const raw = await mb.openAsRecipient(mb.unpackSealed({ ephemeralPublicJwk: c.accountWrap.ephemeralPublicJwk, wrap: c.accountWrap.wrap }), recipientPrivateKey); return await openText(await mb.importAesKey(raw), c.titleCipher); } catch { return fallback; } } return c.capsuleTitle ?? fallback; } /** Seal a capsule title with the Content Key the envelope was just sealed with. */ export async function sealCapsuleTitle(vaultKey: CryptoKey, ownerWrap: CipherBlobDto, title: string): Promise { const raw = await mb.unwrapContentKeyAsOwner(ownerWrap, vaultKey); return sealText(await mb.importAesKey(raw), title); }