1package com.peachpasswords.sync23import java.security.MessageDigest4import javax.inject.Inject5import javax.inject.Singleton6import kotlinx.coroutines.CancellationException7import kotlinx.coroutines.withTimeout8import kotlinx.coroutines.withTimeoutOrNull9import org.json.JSONObject10import com.peachpasswords.sync.hexToPubkey1112131415161718@Singleton19class RelayAdoptionReceiver @Inject constructor(20 private val generation: SyncGenerationPort,21 private val deviceStore: PairedDeviceRegistry,22) {23 2425262728 suspend fun adopt(29 encodedInvitation: String,30 deps: AdoptionReceiverV2Deps,31 confirm: suspend (sas: String) -> Boolean,32 windowMs: Long = PAIRING_WINDOW_MS,33 ): PairedDevice {34 val invitation = parsePairingInvitation(encodedInvitation)35 ?: throw IllegalArgumentException("invalid_pairing_invitation")36 require(invitation.vaultStatus == VaultStatus.POPULATED) {37 "receiver adopt() expects a populated invitation; got ${invitation.vaultStatus}"38 }39 val socket = OkHttpRelaySocket.connectPairing(invitation.roomUrl())40 val adopted = adoptFromRelaySocket(41 socket = socket,42 invitation = invitation,43 deps = deps,44 confirm = confirm,45 windowMs = windowMs,46 )47 markRepairProgress()48 return adopted49 }5051 5253545556 private fun markRepairProgress() {57 onDirectV2PairingEstablished(58 generation,59 hasDirectDevice = deviceStore.getAll().any { it.trustSource == "direct" },60 nowMs = System.currentTimeMillis(),61 )62 }6364 65666768697071 suspend fun grantFromInvitation(72 encodedInvitation: String,73 sourceDeps: AdoptionSourceV2Deps,74 confirm: suspend (sas: String, request: AdoptionFrame.Request) -> Boolean,75 windowMs: Long = PAIRING_WINDOW_MS,76 ): PairedDevice {77 val invitation = parsePairingInvitation(encodedInvitation)78 ?: throw IllegalArgumentException("invalid_pairing_invitation")79 require(invitation.vaultStatus == VaultStatus.EMPTY) {80 "grantFromInvitation() expects an empty invitation; got ${invitation.vaultStatus}"81 }82 val socket = OkHttpRelaySocket.connectPairing(invitation.roomUrl())83 val granted = grantFromRelaySocket(84 socket = socket,85 invitation = invitation,86 sourceDeps = sourceDeps,87 confirm = confirm,88 windowMs = windowMs,89 )90 markRepairProgress()91 return granted92 }93}949596979899100101102103internal suspend fun adoptFromRelaySocket(104 socket: RelayBinarySocket,105 invitation: PairingInvitation,106 deps: AdoptionReceiverV2Deps,107 confirm: suspend (sas: String) -> Boolean,108 windowMs: Long = PAIRING_WINDOW_MS,109): PairedDevice {110 var completed = false111 return try {112 val adopted =113 withTimeout(windowMs) {114 runRelayAdoptionReceiverSession(115 socket = socket,116 invitation = invitation,117 receiverDeps = deps,118 confirm = confirm,119 ) ?: throw IllegalStateException("adoption_rejected")120 }121 completed = true122 adopted123 } finally {124 if (completed) {125 socket.closeAfterQueuedFrames()126 } else {127 socket.close()128 }129 }130}131132133134135136137138internal suspend fun grantFromRelaySocket(139 socket: RelayBinarySocket,140 invitation: PairingInvitation,141 sourceDeps: AdoptionSourceV2Deps,142 confirm: suspend (sas: String, request: AdoptionFrame.Request) -> Boolean,143 windowMs: Long = PAIRING_WINDOW_MS,144): PairedDevice {145 var completed = false146 return try {147 val granted = withTimeout(windowMs) {148 runRelayAdoptionInitiatorSourceSession(149 socket = socket,150 invitation = invitation,151 sourceDeps = sourceDeps,152 confirm = confirm,153 ) ?: throw IllegalStateException("adoption_rejected")154 }155 completed = true156 granted157 } finally {158 if (completed) {159 socket.closeAfterQueuedFrames()160 } else {161 socket.close()162 }163 }164}165166167168169170internal suspend fun runRelayAdoptionReceiverSession(171 socket: RelayBinarySocket,172 invitation: PairingInvitation,173 receiverDeps: AdoptionReceiverV2Deps,174 confirm: suspend (sas: String) -> Boolean,175): PairedDevice? {176 socket.send(177 JSONObject()178 .put("type", "PEACH_HELLO")179 .put("token", invitation.token)180 .toString()181 .toByteArray(Charsets.UTF_8),182 )183184 val ack = JSONObject(String(socket.receive(), Charsets.UTF_8))185 require(ack.optString("type") == "PEACH_HELLO_ACK") {186 "expected PEACH_HELLO_ACK"187 }188 val sourceStatic = hexToPubkey(ack.optString("ephemeralPublicKeyHex"))189 val invitedStatic = invitation.noiseStaticPublicKeyHex190 ?.let(::hexToPubkey)191 ?: throw IllegalArgumentException("pairing_invitation_missing_static_key")192 val staticMatches = MessageDigest.isEqual(sourceStatic, invitedStatic)193 invitedStatic.fill(0)194 if (!staticMatches) {195 sourceStatic.fill(0)196 throw IllegalArgumentException("pairing_static_key_mismatch")197 }198 val noise = try {199 noiseNKInitiator(200 sourceStatic,201 socket::send,202 socket::receive,203 )204 } finally {205 sourceStatic.fill(0)206 }207 try {208 val channel = object : PairingTransport {209 override suspend fun send(msg: ByteArray) = socket.send(noise.encrypt(msg))210 override suspend fun receive(): ByteArray = noise.decrypt(socket.receive())211 override suspend fun close() = socket.close()212 }213 val pairState = AdoptionPairState(214 rendezvousSecretHex = Rendezvous.bytesToHex(215 Rendezvous.deriveSecret(noise.handshakeHash),216 ),217 relayUrl = invitation.relayUrl,218 )219 val boundDeps = object : AdoptionReceiverV2Deps {220 override val deviceName = receiverDeps.deviceName221 override val deviceType = receiverDeps.deviceType222 override val pairState = pairState223 override fun generateDeviceId() = receiverDeps.generateDeviceId()224 override suspend fun confirmSas(): Boolean =225 confirm(SASDerivation.derive(noise.handshakeHash))226227 228 229 override fun localIdentity(): LocalDeviceIdentity = receiverDeps.localIdentity()230231 override suspend fun rotateLocalIdentity(): LocalDeviceIdentity =232 receiverDeps.rotateLocalIdentity()233234 override suspend fun validateSource(prepare: AdoptionFrame.Prepare) {235 receiverDeps.validateSource(prepare)236 }237238 override suspend fun hasSourceIdentityCollision(prepare: AdoptionFrame.Prepare): Boolean =239 receiverDeps.hasSourceIdentityCollision(prepare)240241 override suspend fun validateSource(source: AdoptionFrame.Source) {242 receiverDeps.validateSource(source)243 }244245 override suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source): Boolean =246 receiverDeps.hasSourceIdentityCollision(source)247248 override suspend fun createVaultFromRootKey(rootKeyHex: String): String =249 receiverDeps.createVaultFromRootKey(rootKeyHex)250251 override suspend fun deriveLocalIdentity(): LocalDeviceIdentity =252 receiverDeps.deriveLocalIdentity()253 override suspend fun clearPairedDeviceRevocation(deviceId: String) {254 receiverDeps.clearPairedDeviceRevocation(deviceId)255 }256257 override suspend fun upsertPairedDeviceAndClearRevocation(device: PairedDevice) {258 receiverDeps.upsertPairedDeviceAndClearRevocation(device)259 }260261 override suspend fun upsertPairedDevice(device: PairedDevice) {262 receiverDeps.upsertPairedDevice(device)263 }264265 override suspend fun applyLicense(license: String) {266 receiverDeps.applyLicense(license)267 }268269 override suspend fun license(): String? = receiverDeps.license()270271 override fun onError(error: String) {272 receiverDeps.onError(error)273 }274 override suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String?) {275 receiverDeps.applySnapshot(entries, tombstones, duressSlot)276 }277 override suspend fun applyIncomingDeviceManifest(278 manifest: SignedDeviceManifest,279 authenticatedRemoteStaticPublicKey: ByteArray,280 ) {281 receiverDeps.applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey)282 }283 override suspend fun markSynced(deviceId: String) {284 receiverDeps.markSynced(deviceId)285 }286 }287 288 289 var sourceCanSendSnapshot = false290 val adopted = requestAdoptionV2(291 channel,292 boundDeps,293 onPrepare = { prepare -> sourceCanSendSnapshot = prepare.snapshotCapable == true },294 ) ?: return null295 if (sourceCanSendSnapshot) {296 297 try {298 val snapshot = withTimeoutOrNull(15_000) {299 receiveVaultSnapshot(channel)300 }301 if (snapshot != null) {302 boundDeps.applySnapshot(snapshot.entries, snapshot.tombstones, snapshot.duressSlot)303 sendFrame(channel, AdoptionFrame.SnapshotApplied(304 entriesReceived = snapshot.entries.size,305 tombstonesReceived = snapshot.tombstones.size,306 ))307 308 309 310 311 312 try {313 val manifestFrame = withTimeoutOrNull(5_000) { receiveFrame(channel) }314 if (manifestFrame is AdoptionFrame.DeviceManifestFrame) {315 val sourceLongTerm = adopted.longTermPublicKeyHex316 if (sourceLongTerm != null && sourceLongTerm.length == 64) {317 boundDeps.applyIncomingDeviceManifest(318 manifestFrame.manifest,319 hexToPubkey(sourceLongTerm),320 )321 }322 sendFrame(channel, AdoptionFrame.DeviceManifestApplied)323 }324 } catch (_: Exception) {}325 boundDeps.markSynced(adopted.deviceId)326 } else {327 PeachSyncLog.i("adoption: snapshot receive timed out")328 }329 } catch (e: Exception) {330 PeachSyncLog.w("adoption: snapshot receive failed — reason=${relayLogReason(e)}")331 }332 }333 return adopted334 } finally {335 noise.close()336 }337}338339340341342343344345346347internal suspend fun runRelayAdoptionInitiatorSourceSession(348 socket: RelayBinarySocket,349 invitation: PairingInvitation,350 sourceDeps: AdoptionSourceV2Deps,351 confirm: suspend (sas: String, request: AdoptionFrame.Request) -> Boolean,352): PairedDevice? {353 socket.send(354 JSONObject()355 .put("type", "PEACH_HELLO")356 .put("token", invitation.token)357 .toString()358 .toByteArray(Charsets.UTF_8),359 )360361 val ack = JSONObject(String(socket.receive(), Charsets.UTF_8))362 require(ack.optString("type") == "PEACH_HELLO_ACK") {363 "expected PEACH_HELLO_ACK"364 }365 366 367 368 369 370 371 val responderStatic = hexToPubkey(ack.optString("ephemeralPublicKeyHex"))372 val invitedStatic = invitation.noiseStaticPublicKeyHex373 ?.let(::hexToPubkey)374 ?: throw IllegalArgumentException("pairing_invitation_missing_static_key")375 val staticMatches = MessageDigest.isEqual(responderStatic, invitedStatic)376 invitedStatic.fill(0)377 if (!staticMatches) {378 responderStatic.fill(0)379 throw IllegalArgumentException("pairing_static_key_mismatch")380 }381 val noise = try {382 noiseNKInitiator(383 responderStatic,384 socket::send,385 socket::receive,386 )387 } finally {388 responderStatic.fill(0)389 }390 try {391 val channel = object : PairingTransport {392 override suspend fun send(msg: ByteArray) = socket.send(noise.encrypt(msg))393 override suspend fun receive(): ByteArray = noise.decrypt(socket.receive())394 override suspend fun close() = socket.close()395 }396 val request = receiveFrame(channel)397 if (request !is AdoptionFrame.RequestV2 && !isAdoptRequest(request)) return null398399 val pairState = AdoptionPairState(400 rendezvousSecretHex = Rendezvous.bytesToHex(401 Rendezvous.deriveSecret(noise.handshakeHash),402 ),403 relayUrl = invitation.relayUrl,404 )405 val boundDeps = bindSourceSessionDeps(406 sourceDeps = sourceDeps,407 sourceIdentity = sourceDeps.sourceIdentity,408 pairState = pairState,409 sas = SASDerivation.derive(noise.handshakeHash),410 snapshotCapable = true,411 confirm = confirm,412 )413 414 415 val adopted = when (request) {416 is AdoptionFrame.RequestV2 -> grantAdoptionV2(channel, request, boundDeps)417 is AdoptionFrame.Request -> {418 if (!confirm(SASDerivation.derive(noise.handshakeHash), request)) return null419 grantAdoption(channel, request, boundDeps)420 }421 else -> null422 } ?: return null423 424 val receiverWantsSnapshot = when (request) {425 is AdoptionFrame.Request -> request.snapshotCapable == true426 is AdoptionFrame.RequestV2 -> request.snapshotCapable == true427 else -> false428 }429 if (receiverWantsSnapshot) {430 try {431 val snapshot = boundDeps.vaultSnapshot()432 if (snapshot != null) {433 val duressSlot = runCatching { boundDeps.duressSlotJson() }.getOrNull()434 sendVaultSnapshot(channel, snapshot.first, snapshot.second, duressSlot)435 val applied = receiveFrame(channel)436 if (applied is AdoptionFrame.SnapshotApplied) {437 val manifest = boundDeps.outgoingDeviceManifest()438 if (manifest != null) {439 sendFrame(channel, AdoptionFrame.DeviceManifestFrame(manifest))440 withTimeoutOrNull(5_000) { receiveFrame(channel) }441 }442 boundDeps.markSynced(adopted.deviceId)443 }444 }445 } catch (error: Exception) {446 if (error is SnapshotDuressFrameTooLargeException) throw error447 if (error is CancellationException) throw error448 PeachSyncLog.w("adoption: snapshot send failed — reason=${relayLogReason(error)}")449 }450 }451 return adopted452 } finally {453 noise.close()454 }455}