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.AdoptionPairState21import com.peachpasswords.sync.AdoptionSourceDeps22import com.peachpasswords.sync.AdoptionSourceV2Deps23import com.peachpasswords.sync.LocalDeviceIdentity24import com.peachpasswords.sync.PairedDevice25import com.peachpasswords.sync.PairedDeviceStore26import com.peachpasswords.sync.SignedDeviceManifest27import com.peachpasswords.sync.VaultSyncAdapter28import com.peachpasswords.sync.buildLocalIdentity29import com.peachpasswords.sync.loadOrCreateLocalIdentity30import com.peachpasswords.sync.localSyncKeypair31import com.peachpasswords.sync.rotateDeviceId32import com.peachpasswords.vault.VaultCrypto33import com.peachpasswords.vault.VaultRepository34import com.peachpasswords.license.LicenseRepository35import dagger.hilt.android.lifecycle.HiltViewModel36import dagger.hilt.android.qualifiers.ApplicationContext37import kotlinx.coroutines.Job38import kotlinx.coroutines.flow.MutableStateFlow39import kotlinx.coroutines.flow.StateFlow40import kotlinx.coroutines.flow.asStateFlow41import kotlinx.coroutines.launch42import javax.inject.Inject43444546474849505152sealed interface CodePairUiState {53 data object Starting : CodePairUiState54 data class ShowingInvitation(val invitation: String) : CodePairUiState55 data class AwaitingPeerConfirmation(val sas: String, val deviceName: String) : CodePairUiState56 data class Paired(val deviceName: String) : CodePairUiState57 data object Expired : CodePairUiState58 data class Failed(val reason: String) : CodePairUiState59}6061@HiltViewModel62class CodePairViewModel @Inject constructor(63 private val vault: VaultRepository,64 private val relayHost: RelayAdoptionHost,65 private val relaySettings: RelaySettingsStore,66 private val backgroundSync: BackgroundSyncPreference,67 private val deviceStore: PairedDeviceStore,68 private val pendingVouchedStore: PendingVouchedDeviceStore,69 private val license: LicenseRepository,70 @ApplicationContext private val appContext: Context,71) : ViewModel() {7273 private val _state = MutableStateFlow<CodePairUiState>(CodePairUiState.Starting)74 val state: StateFlow<CodePairUiState> = _state.asStateFlow()7576 private val _syncMode = MutableStateFlow(relaySettings.syncMode())77 val syncMode: StateFlow<SyncMode> = _syncMode.asStateFlow()7879 private val _privateRelayUrl = MutableStateFlow(relaySettings.privateRelayUrl())80 val privateRelayUrl: StateFlow<String> = _privateRelayUrl.asStateFlow()8182 8384858687 private var collectJob: Job? = null8889 909192939495969798 fun batteryExemptionIntent(userConfirmed: Boolean): android.content.Intent? =99 BatteryExemption.requestIntent(appContext, userConfirmed)100101 102 fun syncOnce() = BatteryExemption.syncOnce(appContext)103104 fun start() {105 val master = vault.syncMasterKey() ?: run {106 _state.value = CodePairUiState.Failed("vault_locked")107 return108 }109 val decision = relaySettings.relayInForce()110 if (decision is RelayDecision.Refuse) {111 _state.value = CodePairUiState.Failed(decision.reason.wire())112 return113 }114 PeachSyncService.start(appContext)115 val credentials = loadOrCreateLocalIdentity(appContext)116 val keys = localSyncKeypair(credentials)117 val identity = buildLocalIdentity(appContext, credentials)118 VaultCrypto.zero(master)119 startRelay(keys.secretKey, keys.publicKey, identity, sourceDeps(identity))120 }121122 private fun startRelay(123 privateKey: ByteArray,124 publicKey: ByteArray,125 identity: LocalDeviceIdentity,126 sourceDeps: AdoptionSourceV2Deps,127 ) {128 collectJob = viewModelScope.launch {129 try {130 relayHost.start(131 viewModelScope,132 privateKey,133 publicKey,134 identity,135 sourceDeps,136 ).collect { event ->137 _state.value = when (event) {138 is RelayAdoptionEvent.InvitationReady ->139 CodePairUiState.ShowingInvitation(event.invitation)140 is RelayAdoptionEvent.AwaitingPeerConfirmation ->141 CodePairUiState.AwaitingPeerConfirmation(142 event.sas,143 event.deviceName,144 )145 is RelayAdoptionEvent.Adopted ->146 CodePairUiState.Paired(event.deviceName)147 RelayAdoptionEvent.Expired -> CodePairUiState.Expired148 is RelayAdoptionEvent.Rejected -> {149 if (BuildConfig.DEBUG) {150 Log.w(151 "PeachPairing",152 "relay adoption rejected: ${event.reason}",153 )154 }155 CodePairUiState.Failed(event.reason)156 }157 }158 }159 } finally {160 VaultCrypto.zero(privateKey)161 VaultCrypto.zero(publicKey)162 }163 }164 }165166 private fun sourceDeps(identity: LocalDeviceIdentity): AdoptionSourceV2Deps =167 object : AdoptionSourceV2Deps {168 override val sourceIdentity: LocalDeviceIdentity = identity169170 171 172 override val pairState: AdoptionPairState? get() = null173174 override fun snapshotCapable(): Boolean = true175176 override suspend fun onConsent(request: AdoptionFrame.RequestV2): Boolean = true177178 179 180 override suspend fun persistPendingIdentity(device: PairedDevice, nowMs: Long): Boolean {181 val deviceName = device.deviceName ?: return false182 val deviceType = device.deviceType ?: return false183 val longTermKey = device.longTermPublicKeyHex ?: return false184 val signingKey = device.signingPublicKeyHex ?: return false185 return runCatching {186 pendingVouchedStore.upsertAndReport(187 PendingVouchedDevice(188 deviceId = device.deviceId,189 deviceName = deviceName,190 deviceType = deviceType,191 longTermPublicKeyHex = longTermKey,192 signingPublicKeyHex = signingKey,193 wsPort = device.wsPort,194 pairedAt = nowMs,195 receivedAt = nowMs,196 vouchedByDeviceId = identity.deviceId,197 ),198 )199 }.getOrDefault(false)200 }201202 override suspend fun completePendingIdentity(device: PairedDevice): Boolean =203 runCatching { pendingVouchedStore.removeIdentityAndReport(device) }.getOrDefault(false)204205 override suspend fun rootKeyHex(): String {206 val root = vault.syncMasterKey()207 ?: throw IllegalStateException("vault_locked")208 return try {209 root.joinToString("") { "%02x".format(it) }210 } finally {211 VaultCrypto.zero(root)212 }213 }214215 override suspend fun vaultId(): String =216 vault.syncVaultId() ?: throw IllegalStateException("vault_locked")217218 override suspend fun license(): String? =219 license.getLicenseKey()?.takeIf(license::validateLicense)220221 override suspend fun applyLicense(licenseKey: String) {222 if (!license.storeLicense(licenseKey) || !license.isProActive()) {223 throw IllegalStateException("license_transfer_failed")224 }225 }226227 228 229 override suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long): Boolean =230 runCatching {231 pendingVouchedStore.upsertAndReport(232 PendingVouchedDevice(233 deviceId = request.sessionRequestId,234 deviceName = request.deviceName,235 deviceType = request.deviceType,236 longTermPublicKeyHex = identity.longTermPublicKeyHex,237 signingPublicKeyHex = identity.signingPublicKeyHex,238 pairedAt = nowMs,239 receivedAt = nowMs,240 vouchedByDeviceId = identity.deviceId,241 ),242 )243 }.getOrDefault(false)244 override suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice): Boolean =245 runCatching {246 pendingVouchedStore.removeAndReport(request.sessionRequestId)247 }.getOrDefault(false)248 override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true249250 override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =251 deviceStore.hasIdentityCollision(device)252253 override suspend fun rotateSourceIdentity(): LocalDeviceIdentity {254 rotateDeviceId(appContext)255 val master = vault.syncMasterKey()256 ?: throw IllegalStateException("vault_locked")257 return try {258 buildLocalIdentity(appContext, master)259 } finally {260 VaultCrypto.zero(master)261 }262 }263264 override suspend fun upsertPairedDevice(device: PairedDevice) {265 266 267 deviceStore.upsertAndClearRevocation(device)268 }269270 override suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? {271 val credentials = loadOrCreateLocalIdentity(appContext)272 val adapter = VaultSyncAdapter(273 repo = vault,274 ourDeviceId = credentials.deviceId,275 pairedDevices = deviceStore,276 localCredentials = credentials,277 )278 val entryManifest = adapter.buildEntryManifest()279 val entryIds = entryManifest.keys.toList()280 val entries = if (entryIds.isNotEmpty()) adapter.getEncryptedEntries(entryIds) else emptyMap()281 val tombstones = adapter.buildTombstoneManifest()282 return entries to tombstones283 }284285 override suspend fun outgoingDeviceManifest(): SignedDeviceManifest? {286 val credentials = loadOrCreateLocalIdentity(appContext)287 val adapter = VaultSyncAdapter(288 repo = vault,289 ourDeviceId = credentials.deviceId,290 pairedDevices = deviceStore,291 localCredentials = credentials,292 )293 return adapter.buildOutgoingDeviceManifest()294 }295296 override suspend fun markSynced(deviceId: String) {297 deviceStore.updateLastSync(deviceId)298 }299300 override suspend fun duressSlotJson(): String? =301 vault.exportDuressSlotForAdoption()302 }303304 fun setBackgroundSync(enabled: Boolean) {305 backgroundSync.setEnabled(enabled)306 if (enabled) PeachSyncService.start(appContext) else PeachSyncService.stop(appContext)307 }308309 fun selectRelayMode(mode: SyncMode) {310 require(mode != SyncMode.OFF) { "Pairing requires a relay" }311 relaySettings.setSyncMode(mode)312 refreshRelayState()313 if (relaySettings.relayInForce() is RelayDecision.Dial) {314 restart()315 } else {316 stop()317 _state.value = CodePairUiState.Failed("private_relay_unset")318 }319 }320321 fun savePrivateRelayUrl(input: String): Boolean = runCatching {322 relaySettings.setRelayUrl(input)323 refreshRelayState()324 restart()325 true326 }.getOrDefault(false)327328 private fun refreshRelayState() {329 _syncMode.value = relaySettings.syncMode()330 _privateRelayUrl.value = relaySettings.privateRelayUrl()331 }332333 fun restart() {334 collectJob?.cancel()335 collectJob = null336 relayHost.stop()337 _state.value = CodePairUiState.Starting338 start()339 }340341 fun stop() {342 collectJob?.cancel()343 collectJob = null344 relayHost.stop()345 }346347 override fun onCleared() {348 stop()349 super.onCleared()350 }351}