RelayAdoptionHost.kt

13.4 KB · raw

1package com.peachpasswords.sync23import java.security.MessageDigest4import javax.inject.Inject5import javax.inject.Singleton6import kotlinx.coroutines.CoroutineScope7import kotlinx.coroutines.Dispatchers8import kotlinx.coroutines.Job9import kotlinx.coroutines.channels.awaitClose10import kotlinx.coroutines.flow.Flow11import kotlinx.coroutines.flow.callbackFlow12import kotlinx.coroutines.launch13import kotlinx.coroutines.withTimeout14import kotlinx.coroutines.withTimeoutOrNull15import org.json.JSONObject1617sealed interface RelayAdoptionEvent {18    /** The source is already occupying the non-buffering room; it is safe to show this. */19    data class InvitationReady(val invitation: String) : RelayAdoptionEvent20    data class AwaitingPeerConfirmation(21        val sas: String,22        val deviceName: String,23    ) : RelayAdoptionEvent24    data class Adopted(val deviceName: String) : RelayAdoptionEvent25    data object Expired : RelayAdoptionEvent26    data class Rejected(val reason: String) : RelayAdoptionEvent27}2829@Singleton30class RelayAdoptionHost @Inject constructor(31    private val relaySettings: RelaySettingsStore,32    private val generation: SyncGenerationPort,33    private val deviceStore: PairedDeviceRegistry,34) {35    private var job: Job? = null36    private var socket: RelayBinarySocket? = null3738    fun start(39        scope: CoroutineScope,40        ourStaticPrivateKey: ByteArray,41        ourStaticPublicKey: ByteArray,42        localIdentity: LocalDeviceIdentity,43        sourceDeps: AdoptionSourceV2Deps,44        windowMs: Long = PAIRING_WINDOW_MS,45    ): Flow<RelayAdoptionEvent> = callbackFlow {46        // Pairing is also how this mesh's relay reaches a new peer: the address47        // in the invitation is the one the receiver will dial for ever after.48        // Handing out Peach's relay while the user has asked for a private one49        // would push the same lie one layer down, into the mesh.50        val relayUrl = when (val decision = relaySettings.relayInForce()) {51            is RelayDecision.Refuse -> {52                trySend(RelayAdoptionEvent.Rejected(decision.reason.wire()))53                close()54                return@callbackFlow55            }5657            is RelayDecision.Dial -> decision.relayUrl58        }59        val token = Rendezvous.newPairingToken()60        val invitation = createPairingInvitation(61            relayUrl,62            token,63            noiseStaticPublicKeyHex = Rendezvous.bytesToHex(ourStaticPublicKey),64        )6566        job = scope.launch(Dispatchers.IO) {67            try {68                val connected = OkHttpRelaySocket.connectPairing(69                    Rendezvous.buildUrl(relayUrl, token),70                )71                socket = connected72                // The relay buffers nothing, so the invitation is not surfaced73                // until the source WebSocket is open and waiting in the room.74                trySend(RelayAdoptionEvent.InvitationReady(invitation))7576                var peerOutdated = false77                val adopted = withTimeout(windowMs) {78                    runRelayAdoptionSourceSession(79                        socket = connected,80                        expectedToken = token,81                        relayUrl = relayUrl,82                        ourStaticPrivateKey = ourStaticPrivateKey,83                        ourStaticPublicKey = ourStaticPublicKey,84                        localIdentity = localIdentity,85                        sourceDeps = sourceDeps,86                        // §11.6: once this device has reset its generation, a v187                        // peer is repair-required exactly as an outdated sync88                        // peer is. The invitation still goes out; the refusal89                        // happens at the first frame.90                        postReset = { generation.isPostReset(System.currentTimeMillis()) },91                        onPeerOutdated = { peerOutdated = true },92                        confirm = { sas, request ->93                            trySend(94                                RelayAdoptionEvent.AwaitingPeerConfirmation(95                                    sas = sas,96                                    deviceName = capDeviceName(request.deviceName.ifBlank { "New device" }),97                                ),98                            )99                            // Showing a fresh invitation from an unlocked vault100                            // is source-side authorization. The scanning device's101                            // explicit SAS confirmation is the single commit gate.102                            true103                        },104                    )105                }106                if (peerOutdated) {107                    trySend(RelayAdoptionEvent.Rejected(PEER_PROTOCOL_OUTDATED))108                } else if (adopted == null) {109                    trySend(RelayAdoptionEvent.Rejected("adoption_rejected"))110                } else {111                    onDirectV2PairingEstablished(112                        generation,113                        hasDirectDevice = deviceStore.getAll().any { it.trustSource == "direct" },114                        nowMs = System.currentTimeMillis(),115                    )116                    trySend(117                        RelayAdoptionEvent.Adopted(118                            capDeviceName(adopted.deviceName?.takeIf(String::isNotBlank) ?: "New device"),119                        ),120                    )121                }122            } catch (error: kotlinx.coroutines.TimeoutCancellationException) {123                trySend(RelayAdoptionEvent.Expired)124            } catch (error: kotlinx.coroutines.CancellationException) {125                // stop() cancels this job when the user leaves the screen or126                // restarts pairing. That is not a pairing failure — reporting it127                // as one raced the new session and replaced the freshly shown128                // code with "Couldn't pair: StandaloneCoroutine was cancelled".129                // Cancellation must propagate, never be swallowed.130                throw error131            } catch (error: Throwable) {132                trySend(RelayAdoptionEvent.Rejected(error.message ?: "relay_adoption_failed"))133            } finally {134                socket?.close()135                socket = null136                close()137            }138        }139140        awaitClose { stop() }141    }142143    fun stop() {144        job?.cancel()145        job = null146        socket?.close()147        socket = null148    }149}150151/**152 * Source half of first-contact adoption through an opaque relay splice.153 *154 * The relay token selects only a room. Authentication and confidentiality155 * begin with Noise NK; the root grant remains behind both SAS decisions in156 * [grantAdoption].157 */158internal suspend fun runRelayAdoptionSourceSession(159    socket: RelayBinarySocket,160    expectedToken: String,161    relayUrl: String,162    ourStaticPrivateKey: ByteArray,163    ourStaticPublicKey: ByteArray,164    localIdentity: LocalDeviceIdentity,165    sourceDeps: AdoptionSourceV2Deps,166    confirm: suspend (sas: String, request: AdoptionFrame.Request) -> Boolean,167    postReset: () -> Boolean = { false },168    onPeerOutdated: () -> Unit = {},169): PairedDevice? {170    val hello = JSONObject(String(socket.receive(), Charsets.UTF_8))171    require(hello.optString("type") == "PEACH_HELLO") { "expected PEACH_HELLO" }172    require(173        MessageDigest.isEqual(174            expectedToken.toByteArray(Charsets.US_ASCII),175            hello.optString("token").toByteArray(Charsets.US_ASCII),176        ),177    ) { "pairing token mismatch" }178179    socket.send(180        JSONObject()181            .put("type", "PEACH_HELLO_ACK")182            .put(183                "ephemeralPublicKeyHex",184                ourStaticPublicKey.joinToString("") { "%02x".format(it) },185            )186            .toString()187            .toByteArray(Charsets.UTF_8),188    )189190    val noise = noiseNKResponder(191        ourStaticPrivateKey,192        ourStaticPublicKey,193        socket::send,194        socket::receive,195    )196    try {197        val channel = object : PairingTransport {198            override suspend fun send(msg: ByteArray) = socket.send(noise.encrypt(msg))199            override suspend fun receive(): ByteArray = noise.decrypt(socket.receive())200            override suspend fun close() = socket.close()201        }202203        val request = receiveFrame(channel)204        require(request is AdoptionFrame.Request || request is AdoptionFrame.RequestV2) { "expected ADOPT_REQUEST" }205        // §11.6: refused before any SAS prompt and before any grant. §10.3206        // freezes the wire reason set to the two v1 peers already understand, so207        // this is a local refusal rather than a new ADOPT_REJECT reason.208        if (request is AdoptionFrame.Request && postReset()) {209            onPeerOutdated()210            return null211        }212        if (request is AdoptionFrame.Request && !confirm(SASDerivation.derive(noise.handshakeHash), request)) return null213214        val pairState = AdoptionPairState(215            rendezvousSecretHex = Rendezvous.bytesToHex(216                Rendezvous.deriveSecret(noise.handshakeHash),217            ),218            relayUrl = Rendezvous.normalizeRelayUrl(relayUrl),219        )220        val boundDeps = object : AdoptionSourceV2Deps {221            override val sourceIdentity = localIdentity222            override val pairState: AdoptionPairState = pairState223            override suspend fun rootKeyHex() = sourceDeps.rootKeyHex()224            override suspend fun vaultId() = sourceDeps.vaultId()225            override suspend fun license() = sourceDeps.license()226            override suspend fun applyLicense(license: String) = sourceDeps.applyLicense(license)227            override suspend fun onConsent(request: AdoptionFrame.Request) = true228229            // The transcript sends ADOPT_CONFIRM_REQUIRED before calling this, so230            // the receiver's own prompt is already live when we ask our human to231            // compare the same SAS. The request is only a prompt label here.232            override suspend fun onConsent(request: AdoptionFrame.RequestV2): Boolean =233                confirm(234                    SASDerivation.derive(noise.handshakeHash),235                    AdoptionFrame.Request(236                        sessionRequestId = request.deviceId,237                        deviceName = request.deviceName,238                        deviceType = request.deviceType,239                        license = request.license,240                        snapshotCapable = request.snapshotCapable,241                    ),242                )243            override suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long) = sourceDeps.persistPendingHolder(request, nowMs)244            override suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice) = sourceDeps.completePendingHolder(request, device)245            override suspend fun persistPendingIdentity(device: PairedDevice, nowMs: Long) = sourceDeps.persistPendingIdentity(device, nowMs)246            override suspend fun completePendingIdentity(device: PairedDevice) = sourceDeps.completePendingIdentity(device)247            override suspend fun upsertPairedDevice(device: PairedDevice) = sourceDeps.upsertPairedDevice(device)248            override fun hasDeviceIdentityCollision(device: PairedDevice) = sourceDeps.hasDeviceIdentityCollision(device)249            override suspend fun rotateSourceIdentity() = sourceDeps.rotateSourceIdentity()250            override fun snapshotCapable() = sourceDeps.snapshotCapable()251            override suspend fun vaultSnapshot() = sourceDeps.vaultSnapshot()252            override suspend fun outgoingDeviceManifest() = sourceDeps.outgoingDeviceManifest()253            override suspend fun markSynced(deviceId: String) = sourceDeps.markSynced(deviceId)254            override suspend fun duressSlotJson() = sourceDeps.duressSlotJson()255        }256        val adopted = when (request) {257            is AdoptionFrame.RequestV2 -> grantAdoptionV2(channel, request, boundDeps)258            is AdoptionFrame.Request -> grantAdoption(channel, request, boundDeps)259            else -> null260        } ?: return null261        // If the receiver advertised snapshot support, send the vault inline.262        val receiverWantsSnapshot = when (request) {263            is AdoptionFrame.Request -> request.snapshotCapable == true264            is AdoptionFrame.RequestV2 -> request.snapshotCapable == true265            else -> false266        }267        if (receiverWantsSnapshot) {268            try {269                val snapshot = boundDeps.vaultSnapshot()270                if (snapshot != null) {271                    val duressSlot = runCatching { boundDeps.duressSlotJson() }.getOrNull()272                    sendVaultSnapshot(channel, snapshot.first, snapshot.second, duressSlot)273                    val applied = receiveFrame(channel)274                    if (applied is AdoptionFrame.SnapshotApplied) {275                        val manifest = boundDeps.outgoingDeviceManifest()276                        if (manifest != null) {277                            sendFrame(channel, AdoptionFrame.DeviceManifestFrame(manifest))278                            withTimeoutOrNull(5_000) { receiveFrame(channel) }279                        }280                        boundDeps.markSynced(adopted.deviceId)281                    }282                }283            } catch (error: Exception) {284                if (error is SnapshotDuressFrameTooLargeException) throw error285                if (error is kotlinx.coroutines.CancellationException) throw error286                PeachSyncLog.w("adoption: snapshot send failed — reason=${relayLogReason(error)}")287            }288        }289        return adopted290    } finally {291        noise.close()292    }293}