/** * Seed phrases, split on the device (R-19). The phrase is checked against the BIP-39 word list and * checksum, turned back into its entropy, split with Shamir's scheme, and each share is sealed as a * HighValue capsule to the person who will hold it. The server learns the shape of the split and * nothing else. A rehearsal reopens the owner's copies, recombines a random subset and proves the * phrase still comes back — without ever displaying it. */ import * as bip39 from '@scure/bip39'; import { wordlist } from '@scure/bip39/wordlists/english.js'; import * as mb from './crypto'; import { api } from './api'; import { combine, decodeShare, encodeShare, split, type Share } from './shamir'; import { openText, sealCapsuleTitle, sealText } from './metadata'; import type { CapsuleDto, CipherBlobDto, RecipientDto, SeedSplitDto } from './types'; export const WORD_COUNTS = [12, 15, 18, 21, 24]; export function normalizePhrase(input: string): string { return input.trim().toLowerCase().split(/\s+/).filter(Boolean).join(' '); } export type PhraseCheck = { ok: true; words: number; entropy: Uint8Array } | { ok: false; error: string }; /** Word list, count and checksum — the same checks a wallet makes when restoring. */ export function checkPhrase(input: string): PhraseCheck { const phrase = normalizePhrase(input); const words = phrase ? phrase.split(' ') : []; if (!WORD_COUNTS.includes(words.length)) return { ok: false, error: `A seed phrase has 12, 15, 18, 21 or 24 words — this has ${words.length}.` }; const unknown = words.filter((w) => !wordlist.includes(w)); if (unknown.length) return { ok: false, error: `Not on the word list: ${unknown.slice(0, 3).join(', ')}${unknown.length > 3 ? '…' : ''}. Check the spelling.` }; if (!bip39.validateMnemonic(phrase, wordlist)) return { ok: false, error: 'The checksum does not match — a word is probably wrong or out of order.' }; return { ok: true, words: words.length, entropy: bip39.mnemonicToEntropy(phrase, wordlist) }; } export function phraseFromEntropy(entropy: Uint8Array): string { return bip39.entropyToMnemonic(entropy, wordlist); } export interface HolderRef { index: number; name: string; hint?: string | null } export interface OpenedSplit { label: string; holders: HolderRef[] } /** The words a holder reads when their share capsule opens. */ export function shareCapsuleText(opts: { label: string; share: Share; total: number; holder: string; owner: string; recoverUrl: string }): string { const { label, share, total, holder, owner, recoverUrl } = opts; return ( `${holder}, this is share ${share.index} of ${total} of the recovery phrase for “${label}”, left by ${owner}.\n\n` + `${encodeShare(share)}\n\n` + `${share.threshold} of the ${total} shares are needed to rebuild the phrase; this one alone reveals nothing. ` + `Give it only to the person settling ${owner}'s affairs — in person, or on a call you started. ` + `Never to anyone who contacts you asking for it, however convincing. ` + `They combine the shares at ${recoverUrl} on their own device; nobody at CapsuleBridge can see or rebuild the phrase.` ); } export function findShareText(text: string): string | null { const m = text.match(/cbseed1-[a-z2-7-]+/i); return m ? m[0] : null; } async function sha256Hex(bytes: Uint8Array): Promise { return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', new Uint8Array(bytes)))).map((b) => b.toString(16).padStart(2, '0')).join(''); } export interface SplitPlan { label: string; threshold: number; wordCount: number; entropy: Uint8Array; assetId: string | null; holders: { recipient: RecipientDto; name: string; hint?: string }[]; ownerName: string; } /** Split, seal one HighValue capsule per holder, then record the shape of the split. */ export async function createSplit(vaultKey: CryptoKey, mapKey: CryptoKey, plan: SplitPlan): Promise { const n = plan.holders.length; const shares = split(plan.entropy, plan.threshold, n); const recoverUrl = `${window.location.origin}/recover`; const shareRefs: { index: number; capsuleId: string; recipientId: string }[] = []; for (let i = 0; i < n; i++) { const h = plan.holders[i]; const text = shareCapsuleText({ label: plan.label, share: shares[i], total: n, holder: h.name, owner: plan.ownerName, recoverUrl }); const env = await mb.sealCapsule({ contentText: text, ownerVaultKey: vaultKey, recipients: [{ id: h.recipient.id, publicKey: h.recipient.publicJwk, accountPublicKey: h.recipient.accountPublicJwk ?? null }], }); const recipientWraps = [{ recipientId: h.recipient.id, ...mb.packSealed(env.recipientWraps[h.recipient.id]), keyKind: 'Keycard' }]; const account = env.accountWraps?.[h.recipient.id]; if (account) recipientWraps.push({ recipientId: h.recipient.id, ...mb.packSealed(account), keyKind: 'Account' }); const capsule = await api('/capsules/seal', { method: 'POST', body: { title: null, titleCipher: await sealCapsuleTitle(vaultKey, env.ownerWrap, `Seed share ${i + 1} of ${n} · ${plan.label}`), alg: env.alg, payload: env.payload, ownerWrap: env.ownerWrap, triggerType: 'OnTrigger', deliverOnUtc: null, sensitivity: 'HighValue', recipientWraps, attachments: [], contentKind: 'Text', }, }); shareRefs.push({ index: i + 1, capsuleId: capsule.id, recipientId: h.recipient.id }); } const holders: HolderRef[] = plan.holders.map((h, i) => ({ index: i + 1, name: h.name, hint: h.hint ?? null })); return api('/crypto/splits', { method: 'POST', body: { assetId: plan.assetId, threshold: plan.threshold, totalShares: n, wordCount: plan.wordCount, labelCipher: await sealText(mapKey, plan.label), holdersCipher: await sealText(mapKey, JSON.stringify(holders)), checkCipher: await sealText(vaultKey, await sha256Hex(plan.entropy)), shares: shareRefs, }, }); } interface EnvelopeResponse { alg: string; payload: CipherBlobDto; ownerWrap: CipherBlobDto } export interface Rehearsal { ok: boolean; used: number[]; wordCount: number; detail: string } /** Reopen the owner's copies, recombine a random k-subset and compare against the check value. */ export async function rehearse(vaultKey: CryptoKey, dto: SeedSplitDto): Promise { const shares: Share[] = []; for (const ref of dto.shares) { const env = await api(`/capsules/${ref.capsuleId}`); const text = await mb.openCapsuleAsOwner({ v: 1, alg: env.alg, payload: env.payload, ownerWrap: env.ownerWrap, recipientWraps: {}, sealedAt: '' }, vaultKey); const found = findShareText(text); if (!found) return { ok: false, used: [], wordCount: dto.wordCount, detail: `Share ${ref.index}'s capsule no longer contains a share.` }; shares.push(decodeShare(found)); } // A different random subset every time, so every share gets exercised over the years. const pool = [...shares]; for (let i = pool.length - 1; i > 0; i--) { const j = crypto.getRandomValues(new Uint32Array(1))[0] % (i + 1); [pool[i], pool[j]] = [pool[j], pool[i]]; } const chosen = pool.slice(0, dto.threshold); const entropy = combine(chosen); const used = chosen.map((s) => s.index).sort((a, b) => a - b); if (!dto.checkCipher) return { ok: true, used, wordCount: dto.wordCount, detail: 'The shares combine, but this split has no check value to compare against.' }; const expected = await openText(vaultKey, dto.checkCipher); const ok = (await sha256Hex(entropy)) === expected; return { ok, used, wordCount: dto.wordCount, detail: ok ? `Shares ${used.join(', ')} rebuilt the ${dto.wordCount}-word phrase exactly. It was never displayed.` : `Shares ${used.join(', ')} combined into something that is NOT your phrase. Re-split it — a share may have been altered.`, }; } /** The label and holders, readable to anyone who holds the Map key (the owner and each executor). */ export async function openSplit(mapKey: CryptoKey | null, s: { labelCipher: CipherBlobDto; holdersCipher: CipherBlobDto }): Promise { if (!mapKey) return { label: '(sealed)', holders: [] }; try { const label = await openText(mapKey, s.labelCipher); const holders = JSON.parse(await openText(mapKey, s.holdersCipher)) as HolderRef[]; return { label, holders }; } catch { return { label: '(sealed)', holders: [] }; } } /** For the executor: combine pasted shares into the phrase. Throws plain-English errors. */ export function recoverPhrase(shareTexts: string[]): { phrase: string; words: number; threshold: number } { const shares = shareTexts.map((t) => t.trim()).filter(Boolean).map((t) => decodeShare(t)); const entropy = combine(shares); if (![16, 20, 24, 28, 32].includes(entropy.length)) throw new Error('These shares do not rebuild a seed phrase of a known length.'); const phrase = phraseFromEntropy(entropy); return { phrase, words: phrase.split(' ').length, threshold: shares[0].threshold }; }