1package com.peachpasswords.sync23import java.security.MessageDigest4import javax.inject.Inject5import javax.inject.Singleton6import kotlinx.coroutines.CoroutineScope7import kotlinx.coroutines.Dispatchers8import kotlinx.coroutines.Job9import kotlinx.coroutines.channels.awaitClose10import kotlinx.coroutines.flow.Flow11import kotlinx.coroutines.flow.callbackFlow12import kotlinx.coroutines.launch13import kotlinx.coroutines.withTimeout14import kotlinx.coroutines.withTimeoutOrNull15import org.json.JSONObject1617sealed interface RelayAdoptionEvent {18 19 data class InvitationReady(val invitation: String) : RelayAdoptionEvent20 data class AwaitingPeerConfirmation(21 val sas: String,22 val deviceName: String,23 ) : RelayAdoptionEvent24 data class Adopted(val deviceName: String) : RelayAdoptionEvent25 data object Expired : RelayAdoptionEvent26 data class Rejected(val reason: String) : RelayAdoptionEvent27}2829@Singleton30class RelayAdoptionHost @Inject constructor(31 private val relaySettings: RelaySettingsStore,32 private val generation: SyncGenerationPort,33 private val deviceStore: PairedDeviceRegistry,34) {35 private var job: Job? = null36 private var socket: RelayBinarySocket? = null3738 fun start(39 scope: CoroutineScope,40 ourStaticPrivateKey: ByteArray,41 ourStaticPublicKey: ByteArray,42 localIdentity: LocalDeviceIdentity,43 sourceDeps: AdoptionSourceV2Deps,44 windowMs: Long = PAIRING_WINDOW_MS,45 ): Flow<RelayAdoptionEvent> = callbackFlow {46 47 48 49 50 val relayUrl = when (val decision = relaySettings.relayInForce()) {51 is RelayDecision.Refuse -> {52 trySend(RelayAdoptionEvent.Rejected(decision.reason.wire()))53 close()54 return@callbackFlow55 }5657 is RelayDecision.Dial -> decision.relayUrl58 }59 val token = Rendezvous.newPairingToken()60 val invitation = createPairingInvitation(61 relayUrl,62 token,63 noiseStaticPublicKeyHex = Rendezvous.bytesToHex(ourStaticPublicKey),64 )6566 job = scope.launch(Dispatchers.IO) {67 try {68 val connected = OkHttpRelaySocket.connectPairing(69 Rendezvous.buildUrl(relayUrl, token),70 )71 socket = connected72 73 74 trySend(RelayAdoptionEvent.InvitationReady(invitation))7576 var peerOutdated = false77 val adopted = withTimeout(windowMs) {78 runRelayAdoptionSourceSession(79 socket = connected,80 expectedToken = token,81 relayUrl = relayUrl,82 ourStaticPrivateKey = ourStaticPrivateKey,83 ourStaticPublicKey = ourStaticPublicKey,84 localIdentity = localIdentity,85 sourceDeps = sourceDeps,86 87 88 89 90 postReset = { generation.isPostReset(System.currentTimeMillis()) },91 onPeerOutdated = { peerOutdated = true },92 confirm = { sas, request ->93 trySend(94 RelayAdoptionEvent.AwaitingPeerConfirmation(95 sas = sas,96 deviceName = capDeviceName(request.deviceName.ifBlank { "New device" }),97 ),98 )99 100 101 102 true103 },104 )105 }106 if (peerOutdated) {107 trySend(RelayAdoptionEvent.Rejected(PEER_PROTOCOL_OUTDATED))108 } else if (adopted == null) {109 trySend(RelayAdoptionEvent.Rejected("adoption_rejected"))110 } else {111 onDirectV2PairingEstablished(112 generation,113 hasDirectDevice = deviceStore.getAll().any { it.trustSource == "direct" },114 nowMs = System.currentTimeMillis(),115 )116 trySend(117 RelayAdoptionEvent.Adopted(118 capDeviceName(adopted.deviceName?.takeIf(String::isNotBlank) ?: "New device"),119 ),120 )121 }122 } catch (error: kotlinx.coroutines.TimeoutCancellationException) {123 trySend(RelayAdoptionEvent.Expired)124 } catch (error: kotlinx.coroutines.CancellationException) {125 126 127 128 129 130 throw error131 } catch (error: Throwable) {132 trySend(RelayAdoptionEvent.Rejected(error.message ?: "relay_adoption_failed"))133 } finally {134 socket?.close()135 socket = null136 close()137 }138 }139140 awaitClose { stop() }141 }142143 fun stop() {144 job?.cancel()145 job = null146 socket?.close()147 socket = null148 }149}150151152153154155156157158internal suspend fun runRelayAdoptionSourceSession(159 socket: RelayBinarySocket,160 expectedToken: String,161 relayUrl: String,162 ourStaticPrivateKey: ByteArray,163 ourStaticPublicKey: ByteArray,164 localIdentity: LocalDeviceIdentity,165 sourceDeps: AdoptionSourceV2Deps,166 confirm: suspend (sas: String, request: AdoptionFrame.Request) -> Boolean,167 postReset: () -> Boolean = { false },168 onPeerOutdated: () -> Unit = {},169): PairedDevice? {170 val hello = JSONObject(String(socket.receive(), Charsets.UTF_8))171 require(hello.optString("type") == "PEACH_HELLO") { "expected PEACH_HELLO" }172 require(173 MessageDigest.isEqual(174 expectedToken.toByteArray(Charsets.US_ASCII),175 hello.optString("token").toByteArray(Charsets.US_ASCII),176 ),177 ) { "pairing token mismatch" }178179 socket.send(180 JSONObject()181 .put("type", "PEACH_HELLO_ACK")182 .put(183 "ephemeralPublicKeyHex",184 ourStaticPublicKey.joinToString("") { "%02x".format(it) },185 )186 .toString()187 .toByteArray(Charsets.UTF_8),188 )189190 val noise = noiseNKResponder(191 ourStaticPrivateKey,192 ourStaticPublicKey,193 socket::send,194 socket::receive,195 )196 try {197 val channel = object : PairingTransport {198 override suspend fun send(msg: ByteArray) = socket.send(noise.encrypt(msg))199 override suspend fun receive(): ByteArray = noise.decrypt(socket.receive())200 override suspend fun close() = socket.close()201 }202203 val request = receiveFrame(channel)204 require(request is AdoptionFrame.Request || request is AdoptionFrame.RequestV2) { "expected ADOPT_REQUEST" }205 206 207 208 if (request is AdoptionFrame.Request && postReset()) {209 onPeerOutdated()210 return null211 }212 if (request is AdoptionFrame.Request && !confirm(SASDerivation.derive(noise.handshakeHash), request)) return null213214 val pairState = AdoptionPairState(215 rendezvousSecretHex = Rendezvous.bytesToHex(216 Rendezvous.deriveSecret(noise.handshakeHash),217 ),218 relayUrl = Rendezvous.normalizeRelayUrl(relayUrl),219 )220 val boundDeps = object : AdoptionSourceV2Deps {221 override val sourceIdentity = localIdentity222 override val pairState: AdoptionPairState = pairState223 override suspend fun rootKeyHex() = sourceDeps.rootKeyHex()224 override suspend fun vaultId() = sourceDeps.vaultId()225 override suspend fun license() = sourceDeps.license()226 override suspend fun applyLicense(license: String) = sourceDeps.applyLicense(license)227 override suspend fun onConsent(request: AdoptionFrame.Request) = true228229 230 231 232 override suspend fun onConsent(request: AdoptionFrame.RequestV2): Boolean =233 confirm(234 SASDerivation.derive(noise.handshakeHash),235 AdoptionFrame.Request(236 sessionRequestId = request.deviceId,237 deviceName = request.deviceName,238 deviceType = request.deviceType,239 license = request.license,240 snapshotCapable = request.snapshotCapable,241 ),242 )243 override suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long) = sourceDeps.persistPendingHolder(request, nowMs)244 override suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice) = sourceDeps.completePendingHolder(request, device)245 override suspend fun persistPendingIdentity(device: PairedDevice, nowMs: Long) = sourceDeps.persistPendingIdentity(device, nowMs)246 override suspend fun completePendingIdentity(device: PairedDevice) = sourceDeps.completePendingIdentity(device)247 override suspend fun upsertPairedDevice(device: PairedDevice) = sourceDeps.upsertPairedDevice(device)248 override fun hasDeviceIdentityCollision(device: PairedDevice) = sourceDeps.hasDeviceIdentityCollision(device)249 override suspend fun rotateSourceIdentity() = sourceDeps.rotateSourceIdentity()250 override fun snapshotCapable() = sourceDeps.snapshotCapable()251 override suspend fun vaultSnapshot() = sourceDeps.vaultSnapshot()252 override suspend fun outgoingDeviceManifest() = sourceDeps.outgoingDeviceManifest()253 override suspend fun markSynced(deviceId: String) = sourceDeps.markSynced(deviceId)254 override suspend fun duressSlotJson() = sourceDeps.duressSlotJson()255 }256 val adopted = when (request) {257 is AdoptionFrame.RequestV2 -> grantAdoptionV2(channel, request, boundDeps)258 is AdoptionFrame.Request -> grantAdoption(channel, request, boundDeps)259 else -> null260 } ?: return null261 262 val receiverWantsSnapshot = when (request) {263 is AdoptionFrame.Request -> request.snapshotCapable == true264 is AdoptionFrame.RequestV2 -> request.snapshotCapable == true265 else -> false266 }267 if (receiverWantsSnapshot) {268 try {269 val snapshot = boundDeps.vaultSnapshot()270 if (snapshot != null) {271 val duressSlot = runCatching { boundDeps.duressSlotJson() }.getOrNull()272 sendVaultSnapshot(channel, snapshot.first, snapshot.second, duressSlot)273 val applied = receiveFrame(channel)274 if (applied is AdoptionFrame.SnapshotApplied) {275 val manifest = boundDeps.outgoingDeviceManifest()276 if (manifest != null) {277 sendFrame(channel, AdoptionFrame.DeviceManifestFrame(manifest))278 withTimeoutOrNull(5_000) { receiveFrame(channel) }279 }280 boundDeps.markSynced(adopted.deviceId)281 }282 }283 } catch (error: Exception) {284 if (error is SnapshotDuressFrameTooLargeException) throw error285 if (error is kotlinx.coroutines.CancellationException) throw error286 PeachSyncLog.w("adoption: snapshot send failed — reason=${relayLogReason(error)}")287 }288 }289 return adopted290 } finally {291 noise.close()292 }293}