RelayAdoptionReceiver.kt

21.0 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    private val generation: SyncGenerationPort,21    private val deviceStore: PairedDeviceRegistry,22) {23    /**24     * Phone as receiver: scan a [VaultStatus.POPULATED] invitation, dial the25     * relay room, complete Noise, and receive the source's root key. This is26     * the historical pairing direction and stays byte-for-byte unchanged.27     */28    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    /**52     * §11.3 REPAIRING → V2_ACTIVE. Any adoption that reaches here while this53     * device is still anchored is a v2 one: the post-reset source refuses v1 at54     * the first frame, and a v1 source cannot answer a v2 request.55     */56    private fun markRepairProgress() {57        onDirectV2PairingEstablished(58            generation,59            hasDirectDevice = deviceStore.getAll().any { it.trustSource == "direct" },60            nowMs = System.currentTimeMillis(),61        )62    }6364    /**65     * Phone as source: scan a [VaultStatus.EMPTY] invitation from an empty66     * device, dial the relay room, complete Noise, and hand our root key over.67     * Symmetric to [adopt]: the initiator runs Noise NK, but the payload68     * direction flips — the phone sends the grant, the empty device receives69     * it.70     */71    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}9495/**96 * Complete one receiver session and choose the correct socket shutdown.97 *98 * The final receiver action is an encrypted ADOPT_APPLIED frame. OkHttp's99 * send() only queues it, so a successful session must close gracefully; an100 * immediate cancel can discard that frame after both devices have already101 * persisted one another, leaving the source to report a false failure.102 */103internal 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}131132/**133 * Source-initiator counterpart to [adoptFromRelaySocket]: phone dials the134 * relay room, runs Noise as initiator, and hands the root key over to the135 * empty responder. The final source action is an encrypted ADOPT_COMPLETE,136 * so a graceful close is required to land it.137 */138internal 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}165166/**167 * Pure live-session seam used by both production and the real Noise interop168 * test. The source must already occupy the relay room before this starts.169 */170internal 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            // The v2 transcript presents this device's durable identity, which228            // exists before the vault does; the v1 path still derives its own.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        // Capture the source's snapshot capability so we can skip the 15s288        // inline-snapshot wait when the source has nothing to send.289        var sourceCanSendSnapshot = false290        val adopted = requestAdoptionV2(291            channel,292            boundDeps,293            onPrepare = { prepare -> sourceCanSendSnapshot = prepare.snapshotCapable == true },294        ) ?: return null295        if (sourceCanSendSnapshot) {296            // Try to receive the inline vault snapshot.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                    // Optional device manifest from source. Apply before acking so308                    // the receiver graduates into the mesh pool on the same309                    // adoption session; a missing or invalid long-term key is310                    // accepted (we still ack) because the graph can arrive via311                    // the regular sync path on the next SYNC_DEVICE_MANIFEST.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}338339/**340 * Phone-initiator source session for the "empty browser" invitation path.341 * The phone dials the relay room and waits for the empty responder to send342 * ADOPT_REQUEST, then hands over its root key through [grantAdoption]. The343 * SAS gate is the single commit signal — same model as the existing source344 * session — and onConsent is pre-cleared because the user already opted in345 * by scanning the QR.346 */347internal 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    // PB-26-103: authenticate the cleartext ACK against the static pinned in the366    // invitation before running Noise. This is the root-key-bearing direction —367    // the phone grants its vault here — so trusting the ACK lets a relay368    // terminate both sessions, present its own key to each side, and collect369    // ADOPT_GRANT.root_key_hex. The mirror check on the receiver path is at370    // runRelayAdoptionReceiverSession.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 = object : AdoptionSourceV2Deps {406            override val sourceIdentity = sourceDeps.sourceIdentity407            override val pairState = pairState408            override suspend fun rootKeyHex(): String = sourceDeps.rootKeyHex()409            override suspend fun vaultId(): String = sourceDeps.vaultId()410            override suspend fun license(): String? = sourceDeps.license()411            override suspend fun applyLicense(license: String) {412                sourceDeps.applyLicense(license)413            }414            override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true415416            // Called by the v2 transcript after ADOPT_CONFIRM_REQUIRED goes out,417            // so both prompts are live at once. The prompt itself is the same418            // human SAS comparison as v1; the label is never persisted.419            override suspend fun onConsent(request: AdoptionFrame.RequestV2): Boolean =420                confirm(421                    SASDerivation.derive(noise.handshakeHash),422                    AdoptionFrame.Request(423                        sessionRequestId = request.deviceId,424                        deviceName = request.deviceName,425                        deviceType = request.deviceType,426                        license = request.license,427                        snapshotCapable = request.snapshotCapable,428                    ),429                )430431            override suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long) =432                sourceDeps.persistPendingHolder(request, nowMs)433            override suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice) =434                sourceDeps.completePendingHolder(request, device)435            override suspend fun persistPendingIdentity(device: PairedDevice, nowMs: Long) =436                sourceDeps.persistPendingIdentity(device, nowMs)437            override suspend fun completePendingIdentity(device: PairedDevice) =438                sourceDeps.completePendingIdentity(device)439            override fun snapshotCapable(): Boolean = true440            override suspend fun upsertPairedDevice(device: PairedDevice) {441                sourceDeps.upsertPairedDevice(device)442            }443            override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =444                sourceDeps.hasDeviceIdentityCollision(device)445            override suspend fun rotateSourceIdentity(): LocalDeviceIdentity =446                sourceDeps.rotateSourceIdentity()447            override suspend fun vaultSnapshot() = sourceDeps.vaultSnapshot()448            override suspend fun outgoingDeviceManifest() = sourceDeps.outgoingDeviceManifest()449            override suspend fun markSynced(deviceId: String) = sourceDeps.markSynced(deviceId)450            override suspend fun duressSlotJson() = sourceDeps.duressSlotJson()451        }452        // A v2 receiver introduces itself first; a v1 receiver still opens with453        // the label-only ADOPT_REQUEST and is served by the legacy path.454        val adopted = when (request) {455            is AdoptionFrame.RequestV2 -> grantAdoptionV2(channel, request, boundDeps)456            is AdoptionFrame.Request -> {457                if (!confirm(SASDerivation.derive(noise.handshakeHash), request)) return null458                grantAdoption(channel, request, boundDeps)459            }460            else -> null461        } ?: return null462        // If the receiver advertised snapshot support, send the vault inline.463        val receiverWantsSnapshot = when (request) {464            is AdoptionFrame.Request -> request.snapshotCapable == true465            is AdoptionFrame.RequestV2 -> request.snapshotCapable == true466            else -> false467        }468        if (receiverWantsSnapshot) {469            try {470                val snapshot = boundDeps.vaultSnapshot()471                if (snapshot != null) {472                    val duressSlot = runCatching { boundDeps.duressSlotJson() }.getOrNull()473                    sendVaultSnapshot(channel, snapshot.first, snapshot.second, duressSlot)474                    val applied = receiveFrame(channel)475                    if (applied is AdoptionFrame.SnapshotApplied) {476                        val manifest = boundDeps.outgoingDeviceManifest()477                        if (manifest != null) {478                            sendFrame(channel, AdoptionFrame.DeviceManifestFrame(manifest))479                            withTimeoutOrNull(5_000) { receiveFrame(channel) }480                        }481                        boundDeps.markSynced(adopted.deviceId)482                    }483                }484            } catch (error: Exception) {485                if (error is SnapshotDuressFrameTooLargeException) throw error486                if (error is CancellationException) throw error487                PeachSyncLog.w("adoption: snapshot send failed — reason=${relayLogReason(error)}")488            }489        }490        return adopted491    } finally {492        noise.close()493    }494}