CodePairViewModel.kt

12.8 KB · raw

1package com.peachpasswords.ui.pairing23import android.content.Context4import android.util.Log5import com.peachpasswords.BuildConfig6import androidx.lifecycle.ViewModel7import androidx.lifecycle.viewModelScope8import com.peachpasswords.sync.BackgroundSyncPreference9import com.peachpasswords.sync.BatteryExemption10import com.peachpasswords.sync.PairingSession11import com.peachpasswords.sync.PeachSyncService12import com.peachpasswords.sync.RelayAdoptionEvent13import com.peachpasswords.sync.RelayAdoptionHost14import com.peachpasswords.sync.RelaySettingsStore15import com.peachpasswords.sync.RelayDecision16import com.peachpasswords.sync.SyncMode17import com.peachpasswords.sync.PendingVouchedDevice18import com.peachpasswords.sync.PendingVouchedDeviceStore19import com.peachpasswords.sync.AdoptionFrame20import com.peachpasswords.sync.AdoptionSourceDeps21import com.peachpasswords.sync.LocalDeviceIdentity22import com.peachpasswords.sync.PairedDevice23import com.peachpasswords.sync.PairedDeviceStore24import com.peachpasswords.sync.SignedDeviceManifest25import com.peachpasswords.sync.VaultSyncAdapter26import com.peachpasswords.sync.buildLocalIdentity27import com.peachpasswords.sync.loadOrCreateLocalIdentity28import com.peachpasswords.sync.localSyncKeypair29import com.peachpasswords.sync.rotateDeviceId30import com.peachpasswords.vault.VaultCrypto31import com.peachpasswords.vault.VaultRepository32import com.peachpasswords.license.LicenseRepository33import dagger.hilt.android.lifecycle.HiltViewModel34import dagger.hilt.android.qualifiers.ApplicationContext35import kotlinx.coroutines.Job36import kotlinx.coroutines.flow.MutableStateFlow37import kotlinx.coroutines.flow.StateFlow38import kotlinx.coroutines.flow.asStateFlow39import kotlinx.coroutines.launch40import javax.inject.Inject4142/**43 * The phone half of pairing: occupy a relay room, show the invitation, wait to44 * be scanned.45 *46 * There is one transport. LAN pairing codes are retired along with LAN sync47 * (docs/sync-lan-retirement.md), so this screen only ever displays a QR and48 * then presents the SAS for comparison.49 */50sealed interface CodePairUiState {51    data object Starting : CodePairUiState52    data class ShowingInvitation(val invitation: String) : CodePairUiState53    data class AwaitingPeerConfirmation(val sas: String, val deviceName: String) : CodePairUiState54    data class Paired(val deviceName: String) : CodePairUiState55    data object Expired : CodePairUiState56    data class Failed(val reason: String) : CodePairUiState57}5859@HiltViewModel60class CodePairViewModel @Inject constructor(61    private val vault: VaultRepository,62    private val relayHost: RelayAdoptionHost,63    private val relaySettings: RelaySettingsStore,64    private val backgroundSync: BackgroundSyncPreference,65    private val deviceStore: PairedDeviceStore,66    private val pendingVouchedStore: PendingVouchedDeviceStore,67    private val license: LicenseRepository,68    @ApplicationContext private val appContext: Context,69) : ViewModel() {7071    private val _state = MutableStateFlow<CodePairUiState>(CodePairUiState.Starting)72    val state: StateFlow<CodePairUiState> = _state.asStateFlow()7374    private val _syncMode = MutableStateFlow(relaySettings.syncMode())75    val syncMode: StateFlow<SyncMode> = _syncMode.asStateFlow()7677    private val _privateRelayUrl = MutableStateFlow(relaySettings.privateRelayUrl())78    val privateRelayUrl: StateFlow<String> = _privateRelayUrl.asStateFlow()7980    /**81     * The single live transport collector. Switching between relay and LAN82     * restarts the screen, and without cancelling the previous collector both83     * would keep writing [_state] — the older one landing last and winning.84     */85    private var collectJob: Job? = null8687    /**88     * The battery-exemption dialog to show, or null if it's already granted or89     * already been declined once. Consumed by the screen, which owns an90     * Activity to launch it from.91     *92     * [userConfirmed] must come from the tap itself — see [BatteryExemption]'s93     * distribution note. When it yields nothing, sync still works; it just runs94     * from the foreground ([BatteryExemption.syncOnce]).95     */96    fun batteryExemptionIntent(userConfirmed: Boolean): android.content.Intent? =97        BatteryExemption.requestIntent(appContext, userConfirmed)9899    /** Degraded sync for a device with no Doze exemption — see [BatteryExemption.syncOnce]. */100    fun syncOnce() = BatteryExemption.syncOnce(appContext)101102    fun start() {103        val master = vault.syncMasterKey() ?: run {104            _state.value = CodePairUiState.Failed("vault_locked")105            return106        }107        val decision = relaySettings.relayInForce()108        if (decision is RelayDecision.Refuse) {109            _state.value = CodePairUiState.Failed(decision.reason.wire())110            return111        }112        PeachSyncService.start(appContext)113        val credentials = loadOrCreateLocalIdentity(appContext)114        val keys = localSyncKeypair(credentials)115        val identity = buildLocalIdentity(appContext, credentials)116        VaultCrypto.zero(master)117        startRelay(keys.secretKey, keys.publicKey, identity, sourceDeps(identity))118    }119120    private fun startRelay(121        privateKey: ByteArray,122        publicKey: ByteArray,123        identity: LocalDeviceIdentity,124        sourceDeps: AdoptionSourceDeps,125    ) {126        collectJob = viewModelScope.launch {127            try {128                relayHost.start(129                    viewModelScope,130                    privateKey,131                    publicKey,132                    identity,133                    sourceDeps,134                ).collect { event ->135                    _state.value = when (event) {136                        is RelayAdoptionEvent.InvitationReady ->137                            CodePairUiState.ShowingInvitation(event.invitation)138                        is RelayAdoptionEvent.AwaitingPeerConfirmation ->139                            CodePairUiState.AwaitingPeerConfirmation(140                                event.sas,141                                event.deviceName,142                            )143                        is RelayAdoptionEvent.Adopted ->144                            CodePairUiState.Paired(event.deviceName)145                        RelayAdoptionEvent.Expired -> CodePairUiState.Expired146                        is RelayAdoptionEvent.Rejected -> {147                            if (BuildConfig.DEBUG) {148                                Log.w(149                                    "PeachPairing",150                                    "relay adoption rejected: ${event.reason}",151                                )152                            }153                            CodePairUiState.Failed(event.reason)154                        }155                    }156                }157            } finally {158                VaultCrypto.zero(privateKey)159                VaultCrypto.zero(publicKey)160            }161        }162    }163164    private fun sourceDeps(identity: LocalDeviceIdentity): AdoptionSourceDeps =165        object : AdoptionSourceDeps {166            override val sourceIdentity: LocalDeviceIdentity = identity167168            override suspend fun rootKeyHex(): String {169                val root = vault.syncMasterKey()170                    ?: throw IllegalStateException("vault_locked")171                return try {172                    root.joinToString("") { "%02x".format(it) }173                } finally {174                    VaultCrypto.zero(root)175                }176            }177178            override suspend fun vaultId(): String =179                vault.syncVaultId() ?: throw IllegalStateException("vault_locked")180181            override suspend fun license(): String? =182                license.getLicenseKey()?.takeIf(license::validateLicense)183184            override suspend fun applyLicense(licenseKey: String) {185                if (!license.storeLicense(licenseKey) || !license.isProActive()) {186                    throw IllegalStateException("license_transfer_failed")187                }188            }189190            // Opening this source screen while unlocked is the source-side191            // consent. The scanning device confirms the SAS before any grant.192            override suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long): Boolean =193                runCatching {194                    pendingVouchedStore.upsertAndReport(195                        PendingVouchedDevice(196                            deviceId = request.sessionRequestId,197                            deviceName = request.deviceName,198                            deviceType = request.deviceType,199                            longTermPublicKeyHex = identity.longTermPublicKeyHex,200                            signingPublicKeyHex = identity.signingPublicKeyHex,201                            pairedAt = nowMs,202                            receivedAt = nowMs,203                            vouchedByDeviceId = identity.deviceId,204                        ),205                    )206                }.getOrDefault(false)207            override suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice): Boolean =208                runCatching {209                    pendingVouchedStore.removeAndReport(request.sessionRequestId)210                }.getOrDefault(false)211            override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true212213            override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =214                deviceStore.hasIdentityCollision(device)215216            override suspend fun rotateSourceIdentity(): LocalDeviceIdentity {217                rotateDeviceId(appContext)218                val master = vault.syncMasterKey()219                    ?: throw IllegalStateException("vault_locked")220                return try {221                    buildLocalIdentity(appContext, master)222                } finally {223                    VaultCrypto.zero(master)224                }225            }226227            override suspend fun upsertPairedDevice(device: PairedDevice) {228                // SAS-confirmed direct adoption atomically validates identity,229                // lifts terminal revocation, and persists the paired row.230                deviceStore.upsertAndClearRevocation(device)231            }232233            override suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? {234                val credentials = loadOrCreateLocalIdentity(appContext)235                val adapter = VaultSyncAdapter(236                    repo = vault,237                    ourDeviceId = credentials.deviceId,238                    pairedDevices = deviceStore,239                    localCredentials = credentials,240                )241                val entryManifest = adapter.buildEntryManifest()242                val entryIds = entryManifest.keys.toList()243                val entries = if (entryIds.isNotEmpty()) adapter.getEncryptedEntries(entryIds) else emptyMap()244                val tombstones = adapter.buildTombstoneManifest()245                return entries to tombstones246            }247248            override suspend fun outgoingDeviceManifest(): SignedDeviceManifest? {249                val credentials = loadOrCreateLocalIdentity(appContext)250                val adapter = VaultSyncAdapter(251                    repo = vault,252                    ourDeviceId = credentials.deviceId,253                    pairedDevices = deviceStore,254                    localCredentials = credentials,255                )256                return adapter.buildOutgoingDeviceManifest()257            }258259            override suspend fun markSynced(deviceId: String) {260                deviceStore.updateLastSync(deviceId)261            }262263            override suspend fun duressSlotJson(): String? =264                vault.exportDuressSlotForAdoption()265        }266267    fun setBackgroundSync(enabled: Boolean) {268        backgroundSync.setEnabled(enabled)269        if (enabled) PeachSyncService.start(appContext) else PeachSyncService.stop(appContext)270    }271272    fun selectRelayMode(mode: SyncMode) {273        require(mode != SyncMode.OFF) { "Pairing requires a relay" }274        relaySettings.setSyncMode(mode)275        refreshRelayState()276        if (relaySettings.relayInForce() is RelayDecision.Dial) {277            restart()278        } else {279            stop()280            _state.value = CodePairUiState.Failed("private_relay_unset")281        }282    }283284    fun savePrivateRelayUrl(input: String): Boolean = runCatching {285        relaySettings.setRelayUrl(input)286        refreshRelayState()287        restart()288        true289    }.getOrDefault(false)290291    private fun refreshRelayState() {292        _syncMode.value = relaySettings.syncMode()293        _privateRelayUrl.value = relaySettings.privateRelayUrl()294    }295296    fun restart() {297        collectJob?.cancel()298        collectJob = null299        relayHost.stop()300        _state.value = CodePairUiState.Starting301        start()302    }303304    fun stop() {305        collectJob?.cancel()306        collectJob = null307        relayHost.stop()308    }309310    override fun onCleared() {311        stop()312        super.onCleared()313    }314}