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 2122232425 suspend fun adopt(26 encodedInvitation: String,27 deps: AdoptionReceiverDeps,28 confirm: suspend (sas: String) -> Boolean,29 windowMs: Long = PAIRING_WINDOW_MS,30 ): PairedDevice {31 val invitation = parsePairingInvitation(encodedInvitation)32 ?: throw IllegalArgumentException("invalid_pairing_invitation")33 require(invitation.vaultStatus == VaultStatus.POPULATED) {34 "receiver adopt() expects a populated invitation; got ${invitation.vaultStatus}"35 }36 val socket = OkHttpRelaySocket.connectPairing(invitation.roomUrl())37 return adoptFromRelaySocket(38 socket = socket,39 invitation = invitation,40 deps = deps,41 confirm = confirm,42 windowMs = windowMs,43 )44 }4546 47484950515253 suspend fun grantFromInvitation(54 encodedInvitation: String,55 sourceDeps: AdoptionSourceDeps,56 confirm: suspend (sas: String, request: AdoptionFrame.Request) -> Boolean,57 windowMs: Long = PAIRING_WINDOW_MS,58 ): PairedDevice {59 val invitation = parsePairingInvitation(encodedInvitation)60 ?: throw IllegalArgumentException("invalid_pairing_invitation")61 require(invitation.vaultStatus == VaultStatus.EMPTY) {62 "grantFromInvitation() expects an empty invitation; got ${invitation.vaultStatus}"63 }64 val socket = OkHttpRelaySocket.connectPairing(invitation.roomUrl())65 return grantFromRelaySocket(66 socket = socket,67 invitation = invitation,68 sourceDeps = sourceDeps,69 confirm = confirm,70 windowMs = windowMs,71 )72 }73}74757677787980818283internal suspend fun adoptFromRelaySocket(84 socket: RelayBinarySocket,85 invitation: PairingInvitation,86 deps: AdoptionReceiverDeps,87 confirm: suspend (sas: String) -> Boolean,88 windowMs: Long = PAIRING_WINDOW_MS,89): PairedDevice {90 var completed = false91 return try {92 val adopted =93 withTimeout(windowMs) {94 runRelayAdoptionReceiverSession(95 socket = socket,96 invitation = invitation,97 receiverDeps = deps,98 confirm = confirm,99 ) ?: throw IllegalStateException("adoption_rejected")100 }101 completed = true102 adopted103 } finally {104 if (completed) {105 socket.closeAfterQueuedFrames()106 } else {107 socket.close()108 }109 }110}111112113114115116117118internal suspend fun grantFromRelaySocket(119 socket: RelayBinarySocket,120 invitation: PairingInvitation,121 sourceDeps: AdoptionSourceDeps,122 confirm: suspend (sas: String, request: AdoptionFrame.Request) -> Boolean,123 windowMs: Long = PAIRING_WINDOW_MS,124): PairedDevice {125 var completed = false126 return try {127 val granted = withTimeout(windowMs) {128 runRelayAdoptionInitiatorSourceSession(129 socket = socket,130 invitation = invitation,131 sourceDeps = sourceDeps,132 confirm = confirm,133 ) ?: throw IllegalStateException("adoption_rejected")134 }135 completed = true136 granted137 } finally {138 if (completed) {139 socket.closeAfterQueuedFrames()140 } else {141 socket.close()142 }143 }144}145146147148149150internal suspend fun runRelayAdoptionReceiverSession(151 socket: RelayBinarySocket,152 invitation: PairingInvitation,153 receiverDeps: AdoptionReceiverDeps,154 confirm: suspend (sas: String) -> Boolean,155): PairedDevice? {156 socket.send(157 JSONObject()158 .put("type", "PEACH_HELLO")159 .put("token", invitation.token)160 .toString()161 .toByteArray(Charsets.UTF_8),162 )163164 val ack = JSONObject(String(socket.receive(), Charsets.UTF_8))165 require(ack.optString("type") == "PEACH_HELLO_ACK") {166 "expected PEACH_HELLO_ACK"167 }168 val sourceStatic = hexToPubkey(ack.optString("ephemeralPublicKeyHex"))169 val invitedStatic = invitation.noiseStaticPublicKeyHex170 ?.let(::hexToPubkey)171 ?: throw IllegalArgumentException("pairing_invitation_missing_static_key")172 val staticMatches = MessageDigest.isEqual(sourceStatic, invitedStatic)173 invitedStatic.fill(0)174 if (!staticMatches) {175 sourceStatic.fill(0)176 throw IllegalArgumentException("pairing_static_key_mismatch")177 }178 val noise = try {179 noiseNKInitiator(180 sourceStatic,181 socket::send,182 socket::receive,183 )184 } finally {185 sourceStatic.fill(0)186 }187 try {188 val channel = object : PairingTransport {189 override suspend fun send(msg: ByteArray) = socket.send(noise.encrypt(msg))190 override suspend fun receive(): ByteArray = noise.decrypt(socket.receive())191 override suspend fun close() = socket.close()192 }193 val pairState = AdoptionPairState(194 rendezvousSecretHex = Rendezvous.bytesToHex(195 Rendezvous.deriveSecret(noise.handshakeHash),196 ),197 relayUrl = invitation.relayUrl,198 )199 val boundDeps = object : AdoptionReceiverDeps {200 override val deviceName = receiverDeps.deviceName201 override val deviceType = receiverDeps.deviceType202 override val pairState = pairState203 override fun generateDeviceId() = receiverDeps.generateDeviceId()204 override suspend fun confirmSas(): Boolean =205 confirm(SASDerivation.derive(noise.handshakeHash))206207 override suspend fun validateSource(source: AdoptionFrame.Source) {208 receiverDeps.validateSource(source)209 }210211 override suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source): Boolean =212 receiverDeps.hasSourceIdentityCollision(source)213214 override suspend fun createVaultFromRootKey(rootKeyHex: String): String =215 receiverDeps.createVaultFromRootKey(rootKeyHex)216217 override suspend fun deriveLocalIdentity(): LocalDeviceIdentity =218 receiverDeps.deriveLocalIdentity()219 override suspend fun clearPairedDeviceRevocation(deviceId: String) {220 receiverDeps.clearPairedDeviceRevocation(deviceId)221 }222223 override suspend fun upsertPairedDeviceAndClearRevocation(device: PairedDevice) {224 receiverDeps.upsertPairedDeviceAndClearRevocation(device)225 }226227 override suspend fun upsertPairedDevice(device: PairedDevice) {228 receiverDeps.upsertPairedDevice(device)229 }230231 override suspend fun applyLicense(license: String) {232 receiverDeps.applyLicense(license)233 }234235 override suspend fun license(): String? = receiverDeps.license()236237 override fun onError(error: String) {238 receiverDeps.onError(error)239 }240 override suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String?) {241 receiverDeps.applySnapshot(entries, tombstones, duressSlot)242 }243 override suspend fun applyIncomingDeviceManifest(244 manifest: SignedDeviceManifest,245 authenticatedRemoteStaticPublicKey: ByteArray,246 ) {247 receiverDeps.applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey)248 }249 override suspend fun markSynced(deviceId: String) {250 receiverDeps.markSynced(deviceId)251 }252 }253 254 255 256 var sourceCanSendSnapshot = false257 val adopted = requestAdoption(258 channel,259 boundDeps,260 onGrant = { grant -> sourceCanSendSnapshot = grant.snapshotCapable },261 ) ?: return null262 if (sourceCanSendSnapshot) {263 264 try {265 val snapshot = withTimeoutOrNull(15_000) {266 receiveVaultSnapshot(channel)267 }268 if (snapshot != null) {269 boundDeps.applySnapshot(snapshot.entries, snapshot.tombstones, snapshot.duressSlot)270 sendFrame(channel, AdoptionFrame.SnapshotApplied(271 entriesReceived = snapshot.entries.size,272 tombstonesReceived = snapshot.tombstones.size,273 ))274 275 276 277 278 279 try {280 val manifestFrame = withTimeoutOrNull(5_000) { receiveFrame(channel) }281 if (manifestFrame is AdoptionFrame.DeviceManifestFrame) {282 val sourceLongTerm = adopted.longTermPublicKeyHex283 if (sourceLongTerm != null && sourceLongTerm.length == 64) {284 boundDeps.applyIncomingDeviceManifest(285 manifestFrame.manifest,286 hexToPubkey(sourceLongTerm),287 )288 }289 sendFrame(channel, AdoptionFrame.DeviceManifestApplied)290 }291 } catch (_: Exception) {}292 boundDeps.markSynced(adopted.deviceId)293 } else {294 PeachSyncLog.i("adoption: snapshot receive timed out")295 }296 } catch (e: Exception) {297 PeachSyncLog.w("adoption: snapshot receive failed — reason=${relayLogReason(e)}")298 }299 }300 return adopted301 } finally {302 noise.close()303 }304}305306307308309310311312313314internal suspend fun runRelayAdoptionInitiatorSourceSession(315 socket: RelayBinarySocket,316 invitation: PairingInvitation,317 sourceDeps: AdoptionSourceDeps,318 confirm: suspend (sas: String, request: AdoptionFrame.Request) -> Boolean,319): PairedDevice? {320 socket.send(321 JSONObject()322 .put("type", "PEACH_HELLO")323 .put("token", invitation.token)324 .toString()325 .toByteArray(Charsets.UTF_8),326 )327328 val ack = JSONObject(String(socket.receive(), Charsets.UTF_8))329 require(ack.optString("type") == "PEACH_HELLO_ACK") {330 "expected PEACH_HELLO_ACK"331 }332 333 334 335 336 337 338 val responderStatic = hexToPubkey(ack.optString("ephemeralPublicKeyHex"))339 val invitedStatic = invitation.noiseStaticPublicKeyHex340 ?.let(::hexToPubkey)341 ?: throw IllegalArgumentException("pairing_invitation_missing_static_key")342 val staticMatches = MessageDigest.isEqual(responderStatic, invitedStatic)343 invitedStatic.fill(0)344 if (!staticMatches) {345 responderStatic.fill(0)346 throw IllegalArgumentException("pairing_static_key_mismatch")347 }348 val noise = try {349 noiseNKInitiator(350 responderStatic,351 socket::send,352 socket::receive,353 )354 } finally {355 responderStatic.fill(0)356 }357 try {358 val channel = object : PairingTransport {359 override suspend fun send(msg: ByteArray) = socket.send(noise.encrypt(msg))360 override suspend fun receive(): ByteArray = noise.decrypt(socket.receive())361 override suspend fun close() = socket.close()362 }363 val request = receiveFrame(channel)364 if (!isAdoptRequest(request)) return null365 request as AdoptionFrame.Request366 if (!confirm(SASDerivation.derive(noise.handshakeHash), request)) return null367368 val pairState = AdoptionPairState(369 rendezvousSecretHex = Rendezvous.bytesToHex(370 Rendezvous.deriveSecret(noise.handshakeHash),371 ),372 relayUrl = invitation.relayUrl,373 )374 val boundDeps = object : AdoptionSourceDeps {375 override val sourceIdentity = sourceDeps.sourceIdentity376 override val pairState = pairState377 override suspend fun rootKeyHex(): String = sourceDeps.rootKeyHex()378 override suspend fun vaultId(): String = sourceDeps.vaultId()379 override suspend fun license(): String? = sourceDeps.license()380 override suspend fun applyLicense(license: String) {381 sourceDeps.applyLicense(license)382 }383 override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true384 override suspend fun upsertPairedDevice(device: PairedDevice) {385 sourceDeps.upsertPairedDevice(device)386 }387 override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =388 sourceDeps.hasDeviceIdentityCollision(device)389 override suspend fun rotateSourceIdentity(): LocalDeviceIdentity =390 sourceDeps.rotateSourceIdentity()391 override suspend fun vaultSnapshot() = sourceDeps.vaultSnapshot()392 override suspend fun outgoingDeviceManifest() = sourceDeps.outgoingDeviceManifest()393 override suspend fun markSynced(deviceId: String) = sourceDeps.markSynced(deviceId)394 override suspend fun duressSlotJson() = sourceDeps.duressSlotJson()395 }396 val adopted = grantAdoption(channel, request, boundDeps) ?: return null397 398 if (request.snapshotCapable == true) {399 try {400 val snapshot = boundDeps.vaultSnapshot()401 if (snapshot != null) {402 val duressSlot = runCatching { boundDeps.duressSlotJson() }.getOrNull()403 sendVaultSnapshot(channel, snapshot.first, snapshot.second, duressSlot)404 val applied = receiveFrame(channel)405 if (applied is AdoptionFrame.SnapshotApplied) {406 val manifest = boundDeps.outgoingDeviceManifest()407 if (manifest != null) {408 sendFrame(channel, AdoptionFrame.DeviceManifestFrame(manifest))409 withTimeoutOrNull(5_000) { receiveFrame(channel) }410 }411 boundDeps.markSynced(adopted.deviceId)412 }413 }414 } catch (error: Exception) {415 if (error is SnapshotDuressFrameTooLargeException) throw error416 if (error is CancellationException) throw error417 PeachSyncLog.w("adoption: snapshot send failed — reason=${relayLogReason(error)}")418 }419 }420 return adopted421 } finally {422 noise.close()423 }424}