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}144145146147148149150151152suspend 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 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 233 }234 }235 }236}237238suspend fun openAndroidAudioIO(): AudioIO {239 throw ChirpExchangeError(240 ChirpExchangeErrorKind.AUDIO_UNAVAILABLE,241 "Android audio bridge is not yet implemented",242 )243}244245suspend fun runChirpPairing(246 deps: ChirpPairingDeps,247 role: PairingRole = PairingRole.RESPONDER,248 codecFactory: ChirpCodecFactory = ::createChirpCodec,249): PairedDevice {250 deps.onProgress(PairingProgress(phase = PairingPhase.IDLE))251252 val localIdentity = deps.fetchLocalIdentity()253254 if (role == PairingRole.RESPONDER && localIdentity.deviceType != DeviceType.EXTENSION) {255 throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, "responder requires extension identity")256 }257 if (role == PairingRole.INITIATOR && localIdentity.deviceType == DeviceType.EXTENSION) {258 throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, "initiator requires non-extension identity")259 }260261 deps.onProgress(PairingProgress(phase = PairingPhase.LISTENING))262263 val deviceTypeByte = when (localIdentity.deviceType) {264 DeviceType.ANDROID -> deviceTypeToByte(DeviceType.ANDROID)265 DeviceType.IOS -> deviceTypeToByte(DeviceType.IOS)266 DeviceType.DESKTOP -> deviceTypeToByte(DeviceType.DESKTOP)267 DeviceType.EXTENSION -> deviceTypeToByte(DeviceType.EXTENSION)268 }269 val attempt = createPairingAttempt(deviceTypeByte)270271 val remoteChirpPublicKey: ByteArray272 try {273 val audio = deps.openAudio()274 val result = runChirpExchange(275 io = audio,276 opts = ChirpExchangeOptions(277 attempt = attempt,278 timeoutMs = deps.chirpTimeoutMs,279 ),280 codecFactory = codecFactory,281 )282 remoteChirpPublicKey = result.remoteChirp.ephemeralPublicKey283 } catch (err: ChirpExchangeError) {284 val phase = when (err.kind) {285 ChirpExchangeErrorKind.TIMEOUT -> PairingPhase.TIMEOUT286 ChirpExchangeErrorKind.VERSION_MISMATCH -> PairingPhase.VERSION_MISMATCH287 ChirpExchangeErrorKind.MIC_DENIED -> PairingPhase.MIC_DENIED288 ChirpExchangeErrorKind.AUDIO_UNAVAILABLE -> PairingPhase.HANDSHAKE_FAILED289 }290 deps.onProgress(PairingProgress(phase = phase, errorMessage = err.message))291 throw ChirpPairingFailure(phase, err.message ?: phase.wireValue)292 }293294 deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE))295296 if (role == PairingRole.RESPONDER) {297 return runResponderHandshake(deps, attempt, localIdentity)298 }299 return runInitiatorHandshake(deps, remoteChirpPublicKey, localIdentity)300}301302private suspend fun runResponderHandshake(303 deps: ChirpPairingDeps,304 attempt: PairingAttempt,305 localIdentity: LocalChirpIdentity,306): PairedDevice {307 val subnet = deps.getLocalSubnet()308 if (subnet.isNullOrBlank()) {309 deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = "no_subnet"))310 throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, "could not determine local subnet")311 }312313 val peerEndpoint = firstResponsivePeer(deps, subnet, CHIRP_PAIRING_PORT)314 if (peerEndpoint == null) {315 deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = "peer_not_found"))316 throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, "could not reach paired peer on subnet")317 }318319 val transport = deps.openPairingTransport(peerEndpoint)320 val result = try {321 runPairingResponder(322 ourEphemeralPrivateKey = attempt.ephemeralPrivateKey,323 ourEphemeralPublicKey = attempt.ephemeralPublicKey,324 ourIdentity = localIdentity,325 transport = transport,326 )327 } catch (err: Throwable) {328 try {329 transport.close()330 } catch (_: Throwable) {331 332 }333 deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = err.message))334 throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, err.message ?: "handshake failed")335 }336 transport.close()337338 val paired = gateOnSAS(deps, result)339 deps.completePairing(paired)340 deps.cacheLastKnownIp(paired.longTermPublicKeyHex.orEmpty(), peerEndpoint.ip)341 deps.onProgress(PairingProgress(phase = PairingPhase.PAIRED, peerDeviceName = paired.deviceName))342 return paired343}344345private suspend fun gateOnSAS(346 deps: ChirpPairingDeps,347 result: PairingHandshakeResult,348): PairedDevice {349 val confirmed = try {350 deps.confirmSAS(result.sas)351 } catch (err: Throwable) {352 deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = err.message))353 throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, err.message ?: "handshake failed")354 }355 if (!confirmed) {356 deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = "sas_rejected"))357 throw ChirpPairingFailure(358 PairingPhase.HANDSHAKE_FAILED,359 "pairing rejected - the verification codes did not match",360 )361 }362 return result.device363}364365private suspend fun runInitiatorHandshake(366 deps: ChirpPairingDeps,367 remoteChirpPublicKey: ByteArray,368 localIdentity: LocalChirpIdentity,369): PairedDevice {370 val server = try {371 deps.openPairingServer()372 } catch (err: Throwable) {373 deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = err.message))374 throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, err.message ?: "handshake failed")375 }376377 val result = try {378 runPairingInitiator(remoteChirpPublicKey, localIdentity, server.transport)379 } catch (err: Throwable) {380 try {381 server.transport.close()382 } catch (_: Throwable) {383 384 }385 deps.onProgress(PairingProgress(phase = PairingPhase.HANDSHAKE_FAILED, errorMessage = err.message))386 throw ChirpPairingFailure(PairingPhase.HANDSHAKE_FAILED, err.message ?: "handshake failed")387 }388 server.transport.close()389390 val paired = gateOnSAS(deps, result)391 deps.completePairing(paired)392 deps.cacheLastKnownIp(paired.longTermPublicKeyHex.orEmpty(), server.peerIp)393 deps.onProgress(PairingProgress(phase = PairingPhase.PAIRED, peerDeviceName = paired.deviceName))394 return paired395}396397private suspend fun firstResponsivePeer(398 deps: ChirpPairingDeps,399 subnet: String,400 port: Int,401): PairingEndpoint? {402 val probeTimeoutMs = 250L403 val batch = 16404 for (start in 1..254 step batch) {405 val end = minOf(start + batch - 1, 254)406 val ips = (start..end).map { "$subnet.$it" }407 val results = coroutineScope {408 ips.map { ip ->409 async {410 try {411 val transport = withTimeoutOrNull(probeTimeoutMs) {412 deps.openPairingTransport(PairingEndpoint(ip = ip, port = port))413 }414 if (transport != null) {415 transport.close()416 PairingEndpoint(ip = ip, port = port)417 } else {418 null419 }420 } catch (_: Throwable) {421 null422 }423 }424 }.mapNotNull { it.await() }425 }426 val hit = results.firstOrNull()427 if (hit != null) return hit428 }429 return null430}431432private suspend fun runPairingInitiator(433 remoteEphemeralPublicKey: ByteArray,434 ourIdentity: LocalChirpIdentity,435 transport: PairingTransport,436): PairingHandshakeResult {437 val session = noiseNKInitiator(438 remoteEphemeralPublicKey,439 transport::send,440 transport::receive,441 )442443 transport.send(444 session.encrypt(445 encodePairingFrame(446 PairingFrame(447 type = "PAIR_IDENTITY",448 deviceId = ourIdentity.deviceId,449 deviceName = ourIdentity.deviceName,450 deviceType = ourIdentity.deviceType,451 longTermPublicKeyHex = ourIdentity.longTermPublicKeyHex,452 signingPublicKeyHex = ourIdentity.signingPublicKeyHex,453 wsPort = ourIdentity.wsPort,454 ),455 ),456 ),457 )458459 val theirCipher = transport.receive()460 val theirPlain = session.decrypt(theirCipher)461 val theirFrame = decodePairingFrame(theirPlain)462 return PairingHandshakeResult(463 device = frameToPairedDevice(theirFrame),464 sas = SASDerivation.derive(session.handshakeHash),465 )466}467468private suspend fun runPairingResponder(469 ourEphemeralPrivateKey: ByteArray,470 ourEphemeralPublicKey: ByteArray,471 ourIdentity: LocalChirpIdentity,472 transport: PairingTransport,473): PairingHandshakeResult {474 val session = noiseNKResponder(475 ourEphemeralPrivateKey,476 ourEphemeralPublicKey,477 transport::send,478 transport::receive,479 )480481 val theirCipher = transport.receive()482 val theirPlain = session.decrypt(theirCipher)483 val theirFrame = decodePairingFrame(theirPlain)484485 transport.send(486 session.encrypt(487 encodePairingFrame(488 PairingFrame(489 type = "PAIR_IDENTITY",490 deviceId = ourIdentity.deviceId,491 deviceName = ourIdentity.deviceName,492 deviceType = ourIdentity.deviceType,493 longTermPublicKeyHex = ourIdentity.longTermPublicKeyHex,494 signingPublicKeyHex = ourIdentity.signingPublicKeyHex,495 wsPort = ourIdentity.wsPort,496 ),497 ),498 ),499 )500501 return PairingHandshakeResult(502 device = frameToPairedDevice(theirFrame),503 sas = SASDerivation.derive(session.handshakeHash),504 )505}506507private data class PairingFrame(508 val type: String,509 val deviceId: String,510 val deviceName: String,511 val deviceType: DeviceType,512 val longTermPublicKeyHex: String,513 val signingPublicKeyHex: String? = null,514 val wsPort: Int? = null,515)516517private fun encodePairingFrame(frame: PairingFrame): ByteArray {518 val builder = StringBuilder()519 builder.append('{')520 builder.append("\"type\":\"").append(frame.type).append('\"')521 builder.append(",\"device_id\":\"").append(escapeJson(frame.deviceId)).append('\"')522 builder.append(",\"device_name\":\"").append(escapeJson(frame.deviceName)).append('\"')523 builder.append(",\"device_type\":\"").append(frame.deviceType.wireValue).append('\"')524 builder.append(",\"long_term_public_key_hex\":\"").append(frame.longTermPublicKeyHex).append('\"')525 if (!frame.signingPublicKeyHex.isNullOrBlank()) {526 builder.append(",\"signing_public_key_hex\":\"").append(frame.signingPublicKeyHex).append('\"')527 }528 if (frame.wsPort != null) {529 builder.append(",\"ws_port\":").append(frame.wsPort)530 }531 builder.append('}')532 return builder.toString().encodeToByteArray()533}534535private fun decodePairingFrame(bytes: ByteArray): PairingFrame {536 val text = bytes.decodeToString()537 val parsed = simpleJsonObject(text)538 require(parsed["type"] == "PAIR_IDENTITY") { "expected PAIR_IDENTITY frame" }539 val deviceId = parsed["device_id"] ?: error("device_id missing")540 val deviceName = parsed["device_name"] ?: error("device_name missing")541 val deviceType = when (parsed["device_type"]) {542 "extension" -> DeviceType.EXTENSION543 "android" -> DeviceType.ANDROID544 "ios" -> DeviceType.IOS545 "desktop" -> DeviceType.DESKTOP546 else -> error("device_type missing")547 }548 val longTermPublicKeyHex = parsed["long_term_public_key_hex"] ?: error("long_term_public_key_hex missing")549 require(longTermPublicKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {550 "long_term_public_key_hex is not 32-byte hex"551 }552 val signingPublicKeyHex = parsed["signing_public_key_hex"]?.takeIf { it.isNotBlank() }553 if (signingPublicKeyHex != null) {554 require(signingPublicKeyHex.matches(Regex("^[0-9a-f]{64}$"))) {555 "signing_public_key_hex is not 32-byte hex"556 }557 }558 val wsPort = parsed["ws_port"]?.toIntOrNull()559 return PairingFrame(560 type = "PAIR_IDENTITY",561 deviceId = deviceId,562 deviceName = deviceName,563 deviceType = deviceType,564 longTermPublicKeyHex = longTermPublicKeyHex,565 signingPublicKeyHex = signingPublicKeyHex,566 wsPort = wsPort,567 )568}569570private fun frameToPairedDevice(frame: PairingFrame): PairedDevice {571 return PairedDevice(572 deviceId = frame.deviceId,573 deviceName = frame.deviceName,574 deviceType = frame.deviceType.wireValue,575 longTermPublicKeyHex = frame.longTermPublicKeyHex,576 signingPublicKeyHex = frame.signingPublicKeyHex,577 trustSource = "direct",578 wsPort = frame.wsPort,579 pairedAt = System.currentTimeMillis(),580 )581}582583private fun escapeJson(value: String): String {584 return buildString(value.length) {585 for (ch in value) {586 when (ch) {587 '\\' -> append("\\\\")588 '"' -> append("\\\"")589 '\b' -> append("\\b")590 '\u000C' -> append("\\f")591 '\n' -> append("\\n")592 '\r' -> append("\\r")593 '\t' -> append("\\t")594 else -> append(ch)595 }596 }597 }598}599600private fun simpleJsonObject(text: String): Map<String, String> {601 val trimmed = text.trim()602 require(trimmed.startsWith("{") && trimmed.endsWith("}")) { "expected JSON object" }603 val body = trimmed.substring(1, trimmed.length - 1).trim()604 if (body.isEmpty()) return emptyMap()605 val out = linkedMapOf<String, String>()606 var i = 0607 while (i < body.length) {608 while (i < body.length && body[i].isWhitespace()) i++609 require(i < body.length && body[i] == '"') { "expected string key" }610 i++611 val keyStart = i612 while (i < body.length && body[i] != '"') i++613 val key = body.substring(keyStart, i)614 i++615 while (i < body.length && (body[i].isWhitespace() || body[i] == ':')) i++616 val value: String617 if (i < body.length && body[i] == '"') {618 i++619 val valueStart = i620 while (i < body.length && body[i] != '"') i++621 value = body.substring(valueStart, i)622 i++623 } else {624 val valueStart = i625 while (i < body.length && body[i] != ',') i++626 value = body.substring(valueStart, i).trim()627 }628 out[key] = value629 while (i < body.length && body[i].isWhitespace()) i++630 if (i < body.length && body[i] == ',') i++631 }632 return out633}