0df7b5bb4dfe

feat: C1 forgot-password recovery — add StoredVault.recoveryEscrow + VaultCrypto.AAD_RECOVERY; VaultRepository seals/opens the slot-A plaintext under a recovery key derived from the BIP39 words (keyed off canonical word strings, not the ambiguous duplicate-abandon index path) via unlockWithRecoveryWords/resetPasswordWithRecoveryWords/hasRecoveryEscrow; RecoveryWordEntryScreen (2-step grid + StrengthBar) + PeachNav.RecoveryEntry + LockScreen 'Forgot your password?'; 6 RecoveryEscrowTest cases (v2.1.39)

time
2026-06-09 06:19 UTC · 5 months ago
machine
koh2
agent
claude-opus-4-8
session
recovery key escrow
parent
13e30e67cf31
21 files app/build.gradle+2 −2app/drafts/C1/C1-INTEGRATION.md+218 −0app/drafts/C1/C1-RecoveryEscrowTest.kt+131 −0app/drafts/C1/C1-crypto-notes.md+175 −0app/drafts/C1/C1-repo-additions.kt+220 −0app/drafts/C1/RecoveryWordEntryScreen.kt+540 −0app/drafts/C7/C7-ChirpTransportTest.kt+177 −0app/drafts/C7/C7-INTEGRATION.md+329 −0app/drafts/C7/PairedDeviceStore.kt+117 −0app/drafts/C7/PairingFrames.kt+114 −0app/drafts/C7/PairingServer.kt+321 −0app/drafts/C7/PairingTransport.kt+203 −0app/src/main/java/com/peachpasswords/ui/PeachAppNavHost.kt+12 −0app/src/main/java/com/peachpasswords/ui/PeachNav.kt+1 −0app/src/main/java/com/peachpasswords/ui/lock/LockScreen.kt+14 −0app/src/main/java/com/peachpasswords/ui/recovery/RecoveryWordEntryScreen.kt+522 −0app/src/main/java/com/peachpasswords/vault/RecoveryWords.kt+21 −0app/src/main/java/com/peachpasswords/vault/VaultCrypto.kt+6 −0app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+161 −2app/src/main/java/com/peachpasswords/vault/VaultStore.kt+19 −2app/src/test/java/com/peachpasswords/vault/RecoveryEscrowTest.kt+129 −0
app/build.gradle+2 −2
@@ -16,8 +16,8 @@1616         applicationId "com.peachpasswords"1717         minSdk 261818         targetSdk 3519-        versionCode 20103020-        versionName "2.1.30"19+        versionCode 20103920+        versionName "2.1.39"2121 2222         testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"2323         vectorDrawables {

view file

app/drafts/C1/C1-INTEGRATION.md+218 −0
@@ -0,0 +1,218 @@1+# C1 — Forgot-Password Recovery (Recovery Key Escrow): Integration Contract2+3+Draft implementation of spec C1. All draft artifacts live under `app/drafts/C1/`.4+No shared/source file was edited by the subagent — every file below was read only:5+`VaultRepository.kt`, `VaultCrypto.kt`, `VaultStore.kt`, `VaultEntry.kt`,6+`RecoveryWords.kt`, `RecoveryWordList.kt`, `RecoveryWordsScreen.kt`,7+`LockScreen.kt`, `LockViewModel.kt`, `PeachNav.kt`, `PeachAppNavHost.kt`, theme8+files, `StrengthBar.kt`.9+10+The drafts compile against the REAL v2.1.38 signatures **once the orchestrator11+applies the data-model + repo deltas** described below (the new methods reference12+`StoredVault.recoveryEscrow`, `RecoveryEscrow`, and `VaultCrypto.AAD_RECOVERY`,13+which do not exist yet).14+15+---16+17+## 1. Draft files and their destinations18+19+| Draft file | Destination | Kind |20+|---|---|---|21+| `RecoveryWordEntryScreen.kt` | `app/src/main/java/com/peachpasswords/ui/recovery/RecoveryWordEntryScreen.kt` | New Compose screen + `@HiltViewModel RecoveryEntryViewModel` (package `com.peachpasswords.ui.recovery` — **new package dir**) |22+| `C1-RecoveryEscrowTest.kt` | `app/src/test/java/com/peachpasswords/vault/RecoveryEscrowTest.kt` | New JUnit test (rename file to `RecoveryEscrowTest.kt`) |23+| `C1-repo-additions.kt` | *(not a file)* — apply its members/edits INTO `vault/VaultRepository.kt` | Snippet |24+| `C1-crypto-notes.md` | *(not a file)* — apply its model/crypto deltas | Notes |25+| `C1-INTEGRATION.md` | stays in drafts | This doc |26+27+> The screen lives in a NEW package `com.peachpasswords.ui.recovery`. If you28+> prefer to keep it under `ui.vault` or `ui.lock`, change the `package` line and29+> the one PeachAppNavHost import — nothing else depends on the package.30+31+Public composable signature:32+33+```kotlin34+@Composable35+fun RecoveryWordEntryScreen(36+    onSuccess: () -> Unit,37+    onBack: () -> Unit,38+    onRestore: () -> Unit = onBack,           // defaults to onBack if you don't wire Import39+    vm: RecoveryEntryViewModel = hiltViewModel(),40+)41+```42+43+---44+45+## 2. Shared-file edits the orchestrator must make46+47+### 2a. `vault/VaultStore.kt` — data model (from C1-crypto-notes.md §2)48+49+Add a nullable `recoveryEscrow` field to `StoredVault` and a new `RecoveryEscrow`50+data class:51+52+```kotlin53+@Serializable54+data class StoredVault(55+    val version: Int = 1,56+    val salt: String,57+    val blob: String,58+    val recoveryEscrow: RecoveryEscrow? = null, // NEW59+)60+61+@Serializable62+data class RecoveryEscrow(63+    val salt: String,   // base64, 16B — HKDF salt for deriveRecoveryKey64+    val blob: String,   // base64 — VaultCrypto.encrypt(slotAPlaintext, recoveryKey, AAD_RECOVERY)65+)66+```67+68+`VaultCodec` already uses `ignoreUnknownKeys = true; encodeDefaults = true`, so69+old vaults decode with `recoveryEscrow = null` and no migration is needed.70+71+### 2b. `vault/VaultCrypto.kt` — new AAD constant72+73+Add beside the other AAD constants:74+75+```kotlin76+const val AAD_RECOVERY = "recovery_escrow_v1"77+```78+79+### 2c. `vault/VaultRepository.kt` — methods + edits (from C1-repo-additions.kt)80+81+1. **REPLACE the body of the existing `setRecoveryWords`** so it also seals the82+   escrow (snippet §3a) — adds `buildRecoveryEscrow()` and83+   `persistSlotAWithEscrow()` private helpers.84+2. **Edit `changePassword`** (snippet §3b): the single `val next = StoredVault(...)`85+   line must carry `recoveryEscrow = slotA.recoveryEscrow` forward. The escrow86+   seals the slot-A *plaintext*, which a password change does not alter, so it87+   stays valid — preserve it, do not regenerate.88+3. **ADD** `unlockWithRecoveryWords(words): Boolean`,89+   `resetPasswordWithRecoveryWords(words, newPassword): Boolean`, and90+   `hasRecoveryEscrow(): Boolean` (snippet §3c).91+4. Add import `import javax.crypto.AEADBadTagException` (referenced in notes; the92+   snippet itself catches broad `Exception`, so this import is optional).93+94+> **API-shape deviation from the brief, flagged:** the brief specifies95+> `unlockWithRecoveryWords(words): ByteArray?` and96+> `resetPasswordWithRecoveryKey(vaultKey, newPassword)`. There is no single97+> detached "vault key" in this codebase that both decrypts slot A and survives a98+> password change (slot A is wrapped under the rotating Argon2id key). So the99+> escrow seals the **slot-A plaintext envelope**, `unlockWithRecoveryWords`100+> returns `Boolean` and adopts that plaintext as the live session, and101+> `resetPasswordWithRecoveryWords(words, newPassword)` re-seals + unlocks in one102+> call. If you want to preserve the brief's exact signatures, they can wrap103+> these, but the Boolean form is what the screen and tests use.104+105+### 2d. `ui/PeachNav.kt` — new route106+107+Add one destination (mirrors `RecoverySetup`/`RecoveryView`):108+109+```kotlin110+data object RecoveryEntry : PeachNav("recovery/entry")111+```112+113+### 2e. `ui/PeachAppNavHost.kt` — register the composable114+115+Add import `import com.peachpasswords.ui.recovery.RecoveryWordEntryScreen` and a116+composable. The existing `nav`/`back` lambdas are in scope:117+118+```kotlin119+composable(PeachNav.RecoveryEntry.route) {120+    RecoveryWordEntryScreen(121+        onSuccess = {122+            navController.navigate(PeachNav.VaultList.route) {123+                popUpTo(PeachNav.Lock.route) { inclusive = true }124+            }125+        },126+        onBack = back,127+        onRestore = { nav(PeachNav.Import) },128+    )129+}130+```131+132+(`onSuccess` pops Lock off the back stack, matching how `RecoverySetup` routes133+into the vault. `popUpTo(0)` as in the brief also works but would clear the whole134+stack; `popUpTo(Lock)` is the established pattern here.)135+136+### 2f. `ui/lock/LockScreen.kt` — "Forgot your password?" entry point137+138+**Reality check / deviation flagged:** the brief assumes a `hasVault` unlock139+state that already shows restore affordances. In the real `LockScreen`, the140+restore tabs (`RestoreTabs`) render only in the `!state.hasVault` (create) branch.141+The "Forgot your password?" link must be added to the **unlock** branch, where142+there is currently no such affordance. Place it inside the `GlassPanel`, after143+the biometric `"Use biometrics"` block, guarded by `state.hasVault`:144+145+```kotlin146+if (state.hasVault) {147+    Spacer(Modifier.height(8.dp))148+    Text(149+        "Forgot your password?",150+        color = PeachColors.T2,151+        style = PeachType.labelMono.copy(fontSize = 11.sp),152+        textAlign = TextAlign.Center,153+        modifier = Modifier.fillMaxWidth()154+            .clip(RoundedCornerShape(8.dp))155+            .clickable { onNavigate(PeachNav.RecoveryEntry) }156+            .padding(vertical = 8.dp),157+    )158+}159+```160+161+`LockScreen` already has `onNavigate: (PeachNav) -> Unit` in scope (it is how162+`RestoreTabs` navigates), so **no new screen parameter is needed** — do NOT add163+an `onForgotPassword` callback as the brief's pseudo-code implies; reuse164+`onNavigate`. `PeachColors`, `PeachType`, `RoundedCornerShape`, `clickable`,165+`clip`, `TextAlign` are all already imported in `LockScreen.kt`.166+167+---168+169+## 3. New resources / dependencies170+171+- **No new resources.** The brief says to load BIP39 from172+  `res/raw/bip39_english.txt` — that file does **not** exist and is **not**173+  needed. The 2048-word list is the Kotlin `val WORD_LIST` in174+  `vault/RecoveryWordList.kt`, already used by `getWordSuggestions`,175+  `findInvalidWords`, `wordsToRootKeyMaterial`. The screen imports `WORD_LIST`176+  and `getWordSuggestions` directly. Do not add a raw asset.177+- **No new Gradle dependencies.** Argon2id/HKDF/Blake3 are already provided by178+  BouncyCastle (used by `VaultCrypto` / `RecoveryWords`). The recovery key uses179+  the existing `deriveRecoveryKey` (HKDF-SHA256), not a new KDF.180+- **No new string resources** — copy is inline (the codebase uses inline literals181+  throughout, e.g. LockScreen, RecoveryWordsScreen).182+183+---184+185+## 4. Where the brief's assumed API differed from reality (full list)186+187+| # | Brief assumption | Reality / what the drafts use |188+|---|---|---|189+| 1 | `StoredVault` has `slotA`, `slotDuress`, `recoveryEscrow` fields | `StoredVault` = `(version, salt, blob)`, one slot. Duress/decoy is a separate `StoredVault` under a different prefs key. Drafts add ONE nullable `recoveryEscrow` field to `StoredVault`. |190+| 2 | `VaultCrypto.encryptRaw/decryptRaw/encryptSlot` | None exist. Use `encrypt(plaintext, key, aad)` / `decrypt(data, key, aad)` (12-byte nonce managed internally; AAD is a required String). New `AAD_RECOVERY` constant. |191+| 3 | `deriveRecoveryKey(joinedWordString, salt)` via **Argon2id** | `deriveRecoveryKey(material: ByteArray, salt): SecretKeySpec` ALREADY EXISTS using **HKDF-SHA256** (`info = "peach-recovery-v1"`). `material` is the 16-byte entropy from `wordsToRootKeyMaterial(words)`, not the joined string. |192+| 4 | Escrow the "vault master key" from `currentVaultKey()` | `currentVaultKey()` is the rotating Argon2id password key — escrowing it breaks after a password change. Drafts escrow the **slot-A plaintext envelope** instead (stable; carries entries + rootKey). |193+| 5 | `unlockWithRecoveryWords(): ByteArray?` + `resetPasswordWithRecoveryKey(vaultKey, …)` | Returns `Boolean` and adopts the recovered payload; reset is `resetPasswordWithRecoveryWords(words, newPassword): Boolean` (re-seal + unlock in one call). No detached vault key. |194+| 6 | BIP39 list in `res/raw/bip39_english.txt`; "add it if missing" | Lives in Kotlin `WORD_LIST` (RecoveryWordList.kt). No raw asset. Note the list has 2052 entries (index 0 and 1 both `"abandon"`); the existing encode/decode already accounts for this — do not "fix" it. |195+| 7 | `secureRandom(16)`, `blake3(...)` helpers; add `recoveryWordsHash` | `VaultCrypto.generateSalt()` (16B) and the existing `recoveryWordsHash(words)` cover these; `setRecoveryWords` already stores the BLAKE3 hash. |196+| 8 | §3b: escrow needs no re-seal because it seals "the vault master key" | Wrong rationale, right conclusion: escrow seals the slot-A plaintext (unchanged by a password change), so it stays valid — but `changePassword` rebuilds `StoredVault` and would DROP the field. Required edit: carry `recoveryEscrow` forward. |197+| 9 | A shared `PeachField` underline component exists | It does not. `LockScreen` uses a private `UnderlineField`. The draft screen uses its own local underline fields (same idiom). |198+| 10 | LockScreen `hasVault` unlock state already shows restore affordances; add `onForgotPassword` callback | Restore tabs render only in the `!hasVault` (create) branch. Add the link to the unlock branch and reuse the existing `onNavigate(PeachNav.RecoveryEntry)` — no new callback param. |199+| 11 | `MIN_PASSWORD_LENGTH` / strength gate | Reuse `MIN_PASSWORD_LENGTH = 12` and `MIN_CREATE_STRENGTH = 2` from `ui/lock/LockViewModel.kt`; `scorePassword` returns 0–4. The screen gates on `score >= 2` + match + length, matching create-vault. |200+201+---202+203+## 5. Security notes (for reviewer)204+205+- The escrow blob is AES-256-GCM under a key the recovery words derive via HKDF.206+  AAD `recovery_escrow_v1` is distinct from `slot_a_v1`, so an escrow blob can207+  never be swapped in as a slot-A blob.208+- Wrong words surface as `AEADBadTagException` (GCM tag mismatch) or an209+  `IllegalArgumentException` from `wordsToRootKeyMaterial` (bad BIP39 checksum/210+  unknown word) — both map to `false` / `null` in the repo, and to the211+  "Incorrect recovery words" UI error.212+- All transient key material (`wordsToRootKeyMaterial` entropy, the213+  `SecretKeySpec.encoded` copy, the decoded plaintext) is zeroed in `finally`214+  blocks, consistent with the existing repo's `VaultCrypto.zero` discipline.215+- The escrow weakens the threat model deliberately: anyone with the 12 words can216+  decrypt the vault without the password (that is the feature). This matches the217+  browser design referenced in CONTINUITY.md. Recovery is never offered for the218+  decoy/duress slot (`persistSlotAWithEscrow` refuses in `decoyMode`).

view file

