1package com.peachpasswords.ui.sync23import android.content.Context4import androidx.lifecycle.ViewModel5import androidx.lifecycle.viewModelScope6import com.peachpasswords.sync.BackgroundSyncCoordinator7import com.peachpasswords.sync.BackgroundSyncPreference8import com.peachpasswords.sync.RESET_NOT_COMPLETED9import com.peachpasswords.sync.ResetResult10import com.peachpasswords.sync.SyncGeneration11import com.peachpasswords.sync.SyncGenerationStore12import com.peachpasswords.sync.SyncVaultAdapter13import com.peachpasswords.sync.confirmSecureReset14import com.peachpasswords.sync.enterResetRequired15import com.peachpasswords.sync.resolveGeneration16import com.peachpasswords.sync.syncAllowedNow17import com.peachpasswords.sync.PairedDevice18import com.peachpasswords.sync.PairedDeviceStore19import com.peachpasswords.sync.PendingVouchedDevice20import com.peachpasswords.sync.PendingVouchedDeviceStore21import com.peachpasswords.sync.PeachSyncService22import com.peachpasswords.sync.RelayDecision23import com.peachpasswords.sync.RelaySettingsStore24import com.peachpasswords.sync.SyncMode25import com.peachpasswords.sync.SyncAlertStore26import com.peachpasswords.sync.SyncOutcomeReason27import com.peachpasswords.sync.SyncOutcomeStore28import com.peachpasswords.sync.SyncOutcomeSummary29import com.peachpasswords.sync.VaultSyncAdapter30import com.peachpasswords.sync.loadOrCreateLocalIdentity31import com.peachpasswords.vault.VaultRepository32import dagger.hilt.android.lifecycle.HiltViewModel33import dagger.hilt.android.qualifiers.ApplicationContext34import kotlinx.coroutines.flow.MutableStateFlow35import kotlinx.coroutines.flow.SharingStarted36import kotlinx.coroutines.flow.StateFlow37import kotlinx.coroutines.flow.asStateFlow38import kotlinx.coroutines.flow.combine39import kotlinx.coroutines.flow.stateIn40import kotlinx.coroutines.Dispatchers41import kotlinx.coroutines.delay42import kotlinx.coroutines.Job43import kotlinx.coroutines.launch44import kotlinx.coroutines.withContext45import javax.inject.Inject46474849505152535455565758@HiltViewModel59class SyncViewModel @Inject constructor(60 @ApplicationContext private val context: Context,61 private val vault: VaultRepository,62 private val deviceStore: PairedDeviceStore,63 private val pendingVouchedStore: PendingVouchedDeviceStore,64 private val syncAlertStore: SyncAlertStore,65 private val backgroundSync: BackgroundSyncPreference,66 private val relaySettings: RelaySettingsStore,67 private val syncOutcomes: SyncOutcomeStore,68 private val generation: SyncGenerationStore,69) : ViewModel() {7071 72 val status: StateFlow<SyncOutcomeSummary> =73 combine(syncOutcomes.summary, vault.isUnlocked) { summary, unlocked ->74 if (unlocked && vault.syncVaultId() == null) SyncOutcomeSummary() else summary75 }.stateIn(76 viewModelScope,77 SharingStarted.WhileSubscribed(5_000),78 if (vault.isUnlocked.value && vault.syncVaultId() == null) {79 SyncOutcomeSummary()80 } else {81 syncOutcomes.summary.value82 },83 )8485 868788899091 private val backgroundSyncCoordinator = BackgroundSyncCoordinator(92 start = { PeachSyncService.start(context) },93 stop = { PeachSyncService.stop(context) },94 isUnlocked = vault.isUnlocked,95 preferenceEnabled = backgroundSync.enabled,96 syncVaultId = vault::syncVaultId,97 syncAllowed = { syncAllowedNow(generation) },98 )99100 init {101 102 103 104 105 backgroundSyncCoordinator.observe(viewModelScope)106 }107108 fun setBackgroundSyncEnabled(enabled: Boolean) {109 if (isDecoySession()) return110 backgroundSync.setEnabled(enabled)111 backgroundSyncCoordinator.setEnabled(enabled)112 }113 val backgroundSyncEnabled: StateFlow<Boolean> = backgroundSync.enabled114115 116 private val _privateRelayUrl = MutableStateFlow(relaySettings.privateRelayUrl())117 val privateRelayUrl: StateFlow<String> = _privateRelayUrl.asStateFlow()118119120 private val _syncMode = MutableStateFlow(relaySettings.syncMode())121 val syncMode: StateFlow<SyncMode> = _syncMode.asStateFlow()122123 fun setSyncMode(mode: SyncMode) {124 if (isDecoySession()) return125 relaySettings.setSyncMode(mode)126 _syncMode.value = relaySettings.syncMode()127 _privateRelayUrl.value = relaySettings.privateRelayUrl()128 }129130 131 fun setRelayUrl(input: String): Boolean {132 if (isDecoySession()) return false133 return runCatching {134 relaySettings.setRelayUrl(input)135 _privateRelayUrl.value = relaySettings.privateRelayUrl()136 _syncMode.value = relaySettings.syncMode()137 true138 }.getOrDefault(false)139 }140141142 143 val pairedDevices: StateFlow<List<PairedDevice>> =144 combine(deviceStore.observeAll(), vault.isUnlocked) { devices, unlocked ->145 if (unlocked && vault.syncVaultId() == null) emptyList() else devices146 }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())147148 val pendingVouched: StateFlow<List<PendingVouchedDevice>> =149 combine(pendingVouchedStore.observeAll(), vault.isUnlocked) { pending, unlocked ->150 if (unlocked && vault.syncVaultId() == null) emptyList() else pending151 }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())152153 154155156157158 fun unpairDevice(id: String) = viewModelScope.launch {159 if (isDecoySession()) return@launch160 deviceStore.revoke(id, loadOrCreateLocalIdentity(context).deviceId)161 PeachSyncService.start(context)162 }163164 fun renameDevice(id: String, name: String) = viewModelScope.launch {165 if (isDecoySession()) return@launch166 deviceStore.rename(id, name)167 }168169 fun confirmVouchedDevice(id: String) = viewModelScope.launch {170 if (isDecoySession()) return@launch171 val candidate = pendingVouchedStore.get(id) ?: return@launch172 val pending = pendingVouchedStore.get(173 candidate.deviceId,174 candidate.longTermPublicKeyHex,175 candidate.signingPublicKeyHex,176 ) ?: return@launch177 178 if (deviceStore.isRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {179 pendingVouchedStore.removeBatch(setOf(id))180 return@launch181 }182 183 184 185 if (deviceStore.get(pending.deviceId) != null) {186 pendingVouchedStore.removeBatch(setOf(id))187 return@launch188 }189 190 191 192 if (!pendingVouchedStore.removeBatch(setOf(id))) return@launch193 if (deviceStore.isRevoked(pending.deviceId, pending.longTermPublicKeyHex)) return@launch194 deviceStore.upsert(195 PairedDevice(196 deviceId = pending.deviceId,197 deviceName = pending.deviceName,198 deviceType = pending.deviceType,199 longTermPublicKeyHex = pending.longTermPublicKeyHex,200 signingPublicKeyHex = pending.signingPublicKeyHex,201 trustSource = "vouched",202 wsPort = pending.wsPort,203 pairedAt = pending.pairedAt,204 ),205 )206 }207208 fun rejectVouchedDevice(id: String) = viewModelScope.launch {209 if (isDecoySession()) return@launch210 pendingVouchedStore.remove(id)211 }212213214 215 suspend fun rotateSyncIdentity(): Boolean {216 if (isDecoySession()) return false217 val ok = vault.rotateSyncIdentity()218 if (ok) {219 deviceStore.clear()220 syncOutcomes.reset()221 }222 return ok223 }224225 226 fun buildAdapter(): SyncVaultAdapter? {227 if (!vault.isUnlocked.value || isDecoySession()) return null228 if (!syncAllowedNow(generation)) return null229 val credentials = loadOrCreateLocalIdentity(context)230 return VaultSyncAdapter(231 repo = vault,232 ourDeviceId = credentials.deviceId,233 pairedDevices = deviceStore,234 pendingVouched = pendingVouchedStore,235 syncAlerts = syncAlertStore,236 localCredentials = credentials,237 )238 }239240 241242243244245 private val _generationState = MutableStateFlow(generationRecord())246 val generationState: StateFlow<SyncGeneration> = _generationState.asStateFlow()247248 private fun generationRecord(): SyncGeneration = resolveGeneration(generation, System.currentTimeMillis())249250 251252253254255256257258259 suspend fun confirmReset(masterPassword: String): String? {260 if (isDecoySession()) return "Reset is unavailable in this session"261 if (masterPassword.isBlank()) return "Enter your master password"262 val masterMatches = withContext(Dispatchers.Default) {263 vault.tryUnlockSlotA(masterPassword)?.let {264 vault.discardSlotAUnlock(it)265 true266 } ?: false267 }268 if (!masterMatches) return "Incorrect master password"269 val result = withContext(Dispatchers.Default) {270 _generationState.value = enterResetRequired(generation, System.currentTimeMillis())271 confirmSecureReset(generation, System.currentTimeMillis())272 }273 _generationState.value = generationRecord()274 return when (result) {275 ResetResult.V2_ANCHOR -> null276 ResetResult.RESET_NOT_COMPLETED ->277 "The reset did not complete — nothing was lost, try again ($RESET_NOT_COMPLETED)"278 }279 }280281 282283284285286287288289290 fun syncNow() {291 292 293 if (isDecoySession()) return294295 val decision = relaySettings.relayInForce()296 if (decision is RelayDecision.Refuse) {297 syncOutcomes.report(SyncOutcomeSummary(reason = decision.reason))298 return299 }300 if (!vault.isUnlocked.value) {301 syncOutcomes.report(SyncOutcomeSummary(reason = SyncOutcomeReason.VAULT_LOCKED))302 return303 }304305 306 307 308 309 val devices = deviceStore.getAll()310 if (devices.isEmpty()) {311 syncOutcomes.report(SyncOutcomeSummary(reason = SyncOutcomeReason.NO_PAIRED_DEVICES))312 return313 }314 315 316 317 318 if (devices.none { it.rendezvousSecretHex != null }) {319 syncOutcomes.report(320 SyncOutcomeSummary(321 reason = SyncOutcomeReason.NO_ELIGIBLE_HOST,322 detail = devices.joinToString("; ") {323 "${it.deviceName ?: it.deviceId} [type=${it.deviceType ?: "unset"}, trust=${it.trustSource ?: "unset"}]"324 },325 ),326 )327 return328 }329330 syncOutcomes.begin()331 PeachSyncService.start(context)332 333 334 335 336 337 attemptTimeout?.cancel()338 attemptTimeout = viewModelScope.launch {339 delay(SYNC_ATTEMPT_TIMEOUT_MS)340 if (syncOutcomes.summary.value.syncing) {341 syncOutcomes.report(342 SyncOutcomeSummary(343 reason = SyncOutcomeReason.RELAY_UNREACHABLE,344 detail = "no peer answered within ${SYNC_ATTEMPT_TIMEOUT_MS / 1000}s",345 ),346 )347 }348 }349 }350 private fun isDecoySession(): Boolean =351 vault.isUnlocked.value && vault.syncVaultId() == null352353 354355356357 fun triggerSync() = syncNow()358359 private var attemptTimeout: Job? = null360361 private companion object {362 const val SYNC_ATTEMPT_TIMEOUT_MS = 20_000L363 }364}