SyncViewModel.kt

13.1 KB · raw

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.SyncVaultAdapter9import com.peachpasswords.sync.PairedDevice10import com.peachpasswords.sync.PairedDeviceStore11import com.peachpasswords.sync.PendingVouchedDevice12import com.peachpasswords.sync.PendingVouchedDeviceStore13import com.peachpasswords.sync.PeachSyncService14import com.peachpasswords.sync.RelayDecision15import com.peachpasswords.sync.RelaySettingsStore16import com.peachpasswords.sync.SyncMode17import com.peachpasswords.sync.SyncAlertStore18import com.peachpasswords.sync.SyncOutcomeReason19import com.peachpasswords.sync.SyncOutcomeStore20import com.peachpasswords.sync.SyncOutcomeSummary21import com.peachpasswords.sync.VaultSyncAdapter22import com.peachpasswords.sync.loadOrCreateLocalIdentity23import com.peachpasswords.vault.VaultRepository24import dagger.hilt.android.lifecycle.HiltViewModel25import dagger.hilt.android.qualifiers.ApplicationContext26import kotlinx.coroutines.flow.MutableStateFlow27import kotlinx.coroutines.flow.SharingStarted28import kotlinx.coroutines.flow.StateFlow29import kotlinx.coroutines.flow.asStateFlow30import kotlinx.coroutines.flow.combine31import kotlinx.coroutines.flow.stateIn32import kotlinx.coroutines.delay33import kotlinx.coroutines.Job34import kotlinx.coroutines.launch35import javax.inject.Inject3637/**38 * Backs the Sync settings card: relay mode, the paired-device list, and the39 * manual sync control.40 *41 * Sync itself runs in [PeachSyncService], which holds a socket in each paired42 * peer's rendezvous room. Which side opens the conversation there depends on43 * the peer: we wait for a browser extension, because an extension can only44 * dial, and for another phone the lower long-term key dials. So45 * "sync now" makes sure the service is up and asks it to re-read the device46 * list — the work happens there, not here. See docs/sync-lan-retirement.md.47 */48@HiltViewModel49class SyncViewModel @Inject constructor(50    @ApplicationContext private val context: Context,51    private val vault: VaultRepository,52    private val deviceStore: PairedDeviceStore,53    private val pendingVouchedStore: PendingVouchedDeviceStore,54    private val syncAlertStore: SyncAlertStore,55    private val backgroundSync: BackgroundSyncPreference,56    private val relaySettings: RelaySettingsStore,57    private val syncOutcomes: SyncOutcomeStore,58) : ViewModel() {5960    /** The last sync attempt, whatever it was. Survives process death. */61    val status: StateFlow<SyncOutcomeSummary> =62        combine(syncOutcomes.summary, vault.isUnlocked) { summary, unlocked ->63            if (unlocked && vault.syncVaultId() == null) SyncOutcomeSummary() else summary64        }.stateIn(65            viewModelScope,66            SharingStarted.WhileSubscribed(5_000),67            if (vault.isUnlocked.value && vault.syncVaultId() == null) {68                SyncOutcomeSummary()69            } else {70                syncOutcomes.summary.value71            },72        )7374    /**75     * Decides when the sync service actually runs for the background-sync76     * preference. The service's own locked-handling is the gate — refusing to77     * start here while locked used to leave the preference on with no78     * notification, which was exactly the v2.5.13 "no peer answered" symptom.79     */80    private val backgroundSyncCoordinator = BackgroundSyncCoordinator(81        start = { PeachSyncService.start(context) },82        stop = { PeachSyncService.stop(context) },83        isUnlocked = vault.isUnlocked,84        preferenceEnabled = backgroundSync.enabled,85        syncVaultId = vault::syncVaultId,86    )8788    init {89        // Catches the lock-then-unlock case: the user enables the setting while90        // locked, then unlocks — the service should come up the moment a sync91        // identity exists. StateFlow.collect fires the current value92        // immediately, so the already-unlocked case is covered too.93        backgroundSyncCoordinator.observe(viewModelScope)94    }9596    fun setBackgroundSyncEnabled(enabled: Boolean) {97        if (isDecoySession()) return98        backgroundSync.setEnabled(enabled)99        backgroundSyncCoordinator.setEnabled(enabled)100    }101    val backgroundSyncEnabled: StateFlow<Boolean> = backgroundSync.enabled102103    /** Blank while no private relay is configured, so the field stays honest. */104    private val _privateRelayUrl = MutableStateFlow(relaySettings.privateRelayUrl())105    val privateRelayUrl: StateFlow<String> = _privateRelayUrl.asStateFlow()106107108    private val _syncMode = MutableStateFlow(relaySettings.syncMode())109    val syncMode: StateFlow<SyncMode> = _syncMode.asStateFlow()110111    fun setSyncMode(mode: SyncMode) {112        if (isDecoySession()) return113        relaySettings.setSyncMode(mode)114        _syncMode.value = relaySettings.syncMode()115        _privateRelayUrl.value = relaySettings.privateRelayUrl()116    }117118    /** A custom URL implies private mode. Returns false on an invalid URL. */119    fun setRelayUrl(input: String): Boolean {120        if (isDecoySession()) return false121        return runCatching {122            relaySettings.setRelayUrl(input)123            _privateRelayUrl.value = relaySettings.privateRelayUrl()124            _syncMode.value = relaySettings.syncMode()125            true126        }.getOrDefault(false)127    }128129130    /** Live list of trusted peers, redacted while a decoy session is active (C7). */131    val pairedDevices: StateFlow<List<PairedDevice>> =132        combine(deviceStore.observeAll(), vault.isUnlocked) { devices, unlocked ->133            if (unlocked && vault.syncVaultId() == null) emptyList() else devices134        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())135136    val pendingVouched: StateFlow<List<PendingVouchedDevice>> =137        combine(pendingVouchedStore.observeAll(), vault.isUnlocked) { pending, unlocked ->138            if (unlocked && vault.syncVaultId() == null) emptyList() else pending139        }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())140141    /**142     * Revoke a paired device. Removing it REVOKES rather than just dropping the143     * local row: a plain removal is undone the moment any other peer vouches it144     * back through a manifest, which is exactly what the relay makes easy.145     */146    fun unpairDevice(id: String) = viewModelScope.launch {147        if (isDecoySession()) return@launch148        deviceStore.revoke(id, loadOrCreateLocalIdentity(context).deviceId)149        PeachSyncService.start(context)150    }151152    fun renameDevice(id: String, name: String) = viewModelScope.launch {153        if (isDecoySession()) return@launch154        deviceStore.rename(id, name)155    }156157    fun confirmVouchedDevice(id: String) = viewModelScope.launch {158        if (isDecoySession()) return@launch159        val candidate = pendingVouchedStore.get(id) ?: return@launch160        val pending = pendingVouchedStore.get(161            candidate.deviceId,162            candidate.longTermPublicKeyHex,163            candidate.signingPublicKeyHex,164        ) ?: return@launch165        // here rather than trusted to have swept the queue.166        if (deviceStore.isRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {167            pendingVouchedStore.removeBatch(setOf(id))168            return@launch169        }170        // Never let a stale queue item overwrite an already trusted row (in171        // particular a direct SAS-paired row). The queued introduction is172        // consumed, but the established trust record remains authoritative.173        if (deviceStore.get(pending.deviceId) != null) {174            pendingVouchedStore.removeBatch(setOf(id))175            return@launch176        }177        // Remove the pending row synchronously before publishing trust. If the178        // subsequent upsert fails, the safe outcome is a lost introduction,179        // not a restart that replays stale pending trust over a revocation.180        if (!pendingVouchedStore.removeBatch(setOf(id))) return@launch181        if (deviceStore.isRevoked(pending.deviceId, pending.longTermPublicKeyHex)) return@launch182        deviceStore.upsert(183            PairedDevice(184                deviceId = pending.deviceId,185                deviceName = pending.deviceName,186                deviceType = pending.deviceType,187                longTermPublicKeyHex = pending.longTermPublicKeyHex,188                signingPublicKeyHex = pending.signingPublicKeyHex,189                trustSource = "vouched",190                wsPort = pending.wsPort,191                pairedAt = pending.pairedAt,192            ),193        )194    }195196    fun rejectVouchedDevice(id: String) = viewModelScope.launch {197        if (isDecoySession()) return@launch198        pendingVouchedStore.remove(id)199    }200201202    /** Browser-style nuclear recovery path: re-key sync and forget every peer. */203    suspend fun rotateSyncIdentity(): Boolean {204        if (isDecoySession()) return false205        val ok = vault.rotateSyncIdentity()206        if (ok) {207            deviceStore.clear()208            syncOutcomes.reset()209        }210        return ok211    }212213    /** Adapter over the live vault; null while the vault is locked. */214    fun buildAdapter(): SyncVaultAdapter? {215        if (!vault.isUnlocked.value || isDecoySession()) return null216        val credentials = loadOrCreateLocalIdentity(context)217        return VaultSyncAdapter(218            repo = vault,219            ourDeviceId = credentials.deviceId,220            pairedDevices = deviceStore,221            pendingVouched = pendingVouchedStore,222            syncAlerts = syncAlertStore,223            localCredentials = credentials,224        )225    }226227    /**228     * Manual trigger, and the one place a sync attempt is started on purpose.229     *230     * It used to claim a completed sync the instant the service was231     * asked to start, which is a success it had not earned — the service only232     * re-reads the device list, and the sync itself happens later in a233     * rendezvous room or not at all. Now the attempt goes busy and the outcome234     * comes from whoever actually finishes it.235     */236    fun syncNow() {237        // A decoy session must not touch the real outcome store or start the238        // sync service: either would expose or mutate real-session history.239        if (isDecoySession()) return240241        val decision = relaySettings.relayInForce()242        if (decision is RelayDecision.Refuse) {243            syncOutcomes.report(SyncOutcomeSummary(reason = decision.reason))244            return245        }246        if (!vault.isUnlocked.value) {247            syncOutcomes.report(SyncOutcomeSummary(reason = SyncOutcomeReason.VAULT_LOCKED))248            return249        }250251        // Read the store, not `pairedDevices.value`: that flow only holds a real252        // list while something is collecting it, so pull-to-refresh on the vault253        // list — which collects `status` and nothing else — always saw an empty254        // list and reported "no devices paired" against a fully paired phone.255        val devices = deviceStore.getAll()256        if (devices.isEmpty()) {257            syncOutcomes.report(SyncOutcomeSummary(reason = SyncOutcomeReason.NO_PAIRED_DEVICES))258            return259        }260        // The same filter CloudRelayReconnectListener applies when it decides261        // which rooms to hold — a peer with no rendezvous secret is skipped262        // there in silence, which is precisely the case that must not look like263        // a successful no-op.264        if (devices.none { it.rendezvousSecretHex != null }) {265            syncOutcomes.report(266                SyncOutcomeSummary(267                    reason = SyncOutcomeReason.NO_ELIGIBLE_HOST,268                    detail = devices.joinToString("; ") {269                        "${it.deviceName ?: it.deviceId} [type=${it.deviceType ?: "unset"}, trust=${it.trustSource ?: "unset"}]"270                    },271                ),272            )273            return274        }275276        syncOutcomes.begin()277        PeachSyncService.start(context)278        // Nothing else can close this attempt: the phone usually WAITS to be279        // dialled, so if no peer turns up there is no session to report a280        // failure from and the light would pulse for ever. Deliberately shorter281        // than the dialler's own bound: this one answers the person holding the282        // phone, and a session still running will report over it.283        attemptTimeout?.cancel()284        attemptTimeout = viewModelScope.launch {285            delay(SYNC_ATTEMPT_TIMEOUT_MS)286            if (syncOutcomes.summary.value.syncing) {287                syncOutcomes.report(288                    SyncOutcomeSummary(289                        reason = SyncOutcomeReason.RELAY_UNREACHABLE,290                        detail = "no peer answered within ${SYNC_ATTEMPT_TIMEOUT_MS / 1000}s",291                    ),292                )293            }294        }295    }296    private fun isDecoySession(): Boolean =297        vault.isUnlocked.value && vault.syncVaultId() == null298299    /**300     * Legacy manual / discovery trigger kept for existing callers; now routes301     * through [syncNow] so a populated device store actually dials peers.302     */303    fun triggerSync() = syncNow()304305    private var attemptTimeout: Job? = null306307    private companion object {308        const val SYNC_ATTEMPT_TIMEOUT_MS = 20_000L309    }310}