fe16465c6763

feat: Section A data model — purgeDeletedEntries + retention auto-purge on unlock, getDistinctTags + getActiveEntries(tagFilter), recovery-word BLAKE3 metadata (VaultPayload + set/verify), cardNetwork field; 7 unit tests (v2.1.18)

time
2026-06-09 02:00 UTC · 5 months ago
machine
koh2
agent
claude-opus-4-8
session
peach gap implementation
parent
222fa77b6d17
6 files app/build.gradle+2 −2app/src/main/java/com/peachpasswords/vault/RecoveryWords.kt+14 −0app/src/main/java/com/peachpasswords/vault/VaultEntry.kt+2 −0app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+89 −2app/src/main/java/com/peachpasswords/vault/VaultStore.kt+7 −0app/src/test/java/com/peachpasswords/vault/VaultRepositoryTest.kt+94 −0
app/build.gradle+2 −2
@@ -16,8 +16,8 @@1616         applicationId "com.peachpasswords"1717         minSdk 261818         targetSdk 3519-        versionCode 20101720-        versionName "2.1.17"19+        versionCode 20101820+        versionName "2.1.18"2121 2222         testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"2323         vectorDrawables {

view file

app/src/main/java/com/peachpasswords/vault/RecoveryWords.kt+14 −0
@@ -85,3 +85,17 @@8585     if (p.length < 2) return emptyList()8686     return WORD_LIST.filter { it.startsWith(p) }.take(maxResults)8787 }88+89+/**90+ * BLAKE3 hash (hex) of the space-joined, trimmed, lowercased recovery words.91+ * Stored in vault metadata so recovery-word entry can be verified without92+ * persisting the words. Mirrors the browser's recovery-hash derivation.93+ */94+fun recoveryWordsHash(words: List<String>): String {95+    val canonical = words.joinToString(" ") { it.trim().lowercase() }.encodeToByteArray()96+    val digest = org.bouncycastle.crypto.digests.Blake3Digest(256)97+    digest.update(canonical, 0, canonical.size)98+    val out = ByteArray(32)99+    digest.doFinal(out, 0)100+    return out.joinToString("") { "%02x".format(it) }101+}

view file

app/src/main/java/com/peachpasswords/vault/VaultEntry.kt+2 −0
@@ -35,6 +35,8 @@3535     val expYear: String? = null,3636     val cvc: String? = null,3737     val cardNickname: String? = null,38+    /** "visa" | "mastercard" | "amex" | "discover" | "unknown" — derivable from cardNumber. */39+    val cardNetwork: String? = null,3840     val rpId: String? = null,3941     val rpName: String? = null,4042     val credentialId: String? = null,

view file

