ChirpPairing.kt

21.4 KB · raw

1package com.peachpasswords.sync23import kotlinx.coroutines.async4import kotlinx.coroutines.coroutineScope5import kotlinx.coroutines.cancelAndJoin6import kotlinx.coroutines.delay7import kotlinx.coroutines.isActive8import kotlinx.coroutines.withTimeoutOrNull9import java.security.SecureRandom10import java.util.concurrent.atomic.AtomicBoolean11import org.bouncycastle.crypto.params.X25519PrivateKeyParameters1213const val CHIRP_PAIRING_PORT: Int = 491421415interface PairingTransport {16    suspend fun send(msg: ByteArray)17    suspend fun receive(): ByteArray18    suspend fun close()19}2021data class PairingEndpoint(22    val ip: String,23    val port: Int,24)2526data class PairingServer(27    val transport: PairingTransport,28    val peerIp: String,29)3031data class PairingHandshakeResult(32    val device: PairedDevice,33    val sas: String,34)3536enum class PairingRole {37    INITIATOR,38    RESPONDER,39}4041interface ChirpPairingDeps {42    suspend fun fetchLocalIdentity(): LocalChirpIdentity43    suspend fun completePairing(paired: PairedDevice)44    suspend fun confirmSAS(sas: String): Boolean45    suspend fun cacheLastKnownIp(pubkeyHex: String, ip: String)46    suspend fun getLocalSubnet(): String?47    suspend fun openPairingTransport(endpoint: PairingEndpoint): PairingTransport48    suspend fun openPairingServer(): PairingServer49    suspend fun openAudio(): AudioIO50    val chirpTimeoutMs: Long51    fun onProgress(progress: PairingProgress)52}5354class ChirpPairingFailure(55    val phase: PairingPhase,56    message: String,57) : Error(message)5859interface AudioIO {60    val sampleRate: Int61    suspend fun play(waveform: FloatArray)62    suspend fun pullSamples(): FloatArray63    suspend fun close()64}6566interface PairingKeyPair {67    val publicKey: ByteArray68    val secretKey: ByteArray69}7071private data class PairingX25519KeyPair(72    override val publicKey: ByteArray,73    override val secretKey: ByteArray,74) : PairingKeyPair7576data class PairingAttempt(77    val ephemeralPrivateKey: ByteArray,78    val ephemeralPublicKey: ByteArray,79    val sessionNonce: ByteArray,80    val outgoingPayload: ChirpPayload,81)8283fun createPairingAttempt(deviceType: Byte): PairingAttempt {84    val kp = generatePairingKeyPair()85    val nonce = ByteArray(16)86    secureRandom().nextBytes(nonce)87    return PairingAttempt(88        ephemeralPrivateKey = kp.secretKey,89        ephemeralPublicKey = kp.publicKey,90        sessionNonce = nonce,91        outgoingPayload = ChirpPayload(92            version = CHIRP_PROTOCOL_VERSION,93            deviceType = deviceType,94            ephemeralPublicKey = kp.publicKey,95            sessionNonce = nonce,96        ),97    )98}99100data class ChirpExchangeResult(101    val remoteChirp: ChirpPayload,102)103104data class ChirpExchangeOptions(105    val attempt: PairingAttempt,106    val timeoutMs: Long = DEFAULT_CHIRP_TIMEOUT_MS,107    val onDiscard: ((ChirpDecodeError.Kind) -> Unit)? = null,108    val onChirpPlayed: ((Int) -> Unit)? = null,109)110111enum class ChirpExchangeErrorKind {112    TIMEOUT,113    VERSION_MISMATCH,114    MIC_DENIED,115    AUDIO_UNAVAILABLE,116}117118class ChirpExchangeError(119    val kind: ChirpExchangeErrorKind,120    message: String? = null,121) : Error(message ?: kind.name.lowercase())122123private const val CHIRP_LOOP_INTERVAL_MS = 4_000L124private const val DEFAULT_CHIRP_TIMEOUT_MS = 90_000L125private const val LISTEN_FRAME_SAMPLES = 4096126127fun generatePairingKeyPair(): PairingKeyPair {128    val priv = X25519PrivateKeyParameters(secureRandom())129    return PairingX25519KeyPair(130        publicKey = priv.generatePublicKey().encoded,131        secretKey = priv.encoded,132    )133}134135private fun secureRandom(): SecureRandom = SecureRandom()136137private fun sameBytes(a: ByteArray, b: ByteArray): Boolean {138    if (a.size != b.size) return false139    for (i in a.indices) {140        if (a[i] != b[i]) return false141    }142    return true143}144145/**146 * Run the two-chirp exchange against a provided audio interface.147 *148 * This is a direct port of the browser coordinator logic. The codec and149 * audio bridge are injectable so the protocol can be unit-tested before the150 * Android-native ggwave bridge lands.151 */152suspend fun runChirpExchange(153    io: AudioIO,154    opts: ChirpExchangeOptions,155    codecFactory: ChirpCodecFactory = ::createChirpCodec,156): ChirpExchangeResult {157    return coroutineScope {158        val codec = codecFactory(159            ChirpCodecOptions(160                sampleRate = io.sampleRate,161                protocol = GgwaveProtocol.ULTRASOUND_FASTEST,162                volumePercent = 10,163            ),164        )165        val ourBytes = encodeChirpPayload(opts.attempt.outgoingPayload)166        val ourWaveform = codec.encode(ourBytes)167168        val deadline = System.currentTimeMillis() + opts.timeoutMs169        val stopped = AtomicBoolean(false)170171        val playLoop = async {172            var playCount = 0173            while (isActive && !stopped.get() && System.currentTimeMillis() < deadline) {174                try {175                    io.play(ourWaveform)176                    playCount++177                    opts.onChirpPlayed?.invoke(playCount)178                } catch (_: Throwable) {179                    // Play failures are non-fatal; keep listening.180                }181                if (stopped.get()) break182                val remaining = deadline - System.currentTimeMillis()183                val wait = minOf(CHIRP_LOOP_INTERVAL_MS, maxOf(0L, remaining))184                if (wait <= 0L) break185                delay(wait)186            }187        }188189        try {190            while (System.currentTimeMillis() < deadline && !stopped.get()) {191                val samples = io.pullSamples()192                if (samples.isEmpty()) {193                    delay(50)194                    continue195                }196197                val decoded = codec.decode(samples)198                if (decoded == null) continue199                if (decoded.size != CHIRP_PAYLOAD_LENGTH) {200                    opts.onDiscard?.invoke(ChirpDecodeError.Kind.LENGTH)201                    continue202                }203204                try {205                    val payload = decodeChirpPayload(decoded)206                    if (sameBytes(payload.ephemeralPublicKey, opts.attempt.ephemeralPublicKey)) {207                        continue208                    }209                    if (payload.version != CHIRP_PROTOCOL_VERSION) {210                        throw ChirpExchangeError(ChirpExchangeErrorKind.VERSION_MISMATCH)211                    }212                    stopped.set(true)213                    return@coroutineScope ChirpExchangeResult(remoteChirp = payload)214                } catch (err: ChirpExchangeError) {215                    throw err216                } catch (err: ChirpDecodeError) {217                    if (err.kind == ChirpDecodeError.Kind.VERSION) {218                        throw ChirpExchangeError(ChirpExchangeErrorKind.VERSION_MISMATCH)219                    }220                    opts.onDiscard?.invoke(err.kind)221                    continue222                }223            }224            throw ChirpExchangeError(ChirpExchangeErrorKind.TIMEOUT)225        } finally {226            stopped.set(true)227            codec.free()228            playLoop.cancelAndJoin()229            try {230                io.close()231            } catch (_: Throwable) {232                // ignore233            }234        }235    }236}237238suspend fun openAndroidAudioIO(): AudioIO = openPcmFloatAudioIO()239240suspend fun runChirpPairing(241    deps: ChirpPairingDeps,242    role: PairingRole = PairingRole.RESPONDER,243    codecFactory: ChirpCodecFactory = ::createChirpCodec,244): PairedDevice {245    deps.onProgress(PairingProgress(phase = PairingPhase.IDLE))246247    val localIdentity = deps.fetchLocalIdentity()248249    if (role == PairingRole.RESPONDER && localIdentity.deviceType != DeviceType.EXTENSION) {250        throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, "responder requires extension identity")251    }252    if (role == PairingRole.INITIATOR && localIdentity.deviceType == DeviceType.EXTENSION) {253        throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, "initiator requires non-extension identity")254    }255256    deps.onProgress(PairingProgress(phase = PairingPhase.LISTENING))257258    val deviceTypeByte = when (localIdentity.deviceType) {259        DeviceType.ANDROID -> deviceTypeToByte(DeviceType.ANDROID)260        DeviceType.IOS -> deviceTypeToByte(DeviceType.IOS)261        DeviceType.DESKTOP -> deviceTypeToByte(DeviceType.DESKTOP)262        DeviceType.EXTENSION -> deviceTypeToByte(DeviceType.EXTENSION)263    }264    val attempt = createPairingAttempt(deviceTypeByte)265266    val remoteChirpPublicKey: ByteArray267    try {268        val audio = deps.openAudio()269        val result = runChirpExchange(270            io = audio,271            opts = ChirpExchangeOptions(272                attempt = attempt,273                timeoutMs = deps.chirpTimeoutMs,274            ),275            codecFactory = codecFactory,276        )277        remoteChirpPublicKey = result.remoteChirp.ephemeralPublicKey278    } catch (err: ChirpExchangeError) {279        val phase = when (err.kind) {280            ChirpExchangeErrorKind.TIMEOUT -> PairingPhase.TIMEOUT281            ChirpExchangeErrorKind.VERSION_MISMATCH -> PairingPhase.VERSION_MISMATCH282            ChirpExchangeErrorKind.MIC_DENIED -> PairingPhase.MIC_DENIED283            ChirpExchangeErrorKind.AUDIO_UNAVAILABLE -> PairingPhase.HANDSHAKE_FAILED284        }285        deps.onProgress(PairingProgress(phase = phase, errorMessage = err.message))286        throw ChirpPairingFailure(phase, err.message ?: phase.wireValue)287    }288289    deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE))290291    if (role == PairingRole.RESPONDER) {292        return runResponderHandshake(deps, attempt, localIdentity)293    }294    return runInitiatorHandshake(deps, remoteChirpPublicKey, localIdentity)295}296297private suspend fun runResponderHandshake(298    deps: ChirpPairingDeps,299    attempt: PairingAttempt,300    localIdentity: LocalChirpIdentity,301): PairedDevice {302    val subnet = deps.getLocalSubnet()303    if (subnet.isNullOrBlank()) {304        deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = "no_subnet"))305        throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, "could not determine local subnet")306    }307308    val peerEndpoint = firstResponsivePeer(deps, subnet, CHIRP_PAIRING_PORT)309    if (peerEndpoint == null) {310        deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = "peer_not_found"))311        throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, "could not reach paired peer on subnet")312    }313314    val transport = deps.openPairingTransport(peerEndpoint)315    val result = try {316        runPairingResponder(317            ourEphemeralPrivateKey = attempt.ephemeralPrivateKey,318            ourEphemeralPublicKey = attempt.ephemeralPublicKey,319            ourIdentity = localIdentity,320            transport = transport,321        )322    } catch (err: Throwable) {323        try {324            transport.close()325        } catch (_: Throwable) {326            // ignore327        }328        deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = err.message))329        throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, err.message ?: "handshake failed")330    }331    transport.close()332333    val paired = gateOnSAS(deps, result)334    deps.completePairing(paired)335    deps.cacheLastKnownIp(paired.longTermPublicKeyHex.orEmpty(), peerEndpoint.ip)336    deps.onProgress(PairingProgress(phase = PairingPhase.PAIRED, peerDeviceName = paired.deviceName))337    return paired338}339340private suspend fun gateOnSAS(341    deps: ChirpPairingDeps,342    result: PairingHandshakeResult,343): PairedDevice {344    val confirmed = try {345        deps.confirmSAS(result.sas)346    } catch (err: Throwable) {347        deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = err.message))348        throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, err.message ?: "handshake failed")349    }350    if (!confirmed) {351        deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = "sas_rejected"))352        throw ChirpPairingFailure(353            PairingPhase.HANDSHAKE_FAILED,354            "pairing rejected - the verification codes did not match",355        )356    }357    return result.device358}359360private suspend fun runInitiatorHandshake(361    deps: ChirpPairingDeps,362    remoteChirpPublicKey: ByteArray,363    localIdentity: LocalChirpIdentity,364): PairedDevice {365    val server = try {366        deps.openPairingServer()367    } catch (err: Throwable) {368        deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = err.message))369        throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, err.message ?: "handshake failed")370    }371372    val result = try {373        runPairingInitiator(remoteChirpPublicKey, localIdentity, server.transport)374    } catch (err: Throwable) {375        try {376            server.transport.close()377        } catch (_: Throwable) {378            // ignore379        }380        deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = err.message))381        throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, err.message ?: "handshake failed")382    }383    server.transport.close()384385    val paired = gateOnSAS(deps, result)386    deps.completePairing(paired)387    deps.cacheLastKnownIp(paired.longTermPublicKeyHex.orEmpty(), server.peerIp)388    deps.onProgress(PairingProgress(phase = PairingPhase.PAIRED, peerDeviceName = paired.deviceName))389    return paired390}391392private suspend fun firstResponsivePeer(393    deps: ChirpPairingDeps,394    subnet: String,395    port: Int,396): PairingEndpoint? {397    val probeTimeoutMs = 250L398    val batch = 16399    for (start in 1..254 step batch) {400        val end = minOf(start + batch - 1, 254)401        val ips = (start..end).map { "$subnet.$it" }402        val results = coroutineScope {403            ips.map { ip ->404                async {405                    try {406                        val transport = withTimeoutOrNull(probeTimeoutMs) {407                            deps.openPairingTransport(PairingEndpoint(ip = ip, port = port))408                        }409                        if (transport != null) {410                            transport.close()411                            PairingEndpoint(ip = ip, port = port)412                        } else {413                            null414                        }415                    } catch (_: Throwable) {416                        null417                    }418                }419            }.mapNotNull { it.await() }420        }421        val hit = results.firstOrNull()422        if (hit != null) return hit423    }424    return null425}426427private suspend fun runPairingInitiator(428    remoteEphemeralPublicKey: ByteArray,429    ourIdentity: LocalChirpIdentity,430    transport: PairingTransport,431): PairingHandshakeResult {432    val session = noiseNKInitiator(433        remoteEphemeralPublicKey,434        transport::send,435        transport::receive,436    )437438    transport.send(439        session.encrypt(440            encodePairingFrame(441                PairingFrame(442                    type = "PAIR_IDENTITY",443                    deviceId = ourIdentity.deviceId,444                    deviceName = ourIdentity.deviceName,445                    deviceType = ourIdentity.deviceType,446                    longTermPublicKeyHex = ourIdentity.longTermPublicKeyHex,447                    signingPublicKeyHex = ourIdentity.signingPublicKeyHex,448                    wsPort = ourIdentity.wsPort,449                ),450            ),451        ),452    )453454    val theirCipher = transport.receive()455    val theirPlain = session.decrypt(theirCipher)456    val theirFrame = decodePairingFrame(theirPlain)457    return PairingHandshakeResult(458        device = frameToPairedDevice(theirFrame),459        sas = SASDerivation.derive(session.handshakeHash),460    )461}462463private suspend fun runPairingResponder(464    ourEphemeralPrivateKey: ByteArray,465    ourEphemeralPublicKey: ByteArray,466    ourIdentity: LocalChirpIdentity,467    transport: PairingTransport,468): PairingHandshakeResult {469    val session = noiseNKResponder(470        ourEphemeralPrivateKey,471        ourEphemeralPublicKey,472        transport::send,473        transport::receive,474    )475476    val theirCipher = transport.receive()477    val theirPlain = session.decrypt(theirCipher)478    val theirFrame = decodePairingFrame(theirPlain)479480    transport.send(481        session.encrypt(482            encodePairingFrame(483                PairingFrame(484                    type = "PAIR_IDENTITY",485                    deviceId = ourIdentity.deviceId,486                    deviceName = ourIdentity.deviceName,487                    deviceType = ourIdentity.deviceType,488                    longTermPublicKeyHex = ourIdentity.longTermPublicKeyHex,489                    signingPublicKeyHex = ourIdentity.signingPublicKeyHex,490                    wsPort = ourIdentity.wsPort,491                ),492            ),493        ),494    )495496    return PairingHandshakeResult(497        device = frameToPairedDevice(theirFrame),498        sas = SASDerivation.derive(session.handshakeHash),499    )500}501502private data class PairingFrame(503    val type: String,504    val deviceId: String,505    val deviceName: String,506    val deviceType: DeviceType,507    val longTermPublicKeyHex: String,508    val signingPublicKeyHex: String? = null,509    val wsPort: Int? = null,510)511512private fun encodePairingFrame(frame: PairingFrame): ByteArray {513    val builder = StringBuilder()514    builder.append('{')515    builder.append("\"type\":\"").append(frame.type).append('\"')516    builder.append(",\"device_id\":\"").append(escapeJson(frame.deviceId)).append('\"')517    builder.append(",\"device_name\":\"").append(escapeJson(frame.deviceName)).append('\"')518    builder.append(",\"device_type\":\"").append(frame.deviceType.wireValue).append('\"')519    builder.append(",\"long_term_public_key_hex\":\"").append(frame.longTermPublicKeyHex).append('\"')520    if (!frame.signingPublicKeyHex.isNullOrBlank()) {521        builder.append(",\"signing_public_key_hex\":\"").append(frame.signingPublicKeyHex).append('\"')522    }523    if (frame.wsPort != null) {524        builder.append(",\"ws_port\":").append(frame.wsPort)525    }526    builder.append('}')527    return builder.toString().encodeToByteArray()528}529530private fun decodePairingFrame(bytes: ByteArray): PairingFrame {531    val text = bytes.decodeToString()532    val parsed = simpleJsonObject(text)533    require(parsed["type"] == "PAIR_IDENTITY") { "expected PAIR_IDENTITY frame" }534    val deviceId = parsed["device_id"] ?: error("device_id missing")535    val deviceName = parsed["device_name"] ?: error("device_name missing")536    val deviceType = when (parsed["device_type"]) {537        "extension" -> DeviceType.EXTENSION538        "android" -> DeviceType.ANDROID539        "ios" -> DeviceType.IOS540        "desktop" -> DeviceType.DESKTOP541        else -> error("device_type missing")542    }543    val longTermPublicKeyHex = parsed["long_term_public_key_hex"] ?: error("long_term_public_key_hex missing")544    require(longTermPublicKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {545        "long_term_public_key_hex is not 32-byte hex"546    }547    val signingPublicKeyHex = parsed["signing_public_key_hex"]?.takeIf { it.isNotBlank() }548    if (signingPublicKeyHex != null) {549        require(signingPublicKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {550            "signing_public_key_hex is not 32-byte hex"551        }552    }553    val wsPort = parsed["ws_port"]?.toIntOrNull()554    return PairingFrame(555        type = "PAIR_IDENTITY",556        deviceId = deviceId,557        deviceName = deviceName,558        deviceType = deviceType,559        longTermPublicKeyHex = longTermPublicKeyHex,560        signingPublicKeyHex = signingPublicKeyHex,561        wsPort = wsPort,562    )563}564565private fun frameToPairedDevice(frame: PairingFrame): PairedDevice {566    return PairedDevice(567        deviceId = frame.deviceId,568        deviceName = frame.deviceName,569        deviceType = frame.deviceType.wireValue,570        longTermPublicKeyHex = frame.longTermPublicKeyHex,571        signingPublicKeyHex = frame.signingPublicKeyHex,572        trustSource = "direct",573        wsPort = frame.wsPort,574        pairedAt = System.currentTimeMillis(),575    )576}577578private fun escapeJson(value: String): String {579    return buildString(value.length) {580        for (ch in value) {581            when (ch) {582                '\\' -> append("\\\\")583                '"' -> append("\\\"")584                '\b' -> append("\\b")585                '\u000C' -> append("\\f")586                '\n' -> append("\\n")587                '\r' -> append("\\r")588                '\t' -> append("\\t")589                else -> append(ch)590            }591        }592    }593}594595private fun simpleJsonObject(text: String): Map<String, String> {596    val trimmed = text.trim()597    require(trimmed.startsWith("{") && trimmed.endsWith("}")) { "expected JSON object" }598    val body = trimmed.substring(1, trimmed.length - 1).trim()599    if (body.isEmpty()) return emptyMap()600    val out = linkedMapOf<String, String>()601    var i = 0602    while (i < body.length) {603        while (i < body.length && body[i].isWhitespace()) i++604        require(i < body.length && body[i] == '"') { "expected string key" }605        i++606        val keyStart = i607        while (i < body.length && body[i] != '"') i++608        val key = body.substring(keyStart, i)609        i++610        while (i < body.length && (body[i].isWhitespace() || body[i] == ':')) i++611        val value: String612        if (i < body.length && body[i] == '"') {613            i++614            val valueStart = i615            while (i < body.length && body[i] != '"') i++616            value = body.substring(valueStart, i)617            i++618        } else {619            val valueStart = i620            while (i < body.length && body[i] != ',') i++621            value = body.substring(valueStart, i).trim()622        }623        out[key] = value624        while (i < body.length && body[i].isWhitespace()) i++625        if (i < body.length && body[i] == ',') i++626    }627    return out628}