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: AdoptionReceiverV2Deps,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: AdoptionSourceV2Deps,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: AdoptionReceiverV2Deps,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: AdoptionSourceV2Deps,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: AdoptionReceiverV2Deps,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 : AdoptionReceiverV2Deps {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 208 209 override fun localIdentity(): LocalDeviceIdentity = receiverDeps.localIdentity()210211 override suspend fun rotateLocalIdentity(): LocalDeviceIdentity =212 receiverDeps.rotateLocalIdentity()213214 override suspend fun validateSource(prepare: AdoptionFrame.Prepare) {215 receiverDeps.validateSource(prepare)216 }217218 override suspend fun hasSourceIdentityCollision(prepare: AdoptionFrame.Prepare): Boolean =219 receiverDeps.hasSourceIdentityCollision(prepare)220221 override suspend fun validateSource(source: AdoptionFrame.Source) {222 receiverDeps.validateSource(source)223 }224225 override suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source): Boolean =226 receiverDeps.hasSourceIdentityCollision(source)227228 override suspend fun createVaultFromRootKey(rootKeyHex: String): String =229 receiverDeps.createVaultFromRootKey(rootKeyHex)230231 override suspend fun deriveLocalIdentity(): LocalDeviceIdentity =232 receiverDeps.deriveLocalIdentity()233 override suspend fun clearPairedDeviceRevocation(deviceId: String) {234 receiverDeps.clearPairedDeviceRevocation(deviceId)235 }236237 override suspend fun upsertPairedDeviceAndClearRevocation(device: PairedDevice) {238 receiverDeps.upsertPairedDeviceAndClearRevocation(device)239 }240241 override suspend fun upsertPairedDevice(device: PairedDevice) {242 receiverDeps.upsertPairedDevice(device)243 }244245 override suspend fun applyLicense(license: String) {246 receiverDeps.applyLicense(license)247 }248249 override suspend fun license(): String? = receiverDeps.license()250251 override fun onError(error: String) {252 receiverDeps.onError(error)253 }254 override suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String?) {255 receiverDeps.applySnapshot(entries, tombstones, duressSlot)256 }257 override suspend fun applyIncomingDeviceManifest(258 manifest: SignedDeviceManifest,259 authenticatedRemoteStaticPublicKey: ByteArray,260 ) {261 receiverDeps.applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey)262 }263 override suspend fun markSynced(deviceId: String) {264 receiverDeps.markSynced(deviceId)265 }266 }267 268 269 var sourceCanSendSnapshot = false270 val adopted = requestAdoptionV2(271 channel,272 boundDeps,273 onPrepare = { prepare -> sourceCanSendSnapshot = prepare.snapshotCapable == true },274 ) ?: return null275 if (sourceCanSendSnapshot) {276 277 try {278 val snapshot = withTimeoutOrNull(15_000) {279 receiveVaultSnapshot(channel)280 }281 if (snapshot != null) {282 boundDeps.applySnapshot(snapshot.entries, snapshot.tombstones, snapshot.duressSlot)283 sendFrame(channel, AdoptionFrame.SnapshotApplied(284 entriesReceived = snapshot.entries.size,285 tombstonesReceived = snapshot.tombstones.size,286 ))287 288 289 290 291 292 try {293 val manifestFrame = withTimeoutOrNull(5_000) { receiveFrame(channel) }294 if (manifestFrame is AdoptionFrame.DeviceManifestFrame) {295 val sourceLongTerm = adopted.longTermPublicKeyHex296 if (sourceLongTerm != null && sourceLongTerm.length == 64) {297 boundDeps.applyIncomingDeviceManifest(298 manifestFrame.manifest,299 hexToPubkey(sourceLongTerm),300 )301 }302 sendFrame(channel, AdoptionFrame.DeviceManifestApplied)303 }304 } catch (_: Exception) {}305 boundDeps.markSynced(adopted.deviceId)306 } else {307 PeachSyncLog.i("adoption: snapshot receive timed out")308 }309 } catch (e: Exception) {310 PeachSyncLog.w("adoption: snapshot receive failed — reason=${relayLogReason(e)}")311 }312 }313 return adopted314 } finally {315 noise.close()316 }317}318319320321322323324325326327internal suspend fun runRelayAdoptionInitiatorSourceSession(328 socket: RelayBinarySocket,329 invitation: PairingInvitation,330 sourceDeps: AdoptionSourceV2Deps,331 confirm: suspend (sas: String, request: AdoptionFrame.Request) -> Boolean,332): PairedDevice? {333 socket.send(334 JSONObject()335 .put("type", "PEACH_HELLO")336 .put("token", invitation.token)337 .toString()338 .toByteArray(Charsets.UTF_8),339 )340341 val ack = JSONObject(String(socket.receive(), Charsets.UTF_8))342 require(ack.optString("type") == "PEACH_HELLO_ACK") {343 "expected PEACH_HELLO_ACK"344 }345 346 347 348 349 350 351 val responderStatic = hexToPubkey(ack.optString("ephemeralPublicKeyHex"))352 val invitedStatic = invitation.noiseStaticPublicKeyHex353 ?.let(::hexToPubkey)354 ?: throw IllegalArgumentException("pairing_invitation_missing_static_key")355 val staticMatches = MessageDigest.isEqual(responderStatic, invitedStatic)356 invitedStatic.fill(0)357 if (!staticMatches) {358 responderStatic.fill(0)359 throw IllegalArgumentException("pairing_static_key_mismatch")360 }361 val noise = try {362 noiseNKInitiator(363 responderStatic,364 socket::send,365 socket::receive,366 )367 } finally {368 responderStatic.fill(0)369 }370 try {371 val channel = object : PairingTransport {372 override suspend fun send(msg: ByteArray) = socket.send(noise.encrypt(msg))373 override suspend fun receive(): ByteArray = noise.decrypt(socket.receive())374 override suspend fun close() = socket.close()375 }376 val request = receiveFrame(channel)377 if (request !is AdoptionFrame.RequestV2 && !isAdoptRequest(request)) return null378379 val pairState = AdoptionPairState(380 rendezvousSecretHex = Rendezvous.bytesToHex(381 Rendezvous.deriveSecret(noise.handshakeHash),382 ),383 relayUrl = invitation.relayUrl,384 )385 val boundDeps = object : AdoptionSourceV2Deps {386 override val sourceIdentity = sourceDeps.sourceIdentity387 override val pairState = pairState388 override suspend fun rootKeyHex(): String = sourceDeps.rootKeyHex()389 override suspend fun vaultId(): String = sourceDeps.vaultId()390 override suspend fun license(): String? = sourceDeps.license()391 override suspend fun applyLicense(license: String) {392 sourceDeps.applyLicense(license)393 }394 override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true395396 397 398 399 override suspend fun onConsent(request: AdoptionFrame.RequestV2): Boolean =400 confirm(401 SASDerivation.derive(noise.handshakeHash),402 AdoptionFrame.Request(403 sessionRequestId = request.deviceId,404 deviceName = request.deviceName,405 deviceType = request.deviceType,406 license = request.license,407 snapshotCapable = request.snapshotCapable,408 ),409 )410411 override suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long) =412 sourceDeps.persistPendingHolder(request, nowMs)413 override suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice) =414 sourceDeps.completePendingHolder(request, device)415 override suspend fun persistPendingIdentity(device: PairedDevice, nowMs: Long) =416 sourceDeps.persistPendingIdentity(device, nowMs)417 override suspend fun completePendingIdentity(device: PairedDevice) =418 sourceDeps.completePendingIdentity(device)419 override fun snapshotCapable(): Boolean = true420 override suspend fun upsertPairedDevice(device: PairedDevice) {421 sourceDeps.upsertPairedDevice(device)422 }423 override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =424 sourceDeps.hasDeviceIdentityCollision(device)425 override suspend fun rotateSourceIdentity(): LocalDeviceIdentity =426 sourceDeps.rotateSourceIdentity()427 override suspend fun vaultSnapshot() = sourceDeps.vaultSnapshot()428 override suspend fun outgoingDeviceManifest() = sourceDeps.outgoingDeviceManifest()429 override suspend fun markSynced(deviceId: String) = sourceDeps.markSynced(deviceId)430 override suspend fun duressSlotJson() = sourceDeps.duressSlotJson()431 }432 433 434 val adopted = when (request) {435 is AdoptionFrame.RequestV2 -> grantAdoptionV2(channel, request, boundDeps)436 is AdoptionFrame.Request -> {437 if (!confirm(SASDerivation.derive(noise.handshakeHash), request)) return null438 grantAdoption(channel, request, boundDeps)439 }440 else -> null441 } ?: return null442 443 val receiverWantsSnapshot = when (request) {444 is AdoptionFrame.Request -> request.snapshotCapable == true445 is AdoptionFrame.RequestV2 -> request.snapshotCapable == true446 else -> false447 }448 if (receiverWantsSnapshot) {449 try {450 val snapshot = boundDeps.vaultSnapshot()451 if (snapshot != null) {452 val duressSlot = runCatching { boundDeps.duressSlotJson() }.getOrNull()453 sendVaultSnapshot(channel, snapshot.first, snapshot.second, duressSlot)454 val applied = receiveFrame(channel)455 if (applied is AdoptionFrame.SnapshotApplied) {456 val manifest = boundDeps.outgoingDeviceManifest()457 if (manifest != null) {458 sendFrame(channel, AdoptionFrame.DeviceManifestFrame(manifest))459 withTimeoutOrNull(5_000) { receiveFrame(channel) }460 }461 boundDeps.markSynced(adopted.deviceId)462 }463 }464 } catch (error: Exception) {465 if (error is SnapshotDuressFrameTooLargeException) throw error466 if (error is CancellationException) throw error467 PeachSyncLog.w("adoption: snapshot send failed — reason=${relayLogReason(error)}")468 }469 }470 return adopted471 } finally {472 noise.close()473 }474}