app/drafts/C1/C1-RecoveryEscrowTest.kt+131 −0
@@ -0,0 +1,131 @@1+/*2+ * C1 — RecoveryEscrowTest3+ * Target destination: app/src/test/java/com/peachpasswords/vault/RecoveryEscrowTest.kt4+ *5+ * The 5 tests from brief Part 3d, written against the REAL repo/crypto API and6+ * the C1 additions (unlockWithRecoveryWords/resetPasswordWithRecoveryWords/7+ * hasRecoveryEscrow + StoredVault.recoveryEscrow).8+ *9+ * Self-contained FakeStorage (the one in VaultRepositoryTest.kt is file-private,10+ * so we declare our own). After the C1 StoredVault delta lands, this FakeStorage11+ * needs no change — it stores the whole StoredVault object, so the new12+ * recoveryEscrow field round-trips automatically.13+ *14+ * Recovery words must be a CHECKSUM-VALID BIP39 phrase. We get one for free from15+ * rootKeyToWords(rootKey) — exactly the words this vault would display, and the16+ * same construction the existing recovery_words tests use.17+ */18+19+package com.peachpasswords.vault20+21+import kotlinx.coroutines.runBlocking22+import org.junit.Assert.assertEquals23+import org.junit.Assert.assertFalse24+import org.junit.Assert.assertNotNull25+import org.junit.Assert.assertNull26+import org.junit.Assert.assertTrue27+import org.junit.Test28+29+private class FakeStorage : VaultStorage {30+    var slotA: StoredVault? = null31+    var slotB: String? = null32+    private var ver: Long = 033+    private var settings = VaultSettings()34+    override fun loadSlotA() = slotA35+    override fun hasVault() = slotA != null36+    override fun writeSlotA(slot: StoredVault): Boolean { slotA = slot; return true }37+    override fun writeSlotB(blobBase64: String): Boolean { slotB = blobBase64; return true }38+    var decoy: StoredVault? = null39+    override fun loadDecoySlot() = decoy40+    override fun writeDecoySlot(slot: StoredVault): Boolean { decoy = slot; return true }41+    override fun hasDecoySlot() = decoy != null42+    override fun clearDecoySlot() { decoy = null }43+    override fun version() = ver44+    override fun stampLocalMutation(): Long { ver = maxOf(System.currentTimeMillis(), ver + 1); return ver }45+    override fun loadSettings() = settings46+    override fun writeSettings(s: VaultSettings): Boolean { settings = s; return true }47+    override fun clearVault() { slotA = null; slotB = null; ver = 0; settings = VaultSettings() }48+}49+50+class RecoveryEscrowTest {51+52+    /** Recovery words this vault would actually show — derived from its sync root key. */53+    private fun recoveryWordsOf(repo: VaultRepository): List<String> {54+        val key = repo.syncMasterKey()!!55+        return try { rootKeyToWords(key) } finally { VaultCrypto.zero(key) }56+    }57+58+    private fun login(title: String, password: String = "pw") =59+        VaultEntry(id = "", title = title, type = "login", password = password, createdAt = 0, modifiedAt = 0)60+61+    // 1 — setRecoveryWords stores a non-null RecoveryEscrow in StoredVault.62+    @Test fun set_recovery_words_writes_escrow() = runBlocking {63+        val storage = FakeStorage()64+        val repo = VaultRepository(storage)65+        repo.createVault("pw")66+        assertNull(storage.slotA?.recoveryEscrow)67+        assertTrue(repo.setRecoveryWords(recoveryWordsOf(repo)))68+        assertNotNull(storage.slotA?.recoveryEscrow)69+        assertTrue(repo.hasRecoveryEscrow())70+    }71+72+    // 2 — unlockWithRecoveryWords with correct words succeeds.73+    @Test fun unlock_with_correct_words_succeeds() = runBlocking {74+        val storage = FakeStorage()75+        val repo = VaultRepository(storage)76+        repo.createVault("pw")77+        repo.addEntry(login("GitHub"))78+        val words = recoveryWordsOf(repo)79+        repo.setRecoveryWords(words)80+        repo.lock()81+        assertTrue(repo.unlockWithRecoveryWords(words))82+        // Recovered session sees the entry that was sealed into the escrow.83+        assertTrue(repo.getEntries().any { it.title == "GitHub" })84+    }85+86+    // 3 — unlockWithRecoveryWords with wrong words fails.87+    @Test fun unlock_with_wrong_words_fails() = runBlocking {88+        val storage = FakeStorage()89+        val repo = VaultRepository(storage)90+        repo.createVault("pw")91+        repo.setRecoveryWords(recoveryWordsOf(repo))92+        repo.lock()93+        // A different, still-checksum-valid phrase from an unrelated root key.94+        val wrong = rootKeyToWords(ByteArray(32) { (it + 7).toByte() })95+        assertFalse(repo.unlockWithRecoveryWords(wrong))96+    }97+98+    // 4 — unlockWithRecoveryWords with no escrow set returns false.99+    @Test fun unlock_with_no_escrow_fails() = runBlocking {100+        val storage = FakeStorage()101+        val repo = VaultRepository(storage)102+        repo.createVault("pw")103+        val words = recoveryWordsOf(repo) // never call setRecoveryWords104+        repo.lock()105+        assertFalse(repo.hasRecoveryEscrow())106+        assertFalse(repo.unlockWithRecoveryWords(words))107+    }108+109+    // 5 — Full round-trip: create → set words → reset password via recovery → unlock with new password.110+    @Test fun full_recovery_resets_password() = runBlocking {111+        val storage = FakeStorage()112+        val repo = VaultRepository(storage)113+        repo.createVault("old-pass")114+        repo.addEntry(login("Bank"))115+        val words = recoveryWordsOf(repo)116+        repo.setRecoveryWords(words)117+        repo.lock()118+119+        assertTrue(repo.unlockWithRecoveryWords(words))120+        assertTrue(repo.resetPasswordWithRecoveryWords(words, "brand-new-pass"))121+        assertTrue(repo.isUnlocked.value)122+        repo.lock()123+124+        // Old password no longer works; the new one does and the entry survived.125+        assertEquals(UnlockResult.WrongPassword, repo.unlock("old-pass"))126+        assertEquals(UnlockResult.Success, repo.unlock("brand-new-pass"))127+        assertTrue(repo.getEntries().any { it.title == "Bank" })128+        // Escrow survived the password reset, so a second recovery still works.129+        assertTrue(repo.hasRecoveryEscrow())130+    }131+}

view file

app/drafts/C1/C1-crypto-notes.md+175 −0
@@ -0,0 +1,175 @@1+# C1 — Crypto & Model Deltas (Recovery Key Escrow)2+3+This file describes the EXACT data-model and crypto changes the orchestrator4+must apply to the real source. It does **not** edit the shared files itself.5+Everything here is reconciled against the real `VaultCrypto.kt`, `VaultStore.kt`,6+`RecoveryWords.kt` and `VaultRepository.kt` (read v2.1.38).7+8+---9+10+## 0. Where the brief is wrong (read this first)11+12+The brief invents several APIs. Real ground truth:13+14+| Brief assumed | Reality |15+|---|---|16+| `data class StoredVault(slotA, slotDuress, recoveryEscrow, …)` | `StoredVault` is just `(version: Int, salt: String, blob: String)` — ONE encrypted slot. The duress/decoy slot is a **separate** `StoredVault` under a different prefs key (`KEY_SLOT_DURESS`), not a field. There is no `slotA`/`slotDuress`/`recoveryEscrow` field. |17+| `VaultCrypto.encryptRaw` / `decryptRaw` / `encryptSlot` | Do not exist. Real API is `encrypt(plaintext, key, aad): ByteArray` and `decrypt(data, key, aad): ByteArray`. Both manage a 12-byte prepended nonce; `encrypt` output is `nonce(12) || ciphertext||tag`. AAD is a **required** `String` arg. |18+| `deriveRecoveryKey(wordMaterial: String, salt)` using **Argon2id** via `VaultCrypto.deriveKey` | `deriveRecoveryKey` ALREADY EXISTS in `RecoveryWords.kt`, signature `deriveRecoveryKey(wordMaterial: ByteArray, salt: ByteArray): SecretKeySpec`, and it uses **HKDF-SHA256** with info `"peach-recovery-v1"`, NOT Argon2id. The `wordMaterial` is the 16-byte entropy from `wordsToRootKeyMaterial(words)`, NOT the joined word string. |19+| `secureRandom(16)` helper | No such helper. Use `VaultCrypto.generateSalt()` (16 bytes) or `VaultCrypto.generateNoise()`. |20+| `currentVaultKey()` is the thing to escrow | `currentVaultKey()` returns the **Argon2id-derived password key** (`derivedKey`), which ROTATES on every password change. Escrowing it would break after a password change. We must escrow something password-independent. See §2. |21+| BIP39 list lives in `res/raw/bip39_english.txt` | It does **not**. The 2048-word list is a Kotlin `val WORD_LIST` in `RecoveryWordList.kt`. (Note quirk: it has 2052 entries because index 0 and 1 are both `"abandon"` — `rootKeyToWords`/`wordsToRootKeyMaterial` already account for this; do not "fix" it.) Helpers `getWordSuggestions`, `findInvalidWords`, `wordsToRootKeyMaterial` (checksum-validating) already exist. |22+| `blake3(...)` / `recoveryWordsHash` to add | `recoveryWordsHash(words)` already exists in `RecoveryWords.kt`. `setRecoveryWords` already stores it. |23+24+---25+26+## 1. What "the vault master key" actually is here27+28+There are THREE distinct keys in play; the brief conflates them:29+30+1. **`derivedKey`** — Argon2id(password, slotA.salt). Wraps slot A. Rotates on31+   every `changePassword`. NOT stable.32+2. **`rootKey`** (`VaultPayload.rootKeyB64`) — the stable 32-byte sync master key.33+   Stable across password changes. This is what the 12 recovery words are34+   DERIVED from (`rootKeyToWords`). But it is NOT the key that decrypts slot A.35+3. The **slot-A plaintext** (`VaultPayload` JSON: entries, rootKey, flags). This36+   is what we ultimately need to recover a vault and re-seal it under a new37+   password.38+39+The recovery flow needs to produce a usable, unlocked session AND a re-wrapped40+slot A under the new password. That requires the **slot-A plaintext**, not just41+the rootKey. So the escrow seals the slot-A plaintext envelope.42+43+> Why not escrow `derivedKey`? It rotates on password change, so the escrow44+> would silently go stale (brief §3b's own concern). Why not escrow only45+> `rootKey`? rootKey alone cannot decrypt slot A — you would still be locked46+> out of the entries. Sealing the plaintext envelope is the only choice that47+> makes recovery actually unlock the vault without the password.48+49+---50+51+## 2. Data-model delta — add the escrow to `StoredVault`52+53+The escrow MUST be readable without the password (that is the entire point), so54+it cannot live inside the AES-GCM `blob`. The clean home is a new **nullable**55+field on `StoredVault` (the same record `writeSlotA` already persists, and whose56+`salt` is already plaintext at rest). Being nullable + `ignoreUnknownKeys` keeps57+old vaults and the JSON codec backward compatible.58+59+Apply this delta to `VaultStore.kt`:60+61+```kotlin62+@Serializable63+data class StoredVault(64+    val version: Int = 1,65+    val salt: String,66+    val blob: String,67+    val recoveryEscrow: RecoveryEscrow? = null, // NEW — null until recovery words set68+)69+70+/**71+ * A second, password-independent copy of the slot-A plaintext envelope, sealed72+ * under a key derived from the 12 BIP39 recovery words. Lets the vault be73+ * recovered (and re-wrapped under a new password) without the old password.74+ *75+ * [salt] (base64, 16B) is the HKDF salt for deriveRecoveryKey.76+ * [blob] (base64) is VaultCrypto.encrypt(slotAPlaintext, recoveryKey, AAD_RECOVERY)77+ *   i.e. nonce(12) || AES-256-GCM ciphertext||tag.78+ */79+@Serializable80+data class RecoveryEscrow(81+    val salt: String,82+    val blob: String,83+)84+```85+86+Because `StoredVault` is `@Serializable` and `VaultCodec` uses87+`ignoreUnknownKeys = true; encodeDefaults = true`, both encode and decode88+continue to work; a vault written before C1 simply decodes with89+`recoveryEscrow = null`.90+91+> Note for the decoy/duress slot: it is also a `StoredVault`, so it will gain a92+> (always-null) `recoveryEscrow` field too. That is harmless — recovery is never93+> offered for the decoy. Leave it null.94+95+---96+97+## 3. Add a recovery AAD constant98+99+Add to `VaultCrypto.kt` alongside the other AAD constants:100+101+```kotlin102+const val AAD_RECOVERY = "recovery_escrow_v1"103+```104+105+This is the AAD passed to `encrypt`/`decrypt` for the escrow blob. It is106+distinct from `AAD_SLOT_A` so an escrow blob can never be confused with /107+substituted for a slot-A blob.108+109+---110+111+## 4. Seal / open the escrow — the real calls112+113+`deriveRecoveryKey` already exists and takes the **16-byte entropy** material,114+not the joined string. The entropy is obtained from the words via115+`wordsToRootKeyMaterial(words)` (which also validates the BIP39 checksum and116+throws on a bad phrase). So:117+118+### Seal (in setRecoveryWords)119+120+```kotlin121+// payloadPlain: ByteArray = VaultCodec.encode(currentPayload())  // slot-A plaintext122+val material = wordsToRootKeyMaterial(words)          // 16B entropy (throws if checksum bad)123+val salt = VaultCrypto.generateSalt()                 // 16B124+val recoveryKey = deriveRecoveryKey(material, salt)   // SecretKeySpec (AES-256, HKDF)125+val sealed = VaultCrypto.encrypt(payloadPlain, recoveryKey.encoded, VaultCrypto.AAD_RECOVERY)126+val escrow = RecoveryEscrow(salt = b64(salt), blob = b64(sealed))127+VaultCrypto.zero(material)128+VaultCrypto.zero(recoveryKey.encoded)  // SecretKeySpec.encoded returns a copy; zero it129+VaultCrypto.zero(payloadPlain)130+```131+132+> `deriveRecoveryKey` returns a `SecretKeySpec`; `VaultCrypto.encrypt` wants a133+> `ByteArray` key. Use `recoveryKey.encoded` (a fresh copy of the 32 key bytes)134+> and zero it afterwards.135+136+### Open (in unlockWithRecoveryWords)137+138+```kotlin139+val escrow = storedVault.recoveryEscrow ?: return null140+val material = try { wordsToRootKeyMaterial(words) } catch (_: Exception) { return null }141+val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))142+return try {143+    val payloadPlain = VaultCrypto.decrypt(unb64(escrow.blob), recoveryKey.encoded, VaultCrypto.AAD_RECOVERY)144+    // payloadPlain is the slot-A VaultPayload JSON — decode + adopt it as the live session145+    VaultCodec.decode(payloadPlain)146+} catch (e: javax.crypto.AEADBadTagException) {147+    null  // wrong words (GCM tag mismatch)148+} finally {149+    VaultCrypto.zero(material)150+    VaultCrypto.zero(recoveryKey.encoded)151+}152+```153+154+> `wordsToRootKeyMaterial` throws `IllegalArgumentException` on a bad checksum or155+> unknown word; a GCM mismatch throws `AEADBadTagException`. Both mean "wrong156+> words" → return null. The repo method in `C1-repo-additions.kt` catches both.157+158+---159+160+## 5. Password-change re-seal (brief §3b)161+162+The brief's §3b reasoning is WRONG for this codebase: it assumes the escrow seals163+"the vault master key" which doesn't change. Here the escrow seals the slot-A164+**plaintext**, and that plaintext is logically unchanged by a password change165+(same entries, same rootKey) — `changePassword` only re-wraps it under a new166+Argon2id key. **Therefore the existing `recoveryEscrow` remains valid after a167+password change with no re-seal needed** — as long as `changePassword` PRESERVES168+the existing `recoveryEscrow` field when it writes the new `StoredVault`.169+170+The real `changePassword` builds a brand-new `StoredVault(version, salt, blob)`171+and drops any extra fields. So the ONE required change is to carry the escrow172+forward. See the exact edit in `C1-repo-additions.kt` §3b. (Recovery words are173+derived from `rootKey`, which `changePassword` preserves inside the re-encrypted174+payload, so the words themselves also stay valid — consistent with the existing175+`recovery_words_set_verify_and_persist` behaviour.)

view file

app/drafts/C1/C1-repo-additions.kt+220 −0
@@ -0,0 +1,220 @@1+/*2+ * C1 — VaultRepository additions (Recovery Key Escrow)3+ *4+ * DRAFT SNIPPET — not a standalone compilation unit. These members and edits go5+ * INTO the existing `com.peachpasswords.vault.VaultRepository` class (and one6+ * helper). They are bound to the REAL repo internals read at v2.1.38:7+ *   - mutex (kotlinx Mutex), withLock8+ *   - store.loadSlotA() / store.writeSlotA(StoredVault) / store.stampLocalMutation()9+ *   - derivedKey: ByteArray? / rootKey / entryList / _settings / publish() / _isUnlocked10+ *   - currentPayload(): VaultPayload  (private — already exists)11+ *   - sealSlotA / persistSlotA (private — already exist)12+ *   - b64()/unb64() top-level helpers in VaultRepository.kt13+ *   - VaultCrypto.encrypt/decrypt/zero/generateSalt14+ *   - RecoveryWords.kt: wordsToRootKeyMaterial(words), deriveRecoveryKey(material, salt)15+ *16+ * Requires the model delta from C1-crypto-notes.md (StoredVault.recoveryEscrow,17+ * RecoveryEscrow, VaultCrypto.AAD_RECOVERY).18+ *19+ * Needed import (top of VaultRepository.kt):20+ *   import javax.crypto.AEADBadTagException21+ */22+23+// ─────────────────────────────────────────────────────────────────────────────24+// 3a — Seal escrow inside the EXISTING setRecoveryWords (REPLACE its body)25+//26+// Current (v2.1.38):27+//   suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {28+//       requireUnlocked()29+//       recoveryWordHash = recoveryWordsHash(words)30+//       recoveryWordsSet = true31+//       runCatching { persistSlotA(bumpVersion = false) }.getOrDefault(false)32+//   }33+//34+// Replacement: also seal the slot-A plaintext under the recovery key and write35+// the escrow into slot A. We persist via a dedicated helper because persistSlotA36+// re-seals slot A but does NOT carry the new escrow field, so we set it here.37+// ─────────────────────────────────────────────────────────────────────────────38+39+    suspend fun setRecoveryWords(words: List<String>): Boolean = mutex.withLock {40+        requireUnlocked()41+        recoveryWordHash = recoveryWordsHash(words)42+        recoveryWordsSet = true43+        runCatching { persistSlotAWithEscrow(buildRecoveryEscrow(words)) }.getOrDefault(false)44+    }45+46+    /**47+     * Seal the current slot-A plaintext envelope under a key derived from the 1248+     * BIP39 recovery [words], for password-independent recovery. Returns null if49+     * the words are not a valid BIP39 phrase (checksum/unknown word).50+     */51+    private fun buildRecoveryEscrow(words: List<String>): RecoveryEscrow? {52+        val material = try {53+            wordsToRootKeyMaterial(words)54+        } catch (_: Exception) {55+            return null56+        }57+        val salt = VaultCrypto.generateSalt()58+        val recoveryKey = deriveRecoveryKey(material, salt)59+        val keyBytes = recoveryKey.encoded60+        val plaintext = VaultCodec.encode(currentPayload())61+        return try {62+            val sealed = VaultCrypto.encrypt(plaintext, keyBytes, VaultCrypto.AAD_RECOVERY)63+            RecoveryEscrow(salt = b64(salt), blob = b64(sealed))64+        } finally {65+            VaultCrypto.zero(material)66+            VaultCrypto.zero(keyBytes)67+            VaultCrypto.zero(plaintext)68+        }69+    }70+71+    /**72+     * Re-seal slot A from the current in-memory state under the live key, and set73+     * [escrow] on the written record. Mirrors persistSlotA's non-decoy path but74+     * carries the recovery escrow field. Never runs in decoy mode (caller is a75+     * real-vault action). Persists without a version bump (recovery metadata is76+     * local-only, like the existing setRecoveryWords).77+     */78+    private fun persistSlotAWithEscrow(escrow: RecoveryEscrow?): Boolean {79+        val key = derivedKey ?: throw IllegalStateException("vault_locked")80+        if (decoyMode) return false // recovery is never offered for the decoy81+        val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")82+        val plaintext = VaultCodec.encode(currentPayload())83+        val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))84+        val next = prior.copy(blob = blob, recoveryEscrow = escrow ?: prior.recoveryEscrow)85+        if (!store.writeSlotA(next)) return false86+        try {87+            writeMatchingNoiseSlotB(next)88+        } catch (e: Exception) {89+            store.writeSlotA(prior)90+            throw e91+        }92+        return true93+    }94+95+// ─────────────────────────────────────────────────────────────────────────────96+// 3b — Preserve escrow on password change (ONE-LINE edit inside changePassword)97+//98+// In the real changePassword, the new StoredVault is built as:99+//     val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob)100+// This DROPS the recoveryEscrow. Change it to carry the existing escrow forward.101+// The escrow seals the slot-A PLAINTEXT (entries + rootKey), which a password102+// change does not alter — only the slot-A wrapping changes — so the existing103+// escrow stays valid and must be preserved, not regenerated.104+//105+// REPLACE that one line with:106+//     val next = StoredVault(107+//         version = slotA.version,108+//         salt = b64(newSalt),109+//         blob = blob,110+//         recoveryEscrow = slotA.recoveryEscrow, // carry forward — still valid111+//     )112+// ─────────────────────────────────────────────────────────────────────────────113+114+// ─────────────────────────────────────────────────────────────────────────────115+// 3c — Recovery unlock + password reset (NEW methods; add to VaultRepository)116+// ─────────────────────────────────────────────────────────────────────────────117+118+    /**119+     * Attempt to unlock the vault using the 12 BIP39 recovery [words] instead of120+     * the master password. On success the session is fully unlocked (entries,121+     * rootKey, settings adopted) exactly as a normal unlock, and the decrypted122+     * slot-A plaintext is adopted as live state. Returns true on success, false123+     * if there is no escrow, the words are invalid, or the words are wrong.124+     *125+     * Unlike the brief's `unlockWithRecoveryWords(): ByteArray?`, this does not126+     * hand back a raw key — there is no single "vault key" to return here (slot A127+     * is wrapped under the rotating Argon2id key). It opens the escrowed payload128+     * directly. Call [resetPasswordWithRecoveryWords] next to set a new password.129+     */130+    suspend fun unlockWithRecoveryWords(words: List<String>): Boolean = mutex.withLock {131+        val slotA = store.loadSlotA() ?: return false132+        val escrow = slotA.recoveryEscrow ?: return false133+        val material = try {134+            wordsToRootKeyMaterial(words)135+        } catch (_: Exception) {136+            return false137+        }138+        val recoveryKey = deriveRecoveryKey(material, unb64(escrow.salt))139+        val keyBytes = recoveryKey.encoded140+        return try {141+            val plaintext = VaultCrypto.decrypt(unb64(escrow.blob), keyBytes, VaultCrypto.AAD_RECOVERY)142+            val payload = VaultCodec.decode(plaintext)143+            // Adopt the recovered payload as the live session. There is no derived144+            // password key yet (we have no password), so derivedKey stays null145+            // until resetPasswordWithRecoveryWords seals slot A under a new password.146+            decoyMode = false147+            entryList = payload.entries.toMutableList()148+            duressConfigured = payload.duressConfigured149+            recoveryWordHash = payload.recoveryWordHash150+            recoveryWordsSet = payload.recoveryWordsSet151+            rootKey = if (payload.rootKeyB64.isNotBlank()) unb64(payload.rootKeyB64)152+                      else VaultCrypto.generateRootKey()153+            _settings.value = store.loadSettings()154+            VaultCrypto.zero(plaintext)155+            true156+        } catch (_: Exception) {157+            false // AEADBadTagException (wrong words) or any decode failure158+        } finally {159+            VaultCrypto.zero(material)160+            VaultCrypto.zero(keyBytes)161+        }162+    }163+164+    /**165+     * After [unlockWithRecoveryWords] succeeds, set a brand-new master password:166+     * re-seal slot A (and refresh the escrow under the same words) under a fresh167+     * Argon2id key, mark the session fully unlocked, and publish. Returns false168+     * if called without a prior successful recovery unlock (no in-memory state).169+     *170+     * Folds the brief's separate `resetPasswordWithRecoveryKey(vaultKey, …)` +171+     * `unlock(newPassword)` into one step, since there is no detached vault key.172+     */173+    suspend fun resetPasswordWithRecoveryWords(174+        words: List<String>,175+        newPassword: String,176+    ): Boolean = mutex.withLock {177+        if (rootKey == null) return false // must have recovered first178+        return try {179+            val newSalt = VaultCrypto.generateSalt()180+            val newKey = VaultCrypto.deriveKey(newPassword, newSalt)181+            val plaintext = VaultCodec.encode(currentPayload())182+            val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))183+            val prior = store.loadSlotA()184+            // Refresh the escrow against the (unchanged) payload so its salt rotates185+            // with the password reset; reuse the prior escrow if word re-seal fails.186+            val freshEscrow = run {187+                val material = try { wordsToRootKeyMaterial(words) } catch (_: Exception) { null }188+                if (material == null) prior?.recoveryEscrow else {189+                    val salt = VaultCrypto.generateSalt()190+                    val rk = deriveRecoveryKey(material, salt)191+                    val kb = rk.encoded192+                    try {193+                        RecoveryEscrow(salt = b64(salt), blob = b64(VaultCrypto.encrypt(plaintext, kb, VaultCrypto.AAD_RECOVERY)))194+                    } finally {195+                        VaultCrypto.zero(material); VaultCrypto.zero(kb)196+                    }197+                }198+            }199+            val next = StoredVault(200+                version = prior?.version ?: 1,201+                salt = b64(newSalt),202+                blob = blob,203+                recoveryEscrow = freshEscrow,204+            )205+            if (!store.writeSlotA(next)) return false206+            writeMatchingNoiseSlotB(next)207+            store.stampLocalMutation()208+            derivedKey?.let(VaultCrypto::zero)209+            derivedKey = newKey210+            VaultCrypto.zero(plaintext)211+            publish()212+            _isUnlocked.value = true213+            true214+        } catch (_: Exception) {215+            false216+        }217+    }218+219+    /** True at rest if this vault has a recovery escrow the recovery flow can use. */220+    fun hasRecoveryEscrow(): Boolean = store.loadSlotA()?.recoveryEscrow != null

view file

app/drafts/C1/RecoveryWordEntryScreen.kt+540 −0
@@ -0,0 +1,540 @@1+/*2+ * C1 — RecoveryWordEntryScreen3+ * Target destination: app/src/main/java/com/peachpasswords/ui/recovery/RecoveryWordEntryScreen.kt4+ *5+ * Two-step "Forgot your password?" recovery flow:6+ *   Step 1 — enter the 12 BIP39 recovery words (3×4 grid, autocomplete, checksum).7+ *   Step 2 — set a new master password (shared StrengthBar), then recover+unlock.8+ *   No-escrow state — shown if this vault has no recovery escrow.9+ *10+ * Bound to REAL APIs (v2.1.38):11+ *   - RecoveryWords.kt: getWordSuggestions(prefix, max), wordsToRootKeyMaterial(words) [checksum]12+ *   - WORD_LIST (in RecoveryWordList.kt) for valid-word tinting13+ *   - VaultRepository: hasRecoveryEscrow(), unlockWithRecoveryWords(words),14+ *                      resetPasswordWithRecoveryWords(words, newPassword)   [C1 additions]15+ *   - ui/security: StrengthBar, scorePassword, strengthColor, strengthLabel16+ *   - theme: PeachColors, PeachType, ShellBackground, LocalPeachAccent17+ *   - MIN_PASSWORD_LENGTH (= 12) from ui/lock/LockViewModel.kt18+ *19+ * NOTE: there is no shared `PeachField` component in this codebase (the brief20+ * assumes one). LockScreen uses a private `UnderlineField`; this file follows21+ * the same idiom with its own local underline fields, matching RecoveryWordsScreen22+ * / LockScreen styling.23+ */24+25+package com.peachpasswords.ui.recovery26+27+import androidx.compose.foundation.background28+import androidx.compose.foundation.border29+import androidx.compose.foundation.clickable30+import androidx.compose.foundation.interaction.MutableInteractionSource31+import androidx.compose.foundation.interaction.collectIsFocusedAsState32+import androidx.compose.foundation.layout.Arrangement33+import androidx.compose.foundation.layout.Box34+import androidx.compose.foundation.layout.Column35+import androidx.compose.foundation.layout.Row36+import androidx.compose.foundation.layout.Spacer37+import androidx.compose.foundation.layout.fillMaxSize38+import androidx.compose.foundation.layout.fillMaxWidth39+import androidx.compose.foundation.layout.height40+import androidx.compose.foundation.layout.padding41+import androidx.compose.foundation.layout.size42+import androidx.compose.foundation.layout.systemBarsPadding43+import androidx.compose.foundation.layout.width44+import androidx.compose.foundation.rememberScrollState45+import androidx.compose.foundation.shape.RoundedCornerShape46+import androidx.compose.foundation.text.BasicTextField47+import androidx.compose.foundation.text.KeyboardActions48+import androidx.compose.foundation.text.KeyboardOptions49+import androidx.compose.foundation.verticalScroll50+import androidx.compose.material3.Text51+import androidx.compose.runtime.Composable52+import androidx.compose.runtime.collectAsState53+import androidx.compose.runtime.getValue54+import androidx.compose.runtime.mutableStateListOf55+import androidx.compose.runtime.mutableStateOf56+import androidx.compose.runtime.remember57+import androidx.compose.runtime.setValue58+import androidx.compose.ui.Alignment59+import androidx.compose.ui.Modifier60+import androidx.compose.ui.draw.clip61+import androidx.compose.ui.draw.drawBehind62+import androidx.compose.ui.focus.FocusRequester63+import androidx.compose.ui.focus.focusRequester64+import androidx.compose.ui.geometry.Offset65+import androidx.compose.ui.geometry.Size66+import androidx.compose.ui.graphics.Color67+import androidx.compose.ui.graphics.SolidColor68+import androidx.compose.ui.text.TextStyle69+import androidx.compose.ui.text.font.FontStyle70+import androidx.compose.ui.text.input.ImeAction71+import androidx.compose.ui.text.input.KeyboardType72+import androidx.compose.ui.text.input.PasswordVisualTransformation73+import androidx.compose.ui.text.input.VisualTransformation74+import androidx.compose.ui.text.style.TextAlign75+import androidx.compose.ui.unit.dp76+import androidx.compose.ui.unit.em77+import androidx.compose.ui.unit.sp78+import androidx.hilt.navigation.compose.hiltViewModel79+import androidx.lifecycle.ViewModel80+import androidx.lifecycle.viewModelScope81+import com.peachpasswords.ui.lock.MIN_PASSWORD_LENGTH82+import com.peachpasswords.ui.security.StrengthBar83+import com.peachpasswords.ui.security.scorePassword84+import com.peachpasswords.ui.security.strengthColor85+import com.peachpasswords.ui.security.strengthLabel86+import com.peachpasswords.ui.theme.LocalPeachAccent87+import com.peachpasswords.ui.theme.PeachColors88+import com.peachpasswords.ui.theme.PeachType89+import com.peachpasswords.ui.theme.ShellBackground90+import com.peachpasswords.vault.VaultRepository91+import com.peachpasswords.vault.WORD_LIST92+import com.peachpasswords.vault.getWordSuggestions93+import com.peachpasswords.vault.wordsToRootKeyMaterial94+import dagger.hilt.android.lifecycle.HiltViewModel95+import kotlinx.coroutines.Dispatchers96+import kotlinx.coroutines.flow.MutableStateFlow97+import kotlinx.coroutines.flow.StateFlow98+import kotlinx.coroutines.flow.asStateFlow99+import kotlinx.coroutines.flow.update100+import kotlinx.coroutines.launch101+import kotlinx.coroutines.withContext102+import javax.inject.Inject103+104+private const val WORD_COUNT = 12105+106+private enum class RecoveryStep { WORDS, PASSWORD, NO_ESCROW }107+108+data class RecoveryEntryUiState(109+    val step: RecoveryStep = RecoveryStep.WORDS,110+    val checksumValid: Boolean = false,111+    val wordsError: String? = null,112+    val passwordError: String? = null,113+    val working: Boolean = false,114+)115+116+@HiltViewModel117+class RecoveryEntryViewModel @Inject constructor(118+    private val vault: VaultRepository,119+) : ViewModel() {120+121+    private val _state = MutableStateFlow(122+        RecoveryEntryUiState(123+            // If this vault was never set up for recovery, drop straight to the124+            // no-escrow state instead of letting the user type 12 words for nothing.125+            step = if (vault.hasRecoveryEscrow()) RecoveryStep.WORDS else RecoveryStep.NO_ESCROW,126+        ),127+    )128+    val state: StateFlow<RecoveryEntryUiState> = _state.asStateFlow()129+130+    private var validatedWords: List<String> = emptyList()131+132+    /** Validate the BIP39 checksum off the main thread; gates the [Continue] button. */133+    fun validateWords(words: List<String>) {134+        viewModelScope.launch {135+            val ok = withContext(Dispatchers.Default) {136+                runCatching { wordsToRootKeyMaterial(words) }.isSuccess137+            }138+            validatedWords = if (ok) words.map { it.trim().lowercase() } else emptyList()139+            _state.update {140+                it.copy(141+                    checksumValid = ok,142+                    wordsError = if (!ok && words.all { w -> w.isNotBlank() }) {143+                        "These words don't form a valid recovery phrase — check for typos"144+                    } else null,145+                )146+            }147+        }148+    }149+150+    fun continueToPassword() {151+        if (_state.value.checksumValid) _state.update { it.copy(step = RecoveryStep.PASSWORD) }152+    }153+154+    /**155+     * Recover the vault with the validated words and set [newPassword]. On success156+     * the vault is left unlocked; [onSuccess] should navigate to the vault list.157+     */158+    fun recover(newPassword: String, confirm: String, onSuccess: () -> Unit) {159+        val s = _state.value160+        if (s.working) return161+        when {162+            newPassword.length < MIN_PASSWORD_LENGTH ->163+                return _state.update { it.copy(passwordError = "Password must be at least $MIN_PASSWORD_LENGTH characters") }164+            newPassword != confirm ->165+                return _state.update { it.copy(passwordError = "Passwords do not match") }166+            scorePassword(newPassword) < 2 ->167+                return _state.update { it.copy(passwordError = "Password too weak — try a longer or more varied password") }168+        }169+        _state.update { it.copy(working = true, passwordError = null) }170+        viewModelScope.launch {171+            val unlocked = vault.unlockWithRecoveryWords(validatedWords)172+            if (!unlocked) {173+                _state.update { it.copy(working = false, passwordError = "Incorrect recovery words — vault cannot be unlocked") }174+                return@launch175+            }176+            val reset = vault.resetPasswordWithRecoveryWords(validatedWords, newPassword)177+            if (!reset) {178+                _state.update { it.copy(working = false, passwordError = "Something went wrong — please try again") }179+                return@launch180+            }181+            _state.update { it.copy(working = false) }182+            onSuccess()183+        }184+    }185+}186+187+@Composable188+fun RecoveryWordEntryScreen(189+    onSuccess: () -> Unit,190+    onBack: () -> Unit,191+    onRestore: () -> Unit = onBack,192+    vm: RecoveryEntryViewModel = hiltViewModel(),193+) {194+    val state by vm.state.collectAsState()195+    ShellBackground {196+        Column(197+            modifier = Modifier198+                .fillMaxSize()199+                .systemBarsPadding()200+                .padding(horizontal = 22.dp, vertical = 18.dp)201+                .verticalScroll(rememberScrollState()),202+        ) {203+            when (state.step) {204+                RecoveryStep.WORDS -> WordStep(state, vm, onBack)205+                RecoveryStep.PASSWORD -> PasswordStep(state, vm, onSuccess)206+                RecoveryStep.NO_ESCROW -> NoEscrowStep(onRestore = onRestore, onBack = onBack)207+            }208+        }209+    }210+}211+212+@Composable213+private fun WordStep(state: RecoveryEntryUiState, vm: RecoveryEntryViewModel, onBack: () -> Unit) {214+    val words = remember { mutableStateListOf(*Array(WORD_COUNT) { "" }) }215+    val focusers = remember { List(WORD_COUNT) { FocusRequester() } }216+217+    fun onWordChange(i: Int, raw: String) {218+        words[i] = raw.trim().lowercase().filter { it.isLetter() }219+        // Re-run checksum validation once all 12 are filled, or to clear a stale220+        // valid/error state the moment a previously-complete grid is edited.221+        if (words.all { it.isNotBlank() } || state.checksumValid || state.wordsError != null) {222+            vm.validateWords(words.toList())223+        }224+    }225+226+    Eyebrow("VAULT RECOVERY")227+    Spacer(Modifier.height(10.dp))228+    Headline("enter your\nrecovery words.")229+    Spacer(Modifier.height(18.dp))230+231+    GlassPanel {232+        // 3 columns × 4 rows.233+        for (row in 0 until 4) {234+            Row(Modifier.fillMaxWidth().padding(vertical = 6.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {235+                for (col in 0 until 3) {236+                    val i = row * 3 + col237+                    WordSlot(238+                        index = i,239+                        value = words[i],240+                        focusRequester = focusers[i],241+                        onValueChange = { onWordChange(i, it) },242+                        onPicked = { picked ->243+                            words[i] = picked244+                            if (i + 1 < WORD_COUNT) focusers[i + 1].requestFocus()245+                            if (words.all { it.isNotBlank() }) vm.validateWords(words.toList())246+                        },247+                        imeAction = if (i == WORD_COUNT - 1) ImeAction.Done else ImeAction.Next,248+                        onNext = { if (i + 1 < WORD_COUNT) focusers[i + 1].requestFocus() },249+                        modifier = Modifier.weight(1f),250+                    )251+                }252+            }253+        }254+255+        if (state.wordsError != null) {256+            Spacer(Modifier.height(10.dp))257+            Text(258+                state.wordsError,259+                color = PeachColors.Breach,260+                style = PeachType.labelMono.copy(fontSize = 10.sp),261+            )262+        }263+    }264+265+    Spacer(Modifier.height(18.dp))266+    AccentButton("Continue", enabled = state.checksumValid, onClick = vm::continueToPassword)267+    Spacer(Modifier.height(10.dp))268+    GhostButton("Back to login", PeachColors.T1, onBack)269+}270+271+@Composable272+private fun WordSlot(273+    index: Int,274+    value: String,275+    focusRequester: FocusRequester,276+    onValueChange: (String) -> Unit,277+    onPicked: (String) -> Unit,278+    imeAction: ImeAction,279+    onNext: () -> Unit,280+    modifier: Modifier = Modifier,281+) {282+    val accent = LocalPeachAccent.current283+    val interaction = remember { MutableInteractionSource() }284+    val focused by interaction.collectIsFocusedAsState()285+    val isValidWord = remember(value) { value.isNotBlank() && WORD_LIST.contains(value) }286+    val suggestions = remember(value, focused) {287+        if (focused && value.isNotBlank() && !isValidWord) getWordSuggestions(value, 4) else emptyList()288+    }289+290+    Column(modifier = modifier) {291+        Row(verticalAlignment = Alignment.CenterVertically) {292+            Text(293+                "${index + 1}",294+                color = accent,295+                style = PeachType.recoveryNumeral,296+                textAlign = TextAlign.End,297+                modifier = Modifier.width(20.dp),298+            )299+            Spacer(Modifier.width(4.dp))300+            BasicTextField(301+                value = value,302+                onValueChange = onValueChange,303+                singleLine = true,304+                textStyle = PeachType.recoveryWord.copy(color = PeachColors.T0),305+                cursorBrush = SolidColor(accent),306+                keyboardOptions = KeyboardOptions(307+                    keyboardType = KeyboardType.Password, // hint: no autocorrect/suggestions308+                    imeAction = imeAction,309+                ),310+                keyboardActions = KeyboardActions(onNext = { onNext() }, onDone = { onNext() }),311+                interactionSource = interaction,312+                modifier = Modifier313+                    .weight(1f)314+                    .focusRequester(focusRequester)315+                    .background(if (isValidWord) accent.copy(alpha = 0.08f) else Color.Transparent)316+                    .drawBehind {317+                        drawRect(318+                            color = if (focused) accent else PeachColors.T3,319+                            topLeft = Offset(0f, size.height - 1.dp.toPx()),320+                            size = Size(size.width, 1.dp.toPx()),321+                        )322+                    }323+                    .padding(vertical = 6.dp, horizontal = 2.dp),324+            )325+        }326+        // Inline autocomplete dropdown.327+        if (suggestions.isNotEmpty()) {328+            Column(329+                Modifier330+                    .fillMaxWidth()331+                    .clip(RoundedCornerShape(6.dp))332+                    .background(PeachColors.S2)333+                    .padding(vertical = 2.dp),334+            ) {335+                suggestions.forEach { word ->336+                    Text(337+                        word,338+                        color = PeachColors.T1,339+                        style = PeachType.labelMono.copy(fontSize = 11.sp),340+                        modifier = Modifier341+                            .fillMaxWidth()342+                            .clickable { onPicked(word) }343+                            .padding(horizontal = 8.dp, vertical = 5.dp),344+                    )345+                }346+            }347+        }348+    }349+}350+351+@Composable352+private fun PasswordStep(state: RecoveryEntryUiState, vm: RecoveryEntryViewModel, onSuccess: () -> Unit) {353+    var password by remember { mutableStateOf("") }354+    var confirm by remember { mutableStateOf("") }355+    var reveal by remember { mutableStateOf(false) }356+    val score = remember(password) { scorePassword(password) }357+    val canSubmit = score >= 2 && password.isNotEmpty() && password == confirm && !state.working358+359+    Eyebrow("VAULT RECOVERY")360+    Spacer(Modifier.height(10.dp))361+    Headline("set a new\npassword.")362+    Spacer(Modifier.height(18.dp))363+364+    GlassPanel {365+        FieldLabel("new password")366+        Spacer(Modifier.height(4.dp))367+        PasswordField(368+            value = password,369+            onChange = { password = it },370+            reveal = reveal,371+            onToggleReveal = { reveal = !reveal },372+            imeAction = ImeAction.Next,373+        )374+375+        if (password.isNotEmpty()) {376+            Spacer(Modifier.height(14.dp))377+            StrengthBar(score = score)378+            Spacer(Modifier.height(6.dp))379+            Text(380+                "strength: ${strengthLabel(score)}",381+                color = strengthColor(score),382+                style = PeachType.labelMono,383+                modifier = Modifier.fillMaxWidth(),384+                textAlign = TextAlign.Center,385+            )386+        }387+388+        Spacer(Modifier.height(16.dp))389+        FieldLabel("confirm password")390+        Spacer(Modifier.height(4.dp))391+        PasswordField(392+            value = confirm,393+            onChange = { confirm = it },394+            reveal = reveal,395+            onToggleReveal = { reveal = !reveal },396+            imeAction = ImeAction.Done,397+        )398+399+        Text(400+            state.passwordError ?: " ",401+            color = PeachColors.Breach,402+            style = PeachType.labelMono.copy(fontSize = 10.sp),403+            textAlign = TextAlign.Center,404+            modifier = Modifier.fillMaxWidth().padding(top = 12.dp).height(16.dp),405+        )406+    }407+408+    Spacer(Modifier.height(18.dp))409+    AccentButton(410+        label = if (state.working) "recovering…" else "Recover vault",411+        enabled = canSubmit,412+        onClick = { vm.recover(password, confirm, onSuccess) },413+    )414+}415+416+@Composable417+private fun NoEscrowStep(onRestore: () -> Unit, onBack: () -> Unit) {418+    GlassPanel {419+        Text("⊘", color = PeachColors.T2, style = TextStyle(fontFamily = PeachType.Display, fontSize = 40.sp))420+        Spacer(Modifier.height(12.dp))421+        Text(422+            "recovery not available",423+            color = PeachColors.T1,424+            style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 26.sp),425+        )426+        Spacer(Modifier.height(10.dp))427+        Text(428+            "Recovery words were not set up for this vault. You can restore from a backup instead.",429+            color = PeachColors.T2,430+            style = PeachType.labelMono.copy(fontSize = 10.sp),431+        )432+        Spacer(Modifier.height(18.dp))433+        GhostButton("Restore from backup", LocalPeachAccent.current, onRestore)434+        Spacer(Modifier.height(8.dp))435+        GhostButton("Back to login", PeachColors.T1, onBack)436+    }437+}438+439+// ── Shared local primitives (match LockScreen / RecoveryWordsScreen idiom) ──440+441+@Composable442+private fun Eyebrow(text: String) =443+    Text(text, color = PeachColors.T2, style = PeachType.lockEyebrow)444+445+@Composable446+private fun Headline(text: String) =447+    Text(448+        text,449+        color = PeachColors.T0,450+        style = PeachType.lockHeadline,451+    )452+453+@Composable454+private fun FieldLabel(text: String) =455+    Text(text.uppercase(), color = PeachColors.T2, style = PeachType.labelMono.copy(letterSpacing = 0.08.em))456+457+@Composable458+private fun PasswordField(459+    value: String,460+    onChange: (String) -> Unit,461+    reveal: Boolean,462+    onToggleReveal: () -> Unit,463+    imeAction: ImeAction,464+) {465+    val accent = LocalPeachAccent.current466+    val interaction = remember { MutableInteractionSource() }467+    val focused by interaction.collectIsFocusedAsState()468+    Row(verticalAlignment = Alignment.CenterVertically) {469+        BasicTextField(470+            value = value,471+            onValueChange = onChange,472+            singleLine = true,473+            textStyle = PeachType.unlockInput.copy(color = PeachColors.T0),474+            cursorBrush = SolidColor(accent),475+            visualTransformation = if (reveal) VisualTransformation.None else PasswordVisualTransformation(),476+            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = imeAction),477+            interactionSource = interaction,478+            modifier = Modifier479+                .weight(1f)480+                .drawBehind {481+                    drawRect(482+                        color = if (focused) accent else PeachColors.T3,483+                        topLeft = Offset(0f, size.height - 1.dp.toPx()),484+                        size = Size(size.width, 1.dp.toPx()),485+                    )486+                }487+                .padding(vertical = 8.dp),488+        )489+        Text(490+            if (reveal) "hide" else "show",491+            color = accent,492+            style = PeachType.labelMono,493+            modifier = Modifier.clickable(onClick = onToggleReveal).padding(start = 8.dp, top = 6.dp, bottom = 6.dp),494+        )495+    }496+}497+498+@Composable499+private fun GlassPanel(content: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit) {500+    Column(501+        modifier = Modifier502+            .fillMaxWidth()503+            .clip(RoundedCornerShape(18.dp))504+            .background(Color(0xE0131109))505+            .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))506+            .padding(20.dp),507+        content = content,508+    )509+}510+511+@Composable512+private fun AccentButton(label: String, enabled: Boolean, onClick: () -> Unit) {513+    val accent = LocalPeachAccent.current514+    Box(515+        modifier = Modifier516+            .fillMaxWidth()517+            .clip(RoundedCornerShape(12.dp))518+            .background(if (enabled) accent else accent.copy(alpha = 0.3f))519+            .clickable(enabled = enabled, onClick = onClick)520+            .padding(vertical = 14.dp),521+        contentAlignment = Alignment.Center,522+    ) {523+        Text(label, color = Color(0xFF0C0A06), style = PeachType.bodyMono)524+    }525+}526+527+@Composable528+private fun GhostButton(label: String, color: Color, onClick: () -> Unit) {529+    Box(530+        modifier = Modifier531+            .fillMaxWidth()532+            .clip(RoundedCornerShape(12.dp))533+            .border(1.dp, color.copy(alpha = 0.4f), RoundedCornerShape(12.dp))534+            .clickable(onClick = onClick)535+            .padding(vertical = 12.dp),536+        contentAlignment = Alignment.Center,537+    ) {538+        Text(label, color = color, style = PeachType.bodyMono)539+    }540+}

view file

app/drafts/C7/C7-ChirpTransportTest.kt+177 −0
@@ -0,0 +1,177 @@1+// Intended source path: app/src/test/java/com/peachpasswords/sync/C7ChirpTransportTest.kt2+package com.peachpasswords.sync3+4+import kotlinx.coroutines.Dispatchers5+import kotlinx.coroutines.launch6+import kotlinx.coroutines.runBlocking7+import kotlinx.coroutines.withContext8+import kotlinx.serialization.builtins.ListSerializer9+import kotlinx.serialization.json.Json10+import org.bouncycastle.crypto.params.X25519PrivateKeyParameters11+import org.junit.Assert.assertArrayEquals12+import org.junit.Assert.assertEquals13+import org.junit.Assert.assertNotNull14+import org.junit.Assert.assertTrue15+import org.junit.Test16+import java.io.PipedInputStream17+import java.io.PipedOutputStream18+import java.security.SecureRandom19+20+/**21+ * C7 transport tests. Mirrors the existing ChirpSyncTransportTest idiom: plain22+ * JUnit + runBlocking, no Robolectric. PairedDeviceStore itself needs an Android23+ * Context (EncryptedSharedPreferences), so its persistence is exercised by the24+ * orchestrator's instrumentation tests; here we test the pure-JVM serialization25+ * layer the store round-trips through (test 1) plus its upsert/replace semantics26+ * against an in-memory list (test 2), the frame codec (test 3), the full27+ * Noise-NK-over-frames exchange the server/client share (test 4), and the28+ * timeout/error path (test 5).29+ */30+class C7ChirpTransportTest {31+32+    private val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }33+    private val listSerializer = ListSerializer(PairedDevice.serializer())34+35+    private fun newKeyPair(): Pair<ByteArray, ByteArray> {36+        val priv = X25519PrivateKeyParameters(SecureRandom())37+        return priv.encoded to priv.generatePublicKey().encoded38+    }39+40+    private fun device(id: String, name: String = "Peer") = PairedDevice(41+        deviceId = id,42+        deviceName = name,43+        deviceType = "android",44+        longTermPublicKeyHex = "ab".repeat(32),45+        trustSource = "direct",46+        pairedAt = 1_000L,47+        lastSyncedAt = null,48+    )49+50+    /** Test 1: PairedDevice list survives JSON round-trip (the store's wire form). */51+    @Test52+    fun `paired device list round-trips through json`() {53+        val devices = listOf(device("a", "Alice"), device("b", "Bob"))54+        val encoded = json.encodeToString(listSerializer, devices)55+        val decoded = json.decodeFromString(listSerializer, encoded)56+        assertEquals(devices, decoded)57+        assertEquals("Alice", decoded[0].deviceName)58+        assertEquals("ab".repeat(32), decoded[1].longTermPublicKeyHex)59+    }60+61+    /** Test 2: upsert replaces an existing entry by deviceId (store semantics). */62+    @Test63+    fun `upsert by deviceId replaces rather than duplicates`() {64+        // Mirror PairedDeviceStore.upsert's pure list transform.65+        fun upsert(list: List<PairedDevice>, d: PairedDevice) =66+            list.filterNot { it.deviceId == d.deviceId } + d67+68+        var list = listOf(device("a", "Alice"))69+        list = upsert(list, device("b", "Bob"))70+        assertEquals(2, list.size)71+        list = upsert(list, device("a", "Alice-renamed"))72+        assertEquals(2, list.size)73+        assertEquals("Alice-renamed", list.first { it.deviceId == "a" }.deviceName)74+    }75+76+    /** Test 3: writeFrame/readFrame round-trip across payload sizes. */77+    @Test78+    fun `frame codec round-trips for various sizes`() {79+        for (size in intArrayOf(0, 1, 31, 64, 1500, 65_537)) {80+            val payload = ByteArray(size) { (it % 251).toByte() }81+            val pin = PipedInputStream(1 shl 18)82+            val pout = PipedOutputStream(pin)83+            writeFrame(pout, payload)84+            val read = readFrame(pin)85+            assertArrayEquals("size=$size", payload, read)86+        }87+    }88+89+    /**90+     * Test 4: a full Noise NK handshake + identity frame exchange over a Piped91+     * socket pair — the exact wire the server (responder) and client (initiator)92+     * share. Proves the handshake completes, both sides derive the SAME SAS, and93+     * an encrypted identity frame decrypts correctly. No real network.94+     */95+    @Test96+    fun `noise NK handshake over frames yields matching SAS and decodable identity`() = runBlocking {97+        val (responderPriv, responderPub) = newKeyPair()98+99+        // Cross-wired pipes: initiator's out -> responder's in and vice versa.100+        val i2r = PipedInputStream(1 shl 18); val i2rOut = PipedOutputStream(i2r)101+        val r2i = PipedInputStream(1 shl 18); val r2iOut = PipedOutputStream(r2i)102+103+        val initiator = SocketFrameIO(input = r2i, output = i2rOut)104+        val responder = SocketFrameIO(input = i2r, output = r2iOut)105+106+        val localId = LocalChirpIdentity(107+            deviceId = "client-1",108+            deviceName = "Client",109+            deviceType = DeviceType.ANDROID,110+            longTermPublicKeyHex = "cd".repeat(32),111+            signingPublicKeyHex = "ef".repeat(32),112+        )113+        val serverId = localId.copy(deviceId = "server-1", deviceName = "Server")114+115+        var initiatorSas: String? = null116+        var responderSas: String? = null117+        var receivedByServer: PairIdentity? = null118+119+        val responderJob = launch(Dispatchers.IO) {120+            val session = noiseNKResponder(responderPriv, responderPub, responder::send, responder::receive)121+            receivedByServer = parsePairIdentityFrame(session.decrypt(responder.receive()))122+            responder.send(session.encrypt(encodePairIdentityFrame(serverId)))123+            responderSas = SASDerivation.derive(session.handshakeHash)124+        }125+126+        val initiatorJob = launch(Dispatchers.IO) {127+            val session = noiseNKInitiator(responderPub, initiator::send, initiator::receive)128+            initiator.send(session.encrypt(encodePairIdentityFrame(localId)))129+            session.decrypt(initiator.receive()) // server identity (discarded here)130+            initiatorSas = SASDerivation.derive(session.handshakeHash)131+        }132+133+        initiatorJob.join()134+        responderJob.join()135+136+        assertNotNull(initiatorSas)137+        assertEquals("both sides derive the same SAS", initiatorSas, responderSas)138+        assertEquals("client-1", receivedByServer?.deviceId)139+        assertEquals("cd".repeat(32), receivedByServer?.longTermPublicKeyHex)140+    }141+142+    /**143+     * Test 5: a wrong responder static key fails the initiator handshake — the144+     * NK auth tag rejects a MITM / mismatched key, which connectAndSync surfaces145+     * as PairingError.HANDSHAKE_FAILED.146+     */147+    @Test148+    fun `handshake fails when responder static key is wrong`() = runBlocking {149+        val (responderPriv, responderPub) = newKeyPair()150+        val (_, wrongPub) = newKeyPair()151+152+        val i2r = PipedInputStream(1 shl 18); val i2rOut = PipedOutputStream(i2r)153+        val r2i = PipedInputStream(1 shl 18); val r2iOut = PipedOutputStream(r2i)154+        val initiator = SocketFrameIO(input = r2i, output = i2rOut)155+        val responder = SocketFrameIO(input = i2r, output = r2iOut)156+157+        val responderJob = launch(Dispatchers.IO) {158+            runCatching { noiseNKResponder(responderPriv, responderPub, responder::send, responder::receive) }159+        }160+161+        var initiatorFailed = false162+        val initiatorJob = launch(Dispatchers.IO) {163+            try {164+                // Initiator pins the WRONG static key; NK msg2 auth must fail.165+                noiseNKInitiator(wrongPub, initiator::send, initiator::receive)166+            } catch (_: Throwable) {167+                initiatorFailed = true168+            }169+        }170+171+        withContext(Dispatchers.IO) {172+            initiatorJob.join()173+            responderJob.cancel()174+        }175+        assertTrue("initiator handshake must reject the wrong responder key", initiatorFailed)176+    }177+}

view file

app/drafts/C7/C7-INTEGRATION.md+329 −0
@@ -0,0 +1,329 @@1+# C7 — Chirp Sync Transport (TCP + mDNS + Noise NK): Integration Note2+3+Draft implementation of spec C7. Five Kotlin files plus this note, all under4+`app/drafts/C7/`. Package is already `com.peachpasswords.sync`, so the source5+files drop straight into the sync tree. **No existing file was edited** — every6+shared file (ChirpPairing.kt, NoiseNK.kt, VaultSyncAdapter.kt,7+ChirpSyncCoordinator.kt, ChirpPairViewModel.kt, SyncViewModel.kt,8+SettingsCardBodies.kt, VaultModule.kt, AndroidManifest.xml, build.gradle) was9+read only.10+11+> **Read this first.** The C7 brief substantially overstates what is missing and12+> invents the entire crypto surface. The transport primitives the brief assumes13+> are absent (Noise NK handshake, identity frames, per-entry sync, SAS,14+> PairedDevice) **all already exist** in `com.peachpasswords.sync`. The brief's15+> proposed `_peach._tcp` mDNS + `ServerSocket` design is also an **alternative16+> transport** to the one already shipped (audio-chirp ephemeral key exchange +17+> WebSocket/subnet-probe sync). These drafts add the TCP+mDNS transport on top of18+> the **real** crypto/sync APIs, and flag every divergence below.19+20+---21+22+## Files to MOVE into the source set23+24+| Draft file | Destination | Contents |25+|---|---|---|26+| `PairedDeviceStore.kt` | `sync/PairedDeviceStore.kt` | `@Singleton` EncryptedSharedPreferences registry of the REAL `PairedDevice`; `getAll/get/upsert/remove/clear/updateLastSeen/updateLastSync/observeAll` |27+| `PairingFrames.kt` | `sync/PairingFrames.kt` | `writeFrame/readFrame` (4-byte BE length prefix), `SocketFrameIO` (implements the real `PairingTransport` interface over a TCP socket), `sendEncrypted/receiveEncrypted` |28+| `PairingServer.kt` | `sync/PairingServer.kt` | TCP `ServerSocket` + `NsdManager` `_peach._tcp` advertisement; `noiseNKResponder` handshake; `runChirpSyncResponder` round; `PairingServerEvent`. **Name clash, see below.** |29+| `PairingTransport.kt` | `sync/PairingDiscoveryClient.kt` | `NsdManager` discovery (`callbackFlow`) + TCP `connectAndSync` initiator; `DiscoveredPeer`, `PairingResult`, `PairingError`. **Renamed, see below.** |30+| `C7-ChirpTransportTest.kt` | `app/src/test/java/com/peachpasswords/sync/C7ChirpTransportTest.kt` | 5 pure-JVM/Piped-stream tests |31+32+`C7-INTEGRATION.md` stays in drafts — it is not source.33+34+### Name collisions the orchestrator MUST resolve35+36+1. **`PairingServer`** — the brief wants a `@Singleton class PairingServer`. A37+   `data class PairingServer(val transport, val peerIp)` **already exists** in38+   `ChirpPairing.kt`. The draft's class would collide. Options:39+   - (preferred) rename the draft class to **`PairingListener`** /40+     **`MdnsPairingServer`** and keep the existing `data class PairingServer`; or41+   - rename the existing data class (it is only used inside `ChirpPairingDeps`).42+   The draft is written as `class PairingServer` per the brief; pick a rename43+   before merge or the module will not compile.44+2. **`PairingTransport`** — the brief wants a `@Singleton class PairingTransport`.45+   `PairingTransport` is **already an interface** in `ChirpPairing.kt`46+   (`send/receive/close`) consumed by the existing handshake. The draft file is47+   therefore authored as **`class PairingDiscoveryClient`** (destination filename48+   `PairingDiscoveryClient.kt`) to avoid shadowing the interface. `SocketFrameIO`49+   in `PairingFrames.kt` **implements that real interface**, so the existing50+   `runPairingInitiator`/`runPairingResponder` could drive a TCP socket unchanged51+   if those private functions are promoted (see item 4 below).52+53+---54+55+## TOP API DISCREPANCIES (brief vs reality)56+57+### 1. NoiseNK — the single most important reconciliation58+59+The brief assumes a stateful `NoiseNK` object:60+```kotlin61+val handshake = noiseNK.acceptHandshake(stream, out)      // server62+val handshake = noiseNK.initiateHandshake(stream, out, remotePub) // client63+handshake.sendCipher; handshake.recvCipher; handshake.handshakeHash64+```65+**None of this exists.** `NoiseNK.kt` exposes two **suspend free functions**:66+```kotlin67+suspend fun noiseNKInitiator(68+    responderStaticPublicKey: ByteArray,69+    send: suspend (ByteArray) -> Unit,70+    receive: suspend () -> ByteArray,71+): NoiseNKSession72+73+suspend fun noiseNKResponder(74+    ourStaticPrivateKey: ByteArray,75+    ourStaticPublicKey: ByteArray,76+    send: suspend (ByteArray) -> Unit,77+    receive: suspend () -> ByteArray,78+): NoiseNKSession79+```80+`NoiseNKSession` has **one bidirectional cipher** — `encrypt(plaintext)`,81+`decrypt(ciphertext)`, and `val handshakeHash` — **not** split82+`sendCipher`/`recvCipher`. Bound to:83+- The drafts pass `transport::send` / `transport::receive` (where `transport` is84+  a `SocketFrameIO`) as the handshake's `send`/`receive`. The handshake messages85+  are themselves length-prefixed frames.86+- All post-handshake encryption uses `session.encrypt` / `session.decrypt`.87+- Noise **NK** = responder has a static key, initiator does not; the initiator88+  must already KNOW the responder's static public key. The drafts use the89+  device's **long-term sync identity** (`deriveSyncIdentityKeypair(masterKey,90+  deviceId)`) as the responder static, and publish its public half in the mDNS91+  TXT `pk` record so the initiator can pin it. (The brief's `remotePublicKey`92+  "from TXT pk" maps onto this exactly — but it is the *responder's static*, not93+  an ephemeral.)94+- SAS: `SASDerivation.derive(session.handshakeHash)` (the existing helper; there95+  is also `derivePairingSAS(hash)`). The brief's `deriveSAS(...)` does not exist.96+97+### 2. VaultSyncAdapter — no buildRequest/applyRequest/buildResponse/applyResponse98+99+The brief calls `syncAdapter.buildResponse(req)` / `applyRequest(req)` /100+`buildRequest()` / `applyResponse(resp)`. **None exist.** `VaultSyncAdapter`101+implements `ChirpSyncVaultAdapter` (`computeVaultId`, `getOurDeviceId`,102+`getLocalVersion`, `buildEntryManifest`, `buildTombstoneManifest`,103+`getEncryptedEntries`, `applyEntries`, `applyTombstones`). The actual sync is a104+**full multi-message round** driven by the existing free functions:105+```kotlin106+suspend fun runChirpSyncInitiator(session: ChirpSyncSession, vault: ChirpSyncVaultAdapter): SyncOutcome107+suspend fun runChirpSyncResponder(session: ChirpSyncSession, vault: ChirpSyncVaultAdapter): SyncOutcome108+```109+over a `ChirpSyncSession(remoteStaticPublicKey, send, receive, close)`. Bound to:110+- `PairingServer` runs `runChirpSyncResponder`; `PairingDiscoveryClient` runs111+  `runChirpSyncInitiator`. Both build a `ChirpSyncSession` via112+  `chirpSessionOver(noiseSession, socketFrameIO)` — `send` = `encrypt → frame`,113+  `receive` = `frame → decrypt`. `ChirpSyncSession.send` is **non-suspending**114+  (matches `openChirpSyncSession`), so `SocketFrameIO.sendBlocking` is used115+  there, not the suspend `send`.116+- The adapter is built per round with `VaultSyncAdapter(repo, deviceId)`; pass a117+  `vaultFactory: () -> ChirpSyncVaultAdapter?` (null when the vault is locked).118+119+### 3. PairedDevice / TrustStatus — already exist, different shape120+121+The brief redefines `PairedDevice(id, name, publicKey: ByteArray, lastSeen,122+trustStatus, lastSyncAt)` and a `TrustStatus { TRUSTED, UNVERIFIED, REVOKED }`123+enum. **The real `PairedDevice` (PairedDevice.kt) is reused verbatim** and has a124+different shape:125+```kotlin126+@Serializable data class PairedDevice(127+    val deviceId: String, val deviceName: String?, val deviceType: String?,128+    val longTermPublicKeyHex: String?, val signingPublicKeyHex: String?,129+    val trustSource: String?, val wsPort: Int?, val pairedAt: Long,130+    val lastSyncedAt: Long?, val lastKnownIp: String?,131+)132+```133+Field mapping (brief → real):134+- `id` → `deviceId`; `name` → `deviceName`; `publicKey: ByteArray` →135+  `longTermPublicKeyHex: String?` (hex, not Base64/ByteArray); `lastSyncAt` →136+  `lastSyncedAt`.137+- `lastSeen` → **no equivalent**. The store's `updateLastSeen(id, ip)` refreshes138+  `lastKnownIp` instead (closest real analogue). If a real "last seen" timestamp139+  is wanted, **that is an integration delta**: add `val lastSeen: Long? = null`140+  to `PairedDevice` (defaulted so serialization stays backward-compatible).141+- `trustStatus: TrustStatus` → **no enum exists**; trust is `trustSource: String?`142+  ("direct" / "manifest"). **Integration delta if a tri-state TRUSTED/UNVERIFIED/143+  REVOKED model is required:** add an enum + field to `PairedDevice` (defaulted).144+  The drafts set `trustSource = "direct"` on pair, matching145+  `ChirpPairing.frameToPairedDevice`. The brief's `confirmSAS → TRUSTED` /146+  `rejectSAS → remove` flow maps onto: keep the device on confirm, `remove(id)`147+  on reject. If you add the enum, set it to TRUSTED on confirm.148+149+`TrustBadge`, `GhostButton`, `ChirpPairUiState`, `SyncStatus.Busy`, and150+`syncAdapter.applyResponse` referenced by the brief's UI/VM snippets **do not151+exist either** — see the wiring sections.152+153+### 4. (architectural) The mDNS+ServerSocket transport is NEW; the chirp transport already ships154+155+`ChirpPairing.runChirpPairing(...)` already implements an end-to-end pairing156+flow: ggwave **audio chirp** carries the peer's ephemeral X25519 key, then157+`noiseNKInitiator/Responder` runs over the `PairingTransport` interface, identity158+`PAIR_IDENTITY` frames are exchanged (`encodePairingFrame`/`decodePairingFrame`,159+both **file-private**), and `SASDerivation.derive` produces the SAS. Sync uses160+`openChirpSyncSession` (WebSocket) + subnet probe (`probeSubnetForPeer`). The C7161+brief's mDNS+`ServerSocket` path is a **second discovery/transport** that reuses162+the same Noise+sync primitives. The drafts re-implement the `PAIR_IDENTITY`163+encode/parse as `internal` shims (`encodePairIdentityFrame`/164+`parsePairIdentityFrame` in `PairingServer.kt`) **because the originals are165+private**. **Cleaner integration:** promote `ChirpPairing`'s166+`encodePairingFrame`/`decodePairingFrame`/`frameToPairedDevice` from `private` to167+`internal` and delete the draft shims, so there is exactly one identity-frame168+codec. Likewise consider promoting `runPairingInitiator`/`runPairingResponder` to169+`internal` so the TCP transport can reuse them via `SocketFrameIO` instead of170+re-deriving the handshake-then-identity sequence.171+172+---173+174+## Shared-file edits the orchestrator must make175+176+### ChirpPairViewModel (`ui/pairing/ChirpPairViewModel.kt`)177+178+The brief's rewrite (`ChirpPairUiState.Listening/Handshake/VerifySAS/Paired/...`,179+`uiState =`) does **not** match reality. The real VM exposes:180+- `val progress: StateFlow<PairingProgress>` where181+  `PairingProgress(phase: PairingPhase, peerDeviceName: String?, errorMessage:182+  String?)` and `PairingPhase` ∈ {IDLE, LISTENING, CHIRPING, HANDSHAKE, PAIRED,183+  TIMEOUT, MIC_DENIED, VERSION_MISMATCH, HANDSHAKE_FAILED} (PairingProgress.kt).184+- `val sasCode: StateFlow<String?>` and `fun confirmSas(accepted: Boolean)`185+  (a `CompletableDeferred<Boolean>` gate) — NOT separate `confirmSAS()/rejectSAS()`.186+- `fun startPairing()` already runs the real `runChirpPairing(deps(master),187+  role = INITIATOR)`.188+189+The brief's "`runChirpPairing()` throws UnsupportedOperationException" is **stale**190+— `runChirpPairing` is fully implemented. What is actually stubbed is two methods191+on the VM's `ChirpPairingDeps`:192+```kotlin193+override suspend fun completePairing(paired: PairedDevice) { /* TODO */ }194+override suspend fun openPairingTransport(endpoint): PairingTransport =195+    throw UnsupportedOperationException("...until sync persistence")196+override suspend fun openPairingServer(): PairingServer =197+    throw UnsupportedOperationException("...until sync persistence")198+```199+**Minimal real wiring (no UI-state rewrite needed):**200+1. Inject `PairedDeviceStore` (and `PairingDiscoveryClient` / the renamed201+   `PairingServer`) into `ChirpPairViewModel`.202+2. Implement `completePairing(paired)` → `deviceStore.upsert(paired)`.203+3. Implement `openPairingTransport(endpoint)` → return a `SocketFrameIO` over204+   `Socket(endpoint.ip, endpoint.port)` (this satisfies the existing205+   `PairingTransport` interface and unblocks `runResponderHandshake`).206+4. Implement `openPairingServer()` → bind a `ServerSocket`, `accept()` one207+   client, wrap it in `SocketFrameIO`, return `PairingServer(transport, peerIp)`208+   (the existing data class). (Or fold this into the new mDNS server.)209+5. SAS confirm already persists via `confirmSas(true)` → `completePairing`; on210+   `confirmSas(false)` the flow throws `sas_rejected` and nothing is stored211+   (matches the brief's `rejectSAS` intent).212+213+> If the product genuinely wants the brief's mDNS pairing instead of chirp, that214+> is a larger VM change: add a path that calls215+> `PairingDiscoveryClient.discoverPeers().first()` → `connectAndSync(...)` →216+> surface SAS through `sasCode`. That is **net-new UI behavior**, not a one-line217+> swap; flag for product before building.218+219+### SyncViewModel (`ui/sync/SyncViewModel.kt`)220+221+The brief's `SyncStatus.Busy`, `deviceStore.observeAll().stateIn(...)`,222+`transport.discoverPeers(5_000L)`, `connectAndSync(peer)` map onto reality as:223+- `SyncStatus` is `{ Idle, Syncing, LastSynced(ts), Error(msg), Offline }` — use224+  `Syncing` where the brief says `Busy`.225+- Add to the VM:226+  ```kotlin227+  // inject PairedDeviceStore + PairingDiscoveryClient228+  val pairedDevices: StateFlow<List<PairedDevice>> =229+      deviceStore.observeAll()230+          .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())231+232+  fun unpairDevice(id: String) = viewModelScope.launch { deviceStore.remove(id) }233+234+  fun syncNow() = viewModelScope.launch {235+      val master = vault.syncMasterKey() ?: return@launch236+      val identity = buildLocalIdentity(context, master)237+      _status.value = SyncStatus.Syncing238+      pairedDevices.value.forEach { dev ->239+          discoveryClient.syncWithKnownDevice(dev.deviceId, identity, ::buildAdapter)240+      }241+      VaultCrypto.zero(master)242+      _status.value = SyncStatus.Idle243+  }244+  ```245+  `observeAll()` is provided by `PairedDeviceStore`. `buildAdapter()` already246+  exists. `syncWithKnownDevice` is on `PairingDiscoveryClient`. (`triggerSync()`247+  already returns `Offline` when there is nothing to dial — keep it, or route it248+  through `syncNow`.)249+250+### SettingsCardBodies.SyncBody (`ui/settings/SettingsCardBodies.kt`)251+252+The brief's `GhostButton`, `TrustBadge`, `PeachType.bodyMono/labelMono/253+settingsLede`, `pairedDevices.forEach`, `vm.syncNow()` snippet does **not** match254+the file's vocabulary. Reality:255+- `SyncBody(fg: Color, onNavigate: (PeachNav) -> Unit)` is a **private256+  @Composable** with NO ViewModel and NO device list today — it shows static257+  PAIRING/DEVICE FLOW rows and navigates to `PeachNav.ChirpPair`.258+- The real helpers are `SubLabel`, `RowLine`, `RowScope.Name`, `ValueText`,259+  `SubtleButton`, `Hint`, `ProBadge` — **not** `GhostButton`/`TrustBadge`.260+- `PeachType.bodyMono`, `PeachType.labelMono`, `PeachType.settingsLede` **do261+  exist** (PeachType.kt) — those three names are correct.262+263+**To show real devices:** change `SyncBody`'s signature to take the VM (or a264+`pairedDevices: List<PairedDevice>` + callbacks) and render with the existing265+helpers, e.g.:266+```kotlin267+if (pairedDevices.isEmpty()) {268+    Text("No paired devices yet.", color = fg.copy(alpha = 0.7f),269+         fontFamily = PeachType.Body, fontSize = 12.sp)270+} else pairedDevices.forEach { d ->271+    RowLine(fg) {272+        Name(d.deviceName ?: d.deviceId, fg)273+        ValueText(d.lastSyncedAt?.let { "synced" } ?: "never", fg)274+    }275+}276+if (pairedDevices.isNotEmpty()) RowLine(fg) { Name("Sync", fg); SubtleButton("sync now", fg) { vm.syncNow() } }277+```278+Use a `SubtleButton` (real) rather than `GhostButton` (nonexistent). Trust state:279+render `d.trustSource` as text, or add a real `TrustBadge` composable if the enum280+delta (§3) is adopted. The caller of `SyncBody` lives in this same file's card281+dispatcher — pass the VM/state through.282+283+### Hilt (`di/VaultModule.kt` or a new module)284+285+`PairedDeviceStore`, `PairingServer`/`PairingListener`, and286+`PairingDiscoveryClient` are all `@Singleton class ... @Inject constructor(...)`287+with only `@ApplicationContext Context` + other `@Inject` singletons — so Hilt288+constructs them with **no `@Provides`/`@Binds` needed**. `VaultModule` is a289+`@Binds` module and needs no change. (Add providers only if you want to inject290+them behind an interface.)291+292+### AndroidManifest.xml293+294+`INTERNET` is **already present** (line 5). Add only:295+```xml296+<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />297+<uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />298+```299+`CHANGE_WIFI_MULTICAST_STATE` is required for mDNS/NSD multicast on Wi-Fi.300+(NsdManager on recent Android also benefits from acquiring a301+`WifiManager.MulticastLock` at runtime — consider adding one around discovery.)302+303+### build.gradle304+305+**No new dependencies.** `androidx.security:security-crypto:1.1.0-alpha06`306+(line 87) and `org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.1` (line 107)307+are present; `NsdManager`/`ServerSocket`/`Socket` are framework/JDK. The test308+file uses only JUnit + kotlinx-coroutines + BouncyCastle, all already on the test309+classpath (see `ChirpSyncTransportTest`).310+311+---312+313+## Tests (`C7-ChirpTransportTest.kt`)314+315+Pure-JVM, no Robolectric, matching `ChirpSyncTransportTest`'s idiom:316+1. `PairedDevice` list JSON round-trip (the store's serialization layer).317+2. `upsert`-by-`deviceId` replaces rather than duplicates (store list semantics).318+3. `writeFrame`/`readFrame` round-trip across sizes (0, 1, 31, 64, 1500, 65537).319+4. Full `noiseNKResponder`↔`noiseNKInitiator` handshake + encrypted320+   `PAIR_IDENTITY` exchange over cross-wired `PipedInputStream/PipedOutputStream`321+   via `SocketFrameIO`; asserts both sides derive the **same SAS** and the server322+   decodes the client identity.323+5. Wrong responder static key → initiator handshake rejects (NK auth tag) →324+   `PairingError.HANDSHAKE_FAILED` path.325+326+`PairedDeviceStore`'s on-disk persistence (EncryptedSharedPreferences) needs an327+Android `Context`; cover that in an instrumentation test (`androidTest`) — out of328+scope for the unit suite, consistent with how the project tests other329+EncryptedSharedPreferences stores.

view file

app/drafts/C7/PairedDeviceStore.kt+117 −0
@@ -0,0 +1,117 @@1+// Intended source path: app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt2+package com.peachpasswords.sync3+4+import android.content.Context5+import androidx.security.crypto.EncryptedSharedPreferences6+import androidx.security.crypto.MasterKey7+import dagger.hilt.android.qualifiers.ApplicationContext8+import kotlinx.coroutines.channels.awaitClose9+import kotlinx.coroutines.flow.Flow10+import kotlinx.coroutines.flow.callbackFlow11+import kotlinx.serialization.builtins.ListSerializer12+import kotlinx.serialization.json.Json13+import javax.inject.Inject14+import javax.inject.Singleton15+16+/**17+ * Persistent registry of paired devices, encrypted at rest with18+ * EncryptedSharedPreferences (same construction as DuressConfigStore /19+ * LicenseRepository, v2.1.36). The whole list lives under a single key as a20+ * kotlinx.serialization JSON array of the REAL [PairedDevice] (sync package).21+ *22+ * Reconciliation with the C7 brief:23+ *  - The brief invents a fresh `PairedDevice(id, name, publicKey: ByteArray,24+ *    lastSeen, trustStatus, lastSyncAt)`. That type does NOT exist in this25+ *    shape. The real [PairedDevice] (PairedDevice.kt) keys on `deviceId`, holds26+ *    the public key as `longTermPublicKeyHex` (hex, not ByteArray), and tracks27+ *    `pairedAt` / `lastSyncedAt` / `lastKnownIp`. This store reuses it verbatim;28+ *    Base64 publicKey storage is therefore unnecessary — the hex field is the29+ *    canonical wire form already produced by ChirpPairing.frameToPairedDevice.30+ *  - The brief's `TrustStatus` enum does not exist either. The real model uses a31+ *    nullable `trustSource: String?` (e.g. "direct", "manifest"). Trust state is32+ *    expressed there. See C7-INTEGRATION.md for the trust-status delta.33+ *  - `updateLastSync` here maps to the real `lastSyncedAt` field. There is no34+ *    `lastSeen` field on the real PairedDevice; [updateLastSeen] folds into35+ *    `lastKnownIp` refresh + `lastSyncedAt` is left untouched. It is kept as a36+ *    no-op-friendly hook so callers from the brief compile; see integration note.37+ */38+@Singleton39+class PairedDeviceStore @Inject constructor(40+    @ApplicationContext context: Context,41+) {42+    private val masterKey = MasterKey.Builder(context)43+        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)44+        .build()45+46+    private val prefs = EncryptedSharedPreferences.create(47+        context,48+        PREFS_FILE,49+        masterKey,50+        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,51+        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,52+    )53+54+    private val listSerializer = ListSerializer(PairedDevice.serializer())55+56+    fun getAll(): List<PairedDevice> {57+        val raw = prefs.getString(KEY_DEVICES, null) ?: return emptyList()58+        return runCatching { json.decodeFromString(listSerializer, raw) }.getOrDefault(emptyList())59+    }60+61+    fun get(id: String): PairedDevice? = getAll().firstOrNull { it.deviceId == id }62+63+    /** Insert or replace by [PairedDevice.deviceId]. */64+    fun upsert(device: PairedDevice) {65+        val next = getAll().filterNot { it.deviceId == device.deviceId } + device66+        persist(next)67+    }68+69+    fun remove(id: String) {70+        persist(getAll().filterNot { it.deviceId == id })71+    }72+73+    fun clear() {74+        prefs.edit().remove(KEY_DEVICES).apply()75+    }76+77+    /**78+     * Refresh the device's `lastKnownIp` (the closest real analogue to the79+     * brief's `lastSeen`). No-op when the id is unknown or [ip] is null.80+     */81+    fun updateLastSeen(id: String, ip: String? = null) {82+        val current = get(id) ?: return83+        if (ip == null) return84+        upsert(current.copy(lastKnownIp = ip))85+    }86+87+    fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {88+        val current = get(id) ?: return89+        upsert(current.copy(lastSyncedAt = at))90+    }91+92+    /**93+     * Observe the full list. EncryptedSharedPreferences supports94+     * OnSharedPreferenceChangeListener, so this emits on every persist —95+     * including writes from other components in-process.96+     */97+    fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {98+        trySend(getAll())99+        val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->100+            if (key == KEY_DEVICES || key == null) trySend(getAll())101+        }102+        prefs.registerOnSharedPreferenceChangeListener(listener)103+        awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }104+    }105+106+    private fun persist(devices: List<PairedDevice>) {107+        prefs.edit()108+            .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))109+            .apply()110+    }111+112+    private companion object {113+        const val PREFS_FILE = "peach_paired_devices"114+        const val KEY_DEVICES = "paired_devices"115+        val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }116+    }117+}

view file

app/drafts/C7/PairingFrames.kt+114 −0
@@ -0,0 +1,114 @@1+// Intended source path: app/src/main/java/com/peachpasswords/sync/PairingFrames.kt2+package com.peachpasswords.sync3+4+import kotlinx.coroutines.Dispatchers5+import kotlinx.coroutines.withContext6+import java.io.DataInputStream7+import java.io.EOFException8+import java.io.InputStream9+import java.io.OutputStream10+11+/**12+ * Length-prefixed framing for the C7 TCP transport, shared by [PairingServer]13+ * and [PairingTransport] so neither duplicates the wire format.14+ *15+ * Frame = [4-byte big-endian length][payload]. This is the framing the existing16+ * ChirpPairing.runPairingInitiator/Responder already assume implicitly when they17+ * call `transport.send(bytes)` / `transport.receive()` — the WebSocket transport18+ * gets framing for free from the protocol; a raw TCP socket does not, so we add19+ * it here.20+ *21+ * A frame length cap guards against a hostile/garbled peer asking us to allocate22+ * gigabytes before the Noise layer has authenticated anything.23+ */24+const val MAX_PAIRING_FRAME_BYTES: Int = 1 shl 20 // 1 MiB25+26+/** Blocking write of a single length-prefixed frame. */27+fun writeFrame(out: OutputStream, payload: ByteArray) {28+    require(payload.size <= MAX_PAIRING_FRAME_BYTES) { "frame too large: ${payload.size}" }29+    val header = ByteArray(4)30+    header[0] = (payload.size ushr 24).toByte()31+    header[1] = (payload.size ushr 16).toByte()32+    header[2] = (payload.size ushr 8).toByte()33+    header[3] = payload.size.toByte()34+    out.write(header)35+    out.write(payload)36+    out.flush()37+}38+39+/** Blocking read of a single length-prefixed frame. Throws on EOF / oversize. */40+fun readFrame(input: InputStream): ByteArray {41+    val data = if (input is DataInputStream) input else DataInputStream(input)42+    val length = try {43+        data.readInt()44+    } catch (e: EOFException) {45+        throw java.io.IOException("peer closed before frame header", e)46+    }47+    require(length in 0..MAX_PAIRING_FRAME_BYTES) { "invalid frame length: $length" }48+    val buf = ByteArray(length)49+    data.readFully(buf)50+    return buf51+}52+53+/**54+ * Adapts a blocking TCP socket pair to the suspend send/receive shape the REAL55+ * crypto stack expects:56+ *   - noiseNKInitiator / noiseNKResponder take `send: suspend (ByteArray)->Unit`57+ *     and `receive: suspend ()->ByteArray` (see NoiseNK.kt).58+ *   - ChirpPairing's [PairingTransport] interface is `send/receive/close`.59+ *60+ * Both the Noise handshake messages and the post-handshake encrypted payloads61+ * travel as length-prefixed frames over the same socket, so one [SocketFrameIO]62+ * serves the whole session. All IO hops to Dispatchers.IO.63+ *64+ * This implements the EXISTING [PairingTransport] interface (ChirpPairing.kt),65+ * which is the contract `runPairingInitiator` / `runPairingResponder` consume —66+ * so a TCP socket can drive the already-written handshake unchanged.67+ */68+class SocketFrameIO(69+    private val input: InputStream,70+    private val output: OutputStream,71+    private val onClose: suspend () -> Unit = {},72+) : PairingTransport {73+    private val buffered = DataInputStream(input)74+75+    /**76+     * Synchronous frame write. [ChirpSyncSession.send] is non-suspending (see77+     * ChirpSyncTransport.kt), so the sync-exchange bridge needs a blocking send78+     * that does NOT wrap a coroutine. Socket writes are bounded by soTimeout.79+     */80+    fun sendBlocking(msg: ByteArray) {81+        writeFrame(output, msg)82+    }83+84+    override suspend fun send(msg: ByteArray) = withContext(Dispatchers.IO) {85+        writeFrame(output, msg)86+    }87+88+    override suspend fun receive(): ByteArray = withContext(Dispatchers.IO) {89+        readFrame(buffered)90+    }91+92+    override suspend fun close() {93+        onClose()94+    }95+}96+97+/**98+ * Convenience wrappers for the post-handshake encrypted exchange. The Noise99+ * [NoiseNKSession] already owns the cipher (encrypt/decrypt); these just splice100+ * it onto the frame layer so call sites read clearly.101+ *102+ * NOTE: the existing ChirpPairing handshake calls `session.encrypt` /103+ * `session.decrypt` directly around `transport.send` / `transport.receive`; the104+ * post-pairing SYNC exchange (runChirpSyncInitiator/Responder) does the same via105+ * a [ChirpSyncSession]. These helpers exist for the raw-frame paths in106+ * PairingServer/PairingTransport that don't go through a ChirpSyncSession.107+ */108+suspend fun PairingTransport.sendEncrypted(session: NoiseNKSession, plaintext: ByteArray) {109+    send(session.encrypt(plaintext))110+}111+112+suspend fun PairingTransport.receiveEncrypted(session: NoiseNKSession): ByteArray {113+    return session.decrypt(receive())114+}

view file

app/drafts/C7/PairingServer.kt+321 −0
@@ -0,0 +1,321 @@1+// Intended source path: app/src/main/java/com/peachpasswords/sync/PairingServer.kt2+package com.peachpasswords.sync3+4+import android.content.Context5+import android.net.nsd.NsdManager6+import android.net.nsd.NsdServiceInfo7+import android.os.Build8+import dagger.hilt.android.qualifiers.ApplicationContext9+import kotlinx.coroutines.CoroutineScope10+import kotlinx.coroutines.Dispatchers11+import kotlinx.coroutines.channels.awaitClose12+import kotlinx.coroutines.flow.Flow13+import kotlinx.coroutines.flow.callbackFlow14+import kotlinx.coroutines.isActive15+import kotlinx.coroutines.launch16+import kotlinx.coroutines.withContext17+import java.net.ServerSocket18+import java.net.Socket19+import java.nio.charset.StandardCharsets20+import javax.inject.Inject21+import javax.inject.Singleton22+23+/**24+ * C7 TCP + mDNS pairing/sync SERVER (responder side).25+ *26+ * Listens on an OS-assigned TCP port, advertises itself over mDNS as27+ * `_peach._tcp`, and for each inbound connection runs the REAL responder28+ * pipeline:29+ *   1. Noise NK responder handshake ([noiseNKResponder]) over length-prefixed30+ *      frames ([SocketFrameIO]).31+ *   2. PAIR_IDENTITY frame exchange — encoded/decoded with the SAME private32+ *      helpers ChirpPairing uses; since those are file-private there, this draft33+ *      re-derives the identity frame via [LocalChirpIdentity] and a minimal34+ *      JSON, and parses the peer's via [parsePairIdentityFrame]. See35+ *      C7-INTEGRATION.md: the cleanest integration promotes ChirpPairing's36+ *      encode/decodePairingFrame to internal and deletes these shims.37+ *   3. Encrypted vault sync via the REAL [runChirpSyncResponder] over a38+ *      [ChirpSyncSession] backed by the Noise session.39+ *40+ * ── Reconciliation with the brief ──────────────────────────────────────────41+ *  - The brief calls `noiseNK.acceptHandshake(stream, out)` returning an object42+ *    with `.sendCipher/.recvCipher/.handshakeHash`. NO SUCH API EXISTS. The real43+ *    handshake is the suspend free function `noiseNKResponder(ourPriv, ourPub,44+ *    send, receive)` returning a single [NoiseNKSession] (encrypt/decrypt/45+ *    handshakeHash) — one bidirectional cipher, not split send/recv ciphers.46+ *  - NK is a responder-static / no-initiator-static pattern: the responder needs47+ *    its OWN static keypair, and the initiator must already know the responder's48+ *    static public key. We use the device's long-term sync identity49+ *    ([deriveSyncIdentityKeypair]) as that static key and publish its public half50+ *    in the mDNS TXT "pk" record so initiators can pin it.51+ *  - The brief calls `syncAdapter.buildResponse/applyRequest`. NO SUCH METHODS.52+ *    The real per-round protocol is [runChirpSyncResponder]; the adapter is a53+ *    [ChirpSyncVaultAdapter] ([VaultSyncAdapter]) with getEncryptedEntries/54+ *    applyEntries/etc. We drive the whole round, not single request/response.55+ */56+@Singleton57+class PairingServer @Inject constructor(58+    private val deviceStore: PairedDeviceStore,59+    @ApplicationContext private val ctx: Context,60+) {61+    private var serverSocket: ServerSocket? = null62+    private var nsdManager: NsdManager? = null63+    private var registrationListener: NsdManager.RegistrationListener? = null64+65+    /**66+     * Start listening + advertise + accept. Caller supplies:67+     *  - [ourStaticPrivateKey]/[ourStaticPublicKey]: the device's long-term sync68+     *    identity (from [deriveSyncIdentityKeypair]) — the Noise NK responder69+     *    static key, also published in mDNS TXT "pk".70+     *  - [vaultFactory]: builds a fresh [ChirpSyncVaultAdapter] per connection71+     *    (the vault may lock/unlock between connections).72+     *  - [localIdentity]: our PAIR_IDENTITY payload.73+     */74+    fun start(75+        scope: CoroutineScope,76+        ourStaticPrivateKey: ByteArray,77+        ourStaticPublicKey: ByteArray,78+        localIdentity: LocalChirpIdentity,79+        vaultFactory: () -> ChirpSyncVaultAdapter?,80+    ): Flow<PairingServerEvent> = callbackFlow {81+        val socket = withContext(Dispatchers.IO) { ServerSocket(0) }82+        serverSocket = socket83+        val port = socket.localPort84+85+        registerMdns(port, ourStaticPublicKey, localIdentity.deviceId)86+        trySend(PairingServerEvent.Started(port))87+88+        val acceptJob = scope.launch(Dispatchers.IO) {89+            while (isActive && !socket.isClosed) {90+                val client = try {91+                    socket.accept()92+                } catch (_: Throwable) {93+                    break94+                }95+                launch {96+                    val event = handleClient(client, ourStaticPrivateKey, ourStaticPublicKey, localIdentity, vaultFactory)97+                    trySend(event)98+                }99+            }100+        }101+102+        awaitClose {103+            acceptJob.cancel()104+            stop()105+        }106+    }107+108+    fun stop() {109+        registrationListener?.let { l -> runCatching { nsdManager?.unregisterService(l) } }110+        registrationListener = null111+        runCatching { serverSocket?.close() }112+        serverSocket = null113+    }114+115+    private suspend fun handleClient(116+        socket: Socket,117+        ourStaticPrivateKey: ByteArray,118+        ourStaticPublicKey: ByteArray,119+        localIdentity: LocalChirpIdentity,120+        vaultFactory: () -> ChirpSyncVaultAdapter?,121+    ): PairingServerEvent {122+        val transport = SocketFrameIO(123+            input = socket.getInputStream(),124+            output = socket.getOutputStream(),125+            onClose = { withContext(Dispatchers.IO) { runCatching { socket.close() } } },126+        )127+        return try {128+            // 1. Noise NK responder handshake — real free function, single session.129+            val session = noiseNKResponder(130+                ourStaticPrivateKey,131+                ourStaticPublicKey,132+                transport::send,133+                transport::receive,134+            )135+136+            // 2. PAIR_IDENTITY exchange (responder reads first, then answers) —137+            //    mirrors ChirpPairing.runPairingResponder ordering.138+            val theirIdentity = parsePairIdentityFrame(session.decrypt(transport.receive()))139+            transport.send(session.encrypt(encodePairIdentityFrame(localIdentity)))140+141+            val sas = SASDerivation.derive(session.handshakeHash)142+            val device = pairIdentityToPairedDevice(theirIdentity)143+            deviceStore.upsert(device)144+145+            // 3. Encrypted vault sync — real responder round over a ChirpSyncSession.146+            val vault = vaultFactory()147+            if (vault != null) {148+                val syncSession = chirpSessionOver(session, transport)149+                val outcome = runChirpSyncResponder(syncSession, vault)150+                if (outcome.status == SyncOutcomeStatus.COMPLETED) {151+                    deviceStore.updateLastSync(device.deviceId)152+                }153+            }154+            transport.close()155+            PairingServerEvent.SyncComplete(device.deviceId, sas)156+        } catch (e: Throwable) {157+            transport.close()158+            PairingServerEvent.Error(e.message ?: "pairing_server_error")159+        }160+    }161+162+    private fun registerMdns(port: Int, staticPub: ByteArray, deviceId: String) {163+        val manager = ctx.getSystemService(NsdManager::class.java) ?: return164+        nsdManager = manager165+        val info = NsdServiceInfo().apply {166+            serviceName = buildServiceName(deviceId)167+            serviceType = PEACH_SERVICE_TYPE168+            this.port = port169+            // NsdServiceInfo.setAttribute is API 21+; minSdk is 26.170+            setAttribute("v", PROTOCOL_VERSION)171+            setAttribute("pk", pubkeyToHex(staticPub))172+            setAttribute("id", deviceId)173+        }174+        val listener = object : NsdManager.RegistrationListener {175+            override fun onServiceRegistered(info: NsdServiceInfo) {}176+            override fun onRegistrationFailed(info: NsdServiceInfo, errorCode: Int) {}177+            override fun onServiceUnregistered(info: NsdServiceInfo) {}178+            override fun onUnregistrationFailed(info: NsdServiceInfo, errorCode: Int) {}179+        }180+        registrationListener = listener181+        manager.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)182+    }183+184+    private fun buildServiceName(deviceId: String): String {185+        val shortId = deviceId.take(8)186+        val model = Build.MODEL.replace(Regex("[^A-Za-z0-9-]"), "")187+        // mDNS service-instance names are capped at 63 bytes; reserve room for188+        // the "Peach-" prefix and the "-${shortId}" suffix.189+        val maxModel = 63 - "Peach-".length - 1 - shortId.length190+        val trimmedModel = if (model.length > maxModel && maxModel > 0) model.take(maxModel) else model191+        return "Peach-$trimmedModel-$shortId".take(63)192+    }193+194+    private companion object {195+        const val PEACH_SERVICE_TYPE = "_peach._tcp"196+        const val PROTOCOL_VERSION = "1"197+    }198+}199+200+sealed class PairingServerEvent {201+    data class Started(val port: Int) : PairingServerEvent()202+    data class SyncComplete(val deviceId: String, val sas: String) : PairingServerEvent()203+    data class Error(val message: String) : PairingServerEvent()204+    data object Stopped : PairingServerEvent()205+}206+207+/* ── PAIR_IDENTITY shims (see C7-INTEGRATION.md item: promote ChirpPairing's208+   private encode/decodePairingFrame to internal and drop these) ───────────── */209+210+internal data class PairIdentity(211+    val deviceId: String,212+    val deviceName: String,213+    val deviceType: DeviceType,214+    val longTermPublicKeyHex: String,215+    val signingPublicKeyHex: String?,216+    val wsPort: Int?,217+)218+219+internal fun encodePairIdentityFrame(id: LocalChirpIdentity): ByteArray {220+    val sb = StringBuilder()221+    sb.append('{')222+    sb.append("\"type\":\"PAIR_IDENTITY\"")223+    sb.append(",\"device_id\":\"").append(jsonEscape(id.deviceId)).append('"')224+    sb.append(",\"device_name\":\"").append(jsonEscape(id.deviceName)).append('"')225+    sb.append(",\"device_type\":\"").append(id.deviceType.wireValue).append('"')226+    sb.append(",\"long_term_public_key_hex\":\"").append(id.longTermPublicKeyHex).append('"')227+    sb.append(",\"signing_public_key_hex\":\"").append(id.signingPublicKeyHex).append('"')228+    id.wsPort?.let { sb.append(",\"ws_port\":").append(it) }229+    sb.append('}')230+    return sb.toString().toByteArray(StandardCharsets.UTF_8)231+}232+233+internal fun parsePairIdentityFrame(bytes: ByteArray): PairIdentity {234+    val map = miniJsonObject(String(bytes, StandardCharsets.UTF_8))235+    require(map["type"] == "PAIR_IDENTITY") { "expected PAIR_IDENTITY frame" }236+    val deviceType = when (map["device_type"]) {237+        "extension" -> DeviceType.EXTENSION238+        "android" -> DeviceType.ANDROID239+        "ios" -> DeviceType.IOS240+        "desktop" -> DeviceType.DESKTOP241+        else -> error("device_type missing")242+    }243+    val ltpk = map["long_term_public_key_hex"] ?: error("long_term_public_key_hex missing")244+    require(ltpk.matches(Regex("^[0-9a-f]{64}$"))) { "long_term_public_key_hex not 32-byte hex" }245+    return PairIdentity(246+        deviceId = map["device_id"] ?: error("device_id missing"),247+        deviceName = map["device_name"] ?: error("device_name missing"),248+        deviceType = deviceType,249+        longTermPublicKeyHex = ltpk,250+        signingPublicKeyHex = map["signing_public_key_hex"]?.takeIf { it.isNotBlank() },251+        wsPort = map["ws_port"]?.toIntOrNull(),252+    )253+}254+255+internal fun pairIdentityToPairedDevice(id: PairIdentity): PairedDevice = PairedDevice(256+    deviceId = id.deviceId,257+    deviceName = id.deviceName,258+    deviceType = id.deviceType.wireValue,259+    longTermPublicKeyHex = id.longTermPublicKeyHex,260+    signingPublicKeyHex = id.signingPublicKeyHex,261+    trustSource = "direct",262+    wsPort = id.wsPort,263+    pairedAt = System.currentTimeMillis(),264+    lastSyncedAt = System.currentTimeMillis(),265+)266+267+/**268+ * Build a [ChirpSyncSession] over an established Noise session + frame269+ * transport, so the REAL [runChirpSyncInitiator]/[runChirpSyncResponder] can run270+ * the encrypted vault exchange. Send/receive splice the Noise cipher onto the271+ * length-prefixed frame layer; `remoteStaticPublicKey` is informational here.272+ */273+internal fun chirpSessionOver(session: NoiseNKSession, transport: SocketFrameIO): ChirpSyncSession =274+    ChirpSyncSession(275+        remoteStaticPublicKey = ByteArray(0),276+        // ChirpSyncSession.send is non-suspending (matches openChirpSyncSession);277+        // SocketFrameIO.sendBlocking writes a frame synchronously.278+        send = { plaintext -> transport.sendBlocking(session.encrypt(plaintext)) },279+        receive = { session.decrypt(transport.receive()) },280+        close = { transport.close() },281+    )282+283+private fun jsonEscape(value: String): String = buildString(value.length) {284+    for (ch in value) when (ch) {285+        '\\' -> append("\\\\"); '"' -> append("\\\"")286+        '\n' -> append("\\n"); '\r' -> append("\\r"); '\t' -> append("\\t")287+        else -> append(ch)288+    }289+}290+291+private fun miniJsonObject(text: String): Map<String, String> {292+    val trimmed = text.trim()293+    require(trimmed.startsWith("{") && trimmed.endsWith("}")) { "expected JSON object" }294+    val body = trimmed.substring(1, trimmed.length - 1)295+    val out = linkedMapOf<String, String>()296+    var i = 0297+    while (i < body.length) {298+        while (i < body.length && body[i].isWhitespace()) i++299+        if (i >= body.length || body[i] != '"') break300+        i++301+        val keyStart = i302+        while (i < body.length && body[i] != '"') i++303+        val key = body.substring(keyStart, i); i++304+        while (i < body.length && (body[i].isWhitespace() || body[i] == ':')) i++305+        val value: String306+        if (i < body.length && body[i] == '"') {307+            i++308+            val vStart = i309+            while (i < body.length && body[i] != '"') i++310+            value = body.substring(vStart, i); i++311+        } else {312+            val vStart = i313+            while (i < body.length && body[i] != ',') i++314+            value = body.substring(vStart, i).trim()315+        }316+        out[key] = value317+        while (i < body.length && body[i].isWhitespace()) i++318+        if (i < body.length && body[i] == ',') i++319+    }320+    return out321+}

view file

app/drafts/C7/PairingTransport.kt+203 −0
@@ -0,0 +1,203 @@1+// Intended source path: app/src/main/java/com/peachpasswords/sync/PairingDiscoveryClient.kt2+//3+// NAME NOTE: the brief calls this class `PairingTransport`, but that symbol is4+// ALREADY TAKEN — `PairingTransport` is an interface in ChirpPairing.kt5+// (send/receive/close) that the existing handshake consumes. Reusing the name6+// would shadow it. This C7 client is therefore named [PairingDiscoveryClient].7+// See C7-INTEGRATION.md.8+package com.peachpasswords.sync9+10+import android.content.Context11+import android.net.nsd.NsdManager12+import android.net.nsd.NsdServiceInfo13+import dagger.hilt.android.qualifiers.ApplicationContext14+import kotlinx.coroutines.Dispatchers15+import kotlinx.coroutines.channels.awaitClose16+import kotlinx.coroutines.flow.Flow17+import kotlinx.coroutines.flow.callbackFlow18+import kotlinx.coroutines.flow.first19+import kotlinx.coroutines.withContext20+import kotlinx.coroutines.withTimeoutOrNull21+import java.net.InetSocketAddress22+import java.net.Socket23+import java.net.SocketTimeoutException24+import javax.inject.Inject25+import javax.inject.Singleton26+27+/**28+ * C7 TCP + mDNS pairing/sync CLIENT (initiator side). Discovers `_peach._tcp`29+ * peers, dials one, and runs the REAL initiator pipeline:30+ *   1. Noise NK initiator handshake ([noiseNKInitiator]) — pins the responder's31+ *      static public key from the mDNS TXT "pk" record.32+ *   2. PAIR_IDENTITY exchange (initiator writes first, then reads), matching33+ *      ChirpPairing.runPairingInitiator ordering.34+ *   3. SAS via the REAL [SASDerivation.derive] over the Noise handshake hash.35+ *   4. Encrypted vault sync via the REAL [runChirpSyncInitiator] over a36+ *      [ChirpSyncSession].37+ *38+ * ── Reconciliation with the brief ──────────────────────────────────────────39+ *  - `noiseNK.initiateHandshake(stream, out, remotePublicKey)` does NOT exist.40+ *    Real: `noiseNKInitiator(responderStaticPublicKey, send, receive)` →41+ *    [NoiseNKSession]. One bidirectional cipher; no `.sendCipher/.recvCipher`.42+ *  - `syncAdapter.buildRequest/applyResponse` do NOT exist. Real round driver is43+ *    [runChirpSyncInitiator] against a [ChirpSyncVaultAdapter].44+ *  - `peer.serviceInfo.host/.port`: on API < 34, [NsdServiceInfo.getHost] is45+ *    deprecated; on the supported floor it still returns the resolved46+ *    InetAddress, which we use for the dial. The resolved port is authoritative.47+ */48+@Singleton49+class PairingDiscoveryClient @Inject constructor(50+    @ApplicationContext private val ctx: Context,51+    private val deviceStore: PairedDeviceStore,52+) {53+    /**54+     * Discover nearby Peach instances via mDNS. Each found service is resolved,55+     * its TXT records parsed into a [DiscoveredPeer], and emitted. The flow runs56+     * until the collector cancels (e.g. via kotlinx `.timeout(...)` or `first`).57+     */58+    fun discoverPeers(): Flow<DiscoveredPeer> = callbackFlow {59+        val manager = ctx.getSystemService(NsdManager::class.java)60+            ?: run { close(); return@callbackFlow }61+62+        val resolveListener = object : NsdManager.ResolveListener {63+            override fun onServiceResolved(resolved: NsdServiceInfo) {64+                parsePeer(resolved)?.let { trySend(it) }65+            }66+            override fun onResolveFailed(info: NsdServiceInfo, errorCode: Int) {}67+        }68+69+        val discoveryListener = object : NsdManager.DiscoveryListener {70+            override fun onServiceFound(info: NsdServiceInfo) {71+                if (info.serviceType.trimEnd('.') == PEACH_SERVICE_TYPE) {72+                    runCatching { manager.resolveService(info, resolveListener) }73+                }74+            }75+            override fun onServiceLost(info: NsdServiceInfo) {}76+            override fun onDiscoveryStarted(serviceType: String) {}77+            override fun onDiscoveryStopped(serviceType: String) {}78+            override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { close() }79+            override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) {}80+        }81+82+        manager.discoverServices(PEACH_SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, discoveryListener)83+        awaitClose { runCatching { manager.stopServiceDiscovery(discoveryListener) } }84+    }85+86+    /**87+     * Dial [peer], run the Noise NK initiator handshake, exchange identities and88+     * derive the SAS, then run one initiator sync round.89+     *90+     * Caller supplies the local static identity (Noise initiator does not have a91+     * static key in NK, but our PAIR_IDENTITY + the sync layer still carry our92+     * long-term identity) and a vault adapter factory.93+     */94+    suspend fun connectAndSync(95+        peer: DiscoveredPeer,96+        localIdentity: LocalChirpIdentity,97+        vaultFactory: () -> ChirpSyncVaultAdapter?,98+        connectTimeoutMs: Int = 15_000,99+    ): PairingResult = withContext(Dispatchers.IO) {100+        val socket = Socket()101+        try {102+            socket.connect(InetSocketAddress(peer.host, peer.port), connectTimeoutMs)103+            socket.soTimeout = connectTimeoutMs104+105+            val transport = SocketFrameIO(106+                input = socket.getInputStream(),107+                output = socket.getOutputStream(),108+                onClose = { withContext(Dispatchers.IO) { runCatching { socket.close() } } },109+            )110+111+            val session = try {112+                noiseNKInitiator(peer.remoteStaticPublicKey, transport::send, transport::receive)113+            } catch (e: Throwable) {114+                transport.close()115+                return@withContext PairingResult.Error(PairingError.HANDSHAKE_FAILED)116+            }117+118+            // PAIR_IDENTITY: initiator writes first, then reads (mirrors119+            // ChirpPairing.runPairingInitiator).120+            transport.send(session.encrypt(encodePairIdentityFrame(localIdentity)))121+            val theirIdentity = parsePairIdentityFrame(session.decrypt(transport.receive()))122+123+            val sas = SASDerivation.derive(session.handshakeHash)124+            val device = pairIdentityToPairedDevice(theirIdentity)125+            deviceStore.upsert(device)126+127+            // Encrypted vault sync — real initiator round.128+            val vault = vaultFactory()129+            if (vault != null) {130+                val syncSession = chirpSessionOver(session, transport)131+                val outcome = runChirpSyncInitiator(syncSession, vault)132+                if (outcome.status == SyncOutcomeStatus.COMPLETED) {133+                    deviceStore.updateLastSync(device.deviceId)134+                }135+            }136+137+            transport.close()138+            PairingResult.Success(device, sas)139+        } catch (e: SocketTimeoutException) {140+            runCatching { socket.close() }141+            PairingResult.Error(PairingError.TIMEOUT)142+        } catch (e: Throwable) {143+            runCatching { socket.close() }144+            PairingResult.Error(PairingError.IO_ERROR)145+        }146+    }147+148+    /** Discover then dial the first peer whose deviceId matches [deviceId]. */149+    suspend fun syncWithKnownDevice(150+        deviceId: String,151+        localIdentity: LocalChirpIdentity,152+        vaultFactory: () -> ChirpSyncVaultAdapter?,153+        discoveryTimeoutMs: Long = 5_000L,154+    ): PairingResult {155+        val peer = withTimeoutOrNull(discoveryTimeoutMs) {156+            discoverPeers().first { it.deviceId == deviceId }157+        } ?: return PairingResult.Error(PairingError.NOT_FOUND)158+        return connectAndSync(peer, localIdentity, vaultFactory)159+    }160+161+    private fun parsePeer(info: NsdServiceInfo): DiscoveredPeer? {162+        val attrs = info.attributes ?: return null163+        val pkHex = attrs["pk"]?.let { String(it, Charsets.UTF_8) } ?: return null164+        if (!pkHex.matches(Regex("^[0-9a-f]{64}$"))) return null165+        val deviceId = attrs["id"]?.let { String(it, Charsets.UTF_8) } ?: return null166+        @Suppress("DEPRECATION")167+        val host = info.host?.hostAddress ?: return null168+        return DiscoveredPeer(169+            deviceId = deviceId,170+            deviceName = info.serviceName,171+            host = host,172+            port = info.port,173+            remoteStaticPublicKey = hexToPubkey(pkHex),174+        )175+    }176+177+    private companion object {178+        const val PEACH_SERVICE_TYPE = "_peach._tcp"179+    }180+}181+182+data class DiscoveredPeer(183+    val deviceId: String,184+    val deviceName: String,185+    val host: String,186+    val port: Int,187+    /** Noise NK responder static public key, parsed from TXT "pk". */188+    val remoteStaticPublicKey: ByteArray,189+)190+191+sealed class PairingResult {192+    data class Success(val device: PairedDevice, val sasCode: String) : PairingResult()193+    data class Error(val reason: PairingError) : PairingResult()194+}195+196+enum class PairingError {197+    NOT_FOUND,198+    HANDSHAKE_FAILED,199+    VERSION_MISMATCH,200+    ALREADY_PAIRED,201+    TIMEOUT,202+    IO_ERROR,203+}

view file

app/src/main/java/com/peachpasswords/ui/PeachAppNavHost.kt+12 −0
@@ -17,6 +17,7 @@1717 import com.peachpasswords.ui.lock.LockScreen1818 import com.peachpasswords.ui.onboarding.OnboardingScreen1919 import com.peachpasswords.ui.pairing.ChirpPairScreen20+import com.peachpasswords.ui.recovery.RecoveryWordEntryScreen2021 import com.peachpasswords.ui.screens.SimpleStub2122 import com.peachpasswords.ui.settings.PanicScreen2223 import com.peachpasswords.ui.settings.SettingsScreen@@ -147,6 +148,17 @@147148         }148149         composable(PeachNav.RecoveryView.route) {149150             RecoveryWordsScreen(requireConfirm = false, onDone = back)151+        }152+        composable(PeachNav.RecoveryEntry.route) {153+            RecoveryWordEntryScreen(154+                onSuccess = {155+                    navController.navigate(PeachNav.VaultList.route) {156+                        popUpTo(PeachNav.Lock.route) { inclusive = true }157+                    }158+                },159+                onBack = back,160+                onRestore = { nav(PeachNav.Import) },161+            )150162         }151163     }152164 }

view file

app/src/main/java/com/peachpasswords/ui/PeachNav.kt+1 −0
@@ -47,4 +47,5 @@4747     data object Panic : PeachNav("panic")4848     data object RecoverySetup : PeachNav("recovery/setup")4949     data object RecoveryView : PeachNav("recovery/view")50+    data object RecoveryEntry : PeachNav("recovery/entry")5051 }

