1package com.peachpasswords.ui.pairing23import android.content.Context4import android.util.Log5import androidx.lifecycle.ViewModel6import androidx.lifecycle.viewModelScope7import com.peachpasswords.license.LicenseRepository8import com.peachpasswords.sync.AdoptionPairState9import com.peachpasswords.sync.AdoptionReceiverDeps10import com.peachpasswords.sync.AdoptionReceiverV2Deps11import com.peachpasswords.sync.AdoptionSourceDeps12import com.peachpasswords.sync.AdoptionSourceV2Deps13import com.peachpasswords.sync.BackgroundSyncPreference14import com.peachpasswords.sync.DeviceType15import com.peachpasswords.sync.AdoptionFrame16import com.peachpasswords.sync.LocalDeviceIdentity17import com.peachpasswords.sync.PairedDevice18import com.peachpasswords.sync.PairedDeviceStore19import com.peachpasswords.sync.PendingVouchedDevice20import com.peachpasswords.sync.PendingVouchedDeviceStore21import com.peachpasswords.sync.SignedDeviceManifest22import com.peachpasswords.sync.VaultSyncAdapter23import com.peachpasswords.sync.PeachSyncService24import com.peachpasswords.sync.RelayAdoptionReceiver25import com.peachpasswords.sync.RelaySettingsStore26import com.peachpasswords.sync.RelayDecision27import com.peachpasswords.sync.VaultStatus28import com.peachpasswords.sync.buildLocalIdentity29import com.peachpasswords.sync.computeVaultId30import com.peachpasswords.sync.getDeviceName31import com.peachpasswords.sync.hexToPubkey32import com.peachpasswords.sync.loadOrCreateLocalIdentity33import com.peachpasswords.sync.localSyncKeypair34import com.peachpasswords.sync.rotateDeviceId35import com.peachpasswords.sync.parsePairingInvitation36import com.peachpasswords.ui.security.scorePassword37import com.peachpasswords.vault.AdoptVaultResult38import com.peachpasswords.vault.VaultCrypto39import com.peachpasswords.vault.VaultRepository40import dagger.hilt.android.lifecycle.HiltViewModel41import dagger.hilt.android.qualifiers.ApplicationContext42import java.util.UUID43import javax.inject.Inject44import kotlinx.coroutines.CompletableDeferred45import kotlinx.coroutines.CancellationException46import kotlinx.coroutines.Job47import kotlinx.coroutines.flow.MutableStateFlow48import kotlinx.coroutines.flow.StateFlow49import kotlinx.coroutines.flow.asStateFlow50import kotlinx.coroutines.launch5152sealed interface AdoptVaultUiState {53 data object Password : AdoptVaultUiState54 data object Pair : AdoptVaultUiState55 data object Connecting : AdoptVaultUiState56 5758596061 data class ConfirmSas(62 val sas: String,63 val isSource: Boolean = false,64 val peerName: String? = null,65 ) : AdoptVaultUiState66 data object Adopting : AdoptVaultUiState67 data class Complete(val sourceName: String) : AdoptVaultUiState68 data class Failed(val reason: String) : AdoptVaultUiState69}7071@HiltViewModel72class AdoptVaultViewModel @Inject constructor(73 private val receiver: RelayAdoptionReceiver,74 private val vault: VaultRepository,75 private val devices: PairedDeviceStore,76 private val relaySettings: RelaySettingsStore,77 private val backgroundSync: BackgroundSyncPreference,78 private val license: LicenseRepository,79 private val pendingVouchedStore: PendingVouchedDeviceStore,80 @ApplicationContext private val appContext: Context,81) : ViewModel() {82 8384858687 val joining: Boolean = vault.hasVault()8889 private val _state = MutableStateFlow<AdoptVaultUiState>(90 initialAdoptVaultState(joining),91 )92 val state: StateFlow<AdoptVaultUiState> = _state.asStateFlow()9394 private var password: String? = null95 private var confirmation: CompletableDeferred<Boolean>? = null96 private var adoptionJob: Job? = null97 private var protocolError: String? = null9899 fun acceptPassword(value: String, repeated: String): Boolean {100 if (value.length < 12 || value != repeated || scorePassword(value) < 2) {101 return false102 }103 password = value104 _state.value = AdoptVaultUiState.Pair105 return true106 }107108 fun adopt(invitation: String) {109 if (_state.value !is AdoptVaultUiState.Pair) return110 val parsed = parsePairingInvitation(invitation)111 if (parsed == null) {112 _state.value = AdoptVaultUiState.Failed("invalid_pairing_invitation")113 clearPassword()114 return115 }116 when (parsed.vaultStatus) {117 VaultStatus.POPULATED -> startReceiverFlow(invitation)118 VaultStatus.EMPTY -> startSourceFlow(invitation)119 }120 }121122 private fun startReceiverFlow(invitation: String) {123 _state.value = AdoptVaultUiState.Connecting124 protocolError = null125 adoptionJob = viewModelScope.launch {126 try {127 val adopted = receiver.adopt(128 encodedInvitation = invitation,129 deps = receiverDeps(),130 confirm = { sas ->131 val pending = CompletableDeferred<Boolean>()132 confirmation = pending133 _state.value = AdoptVaultUiState.ConfirmSas(134 sas = sas,135 isSource = false,136 )137 pending.await()138 },139 )140 141 142 143 144 145 adopted.relayUrl?.let(relaySettings::setRelayUrl)146 _state.value = AdoptVaultUiState.Complete(147 adopted.deviceName?.takeIf(String::isNotBlank) ?: "Your other device",148 )149 } catch (error: CancellationException) {150 throw error151 } catch (error: Throwable) {152 _state.value = AdoptVaultUiState.Failed(153 protocolError ?: error.message ?: "adoption_failed",154 )155 } finally {156 confirmation = null157 clearPassword()158 }159 }160 }161162 163164165166167168169 private fun startSourceFlow(invitation: String) {170 val master = vault.syncMasterKey()171 if (master == null) {172 _state.value = AdoptVaultUiState.Failed("vault_locked")173 clearPassword()174 return175 }176 when (val decision = relaySettings.relayInForce()) {177 is RelayDecision.Refuse -> {178 VaultCrypto.zero(master)179 _state.value = AdoptVaultUiState.Failed(decision.reason.wire())180 clearPassword()181 return182 }183 is RelayDecision.Dial -> Unit184 }185 _state.value = AdoptVaultUiState.Connecting186 protocolError = null187188 val credentials = loadOrCreateLocalIdentity(appContext)189 val keys = localSyncKeypair(credentials)190 val identity = buildLocalIdentity(appContext, credentials)191 VaultCrypto.zero(master)192 adoptionJob = viewModelScope.launch {193 try {194 val paired = receiver.grantFromInvitation(195 encodedInvitation = invitation,196 sourceDeps = sourceDeps(identity),197 confirm = { sas, request ->198 val pending = CompletableDeferred<Boolean>()199 confirmation = pending200 _state.value = AdoptVaultUiState.ConfirmSas(201 sas = sas,202 isSource = true,203 peerName = request.deviceName.ifBlank { "New device" },204 )205 pending.await()206 },207 )208 paired.relayUrl?.let(relaySettings::setRelayUrl)209 _state.value = AdoptVaultUiState.Complete(210 paired.deviceName?.takeIf(String::isNotBlank) ?: "Your other device",211 )212 } catch (error: CancellationException) {213 throw error214 } catch (error: Throwable) {215 _state.value = AdoptVaultUiState.Failed(216 protocolError ?: error.message ?: "adoption_failed",217 )218 } finally {219 VaultCrypto.zero(keys.secretKey)220 VaultCrypto.zero(keys.publicKey)221 confirmation = null222 clearPassword()223 }224 }225 }226227 fun confirmSas(matches: Boolean) {228 val pending = confirmation ?: return229 confirmation = null230 if (matches) _state.value = AdoptVaultUiState.Adopting231 pending.complete(matches)232 }233234 fun restart() {235 adoptionJob?.cancel()236 adoptionJob = null237 confirmation?.complete(false)238 confirmation = null239 clearPassword()240 _state.value = initialAdoptVaultState(joining)241 }242243 private fun receiverDeps(): AdoptionReceiverV2Deps =244 object : AdoptionReceiverV2Deps {245 override val deviceName = getDeviceName(appContext)246 override val deviceType = DeviceType.ANDROID247 override fun localIdentity(): LocalDeviceIdentity =248 buildLocalIdentity(appContext, loadOrCreateLocalIdentity(appContext))249 250 251 override val pairState: AdoptionPairState? get() = null252 override suspend fun rotateLocalIdentity(): LocalDeviceIdentity {253 rotateDeviceId(appContext)254 return localIdentity()255 }256 override suspend fun validateSource(prepare: AdoptionFrame.Prepare) {}257 override suspend fun hasSourceIdentityCollision(prepare: AdoptionFrame.Prepare): Boolean =258 devices.isRevoked(prepare.deviceId, prepare.longTermPublicKeyHex)259 override fun generateDeviceId(): String = UUID.randomUUID().toString()260261 262 263 override suspend fun confirmSas(): Boolean = false264265 override suspend fun validateSource(source: AdoptionFrame.Source) {266 267 268 269 270 271 272 if (!joining) return273 }274275 override suspend fun hasSourceIdentityCollision(source: AdoptionFrame.Source): Boolean =276 devices.isRevoked(source.deviceId, source.longTermPublicKeyHex)277278 override suspend fun createVaultFromRootKey(rootKeyHex: String): String {279 280 281 282 val result = if (joining) {283 val incomingRoot = hexToPubkey(rootKeyHex)284 val incomingVaultId = try {285 computeVaultId(incomingRoot)286 } finally {287 VaultCrypto.zero(incomingRoot)288 }289 AdoptVaultResult.Success(290 requireSameVaultForPopulatedRePair(291 localVaultId = vault.syncVaultId(),292 incomingVaultId = incomingVaultId,293 ),294 )295 } else {296 val localPassword = password297 ?: throw IllegalStateException("adoption_password_unavailable")298 vault.createVaultFromRootKey(localPassword, rootKeyHex)299 }300 return when (result) {301 is AdoptVaultResult.Success -> result.vaultId302 is AdoptVaultResult.Error -> throw IllegalStateException(result.reason)303 }304 }305306 override suspend fun deriveLocalIdentity(): LocalDeviceIdentity {307 val master = vault.syncMasterKey()308 ?: throw IllegalStateException("adopted_vault_unavailable")309 return try {310 buildLocalIdentity(appContext, master)311 } finally {312 VaultCrypto.zero(master)313 }314 }315316 override suspend fun clearPairedDeviceRevocation(deviceId: String) {317 devices.clearRevocation(deviceId)318 }319320 override suspend fun upsertPairedDeviceAndClearRevocation(device: PairedDevice) {321 devices.upsertAndClearRevocation(device)322 }323324 override suspend fun upsertPairedDevice(device: PairedDevice) {325 devices.upsert(device)326 }327328 override suspend fun applyLicense(licenseKey: String) {329 if (!license.storeLicense(licenseKey) || !license.isProActive()) {330 throw IllegalStateException("license_transfer_failed")331 }332 }333334 override suspend fun license(): String? =335 license.getLicenseKey()?.takeIf(license::validateLicense)336337 override fun onError(error: String) {338 protocolError = error339 }340341 override suspend fun applySnapshot(entries: Map<String, String>, tombstones: Map<String, Long>, duressSlot: String?) {342 val credentials = loadOrCreateLocalIdentity(appContext)343 val adapter = VaultSyncAdapter(344 repo = vault,345 ourDeviceId = credentials.deviceId,346 pairedDevices = devices,347 localCredentials = credentials,348 )349 adapter.applyEntries(entries)350 adapter.applyTombstones(tombstones)351 if (!duressSlot.isNullOrBlank()) {352 try {353 val ok = vault.installAdoptedDuressSlot(duressSlot)354 if (!ok) Log.w("PeachAdopt", "duress slot install returned false; adoption continues")355 } catch (e: Exception) {356 Log.w("PeachAdopt", "duress slot install failed; adoption continues", e)357 }358 }359 }360361 override suspend fun applyIncomingDeviceManifest(362 manifest: SignedDeviceManifest,363 authenticatedRemoteStaticPublicKey: ByteArray,364 ) {365 366 367 368 369 val credentials = loadOrCreateLocalIdentity(appContext)370 val adapter = VaultSyncAdapter(371 repo = vault,372 ourDeviceId = credentials.deviceId,373 pairedDevices = devices,374 pendingVouched = pendingVouchedStore,375 localCredentials = credentials,376 )377 adapter.applyIncomingDeviceManifest(manifest, authenticatedRemoteStaticPublicKey)378 }379380 override suspend fun markSynced(deviceId: String) {381 devices.updateLastSync(deviceId)382 }383 }384385 private fun sourceDeps(identity: LocalDeviceIdentity): AdoptionSourceV2Deps =386 object : AdoptionSourceV2Deps {387 override val sourceIdentity: LocalDeviceIdentity = identity388389 390 391 override val pairState: AdoptionPairState? get() = null392393 override fun snapshotCapable(): Boolean = true394395 override suspend fun rootKeyHex(): String {396 val root = vault.syncMasterKey()397 ?: throw IllegalStateException("vault_locked")398 return try {399 root.joinToString("") { "%02x".format(it) }400 } finally {401 VaultCrypto.zero(root)402 }403 }404405 override suspend fun vaultId(): String =406 vault.syncVaultId() ?: throw IllegalStateException("vault_locked")407408 override suspend fun license(): String? =409 license.getLicenseKey()?.takeIf(license::validateLicense)410411 override suspend fun applyLicense(licenseKey: String) {412 if (!license.storeLicense(licenseKey) || !license.isProActive()) {413 throw IllegalStateException("license_transfer_failed")414 }415 }416417 override suspend fun onConsent(request: AdoptionFrame.RequestV2): Boolean = true418419 420 421 override suspend fun persistPendingIdentity(device: PairedDevice, nowMs: Long): Boolean {422 val deviceName = device.deviceName ?: return false423 val deviceType = device.deviceType ?: return false424 val longTermKey = device.longTermPublicKeyHex ?: return false425 val signingKey = device.signingPublicKeyHex ?: return false426 return runCatching {427 pendingVouchedStore.upsertAndReport(428 PendingVouchedDevice(429 deviceId = device.deviceId,430 deviceName = deviceName,431 deviceType = deviceType,432 longTermPublicKeyHex = longTermKey,433 signingPublicKeyHex = signingKey,434 wsPort = device.wsPort,435 pairedAt = nowMs,436 receivedAt = nowMs,437 vouchedByDeviceId = identity.deviceId,438 ),439 )440 }.getOrDefault(false)441 }442443 override suspend fun completePendingIdentity(device: PairedDevice): Boolean =444 runCatching { pendingVouchedStore.removeIdentityAndReport(device) }.getOrDefault(false)445 override suspend fun onConsent(request: AdoptionFrame.Request): Boolean = true446 override suspend fun persistPendingHolder(request: AdoptionFrame.Request, nowMs: Long): Boolean {447 return runCatching {448 pendingVouchedStore.upsertAndReport(449 com.peachpasswords.sync.PendingVouchedDevice(450 deviceId = request.sessionRequestId,451 deviceName = request.deviceName,452 deviceType = request.deviceType,453 longTermPublicKeyHex = identity.longTermPublicKeyHex,454 signingPublicKeyHex = identity.signingPublicKeyHex,455 pairedAt = nowMs,456 receivedAt = nowMs,457 vouchedByDeviceId = identity.deviceId,458 ),459 )460 }.getOrDefault(false)461 }462463 override suspend fun completePendingHolder(request: AdoptionFrame.Request, device: PairedDevice): Boolean {464 return runCatching {465 pendingVouchedStore.removeAndReport(request.sessionRequestId)466 }.getOrDefault(false)467 }468469 override fun hasDeviceIdentityCollision(device: PairedDevice): Boolean =470 devices.hasIdentityCollision(device)471472 override suspend fun rotateSourceIdentity(): LocalDeviceIdentity {473 rotateDeviceId(appContext)474 val master = vault.syncMasterKey()475 ?: throw IllegalStateException("vault_locked")476 return try {477 buildLocalIdentity(appContext, master)478 } finally {479 VaultCrypto.zero(master)480 }481 }482483 override suspend fun upsertPairedDevice(device: PairedDevice) {484 485 486 devices.upsertAndClearRevocation(device)487 }488489 override suspend fun vaultSnapshot(): Pair<Map<String, String>, Map<String, Long>>? {490 val credentials = loadOrCreateLocalIdentity(appContext)491 val adapter = VaultSyncAdapter(492 repo = vault,493 ourDeviceId = credentials.deviceId,494 pairedDevices = devices,495 localCredentials = credentials,496 )497 val entryManifest = adapter.buildEntryManifest()498 val entryIds = entryManifest.keys.toList()499 val entries = if (entryIds.isNotEmpty()) adapter.getEncryptedEntries(entryIds) else emptyMap()500 val tombstones = adapter.buildTombstoneManifest()501 return entries to tombstones502 }503 override suspend fun outgoingDeviceManifest(): SignedDeviceManifest? {504 val credentials = loadOrCreateLocalIdentity(appContext)505 val adapter = VaultSyncAdapter(506 repo = vault,507 ourDeviceId = credentials.deviceId,508 pairedDevices = devices,509 localCredentials = credentials,510 )511 return adapter.buildOutgoingDeviceManifest()512 }513514 override suspend fun markSynced(deviceId: String) {515 devices.updateLastSync(deviceId)516 }517518 override suspend fun duressSlotJson(): String? =519 vault.exportDuressSlotForAdoption()520 }521522 fun setBackgroundSync(enabled: Boolean) {523 backgroundSync.setEnabled(enabled)524 if (enabled) PeachSyncService.start(appContext) else PeachSyncService.stop(appContext)525 }526527 private fun clearPassword() {528 password = null529 }530531 override fun onCleared() {532 adoptionJob?.cancel()533 confirmation?.complete(false)534 clearPassword()535 super.onCleared()536 }537}538539internal fun initialAdoptVaultState(hasVault: Boolean): AdoptVaultUiState =540 if (hasVault) AdoptVaultUiState.Pair else AdoptVaultUiState.Password541542543544545546547internal fun requireSameVaultForPopulatedRePair(548 localVaultId: String?,549 incomingVaultId: String,550): String {551 if (localVaultId == null) throw IllegalStateException("vault_locked")552 if (localVaultId != incomingVaultId) {553 throw IllegalStateException("JOIN_POPULATED_VAULT_BLOCKED")554 }555 return localVaultId556}