058c9f643c5b
docs: record C1 recovery-escrow + C7 chirp-transport session in CONTINUITY (escrow-keys-off-word-strings fix for the duplicate-abandon WORD_LIST; C7 transport lands ahead of product-gated VM/UI wiring; piped-stream deadlock koh lesson); trash consumed C1/C7 impl drafts, keep INTEGRATION.md reconciliation records
- time
- 2026-06-09 07:36 UTC · 5 months ago
- machine
- koh2
- agent
- claude-opus-4-8
- session
- chirp sync transport
- parent
- 0d9858b8539c
↓ peach-android-058c9f64.tar.gzatlas at this save
files changed9 files
app/drafts/C1/C1-RecoveryEscrowTest.kt+0 −131app/drafts/C1/C1-crypto-notes.md+0 −175app/drafts/C1/C1-repo-additions.kt+0 −220app/drafts/C1/RecoveryWordEntryScreen.kt+0 −540app/drafts/C7/C7-ChirpTransportTest.kt+0 −177app/drafts/C7/PairedDeviceStore.kt+0 −117app/drafts/C7/PairingFrames.kt+0 −114app/drafts/C7/PairingServer.kt+0 −321app/drafts/C7/PairingTransport.kt+0 −203app/drafts/C1/C1-RecoveryEscrowTest.kt+0 −131
@@ -1,131 +0,0 @@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-}app/drafts/C1/C1-crypto-notes.md+0 −175
@@ -1,175 +0,0 @@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.)app/drafts/C1/C1-repo-additions.kt+0 −220
@@ -1,220 +0,0 @@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 != nullapp/drafts/C1/RecoveryWordEntryScreen.kt+0 −540
@@ -1,540 +0,0 @@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-}app/drafts/C7/C7-ChirpTransportTest.kt+0 −177
@@ -1,177 +0,0 @@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-}app/drafts/C7/PairedDeviceStore.kt+0 −117
@@ -1,117 +0,0 @@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-}app/drafts/C7/PairingFrames.kt+0 −114
@@ -1,114 +0,0 @@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-}app/drafts/C7/PairingServer.kt+0 −321
@@ -1,321 +0,0 @@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-}app/drafts/C7/PairingTransport.kt+0 −203
@@ -1,203 +0,0 @@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-}