C1-repo-additions.kt
1/*2 * C1 — VaultRepository additions (Recovery Key Escrow)3 *4 * DRAFT SNIPPET — not a standalone compilation unit. These members and edits go5 * INTO the existing `com.peachpasswords.vault.VaultRepository` class (and one6 * helper). They are bound to the REAL repo internals read at v2.1.38:7 * - mutex (kotlinx Mutex), withLock8 * - store.loadSlotA() / store.writeSlotA(StoredVault) / store.stampLocalMutation()9 * - derivedKey: ByteArray? / rootKey / entryList / _settings / publish() / _isUnlocked10 * - currentPayload(): VaultPayload (private — already exists)11 * - sealSlotA / persistSlotA (private — already exist)12 * - b64()/unb64() top-level helpers in VaultRepository.kt13 * - VaultCrypto.encrypt/decrypt/zero/generateSalt14 * - RecoveryWords.kt: wordsToRootKeyMaterial(words), deriveRecoveryKey(material, salt)15 *16 * Requires the model delta from C1-crypto-notes.md (StoredVault.recoveryEscrow,17 * RecoveryEscrow, VaultCrypto.AAD_RECOVERY).18 *19 * Needed import (top of VaultRepository.kt):20 * import javax.crypto.AEADBadTagException21 */2223// ─────────────────────────────────────────────────────────────────────────────24// 3a — Seal escrow inside the EXISTING setRecoveryWords (REPLACE its body)25//26// Current (v2.1.38):27// suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {28// requireUnlocked()29// recoveryWordHash = recoveryWordsHash(words)30// recoveryWordsSet = true31// runCatching { persistSlotA(bumpVersion = false) }.getOrDefault(false)32// }33//34// Replacement: also seal the slot-A plaintext under the recovery key and write35// the escrow into slot A. We persist via a dedicated helper because persistSlotA36// re-seals slot A but does NOT carry the new escrow field, so we set it here.37// ─────────────────────────────────────────────────────────────────────────────3839 suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {40 requireUnlocked()41 recoveryWordHash = recoveryWordsHash(words)42 recoveryWordsSet = true43 runCatching { persistSlotAWithEscrow(buildRecoveryEscrow(words)) }.getOrDefault(false)44 }4546 /**47 * Seal the current slot-A plaintext envelope under a key derived from the 1248 * BIP39 recovery [words], for password-independent recovery. Returns null if49 * the words are not a valid BIP39 phrase (checksum/unknown word).50 */51 private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {52 val material = try {53 wordsToRootKeyMaterial(words)54 } catch (_: Exception) {55 return null56 }57 val salt = VaultCrypto.generateSalt()58 val recoveryKey = deriveRecoveryKey(material, salt)59 val keyBytes = recoveryKey.encoded60 val plaintext = VaultCodec.encode(currentPayload())61 return try {62 val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)63 RecoveryEscrow(salt = b64(salt), blob = b64(sealed))64 } finally {65 VaultCrypto.zero(material)66 VaultCrypto.zero(keyBytes)67 VaultCrypto.zero(plaintext)68 }69 }7071 /**72 * Re-seal slot A from the current in-memory state under the live key, and set73 * [escrow] on the written record. Mirrors persistSlotA's non-decoy path but74 * carries the recovery escrow field. Never runs in decoy mode (caller is a75 * real-vault action). Persists without a version bump (recovery metadata is76 * local-only, like the existing setRecoveryWords).77 */78 private fun persistSlotAWithEscrow(escrow: RecoveryEscrow?): Boolean {79 val key = derivedKey ?: throw IllegalStateException("vault_locked")80 if (decoyMode) return false // recovery is never offered for the decoy81 val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")82 val plaintext = VaultCodec.encode(currentPayload())83 val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))84 val next = prior.copy(blob = blob, recoveryEscrow = escrow ?: prior.recoveryEscrow)85 if (!store.writeSlotA(next)) return false86 try {87 writeMatchingNoiseSlotB(next)88 } catch (e: Exception) {89 store.writeSlotA(prior)90 throw e91 }92 return true93 }9495// ─────────────────────────────────────────────────────────────────────────────96// 3b — Preserve escrow on password change (ONE-LINE edit inside changePassword)97//98// In the real changePassword, the new StoredVault is built as:99// val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob)100// This DROPS the recoveryEscrow. Change it to carry the existing escrow forward.101// The escrow seals the slot-A PLAINTEXT (entries + rootKey), which a password102// change does not alter — only the slot-A wrapping changes — so the existing103// escrow stays valid and must be preserved, not regenerated.104//105// REPLACE that one line with:106// val next = StoredVault(107// version = slotA.version,108// salt = b64(newSalt),109// blob = blob,110// recoveryEscrow = slotA.recoveryEscrow, // carry forward — still valid111// )112// ─────────────────────────────────────────────────────────────────────────────113114// ─────────────────────────────────────────────────────────────────────────────115// 3c — Recovery unlock + password reset (NEW methods; add to VaultRepository)116// ─────────────────────────────────────────────────────────────────────────────117118 /**119 * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of120 * the master password. On success the session is fully unlocked (entries,121 * rootKey, settings adopted) exactly as a normal unlock, and the decrypted122 * slot-A plaintext is adopted as live state. Returns true on success, false123 * if there is no escrow, the words are invalid, or the words are wrong.124 *125 * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, this does not126 * hand back a raw key — there is no single "vault key" to return here (slot A127 * is wrapped under the rotating Argon2id key). It opens the escrowed payload128 * directly. Call [resetPasswordWithRecoveryWords] next to set a new password.129 */130 suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {131 val slotA = store.loadSlotA() ?: return false132 val escrow = slotA.recoveryEscrow ?: return false133 val material = try {134 wordsToRootKeyMaterial(words)135 } catch (_: Exception) {136 return false137 }138 val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))139 val keyBytes = recoveryKey.encoded140 return try {141 val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)142 val payload = VaultCodec.decode(plaintext)143 // Adopt the recovered payload as the live session. There is no derived144 // password key yet (we have no password), so derivedKey stays null145 // until resetPasswordWithRecoveryWords seals slot A under a new password.146 decoyMode = false147 entryList = payload.entries.toMutableList()148 duressConfigured = payload.duressConfigured149 recoveryWordHash = payload.recoveryWordHash150 recoveryWordsSet = payload.recoveryWordsSet151 rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)152 else VaultCrypto.generateRootKey()153 _settings.value = store.loadSettings()154 VaultCrypto.zero(plaintext)155 true156 } catch (_: Exception) {157 false // AEADBadTagException (wrong words) or any decode failure158 } finally {159 VaultCrypto.zero(material)160 VaultCrypto.zero(keyBytes)161 }162 }163164 /**165 * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:166 * re-seal slot A (and refresh the escrow under the same words) under a fresh167 * Argon2id key, mark the session fully unlocked, and publish. Returns false168 * if called without a prior successful recovery unlock (no in-memory state).169 *170 * Folds the brief's separate `resetPasswordWithRecoveryKey(vaultKey, …)` +171 * `unlock(newPassword)` into one step, since there is no detached vault key.172 */173 suspend fun resetPasswordWithRecoveryWords(174 words: List<String>,175 newPassword: String,176 ): Boolean = mutex.withLock {177 if (rootKey == null) return false // must have recovered first178 return try {179 val newSalt = VaultCrypto.generateSalt()180 val newKey = VaultCrypto.deriveKey(newPassword, newSalt)181 val plaintext = VaultCodec.encode(currentPayload())182 val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))183 val prior = store.loadSlotA()184 // Refresh the escrow against the (unchanged) payload so its salt rotates185 // with the password reset; reuse the prior escrow if word re-seal fails.186 val freshEscrow = run {187 val material = try { wordsToRootKeyMaterial(words) } catch (_: Exception) { null }188 if (material == null) prior?.recoveryEscrow else {189 val salt = VaultCrypto.generateSalt()190 val rk = deriveRecoveryKey(material, salt)191 val kb = rk.encoded192 try {193 RecoveryEscrow(salt = b64(salt), blob = b64(VaultCrypto.encrypt(plaintext, kb, VaultCrypto.AAD_RECOVERY)))194 } finally {195 VaultCrypto.zero(material); VaultCrypto.zero(kb)196 }197 }198 }199 val next = StoredVault(200 version = prior?.version ?: 1,201 salt = b64(newSalt),202 blob = blob,203 recoveryEscrow = freshEscrow,204 )205 if (!store.writeSlotA(next)) return false206 writeMatchingNoiseSlotB(next)207 store.stampLocalMutation()208 derivedKey?.let(VaultCrypto::zero)209 derivedKey = newKey210 VaultCrypto.zero(plaintext)211 publish()212 _isUnlocked.value = true213 true214 } catch (_: Exception) {215 false216 }217 }218219 /** True at rest if this vault has a recovery escrow the recovery flow can use. */220 fun hasRecoveryEscrow(): Boolean = store.loadSlotA()?.recoveryEscrow != null