a259dd8169f1

feat: Phase 8 — ChirpSyncCoordinator (initiator + complementary responder), VaultSyncAdapter per-entry HKDF envelopes, SyncMessage wire types, vault sync root key, SyncViewModel, 7 tests (v2.1.8)

time
2026-06-03 00:04 UTC · 5 months ago
machine
koh2
agent
claude-opus-4-8
session
phase 8-12 sync autofill codex integrations
parent
5894c92dd4ba
9 files app/build.gradle+2 −2app/src/main/java/com/peachpasswords/sync/ChirpSyncCoordinator.kt+284 −0app/src/main/java/com/peachpasswords/sync/SyncMessage.kt+100 −0app/src/main/java/com/peachpasswords/sync/VaultSyncAdapter.kt+131 −0app/src/main/java/com/peachpasswords/ui/sync/SyncViewModel.kt+106 −0app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+38 −2app/src/main/java/com/peachpasswords/vault/VaultStore.kt+12 −1app/src/test/java/com/peachpasswords/sync/ChirpSyncCoordinatorTest.kt+111 −0app/src/test/java/com/peachpasswords/sync/VaultSyncAdapterTest.kt+65 −0
app/build.gradle+2 −2
@@ -16,8 +16,8 @@1616         applicationId "com.peachpasswords"1717         minSdk 261818         targetSdk 3519-        versionCode 20100720-        versionName "2.1.7"19+        versionCode 20100820+        versionName "2.1.8"2121 2222         testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"2323         vectorDrawables {

view file

