SyncViewModel.kt

15.7 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.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.Inject4647/**48 * Backs the Sync settings card: relay mode, the paired-device list, and the49 * manual sync control.50 *51 * Sync itself runs in [PeachSyncService], which holds a socket in each paired52 * peer's rendezvous room. Which side opens the conversation there depends on53 * the peer: we wait for a browser extension, because an extension can only54 * dial, and for another phone the lower long-term key dials. So55 * "sync now" makes sure the service is up and asks it to re-read the device56 * list — the work happens there, not here. See docs/sync-lan-retirement.md.57 */58@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    /** The last sync attempt, whatever it was. Survives process death. */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    /**86     * Decides when the sync service actually runs for the background-sync87     * preference. The service's own locked-handling is the gate — refusing to88     * start here while locked used to leave the preference on with no89     * notification, which was exactly the v2.5.13 "no peer answered" symptom.90     */91    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        // Catches the lock-then-unlock case: the user enables the setting while102        // locked, then unlocks — the service should come up the moment a sync103        // identity exists. StateFlow.collect fires the current value104        // immediately, so the already-unlocked case is covered too.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    /** Blank while no private relay is configured, so the field stays honest. */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    /** A custom URL implies private mode. Returns false on an invalid URL. */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    /** Live list of trusted peers, redacted while a decoy session is active (C7). */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    /**154     * Revoke a paired device. Removing it REVOKES rather than just dropping the155     * local row: a plain removal is undone the moment any other peer vouches it156     * back through a manifest, which is exactly what the relay makes easy.157     */158    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        // here rather than trusted to have swept the queue.178        if (deviceStore.isRevoked(pending.deviceId, pending.longTermPublicKeyHex)) {179            pendingVouchedStore.removeBatch(setOf(id))180            return@launch181        }182        // Never let a stale queue item overwrite an already trusted row (in183        // particular a direct SAS-paired row). The queued introduction is184        // consumed, but the established trust record remains authoritative.185        if (deviceStore.get(pending.deviceId) != null) {186            pendingVouchedStore.removeBatch(setOf(id))187            return@launch188        }189        // Remove the pending row synchronously before publishing trust. If the190        // subsequent upsert fails, the safe outcome is a lost introduction,191        // not a restart that replays stale pending trust over a revocation.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    /** Browser-style nuclear recovery path: re-key sync and forget every peer. */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    /** Adapter over the live vault; null while the vault is locked. */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    /**241     * The §11 migration panel: what this device's Sync generation is, and what242     * it still owes the user. Not secret — it is a version and a state name —243     * so a decoy session shows the same thing without leaking anything.244     */245    private val _generationState = MutableStateFlow(generationRecord())246    val generationState: StateFlow<SyncGeneration> = _generationState.asStateFlow()247248    private fun generationRecord(): SyncGeneration = resolveGeneration(generation, System.currentTimeMillis())249250    /**251     * Enter the state that blocks sync, then run the migration. Entry is252     * separate from confirmation so a crash between them leaves the device253     * refusing sync rather than mid-reset with trust still live (§11.3).254     *255     * The master password confirms a trust-resetting action (§11.9), then the256     * archive → identity → pointer-flip sequence runs in that order. Returns257     * null on success, or the line to show the user.258     */259    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    /**282     * Manual trigger, and the one place a sync attempt is started on purpose.283     *284     * It used to claim a completed sync the instant the service was285     * asked to start, which is a success it had not earned — the service only286     * re-reads the device list, and the sync itself happens later in a287     * rendezvous room or not at all. Now the attempt goes busy and the outcome288     * comes from whoever actually finishes it.289     */290    fun syncNow() {291        // A decoy session must not touch the real outcome store or start the292        // sync service: either would expose or mutate real-session history.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        // Read the store, not `pairedDevices.value`: that flow only holds a real306        // list while something is collecting it, so pull-to-refresh on the vault307        // list — which collects `status` and nothing else — always saw an empty308        // list and reported "no devices paired" against a fully paired phone.309        val devices = deviceStore.getAll()310        if (devices.isEmpty()) {311            syncOutcomes.report(SyncOutcomeSummary(reason = SyncOutcomeReason.NO_PAIRED_DEVICES))312            return313        }314        // The same filter CloudRelayReconnectListener applies when it decides315        // which rooms to hold — a peer with no rendezvous secret is skipped316        // there in silence, which is precisely the case that must not look like317        // a successful no-op.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        // Nothing else can close this attempt: the phone usually WAITS to be333        // dialled, so if no peer turns up there is no session to report a334        // failure from and the light would pulse for ever. Deliberately shorter335        // than the dialler's own bound: this one answers the person holding the336        // phone, and a session still running will report over it.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    /**354     * Legacy manual / discovery trigger kept for existing callers; now routes355     * through [syncNow] so a populated device store actually dials peers.356     */357    fun triggerSync() = syncNow()358359    private var attemptTimeout: Job? = null360361    private companion object {362        const val SYNC_ATTEMPT_TIMEOUT_MS = 20_000L363    }364}