PairingServer.kt

13.8 KB · raw

1// Intended source path: app/src/main/java/com/peachpasswords/sync/PairingServer.kt2package com.peachpasswords.sync34import android.content.Context5import android.net.nsd.NsdManager6import android.net.nsd.NsdServiceInfo7import android.os.Build8import dagger.hilt.android.qualifiers.ApplicationContext9import kotlinx.coroutines.CoroutineScope10import kotlinx.coroutines.Dispatchers11import kotlinx.coroutines.channels.awaitClose12import kotlinx.coroutines.flow.Flow13import kotlinx.coroutines.flow.callbackFlow14import kotlinx.coroutines.isActive15import kotlinx.coroutines.launch16import kotlinx.coroutines.withContext17import java.net.ServerSocket18import java.net.Socket19import java.nio.charset.StandardCharsets20import javax.inject.Inject21import javax.inject.Singleton2223/**24 * C7 TCP + mDNS pairing/sync 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. Noise NK responder handshake ([noiseNKResponder]) over length-prefixed30 *      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 * ── Reconciliation with the brief ──────────────────────────────────────────41 *  - The brief calls `noiseNK.acceptHandshake(stream, out)` returning an object42 *    with `.sendCipher/.recvCipher/.handshakeHash`. NO SUCH API EXISTS. The real43 *    handshake is the suspend free function `noiseNKResponder(ourPriv, ourPub,44 *    send, receive)` returning a single [NoiseNKSession] (encrypt/decrypt/45 *    handshakeHash) — one bidirectional cipher, not split send/recv ciphers.46 *  - NK is a responder-static / no-initiator-static pattern: the responder needs47 *    its OWN static keypair, and the initiator must already know the responder's48 *    static public key. We use the device's long-term sync identity49 *    ([deriveSyncIdentityKeypair]) as that static key and publish its public half50 *    in the mDNS TXT "pk" record so initiators can pin it.51 *  - The brief calls `syncAdapter.buildResponse/applyRequest`. NO SUCH METHODS.52 *    The real per-round protocol is [runChirpSyncResponder]; the adapter is a53 *    [ChirpSyncVaultAdapter] ([VaultSyncAdapter]) with getEncryptedEntries/54 *    applyEntries/etc. We drive the whole round, not single request/response.55 */56@Singleton57class PairingServer @Inject constructor(58    private val deviceStore: PairedDeviceStore,59    @ApplicationContext private val ctx: Context,60) {61    private var serverSocket: ServerSocket? = null62    private var nsdManager: NsdManager? = null63    private var registrationListener: NsdManager.RegistrationListener? = null6465    /**66     * Start listening + advertise + accept. Caller supplies:67     *  - [ourStaticPrivateKey]/[ourStaticPublicKey]: the device's long-term sync68     *    identity (from [deriveSyncIdentityKeypair]) — the Noise NK responder69     *    static key, also published in mDNS TXT "pk".70     *  - [vaultFactory]: builds a fresh [ChirpSyncVaultAdapter] per connection71     *    (the vault may lock/unlock between connections).72     *  - [localIdentity]: our PAIR_IDENTITY payload.73     */74    fun start(75        scope: CoroutineScope,76        ourStaticPrivateKey: ByteArray,77        ourStaticPublicKey: ByteArray,78        localIdentity: LocalChirpIdentity,79        vaultFactory: () -> ChirpSyncVaultAdapter?,80    ): Flow<PairingServerEvent> = callbackFlow {81        val socket = withContext(Dispatchers.IO) { ServerSocket(0) }82        serverSocket = socket83        val port = socket.localPort8485        registerMdns(port, ourStaticPublicKey, localIdentity.deviceId)86        trySend(PairingServerEvent.Started(port))8788        val acceptJob = scope.launch(Dispatchers.IO) {89            while (isActive && !socket.isClosed) {90                val client = try {91                    socket.accept()92                } catch (_: Throwable) {93                    break94                }95                launch {96                    val event = handleClient(client, ourStaticPrivateKey, ourStaticPublicKey, localIdentity, vaultFactory)97                    trySend(event)98                }99            }100        }101102        awaitClose {103            acceptJob.cancel()104            stop()105        }106    }107108    fun stop() {109        registrationListener?.let { l -> runCatching { nsdManager?.unregisterService(l) } }110        registrationListener = null111        runCatching { serverSocket?.close() }112        serverSocket = null113    }114115    private suspend fun handleClient(116        socket: Socket,117        ourStaticPrivateKey: ByteArray,118        ourStaticPublicKey: ByteArray,119        localIdentity: LocalChirpIdentity,120        vaultFactory: () -> ChirpSyncVaultAdapter?,121    ): PairingServerEvent {122        val transport = SocketFrameIO(123            input = socket.getInputStream(),124            output = socket.getOutputStream(),125            onClose = { withContext(Dispatchers.IO) { runCatching { socket.close() } } },126        )127        return try {128            // 1. Noise NK responder handshake — real free function, single session.129            val session = noiseNKResponder(130                ourStaticPrivateKey,131                ourStaticPublicKey,132                transport::send,133                transport::receive,134            )135136            // 2. PAIR_IDENTITY exchange (responder reads first, then answers) —137            //    mirrors ChirpPairing.runPairingResponder ordering.138            val theirIdentity = parsePairIdentityFrame(session.decrypt(transport.receive()))139            transport.send(session.encrypt(encodePairIdentityFrame(localIdentity)))140141            val sas = SASDerivation.derive(session.handshakeHash)142            val device = pairIdentityToPairedDevice(theirIdentity)143            deviceStore.upsert(device)144145            // 3. Encrypted vault sync — real responder round over a ChirpSyncSession.146            val vault = vaultFactory()147            if (vault != null) {148                val syncSession = chirpSessionOver(session, transport)149                val outcome = runChirpSyncResponder(syncSession, vault)150                if (outcome.status == SyncOutcomeStatus.COMPLETED) {151                    deviceStore.updateLastSync(device.deviceId)152                }153            }154            transport.close()155            PairingServerEvent.SyncComplete(device.deviceId, sas)156        } catch (e: Throwable) {157            transport.close()158            PairingServerEvent.Error(e.message ?: "pairing_server_error")159        }160    }161162    private fun registerMdns(port: Int, staticPub: ByteArray, deviceId: String) {163        val manager = ctx.getSystemService(NsdManager::class.java) ?: return164        nsdManager = manager165        val info = NsdServiceInfo().apply {166            serviceName = buildServiceName(deviceId)167            serviceType = PEACH_SERVICE_TYPE168            this.port = port169            // NsdServiceInfo.setAttribute is API 21+; minSdk is 26.170            setAttribute("v", PROTOCOL_VERSION)171            setAttribute("pk", pubkeyToHex(staticPub))172            setAttribute("id", deviceId)173        }174        val listener = object : NsdManager.RegistrationListener {175            override fun onServiceRegistered(info: NsdServiceInfo) {}176            override fun onRegistrationFailed(info: NsdServiceInfo, errorCode: Int) {}177            override fun onServiceUnregistered(info: NsdServiceInfo) {}178            override fun onUnregistrationFailed(info: NsdServiceInfo, errorCode: Int) {}179        }180        registrationListener = listener181        manager.registerService(info, NsdManager.PROTOCOL_DNS_SD, listener)182    }183184    private fun buildServiceName(deviceId: String): String {185        val shortId = deviceId.take(8)186        val model = Build.MODEL.replace(Regex("[^A-Za-z0-9-]"), "")187        // mDNS service-instance names are capped at 63 bytes; reserve room for188        // the "Peach-" prefix and the "-${shortId}" suffix.189        val maxModel = 63 - "Peach-".length - 1 - shortId.length190        val trimmedModel = if (model.length > maxModel && maxModel > 0) model.take(maxModel) else model191        return "Peach-$trimmedModel-$shortId".take(63)192    }193194    private companion object {195        const val PEACH_SERVICE_TYPE = "_peach._tcp"196        const val PROTOCOL_VERSION = "1"197    }198}199200sealed class PairingServerEvent {201    data class Started(val port: Int) : PairingServerEvent()202    data class SyncComplete(val deviceId: String, val sas: String) : PairingServerEvent()203    data class Error(val message: String) : PairingServerEvent()204    data object Stopped : PairingServerEvent()205}206207/* ── PAIR_IDENTITY shims (see C7-INTEGRATION.md item: promote ChirpPairing's208   private encode/decodePairingFrame to internal and drop these) ───────────── */209210internal data class PairIdentity(211    val deviceId: String,212    val deviceName: String,213    val deviceType: DeviceType,214    val longTermPublicKeyHex: String,215    val signingPublicKeyHex: String?,216    val wsPort: Int?,217)218219internal fun encodePairIdentityFrame(id: LocalChirpIdentity): ByteArray {220    val sb = StringBuilder()221    sb.append('{')222    sb.append("\"type\":\"PAIR_IDENTITY\"")223    sb.append(",\"device_id\":\"").append(jsonEscape(id.deviceId)).append('"')224    sb.append(",\"device_name\":\"").append(jsonEscape(id.deviceName)).append('"')225    sb.append(",\"device_type\":\"").append(id.deviceType.wireValue).append('"')226    sb.append(",\"long_term_public_key_hex\":\"").append(id.longTermPublicKeyHex).append('"')227    sb.append(",\"signing_public_key_hex\":\"").append(id.signingPublicKeyHex).append('"')228    id.wsPort?.let { sb.append(",\"ws_port\":").append(it) }229    sb.append('}')230    return sb.toString().toByteArray(StandardCharsets.UTF_8)231}232233internal fun parsePairIdentityFrame(bytes: ByteArray): PairIdentity {234    val map = miniJsonObject(String(bytes, StandardCharsets.UTF_8))235    require(map["type"] == "PAIR_IDENTITY") { "expected PAIR_IDENTITY frame" }236    val deviceType = when (map["device_type"]) {237        "extension" -> DeviceType.EXTENSION238        "android" -> DeviceType.ANDROID239        "ios" -> DeviceType.IOS240        "desktop" -> DeviceType.DESKTOP241        else -> error("device_type missing")242    }243    val ltpk = map["long_term_public_key_hex"] ?: error("long_term_public_key_hex missing")244    require(ltpk.matches(Regex("^[0-9a-f]{64}$"))) { "long_term_public_key_hex not 32-byte hex" }245    return PairIdentity(246        deviceId = map["device_id"] ?: error("device_id missing"),247        deviceName = map["device_name"] ?: error("device_name missing"),248        deviceType = deviceType,249        longTermPublicKeyHex = ltpk,250        signingPublicKeyHex = map["signing_public_key_hex"]?.takeIf { it.isNotBlank() },251        wsPort = map["ws_port"]?.toIntOrNull(),252    )253}254255internal fun pairIdentityToPairedDevice(id: PairIdentity): PairedDevice = PairedDevice(256    deviceId = id.deviceId,257    deviceName = id.deviceName,258    deviceType = id.deviceType.wireValue,259    longTermPublicKeyHex = id.longTermPublicKeyHex,260    signingPublicKeyHex = id.signingPublicKeyHex,261    trustSource = "direct",262    wsPort = id.wsPort,263    pairedAt = System.currentTimeMillis(),264    lastSyncedAt = System.currentTimeMillis(),265)266267/**268 * Build a [ChirpSyncSession] over an established Noise session + frame269 * transport, so the REAL [runChirpSyncInitiator]/[runChirpSyncResponder] can run270 * the encrypted vault exchange. Send/receive splice the Noise cipher onto the271 * length-prefixed frame layer; `remoteStaticPublicKey` is informational here.272 */273internal fun chirpSessionOver(session: NoiseNKSession, transport: SocketFrameIO): ChirpSyncSession =274    ChirpSyncSession(275        remoteStaticPublicKey = ByteArray(0),276        // ChirpSyncSession.send is non-suspending (matches openChirpSyncSession);277        // SocketFrameIO.sendBlocking writes a frame synchronously.278        send = { plaintext -> transport.sendBlocking(session.encrypt(plaintext)) },279        receive = { session.decrypt(transport.receive()) },280        close = { transport.close() },281    )282283private fun jsonEscape(value: String): String = buildString(value.length) {284    for (ch in value) when (ch) {285        '\\' -> append("\\\\"); '"' -> append("\\\"")286        '\n' -> append("\\n"); '\r' -> append("\\r"); '\t' -> append("\\t")287        else -> append(ch)288    }289}290291private fun miniJsonObject(text: String): Map<String, String> {292    val trimmed = text.trim()293    require(trimmed.startsWith("{") && trimmed.endsWith("}")) { "expected JSON object" }294    val body = trimmed.substring(1, trimmed.length - 1)295    val out = linkedMapOf<String, String>()296    var i = 0297    while (i < body.length) {298        while (i < body.length && body[i].isWhitespace()) i++299        if (i >= body.length || body[i] != '"') break300        i++301        val keyStart = i302        while (i < body.length && body[i] != '"') i++303        val key = body.substring(keyStart, i); i++304        while (i < body.length && (body[i].isWhitespace() || body[i] == ':')) i++305        val value: String306        if (i < body.length && body[i] == '"') {307            i++308            val vStart = i309            while (i < body.length && body[i] != '"') i++310            value = body.substring(vStart, i); i++311        } else {312            val vStart = i313            while (i < body.length && body[i] != ',') i++314            value = body.substring(vStart, i).trim()315        }316        out[key] = value317        while (i < body.length && body[i].isWhitespace()) i++318        if (i < body.length && body[i] == ',') i++319    }320    return out321}