VaultRepository.kt

34.0 KB · raw

1package com.peachpasswords.vault23import kotlinx.coroutines.flow.MutableStateFlow4import kotlinx.coroutines.flow.StateFlow5import kotlinx.coroutines.flow.asStateFlow6import kotlinx.coroutines.sync.Mutex7import kotlinx.coroutines.sync.withLock8import java.security.SecureRandom9import java.util.Base6410import java.util.UUID11import javax.inject.Inject12import javax.inject.Singleton1314private fun b64(bytes: ByteArray): String = Base64.getEncoder().withoutPadding().encodeToString(bytes)15private fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)1617/** Cap on retained past passwords per entry. Mirrors the browser PASSWORD_HISTORY_MAX. */18private const val PASSWORD_HISTORY_MAX = 501920/** Fixed in-app key material for the decoy vault — holds nothing secret by design. */21private const val DECOY_SENTINEL = "peach_decoy_v1"2223sealed interface UnlockResult {24    data object Success : UnlockResult25    data object WrongPassword : UnlockResult26    data class Error(val reason: String) : UnlockResult27}2829sealed interface CreateVaultResult {30    data object Success : CreateVaultResult31    data class Error(val reason: String) : CreateVaultResult32}3334/**35 * In-memory vault session backed by [VaultStore]. Faithful port of the browser36 * `vault.ts` semantics that matter for correctness:37 *38 *  - Two-slot at rest: slot A is the real (encrypted) vault, slot B a size-matched39 *    noise blob so a fresh install shows two similarly-shaped records.40 *  - Every modifiedAt/deletedAt uses [VaultCrypto.monotonicEntryTimestamp] so a41 *    deletion always wins last-write-wins against an in-flight edit.42 *  - Local writes bump the version counter; sync-applied writes do NOT (so a43 *    sync round never cascades into another outbound sync).44 *  - add/update/delete roll back in-memory state if the disk write fails.45 *  - destroyVault never touches the Pro license (separate store).46 */47@Singleton48class VaultRepository @Inject constructor(49    private val store: VaultStorage,50) {51    private val mutex = Mutex()52    private val rng = SecureRandom()5354    private var derivedKey: ByteArray? = null55    private var rootKey: ByteArray? = null56    private var entryList: MutableList<VaultEntry> = mutableListOf()57    private var duressConfigured: Boolean = false58    private var recoveryWordHash: String? = null59    private var recoveryWordsSet: Boolean = false60    /** True while a decoy (duress) session is active — persistence targets the decoy slot. */61    private var decoyMode: Boolean = false6263    private val _isUnlocked = MutableStateFlow(false)64    val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()6566    private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())67    /** Active (non-deleted) entryList. */68    val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()6970    private val _settings = MutableStateFlow(VaultSettings())71    val settings: StateFlow<VaultSettings> = _settings.asStateFlow()7273    fun hasVault(): Boolean = store.hasVault()7475    // ---- Codex (printed paper backup) -------------------------------------7677    /**78     * The at-rest slot-A envelope as base64 JSON `{"a": <StoredVault>}` — the79     * Codex payload's vaultBlob. Slot B is noise, so it is omitted. Restorable80     * on any device that has the master password. Null when no vault exists.81     */82    fun codexVaultBlobBase64(): String? {83        val slotA = store.loadSlotA() ?: return null84        val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""85        return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))86    }8788    /**89     * Replace the local vault from a Codex blob, then unlock with [password].90     * Writes slot A (and a size-matched noise slot B) before unlocking so the91     * restored vault is at rest exactly as a freshly-created one would be.92     */93    suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {94        return try {95            val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)96            val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)97                ?: return UnlockResult.Error("invalid_codex_blob")98            val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")99            if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")100            writeMatchingNoiseSlotB(slotA)101            store.stampLocalMutation()102            unlockLocked(password)103        } catch (e: Exception) {104            UnlockResult.Error(e.message ?: "restore_failed")105        }106    }107108    suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {109        return try {110            val salt = VaultCrypto.generateSalt()111            val key = VaultCrypto.deriveKey(password, salt)112            entryList = mutableListOf()113            duressConfigured = false114            recoveryWordHash = null115            recoveryWordsSet = false116            decoyMode = false117            rootKey = VaultCrypto.generateRootKey()118            val slotA = sealSlotA(key, salt)119            if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")120            writeMatchingNoiseSlotB(slotA)121            store.stampLocalMutation()122            store.writeSettings(_settings.value)123            derivedKey = key124            publish()125            _isUnlocked.value = true126            CreateVaultResult.Success127        } catch (e: Exception) {128            CreateVaultResult.Error(e.message ?: "create_failed")129        }130    }131132    suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }133134    /** Unlock body without acquiring the mutex — callers must already hold it. */135    private fun unlockLocked(password: String): UnlockResult {136        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")137        return try {138            val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))139            val payload = try {140                VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))141            } catch (_: Exception) {142                VaultCrypto.zero(key)143                return UnlockResult.WrongPassword144            }145            derivedKey = key146            decoyMode = false147            entryList = payload.entries.toMutableList()148            duressConfigured = payload.duressConfigured149            recoveryWordHash = payload.recoveryWordHash150            recoveryWordsSet = payload.recoveryWordsSet151            _settings.value = store.loadSettings()152            ensureRootKey(payload)153            autoPurgeExpiredTrash()154            publish()155            _isUnlocked.value = true156            UnlockResult.Success157        } catch (e: Exception) {158            UnlockResult.Error(e.message ?: "unlock_failed")159        }160    }161162    /**163     * Unlock into the decoy (duress) vault. Creates an empty decoy on first use,164     * sealed under a fixed in-app sentinel key with its own salt. The real slot A165     * is never read, so the real vault stays hidden. Edits during a decoy session166     * persist to the decoy slot only (see [persistSlotA]).167     */168    suspend fun unlockDecoy(): UnlockResult = mutex.withLock {169        return try {170            val existing = store.loadDecoySlot()171            if (existing == null) {172                val salt = VaultCrypto.generateSalt()173                val key = VaultCrypto.deriveKey(DECOY_SENTINEL, salt)174                entryList = mutableListOf()175                duressConfigured = false176                recoveryWordHash = null177                recoveryWordsSet = false178                rootKey = VaultCrypto.generateRootKey()179                derivedKey = key180                decoyMode = true181                val plaintext = VaultCodec.encode(currentPayload())182                val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))183                if (!store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob)))184                    return UnlockResult.Error("storage_write_failed")185            } else {186                val key = VaultCrypto.deriveKey(DECOY_SENTINEL, unb64(existing.salt))187                val payload = VaultCodec.decode(188                    VaultCrypto.decrypt(unb64(existing.blob), key, VaultCrypto.AAD_SLOT_A),189                )190                derivedKey = key191                decoyMode = true192                entryList = payload.entries.toMutableList()193                duressConfigured = false194                recoveryWordHash = payload.recoveryWordHash195                recoveryWordsSet = payload.recoveryWordsSet196                rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)197                          else VaultCrypto.generateRootKey()198            }199            _settings.value = store.loadSettings()200            publish()201            _isUnlocked.value = true202            UnlockResult.Success203        } catch (e: Exception) {204            UnlockResult.Error(e.message ?: "decoy_unlock_failed")205        }206    }207208    /** Unlock with an already-derived AES-256 key (biometric path). */209    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {210        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")211        return try {212            val payload = VaultCodec.decode(213                VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),214            )215            derivedKey = key.copyOf()216            decoyMode = false217            entryList = payload.entries.toMutableList()218            duressConfigured = payload.duressConfigured219            recoveryWordHash = payload.recoveryWordHash220            recoveryWordsSet = payload.recoveryWordsSet221            _settings.value = store.loadSettings()222            ensureRootKey(payload)223            autoPurgeExpiredTrash()224            publish()225            _isUnlocked.value = true226            UnlockResult.Success227        } catch (_: Exception) {228            UnlockResult.WrongPassword229        }230    }231232    fun lock() {233        derivedKey?.let(VaultCrypto::zero)234        rootKey?.let(VaultCrypto::zero)235        derivedKey = null236        rootKey = null237        entryList = mutableListOf()238        duressConfigured = false239        recoveryWordHash = null240        recoveryWordsSet = false241        decoyMode = false242        _entries.value = emptyList()243        _isUnlocked.value = false244    }245246    // ---- Sync identity ----------------------------------------------------247248    /**249     * The vault's stable sync master key (a copy). Caller must zero it. Backs250     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry251     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].252     */253    fun syncMasterKey(): ByteArray? = rootKey?.copyOf()254255    /** Stable per-vault id two paired devices must share to sync. Null when locked. */256    fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }257258    /**259     * A copy of the live Argon2id-derived vault key, for biometric escrow only260     * (wrapped under a hardware KeyStore key on biometric enable). Null when261     * locked. Caller must [VaultCrypto.zero] it after use.262     */263    fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()264265    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {266        val slotA = store.loadSlotA() ?: return false267        return try {268            val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))269            val payload = VaultCodec.decode(270                VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),271            )272            val newSalt = VaultCrypto.generateSalt()273            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)274            // Re-seal the existing payload under the new key/salt.275            val plaintext = VaultCodec.encode(payload)276            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))277            // The escrow seals the slot-A PLAINTEXT, which a password change does not278            // alter — only the wrapping changes — so carry it forward; rebuilding the279            // StoredVault from scratch would silently drop it.280            val next = StoredVault(281                version = slotA.version,282                salt = b64(newSalt),283                blob = blob,284                recoveryEscrow = slotA.recoveryEscrow,285            )286            if (!store.writeSlotA(next)) return false287            writeMatchingNoiseSlotB(next)288            store.stampLocalMutation()289            VaultCrypto.zero(oldKey)290            derivedKey?.let(VaultCrypto::zero)291            derivedKey = newKey292            true293        } catch (_: Exception) {294            false295        }296    }297298    /**299     * Irreversible wipe. Locks the session and clears every vault key. The Pro300     * license is in a separate store and is preserved by construction.301     */302    suspend fun destroyVault() = mutex.withLock {303        lock()304        store.clearVault()305        store.clearDecoySlot()306    }307308    // ---- Entry CRUD -------------------------------------------------------309310    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {311        requireUnlocked()312        val stamp = VaultCrypto.monotonicEntryTimestamp()313        val now = System.currentTimeMillis()314        val entry = draft.copy(315            id = draft.id.ifBlank { UUID.randomUUID().toString() },316            createdAt = if (draft.createdAt > 0) draft.createdAt else now,317            modifiedAt = stamp,318            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,319        )320        val rollback = entryList.toMutableList()321        entryList.add(entry)322        persistOrRollback(rollback)323        entry324    }325326    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {327        requireUnlocked()328        val idx = entryList.indexOfFirst { it.id == patch.id }329        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")330        val current = entryList[idx]331        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)332        // Only refresh passwordChangedAt when the password value actually changes.333        val passwordChanged = patch.password != null && patch.password != current.password334        // Capture the outgoing password (newest first) so the user can reveal/copy/335        // restore it later. History is computed authoritatively from `current`, not336        // the patch — updateEntry is a full-entry replace, so trusting patch's value337        // would let a stale form clobber the real history. Record the age the old338        // password carried, skip an empty prior, and skip an immediate exact dupe339        // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.340        val priorPassword = current.password341        val shouldCapture = passwordChanged &&342            !priorPassword.isNullOrEmpty() &&343            current.passwordHistory?.firstOrNull()?.password != priorPassword344        val nextHistory = if (shouldCapture) {345            (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +346                (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)347        } else {348            current.passwordHistory349        }350        val updated = patch.copy(351            createdAt = current.createdAt,352            modifiedAt = stamp,353            passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,354            passwordHistory = nextHistory,355        )356        val rollback = entryList.toMutableList()357        entryList[idx] = updated358        persistOrRollback(rollback)359        updated360    }361362    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */363    suspend fun deleteEntry(id: String) = mutex.withLock {364        requireUnlocked()365        val idx = entryList.indexOfFirst { it.id == id }366        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")367        val current = entryList[idx]368        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)369        val rollback = entryList.toMutableList()370        entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)371        persistOrRollback(rollback)372    }373374    suspend fun restoreEntry(id: String) = mutex.withLock {375        requireUnlocked()376        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }377        if (idx == -1) throw IllegalStateException("deleted entry not found")378        val current = entryList[idx]379        val rollback = entryList.toMutableList()380        entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))381        persistOrRollback(rollback)382    }383384    /** Permanent delete — no tombstone, no recovery. */385    suspend fun purgeEntry(id: String) = mutex.withLock {386        requireUnlocked()387        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }388        if (idx == -1) throw IllegalStateException("deleted entry not found")389        val rollback = entryList.toMutableList()390        entryList.removeAt(idx)391        persistOrRollback(rollback)392    }393394    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */395    suspend fun purgeDeletedEntries(): Int = mutex.withLock {396        requireUnlocked()397        val rollback = entryList.toMutableList()398        val before = entryList.size399        entryList.removeAll { it.deletedAt != null }400        val removed = before - entryList.size401        if (removed > 0) persistOrRollback(rollback)402        removed403    }404405    fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }406    fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }407    fun getDeletedEntries(): List<VaultEntry> =408        entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }409410    /** Active entries, optionally narrowed to those carrying [tagFilter]. */411    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {412        val active = entryList.filter { it.deletedAt == null }413        if (tagFilter == null) return active414        val needle = tagFilter.trim().lowercase()415        return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }416    }417418    /** Sorted, de-duplicated tags across all active entries. */419    fun getDistinctTags(): List<String> =420        entryList.asSequence()421            .filter { it.deletedAt == null }422            .flatMap { it.tags?.asSequence() ?: emptySequence() }423            .map { it.trim().lowercase() }424            .filter { it.isNotEmpty() }425            .distinct()426            .sorted()427            .toList()428429    /**430     * Distinct non-blank values for an identity field across active entries,431     * most-frequently-used first. Supports "username" and "email"; unknown field432     * names return an empty list. Values keep original casing (deduped433     * case-insensitively) so a suggestion matches what the user typed.434     */435    fun getDistinctFieldValues(field: String): List<String> {436        val select: (VaultEntry) -> String? = when (field) {437            "username" -> { e -> e.username }438            "email" -> { e -> e.email }439            else -> return emptyList()440        }441        return entryList.asSequence()442            .filter { it.deletedAt == null }443            .mapNotNull { select(it)?.trim() }444            .filter { it.isNotEmpty() }445            .groupingBy { it.lowercase() }446            .aggregate { _, acc: Pair<String, Int>?, value, _ ->447                Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)448            }449            .values450            .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })451            .map { it.first }452    }453454    fun getTombstones(): List<Tombstone> =455        entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }456    fun getVaultVersion(): Long = store.version()457458    // ---- Sync apply (does NOT advance the version) ------------------------459460    /**461     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists462     * WITHOUT bumping the version counter, so a sync round cannot cascade into463     * another outbound sync. Returns the number of locally-applied changes.464     */465    suspend fun applyMergedRemoteEntries(466        remoteEntries: List<VaultEntry>,467        remoteTombstones: List<Tombstone>,468    ): Int = mutex.withLock {469        requireUnlocked()470        val tombMap = remoteTombstones.associate { it.id to it.deletedAt }471        var applied = 0472        val byId = entryList.associateBy { it.id }.toMutableMap()473474        for (remote in remoteEntries) {475            val tomb = tombMap[remote.id]476            if (tomb != null && tomb >= remote.modifiedAt) continue477            val local = byId[remote.id]478            if (local == null) {479                entryList.add(remote); byId[remote.id] = remote; applied++480            } else if (remote.modifiedAt > local.modifiedAt) {481                val i = entryList.indexOfFirst { it.id == local.id }482                if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }483            }484        }485486        for ((id, deletedAt) in tombMap) {487            val local = byId[id] ?: continue488            if (local.deletedAt != null && local.deletedAt >= deletedAt) continue489            if (deletedAt < local.modifiedAt) continue490            val i = entryList.indexOfFirst { it.id == id }491            if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }492        }493494        if (applied > 0) {495            persistSlotA(bumpVersion = false)496            publish()497        }498        applied499    }500501    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {502        _settings.value = settings503        store.writeSettings(settings)504    }505506    // ---- Recovery words (vault metadata) ----------------------------------507508    /** True once the user has confirmed their recovery words for this vault. */509    fun isRecoveryWordsSet(): Boolean = recoveryWordsSet510511    /**512     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.513     * Persisted without bumping the version — recovery metadata is local-only and514     * is not an entry mutation paired devices should sync against.515     */516    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {517        requireUnlocked()518        recoveryWordHash = recoveryWordsHash(words)519        recoveryWordsSet = true520        // Also seal a password-independent escrow so the forgot-password flow can521        // recover this vault without the master password.522        runCatching { persistSlotAWithEscrow(buildRecoveryEscrow(words)) }.getOrDefault(false)523    }524525    /** Verify entered words against the stored recovery hash. */526    fun verifyRecoveryWords(words: List<String>): Boolean {527        val stored = recoveryWordHash ?: return false528        return stored == recoveryWordsHash(words)529    }530531    // ---- Recovery escrow (forgot-password) --------------------------------532533    /** True at rest if this vault has a recovery escrow the recovery flow can use. */534    fun hasRecoveryEscrow(): Boolean = store.loadSlotA()?.recoveryEscrow != null535536    /**537     * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of538     * the master password. On success the slot-A plaintext sealed in the escrow is539     * adopted as the live session (entries, rootKey, settings), but no Argon2id540     * password key exists yet — call [resetPasswordWithRecoveryWords] next to set a541     * new password and finish unlocking. Returns false when there is no escrow, the542     * words fail the BIP39 checksum, or the words are wrong (GCM tag mismatch).543     *544     * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, there is no545     * detached vault key to return here — slot A is wrapped under the rotating546     * Argon2id key — so this opens the escrowed payload directly.547     */548    suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {549        val slotA = store.loadSlotA() ?: return false550        val escrow = slotA.recoveryEscrow ?: return false551        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false552        val material = wordKeyMaterial(words)553        val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))554        val keyBytes = recoveryKey.encoded555        return try {556            val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)557            val payload = VaultCodec.decode(plaintext)558            decoyMode = false559            entryList = payload.entries.toMutableList()560            duressConfigured = payload.duressConfigured561            recoveryWordHash = payload.recoveryWordHash562            recoveryWordsSet = payload.recoveryWordsSet563            rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)564                      else VaultCrypto.generateRootKey()565            _settings.value = store.loadSettings()566            VaultCrypto.zero(plaintext)567            true568        } catch (_: Exception) {569            false // AEADBadTagException (wrong words) or any decode failure570        } finally {571            VaultCrypto.zero(material)572            VaultCrypto.zero(keyBytes)573        }574    }575576    /**577     * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:578     * re-seal slot A under a fresh Argon2id key, rotate the escrow under the same579     * words, mark the session fully unlocked, and publish. Returns false if called580     * without a prior successful recovery unlock (no in-memory root key).581     *582     * Folds the brief's `resetPasswordWithRecoveryKey(vaultKey, …)` + `unlock(…)`583     * into one step, since there is no detached vault key here.584     */585    suspend fun resetPasswordWithRecoveryWords(586        words: List<String>,587        newPassword: String,588    ): Boolean = mutex.withLock {589        if (rootKey == null) return false // must have recovered first590        return try {591            val newSalt = VaultCrypto.generateSalt()592            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)593            val plaintext = VaultCodec.encode(currentPayload())594            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))595            val prior = store.loadSlotA()596            // Refresh the escrow against the (unchanged) payload so its salt rotates597            // with the password reset; fall back to the prior escrow if re-seal fails.598            val freshEscrow = if (words.size != 12 || findInvalidWords(words).isNotEmpty()) {599                prior?.recoveryEscrow600            } else {601                val material = wordKeyMaterial(words)602                val salt = VaultCrypto.generateSalt()603                val rk = deriveRecoveryKey(material, salt)604                val kb = rk.encoded605                try {606                    RecoveryEscrow(607                        salt = b64(salt),608                        blob = b64(VaultCrypto.encrypt(plaintext, kb, VaultCrypto.AAD_RECOVERY)),609                    )610                } finally {611                    VaultCrypto.zero(material); VaultCrypto.zero(kb)612                }613            }614            val next = StoredVault(615                version = prior?.version ?: 1,616                salt = b64(newSalt),617                blob = blob,618                recoveryEscrow = freshEscrow,619            )620            if (!store.writeSlotA(next)) return false621            writeMatchingNoiseSlotB(next)622            store.stampLocalMutation()623            derivedKey?.let(VaultCrypto::zero)624            derivedKey = newKey625            VaultCrypto.zero(plaintext)626            publish()627            _isUnlocked.value = true628            true629        } catch (_: Exception) {630            false631        }632    }633634    /**635     * Seal the current slot-A plaintext under a key derived from the 12 BIP39636     * recovery [words], for password-independent recovery. Returns null if the637     * words are not a valid BIP39 phrase (checksum/unknown word).638     */639    private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {640        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null641        val material = wordKeyMaterial(words)642        val salt = VaultCrypto.generateSalt()643        val recoveryKey = deriveRecoveryKey(material, salt)644        val keyBytes = recoveryKey.encoded645        val plaintext = VaultCodec.encode(currentPayload())646        return try {647            val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)648            RecoveryEscrow(salt = b64(salt), blob = b64(sealed))649        } finally {650            VaultCrypto.zero(material)651            VaultCrypto.zero(keyBytes)652            VaultCrypto.zero(plaintext)653        }654    }655656    /**657     * Re-seal slot A from the current in-memory state under the live key, carrying658     * [escrow] onto the written record. Mirrors [persistSlotA]'s real-slot path but659     * adds the recovery escrow field. Never runs in decoy mode (recovery is never660     * offered for the decoy) and persists without a version bump, like the661     * recovery-words metadata write it replaces.662     */663    private fun persistSlotAWithEscrow(escrow: RecoveryEscrow?): Boolean {664        val key = derivedKey ?: throw IllegalStateException("vault_locked")665        if (decoyMode) return false666        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")667        val plaintext = VaultCodec.encode(currentPayload())668        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))669        val next = prior.copy(blob = blob, recoveryEscrow = escrow ?: prior.recoveryEscrow)670        if (!store.writeSlotA(next)) return false671        try {672            writeMatchingNoiseSlotB(next)673        } catch (e: Exception) {674            store.writeSlotA(prior)675            throw e676        }677        return true678    }679680    // ---- Internals --------------------------------------------------------681682    private fun requireUnlocked() {683        if (derivedKey == null) throw IllegalStateException("vault_locked")684    }685686    /**687     * On unlock, hard-delete trashed entries older than the retention window.688     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"689     * (the app's "Never" option), so nothing is purged. Persists without a690     * version bump and without touching the publish state (caller publishes).691     */692    private fun autoPurgeExpiredTrash() {693        val days = _settings.value.trashRetentionDays ?: return694        if (days <= 0) return695        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L696        val before = entryList.size697        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }698        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }699    }700701    /** The slot-A plaintext envelope for the current in-memory session. */702    private fun currentPayload(): VaultPayload =703        VaultPayload(704            entries = entryList.toList(),705            duressConfigured = duressConfigured,706            rootKeyB64 = rootKey?.let(::b64) ?: "",707            recoveryWordHash = recoveryWordHash,708            recoveryWordsSet = recoveryWordsSet,709        )710711    /**712     * Adopt the payload's root key, lazily minting one for legacy payloads.713     * A freshly-minted key is persisted WITHOUT bumping the version — adopting714     * a root key is not a mutation paired devices should sync against.715     */716    private fun ensureRootKey(payload: VaultPayload) {717        if (payload.rootKeyB64.isNotBlank()) {718            rootKey = unb64(payload.rootKeyB64)719            return720        }721        rootKey = VaultCrypto.generateRootKey()722        runCatching { persistSlotA(bumpVersion = false) }723    }724725    private fun publish() {726        _entries.value = entryList.filter { it.deletedAt == null }727    }728729    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {730        val plaintext = VaultCodec.encode(currentPayload())731        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))732        return StoredVault(version = 1, salt = b64(salt), blob = blob)733    }734735    private fun writeMatchingNoiseSlotB(slotA: StoredVault) {736        val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)737        val noise = ByteArray(approxBytes).also(rng::nextBytes)738        store.writeSlotB(b64(noise))739    }740741    /** Re-seal slot A from the current in-memory state under the live key. */742    private fun persistSlotA(bumpVersion: Boolean): Boolean {743        val key = derivedKey ?: throw IllegalStateException("vault_locked")744        // Decoy sessions persist to the decoy slot only — never touch the real slot A.745        if (decoyMode) {746            val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")747            val plaintext = VaultCodec.encode(currentPayload())748            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))749            return store.writeDecoySlot(prior.copy(blob = blob))750        }751        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")752        val plaintext = VaultCodec.encode(currentPayload())753        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))754        val next = prior.copy(blob = blob)755        if (!store.writeSlotA(next)) return false756        // Slot A committed — keep slot B size-matched, then advance the version757        // for local writes only. Restore slot A if a later step fails.758        try {759            writeMatchingNoiseSlotB(next)760            if (bumpVersion) store.stampLocalMutation()761        } catch (e: Exception) {762            store.writeSlotA(prior)763            throw e764        }765        return true766    }767768    /** Persist a local mutation, rolling the in-memory list back on failure. */769    private fun persistOrRollback(rollback: MutableList<VaultEntry>) {770        try {771            if (!persistSlotA(bumpVersion = true)) {772                entryList = rollback773                throw IllegalStateException("storage_write_failed")774            }775        } catch (e: Exception) {776            entryList = rollback777            throw e778        }779        publish()780    }781}