PairingDiscoveryClient.kt

8.2 KB · raw

1package com.peachpasswords.sync23import android.content.Context4import android.net.nsd.NsdManager5import android.net.nsd.NsdServiceInfo6import dagger.hilt.android.qualifiers.ApplicationContext7import kotlinx.coroutines.Dispatchers8import kotlinx.coroutines.channels.awaitClose9import kotlinx.coroutines.flow.Flow10import kotlinx.coroutines.flow.callbackFlow11import kotlinx.coroutines.flow.first12import kotlinx.coroutines.withContext13import kotlinx.coroutines.withTimeoutOrNull14import java.net.InetSocketAddress15import java.net.Socket16import java.net.SocketTimeoutException17import javax.inject.Inject18import javax.inject.Singleton1920/**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@Singleton42class 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 }5455        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        }6162        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        }7475        manager.discoverServices(PEACH_SERVICE_TYPE, NsdManager.PROTOCOL_DNS_SD, discoveryListener)76        awaitClose { runCatching { manager.stopServiceDiscovery(discoveryListener) } }77    }7879    /**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 = connectTimeoutMs9798            val transport = SocketFrameIO(99                input = socket.getInputStream(),100                output = socket.getOutputStream(),101                onClose = { withContext(Dispatchers.IO) { runCatching { socket.close() } } },102            )103104            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            }110111            // 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()))115116            val sas = SASDerivation.derive(session.handshakeHash)117            val device = pairIdentityToPairedDevice(theirIdentity)118            deviceStore.upsert(device)119120            // 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            }129130            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    }140141    /** 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    }153154    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    }169170    private companion object {171        const val PEACH_SERVICE_TYPE = "_peach._tcp"172    }173}174175data 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)183184sealed class PairingResult {185    data class Success(val device: PairedDevice, val sasCode: String) : PairingResult()186    data class Error(val reason: PairingError) : PairingResult()187}188189enum class PairingError {190    NOT_FOUND,191    HANDSHAKE_FAILED,192    VERSION_MISMATCH,193    ALREADY_PAIRED,194    TIMEOUT,195    IO_ERROR,196}