app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+89 −2
@@ -52,6 +52,8 @@5252     private var rootKey: ByteArray? = null5353     private var entryList: MutableList<VaultEntry> = mutableListOf()5454     private var duressConfigured: Boolean = false55+    private var recoveryWordHash: String? = null56+    private var recoveryWordsSet: Boolean = false5557 5658     private val _isUnlocked = MutableStateFlow(false)5759     val isUnlocked: StateFlow<Boolean> = _isUnlocked.asStateFlow()@@ -104,6 +106,8 @@104106             val key = VaultCrypto.deriveKey(password, salt)105107             entryList = mutableListOf()106108             duressConfigured = false109+            recoveryWordHash = null110+            recoveryWordsSet = false107111             rootKey = VaultCrypto.generateRootKey()108112             val slotA = sealSlotA(key, salt)109113             if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")@@ -135,8 +139,11 @@135139             derivedKey = key136140             entryList = payload.entries.toMutableList()137141             duressConfigured = payload.duressConfigured142+            recoveryWordHash = payload.recoveryWordHash143+            recoveryWordsSet = payload.recoveryWordsSet138144             _settings.value = store.loadSettings()139145             ensureRootKey(payload)146+            autoPurgeExpiredTrash()140147             publish()141148             _isUnlocked.value = true142149             UnlockResult.Success@@ -155,8 +162,11 @@155162             derivedKey = key.copyOf()156163             entryList = payload.entries.toMutableList()157164             duressConfigured = payload.duressConfigured165+            recoveryWordHash = payload.recoveryWordHash166+            recoveryWordsSet = payload.recoveryWordsSet158167             _settings.value = store.loadSettings()159168             ensureRootKey(payload)169+            autoPurgeExpiredTrash()160170             publish()161171             _isUnlocked.value = true162172             UnlockResult.Success@@ -172,6 +182,8 @@172182         rootKey = null173183         entryList = mutableListOf()174184         duressConfigured = false185+        recoveryWordHash = null186+        recoveryWordsSet = false175187         _entries.value = emptyList()176188         _isUnlocked.value = false177189     }@@ -308,9 +320,40 @@308320         persistOrRollback(rollback)309321     }310322 323+    /** Permanently empty the trash — hard-deletes every soft-deleted entry. */324+    suspend fun purgeDeletedEntries(): Int = mutex.withLock {325+        requireUnlocked()326+        val rollback = entryList.toMutableList()327+        val before = entryList.size328+        entryList.removeAll { it.deletedAt != null }329+        val removed = before - entryList.size330+        if (removed > 0) persistOrRollback(rollback)331+        removed332+    }333+311334     fun getEntries(): List<VaultEntry> = entryList.filter { it.deletedAt == null }312335     fun getEntry(id: String): VaultEntry? = entryList.firstOrNull { it.id == id && it.deletedAt == null }313-    fun getDeletedEntries(): List<VaultEntry> = entryList.filter { it.deletedAt != null }336+    fun getDeletedEntries(): List<VaultEntry> =337+        entryList.filter { it.deletedAt != null }.sortedByDescending { it.deletedAt }338+339+    /** Active entries, optionally narrowed to those carrying [tagFilter]. */340+    fun getActiveEntries(tagFilter: String? = null): List<VaultEntry> {341+        val active = entryList.filter { it.deletedAt == null }342+        if (tagFilter == null) return active343+        val needle = tagFilter.trim().lowercase()344+        return active.filter { e -> e.tags?.any { it.equals(needle, ignoreCase = true) } == true }345+    }346+347+    /** Sorted, de-duplicated tags across all active entries. */348+    fun getDistinctTags(): List<String> =349+        entryList.asSequence()350+            .filter { it.deletedAt == null }351+            .flatMap { it.tags?.asSequence() ?: emptySequence() }352+            .map { it.trim().lowercase() }353+            .filter { it.isNotEmpty() }354+            .distinct()355+            .sorted()356+            .toList()314357     fun getTombstones(): List<Tombstone> =315358         entryList.filter { it.deletedAt != null }.map { Tombstone(it.id, it.deletedAt!!) }316359     fun getVaultVersion(): Long = store.version()@@ -363,15 +406,59 @@363406         store.writeSettings(settings)364407     }365408 409+    // ---- Recovery words (vault metadata) ----------------------------------410+411+    /** True once the user has confirmed their recovery words for this vault. */412+    fun isRecoveryWordsSet(): Boolean = recoveryWordsSet413+414+    /**415+     * Record the BLAKE3 hash of the confirmed recovery words and mark them set.416+     * Persisted without bumping the version — recovery metadata is local-only and417+     * is not an entry mutation paired devices should sync against.418+     */419+    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {420+        requireUnlocked()421+        recoveryWordHash = recoveryWordsHash(words)422+        recoveryWordsSet = true423+        runCatching { persistSlotA(bumpVersion = false) }.getOrDefault(false)424+    }425+426+    /** Verify entered words against the stored recovery hash. */427+    fun verifyRecoveryWords(words: List<String>): Boolean {428+        val stored = recoveryWordHash ?: return false429+        return stored == recoveryWordsHash(words)430+    }431+366432     // ---- Internals --------------------------------------------------------367433 368434     private fun requireUnlocked() {369435         if (derivedKey == null) throw IllegalStateException("vault_locked")370436     }371437 438+    /**439+     * On unlock, hard-delete trashed entries older than the retention window.440+     * A null or non-positive [VaultSettings.trashRetentionDays] means "never"441+     * (the app's "Never" option), so nothing is purged. Persists without a442+     * version bump and without touching the publish state (caller publishes).443+     */444+    private fun autoPurgeExpiredTrash() {445+        val days = _settings.value.trashRetentionDays ?: return446+        if (days <= 0) return447+        val cutoff = System.currentTimeMillis() - days.toLong() * 24L * 60L * 60L * 1000L448+        val before = entryList.size449+        entryList.removeAll { it.deletedAt != null && it.deletedAt < cutoff }450+        if (entryList.size != before) runCatching { persistSlotA(bumpVersion = false) }451+    }452+372453     /** The slot-A plaintext envelope for the current in-memory session. */373454     private fun currentPayload(): VaultPayload =374-        VaultPayload(entryList.toList(), duressConfigured, rootKey?.let(::b64) ?: "")455+        VaultPayload(456+            entries = entryList.toList(),457+            duressConfigured = duressConfigured,458+            rootKeyB64 = rootKey?.let(::b64) ?: "",459+            recoveryWordHash = recoveryWordHash,460+            recoveryWordsSet = recoveryWordsSet,461+        )375462 376463     /**377464      * Adopt the payload's root key, lazily minting one for legacy payloads.

view file

app/src/main/java/com/peachpasswords/vault/VaultStore.kt+7 −0
@@ -42,6 +42,13 @@4242     val entries: List<VaultEntry> = emptyList(),4343     val duressConfigured: Boolean = false,4444     val rootKeyB64: String = "",45+    /**46+     * BLAKE3 hash of the space-joined 12 BIP39 recovery words. Lets the app verify47+     * recovery-word entry without storing the words themselves. Null until set.48+     */49+    val recoveryWordHash: String? = null,50+    /** True once the user has confirmed (written down) their recovery words. */51+    val recoveryWordsSet: Boolean = false,4552 )4653 4754 /** Pure JSON codec for the slot-A plaintext envelope — usable without Android. */

view file