app/src/main/java/com/peachpasswords/sync/ChirpSyncCoordinator.kt+284 −0
@@ -0,0 +1,284 @@1+package com.peachpasswords.sync2+3+import kotlinx.coroutines.TimeoutCancellationException4+import kotlinx.coroutines.withTimeout5+6+/**7+ * Chirp Sync — Phase 2 manifest-diff coordinator. Exact port of the browser8+ * `chirp-sync-coordinator.ts`, with the complementary responder the browser9+ * leaves to "the mobile-side coordinator that calls this same protocol the10+ * other way".11+ *12+ * After Noise XX is open and the peer's static key is verified against the13+ * paired-device registry, the two sides drive:14+ *15+ *   ->  SYNC_HELLO { vaultId, deviceId, version, deviceTime }16+ *   <-  SYNC_HELLO                                  (mismatch → vault_mismatch)17+ *   <-> SYNC_MANIFEST { entries, tombstones }       (each side sends one)18+ *   ->  SYNC_REQUEST { entryIds }                   (entries newer on the peer)19+ *   <-  SYNC_REQUEST20+ *   <-> SYNC_ENTRIES   (sender unconditional; receiver reads iff it requested)21+ *   <-> SYNC_TOMBSTONES22+ *   <-> SYNC_DEVICE_MANIFEST                         (optional, both opt in)23+ *   <-> SYNC_DONE24+ *25+ * Entries are opaque base64 ciphertext — the coordinator never decrypts.26+ * Last-write-wins at the entry level by mtime; tombstones override updates with27+ * a later deletion timestamp.28+ */29+private const val SESSION_TIMEOUT_MS = 30_000L30+private const val CLOCK_SKEW_WARN_MS = 120_000L31+32+/** 128 hex zeroes — the placeholder a peer sends when it has no real manifest. */33+private const val EMPTY_MANIFEST_SIGNATURE = "00000000000000000000000000000000" +34+    "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"35+36+val EMPTY_MANIFEST_PLACEHOLDER = SignedDeviceManifest(37+    body = DeviceManifestBody(manifestVersion = 1, issuerDeviceId = "", issuedAt = 0, devices = emptyList()),38+    signatureHex = EMPTY_MANIFEST_SIGNATURE,39+)40+41+/**42+ * Vault-side dependency of the coordinator. The vault holds the canonical43+ * entry/tombstone tables; the coordinator pulls a manifest, requests entries by44+ * id, applies remote entries, and applies remote tombstones. Mirrors the45+ * browser `ChirpSyncVaultAdapter`.46+ */47+interface ChirpSyncVaultAdapter {48+    suspend fun computeVaultId(): String49+    suspend fun getOurDeviceId(): String50+51+    /** The vault's monotonic version (`peach_last_modified_at`). */52+    suspend fun getLocalVersion(): Long53+54+    /** Per-entry mtimes for our active entries. */55+    suspend fun buildEntryManifest(): Map<String, Long>56+57+    /** Per-entry deletion timestamps for our tombstones. */58+    suspend fun buildTombstoneManifest(): Map<String, Long>59+60+    /** Base64 ciphertext for each requested entry id. */61+    suspend fun getEncryptedEntries(entryIds: List<String>): Map<String, String>62+63+    /** Apply incoming encrypted entries; the vault decides per-entry overwrite. */64+    suspend fun applyEntries(entries: Map<String, String>)65+66+    /** Apply incoming tombstones; the vault retains the latest deletion ts. */67+    suspend fun applyTombstones(tombstones: Map<String, Long>)68+69+    /** Optional device-manifest exchange (v2 brief §4.3). Null disables it. */70+    suspend fun buildOutgoingDeviceManifest(): SignedDeviceManifest? = null71+    suspend fun applyIncomingDeviceManifest(manifest: SignedDeviceManifest) {}72+73+    /** Both ends must opt in for the device-manifest step to run. */74+    val supportsDeviceManifest: Boolean get() = false75+}76+77+enum class SyncOutcomeStatus { COMPLETED, VAULT_MISMATCH, ERRORED, TIMEOUT }78+79+data class SyncOutcome(80+    val status: SyncOutcomeStatus,81+    val entriesReceived: Int = 0,82+    val entriesSent: Int = 0,83+    val tombstonesReceived: Int = 0,84+    val tombstonesSent: Int = 0,85+    val error: String? = null,86+)87+88+/**89+ * Run one sync round as the WebSocket client (initiator). The extension is90+ * always the initiator; Android initiates when it dials another device.91+ */92+suspend fun runChirpSyncInitiator(93+    session: ChirpSyncSession,94+    vault: ChirpSyncVaultAdapter,95+    nowMs: Long = System.currentTimeMillis(),96+): SyncOutcome {97+    var entriesReceived = 098+    var entriesSent = 099+    var tombstonesReceived = 0100+    var tombstonesSent = 0101+102+    return try {103+        withTimeout(SESSION_TIMEOUT_MS) {104+            val ourVaultId = vault.computeVaultId()105+            val localVersion = vault.getLocalVersion()106+107+            session.sendMsg(108+                SyncMessage.Hello(ourVaultId, vault.getOurDeviceId(), localVersion, nowMs),109+            )110+            val hello = session.recvAs<SyncMessage.Hello>("SYNC_HELLO")111+            if (hello.vaultId != ourVaultId) {112+                session.sendMsg(SyncMessage.Error("vault_id_mismatch"))113+                return@withTimeout SyncOutcome(SyncOutcomeStatus.VAULT_MISMATCH)114+            }115+            warnOnSkew(nowMs, hello.deviceTime)116+117+            if (hello.version == localVersion) {118+                session.sendMsg(SyncMessage.Done(0, 0))119+                session.recvAs<SyncMessage.Done>("SYNC_DONE")120+                return@withTimeout SyncOutcome(SyncOutcomeStatus.COMPLETED)121+            }122+123+            val ourEntries = vault.buildEntryManifest()124+            val ourTombstones = vault.buildTombstoneManifest()125+            session.sendMsg(SyncMessage.Manifest(ourEntries, ourTombstones))126+            val peerManifest = session.recvAs<SyncMessage.Manifest>("SYNC_MANIFEST")127+128+            val wantFromPeer = diffNewer(peerManifest.entries, ourEntries)129+            session.sendMsg(SyncMessage.Request(wantFromPeer))130+            val peerRequest = session.recvAs<SyncMessage.Request>("SYNC_REQUEST")131+132+            val ourPayload = vault.getEncryptedEntries(peerRequest.entryIds)133+            session.sendMsg(SyncMessage.Entries(ourPayload))134+            entriesSent = ourPayload.size135+136+            if (wantFromPeer.isNotEmpty()) {137+                val incoming = session.recvAs<SyncMessage.Entries>("SYNC_ENTRIES")138+                vault.applyEntries(incoming.entries)139+                entriesReceived = incoming.entries.size140+            }141+142+            val newerForPeer = newerTombstones(ourTombstones, peerManifest.tombstones)143+            session.sendMsg(SyncMessage.Tombstones(newerForPeer))144+            tombstonesSent = newerForPeer.size145+146+            val peerTombstones = session.recvAs<SyncMessage.Tombstones>("SYNC_TOMBSTONES")147+            vault.applyTombstones(peerTombstones.tombstones)148+            tombstonesReceived = peerTombstones.tombstones.size149+150+            if (vault.supportsDeviceManifest) {151+                val ours = vault.buildOutgoingDeviceManifest() ?: EMPTY_MANIFEST_PLACEHOLDER152+                session.sendMsg(SyncMessage.DeviceManifest(ours))153+                val theirs = session.recvAs<SyncMessage.DeviceManifest>("SYNC_DEVICE_MANIFEST")154+                if (theirs.manifest.signatureHex != EMPTY_MANIFEST_PLACEHOLDER.signatureHex) {155+                    vault.applyIncomingDeviceManifest(theirs.manifest)156+                }157+            }158+159+            session.sendMsg(SyncMessage.Done(entriesReceived, entriesSent))160+            session.recvAs<SyncMessage.Done>("SYNC_DONE")161+            SyncOutcome(162+                SyncOutcomeStatus.COMPLETED,163+                entriesReceived, entriesSent, tombstonesReceived, tombstonesSent,164+            )165+        }166+    } catch (_: TimeoutCancellationException) {167+        SyncOutcome(SyncOutcomeStatus.TIMEOUT, error = "session timed out after 30s")168+    } catch (e: Exception) {169+        SyncOutcome(SyncOutcomeStatus.ERRORED, error = e.message ?: "sync_failed")170+    }171+}172+173+/**174+ * Run one sync round as the WebSocket server (responder) — the exact175+ * complement of [runChirpSyncInitiator]. Send/recv are mirrored so the two176+ * halves never deadlock and stale frames never leak between phases: the177+ * responder reads the initiator's unconditional SYNC_ENTRIES, but only emits178+ * its own when the initiator actually requested something.179+ */180+suspend fun runChirpSyncResponder(181+    session: ChirpSyncSession,182+    vault: ChirpSyncVaultAdapter,183+    nowMs: Long = System.currentTimeMillis(),184+): SyncOutcome {185+    var entriesReceived = 0186+    var entriesSent = 0187+    var tombstonesReceived = 0188+    var tombstonesSent = 0189+190+    return try {191+        withTimeout(SESSION_TIMEOUT_MS) {192+            val ourVaultId = vault.computeVaultId()193+            val localVersion = vault.getLocalVersion()194+195+            val hello = session.recvAs<SyncMessage.Hello>("SYNC_HELLO")196+            // Always answer HELLO so the initiator's recv completes, even on a197+            // mismatch where we bail immediately after.198+            session.sendMsg(199+                SyncMessage.Hello(ourVaultId, vault.getOurDeviceId(), localVersion, nowMs),200+            )201+            if (hello.vaultId != ourVaultId) {202+                return@withTimeout SyncOutcome(SyncOutcomeStatus.VAULT_MISMATCH)203+            }204+            warnOnSkew(nowMs, hello.deviceTime)205+206+            if (hello.version == localVersion) {207+                session.recvAs<SyncMessage.Done>("SYNC_DONE")208+                session.sendMsg(SyncMessage.Done(0, 0))209+                return@withTimeout SyncOutcome(SyncOutcomeStatus.COMPLETED)210+            }211+212+            val ourEntries = vault.buildEntryManifest()213+            val ourTombstones = vault.buildTombstoneManifest()214+            val peerManifest = session.recvAs<SyncMessage.Manifest>("SYNC_MANIFEST")215+            session.sendMsg(SyncMessage.Manifest(ourEntries, ourTombstones))216+217+            val initiatorWants = session.recvAs<SyncMessage.Request>("SYNC_REQUEST").entryIds218+            val wantFromPeer = diffNewer(peerManifest.entries, ourEntries)219+            session.sendMsg(SyncMessage.Request(wantFromPeer))220+221+            // Drain the initiator's unconditional SYNC_ENTRIES first.222+            val incoming = session.recvAs<SyncMessage.Entries>("SYNC_ENTRIES")223+            if (wantFromPeer.isNotEmpty()) {224+                vault.applyEntries(incoming.entries)225+                entriesReceived = incoming.entries.size226+            }227+            // Only emit ours when the initiator asked — its recv is conditional.228+            if (initiatorWants.isNotEmpty()) {229+                val ourPayload = vault.getEncryptedEntries(initiatorWants)230+                session.sendMsg(SyncMessage.Entries(ourPayload))231+                entriesSent = ourPayload.size232+            }233+234+            val peerTombstones = session.recvAs<SyncMessage.Tombstones>("SYNC_TOMBSTONES")235+            vault.applyTombstones(peerTombstones.tombstones)236+            tombstonesReceived = peerTombstones.tombstones.size237+238+            val newerForPeer = newerTombstones(ourTombstones, peerManifest.tombstones)239+            session.sendMsg(SyncMessage.Tombstones(newerForPeer))240+            tombstonesSent = newerForPeer.size241+242+            if (vault.supportsDeviceManifest) {243+                val theirs = session.recvAs<SyncMessage.DeviceManifest>("SYNC_DEVICE_MANIFEST")244+                val ours = vault.buildOutgoingDeviceManifest() ?: EMPTY_MANIFEST_PLACEHOLDER245+                session.sendMsg(SyncMessage.DeviceManifest(ours))246+                if (theirs.manifest.signatureHex != EMPTY_MANIFEST_PLACEHOLDER.signatureHex) {247+                    vault.applyIncomingDeviceManifest(theirs.manifest)248+                }249+            }250+251+            session.recvAs<SyncMessage.Done>("SYNC_DONE")252+            session.sendMsg(SyncMessage.Done(entriesReceived, entriesSent))253+            SyncOutcome(254+                SyncOutcomeStatus.COMPLETED,255+                entriesReceived, entriesSent, tombstonesReceived, tombstonesSent,256+            )257+        }258+    } catch (_: TimeoutCancellationException) {259+        SyncOutcome(SyncOutcomeStatus.TIMEOUT, error = "session timed out after 30s")260+    } catch (e: Exception) {261+        SyncOutcome(SyncOutcomeStatus.ERRORED, error = e.message ?: "sync_failed")262+    }263+}264+265+/** Entry ids the peer holds at a strictly newer mtime than we do. */266+private fun diffNewer(remote: Map<String, Long>, local: Map<String, Long>): List<String> =267+    remote.filter { (id, ts) -> local[id]?.let { ts > it } ?: true }.keys.toList()268+269+/** Our tombstones the peer has no newer deletion record for. */270+private fun newerTombstones(ours: Map<String, Long>, peer: Map<String, Long>): Map<String, Long> =271+    ours.filter { (id, ts) -> ts > (peer[id] ?: 0L) }272+273+private fun warnOnSkew(localTime: Long, remoteTime: Long) {274+    if (kotlin.math.abs(localTime - remoteTime) > CLOCK_SKEW_WARN_MS) {275+        android.util.Log.w("chirp-sync", "clock skew detected: local=$localTime remote=$remoteTime")276+    }277+}278+279+private suspend fun ChirpSyncSession.sendMsg(msg: SyncMessage) = send(msg.encodeToBytes())280+281+private suspend inline fun <reified T : SyncMessage> ChirpSyncSession.recvAs(expected: String): T {282+    val msg = decodeSyncMessage(receive())283+    return msg as? T ?: throw IllegalStateException("expected $expected, got ${msg::class.simpleName}")284+}

view file

app/src/main/java/com/peachpasswords/sync/SyncMessage.kt+100 −0
@@ -0,0 +1,100 @@1+package com.peachpasswords.sync2+3+import kotlinx.serialization.SerialName4+import kotlinx.serialization.Serializable5+import kotlinx.serialization.json.Json6+7+/**8+ * Chirp Sync wire protocol — exact port of the browser `ChirpSyncMessage`9+ * union (shared/sync-types.ts). Each frame is JSON with a `type` discriminator,10+ * sent over the Noise-XX-encrypted session. Entries travel as opaque base6411+ * ciphertext envelopes; the coordinator never sees plaintext.12+ */13+@Serializable14+sealed class SyncMessage {15+    @Serializable16+    @SerialName("SYNC_HELLO")17+    data class Hello(18+        val vaultId: String,19+        val deviceId: String,20+        val version: Long,21+        val deviceTime: Long,22+    ) : SyncMessage()23+24+    @Serializable25+    @SerialName("SYNC_MANIFEST")26+    data class Manifest(27+        val entries: Map<String, Long>,28+        val tombstones: Map<String, Long>,29+    ) : SyncMessage()30+31+    @Serializable32+    @SerialName("SYNC_REQUEST")33+    data class Request(val entryIds: List<String>) : SyncMessage()34+35+    @Serializable36+    @SerialName("SYNC_ENTRIES")37+    data class Entries(val entries: Map<String, String>) : SyncMessage()38+39+    @Serializable40+    @SerialName("SYNC_TOMBSTONES")41+    data class Tombstones(val tombstones: Map<String, Long>) : SyncMessage()42+43+    @Serializable44+    @SerialName("SYNC_DEVICE_MANIFEST")45+    data class DeviceManifest(val manifest: SignedDeviceManifest) : SyncMessage()46+47+    @Serializable48+    @SerialName("SYNC_DONE")49+    data class Done(50+        val entriesReceived: Int = 0,51+        val entriesSent: Int = 0,52+    ) : SyncMessage()53+54+    @Serializable55+    @SerialName("SYNC_ERROR")56+    data class Error(val error: String) : SyncMessage()57+}58+59+@Serializable60+data class ManifestDeviceEntry(61+    val deviceId: String,62+    val deviceName: String,63+    val deviceType: String,64+    val longTermPublicKeyHex: String,65+    val signingPublicKeyHex: String,66+    val wsPort: Int? = null,67+    val pairedAt: Long,68+)69+70+@Serializable71+data class DeviceManifestBody(72+    val manifestVersion: Int,73+    val issuerDeviceId: String,74+    val issuedAt: Long,75+    val devices: List<ManifestDeviceEntry>,76+)77+78+@Serializable79+data class SignedDeviceManifest(80+    val body: DeviceManifestBody,81+    /** Hex-encoded 64-byte Ed25519 signature over the canonicalised body. */82+    val signatureHex: String,83+)84+85+/**86+ * The wire codec. `classDiscriminator = "type"` reproduces the browser's flat87+ * `{ "type": "SYNC_HELLO", ... }` shape exactly; `encodeDefaults` keeps the88+ * optional SYNC_DONE counters on the wire.89+ */90+val SyncJson: Json = Json {91+    classDiscriminator = "type"92+    encodeDefaults = true93+    ignoreUnknownKeys = true94+}95+96+fun SyncMessage.encodeToBytes(): ByteArray =97+    SyncJson.encodeToString(SyncMessage.serializer(), this).toByteArray(Charsets.UTF_8)98+99+fun decodeSyncMessage(bytes: ByteArray): SyncMessage =100+    SyncJson.decodeFromString(SyncMessage.serializer(), String(bytes, Charsets.UTF_8))

view file

app/src/main/java/com/peachpasswords/sync/VaultSyncAdapter.kt+131 −0
@@ -0,0 +1,131 @@1+package com.peachpasswords.sync2+3+import com.peachpasswords.vault.Tombstone4+import com.peachpasswords.vault.VaultEntry5+import com.peachpasswords.vault.VaultRepository6+import kotlinx.serialization.json.Json7+import org.bouncycastle.crypto.digests.SHA256Digest8+import org.bouncycastle.crypto.generators.HKDFBytesGenerator9+import org.bouncycastle.crypto.params.HKDFParameters10+import java.security.SecureRandom11+import java.util.Base6412+import javax.crypto.Cipher13+import javax.crypto.spec.GCMParameterSpec14+import javax.crypto.spec.SecretKeySpec15+16+/**17+ * Production [ChirpSyncVaultAdapter] backing the coordinator with the live18+ * [VaultRepository]. Exact port of the browser `chirp-sync-vault-adapter.ts`:19+ * the coordinator only ever moves opaque base64 envelopes; plaintext crosses20+ * this boundary and nowhere else.21+ *22+ * Envelope cipher: AES-GCM under a PER-ENTRY key23+ *   HKDF-SHA256(ikm = syncMasterKey, salt = "", info = entryId + "sync-entry-v1")24+ * with a random 12-byte nonce and aad = "peach-sync-entry-v1". Binding the key25+ * to the entry id means a ciphertext minted for one slot cannot be replayed26+ * into another — [applyEntries] rejects any envelope whose decrypted id does27+ * not match the map key it arrived under. Both paired devices hold the same28+ * syncMasterKey (same vault root key), so keys match without negotiation; the29+ * Noise XX session is a second, independent encryption layer on top.30+ */31+class VaultSyncAdapter(32+    private val repo: VaultRepository,33+    private val ourDeviceId: String,34+    override val supportsDeviceManifest: Boolean = false,35+) : ChirpSyncVaultAdapter {36+37+    override suspend fun computeVaultId(): String =38+        repo.syncVaultId() ?: throw VaultLockedException()39+40+    override suspend fun getOurDeviceId(): String = ourDeviceId41+42+    override suspend fun getLocalVersion(): Long = repo.getVaultVersion()43+44+    override suspend fun buildEntryManifest(): Map<String, Long> =45+        repo.getEntries().associate { it.id to it.modifiedAt }46+47+    override suspend fun buildTombstoneManifest(): Map<String, Long> =48+        repo.getTombstones().associate { it.id to it.deletedAt }49+50+    override suspend fun getEncryptedEntries(entryIds: List<String>): Map<String, String> {51+        val master = requireMasterKey()52+        try {53+            val out = LinkedHashMap<String, String>()54+            for (id in entryIds) {55+                val entry = repo.getEntry(id) ?: continue56+                out[id] = encryptEntry(deriveEntryKey(master, id), entry)57+            }58+            return out59+        } finally {60+            master.fill(0)61+        }62+    }63+64+    override suspend fun applyEntries(entries: Map<String, String>) {65+        val master = requireMasterKey()66+        val decrypted = try {67+            entries.mapNotNull { (id, envelope) ->68+                val entry = decryptEntryOrNull(deriveEntryKey(master, id), envelope)69+                // The map key is the authority on id — refuse a swapped envelope70+                // so a ciphertext can't poison a different entry slot.71+                if (entry != null && entry.id == id) entry else null72+            }73+        } finally {74+            master.fill(0)75+        }76+        if (decrypted.isNotEmpty()) repo.applyMergedRemoteEntries(decrypted, emptyList())77+    }78+79+    override suspend fun applyTombstones(tombstones: Map<String, Long>) {80+        val cleaned = tombstones81+            .filterValues { it > 0L }82+            .map { (id, ts) -> Tombstone(id, ts) }83+        if (cleaned.isNotEmpty()) repo.applyMergedRemoteEntries(emptyList(), cleaned)84+    }85+86+    private fun requireMasterKey(): ByteArray =87+        repo.syncMasterKey() ?: throw VaultLockedException()88+89+    private fun deriveEntryKey(masterKey: ByteArray, entryId: String): ByteArray {90+        val info = (entryId + ENTRY_KEY_INFO_SUFFIX).toByteArray(Charsets.UTF_8)91+        val gen = HKDFBytesGenerator(SHA256Digest())92+        gen.init(HKDFParameters(masterKey, ByteArray(0), info))93+        return ByteArray(32).also { gen.generateBytes(it, 0, it.size) }94+    }95+96+    private fun encryptEntry(key: ByteArray, entry: VaultEntry): String {97+        val plaintext = entryJson.encodeToString(VaultEntry.serializer(), entry).toByteArray(Charsets.UTF_8)98+        val nonce = ByteArray(12).also(rng::nextBytes)99+        val cipher = Cipher.getInstance("AES/GCM/NoPadding")100+        cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))101+        cipher.updateAAD(ENTRY_AAD)102+        val ct = cipher.doFinal(plaintext)103+        return b64(nonce + ct)104+    }105+106+    private fun decryptEntryOrNull(key: ByteArray, envelopeB64: String): VaultEntry? = try {107+        val bytes = unb64(envelopeB64)108+        if (bytes.size < 12 + 16) null else {109+            val nonce = bytes.copyOfRange(0, 12)110+            val ct = bytes.copyOfRange(12, bytes.size)111+            val cipher = Cipher.getInstance("AES/GCM/NoPadding")112+            cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))113+            cipher.updateAAD(ENTRY_AAD)114+            val pt = cipher.doFinal(ct)115+            entryJson.decodeFromString(VaultEntry.serializer(), String(pt, Charsets.UTF_8))116+        }117+    } catch (_: Exception) {118+        null119+    }120+121+    private companion object {122+        const val ENTRY_KEY_INFO_SUFFIX = "sync-entry-v1"123+        val ENTRY_AAD = "peach-sync-entry-v1".toByteArray(Charsets.UTF_8)124+        val rng = SecureRandom()125+        val entryJson = Json { encodeDefaults = false; ignoreUnknownKeys = true }126+        fun b64(b: ByteArray): String = Base64.getEncoder().encodeToString(b)127+        fun unb64(s: String): ByteArray = Base64.getDecoder().decode(s)128+    }129+}130+131+class VaultLockedException : Exception("vault_locked")

view file

app/src/main/java/com/peachpasswords/ui/sync/SyncViewModel.kt+106 −0
@@ -0,0 +1,106 @@1+package com.peachpasswords.ui.sync2+3+import android.content.Context4+import androidx.lifecycle.ViewModel5+import androidx.lifecycle.viewModelScope6+import com.peachpasswords.sync.ChirpSyncVaultAdapter7+import com.peachpasswords.sync.SyncEndpoint8+import com.peachpasswords.sync.SyncOutcomeStatus9+import com.peachpasswords.sync.SyncStatus10+import com.peachpasswords.sync.VaultSyncAdapter11+import com.peachpasswords.sync.deriveSyncIdentityKeypair12+import com.peachpasswords.sync.getOrCreateDeviceId13+import com.peachpasswords.sync.openChirpSyncSession14+import com.peachpasswords.sync.runChirpSyncInitiator15+import com.peachpasswords.vault.VaultCrypto16+import com.peachpasswords.vault.VaultRepository17+import dagger.hilt.android.lifecycle.HiltViewModel18+import dagger.hilt.android.qualifiers.ApplicationContext19+import kotlinx.coroutines.flow.MutableStateFlow20+import kotlinx.coroutines.flow.StateFlow21+import kotlinx.coroutines.flow.asStateFlow22+import kotlinx.coroutines.launch23+import javax.inject.Inject24+25+/**26+ * Drives a Chirp Sync round and surfaces its status to the Sync settings card.27+ *28+ * Trigger conditions (browser `sync-trigger.ts` parity):29+ *   1. Vault mutation — a local add/update/delete should schedule a sync.30+ *   2. App foreground — reconnect to nearby peers on resume.31+ *   3. Manual — the "Sync now" control on the Sync card.32+ *   4. mDNS peer discovery — a paired device appears on the LAN.33+ *34+ * Discovery, the WebSocket server role, and the paired-device store land with35+ * the pairing UI (Phase 10); [syncWith] already performs a real initiator round36+ * against a known endpoint so those wirings have a finished target to call.37+ */38+@HiltViewModel39+class SyncViewModel @Inject constructor(40+    @ApplicationContext private val context: Context,41+    private val vault: VaultRepository,42+) : ViewModel() {43+44+    private val _status = MutableStateFlow<SyncStatus>(SyncStatus.Idle)45+    val status: StateFlow<SyncStatus> = _status.asStateFlow()46+47+    /** Adapter over the live vault; null while the vault is locked. */48+    fun buildAdapter(): ChirpSyncVaultAdapter? {49+        if (!vault.isUnlocked.value) return null50+        return VaultSyncAdapter(vault, getOrCreateDeviceId(context))51+    }52+53+    /**54+     * Manual / discovery trigger. With no paired-device store yet, this reports55+     * Offline when there is nothing to dial; pairing (Phase 10) supplies peers.56+     */57+    fun triggerSync() {58+        if (!vault.isUnlocked.value) {59+            _status.value = SyncStatus.Error("vault_locked")60+            return61+        }62+        // No paired-device registry on Android yet — nothing reachable to dial.63+        _status.value = SyncStatus.Offline64+    }65+66+    /** Run one initiator round against a known peer endpoint. */67+    fun syncWith(endpoint: SyncEndpoint, expectedRemotePubkeyHex: String) {68+        val master = vault.syncMasterKey() ?: run {69+            _status.value = SyncStatus.Error("vault_locked")70+            return71+        }72+        val adapter = buildAdapter() ?: run {73+            _status.value = SyncStatus.Error("vault_locked")74+            master.fill(0)75+            return76+        }77+        _status.value = SyncStatus.Syncing78+        viewModelScope.launch {79+            try {80+                val deviceId = getOrCreateDeviceId(context)81+                val identity = deriveSyncIdentityKeypair(master, deviceId)82+                val session = openChirpSyncSession(83+                    endpoint = endpoint,84+                    ourLongTermPrivateKey = identity.secretKey,85+                    ourLongTermPublicKey = identity.publicKey,86+                    expectedRemotePubkeyHex = expectedRemotePubkeyHex,87+                )88+                val outcome = try {89+                    runChirpSyncInitiator(session, adapter)90+                } finally {91+                    session.close()92+                }93+                _status.value = when (outcome.status) {94+                    SyncOutcomeStatus.COMPLETED -> SyncStatus.LastSynced(System.currentTimeMillis())95+                    SyncOutcomeStatus.VAULT_MISMATCH -> SyncStatus.Error("vault_id_mismatch")96+                    SyncOutcomeStatus.TIMEOUT -> SyncStatus.Error("timeout")97+                    SyncOutcomeStatus.ERRORED -> SyncStatus.Error(outcome.error ?: "sync_failed")98+                }99+            } catch (e: Exception) {100+                _status.value = SyncStatus.Error(e.message ?: "sync_failed")101+            } finally {102+                VaultCrypto.zero(master)103+            }104+        }105+    }106+}

view file

app/src/main/java/com/peachpasswords/vault/VaultRepository.kt+38 −2
@@ -46,6 +46,7 @@4646     private val rng = SecureRandom()4747 4848     private var derivedKey: ByteArray? = null49+    private var rootKey: ByteArray? = null4950     private var entryList: MutableList<VaultEntry> = mutableListOf()5051     private var duressConfigured: Boolean = false5152 @@ -67,6 +68,7 @@6768             val key = VaultCrypto.deriveKey(password, salt)6869             entryList = mutableListOf()6970             duressConfigured = false71+            rootKey = VaultCrypto.generateRootKey()7072             val slotA = sealSlotA(key, salt)7173             if (!store.writeSlotA(slotA)) return CreateVaultResult.Error("storage_write_failed")7274             writeMatchingNoiseSlotB(slotA)@@ -95,6 +97,7 @@9597             entryList = payload.entries.toMutableList()9698             duressConfigured = payload.duressConfigured9799             _settings.value = store.loadSettings()100+            ensureRootKey(payload)98101             publish()99102             _isUnlocked.value = true100103             UnlockResult.Success@@ -114,6 +117,7 @@114117             entryList = payload.entries.toMutableList()115118             duressConfigured = payload.duressConfigured116119             _settings.value = store.loadSettings()120+            ensureRootKey(payload)117121             publish()118122             _isUnlocked.value = true119123             UnlockResult.Success@@ -124,13 +128,27 @@124128 125129     fun lock() {126130         derivedKey?.let(VaultCrypto::zero)131+        rootKey?.let(VaultCrypto::zero)127132         derivedKey = null133+        rootKey = null128134         entryList = mutableListOf()129135         duressConfigured = false130136         _entries.value = emptyList()131137         _isUnlocked.value = false132138     }133139 140+    // ---- Sync identity ----------------------------------------------------141+142+    /**143+     * The vault's stable sync master key (a copy). Caller must zero it. Backs144+     * vault_id, the Noise static key, the Ed25519 manifest key, and per-entry145+     * envelope keys. Null when locked. See [VaultPayload.rootKeyB64].146+     */147+    fun syncMasterKey(): ByteArray? = rootKey?.copyOf()148+149+    /** Stable per-vault id two paired devices must share to sync. Null when locked. */150+    fun syncVaultId(): String? = rootKey?.let { com.peachpasswords.sync.computeVaultId(it) }151+134152     suspend fun changePassword(oldPassword: String, newPassword: String): Boolean = mutex.withLock {135153         val slotA = store.loadSlotA() ?: return false136154         return try {@@ -295,12 +313,30 @@295313         if (derivedKey == null) throw IllegalStateException("vault_locked")296314     }297315 316+    /** The slot-A plaintext envelope for the current in-memory session. */317+    private fun currentPayload(): VaultPayload =318+        VaultPayload(entryList.toList(), duressConfigured, rootKey?.let(::b64) ?: "")319+320+    /**321+     * Adopt the payload's root key, lazily minting one for legacy payloads.322+     * A freshly-minted key is persisted WITHOUT bumping the version — adopting323+     * a root key is not a mutation paired devices should sync against.324+     */325+    private fun ensureRootKey(payload: VaultPayload) {326+        if (payload.rootKeyB64.isNotBlank()) {327+            rootKey = unb64(payload.rootKeyB64)328+            return329+        }330+        rootKey = VaultCrypto.generateRootKey()331+        runCatching { persistSlotA(bumpVersion = false) }332+    }333+298334     private fun publish() {299335         _entries.value = entryList.filter { it.deletedAt == null }300336     }301337 302338     private fun sealSlotA(key: ByteArray, salt: ByteArray): StoredVault {303-        val plaintext = VaultCodec.encode(VaultPayload(entryList.toList(), duressConfigured))339+        val plaintext = VaultCodec.encode(currentPayload())304340         val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))305341         return StoredVault(version = 1, salt = b64(salt), blob = blob)306342     }@@ -315,7 +351,7 @@315351     private fun persistSlotA(bumpVersion: Boolean): Boolean {316352         val key = derivedKey ?: throw IllegalStateException("vault_locked")317353         val prior = store.loadSlotA() ?: throw IllegalStateException("missing slot A")318-        val plaintext = VaultCodec.encode(VaultPayload(entryList.toList(), duressConfigured))354+        val plaintext = VaultCodec.encode(currentPayload())319355         val blob = b64(VaultCrypto.encrypt(plaintext, key, VaultCrypto.AAD_SLOT_A))320356         val next = prior.copy(blob = blob)321357         if (!store.writeSlotA(next)) return false

view file

app/src/main/java/com/peachpasswords/vault/VaultStore.kt+12 −1
@@ -26,11 +26,22 @@2626 @Serializable2727 data class Tombstone(val id: String, val deletedAt: Long)2828 29-/** The decrypted slot-A envelope: the entry list plus the duress flag. */29+/**30+ * The decrypted slot-A envelope: the entry list, the duress flag, and the31+ * stable sync root key.32+ *33+ * [rootKeyB64] is the vault's stable 32-byte sync master key (base64, no34+ * padding). Unlike the Argon2id password key it never rotates on a password35+ * change, so paired devices keep deriving the same vault_id, Noise static key,36+ * and per-entry envelope keys across independent password rotations (browser37+ * SEV-2-B). Empty on legacy payloads written before sync landed — the38+ * repository lazily mints and persists one on first unlock.39+ */3040 @Serializable3141 data class VaultPayload(3242     val entries: List<VaultEntry> = emptyList(),3343     val duressConfigured: Boolean = false,44+    val rootKeyB64: String = "",3445 )3546 3647 /** Pure JSON codec for the slot-A plaintext envelope — usable without Android. */

view file

app/src/test/java/com/peachpasswords/sync/ChirpSyncCoordinatorTest.kt+111 −0
@@ -0,0 +1,111 @@1+package com.peachpasswords.sync2+3+import kotlinx.coroutines.async4+import kotlinx.coroutines.channels.Channel5+import kotlinx.coroutines.runBlocking6+import org.junit.Assert.assertEquals7+import org.junit.Assert.assertFalse8+import org.junit.Assert.assertTrue9+import org.junit.Test10+11+/** Two in-memory [ChirpSyncSession]s wired back to back. */12+private fun duplex(): Pair<ChirpSyncSession, ChirpSyncSession> {13+    val a2b = Channel<ByteArray>(Channel.UNLIMITED)14+    val b2a = Channel<ByteArray>(Channel.UNLIMITED)15+    val pk = ByteArray(32)16+    val a = ChirpSyncSession(pk, send = { a2b.trySend(it); Unit }, receive = { b2a.receive() }, close = {})17+    val b = ChirpSyncSession(pk, send = { b2a.trySend(it); Unit }, receive = { a2b.receive() }, close = {})18+    return a to b19+}20+21+/**22+ * Fake adapter. The blob is just the mtime as text, so [applyEntries] can keep23+ * its manifest in step — enough to prove the diff/transfer logic moved data.24+ */25+private class FakeAdapter(26+    val deviceId: String,27+    var version: Long,28+    val vaultId: String = "VAULT",29+) : ChirpSyncVaultAdapter {30+    val entries = HashMap<String, Long>()31+    val blobs = HashMap<String, String>()32+    val tombstones = HashMap<String, Long>()33+34+    fun put(id: String, mtime: Long) { entries[id] = mtime; blobs[id] = mtime.toString() }35+36+    override suspend fun computeVaultId() = vaultId37+    override suspend fun getOurDeviceId() = deviceId38+    override suspend fun getLocalVersion() = version39+    override suspend fun buildEntryManifest() = entries.toMap()40+    override suspend fun buildTombstoneManifest() = tombstones.toMap()41+    override suspend fun getEncryptedEntries(entryIds: List<String>) =42+        entryIds.filter { blobs.containsKey(it) }.associateWith { blobs[it]!! }43+    override suspend fun applyEntries(entries: Map<String, String>) {44+        for ((id, blob) in entries) { blobs[id] = blob; this.entries[id] = blob.toLong() }45+    }46+    override suspend fun applyTombstones(tombstones: Map<String, Long>) {47+        for ((id, ts) in tombstones) this.tombstones[id] = ts48+    }49+}50+51+class ChirpSyncCoordinatorTest {52+53+    @Test fun full_round_trip_exchanges_entries_both_ways() = runBlocking {54+        val (sa, sb) = duplex()55+        val a = FakeAdapter("A", version = 1).apply { put("x", 100) }56+        val b = FakeAdapter("B", version = 2).apply { put("y", 200) }57+58+        val ra = async { runChirpSyncInitiator(sa, a, nowMs = 1_000) }59+        val rb = async { runChirpSyncResponder(sb, b, nowMs = 1_000) }60+        val (outA, outB) = ra.await() to rb.await()61+62+        assertEquals(SyncOutcomeStatus.COMPLETED, outA.status)63+        assertEquals(SyncOutcomeStatus.COMPLETED, outB.status)64+        // A pulled y; B pulled x.65+        assertTrue(a.blobs.containsKey("y"))66+        assertTrue(b.blobs.containsKey("x"))67+        assertEquals(1, outA.entriesReceived)68+        assertEquals(1, outA.entriesSent)69+    }70+71+    @Test fun equal_versions_short_circuit_without_transfer() = runBlocking {72+        val (sa, sb) = duplex()73+        val a = FakeAdapter("A", version = 7).apply { put("x", 100) }74+        val b = FakeAdapter("B", version = 7).apply { put("y", 200) }75+76+        val ra = async { runChirpSyncInitiator(sa, a, nowMs = 0) }77+        val rb = async { runChirpSyncResponder(sb, b, nowMs = 0) }78+        val (outA, outB) = ra.await() to rb.await()79+80+        assertEquals(SyncOutcomeStatus.COMPLETED, outA.status)81+        assertEquals(SyncOutcomeStatus.COMPLETED, outB.status)82+        assertEquals(0, outA.entriesReceived)83+        assertFalse(a.blobs.containsKey("y"))84+        assertFalse(b.blobs.containsKey("x"))85+    }86+87+    @Test fun vault_id_mismatch_aborts_both_sides() = runBlocking {88+        val (sa, sb) = duplex()89+        val a = FakeAdapter("A", version = 1, vaultId = "V1")90+        val b = FakeAdapter("B", version = 2, vaultId = "V2")91+92+        val ra = async { runChirpSyncInitiator(sa, a, nowMs = 0) }93+        val rb = async { runChirpSyncResponder(sb, b, nowMs = 0) }94+        val (outA, outB) = ra.await() to rb.await()95+96+        assertEquals(SyncOutcomeStatus.VAULT_MISMATCH, outA.status)97+        assertEquals(SyncOutcomeStatus.VAULT_MISMATCH, outB.status)98+    }99+100+    @Test fun tombstone_propagates_to_peer() = runBlocking {101+        val (sa, sb) = duplex()102+        val a = FakeAdapter("A", version = 3).apply { tombstones["gone"] = 500 }103+        val b = FakeAdapter("B", version = 4).apply { put("gone", 100) }104+105+        val ra = async { runChirpSyncInitiator(sa, a, nowMs = 0) }106+        val rb = async { runChirpSyncResponder(sb, b, nowMs = 0) }107+        ra.await(); rb.await()108+109+        assertEquals(500L, b.tombstones["gone"])110+    }111+}

view file

app/src/test/java/com/peachpasswords/sync/VaultSyncAdapterTest.kt+65 −0
@@ -0,0 +1,65 @@1+package com.peachpasswords.sync2+3+import com.peachpasswords.vault.StoredVault4+import com.peachpasswords.vault.VaultEntry5+import com.peachpasswords.vault.VaultRepository6+import com.peachpasswords.vault.VaultSettings7+import com.peachpasswords.vault.VaultStorage8+import kotlinx.coroutines.runBlocking9+import org.junit.Assert.assertEquals10+import org.junit.Assert.assertNull11+import org.junit.Assert.assertTrue12+import org.junit.Test13+14+private class FakeStorage : VaultStorage {15+    private var slotA: StoredVault? = null16+    private var slotB: String? = null17+    private var ver: Long = 018+    private var settings = VaultSettings()19+    override fun loadSlotA() = slotA20+    override fun hasVault() = slotA != null21+    override fun writeSlotA(slot: StoredVault): Boolean { slotA = slot; return true }22+    override fun writeSlotB(blobBase64: String): Boolean { slotB = blobBase64; return true }23+    override fun version() = ver24+    override fun stampLocalMutation(): Long { ver = maxOf(System.currentTimeMillis(), ver + 1); return ver }25+    override fun loadSettings() = settings26+    override fun writeSettings(s: VaultSettings): Boolean { settings = s; return true }27+    override fun clearVault() { slotA = null; slotB = null; ver = 0; settings = VaultSettings() }28+}29+30+class VaultSyncAdapterTest {31+    private fun newAdapter(): Pair<VaultRepository, VaultSyncAdapter> {32+        val repo = VaultRepository(FakeStorage())33+        runBlocking { repo.createVault("correct horse") }34+        return repo to VaultSyncAdapter(repo, ourDeviceId = "android-test")35+    }36+37+    @Test fun manifest_and_vault_id_reflect_the_vault() = runBlocking {38+        val (repo, adapter) = newAdapter()39+        val e = repo.addEntry(VaultEntry(id = "", title = "GitHub", createdAt = 0, modifiedAt = 0, password = "p"))40+        val manifest = adapter.buildEntryManifest()41+        assertEquals(setOf(e.id), manifest.keys)42+        assertTrue(adapter.computeVaultId().length == 64) // blake3-256 hex43+    }44+45+    @Test fun envelope_round_trips_within_the_vault() = runBlocking {46+        val (repo, adapter) = newAdapter()47+        val e = repo.addEntry(VaultEntry(id = "", title = "Mail", createdAt = 0, modifiedAt = 0, password = "secret"))48+        val envelopes = adapter.getEncryptedEntries(listOf(e.id))49+        assertTrue(envelopes.containsKey(e.id))50+        // Re-applying the same envelope is a safe no-op (same mtime, no overwrite).51+        adapter.applyEntries(envelopes)52+        assertEquals(1, repo.getEntries().size)53+    }54+55+    @Test fun swapped_envelope_is_rejected_by_id_binding() = runBlocking {56+        val (repo, adapter) = newAdapter()57+        val e = repo.addEntry(VaultEntry(id = "", title = "Bank", createdAt = 0, modifiedAt = 0, password = "x"))58+        val blob = adapter.getEncryptedEntries(listOf(e.id)).getValue(e.id)59+        // Present the ciphertext under a different id — the decrypted entry.id60+        // won't match, so it must be dropped, not poison a new slot.61+        adapter.applyEntries(mapOf("attacker-chosen-id" to blob))62+        assertNull(repo.getEntry("attacker-chosen-id"))63+        assertEquals(1, repo.getEntries().size)64+    }65+}

view file