diff --git a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt index 83f26930f1..751a14c8ae 100644 --- a/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/WatchOnlyAccountRepo.kt @@ -64,18 +64,34 @@ class WatchOnlyAccountRepo @Inject constructor( } val currentWalletAccountCount: Flow = currentWalletAccounts.map { it.size } - suspend fun prepareUnsignedClaim(authUrl: String, name: String): PreparedWatchOnlyAccountClaim = + /** + * Prepares the claim for a Paykit server approval. With [reuseAccountId] the claim shares that active account + * of the current wallet again instead of reserving a new one; the user picks it when re-approving a server. + */ + suspend fun prepareUnsignedClaim( + authUrl: String, + name: String, + reuseAccountId: String? = null, + ): PreparedWatchOnlyAccountClaim = withContext(bgDispatcher) { lifecycleCoordinator.withLock { - val normalizedName = normalizeName(name) val walletIndex = lightningService.currentWalletIndex val fingerprint = requestFingerprint(authUrl) val current = store.load() - current.firstOrNull { - it.walletIndex == walletIndex && - it.requestFingerprint == fingerprint && - it.setupState != WatchOnlyAccountSetupState.Active - }?.let { existing -> + val incomplete = current.incompleteSetup(walletIndex, fingerprint) + if (reuseAccountId != null && incomplete == null) { + val reused = current.firstOrNull { + it.id == reuseAccountId && + it.walletIndex == walletIndex && + it.setupState == WatchOnlyAccountSetupState.Active + } ?: throw WatchOnlyAccountError.AuthorizationAccountMissing() + return@withLock PreparedWatchOnlyAccountClaim( + account = reused, + payload = WatchOnlyAccountClaimCodec.encode(reused, xpubSerializer::serialize), + ) + } + val normalizedName = normalizeName(name) + incomplete?.let { existing -> val refreshed = existing.copy(name = normalizedName) if (refreshed != existing) { store.save(current.map { if (it.id == existing.id) refreshed else it }) @@ -200,18 +216,43 @@ class WatchOnlyAccountRepo @Inject constructor( val account = current.firstOrNull { it.id == id } ?: return@withLock if (account.setupState != WatchOnlyAccountSetupState.Active) return@withLock if (account.isTrackingEnabled == enabled) return@withLock + saveTracking(current, account, enabled) + } + } - setAccountTracking(account, enabled) - val saveResult = runSuspendCatching { - store.save(current.map { if (it.id == id) it.copy(isTrackingEnabled = enabled) else it }) - } - saveResult.onFailure { - runSuspendCatching { setAccountTracking(account, enabled = !enabled) } + /** Tracks a reused account before its claim is sent, failing when it is no longer active on this wallet. */ + suspend fun trackReusedAccount(id: String) = withContext(NonCancellable) { + lifecycleCoordinator.withLock { + val current = store.load() + val account = current.firstOrNull { + it.id == id && + it.walletIndex == lightningService.currentWalletIndex && + it.setupState == WatchOnlyAccountSetupState.Active + } ?: throw WatchOnlyAccountError.AuthorizationAccountMissing() + // The store can say tracked while the node lost the account, so the node is always asked to track it. + if (account.isTrackingEnabled) { + setAccountTracking(account, enabled = true) + } else { + saveTracking(current, account, enabled = true) } - saveResult.getOrThrow() } } + private suspend fun saveTracking( + current: List, + account: WatchOnlyAccountRecord, + enabled: Boolean, + ) { + setAccountTracking(account, enabled) + val saveResult = runSuspendCatching { + store.save(current.map { if (it.id == account.id) it.copy(isTrackingEnabled = enabled) else it }) + } + saveResult.onFailure { + runSuspendCatching { setAccountTracking(account, enabled = !enabled) } + } + saveResult.getOrThrow() + } + suspend fun restore( accounts: List?, allocationState: WatchOnlyAccountAllocationState? = null, @@ -297,6 +338,17 @@ class WatchOnlyAccountRepo @Inject constructor( } } + /** Whether this request already has an account whose setup has not finished; approving it resumes that account. */ + suspend fun hasIncompleteSetup(authUrl: String): Boolean = withContext(bgDispatcher) { + store.load().incompleteSetup(lightningService.currentWalletIndex, requestFingerprint(authUrl)) != null + } + + private fun List.incompleteSetup(walletIndex: Int, fingerprint: String) = firstOrNull { + it.walletIndex == walletIndex && + it.requestFingerprint == fingerprint && + it.setupState != WatchOnlyAccountSetupState.Active + } + private fun normalizeName(name: String): String { val normalized = name.trim() if (normalized.isEmpty() || normalized.length > MAX_NAME_LENGTH) { diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt index 3621d40178..2d0b3e88dd 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalSheet.kt @@ -40,6 +40,8 @@ import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.semantics.Role import androidx.compose.ui.semantics.clearAndSetSemantics +import androidx.compose.ui.semantics.selected +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.tooling.preview.Preview import androidx.compose.ui.unit.dp @@ -52,6 +54,9 @@ import to.bitkit.models.PubkyAuthClaim import to.bitkit.models.PubkyAuthClaim.Item import to.bitkit.models.PubkyAuthPermission import to.bitkit.models.PubkyProfile +import to.bitkit.models.WATCH_ONLY_ACCOUNT_NATIVE_SEGWIT_ADDRESS_TYPE +import to.bitkit.models.WatchOnlyAccountRecord +import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.ui.appViewModel import to.bitkit.ui.components.AuthCheckView import to.bitkit.ui.components.BiometricsView @@ -71,6 +76,8 @@ import to.bitkit.ui.components.SecondaryButton import to.bitkit.ui.components.SheetSize import to.bitkit.ui.components.Text13Up import to.bitkit.ui.components.VerticalSpacer +import to.bitkit.ui.components.settings.SettingsButtonRow +import to.bitkit.ui.components.settings.SettingsButtonValue import to.bitkit.ui.scaffold.SheetTopBar import to.bitkit.ui.settingsViewModel import to.bitkit.ui.shared.modifiers.sheetHeight @@ -106,9 +113,11 @@ fun PubkyAuthApprovalSheet( onApproveWatchOnly = { if (uiState.authUrl == authUrl) viewModel.approveWatchOnlyConsent(authUrl) }, - onBackToWatchOnly = { - if (uiState.authUrl == authUrl) viewModel.returnToWatchOnlyConsent(authUrl) + onBack = { + if (uiState.authUrl == authUrl) viewModel.returnToPreviousStep(authUrl) }, + onSelectAccount = { viewModel.selectAccount(authUrl, it) }, + onConfirmAccount = { viewModel.confirmAccountChoice(authUrl) }, onRetryUsdt = { viewModel.loadUsdtAddress(authUrl) }, onShareUsdt = viewModel::setShareUsdt, onCancel = { viewModel.dismiss() }, @@ -222,18 +231,20 @@ private fun Content( isCurrentRequest: Boolean, onAuthorize: () -> Unit, onApproveWatchOnly: () -> Unit, - onBackToWatchOnly: () -> Unit, + onBack: () -> Unit, onCancel: () -> Unit, onDismiss: () -> Unit, onRetryUsdt: () -> Unit = {}, onShareUsdt: (Boolean) -> Unit = {}, + onSelectAccount: (String?) -> Unit = {}, + onConfirmAccount: () -> Unit = {}, ) { val approvalState = if (isCurrentRequest) uiState.state else ApprovalState.Loading val headerTitle = approvalHeaderTitle(approvalState) - val onBack = approvalBackAction( + val onBackAction = approvalBackAction( approvalState = approvalState, showsReceivingDetails = uiState.showsReceivingDetails, - onBackToWatchOnly = onBackToWatchOnly, + onBack = onBack, onCancel = onCancel, onDismiss = onDismiss, ) @@ -247,7 +258,7 @@ private fun Content( ) { SheetTopBar( titleText = headerTitle, - onBack = onBack, + onBack = onBackAction, titleStyle = if (approvalState == ApprovalState.WatchOnlyConsent) { AppTextStyles.Subtitle.copy(letterSpacing = 0.sp, lineHeight = 22.sp) } else { @@ -264,6 +275,12 @@ private fun Content( onApprove = onApproveWatchOnly, onCancel = onCancel, ) + ApprovalState.ChooseAccount -> ChooseAccountContent( + uiState = uiState, + onSelect = onSelectAccount, + onContinue = onConfirmAccount, + onCancel = onCancel, + ) ApprovalState.Authorize -> AuthorizeContent( uiState = uiState, onAuthorize = onAuthorize, @@ -283,6 +300,7 @@ private fun Content( @Composable private fun approvalHeaderTitle(approvalState: ApprovalState): String = when (approvalState) { ApprovalState.WatchOnlyConsent -> stringResource(R.string.profile__auth_approval_watch_only_intro_nav_title) + ApprovalState.ChooseAccount -> stringResource(R.string.profile__auth_approval_account_nav_title) ApprovalState.Success -> stringResource(R.string.profile__auth_approval_success) else -> stringResource(R.string.profile__auth_approval_title) } @@ -290,11 +308,12 @@ private fun approvalHeaderTitle(approvalState: ApprovalState): String = when (ap private fun approvalBackAction( approvalState: ApprovalState, showsReceivingDetails: Boolean, - onBackToWatchOnly: () -> Unit, + onBack: () -> Unit, onCancel: () -> Unit, onDismiss: () -> Unit, ): (() -> Unit)? = when (approvalState) { - ApprovalState.Authorize if showsReceivingDetails -> onBackToWatchOnly + ApprovalState.ChooseAccount -> onBack + ApprovalState.Authorize if showsReceivingDetails -> onBack ApprovalState.Authorize, ApprovalState.Authenticating, ApprovalState.Authorizing -> onCancel ApprovalState.Success -> onDismiss else -> null @@ -369,6 +388,64 @@ private fun ColumnScope.WatchOnlyConsentContent( VerticalSpacer(16.dp) } +@Composable +private fun ColumnScope.ChooseAccountContent( + uiState: PubkyAuthApprovalUiState, + onSelect: (String?) -> Unit, + onContinue: () -> Unit, + onCancel: () -> Unit, +) { + Column( + modifier = Modifier + .weight(1f) + .verticalScroll(rememberScrollState()) + .testTag("PubkyAuthChooseAccount") + ) { + VerticalSpacer(8.dp) + BodyM( + text = stringResource(R.string.profile__auth_approval_account_description), + color = Colors.White64, + letterSpacing = 0.sp, + ) + VerticalSpacer(16.dp) + uiState.existingAccounts.forEach { account -> + SettingsButtonRow( + title = account.name, + subtitle = account.derivationPath, + value = SettingsButtonValue.BooleanValue(uiState.selectedAccountId == account.id), + onClick = { onSelect(account.id) }, + modifier = Modifier + .semantics { selected = uiState.selectedAccountId == account.id } + .testTag("PubkyAuthAccount_${account.accountIndex}") + ) + } + SettingsButtonRow( + title = stringResource(R.string.profile__auth_approval_account_new), + value = SettingsButtonValue.BooleanValue(uiState.selectedAccountId == null), + onClick = { onSelect(null) }, + modifier = Modifier + .semantics { selected = uiState.selectedAccountId == null } + .testTag("PubkyAuthAccountNew") + ) + } + VerticalSpacer(32.dp) + Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) { + SecondaryButton( + text = stringResource(R.string.common__cancel), + onClick = onCancel, + textStyle = AppTextStyles.BodySSB.copy(letterSpacing = 0.sp), + modifier = Modifier.weight(1f).testTag("PubkyAuthAccountCancel") + ) + PrimaryButton( + text = stringResource(R.string.common__continue), + onClick = onContinue, + textStyle = AppTextStyles.BodySSB.copy(letterSpacing = 0.sp), + modifier = Modifier.weight(1f).testTag("PubkyAuthAccountContinue") + ) + } + VerticalSpacer(16.dp) +} + @Composable private fun UsdtSharingChoice( uiState: PubkyAuthApprovalUiState, @@ -833,7 +910,34 @@ private fun WatchOnlyConsentPreview() { isCurrentRequest = true, onAuthorize = {}, onApproveWatchOnly = {}, - onBackToWatchOnly = {}, + onBack = {}, + onCancel = {}, + onDismiss = {}, + ) + } + } +} + +@Preview(showSystemUi = true) +@Composable +private fun ChooseAccountPreview() { + AppThemeSurface { + BottomSheetPreview { + Content( + uiState = PubkyAuthApprovalUiState( + state = ApprovalState.ChooseAccount, + serviceName = "paykit", + bitkitClaim = PubkyAuthClaim(Item.PAYKIT_ACCESS_V1, Item.WATCH_ONLY_ACCOUNT_V1), + existingAccounts = persistentListOf( + previewAccount(id = "1", accountIndex = 1, name = "paykit server"), + previewAccount(id = "2", accountIndex = 2, name = "shop server"), + ), + selectedAccountId = "1", + ), + isCurrentRequest = true, + onAuthorize = {}, + onApproveWatchOnly = {}, + onBack = {}, onCancel = {}, onDismiss = {}, ) @@ -841,6 +945,19 @@ private fun WatchOnlyConsentPreview() { } } +private fun previewAccount(id: String, accountIndex: Int, name: String) = WatchOnlyAccountRecord( + id = id, + walletIndex = 0, + accountIndex = accountIndex, + addressType = WATCH_ONLY_ACCOUNT_NATIVE_SEGWIT_ADDRESS_TYPE, + xpub = "", + requestFingerprint = "", + createdAt = 0, + name = name, + isTrackingEnabled = true, + setupState = WatchOnlyAccountSetupState.Active, +) + @Preview(showSystemUi = true) @Composable private fun AuthorizePreview() { @@ -868,7 +985,7 @@ private fun AuthorizePreview() { isCurrentRequest = true, onAuthorize = {}, onApproveWatchOnly = {}, - onBackToWatchOnly = {}, + onBack = {}, onCancel = {}, onDismiss = {}, ) @@ -890,7 +1007,7 @@ private fun SuccessPreview() { isCurrentRequest = true, onAuthorize = {}, onApproveWatchOnly = {}, - onBackToWatchOnly = {}, + onBack = {}, onCancel = {}, onDismiss = {}, ) diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt index 7af36f1a84..56a3bcd49d 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModel.kt @@ -25,6 +25,7 @@ import to.bitkit.models.PubkyAuthRequest import to.bitkit.models.PubkyAuthRequestError import to.bitkit.models.PubkyProfile import to.bitkit.models.Toast +import to.bitkit.models.WatchOnlyAccountRecord import to.bitkit.models.WatchOnlyAccountSetupState import to.bitkit.repositories.Endpoint import to.bitkit.repositories.PubkyAlreadySignedInError @@ -129,6 +130,27 @@ class PubkyAuthApprovalViewModel @Inject constructor( return@launch } val profile = approvalProfile(identityPublicKey) + val existingAccounts = runSuspendCatching { + if (request.bitkitClaim?.sharesBitcoin == true && + !watchOnlyAccountRepo.hasIncompleteSetup(authUrl) + ) { + watchOnlyAccountRepo.currentWalletAccounts.first() + .filter { it.setupState == WatchOnlyAccountSetupState.Active } + } else { + emptyList() + } + }.getOrElse { + if (_uiState.value.authUrl != authUrl) return@launch + Logger.error("Failed to load server accounts", it, context = TAG) + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.profile__auth_error_title), + description = it.localizedPubkyAuthMessage(context), + ) + _effects.emit(PubkyAuthApprovalEffect.Dismiss) + return@launch + } + if (_uiState.value.authUrl != authUrl) return@launch _uiState.update { it.copy( state = if (request.bitkitClaim?.sharesBitcoin == true || @@ -148,6 +170,7 @@ class PubkyAuthApprovalViewModel @Inject constructor( profile = profile, isUsdtEnabled = usdtEnabled, shareUsdt = usdtEnabled, + existingAccounts = existingAccounts.toImmutableList(), ) } if (usdtEnabled) loadUsdtAddress(authUrl) @@ -198,27 +221,49 @@ class PubkyAuthApprovalViewModel @Inject constructor( fun approveWatchOnlyConsent(authUrl: String) { _uiState.update { state -> if (state.authUrl == authUrl && state.state == ApprovalState.WatchOnlyConsent && state.canAuthorize) { - state.copy(state = ApprovalState.Authorize) + state.copy( + state = if (state.showsAccountChoice) ApprovalState.ChooseAccount else ApprovalState.Authorize, + ) } else { state } } } - fun returnToWatchOnlyConsent(authUrl: String) { + /** Selects the existing account to share again, or `null` for a new account. */ + fun selectAccount(authUrl: String, accountId: String?) { _uiState.update { state -> - if ( - state.authUrl == authUrl && - state.state == ApprovalState.Authorize && - state.showsReceivingDetails - ) { - state.copy(state = ApprovalState.WatchOnlyConsent) + if (state.authUrl == authUrl && state.state == ApprovalState.ChooseAccount) { + state.copy(selectedAccountId = accountId) } else { state } } } + fun confirmAccountChoice(authUrl: String) { + _uiState.update { state -> + if (state.authUrl == authUrl && state.state == ApprovalState.ChooseAccount) { + state.copy(state = ApprovalState.Authorize) + } else { + state + } + } + } + + fun returnToPreviousStep(authUrl: String) { + _uiState.update { state -> + if (state.authUrl != authUrl) return@update state + when { + state.state == ApprovalState.ChooseAccount -> state.copy(state = ApprovalState.WatchOnlyConsent) + state.state != ApprovalState.Authorize -> state + state.showsAccountChoice -> state.copy(state = ApprovalState.ChooseAccount) + state.showsReceivingDetails -> state.copy(state = ApprovalState.WatchOnlyConsent) + else -> state + } + } + } + fun cancelLocalAuth(authUrl: String) { _uiState.update { state -> if (state.authUrl == authUrl && state.state == ApprovalState.Authenticating) { @@ -261,7 +306,13 @@ class PubkyAuthApprovalViewModel @Inject constructor( handleApprovalFailure(PubkyAuthRequestError.RequesterChanged, authUrl) return } - if (!approveRequest(request, authUrl, approvalState.createsIdentity)) return + val reuseAccountId = approvalState.deliveredAccountId + ?: approvalState.selectedAccountId.takeIf { approvalState.showsAccountChoice } + if (!approveRequest(request, authUrl, approvalState.createsIdentity, reuseAccountId)) { + // A retry resumes an unfinished new account, so the choice of an existing one is no longer offered. + dropAccountChoiceIfSetupUnfinished(authUrl) + return + } Logger.info("Auth approved for '${request.serviceNames.firstOrNull().orEmpty()}'", context = TAG) if (approvalState.createsIdentity) { @@ -277,6 +328,7 @@ class PubkyAuthApprovalViewModel @Inject constructor( request: PubkyAuthRequest, authUrl: String, createsIdentity: Boolean, + reuseAccountId: String?, ): Boolean = if (createsIdentity) { pubkyRepo.approveSignupAuth(request).fold( onSuccess = { true }, @@ -286,12 +338,13 @@ class PubkyAuthApprovalViewModel @Inject constructor( }, ) } else { - approveSignInRequest(request, authUrl) + approveSignInRequest(request, authUrl, reuseAccountId) } private suspend fun approveSignInRequest( request: PubkyAuthRequest, authUrl: String, + reuseAccountId: String?, ): Boolean { if (request.expectedSigner != null) { pubkyRepo.checkExpectedSigner(authUrl).onFailure { @@ -308,7 +361,7 @@ class PubkyAuthApprovalViewModel @Inject constructor( } val preparedClaim = runSuspendCatching { if (request.bitkitClaim?.sharesBitcoin == true) { - watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, defaultWatchOnlyAccountName(request)) + watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, defaultWatchOnlyAccountName(request), reuseAccountId) } else { null } @@ -317,8 +370,18 @@ class PubkyAuthApprovalViewModel @Inject constructor( return false } + // A reused account is already active: it skips the setup states and only needs tracking on. + val isReused = preparedClaim?.account?.setupState == WatchOnlyAccountSetupState.Active + // The server can hold the claim as soon as it is sent, so a reused account is tracked before delivery and + // stays tracked whatever the outcome. + preparedClaim?.takeIf { isReused }?.let { claim -> + runSuspendCatching { watchOnlyAccountRepo.trackReusedAccount(claim.account.id) }.getOrElse { + handleApprovalFailure(it, authUrl) + return false + } + } var preserveAuthorizingState = preparedClaim?.account?.setupState == WatchOnlyAccountSetupState.Authorizing - preparedClaim?.let { claim -> + preparedClaim?.takeUnless { isReused }?.let { claim -> runSuspendCatching { watchOnlyAccountRepo.beginAuthorization(claim.account.id) } .onSuccess { preserveAuthorizingState = it } .getOrElse { @@ -345,8 +408,11 @@ class PubkyAuthApprovalViewModel @Inject constructor( if (approvalResult.isFailure) { val approvalError = checkNotNull(approvalResult.exceptionOrNull()) { "Authorization failed" } preparedClaim?.let { claim -> - if (!approvalError.isPostDeliveryAuthorizationFailure()) { - cancelIncompleteSetup( + when { + // The server holds the reused account now, so a retry must share the same one. + isReused && approvalError.isPostDeliveryAuthorizationFailure() -> + pinDeliveredAccount(authUrl, claim.account.id) + !isReused && !approvalError.isPostDeliveryAuthorizationFailure() -> cancelIncompleteSetup( claim.account.id, preserveAuthorizingState, ) @@ -357,10 +423,46 @@ class PubkyAuthApprovalViewModel @Inject constructor( } return runSuspendCatching { - preparedClaim?.let { watchOnlyAccountRepo.markActive(it.account.id) } + preparedClaim?.takeUnless { isReused }?.let { watchOnlyAccountRepo.markActive(it.account.id) } }.onFailure { handleApprovalFailure(it, authUrl) }.isSuccess } + private fun pinDeliveredAccount(authUrl: String, accountId: String) { + _uiState.update { state -> + if (state.authUrl == authUrl) { + state.copy( + deliveredAccountId = accountId, + existingAccounts = persistentListOf(), + selectedAccountId = accountId, + state = state.state + .takeUnless { it == ApprovalState.ChooseAccount } + ?: ApprovalState.WatchOnlyConsent, + ) + } else { + state + } + } + } + + private suspend fun dropAccountChoiceIfSetupUnfinished(authUrl: String) { + if (!_uiState.value.showsAccountChoice) return + val isUnfinished = runSuspendCatching { watchOnlyAccountRepo.hasIncompleteSetup(authUrl) }.getOrDefault(false) + if (!isUnfinished) return + _uiState.update { state -> + if (state.authUrl == authUrl) { + state.copy( + existingAccounts = persistentListOf(), + selectedAccountId = null, + state = state.state + .takeUnless { it == ApprovalState.ChooseAccount } + ?: ApprovalState.WatchOnlyConsent, + ) + } else { + state + } + } + } + private suspend fun validatedUsdtEndpoint(request: PubkyAuthRequest): Endpoint? { val claim = request.bitkitClaim ?: return null if (!claim.sharesUsdt) return null @@ -470,7 +572,11 @@ data class PubkyAuthApprovalUiState( val usdtUnavailable: Boolean = false, val shareUsdt: Boolean = true, val isUsdtEnabled: Boolean = false, + val existingAccounts: ImmutableList = persistentListOf(), + val selectedAccountId: String? = null, + val deliveredAccountId: String? = null, ) { + val showsAccountChoice: Boolean get() = bitkitClaim?.sharesBitcoin == true && existingAccounts.isNotEmpty() val showsUsdtDetails: Boolean get() = bitkitClaim?.sharesUsdt == true && isUsdtEnabled val showsReceivingDetails: Boolean get() = bitkitClaim?.sharesBitcoin == true || showsUsdtDetails val usdtRequired: Boolean get() = bitkitClaim?.requiresUsdtAddress == true @@ -483,6 +589,7 @@ data class PubkyAuthApprovalUiState( sealed interface ApprovalState { data object Loading : ApprovalState data object WatchOnlyConsent : ApprovalState + data object ChooseAccount : ApprovalState data object Authorize : ApprovalState data object Authenticating : ApprovalState data object Authorizing : ApprovalState diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c930a202b0..d40806d509 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -767,6 +767,9 @@ Add Tag TAG For example: \'Developer\' + Choose the Bitcoin account this server can view. A new account keeps this server apart from your other servers. + Bitcoin Account + New account Authorize Authorizing… Before you continue diff --git a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt index 20dcdb3150..15c8a16a61 100644 --- a/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/WatchOnlyAccountRepoTest.kt @@ -76,6 +76,64 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { verify(node, never()).addOnchainWalletAccount(any(), any(), any()) } + @Test + fun `chosen active account is shared again without reserving an index`() = test { + val active = account() + val store = mock() + val lightningService = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = listOf(active)))) + whenever(store.load()).thenReturn(listOf(active)) + + val prepared = repository(store, lightningService).prepareUnsignedClaim( + "pubkyauth://signin?secret=again&x-bitkit-claim=watch-only-account-v1", + "paykit server", + reuseAccountId = active.id, + ) + + assertSame(active, prepared.account) + assertEquals(WatchOnlyAccountClaimCodec.PAYLOAD_LENGTH, prepared.payload.size) + verify(store, never()).reserveAccountIndex(any(), any()) + verify(store, never()).save(any()) + } + + @Test + fun `unfinished setup for the request is resumed instead of a chosen account`() = test { + val active = account() + val pending = account().copy( + id = "pending", + accountIndex = 2, + requestFingerprint = RESTORED_REQUEST_FINGERPRINT, + setupState = WatchOnlyAccountSetupState.Authorizing, + ) + val store = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = listOf(active, pending)))) + whenever(store.load()).thenReturn(listOf(active, pending)) + val sut = repository(store, mock()) + + assertTrue(sut.hasIncompleteSetup(RESTORED_AUTH_URL)) + val prepared = sut.prepareUnsignedClaim(RESTORED_AUTH_URL, "paykit server", reuseAccountId = active.id) + + assertEquals(pending.id, prepared.account.id) + verify(store, never()).reserveAccountIndex(any(), any()) + } + + @Test + fun `chosen account must be active on the current wallet`() = test { + val pending = account().copy(setupState = WatchOnlyAccountSetupState.PendingDelivery) + val otherWallet = account().copy(id = "other-wallet", walletIndex = 1) + val store = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = listOf(pending, otherWallet)))) + whenever(store.load()).thenReturn(listOf(pending, otherWallet)) + val sut = repository(store, mock()) + + listOf(pending.id, otherWallet.id, "missing").forEach { id -> + assertFailsWith { + sut.prepareUnsignedClaim("pubkyauth://signin?secret=again", "paykit server", reuseAccountId = id) + } + } + verify(store, never()).reserveAccountIndex(any(), any()) + } + @Test fun `authorization rejects an active account before tracking`() = test { val active = account() @@ -91,6 +149,64 @@ class WatchOnlyAccountRepoTest : BaseUnitTest() { verify(store, never()).update(any()) } + @Test + fun `tracking a reused account fails when it is no longer active on this wallet`() = test { + val authorizing = account().copy(isTrackingEnabled = false, setupState = WatchOnlyAccountSetupState.Authorizing) + val otherWallet = account().copy(id = "other-wallet", walletIndex = 1) + val store = mock() + val lightningService = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = listOf(authorizing, otherWallet)))) + whenever(store.load()).thenReturn(listOf(authorizing, otherWallet)) + val sut = repository(store, lightningService) + + listOf(authorizing.id, otherWallet.id, "missing").forEach { id -> + assertFailsWith { sut.trackReusedAccount(id) } + } + verify(lightningService, never()).node + verify(store, never()).save(any()) + } + + @Test + fun `tracking a reused account adds it to the node and saves it`() = test { + val untracked = account().copy(isTrackingEnabled = false) + var storedAccounts = listOf(untracked) + val store = mock() + val lightningService = mock() + val node = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = storedAccounts))) + whenever(store.load()).thenAnswer { storedAccounts } + whenever(store.save(any())).thenAnswer { + storedAccounts = it.getArgument(0) + Unit + } + whenever(lightningService.node).thenReturn(node) + whenever(node.listOnchainWalletAccounts()).thenReturn(emptyList()) + whenever(node.onchainPayment()).thenReturn(mock()) + + repository(store, lightningService).trackReusedAccount(untracked.id) + + assertTrue(storedAccounts.single().isTrackingEnabled) + verify(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, untracked.xpub) + } + + @Test + fun `tracking an already tracked reused account adds it back to the node`() = test { + val tracked = account() + val store = mock() + val lightningService = mock() + val node = mock() + whenever(store.data).thenReturn(flowOf(WatchOnlyAccountData(accounts = listOf(tracked)))) + whenever(store.load()).thenReturn(listOf(tracked)) + whenever(lightningService.node).thenReturn(node) + whenever(node.listOnchainWalletAccounts()).thenReturn(emptyList()) + whenever(node.onchainPayment()).thenReturn(mock()) + + repository(store, lightningService).trackReusedAccount(tracked.id) + + verify(node).addOnchainWalletAccount(AddressType.NATIVE_SEGWIT, 1u, tracked.xpub) + verify(store, never()).save(any()) + } + @Test fun `current wallet accounts exclude records from other wallets`() = test { val currentWalletAccount = account().copy(walletIndex = 1) diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt index 881f49c1a9..750b106803 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/PubkyAuthApprovalViewModelTest.kt @@ -19,6 +19,7 @@ import org.junit.Before import org.junit.Test import org.mockito.Mockito.mockStatic import org.mockito.kotlin.any +import org.mockito.kotlin.anyOrNull import org.mockito.kotlin.argThat import org.mockito.kotlin.clearInvocations import org.mockito.kotlin.doReturn @@ -57,6 +58,7 @@ import to.bitkit.utils.AppError import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertNotEquals import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) @@ -75,10 +77,14 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { } private val usdtEnabled = MutableStateFlow(true) private val usdtRepo: UsdtRepo = mock() - private val watchOnlyAccountRepo: WatchOnlyAccountRepo = mock() + private val existingAccounts = MutableStateFlow>(emptyList()) + private val watchOnlyAccountRepo: WatchOnlyAccountRepo = mock { + on { currentWalletAccounts } doReturn existingAccounts + } @Before fun setUp() { + whenever { watchOnlyAccountRepo.hasIncompleteSetup(any()) }.thenReturn(false) whenever(context.getString(R.string.profile__auth_approval_service_unknown)).thenReturn("Unknown service") whenever(context.getString(R.string.profile__auth_approval_services_separator)).thenReturn(" and ") whenever(context.getString(R.string.profile__auth_error_title)).thenReturn("Authorization failed") @@ -171,7 +177,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { sut.dismiss() advanceUntilIdle() - verifyNoInteractions(watchOnlyAccountRepo) + verifyNoAccountChanges() verifyBlocking(pubkyRepo, never()) { approveAuthWithCompanionClaim(any(), any(), any()) } } @@ -219,7 +225,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { advanceUntilIdle() } assertEquals(ApprovalState.Authorize, sut.uiState.value.state) - verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any()) } + verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any(), anyOrNull()) } verifyBlocking(pubkyRepo, never()) { approveAuthWithCompanionClaim(any(), any(), any()) } } @@ -366,7 +372,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { assertEquals("https://httprelay.pubky.app/inbox/", sut.uiState.value.relayUrl) verifyBlocking(pubkyRepo) { approveAuth(authUrl, capabilities, clientId) } verifyBlocking(pubkyRepo, never()) { approveAuthWithCompanionClaim(any(), any(), any()) } - verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any()) } + verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any(), anyOrNull()) } } @Test @@ -431,7 +437,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { assertEquals(ApprovalState.Authorize, sut.uiState.value.state) assertEquals("This request is for 5jsj...tryo, not this wallet's pubky.", toasts.single().description) - verifyNoInteractions(watchOnlyAccountRepo) + verifyNoAccountChanges() verifyBlocking(pubkyRepo, never()) { approveAuth(any(), any(), any()) } verifyBlocking(pubkyRepo, never()) { approveAuthWithCompanionClaim(any(), any(), any()) } toastJob.cancel() @@ -728,7 +734,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { sut.cancelLocalAuth(authUrl) assertEquals(ApprovalState.Authorize, sut.uiState.value.state) - sut.returnToWatchOnlyConsent(authUrl) + sut.returnToPreviousStep(authUrl) assertEquals(ApprovalState.WatchOnlyConsent, sut.uiState.value.state) } @@ -1155,7 +1161,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { ) verifyBlocking(watchOnlyAccountRepo) { markActive(prepared.account.id) } } else { - verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any()) } + verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(any(), any(), anyOrNull()) } } } } @@ -1177,7 +1183,7 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { assertEquals(ApprovalState.Authorize, sut.uiState.value.state) assertFalse(sut.uiState.value.shareUsdt) assertTrue(sut.uiState.value.canAuthorize) - sut.returnToWatchOnlyConsent(url) + sut.returnToPreviousStep(url) assertFalse(sut.uiState.value.shareUsdt) sut.setShareUsdt(true) assertTrue(sut.uiState.value.shareUsdt) @@ -1391,6 +1397,298 @@ class PubkyAuthApprovalViewModelTest : BaseUnitTest() { return url } + @Test + fun `re-approval preselects no account and shares a picked one again`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=paykit-access-v1.watch-only-account-v1" + val request = authRequest( + authUrl, + PubkyAuthClaim.REQUIRED_CAPABILITIES, + PubkyAuthClaim(Item.PAYKIT_ACCESS_V1, Item.WATCH_ONLY_ACCOUNT_V1), + ) + val untracked = activeAccount(id = "old", accountIndex = 1, isTrackingEnabled = false, createdAt = 3) + val tracked = activeAccount(id = "tracked", accountIndex = 2, createdAt = 1) + val newer = activeAccount(id = "newer", accountIndex = 3, createdAt = 2) + val other = activeAccount(id = "other", accountIndex = 4, name = "shop server", createdAt = 4) + existingAccounts.value = listOf(untracked, tracked, newer, other, watchOnlyAccount()) + val prepared = PreparedWatchOnlyAccountClaim(newer, ByteArray(84)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn(Result.success(request)) + whenever(watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, "paykit server", newer.id)).thenReturn(prepared) + whenever(pubkyRepo.approveAuthWithCompanionClaim(authUrl, clientId, prepared.payload)) + .thenReturn(Result.success(Unit)) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + + assertEquals(ApprovalState.ChooseAccount, sut.uiState.value.state) + assertEquals(listOf(untracked, tracked, newer, other), sut.uiState.value.existingAccounts) + assertEquals(null, sut.uiState.value.selectedAccountId) + + sut.selectAccount(authUrl, newer.id) + sut.confirmAccountChoice(authUrl) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + assertEquals(ApprovalState.Success, sut.uiState.value.state) + verifyBlocking(watchOnlyAccountRepo) { trackReusedAccount(newer.id) } + verifyBlocking(watchOnlyAccountRepo, never()) { beginAuthorization(any()) } + verifyBlocking(watchOnlyAccountRepo, never()) { markActive(any()) } + } + + @Test + fun `a picked account stays selected after going back`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + existingAccounts.value = listOf(activeAccount(id = "other", accountIndex = 1, name = "shop server")) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + + assertEquals(ApprovalState.ChooseAccount, sut.uiState.value.state) + assertEquals(null, sut.uiState.value.selectedAccountId) + + sut.selectAccount(authUrl, "other") + sut.confirmAccountChoice(authUrl) + sut.returnToPreviousStep(authUrl) + assertEquals(ApprovalState.ChooseAccount, sut.uiState.value.state) + assertEquals("other", sut.uiState.value.selectedAccountId) + sut.returnToPreviousStep(authUrl) + assertEquals(ApprovalState.WatchOnlyConsent, sut.uiState.value.state) + } + + @Test + fun `choosing a new account beside existing ones sets up a new account`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + existingAccounts.value = listOf(activeAccount(id = "old", accountIndex = 1)) + val prepared = PreparedWatchOnlyAccountClaim(watchOnlyAccount(), ByteArray(84)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + whenever(watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, "paykit server", null)).thenReturn(prepared) + whenever(watchOnlyAccountRepo.beginAuthorization(prepared.account.id)).thenReturn(false) + whenever(pubkyRepo.approveAuthWithCompanionClaim(authUrl, clientId, prepared.payload)) + .thenReturn(Result.success(Unit)) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + sut.selectAccount(authUrl, null) + sut.confirmAccountChoice(authUrl) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + assertEquals(ApprovalState.Success, sut.uiState.value.state) + verifyBlocking(watchOnlyAccountRepo) { beginAuthorization(prepared.account.id) } + verifyBlocking(watchOnlyAccountRepo) { markActive(prepared.account.id) } + verifyBlocking(watchOnlyAccountRepo, never()) { trackReusedAccount(any()) } + } + + @Test + fun `unfinished new account after a failed authorization drops the account choice`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + existingAccounts.value = listOf(activeAccount(id = "old", accountIndex = 1)) + val prepared = PreparedWatchOnlyAccountClaim(watchOnlyAccount(), ByteArray(84)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + whenever(watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, "paykit server", null)).thenReturn(prepared) + whenever(watchOnlyAccountRepo.beginAuthorization(prepared.account.id)).thenReturn(false) + whenever(pubkyRepo.approveAuthWithCompanionClaim(authUrl, clientId, prepared.payload)).thenReturn( + Result.failure(PubkyAuthCompanionClaimApprovalException.AuthorizationFailure("AuthToken delivery failed")), + ) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + sut.selectAccount(authUrl, null) + sut.confirmAccountChoice(authUrl) + whenever(watchOnlyAccountRepo.hasIncompleteSetup(authUrl)).thenReturn(true) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + sut.returnToPreviousStep(authUrl) + + assertFalse(sut.uiState.value.showsAccountChoice) + assertNotEquals(ApprovalState.ChooseAccount, sut.uiState.value.state) + } + + @Test + fun `reused account stays tracked and pinned when authorization fails after delivery`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + val reused = activeAccount(id = "old", accountIndex = 1, isTrackingEnabled = false) + existingAccounts.value = listOf(reused) + val prepared = PreparedWatchOnlyAccountClaim(reused, ByteArray(84)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + whenever(watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, "paykit server", reused.id)).thenReturn(prepared) + whenever(pubkyRepo.approveAuthWithCompanionClaim(authUrl, clientId, prepared.payload)).thenReturn( + Result.failure(PubkyAuthCompanionClaimApprovalException.AuthorizationFailure("AuthToken delivery failed")), + ) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + sut.selectAccount(authUrl, reused.id) + sut.confirmAccountChoice(authUrl) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + verifyBlocking(watchOnlyAccountRepo) { trackReusedAccount(reused.id) } + verifyBlocking(watchOnlyAccountRepo, never()) { setTrackingEnabled(reused.id, false) } + verifyBlocking(watchOnlyAccountRepo, never()) { cancelAuthorization(any(), any()) } + verifyBlocking(watchOnlyAccountRepo, never()) { markActive(any()) } + assertFalse(sut.uiState.value.showsAccountChoice) + + sut.selectAccount(authUrl, null) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + verifyBlocking(watchOnlyAccountRepo, times(2)) { prepareUnsignedClaim(authUrl, "paykit server", reused.id) } + verifyBlocking(watchOnlyAccountRepo, never()) { prepareUnsignedClaim(authUrl, "paykit server", null) } + } + + @Test + fun `reused account stays tracked when authorization fails before delivery`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + val reused = activeAccount(id = "old", accountIndex = 1, isTrackingEnabled = false) + existingAccounts.value = listOf(reused) + val prepared = PreparedWatchOnlyAccountClaim(reused, ByteArray(84)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + whenever(watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, "paykit server", reused.id)).thenReturn(prepared) + whenever(pubkyRepo.approveAuthWithCompanionClaim(authUrl, clientId, prepared.payload)) + .thenReturn(Result.failure(IllegalStateException("relay unreachable"))) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + sut.selectAccount(authUrl, reused.id) + sut.confirmAccountChoice(authUrl) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + verifyBlocking(watchOnlyAccountRepo) { trackReusedAccount(reused.id) } + verifyBlocking(watchOnlyAccountRepo, never()) { setTrackingEnabled(reused.id, false) } + verifyBlocking(watchOnlyAccountRepo, never()) { cancelAuthorization(any(), any()) } + assertTrue(sut.uiState.value.showsAccountChoice) + } + + @Test + fun `reused account that cannot be tracked is not sent`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + val reused = activeAccount(id = "old", accountIndex = 1, isTrackingEnabled = false) + existingAccounts.value = listOf(reused) + val prepared = PreparedWatchOnlyAccountClaim(reused, ByteArray(84)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + whenever(watchOnlyAccountRepo.prepareUnsignedClaim(authUrl, "paykit server", reused.id)).thenReturn(prepared) + whenever(watchOnlyAccountRepo.trackReusedAccount(reused.id)) + .thenThrow(IllegalStateException("node stopped")) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + sut.selectAccount(authUrl, reused.id) + sut.confirmAccountChoice(authUrl) + sut.confirmAuthorize(authUrl) + advanceUntilIdle() + + verifyBlocking(pubkyRepo, never()) { approveAuthWithCompanionClaim(any(), any(), any()) } + assertEquals(ApprovalState.Authorize, sut.uiState.value.state) + assertTrue(sut.uiState.value.showsAccountChoice) + } + + @Test + fun `unfinished setup for the request skips the account choice`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + existingAccounts.value = listOf(activeAccount(id = "old", accountIndex = 1)) + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + whenever(watchOnlyAccountRepo.hasIncompleteSetup(authUrl)).thenReturn(true) + val sut = createSut() + + sut.load(authUrl) + advanceUntilIdle() + sut.approveWatchOnlyConsent(authUrl) + + assertEquals(ApprovalState.Authorize, sut.uiState.value.state) + assertTrue(sut.uiState.value.existingAccounts.isEmpty()) + } + + @Test + fun `unreadable server accounts end the request before consent`() = test { + val authUrl = "pubkyauth://signin?x-bitkit-claim=watch-only-account-v1" + whenever(pubkyRepo.parseAuthUrl(authUrl)).thenReturn( + Result.success( + authRequest(authUrl, PubkyAuthClaim.REQUIRED_CAPABILITIES, PubkyAuthClaim(Item.WATCH_ONLY_ACCOUNT_V1)), + ), + ) + whenever(watchOnlyAccountRepo.hasIncompleteSetup(authUrl)).thenThrow(IllegalStateException("store")) + val sut = createSut() + val toasts = mutableListOf() + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + + sut.effects.test { + sut.load(authUrl) + advanceUntilIdle() + assertEquals(PubkyAuthApprovalEffect.Dismiss, awaitItem()) + } + + assertEquals(ApprovalState.Loading, sut.uiState.value.state) + assertEquals("Authorization failed", toasts.single().title) + verifyNoAccountChanges() + toastJob.cancel() + } + + private suspend fun verifyNoAccountChanges() { + verify(watchOnlyAccountRepo, never()).prepareUnsignedClaim(any(), any(), anyOrNull()) + verify(watchOnlyAccountRepo, never()).beginAuthorization(any()) + verify(watchOnlyAccountRepo, never()).trackReusedAccount(any()) + verify(watchOnlyAccountRepo, never()).markActive(any()) + } + + private fun activeAccount( + id: String, + accountIndex: Int, + name: String = "paykit server", + isTrackingEnabled: Boolean = true, + createdAt: Long = 1, + ) = watchOnlyAccount().copy( + id = id, + accountIndex = accountIndex, + name = name, + isTrackingEnabled = isTrackingEnabled, + createdAt = createdAt, + setupState = WatchOnlyAccountSetupState.Active, + ) + private fun createSut() = PubkyAuthApprovalViewModel( context = context, pubkyRepo = pubkyRepo, diff --git a/changelog.d/next/2237.fixed.md b/changelog.d/next/2237.fixed.md new file mode 100644 index 0000000000..5c8bbd2c7d --- /dev/null +++ b/changelog.d/next/2237.fixed.md @@ -0,0 +1 @@ +Re-approving a Paykit server now offers to share an existing server account instead of always creating a new one. diff --git a/docs/pubky-auth-companion-claims.md b/docs/pubky-auth-companion-claims.md index a9003836f9..ae7e78f732 100644 --- a/docs/pubky-auth-companion-claims.md +++ b/docs/pubky-auth-companion-claims.md @@ -7,7 +7,7 @@ Bitkit's own session includes the Paykit authorizer scope. On identity activatio ## Request - The Pubky Auth URL includes one `x-bitkit-claim` query parameter containing a dot-separated list of independent items: `paykit-access-v1` and `watch-only-account-v1`. Each item requests only its corresponding permission and material. -- Request builders emit Paykit first when requesting both: `x-bitkit-claim=paykit-access-v1.watch-only-account-v1`. Paykit Server requests both items for initial setup and only `paykit-access-v1` for reconnect. +- Request builders emit Paykit first when requesting both: `x-bitkit-claim=paykit-access-v1.watch-only-account-v1`. Paykit Server requests both items for initial setup and for its default reconnect (`/setup/reconnect` without `asset`); a Paykit-only reconnect requests only `paykit-access-v1`. - Either item order is accepted. Bitkit preserves the exact received list string as the SDK's `claim_type`; it must not be reordered before signing or relay delivery. - The capability is `/pub/paykit/:rw`. - Empty, unknown, or duplicate items, mismatched selections, and duplicate companion query parameters are rejected. Ordinary Pubky Auth without a companion claim shares only the session, not a Paykit access key or watch-only account. diff --git a/journeys/pubky-marketplace/README.md b/journeys/pubky-marketplace/README.md index 4f3448fe07..f8efc6f780 100644 --- a/journeys/pubky-marketplace/README.md +++ b/journeys/pubky-marketplace/README.md @@ -16,6 +16,7 @@ The companion journey is shared with iOS; only platform build instructions diffe - `paykit-only-approval.xml` checks Paykit-only consent and cancellation without account creation. - `paykit-reconnect.xml` checks Paykit-only reconnect consent and cancellation without changing the existing service account. +- `reapprove-server-account.xml` checks that re-approving a server offers its existing account with "New account" selected, keeps one account when the existing one is picked and adds one when "New account" is kept. Every server's request has the same default account name, so no account is preselected. - `approval-while-node-restarts.xml` checks that a Bitcoin watch-only setup approved while the node is stopped or rebuilding completes on the first Authorize and is tracked once the node starts. These visible consent and cancel checks require valid auth URL fixtures but do not authorize a @@ -74,6 +75,11 @@ The [bitkit-docker](https://github.com/synonymdev/bitkit-docker) `marketplace` p ([`docs/pubky-marketplace.md`](https://github.com/synonymdev/bitkit-docker/blob/main/docs/pubky-marketplace.md)): - `./pubky-marketplace setup-url` prints the `/setup` auth URL; `setup-wait ` waits for the setup to complete. +- The fixture has no reconnect command. For a creator whose setup completed (`setup-wait`), fetch Paykit Server's + `/setup/reconnect?return_to=http%3A%2F%2Flocalhost%3A8080&state=&creator=` page + (`http://127.0.0.1:23101`, or the `MARKETPLACE_PAYKIT_PORT` override; URL quoted) and take the auth URL from its "Continue with Bitkit" link HTML-decoded (`&` becomes `&`, or Bitkit rejects the request), and the flow id from its + `flowId`; `setup-wait ` then waits for that flow too. Without an `asset` parameter it requests the same claims as + `/setup`, the watch-only account included (`reapprove-server-account.xml`), not the Paykit-only claim. - `./pubky-marketplace seller-auth` prints the marketplace grant request as its first JSON line and waits for the approval. Run its printed `android` command, `adb shell "am start -a android.intent.action.VIEW -d ''"`, with the double quotes kept, or the device shell cuts the URL at the first `&`. The request goes through the diff --git a/journeys/pubky-marketplace/reapprove-server-account.xml b/journeys/pubky-marketplace/reapprove-server-account.xml new file mode 100644 index 0000000000..a10896cd2b --- /dev/null +++ b/journeys/pubky-marketplace/reapprove-server-account.xml @@ -0,0 +1,35 @@ + + + Verifies that re-approving a Paykit server offers the existing server accounts instead of + always creating a new one. Precondition: an isolated wallet with one active server account + created by approving the setup fixture once (combined x-bitkit-claim=paykit-access-v1.watch-only-account-v1) + and completing it with ./pubky-marketplace setup-wait <flow>. + The server rejects a second /setup flow once the creator exists, while Bitkit can still show success, + so each later approval uses a fresh reconnect auth URL for the same creator. Fetch the Paykit Server's + /setup/reconnect?return_to=<setup origin>&state=<new state>&creator=<wallet pubky> page + (with the marketplace profile: curl 'http://127.0.0.1:23101/setup/reconnect?return_to=http%3A%2F%2Flocalhost%3A8080&state=…&creator=…', or the MARKETPLACE_PAYKIT_PORT override) + and take the auth URL from its "Continue with Bitkit" link HTML-decoded (&amp; becomes &, or Bitkit rejects the request), and the flow id from its flowId. Without an asset + parameter it requests the same claims as /setup, the watch-only account included, so the account step is shown; + a Paykit-only reconnect has none. + The cancel steps need no live authorization relay; the authorize steps need the same fixture runtime as wallet-leg.xml. + + + Open Settings, Advanced, Server Accounts and record the existing account's name, derivation path and xpub + Open a reconnect auth URL in the wallet + Verify the Earn introduction is visible and tap Approve (id "PubkyAuthWatchOnlyApprove") + Verify the account choice (id "PubkyAuthChooseAccount") lists the existing account (id "PubkyAuthAccount_1") with its name and derivation path, and a "New account" row (id "PubkyAuthAccountNew") + Verify "New account" is selected and the existing account is not + Select the existing account + Tap Back and verify the Earn introduction is shown again; tap Approve and verify the account choice returns with the same selection + Tap Continue (id "PubkyAuthAccountContinue"), verify the authorization screen, then tap Back and verify the account choice is shown + Tap Cancel and verify Server Accounts still lists exactly one account, unchanged + Open a fresh reconnect auth URL, tap Approve, select the existing account, tap Continue and Authorize + Verify the success screen and tap OK (id "PubkyAuthOK") + Run `./pubky-marketplace setup-wait <flow>` and verify it reports the flow complete + Open Settings, Advanced, Server Accounts and verify it still lists exactly one account, tracked, with the same derivation path; open it and verify the same xpub + Open a fresh reconnect auth URL, tap Approve, keep "New account" selected, tap Continue and Authorize + Verify the success screen and tap OK (id "PubkyAuthOK") + Run `./pubky-marketplace setup-wait <flow>` and verify it reports the flow complete + Open Settings, Advanced, Server Accounts and verify it now lists two accounts, the new one at the next derivation path + +