CodePairViewModel.kt

11.3 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.AdoptionSourceDeps18import com.peachpasswords.sync.AdoptionFrame19import com.peachpasswords.sync.LocalDeviceIdentity20import com.peachpasswords.sync.PairedDevice21import com.peachpasswords.sync.PairedDeviceStore22import com.peachpasswords.sync.SignedDeviceManifest23import com.peachpasswords.sync.VaultSyncAdapter24import com.peachpasswords.sync.buildLocalIdentity25import com.peachpasswords.sync.deriveLocalSyncKeypair26import com.peachpasswords.sync.getOrCreateDeviceId27import com.peachpasswords.sync.rotateDeviceId28import com.peachpasswords.vault.VaultCrypto29import com.peachpasswords.vault.VaultRepository30import com.peachpasswords.license.LicenseRepository31import dagger.hilt.android.lifecycle.HiltViewModel32import dagger.hilt.android.qualifiers.ApplicationContext33import kotlinx.coroutines.Job34import kotlinx.coroutines.flow.MutableStateFlow35import kotlinx.coroutines.flow.StateFlow36import kotlinx.coroutines.flow.asStateFlow37import kotlinx.coroutines.launch38import javax.inject.Inject3940/**41 * The phone half of pairing: occupy a relay room, show the invitation, wait to42 * be scanned.43 *44 * There is one transport. LAN pairing codes are retired along with LAN sync45 * (docs/sync-lan-retirement.md), so this screen only ever displays a QR and46 * then presents the SAS for comparison.47 */48sealed interface CodePairUiState {49    data object Starting : CodePairUiState50    data class ShowingInvitation(val invitation: String) : CodePairUiState51    data class AwaitingPeerConfirmation(val sas: String, val deviceName: String) : CodePairUiState52    data class Paired(val deviceName: String) : CodePairUiState53    data object Expired : CodePairUiState54    data class Failed(val reason: String) : CodePairUiState55}5657@HiltViewModel58class CodePairViewModel @Inject constructor(59    private val vault: VaultRepository,60    private val relayHost: RelayAdoptionHost,61    private val relaySettings: RelaySettingsStore,62    private val backgroundSync: BackgroundSyncPreference,63    private val deviceStore: PairedDeviceStore,64    private val license: LicenseRepository,65    @ApplicationContext private val appContext: Context,66) : ViewModel() {6768    private val _state = MutableStateFlow<CodePairUiState>(CodePairUiState.Starting)69    val state: StateFlow<CodePairUiState> = _state.asStateFlow()7071    private val _syncMode = MutableStateFlow(relaySettings.syncMode())72    val syncMode: StateFlow<SyncMode> = _syncMode.asStateFlow()7374    private val _privateRelayUrl = MutableStateFlow(relaySettings.privateRelayUrl())75    val privateRelayUrl: StateFlow<String> = _privateRelayUrl.asStateFlow()7677    /**78     * The single live transport collector. Switching between relay and LAN79     * restarts the screen, and without cancelling the previous collector both80     * would keep writing [_state] — the older one landing last and winning.81     */82    private var collectJob: Job? = null8384    /**85     * The battery-exemption dialog to show, or null if it's already granted or86     * already been declined once. Consumed by the screen, which owns an87     * Activity to launch it from.88     *89     * [userConfirmed] must come from the tap itself — see [BatteryExemption]'s90     * distribution note. When it yields nothing, sync still works; it just runs91     * from the foreground ([BatteryExemption.syncOnce]).92     */93    fun batteryExemptionIntent(userConfirmed: Boolean): android.content.Intent? =94        BatteryExemption.requestIntent(appContext, userConfirmed)9596    /** Degraded sync for a device with no Doze exemption — see [BatteryExemption.syncOnce]. */97    fun syncOnce() = BatteryExemption.syncOnce(appContext)9899    fun start() {100        val master = vault.syncMasterKey() ?: run {101            _state.value = CodePairUiState.Failed("vault_locked")102            return103        }104        val decision = relaySettings.relayInForce()105        if (decision is RelayDecision.Refuse) {106            _state.value = CodePairUiState.Failed(decision.reason.wire())107            return108        }109        PeachSyncService.start(appContext)110111        val keys = deriveLocalSyncKeypair(master, getOrCreateDeviceId(appContext))112        val identity = buildLocalIdentity(appContext, master)113        VaultCrypto.zero(master)114        startRelay(keys.secretKey, keys.publicKey, identity, sourceDeps(identity))115    }116117    private fun startRelay(118        privateKey: ByteArray,119        publicKey: ByteArray,120        identity: LocalDeviceIdentity,121        sourceDeps: AdoptionSourceDeps,122    ) {123        collectJob = viewModelScope.launch {124            try {125                relayHost.start(126                    viewModelScope,127                    privateKey,128                    publicKey,129                    identity,130                    sourceDeps,131                ).collect { event ->132                    _state.value = when (event) {133                        is RelayAdoptionEvent.InvitationReady ->134                            CodePairUiState.ShowingInvitation(event.invitation)135                        is RelayAdoptionEvent.AwaitingPeerConfirmation ->136                            CodePairUiState.AwaitingPeerConfirmation(137                                event.sas,138                                event.deviceName,139                            )140                        is RelayAdoptionEvent.Adopted ->141                            CodePairUiState.Paired(event.deviceName)142                        RelayAdoptionEvent.Expired -> CodePairUiState.Expired143                        is RelayAdoptionEvent.Rejected -> {144                            if (BuildConfig.DEBUG) {145                                Log.w(146                                    "PeachPairing",147                                    "relay adoption rejected: ${event.reason}",148                                )149                            }150                            CodePairUiState.Failed(event.reason)151                        }152                    }153                }154            } finally {155                VaultCrypto.zero(privateKey)156                VaultCrypto.zero(publicKey)157            }158        }159    }160161    private fun sourceDeps(identity: LocalDeviceIdentity): AdoptionSourceDeps =162        object : AdoptionSourceDeps {163            override val sourceIdentity: LocalDeviceIdentity = identity164165            override suspend fun rootKeyHex(): String {166                val root = vault.syncMasterKey()167                    ?: throw IllegalStateException("vault_locked")168                return try {169                    root.joinToString("") { "%02x".format(it) }170                } finally {171                    VaultCrypto.zero(root)172                }173            }174175            override suspend fun vaultId(): String =176                vault.syncVaultId() ?: throw IllegalStateException("vault_locked")177178            override suspend fun license(): String? =179                license.getLicenseKey()?.takeIf(license::validateLicense)180181            override suspend fun applyLicense(licenseKey: String) {182                if (!license.storeLicense(licenseKey) || !license.isProActive()) {183                    throw IllegalStateException("license_transfer_failed")184                }185            }186187            // Opening this source screen while unlocked is the source-side188            // consent. The scanning device confirms the SAS before any grant.189            override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true190191            override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =192                deviceStore.hasIdentityCollision(device)193194            override suspend fun rotateSourceIdentity(): LocalDeviceIdentity {195                rotateDeviceId(appContext)196                val master = vault.syncMasterKey()197                    ?: throw IllegalStateException("vault_locked")198                return try {199                    buildLocalIdentity(appContext, master)200                } finally {201                    VaultCrypto.zero(master)202                }203            }204205            override suspend fun upsertPairedDevice(device: PairedDevice) {206                // SAS-confirmed direct adoption atomically validates identity,207                // lifts terminal revocation, and persists the paired row.208                deviceStore.upsertAndClearRevocation(device)209            }210211            override suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? {212                val adapter = VaultSyncAdapter(213                    repo = vault,214                    ourDeviceId = getOrCreateDeviceId(appContext),215                    pairedDevices = deviceStore,216                )217                val entryManifest = adapter.buildEntryManifest()218                val entryIds = entryManifest.keys.toList()219                val entries = if (entryIds.isNotEmpty()) adapter.getEncryptedEntries(entryIds) else emptyMap()220                val tombstones = adapter.buildTombstoneManifest()221                return entries to tombstones222            }223224            override suspend fun outgoingDeviceManifest(): SignedDeviceManifest? {225                val adapter = VaultSyncAdapter(226                    repo = vault,227                    ourDeviceId = getOrCreateDeviceId(appContext),228                    pairedDevices = deviceStore,229                )230                return adapter.buildOutgoingDeviceManifest()231            }232233            override suspend fun markSynced(deviceId: String) {234                deviceStore.updateLastSync(deviceId)235            }236237            override suspend fun duressSlotJson(): String? =238                vault.exportDuressSlotForAdoption()239        }240241    fun setBackgroundSync(enabled: Boolean) {242        backgroundSync.setEnabled(enabled)243        if (enabled) PeachSyncService.start(appContext) else PeachSyncService.stop(appContext)244    }245246    fun selectRelayMode(mode: SyncMode) {247        require(mode != SyncMode.OFF) { "Pairing requires a relay" }248        relaySettings.setSyncMode(mode)249        refreshRelayState()250        if (relaySettings.relayInForce() is RelayDecision.Dial) {251            restart()252        } else {253            stop()254            _state.value = CodePairUiState.Failed("private_relay_unset")255        }256    }257258    fun savePrivateRelayUrl(input: String): Boolean = runCatching {259        relaySettings.setRelayUrl(input)260        refreshRelayState()261        restart()262        true263    }.getOrDefault(false)264265    private fun refreshRelayState() {266        _syncMode.value = relaySettings.syncMode()267        _privateRelayUrl.value = relaySettings.privateRelayUrl()268    }269270    fun restart() {271        collectJob?.cancel()272        collectJob = null273        relayHost.stop()274        _state.value = CodePairUiState.Starting275        start()276    }277278    fun stop() {279        collectJob?.cancel()280        collectJob = null281        relayHost.stop()282    }283284    override fun onCleared() {285        stop()286        super.onCleared()287    }288}