view file

app/src/main/java/com/peachpasswords/ui/lock/LockScreen.kt+14 −0
@@ -214,6 +214,20 @@214214                             .padding(vertical = 8.dp),215215                     )216216                 }217+218+                if (state.hasVault) {219+                    Spacer(Modifier.height(8.dp))220+                    Text(221+                        text = "Forgot your password?",222+                        color = PeachColors.T2,223+                        style = PeachType.labelMono.copy(fontSize = 11.sp),224+                        textAlign = TextAlign.Center,225+                        modifier = Modifier.fillMaxWidth()226+                            .clip(RoundedCornerShape(8.dp))227+                            .clickable { onNavigate(PeachNav.RecoveryEntry) }228+                            .padding(vertical = 8.dp),229+                    )230+                }217231             }218232 219233             if (!state.hasVault) {

view file

app/src/main/java/com/peachpasswords/ui/recovery/RecoveryWordEntryScreen.kt+522 −0
@@ -0,0 +1,522 @@1+package com.peachpasswords.ui.recovery2+3+import androidx.compose.foundation.background4+import androidx.compose.foundation.border5+import androidx.compose.foundation.clickable6+import androidx.compose.foundation.interaction.MutableInteractionSource7+import androidx.compose.foundation.interaction.collectIsFocusedAsState8+import androidx.compose.foundation.layout.Arrangement9+import androidx.compose.foundation.layout.Box10+import androidx.compose.foundation.layout.Column11+import androidx.compose.foundation.layout.Row12+import androidx.compose.foundation.layout.Spacer13+import androidx.compose.foundation.layout.fillMaxSize14+import androidx.compose.foundation.layout.fillMaxWidth15+import androidx.compose.foundation.layout.height16+import androidx.compose.foundation.layout.padding17+import androidx.compose.foundation.layout.size18+import androidx.compose.foundation.layout.systemBarsPadding19+import androidx.compose.foundation.layout.width20+import androidx.compose.foundation.rememberScrollState21+import androidx.compose.foundation.shape.RoundedCornerShape22+import androidx.compose.foundation.text.BasicTextField23+import androidx.compose.foundation.text.KeyboardActions24+import androidx.compose.foundation.text.KeyboardOptions25+import androidx.compose.foundation.verticalScroll26+import androidx.compose.material3.Text27+import androidx.compose.runtime.Composable28+import androidx.compose.runtime.collectAsState29+import androidx.compose.runtime.getValue30+import androidx.compose.runtime.mutableStateListOf31+import androidx.compose.runtime.mutableStateOf32+import androidx.compose.runtime.remember33+import androidx.compose.runtime.setValue34+import androidx.compose.ui.Alignment35+import androidx.compose.ui.Modifier36+import androidx.compose.ui.draw.clip37+import androidx.compose.ui.draw.drawBehind38+import androidx.compose.ui.focus.FocusRequester39+import androidx.compose.ui.focus.focusRequester40+import androidx.compose.ui.geometry.Offset41+import androidx.compose.ui.geometry.Size42+import androidx.compose.ui.graphics.Color43+import androidx.compose.ui.graphics.SolidColor44+import androidx.compose.ui.text.TextStyle45+import androidx.compose.ui.text.font.FontStyle46+import androidx.compose.ui.text.input.ImeAction47+import androidx.compose.ui.text.input.KeyboardType48+import androidx.compose.ui.text.input.PasswordVisualTransformation49+import androidx.compose.ui.text.input.VisualTransformation50+import androidx.compose.ui.text.style.TextAlign51+import androidx.compose.ui.unit.dp52+import androidx.compose.ui.unit.em53+import androidx.compose.ui.unit.sp54+import androidx.hilt.navigation.compose.hiltViewModel55+import androidx.lifecycle.ViewModel56+import androidx.lifecycle.viewModelScope57+import com.peachpasswords.ui.lock.MIN_PASSWORD_LENGTH58+import com.peachpasswords.ui.security.StrengthBar59+import com.peachpasswords.ui.security.scorePassword60+import com.peachpasswords.ui.security.strengthColor61+import com.peachpasswords.ui.security.strengthLabel62+import com.peachpasswords.ui.theme.LocalPeachAccent63+import com.peachpasswords.ui.theme.PeachColors64+import com.peachpasswords.ui.theme.PeachType65+import com.peachpasswords.ui.theme.ShellBackground66+import com.peachpasswords.vault.VaultRepository67+import com.peachpasswords.vault.WORD_LIST68+import com.peachpasswords.vault.findInvalidWords69+import com.peachpasswords.vault.getWordSuggestions70+import dagger.hilt.android.lifecycle.HiltViewModel71+import kotlinx.coroutines.Dispatchers72+import kotlinx.coroutines.flow.MutableStateFlow73+import kotlinx.coroutines.flow.StateFlow74+import kotlinx.coroutines.flow.asStateFlow75+import kotlinx.coroutines.flow.update76+import kotlinx.coroutines.launch77+import kotlinx.coroutines.withContext78+import javax.inject.Inject79+80+private const val WORD_COUNT = 1281+82+enum class RecoveryStep { WORDS, PASSWORD, NO_ESCROW }83+84+data class RecoveryEntryUiState(85+    val step: RecoveryStep = RecoveryStep.WORDS,86+    val checksumValid: Boolean = false,87+    val wordsError: String? = null,88+    val passwordError: String? = null,89+    val working: Boolean = false,90+)91+92+@HiltViewModel93+class RecoveryEntryViewModel @Inject constructor(94+    private val vault: VaultRepository,95+) : ViewModel() {96+97+    private val _state = MutableStateFlow(98+        RecoveryEntryUiState(99+            // If this vault was never set up for recovery, drop straight to the100+            // no-escrow state instead of letting the user type 12 words for nothing.101+            step = if (vault.hasRecoveryEscrow()) RecoveryStep.WORDS else RecoveryStep.NO_ESCROW,102+        ),103+    )104+    val state: StateFlow<RecoveryEntryUiState> = _state.asStateFlow()105+106+    private var validatedWords: List<String> = emptyList()107+108+    /**109+     * Gate the [Continue] button on all 12 slots holding valid BIP39 words. We do110+     * NOT use the entropy checksum here: WORD_LIST carries a duplicate "abandon",111+     * so an app-generated phrase using that index fails a strict checksum even112+     * though it is the user's real phrase. The escrow's GCM tag is the true113+     * correctness check at recovery time (surfaced as "Incorrect recovery words").114+     */115+    fun validateWords(words: List<String>) {116+        viewModelScope.launch {117+            val ok = withContext(Dispatchers.Default) {118+                words.size == WORD_COUNT && words.all { it.isNotBlank() } && findInvalidWords(words).isEmpty()119+            }120+            validatedWords = if (ok) words.map { it.trim().lowercase() } else emptyList()121+            _state.update {122+                it.copy(123+                    checksumValid = ok,124+                    wordsError = if (!ok && words.all { w -> w.isNotBlank() }) {125+                        "Some words aren't valid recovery words — check for typos"126+                    } else null,127+                )128+            }129+        }130+    }131+132+    fun continueToPassword() {133+        if (_state.value.checksumValid) _state.update { it.copy(step = RecoveryStep.PASSWORD) }134+    }135+136+    /**137+     * Recover the vault with the validated words and set [newPassword]. On success138+     * the vault is left unlocked; [onSuccess] should navigate to the vault list.139+     */140+    fun recover(newPassword: String, confirm: String, onSuccess: () -> Unit) {141+        val s = _state.value142+        if (s.working) return143+        when {144+            newPassword.length < MIN_PASSWORD_LENGTH ->145+                return _state.update { it.copy(passwordError = "Password must be at least $MIN_PASSWORD_LENGTH characters") }146+            newPassword != confirm ->147+                return _state.update { it.copy(passwordError = "Passwords do not match") }148+            scorePassword(newPassword) < 2 ->149+                return _state.update { it.copy(passwordError = "Password too weak — try a longer or more varied password") }150+        }151+        _state.update { it.copy(working = true, passwordError = null) }152+        viewModelScope.launch {153+            val unlocked = vault.unlockWithRecoveryWords(validatedWords)154+            if (!unlocked) {155+                _state.update { it.copy(working = false, passwordError = "Incorrect recovery words — vault cannot be unlocked") }156+                return@launch157+            }158+            val reset = vault.resetPasswordWithRecoveryWords(validatedWords, newPassword)159+            if (!reset) {160+                _state.update { it.copy(working = false, passwordError = "Something went wrong — please try again") }161+                return@launch162+            }163+            _state.update { it.copy(working = false) }164+            onSuccess()165+        }166+    }167+}168+169+@Composable170+fun RecoveryWordEntryScreen(171+    onSuccess: () -> Unit,172+    onBack: () -> Unit,173+    onRestore: () -> Unit = onBack,174+    vm: RecoveryEntryViewModel = hiltViewModel(),175+) {176+    val state by vm.state.collectAsState()177+    ShellBackground {178+        Column(179+            modifier = Modifier180+                .fillMaxSize()181+                .systemBarsPadding()182+                .padding(horizontal = 22.dp, vertical = 18.dp)183+                .verticalScroll(rememberScrollState()),184+        ) {185+            when (state.step) {186+                RecoveryStep.WORDS -> WordStep(state, vm, onBack)187+                RecoveryStep.PASSWORD -> PasswordStep(state, vm, onSuccess)188+                RecoveryStep.NO_ESCROW -> NoEscrowStep(onRestore = onRestore, onBack = onBack)189+            }190+        }191+    }192+}193+194+@Composable195+private fun WordStep(state: RecoveryEntryUiState, vm: RecoveryEntryViewModel, onBack: () -> Unit) {196+    val words = remember { mutableStateListOf(*Array(WORD_COUNT) { "" }) }197+    val focusers = remember { List(WORD_COUNT) { FocusRequester() } }198+199+    fun onWordChange(i: Int, raw: String) {200+        words[i] = raw.trim().lowercase().filter { it.isLetter() }201+        // Re-run checksum validation once all 12 are filled, or to clear a stale202+        // valid/error state the moment a previously-complete grid is edited.203+        if (words.all { it.isNotBlank() } || state.checksumValid || state.wordsError != null) {204+            vm.validateWords(words.toList())205+        }206+    }207+208+    Eyebrow("VAULT RECOVERY")209+    Spacer(Modifier.height(10.dp))210+    Headline("enter your\nrecovery words.")211+    Spacer(Modifier.height(18.dp))212+213+    GlassPanel {214+        // 3 columns × 4 rows.215+        for (row in 0 until 4) {216+            Row(Modifier.fillMaxWidth().padding(vertical = 6.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {217+                for (col in 0 until 3) {218+                    val i = row * 3 + col219+                    WordSlot(220+                        index = i,221+                        value = words[i],222+                        focusRequester = focusers[i],223+                        onValueChange = { onWordChange(i, it) },224+                        onPicked = { picked ->225+                            words[i] = picked226+                            if (i + 1 < WORD_COUNT) focusers[i + 1].requestFocus()227+                            if (words.all { it.isNotBlank() }) vm.validateWords(words.toList())228+                        },229+                        imeAction = if (i == WORD_COUNT - 1) ImeAction.Done else ImeAction.Next,230+                        onNext = { if (i + 1 < WORD_COUNT) focusers[i + 1].requestFocus() },231+                        modifier = Modifier.weight(1f),232+                    )233+                }234+            }235+        }236+237+        if (state.wordsError != null) {238+            Spacer(Modifier.height(10.dp))239+            Text(240+                state.wordsError,241+                color = PeachColors.Breach,242+                style = PeachType.labelMono.copy(fontSize = 10.sp),243+            )244+        }245+    }246+247+    Spacer(Modifier.height(18.dp))248+    AccentButton("Continue", enabled = state.checksumValid, onClick = vm::continueToPassword)249+    Spacer(Modifier.height(10.dp))250+    GhostButton("Back to login", PeachColors.T1, onBack)251+}252+253+@Composable254+private fun WordSlot(255+    index: Int,256+    value: String,257+    focusRequester: FocusRequester,258+    onValueChange: (String) -> Unit,259+    onPicked: (String) -> Unit,260+    imeAction: ImeAction,261+    onNext: () -> Unit,262+    modifier: Modifier = Modifier,263+) {264+    val accent = LocalPeachAccent.current265+    val interaction = remember { MutableInteractionSource() }266+    val focused by interaction.collectIsFocusedAsState()267+    val isValidWord = remember(value) { value.isNotBlank() && WORD_LIST.contains(value) }268+    val suggestions = remember(value, focused) {269+        if (focused && value.isNotBlank() && !isValidWord) getWordSuggestions(value, 4) else emptyList()270+    }271+272+    Column(modifier = modifier) {273+        Row(verticalAlignment = Alignment.CenterVertically) {274+            Text(275+                "${index + 1}",276+                color = accent,277+                style = PeachType.recoveryNumeral,278+                textAlign = TextAlign.End,279+                modifier = Modifier.width(20.dp),280+            )281+            Spacer(Modifier.width(4.dp))282+            BasicTextField(283+                value = value,284+                onValueChange = onValueChange,285+                singleLine = true,286+                textStyle = PeachType.recoveryWord.copy(color = PeachColors.T0),287+                cursorBrush = SolidColor(accent),288+                keyboardOptions = KeyboardOptions(289+                    keyboardType = KeyboardType.Password, // hint: no autocorrect/suggestions290+                    imeAction = imeAction,291+                ),292+                keyboardActions = KeyboardActions(onNext = { onNext() }, onDone = { onNext() }),293+                interactionSource = interaction,294+                modifier = Modifier295+                    .weight(1f)296+                    .focusRequester(focusRequester)297+                    .background(if (isValidWord) accent.copy(alpha = 0.08f) else Color.Transparent)298+                    .drawBehind {299+                        drawRect(300+                            color = if (focused) accent else PeachColors.T3,301+                            topLeft = Offset(0f, size.height - 1.dp.toPx()),302+                            size = Size(size.width, 1.dp.toPx()),303+                        )304+                    }305+                    .padding(vertical = 6.dp, horizontal = 2.dp),306+            )307+        }308+        // Inline autocomplete dropdown.309+        if (suggestions.isNotEmpty()) {310+            Column(311+                Modifier312+                    .fillMaxWidth()313+                    .clip(RoundedCornerShape(6.dp))314+                    .background(PeachColors.S2)315+                    .padding(vertical = 2.dp),316+            ) {317+                suggestions.forEach { word ->318+                    Text(319+                        word,320+                        color = PeachColors.T1,321+                        style = PeachType.labelMono.copy(fontSize = 11.sp),322+                        modifier = Modifier323+                            .fillMaxWidth()324+                            .clickable { onPicked(word) }325+                            .padding(horizontal = 8.dp, vertical = 5.dp),326+                    )327+                }328+            }329+        }330+    }331+}332+333+@Composable334+private fun PasswordStep(state: RecoveryEntryUiState, vm: RecoveryEntryViewModel, onSuccess: () -> Unit) {335+    var password by remember { mutableStateOf("") }336+    var confirm by remember { mutableStateOf("") }337+    var reveal by remember { mutableStateOf(false) }338+    val score = remember(password) { scorePassword(password) }339+    val canSubmit = score >= 2 && password.isNotEmpty() && password == confirm && !state.working340+341+    Eyebrow("VAULT RECOVERY")342+    Spacer(Modifier.height(10.dp))343+    Headline("set a new\npassword.")344+    Spacer(Modifier.height(18.dp))345+346+    GlassPanel {347+        FieldLabel("new password")348+        Spacer(Modifier.height(4.dp))349+        PasswordField(350+            value = password,351+            onChange = { password = it },352+            reveal = reveal,353+            onToggleReveal = { reveal = !reveal },354+            imeAction = ImeAction.Next,355+        )356+357+        if (password.isNotEmpty()) {358+            Spacer(Modifier.height(14.dp))359+            StrengthBar(score = score)360+            Spacer(Modifier.height(6.dp))361+            Text(362+                "strength: ${strengthLabel(score)}",363+                color = strengthColor(score),364+                style = PeachType.labelMono,365+                modifier = Modifier.fillMaxWidth(),366+                textAlign = TextAlign.Center,367+            )368+        }369+370+        Spacer(Modifier.height(16.dp))371+        FieldLabel("confirm password")372+        Spacer(Modifier.height(4.dp))373+        PasswordField(374+            value = confirm,375+            onChange = { confirm = it },376+            reveal = reveal,377+            onToggleReveal = { reveal = !reveal },378+            imeAction = ImeAction.Done,379+        )380+381+        Text(382+            state.passwordError ?: " ",383+            color = PeachColors.Breach,384+            style = PeachType.labelMono.copy(fontSize = 10.sp),385+            textAlign = TextAlign.Center,386+            modifier = Modifier.fillMaxWidth().padding(top = 12.dp).height(16.dp),387+        )388+    }389+390+    Spacer(Modifier.height(18.dp))391+    AccentButton(392+        label = if (state.working) "recovering…" else "Recover vault",393+        enabled = canSubmit,394+        onClick = { vm.recover(password, confirm, onSuccess) },395+    )396+}397+398+@Composable399+private fun NoEscrowStep(onRestore: () -> Unit, onBack: () -> Unit) {400+    GlassPanel {401+        Text("⊘", color = PeachColors.T2, style = TextStyle(fontFamily = PeachType.Display, fontSize = 40.sp))402+        Spacer(Modifier.height(12.dp))403+        Text(404+            "recovery not available",405+            color = PeachColors.T1,406+            style = TextStyle(fontFamily = PeachType.Display, fontStyle = FontStyle.Italic, fontSize = 26.sp),407+        )408+        Spacer(Modifier.height(10.dp))409+        Text(410+            "Recovery words were not set up for this vault. You can restore from a backup instead.",411+            color = PeachColors.T2,412+            style = PeachType.labelMono.copy(fontSize = 10.sp),413+        )414+        Spacer(Modifier.height(18.dp))415+        GhostButton("Restore from backup", LocalPeachAccent.current, onRestore)416+        Spacer(Modifier.height(8.dp))417+        GhostButton("Back to login", PeachColors.T1, onBack)418+    }419+}420+421+// ── Shared local primitives (match LockScreen / RecoveryWordsScreen idiom) ──422+423+@Composable424+private fun Eyebrow(text: String) =425+    Text(text, color = PeachColors.T2, style = PeachType.lockEyebrow)426+427+@Composable428+private fun Headline(text: String) =429+    Text(430+        text,431+        color = PeachColors.T0,432+        style = PeachType.lockHeadline,433+    )434+435+@Composable436+private fun FieldLabel(text: String) =437+    Text(text.uppercase(), color = PeachColors.T2, style = PeachType.labelMono.copy(letterSpacing = 0.08.em))438+439+@Composable440+private fun PasswordField(441+    value: String,442+    onChange: (String) -> Unit,443+    reveal: Boolean,444+    onToggleReveal: () -> Unit,445+    imeAction: ImeAction,446+) {447+    val accent = LocalPeachAccent.current448+    val interaction = remember { MutableInteractionSource() }449+    val focused by interaction.collectIsFocusedAsState()450+    Row(verticalAlignment = Alignment.CenterVertically) {451+        BasicTextField(452+            value = value,453+            onValueChange = onChange,454+            singleLine = true,455+            textStyle = PeachType.unlockInput.copy(color = PeachColors.T0),456+            cursorBrush = SolidColor(accent),457+            visualTransformation = if (reveal) VisualTransformation.None else PasswordVisualTransformation(),458+            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password, imeAction = imeAction),459+            interactionSource = interaction,460+            modifier = Modifier461+                .weight(1f)462+                .drawBehind {463+                    drawRect(464+                        color = if (focused) accent else PeachColors.T3,465+                        topLeft = Offset(0f, size.height - 1.dp.toPx()),466+                        size = Size(size.width, 1.dp.toPx()),467+                    )468+                }469+                .padding(vertical = 8.dp),470+        )471+        Text(472+            if (reveal) "hide" else "show",473+            color = accent,474+            style = PeachType.labelMono,475+            modifier = Modifier.clickable(onClick = onToggleReveal).padding(start = 8.dp, top = 6.dp, bottom = 6.dp),476+        )477+    }478+}479+480+@Composable481+private fun GlassPanel(content: @Composable androidx.compose.foundation.layout.ColumnScope.() -> Unit) {482+    Column(483+        modifier = Modifier484+            .fillMaxWidth()485+            .clip(RoundedCornerShape(18.dp))486+            .background(Color(0xE0131109))487+            .border(1.dp, PeachColors.T3, RoundedCornerShape(18.dp))488+            .padding(20.dp),489+        content = content,490+    )491+}492+493+@Composable494+private fun AccentButton(label: String, enabled: Boolean, onClick: () -> Unit) {495+    val accent = LocalPeachAccent.current496+    Box(497+        modifier = Modifier498+            .fillMaxWidth()499+            .clip(RoundedCornerShape(12.dp))500+            .background(if (enabled) accent else accent.copy(alpha = 0.3f))501+            .clickable(enabled = enabled, onClick = onClick)502+            .padding(vertical = 14.dp),503+        contentAlignment = Alignment.Center,504+    ) {505+        Text(label, color = Color(0xFF0C0A06), style = PeachType.bodyMono)506+    }507+}508+509+@Composable510+private fun GhostButton(label: String, color: Color, onClick: () -> Unit) {511+    Box(512+        modifier = Modifier513+            .fillMaxWidth()514+            .clip(RoundedCornerShape(12.dp))515+            .border(1.dp, color.copy(alpha = 0.4f), RoundedCornerShape(12.dp))516+            .clickable(onClick = onClick)517+            .padding(vertical = 12.dp),518+        contentAlignment = Alignment.Center,519+    ) {520+        Text(label, color = color, style = PeachType.bodyMono)521+    }522+}

view file

app/src/main/java/com/peachpasswords/vault/RecoveryWords.kt+21 −0
@@ -61,6 +61,27 @@6161     return ByteArray(32).also { it.fill(0); System.arraycopy(entropy, 0, it, 0, entropy.size) }6262 }6363 64+/**65+ * Collision-stable key material for the recovery escrow, derived from the canonical66+ * word *strings* rather than reconstructed entropy indices.67+ *68+ * WORD_LIST carries "abandon" at both index 0 and 1 (a deliberate parity copy of69+ * the browser list), so `wordsToRootKeyMaterial` — which reconstructs entropy via70+ * `indexOf` — is NOT a perfect inverse of `rootKeyToWords` for any phrase that uses71+ * index 1: the words become ambiguous. The escrow must round-trip for EVERY vault,72+ * so it keys off BLAKE3 of the space-joined words (the same canonical form73+ * [recoveryWordsHash] verifies), which is identical whichever "abandon" index the74+ * phrase was generated from.75+ */76+fun wordKeyMaterial(words: List<String>): ByteArray {77+    val canonical = words.joinToString(" ") { it.trim().lowercase() }.encodeToByteArray()78+    val digest = org.bouncycastle.crypto.digests.Blake3Digest(256)79+    digest.update(canonical, 0, canonical.size)80+    val out = ByteArray(32)81+    digest.doFinal(out, 0)82+    return out83+}84+6485 fun deriveRecoveryKey(wordMaterial: ByteArray, salt: ByteArray): SecretKeySpec {6586     val generator = HKDFBytesGenerator(SHA256Digest())6687     generator.init(HKDFParameters(wordMaterial, salt, "peach-recovery-v1".encodeToByteArray()))

view file

app/src/main/java/com/peachpasswords/vault/VaultCrypto.kt+6 −0
@@ -25,6 +25,12 @@2525     const val AAD_SLOT_B = "slot_b_v1"2626     const val AAD_ROOT_KEY = "pw_root_v1"2727 28+    /**29+     * Distinct from [AAD_SLOT_A] so a recovery-escrow blob can never be swapped in30+     * as a slot-A blob (GCM auth covers the AAD).31+     */32+    const val AAD_RECOVERY = "recovery_escrow_v1"33+2834     private val secureRandom = SecureRandom()2935     private var _lastTimestamp = 0L3036 

view file

app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+161 −2
@@ -274,7 +274,15 @@274274             // Re-seal the existing payload under the new key/salt.275275             val plaintext = VaultCodec.encode(payload)276276             val blob = b64(VaultCrypto.encrypt(plaintext, newKey, VaultCrypto.AAD_SLOT_A))277-            val next = StoredVault(version = slotA.version, salt = b64(newSalt), blob = blob)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+            )278286             if (!store.writeSlotA(next)) return false279287             writeMatchingNoiseSlotB(next)280288             store.stampLocalMutation()@@ -509,13 +517,164 @@509517         requireUnlocked()510518         recoveryWordHash = recoveryWordsHash(words)511519         recoveryWordsSet = true512-        runCatching { persistSlotA(bumpVersion = false) }.getOrDefault(false)520+        // 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)513523     }514524 515525     /** Verify entered words against the stored recovery hash. */516526     fun verifyRecoveryWords(words: List<String>): Boolean {517527         val stored = recoveryWordHash ?: return false518528         return stored == recoveryWordsHash(words)529+    }530+531+    // ---- Recovery escrow (forgot-password) --------------------------------532+533+    /** True at rest if this vault has a recovery escrow the recovery flow can use. */534+    fun hasRecoveryEscrow(): Boolean = store.loadSlotA()?.recoveryEscrow != null535+536+    /**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+    }575+576+    /**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+    }633+634+    /**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+    }655+656+    /**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 true519678     }520679 521680     // ---- Internals --------------------------------------------------------

view file

app/src/main/java/com/peachpasswords/vault/VaultStore.kt+19 −2
@@ -12,12 +12,29 @@1212 /**1313  * One encrypted slot at rest. [blob] is base64 of VaultCrypto's1414  * `nonce || ciphertext || tag` output; [salt] (base64) drives Argon2id.15- * Mirrors the browser's StoredVault, minus the recovery-escrow fields which16- * the Android port wires in a later phase.15+ * Mirrors the browser's StoredVault. [recoveryEscrow] is null until the user16+ * sets recovery words; it is a password-independent second copy of the slot-A17+ * plaintext that powers the forgot-password flow.1718  */1819 @Serializable1920 data class StoredVault(2021     val version: Int = 1,22+    val salt: String,23+    val blob: String,24+    val recoveryEscrow: RecoveryEscrow? = null,25+)26+27+/**28+ * A second, password-independent copy of the slot-A plaintext envelope, sealed29+ * under a key the 12 BIP39 recovery words derive (HKDF). Lets the vault be30+ * recovered and re-wrapped under a new password without the old password.31+ *32+ * [salt] (base64, 16B) is the HKDF salt for `deriveRecoveryKey`.33+ * [blob] (base64) is `VaultCrypto.encrypt(slotAPlaintext, recoveryKey, AAD_RECOVERY)`34+ *   i.e. `nonce(12) || AES-256-GCM ciphertext||tag`.35+ */36+@Serializable37+data class RecoveryEscrow(2138     val salt: String,2239     val blob: String,2340 )

view file

app/src/test/java/com/peachpasswords/vault/RecoveryEscrowTest.kt+129 −0
@@ -0,0 +1,129 @@1+package com.peachpasswords.vault2+3+import kotlinx.coroutines.runBlocking4+import org.junit.Assert.assertEquals5+import org.junit.Assert.assertFalse6+import org.junit.Assert.assertNotNull7+import org.junit.Assert.assertNull8+import org.junit.Assert.assertTrue9+import org.junit.Test10+11+private class RecoveryFakeStorage : VaultStorage {12+    var slotA: StoredVault? = null13+    var slotB: String? = null14+    private var ver: Long = 015+    private var settings = VaultSettings()16+    override fun loadSlotA() = slotA17+    override fun hasVault() = slotA != null18+    override fun writeSlotA(slot: StoredVault): Boolean { slotA = slot; return true }19+    override fun writeSlotB(blobBase64: String): Boolean { slotB = blobBase64; return true }20+    var decoy: StoredVault? = null21+    override fun loadDecoySlot() = decoy22+    override fun writeDecoySlot(slot: StoredVault): Boolean { decoy = slot; return true }23+    override fun hasDecoySlot() = decoy != null24+    override fun clearDecoySlot() { decoy = null }25+    override fun version() = ver26+    override fun stampLocalMutation(): Long { ver = maxOf(System.currentTimeMillis(), ver + 1); return ver }27+    override fun loadSettings() = settings28+    override fun writeSettings(s: VaultSettings): Boolean { settings = s; return true }29+    override fun clearVault() { slotA = null; slotB = null; ver = 0; settings = VaultSettings() }30+}31+32+class RecoveryEscrowTest {33+34+    /** Recovery words this vault would actually show — derived from its sync root key. */35+    private fun recoveryWordsOf(repo: VaultRepository): List<String> {36+        val key = repo.syncMasterKey()!!37+        return try { rootKeyToWords(key) } finally { VaultCrypto.zero(key) }38+    }39+40+    private fun login(title: String, password: String = "pw") =41+        VaultEntry(id = "", title = title, type = "login", password = password, createdAt = 0, modifiedAt = 0)42+43+    // 1 — setRecoveryWords stores a non-null RecoveryEscrow in StoredVault.44+    @Test fun set_recovery_words_writes_escrow() = runBlocking {45+        val storage = RecoveryFakeStorage()46+        val repo = VaultRepository(storage)47+        repo.createVault("pw")48+        assertNull(storage.slotA?.recoveryEscrow)49+        assertTrue(repo.setRecoveryWords(recoveryWordsOf(repo)))50+        assertNotNull(storage.slotA?.recoveryEscrow)51+        assertTrue(repo.hasRecoveryEscrow())52+    }53+54+    // 2 — unlockWithRecoveryWords with correct words succeeds.55+    @Test fun unlock_with_correct_words_succeeds() = runBlocking {56+        val storage = RecoveryFakeStorage()57+        val repo = VaultRepository(storage)58+        repo.createVault("pw")59+        repo.addEntry(login("GitHub"))60+        val words = recoveryWordsOf(repo)61+        repo.setRecoveryWords(words)62+        repo.lock()63+        assertTrue(repo.unlockWithRecoveryWords(words))64+        // Recovered session sees the entry that was sealed into the escrow.65+        assertTrue(repo.getEntries().any { it.title == "GitHub" })66+    }67+68+    // 3 — unlockWithRecoveryWords with wrong words fails.69+    @Test fun unlock_with_wrong_words_fails() = runBlocking {70+        val storage = RecoveryFakeStorage()71+        val repo = VaultRepository(storage)72+        repo.createVault("pw")73+        repo.setRecoveryWords(recoveryWordsOf(repo))74+        repo.lock()75+        // A different, still-checksum-valid phrase from an unrelated root key.76+        val wrong = rootKeyToWords(ByteArray(32) { (it + 7).toByte() })77+        assertFalse(repo.unlockWithRecoveryWords(wrong))78+    }79+80+    // 4 — unlockWithRecoveryWords with no escrow set returns false.81+    @Test fun unlock_with_no_escrow_fails() = runBlocking {82+        val storage = RecoveryFakeStorage()83+        val repo = VaultRepository(storage)84+        repo.createVault("pw")85+        val words = recoveryWordsOf(repo) // never call setRecoveryWords86+        repo.lock()87+        assertFalse(repo.hasRecoveryEscrow())88+        assertFalse(repo.unlockWithRecoveryWords(words))89+    }90+91+    // 5 — Full round-trip: create → set words → reset password via recovery → unlock with new password.92+    @Test fun full_recovery_resets_password() = runBlocking {93+        val storage = RecoveryFakeStorage()94+        val repo = VaultRepository(storage)95+        repo.createVault("old-pass")96+        repo.addEntry(login("Bank"))97+        val words = recoveryWordsOf(repo)98+        repo.setRecoveryWords(words)99+        repo.lock()100+101+        assertTrue(repo.unlockWithRecoveryWords(words))102+        assertTrue(repo.resetPasswordWithRecoveryWords(words, "brand-new-pass"))103+        assertTrue(repo.isUnlocked.value)104+        repo.lock()105+106+        // Old password no longer works; the new one does and the entry survived.107+        assertEquals(UnlockResult.WrongPassword, repo.unlock("old-pass"))108+        assertEquals(UnlockResult.Success, repo.unlock("brand-new-pass"))109+        assertTrue(repo.getEntries().any { it.title == "Bank" })110+        // Escrow survived the password reset, so a second recovery still works.111+        assertTrue(repo.hasRecoveryEscrow())112+    }113+114+    // 6 — Round-trips for a phrase containing the duplicate "abandon" (WORD_LIST115+    // index 0/1). Index-based entropy derivation can't invert these; the escrow116+    // keys off the word strings, so seal+unlock stay consistent.117+    @Test fun escrow_round_trips_for_phrase_with_duplicate_abandon() = runBlocking {118+        val storage = RecoveryFakeStorage()119+        val repo = VaultRepository(storage)120+        repo.createVault("pw")121+        repo.addEntry(login("Mail"))122+        val words = List(12) { "abandon" }123+        repo.setRecoveryWords(words)124+        assertNotNull(storage.slotA?.recoveryEscrow)125+        repo.lock()126+        assertTrue(repo.unlockWithRecoveryWords(words))127+        assertTrue(repo.getEntries().any { it.title == "Mail" })128+    }129+}

view file