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.Inject39404142434445464748sealed 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 7879808182 private var collectJob: Job? = null8384 858687888990919293 fun batteryExemptionIntent(userConfirmed: Boolean): android.content.Intent? =94 BatteryExemption.requestIntent(appContext, userConfirmed)9596 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 188 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 207 208 deviceStore.clearRevocation(device.deviceId)209 deviceStore.upsert(device)210 }211212 override suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? {213 val adapter = VaultSyncAdapter(214 repo = vault,215 ourDeviceId = getOrCreateDeviceId(appContext),216 pairedDevices = deviceStore,217 )218 val entryManifest = adapter.buildEntryManifest()219 val entryIds = entryManifest.keys.toList()220 val entries = if (entryIds.isNotEmpty()) adapter.getEncryptedEntries(entryIds) else emptyMap()221 val tombstones = adapter.buildTombstoneManifest()222 return entries to tombstones223 }224225 override suspend fun outgoingDeviceManifest(): SignedDeviceManifest? {226 val adapter = VaultSyncAdapter(227 repo = vault,228 ourDeviceId = getOrCreateDeviceId(appContext),229 pairedDevices = deviceStore,230 )231 return adapter.buildOutgoingDeviceManifest()232 }233234 override suspend fun markSynced(deviceId: String) {235 deviceStore.updateLastSync(deviceId)236 }237238 override suspend fun duressSlotJson(): String? =239 vault.exportDuressSlotForAdoption()240 }241242 fun setBackgroundSync(enabled: Boolean) {243 backgroundSync.setEnabled(enabled)244 if (enabled) PeachSyncService.start(appContext) else PeachSyncService.stop(appContext)245 }246247 fun selectRelayMode(mode: SyncMode) {248 require(mode != SyncMode.OFF) { "Pairing requires a relay" }249 relaySettings.setSyncMode(mode)250 refreshRelayState()251 if (relaySettings.relayInForce() is RelayDecision.Dial) {252 restart()253 } else {254 stop()255 _state.value = CodePairUiState.Failed("private_relay_unset")256 }257 }258259 fun savePrivateRelayUrl(input: String): Boolean = runCatching {260 relaySettings.setRelayUrl(input)261 refreshRelayState()262 restart()263 true264 }.getOrDefault(false)265266 private fun refreshRelayState() {267 _syncMode.value = relaySettings.syncMode()268 _privateRelayUrl.value = relaySettings.privateRelayUrl()269 }270271 fun restart() {272 collectJob?.cancel()273 collectJob = null274 relayHost.stop()275 _state.value = CodePairUiState.Starting276 start()277 }278279 fun stop() {280 collectJob?.cancel()281 collectJob = null282 relayHost.stop()283 }284285 override fun onCleared() {286 stop()287 super.onCleared()288 }289}