/* ============================================================================ * CapsuleBridge — Zero-Knowledge Crypto Core (hardened) * * Runs entirely in the browser via Web Crypto + WASM. The server stores only * ciphertext, wrapped keys, and a KDF descriptor — this whole file can change * without any server change, because the server holds no key. * * KDF: Argon2id (hash-wasm, m=19 MiB / t=2) — replaces the PBKDF2 stand-in. * Vault: AES-256-GCM. * Envelope: HYBRID post-quantum — X25519-style ECDH (P-256) + ML-KEM-768. * A capsule's content key is wrapped to each recipient using BOTH a * classical ECDH secret and a post-quantum ML-KEM secret; an attacker * must break both. This defends the 100-year guarantee against * "harvest now, decrypt later." (analysis/02-data-security-architecture.md §1) * ==========================================================================*/ import { argon2id } from 'hash-wasm'; import { ml_kem768 } from '@noble/post-quantum/ml-kem.js'; const subtle = crypto.subtle; const encoder = new TextEncoder(); const decoder = new TextDecoder(); const HKDF_INFO = encoder.encode('MB-capsule-kek-v3'); export interface CipherBlob { iv: string; ct: string } /** A recipient keypair. Both halves are composite JSON strings (ECDH + ML-KEM). */ export interface RecipientKeypair { publicKey: string; privateKey: string } /** A content key sealed to one recipient (hybrid). */ export interface SealedKey { epk: JsonWebKey; kemCt: string; wrapped: CipherBlob } export interface CapsuleEnvelope { /** Wraps to recipients' ACCOUNT keys (present for recipients who accepted their intro). */ accountWraps?: Record; v: number; alg: string; payload: CipherBlob; ownerWrap: CipherBlob; recipientWraps: Record; sealedAt: string; } interface CompositePublic { v: 2; ecdh: JsonWebKey; kem: string } interface CompositePrivate { v: 2; ecdh: JsonWebKey; kem: string } /* ---------- encoding ---------- */ const bs = (a: Uint8Array): BufferSource => a as unknown as BufferSource; const u8 = (buf: ArrayBuffer | Uint8Array): Uint8Array => (buf instanceof Uint8Array ? buf : new Uint8Array(buf)); export const b64 = (buf: ArrayBuffer | Uint8Array): string => btoa(String.fromCharCode(...u8(buf))); export const unb64 = (s: string): Uint8Array => Uint8Array.from(atob(s), (c) => c.charCodeAt(0)); export const utf8 = (s: string): Uint8Array => encoder.encode(s); export const fromUtf8 = (buf: ArrayBuffer | Uint8Array): string => decoder.decode(buf); export const randomBytes = (n: number): Uint8Array => crypto.getRandomValues(new Uint8Array(n)); const concat = (a: Uint8Array, b: Uint8Array): Uint8Array => { const o = new Uint8Array(a.length + b.length); o.set(a); o.set(b, a.length); return o; }; /* ---------- master key: password -> AES-GCM key (Argon2id) ---------- */ const ARGON = { m: 19456, t: 2, p: 1 }; /** Produce a KDF descriptor for a NEW account: `argon2id:m=..,t=..,p=..:[:rc]`. * The trailing `rc` marker means the master key also mixes in the account's recovery code * (the Emergency Kit): a stolen database plus a guessable password is then not enough. */ export function newKdfSalt(withRecoveryCode = true): string { return `argon2id:m=${ARGON.m},t=${ARGON.t},p=${ARGON.p}:${b64(randomBytes(16))}${withRecoveryCode ? ':rc' : ''}`; } /** Does this account's key derivation need the recovery code as well as the password? */ export function kdfNeedsRecoveryCode(kdfSalt: string | null | undefined): boolean { return !!kdfSalt && kdfSalt.split(':')[3] === 'rc'; } /* ---------- recovery code (Emergency Kit) ---------- */ // Crockford base32 — no I, L, O or U, so a printed code survives handwriting and reading aloud. const RC_ALPHABET = '0123456789ABCDEFGHJKMNPQRSTVWXYZ'; /** 25 random characters (125 bits), generated on the device and never sent to the server. */ export function generateRecoveryCode(): string { let s = ''; for (const b of randomBytes(25)) s += RC_ALPHABET[b % 32]; // 256 is a multiple of 32: no bias return s; } /** Accept any typing of the code: case, dashes, spaces, the CB prefix, and the usual look-alikes. */ export function normalizeRecoveryCode(input: string): string { let s = input.toUpperCase().replace(/[^0-9A-Z]/g, ''); if (s.startsWith('CB') && s.length >= 27) s = s.slice(2); return s.replace(/[IL]/g, '1').replace(/O/g, '0').replace(/U/g, 'V'); } /** The printed form: CB-XXXXX-XXXXX-XXXXX-XXXXX-XXXXX. */ export function formatRecoveryCode(code: string): string { const n = normalizeRecoveryCode(code); return 'CB-' + (n.match(/.{1,5}/g) ?? []).join('-'); } export class RecoveryCodeRequiredError extends Error { constructor() { super('This account is protected with a recovery code. Enter the code from your Emergency Kit.'); this.name = 'RecoveryCodeRequiredError'; } } /** HKDF(password-derived key, salt = SHA-256(recovery code)) — the 1Password "Secret Key" pattern. */ async function mixRecoveryCode(passwordKey: Uint8Array, code: string): Promise { const salt = u8(await subtle.digest('SHA-256', bs(utf8(normalizeRecoveryCode(code))))); const ikm = await subtle.importKey('raw', bs(passwordKey), 'HKDF', false, ['deriveBits']); return u8(await subtle.deriveBits({ name: 'HKDF', hash: 'SHA-256', salt: bs(salt), info: bs(utf8('CB-master-key-v2')) }, ikm, 256)); } export async function deriveMasterKey(password: string, kdfSalt: string, recoveryCode?: string | null): Promise { let raw: Uint8Array; if (kdfSalt.startsWith('argon2id:')) { const parts = kdfSalt.split(':'); const [, paramStr, saltB64] = parts; const p = Object.fromEntries( paramStr.split(',').map((kv) => { const [k, v] = kv.split('='); return [k, Number(v)] as [string, number]; }), ) as Record; raw = await argon2id({ password, salt: unb64(saltB64), parallelism: p.p, iterations: p.t, memorySize: p.m, hashLength: 32, outputType: 'binary', }); if (parts[3] === 'rc') { if (!recoveryCode) throw new RecoveryCodeRequiredError(); raw = await mixRecoveryCode(raw, recoveryCode); } } else { // Legacy PBKDF2 accounts (kdfSalt is a plain base64 salt). const base = await subtle.importKey('raw', bs(utf8(password)), 'PBKDF2', false, ['deriveBits']); raw = u8(await subtle.deriveBits({ name: 'PBKDF2', salt: bs(unb64(kdfSalt)), iterations: 600_000, hash: 'SHA-256' }, base, 256)); } return subtle.importKey('raw', bs(raw), { name: 'AES-GCM' }, false, ['encrypt', 'decrypt']); } /* ---------- vault key ---------- */ export function generateVaultKey(): Promise { return subtle.generateKey({ name: 'AES-GCM', length: 256 }, true, ['encrypt', 'decrypt']); } export async function exportRawKey(key: CryptoKey): Promise { return u8(await subtle.exportKey('raw', key)); } export function importAesKey(raw: Uint8Array): Promise { return subtle.importKey('raw', bs(raw), { name: 'AES-GCM' }, true, ['encrypt', 'decrypt']); } /* ---------- AES-256-GCM ---------- */ export async function aesEncrypt(key: CryptoKey, plaintext: Uint8Array): Promise { const iv = randomBytes(12); const ct = await subtle.encrypt({ name: 'AES-GCM', iv: bs(iv) }, key, bs(plaintext)); return { iv: b64(iv), ct: b64(ct) }; } export async function aesDecrypt(key: CryptoKey, blob: CipherBlob): Promise { return u8(await subtle.decrypt({ name: 'AES-GCM', iv: bs(unb64(blob.iv)) }, key, bs(unb64(blob.ct)))); } /* ---------- wrap Vault Key under Master Key ---------- */ export async function wrapVaultKey(masterKey: CryptoKey, vaultKey: CryptoKey): Promise { return aesEncrypt(masterKey, await exportRawKey(vaultKey)); } export async function unwrapVaultKey(masterKey: CryptoKey, wrapped: CipherBlob): Promise { return importAesKey(await aesDecrypt(masterKey, wrapped)); } /* ---------- hybrid recipient envelope (ECDH P-256 + ML-KEM-768) ---------- */ export async function generateRecipientKeypair(): Promise { const ecdh = await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits']); const kem = ml_kem768.keygen(); const pub: CompositePublic = { v: 2, ecdh: await subtle.exportKey('jwk', ecdh.publicKey), kem: b64(kem.publicKey) }; const priv: CompositePrivate = { v: 2, ecdh: await subtle.exportKey('jwk', ecdh.privateKey), kem: b64(kem.secretKey) }; return { publicKey: JSON.stringify(pub), privateKey: JSON.stringify(priv) }; } const importEcdhPub = (jwk: JsonWebKey) => subtle.importKey('jwk', jwk, { name: 'ECDH', namedCurve: 'P-256' }, true, []); const importEcdhPriv = (jwk: JsonWebKey) => subtle.importKey('jwk', jwk, { name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits']); // Combiner binds BOTH shared secrets AND the transcript (ephemeral pubkey + KEM // ciphertext) into the KEK, following HPKE/X-Wing guidance so the hybrid KEM is // robust rather than a bare KDF(ss1‖ss2) concatenation. The transcript is first // hashed to a fixed 32 bytes: the ML-KEM ciphertext alone is 1088 bytes and some // WebCrypto engines (Node, and per-spec-optional implementations) cap HKDF `info` // at 1024 bytes — hashing keeps the binding while staying portable. async function kekFromSecrets(secrets: Uint8Array, transcript: Uint8Array): Promise { const th = u8(await subtle.digest('SHA-256', bs(transcript))); const base = await subtle.importKey('raw', bs(secrets), 'HKDF', false, ['deriveKey']); return subtle.deriveKey( { name: 'HKDF', hash: 'SHA-256', salt: bs(new Uint8Array(0)), info: bs(concat(HKDF_INFO, th)) }, base, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt'], ); } export async function sealToRecipient(contentKeyRaw: Uint8Array, recipientPublicKey: string): Promise { const pub = JSON.parse(recipientPublicKey) as CompositePublic; // classical ECDH leg const ecdhPub = await importEcdhPub(pub.ecdh); const eph = await subtle.generateKey({ name: 'ECDH', namedCurve: 'P-256' }, true, ['deriveBits']); const epk = await subtle.exportKey('jwk', eph.publicKey); const ss1 = u8(await subtle.deriveBits({ name: 'ECDH', public: ecdhPub }, eph.privateKey, 256)); // post-quantum ML-KEM leg const { cipherText, sharedSecret: ss2 } = ml_kem768.encapsulate(unb64(pub.kem)); // combine both secrets, binding the transcript (epk + KEM ciphertext) const transcript = concat(utf8(JSON.stringify(epk)), u8(cipherText)); const kek = await kekFromSecrets(concat(ss1, u8(ss2)), transcript); const wrapped = await aesEncrypt(kek, contentKeyRaw); return { epk, kemCt: b64(cipherText), wrapped }; } export async function openAsRecipient(sealed: SealedKey, recipientPrivateKey: string): Promise { const priv = JSON.parse(recipientPrivateKey) as CompositePrivate; const ecdhPriv = await importEcdhPriv(priv.ecdh); const ephPub = await importEcdhPub(sealed.epk); const ss1 = u8(await subtle.deriveBits({ name: 'ECDH', public: ephPub }, ecdhPriv, 256)); const ss2 = ml_kem768.decapsulate(unb64(sealed.kemCt), unb64(priv.kem)); const transcript = concat(utf8(JSON.stringify(sealed.epk)), unb64(sealed.kemCt)); const kek = await kekFromSecrets(concat(ss1, u8(ss2)), transcript); return aesDecrypt(kek, sealed.wrapped); } /** Wire form: fold epk + kemCt into the single `ephemeralPublicJwk` string field. */ export function packSealed(s: SealedKey): { ephemeralPublicJwk: string; wrap: CipherBlob } { return { ephemeralPublicJwk: JSON.stringify({ epk: s.epk, kemCt: s.kemCt }), wrap: s.wrapped }; } export function unpackSealed(w: { ephemeralPublicJwk: string; wrap: CipherBlob }): SealedKey { const { epk, kemCt } = JSON.parse(w.ephemeralPublicJwk) as { epk: JsonWebKey; kemCt: string }; return { epk, kemCt, wrapped: w.wrap }; } /* ---------- capsule ---------- */ export async function sealCapsule(opts: { contentText: string; ownerVaultKey: CryptoKey; recipients: { id: string; publicKey: string; accountPublicKey?: string | null }[]; }): Promise { const contentKey = await generateVaultKey(); const contentKeyRaw = await exportRawKey(contentKey); const payload = await aesEncrypt(contentKey, utf8(opts.contentText)); const recipientWraps: Record = {}; const accountWraps: Record = {}; for (const r of opts.recipients) { recipientWraps[r.id] = await sealToRecipient(contentKeyRaw, r.publicKey); // A recipient who accepted their intro also gets a wrap to their own account key — no Keycard needed at delivery. if (r.accountPublicKey) accountWraps[r.id] = await sealToRecipient(contentKeyRaw, r.accountPublicKey); } const ownerWrap = await aesEncrypt(opts.ownerVaultKey, contentKeyRaw); return { v: 2, alg: 'AES-256-GCM + ECDH-P256 + ML-KEM-768 (hybrid)', payload, ownerWrap, recipientWraps, accountWraps, sealedAt: new Date().toISOString() }; } export async function openCapsuleAsOwner(env: CapsuleEnvelope, ownerVaultKey: CryptoKey): Promise { const contentKeyRaw = await aesDecrypt(ownerVaultKey, env.ownerWrap); const contentKey = await importAesKey(contentKeyRaw); return fromUtf8(await aesDecrypt(contentKey, env.payload)); } export async function openCapsuleAsRecipient(env: CapsuleEnvelope, recipientId: string, recipientPrivateKey: string): Promise { const sealed = env.recipientWraps[recipientId]; if (!sealed) throw new Error('This message was not sealed for that person.'); const contentKeyRaw = await openAsRecipient(sealed, recipientPrivateKey); const contentKey = await importAesKey(contentKeyRaw); return fromUtf8(await aesDecrypt(contentKey, env.payload)); } /** The raw per-capsule Content Key, recovered with the owner's Vault Key — used to re-seal an * existing capsule to a recipient's new ACCOUNT key after they accepted their intro. */ export async function unwrapContentKeyAsOwner(ownerWrap: CipherBlob, ownerVaultKey: CryptoKey): Promise { return aesDecrypt(ownerVaultKey, ownerWrap); }