/* * C1 — VaultRepository additions (Recovery Key Escrow) * * DRAFT SNIPPET — not a standalone compilation unit. These members and edits go * INTO the existing `com.peachpasswords.vault.VaultRepository` class (and one * helper). They are bound to the REAL repo internals read at v2.1.38: * - mutex (kotlinx Mutex), withLock * - store.loadSlotA() / store.writeSlotA(StoredVault) / store.stampLocalMutation() * - derivedKey: ByteArray? / rootKey / entryList / _settings / publish() / _isUnlocked * - currentPayload(): VaultPayload (private — already exists) * - sealSlotA / persistSlotA (private — already exist) * - b64()/unb64() top-level helpers in VaultRepository.kt * - VaultCrypto.encrypt/decrypt/zero/generateSalt * - RecoveryWords.kt: wordsToRootKeyMaterial(words), deriveRecoveryKey(material, salt) * * Requires the model delta from C1-crypto-notes.md (StoredVault.recoveryEscrow, * RecoveryEscrow, VaultCrypto.AAD_RECOVERY). * * Needed import (top of VaultRepository.kt): * import javax.crypto.AEADBadTagException */ // ───────────────────────────────────────────────────────────────────────────── // 3a — Seal escrow inside the EXISTING setRecoveryWords (REPLACE its body) // // Current (v2.1.38): // suspend fun setRecoveryWords(words: List): Boolean = mutex.withLock { // requireUnlocked() // recoveryWordHash = recoveryWordsHash(words) // recoveryWordsSet = true // runCatching { persistSlotA(bumpVersion = false) }.getOrDefault(false) // } // // Replacement: also seal the slot-A plaintext under the recovery key and write // the escrow into slot A. We persist via a dedicated helper because persistSlotA // re-seals slot A but does NOT carry the new escrow field, so we set it here. // ───────────────────────────────────────────────────────────────────────────── suspend fun setRecoveryWords(words: List): Boolean = mutex.withLock { requireUnlocked() recoveryWordHash = recoveryWordsHash(words) recoveryWordsSet = true runCatching { persistSlotAWithEscrow(buildRecoveryEscrow(words)) }.getOrDefault(false) } /** * Seal the current slot-A plaintext envelope under a key derived from the 12 * BIP39 recovery [words], for password-independent recovery. Returns null if * the words are not a valid BIP39 phrase (checksum/unknown word). */ private fun buildRecoveryEscrow(words: List): RecoveryEscrow? { val material = try { wordsToRootKeyMaterial(words) } catch (_: Exception) { return null } val salt = VaultCrypto.generateSalt() val recoveryKey = deriveRecoveryKey(material, salt) val keyBytes = recoveryKey.encoded val plaintext = VaultCodec.encode(currentPayload()) return try { val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY) RecoveryEscrow(salt = b64(salt), blob = b64(sealed)) } finally { VaultCrypto.zero(material) VaultCrypto.zero(keyBytes) VaultCrypto.zero(plaintext) } } /** * Re-seal slot A from the current in-memory state under the live key, and set * [escrow] on the written record. Mirrors persistSlotA's non-decoy path but * carries the recovery escrow field. Never runs in decoy mode (caller is a * real-vault action). Persists without a version bump (recovery metadata is * local-only, like the existing setRecoveryWords). */ private fun persistSlotAWithEscrow(escrow: RecoveryEscrow?): Boolean { val key = derivedKey ?: throw IllegalStateException("vault_locked") if (decoyMode) return false // recovery is never offered for the decoy val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A") val plaintext = VaultCodec.encode(currentPayload()) val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A)) val next = prior.copy(blob = blob, recoveryEscrow = escrow ?: prior.recoveryEscrow) if (!store.writeSlotA(next)) return false try { writeMatchingNoiseSlotB(next) } catch (e: Exception) { store.writeSlotA(prior) throw e } return true } // ───────────────────────────────────────────────────────────────────────────── // 3b — Preserve escrow on password change (ONE-LINE edit inside changePassword) // // In the real changePassword, the new StoredVault is built as: // val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob) // This DROPS the recoveryEscrow. Change it to carry the existing escrow forward. // The escrow seals the slot-A PLAINTEXT (entries + rootKey), which a password // change does not alter — only the slot-A wrapping changes — so the existing // escrow stays valid and must be preserved, not regenerated. // // REPLACE that one line with: // val next = StoredVault( // version = slotA.version, // salt = b64(newSalt), // blob = blob, // recoveryEscrow = slotA.recoveryEscrow, // carry forward — still valid // ) // ───────────────────────────────────────────────────────────────────────────── // ───────────────────────────────────────────────────────────────────────────── // 3c — Recovery unlock + password reset (NEW methods; add to VaultRepository) // ───────────────────────────────────────────────────────────────────────────── /** * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of * the master password. On success the session is fully unlocked (entries, * rootKey, settings adopted) exactly as a normal unlock, and the decrypted * slot-A plaintext is adopted as live state. Returns true on success, false * if there is no escrow, the words are invalid, or the words are wrong. * * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, this does not * hand back a raw key — there is no single "vault key" to return here (slot A * is wrapped under the rotating Argon2id key). It opens the escrowed payload * directly. Call [resetPasswordWithRecoveryWords] next to set a new password. */ suspend fun unlockWithRecoveryWords(words: List): Boolean = mutex.withLock { val slotA = store.loadSlotA() ?: return false val escrow = slotA.recoveryEscrow ?: return false val material = try { wordsToRootKeyMaterial(words) } catch (_: Exception) { return false } val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt)) val keyBytes = recoveryKey.encoded return try { val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY) val payload = VaultCodec.decode(plaintext) // Adopt the recovered payload as the live session. There is no derived // password key yet (we have no password), so derivedKey stays null // until resetPasswordWithRecoveryWords seals slot A under a new password. decoyMode = false entryList = payload.entries.toMutableList() duressConfigured = payload.duressConfigured recoveryWordHash = payload.recoveryWordHash recoveryWordsSet = payload.recoveryWordsSet rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64) else VaultCrypto.generateRootKey() _settings.value = store.loadSettings() VaultCrypto.zero(plaintext) true } catch (_: Exception) { false // AEADBadTagException (wrong words) or any decode failure } finally { VaultCrypto.zero(material) VaultCrypto.zero(keyBytes) } } /** * After [unlockWithRecoveryWords] succeeds, set a brand-new master password: * re-seal slot A (and refresh the escrow under the same words) under a fresh * Argon2id key, mark the session fully unlocked, and publish. Returns false * if called without a prior successful recovery unlock (no in-memory state). * * Folds the brief's separate `resetPasswordWithRecoveryKey(vaultKey, …)` + * `unlock(newPassword)` into one step, since there is no detached vault key. */ suspend fun resetPasswordWithRecoveryWords( words: List, newPassword: String, ): Boolean = mutex.withLock { if (rootKey == null) return false // must have recovered first return try { val newSalt = VaultCrypto.generateSalt() val newKey = VaultCrypto.deriveKey(newPassword, newSalt) val plaintext = VaultCodec.encode(currentPayload()) val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A)) val prior = store.loadSlotA() // Refresh the escrow against the (unchanged) payload so its salt rotates // with the password reset; reuse the prior escrow if word re-seal fails. val freshEscrow = run { val material = try { wordsToRootKeyMaterial(words) } catch (_: Exception) { null } if (material == null) prior?.recoveryEscrow else { val salt = VaultCrypto.generateSalt() val rk = deriveRecoveryKey(material, salt) val kb = rk.encoded try { RecoveryEscrow(salt = b64(salt), blob = b64(VaultCrypto.encrypt(plaintext, kb, VaultCrypto.AAD_RECOVERY))) } finally { VaultCrypto.zero(material); VaultCrypto.zero(kb) } } } val next = StoredVault( version = prior?.version ?: 1, salt = b64(newSalt), blob = blob, recoveryEscrow = freshEscrow, ) if (!store.writeSlotA(next)) return false writeMatchingNoiseSlotB(next) store.stampLocalMutation() derivedKey?.let(VaultCrypto::zero) derivedKey = newKey VaultCrypto.zero(plaintext) publish() _isUnlocked.value = true true } catch (_: Exception) { false } } /** True at rest if this vault has a recovery escrow the recovery flow can use. */ fun hasRecoveryEscrow(): Boolean = store.loadSlotA()?.recoveryEscrow != null