RelayAdoptionReceiver.kt

17.5 KB · raw

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.hexToPubkey1112/**13 * Receiver half of relay-first vault adoption.14 *15 * The invitation is reachability only. The relay never sees identity, SAS, or16 * vault material; those enter only after the Noise NK session is established.17 */18@Singleton19class RelayAdoptionReceiver @Inject constructor() {20    /**21     * Phone as receiver: scan a [VaultStatus.POPULATED] invitation, dial the22     * relay room, complete Noise, and receive the source's root key. This is23     * the historical pairing direction and stays byte-for-byte unchanged.24     */25    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    /**47     * Phone as source: scan a [VaultStatus.EMPTY] invitation from an empty48     * device, dial the relay room, complete Noise, and hand our root key over.49     * Symmetric to [adopt]: the initiator runs Noise NK, but the payload50     * direction flips — the phone sends the grant, the empty device receives51     * it.52     */53    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}7475/**76 * Complete one receiver session and choose the correct socket shutdown.77 *78 * The final receiver action is an encrypted ADOPT_APPLIED frame. OkHttp's79 * send() only queues it, so a successful session must close gracefully; an80 * immediate cancel can discard that frame after both devices have already81 * persisted one another, leaving the source to report a false failure.82 */83internal 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}111112/**113 * Source-initiator counterpart to [adoptFromRelaySocket]: phone dials the114 * relay room, runs Noise as initiator, and hands the root key over to the115 * empty responder. The final source action is an encrypted ADOPT_COMPLETE,116 * so a graceful close is required to land it.117 */118internal 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}145146/**147 * Pure live-session seam used by both production and the real Noise interop148 * test. The source must already occupy the relay room before this starts.149 */150internal 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()219220            override suspend fun clearPairedDeviceRevocation(deviceId: String) {221                receiverDeps.clearPairedDeviceRevocation(deviceId)222            }223224            override suspend fun upsertPairedDevice(device: PairedDevice) {225                receiverDeps.upsertPairedDevice(device)226            }227228            override suspend fun applyLicense(license: String) {229                receiverDeps.applyLicense(license)230            }231232            override suspend fun license(): String? = receiverDeps.license()233234            override fun onError(error: String) {235                receiverDeps.onError(error)236            }237            override suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String?) {238                receiverDeps.applySnapshot(entries, tombstones, duressSlot)239            }240            override suspend fun applyIncomingDeviceManifest(241                manifest: SignedDeviceManifest,242                authenticatedRemoteStaticPublicKey: ByteArray,243            ) {244                receiverDeps.applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey)245            }246            override suspend fun markSynced(deviceId: String) {247                receiverDeps.markSynced(deviceId)248            }249        }250        // Capture the source's ADOPT_GRANT.snapshot_capable echo so we can skip251        // the 15s inline-snapshot wait when the source has nothing to send.252        // Default false = "pre-C source, no echo" = skip the wait.253        var sourceCanSendSnapshot = false254        val adopted = requestAdoption(255            channel,256            boundDeps,257            onGrant = { grant -> sourceCanSendSnapshot = grant.snapshotCapable },258        ) ?: return null259        if (sourceCanSendSnapshot) {260            // Try to receive the inline vault snapshot.261            try {262                val snapshot = withTimeoutOrNull(15_000) {263                    receiveVaultSnapshot(channel)264                }265                if (snapshot != null) {266                    boundDeps.applySnapshot(snapshot.entries, snapshot.tombstones, snapshot.duressSlot)267                    sendFrame(channel, AdoptionFrame.SnapshotApplied(268                        entriesReceived = snapshot.entries.size,269                        tombstonesReceived = snapshot.tombstones.size,270                    ))271                    // Optional device manifest from source. Apply before acking so272                    // the receiver graduates into the mesh pool on the same273                    // adoption session; a missing or invalid long-term key is274                    // accepted (we still ack) because the graph can arrive via275                    // the regular sync path on the next SYNC_DEVICE_MANIFEST.276                    try {277                        val manifestFrame = withTimeoutOrNull(5_000) { receiveFrame(channel) }278                        if (manifestFrame is AdoptionFrame.DeviceManifestFrame) {279                            val sourceLongTerm = adopted.longTermPublicKeyHex280                            if (sourceLongTerm != null && sourceLongTerm.length == 64) {281                                boundDeps.applyIncomingDeviceManifest(282                                    manifestFrame.manifest,283                                    hexToPubkey(sourceLongTerm),284                                )285                            }286                            sendFrame(channel, AdoptionFrame.DeviceManifestApplied)287                        }288                    } catch (_: Exception) {}289                    boundDeps.markSynced(adopted.deviceId)290                } else {291                    PeachSyncLog.i("adoption: snapshot receive timed out")292                }293            } catch (e: Exception) {294                PeachSyncLog.w("adoption: snapshot receive failed — reason=${relayLogReason(e)}")295            }296        }297        return adopted298    } finally {299        noise.close()300    }301}302303/**304 * Phone-initiator source session for the "empty browser" invitation path.305 * The phone dials the relay room and waits for the empty responder to send306 * ADOPT_REQUEST, then hands over its root key through [grantAdoption]. The307 * SAS gate is the single commit signal — same model as the existing source308 * session — and onConsent is pre-cleared because the user already opted in309 * by scanning the QR.310 */311internal suspend fun runRelayAdoptionInitiatorSourceSession(312    socket: RelayBinarySocket,313    invitation: PairingInvitation,314    sourceDeps: AdoptionSourceDeps,315    confirm: suspend (sas: String, request: AdoptionFrame.Request) -> Boolean,316): PairedDevice? {317    socket.send(318        JSONObject()319            .put("type", "PEACH_HELLO")320            .put("token", invitation.token)321            .toString()322            .toByteArray(Charsets.UTF_8),323    )324325    val ack = JSONObject(String(socket.receive(), Charsets.UTF_8))326    require(ack.optString("type") == "PEACH_HELLO_ACK") {327        "expected PEACH_HELLO_ACK"328    }329    // PB-26-103: authenticate the cleartext ACK against the static pinned in the330    // invitation before running Noise. This is the root-key-bearing direction —331    // the phone grants its vault here — so trusting the ACK lets a relay332    // terminate both sessions, present its own key to each side, and collect333    // ADOPT_GRANT.root_key_hex. The mirror check on the receiver path is at334    // runRelayAdoptionReceiverSession.335    val responderStatic = hexToPubkey(ack.optString("ephemeralPublicKeyHex"))336    val invitedStatic = invitation.noiseStaticPublicKeyHex337        ?.let(::hexToPubkey)338        ?: throw IllegalArgumentException("pairing_invitation_missing_static_key")339    val staticMatches = MessageDigest.isEqual(responderStatic, invitedStatic)340    invitedStatic.fill(0)341    if (!staticMatches) {342        responderStatic.fill(0)343        throw IllegalArgumentException("pairing_static_key_mismatch")344    }345    val noise = try {346        noiseNKInitiator(347            responderStatic,348            socket::send,349            socket::receive,350        )351    } finally {352        responderStatic.fill(0)353    }354    try {355        val channel = object : PairingTransport {356            override suspend fun send(msg: ByteArray) = socket.send(noise.encrypt(msg))357            override suspend fun receive(): ByteArray = noise.decrypt(socket.receive())358            override suspend fun close() = socket.close()359        }360        val request = receiveFrame(channel)361        if (!isAdoptRequest(request)) return null362        request as AdoptionFrame.Request363        if (!confirm(SASDerivation.derive(noise.handshakeHash), request)) return null364365        val pairState = AdoptionPairState(366            rendezvousSecretHex = Rendezvous.bytesToHex(367                Rendezvous.deriveSecret(noise.handshakeHash),368            ),369            relayUrl = invitation.relayUrl,370        )371        val boundDeps = object : AdoptionSourceDeps {372            override val sourceIdentity = sourceDeps.sourceIdentity373            override val pairState = pairState374            override suspend fun rootKeyHex(): String = sourceDeps.rootKeyHex()375            override suspend fun vaultId(): String = sourceDeps.vaultId()376            override suspend fun license(): String? = sourceDeps.license()377            override suspend fun applyLicense(license: String) {378                sourceDeps.applyLicense(license)379            }380            override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true381            override suspend fun upsertPairedDevice(device: PairedDevice) {382                sourceDeps.upsertPairedDevice(device)383            }384            override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =385                sourceDeps.hasDeviceIdentityCollision(device)386            override suspend fun rotateSourceIdentity(): LocalDeviceIdentity =387                sourceDeps.rotateSourceIdentity()388            override suspend fun vaultSnapshot() = sourceDeps.vaultSnapshot()389            override suspend fun outgoingDeviceManifest() = sourceDeps.outgoingDeviceManifest()390            override suspend fun markSynced(deviceId: String) = sourceDeps.markSynced(deviceId)391            override suspend fun duressSlotJson() = sourceDeps.duressSlotJson()392        }393        val adopted = grantAdoption(channel, request, boundDeps) ?: return null394        // If the receiver advertised snapshot support, send the vault inline.395        if (request.snapshotCapable == true) {396            try {397                val snapshot = boundDeps.vaultSnapshot()398                if (snapshot != null) {399                    val duressSlot = runCatching { boundDeps.duressSlotJson() }.getOrNull()400                    sendVaultSnapshot(channel, snapshot.first, snapshot.second, duressSlot)401                    val applied = receiveFrame(channel)402                    if (applied is AdoptionFrame.SnapshotApplied) {403                        val manifest = boundDeps.outgoingDeviceManifest()404                        if (manifest != null) {405                            sendFrame(channel, AdoptionFrame.DeviceManifestFrame(manifest))406                            withTimeoutOrNull(5_000) { receiveFrame(channel) }407                        }408                        boundDeps.markSynced(adopted.deviceId)409                    }410                }411            } catch (error: Exception) {412                if (error is SnapshotDuressFrameTooLargeException) throw error413                if (error is CancellationException) throw error414                PeachSyncLog.w("adoption: snapshot send failed — reason=${relayLogReason(error)}")415            }416        }417        return adopted418    } finally {419        noise.close()420    }421}