AdoptVaultViewModel.kt

19.7 KB · raw

1package com.peachpasswords.ui.pairing23import android.content.Context4import android.util.Log5import androidx.lifecycle.ViewModel6import androidx.lifecycle.viewModelScope7import com.peachpasswords.license.LicenseRepository8import com.peachpasswords.sync.AdoptionReceiverDeps9import com.peachpasswords.sync.AdoptionSourceDeps10import com.peachpasswords.sync.BackgroundSyncPreference11import com.peachpasswords.sync.DeviceType12import com.peachpasswords.sync.AdoptionFrame13import com.peachpasswords.sync.LocalDeviceIdentity14import com.peachpasswords.sync.PairedDevice15import com.peachpasswords.sync.PairedDeviceStore16import com.peachpasswords.sync.PendingVouchedDeviceStore17import com.peachpasswords.sync.SignedDeviceManifest18import com.peachpasswords.sync.VaultSyncAdapter19import com.peachpasswords.sync.PeachSyncService20import com.peachpasswords.sync.RelayAdoptionReceiver21import com.peachpasswords.sync.RelaySettingsStore22import com.peachpasswords.sync.RelayDecision23import com.peachpasswords.sync.VaultStatus24import com.peachpasswords.sync.buildLocalIdentity25import com.peachpasswords.sync.computeVaultId26import com.peachpasswords.sync.deriveLocalSyncKeypair27import com.peachpasswords.sync.getDeviceName28import com.peachpasswords.sync.getOrCreateDeviceId29import com.peachpasswords.sync.hexToPubkey30import com.peachpasswords.sync.rotateDeviceId31import com.peachpasswords.sync.parsePairingInvitation32import com.peachpasswords.ui.security.scorePassword33import com.peachpasswords.vault.AdoptVaultResult34import com.peachpasswords.vault.VaultCrypto35import com.peachpasswords.vault.VaultRepository36import dagger.hilt.android.lifecycle.HiltViewModel37import dagger.hilt.android.qualifiers.ApplicationContext38import java.util.UUID39import javax.inject.Inject40import kotlinx.coroutines.CompletableDeferred41import kotlinx.coroutines.CancellationException42import kotlinx.coroutines.Job43import kotlinx.coroutines.flow.MutableStateFlow44import kotlinx.coroutines.flow.StateFlow45import kotlinx.coroutines.flow.asStateFlow46import kotlinx.coroutines.launch4748sealed interface AdoptVaultUiState {49    data object Password : AdoptVaultUiState50    data object Pair : AdoptVaultUiState51    data object Connecting : AdoptVaultUiState52    /**53     * Source-initiator flow exposes [isSource] so the screen can phrase the54     * confirmation as "send vault" instead of "adopt/join vault". The SAS is55     * identical to the receiver flow; only the payload direction differs.56     */57    data class ConfirmSas(58        val sas: String,59        val isSource: Boolean = false,60        val peerName: String? = null,61    ) : AdoptVaultUiState62    data object Adopting : AdoptVaultUiState63    data class Complete(val sourceName: String) : AdoptVaultUiState64    data class Failed(val reason: String) : AdoptVaultUiState65}6667@HiltViewModel68class AdoptVaultViewModel @Inject constructor(69    private val receiver: RelayAdoptionReceiver,70    private val vault: VaultRepository,71    private val devices: PairedDeviceStore,72    private val relaySettings: RelaySettingsStore,73    private val backgroundSync: BackgroundSyncPreference,74    private val license: LicenseRepository,75    private val pendingVouchedStore: PendingVouchedDeviceStore,76    @ApplicationContext private val appContext: Context,77) : ViewModel() {78    /**79     * True when this device already has a vault. A populated device may refresh80     * a pairing only for that exact vault identity; it may not adopt a different81     * root key and silently merge two record sets.82     */83    val joining: Boolean = vault.hasVault()8485    private val _state = MutableStateFlow<AdoptVaultUiState>(86        initialAdoptVaultState(joining),87    )88    val state: StateFlow<AdoptVaultUiState> = _state.asStateFlow()8990    private var password: String? = null91    private var confirmation: CompletableDeferred<Boolean>? = null92    private var adoptionJob: Job? = null93    private var protocolError: String? = null9495    fun acceptPassword(value: String, repeated: String): Boolean {96        if (value.length < 12 || value != repeated || scorePassword(value) < 2) {97            return false98        }99        password = value100        _state.value = AdoptVaultUiState.Pair101        return true102    }103104    fun adopt(invitation: String) {105        if (_state.value !is AdoptVaultUiState.Pair) return106        val parsed = parsePairingInvitation(invitation)107        if (parsed == null) {108            _state.value = AdoptVaultUiState.Failed("invalid_pairing_invitation")109            clearPassword()110            return111        }112        when (parsed.vaultStatus) {113            VaultStatus.POPULATED -> startReceiverFlow(invitation)114            VaultStatus.EMPTY -> startSourceFlow(invitation)115        }116    }117118    private fun startReceiverFlow(invitation: String) {119        _state.value = AdoptVaultUiState.Connecting120        protocolError = null121        adoptionJob = viewModelScope.launch {122            try {123                val adopted = receiver.adopt(124                    encodedInvitation = invitation,125                    deps = receiverDeps(),126                    confirm = { sas ->127                        val pending = CompletableDeferred<Boolean>()128                        confirmation = pending129                        _state.value = AdoptVaultUiState.ConfirmSas(130                            sas = sas,131                            isSource = false,132                        )133                        pending.await()134                    },135                )136                // The pair carries the source's relay, but the Sync card reads137                // this device's own setting — left alone it would say "Public138                // relay" on a phone dialling a private one. Peach's own URL139                // still lands on PUBLIC, so joining over the public relay is140                // not relabelled private.141                adopted.relayUrl?.let(relaySettings::setRelayUrl)142                _state.value = AdoptVaultUiState.Complete(143                    adopted.deviceName?.takeIf(String::isNotBlank) ?: "Your other device",144                )145            } catch (error: CancellationException) {146                throw error147            } catch (error: Throwable) {148                _state.value = AdoptVaultUiState.Failed(149                    protocolError ?: error.message ?: "adoption_failed",150                )151            } finally {152                confirmation = null153                clearPassword()154            }155        }156    }157158    /**159     * Source-initiator flow: the scanning invitation came from a vault-less160     * device, so the phone dials the relay, completes Noise, and sends the161     * root key over. Uses the same UI states as the receiver flow so the162     * surface area stays the same; only [AdoptVaultUiState.ConfirmSas.isSource]163     * distinguishes the role for the confirmation copy.164     */165    private fun startSourceFlow(invitation: String) {166        val master = vault.syncMasterKey()167        if (master == null) {168            _state.value = AdoptVaultUiState.Failed("vault_locked")169            clearPassword()170            return171        }172        when (val decision = relaySettings.relayInForce()) {173            is RelayDecision.Refuse -> {174                VaultCrypto.zero(master)175                _state.value = AdoptVaultUiState.Failed(decision.reason.wire())176                clearPassword()177                return178            }179            is RelayDecision.Dial -> Unit180        }181        _state.value = AdoptVaultUiState.Connecting182        protocolError = null183184        val keys = deriveLocalSyncKeypair(master, getOrCreateDeviceId(appContext))185        val identity = buildLocalIdentity(appContext, master)186        VaultCrypto.zero(master)187        adoptionJob = viewModelScope.launch {188            try {189                val paired = receiver.grantFromInvitation(190                    encodedInvitation = invitation,191                    sourceDeps = sourceDeps(identity),192                    confirm = { sas, request ->193                        val pending = CompletableDeferred<Boolean>()194                        confirmation = pending195                        _state.value = AdoptVaultUiState.ConfirmSas(196                            sas = sas,197                            isSource = true,198                            peerName = request.deviceName.ifBlank { "New device" },199                        )200                        pending.await()201                    },202                )203                paired.relayUrl?.let(relaySettings::setRelayUrl)204                _state.value = AdoptVaultUiState.Complete(205                    paired.deviceName?.takeIf(String::isNotBlank) ?: "Your other device",206                )207            } catch (error: CancellationException) {208                throw error209            } catch (error: Throwable) {210                _state.value = AdoptVaultUiState.Failed(211                    protocolError ?: error.message ?: "adoption_failed",212                )213            } finally {214                VaultCrypto.zero(keys.secretKey)215                VaultCrypto.zero(keys.publicKey)216                confirmation = null217                clearPassword()218            }219        }220    }221222    fun confirmSas(matches: Boolean) {223        val pending = confirmation ?: return224        confirmation = null225        if (matches) _state.value = AdoptVaultUiState.Adopting226        pending.complete(matches)227    }228229    fun restart() {230        adoptionJob?.cancel()231        adoptionJob = null232        confirmation?.complete(false)233        confirmation = null234        clearPassword()235        _state.value = initialAdoptVaultState(joining)236    }237238    private fun receiverDeps(): AdoptionReceiverDeps =239        object : AdoptionReceiverDeps {240            override val deviceName = getDeviceName(appContext)241            override val deviceType = DeviceType.ANDROID242            override fun generateDeviceId(): String = UUID.randomUUID().toString()243244            // RelayAdoptionReceiver replaces this with the SAS bound to its245            // completed Noise transcript.246            override suspend fun confirmSas(): Boolean = false247248            override suspend fun validateSource(source: AdoptionFrame.Source) {249                // First contact on a populated vault is allowed: a second250                // browser, a tablet, another phone — any device that holds the251                // same root key (the same recovery words) is the same vault.252                // The vault-id check in createVaultFromRootKey is the real253                // security boundary; this callback now only documents intent254                // for callers that want to layer their own policy on top.255                if (!joining) return256            }257258            override suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source): Boolean =259                devices.isRevoked(source.deviceId, source.longTermPublicKeyHex)260261            override suspend fun createVaultFromRootKey(rootKeyHex: String): String {262                // Same protocol seam, two safe outcomes: a fresh device builds263                // around the granted key; a populated device may only refresh a264                // pairing when it already has that exact vault identity.265                val result = if (joining) {266                    val incomingRoot = hexToPubkey(rootKeyHex)267                    val incomingVaultId = try {268                        computeVaultId(incomingRoot)269                    } finally {270                        VaultCrypto.zero(incomingRoot)271                    }272                    AdoptVaultResult.Success(273                        requireSameVaultForPopulatedRePair(274                            localVaultId = vault.syncVaultId(),275                            incomingVaultId = incomingVaultId,276                        ),277                    )278                } else {279                    val localPassword = password280                        ?: throw IllegalStateException("adoption_password_unavailable")281                    vault.createVaultFromRootKey(localPassword, rootKeyHex)282                }283                return when (result) {284                    is AdoptVaultResult.Success -> result.vaultId285                    is AdoptVaultResult.Error -> throw IllegalStateException(result.reason)286                }287            }288289            override suspend fun deriveLocalIdentity(): LocalDeviceIdentity {290                val master = vault.syncMasterKey()291                    ?: throw IllegalStateException("adopted_vault_unavailable")292                return try {293                    buildLocalIdentity(appContext, master)294                } finally {295                    VaultCrypto.zero(master)296                }297            }298299            override suspend fun clearPairedDeviceRevocation(deviceId: String) {300                devices.clearRevocation(deviceId)301            }302303            override suspend fun upsertPairedDeviceAndClearRevocation(device: PairedDevice) {304                devices.upsertAndClearRevocation(device)305            }306307            override suspend fun upsertPairedDevice(device: PairedDevice) {308                devices.upsert(device)309            }310311            override suspend fun applyLicense(licenseKey: String) {312                if (!license.storeLicense(licenseKey) || !license.isProActive()) {313                    throw IllegalStateException("license_transfer_failed")314                }315            }316317            override suspend fun license(): String? =318                license.getLicenseKey()?.takeIf(license::validateLicense)319320            override fun onError(error: String) {321                protocolError = error322            }323324            override suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String?) {325                val adapter = VaultSyncAdapter(326                    repo = vault,327                    ourDeviceId = getOrCreateDeviceId(appContext),328                    pairedDevices = devices,329                )330                adapter.applyEntries(entries)331                adapter.applyTombstones(tombstones)332                if (!duressSlot.isNullOrBlank()) {333                    try {334                        val ok = vault.installAdoptedDuressSlot(duressSlot)335                        if (!ok) Log.w("PeachAdopt", "duress slot install returned false; adoption continues")336                    } catch (e: Exception) {337                        Log.w("PeachAdopt", "duress slot install failed; adoption continues", e)338                    }339                }340            }341342            override suspend fun applyIncomingDeviceManifest(343                manifest: SignedDeviceManifest,344                authenticatedRemoteStaticPublicKey: ByteArray,345            ) {346                // Mesh graduation: the source's signed device graph promotes347                // the receiver into the full mesh pool. The receiver must348                // already have the source as a paired device (see applySnapshot349                // above which calls upsertPairedDevice via the Grant path),350                // so applyIncomingDeviceManifest can resolve the issuer by its351                // transport static key and verify the manifest signature.352                val adapter = VaultSyncAdapter(353                    repo = vault,354                    ourDeviceId = getOrCreateDeviceId(appContext),355                    pairedDevices = devices,356                    pendingVouched = pendingVouchedStore,357                )358                adapter.applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey)359            }360361            override suspend fun markSynced(deviceId: String) {362                devices.updateLastSync(deviceId)363            }364        }365366    private fun sourceDeps(identity: LocalDeviceIdentity): AdoptionSourceDeps =367        object : AdoptionSourceDeps {368            override val sourceIdentity: LocalDeviceIdentity = identity369370            override suspend fun rootKeyHex(): String {371                val root = vault.syncMasterKey()372                    ?: throw IllegalStateException("vault_locked")373                return try {374                    root.joinToString("") { "%02x".format(it) }375                } finally {376                    VaultCrypto.zero(root)377                }378            }379380            override suspend fun vaultId(): String =381                vault.syncVaultId() ?: throw IllegalStateException("vault_locked")382383            override suspend fun license(): String? =384                license.getLicenseKey()?.takeIf(license::validateLicense)385386            override suspend fun applyLicense(licenseKey: String) {387                if (!license.storeLicense(licenseKey) || !license.isProActive()) {388                    throw IllegalStateException("license_transfer_failed")389                }390            }391392            override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true393394            override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =395                devices.hasIdentityCollision(device)396397            override suspend fun rotateSourceIdentity(): LocalDeviceIdentity {398                rotateDeviceId(appContext)399                val master = vault.syncMasterKey()400                    ?: throw IllegalStateException("vault_locked")401                return try {402                    buildLocalIdentity(appContext, master)403                } finally {404                    VaultCrypto.zero(master)405                }406            }407408            override suspend fun upsertPairedDevice(device: PairedDevice) {409                // SAS-confirmed direct adoption atomically validates identity,410                // lifts terminal revocation, and persists the paired row.411                devices.upsertAndClearRevocation(device)412            }413414            override suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? {415                val adapter = VaultSyncAdapter(416                    repo = vault,417                    ourDeviceId = getOrCreateDeviceId(appContext),418                    pairedDevices = devices,419                )420                val entryManifest = adapter.buildEntryManifest()421                val entryIds = entryManifest.keys.toList()422                val entries = if (entryIds.isNotEmpty()) adapter.getEncryptedEntries(entryIds) else emptyMap()423                val tombstones = adapter.buildTombstoneManifest()424                return entries to tombstones425            }426427            override suspend fun outgoingDeviceManifest(): SignedDeviceManifest? {428                val adapter = VaultSyncAdapter(429                    repo = vault,430                    ourDeviceId = getOrCreateDeviceId(appContext),431                    pairedDevices = devices,432                )433                return adapter.buildOutgoingDeviceManifest()434            }435436            override suspend fun markSynced(deviceId: String) {437                devices.updateLastSync(deviceId)438            }439440            override suspend fun duressSlotJson(): String? =441                vault.exportDuressSlotForAdoption()442        }443444    fun setBackgroundSync(enabled: Boolean) {445        backgroundSync.setEnabled(enabled)446        if (enabled) PeachSyncService.start(appContext) else PeachSyncService.stop(appContext)447    }448449    private fun clearPassword() {450        password = null451    }452453    override fun onCleared() {454        adoptionJob?.cancel()455        confirmation?.complete(false)456        clearPassword()457        super.onCleared()458    }459}460461internal fun initialAdoptVaultState(hasVault: Boolean): AdoptVaultUiState =462    if (hasVault) AdoptVaultUiState.Pair else AdoptVaultUiState.Password463464/**465 * Pairing is not a merge tool. A populated destination may re-pair only when466 * both sides already derive the same vault id. Different ids must stop before467 * recovery words, entries, revocations, or paired-device state are changed.468 */469internal fun requireSameVaultForPopulatedRePair(470    localVaultId: String?,471    incomingVaultId: String,472): String {473    if (localVaultId == null) throw IllegalStateException("vault_locked")474    if (localVaultId != incomingVaultId) {475        throw IllegalStateException("JOIN_POPULATED_VAULT_BLOCKED")476    }477    return localVaultId478}