VaultRepository.kt

40.5 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 = generateRecoverableRootKey()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        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))138        val payload = try {139            VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))140        } catch (_: Exception) {141            VaultCrypto.zero(key)142            return UnlockResult.WrongPassword143        }144        return adoptSlotA(key, payload)145    }146147    /** Adopt a derived slot-A [key]/[payload] as the live (real-vault) session. */148    private fun adoptSlotA(key: ByteArray, payload: VaultPayload): UnlockResult {149        return try {150            derivedKey = key151            decoyMode = false152            entryList = payload.entries.toMutableList()153            duressConfigured = payload.duressConfigured154            recoveryWordHash = payload.recoveryWordHash155            recoveryWordsSet = payload.recoveryWordsSet156            _settings.value = store.loadSettings()157            ensureRootKey(payload)158            autoPurgeExpiredTrash()159            publish()160            _isUnlocked.value = true161            UnlockResult.Success162        } catch (e: Exception) {163            UnlockResult.Error(e.message ?: "unlock_failed")164        }165    }166167    // ---- Constant-time unlock (MF-5) --------------------------------------168169    /**170     * A slot-A unlock that has been derived but not yet adopted. Holds the live171     * Argon2id key and decoded payload so the caller can derive several candidates172     * concurrently and commit only the winner. The key is owned by this token until173     * [commitSlotAUnlock] adopts it or [discardSlotAUnlock] zeroes it.174     */175    class SlotAUnlock internal constructor(176        internal val key: ByteArray,177        internal val payload: VaultPayload,178    )179180    /**181     * Derive the slot-A key and decrypt its payload WITHOUT mutating session state.182     * Pure computation (no mutex), so it can run concurrently with other candidate183     * derivations before the caller decides which to commit (MF-5). Returns null on184     * no-vault or wrong password (the derived key is zeroed on a tag mismatch).185     */186    fun tryUnlockSlotA(password: String): SlotAUnlock? {187        val slotA = store.loadSlotA() ?: return null188        val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))189        return try {190            val payload = VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))191            SlotAUnlock(key, payload)192        } catch (_: Exception) {193            VaultCrypto.zero(key)194            null195        }196    }197198    /** Adopt a previously-derived [SlotAUnlock] as the live session. */199    suspend fun commitSlotAUnlock(unlock: SlotAUnlock): UnlockResult = mutex.withLock {200        adoptSlotA(unlock.key, unlock.payload)201    }202203    /** Zero a derived [SlotAUnlock] that will not be adopted. */204    fun discardSlotAUnlock(unlock: SlotAUnlock) = VaultCrypto.zero(unlock.key)205206    /**207     * Unlock into the decoy (duress) vault. Creates an empty decoy on first use,208     * sealed under a fixed in-app sentinel key with its own salt. The real slot A209     * is never read, so the real vault stays hidden. Edits during a decoy session210     * persist to the decoy slot only (see [persistSlotA]).211     */212    suspend fun unlockDecoy(): UnlockResult = mutex.withLock {213        return try {214            val existing = store.loadDecoySlot()215            if (existing == null) {216                val salt = VaultCrypto.generateSalt()217                val key = VaultCrypto.deriveKey(DECOY_SENTINEL, salt)218                entryList = mutableListOf()219                duressConfigured = false220                recoveryWordHash = null221                recoveryWordsSet = false222                rootKey = VaultCrypto.generateRootKey()223                derivedKey = key224                decoyMode = true225                val plaintext = VaultCodec.encode(currentPayload())226                val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))227                if (!store.writeDecoySlot(StoredVault(version = 1, salt = b64(salt), blob = blob)))228                    return UnlockResult.Error("storage_write_failed")229            } else {230                val key = VaultCrypto.deriveKey(DECOY_SENTINEL, unb64(existing.salt))231                val payload = VaultCodec.decode(232                    VaultCrypto.decrypt(unb64(existing.blob), key, VaultCrypto.AAD_SLOT_A),233                )234                derivedKey = key235                decoyMode = true236                entryList = payload.entries.toMutableList()237                duressConfigured = false238                recoveryWordHash = payload.recoveryWordHash239                recoveryWordsSet = payload.recoveryWordsSet240                rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)241                          else VaultCrypto.generateRootKey()242            }243            _settings.value = store.loadSettings()244            publish()245            _isUnlocked.value = true246            UnlockResult.Success247        } catch (e: Exception) {248            UnlockResult.Error(e.message ?: "decoy_unlock_failed")249        }250    }251252    /** Unlock with an already-derived AES-256 key (biometric path). */253    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {254        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")255        return try {256            val payload = VaultCodec.decode(257                VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),258            )259            derivedKey = key.copyOf()260            decoyMode = false261            entryList = payload.entries.toMutableList()262            duressConfigured = payload.duressConfigured263            recoveryWordHash = payload.recoveryWordHash264            recoveryWordsSet = payload.recoveryWordsSet265            _settings.value = store.loadSettings()266            ensureRootKey(payload)267            autoPurgeExpiredTrash()268            publish()269            _isUnlocked.value = true270            UnlockResult.Success271        } catch (_: Exception) {272            UnlockResult.WrongPassword273        }274    }275276    fun lock() {277        derivedKey?.let(VaultCrypto::zero)278        rootKey?.let(VaultCrypto::zero)279        derivedKey = null280        rootKey = null281        entryList = mutableListOf()282        duressConfigured = false283        recoveryWordHash = null284        recoveryWordsSet = false285        decoyMode = false286        _entries.value = emptyList()287        _isUnlocked.value = false288    }289290    // ---- Sync identity ----------------------------------------------------291292    /**293     * The vault's stable sync master key (a copy). Caller must zero it. Backs294     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry295     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].296     */297    fun syncMasterKey(): ByteArray? = rootKey?.copyOf()298299    /** Stable per-vault id two paired devices must share to sync. Null when locked. */300    fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }301302    /**303     * A copy of the live Argon2id-derived vault key, for biometric escrow only304     * (wrapped under a hardware KeyStore key on biometric enable). Null when305     * locked. Caller must [VaultCrypto.zero] it after use.306     */307    fun currentVaultKey(): ByteArray? = derivedKey?.copyOf()308309    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {310        val slotA = store.loadSlotA() ?: return false311        return try {312            val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))313            val payload = VaultCodec.decode(314                VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),315            )316            val newSalt = VaultCrypto.generateSalt()317            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)318            // Re-seal the existing payload under the new key/salt.319            val plaintext = VaultCodec.encode(payload)320            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))321            // The escrow seals the slot-A PLAINTEXT, which a password change does not322            // alter — only the wrapping changes — so carry it forward; rebuilding the323            // StoredVault from scratch would silently drop it.324            // Carry BOTH escrows forward unchanged: each seals plaintext/root-key325            // content that a password change does not alter — only the slot-A326            // wrapping rotates. The root-key escrow staying stable across password327            // changes matches the browser (`vault.ts:363-364`).328            val next = StoredVault(329                version = slotA.version,330                salt = b64(newSalt),331                blob = blob,332                recoveryEscrow = slotA.recoveryEscrow,333                rootKeyEscrow = slotA.rootKeyEscrow,334            )335            if (!store.writeSlotA(next)) return false336            writeMatchingNoiseSlotB(next)337            store.stampLocalMutation()338            VaultCrypto.zero(oldKey)339            derivedKey?.let(VaultCrypto::zero)340            derivedKey = newKey341            true342        } catch (_: Exception) {343            false344        }345    }346347    /**348     * Irreversible wipe. Locks the session and clears every vault key. The Pro349     * license is in a separate store and is preserved by construction.350     */351    suspend fun destroyVault() = mutex.withLock {352        lock()353        store.clearVault()354        store.clearDecoySlot()355    }356357    // ---- Entry CRUD -------------------------------------------------------358359    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {360        requireUnlocked()361        val stamp = VaultCrypto.monotonicEntryTimestamp()362        val now = System.currentTimeMillis()363        val entry = withDerivedLast4(draft.copy(364            id = draft.id.ifBlank { UUID.randomUUID().toString() },365            createdAt = if (draft.createdAt > 0) draft.createdAt else now,366            modifiedAt = stamp,367            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,368        ))369        val rollback = entryList.toMutableList()370        entryList.add(entry)371        persistOrRollback(rollback)372        entry373    }374375    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {376        requireUnlocked()377        val idx = entryList.indexOfFirst { it.id == patch.id }378        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")379        val current = entryList[idx]380        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)381        // Only refresh passwordChangedAt when the password value actually changes.382        val passwordChanged = patch.password != null && patch.password != current.password383        // Capture the outgoing password (newest first) so the user can reveal/copy/384        // restore it later. History is computed authoritatively from `current`, not385        // the patch — updateEntry is a full-entry replace, so trusting patch's value386        // would let a stale form clobber the real history. Record the age the old387        // password carried, skip an empty prior, and skip an immediate exact dupe388        // (e.g. restore-then-restore). Capped at PASSWORD_HISTORY_MAX.389        val priorPassword = current.password390        val shouldCapture = passwordChanged &&391            !priorPassword.isNullOrEmpty() &&392            current.passwordHistory?.firstOrNull()?.password != priorPassword393        val nextHistory = if (shouldCapture) {394            (listOf(PasswordHistoryItem(priorPassword!!, current.passwordChangedAt ?: current.createdAt)) +395                (current.passwordHistory ?: emptyList())).take(PASSWORD_HISTORY_MAX)396        } else {397            current.passwordHistory398        }399        val updated = withDerivedLast4(patch.copy(400            createdAt = current.createdAt,401            modifiedAt = stamp,402            passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,403            passwordHistory = nextHistory,404        ))405        val rollback = entryList.toMutableList()406        entryList[idx] = updated407        persistOrRollback(rollback)408        updated409    }410411    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */412    suspend fun deleteEntry(id: String) = mutex.withLock {413        requireUnlocked()414        val idx = entryList.indexOfFirst { it.id == id }415        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")416        val current = entryList[idx]417        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)418        val rollback = entryList.toMutableList()419        entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)420        persistOrRollback(rollback)421    }422423    suspend fun restoreEntry(id: String) = mutex.withLock {424        requireUnlocked()425        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }426        if (idx == -1) throw IllegalStateException("deleted entry not found")427        val current = entryList[idx]428        val rollback = entryList.toMutableList()429        entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))430        persistOrRollback(rollback)431    }432433    /** Permanent delete — no tombstone, no recovery. */434    suspend fun purgeEntry(id: String) = mutex.withLock {435        requireUnlocked()436        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }437        if (idx == -1) throw IllegalStateException("deleted entry not found")438        val rollback = entryList.toMutableList()439        entryList.removeAt(idx)440        persistOrRollback(rollback)441    }442443    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */444    suspend fun purgeDeletedEntries(): Int = mutex.withLock {445        requireUnlocked()446        val rollback = entryList.toMutableList()447        val before = entryList.size448        entryList.removeAll { it.deletedAt != null }449        val removed = before - entryList.size450        if (removed > 0) persistOrRollback(rollback)451        removed452    }453454    fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }455    fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }456    fun getDeletedEntries(): List<VaultEntry> =457        entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }458459    /** Active entries, optionally narrowed to those carrying [tagFilter]. */460    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {461        val active = entryList.filter { it.deletedAt == null }462        if (tagFilter == null) return active463        val needle = tagFilter.trim().lowercase()464        return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }465    }466467    /** Sorted, de-duplicated tags across all active entries. */468    fun getDistinctTags(): List<String> =469        entryList.asSequence()470            .filter { it.deletedAt == null }471            .flatMap { it.tags?.asSequence() ?: emptySequence() }472            .map { it.trim().lowercase() }473            .filter { it.isNotEmpty() }474            .distinct()475            .sorted()476            .toList()477478    /**479     * Distinct non-blank values for an identity field across active entries,480     * most-frequently-used first. Supports "username" and "email"; unknown field481     * names return an empty list. Values keep original casing (deduped482     * case-insensitively) so a suggestion matches what the user typed.483     */484    fun getDistinctFieldValues(field: String): List<String> {485        val select: (VaultEntry) -> String? = when (field) {486            "username" -> { e -> e.username }487            "email" -> { e -> e.email }488            else -> return emptyList()489        }490        return entryList.asSequence()491            .filter { it.deletedAt == null }492            .mapNotNull { select(it)?.trim() }493            .filter { it.isNotEmpty() }494            .groupingBy { it.lowercase() }495            .aggregate { _, acc: Pair<String, Int>?, value, _ ->496                Pair(acc?.first ?: value, (acc?.second ?: 0) + 1)497            }498            .values499            .sortedWith(compareByDescending<Pair<String, Int>> { it.second }.thenBy { it.first.lowercase() })500            .map { it.first }501    }502503    fun getTombstones(): List<Tombstone> =504        entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }505    fun getVaultVersion(): Long = store.version()506507    // ---- Sync apply (does NOT advance the version) ------------------------508509    /**510     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists511     * WITHOUT bumping the version counter, so a sync round cannot cascade into512     * another outbound sync. Returns the number of locally-applied changes.513     */514    suspend fun applyMergedRemoteEntries(515        remoteEntries: List<VaultEntry>,516        remoteTombstones: List<Tombstone>,517    ): Int = mutex.withLock {518        requireUnlocked()519        val tombMap = remoteTombstones.associate { it.id to it.deletedAt }520        var applied = 0521        val byId = entryList.associateBy { it.id }.toMutableMap()522523        for (remote in remoteEntries) {524            val tomb = tombMap[remote.id]525            if (tomb != null && tomb >= remote.modifiedAt) continue526            val local = byId[remote.id]527            if (local == null) {528                entryList.add(remote); byId[remote.id] = remote; applied++529            } else if (remote.modifiedAt > local.modifiedAt) {530                val i = entryList.indexOfFirst { it.id == local.id }531                if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }532            }533        }534535        for ((id, deletedAt) in tombMap) {536            val local = byId[id] ?: continue537            if (local.deletedAt != null && local.deletedAt >= deletedAt) continue538            if (deletedAt < local.modifiedAt) continue539            val i = entryList.indexOfFirst { it.id == id }540            if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }541        }542543        if (applied > 0) {544            persistSlotA(bumpVersion = false)545            publish()546        }547        applied548    }549550    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {551        _settings.value = settings552        store.writeSettings(settings)553    }554555    // ---- Recovery words (vault metadata) ----------------------------------556557    /** True once the user has confirmed their recovery words for this vault. */558    fun isRecoveryWordsSet(): Boolean = recoveryWordsSet559560    /**561     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.562     * Persisted without bumping the version — recovery metadata is local-only and563     * is not an entry mutation paired devices should sync against.564     */565    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {566        requireUnlocked()567        recoveryWordHash = recoveryWordsHash(words)568        recoveryWordsSet = true569        // Seal TWO escrows (MF-1): the browser-byte-compatible root-key escrow570        // (cross-platform recovery of the sync root key) and Android's whole-payload571        // escrow (offline forgot-password restore of entries). Both derive their key572        // from the same `wordsToRootKeyMaterial` IKM but use distinct AADs.573        runCatching {574            persistSlotAWithEscrows(buildRecoveryEscrow(words), buildRootKeyEscrow(words))575        }.getOrDefault(false)576    }577578    /** Verify entered words against the stored recovery hash. */579    fun verifyRecoveryWords(words: List<String>): Boolean {580        val stored = recoveryWordHash ?: return false581        return stored == recoveryWordsHash(words)582    }583584    // ---- Recovery escrow (forgot-password) --------------------------------585586    /** True at rest if this vault has any recovery escrow the recovery flow can use. */587    fun hasRecoveryEscrow(): Boolean =588        store.loadSlotA()?.let { it.recoveryEscrow != null || it.rootKeyEscrow != null } ?: false589590    /**591     * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of592     * the master password. On success the slot-A plaintext sealed in the escrow is593     * adopted as the live session (entries, rootKey, settings), but no Argon2id594     * password key exists yet — call [resetPasswordWithRecoveryWords] next to set a595     * new password and finish unlocking. Returns false when there is no escrow, the596     * words fail the BIP39 checksum, or the words are wrong (GCM tag mismatch).597     *598     * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, there is no599     * detached vault key to return here — slot A is wrapped under the rotating600     * Argon2id key — so this opens the escrowed payload directly.601     */602    suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {603        val slotA = store.loadSlotA() ?: return false604        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return false605606        // Prefer Android's whole-payload escrow: a full offline restore of entries,607        // root key, and settings. Present for Android-created vaults.608        slotA.recoveryEscrow?.let { escrow ->609            val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return@let610            val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))611            val keyBytes = recoveryKey.encoded612            try {613                val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)614                val payload = VaultCodec.decode(plaintext)615                decoyMode = false616                entryList = payload.entries.toMutableList()617                duressConfigured = payload.duressConfigured618                recoveryWordHash = payload.recoveryWordHash619                recoveryWordsSet = payload.recoveryWordsSet620                rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)621                          else generateRecoverableRootKey()622                _settings.value = store.loadSettings()623                VaultCrypto.zero(plaintext)624                return true625            } catch (_: Exception) {626                // Wrong words against this escrow — fall through to the root-key escrow.627            } finally {628                VaultCrypto.zero(material)629                VaultCrypto.zero(keyBytes)630            }631        }632633        // Browser-format vault (only the root-key escrow): recover the 32-byte root634        // key (sync identity) and reset the password; entries return via sync. This635        // is exactly the browser's recovery semantics (`messages.ts:312-347`).636        slotA.rootKeyEscrow?.let { escrow ->637            val rk = unsealRootKeyEscrow(words, escrow) ?: return false638            decoyMode = false639            entryList = mutableListOf()640            duressConfigured = false641            recoveryWordHash = recoveryWordsHash(words)642            recoveryWordsSet = true643            rootKey = rk644            _settings.value = store.loadSettings()645            return true646        }647        return false648    }649650    /**651     * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:652     * re-seal slot A under a fresh Argon2id key, rotate the escrow under the same653     * words, mark the session fully unlocked, and publish. Returns false if called654     * without a prior successful recovery unlock (no in-memory root key).655     *656     * Folds the brief's `resetPasswordWithRecoveryKey(vaultKey, …)` + `unlock(…)`657     * into one step, since there is no detached vault key here.658     */659    suspend fun resetPasswordWithRecoveryWords(660        words: List<String>,661        newPassword: String,662    ): Boolean = mutex.withLock {663        if (rootKey == null) return false // must have recovered first664        return try {665            val newSalt = VaultCrypto.generateSalt()666            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)667            val plaintext = VaultCodec.encode(currentPayload())668            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))669            val prior = store.loadSlotA()670            // Rebuild both escrows against the recovered session so their salts rotate671            // with the password reset; fall back to the prior escrows if rebuild fails672            // (e.g. a checksum-invalid phrase). The same 12 words keep working.673            val valid = words.size == 12 && findInvalidWords(words).isEmpty()674            val freshRecovery = if (valid) buildRecoveryEscrow(words) ?: prior?.recoveryEscrow else prior?.recoveryEscrow675            val freshRootKey = if (valid) buildRootKeyEscrow(words) ?: prior?.rootKeyEscrow else prior?.rootKeyEscrow676            val next = StoredVault(677                version = prior?.version ?: 1,678                salt = b64(newSalt),679                blob = blob,680                recoveryEscrow = freshRecovery,681                rootKeyEscrow = freshRootKey,682            )683            if (!store.writeSlotA(next)) return false684            writeMatchingNoiseSlotB(next)685            store.stampLocalMutation()686            derivedKey?.let(VaultCrypto::zero)687            derivedKey = newKey688            VaultCrypto.zero(plaintext)689            publish()690            _isUnlocked.value = true691            true692        } catch (_: Exception) {693            false694        }695    }696697    /**698     * Seal the current slot-A plaintext under a key derived from the 12 BIP39699     * recovery [words] (Android offline-restore escrow). IKM is the browser's700     * `wordsToRootKeyMaterial` (MF-1), AAD is the string [VaultCrypto.AAD_RECOVERY].701     * Returns null for a checksum-invalid phrase.702     */703    private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {704        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null705        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null706        val salt = VaultCrypto.generateSalt()707        val recoveryKey = deriveRecoveryKey(material, salt)708        val keyBytes = recoveryKey.encoded709        val plaintext = VaultCodec.encode(currentPayload())710        return try {711            val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)712            RecoveryEscrow(salt = b64(salt), blob = b64(sealed))713        } finally {714            VaultCrypto.zero(material)715            VaultCrypto.zero(keyBytes)716            VaultCrypto.zero(plaintext)717        }718    }719720    /**721     * Seal ONLY the 32-byte root key under a key the recovery [words] derive,722     * byte-for-byte the browser algorithm (MF-1): plaintext = lowercase ASCII hex723     * of the root key, IKM = `wordsToRootKeyMaterial`, HKDF salt random-16,724     * info `peach-recovery-v1`, AES-256-GCM AAD = 0x01. The same 12 words unwrap725     * the same root key on the browser. Returns null with no in-memory root key or726     * a checksum-invalid phrase.727     */728    private fun buildRootKeyEscrow(words: List<String>): RootKeyEscrow? {729        if (words.size != 12 || findInvalidWords(words).isNotEmpty()) return null730        val rk = rootKey ?: return null731        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null732        val salt = VaultCrypto.generateSalt()733        val recoveryKey = deriveRecoveryKey(material, salt)734        val keyBytes = recoveryKey.encoded735        val plaintext = rootKeyToHex(rk).toByteArray(Charsets.US_ASCII)736        return try {737            // combined = nonce(12) || ciphertext || tag(16)738            val combined = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)739            val nonce = combined.copyOfRange(0, VaultCrypto.NONCE_SIZE)740            val ctTag = combined.copyOfRange(VaultCrypto.NONCE_SIZE, combined.size)741            val tag = ctTag.copyOfRange(ctTag.size - 16, ctTag.size)742            val ct = ctTag.copyOfRange(0, ctTag.size - 16)743            RootKeyEscrow(salt = b64(salt), wrappedRootKey = b64(ct), nonce = b64(nonce), tag = b64(tag))744        } finally {745            VaultCrypto.zero(material)746            VaultCrypto.zero(keyBytes)747            VaultCrypto.zero(plaintext)748        }749    }750751    /** Unwrap the 32-byte root key from a browser-compatible [escrow]; null on wrong words. */752    private fun unsealRootKeyEscrow(words: List<String>, escrow: RootKeyEscrow): ByteArray? {753        val material = runCatching { wordsToRootKeyMaterial(words) }.getOrNull() ?: return null754        val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))755        val keyBytes = recoveryKey.encoded756        return try {757            val combined = unb64(escrow.nonce) + unb64(escrow.wrappedRootKey) + unb64(escrow.tag)758            val pt = VaultCrypto.decrypt(combined, keyBytes, VaultCrypto.AAD_RECOVERY_ROOTKEY)759            hexToRootKey(String(pt, Charsets.US_ASCII))760        } catch (_: Exception) {761            null762        } finally {763            VaultCrypto.zero(material)764            VaultCrypto.zero(keyBytes)765        }766    }767768    /**769     * Re-seal slot A from the current in-memory state under the live key, carrying770     * both [recoveryEscrow] and [rootKeyEscrow] onto the written record. Never runs771     * in decoy mode (recovery is never offered for the decoy) and persists without772     * a version bump, like the recovery-words metadata write it replaces.773     */774    private fun persistSlotAWithEscrows(775        recoveryEscrow: RecoveryEscrow?,776        rootKeyEscrow: RootKeyEscrow?,777    ): Boolean {778        val key = derivedKey ?: throw IllegalStateException("vault_locked")779        if (decoyMode) return false780        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")781        val plaintext = VaultCodec.encode(currentPayload())782        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))783        val next = prior.copy(784            blob = blob,785            recoveryEscrow = recoveryEscrow ?: prior.recoveryEscrow,786            rootKeyEscrow = rootKeyEscrow ?: prior.rootKeyEscrow,787        )788        if (!store.writeSlotA(next)) return false789        try {790            writeMatchingNoiseSlotB(next)791        } catch (e: Exception) {792            store.writeSlotA(prior)793            throw e794        }795        return true796    }797798    // ---- Internals --------------------------------------------------------799800    private fun requireUnlocked() {801        if (derivedKey == null) throw IllegalStateException("vault_locked")802    }803804    /**805     * Keep [VaultEntry.last4] in sync with the card number for card entries (MF-3),806     * so it is stored explicitly and survives the sync wire format rather than being807     * re-derived at render time. Non-card entries pass through unchanged.808     */809    private fun withDerivedLast4(entry: VaultEntry): VaultEntry {810        if (!entry.isCard()) return entry811        val digits = entry.cardNumber?.filter { it.isDigit() } ?: ""812        return entry.copy(last4 = if (digits.length >= 4) digits.takeLast(4) else null)813    }814815    /**816     * On unlock, hard-delete trashed entries older than the retention window.817     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"818     * (the app's "Never" option), so nothing is purged. Persists without a819     * version bump and without touching the publish state (caller publishes).820     */821    private fun autoPurgeExpiredTrash() {822        val days = _settings.value.trashRetentionDays ?: return823        if (days <= 0) return824        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L825        val before = entryList.size826        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }827        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }828    }829830    /** The slot-A plaintext envelope for the current in-memory session. */831    private fun currentPayload(): VaultPayload =832        VaultPayload(833            entries = entryList.toList(),834            duressConfigured = duressConfigured,835            rootKeyB64 = rootKey?.let(::b64) ?: "",836            recoveryWordHash = recoveryWordHash,837            recoveryWordsSet = recoveryWordsSet,838        )839840    /**841     * Adopt the payload's root key, lazily minting one for legacy payloads.842     * A freshly-minted key is persisted WITHOUT bumping the version — adopting843     * a root key is not a mutation paired devices should sync against.844     */845    private fun ensureRootKey(payload: VaultPayload) {846        if (payload.rootKeyB64.isNotBlank()) {847            rootKey = unb64(payload.rootKeyB64)848            return849        }850        rootKey = generateRecoverableRootKey()851        runCatching { persistSlotA(bumpVersion = false) }852    }853854    private fun publish() {855        _entries.value = entryList.filter { it.deletedAt == null }856    }857858    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {859        val plaintext = VaultCodec.encode(currentPayload())860        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))861        return StoredVault(version = 1, salt = b64(salt), blob = blob)862    }863864    private fun writeMatchingNoiseSlotB(slotA: StoredVault) {865        val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)866        val noise = ByteArray(approxBytes).also(rng::nextBytes)867        store.writeSlotB(b64(noise))868    }869870    /** Re-seal slot A from the current in-memory state under the live key. */871    private fun persistSlotA(bumpVersion: Boolean): Boolean {872        val key = derivedKey ?: throw IllegalStateException("vault_locked")873        // Decoy sessions persist to the decoy slot only — never touch the real slot A.874        if (decoyMode) {875            val prior = store.loadDecoySlot() ?: throw IllegalStateException("missing decoy slot")876            val plaintext = VaultCodec.encode(currentPayload())877            val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))878            return store.writeDecoySlot(prior.copy(blob = blob))879        }880        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")881        val plaintext = VaultCodec.encode(currentPayload())882        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))883        val next = prior.copy(blob = blob)884        if (!store.writeSlotA(next)) return false885        // Slot A committed — keep slot B size-matched, then advance the version886        // for local writes only. Restore slot A if a later step fails.887        try {888            writeMatchingNoiseSlotB(next)889            if (bumpVersion) store.stampLocalMutation()890        } catch (e: Exception) {891            store.writeSlotA(prior)892            throw e893        }894        return true895    }896897    /** Persist a local mutation, rolling the in-memory list back on failure. */898    private fun persistOrRollback(rollback: MutableList<VaultEntry>) {899        try {900            if (!persistSlotA(bumpVersion = true)) {901                entryList = rollback902                throw IllegalStateException("storage_write_failed")903            }904        } catch (e: Exception) {905            entryList = rollback906            throw e907        }908        publish()909    }910}