VaultRepository.kt

17.4 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)1617sealed interface UnlockResult {18    data object Success : UnlockResult19    data object WrongPassword : UnlockResult20    data class Error(val reason: String) : UnlockResult21}2223sealed interface CreateVaultResult {24    data object Success : CreateVaultResult25    data class Error(val reason: String) : CreateVaultResult26}2728/**29 * In-memory vault session backed by [VaultStore]. Faithful port of the browser30 * `vault.ts` semantics that matter for correctness:31 *32 *  - Two-slot at rest: slot A is the real (encrypted) vault, slot B a size-matched33 *    noise blob so a fresh install shows two similarly-shaped records.34 *  - Every modifiedAt/deletedAt uses [VaultCrypto.monotonicEntryTimestamp] so a35 *    deletion always wins last-write-wins against an in-flight edit.36 *  - Local writes bump the version counter; sync-applied writes do NOT (so a37 *    sync round never cascades into another outbound sync).38 *  - add/update/delete roll back in-memory state if the disk write fails.39 *  - destroyVault never touches the Pro license (separate store).40 */41@Singleton42class VaultRepository @Inject constructor(43    private val store: VaultStorage,44) {45    private val mutex = Mutex()46    private val rng = SecureRandom()4748    private var derivedKey: ByteArray? = null49    private var rootKey: ByteArray? = null50    private var entryList: MutableList<VaultEntry> = mutableListOf()51    private var duressConfigured: Boolean = false5253    private val _isUnlocked = MutableStateFlow(false)54    val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()5556    private val _entries = MutableStateFlow<List<VaultEntry>>(emptyList())57    /** Active (non-deleted) entryList. */58    val entries: StateFlow<List<VaultEntry>> = _entries.asStateFlow()5960    private val _settings = MutableStateFlow(VaultSettings())61    val settings: StateFlow<VaultSettings> = _settings.asStateFlow()6263    fun hasVault(): Boolean = store.hasVault()6465    // ---- Codex (printed paper backup) -------------------------------------6667    /**68     * The at-rest slot-A envelope as base64 JSON `{"a": <StoredVault>}` — the69     * Codex payload's vaultBlob. Slot B is noise, so it is omitted. Restorable70     * on any device that has the master password. Null when no vault exists.71     */72    fun codexVaultBlobBase64(): String? {73        val slotA = store.loadSlotA() ?: return null74        val wrapper = """{"a":${VaultCodec.encodeSlot(slotA)}}"""75        return Base64.getUrlEncoder().withoutPadding().encodeToString(wrapper.toByteArray(Charsets.UTF_8))76    }7778    /**79     * Replace the local vault from a Codex blob, then unlock with [password].80     * Writes slot A (and a size-matched noise slot B) before unlocking so the81     * restored vault is at rest exactly as a freshly-created one would be.82     */83    suspend fun restoreFromCodex(vaultBlobBase64: String, password: String): UnlockResult = mutex.withLock {84        return try {85            val wrapperJson = String(Base64.getUrlDecoder().decode(vaultBlobBase64), Charsets.UTF_8)86            val slotJson = Regex("\"a\"\\s*:\\s*(\\{.*\\})\\s*}\\s*$").find(wrapperJson)?.groupValues?.get(1)87                ?: return UnlockResult.Error("invalid_codex_blob")88            val slotA = VaultCodec.decodeSlot(slotJson) ?: return UnlockResult.Error("invalid_codex_blob")89            if (!store.writeSlotA(slotA)) return UnlockResult.Error("storage_write_failed")90            writeMatchingNoiseSlotB(slotA)91            store.stampLocalMutation()92            unlockLocked(password)93        } catch (e: Exception) {94            UnlockResult.Error(e.message ?: "restore_failed")95        }96    }9798    suspend fun createVault(password: String): CreateVaultResult = mutex.withLock {99        return try {100            val salt = VaultCrypto.generateSalt()101            val key = VaultCrypto.deriveKey(password, salt)102            entryList = mutableListOf()103            duressConfigured = false104            rootKey = VaultCrypto.generateRootKey()105            val slotA = sealSlotA(key, salt)106            if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")107            writeMatchingNoiseSlotB(slotA)108            store.stampLocalMutation()109            store.writeSettings(_settings.value)110            derivedKey = key111            publish()112            _isUnlocked.value = true113            CreateVaultResult.Success114        } catch (e: Exception) {115            CreateVaultResult.Error(e.message ?: "create_failed")116        }117    }118119    suspend fun unlock(password: String): UnlockResult = mutex.withLock { unlockLocked(password) }120121    /** Unlock body without acquiring the mutex — callers must already hold it. */122    private fun unlockLocked(password: String): UnlockResult {123        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")124        return try {125            val key = VaultCrypto.deriveKey(password, unb64(slotA.salt))126            val payload = try {127                VaultCodec.decode(VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A))128            } catch (_: Exception) {129                VaultCrypto.zero(key)130                return UnlockResult.WrongPassword131            }132            derivedKey = key133            entryList = payload.entries.toMutableList()134            duressConfigured = payload.duressConfigured135            _settings.value = store.loadSettings()136            ensureRootKey(payload)137            publish()138            _isUnlocked.value = true139            UnlockResult.Success140        } catch (e: Exception) {141            UnlockResult.Error(e.message ?: "unlock_failed")142        }143    }144145    /** Unlock with an already-derived AES-256 key (biometric path). */146    suspend fun unlockWithKey(key: ByteArray): UnlockResult = mutex.withLock {147        val slotA = store.loadSlotA() ?: return UnlockResult.Error("no_vault")148        return try {149            val payload = VaultCodec.decode(150                VaultCrypto.decrypt(unb64(slotA.blob), key, VaultCrypto.AAD_SLOT_A),151            )152            derivedKey = key.copyOf()153            entryList = payload.entries.toMutableList()154            duressConfigured = payload.duressConfigured155            _settings.value = store.loadSettings()156            ensureRootKey(payload)157            publish()158            _isUnlocked.value = true159            UnlockResult.Success160        } catch (_: Exception) {161            UnlockResult.WrongPassword162        }163    }164165    fun lock() {166        derivedKey?.let(VaultCrypto::zero)167        rootKey?.let(VaultCrypto::zero)168        derivedKey = null169        rootKey = null170        entryList = mutableListOf()171        duressConfigured = false172        _entries.value = emptyList()173        _isUnlocked.value = false174    }175176    // ---- Sync identity ----------------------------------------------------177178    /**179     * The vault's stable sync master key (a copy). Caller must zero it. Backs180     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry181     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].182     */183    fun syncMasterKey(): ByteArray? = rootKey?.copyOf()184185    /** Stable per-vault id two paired devices must share to sync. Null when locked. */186    fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }187188    suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {189        val slotA = store.loadSlotA() ?: return false190        return try {191            val oldKey = VaultCrypto.deriveKey(oldPassword, unb64(slotA.salt))192            val payload = VaultCodec.decode(193                VaultCrypto.decrypt(unb64(slotA.blob), oldKey, VaultCrypto.AAD_SLOT_A),194            )195            val newSalt = VaultCrypto.generateSalt()196            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)197            // Re-seal the existing payload under the new key/salt.198            val plaintext = VaultCodec.encode(payload)199            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))200            val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob)201            if (!store.writeSlotA(next)) return false202            writeMatchingNoiseSlotB(next)203            store.stampLocalMutation()204            VaultCrypto.zero(oldKey)205            derivedKey?.let(VaultCrypto::zero)206            derivedKey = newKey207            true208        } catch (_: Exception) {209            false210        }211    }212213    /**214     * Irreversible wipe. Locks the session and clears every vault key. The Pro215     * license is in a separate store and is preserved by construction.216     */217    suspend fun destroyVault() = mutex.withLock {218        lock()219        store.clearVault()220    }221222    // ---- Entry CRUD -------------------------------------------------------223224    suspend fun addEntry(draft: VaultEntry): VaultEntry = mutex.withLock {225        requireUnlocked()226        val stamp = VaultCrypto.monotonicEntryTimestamp()227        val now = System.currentTimeMillis()228        val entry = draft.copy(229            id = draft.id.ifBlank { UUID.randomUUID().toString() },230            createdAt = if (draft.createdAt > 0) draft.createdAt else now,231            modifiedAt = stamp,232            passwordChangedAt = if (!draft.password.isNullOrEmpty()) stamp else draft.passwordChangedAt,233        )234        val rollback = entryList.toMutableList()235        entryList.add(entry)236        persistOrRollback(rollback)237        entry238    }239240    suspend fun updateEntry(patch: VaultEntry): VaultEntry = mutex.withLock {241        requireUnlocked()242        val idx = entryList.indexOfFirst { it.id == patch.id }243        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")244        val current = entryList[idx]245        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)246        // Only refresh passwordChangedAt when the password value actually changes.247        val passwordChanged = patch.password != null && patch.password != current.password248        val updated = patch.copy(249            createdAt = current.createdAt,250            modifiedAt = stamp,251            passwordChangedAt = if (passwordChanged) stamp else current.passwordChangedAt,252        )253        val rollback = entryList.toMutableList()254        entryList[idx] = updated255        persistOrRollback(rollback)256        updated257    }258259    /** Soft-delete: writes a tombstone whose timestamp beats any in-flight edit. */260    suspend fun deleteEntry(id: String) = mutex.withLock {261        requireUnlocked()262        val idx = entryList.indexOfFirst { it.id == id }263        if (idx == -1 || entryList[idx].deletedAt != null) throw IllegalStateException("entry_not_found")264        val current = entryList[idx]265        val stamp = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt)266        val rollback = entryList.toMutableList()267        entryList[idx] = current.copy(deletedAt = stamp, modifiedAt = stamp)268        persistOrRollback(rollback)269    }270271    suspend fun restoreEntry(id: String) = mutex.withLock {272        requireUnlocked()273        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }274        if (idx == -1) throw IllegalStateException("deleted entry not found")275        val current = entryList[idx]276        val rollback = entryList.toMutableList()277        entryList[idx] = current.copy(deletedAt = null, modifiedAt = VaultCrypto.monotonicEntryTimestamp(current.modifiedAt))278        persistOrRollback(rollback)279    }280281    /** Permanent delete — no tombstone, no recovery. */282    suspend fun purgeEntry(id: String) = mutex.withLock {283        requireUnlocked()284        val idx = entryList.indexOfFirst { it.id == id && it.deletedAt != null }285        if (idx == -1) throw IllegalStateException("deleted entry not found")286        val rollback = entryList.toMutableList()287        entryList.removeAt(idx)288        persistOrRollback(rollback)289    }290291    fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }292    fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }293    fun getDeletedEntries(): List<VaultEntry> = entryList.filter { it.deletedAt != null }294    fun getTombstones(): List<Tombstone> =295        entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }296    fun getVaultVersion(): Long = store.version()297298    // ---- Sync apply (does NOT advance the version) ------------------------299300    /**301     * Apply remote entryList + tombstones with per-entry last-write-wins. Persists302     * WITHOUT bumping the version counter, so a sync round cannot cascade into303     * another outbound sync. Returns the number of locally-applied changes.304     */305    suspend fun applyMergedRemoteEntries(306        remoteEntries: List<VaultEntry>,307        remoteTombstones: List<Tombstone>,308    ): Int = mutex.withLock {309        requireUnlocked()310        val tombMap = remoteTombstones.associate { it.id to it.deletedAt }311        var applied = 0312        val byId = entryList.associateBy { it.id }.toMutableMap()313314        for (remote in remoteEntries) {315            val tomb = tombMap[remote.id]316            if (tomb != null && tomb >= remote.modifiedAt) continue317            val local = byId[remote.id]318            if (local == null) {319                entryList.add(remote); byId[remote.id] = remote; applied++320            } else if (remote.modifiedAt > local.modifiedAt) {321                val i = entryList.indexOfFirst { it.id == local.id }322                if (i != -1) { entryList[i] = remote; byId[remote.id] = remote; applied++ }323            }324        }325326        for ((id, deletedAt) in tombMap) {327            val local = byId[id] ?: continue328            if (local.deletedAt != null && local.deletedAt >= deletedAt) continue329            if (deletedAt < local.modifiedAt) continue330            val i = entryList.indexOfFirst { it.id == id }331            if (i != -1) { entryList[i] = local.copy(deletedAt = deletedAt, modifiedAt = deletedAt); applied++ }332        }333334        if (applied > 0) {335            persistSlotA(bumpVersion = false)336            publish()337        }338        applied339    }340341    suspend fun updateSettings(settings: VaultSettings) = mutex.withLock {342        _settings.value = settings343        store.writeSettings(settings)344    }345346    // ---- Internals --------------------------------------------------------347348    private fun requireUnlocked() {349        if (derivedKey == null) throw IllegalStateException("vault_locked")350    }351352    /** The slot-A plaintext envelope for the current in-memory session. */353    private fun currentPayload(): VaultPayload =354        VaultPayload(entryList.toList(), duressConfigured, rootKey?.let(::b64) ?: "")355356    /**357     * Adopt the payload's root key, lazily minting one for legacy payloads.358     * A freshly-minted key is persisted WITHOUT bumping the version — adopting359     * a root key is not a mutation paired devices should sync against.360     */361    private fun ensureRootKey(payload: VaultPayload) {362        if (payload.rootKeyB64.isNotBlank()) {363            rootKey = unb64(payload.rootKeyB64)364            return365        }366        rootKey = VaultCrypto.generateRootKey()367        runCatching { persistSlotA(bumpVersion = false) }368    }369370    private fun publish() {371        _entries.value = entryList.filter { it.deletedAt == null }372    }373374    private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {375        val plaintext = VaultCodec.encode(currentPayload())376        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))377        return StoredVault(version = 1, salt = b64(salt), blob = blob)378    }379380    private fun writeMatchingNoiseSlotB(slotA: StoredVault) {381        val approxBytes = (slotA.blob.length / 2).coerceAtLeast(VaultCrypto.NONCE_SIZE + 16)382        val noise = ByteArray(approxBytes).also(rng::nextBytes)383        store.writeSlotB(b64(noise))384    }385386    /** Re-seal slot A from the current in-memory state under the live key. */387    private fun persistSlotA(bumpVersion: Boolean): Boolean {388        val key = derivedKey ?: throw IllegalStateException("vault_locked")389        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")390        val plaintext = VaultCodec.encode(currentPayload())391        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))392        val next = prior.copy(blob = blob)393        if (!store.writeSlotA(next)) return false394        // Slot A committed — keep slot B size-matched, then advance the version395        // for local writes only. Restore slot A if a later step fails.396        try {397            writeMatchingNoiseSlotB(next)398            if (bumpVersion) store.stampLocalMutation()399        } catch (e: Exception) {400            store.writeSlotA(prior)401            throw e402        }403        return true404    }405406    /** Persist a local mutation, rolling the in-memory list back on failure. */407    private fun persistOrRollback(rollback: MutableList<VaultEntry>) {408        try {409            if (!persistSlotA(bumpVersion = true)) {410                entryList = rollback411                throw IllegalStateException("storage_write_failed")412            }413        } catch (e: Exception) {414            entryList = rollback415            throw e416        }417        publish()418    }419}