PairingTransport.kt

8.6 KB · raw

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