0d9858b8539c

feat: C7 LAN sync transport layer — PairedDeviceStore (EncryptedSharedPreferences registry of the real PairedDevice + observeAll), PairingFrames (4-byte length framing + SocketFrameIO over the real PairingTransport interface), MdnsPairingServer + PairingDiscoveryClient (NsdManager _peach._tcp discovery/advertise + TCP, driving the real noiseNKResponder/Initiator + runChirpSync* + SASDerivation; brief's invented NoiseNK/VaultSyncAdapter APIs reconciled to reality); ACCESS_WIFI_STATE/CHANGE_WIFI_MULTICAST_STATE perms; 5 C7ChirpTransportTest cases (wrong-key handshake bounded via EOF, not a coroutine timeout). Transport+store land ahead of VM/UI wiring (v2.1.40)

time
2026-06-09 07:35 UTC · 5 months ago
machine
koh2
agent
claude-opus-4-8
session
chirp sync transport
parent
0df7b5bb4dfe
7 files app/build.gradle+2 −2app/src/main/AndroidManifest.xml+3 −0app/src/main/java/com/peachpasswords/sync/MdnsPairingServer.kt+320 −0app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+116 −0app/src/main/java/com/peachpasswords/sync/PairingDiscoveryClient.kt+196 −0app/src/main/java/com/peachpasswords/sync/PairingFrames.kt+113 −0app/src/test/java/com/peachpasswords/sync/C7ChirpTransportTest.kt+179 −0
app/build.gradle+2 −2
@@ -16,8 +16,8 @@1616         applicationId "com.peachpasswords"1717         minSdk 261818         targetSdk 3519-        versionCode 20103920-        versionName "2.1.39"19+        versionCode 20104020+        versionName "2.1.40"2121 2222         testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"2323         vectorDrawables {

view file

app/src/main/AndroidManifest.xml+3 −0
@@ -3,6 +3,9 @@33     xmlns:tools="http://schemas.android.com/tools">44 55     <uses-permission android:name="android.permission.INTERNET" />6+    <!-- mDNS/NSD peer discovery for the C7 LAN sync transport -->7+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />8+    <uses-permission android:name="android.permission.CHANGE_WIFI_MULTICAST_STATE" />69     <uses-permission android:name="android.permission.VIBRATE" />710     <uses-permission android:name="android.permission.USE_BIOMETRIC" />811     <uses-permission android:name="android.permission.RECORD_AUDIO" />

view file

app/src/main/java/com/peachpasswords/sync/MdnsPairingServer.kt+320 −0
@@ -0,0 +1,320 @@1+package com.peachpasswords.sync2+3+import android.content.Context4+import android.net.nsd.NsdManager5+import android.net.nsd.NsdServiceInfo6+import android.os.Build7+import dagger.hilt.android.qualifiers.ApplicationContext8+import kotlinx.coroutines.CoroutineScope9+import kotlinx.coroutines.Dispatchers10+import kotlinx.coroutines.channels.awaitClose11+import kotlinx.coroutines.flow.Flow12+import kotlinx.coroutines.flow.callbackFlow13+import kotlinx.coroutines.isActive14+import kotlinx.coroutines.launch15+import kotlinx.coroutines.withContext16+import java.net.ServerSocket17+import java.net.Socket18+import java.nio.charset.StandardCharsets19+import javax.inject.Inject20+import javax.inject.Singleton21+22+/**23+ * C7 TCP + mDNS pairing/sync SERVER (responder side).24+ *25+ * Listens on an OS-assigned TCP port, advertises itself over mDNS as26+ * `_peach._tcp`, and for each inbound connection runs the REAL responder27+ * pipeline:28+ *   1. Noise NK responder handshake ([noiseNKResponder]) over length-prefixed29+ *      frames ([SocketFrameIO]).30+ *   2. PAIR_IDENTITY frame exchange — encoded/decoded with the SAME private31+ *      helpers ChirpPairing uses; since those are file-private there, this draft32+ *      re-derives the identity frame via [LocalChirpIdentity] and a minimal33+ *      JSON, and parses the peer's via [parsePairIdentityFrame]. See34+ *      C7-INTEGRATION.md: the cleanest integration promotes ChirpPairing's35+ *      encode/decodePairingFrame to internal and deletes these shims.36+ *   3. Encrypted vault sync via the REAL [runChirpSyncResponder] over a37+ *      [ChirpSyncSession] backed by the Noise session.38+ *39+ * ── Reconciliation with the brief ──────────────────────────────────────────40+ *  - The brief calls `noiseNK.acceptHandshake(stream, out)` returning an object41+ *    with `.sendCipher/.recvCipher/.handshakeHash`. NO SUCH API EXISTS. The real42+ *    handshake is the suspend free function `noiseNKResponder(ourPriv, ourPub,43+ *    send, receive)` returning a single [NoiseNKSession] (encrypt/decrypt/44+ *    handshakeHash) — one bidirectional cipher, not split send/recv ciphers.45+ *  - NK is a responder-static / no-initiator-static pattern: the responder needs46+ *    its OWN static keypair, and the initiator must already know the responder's47+ *    static public key. We use the device's long-term sync identity48+ *    ([deriveSyncIdentityKeypair]) as that static key and publish its public half49+ *    in the mDNS TXT "pk" record so initiators can pin it.50+ *  - The brief calls `syncAdapter.buildResponse/applyRequest`. NO SUCH METHODS.51+ *    The real per-round protocol is [runChirpSyncResponder]; the adapter is a52+ *    [ChirpSyncVaultAdapter] ([VaultSyncAdapter]) with getEncryptedEntries/53+ *    applyEntries/etc. We drive the whole round, not single request/response.54+ */55+@Singleton56+class MdnsPairingServer @Inject constructor(57+    private val deviceStore: PairedDeviceStore,58+    @ApplicationContext private val ctx: Context,59+) {60+    private var serverSocket: ServerSocket? = null61+    private var nsdManager: NsdManager? = null62+    private var registrationListener: NsdManager.RegistrationListener? = null63+64+    /**65+     * Start listening + advertise + accept. Caller supplies:66+     *  - [ourStaticPrivateKey]/[ourStaticPublicKey]: the device's long-term sync67+     *    identity (from [deriveSyncIdentityKeypair]) — the Noise NK responder68+     *    static key, also published in mDNS TXT "pk".69+     *  - [vaultFactory]: builds a fresh [ChirpSyncVaultAdapter] per connection70+     *    (the vault may lock/unlock between connections).71+     *  - [localIdentity]: our PAIR_IDENTITY payload.72+     */73+    fun start(74+        scope: CoroutineScope,75+        ourStaticPrivateKey: ByteArray,76+        ourStaticPublicKey: ByteArray,77+        localIdentity: LocalChirpIdentity,78+        vaultFactory: () -> ChirpSyncVaultAdapter?,79+    ): Flow<PairingServerEvent> = callbackFlow {80+        val socket = withContext(Dispatchers.IO) { ServerSocket(0) }81+        serverSocket = socket82+        val port = socket.localPort83+84+        registerMdns(port, ourStaticPublicKey, localIdentity.deviceId)85+        trySend(PairingServerEvent.Started(port))86+87+        val acceptJob = scope.launch(Dispatchers.IO) {88+            while (isActive && !socket.isClosed) {89+                val client = try {90+                    socket.accept()91+                } catch (_: Throwable) {92+                    break93+                }94+                launch {95+                    val event = handleClient(client, ourStaticPrivateKey, ourStaticPublicKey, localIdentity, vaultFactory)96+                    trySend(event)97+                }98+            }99+        }100+101+        awaitClose {102+            acceptJob.cancel()103+            stop()104+        }105+    }106+107+    fun stop() {108+        registrationListener?.let { l -> runCatching { nsdManager?.unregisterService(l) } }109+        registrationListener = null110+        runCatching { serverSocket?.close() }111+        serverSocket = null112+    }113+114+    private suspend fun handleClient(115+        socket: Socket,116+        ourStaticPrivateKey: ByteArray,117+        ourStaticPublicKey: ByteArray,118+        localIdentity: LocalChirpIdentity,119+        vaultFactory: () -> ChirpSyncVaultAdapter?,120+    ): PairingServerEvent {121+        val transport = SocketFrameIO(122+            input = socket.getInputStream(),123+            output = socket.getOutputStream(),124+            onClose = { withContext(Dispatchers.IO) { runCatching { socket.close() } } },125+        )126+        return try {127+            // 1. Noise NK responder handshake — real free function, single session.128+            val session = noiseNKResponder(129+                ourStaticPrivateKey,130+                ourStaticPublicKey,131+                transport::send,132+                transport::receive,133+            )134+135+            // 2. PAIR_IDENTITY exchange (responder reads first, then answers) —136+            //    mirrors ChirpPairing.runPairingResponder ordering.137+            val theirIdentity = parsePairIdentityFrame(session.decrypt(transport.receive()))138+            transport.send(session.encrypt(encodePairIdentityFrame(localIdentity)))139+140+            val sas = SASDerivation.derive(session.handshakeHash)141+            val device = pairIdentityToPairedDevice(theirIdentity)142+            deviceStore.upsert(device)143+144+            // 3. Encrypted vault sync — real responder round over a ChirpSyncSession.145+            val vault = vaultFactory()146+            if (vault != null) {147+                val syncSession = chirpSessionOver(session, transport)148+                val outcome = runChirpSyncResponder(syncSession, vault)149+                if (outcome.status == SyncOutcomeStatus.COMPLETED) {150+                    deviceStore.updateLastSync(device.deviceId)151+                }152+            }153+            transport.close()154+            PairingServerEvent.SyncComplete(device.deviceId, sas)155+        } catch (e: Throwable) {156+            transport.close()157+            PairingServerEvent.Error(e.message ?: "pairing_server_error")158+        }159+    }160+161+    private fun registerMdns(port: Int, staticPub: ByteArray, deviceId: String) {162+        val manager = ctx.getSystemService(NsdManager::class.java) ?: return163+        nsdManager = manager164+        val info = NsdServiceInfo().apply {165+            serviceName = buildServiceName(deviceId)166+            serviceType = PEACH_SERVICE_TYPE167+            this.port = port168+            // NsdServiceInfo.setAttribute is API 21+; minSdk is 26.169+            setAttribute("v", PROTOCOL_VERSION)170+            setAttribute("pk", pubkeyToHex(staticPub))171+            setAttribute("id", deviceId)172+        }173+        val listener = object : NsdManager.RegistrationListener {174+            override fun onServiceRegistered(info: NsdServiceInfo) {}175+            override fun onRegistrationFailed(info: NsdServiceInfo, errorCode: Int) {}176+            override fun onServiceUnregistered(info: NsdServiceInfo) {}177+            override fun onUnregistrationFailed(info: NsdServiceInfo, errorCode: Int) {}178+        }179+        registrationListener = listener180+        manager.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)181+    }182+183+    private fun buildServiceName(deviceId: String): String {184+        val shortId = deviceId.take(8)185+        val model = Build.MODEL.replace(Regex("[^A-Za-z0-9-]"), "")186+        // mDNS service-instance names are capped at 63 bytes; reserve room for187+        // the "Peach-" prefix and the "-${shortId}" suffix.188+        val maxModel = 63 - "Peach-".length - 1 - shortId.length189+        val trimmedModel = if (model.length > maxModel && maxModel > 0) model.take(maxModel) else model190+        return "Peach-$trimmedModel-$shortId".take(63)191+    }192+193+    private companion object {194+        const val PEACH_SERVICE_TYPE = "_peach._tcp"195+        const val PROTOCOL_VERSION = "1"196+    }197+}198+199+sealed class PairingServerEvent {200+    data class Started(val port: Int) : PairingServerEvent()201+    data class SyncComplete(val deviceId: String, val sas: String) : PairingServerEvent()202+    data class Error(val message: String) : PairingServerEvent()203+    data object Stopped : PairingServerEvent()204+}205+206+/* ── PAIR_IDENTITY shims (see C7-INTEGRATION.md item: promote ChirpPairing's207+   private encode/decodePairingFrame to internal and drop these) ───────────── */208+209+internal data class PairIdentity(210+    val deviceId: String,211+    val deviceName: String,212+    val deviceType: DeviceType,213+    val longTermPublicKeyHex: String,214+    val signingPublicKeyHex: String?,215+    val wsPort: Int?,216+)217+218+internal fun encodePairIdentityFrame(id: LocalChirpIdentity): ByteArray {219+    val sb = StringBuilder()220+    sb.append('{')221+    sb.append("\"type\":\"PAIR_IDENTITY\"")222+    sb.append(",\"device_id\":\"").append(jsonEscape(id.deviceId)).append('"')223+    sb.append(",\"device_name\":\"").append(jsonEscape(id.deviceName)).append('"')224+    sb.append(",\"device_type\":\"").append(id.deviceType.wireValue).append('"')225+    sb.append(",\"long_term_public_key_hex\":\"").append(id.longTermPublicKeyHex).append('"')226+    sb.append(",\"signing_public_key_hex\":\"").append(id.signingPublicKeyHex).append('"')227+    id.wsPort?.let { sb.append(",\"ws_port\":").append(it) }228+    sb.append('}')229+    return sb.toString().toByteArray(StandardCharsets.UTF_8)230+}231+232+internal fun parsePairIdentityFrame(bytes: ByteArray): PairIdentity {233+    val map = miniJsonObject(String(bytes, StandardCharsets.UTF_8))234+    require(map["type"] == "PAIR_IDENTITY") { "expected PAIR_IDENTITY frame" }235+    val deviceType = when (map["device_type"]) {236+        "extension" -> DeviceType.EXTENSION237+        "android" -> DeviceType.ANDROID238+        "ios" -> DeviceType.IOS239+        "desktop" -> DeviceType.DESKTOP240+        else -> error("device_type missing")241+    }242+    val ltpk = map["long_term_public_key_hex"] ?: error("long_term_public_key_hex missing")243+    require(ltpk.matches(Regex("^[0-9a-f]{64}$"))) { "long_term_public_key_hex not 32-byte hex" }244+    return PairIdentity(245+        deviceId = map["device_id"] ?: error("device_id missing"),246+        deviceName = map["device_name"] ?: error("device_name missing"),247+        deviceType = deviceType,248+        longTermPublicKeyHex = ltpk,249+        signingPublicKeyHex = map["signing_public_key_hex"]?.takeIf { it.isNotBlank() },250+        wsPort = map["ws_port"]?.toIntOrNull(),251+    )252+}253+254+internal fun pairIdentityToPairedDevice(id: PairIdentity): PairedDevice = PairedDevice(255+    deviceId = id.deviceId,256+    deviceName = id.deviceName,257+    deviceType = id.deviceType.wireValue,258+    longTermPublicKeyHex = id.longTermPublicKeyHex,259+    signingPublicKeyHex = id.signingPublicKeyHex,260+    trustSource = "direct",261+    wsPort = id.wsPort,262+    pairedAt = System.currentTimeMillis(),263+    lastSyncedAt = System.currentTimeMillis(),264+)265+266+/**267+ * Build a [ChirpSyncSession] over an established Noise session + frame268+ * transport, so the REAL [runChirpSyncInitiator]/[runChirpSyncResponder] can run269+ * the encrypted vault exchange. Send/receive splice the Noise cipher onto the270+ * length-prefixed frame layer; `remoteStaticPublicKey` is informational here.271+ */272+internal fun chirpSessionOver(session: NoiseNKSession, transport: SocketFrameIO): ChirpSyncSession =273+    ChirpSyncSession(274+        remoteStaticPublicKey = ByteArray(0),275+        // ChirpSyncSession.send is non-suspending (matches openChirpSyncSession);276+        // SocketFrameIO.sendBlocking writes a frame synchronously.277+        send = { plaintext -> transport.sendBlocking(session.encrypt(plaintext)) },278+        receive = { session.decrypt(transport.receive()) },279+        close = { transport.close() },280+    )281+282+private fun jsonEscape(value: String): String = buildString(value.length) {283+    for (ch in value) when (ch) {284+        '\\' -> append("\\\\"); '"' -> append("\\\"")285+        '\n' -> append("\\n"); '\r' -> append("\\r"); '\t' -> append("\\t")286+        else -> append(ch)287+    }288+}289+290+private fun miniJsonObject(text: String): Map<String, String> {291+    val trimmed = text.trim()292+    require(trimmed.startsWith("{") && trimmed.endsWith("}")) { "expected JSON object" }293+    val body = trimmed.substring(1, trimmed.length - 1)294+    val out = linkedMapOf<String, String>()295+    var i = 0296+    while (i < body.length) {297+        while (i < body.length && body[i].isWhitespace()) i++298+        if (i >= body.length || body[i] != '"') break299+        i++300+        val keyStart = i301+        while (i < body.length && body[i] != '"') i++302+        val key = body.substring(keyStart, i); i++303+        while (i < body.length && (body[i].isWhitespace() || body[i] == ':')) i++304+        val value: String305+        if (i < body.length && body[i] == '"') {306+            i++307+            val vStart = i308+            while (i < body.length && body[i] != '"') i++309+            value = body.substring(vStart, i); i++310+        } else {311+            val vStart = i312+            while (i < body.length && body[i] != ',') i++313+            value = body.substring(vStart, i).trim()314+        }315+        out[key] = value316+        while (i < body.length && body[i].isWhitespace()) i++317+        if (i < body.length && body[i] == ',') i++318+    }319+    return out320+}

view file

app/src/main/java/com/peachpasswords/sync/PairedDeviceStore.kt+116 −0
@@ -0,0 +1,116 @@1+package com.peachpasswords.sync2+3+import android.content.Context4+import androidx.security.crypto.EncryptedSharedPreferences5+import androidx.security.crypto.MasterKey6+import dagger.hilt.android.qualifiers.ApplicationContext7+import kotlinx.coroutines.channels.awaitClose8+import kotlinx.coroutines.flow.Flow9+import kotlinx.coroutines.flow.callbackFlow10+import kotlinx.serialization.builtins.ListSerializer11+import kotlinx.serialization.json.Json12+import javax.inject.Inject13+import javax.inject.Singleton14+15+/**16+ * Persistent registry of paired devices, encrypted at rest with17+ * EncryptedSharedPreferences (same construction as DuressConfigStore /18+ * LicenseRepository, v2.1.36). The whole list lives under a single key as a19+ * kotlinx.serialization JSON array of the REAL [PairedDevice] (sync package).20+ *21+ * Reconciliation with the C7 brief:22+ *  - The brief invents a fresh `PairedDevice(id, name, publicKey: ByteArray,23+ *    lastSeen, trustStatus, lastSyncAt)`. That type does NOT exist in this24+ *    shape. The real [PairedDevice] (PairedDevice.kt) keys on `deviceId`, holds25+ *    the public key as `longTermPublicKeyHex` (hex, not ByteArray), and tracks26+ *    `pairedAt` / `lastSyncedAt` / `lastKnownIp`. This store reuses it verbatim;27+ *    Base64 publicKey storage is therefore unnecessary — the hex field is the28+ *    canonical wire form already produced by ChirpPairing.frameToPairedDevice.29+ *  - The brief's `TrustStatus` enum does not exist either. The real model uses a30+ *    nullable `trustSource: String?` (e.g. "direct", "manifest"). Trust state is31+ *    expressed there. See C7-INTEGRATION.md for the trust-status delta.32+ *  - `updateLastSync` here maps to the real `lastSyncedAt` field. There is no33+ *    `lastSeen` field on the real PairedDevice; [updateLastSeen] folds into34+ *    `lastKnownIp` refresh + `lastSyncedAt` is left untouched. It is kept as a35+ *    no-op-friendly hook so callers from the brief compile; see integration note.36+ */37+@Singleton38+class PairedDeviceStore @Inject constructor(39+    @ApplicationContext context: Context,40+) {41+    private val masterKey = MasterKey.Builder(context)42+        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)43+        .build()44+45+    private val prefs = EncryptedSharedPreferences.create(46+        context,47+        PREFS_FILE,48+        masterKey,49+        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,50+        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,51+    )52+53+    private val listSerializer = ListSerializer(PairedDevice.serializer())54+55+    fun getAll(): List<PairedDevice> {56+        val raw = prefs.getString(KEY_DEVICES, null) ?: return emptyList()57+        return runCatching { json.decodeFromString(listSerializer, raw) }.getOrDefault(emptyList())58+    }59+60+    fun get(id: String): PairedDevice? = getAll().firstOrNull { it.deviceId == id }61+62+    /** Insert or replace by [PairedDevice.deviceId]. */63+    fun upsert(device: PairedDevice) {64+        val next = getAll().filterNot { it.deviceId == device.deviceId } + device65+        persist(next)66+    }67+68+    fun remove(id: String) {69+        persist(getAll().filterNot { it.deviceId == id })70+    }71+72+    fun clear() {73+        prefs.edit().remove(KEY_DEVICES).apply()74+    }75+76+    /**77+     * Refresh the device's `lastKnownIp` (the closest real analogue to the78+     * brief's `lastSeen`). No-op when the id is unknown or [ip] is null.79+     */80+    fun updateLastSeen(id: String, ip: String? = null) {81+        val current = get(id) ?: return82+        if (ip == null) return83+        upsert(current.copy(lastKnownIp = ip))84+    }85+86+    fun updateLastSync(id: String, at: Long = System.currentTimeMillis()) {87+        val current = get(id) ?: return88+        upsert(current.copy(lastSyncedAt = at))89+    }90+91+    /**92+     * Observe the full list. EncryptedSharedPreferences supports93+     * OnSharedPreferenceChangeListener, so this emits on every persist —94+     * including writes from other components in-process.95+     */96+    fun observeAll(): Flow<List<PairedDevice>> = callbackFlow {97+        trySend(getAll())98+        val listener = android.content.SharedPreferences.OnSharedPreferenceChangeListener { _, key ->99+            if (key == KEY_DEVICES || key == null) trySend(getAll())100+        }101+        prefs.registerOnSharedPreferenceChangeListener(listener)102+        awaitClose { prefs.unregisterOnSharedPreferenceChangeListener(listener) }103+    }104+105+    private fun persist(devices: List<PairedDevice>) {106+        prefs.edit()107+            .putString(KEY_DEVICES, json.encodeToString(listSerializer, devices))108+            .apply()109+    }110+111+    private companion object {112+        const val PREFS_FILE = "peach_paired_devices"113+        const val KEY_DEVICES = "paired_devices"114+        val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }115+    }116+}

view file

app/src/main/java/com/peachpasswords/sync/PairingDiscoveryClient.kt+196 −0
@@ -0,0 +1,196 @@1+package com.peachpasswords.sync2+3+import android.content.Context4+import android.net.nsd.NsdManager5+import android.net.nsd.NsdServiceInfo6+import dagger.hilt.android.qualifiers.ApplicationContext7+import kotlinx.coroutines.Dispatchers8+import kotlinx.coroutines.channels.awaitClose9+import kotlinx.coroutines.flow.Flow10+import kotlinx.coroutines.flow.callbackFlow11+import kotlinx.coroutines.flow.first12+import kotlinx.coroutines.withContext13+import kotlinx.coroutines.withTimeoutOrNull14+import java.net.InetSocketAddress15+import java.net.Socket16+import java.net.SocketTimeoutException17+import javax.inject.Inject18+import javax.inject.Singleton19+20+/**21+ * C7 TCP + mDNS pairing/sync CLIENT (initiator side). Discovers `_peach._tcp`22+ * peers, dials one, and runs the REAL initiator pipeline:23+ *   1. Noise NK initiator handshake ([noiseNKInitiator]) — pins the responder's24+ *      static public key from the mDNS TXT "pk" record.25+ *   2. PAIR_IDENTITY exchange (initiator writes first, then reads), matching26+ *      ChirpPairing.runPairingInitiator ordering.27+ *   3. SAS via the REAL [SASDerivation.derive] over the Noise handshake hash.28+ *   4. Encrypted vault sync via the REAL [runChirpSyncInitiator] over a29+ *      [ChirpSyncSession].30+ *31+ * ── Reconciliation with the brief ──────────────────────────────────────────32+ *  - `noiseNK.initiateHandshake(stream, out, remotePublicKey)` does NOT exist.33+ *    Real: `noiseNKInitiator(responderStaticPublicKey, send, receive)` →34+ *    [NoiseNKSession]. One bidirectional cipher; no `.sendCipher/.recvCipher`.35+ *  - `syncAdapter.buildRequest/applyResponse` do NOT exist. Real round driver is36+ *    [runChirpSyncInitiator] against a [ChirpSyncVaultAdapter].37+ *  - `peer.serviceInfo.host/.port`: on API < 34, [NsdServiceInfo.getHost] is38+ *    deprecated; on the supported floor it still returns the resolved39+ *    InetAddress, which we use for the dial. The resolved port is authoritative.40+ */41+@Singleton42+class PairingDiscoveryClient @Inject constructor(43+    @ApplicationContext private val ctx: Context,44+    private val deviceStore: PairedDeviceStore,45+) {46+    /**47+     * Discover nearby Peach instances via mDNS. Each found service is resolved,48+     * its TXT records parsed into a [DiscoveredPeer], and emitted. The flow runs49+     * until the collector cancels (e.g. via kotlinx `.timeout(...)` or `first`).50+     */51+    fun discoverPeers(): Flow<DiscoveredPeer> = callbackFlow {52+        val manager = ctx.getSystemService(NsdManager::class.java)53+            ?: run { close(); return@callbackFlow }54+55+        val resolveListener = object : NsdManager.ResolveListener {56+            override fun onServiceResolved(resolved: NsdServiceInfo) {57+                parsePeer(resolved)?.let { trySend(it) }58+            }59+            override fun onResolveFailed(info: NsdServiceInfo, errorCode: Int) {}60+        }61+62+        val discoveryListener = object : NsdManager.DiscoveryListener {63+            override fun onServiceFound(info: NsdServiceInfo) {64+                if (info.serviceType.trimEnd('.') == PEACH_SERVICE_TYPE) {65+                    runCatching { manager.resolveService(info, resolveListener) }66+                }67+            }68+            override fun onServiceLost(info: NsdServiceInfo) {}69+            override fun onDiscoveryStarted(serviceType: String) {}70+            override fun onDiscoveryStopped(serviceType: String) {}71+            override fun onStartDiscoveryFailed(serviceType: String, errorCode: Int) { close() }72+            override fun onStopDiscoveryFailed(serviceType: String, errorCode: Int) {}73+        }74+75+        manager.discoverServices(PEACH_SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, discoveryListener)76+        awaitClose { runCatching { manager.stopServiceDiscovery(discoveryListener) } }77+    }78+79+    /**80+     * Dial [peer], run the Noise NK initiator handshake, exchange identities and81+     * derive the SAS, then run one initiator sync round.82+     *83+     * Caller supplies the local static identity (Noise initiator does not have a84+     * static key in NK, but our PAIR_IDENTITY + the sync layer still carry our85+     * long-term identity) and a vault adapter factory.86+     */87+    suspend fun connectAndSync(88+        peer: DiscoveredPeer,89+        localIdentity: LocalChirpIdentity,90+        vaultFactory: () -> ChirpSyncVaultAdapter?,91+        connectTimeoutMs: Int = 15_000,92+    ): PairingResult = withContext(Dispatchers.IO) {93+        val socket = Socket()94+        try {95+            socket.connect(InetSocketAddress(peer.host, peer.port), connectTimeoutMs)96+            socket.soTimeout = connectTimeoutMs97+98+            val transport = SocketFrameIO(99+                input = socket.getInputStream(),100+                output = socket.getOutputStream(),101+                onClose = { withContext(Dispatchers.IO) { runCatching { socket.close() } } },102+            )103+104+            val session = try {105+                noiseNKInitiator(peer.remoteStaticPublicKey, transport::send, transport::receive)106+            } catch (e: Throwable) {107+                transport.close()108+                return@withContext PairingResult.Error(PairingError.HANDSHAKE_FAILED)109+            }110+111+            // PAIR_IDENTITY: initiator writes first, then reads (mirrors112+            // ChirpPairing.runPairingInitiator).113+            transport.send(session.encrypt(encodePairIdentityFrame(localIdentity)))114+            val theirIdentity = parsePairIdentityFrame(session.decrypt(transport.receive()))115+116+            val sas = SASDerivation.derive(session.handshakeHash)117+            val device = pairIdentityToPairedDevice(theirIdentity)118+            deviceStore.upsert(device)119+120+            // Encrypted vault sync — real initiator round.121+            val vault = vaultFactory()122+            if (vault != null) {123+                val syncSession = chirpSessionOver(session, transport)124+                val outcome = runChirpSyncInitiator(syncSession, vault)125+                if (outcome.status == SyncOutcomeStatus.COMPLETED) {126+                    deviceStore.updateLastSync(device.deviceId)127+                }128+            }129+130+            transport.close()131+            PairingResult.Success(device, sas)132+        } catch (e: SocketTimeoutException) {133+            runCatching { socket.close() }134+            PairingResult.Error(PairingError.TIMEOUT)135+        } catch (e: Throwable) {136+            runCatching { socket.close() }137+            PairingResult.Error(PairingError.IO_ERROR)138+        }139+    }140+141+    /** Discover then dial the first peer whose deviceId matches [deviceId]. */142+    suspend fun syncWithKnownDevice(143+        deviceId: String,144+        localIdentity: LocalChirpIdentity,145+        vaultFactory: () -> ChirpSyncVaultAdapter?,146+        discoveryTimeoutMs: Long = 5_000L,147+    ): PairingResult {148+        val peer = withTimeoutOrNull(discoveryTimeoutMs) {149+            discoverPeers().first { it.deviceId == deviceId }150+        } ?: return PairingResult.Error(PairingError.NOT_FOUND)151+        return connectAndSync(peer, localIdentity, vaultFactory)152+    }153+154+    private fun parsePeer(info: NsdServiceInfo): DiscoveredPeer? {155+        val attrs = info.attributes ?: return null156+        val pkHex = attrs["pk"]?.let { String(it, Charsets.UTF_8) } ?: return null157+        if (!pkHex.matches(Regex("^[0-9a-f]{64}$"))) return null158+        val deviceId = attrs["id"]?.let { String(it, Charsets.UTF_8) } ?: return null159+        @Suppress("DEPRECATION")160+        val host = info.host?.hostAddress ?: return null161+        return DiscoveredPeer(162+            deviceId = deviceId,163+            deviceName = info.serviceName,164+            host = host,165+            port = info.port,166+            remoteStaticPublicKey = hexToPubkey(pkHex),167+        )168+    }169+170+    private companion object {171+        const val PEACH_SERVICE_TYPE = "_peach._tcp"172+    }173+}174+175+data class DiscoveredPeer(176+    val deviceId: String,177+    val deviceName: String,178+    val host: String,179+    val port: Int,180+    /** Noise NK responder static public key, parsed from TXT "pk". */181+    val remoteStaticPublicKey: ByteArray,182+)183+184+sealed class PairingResult {185+    data class Success(val device: PairedDevice, val sasCode: String) : PairingResult()186+    data class Error(val reason: PairingError) : PairingResult()187+}188+189+enum class PairingError {190+    NOT_FOUND,191+    HANDSHAKE_FAILED,192+    VERSION_MISMATCH,193+    ALREADY_PAIRED,194+    TIMEOUT,195+    IO_ERROR,196+}

view file

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

view file

app/src/test/java/com/peachpasswords/sync/C7ChirpTransportTest.kt+179 −0
@@ -0,0 +1,179 @@1+package com.peachpasswords.sync2+3+import kotlinx.coroutines.Dispatchers4+import kotlinx.coroutines.launch5+import kotlinx.coroutines.runBlocking6+import kotlinx.serialization.builtins.ListSerializer7+import kotlinx.serialization.json.Json8+import org.bouncycastle.crypto.params.X25519PrivateKeyParameters9+import org.junit.Assert.assertArrayEquals10+import org.junit.Assert.assertEquals11+import org.junit.Assert.assertNotNull12+import org.junit.Assert.assertTrue13+import org.junit.Test14+import java.io.PipedInputStream15+import java.io.PipedOutputStream16+import java.security.SecureRandom17+18+/**19+ * C7 transport tests. Mirrors the existing ChirpSyncTransportTest idiom: plain20+ * JUnit + runBlocking, no Robolectric. PairedDeviceStore itself needs an Android21+ * Context (EncryptedSharedPreferences), so its persistence is exercised by the22+ * orchestrator's instrumentation tests; here we test the pure-JVM serialization23+ * layer the store round-trips through (test 1) plus its upsert/replace semantics24+ * against an in-memory list (test 2), the frame codec (test 3), the full25+ * Noise-NK-over-frames exchange the server/client share (test 4), and the26+ * timeout/error path (test 5).27+ */28+class C7ChirpTransportTest {29+30+    private val json = Json { encodeDefaults = true; ignoreUnknownKeys = true }31+    private val listSerializer = ListSerializer(PairedDevice.serializer())32+33+    private fun newKeyPair(): Pair<ByteArray, ByteArray> {34+        val priv = X25519PrivateKeyParameters(SecureRandom())35+        return priv.encoded to priv.generatePublicKey().encoded36+    }37+38+    private fun device(id: String, name: String = "Peer") = PairedDevice(39+        deviceId = id,40+        deviceName = name,41+        deviceType = "android",42+        longTermPublicKeyHex = "ab".repeat(32),43+        trustSource = "direct",44+        pairedAt = 1_000L,45+        lastSyncedAt = null,46+    )47+48+    /** Test 1: PairedDevice list survives JSON round-trip (the store's wire form). */49+    @Test50+    fun `paired device list round-trips through json`() {51+        val devices = listOf(device("a", "Alice"), device("b", "Bob"))52+        val encoded = json.encodeToString(listSerializer, devices)53+        val decoded = json.decodeFromString(listSerializer, encoded)54+        assertEquals(devices, decoded)55+        assertEquals("Alice", decoded[0].deviceName)56+        assertEquals("ab".repeat(32), decoded[1].longTermPublicKeyHex)57+    }58+59+    /** Test 2: upsert replaces an existing entry by deviceId (store semantics). */60+    @Test61+    fun `upsert by deviceId replaces rather than duplicates`() {62+        // Mirror PairedDeviceStore.upsert's pure list transform.63+        fun upsert(list: List<PairedDevice>, d: PairedDevice) =64+            list.filterNot { it.deviceId == d.deviceId } + d65+66+        var list = listOf(device("a", "Alice"))67+        list = upsert(list, device("b", "Bob"))68+        assertEquals(2, list.size)69+        list = upsert(list, device("a", "Alice-renamed"))70+        assertEquals(2, list.size)71+        assertEquals("Alice-renamed", list.first { it.deviceId == "a" }.deviceName)72+    }73+74+    /** Test 3: writeFrame/readFrame round-trip across payload sizes. */75+    @Test76+    fun `frame codec round-trips for various sizes`() {77+        for (size in intArrayOf(0, 1, 31, 64, 1500, 65_537)) {78+            val payload = ByteArray(size) { (it % 251).toByte() }79+            val pin = PipedInputStream(1 shl 18)80+            val pout = PipedOutputStream(pin)81+            writeFrame(pout, payload)82+            val read = readFrame(pin)83+            assertArrayEquals("size=$size", payload, read)84+        }85+    }86+87+    /**88+     * Test 4: a full Noise NK handshake + identity frame exchange over a Piped89+     * socket pair — the exact wire the server (responder) and client (initiator)90+     * share. Proves the handshake completes, both sides derive the SAME SAS, and91+     * an encrypted identity frame decrypts correctly. No real network.92+     */93+    @Test94+    fun `noise NK handshake over frames yields matching SAS and decodable identity`() = runBlocking {95+        val (responderPriv, responderPub) = newKeyPair()96+97+        // Cross-wired pipes: initiator's out -> responder's in and vice versa.98+        val i2r = PipedInputStream(1 shl 18); val i2rOut = PipedOutputStream(i2r)99+        val r2i = PipedInputStream(1 shl 18); val r2iOut = PipedOutputStream(r2i)100+101+        val initiator = SocketFrameIO(input = r2i, output = i2rOut)102+        val responder = SocketFrameIO(input = i2r, output = r2iOut)103+104+        val localId = LocalChirpIdentity(105+            deviceId = "client-1",106+            deviceName = "Client",107+            deviceType = DeviceType.ANDROID,108+            longTermPublicKeyHex = "cd".repeat(32),109+            signingPublicKeyHex = "ef".repeat(32),110+        )111+        val serverId = localId.copy(deviceId = "server-1", deviceName = "Server")112+113+        var initiatorSas: String? = null114+        var responderSas: String? = null115+        var receivedByServer: PairIdentity? = null116+117+        val responderJob = launch(Dispatchers.IO) {118+            val session = noiseNKResponder(responderPriv, responderPub, responder::send, responder::receive)119+            receivedByServer = parsePairIdentityFrame(session.decrypt(responder.receive()))120+            responder.send(session.encrypt(encodePairIdentityFrame(serverId)))121+            responderSas = SASDerivation.derive(session.handshakeHash)122+        }123+124+        val initiatorJob = launch(Dispatchers.IO) {125+            val session = noiseNKInitiator(responderPub, initiator::send, initiator::receive)126+            initiator.send(session.encrypt(encodePairIdentityFrame(localId)))127+            session.decrypt(initiator.receive()) // server identity (discarded here)128+            initiatorSas = SASDerivation.derive(session.handshakeHash)129+        }130+131+        initiatorJob.join()132+        responderJob.join()133+134+        assertNotNull(initiatorSas)135+        assertEquals("both sides derive the same SAS", initiatorSas, responderSas)136+        assertEquals("client-1", receivedByServer?.deviceId)137+        assertEquals("cd".repeat(32), receivedByServer?.longTermPublicKeyHex)138+    }139+140+    /**141+     * Test 5: a wrong responder static key fails the initiator handshake — the142+     * NK auth tag rejects a MITM / mismatched key, which connectAndSync surfaces143+     * as PairingError.HANDSHAKE_FAILED.144+     */145+    @Test146+    fun `handshake fails when responder static key is wrong`() = runBlocking {147+        val (responderPriv, responderPub) = newKeyPair()148+        val (_, wrongPub) = newKeyPair()149+150+        val i2r = PipedInputStream(1 shl 18); val i2rOut = PipedOutputStream(i2r)151+        val r2i = PipedInputStream(1 shl 18); val r2iOut = PipedOutputStream(r2i)152+        val initiator = SocketFrameIO(input = r2i, output = i2rOut)153+        val responder = SocketFrameIO(input = i2r, output = r2iOut)154+155+        // The initiator pins the WRONG static key, so the responder rejects msg1 (its156+        // own ES differs) and never sends msg2. Close the responder's write end on157+        // failure so the initiator's receive() hits EOF and fails fast instead of158+        // blocking forever — the raw-socket analogue is the soTimeout connectAndSync159+        // surfaces as an IO error. (A coroutine timeout can't interrupt the blocking160+        // pipe read, so EOF is the deterministic way to unblock it.)161+        val responderJob = launch(Dispatchers.IO) {162+            runCatching { noiseNKResponder(responderPriv, responderPub, responder::send, responder::receive) }163+            runCatching { r2iOut.close() }164+        }165+166+        var initiatorFailed = false167+        val initiatorJob = launch(Dispatchers.IO) {168+            try {169+                noiseNKInitiator(wrongPub, initiator::send, initiator::receive)170+            } catch (_: Throwable) {171+                initiatorFailed = true172+            }173+        }174+175+        initiatorJob.join()176+        responderJob.join()177+        assertTrue("a wrong responder static key must fail the initiator handshake", initiatorFailed)178+    }179+}

view file