AdoptVaultViewModel.kt

19.4 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 upsertPairedDevice(device: PairedDevice) {304                devices.upsert(device)305            }306307            override suspend fun applyLicense(licenseKey: String) {308                if (!license.storeLicense(licenseKey) || !license.isProActive()) {309                    throw IllegalStateException("license_transfer_failed")310                }311            }312313            override suspend fun license(): String? =314                license.getLicenseKey()?.takeIf(license::validateLicense)315316            override fun onError(error: String) {317                protocolError = error318            }319320            override suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String?) {321                val adapter = VaultSyncAdapter(322                    repo = vault,323                    ourDeviceId = getOrCreateDeviceId(appContext),324                    pairedDevices = devices,325                )326                adapter.applyEntries(entries)327                adapter.applyTombstones(tombstones)328                if (!duressSlot.isNullOrBlank()) {329                    try {330                        val ok = vault.installAdoptedDuressSlot(duressSlot)331                        if (!ok) Log.w("PeachAdopt", "duress slot install returned false; adoption continues")332                    } catch (e: Exception) {333                        Log.w("PeachAdopt", "duress slot install failed; adoption continues", e)334                    }335                }336            }337338            override suspend fun applyIncomingDeviceManifest(339                manifest: SignedDeviceManifest,340                authenticatedRemoteStaticPublicKey: ByteArray,341            ) {342                // Mesh graduation: the source's signed device graph promotes343                // the receiver into the full mesh pool. The receiver must344                // already have the source as a paired device (see applySnapshot345                // above which calls upsertPairedDevice via the Grant path),346                // so applyIncomingDeviceManifest can resolve the issuer by its347                // transport static key and verify the manifest signature.348                val adapter = VaultSyncAdapter(349                    repo = vault,350                    ourDeviceId = getOrCreateDeviceId(appContext),351                    pairedDevices = devices,352                    pendingVouched = pendingVouchedStore,353                )354                adapter.applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey)355            }356357            override suspend fun markSynced(deviceId: String) {358                devices.updateLastSync(deviceId)359            }360        }361362    private fun sourceDeps(identity: LocalDeviceIdentity): AdoptionSourceDeps =363        object : AdoptionSourceDeps {364            override val sourceIdentity: LocalDeviceIdentity = identity365366            override suspend fun rootKeyHex(): String {367                val root = vault.syncMasterKey()368                    ?: throw IllegalStateException("vault_locked")369                return try {370                    root.joinToString("") { "%02x".format(it) }371                } finally {372                    VaultCrypto.zero(root)373                }374            }375376            override suspend fun vaultId(): String =377                vault.syncVaultId() ?: throw IllegalStateException("vault_locked")378379            override suspend fun license(): String? =380                license.getLicenseKey()?.takeIf(license::validateLicense)381382            override suspend fun applyLicense(licenseKey: String) {383                if (!license.storeLicense(licenseKey) || !license.isProActive()) {384                    throw IllegalStateException("license_transfer_failed")385                }386            }387388            override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true389390            override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =391                devices.hasIdentityCollision(device)392393            override suspend fun rotateSourceIdentity(): LocalDeviceIdentity {394                rotateDeviceId(appContext)395                val master = vault.syncMasterKey()396                    ?: throw IllegalStateException("vault_locked")397                return try {398                    buildLocalIdentity(appContext, master)399                } finally {400                    VaultCrypto.zero(master)401                }402            }403404            override suspend fun upsertPairedDevice(device: PairedDevice) {405                devices.clearRevocation(device.deviceId)406                devices.upsert(device)407            }408409            override suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? {410                val adapter = VaultSyncAdapter(411                    repo = vault,412                    ourDeviceId = getOrCreateDeviceId(appContext),413                    pairedDevices = devices,414                )415                val entryManifest = adapter.buildEntryManifest()416                val entryIds = entryManifest.keys.toList()417                val entries = if (entryIds.isNotEmpty()) adapter.getEncryptedEntries(entryIds) else emptyMap()418                val tombstones = adapter.buildTombstoneManifest()419                return entries to tombstones420            }421422            override suspend fun outgoingDeviceManifest(): SignedDeviceManifest? {423                val adapter = VaultSyncAdapter(424                    repo = vault,425                    ourDeviceId = getOrCreateDeviceId(appContext),426                    pairedDevices = devices,427                )428                return adapter.buildOutgoingDeviceManifest()429            }430431            override suspend fun markSynced(deviceId: String) {432                devices.updateLastSync(deviceId)433            }434435            override suspend fun duressSlotJson(): String? =436                vault.exportDuressSlotForAdoption()437        }438439    fun setBackgroundSync(enabled: Boolean) {440        backgroundSync.setEnabled(enabled)441        if (enabled) PeachSyncService.start(appContext) else PeachSyncService.stop(appContext)442    }443444    private fun clearPassword() {445        password = null446    }447448    override fun onCleared() {449        adoptionJob?.cancel()450        confirmation?.complete(false)451        clearPassword()452        super.onCleared()453    }454}455456internal fun initialAdoptVaultState(hasVault: Boolean): AdoptVaultUiState =457    if (hasVault) AdoptVaultUiState.Pair else AdoptVaultUiState.Password458459/**460 * Pairing is not a merge tool. A populated destination may re-pair only when461 * both sides already derive the same vault id. Different ids must stop before462 * recovery words, entries, revocations, or paired-device state are changed.463 */464internal fun requireSameVaultForPopulatedRePair(465    localVaultId: String?,466    incomingVaultId: String,467): String {468    if (localVaultId == null) throw IllegalStateException("vault_locked")469    if (localVaultId != incomingVaultId) {470        throw IllegalStateException("JOIN_POPULATED_VAULT_BLOCKED")471    }472    return localVaultId473}