MdnsPairingServer.kt

14.1 KB · raw

1package com.peachpasswords.sync23import android.content.Context4import android.net.nsd.NsdManager5import android.net.nsd.NsdServiceInfo6import android.os.Build7import dagger.hilt.android.qualifiers.ApplicationContext8import kotlinx.coroutines.CoroutineScope9import kotlinx.coroutines.Dispatchers10import kotlinx.coroutines.channels.awaitClose11import kotlinx.coroutines.flow.Flow12import kotlinx.coroutines.flow.callbackFlow13import kotlinx.coroutines.isActive14import kotlinx.coroutines.launch15import kotlinx.coroutines.withContext16import org.json.JSONObject17import java.net.ServerSocket18import java.net.Socket19import java.nio.charset.StandardCharsets20import javax.inject.Inject21import javax.inject.Singleton2223/**24 * C7 TCP + mDNS reconnect SERVER (responder side).25 *26 * Listens on an OS-assigned TCP port, advertises itself over mDNS as27 * `_peach._tcp`, and for each inbound connection runs the REAL responder28 * pipeline:29 *   1. Resolve PEACH_RECONNECT against paired local state, then run Noise KK30 *      over length-prefixed frames ([SocketFrameIO]).31 *   2. PAIR_IDENTITY frame exchange — encoded/decoded with the SAME private32 *      helpers ChirpPairing uses; since those are file-private there, this draft33 *      re-derives the identity frame via [LocalChirpIdentity] and a minimal34 *      JSON, and parses the peer's via [parsePairIdentityFrame]. See35 *      C7-INTEGRATION.md: the cleanest integration promotes ChirpPairing's36 *      encode/decodePairingFrame to internal and deletes these shims.37 *   3. Encrypted vault sync via the REAL [runChirpSyncResponder] over a38 *      [ChirpSyncSession] backed by the Noise session.39 *40 * Reconnect is strictly KK. The opaque selector capability is resolved against41 * local paired state before the handshake, both static keys are authenticated42 * by the named pattern, and failure never falls back to first-pair NK.43 *  - The brief calls `syncAdapter.buildResponse/applyRequest`. NO SUCH METHODS.44 *    The real per-round protocol is [runChirpSyncResponder]; the adapter is a45 *    [ChirpSyncVaultAdapter] ([VaultSyncAdapter]) with getEncryptedEntries/46 *    applyEntries/etc. We drive the whole round, not single request/response.47 */48@Singleton49class MdnsPairingServer @Inject constructor(50    private val deviceStore: PairedDeviceStore,51    @ApplicationContext private val ctx: Context,52) {53    private var serverSocket: ServerSocket? = null54    private var nsdManager: NsdManager? = null55    private var registrationListener: NsdManager.RegistrationListener? = null5657    /**58     * Start listening + advertise + accept. Caller supplies:59     *  - [ourStaticPrivateKey]/[ourStaticPublicKey]: the device's long-term sync60     *    identity (from [deriveSyncIdentityKeypair]) — the KK responder static61     *    key, also published in mDNS TXT "pk".62     *  - [vaultFactory]: builds a fresh [ChirpSyncVaultAdapter] per connection63     *    (the vault may lock/unlock between connections).64     *  - [localIdentity]: our PAIR_IDENTITY payload.65     */66    fun start(67        scope: CoroutineScope,68        ourStaticPrivateKey: ByteArray,69        ourStaticPublicKey: ByteArray,70        localIdentity: LocalChirpIdentity,71        vaultFactory: () -> ChirpSyncVaultAdapter?,72    ): Flow<PairingServerEvent> = callbackFlow {73        val socket = withContext(Dispatchers.IO) { ServerSocket(0) }74        serverSocket = socket75        val port = socket.localPort7677        registerMdns(port, ourStaticPublicKey, localIdentity.deviceId)78        trySend(PairingServerEvent.Started(port))7980        val acceptJob = scope.launch(Dispatchers.IO) {81            while (isActive && !socket.isClosed) {82                val client = try {83                    socket.accept()84                } catch (_: Throwable) {85                    break86                }87                launch {88                    val event = handleClient(client, ourStaticPrivateKey, ourStaticPublicKey, localIdentity, vaultFactory)89                    trySend(event)90                }91            }92        }9394        awaitClose {95            acceptJob.cancel()96            stop()97        }98    }99100    fun stop() {101        registrationListener?.let { l -> runCatching { nsdManager?.unregisterService(l) } }102        registrationListener = null103        runCatching { serverSocket?.close() }104        serverSocket = null105    }106107    private suspend fun handleClient(108        socket: Socket,109        ourStaticPrivateKey: ByteArray,110        ourStaticPublicKey: ByteArray,111        localIdentity: LocalChirpIdentity,112        vaultFactory: () -> ChirpSyncVaultAdapter?,113    ): PairingServerEvent {114        val transport = SocketFrameIO(115            input = socket.getInputStream(),116            output = socket.getOutputStream(),117            onClose = { withContext(Dispatchers.IO) { runCatching { socket.close() } } },118        )119        return try {120            val selector = JSONObject(String(transport.receive(), Charsets.UTF_8))121            require(selector.optString("type") == "PEACH_RECONNECT") { "expected PEACH_RECONNECT" }122            val rendezvousId = selector.optString("rendezvous_id")123            val known = Rendezvous.resolvePeer(deviceStore.getAll(), rendezvousId)124                ?: throw IllegalArgumentException("unknown reconnect peer")125            val initiatorKeyHex = known.longTermPublicKeyHex126                ?: throw IllegalArgumentException("known peer missing static key")127            val initiatorKey = hexToPubkey(initiatorKeyHex)128129            val session = noiseKKResponder(130                ourStaticPrivateKey,131                ourStaticPublicKey,132                initiatorKey,133                transport::send,134                transport::receive,135            )136137            // 2. PAIR_IDENTITY exchange (responder reads first, then answers) —138            //    mirrors ChirpPairing.runPairingResponder ordering.139            val theirIdentity = parsePairIdentityFrame(session.decrypt(transport.receive()))140            require(theirIdentity.deviceId == known.deviceId) { "peer device id changed after KK" }141            require(142                theirIdentity.longTermPublicKeyHex.equals(initiatorKeyHex, ignoreCase = true),143            ) { "peer identity does not match authenticated KK key" }144            transport.send(session.encrypt(encodePairIdentityFrame(localIdentity)))145146            val sas = SASDerivation.derive(session.handshakeHash)147            // 3. Encrypted vault sync — real responder round over a ChirpSyncSession.148            val vault = vaultFactory()149            if (vault != null) {150                vault.bindAuthenticatedPeer(known)151                val syncSession = chirpSessionOver(session, transport, initiatorKey)152                val outcome = runChirpSyncResponder(syncSession, vault)153                if (outcome.status == SyncOutcomeStatus.COMPLETED) {154                    deviceStore.updateLastSync(known.deviceId)155                }156            }157            transport.close()158            PairingServerEvent.SyncComplete(known.deviceId, sas)159        } catch (e: Throwable) {160            transport.close()161            PairingServerEvent.Error(e.message ?: "pairing_server_error")162        }163    }164165    private fun registerMdns(port: Int, staticPub: ByteArray, deviceId: String) {166        val manager = ctx.getSystemService(NsdManager::class.java) ?: return167        nsdManager = manager168        val info = NsdServiceInfo().apply {169            serviceName = buildServiceName(deviceId)170            serviceType = PEACH_SERVICE_TYPE171            this.port = port172            // NsdServiceInfo.setAttribute is API 21+; minSdk is 26.173            setAttribute("v", PROTOCOL_VERSION)174            setAttribute("pk", pubkeyToHex(staticPub))175            setAttribute("id", deviceId)176        }177        val listener = object : NsdManager.RegistrationListener {178            override fun onServiceRegistered(info: NsdServiceInfo) {}179            override fun onRegistrationFailed(info: NsdServiceInfo, errorCode: Int) {}180            override fun onServiceUnregistered(info: NsdServiceInfo) {}181            override fun onUnregistrationFailed(info: NsdServiceInfo, errorCode: Int) {}182        }183        registrationListener = listener184        manager.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)185    }186187    private fun buildServiceName(deviceId: String): String {188        val shortId = deviceId.take(8)189        val model = Build.MODEL.replace(Regex("[^A-Za-z0-9-]"), "")190        // mDNS service-instance names are capped at 63 bytes; reserve room for191        // the "Peach-" prefix and the "-${shortId}" suffix.192        val maxModel = 63 - "Peach-".length - 1 - shortId.length193        val trimmedModel = if (model.length > maxModel && maxModel > 0) model.take(maxModel) else model194        return "Peach-$trimmedModel-$shortId".take(63)195    }196197    private companion object {198        const val PEACH_SERVICE_TYPE = "_peach._tcp"199        const val PROTOCOL_VERSION = "1"200    }201}202203sealed class PairingServerEvent {204    data class Started(val port: Int) : PairingServerEvent()205    data class SyncComplete(val deviceId: String, val sas: String) : PairingServerEvent()206    data class Error(val message: String) : PairingServerEvent()207    data object Stopped : PairingServerEvent()208}209210/* ── PAIR_IDENTITY shims (see C7-INTEGRATION.md item: promote ChirpPairing's211   private encode/decodePairingFrame to internal and drop these) ───────────── */212213internal data class PairIdentity(214    val deviceId: String,215    val deviceName: String,216    val deviceType: DeviceType,217    val longTermPublicKeyHex: String,218    val signingPublicKeyHex: String?,219    val wsPort: Int?,220    val relayUrl: String?,221)222223internal fun encodePairIdentityFrame(id: LocalChirpIdentity): ByteArray {224    val sb = StringBuilder()225    sb.append('{')226    sb.append("\"type\":\"PAIR_IDENTITY\"")227    sb.append(",\"device_id\":\"").append(jsonEscape(id.deviceId)).append('"')228    sb.append(",\"device_name\":\"").append(jsonEscape(id.deviceName)).append('"')229    sb.append(",\"device_type\":\"").append(id.deviceType.wireValue).append('"')230    sb.append(",\"long_term_public_key_hex\":\"").append(id.longTermPublicKeyHex).append('"')231    sb.append(",\"signing_public_key_hex\":\"").append(id.signingPublicKeyHex).append('"')232    id.wsPort?.let { sb.append(",\"ws_port\":").append(it) }233    sb.append(",\"relay_url\":\"").append(jsonEscape(id.relayUrl)).append('"')234    sb.append('}')235    return sb.toString().toByteArray(StandardCharsets.UTF_8)236}237238internal fun parsePairIdentityFrame(bytes: ByteArray): PairIdentity {239    val map = miniJsonObject(String(bytes, StandardCharsets.UTF_8))240    require(map["type"] == "PAIR_IDENTITY") { "expected PAIR_IDENTITY frame" }241    val deviceType = when (map["device_type"]) {242        "extension" -> DeviceType.EXTENSION243        "android" -> DeviceType.ANDROID244        "ios" -> DeviceType.IOS245        else -> error("device_type missing")246    }247    val ltpk = map["long_term_public_key_hex"] ?: error("long_term_public_key_hex missing")248    require(ltpk.matches(Regex("^[0-9a-f]{64}$"))) { "long_term_public_key_hex not 32-byte hex" }249    return PairIdentity(250        deviceId = map["device_id"] ?: error("device_id missing"),251        deviceName = map["device_name"] ?: error("device_name missing"),252        deviceType = deviceType,253        longTermPublicKeyHex = ltpk,254        signingPublicKeyHex = map["signing_public_key_hex"]?.takeIf { it.isNotBlank() },255        wsPort = map["ws_port"]?.toIntOrNull(),256        relayUrl = map["relay_url"]?.let(Rendezvous::normalizeRelayUrl),257    )258}259260internal fun pairIdentityToPairedDevice(id: PairIdentity): PairedDevice = PairedDevice(261    deviceId = id.deviceId,262    deviceName = id.deviceName,263    deviceType = id.deviceType.wireValue,264    longTermPublicKeyHex = id.longTermPublicKeyHex,265    signingPublicKeyHex = id.signingPublicKeyHex,266    trustSource = "direct",267    wsPort = id.wsPort,268    relayUrl = id.relayUrl,269    pairedAt = System.currentTimeMillis(),270    lastSyncedAt = System.currentTimeMillis(),271)272273/**274 * Build a [ChirpSyncSession] over an established Noise session + frame275 * transport, so the REAL [runChirpSyncInitiator]/[runChirpSyncResponder] can run276 * the encrypted vault exchange. Send/receive splice the Noise cipher onto the277 * length-prefixed frame layer; `remoteStaticPublicKey` is informational here.278 */279internal fun chirpSessionOver(280    session: NoiseNKSession,281    transport: SocketFrameIO,282    remoteStaticPublicKey: ByteArray = ByteArray(0),283): ChirpSyncSession =284    ChirpSyncSession(285        remoteStaticPublicKey = remoteStaticPublicKey.copyOf(),286        // ChirpSyncSession.send is non-suspending;287        // SocketFrameIO.sendBlocking writes a frame synchronously.288        send = { plaintext -> transport.sendBlocking(session.encrypt(plaintext)) },289        receive = { session.decrypt(transport.receive()) },290        close = { transport.close() },291    )292293private fun jsonEscape(value: String): String = buildString(value.length) {294    for (ch in value) when (ch) {295        '\\' -> append("\\\\"); '"' -> append("\\\"")296        '\n' -> append("\\n"); '\r' -> append("\\r"); '\t' -> append("\\t")297        else -> append(ch)298    }299}300301private fun miniJsonObject(text: String): Map<String, String> {302    val trimmed = text.trim()303    require(trimmed.startsWith("{") && trimmed.endsWith("}")) { "expected JSON object" }304    val body = trimmed.substring(1, trimmed.length - 1)305    val out = linkedMapOf<String, String>()306    var i = 0307    while (i < body.length) {308        while (i < body.length && body[i].isWhitespace()) i++309        if (i >= body.length || body[i] != '"') break310        i++311        val keyStart = i312        while (i < body.length && body[i] != '"') i++313        val key = body.substring(keyStart, i); i++314        while (i < body.length && (body[i].isWhitespace() || body[i] == ':')) i++315        val value: String316        if (i < body.length && body[i] == '"') {317            i++318            val vStart = i319            while (i < body.length && body[i] != '"') i++320            value = body.substring(vStart, i); i++321        } else {322            val vStart = i323            while (i < body.length && body[i] != ',') i++324            value = body.substring(vStart, i).trim()325        }326        out[key] = value327        while (i < body.length && body[i].isWhitespace()) i++328        if (i < body.length && body[i] == ',') i++329    }330    return out331}