/** * Encrypted documents — and voice/video recordings, which are files with purpose CapsuleMedia — * entirely on the device. * * - A random per-file Content Key (AES-256-GCM). Its raw bytes are wrapped under the owner's * Vault Key (for the owner) and, at delivery, sealed to each recipient's key exactly like a * capsule's Content Key. * - The file is encrypted in 4 MiB chunks. Nonce = 8 random bytes (per file) ‖ 32-bit chunk index; * the chunk's position is bound as additional data, so chunks cannot be reordered or swapped * between files. * - The file NAME and MIME type are encrypted under the Content Key, so a recipient who holds the * key can read them too — and the server never can. */ import * as mb from './crypto'; import { api, apiGetBytes, apiPutBytes } from './api'; import type { CipherBlobDto, SharedFileDto, VaultFileDto } from './types'; export const CHUNK_SIZE = 4 * 1024 * 1024; const subtle = crypto.subtle; function nonce(prefix: Uint8Array, index: number): Uint8Array { const n = new Uint8Array(12); n.set(prefix.subarray(0, 8), 0); new DataView(n.buffer).setUint32(8, index, false); return n; } const aad = (fileId: string, index: number): Uint8Array => mb.utf8(`${fileId}:${index}`); const bs = (a: Uint8Array): BufferSource => a as unknown as BufferSource; export async function encryptChunk(key: CryptoKey, prefix: Uint8Array, fileId: string, index: number, data: Uint8Array): Promise { return new Uint8Array(await subtle.encrypt({ name: 'AES-GCM', iv: bs(nonce(prefix, index)), additionalData: bs(aad(fileId, index)) }, key, bs(data))); } export async function decryptChunk(key: CryptoKey, prefix: Uint8Array, fileId: string, index: number, data: ArrayBuffer): Promise { return new Uint8Array(await subtle.decrypt({ name: 'AES-GCM', iv: bs(nonce(prefix, index)), additionalData: bs(aad(fileId, index)) }, key, data)); } export interface UploadProgress { phase: 'encrypting' | 'uploading' | 'finishing'; chunk: number; chunks: number; percent: number; } /** Encrypt on the device and upload chunk by chunk. Returns the completed manifest. */ export async function uploadDocument( file: File, vaultKey: CryptoKey, opts: { folderId?: string | null; expiresOn?: string | null; purpose?: 'Document' | 'CapsuleMedia'; durationSeconds?: number | null; onProgress?: (p: UploadProgress) => void } = {}, ): Promise { const contentKey = await mb.generateVaultKey(); const raw = await mb.exportRawKey(contentKey); const prefix = mb.randomBytes(8); const name = await mb.aesEncrypt(contentKey, mb.utf8(file.name)); const mime = await mb.aesEncrypt(contentKey, mb.utf8(file.type || 'application/octet-stream')); const wrappedContentKey = await mb.aesEncrypt(vaultKey, raw); const chunks = Math.max(1, Math.ceil(file.size / CHUNK_SIZE)); const manifest = await api('/vault/files', { method: 'POST', body: { name, mime, sizeBytes: file.size, chunkCount: chunks, chunkSize: CHUNK_SIZE, noncePrefix: mb.b64(prefix), wrappedContentKey, folderId: opts.folderId ?? null, expiresOn: opts.expiresOn ?? null, purpose: opts.purpose ?? 'Document', durationSeconds: opts.durationSeconds ?? null, }, }); for (let i = 0; i < chunks; i++) { opts.onProgress?.({ phase: 'encrypting', chunk: i + 1, chunks, percent: Math.round((i / chunks) * 100) }); const slice = new Uint8Array(await file.slice(i * CHUNK_SIZE, Math.min(file.size, (i + 1) * CHUNK_SIZE)).arrayBuffer()); const ct = await encryptChunk(contentKey, prefix, manifest.id, i, slice); opts.onProgress?.({ phase: 'uploading', chunk: i + 1, chunks, percent: Math.round(((i + 0.5) / chunks) * 100) }); await apiPutBytes(`/vault/files/${manifest.id}/chunks/${i}`, ct); } opts.onProgress?.({ phase: 'finishing', chunk: chunks, chunks, percent: 100 }); return api(`/vault/files/${manifest.id}/complete`, { method: 'POST' }); } /** The owner's route to a file's Content Key: unwrap it with the Vault Key. */ export async function unwrapFileKey(f: { wrappedContentKey: CipherBlobDto }, vaultKey: CryptoKey): Promise<{ key: CryptoKey; raw: Uint8Array }> { const raw = await mb.aesDecrypt(vaultKey, f.wrappedContentKey); return { key: await mb.importAesKey(raw), raw }; } export async function readMeta(key: CryptoKey, f: { name: CipherBlobDto; mime: CipherBlobDto }): Promise<{ name: string; mime: string }> { return { name: mb.fromUtf8(await mb.aesDecrypt(key, f.name)), mime: mb.fromUtf8(await mb.aesDecrypt(key, f.mime)), }; } /** Fetch every chunk, decrypt on the device, assemble the file. */ export async function downloadDocument( f: { id: string; chunkCount: number; noncePrefix: string }, key: CryptoKey, mime: string, chunkPath: (index: number) => string, authed = true, onProgress?: (percent: number) => void, ): Promise { const prefix = mb.unb64(f.noncePrefix); const parts: BlobPart[] = []; for (let i = 0; i < f.chunkCount; i++) { const buf = await apiGetBytes(chunkPath(i), authed); const plain = await decryptChunk(key, prefix, f.id, i, buf); parts.push(plain.buffer as ArrayBuffer); // a fresh, exact-length buffer from subtle.decrypt onProgress?.(Math.round(((i + 1) / f.chunkCount) * 100)); } return new Blob(parts, { type: mime || 'application/octet-stream' }); } export function saveBlob(blob: Blob, filename: string): void { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = filename; document.body.appendChild(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 2000); } export function formatBytes(n: number): string { if (n < 1024) return `${n} B`; if (n < 1024 * 1024) return `${(n / 1024).toFixed(0)} KB`; if (n < 1024 * 1024 * 1024) return `${(n / (1024 * 1024)).toFixed(1)} MB`; return `${(n / (1024 * 1024 * 1024)).toFixed(2)} GB`; } /* ---------- the family vault (R-20): "can view now" ---------- */ /** Seal this document's key to a family member's account key, with its name and type sealed under the file key. */ export async function shareFileNow(vaultKey: CryptoKey, f: VaultFileDto, recipient: { id: string; accountPublicJwk?: string | null }): Promise { if (!recipient.accountPublicJwk) throw new Error('They need an account first.'); const { key, raw } = await unwrapFileKey(f, vaultKey); const meta = await readMeta(key, f); const metaCipher = await mb.aesEncrypt(key, mb.utf8(JSON.stringify(meta))); const sealed = await mb.sealToRecipient(raw, recipient.accountPublicJwk); await api(`/vault/files/${f.id}/share-now`, { method: 'POST', body: { recipientId: recipient.id, ...mb.packSealed(sealed), metaCipher } }); } /** The member's route to a shared document: their account key opens the wrap, the file key opens the metadata. */ export async function openSharedFile(privateKey: string, s: SharedFileDto): Promise<{ key: CryptoKey; name: string; mime: string }> { const raw = await mb.openAsRecipient(mb.unpackSealed({ ephemeralPublicJwk: s.wrap.ephemeralPublicJwk, wrap: s.wrap.wrap }), privateKey); const key = await mb.importAesKey(raw); const meta = JSON.parse(mb.fromUtf8(await mb.aesDecrypt(key, s.metaCipher))) as { name: string; mime: string }; return { key, name: meta.name, mime: meta.mime }; }