From 8717aa76228ac83cf12432df61f3a713241c4461 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Fri, 14 Aug 2026 17:26:01 +0200 Subject: [PATCH 01/13] refactor(passkey): introduce central passkey information API this also moves the timing of the passkey creation after the item creation/selection --- .../create/activity/CreatePasskeyActivity.kt | 16 +----- .../create/activity/CreatePasskeyEvent.kt | 1 - .../create/activity/CreatePasskeyViewModel.kt | 57 +++++++++++-------- rust/rust-code/bindings/src/passkey.rs | 26 ++++++--- .../rust-code/lib/src/passkey/registration.rs | 16 ++++-- .../keygo/rust/passkey/PasskeyManager.kt | 17 +++--- 6 files changed, 74 insertions(+), 59 deletions(-) diff --git a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt index bb0f03adf..c872a1b8a 100644 --- a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt +++ b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt @@ -54,9 +54,6 @@ import kotlinx.serialization.Serializable import org.koin.androidx.viewmodel.ext.android.viewModel -@Serializable -private data object AuthenticatedHome - @Serializable private data object ListDest @@ -74,7 +71,8 @@ internal class CreatePasskeyActivity : FragmentActivity() { val callingRequest = request?.callingRequest as? CreatePublicKeyCredentialRequest ?: return cancel("Invalid CreatePublicKeyCredentialRequest") - viewModel.setRequest(callingRequest) + val success = viewModel.setRequest(callingRequest) + if (!success) return cancel("Failed to set request") setResult(RESULT_CANCELED) @@ -91,10 +89,6 @@ internal class CreatePasskeyActivity : FragmentActivity() { ObserveAsEvents(flow = viewModel.event) { when (it) { CreatePasskeyEvent.Abort -> cancel() - CreatePasskeyEvent.ShowList -> authenticatedNavController.navigate(ListDest) { - popUpTo { inclusive = true } - } - is CreatePasskeyEvent.Finish -> finishWithSuccess(it.responseJson) is CreatePasskeyEvent.OpenConfirmationDialog -> { @@ -185,15 +179,11 @@ internal class CreatePasskeyActivity : FragmentActivity() { Scaffold { innerPadding -> NavHost( navController = authenticatedNavController, - startDestination = AuthenticatedHome, + startDestination = ListDest, modifier = Modifier .padding(innerPadding) .consumeWindowInsets(innerPadding), ) { - composable { - // empty placeholder while operation runs - } - composable { PasskeyItemListScreen( onItemClick = viewModel::onItemClicked, diff --git a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyEvent.kt b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyEvent.kt index 06822d96f..60acf3cb4 100644 --- a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyEvent.kt +++ b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyEvent.kt @@ -4,7 +4,6 @@ import de.davis.keygo.core.item.domain.alias.ItemId internal sealed interface CreatePasskeyEvent { data object Abort : CreatePasskeyEvent - data object ShowList : CreatePasskeyEvent data class OpenConfirmationDialog( val itemId: ItemId, val itemName: String, diff --git a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt index f11ffd91d..f1550cbd2 100644 --- a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt +++ b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt @@ -13,19 +13,25 @@ import de.davis.keygo.core.item.domain.repository.PasskeyRepository import de.davis.keygo.core.security.domain.crypto.CryptographicScopeProvider import de.davis.keygo.core.security.domain.crypto.encrypt import de.davis.keygo.core.security.domain.repository.BiometricAvailabilityRepository +import de.davis.keygo.core.util.Result import de.davis.keygo.core.util.fold import de.davis.keygo.core.util.getOrNull +import de.davis.keygo.core.util.mapFailure +import de.davis.keygo.core.util.onFailure import de.davis.keygo.feature.credentials.presentation.auth.SessionAuthState import de.davis.keygo.feature.credentials.presentation.auth.UnlockOutcome import de.davis.keygo.feature.credentials.presentation.auth.mapUnlockError import de.davis.keygo.rust.passkey.PasskeyManager -import de.davis.keygo.rust.passkey.getExcludedCredentialIds +import de.davis.keygo.rust.passkey.getPasskeyInformation import de.davis.keygo.rust.passkey.registerWithResult +import de.davisalessandro.keygo.rust.PasskeyException +import de.davisalessandro.keygo.rust.PasskeyInformation import de.davisalessandro.keygo.rust.RegistrationResponse import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.receiveAsFlow +import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import org.koin.core.annotation.KoinViewModel @@ -47,8 +53,8 @@ internal class CreatePasskeyViewModel( private val biometricChannel = Channel(Channel.BUFFERED) val biometricFlow = biometricChannel.receiveAsFlow() - private var pendingRequest: CreatePublicKeyCredentialRequest? = null - private var registrationResponse: RegistrationResponse? = null + private lateinit var pendingRequest: CreatePublicKeyCredentialRequest + lateinit var passkeyInformation: PasskeyInformation init { viewModelScope.launch { @@ -64,44 +70,42 @@ internal class CreatePasskeyViewModel( } } - fun setRequest(request: CreatePublicKeyCredentialRequest) { + fun setRequest(request: CreatePublicKeyCredentialRequest): Boolean { pendingRequest = request + passkeyInformation = passkeyManager.getPasskeyInformation(request.requestJson) + .getOrNull() + ?: return false + + return true } fun onUnlocked() { if (_authState.value == SessionAuthState.Authenticated) return - _authState.value = SessionAuthState.Authenticated - val req = pendingRequest ?: return - runOperation(req) + _authState.update { SessionAuthState.Authenticated } } fun onUnlockFailed(error: UnlockError) { when (mapUnlockError(error)) { UnlockOutcome.Abort -> viewModelScope.launch { abort("biometric $error") } - UnlockOutcome.NeedsPassword -> _authState.value = SessionAuthState.NeedsPassword + UnlockOutcome.NeedsPassword -> _authState.update { SessionAuthState.NeedsPassword } } } - private fun runOperation(request: CreatePublicKeyCredentialRequest) { - viewModelScope.launch { - val idsToExclude = - passkeyManager.getExcludedCredentialIds(request.requestJson).getOrNull() - ?.toSet() - ?: return@launch abort("Failed to get excluded IDs") - - val shouldAbort = passkeyRepository.doCredentialIdsExist(idsToExclude) - if (shouldAbort) return@launch abort("Credential ID already exists") - - registrationResponse = passkeyManager.registerWithResult(request.requestJson) - .getOrNull() ?: return@launch abort("Failed to register passkey") + private suspend fun registerPasskey(request: CreatePublicKeyCredentialRequest): Result { + val shouldAbort = passkeyRepository.doCredentialIdsExist(passkeyInformation.excludeCredentials.toSet()) + if (shouldAbort) return Result.Failure(PasskeyCreationError.Excluded) - _event.send(CreatePasskeyEvent.ShowList) - } + return passkeyManager.registerWithResult(request.requestJson) + .mapFailure(PasskeyCreationError::RegistrationFailed) } fun associatePasskeyAndFinish(itemId: ItemId) { viewModelScope.launch { - val response = registrationResponse ?: return@launch abort("Response was null") + val response = registerPasskey(pendingRequest) + .onFailure { + Log.d(TAG, "Failed to register passkey: $it") + }.getOrNull() + ?: return@launch abort("Failed to register passkey") val encryptedPrivateKey = cryptographicScopeProvider.itemScope(itemId = itemId) { Passkey.PrivateKey.encrypt(response.privateKey) @@ -131,7 +135,7 @@ internal class CreatePasskeyViewModel( CreatePasskeyEvent.OpenConfirmationDialog( itemId = itemId, itemName = "N/A", - rp = registrationResponse?.rp ?: "N/A" + rp = passkeyInformation.rp ) ) } @@ -145,3 +149,8 @@ internal class CreatePasskeyViewModel( private const val TAG = "CreatePasskeyViewModel" } } + +internal sealed interface PasskeyCreationError { + data class RegistrationFailed(val exception: PasskeyException) : PasskeyCreationError + data object Excluded : PasskeyCreationError +} diff --git a/rust/rust-code/bindings/src/passkey.rs b/rust/rust-code/bindings/src/passkey.rs index 886ab2bfb..c8bf77427 100644 --- a/rust/rust-code/bindings/src/passkey.rs +++ b/rust/rust-code/bindings/src/passkey.rs @@ -1,7 +1,5 @@ use lib::passkey::provider::{ProviderError, provide_passkey}; -use lib::passkey::registration::{ - KeyGoRegistrationResponse, RegistrationError, get_exclusion_list, register_passkey, -}; +use lib::passkey::registration::{KeyGoRegistrationResponse, PasskeyInformation as CorePasskeyInformation, RegistrationError, get_passkey_information, register_passkey}; use std::sync::Arc; #[derive(Debug, thiserror::Error, uniffi::Error)] @@ -69,6 +67,21 @@ impl From for RegistrationResponse { } } +#[derive(uniffi::Record)] +pub struct PasskeyInformation { + pub exclude_credentials: Vec>, + pub rp: String, +} + +impl From for PasskeyInformation { + fn from(value: CorePasskeyInformation) -> Self { + Self { + exclude_credentials: value.exclude_credentials, + rp: value.rp, + } + } +} + #[derive(uniffi::Object)] pub struct RustPasskey; @@ -89,11 +102,8 @@ impl RustPasskey { .map_err(Into::into) } - pub async fn excluded_credentials( - &self, - json_request: String, - ) -> Result>, PasskeyError> { - get_exclusion_list(&json_request).await.map_err(Into::into) + pub fn passkey_information(&self, json_request: String) -> Result { + get_passkey_information(&json_request).map(Into::into).map_err(Into::into) } pub async fn authenticate( diff --git a/rust/rust-code/lib/src/passkey/registration.rs b/rust/rust-code/lib/src/passkey/registration.rs index 56aa11334..46f54f9b7 100644 --- a/rust/rust-code/lib/src/passkey/registration.rs +++ b/rust/rust-code/lib/src/passkey/registration.rs @@ -29,14 +29,22 @@ pub enum RegistrationError { KeyEncodeError(PasskeyCodecError), } -pub async fn get_exclusion_list(json_request: &str) -> Result>, RegistrationError> { +pub struct PasskeyInformation { + pub exclude_credentials: Vec>, + pub rp: String, +} + +pub fn get_passkey_information(json_request: &str) -> Result { let creation_options: PublicKeyCredentialCreationOptions = serde_json::from_str(json_request).map_err(|_| InvalidJsonFormat)?; - let list = creation_options.exclude_credentials.unwrap_or_default(); - let ids = list.iter().map(|desc| desc.id.clone().into()).collect(); + let exclude_credentials: Vec> = creation_options.exclude_credentials.unwrap_or_default() + .into_iter().map(|desc| desc.id.into()).collect(); + let rp = creation_options.rp.id.unwrap_or_default(); - Ok(ids) + Ok( + PasskeyInformation { exclude_credentials, rp } + ) } pub async fn register_passkey( diff --git a/rust/src/main/kotlin/de/davis/keygo/rust/passkey/PasskeyManager.kt b/rust/src/main/kotlin/de/davis/keygo/rust/passkey/PasskeyManager.kt index a5443c930..d8fe0e0df 100644 --- a/rust/src/main/kotlin/de/davis/keygo/rust/passkey/PasskeyManager.kt +++ b/rust/src/main/kotlin/de/davis/keygo/rust/passkey/PasskeyManager.kt @@ -2,6 +2,7 @@ package de.davis.keygo.rust.passkey import de.davis.keygo.core.util.Result import de.davisalessandro.keygo.rust.PasskeyException +import de.davisalessandro.keygo.rust.PasskeyInformation import de.davisalessandro.keygo.rust.RegistrationResponse import de.davisalessandro.keygo.rust.RustPasskeyInterface import kotlinx.coroutines.Dispatchers @@ -31,15 +32,13 @@ suspend fun RustPasskeyInterface.registerWithResult( ) } -suspend fun RustPasskeyInterface.getExcludedCredentialIds( +fun RustPasskeyInterface.getPasskeyInformation( requestJson: String -): Result, PasskeyException> = withContext(Dispatchers.Default) { - runCatching { - excludedCredentials(requestJson) - }.fold( - onSuccess = { Result.Success(it) }, - onFailure = { Result.Failure(it as PasskeyException) } - ) -} +): Result = runCatching { + passkeyInformation(requestJson) +}.fold( + onSuccess = { Result.Success(it) }, + onFailure = { Result.Failure(it as PasskeyException) } +) typealias PasskeyManager = RustPasskeyInterface \ No newline at end of file From 9eedb0a839d0475bd3331906c6021b7d6d4d2c50 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Fri, 14 Aug 2026 17:35:53 +0200 Subject: [PATCH 02/13] refactor(passkey): migrate to real passkey state list --- .../create/activity/CreatePasskeyActivity.kt | 2 +- .../feature/item/core/domain/model/UpsertLogin.kt | 3 --- .../domain/usecase/CreateNewOrUpdateLoginUseCase.kt | 3 +-- .../item/create/presentation/login/LoginScreen.kt | 6 +++--- .../create/presentation/login/LoginViewModel.kt | 13 +++++++++---- .../create/presentation/login/model/LoginUiState.kt | 11 +++++++---- 6 files changed, 21 insertions(+), 17 deletions(-) diff --git a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt index c872a1b8a..c83b521bc 100644 --- a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt +++ b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt @@ -195,7 +195,7 @@ internal class CreatePasskeyActivity : FragmentActivity() { composable { LoginScreen( - pendingPasskeyCount = 1, + pendingPasskeyRP = viewModel.passkeyInformation.rp, loginCreated = { viewModel.associatePasskeyAndFinish(it) }, diff --git a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/model/UpsertLogin.kt b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/model/UpsertLogin.kt index 328b76ccb..c64ba2509 100644 --- a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/model/UpsertLogin.kt +++ b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/model/UpsertLogin.kt @@ -15,7 +15,6 @@ data class UpsertLogin private constructor( val domains: FieldUpdate>, override val tags: FieldUpdate>, override val note: FieldUpdate, - val hasPendingPasskey: Boolean = false, ) : UpsertItem { companion object { fun create( @@ -27,7 +26,6 @@ data class UpsertLogin private constructor( domains: Set = emptySet(), tags: Set = emptySet(), note: String? = null, - hasPendingPasskey: Boolean = false, ) = UpsertLogin( upsertType = UpsertType.Create(vaultId), name = FieldUpdate.Set(name), @@ -37,7 +35,6 @@ data class UpsertLogin private constructor( username = if (!username.isNullOrBlank()) FieldUpdate.Set(username) else FieldUpdate.Clear, domains = if (domains.isNotEmpty()) FieldUpdate.Set(domains) else FieldUpdate.Clear, tags = if (tags.isNotEmpty()) FieldUpdate.Set(tags) else FieldUpdate.Clear, - hasPendingPasskey = hasPendingPasskey, ) fun update( diff --git a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCase.kt b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCase.kt index f26ceb94a..99660c1e9 100644 --- a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCase.kt +++ b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCase.kt @@ -63,8 +63,7 @@ class CreateNewOrUpdateLoginUseCase( override suspend fun fetchExisting(id: ItemId): Login? = loginRepository.getLoginById(id) - override fun isEmpty(item: Login, upsert: UpsertLogin): Boolean = - !item.hasAnyContent && !upsert.hasPendingPasskey + override fun isEmpty(item: Login, upsert: UpsertLogin): Boolean = !item.hasAnyContent override fun relocate(item: Login, vaultId: VaultId, keyInformation: KeyInformation): Login = item.copy(vaultId = vaultId, keyInformation = keyInformation) diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginScreen.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginScreen.kt index f73d23567..e894c1966 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginScreen.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginScreen.kt @@ -15,7 +15,7 @@ fun LoginScreen( detailPaneInformation: DetailPaneInformation = DetailPaneInformation.Init.New( itemType = VaultItemType.Login, ), - pendingPasskeyCount: Int = 0, + pendingPasskeyRP: String? = null, loginCreated: (ItemId) -> Unit, navigateBack: () -> Unit, ) { @@ -26,8 +26,8 @@ fun LoginScreen( viewmodel.init(detailPaneInformation) } - LaunchedEffect(pendingPasskeyCount) { - viewmodel.setPendingPasskeyCount(pendingPasskeyCount) + LaunchedEffect(pendingPasskeyRP) { + viewmodel.setPendingPasskeyCount(pendingPasskeyRP) } ObserveAsEvents(viewmodel.itemCreatedEvent) { diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt index 3668199e2..e9ddbf2fd 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt @@ -113,8 +113,9 @@ internal class LoginViewModel( .launchIn(viewModelScope) } - fun setPendingPasskeyCount(count: Int) { - _base.update { it.copy(pendingPasskeyCount = count) } + fun setPendingPasskeyCount(rp: String?) { + if (rp == null) return + _base.update { it.copy(passkeyRPs = it.passkeyRPs + setOf(LoginPasskeyInfo(rp, true))) } } fun init(information: DetailPaneInformation) { @@ -192,7 +193,12 @@ internal class LoginViewModel( totpTextFieldState = TextFieldState(decrypted.second ?: ""), usernameTextFieldState = TextFieldState(login.username ?: ""), domains = login.domainInfos, - existingPasskeyCount = login.passkeyRPs.size, + passkeyRPs = login.passkeyRPs.mapTo(mutableSetOf()) { rp -> + LoginPasskeyInfo( + rpId = rp, + pending = false, + ) + }, dialogState = DialogState.None, updating = true, ) @@ -259,7 +265,6 @@ internal class LoginViewModel( password = base.passwordTextFieldState.text.toString(), totpUriOrSecret = base.totpTextFieldState.text.toString(), note = notesTextFieldState.text.toString(), - hasPendingPasskey = base.pendingPasskeyCount > 0, ) createNewOrUpdateLogin( diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiState.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiState.kt index 8c9bb4f4f..73ffd8ebf 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiState.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiState.kt @@ -9,18 +9,22 @@ import de.davis.keygo.feature.item.create.presentation.model.ItemUiState internal typealias LoginUiState = ItemUiState +internal data class LoginPasskeyInfo( + val rpId: String, + val pending: Boolean, +) + @Stable internal data class LoginBaseState( val passwordTextFieldState: TextFieldState = TextFieldState(), val totpTextFieldState: TextFieldState = TextFieldState(), val usernameTextFieldState: TextFieldState = TextFieldState(), val domains: Set = emptySet(), + val passkeyRPs: Set = emptySet(), val strengthScore: PasswordScore = PasswordScore.None, val generatePasswordBottomSheetVisible: Boolean = false, val dialogState: DialogState = DialogState.None, val nameError: InputFieldError? = null, - val existingPasskeyCount: Int = 0, - val pendingPasskeyCount: Int = 0, val scanning: Boolean = false, val updating: Boolean = false, ) { @@ -28,8 +32,7 @@ internal data class LoginBaseState( get() = passwordTextFieldState.text.isNotBlank() || totpTextFieldState.text.isNotBlank() || usernameTextFieldState.text.isNotBlank() - || existingPasskeyCount > 0 - || pendingPasskeyCount > 0 + || passkeyRPs.isNotEmpty() fun canSave(name: CharSequence): Boolean = name.isNotBlank() && hasAnyContent } From a9e3bb22da81ab00c0050bc1054753b57fcfc848 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sat, 15 Aug 2026 13:09:06 +0200 Subject: [PATCH 03/13] refactor(feat-item): move MenuChip to feature/item/core --- .../presentation/component/ChipFormGroup.kt | 79 --------------- .../core/presentation/component/MenuChip.kt | 96 +++++++++++++++++++ 2 files changed, 96 insertions(+), 79 deletions(-) create mode 100644 feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/presentation/component/MenuChip.kt diff --git a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/presentation/component/ChipFormGroup.kt b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/presentation/component/ChipFormGroup.kt index a4ef53afc..785918f20 100644 --- a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/presentation/component/ChipFormGroup.kt +++ b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/presentation/component/ChipFormGroup.kt @@ -9,12 +9,8 @@ import androidx.compose.animation.togetherWith import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.interaction.collectIsFocusedAsState import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.foundation.layout.size -import androidx.compose.foundation.layout.widthIn -import androidx.compose.foundation.layout.wrapContentSize import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.text.input.InputTransformation import androidx.compose.foundation.text.input.KeyboardActionHandler @@ -24,17 +20,7 @@ import androidx.compose.foundation.text.input.delete import androidx.compose.foundation.text.input.rememberTextFieldState import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd import androidx.compose.foundation.text.input.then -import androidx.compose.material.icons.Icons -import androidx.compose.material.icons.filled.Delete -import androidx.compose.material.icons.filled.Edit -import androidx.compose.material3.DropdownMenuGroup -import androidx.compose.material3.DropdownMenuItem -import androidx.compose.material3.DropdownMenuPopup -import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi -import androidx.compose.material3.Icon -import androidx.compose.material3.InputChip import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.MenuDefaults import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.material3.TextFieldLabelScope @@ -51,18 +37,15 @@ import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.runtime.snapshotFlow -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onPreviewKeyEvent import androidx.compose.ui.input.key.type -import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.input.ImeAction import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp -import de.davis.keygo.feature.item.core.R import kotlinx.coroutines.flow.collectLatest @Stable @@ -275,68 +258,6 @@ fun ChipFormGroup( } } -@OptIn(ExperimentalMaterial3ExpressiveApi::class) -@Composable -private fun MenuChip( - chipText: String, - onDeleteClick: () -> Unit, - onModifyClick: () -> Unit -) { - var expanded by rememberSaveable { mutableStateOf(false) } - - Box( - modifier = Modifier.wrapContentSize(Alignment.TopStart) - ) { - InputChip( - selected = false, - onClick = { expanded = !expanded }, - label = { Text(text = chipText) } - ) - - DropdownMenuPopup( - expanded = expanded, - onDismissRequest = { expanded = false }, - modifier = Modifier.widthIn(min = 175.dp) - ) { - DropdownMenuGroup( - shapes = MenuDefaults.groupShape(0, 1), - containerColor = MaterialTheme.colorScheme.surfaceContainerHigh, - ) { - DropdownMenuItem( - onClick = { - expanded = false - onModifyClick() - }, - text = { Text(text = stringResource(R.string.edit)) }, - leadingIcon = { - Icon( - imageVector = Icons.Default.Edit, - modifier = Modifier.size(MenuDefaults.LeadingIconSize), - contentDescription = null - ) - }, - shape = MenuDefaults.itemShape(0, 2).shape, - ) - DropdownMenuItem( - onClick = { - expanded = false - onDeleteClick() - }, - text = { Text(text = stringResource(R.string.delete)) }, - leadingIcon = { - Icon( - imageVector = Icons.Default.Delete, - modifier = Modifier.size(MenuDefaults.LeadingIconSize), - contentDescription = null - ) - }, - shape = MenuDefaults.itemShape(1, 2).shape, - ) - } - } - } -} - private fun CharSequence.splitChipInput(delimiters: Set): List = split(delimiters = delimiters.toCharArray()) .mapNotNull { it.trim().takeIf(String::isNotBlank) } diff --git a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/presentation/component/MenuChip.kt b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/presentation/component/MenuChip.kt new file mode 100644 index 000000000..36fb61fd0 --- /dev/null +++ b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/presentation/component/MenuChip.kt @@ -0,0 +1,96 @@ +package de.davis.keygo.feature.item.core.presentation.component + +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.layout.wrapContentSize +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Delete +import androidx.compose.material.icons.filled.Edit +import androidx.compose.material3.DropdownMenuGroup +import androidx.compose.material3.DropdownMenuItem +import androidx.compose.material3.DropdownMenuPopup +import androidx.compose.material3.ExperimentalMaterial3ExpressiveApi +import androidx.compose.material3.Icon +import androidx.compose.material3.InputChip +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.MenuDefaults +import androidx.compose.material3.Text +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.unit.dp +import de.davis.keygo.feature.item.core.R + +@OptIn(ExperimentalMaterial3ExpressiveApi::class) +@Composable +fun MenuChip( + chipText: String, + onDeleteClick: () -> Unit, + modifier: Modifier = Modifier, + enabled: Boolean = true, + onModifyClick: (() -> Unit)? = null, +) { + var expanded by rememberSaveable { mutableStateOf(false) } + val itemCount = if (onModifyClick != null) 2 else 1 + + Box( + modifier = modifier.wrapContentSize(Alignment.TopStart) + ) { + InputChip( + selected = false, + onClick = { expanded = !expanded }, + label = { Text(text = chipText) }, + enabled = enabled + ) + + DropdownMenuPopup( + expanded = expanded, + onDismissRequest = { expanded = false }, + modifier = Modifier.widthIn(min = 175.dp) + ) { + DropdownMenuGroup( + shapes = MenuDefaults.groupShape(0, 1), + containerColor = MaterialTheme.colorScheme.surfaceContainerHigh, + ) { + onModifyClick?.let { onModify -> + DropdownMenuItem( + onClick = { + expanded = false + onModify() + }, + text = { Text(text = stringResource(R.string.edit)) }, + leadingIcon = { + Icon( + imageVector = Icons.Default.Edit, + modifier = Modifier.size(MenuDefaults.LeadingIconSize), + contentDescription = null + ) + }, + shape = MenuDefaults.itemShape(0, itemCount).shape, + ) + } + DropdownMenuItem( + onClick = { + expanded = false + onDeleteClick() + }, + text = { Text(text = stringResource(R.string.delete)) }, + leadingIcon = { + Icon( + imageVector = Icons.Default.Delete, + modifier = Modifier.size(MenuDefaults.LeadingIconSize), + contentDescription = null + ) + }, + shape = MenuDefaults.itemShape(itemCount - 1, itemCount).shape, + ) + } + } + } +} From 32c7c441795b7b80354713f151038eabc0a45e5d Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sat, 15 Aug 2026 13:13:02 +0200 Subject: [PATCH 04/13] refactor(core-item): remove default for passkey --- .../de/davis/keygo/core/item/domain/model/Login.kt | 2 +- .../keygo/core/item/data/mapper/DomainMapperTest.kt | 1 + .../keygo/core/item/data/mapper/ItemMapperTest.kt | 1 + .../keygo/core/item/data/mapper/LoginMapperTest.kt | 1 + .../item/data/repository/LoginRepositoryImplTest.kt | 2 ++ .../domain/usecase/ObserveAllTagsSortedUseCaseTest.kt | 1 + .../core/item/domain/usecase/UpsertItemUseCaseTest.kt | 1 + .../usecase/AddRegistrableDomainsToLoginUseCaseTest.kt | 1 + .../usecase/DoesItemHaveDomainReferencesUseCaseTest.kt | 1 + .../presentation/activity/AutofillViewModelTest.kt | 1 + .../presentation/dataset/SuggestionFinderTest.kt | 7 +++++++ .../domain/usecase/CreateNewOrUpdateLoginUseCase.kt | 10 +++++++++- .../usecase/CreateNewOrUpdateLoginUseCaseTest.kt | 2 ++ .../domain/usecase/MoveItemsToVaultUseCaseTest.kt | 1 + .../legacy_data/domain/mapper/LegacyItemConverter.kt | 2 ++ 15 files changed, 32 insertions(+), 2 deletions(-) diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/model/Login.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/model/Login.kt index 0d1f63eec..7394b022e 100644 --- a/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/model/Login.kt +++ b/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/model/Login.kt @@ -13,7 +13,7 @@ data class Login( val domainInfos: Set, val passwordCredential: PasswordCredential?, val totp: Totp?, - val passkeyRPs: Set = emptySet(), + val passkeyRPs: Set, override val vaultId: VaultId, override val name: String, override val keyInformation: KeyInformation, diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/DomainMapperTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/DomainMapperTest.kt index 69102d4cf..4b352f5bd 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/DomainMapperTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/DomainMapperTest.kt @@ -30,6 +30,7 @@ class DomainMapperTest { score = PasswordScore.Strong, ), totp = null, + passkeyRPs = emptySet(), vaultId = newVaultId(), name = "Test", keyInformation = KeyInformation(wrappedKey = byteArrayOf(), keyNonce = byteArrayOf()), diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/ItemMapperTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/ItemMapperTest.kt index 3e495ed65..112a9dbe4 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/ItemMapperTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/ItemMapperTest.kt @@ -37,6 +37,7 @@ class ItemMapperTest { score = PasswordScore.Strong, ), totp = null, + passkeyRPs = emptySet(), note = note, pinned = pinned, vaultId = newVaultId(), diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/LoginMapperTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/LoginMapperTest.kt index c088dacb0..c5320b08d 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/LoginMapperTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/LoginMapperTest.kt @@ -123,6 +123,7 @@ class LoginMapperTest { domainInfos = emptySet(), passwordCredential = passwordCredential, totp = null, + passkeyRPs = emptySet(), vaultId = newVaultId(), name = "Test", keyInformation = KeyInformation(byteArrayOf(), byteArrayOf()), diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImplTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImplTest.kt index b9b6123f9..9c7f9d436 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImplTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImplTest.kt @@ -214,6 +214,7 @@ class LoginRepositoryImplTest { score = PasswordScore.Strong, ), tags: Set = emptySet(), + passkeyRPs: Set = emptySet(), totpProvider: ((ItemId) -> Totp)? = null, ): Login { val id = newItemId() @@ -223,6 +224,7 @@ class LoginRepositoryImplTest { domainInfos = emptySet(), passwordCredential = passwordCredential, totp = totpProvider?.invoke(id), + passkeyRPs = passkeyRPs, name = "Test", note = null, pinned = false, diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/ObserveAllTagsSortedUseCaseTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/ObserveAllTagsSortedUseCaseTest.kt index 7dad88e28..36f8d9148 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/ObserveAllTagsSortedUseCaseTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/ObserveAllTagsSortedUseCaseTest.kt @@ -29,6 +29,7 @@ class ObserveAllTagsSortedUseCaseTest { domainInfos = emptySet(), passwordCredential = null, totp = null, + passkeyRPs = emptySet(), vaultId = newVaultId(), name = name, keyInformation = KeyInformation(byteArrayOf(), byteArrayOf()), diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/UpsertItemUseCaseTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/UpsertItemUseCaseTest.kt index eb303355a..92f5d0050 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/UpsertItemUseCaseTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/UpsertItemUseCaseTest.kt @@ -36,6 +36,7 @@ class UpsertItemUseCaseTest { score = PasswordScore.Strong, ), totp = null, + passkeyRPs = emptySet(), name = name, note = null, pinned = false, diff --git a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/AddRegistrableDomainsToLoginUseCaseTest.kt b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/AddRegistrableDomainsToLoginUseCaseTest.kt index df94c45c6..3270a5591 100644 --- a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/AddRegistrableDomainsToLoginUseCaseTest.kt +++ b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/AddRegistrableDomainsToLoginUseCaseTest.kt @@ -39,6 +39,7 @@ class AddRegistrableDomainsToLoginUseCaseTest { domainInfos = domainInfos, passwordCredential = null, totp = null, + passkeyRPs = emptySet(), note = null, pinned = false, vaultId = vaultId, diff --git a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/DoesItemHaveDomainReferencesUseCaseTest.kt b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/DoesItemHaveDomainReferencesUseCaseTest.kt index 3b5ede7cd..a7cfb9d8e 100644 --- a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/DoesItemHaveDomainReferencesUseCaseTest.kt +++ b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/DoesItemHaveDomainReferencesUseCaseTest.kt @@ -40,6 +40,7 @@ class DoesItemHaveDomainReferencesUseCaseTest { domainInfos = domainInfos, passwordCredential = null, totp = null, + passkeyRPs = emptySet(), note = null, pinned = false, vaultId = vaultId, diff --git a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/activity/AutofillViewModelTest.kt b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/activity/AutofillViewModelTest.kt index cbf700ff0..e6b2eb4da 100644 --- a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/activity/AutofillViewModelTest.kt +++ b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/activity/AutofillViewModelTest.kt @@ -143,6 +143,7 @@ internal class AutofillViewModelTest { domainInfos = domainInfos, passwordCredential = null, totp = null, + passkeyRPs = emptySet(), vaultId = newVaultId(), name = name, keyInformation = KeyInformation(byteArrayOf(), byteArrayOf()), diff --git a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/dataset/SuggestionFinderTest.kt b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/dataset/SuggestionFinderTest.kt index b15a21b7e..429fcab72 100644 --- a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/dataset/SuggestionFinderTest.kt +++ b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/dataset/SuggestionFinderTest.kt @@ -54,6 +54,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://example.com", eTLD1 = "example.com")), passwordCredential = null, totp = null, + passkeyRPs = emptySet(), vaultId = vaultId, name = "UserOnly", keyInformation = keyInfo, @@ -67,6 +68,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://example.com", eTLD1 = "example.com")), passwordCredential = minimalPassword, totp = null, + passkeyRPs = emptySet(), vaultId = vaultId, name = "PassOnly", keyInformation = keyInfo, @@ -80,6 +82,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://example.com", eTLD1 = "example.com")), passwordCredential = minimalPassword, totp = null, + passkeyRPs = emptySet(), vaultId = vaultId, name = "Both", keyInformation = keyInfo, @@ -93,6 +96,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://other.com", eTLD1 = "other.com")), passwordCredential = null, totp = minimalTotp, + passkeyRPs = emptySet(), vaultId = vaultId, name = "Neither", keyInformation = keyInfo, @@ -196,6 +200,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://example.com", eTLD1 = "example.com")), passwordCredential = null, totp = null, + passkeyRPs = emptySet(), vaultId = vaultId, name = "Extra1", keyInformation = keyInfo, @@ -209,6 +214,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://example.com", eTLD1 = "example.com")), passwordCredential = null, totp = null, + passkeyRPs = emptySet(), vaultId = vaultId, name = "Extra2", keyInformation = keyInfo, @@ -222,6 +228,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://example.com", eTLD1 = "example.com")), passwordCredential = null, totp = null, + passkeyRPs = emptySet(), vaultId = vaultId, name = "Extra3", keyInformation = keyInfo, diff --git a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCase.kt b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCase.kt index 99660c1e9..59b4403fb 100644 --- a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCase.kt +++ b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCase.kt @@ -63,7 +63,10 @@ class CreateNewOrUpdateLoginUseCase( override suspend fun fetchExisting(id: ItemId): Login? = loginRepository.getLoginById(id) - override fun isEmpty(item: Login, upsert: UpsertLogin): Boolean = !item.hasAnyContent + // buildCreate/buildUpdate already resolve the login's effective passkeys, so this only has to + // account for the one that is not on the item yet. + override fun isEmpty(item: Login, upsert: UpsertLogin): Boolean = + !upsert.pendingPasskey && !item.hasAnyContent override fun relocate(item: Login, vaultId: VaultId, keyInformation: KeyInformation): Login = item.copy(vaultId = vaultId, keyInformation = keyInformation) @@ -98,6 +101,8 @@ class CreateNewOrUpdateLoginUseCase( tags = upsert.tags.getValue().orEmpty(), passwordCredential = newPasswordCredential, totp = totp?.await(), + // A pending passkey is written by its own flow once this id exists. + passkeyRPs = emptySet(), note = upsert.note.getValue(), pinned = false, keyInformation = keyInformation, @@ -130,6 +135,9 @@ class CreateNewOrUpdateLoginUseCase( tags = upsert.tags.on(existing.tags).orEmpty(), passwordCredential = newPasswordCredential, totp = upsert.totpUriOrSecret.on(existing.totp, totp), + // Resolved against what the table holds now, not against what the caller last saw, so + // a passkey attached from elsewhere since then survives this save. + passkeyRPs = existing.passkeyRPs - upsert.removedPasskeyRPs, note = upsert.note.on(existing.note), ) } diff --git a/feature/item/core/src/test/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCaseTest.kt b/feature/item/core/src/test/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCaseTest.kt index 133dc9221..b0ad0092e 100644 --- a/feature/item/core/src/test/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCaseTest.kt +++ b/feature/item/core/src/test/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCaseTest.kt @@ -808,6 +808,7 @@ class CreateNewOrUpdateLoginUseCaseTest { ), totp: Totp? = null, timestamp: Timestamp = Timestamp(), + passkeyRPs: Set = emptySet(), ) = Login( id = newItemId(), name = name, @@ -815,6 +816,7 @@ class CreateNewOrUpdateLoginUseCaseTest { domainInfos = emptySet(), passwordCredential = passwordCredential, totp = totp, + passkeyRPs = passkeyRPs, note = null, pinned = false, vaultId = defaultVault.id, diff --git a/feature/vault/src/test/kotlin/de/davis/keygo/feature/vault/domain/usecase/MoveItemsToVaultUseCaseTest.kt b/feature/vault/src/test/kotlin/de/davis/keygo/feature/vault/domain/usecase/MoveItemsToVaultUseCaseTest.kt index 756aa955b..c561cee90 100644 --- a/feature/vault/src/test/kotlin/de/davis/keygo/feature/vault/domain/usecase/MoveItemsToVaultUseCaseTest.kt +++ b/feature/vault/src/test/kotlin/de/davis/keygo/feature/vault/domain/usecase/MoveItemsToVaultUseCaseTest.kt @@ -367,6 +367,7 @@ class MoveItemsToVaultUseCaseTest { totp = totpPlaintext?.let { Totp(loginId = id, secret = Totp.Secret.encrypt(it)) }, + passkeyRPs = emptySet(), note = note, pinned = pinned, vaultId = vault.id, diff --git a/migration/legacy-data/src/main/kotlin/de/davis/keygo/migration/legacy_data/domain/mapper/LegacyItemConverter.kt b/migration/legacy-data/src/main/kotlin/de/davis/keygo/migration/legacy_data/domain/mapper/LegacyItemConverter.kt index 2dc65cea9..9ac5fa5ef 100644 --- a/migration/legacy-data/src/main/kotlin/de/davis/keygo/migration/legacy_data/domain/mapper/LegacyItemConverter.kt +++ b/migration/legacy-data/src/main/kotlin/de/davis/keygo/migration/legacy_data/domain/mapper/LegacyItemConverter.kt @@ -87,6 +87,8 @@ internal class LegacyItemConverter( .orEmpty(), passwordCredential = credential, totp = null, + // The legacy database had no passkeys, and these are freshly minted ids. + passkeyRPs = emptySet(), vaultId = vaultId, name = item.title, keyInformation = keyInformation, From a69104a168e3301b7fb3050ffc011c86a77744f8 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sat, 15 Aug 2026 13:17:50 +0200 Subject: [PATCH 05/13] refactor(login): implement passkey deletion UI logic --- .../component/DeletePasskeyDialog.kt | 70 +++++++++++++++++++ .../create/presentation/login/LoginContent.kt | 47 +++++++++++++ .../presentation/login/LoginViewModel.kt | 9 +++ .../presentation/login/model/DialogState.kt | 2 + .../presentation/login/model/LoginUiEvent.kt | 4 ++ .../create/src/main/res/values/strings.xml | 5 ++ 6 files changed, 137 insertions(+) create mode 100644 feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/component/DeletePasskeyDialog.kt diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/component/DeletePasskeyDialog.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/component/DeletePasskeyDialog.kt new file mode 100644 index 000000000..46ee501be --- /dev/null +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/component/DeletePasskeyDialog.kt @@ -0,0 +1,70 @@ +package de.davis.keygo.feature.item.create.presentation.component + +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.DeleteForever +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Icon +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.fromHtml +import androidx.compose.ui.tooling.preview.Preview +import de.davis.keygo.core.ui.theme.KeyGoTheme +import de.davis.keygo.feature.item.create.R +import de.davis.keygo.feature.item.create.presentation.login.model.DialogState +import de.davis.keygo.feature.item.core.R as ItemCoreR + +@Composable +fun DeletePasskeyDialog( + state: DialogState.DeletePasskey, + onConfirmDeletion: () -> Unit, + onDismissRequest: () -> Unit, + modifier: Modifier = Modifier, +) { + AlertDialog( + onDismissRequest = onDismissRequest, + title = { + Text(text = stringResource(R.string.delete_passkey)) + }, + confirmButton = { + Button(onClick = onDismissRequest) { + Text(text = stringResource(R.string.cancel)) + } + }, + icon = { + Icon( + imageVector = Icons.Default.DeleteForever, + contentDescription = null, + ) + }, + modifier = modifier, + dismissButton = { + TextButton(onClick = onConfirmDeletion) { + Text(text = stringResource(ItemCoreR.string.delete)) + } + }, + text = { + Text( + text = AnnotatedString.fromHtml( + stringResource(R.string.delete_passkey_warning, state.rpId) + ) + ) + }, + ) +} + +@Preview +@Composable +private fun DeletePasskeyDialogPreview() { + KeyGoTheme { + DeletePasskeyDialog( + state = DialogState.DeletePasskey(rpId = "example.com"), + onConfirmDeletion = {}, + onDismissRequest = {}, + ) + } +} diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginContent.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginContent.kt index 8053700b5..5be3cf855 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginContent.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginContent.kt @@ -3,6 +3,7 @@ package de.davis.keygo.feature.item.create.presentation.login import android.content.res.Configuration import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.FlowRow import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth @@ -24,6 +25,7 @@ import androidx.compose.material3.Text import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue +import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue @@ -47,9 +49,11 @@ import de.davis.keygo.core.ui.theme.KeyGoTheme import de.davis.keygo.feature.item.core.presentation.component.ChipFormGroup import de.davis.keygo.feature.item.core.presentation.component.CreateOrModifyItemTopAppBar import de.davis.keygo.feature.item.core.presentation.component.KeyGoFormField +import de.davis.keygo.feature.item.core.presentation.component.MenuChip import de.davis.keygo.feature.item.core.presentation.component.gatherPendingItems import de.davis.keygo.feature.item.core.presentation.transformation.rememberSchemeStrippingTransformation import de.davis.keygo.feature.item.create.R +import de.davis.keygo.feature.item.create.presentation.component.DeletePasskeyDialog import de.davis.keygo.feature.item.create.presentation.component.FormGroup import de.davis.keygo.feature.item.create.presentation.component.ItemContentWrapper import de.davis.keygo.feature.item.create.presentation.component.KeyGoItemForm @@ -59,6 +63,7 @@ import de.davis.keygo.feature.item.create.presentation.component.TAG_DELIMITERS import de.davis.keygo.feature.item.create.presentation.component.TotpParseErrorDialog import de.davis.keygo.feature.item.create.presentation.login.model.DialogState import de.davis.keygo.feature.item.create.presentation.login.model.LoginBaseState +import de.davis.keygo.feature.item.create.presentation.login.model.LoginPasskeyInfo import de.davis.keygo.feature.item.create.presentation.login.model.LoginUiEvent import de.davis.keygo.feature.item.create.presentation.login.model.LoginUiState import de.davis.keygo.feature.item.create.presentation.model.ItemUiEvent @@ -154,6 +159,31 @@ private fun LoginReadyContent( onTagSubmitted = { onEvent(LoginUiEvent.ItemUi(ItemUiEvent.OnAddTags(it))) }, onDeleteTag = { onEvent(LoginUiEvent.ItemUi(ItemUiEvent.OnRemoveTag(it))) }, ) { + if (state.passkeyRPs.isNotEmpty()) item(key = "passkey_information") { + FormGroup( + title = stringResource(R.string.passkey_information), + modifier = Modifier, + ) { + FlowRow( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalArrangement = Arrangement.spacedBy(8.dp), + ) { + state.passkeyRPs.forEach { passkeyInfo -> + key(passkeyInfo) { + MenuChip( + chipText = passkeyInfo.rpId, + onDeleteClick = { + onEvent(LoginUiEvent.OnDeletePasskeyRequest(passkeyInfo.rpId)) + }, + enabled = !passkeyInfo.pending + ) + } + } + } + } + } + item(key = "password_information") { var forceCompact by rememberSaveable { mutableStateOf(false) } @@ -294,6 +324,19 @@ private fun LoginReadyContent( modifier = Modifier.fillMaxWidth(), ) } + + is DialogState.DeletePasskey -> { + DeletePasskeyDialog( + state = state.dialogState, + onConfirmDeletion = { + onEvent(LoginUiEvent.OnConfirmPasskeyDeletion) + }, + onDismissRequest = { + onEvent(LoginUiEvent.OnPasskeyDeletionDismiss) + }, + modifier = Modifier.fillMaxWidth(), + ) + } } } @@ -333,6 +376,10 @@ private fun LoginContentPreview() { eTLD1 = "example.com", ), ), + passkeyRPs = setOf( + LoginPasskeyInfo(rpId = "example.com", pending = false), + LoginPasskeyInfo(rpId = "example.org", pending = true), + ), ), shared = SharedItemState( nameTextFieldState = TextFieldState(), diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt index e9ddbf2fd..8153b8b77 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt @@ -402,6 +402,15 @@ internal class LoginViewModel( } } + is LoginUiEvent.OnDeletePasskeyRequest -> { + } + + is LoginUiEvent.OnPasskeyDeletionDismiss -> { + } + + is LoginUiEvent.OnConfirmPasskeyDeletion -> { + } + is LoginUiEvent.OnAddDomains -> { event.domains.forEach { domain -> val registrableDomain = registrableDomainResolver.resolve(domain) diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/DialogState.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/DialogState.kt index 2f96a11b8..f0048f35f 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/DialogState.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/DialogState.kt @@ -7,4 +7,6 @@ sealed interface DialogState { data object TotpParseError : DialogState data class SelectItemForModification(val items: List) : DialogState data class OverrideTotp(val fields: Set) : DialogState + + data class DeletePasskey(val rpId: String) : DialogState } diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiEvent.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiEvent.kt index 3dfd32617..70573c8f5 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiEvent.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiEvent.kt @@ -11,6 +11,10 @@ internal sealed interface LoginUiEvent { data object OnCloseBottomSheet : LoginUiEvent data object OnScanCodeRequest : LoginUiEvent + data class OnDeletePasskeyRequest(val rpId: String) : LoginUiEvent + data object OnConfirmPasskeyDeletion : LoginUiEvent + data object OnPasskeyDeletionDismiss : LoginUiEvent + data class OnDeleteDomain(val value: String) : LoginUiEvent data class OnAddDomains(val domains: Set) : LoginUiEvent diff --git a/feature/item/create/src/main/res/values/strings.xml b/feature/item/create/src/main/res/values/strings.xml index 73d07949d..c8294dacb 100644 --- a/feature/item/create/src/main/res/values/strings.xml +++ b/feature/item/create/src/main/res/values/strings.xml @@ -5,6 +5,7 @@ Password Information Credit Card Information Domain Information + Passkey Information Tag information Override TOTP fields? @@ -29,6 +30,10 @@ Warning OK + Cancel + + Delete Passkey + The passkey for <b>%s</b> is removed when you save. You will no longer be able to sign in there with it, and it can not be restored. Generate Password From 0980a3d34e1c4ab70d9b7f29909134a2a91f5f33 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sat, 15 Aug 2026 14:55:44 +0200 Subject: [PATCH 06/13] refactor(login): implement delete paskey logic --- .../core/item/data/local/dao/PasskeyDao.kt | 31 +++- .../data/repository/LoginRepositoryImpl.kt | 6 + .../repository/LoginRepositoryImplTest.kt | 38 +++++ .../item/core/domain/model/UpsertLogin.kt | 10 ++ .../CreateNewOrUpdateLoginUseCaseTest.kt | 157 ++++++++++++++++++ .../presentation/login/LoginViewModel.kt | 24 +++ .../presentation/login/model/LoginUiState.kt | 1 + .../de/davis/keygo/rust/FakePasskeyManager.kt | 16 +- 8 files changed, 271 insertions(+), 12 deletions(-) diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/dao/PasskeyDao.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/dao/PasskeyDao.kt index 0c9e18378..5abb7e852 100644 --- a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/dao/PasskeyDao.kt +++ b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/dao/PasskeyDao.kt @@ -3,24 +3,43 @@ package de.davis.keygo.core.item.data.local.dao import androidx.room.Dao import androidx.room.Insert import androidx.room.Query +import androidx.room.Transaction import de.davis.keygo.core.item.data.local.entity.credential.PasskeyEntity import de.davis.keygo.core.item.data.local.pojo.PasskeyMetadataPojo import de.davis.keygo.core.item.domain.alias.ItemId @Dao -internal interface PasskeyDao { +internal abstract class PasskeyDao { @Insert - suspend fun insertPasskey(passkey: PasskeyEntity) + abstract suspend fun insertPasskey(passkey: PasskeyEntity) @Query("SELECT * FROM passkey WHERE credential_id = :credentialId") - suspend fun getPasskey(credentialId: ByteArray): PasskeyEntity? + abstract suspend fun getPasskey(credentialId: ByteArray): PasskeyEntity? @Query("SELECT * FROM passkey WHERE login_id = :loginId") - suspend fun getPasskeysForLogin(loginId: ItemId): List + abstract suspend fun getPasskeysForLogin(loginId: ItemId): List + + @Query("DELETE FROM passkey WHERE login_id = :loginId") + protected abstract suspend fun deleteAllPasskeysForLogin(loginId: ItemId) + + @Query("DELETE FROM passkey WHERE login_id = :loginId AND rp NOT IN (:rpIds)") + protected abstract suspend fun deletePasskeysForLoginNotIn(loginId: ItemId, rpIds: Set) + + /** + * Drops every passkey [loginId] holds for a relying party outside [rpIds]. + * + * Deletes only. A passkey row carries a credential id and key material, so it can not be + * reconstructed from a relying party name and this can never put one back. + */ + @Transaction + open suspend fun deleteRPsNotIn(loginId: ItemId, rpIds: Set) { + if (rpIds.isEmpty()) deleteAllPasskeysForLogin(loginId) + else deletePasskeysForLoginNotIn(loginId, rpIds) + } @Query("SELECT EXISTS (SELECT 1 FROM passkey WHERE credential_id IN (:credentialIds))") - suspend fun doesCredentialIdsExist(credentialIds: Set): Boolean + abstract suspend fun doesCredentialIdsExist(credentialIds: Set): Boolean @Query( """ @@ -31,5 +50,5 @@ internal interface PasskeyDao { WHERE pk.rp = :rpId """ ) - suspend fun getPasskeysForRP(rpId: String): List + abstract suspend fun getPasskeysForRP(rpId: String): List } diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImpl.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImpl.kt index b7d93e906..ade41ee0b 100644 --- a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImpl.kt +++ b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImpl.kt @@ -4,6 +4,7 @@ import androidx.room.withTransaction import de.davis.keygo.core.item.data.local.dao.DomainInfoDao import de.davis.keygo.core.item.data.local.dao.ItemDao import de.davis.keygo.core.item.data.local.dao.LoginDao +import de.davis.keygo.core.item.data.local.dao.PasskeyDao import de.davis.keygo.core.item.data.local.dao.PasswordDao import de.davis.keygo.core.item.data.local.dao.TagDao import de.davis.keygo.core.item.data.local.dao.TotpDao @@ -38,6 +39,7 @@ internal class LoginRepositoryImpl( private val domainInfoDao: DomainInfoDao, private val totpDao: TotpDao, private val tagDao: TagDao, + private val passkeyDao: PasskeyDao, ) : LoginRepository { override suspend fun createOrUpdateLogin(login: Login): Result = @@ -56,6 +58,10 @@ internal class LoginRepositoryImpl( domainInfoDao.syncForLogin(login.id, login.toDomainInfoEntities()) tagDao.syncTags(login.id, login.tags.toTagEntities()) + // Delete only: passkeys are created through PasskeyRepository, never from here. + // See Login.passkeyRPs for why this set has to come from a fresh read. + passkeyDao.deleteRPsNotIn(login.id, login.passkeyRPs) + login.id } }.fold( diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImplTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImplTest.kt index 9c7f9d436..b2d5f58fb 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImplTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImplTest.kt @@ -4,6 +4,7 @@ import androidx.room.withTransaction import de.davis.keygo.core.item.data.local.dao.DomainInfoDao import de.davis.keygo.core.item.data.local.dao.ItemDao import de.davis.keygo.core.item.data.local.dao.LoginDao +import de.davis.keygo.core.item.data.local.dao.PasskeyDao import de.davis.keygo.core.item.data.local.dao.PasswordDao import de.davis.keygo.core.item.data.local.dao.TagDao import de.davis.keygo.core.item.data.local.dao.TotpDao @@ -46,6 +47,7 @@ class LoginRepositoryImplTest { private val domainInfoDao = mockk(relaxed = true) private val totpDao = mockk(relaxed = true) private val tagDao = mockk(relaxed = true) + private val passkeyDao = mockk(relaxed = true) private val repository = LoginRepositoryImpl( database = database, @@ -55,6 +57,7 @@ class LoginRepositoryImplTest { domainInfoDao = domainInfoDao, totpDao = totpDao, tagDao = tagDao, + passkeyDao = passkeyDao, ) @BeforeTest @@ -208,6 +211,41 @@ class LoginRepositoryImplTest { assertEquals(error, result.error) } + @Test + fun `createOrUpdateLogin drops passkeys whose RP is absent from the login`() = runTest { + val login = testLogin(totpProvider = null, passkeyRPs = setOf("example.org")) + + val result = repository.createOrUpdateLogin(login) + + assertTrue(result.isSuccess()) + coVerify(exactly = 1) { passkeyDao.deleteRPsNotIn(login.id, setOf("example.org")) } + } + + @Test + fun `createOrUpdateLogin with no passkey RPs drops every passkey the login holds`() = runTest { + // An empty set is how "the last passkey was removed" is expressed. There is no way to + // distinguish it from "unknown", which is why Login.passkeyRPs has no default. + val login = testLogin(totpProvider = null) + + val result = repository.createOrUpdateLogin(login) + + assertTrue(result.isSuccess()) + coVerify(exactly = 1) { passkeyDao.deleteRPsNotIn(login.id, emptySet()) } + } + + @Test + fun `createOrUpdateLogin returns Failure when the passkey delete throws`() = runTest { + // The delete shares the login's transaction, so a failure rolls the whole write back and + // surfaces as a Failure rather than escaping uncaught after the login row has landed. + val error = RuntimeException("db error") + coEvery { passkeyDao.deleteRPsNotIn(any(), any()) } throws error + + val result = repository.createOrUpdateLogin(testLogin(totpProvider = null)) + + assertTrue(result.isFailure()) + assertEquals(error, result.error) + } + private fun testLogin( passwordCredential: PasswordCredential? = PasswordCredential( secret = PasswordSecret(EncryptedPayload.EMPTY), diff --git a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/model/UpsertLogin.kt b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/model/UpsertLogin.kt index c64ba2509..5b96ca4d6 100644 --- a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/model/UpsertLogin.kt +++ b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/model/UpsertLogin.kt @@ -15,6 +15,8 @@ data class UpsertLogin private constructor( val domains: FieldUpdate>, override val tags: FieldUpdate>, override val note: FieldUpdate, + val removedPasskeyRPs: Set, + val pendingPasskey: Boolean, ) : UpsertItem { companion object { fun create( @@ -26,6 +28,7 @@ data class UpsertLogin private constructor( domains: Set = emptySet(), tags: Set = emptySet(), note: String? = null, + pendingPasskey: Boolean = false, ) = UpsertLogin( upsertType = UpsertType.Create(vaultId), name = FieldUpdate.Set(name), @@ -35,6 +38,9 @@ data class UpsertLogin private constructor( username = if (!username.isNullOrBlank()) FieldUpdate.Set(username) else FieldUpdate.Clear, domains = if (domains.isNotEmpty()) FieldUpdate.Set(domains) else FieldUpdate.Clear, tags = if (tags.isNotEmpty()) FieldUpdate.Set(tags) else FieldUpdate.Clear, + // A brand-new login holds no passkeys, so there is nothing to remove. + removedPasskeyRPs = emptySet(), + pendingPasskey = pendingPasskey, ) fun update( @@ -47,6 +53,8 @@ data class UpsertLogin private constructor( domains: FieldUpdate> = keep(), tags: FieldUpdate> = keep(), note: FieldUpdate = keep(), + removedPasskeyRPs: Set = emptySet(), + pendingPasskey: Boolean = false, ) = UpsertLogin( upsertType = UpsertType.Update(itemId, vaultId), name = name, @@ -56,6 +64,8 @@ data class UpsertLogin private constructor( tags = tags, username = username, domains = domains, + removedPasskeyRPs = removedPasskeyRPs, + pendingPasskey = pendingPasskey, ) } } diff --git a/feature/item/core/src/test/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCaseTest.kt b/feature/item/core/src/test/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCaseTest.kt index b0ad0092e..feea136e0 100644 --- a/feature/item/core/src/test/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCaseTest.kt +++ b/feature/item/core/src/test/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCaseTest.kt @@ -104,6 +104,163 @@ class CreateNewOrUpdateLoginUseCaseTest { assertEquals(setOf(ItemUpsertError.Empty), result.error) } + @Test + fun `create with a pending passkey and nothing else returns Success`() = runTest { + val result = useCase( + UpsertLogin.create( + vaultId = defaultVault.id, + name = "My site", + password = null, + username = null, + totpUriOrSecret = null, + pendingPasskey = true, + ) + ) + + assertTrue(result.isSuccess()) + } + + @Test + fun `update clearing the only credential while a passkey is pending returns Success`() = + runTest { + val existing = testLogin(username = null, totp = null) + loginRepository.seed(existing) + + val result = useCase( + UpsertLogin.update( + itemId = existing.id, + password = clear(), + pendingPasskey = true, + ) + ) + + assertTrue(result.isSuccess()) + } + + // The use case does not touch the passkey table: it resolves the login's effective relying + // parties, and LoginRepository drops the rows that fall outside that set as part of the same + // write. These assert the resolved set; LoginRepositoryImplTest covers the deletion itself. + + @Test + fun `update deleting a passkey drops it from the saved login`() = runTest { + val existing = testLogin(passkeyRPs = setOf("example.com", "example.org")) + loginRepository.seed(existing) + + val result = useCase( + UpsertLogin.update( + itemId = existing.id, + removedPasskeyRPs = setOf("example.com"), + ) + ) + + assertTrue(result.isSuccess()) + assertEquals( + setOf("example.org"), + loginRepository.getLoginById(existing.id)?.passkeyRPs, + ) + } + + @Test + fun `update deleting the only passkey of an otherwise empty login returns Empty`() = runTest { + val existing = testLogin( + username = null, + passwordCredential = null, + passkeyRPs = setOf("example.com"), + ) + loginRepository.seed(existing) + + val result = useCase( + UpsertLogin.update( + itemId = existing.id, + removedPasskeyRPs = setOf("example.com"), + ) + ) + + assertTrue(result.isFailure()) + assertContains(result.error, ItemUpsertError.Empty) + } + + @Test + fun `a passkey attached after the form loaded survives an unrelated removal`() = runTest { + // The editing screen reads a login's passkeys once, and passkeys can be attached to an + // existing login from the passkey activity while that screen is open. Removals travel as a + // delta for exactly this reason: the effective set is resolved against a fresh read here, + // so a passkey the form never saw is not in the delta and stays. The table below holds + // both; the form that produced this delta only ever saw "example.com". + val existing = testLogin(passkeyRPs = setOf("example.com", "attached-later.example")) + loginRepository.seed(existing) + + val result = useCase( + UpsertLogin.update( + itemId = existing.id, + removedPasskeyRPs = setOf("example.com"), + ) + ) + + assertTrue(result.isSuccess()) + assertEquals( + setOf("attached-later.example"), + loginRepository.getLoginById(existing.id)?.passkeyRPs, + ) + } + + @Test + fun `update rejected as Empty never reaches the repository`() = runTest { + val existing = testLogin( + username = null, + passwordCredential = null, + passkeyRPs = setOf("example.com"), + ) + loginRepository.seed(existing) + + useCase( + UpsertLogin.update( + itemId = existing.id, + removedPasskeyRPs = setOf("example.com"), + ) + ) + + // Validation runs before the write, so the stored login still holds the passkey and the + // repository never gets the chance to delete its row. + assertEquals(setOf("example.com"), loginRepository.getLoginById(existing.id)?.passkeyRPs) + } + + @Test + fun `update deleting the only passkey while a password remains returns Success`() = runTest { + val existing = testLogin(passkeyRPs = setOf("example.com")) + loginRepository.seed(existing) + + val result = useCase( + UpsertLogin.update( + itemId = existing.id, + removedPasskeyRPs = setOf("example.com"), + ) + ) + + assertTrue(result.isSuccess()) + assertTrue(loginRepository.getLoginById(existing.id)?.passkeyRPs.orEmpty().isEmpty()) + } + + @Test + fun `a save can register one passkey and remove another at the same time`() = runTest { + // Not reachable from the UI today: the passkey activity only opens the editor on a new + // login, which holds no passkeys to remove. A guard against the two ever being treated as + // alternatives again if that flow gains an "edit existing" entry point. + val existing = testLogin(passkeyRPs = setOf("old.example")) + loginRepository.seed(existing) + + val result = useCase( + UpsertLogin.update( + itemId = existing.id, + removedPasskeyRPs = setOf("old.example"), + pendingPasskey = true, + ) + ) + + assertTrue(result.isSuccess()) + assertTrue(loginRepository.getLoginById(existing.id)?.passkeyRPs.orEmpty().isEmpty()) + } + @Test fun `create with password only returns Success`() = runTest { val result = useCase( diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt index 8153b8b77..d872f1bb1 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt @@ -36,6 +36,7 @@ import de.davis.keygo.feature.item.create.R import de.davis.keygo.feature.item.create.presentation.ItemViewModel import de.davis.keygo.feature.item.create.presentation.login.model.DialogState import de.davis.keygo.feature.item.create.presentation.login.model.LoginBaseState +import de.davis.keygo.feature.item.create.presentation.login.model.LoginPasskeyInfo import de.davis.keygo.feature.item.create.presentation.login.model.LoginUiEvent import de.davis.keygo.feature.item.create.presentation.login.model.OverrideTotpField import de.davis.keygo.feature.item.create.presentation.model.ItemUiState @@ -199,6 +200,7 @@ internal class LoginViewModel( pending = false, ) }, + deletedPasskeyRPs = emptySet(), dialogState = DialogState.None, updating = true, ) @@ -243,6 +245,8 @@ internal class LoginViewModel( val base = ready.base val assignedTags = ready.shared.itemAssignedTags val selectedVaultId = ready.shared.vaultsState.selectedVaultId + // Independent: a save can both register a passkey and drop another one. + val pendingPasskey = base.passkeyRPs.any { it.pending } viewModelScope.launch { val upsert = itemId?.let { itemId -> UpsertLogin.update( @@ -255,6 +259,8 @@ internal class LoginViewModel( password = fieldUpdate(base.passwordTextFieldState.text.toString()), totpUriOrSecret = fieldUpdate(base.totpTextFieldState.text.toString()), note = fieldUpdate(notesTextFieldState.text.toString()), + removedPasskeyRPs = base.deletedPasskeyRPs, + pendingPasskey = pendingPasskey, ) } ?: UpsertLogin.create( vaultId = selectedVaultId, @@ -265,6 +271,7 @@ internal class LoginViewModel( password = base.passwordTextFieldState.text.toString(), totpUriOrSecret = base.totpTextFieldState.text.toString(), note = notesTextFieldState.text.toString(), + pendingPasskey = pendingPasskey, ) createNewOrUpdateLogin( @@ -403,12 +410,29 @@ internal class LoginViewModel( } is LoginUiEvent.OnDeletePasskeyRequest -> { + _base.update { + it.copy(dialogState = DialogState.DeletePasskey(rpId = event.rpId)) + } } is LoginUiEvent.OnPasskeyDeletionDismiss -> { + _base.update { it.copy(dialogState = DialogState.None) } } is LoginUiEvent.OnConfirmPasskeyDeletion -> { + val dialogState = _base.value.dialogState as? DialogState.DeletePasskey ?: return + + _base.update { + it.copy( + passkeyRPs = it.passkeyRPs + .filterNot { passkey -> + passkey.rpId == dialogState.rpId && !passkey.pending + } + .toSet(), + deletedPasskeyRPs = it.deletedPasskeyRPs + dialogState.rpId, + dialogState = DialogState.None, + ) + } } is LoginUiEvent.OnAddDomains -> { diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiState.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiState.kt index 73ffd8ebf..5d63db619 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiState.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiState.kt @@ -21,6 +21,7 @@ internal data class LoginBaseState( val usernameTextFieldState: TextFieldState = TextFieldState(), val domains: Set = emptySet(), val passkeyRPs: Set = emptySet(), + val deletedPasskeyRPs: Set = emptySet(), val strengthScore: PasswordScore = PasswordScore.None, val generatePasswordBottomSheetVisible: Boolean = false, val dialogState: DialogState = DialogState.None, diff --git a/rust/src/testFixtures/kotlin/de/davis/keygo/rust/FakePasskeyManager.kt b/rust/src/testFixtures/kotlin/de/davis/keygo/rust/FakePasskeyManager.kt index 49b6272c2..6f3811e31 100644 --- a/rust/src/testFixtures/kotlin/de/davis/keygo/rust/FakePasskeyManager.kt +++ b/rust/src/testFixtures/kotlin/de/davis/keygo/rust/FakePasskeyManager.kt @@ -1,5 +1,6 @@ package de.davis.keygo.rust +import de.davisalessandro.keygo.rust.PasskeyInformation import de.davisalessandro.keygo.rust.RegistrationResponse import de.davisalessandro.keygo.rust.RustPasskeyInterface @@ -13,7 +14,7 @@ class FakePasskeyManager : RustPasskeyInterface { val authenticateCalls = mutableListOf() val registerCalls = mutableListOf() - val excludedCredentialsCalls = mutableListOf() + val passkeyInformationCalls = mutableListOf() /** Result returned by [authenticate]. Throws if null. */ var authenticateResult: String? = null @@ -21,8 +22,11 @@ class FakePasskeyManager : RustPasskeyInterface { /** Result returned by [register]. Throws if null. */ var registerResult: RegistrationResponse? = null - /** Result returned by [excludedCredentials]. */ - var excludedCredentialsResult: List = emptyList() + /** Result returned by [passkeyInformation]. */ + var passkeyInformationResult: PasskeyInformation = PasskeyInformation( + excludeCredentials = emptyList(), + rp = "example.com", + ) override suspend fun authenticate( jsonRequest: String, @@ -33,9 +37,9 @@ class FakePasskeyManager : RustPasskeyInterface { return authenticateResult ?: error("authenticateResult not set on FakePasskeyManager") } - override suspend fun excludedCredentials(jsonRequest: String): List { - excludedCredentialsCalls += jsonRequest - return excludedCredentialsResult + override fun passkeyInformation(jsonRequest: String): PasskeyInformation { + passkeyInformationCalls += jsonRequest + return passkeyInformationResult } override suspend fun register(jsonRequest: String): RegistrationResponse { From df4553dc37162b3f4a7eb0d577facb386cf7ec98 Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sun, 16 Aug 2026 10:09:48 +0200 Subject: [PATCH 07/13] feat(passkey): add exclusion dialog --- .../create/activity/CreatePasskeyActivity.kt | 49 ++++++++++++++ .../create/activity/CreatePasskeyViewModel.kt | 67 ++++++++++--------- .../src/main/res/values/strings.xml | 5 ++ 3 files changed, 90 insertions(+), 31 deletions(-) diff --git a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt index c83b521bc..7cea3f4c0 100644 --- a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt +++ b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt @@ -24,9 +24,13 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.fromHtml import androidx.credentials.CreatePublicKeyCredentialRequest import androidx.credentials.CreatePublicKeyCredentialResponse import androidx.credentials.exceptions.CreateCredentialUnknownException +import androidx.credentials.exceptions.domerrors.InvalidStateError +import androidx.credentials.exceptions.publickeycredential.CreatePublicKeyCredentialDomException import androidx.credentials.provider.PendingIntentHandler import androidx.fragment.app.FragmentActivity import androidx.lifecycle.compose.collectAsStateWithLifecycle @@ -134,6 +138,32 @@ internal class CreatePasskeyActivity : FragmentActivity() { ) } + val excluded by viewModel.excluded.collectAsStateWithLifecycle() + if (excluded) { + val rp = viewModel.passkeyInformation.rp + AlertDialog( + onDismissRequest = ::finishExcluded, + title = { + Text(stringResource(R.string.passkey_already_exists)) + }, + confirmButton = { + Button(onClick = ::finishExcluded) { + Text(stringResource(R.string.ok)) + } + }, + text = { + Text( + text = AnnotatedString.fromHtml( + if (rp.isNotBlank()) + stringResource(R.string.passkey_already_exists_message, rp) + else stringResource(R.string.passkey_already_exists_message_generic) + ) + ) + }, + modifier = Modifier.fillMaxWidth(), + ) + } + val biometricCryptoController = rememberBiometricCryptoController() val biometricUnlockAdapter = rememberBiometricUnlockAdapter() @@ -253,6 +283,25 @@ internal class CreatePasskeyActivity : FragmentActivity() { finish() } + /** + * Reports the relying party's own exclusion list back to it. + * + * [InvalidStateError] is what WebAuthn defines for "this authenticator already holds a + * credential for that user", so the site can say so instead of showing a generic failure. + * The framework forwards a provider exception only on RESULT_OK; RESULT_CANCELED is reported + * as a plain user cancellation and would hide it. + */ + private fun finishExcluded() { + val response = Intent() + PendingIntentHandler.setCreateCredentialException( + response, + CreatePublicKeyCredentialDomException(InvalidStateError()), + ) + + setResult(RESULT_OK, response) + finish() + } + private fun cancel(errorMsg: String? = null) { val result = errorMsg?.let { val response = Intent() diff --git a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt index f1550cbd2..19754ffda 100644 --- a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt +++ b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt @@ -13,10 +13,8 @@ import de.davis.keygo.core.item.domain.repository.PasskeyRepository import de.davis.keygo.core.security.domain.crypto.CryptographicScopeProvider import de.davis.keygo.core.security.domain.crypto.encrypt import de.davis.keygo.core.security.domain.repository.BiometricAvailabilityRepository -import de.davis.keygo.core.util.Result import de.davis.keygo.core.util.fold import de.davis.keygo.core.util.getOrNull -import de.davis.keygo.core.util.mapFailure import de.davis.keygo.core.util.onFailure import de.davis.keygo.feature.credentials.presentation.auth.SessionAuthState import de.davis.keygo.feature.credentials.presentation.auth.UnlockOutcome @@ -24,9 +22,7 @@ import de.davis.keygo.feature.credentials.presentation.auth.mapUnlockError import de.davis.keygo.rust.passkey.PasskeyManager import de.davis.keygo.rust.passkey.getPasskeyInformation import de.davis.keygo.rust.passkey.registerWithResult -import de.davisalessandro.keygo.rust.PasskeyException import de.davisalessandro.keygo.rust.PasskeyInformation -import de.davisalessandro.keygo.rust.RegistrationResponse import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow @@ -50,25 +46,16 @@ internal class CreatePasskeyViewModel( private val _authState = MutableStateFlow(SessionAuthState.TryBiometric) val authState = _authState.asStateFlow() + private val _excluded = MutableStateFlow(false) + val excluded = _excluded.asStateFlow() + private val biometricChannel = Channel(Channel.BUFFERED) val biometricFlow = biometricChannel.receiveAsFlow() private lateinit var pendingRequest: CreatePublicKeyCredentialRequest lateinit var passkeyInformation: PasskeyInformation - init { - viewModelScope.launch { - val account = accountRepository.getOrNull() - val biometricUsable = biometricAvailabilityRepository.availability() - && account?.biometricWrappedArk != null - - if (biometricUsable) { - _authState.value = SessionAuthState.TryBiometric - biometricChannel.send(Unit) - } else - _authState.value = SessionAuthState.NeedsPassword - } - } + private var started = false fun setRequest(request: CreatePublicKeyCredentialRequest): Boolean { pendingRequest = request @@ -76,9 +63,40 @@ internal class CreatePasskeyViewModel( .getOrNull() ?: return false + start() return true } + /** + * Answers the relying party's exclusion list before any unlock prompt, then routes to the auth + * path. + * + * Credential ids are not secrets and the passkey table is not gated behind the session, so an + * excluded request can be resolved without making the user authenticate for a registration + * that can never succeed. + * + * Runs once. [setRequest] is called again on every configuration change. + */ + private fun start() { + if (started) return + started = true + + viewModelScope.launch { + val excludeCredentials = passkeyInformation.excludeCredentials.toSet() + if (passkeyRepository.doCredentialIdsExist(excludeCredentials)) + return@launch _excluded.update { true } + + val account = accountRepository.getOrNull() + val biometricUsable = biometricAvailabilityRepository.availability() + && account?.biometricWrappedArk != null + + if (biometricUsable) { + _authState.update { SessionAuthState.TryBiometric } + biometricChannel.send(Unit) + } else _authState.update { SessionAuthState.NeedsPassword } + } + } + fun onUnlocked() { if (_authState.value == SessionAuthState.Authenticated) return _authState.update { SessionAuthState.Authenticated } @@ -91,17 +109,9 @@ internal class CreatePasskeyViewModel( } } - private suspend fun registerPasskey(request: CreatePublicKeyCredentialRequest): Result { - val shouldAbort = passkeyRepository.doCredentialIdsExist(passkeyInformation.excludeCredentials.toSet()) - if (shouldAbort) return Result.Failure(PasskeyCreationError.Excluded) - - return passkeyManager.registerWithResult(request.requestJson) - .mapFailure(PasskeyCreationError::RegistrationFailed) - } - fun associatePasskeyAndFinish(itemId: ItemId) { viewModelScope.launch { - val response = registerPasskey(pendingRequest) + val response = passkeyManager.registerWithResult(pendingRequest.requestJson) .onFailure { Log.d(TAG, "Failed to register passkey: $it") }.getOrNull() @@ -149,8 +159,3 @@ internal class CreatePasskeyViewModel( private const val TAG = "CreatePasskeyViewModel" } } - -internal sealed interface PasskeyCreationError { - data class RegistrationFailed(val exception: PasskeyException) : PasskeyCreationError - data object Excluded : PasskeyCreationError -} diff --git a/feature/credentials/src/main/res/values/strings.xml b/feature/credentials/src/main/res/values/strings.xml index ea4c74fb9..dda5aa806 100644 --- a/feature/credentials/src/main/res/values/strings.xml +++ b/feature/credentials/src/main/res/values/strings.xml @@ -5,6 +5,11 @@ Link Passkey Do you want to link the passkey for %s to this item? + Passkey already saved + You already have a passkey for <b>%s</b> in KeyGo. Delete it from the item first if you want to replace it. + You already have a passkey for this site in KeyGo. Delete it from the item first if you want to replace it. + Yes No + OK \ No newline at end of file From 0a3d1c02bdd51202dff0719d8438fe6698ef359d Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Sun, 16 Aug 2026 10:22:41 +0200 Subject: [PATCH 08/13] chore(passkey): format rust --- rust/rust-code/bindings/src/passkey.rs | 14 +++++++++++--- .../rust-code/lib/src/passkey/registration.rs | 19 +++++++++++++------ 2 files changed, 24 insertions(+), 9 deletions(-) diff --git a/rust/rust-code/bindings/src/passkey.rs b/rust/rust-code/bindings/src/passkey.rs index c8bf77427..899c05dfd 100644 --- a/rust/rust-code/bindings/src/passkey.rs +++ b/rust/rust-code/bindings/src/passkey.rs @@ -1,5 +1,8 @@ use lib::passkey::provider::{ProviderError, provide_passkey}; -use lib::passkey::registration::{KeyGoRegistrationResponse, PasskeyInformation as CorePasskeyInformation, RegistrationError, get_passkey_information, register_passkey}; +use lib::passkey::registration::{ + KeyGoRegistrationResponse, PasskeyInformation as CorePasskeyInformation, RegistrationError, + get_passkey_information, register_passkey, +}; use std::sync::Arc; #[derive(Debug, thiserror::Error, uniffi::Error)] @@ -102,8 +105,13 @@ impl RustPasskey { .map_err(Into::into) } - pub fn passkey_information(&self, json_request: String) -> Result { - get_passkey_information(&json_request).map(Into::into).map_err(Into::into) + pub fn passkey_information( + &self, + json_request: String, + ) -> Result { + get_passkey_information(&json_request) + .map(Into::into) + .map_err(Into::into) } pub async fn authenticate( diff --git a/rust/rust-code/lib/src/passkey/registration.rs b/rust/rust-code/lib/src/passkey/registration.rs index 46f54f9b7..d35f049f7 100644 --- a/rust/rust-code/lib/src/passkey/registration.rs +++ b/rust/rust-code/lib/src/passkey/registration.rs @@ -34,17 +34,24 @@ pub struct PasskeyInformation { pub rp: String, } -pub fn get_passkey_information(json_request: &str) -> Result { +pub fn get_passkey_information( + json_request: &str, +) -> Result { let creation_options: PublicKeyCredentialCreationOptions = serde_json::from_str(json_request).map_err(|_| InvalidJsonFormat)?; - let exclude_credentials: Vec> = creation_options.exclude_credentials.unwrap_or_default() - .into_iter().map(|desc| desc.id.into()).collect(); + let exclude_credentials: Vec> = creation_options + .exclude_credentials + .unwrap_or_default() + .into_iter() + .map(|desc| desc.id.into()) + .collect(); let rp = creation_options.rp.id.unwrap_or_default(); - Ok( - PasskeyInformation { exclude_credentials, rp } - ) + Ok(PasskeyInformation { + exclude_credentials, + rp, + }) } pub async fn register_passkey( From 220da3c78cd4bdd14eddf819ebbaea9721f4e47d Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Wed, 19 Aug 2026 11:09:51 +0200 Subject: [PATCH 09/13] fix(ui): escape format args before parsing HTML string resources The relying party id in the passkey dialogs comes straight from the calling app's requestJson and was substituted into an HTML string resource that AnnotatedString.fromHtml then parsed, so a caller could put markup, including a tappable link, inside KeyGo's own credential dialogs. Add htmlStringResource, which HTML-escapes every format argument before substitution so only the resource itself can contribute markup, and route the "passkey already exists" and "delete passkey" dialogs through it. Co-Authored-By: Claude Opus 5 --- .../keygo/core/ui/text/HtmlStringResource.kt | 24 +++++++++++++++++++ .../create/activity/CreatePasskeyActivity.kt | 11 ++++----- .../component/DeletePasskeyDialog.kt | 7 ++---- 3 files changed, 30 insertions(+), 12 deletions(-) create mode 100644 core/ui/src/main/kotlin/de/davis/keygo/core/ui/text/HtmlStringResource.kt diff --git a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/text/HtmlStringResource.kt b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/text/HtmlStringResource.kt new file mode 100644 index 000000000..efdfaec84 --- /dev/null +++ b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/text/HtmlStringResource.kt @@ -0,0 +1,24 @@ +package de.davis.keygo.core.ui.text + +import android.text.TextUtils +import androidx.annotation.StringRes +import androidx.compose.runtime.Composable +import androidx.compose.runtime.ReadOnlyComposable +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.AnnotatedString +import androidx.compose.ui.text.fromHtml + +/** + * Resolves the HTML-formatted string resource [id] and parses its markup into an [AnnotatedString]. + * + * Every entry of [formatArgs] is HTML-escaped before it is substituted, so only the resource itself + * can contribute markup. An argument that is not ours to trust, such as a relying party id taken + * verbatim from an incoming credential request, therefore renders as plain text instead of turning + * into a link or breaking out of the resource's own formatting. + */ +@Composable +@ReadOnlyComposable +fun htmlStringResource(@StringRes id: Int, vararg formatArgs: String): AnnotatedString = + AnnotatedString.fromHtml( + stringResource(id, *Array(formatArgs.size) { TextUtils.htmlEncode(formatArgs[it]) }), + ) diff --git a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt index 7cea3f4c0..33dd947b9 100644 --- a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt +++ b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt @@ -24,8 +24,6 @@ import androidx.compose.runtime.saveable.rememberSaveable import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.AnnotatedString -import androidx.compose.ui.text.fromHtml import androidx.credentials.CreatePublicKeyCredentialRequest import androidx.credentials.CreatePublicKeyCredentialResponse import androidx.credentials.exceptions.CreateCredentialUnknownException @@ -43,6 +41,7 @@ import de.davis.keygo.core.item.domain.alias.ItemId import de.davis.keygo.core.security.domain.model.BiometricPolicy import de.davis.keygo.core.security.domain.model.BiometricString import de.davis.keygo.core.security.presentation.rememberBiometricCryptoController +import de.davis.keygo.core.ui.text.htmlStringResource import de.davis.keygo.core.ui.theme.KeyGoTheme import de.davis.keygo.core.util.onFailure import de.davis.keygo.core.util.onSuccess @@ -153,11 +152,9 @@ internal class CreatePasskeyActivity : FragmentActivity() { }, text = { Text( - text = AnnotatedString.fromHtml( - if (rp.isNotBlank()) - stringResource(R.string.passkey_already_exists_message, rp) - else stringResource(R.string.passkey_already_exists_message_generic) - ) + text = if (rp.isNotBlank()) + htmlStringResource(R.string.passkey_already_exists_message, rp) + else htmlStringResource(R.string.passkey_already_exists_message_generic) ) }, modifier = Modifier.fillMaxWidth(), diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/component/DeletePasskeyDialog.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/component/DeletePasskeyDialog.kt index 46ee501be..a84dc8d07 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/component/DeletePasskeyDialog.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/component/DeletePasskeyDialog.kt @@ -10,9 +10,8 @@ import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource -import androidx.compose.ui.text.AnnotatedString -import androidx.compose.ui.text.fromHtml import androidx.compose.ui.tooling.preview.Preview +import de.davis.keygo.core.ui.text.htmlStringResource import de.davis.keygo.core.ui.theme.KeyGoTheme import de.davis.keygo.feature.item.create.R import de.davis.keygo.feature.item.create.presentation.login.model.DialogState @@ -49,9 +48,7 @@ fun DeletePasskeyDialog( }, text = { Text( - text = AnnotatedString.fromHtml( - stringResource(R.string.delete_passkey_warning, state.rpId) - ) + text = htmlStringResource(R.string.delete_passkey_warning, state.rpId) ) }, ) From bc14f0d7b18a8ed6bb5fafaae5c5d21078d960bd Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Wed, 19 Aug 2026 11:11:34 +0200 Subject: [PATCH 10/13] fix(passkey): guard associatePasskeyAndFinish against concurrent runs Registration moved out of runOperation into associatePasskeyAndFinish, which left nothing to stop it from running twice. confirmationEvent is only nulled inside the same onClick, so a double tap on Yes in the link-passkey dialog can land before recomposition. Two runs mint two key pairs and credential ids, store both, and send Finish with two different responses. The relying party only learns about whichever wins the race, so the other private key stays in the vault as a credential the site has never heard of and later reports the item as excluded on a credential id the relying party does not know. Co-Authored-By: Claude Opus 5 --- .../create/activity/CreatePasskeyViewModel.kt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt index 19754ffda..8661b53df 100644 --- a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt +++ b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt @@ -56,6 +56,7 @@ internal class CreatePasskeyViewModel( lateinit var passkeyInformation: PasskeyInformation private var started = false + private var associating = false fun setRequest(request: CreatePublicKeyCredentialRequest): Boolean { pendingRequest = request @@ -109,7 +110,21 @@ internal class CreatePasskeyViewModel( } } + /** + * Registers the pending request and links the resulting passkey to [itemId]. + * + * Runs at most once per activity. Every caller is a one-shot UI action, but nothing stops a + * second tap from landing before the first one has recomposed the dialog away. A repeat run + * would mint a second key pair and credential id, store both, and answer the relying party with + * only whichever response wins the race, leaving the other private key in the vault as a + * credential the site has never heard of. + * + * The flag is only ever touched from the main thread, where the UI callbacks run. + */ fun associatePasskeyAndFinish(itemId: ItemId) { + if (associating) return + associating = true + viewModelScope.launch { val response = passkeyManager.registerWithResult(pendingRequest.requestJson) .onFailure { From 8e1c3b8ebe9782404da6410039859f67c566a53e Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Wed, 19 Aug 2026 15:42:22 +0200 Subject: [PATCH 11/13] fix(passkey): register before the item screen is shown Registration had moved to after the item was created and committed, so a failure left an orphan behind. In the create-new-item path a pending passkey keeps CreateNewOrUpdateLoginUseCase.isEmpty from firing even though buildCreate sets passkeyRPs to the empty set, so a login with nothing but a name gets written. A failing registerWithResult then aborts the activity and the user is left with a login that has no password, no TOTP, no passkey, and no hint where it came from. Register right after unlock again, so a failure aborts while there is still nothing to leave behind. The steps are strictly sequential, so express them that way: one coroutine running exclusion check, unlock, registration, item choice, store and finish, in that order. The two points where it waits on the user become suspension points on a CompletableDeferred each. Completing one is idempotent, so the guard against a repeat associatePasskeyAndFinish carries over from the previous commit without needing its own flag, and the registration response stays a local instead of becoming a field. The response also carries the rp id the authenticator resolved, which is populated even when the relying party omits rp.id from its request, so the confirmation dialog and the pending chip now read that instead of the request's own possibly empty value. Co-Authored-By: Claude Opus 5 --- .../create/activity/CreatePasskeyActivity.kt | 6 +- .../create/activity/CreatePasskeyViewModel.kt | 164 ++++++++++-------- 2 files changed, 92 insertions(+), 78 deletions(-) diff --git a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt index 33dd947b9..6cea68dab 100644 --- a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt +++ b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyActivity.kt @@ -74,7 +74,7 @@ internal class CreatePasskeyActivity : FragmentActivity() { val callingRequest = request?.callingRequest as? CreatePublicKeyCredentialRequest ?: return cancel("Invalid CreatePublicKeyCredentialRequest") - val success = viewModel.setRequest(callingRequest) + val success = viewModel.setRequest(callingRequest.requestJson) if (!success) return cancel("Failed to set request") setResult(RESULT_CANCELED) @@ -138,8 +138,8 @@ internal class CreatePasskeyActivity : FragmentActivity() { } val excluded by viewModel.excluded.collectAsStateWithLifecycle() + val rp by viewModel.rp.collectAsStateWithLifecycle() if (excluded) { - val rp = viewModel.passkeyInformation.rp AlertDialog( onDismissRequest = ::finishExcluded, title = { @@ -222,7 +222,7 @@ internal class CreatePasskeyActivity : FragmentActivity() { composable { LoginScreen( - pendingPasskeyRP = viewModel.passkeyInformation.rp, + pendingPasskeyRP = rp, loginCreated = { viewModel.associatePasskeyAndFinish(it) }, diff --git a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt index 8661b53df..add08a097 100644 --- a/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt +++ b/feature/credentials/src/main/kotlin/de/davis/keygo/feature/credentials/presentation/create/activity/CreatePasskeyViewModel.kt @@ -1,7 +1,6 @@ package de.davis.keygo.feature.credentials.presentation.create.activity import android.util.Log -import androidx.credentials.CreatePublicKeyCredentialRequest import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import de.davis.keygo.core.identity.domain.model.UnlockError @@ -13,16 +12,17 @@ import de.davis.keygo.core.item.domain.repository.PasskeyRepository import de.davis.keygo.core.security.domain.crypto.CryptographicScopeProvider import de.davis.keygo.core.security.domain.crypto.encrypt import de.davis.keygo.core.security.domain.repository.BiometricAvailabilityRepository +import de.davis.keygo.core.util.Result import de.davis.keygo.core.util.fold import de.davis.keygo.core.util.getOrNull -import de.davis.keygo.core.util.onFailure import de.davis.keygo.feature.credentials.presentation.auth.SessionAuthState import de.davis.keygo.feature.credentials.presentation.auth.UnlockOutcome import de.davis.keygo.feature.credentials.presentation.auth.mapUnlockError import de.davis.keygo.rust.passkey.PasskeyManager import de.davis.keygo.rust.passkey.getPasskeyInformation import de.davis.keygo.rust.passkey.registerWithResult -import de.davisalessandro.keygo.rust.PasskeyInformation +import de.davisalessandro.keygo.rust.RegistrationResponse +import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.asStateFlow @@ -52,96 +52,85 @@ internal class CreatePasskeyViewModel( private val biometricChannel = Channel(Channel.BUFFERED) val biometricFlow = biometricChannel.receiveAsFlow() - private lateinit var pendingRequest: CreatePublicKeyCredentialRequest - lateinit var passkeyInformation: PasskeyInformation + /** + * The request's own `rp.id`, which the relying party may leave empty, until registration + * replaces it with the id the authenticator resolved. + */ + private val _rp = MutableStateFlow("") + val rp = _rp.asStateFlow() + + /** Completed by [onUnlocked]. */ + private val unlocked = CompletableDeferred() + + /** Completed by [associatePasskeyAndFinish]. */ + private val chosenItem = CompletableDeferred() private var started = false - private var associating = false - fun setRequest(request: CreatePublicKeyCredentialRequest): Boolean { - pendingRequest = request - passkeyInformation = passkeyManager.getPasskeyInformation(request.requestJson) - .getOrNull() + /** + * Parses [requestJson] and starts the flow. False means the request is unusable. + * + * The activity calls this again on every configuration change; only the first call does + * anything. + */ + fun setRequest(requestJson: String): Boolean { + if (started) return true + + val information = passkeyManager.getPasskeyInformation(requestJson).getOrNull() ?: return false - start() + started = true + _rp.update { information.rp } + start(requestJson, information.excludeCredentials.toSet()) + return true } /** - * Answers the relying party's exclusion list before any unlock prompt, then routes to the auth - * path. - * - * Credential ids are not secrets and the passkey table is not gated behind the session, so an - * excluded request can be resolved without making the user authenticate for a registration - * that can never succeed. - * - * Runs once. [setRequest] is called again on every configuration change. + * The whole flow as one coroutine, so the order of the steps is the order of the lines and the + * two waits on the user are plain suspension points. */ - private fun start() { - if (started) return - started = true - + private fun start(requestJson: String, excludeCredentials: Set) { viewModelScope.launch { - val excludeCredentials = passkeyInformation.excludeCredentials.toSet() + // The passkey table is not gated behind the session and credential ids are not secrets, + // so an excluded request is answered without making the user authenticate for a + // registration that can never succeed. if (passkeyRepository.doCredentialIdsExist(excludeCredentials)) return@launch _excluded.update { true } - val account = accountRepository.getOrNull() - val biometricUsable = biometricAvailabilityRepository.availability() - && account?.biometricWrappedArk != null + requestUnlock() + unlocked.await() - if (biometricUsable) { - _authState.update { SessionAuthState.TryBiometric } - biometricChannel.send(Unit) - } else _authState.update { SessionAuthState.NeedsPassword } - } - } + // Before the item screen, so a failure aborts while there is nothing to leave behind. + val response = passkeyManager.registerWithResult(requestJson) + .orAbort("Failed to register passkey") ?: return@launch - fun onUnlocked() { - if (_authState.value == SessionAuthState.Authenticated) return - _authState.update { SessionAuthState.Authenticated } - } + _rp.update { response.rp } + _authState.update { SessionAuthState.Authenticated } - fun onUnlockFailed(error: UnlockError) { - when (mapUnlockError(error)) { - UnlockOutcome.Abort -> viewModelScope.launch { abort("biometric $error") } - UnlockOutcome.NeedsPassword -> _authState.update { SessionAuthState.NeedsPassword } + storeAndFinish(response, chosenItem.await()) } } - /** - * Registers the pending request and links the resulting passkey to [itemId]. - * - * Runs at most once per activity. Every caller is a one-shot UI action, but nothing stops a - * second tap from landing before the first one has recomposed the dialog away. A repeat run - * would mint a second key pair and credential id, store both, and answer the relying party with - * only whichever response wins the race, leaving the other private key in the vault as a - * credential the site has never heard of. - * - * The flag is only ever touched from the main thread, where the UI callbacks run. - */ - fun associatePasskeyAndFinish(itemId: ItemId) { - if (associating) return - associating = true + private suspend fun requestUnlock() { + val biometricUsable = biometricAvailabilityRepository.availability() + && accountRepository.getOrNull()?.biometricWrappedArk != null - viewModelScope.launch { - val response = passkeyManager.registerWithResult(pendingRequest.requestJson) - .onFailure { - Log.d(TAG, "Failed to register passkey: $it") - }.getOrNull() - ?: return@launch abort("Failed to register passkey") - - val encryptedPrivateKey = cryptographicScopeProvider.itemScope(itemId = itemId) { - Passkey.PrivateKey.encrypt(response.privateKey) - }.fold( - onSuccess = { it }, - onFailure = { return@launch abort("Failed to encrypt passkey private key: $it") } - ) + if (biometricUsable) { + _authState.update { SessionAuthState.TryBiometric } + biometricChannel.send(Unit) + } else _authState.update { SessionAuthState.NeedsPassword } + } + + private suspend fun storeAndFinish(response: RegistrationResponse, itemId: ItemId) { + val privateKey = cryptographicScopeProvider.itemScope(itemId = itemId) { + Passkey.PrivateKey.encrypt(response.privateKey) + }.orAbort("Failed to encrypt passkey private key") ?: return - val passkey = Passkey( + passkeyRepository.createPasskey( + Passkey( credentialId = response.credentialId, - privateKey = encryptedPrivateKey, + privateKey = privateKey, rp = response.rp, loginId = itemId, user = PasskeyUser( @@ -149,24 +138,49 @@ internal class CreatePasskeyViewModel( displayName = response.userDisplayName, ), ) + ) + _event.send(CreatePasskeyEvent.Finish(response.response)) + } - passkeyRepository.createPasskey(passkey) - _event.send(CreatePasskeyEvent.Finish(response.response)) + fun onUnlocked() { + unlocked.complete(Unit) + } + + fun onUnlockFailed(error: UnlockError) { + when (mapUnlockError(error)) { + UnlockOutcome.Abort -> viewModelScope.launch { abort("biometric $error") } + UnlockOutcome.NeedsPassword -> _authState.update { SessionAuthState.NeedsPassword } } } + /** + * Names the login the passkey belongs to. Only the first call counts: a second tap landing + * before the dialog recomposes away would otherwise store the credential twice. + */ + fun associatePasskeyAndFinish(itemId: ItemId) { + chosenItem.complete(itemId) + } + fun onItemClicked(itemId: ItemId) { _event.trySend( CreatePasskeyEvent.OpenConfirmationDialog( itemId = itemId, itemName = "N/A", - rp = passkeyInformation.rp + rp = _rp.value, ) ) } - private suspend fun abort(msg: String? = null) { - msg?.let { Log.w(TAG, "Aborting: $it") } + private suspend fun Result.orAbort(reason: String): S? = fold( + onSuccess = { it }, + onFailure = { + abort("$reason: $it") + null + }, + ) + + private suspend fun abort(msg: String) { + Log.w(TAG, "Aborting: $msg") _event.send(CreatePasskeyEvent.Abort) } From 5be5f0db9f0128b8ebbe162738a7fb97dc25fa1d Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Wed, 19 Aug 2026 11:13:54 +0200 Subject: [PATCH 12/13] fix(login): ignore a blank pending passkey rp id The null check missed the empty case. rp.id is optional per WebAuthn, and the Rust side reads it as creation_options.rp.id.unwrap_or_default(), so a request that omits it arrives as "". That passed the null check and added LoginPasskeyInfo("", pending = true): a blank disabled chip under Passkey Information, hasAnyContent flipped true so a name-only login looked saveable, and a confirmation dialog asking whether to link the passkey for nothing. Co-Authored-By: Claude Opus 5 --- .../item/create/presentation/login/LoginViewModel.kt | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt index d872f1bb1..89c220f84 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt @@ -114,8 +114,16 @@ internal class LoginViewModel( .launchIn(viewModelScope) } + /** + * Shows a passkey for [rp] as pending until the item is saved. + * + * A blank id is dropped along with a null one. `rp.id` is optional per WebAuthn, so a request + * that leaves it out reaches us as an empty string, which would otherwise show up as a blank + * chip, make a name-only login look saveable, and leave the confirmation dialog asking about + * nothing. + */ fun setPendingPasskeyCount(rp: String?) { - if (rp == null) return + if (rp.isNullOrBlank()) return _base.update { it.copy(passkeyRPs = it.passkeyRPs + setOf(LoginPasskeyInfo(rp, true))) } } From 6c07fc05d054297c9deaa9dd3aa9efc9c2dca5db Mon Sep 17 00:00:00 2001 From: Davis Wolfermann Date: Wed, 19 Aug 2026 12:48:08 +0200 Subject: [PATCH 13/13] fix(passkey): key passkey listing and deletion on the credential id Deleting by relying party is lossy the moment one login holds two passkeys for the same site, for example two accounts on example.com. LoginProjection.toDomain collapsed both rows into a single rp string, so the editor showed one chip for two credentials and the user could not see there were two. Deleting that chip put example.com into the removal set and deleteRPsNotIn wiped both rows, while the dialog spoke about "the passkey" in the singular. Those rows carry key material and cannot be reconstructed. Carry the credential id alongside the relying party: - PasskeyRef pairs a credential id with its rp, and Login.passkeyRPs becomes Login.passkeys, one entry per credential. - PasskeyDao.deleteRPsNotIn becomes deleteCredentialsNotIn, keyed on credential id. - UpsertLogin.removedPasskeyRPs becomes removedPasskeys and travels as refs, so the use case subtracts exactly the credentials the user dropped. - The editor renders one chip per credential and the delete dialog carries the ref it is about. Co-Authored-By: Claude Opus 5 --- .../core/item/data/local/dao/PasskeyDao.kt | 23 ++++-- .../item/data/local/pojo/LoginProjection.kt | 2 +- .../item/data/local/pojo/PasskeyRefPojo.kt | 19 +++++ .../keygo/core/item/data/local/pojo/RP.kt | 5 -- .../core/item/data/mapper/LoginMapper.kt | 3 +- .../data/repository/LoginRepositoryImpl.kt | 4 +- .../keygo/core/item/domain/model/Login.kt | 11 ++- .../core/item/domain/model/PasskeyRef.kt | 26 ++++++ .../core/item/data/mapper/DomainMapperTest.kt | 2 +- .../core/item/data/mapper/ItemMapperTest.kt | 2 +- .../core/item/data/mapper/LoginMapperTest.kt | 35 +++++++- .../repository/LoginRepositoryImplTest.kt | 25 +++--- .../keygo/core/item/domain/model/LoginTest.kt | 9 ++- .../ObserveAllTagsSortedUseCaseTest.kt | 2 +- .../domain/usecase/UpsertItemUseCaseTest.kt | 2 +- .../de/davis/keygo/core/item/PasskeyRefs.kt | 15 ++++ ...AddRegistrableDomainsToLoginUseCaseTest.kt | 2 +- ...DoesItemHaveDomainReferencesUseCaseTest.kt | 2 +- .../activity/AutofillViewModelTest.kt | 2 +- .../dataset/SuggestionFinderTest.kt | 14 ++-- .../keygo/feature/backup/BackupTestData.kt | 5 +- .../backup/domain/BackupCollectorTest.kt | 13 +-- .../item/core/domain/model/UpsertLogin.kt | 9 ++- .../usecase/CreateNewOrUpdateLoginUseCase.kt | 4 +- .../CreateNewOrUpdateLoginUseCaseTest.kt | 81 ++++++++++++------- .../component/DeletePasskeyDialog.kt | 7 +- .../create/presentation/login/LoginContent.kt | 22 +++-- .../presentation/login/LoginViewModel.kt | 26 +++--- .../presentation/login/model/DialogState.kt | 3 +- .../presentation/login/model/LoginUiEvent.kt | 3 +- .../presentation/login/model/LoginUiState.kt | 29 +++++-- .../item/view/login/ViewLoginContent.kt | 2 +- .../item/view/login/ViewLoginViewModel.kt | 2 +- .../item/view/login/model/ViewLoginState.kt | 3 +- .../usecase/MoveItemsToVaultUseCaseTest.kt | 2 +- .../domain/mapper/LegacyItemConverter.kt | 2 +- 36 files changed, 291 insertions(+), 127 deletions(-) create mode 100644 core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/pojo/PasskeyRefPojo.kt delete mode 100644 core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/pojo/RP.kt create mode 100644 core/item/src/main/kotlin/de/davis/keygo/core/item/domain/model/PasskeyRef.kt create mode 100644 core/item/src/testFixtures/kotlin/de/davis/keygo/core/item/PasskeyRefs.kt diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/dao/PasskeyDao.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/dao/PasskeyDao.kt index 5abb7e852..65af96f4a 100644 --- a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/dao/PasskeyDao.kt +++ b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/dao/PasskeyDao.kt @@ -23,19 +23,26 @@ internal abstract class PasskeyDao { @Query("DELETE FROM passkey WHERE login_id = :loginId") protected abstract suspend fun deleteAllPasskeysForLogin(loginId: ItemId) - @Query("DELETE FROM passkey WHERE login_id = :loginId AND rp NOT IN (:rpIds)") - protected abstract suspend fun deletePasskeysForLoginNotIn(loginId: ItemId, rpIds: Set) + @Query("DELETE FROM passkey WHERE login_id = :loginId AND credential_id NOT IN (:credentialIds)") + protected abstract suspend fun deletePasskeysForLoginNotIn( + loginId: ItemId, + credentialIds: Collection, + ) /** - * Drops every passkey [loginId] holds for a relying party outside [rpIds]. + * Drops every passkey [loginId] holds whose credential id is outside [credentialIds]. + * + * Keyed on the credential id rather than the relying party: one login can hold two credentials + * for the same site, and deleting by relying party would take both when the user only asked for + * one. * - * Deletes only. A passkey row carries a credential id and key material, so it can not be - * reconstructed from a relying party name and this can never put one back. + * Deletes only. A passkey row carries key material, so it can not be reconstructed from a + * credential id and this can never put one back. */ @Transaction - open suspend fun deleteRPsNotIn(loginId: ItemId, rpIds: Set) { - if (rpIds.isEmpty()) deleteAllPasskeysForLogin(loginId) - else deletePasskeysForLoginNotIn(loginId, rpIds) + open suspend fun deleteCredentialsNotIn(loginId: ItemId, credentialIds: Collection) { + if (credentialIds.isEmpty()) deleteAllPasskeysForLogin(loginId) + else deletePasskeysForLoginNotIn(loginId, credentialIds) } @Query("SELECT EXISTS (SELECT 1 FROM passkey WHERE credential_id IN (:credentialIds))") diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/pojo/LoginProjection.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/pojo/LoginProjection.kt index 642d634e7..286e27235 100644 --- a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/pojo/LoginProjection.kt +++ b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/pojo/LoginProjection.kt @@ -32,7 +32,7 @@ internal data class LoginProjection( entityColumn = "login_id", entity = PasskeyEntity::class ) - val rpEntity: List, + val passkeys: List, @Relation( parentColumn = "id", diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/pojo/PasskeyRefPojo.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/pojo/PasskeyRefPojo.kt new file mode 100644 index 000000000..a634e1400 --- /dev/null +++ b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/pojo/PasskeyRefPojo.kt @@ -0,0 +1,19 @@ +package de.davis.keygo.core.item.data.local.pojo + +import androidx.room.ColumnInfo + +/** The columns of a passkey row that identify it, without touching its key material. */ +internal data class PasskeyRefPojo( + @ColumnInfo(name = "credential_id") + val credentialId: ByteArray, + val rp: String, +) { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is PasskeyRefPojo) return false + + return credentialId.contentEquals(other.credentialId) && rp == other.rp + } + + override fun hashCode(): Int = 31 * credentialId.contentHashCode() + rp.hashCode() +} diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/pojo/RP.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/pojo/RP.kt deleted file mode 100644 index e9140b327..000000000 --- a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/local/pojo/RP.kt +++ /dev/null @@ -1,5 +0,0 @@ -package de.davis.keygo.core.item.data.local.pojo - -internal data class RP( - val rp: String -) \ No newline at end of file diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/mapper/LoginMapper.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/mapper/LoginMapper.kt index a5ac86f6a..409f1f783 100644 --- a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/mapper/LoginMapper.kt +++ b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/mapper/LoginMapper.kt @@ -7,6 +7,7 @@ import de.davis.keygo.core.item.data.local.entity.credential.PasswordEntity import de.davis.keygo.core.item.data.local.pojo.LightweightLogin import de.davis.keygo.core.item.data.local.pojo.LoginProjection import de.davis.keygo.core.item.domain.model.Login +import de.davis.keygo.core.item.domain.model.PasskeyRef import de.davis.keygo.core.item.domain.model.PasswordCredential import de.davis.keygo.core.item.domain.model.PasswordSecret import de.davis.keygo.core.item.domain.model.lite.LiteLogin @@ -35,7 +36,7 @@ internal fun LoginProjection.toDomain(): Login = Login( ) }, totp = totp?.toDomain(), - passkeyRPs = rpEntity.map { it.rp }.toSet(), + passkeys = passkeys.mapTo(mutableSetOf()) { PasskeyRef(it.credentialId, it.rp) }, domainInfos = domains.map(DomainInfoEntity::toDomain).toSet(), vaultId = item.itemEntity.vaultId, name = item.itemEntity.name, diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImpl.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImpl.kt index ade41ee0b..7c6f3f38e 100644 --- a/core/item/src/main/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImpl.kt +++ b/core/item/src/main/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImpl.kt @@ -59,8 +59,8 @@ internal class LoginRepositoryImpl( tagDao.syncTags(login.id, login.tags.toTagEntities()) // Delete only: passkeys are created through PasskeyRepository, never from here. - // See Login.passkeyRPs for why this set has to come from a fresh read. - passkeyDao.deleteRPsNotIn(login.id, login.passkeyRPs) + // See Login.passkeys for why this set has to come from a fresh read. + passkeyDao.deleteCredentialsNotIn(login.id, login.passkeys.map { it.credentialId }) login.id } diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/model/Login.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/model/Login.kt index 7394b022e..16c488627 100644 --- a/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/model/Login.kt +++ b/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/model/Login.kt @@ -13,7 +13,14 @@ data class Login( val domainInfos: Set, val passwordCredential: PasswordCredential?, val totp: Totp?, - val passkeyRPs: Set, + /** + * Passkeys this login currently holds, one entry per credential. + * + * Has no default and is never inferred: an empty set means "this login holds no passkeys" and + * saving it deletes every passkey row the login has. A caller that does not know has to read + * them rather than leave them out. + */ + val passkeys: Set, override val vaultId: VaultId, override val name: String, override val keyInformation: KeyInformation, @@ -30,5 +37,5 @@ data class Login( get() = !username.isNullOrBlank() || passwordCredential != null || totp != null - || passkeyRPs.isNotEmpty() + || passkeys.isNotEmpty() } diff --git a/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/model/PasskeyRef.kt b/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/model/PasskeyRef.kt new file mode 100644 index 000000000..a9a575bf7 --- /dev/null +++ b/core/item/src/main/kotlin/de/davis/keygo/core/item/domain/model/PasskeyRef.kt @@ -0,0 +1,26 @@ +package de.davis.keygo.core.item.domain.model + +/** + * A login's passkey, as much of it as anything outside the passkey table needs to know. + * + * The credential id is what identifies a passkey, not [rp]. One login can hold two credentials for + * the same relying party, for example two accounts on the same site, so listing or deleting them by + * relying party alone silently treats the two as one. + * + * Carries no key material. It is a handle onto a row, not the row itself. + */ +class PasskeyRef( + val credentialId: ByteArray, + val rp: String, +) { + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other !is PasskeyRef) return false + + return credentialId.contentEquals(other.credentialId) && rp == other.rp + } + + override fun hashCode(): Int = 31 * credentialId.contentHashCode() + rp.hashCode() + + override fun toString(): String = "PasskeyRef(rp=$rp)" +} diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/DomainMapperTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/DomainMapperTest.kt index 4b352f5bd..aeeb19ff6 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/DomainMapperTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/DomainMapperTest.kt @@ -30,7 +30,7 @@ class DomainMapperTest { score = PasswordScore.Strong, ), totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), vaultId = newVaultId(), name = "Test", keyInformation = KeyInformation(wrappedKey = byteArrayOf(), keyNonce = byteArrayOf()), diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/ItemMapperTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/ItemMapperTest.kt index 112a9dbe4..ef5897c42 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/ItemMapperTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/ItemMapperTest.kt @@ -37,7 +37,7 @@ class ItemMapperTest { score = PasswordScore.Strong, ), totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), note = note, pinned = pinned, vaultId = newVaultId(), diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/LoginMapperTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/LoginMapperTest.kt index c5320b08d..897040685 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/LoginMapperTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/mapper/LoginMapperTest.kt @@ -1,28 +1,30 @@ package de.davis.keygo.core.item.data.mapper import de.davis.keygo.core.item.data.local.entity.ItemEntity +import de.davis.keygo.core.item.data.local.entity.KeyInformation as EntityKeyInformation import de.davis.keygo.core.item.data.local.entity.LoginEntity import de.davis.keygo.core.item.data.local.entity.TagEntity +import de.davis.keygo.core.item.data.local.entity.Timestamp as EntityTimestamp import de.davis.keygo.core.item.data.local.entity.credential.PasswordEntity import de.davis.keygo.core.item.data.local.pojo.ItemProjection import de.davis.keygo.core.item.data.local.pojo.LoginProjection +import de.davis.keygo.core.item.data.local.pojo.PasskeyRefPojo import de.davis.keygo.core.item.domain.alias.ItemId import de.davis.keygo.core.item.domain.alias.newItemId import de.davis.keygo.core.item.domain.alias.newVaultId import de.davis.keygo.core.item.domain.model.EncryptedPayload import de.davis.keygo.core.item.domain.model.KeyInformation import de.davis.keygo.core.item.domain.model.Login +import de.davis.keygo.core.item.domain.model.PasskeyRef import de.davis.keygo.core.item.domain.model.PasswordCredential import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.item.domain.model.PasswordSecret import de.davis.keygo.core.item.domain.model.Tag import de.davis.keygo.core.item.domain.model.Timestamp import de.davis.keygo.core.item.generated.domain.model.VaultItemType -import de.davis.keygo.core.item.data.local.entity.Timestamp as EntityTimestamp import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertNull -import de.davis.keygo.core.item.data.local.entity.KeyInformation as EntityKeyInformation class LoginMapperTest { @@ -33,6 +35,30 @@ class LoginMapperTest { assertNull(login.passwordCredential) } + @Test + fun `toDomain keeps both credentials a login holds for one relying party`() { + // Two accounts on the same site are two rows sharing an rp. Mapping them onto the rp alone + // collapsed them into a single entry, so the editor showed one chip for two passkeys and + // deleting it took both. + val projection = baseProjection( + passwordEntity = null, + passkeys = listOf( + PasskeyRefPojo(credentialId = byteArrayOf(1), rp = "example.com"), + PasskeyRefPojo(credentialId = byteArrayOf(2), rp = "example.com"), + ), + ) + + val login = projection.toDomain() + + assertEquals( + setOf( + PasskeyRef(credentialId = byteArrayOf(1), rp = "example.com"), + PasskeyRef(credentialId = byteArrayOf(2), rp = "example.com"), + ), + login.passkeys, + ) + } + @Test fun `Login with null passwordCredential maps to null PasswordEntity`() { val login = baseLogin(passwordCredential = null) @@ -91,6 +117,7 @@ class LoginMapperTest { id: ItemId = newItemId(), passwordEntity: PasswordEntity?, tags: Set = emptySet(), + passkeys: List = emptyList(), ): LoginProjection = LoginProjection( loginEntity = LoginEntity(id = id, username = "alice"), item = ItemProjection( @@ -110,7 +137,7 @@ class LoginMapperTest { tags = tags, ), passwordEntity = passwordEntity, - rpEntity = emptyList(), + passkeys = passkeys, domains = emptyList(), totp = null, ) @@ -123,7 +150,7 @@ class LoginMapperTest { domainInfos = emptySet(), passwordCredential = passwordCredential, totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), vaultId = newVaultId(), name = "Test", keyInformation = KeyInformation(byteArrayOf(), byteArrayOf()), diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImplTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImplTest.kt index b2d5f58fb..e0e284c38 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImplTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/data/repository/LoginRepositoryImplTest.kt @@ -18,12 +18,14 @@ import de.davis.keygo.core.item.domain.alias.newVaultId import de.davis.keygo.core.item.domain.model.EncryptedPayload import de.davis.keygo.core.item.domain.model.KeyInformation import de.davis.keygo.core.item.domain.model.Login +import de.davis.keygo.core.item.domain.model.PasskeyRef import de.davis.keygo.core.item.domain.model.PasswordCredential import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.item.domain.model.PasswordSecret import de.davis.keygo.core.item.domain.model.Tag import de.davis.keygo.core.item.domain.model.Timestamp import de.davis.keygo.core.item.domain.model.Totp +import de.davis.keygo.core.item.passkeyRef import de.davis.keygo.core.util.isFailure import de.davis.keygo.core.util.isSuccess import io.mockk.coEvery @@ -31,12 +33,12 @@ import io.mockk.coVerify import io.mockk.mockk import io.mockk.mockkStatic import io.mockk.unmockkStatic -import kotlinx.coroutines.test.runTest import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertTrue +import kotlinx.coroutines.test.runTest class LoginRepositoryImplTest { @@ -212,25 +214,28 @@ class LoginRepositoryImplTest { } @Test - fun `createOrUpdateLogin drops passkeys whose RP is absent from the login`() = runTest { - val login = testLogin(totpProvider = null, passkeyRPs = setOf("example.org")) + fun `createOrUpdateLogin drops passkeys whose credential is absent from the login`() = runTest { + val kept = passkeyRef("example.org") + val login = testLogin(totpProvider = null, passkeys = setOf(kept)) val result = repository.createOrUpdateLogin(login) assertTrue(result.isSuccess()) - coVerify(exactly = 1) { passkeyDao.deleteRPsNotIn(login.id, setOf("example.org")) } + coVerify(exactly = 1) { + passkeyDao.deleteCredentialsNotIn(login.id, listOf(kept.credentialId)) + } } @Test - fun `createOrUpdateLogin with no passkey RPs drops every passkey the login holds`() = runTest { + fun `createOrUpdateLogin with no passkeys drops every passkey the login holds`() = runTest { // An empty set is how "the last passkey was removed" is expressed. There is no way to - // distinguish it from "unknown", which is why Login.passkeyRPs has no default. + // distinguish it from "unknown", which is why Login.passkeys has no default. val login = testLogin(totpProvider = null) val result = repository.createOrUpdateLogin(login) assertTrue(result.isSuccess()) - coVerify(exactly = 1) { passkeyDao.deleteRPsNotIn(login.id, emptySet()) } + coVerify(exactly = 1) { passkeyDao.deleteCredentialsNotIn(login.id, emptyList()) } } @Test @@ -238,7 +243,7 @@ class LoginRepositoryImplTest { // The delete shares the login's transaction, so a failure rolls the whole write back and // surfaces as a Failure rather than escaping uncaught after the login row has landed. val error = RuntimeException("db error") - coEvery { passkeyDao.deleteRPsNotIn(any(), any()) } throws error + coEvery { passkeyDao.deleteCredentialsNotIn(any(), any()) } throws error val result = repository.createOrUpdateLogin(testLogin(totpProvider = null)) @@ -252,7 +257,7 @@ class LoginRepositoryImplTest { score = PasswordScore.Strong, ), tags: Set = emptySet(), - passkeyRPs: Set = emptySet(), + passkeys: Set = emptySet(), totpProvider: ((ItemId) -> Totp)? = null, ): Login { val id = newItemId() @@ -262,7 +267,7 @@ class LoginRepositoryImplTest { domainInfos = emptySet(), passwordCredential = passwordCredential, totp = totpProvider?.invoke(id), - passkeyRPs = passkeyRPs, + passkeys = passkeys, name = "Test", note = null, pinned = false, diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/model/LoginTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/model/LoginTest.kt index f0395d38b..ffe1b5948 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/model/LoginTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/model/LoginTest.kt @@ -2,6 +2,7 @@ package de.davis.keygo.core.item.domain.model import de.davis.keygo.core.item.domain.alias.newItemId import de.davis.keygo.core.item.domain.alias.newVaultId +import de.davis.keygo.core.item.passkeyRef import kotlin.test.Test import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -51,8 +52,8 @@ class LoginTest { } @Test - fun `hasAnyContent is true when passkeyRPs is non-empty`() { - val login = baseLogin(passkeyRPs = setOf("example.com")) + fun `hasAnyContent is true when passkeys is non-empty`() { + val login = baseLogin(passkeys = setOf(passkeyRef("example.com"))) assertTrue(login.hasAnyContent) } @@ -60,14 +61,14 @@ class LoginTest { username: String? = null, passwordCredential: PasswordCredential? = null, totp: Totp? = null, - passkeyRPs: Set = emptySet(), + passkeys: Set = emptySet(), ): Login = Login( id = newItemId(), username = username, domainInfos = emptySet(), passwordCredential = passwordCredential, totp = totp, - passkeyRPs = passkeyRPs, + passkeys = passkeys, vaultId = newVaultId(), name = "Test", keyInformation = KeyInformation(byteArrayOf(), byteArrayOf()), diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/ObserveAllTagsSortedUseCaseTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/ObserveAllTagsSortedUseCaseTest.kt index 36f8d9148..996fd9b7f 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/ObserveAllTagsSortedUseCaseTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/ObserveAllTagsSortedUseCaseTest.kt @@ -29,7 +29,7 @@ class ObserveAllTagsSortedUseCaseTest { domainInfos = emptySet(), passwordCredential = null, totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), vaultId = newVaultId(), name = name, keyInformation = KeyInformation(byteArrayOf(), byteArrayOf()), diff --git a/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/UpsertItemUseCaseTest.kt b/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/UpsertItemUseCaseTest.kt index 92f5d0050..b8ffb17cd 100644 --- a/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/UpsertItemUseCaseTest.kt +++ b/core/item/src/test/kotlin/de/davis/keygo/core/item/domain/usecase/UpsertItemUseCaseTest.kt @@ -36,7 +36,7 @@ class UpsertItemUseCaseTest { score = PasswordScore.Strong, ), totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), name = name, note = null, pinned = false, diff --git a/core/item/src/testFixtures/kotlin/de/davis/keygo/core/item/PasskeyRefs.kt b/core/item/src/testFixtures/kotlin/de/davis/keygo/core/item/PasskeyRefs.kt new file mode 100644 index 000000000..99845e6e8 --- /dev/null +++ b/core/item/src/testFixtures/kotlin/de/davis/keygo/core/item/PasskeyRefs.kt @@ -0,0 +1,15 @@ +package de.davis.keygo.core.item + +import de.davis.keygo.core.item.domain.model.PasskeyRef + +/** + * A [PasskeyRef] for [rp] with a credential id derived from [discriminator]. + * + * Two calls with the same [rp] and different discriminators produce the two distinct credentials a + * login can hold for one site, which is the case that distinguishes deleting by credential id from + * deleting by relying party. + */ +fun passkeyRef(rp: String, discriminator: String = ""): PasskeyRef = PasskeyRef( + credentialId = "$rp/$discriminator".toByteArray(), + rp = rp, +) diff --git a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/AddRegistrableDomainsToLoginUseCaseTest.kt b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/AddRegistrableDomainsToLoginUseCaseTest.kt index 3270a5591..f211964ce 100644 --- a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/AddRegistrableDomainsToLoginUseCaseTest.kt +++ b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/AddRegistrableDomainsToLoginUseCaseTest.kt @@ -39,7 +39,7 @@ class AddRegistrableDomainsToLoginUseCaseTest { domainInfos = domainInfos, passwordCredential = null, totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), note = null, pinned = false, vaultId = vaultId, diff --git a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/DoesItemHaveDomainReferencesUseCaseTest.kt b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/DoesItemHaveDomainReferencesUseCaseTest.kt index a7cfb9d8e..3f58d2f27 100644 --- a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/DoesItemHaveDomainReferencesUseCaseTest.kt +++ b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/domain/usecase/DoesItemHaveDomainReferencesUseCaseTest.kt @@ -40,7 +40,7 @@ class DoesItemHaveDomainReferencesUseCaseTest { domainInfos = domainInfos, passwordCredential = null, totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), note = null, pinned = false, vaultId = vaultId, diff --git a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/activity/AutofillViewModelTest.kt b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/activity/AutofillViewModelTest.kt index e6b2eb4da..fb8038195 100644 --- a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/activity/AutofillViewModelTest.kt +++ b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/activity/AutofillViewModelTest.kt @@ -143,7 +143,7 @@ internal class AutofillViewModelTest { domainInfos = domainInfos, passwordCredential = null, totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), vaultId = newVaultId(), name = name, keyInformation = KeyInformation(byteArrayOf(), byteArrayOf()), diff --git a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/dataset/SuggestionFinderTest.kt b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/dataset/SuggestionFinderTest.kt index 429fcab72..d0247ccd8 100644 --- a/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/dataset/SuggestionFinderTest.kt +++ b/feature/autofill/src/test/kotlin/de/davis/keygo/feature/autofill/presentation/dataset/SuggestionFinderTest.kt @@ -54,7 +54,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://example.com", eTLD1 = "example.com")), passwordCredential = null, totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), vaultId = vaultId, name = "UserOnly", keyInformation = keyInfo, @@ -68,7 +68,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://example.com", eTLD1 = "example.com")), passwordCredential = minimalPassword, totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), vaultId = vaultId, name = "PassOnly", keyInformation = keyInfo, @@ -82,7 +82,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://example.com", eTLD1 = "example.com")), passwordCredential = minimalPassword, totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), vaultId = vaultId, name = "Both", keyInformation = keyInfo, @@ -96,7 +96,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://other.com", eTLD1 = "other.com")), passwordCredential = null, totp = minimalTotp, - passkeyRPs = emptySet(), + passkeys = emptySet(), vaultId = vaultId, name = "Neither", keyInformation = keyInfo, @@ -200,7 +200,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://example.com", eTLD1 = "example.com")), passwordCredential = null, totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), vaultId = vaultId, name = "Extra1", keyInformation = keyInfo, @@ -214,7 +214,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://example.com", eTLD1 = "example.com")), passwordCredential = null, totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), vaultId = vaultId, name = "Extra2", keyInformation = keyInfo, @@ -228,7 +228,7 @@ internal class SuggestionFinderTest { domainInfos = setOf(DomainInfo(value = "https://example.com", eTLD1 = "example.com")), passwordCredential = null, totp = null, - passkeyRPs = emptySet(), + passkeys = emptySet(), vaultId = vaultId, name = "Extra3", keyInformation = keyInfo, diff --git a/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/BackupTestData.kt b/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/BackupTestData.kt index 3dc1c5b72..e8fac0136 100644 --- a/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/BackupTestData.kt +++ b/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/BackupTestData.kt @@ -10,6 +10,7 @@ import de.davis.keygo.core.item.domain.model.EncryptedPayload import de.davis.keygo.core.item.domain.model.KeyInformation import de.davis.keygo.core.item.domain.model.Login import de.davis.keygo.core.item.domain.model.Passkey +import de.davis.keygo.core.item.domain.model.PasskeyRef import de.davis.keygo.core.item.domain.model.PasskeyUser import de.davis.keygo.core.item.domain.model.PasswordCredential import de.davis.keygo.core.item.domain.model.PasswordScore @@ -61,7 +62,7 @@ fun testLogin( websites: Set = emptySet(), tags: Set = emptySet(), note: String? = null, - passkeyRPs: Set = emptySet(), + passkeys: Set = emptySet(), ) = Login( id = id, vaultId = vaultId, @@ -72,7 +73,7 @@ fun testLogin( PasswordCredential(secret = PasswordSecret(secretPayload(it)), score = PasswordScore.Strong) }, totp = totpSecret?.let { Totp(loginId = id, secret = Totp.Secret(secretPayload(it))) }, - passkeyRPs = passkeyRPs, + passkeys = passkeys, keyInformation = emptyKey, tags = tags.mapNotNull { Tag.of(it) }.toSet(), note = note, diff --git a/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/domain/BackupCollectorTest.kt b/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/domain/BackupCollectorTest.kt index 7d1d4c920..b0d600acc 100644 --- a/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/domain/BackupCollectorTest.kt +++ b/feature/backup/src/test/kotlin/de/davis/keygo/feature/backup/domain/BackupCollectorTest.kt @@ -7,6 +7,7 @@ import de.davis.keygo.core.item.FakePasskeyRepository import de.davis.keygo.core.item.FakeVaultRepository import de.davis.keygo.core.item.domain.alias.newItemId import de.davis.keygo.core.item.domain.model.Vault +import de.davis.keygo.core.item.passkeyRef import de.davis.keygo.core.security.crypto.FakeCryptographicScopeProvider import de.davis.keygo.core.security.crypto.FakeCryptographicScopeProviderFactory import de.davis.keygo.core.security.crypto.FakeKeyStoreManager @@ -20,9 +21,6 @@ import de.davis.keygo.feature.backup.testCard import de.davis.keygo.feature.backup.testLogin import de.davis.keygo.feature.backup.testPasskey import de.davis.keygo.feature.backup.testVault -import kotlinx.coroutines.Dispatchers -import kotlinx.coroutines.runBlocking -import kotlinx.coroutines.test.runTest import java.time.YearMonth import java.util.concurrent.CopyOnWriteArrayList import kotlin.test.Test @@ -30,6 +28,9 @@ import kotlin.test.assertEquals import kotlin.test.assertIs import kotlin.test.assertNotNull import kotlin.test.assertTrue +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.runBlocking +import kotlinx.coroutines.test.runTest class BackupCollectorTest { @@ -258,7 +259,7 @@ class BackupCollectorTest { vaultId = vault.id, id = loginId, name = "Email", - passkeyRPs = setOf("example.com", "example.org"), + passkeys = setOf(passkeyRef("example.com"), passkeyRef("example.org")), ) ) passkeyRepo.seed( @@ -287,11 +288,11 @@ class BackupCollectorTest { } @Test - fun `passkeys are exported even when the login's passkeyRPs set is empty`() = runTest { + fun `passkeys are exported even when the login's passkeys set is empty`() = runTest { val vault = testVault(name = "Personal") vaultRepo.seed(vault) val loginId = newItemId() - // passkeyRPs deliberately left empty (default) - the table is the source of truth. + // passkeys deliberately left empty (default) - the table is the source of truth. loginRepo.seed(testLogin(vaultId = vault.id, id = loginId, name = "Email")) passkeyRepo.seed(testPasskey(loginId = loginId, rp = "example.com", privateKey = "pk-one")) diff --git a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/model/UpsertLogin.kt b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/model/UpsertLogin.kt index 5b96ca4d6..dc6ed900a 100644 --- a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/model/UpsertLogin.kt +++ b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/model/UpsertLogin.kt @@ -3,6 +3,7 @@ package de.davis.keygo.feature.item.core.domain.model import de.davis.keygo.core.item.domain.alias.ItemId import de.davis.keygo.core.item.domain.alias.VaultId import de.davis.keygo.core.item.domain.model.DomainInfo +import de.davis.keygo.core.item.domain.model.PasskeyRef import de.davis.keygo.core.item.domain.model.Tag @ConsistentCopyVisibility @@ -15,7 +16,7 @@ data class UpsertLogin private constructor( val domains: FieldUpdate>, override val tags: FieldUpdate>, override val note: FieldUpdate, - val removedPasskeyRPs: Set, + val removedPasskeys: Set, val pendingPasskey: Boolean, ) : UpsertItem { companion object { @@ -39,7 +40,7 @@ data class UpsertLogin private constructor( domains = if (domains.isNotEmpty()) FieldUpdate.Set(domains) else FieldUpdate.Clear, tags = if (tags.isNotEmpty()) FieldUpdate.Set(tags) else FieldUpdate.Clear, // A brand-new login holds no passkeys, so there is nothing to remove. - removedPasskeyRPs = emptySet(), + removedPasskeys = emptySet(), pendingPasskey = pendingPasskey, ) @@ -53,7 +54,7 @@ data class UpsertLogin private constructor( domains: FieldUpdate> = keep(), tags: FieldUpdate> = keep(), note: FieldUpdate = keep(), - removedPasskeyRPs: Set = emptySet(), + removedPasskeys: Set = emptySet(), pendingPasskey: Boolean = false, ) = UpsertLogin( upsertType = UpsertType.Update(itemId, vaultId), @@ -64,7 +65,7 @@ data class UpsertLogin private constructor( tags = tags, username = username, domains = domains, - removedPasskeyRPs = removedPasskeyRPs, + removedPasskeys = removedPasskeys, pendingPasskey = pendingPasskey, ) } diff --git a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCase.kt b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCase.kt index 59b4403fb..1a12afbbb 100644 --- a/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCase.kt +++ b/feature/item/core/src/main/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCase.kt @@ -102,7 +102,7 @@ class CreateNewOrUpdateLoginUseCase( passwordCredential = newPasswordCredential, totp = totp?.await(), // A pending passkey is written by its own flow once this id exists. - passkeyRPs = emptySet(), + passkeys = emptySet(), note = upsert.note.getValue(), pinned = false, keyInformation = keyInformation, @@ -137,7 +137,7 @@ class CreateNewOrUpdateLoginUseCase( totp = upsert.totpUriOrSecret.on(existing.totp, totp), // Resolved against what the table holds now, not against what the caller last saw, so // a passkey attached from elsewhere since then survives this save. - passkeyRPs = existing.passkeyRPs - upsert.removedPasskeyRPs, + passkeys = existing.passkeys - upsert.removedPasskeys, note = upsert.note.on(existing.note), ) } diff --git a/feature/item/core/src/test/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCaseTest.kt b/feature/item/core/src/test/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCaseTest.kt index feea136e0..08838a2e8 100644 --- a/feature/item/core/src/test/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCaseTest.kt +++ b/feature/item/core/src/test/kotlin/de/davis/keygo/feature/item/core/domain/usecase/CreateNewOrUpdateLoginUseCaseTest.kt @@ -11,6 +11,7 @@ import de.davis.keygo.core.item.domain.alias.newVaultId import de.davis.keygo.core.item.domain.model.EncryptedPayload import de.davis.keygo.core.item.domain.model.KeyInformation import de.davis.keygo.core.item.domain.model.Login +import de.davis.keygo.core.item.domain.model.PasskeyRef import de.davis.keygo.core.item.domain.model.PasswordCredential import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.item.domain.model.PasswordSecret @@ -18,6 +19,7 @@ import de.davis.keygo.core.item.domain.model.Timestamp import de.davis.keygo.core.item.domain.model.Totp import de.davis.keygo.core.item.domain.model.Vault import de.davis.keygo.core.item.domain.usecase.UpsertVaultItemUseCase +import de.davis.keygo.core.item.passkeyRef import de.davis.keygo.core.security.crypto.FakeCryptographicScopeProvider import de.davis.keygo.core.security.domain.crypto.CryptographicScopeProvider import de.davis.keygo.core.util.Result @@ -32,8 +34,6 @@ import de.davis.keygo.rust.FakeTotpService import de.davis.keygo.rust.totp.TotpService import de.davisalessandro.keygo.rust.Algorithm import de.davisalessandro.keygo.rust.TotpInfo -import kotlinx.coroutines.test.runTest -import kotlin.time.Clock import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertContains @@ -44,6 +44,8 @@ import kotlin.test.assertIs import kotlin.test.assertNotNull import kotlin.test.assertNull import kotlin.test.assertTrue +import kotlin.time.Clock +import kotlinx.coroutines.test.runTest class CreateNewOrUpdateLoginUseCaseTest { @@ -137,27 +139,47 @@ class CreateNewOrUpdateLoginUseCaseTest { assertTrue(result.isSuccess()) } - // The use case does not touch the passkey table: it resolves the login's effective relying - // parties, and LoginRepository drops the rows that fall outside that set as part of the same - // write. These assert the resolved set; LoginRepositoryImplTest covers the deletion itself. + // The use case does not touch the passkey table: it resolves the login's effective credentials, + // and LoginRepository drops the rows that fall outside that set as part of the same write. + // These assert the resolved set; LoginRepositoryImplTest covers the deletion itself. @Test fun `update deleting a passkey drops it from the saved login`() = runTest { - val existing = testLogin(passkeyRPs = setOf("example.com", "example.org")) + val removed = passkeyRef("example.com") + val kept = passkeyRef("example.org") + val existing = testLogin(passkeys = setOf(removed, kept)) loginRepository.seed(existing) val result = useCase( UpsertLogin.update( itemId = existing.id, - removedPasskeyRPs = setOf("example.com"), + removedPasskeys = setOf(removed), ) ) assertTrue(result.isSuccess()) - assertEquals( - setOf("example.org"), - loginRepository.getLoginById(existing.id)?.passkeyRPs, + assertEquals(setOf(kept), loginRepository.getLoginById(existing.id)?.passkeys) + } + + @Test + fun `update deleting one of two passkeys for the same RP keeps the other`() = runTest { + // Two accounts on one site are two credentials sharing an rp. Removals key on the + // credential id, so dropping one leaves the other in place; keying on the rp would take + // both while the dialog only ever spoke about one. + val removed = passkeyRef("example.com", discriminator = "first") + val kept = passkeyRef("example.com", discriminator = "second") + val existing = testLogin(passkeys = setOf(removed, kept)) + loginRepository.seed(existing) + + val result = useCase( + UpsertLogin.update( + itemId = existing.id, + removedPasskeys = setOf(removed), + ) ) + + assertTrue(result.isSuccess()) + assertEquals(setOf(kept), loginRepository.getLoginById(existing.id)?.passkeys) } @Test @@ -165,14 +187,14 @@ class CreateNewOrUpdateLoginUseCaseTest { val existing = testLogin( username = null, passwordCredential = null, - passkeyRPs = setOf("example.com"), + passkeys = setOf(passkeyRef("example.com")), ) loginRepository.seed(existing) val result = useCase( UpsertLogin.update( itemId = existing.id, - removedPasskeyRPs = setOf("example.com"), + removedPasskeys = setOf(passkeyRef("example.com")), ) ) @@ -187,21 +209,19 @@ class CreateNewOrUpdateLoginUseCaseTest { // delta for exactly this reason: the effective set is resolved against a fresh read here, // so a passkey the form never saw is not in the delta and stays. The table below holds // both; the form that produced this delta only ever saw "example.com". - val existing = testLogin(passkeyRPs = setOf("example.com", "attached-later.example")) + val attachedLater = passkeyRef("attached-later.example") + val existing = testLogin(passkeys = setOf(passkeyRef("example.com"), attachedLater)) loginRepository.seed(existing) val result = useCase( UpsertLogin.update( itemId = existing.id, - removedPasskeyRPs = setOf("example.com"), + removedPasskeys = setOf(passkeyRef("example.com")), ) ) assertTrue(result.isSuccess()) - assertEquals( - setOf("attached-later.example"), - loginRepository.getLoginById(existing.id)?.passkeyRPs, - ) + assertEquals(setOf(attachedLater), loginRepository.getLoginById(existing.id)?.passkeys) } @Test @@ -209,36 +229,39 @@ class CreateNewOrUpdateLoginUseCaseTest { val existing = testLogin( username = null, passwordCredential = null, - passkeyRPs = setOf("example.com"), + passkeys = setOf(passkeyRef("example.com")), ) loginRepository.seed(existing) useCase( UpsertLogin.update( itemId = existing.id, - removedPasskeyRPs = setOf("example.com"), + removedPasskeys = setOf(passkeyRef("example.com")), ) ) // Validation runs before the write, so the stored login still holds the passkey and the // repository never gets the chance to delete its row. - assertEquals(setOf("example.com"), loginRepository.getLoginById(existing.id)?.passkeyRPs) + assertEquals( + setOf(passkeyRef("example.com")), + loginRepository.getLoginById(existing.id)?.passkeys, + ) } @Test fun `update deleting the only passkey while a password remains returns Success`() = runTest { - val existing = testLogin(passkeyRPs = setOf("example.com")) + val existing = testLogin(passkeys = setOf(passkeyRef("example.com"))) loginRepository.seed(existing) val result = useCase( UpsertLogin.update( itemId = existing.id, - removedPasskeyRPs = setOf("example.com"), + removedPasskeys = setOf(passkeyRef("example.com")), ) ) assertTrue(result.isSuccess()) - assertTrue(loginRepository.getLoginById(existing.id)?.passkeyRPs.orEmpty().isEmpty()) + assertTrue(loginRepository.getLoginById(existing.id)?.passkeys.orEmpty().isEmpty()) } @Test @@ -246,19 +269,19 @@ class CreateNewOrUpdateLoginUseCaseTest { // Not reachable from the UI today: the passkey activity only opens the editor on a new // login, which holds no passkeys to remove. A guard against the two ever being treated as // alternatives again if that flow gains an "edit existing" entry point. - val existing = testLogin(passkeyRPs = setOf("old.example")) + val existing = testLogin(passkeys = setOf(passkeyRef("old.example"))) loginRepository.seed(existing) val result = useCase( UpsertLogin.update( itemId = existing.id, - removedPasskeyRPs = setOf("old.example"), + removedPasskeys = setOf(passkeyRef("old.example")), pendingPasskey = true, ) ) assertTrue(result.isSuccess()) - assertTrue(loginRepository.getLoginById(existing.id)?.passkeyRPs.orEmpty().isEmpty()) + assertTrue(loginRepository.getLoginById(existing.id)?.passkeys.orEmpty().isEmpty()) } @Test @@ -965,7 +988,7 @@ class CreateNewOrUpdateLoginUseCaseTest { ), totp: Totp? = null, timestamp: Timestamp = Timestamp(), - passkeyRPs: Set = emptySet(), + passkeys: Set = emptySet(), ) = Login( id = newItemId(), name = name, @@ -973,7 +996,7 @@ class CreateNewOrUpdateLoginUseCaseTest { domainInfos = emptySet(), passwordCredential = passwordCredential, totp = totp, - passkeyRPs = passkeyRPs, + passkeys = passkeys, note = null, pinned = false, vaultId = defaultVault.id, diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/component/DeletePasskeyDialog.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/component/DeletePasskeyDialog.kt index a84dc8d07..655c966a0 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/component/DeletePasskeyDialog.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/component/DeletePasskeyDialog.kt @@ -11,6 +11,7 @@ import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview +import de.davis.keygo.core.item.domain.model.PasskeyRef import de.davis.keygo.core.ui.text.htmlStringResource import de.davis.keygo.core.ui.theme.KeyGoTheme import de.davis.keygo.feature.item.create.R @@ -48,7 +49,7 @@ fun DeletePasskeyDialog( }, text = { Text( - text = htmlStringResource(R.string.delete_passkey_warning, state.rpId) + text = htmlStringResource(R.string.delete_passkey_warning, state.passkey.rp) ) }, ) @@ -59,7 +60,9 @@ fun DeletePasskeyDialog( private fun DeletePasskeyDialogPreview() { KeyGoTheme { DeletePasskeyDialog( - state = DialogState.DeletePasskey(rpId = "example.com"), + state = DialogState.DeletePasskey( + passkey = PasskeyRef(credentialId = byteArrayOf(1), rp = "example.com"), + ), onConfirmDeletion = {}, onDismissRequest = {}, ) diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginContent.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginContent.kt index 5be3cf855..9af37217b 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginContent.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginContent.kt @@ -39,6 +39,7 @@ import androidx.compose.ui.unit.dp import de.davis.keygo.core.item.domain.alias.newItemId import de.davis.keygo.core.item.domain.alias.newVaultId import de.davis.keygo.core.item.domain.model.DomainInfo +import de.davis.keygo.core.item.domain.model.PasskeyRef import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.item.domain.model.Tag import de.davis.keygo.core.item.domain.model.Vault @@ -159,7 +160,7 @@ private fun LoginReadyContent( onTagSubmitted = { onEvent(LoginUiEvent.ItemUi(ItemUiEvent.OnAddTags(it))) }, onDeleteTag = { onEvent(LoginUiEvent.ItemUi(ItemUiEvent.OnRemoveTag(it))) }, ) { - if (state.passkeyRPs.isNotEmpty()) item(key = "passkey_information") { + if (state.passkeys.isNotEmpty()) item(key = "passkey_information") { FormGroup( title = stringResource(R.string.passkey_information), modifier = Modifier, @@ -169,12 +170,14 @@ private fun LoginReadyContent( horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { - state.passkeyRPs.forEach { passkeyInfo -> + state.passkeys.forEach { passkeyInfo -> key(passkeyInfo) { MenuChip( chipText = passkeyInfo.rpId, onDeleteClick = { - onEvent(LoginUiEvent.OnDeletePasskeyRequest(passkeyInfo.rpId)) + passkeyInfo.ref?.let { + onEvent(LoginUiEvent.OnDeletePasskeyRequest(it)) + } }, enabled = !passkeyInfo.pending ) @@ -376,9 +379,16 @@ private fun LoginContentPreview() { eTLD1 = "example.com", ), ), - passkeyRPs = setOf( - LoginPasskeyInfo(rpId = "example.com", pending = false), - LoginPasskeyInfo(rpId = "example.org", pending = true), + passkeys = setOf( + LoginPasskeyInfo( + rpId = "example.com", + ref = PasskeyRef(byteArrayOf(1), "example.com"), + ), + LoginPasskeyInfo( + rpId = "example.com", + ref = PasskeyRef(byteArrayOf(2), "example.com"), + ), + LoginPasskeyInfo(rpId = "example.org", ref = null), ), ), shared = SharedItemState( diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt index 89c220f84..b52b8ae67 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginViewModel.kt @@ -124,7 +124,9 @@ internal class LoginViewModel( */ fun setPendingPasskeyCount(rp: String?) { if (rp.isNullOrBlank()) return - _base.update { it.copy(passkeyRPs = it.passkeyRPs + setOf(LoginPasskeyInfo(rp, true))) } + _base.update { + it.copy(passkeys = it.passkeys + LoginPasskeyInfo(rpId = rp, ref = null)) + } } fun init(information: DetailPaneInformation) { @@ -202,13 +204,13 @@ internal class LoginViewModel( totpTextFieldState = TextFieldState(decrypted.second ?: ""), usernameTextFieldState = TextFieldState(login.username ?: ""), domains = login.domainInfos, - passkeyRPs = login.passkeyRPs.mapTo(mutableSetOf()) { rp -> + passkeys = login.passkeys.mapTo(mutableSetOf()) { passkey -> LoginPasskeyInfo( - rpId = rp, - pending = false, + rpId = passkey.rp, + ref = passkey, ) }, - deletedPasskeyRPs = emptySet(), + deletedPasskeys = emptySet(), dialogState = DialogState.None, updating = true, ) @@ -254,7 +256,7 @@ internal class LoginViewModel( val assignedTags = ready.shared.itemAssignedTags val selectedVaultId = ready.shared.vaultsState.selectedVaultId // Independent: a save can both register a passkey and drop another one. - val pendingPasskey = base.passkeyRPs.any { it.pending } + val pendingPasskey = base.passkeys.any { it.pending } viewModelScope.launch { val upsert = itemId?.let { itemId -> UpsertLogin.update( @@ -267,7 +269,7 @@ internal class LoginViewModel( password = fieldUpdate(base.passwordTextFieldState.text.toString()), totpUriOrSecret = fieldUpdate(base.totpTextFieldState.text.toString()), note = fieldUpdate(notesTextFieldState.text.toString()), - removedPasskeyRPs = base.deletedPasskeyRPs, + removedPasskeys = base.deletedPasskeys, pendingPasskey = pendingPasskey, ) } ?: UpsertLogin.create( @@ -419,7 +421,7 @@ internal class LoginViewModel( is LoginUiEvent.OnDeletePasskeyRequest -> { _base.update { - it.copy(dialogState = DialogState.DeletePasskey(rpId = event.rpId)) + it.copy(dialogState = DialogState.DeletePasskey(passkey = event.passkey)) } } @@ -432,12 +434,10 @@ internal class LoginViewModel( _base.update { it.copy( - passkeyRPs = it.passkeyRPs - .filterNot { passkey -> - passkey.rpId == dialogState.rpId && !passkey.pending - } + passkeys = it.passkeys + .filterNot { passkey -> passkey.ref == dialogState.passkey } .toSet(), - deletedPasskeyRPs = it.deletedPasskeyRPs + dialogState.rpId, + deletedPasskeys = it.deletedPasskeys + dialogState.passkey, dialogState = DialogState.None, ) } diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/DialogState.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/DialogState.kt index f0048f35f..2c008e25e 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/DialogState.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/DialogState.kt @@ -1,5 +1,6 @@ package de.davis.keygo.feature.item.create.presentation.login.model +import de.davis.keygo.core.item.domain.model.PasskeyRef import de.davis.keygo.core.item.domain.model.lite.LiteLogin sealed interface DialogState { @@ -8,5 +9,5 @@ sealed interface DialogState { data class SelectItemForModification(val items: List) : DialogState data class OverrideTotp(val fields: Set) : DialogState - data class DeletePasskey(val rpId: String) : DialogState + data class DeletePasskey(val passkey: PasskeyRef) : DialogState } diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiEvent.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiEvent.kt index 70573c8f5..9e868b8ed 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiEvent.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiEvent.kt @@ -1,6 +1,7 @@ package de.davis.keygo.feature.item.create.presentation.login.model import de.davis.keygo.core.item.domain.alias.ItemId +import de.davis.keygo.core.item.domain.model.PasskeyRef import de.davis.keygo.feature.item.core.presentation.login.model.FieldType import de.davis.keygo.feature.item.create.presentation.model.ItemUiEvent @@ -11,7 +12,7 @@ internal sealed interface LoginUiEvent { data object OnCloseBottomSheet : LoginUiEvent data object OnScanCodeRequest : LoginUiEvent - data class OnDeletePasskeyRequest(val rpId: String) : LoginUiEvent + data class OnDeletePasskeyRequest(val passkey: PasskeyRef) : LoginUiEvent data object OnConfirmPasskeyDeletion : LoginUiEvent data object OnPasskeyDeletionDismiss : LoginUiEvent diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiState.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiState.kt index 5d63db619..9c75a64ce 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiState.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/model/LoginUiState.kt @@ -3,16 +3,27 @@ package de.davis.keygo.feature.item.create.presentation.login.model import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.runtime.Stable import de.davis.keygo.core.item.domain.model.DomainInfo +import de.davis.keygo.core.item.domain.model.PasskeyRef import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.feature.item.core.presentation.model.InputFieldError import de.davis.keygo.feature.item.create.presentation.model.ItemUiState internal typealias LoginUiState = ItemUiState +/** + * One passkey chip. There is one per credential, not per relying party: a login can hold two + * credentials for the same site and the user has to be able to tell them apart and drop one. + * + * [ref] is null while the passkey activity is still registering, because a credential id only + * exists once the item it belongs to does. + */ internal data class LoginPasskeyInfo( val rpId: String, - val pending: Boolean, -) + val ref: PasskeyRef?, +) { + val pending: Boolean + get() = ref == null +} @Stable internal data class LoginBaseState( @@ -20,8 +31,8 @@ internal data class LoginBaseState( val totpTextFieldState: TextFieldState = TextFieldState(), val usernameTextFieldState: TextFieldState = TextFieldState(), val domains: Set = emptySet(), - val passkeyRPs: Set = emptySet(), - val deletedPasskeyRPs: Set = emptySet(), + val passkeys: Set = emptySet(), + val deletedPasskeys: Set = emptySet(), val strengthScore: PasswordScore = PasswordScore.None, val generatePasswordBottomSheetVisible: Boolean = false, val dialogState: DialogState = DialogState.None, @@ -29,11 +40,19 @@ internal data class LoginBaseState( val scanning: Boolean = false, val updating: Boolean = false, ) { + /** + * Whether the form holds anything worth saving. + * + * A pending passkey deletion deliberately does not count. A login whose last passkey is gone + * holds nothing, and there is no reason to keep it, so Save stays disabled exactly as it does + * when the last password or TOTP secret is cleared. Leaving the screen without saving keeps the + * passkey. + */ val hasAnyContent: Boolean get() = passwordTextFieldState.text.isNotBlank() || totpTextFieldState.text.isNotBlank() || usernameTextFieldState.text.isNotBlank() - || passkeyRPs.isNotEmpty() + || passkeys.isNotEmpty() fun canSave(name: CharSequence): Boolean = name.isNotBlank() && hasAnyContent } diff --git a/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/ViewLoginContent.kt b/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/ViewLoginContent.kt index c643416f6..89ae7a34d 100644 --- a/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/ViewLoginContent.kt +++ b/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/ViewLoginContent.kt @@ -548,7 +548,7 @@ private fun ViewLoginContentPreview() { ViewLoginContent( state = ViewLoginState( name = "Login 1", - passkeyRPs = setOf("example.com", "example.org"), + passkeyRPs = listOf("example.com", "example.org"), password = ObfuscatedString("Password"), passwordStrengthScore = PasswordScore.Ridiculous, totpState = TotpState.HasTotp( diff --git a/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/ViewLoginViewModel.kt b/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/ViewLoginViewModel.kt index cab65063b..06a557900 100644 --- a/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/ViewLoginViewModel.kt +++ b/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/ViewLoginViewModel.kt @@ -104,7 +104,7 @@ internal class ViewLoginViewModel( ViewLoginState( name = login.name, vaultMetadata = vaultMetadata, - passkeyRPs = login.passkeyRPs, + passkeyRPs = login.passkeys.map { it.rp }, password = obfuscated, passwordStrengthScore = login.passwordCredential?.score, username = login.username.orEmpty(), diff --git a/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/model/ViewLoginState.kt b/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/model/ViewLoginState.kt index 1435de40d..e768dc83e 100644 --- a/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/model/ViewLoginState.kt +++ b/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/model/ViewLoginState.kt @@ -10,7 +10,8 @@ import de.davis.keygo.core.item.domain.model.VaultMetadata data class ViewLoginState( val name: String = "", val vaultMetadata: VaultMetadata? = null, - val passkeyRPs: Set = emptySet(), + /** One entry per credential, so two passkeys for the same site both show. */ + val passkeyRPs: List = emptyList(), val password: ObfuscatedString? = null, val passwordStrengthScore: PasswordScore? = null, val totpState: TotpState = TotpState.NoTotp, diff --git a/feature/vault/src/test/kotlin/de/davis/keygo/feature/vault/domain/usecase/MoveItemsToVaultUseCaseTest.kt b/feature/vault/src/test/kotlin/de/davis/keygo/feature/vault/domain/usecase/MoveItemsToVaultUseCaseTest.kt index c561cee90..fc1cde566 100644 --- a/feature/vault/src/test/kotlin/de/davis/keygo/feature/vault/domain/usecase/MoveItemsToVaultUseCaseTest.kt +++ b/feature/vault/src/test/kotlin/de/davis/keygo/feature/vault/domain/usecase/MoveItemsToVaultUseCaseTest.kt @@ -367,7 +367,7 @@ class MoveItemsToVaultUseCaseTest { totp = totpPlaintext?.let { Totp(loginId = id, secret = Totp.Secret.encrypt(it)) }, - passkeyRPs = emptySet(), + passkeys = emptySet(), note = note, pinned = pinned, vaultId = vault.id, diff --git a/migration/legacy-data/src/main/kotlin/de/davis/keygo/migration/legacy_data/domain/mapper/LegacyItemConverter.kt b/migration/legacy-data/src/main/kotlin/de/davis/keygo/migration/legacy_data/domain/mapper/LegacyItemConverter.kt index 9ac5fa5ef..2ebf818e4 100644 --- a/migration/legacy-data/src/main/kotlin/de/davis/keygo/migration/legacy_data/domain/mapper/LegacyItemConverter.kt +++ b/migration/legacy-data/src/main/kotlin/de/davis/keygo/migration/legacy_data/domain/mapper/LegacyItemConverter.kt @@ -88,7 +88,7 @@ internal class LegacyItemConverter( passwordCredential = credential, totp = null, // The legacy database had no passkeys, and these are freshly minted ids. - passkeyRPs = emptySet(), + passkeys = emptySet(), vaultId = vaultId, name = item.title, keyInformation = keyInformation,