app/src/test/java/com/peachpasswords/vault/VaultRepositoryTest.kt+94 −0
@@ -200,6 +200,100 @@200200         assertEquals(1, repo.getEntries().size)201201     }202202 203+    // ---- A1: trash purge + retention auto-purge ---------------------------204+205+    @Test fun purge_deleted_entries_empties_trash() = runBlocking {206+        val repo = VaultRepository(FakeStorage())207+        repo.createVault("pw")208+        val a = repo.addEntry(login("A"))209+        val b = repo.addEntry(login("B"))210+        repo.addEntry(login("C"))211+        repo.deleteEntry(a.id)212+        repo.deleteEntry(b.id)213+        assertEquals(2, repo.getDeletedEntries().size)214+        assertEquals(2, repo.purgeDeletedEntries())215+        assertEquals(0, repo.getDeletedEntries().size)216+        assertEquals(1, repo.getEntries().size)217+    }218+219+    @Test fun auto_purge_removes_trash_older_than_retention() = runBlocking {220+        val storage = FakeStorage()221+        val repo = VaultRepository(storage)222+        repo.createVault("pw")223+        repo.updateSettings(repo.settings.value.copy(trashRetentionDays = 30))224+        // Insert an ancient soft-deleted entry via the sync-merge path (deletedAt=1000).225+        val ancient = VaultEntry(id = "old", title = "Old", type = "login", password = "x",226+            createdAt = 1000, modifiedAt = 1000, deletedAt = 1000)227+        repo.applyMergedRemoteEntries(listOf(ancient), emptyList())228+        assertEquals(1, repo.getDeletedEntries().size)229+        repo.lock()230+        assertEquals(UnlockResult.Success, repo.unlock("pw"))231+        assertEquals(0, repo.getDeletedEntries().size)232+    }233+234+    @Test fun auto_purge_keeps_trash_when_retention_never() = runBlocking {235+        val storage = FakeStorage()236+        val repo = VaultRepository(storage)237+        repo.createVault("pw") // default trashRetentionDays == null → "Never"238+        val ancient = VaultEntry(id = "old", title = "Old", type = "login", password = "x",239+            createdAt = 1000, modifiedAt = 1000, deletedAt = 1000)240+        repo.applyMergedRemoteEntries(listOf(ancient), emptyList())241+        repo.lock()242+        assertEquals(UnlockResult.Success, repo.unlock("pw"))243+        assertEquals(1, repo.getDeletedEntries().size)244+    }245+246+    // ---- A2: tags ---------------------------------------------------------247+248+    @Test fun tags_distinct_sorted_lowercased() = runBlocking {249+        val repo = VaultRepository(FakeStorage())250+        repo.createVault("pw")251+        repo.addEntry(login("A").copy(tags = listOf("work", "email")))252+        repo.addEntry(login("B").copy(tags = listOf("Work", "social")))253+        assertEquals(listOf("email", "social", "work"), repo.getDistinctTags())254+    }255+256+    @Test fun get_active_entries_filters_by_tag() = runBlocking {257+        val repo = VaultRepository(FakeStorage())258+        repo.createVault("pw")259+        repo.addEntry(login("A").copy(tags = listOf("work")))260+        repo.addEntry(login("B").copy(tags = listOf("home")))261+        val gone = repo.addEntry(login("C").copy(tags = listOf("work")))262+        repo.deleteEntry(gone.id)263+        val work = repo.getActiveEntries("work")264+        assertEquals(1, work.size)265+        assertEquals("A", work.first().title)266+        assertEquals(2, repo.getActiveEntries(null).size)267+    }268+269+    @Test fun tags_round_trip_across_lock_unlock() = runBlocking {270+        val storage = FakeStorage()271+        val repo = VaultRepository(storage)272+        repo.createVault("pw")273+        val e = repo.addEntry(login("T").copy(tags = listOf("alpha", "beta")))274+        repo.lock()275+        repo.unlock("pw")276+        assertEquals(listOf("alpha", "beta"), repo.getEntries().first { it.id == e.id }.tags)277+    }278+279+    // ---- A5: recovery-word metadata ---------------------------------------280+281+    @Test fun recovery_words_set_verify_and_persist() = runBlocking {282+        val storage = FakeStorage()283+        val repo = VaultRepository(storage)284+        repo.createVault("pw")285+        assertFalse(repo.isRecoveryWordsSet())286+        val words = rootKeyToWords(ByteArray(32) { it.toByte() })287+        assertTrue(repo.setRecoveryWords(words))288+        assertTrue(repo.isRecoveryWordsSet())289+        assertTrue(repo.verifyRecoveryWords(words))290+        assertFalse(repo.verifyRecoveryWords(words.reversed()))291+        repo.lock()292+        assertEquals(UnlockResult.Success, repo.unlock("pw"))293+        assertTrue(repo.isRecoveryWordsSet())294+        assertTrue(repo.verifyRecoveryWords(words))295+    }296+203297     @Test fun destroy_clears_everything() = runBlocking {204298         val storage = FakeStorage()205299         val repo = VaultRepository(storage)

view file