AdoptVaultViewModel.kt

21.2 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.loadOrCreateLocalIdentity27import com.peachpasswords.sync.localSyncKeypair28import com.peachpasswords.sync.getDeviceName29import com.peachpasswords.sync.loadOrCreateLocalIdentity30import com.peachpasswords.sync.hexToPubkey31import com.peachpasswords.sync.rotateDeviceId32import com.peachpasswords.sync.parsePairingInvitation33import com.peachpasswords.ui.security.scorePassword34import com.peachpasswords.vault.AdoptVaultResult35import com.peachpasswords.vault.VaultCrypto36import com.peachpasswords.vault.VaultRepository37import dagger.hilt.android.lifecycle.HiltViewModel38import dagger.hilt.android.qualifiers.ApplicationContext39import java.util.UUID40import javax.inject.Inject41import kotlinx.coroutines.CompletableDeferred42import kotlinx.coroutines.CancellationException43import kotlinx.coroutines.Job44import kotlinx.coroutines.flow.MutableStateFlow45import kotlinx.coroutines.flow.StateFlow46import kotlinx.coroutines.flow.asStateFlow47import kotlinx.coroutines.launch4849sealed interface AdoptVaultUiState {50    data object Password : AdoptVaultUiState51    data object Pair : AdoptVaultUiState52    data object Connecting : AdoptVaultUiState53    /**54     * Source-initiator flow exposes [isSource] so the screen can phrase the55     * confirmation as "send vault" instead of "adopt/join vault". The SAS is56     * identical to the receiver flow; only the payload direction differs.57     */58    data class ConfirmSas(59        val sas: String,60        val isSource: Boolean = false,61        val peerName: String? = null,62    ) : AdoptVaultUiState63    data object Adopting : AdoptVaultUiState64    data class Complete(val sourceName: String) : AdoptVaultUiState65    data class Failed(val reason: String) : AdoptVaultUiState66}6768@HiltViewModel69class AdoptVaultViewModel @Inject constructor(70    private val receiver: RelayAdoptionReceiver,71    private val vault: VaultRepository,72    private val devices: PairedDeviceStore,73    private val relaySettings: RelaySettingsStore,74    private val backgroundSync: BackgroundSyncPreference,75    private val license: LicenseRepository,76    private val pendingVouchedStore: PendingVouchedDeviceStore,77    @ApplicationContext private val appContext: Context,78) : ViewModel() {79    /**80     * True when this device already has a vault. A populated device may refresh81     * a pairing only for that exact vault identity; it may not adopt a different82     * root key and silently merge two record sets.83     */84    val joining: Boolean = vault.hasVault()8586    private val _state = MutableStateFlow<AdoptVaultUiState>(87        initialAdoptVaultState(joining),88    )89    val state: StateFlow<AdoptVaultUiState> = _state.asStateFlow()9091    private var password: String? = null92    private var confirmation: CompletableDeferred<Boolean>? = null93    private var adoptionJob: Job? = null94    private var protocolError: String? = null9596    fun acceptPassword(value: String, repeated: String): Boolean {97        if (value.length < 12 || value != repeated || scorePassword(value) < 2) {98            return false99        }100        password = value101        _state.value = AdoptVaultUiState.Pair102        return true103    }104105    fun adopt(invitation: String) {106        if (_state.value !is AdoptVaultUiState.Pair) return107        val parsed = parsePairingInvitation(invitation)108        if (parsed == null) {109            _state.value = AdoptVaultUiState.Failed("invalid_pairing_invitation")110            clearPassword()111            return112        }113        when (parsed.vaultStatus) {114            VaultStatus.POPULATED -> startReceiverFlow(invitation)115            VaultStatus.EMPTY -> startSourceFlow(invitation)116        }117    }118119    private fun startReceiverFlow(invitation: String) {120        _state.value = AdoptVaultUiState.Connecting121        protocolError = null122        adoptionJob = viewModelScope.launch {123            try {124                val adopted = receiver.adopt(125                    encodedInvitation = invitation,126                    deps = receiverDeps(),127                    confirm = { sas ->128                        val pending = CompletableDeferred<Boolean>()129                        confirmation = pending130                        _state.value = AdoptVaultUiState.ConfirmSas(131                            sas = sas,132                            isSource = false,133                        )134                        pending.await()135                    },136                )137                // The pair carries the source's relay, but the Sync card reads138                // this device's own setting — left alone it would say "Public139                // relay" on a phone dialling a private one. Peach's own URL140                // still lands on PUBLIC, so joining over the public relay is141                // not relabelled private.142                adopted.relayUrl?.let(relaySettings::setRelayUrl)143                _state.value = AdoptVaultUiState.Complete(144                    adopted.deviceName?.takeIf(String::isNotBlank) ?: "Your other device",145                )146            } catch (error: CancellationException) {147                throw error148            } catch (error: Throwable) {149                _state.value = AdoptVaultUiState.Failed(150                    protocolError ?: error.message ?: "adoption_failed",151                )152            } finally {153                confirmation = null154                clearPassword()155            }156        }157    }158159    /**160     * Source-initiator flow: the scanning invitation came from a vault-less161     * device, so the phone dials the relay, completes Noise, and sends the162     * root key over. Uses the same UI states as the receiver flow so the163     * surface area stays the same; only [AdoptVaultUiState.ConfirmSas.isSource]164     * distinguishes the role for the confirmation copy.165     */166    private fun startSourceFlow(invitation: String) {167        val master = vault.syncMasterKey()168        if (master == null) {169            _state.value = AdoptVaultUiState.Failed("vault_locked")170            clearPassword()171            return172        }173        when (val decision = relaySettings.relayInForce()) {174            is RelayDecision.Refuse -> {175                VaultCrypto.zero(master)176                _state.value = AdoptVaultUiState.Failed(decision.reason.wire())177                clearPassword()178                return179            }180            is RelayDecision.Dial -> Unit181        }182        _state.value = AdoptVaultUiState.Connecting183        protocolError = null184185        val credentials = loadOrCreateLocalIdentity(appContext)186        val keys = localSyncKeypair(credentials)187        val identity = buildLocalIdentity(appContext, credentials)188        VaultCrypto.zero(master)189        adoptionJob = viewModelScope.launch {190            try {191                val paired = receiver.grantFromInvitation(192                    encodedInvitation = invitation,193                    sourceDeps = sourceDeps(identity),194                    confirm = { sas, request ->195                        val pending = CompletableDeferred<Boolean>()196                        confirmation = pending197                        _state.value = AdoptVaultUiState.ConfirmSas(198                            sas = sas,199                            isSource = true,200                            peerName = request.deviceName.ifBlank { "New device" },201                        )202                        pending.await()203                    },204                )205                paired.relayUrl?.let(relaySettings::setRelayUrl)206                _state.value = AdoptVaultUiState.Complete(207                    paired.deviceName?.takeIf(String::isNotBlank) ?: "Your other device",208                )209            } catch (error: CancellationException) {210                throw error211            } catch (error: Throwable) {212                _state.value = AdoptVaultUiState.Failed(213                    protocolError ?: error.message ?: "adoption_failed",214                )215            } finally {216                VaultCrypto.zero(keys.secretKey)217                VaultCrypto.zero(keys.publicKey)218                confirmation = null219                clearPassword()220            }221        }222    }223224    fun confirmSas(matches: Boolean) {225        val pending = confirmation ?: return226        confirmation = null227        if (matches) _state.value = AdoptVaultUiState.Adopting228        pending.complete(matches)229    }230231    fun restart() {232        adoptionJob?.cancel()233        adoptionJob = null234        confirmation?.complete(false)235        confirmation = null236        clearPassword()237        _state.value = initialAdoptVaultState(joining)238    }239240    private fun receiverDeps(): AdoptionReceiverDeps =241        object : AdoptionReceiverDeps {242            override val deviceName = getDeviceName(appContext)243            override val deviceType = DeviceType.ANDROID244            override fun generateDeviceId(): String = UUID.randomUUID().toString()245246            // RelayAdoptionReceiver replaces this with the SAS bound to its247            // completed Noise transcript.248            override suspend fun confirmSas(): Boolean = false249250            override suspend fun validateSource(source: AdoptionFrame.Source) {251                // First contact on a populated vault is allowed: a second252                // browser, a tablet, another phone — any device that holds the253                // same root key (the same recovery words) is the same vault.254                // The vault-id check in createVaultFromRootKey is the real255                // security boundary; this callback now only documents intent256                // for callers that want to layer their own policy on top.257                if (!joining) return258            }259260            override suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source): Boolean =261                devices.isRevoked(source.deviceId, source.longTermPublicKeyHex)262263            override suspend fun createVaultFromRootKey(rootKeyHex: String): String {264                // Same protocol seam, two safe outcomes: a fresh device builds265                // around the granted key; a populated device may only refresh a266                // pairing when it already has that exact vault identity.267                val result = if (joining) {268                    val incomingRoot = hexToPubkey(rootKeyHex)269                    val incomingVaultId = try {270                        computeVaultId(incomingRoot)271                    } finally {272                        VaultCrypto.zero(incomingRoot)273                    }274                    AdoptVaultResult.Success(275                        requireSameVaultForPopulatedRePair(276                            localVaultId = vault.syncVaultId(),277                            incomingVaultId = incomingVaultId,278                        ),279                    )280                } else {281                    val localPassword = password282                        ?: throw IllegalStateException("adoption_password_unavailable")283                    vault.createVaultFromRootKey(localPassword, rootKeyHex)284                }285                return when (result) {286                    is AdoptVaultResult.Success -> result.vaultId287                    is AdoptVaultResult.Error -> throw IllegalStateException(result.reason)288                }289            }290291            override suspend fun deriveLocalIdentity(): LocalDeviceIdentity {292                val master = vault.syncMasterKey()293                    ?: throw IllegalStateException("adopted_vault_unavailable")294                return try {295                    buildLocalIdentity(appContext, master)296                } finally {297                    VaultCrypto.zero(master)298                }299            }300301            override suspend fun clearPairedDeviceRevocation(deviceId: String) {302                devices.clearRevocation(deviceId)303            }304305            override suspend fun upsertPairedDeviceAndClearRevocation(device: PairedDevice) {306                devices.upsertAndClearRevocation(device)307            }308309            override suspend fun upsertPairedDevice(device: PairedDevice) {310                devices.upsert(device)311            }312313            override suspend fun applyLicense(licenseKey: String) {314                if (!license.storeLicense(licenseKey) || !license.isProActive()) {315                    throw IllegalStateException("license_transfer_failed")316                }317            }318319            override suspend fun license(): String? =320                license.getLicenseKey()?.takeIf(license::validateLicense)321322            override fun onError(error: String) {323                protocolError = error324            }325326            override suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String?) {327                val credentials = loadOrCreateLocalIdentity(appContext)328                val adapter = VaultSyncAdapter(329                    repo = vault,330                    ourDeviceId = credentials.deviceId,331                    pairedDevices = devices,332                    localCredentials = credentials,333                )334                adapter.applyEntries(entries)335                adapter.applyTombstones(tombstones)336                if (!duressSlot.isNullOrBlank()) {337                    try {338                        val ok = vault.installAdoptedDuressSlot(duressSlot)339                        if (!ok) Log.w("PeachAdopt", "duress slot install returned false; adoption continues")340                    } catch (e: Exception) {341                        Log.w("PeachAdopt", "duress slot install failed; adoption continues", e)342                    }343                }344            }345346            override suspend fun applyIncomingDeviceManifest(347                manifest: SignedDeviceManifest,348                authenticatedRemoteStaticPublicKey: ByteArray,349            ) {350                // Mesh graduation: the source's signed device graph promotes351                // the receiver into the full mesh pool. The receiver must352                // already have the source as a paired device (see applySnapshot353                // above which calls upsertPairedDevice via the Grant path),354                val credentials = loadOrCreateLocalIdentity(appContext)355                val adapter = VaultSyncAdapter(356                    repo = vault,357                    ourDeviceId = credentials.deviceId,358                    pairedDevices = devices,359                    pendingVouched = pendingVouchedStore,360                    localCredentials = credentials,361                )362                adapter.applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey)363            }364365            override suspend fun markSynced(deviceId: String) {366                devices.updateLastSync(deviceId)367            }368        }369370    private fun sourceDeps(identity: LocalDeviceIdentity): AdoptionSourceDeps =371        object : AdoptionSourceDeps {372            override val sourceIdentity: LocalDeviceIdentity = identity373374            override suspend fun rootKeyHex(): String {375                val root = vault.syncMasterKey()376                    ?: throw IllegalStateException("vault_locked")377                return try {378                    root.joinToString("") { "%02x".format(it) }379                } finally {380                    VaultCrypto.zero(root)381                }382            }383384            override suspend fun vaultId(): String =385                vault.syncVaultId() ?: throw IllegalStateException("vault_locked")386387            override suspend fun license(): String? =388                license.getLicenseKey()?.takeIf(license::validateLicense)389390            override suspend fun applyLicense(licenseKey: String) {391                if (!license.storeLicense(licenseKey) || !license.isProActive()) {392                    throw IllegalStateException("license_transfer_failed")393                }394            }395396            override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true397            override suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long): Boolean {398                return runCatching {399                    pendingVouchedStore.upsertAndReport(400                        com.peachpasswords.sync.PendingVouchedDevice(401                            deviceId = request.sessionRequestId,402                            deviceName = request.deviceName,403                            deviceType = request.deviceType,404                            longTermPublicKeyHex = identity.longTermPublicKeyHex,405                            signingPublicKeyHex = identity.signingPublicKeyHex,406                            pairedAt = nowMs,407                            receivedAt = nowMs,408                            vouchedByDeviceId = identity.deviceId,409                        ),410                    )411                }.getOrDefault(false)412            }413414            override suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice): Boolean {415                return runCatching {416                    pendingVouchedStore.removeAndReport(request.sessionRequestId)417                }.getOrDefault(false)418            }419420            override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =421                devices.hasIdentityCollision(device)422423            override suspend fun rotateSourceIdentity(): LocalDeviceIdentity {424                rotateDeviceId(appContext)425                val master = vault.syncMasterKey()426                    ?: throw IllegalStateException("vault_locked")427                return try {428                    buildLocalIdentity(appContext, master)429                } finally {430                    VaultCrypto.zero(master)431                }432            }433434            override suspend fun upsertPairedDevice(device: PairedDevice) {435                // SAS-confirmed direct adoption atomically validates identity,436                // lifts terminal revocation, and persists the paired row.437                devices.upsertAndClearRevocation(device)438            }439440            override suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? {441                val credentials = loadOrCreateLocalIdentity(appContext)442                val adapter = VaultSyncAdapter(443                    repo = vault,444                    ourDeviceId = credentials.deviceId,445                    pairedDevices = devices,446                    localCredentials = credentials,447                )448                val entryManifest = adapter.buildEntryManifest()449                val entryIds = entryManifest.keys.toList()450                val entries = if (entryIds.isNotEmpty()) adapter.getEncryptedEntries(entryIds) else emptyMap()451                val tombstones = adapter.buildTombstoneManifest()452                return entries to tombstones453            }454            override suspend fun outgoingDeviceManifest(): SignedDeviceManifest? {455                val credentials = loadOrCreateLocalIdentity(appContext)456                val adapter = VaultSyncAdapter(457                    repo = vault,458                    ourDeviceId = credentials.deviceId,459                    pairedDevices = devices,460                    localCredentials = credentials,461                )462                return adapter.buildOutgoingDeviceManifest()463            }464465            override suspend fun markSynced(deviceId: String) {466                devices.updateLastSync(deviceId)467            }468469            override suspend fun duressSlotJson(): String? =470                vault.exportDuressSlotForAdoption()471        }472473    fun setBackgroundSync(enabled: Boolean) {474        backgroundSync.setEnabled(enabled)475        if (enabled) PeachSyncService.start(appContext) else PeachSyncService.stop(appContext)476    }477478    private fun clearPassword() {479        password = null480    }481482    override fun onCleared() {483        adoptionJob?.cancel()484        confirmation?.complete(false)485        clearPassword()486        super.onCleared()487    }488}489490internal fun initialAdoptVaultState(hasVault: Boolean): AdoptVaultUiState =491    if (hasVault) AdoptVaultUiState.Pair else AdoptVaultUiState.Password492493/**494 * Pairing is not a merge tool. A populated destination may re-pair only when495 * both sides already derive the same vault id. Different ids must stop before496 * recovery words, entries, revocations, or paired-device state are changed.497 */498internal fun requireSameVaultForPopulatedRePair(499    localVaultId: String?,500    incomingVaultId: String,501): String {502    if (localVaultId == null) throw IllegalStateException("vault_locked")503    if (localVaultId != incomingVaultId) {504        throw IllegalStateException("JOIN_POPULATED_VAULT_BLOCKED")505    }506    return localVaultId507}