diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index c6b34945f3..99c82380b3 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -97,6 +97,7 @@ sealed class PubkyContactError(message: String) : AppError(message) { data object CannotAddSelf : PubkyContactError("Cannot add your own pubky as a contact") data object InvalidFormat : PubkyContactError("Invalid pubky key format") data object ActiveSubscription : PubkyContactError("Contact has an active subscription") + class ActiveProfileSubscriptions(val endsAtMillis: Long?) : PubkyContactError("Profile has active subscriptions") data object SignInChanged : PubkyContactError("Pubky sign-in changed while saving the contact") } @@ -1257,14 +1258,14 @@ class PubkyRepo @Inject constructor( } } - suspend fun deleteProfileWithSessionRetry(): Result = withContext(ioDispatcher) { - val initialResult = deleteProfile() - if (initialResult.isSuccess) return@withContext initialResult - - val refreshedSession = refreshSessionIfPossible().getOrDefault(false) - if (!refreshedSession) return@withContext initialResult - - deleteProfile() + suspend fun checkProfileDeletionAllowed(): Result = runSuspendCatching { + withContext(ioDispatcher) { pubkyService.checkProfileDeletionAllowed() } + }.recoverCatching { + generateSequence(it) { error -> error.cause } + .filterIsInstance() + .firstOrNull()?.let { error -> throw error } + if (it.hasCause(PubkyContactError.ActiveSubscription)) throw PubkyContactError.ActiveSubscription + throw it } suspend fun deleteProfile(): Result = runSuspendCatching { @@ -1272,20 +1273,14 @@ class PubkyRepo @Inject constructor( requireNotNull(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)) { "No session available" } + checkProfileDeletionAllowed().getOrThrow() clearSessionContactProfiles() deleteAllContacts() profileWriteMutex.withLock { profileDeletionGeneration.incrementAndGet() try { if (!isRingAdoptedIdentity()) deletePubkyAppProfile() - runSuspendCatching { - pubkyService.deletePaykitProfile() - }.getOrElse { - if (!it.isMissingPubkyData()) { - throw it - } - Logger.info("Continuing sign out, bitkit profile storage already missing", context = TAG) - } + pubkyService.deletePaykitProfile() } finally { profileDeletionGeneration.incrementAndGet() } @@ -1294,42 +1289,40 @@ class PubkyRepo @Inject constructor( } settingsStore.update { it.paykitDisabled(markPublicCleanupPending = it.hasPaykitState()) } signOut().getOrThrow() + }.recoverCatching { + generateSequence(it) { error -> error.cause } + .filterIsInstance() + .firstOrNull()?.let { error -> throw error } + if (it.hasCause(PubkyContactError.ActiveSubscription)) throw PubkyContactError.ActiveSubscription + throw it } private suspend fun deletePubkyAppProfile() { val publicKey = _publicKey.value ?: return val known = ownProfileRevision val revision = known ?: pubkyService.fetchPubkyProfileWithRevision(publicKey)?.revision ?: return - runSuspendCatching { withPubkyAppScope { pubkyService.deletePubkyProfile(revision, publicKey) } }.getOrElse { + runSuspendCatching { pubkyService.deletePubkyProfile(revision, publicKey) }.getOrElse { if (known == null || !it.isConcurrentUpdate()) throw it val current = pubkyService.fetchPubkyProfileWithRevision(publicKey)?.revision - if (current != null) withPubkyAppScope { pubkyService.deletePubkyProfile(current, publicKey) } + if (current != null) pubkyService.deletePubkyProfile(current, publicKey) } ownProfileRevision = null } private suspend fun deleteAllContacts() { - val records = runSuspendCatching { - pubkyService.contactRecords() - }.getOrElse { - if (!it.isMissingPubkyData()) throw it - emptyList() - } - runSuspendCatching { - val removed = pubkyService.removeContacts(records.map { it.publicKey }) - if (removed.size != records.size) { - Logger.warn("Retained contacts that could not be removed during profile deletion", context = TAG) - } - }.onFailure { - Logger.warn("Failed to delete contacts", it, context = TAG) - } - pubkyStore.update { it.copy(contactProfileOverrides = emptyMap()) } + val records = pubkyService.contactRecords() + if (records.isEmpty()) return + val keys = records.map { it.publicKey.ensurePubkyPrefix() }.toSet() + val removedKeys = pubkyService.removeContactsForProfile(records.map { it.publicKey }) + .map { it.publicKey.ensurePubkyPrefix() }.toSet().intersect(keys) + pubkyStore.update { it.copy(contactProfileOverrides = it.contactProfileOverrides - removedKeys) } notifyBackupStateChanged() synchronized(contactsLock) { cancelContactScreenLookups() - updateContacts { emptyList() } + updateContacts { current -> current.filterNot { it.publicKey in removedKeys } } } markContactsLoaded() + if (removedKeys != keys) throw PrivatePaykitError.PrivateUnavailable Logger.info("Deleted all contacts", context = TAG) } @@ -2344,7 +2337,7 @@ class PubkyRepo @Inject constructor( } } - suspend fun refreshSessionIfPossible(): Result = runSuspendCatching { + private suspend fun refreshSessionIfPossible(): Result = runSuspendCatching { withContext(ioDispatcher) { val storedSecretKeyHex = activeSecretKeyHex() ?: return@withContext false @@ -2830,21 +2823,5 @@ class PubkyRepo @Inject constructor( private fun redacted(publicKey: String): String = PubkyPublicKeyFormat.redacted(publicKey) - private fun Throwable.isMissingPubkyData(): Boolean { - val fullMessage = buildErrorMessage() - return fullMessage.contains("404") || - fullMessage.contains("not found", ignoreCase = true) || - fullMessage.contains("missing", ignoreCase = true) - } - - private fun Throwable.buildErrorMessage(): String = - buildString { - append(message.orEmpty()) - cause?.message?.takeIf { it.isNotBlank() }?.let { - append(" ") - append(it) - } - } - // endregion } diff --git a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt index de8c204e7a..7392681558 100644 --- a/app/src/main/java/to/bitkit/services/PaykitSdkService.kt +++ b/app/src/main/java/to/bitkit/services/PaykitSdkService.kt @@ -659,6 +659,7 @@ class PaykitSdkService @Inject constructor( isSetup.await() operationLock.withLock { withPaykitKey { handle -> + requireNoActiveSubscriptions(handle) val publicKey = requireNotNull(completeSdkCall { handle.identityStatus() }?.publicKey) val current = handle.fetchPaykitProfile(publicKey) completeSdkCall { @@ -694,6 +695,7 @@ class PaykitSdkService @Inject constructor( isSetup.await() operationLock.withLock { requireProfileIdentity(currentIdentity(), expectedIdentity) + requireNoActiveSubscriptions(handle()) completeSdkCall { handle().deletePubkyProfile(expectedRevision) } } } @@ -813,6 +815,37 @@ class PaykitSdkService @Inject constructor( return imported } + suspend fun checkProfileDeletionAllowed() { + isSetup.await() + operationLock.withLock { + withStateRevisionTracking { handle -> + requireNoActiveSubscriptions(handle) + } + } + } + + private suspend fun requireNoActiveSubscriptions(handle: PaykitSdk) { + val now = nowMillis() + val subscriptions = completeSdkCall { handle.paymentRequests() }.filter { it.hasActiveSubscription(now) } + requireNoProfileSubscriptions(subscriptions) + } + + private fun PaymentRequestRecord.hasActiveSubscription(now: Long): Boolean { + val endsAt = subscriptionEndsAtMillis() + return state == PaymentRequestLifecycleState.ACTIVE_RECURRING && (endsAt == null || endsAt > now) + } + + private fun PaymentRequestRecord.subscriptionEndsAtMillis(): Long? = terms?.recurrence?.endsAt?.let { timestamp -> + runCatching { Instant.parse(timestamp).toEpochMilliseconds() }.getOrNull() + } + + private fun requireNoProfileSubscriptions(subscriptions: List) { + if (subscriptions.isEmpty()) return + val endDates = subscriptions.mapNotNull { it.subscriptionEndsAtMillis() } + val latestEnd = if (endDates.size == subscriptions.size) endDates.maxOrNull() else null + throw PubkyContactError.ActiveProfileSubscriptions(latestEnd) + } + suspend fun removeContact(publicKey: String): ContactRecord? { isSetup.await() return operationLock.withLock { @@ -822,12 +855,7 @@ class PaykitSdkService @Inject constructor( } val now = nowMillis() val hasActiveSubscription = completeSdkCall { handle.paymentRequests() }.any { - val endsAt = it.terms?.recurrence?.endsAt?.let { timestamp -> - runSuspendCatching { Instant.parse(timestamp).toEpochMilliseconds() }.getOrNull() - } - PubkyPublicKeyFormat.matches(it.counterparty, publicKey) && - it.state == PaymentRequestLifecycleState.ACTIVE_RECURRING && - (endsAt == null || endsAt > now) + PubkyPublicKeyFormat.matches(it.counterparty, publicKey) && it.hasActiveSubscription(now) } if (hasActiveSubscription) throw PubkyContactError.ActiveSubscription peers.filter { it.state == LinkedPeerState.LINKED }.forEach { @@ -847,18 +875,29 @@ class PaykitSdkService @Inject constructor( } } - suspend fun removeContacts(publicKeys: List): List { + suspend fun removeContacts(publicKeys: List): List = + removeContacts(publicKeys, requireAll = false) + + suspend fun removeContactsForProfile(publicKeys: List): List = + removeContacts(publicKeys, requireAll = true) + + private suspend fun removeContacts(publicKeys: List, requireAll: Boolean): List { if (publicKeys.isEmpty()) return emptyList() isSetup.await() return operationLock.withLock { withStateRevisionTracking { handle -> val now = nowMillis() - val subscribedKeys = completeSdkCall { handle.paymentRequests() }.filter { - val endsAt = it.terms?.recurrence?.endsAt?.let { timestamp -> - runSuspendCatching { Instant.parse(timestamp).toEpochMilliseconds() }.getOrNull() - } - it.state == PaymentRequestLifecycleState.ACTIVE_RECURRING && (endsAt == null || endsAt > now) - }.mapNotNull { PubkyPublicKeyFormat.normalized(it.counterparty) }.toSet() + val subscriptions = completeSdkCall { handle.paymentRequests() }.filter { + it.hasActiveSubscription( + now + ) + } + if (requireAll) requireNoProfileSubscriptions(subscriptions) + val subscribedKeys = subscriptions.mapNotNull { + PubkyPublicKeyFormat.normalized( + it.counterparty + ) + }.toSet() val removableKeys = publicKeys.filter { PubkyPublicKeyFormat.normalized(it) !in subscribedKeys } if (removableKeys.isEmpty()) return@withStateRevisionTracking emptyList() completeSdkCall { handle.removeContactsAndBlockPeers(removableKeys) } diff --git a/app/src/main/java/to/bitkit/services/PubkyService.kt b/app/src/main/java/to/bitkit/services/PubkyService.kt index 1b5264c76e..b241f2c925 100644 --- a/app/src/main/java/to/bitkit/services/PubkyService.kt +++ b/app/src/main/java/to/bitkit/services/PubkyService.kt @@ -210,6 +210,15 @@ class PubkyService @Inject constructor( paykitSdkService.uploadProfileAvatar(bytes, contentType) } + suspend fun checkProfileDeletionAllowed() = ServiceQueue.PUBKY.background { + paykitSdkService.checkProfileDeletionAllowed() + } + + suspend fun removeContactsForProfile(publicKeys: List): List = + ServiceQueue.PUBKY.background { + paykitSdkService.removeContactsForProfile(publicKeys) + } + suspend fun deletePaykitProfile() = ServiceQueue.PUBKY.background { paykitSdkService.deletePaykitProfile() } diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt index ad2302f4a4..d8ad8838d8 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileViewModel.kt @@ -22,12 +22,14 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import to.bitkit.R import to.bitkit.ext.runSuspendCatching +import to.bitkit.ext.toLocalizedTimestamp import to.bitkit.models.PROFILE_NAME_MAX_LENGTH import to.bitkit.models.PubkyProfileLink import to.bitkit.models.Toast import to.bitkit.models.takeCodePoints import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.ProfileEditBase +import to.bitkit.repositories.PubkyContactError import to.bitkit.repositories.PubkyProfileChangedError import to.bitkit.repositories.PubkyProfileTagsNotSavedError import to.bitkit.repositories.PubkyRepo @@ -264,7 +266,7 @@ class EditProfileViewModel @Inject constructor( privatePaykitRepo.removePublishedEndpointsForCleanup(TAG).getOrThrow() pubkyRepo.signOut().getOrThrow() } - privatePaykitRepo.closeAndClear() + privatePaykitRepo.closeAndClear().getOrThrow() } } if (result.isSuccess) { @@ -291,12 +293,25 @@ class EditProfileViewModel @Inject constructor( isDeleting = true, ) } + var privatePauseStarted = false try { - privatePaykitRepo.beginProfileDeletion() - privatePaykitRepo.removePublishedEndpointsForCleanup(TAG, deferAppSync = true) - val result = pubkyRepo.deleteProfileWithSessionRetry() + val result = runSuspendCatching { + pubkyRepo.checkProfileDeletionAllowed().getOrThrow() + privatePauseStarted = true + privatePaykitRepo.beginProfileDeletion() + privatePaykitRepo.removePublishedEndpointsForCleanup(TAG, deferAppSync = true).getOrThrow() + pubkyRepo.deleteProfile().getOrThrow() + } if (result.isSuccess) { - privatePaykitRepo.closeAndClear() + privatePaykitRepo.closeAndClear().onFailure { + Logger.error("Failed to clear local state after profile deletion", it, context = TAG) + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.common__error), + description = it.message, + ) + return + } ToastEventBus.send( type = Toast.ToastType.SUCCESS, title = context.getString(_uiState.value.removal.successToast), @@ -304,11 +319,25 @@ class EditProfileViewModel @Inject constructor( _effects.emit(EditProfileEffect.DeleteSuccess) } else { val error = requireNotNull(result.exceptionOrNull()) { "Profile delete failed without an error" } - Logger.error("Failed to delete profile", error, context = TAG) - _uiState.update { it.copy(showDeleteFailureDialog = true) } + if (error is PubkyContactError.ActiveProfileSubscriptions || + error == PubkyContactError.ActiveSubscription + ) { + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.profile__delete_active_subscription), + description = (error as? PubkyContactError.ActiveProfileSubscriptions)?.endsAtMillis?.let { + context.getString(R.string.subscriptions__expires_date, it.toLocalizedTimestamp()) + }, + ) + } else { + Logger.error("Failed to delete profile", error, context = TAG) + _uiState.update { it.copy(showDeleteFailureDialog = true) } + } } } finally { - withContext(NonCancellable) { privatePaykitRepo.endProfileDeletion() } + if (privatePauseStarted) { + withContext(NonCancellable) { privatePaykitRepo.endProfileDeletion() } + } _uiState.update { it.copy(isDeleting = false) } } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index e4cd0e3bca..ac3f4229d5 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1455,6 +1455,7 @@ جارٍ تحميل ملفك الشخصي… ادخل إلى\n<accent>ويب الحرية</accent> فشل إنشاء الملف الشخصي + تمنع الاشتراكات النشطة إزالة هذا الملف الشخصي. يؤدي حذف ملفك الشخصي إلى إزالته من Pubky. قد تحتفظ جهات الاتصال بمعلومات الملف الشخصي والدفع التي شاركتها معهم سابقًا. حذف الملف الشخصي؟ تعذر علينا حذف بيانات ملفك الشخصي. أعد المحاولة، أو افصل هذا الـ pubky عن Bitkit. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 692bc2f515..1e225847e5 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1481,6 +1481,7 @@ Cargando su perfil… Entre a la\n<accent>web de la libertad</accent> No se pudo crear el perfil + Las suscripciones activas impiden eliminar este perfil. Al eliminar su perfil, se borra de Pubky. Es posible que sus contactos conserven la información de perfil y de pago que compartió con ellos anteriormente. ¿Eliminar perfil? No pudimos eliminar los datos de su perfil. Vuelva a intentarlo o desconecte este pubky de Bitkit. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 012af26c5e..8fd7fe9f03 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1477,6 +1477,7 @@ Carregant el teu perfil… Entra a la\n<accent>web de la llibertat</accent> No s\'ha pogut crear el perfil + Les subscripcions actives impedeixen eliminar aquest perfil. Eliminar el teu perfil l\'esborra de Pubky. És possible que els contactes conservin la informació de perfil i de pagament que s\'hi hagi compartit abans. Eliminar el perfil? No hem pogut eliminar les dades del teu perfil. Torna-ho a provar o desconnecta aquest pubky de Bitkit. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 32e9c3b9be..fc6a84244b 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1479,6 +1479,7 @@ Načítání vašeho profilu… Vstupte do\n<accent>svobodného webu</accent> Profil se nepodařilo vytvořit + Aktivní předplatná brání odstranění tohoto profilu. Smazáním profilu ho odstraníte z Pubky. Kontakty si mohou ponechat informace o profilu a platbách, které jste s nimi dříve sdíleli. Smazat profil? Data vašeho profilu se nepodařilo smazat. Zkuste to znovu, nebo tento pubky od Bitkitu odpojte. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 3c67d6f9ec..1aae3a235f 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1477,6 +1477,7 @@ Dein Profil wird geladen… Betritt das\n<accent>freie Web</accent> Profil konnte nicht erstellt werden + Aktive Abonnements verhindern das Entfernen dieses Profils. Durch das Löschen deines Profils wird es von Pubky entfernt. Kontakte können zuvor mit ihnen geteilte Profil- und Zahlungsinformationen weiterhin behalten. Profil löschen? Wir konnten deine Profildaten nicht löschen. Versuche es erneut oder trenne diesen pubky von Bitkit. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index e63ed7a2bd..9e0cecd4db 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1461,6 +1461,7 @@ Φόρτωση του προφίλ σου… Μπες στον\n<accent>ελεύθερο ιστό</accent> Αποτυχία δημιουργίας προφίλ + Οι ενεργές συνδρομές εμποδίζουν την αφαίρεση αυτού του προφίλ. Η διαγραφή του προφίλ σου το αφαιρεί από το Pubky. Οι επαφές μπορεί να διατηρούν ακόμα πληροφορίες προφίλ και πληρωμών που τους κοινοποιήθηκαν παλαιότερα. Διαγραφή προφίλ; Δεν μπορέσαμε να διαγράψουμε τα δεδομένα του προφίλ σου. Δοκίμασε ξανά ή αποσύνδεσε αυτό το pubky από το Bitkit. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index f4b03b2a0e..0bfbbf08d9 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1475,6 +1475,7 @@ Cargando tu perfil… Entra en la\n<accent>web libre</accent> No se pudo crear el perfil + Las suscripciones activas impiden eliminar este perfil. Al eliminar tu perfil, se elimina de Pubky. Es posible que tus contactos conserven la información de perfil y de pago que compartiste con ellos anteriormente. ¿Eliminar el perfil? No pudimos eliminar los datos de tu perfil. Vuelve a intentarlo o desconecta este pubky de Bitkit. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index cb250a075a..60cacec36f 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1474,6 +1474,7 @@ Cargando su perfil… Entre en la\n<accent>web libre</accent> No se pudo crear el perfil + Las suscripciones activas impiden eliminar este perfil. Al eliminar su perfil, se elimina de Pubky. Es posible que sus contactos conserven la información de perfil y de pago que compartió con ellos anteriormente. ¿Eliminar el perfil? No pudimos eliminar los datos de su perfil. Vuelva a intentarlo o desconecte este pubky de Bitkit. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index f4a8687132..bc8b4f7f8a 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1475,6 +1475,7 @@ Chargement de votre profil… Entrez dans le\n<accent>web de la liberté</accent> Échec de la création du profil + Les abonnements actifs empêchent la suppression de ce profil. La suppression de votre profil le retire de Pubky. Vos contacts peuvent encore conserver les informations de profil et de paiement que vous leur avez partagées. Supprimer le profil ? Nous n\'avons pas pu supprimer les données de votre profil. Réessayez ou déconnectez ce pubky de Bitkit. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index a44dda72c2..5a629af8f7 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1480,6 +1480,7 @@ Caricamento del profilo… Entra nel\n<accent>web della libertà</accent> Impossibile creare il profilo + Gli abbonamenti attivi impediscono la rimozione di questo profilo. Eliminando il profilo lo rimuovi da Pubky. I contatti potrebbero conservare le informazioni di profilo e di pagamento condivise in precedenza con loro. Eliminare il Profilo? Non è stato possibile eliminare i dati del tuo profilo. Riprova, oppure disconnetti questo pubky da Bitkit. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index b210d10775..092238bd34 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1477,6 +1477,7 @@ Uw profiel laden… Betreed het\n<accent>vrije web</accent> Profiel aanmaken mislukt + Actieve abonnementen verhinderen het verwijderen van dit profiel. Als u uw profiel verwijdert, wordt het van Pubky verwijderd. Contacten kunnen eerder gedeelde profiel- en betaalgegevens nog bewaren. Profiel verwijderen? We konden uw profielgegevens niet verwijderen. Probeer het opnieuw, of ontkoppel deze pubky van Bitkit. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 480fd04042..893516d2f2 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1478,6 +1478,7 @@ Wczytywanie Twojego profilu… Wejdź do\n<accent>wolnej sieci</accent> Nie udało się utworzyć profilu + Aktywne subskrypcje uniemożliwiają usunięcie tego profilu. Usunięcie profilu usuwa go z Pubky. Kontakty mogą nadal przechowywać udostępnione im wcześniej dane profilu i płatności. Usunąć profil? Nie udało się usunąć danych Twojego profilu. Spróbuj ponownie lub odłącz ten pubky od Bitkit. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 7d48e5a6f6..a96d89e5f0 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1480,6 +1480,7 @@ Carregando seu perfil… Entre na\n<accent>web da liberdade</accent> Falha ao criar perfil + As assinaturas ativas impedem a remoção deste perfil. Excluir seu perfil o remove do Pubky. Os contatos ainda podem manter informações de perfil e de pagamento compartilhadas anteriormente com eles. Excluir Perfil? Não conseguimos excluir os dados do seu perfil. Tente novamente ou desconecte esta pubky da Bitkit. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index aef7c3de1f..6fa8661d40 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1454,6 +1454,7 @@ A carregar o seu perfil… Entre na\n<accent>web da liberdade</accent> Falha ao criar perfil + As subscrições ativas impedem a remoção deste perfil. Eliminar o seu perfil remove-o do Pubky. Os contactos podem manter as informações de perfil e pagamento partilhadas anteriormente com eles. Eliminar perfil? Não foi possível eliminar os dados do seu perfil. Tente novamente ou desligue este pubky da Bitkit. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 6885fd0628..e40226db5c 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1495,6 +1495,7 @@ Загрузка вашего профиля… Войдите в\n<accent>свободный веб</accent> Не удалось создать профиль + Активные подписки не позволяют удалить этот профиль. Удаление профиля удалит его из Pubky. У контактов могут остаться данные профиля и платёжные данные, которыми вы делились ранее. Удалить Профиль? Не удалось удалить данные вашего профиля. Повторите попытку или отключите этот pubky от Bitkit. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index c195a779ce..6f448e5593 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -815,6 +815,7 @@ Enter the\n<accent>freedom web</accent> Failed to create profile Create Profile + Active subscriptions prevent removing this profile. Deleting your profile removes it from Pubky. Contacts may still retain profile and payment information previously shared with them. Delete Profile? We couldn\'t delete your profile data. Retry, or disconnect this pubky from Bitkit. diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 4b0f5cf4d2..b310ff369f 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -1552,6 +1552,26 @@ class PubkyRepoTest : BaseUnitTest() { verifyBlocking(pubkyService) { deletePubkyProfile("revision-Test", VALID_SELF_KEY) } } + @Test + fun `pubky app deletion does not renew the session or replay an identity error`() = test { + val secretKey = "local_secret" + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(secretKey) + whenever(pubkyService.publicKeyFromSecret(secretKey)).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) + val identityError = PaykitException.Identity("identity_error", "Missing capabilities") + whenever(pubkyService.deletePubkyProfile("revision-Test", VALID_SELF_KEY)) + .thenAnswer { throw identityError } + .thenReturn(Unit) + + val result = sut.deleteProfile() + + assertSame(identityError, result.exceptionOrNull()) + verify(pubkyService).deletePubkyProfile("revision-Test", VALID_SELF_KEY) + verify(pubkyService, never()).signIn(any()) + verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).signOut() + } + @Test fun `deleteProfile is not followed by a profile copy write from a load under way`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) @@ -2197,7 +2217,7 @@ class PubkyRepoTest : BaseUnitTest() { createContactRecord(VALID_CONTACT_KEY_B, label = "Bob"), ) whenever(pubkyService.contactRecords()).thenReturn(records) - whenever(pubkyService.removeContacts(records.map { it.publicKey })).thenReturn(records) + whenever(pubkyService.removeContactsForProfile(records.map { it.publicKey })).thenReturn(records) val bulkCancelled = CompletableDeferred() val screenCancelled = CompletableDeferred() whenever(pubkyService.resolveContactProfile(VALID_CONTACT_KEY_A, true, PaykitReadLane.Bulk)) @@ -2236,10 +2256,150 @@ class PubkyRepoTest : BaseUnitTest() { deletion.await().getOrThrow() screenLookup.await() assertTrue(sut.contacts.value.isEmpty()) - verify(pubkyService).removeContacts(records.map { it.publicKey }) + verify(pubkyService).removeContactsForProfile(records.map { it.publicKey }) verify(pubkyService, never()).removeContact(any()) } + @Test + fun `active subscription is preserved through service wrappers before profile cleanup`() = test { + authenticateForTesting() + val expected = PubkyContactError.ActiveProfileSubscriptions(1_800_000_000_000L) + val wrapped = IllegalStateException("Service operation failed", expected) + whenever(pubkyService.checkProfileDeletionAllowed()).thenAnswer { throw wrapped } + clearInvocations(pubkyStore, pubkyService) + + assertSame(expected, sut.checkProfileDeletionAllowed().exceptionOrNull()) + assertSame(expected, sut.deleteProfile().exceptionOrNull()) + + verify(pubkyService, never()).contactRecords() + verify(pubkyService, never()).removeContactsForProfile(any()) + verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).signOut() + verify(pubkyStore, never()).update(any()) + } + + @Test + fun `late subscription rejection retains contacts and credentials`() = test { + authenticateForTesting() + val records = listOf(createContactRecord(VALID_CONTACT_KEY_A, label = "Retained")) + whenever(pubkyService.contactRecords()).thenReturn(records) + sut.loadContacts() + val expected = PubkyContactError.ActiveProfileSubscriptions(1_800_000_000_000L) + val wrapped = IllegalStateException("Service operation failed", expected) + whenever(pubkyService.removeContactsForProfile(any())).thenAnswer { throw wrapped } + clearInvocations(pubkyStore) + + assertSame(expected, sut.deleteProfile().exceptionOrNull()) + + assertEquals(listOf(VALID_CONTACT_KEY_A), sut.contacts.value.map { it.publicKey }) + verify(pubkyStore, never()).update(any()) + verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).signOut() + } + + @Test + fun `subscription refusal at profile deletion preserves the session without contacts`() = test { + authenticateForTesting() + whenever(pubkyService.contactRecords()).thenReturn(emptyList()) + val expected = PubkyContactError.ActiveProfileSubscriptions(null) + whenever(pubkyService.deletePaykitProfile()) + .thenAnswer { throw IllegalStateException("Service operation failed", expected) } + clearInvocations(pubkyStore, settingsStore) + + assertSame(expected, sut.deleteProfile().exceptionOrNull()) + + verify(pubkyService, never()).removeContactsForProfile(any()) + verify(pubkyService, never()).signOut() + verify(pubkyStore, never()).update(any()) + verify(settingsStore, never()).update(any()) + } + + @Test + fun `partial contact cleanup preserves retained contacts and stops profile deletion`() = test { + authenticateForTesting() + val records = listOf( + createContactRecord(VALID_CONTACT_KEY_A, label = "Removed"), + createContactRecord(VALID_CONTACT_KEY_B, label = "Retained"), + ) + val overrides = records.associate { + it.publicKey to PubkyProfile.placeholder(it.publicKey).toProfileData() + } + var stored = PubkyStoreData(contactProfileOverrides = overrides) + whenever(pubkyStore.data).thenReturn(flowOf(stored)) + whenever(pubkyStore.update(any())).thenAnswer { + stored = it.getArgument<(PubkyStoreData) -> PubkyStoreData>(0)(stored) + Unit + } + whenever(pubkyService.contactRecords()).thenReturn(records) + whenever( + pubkyService.removeContactsForProfile(records.map { it.publicKey }) + ).thenReturn(listOf(records.first())) + sut.loadContacts() + + val result = sut.deleteProfile() + + assertTrue(result.isFailure) + assertEquals(listOf(VALID_CONTACT_KEY_B), sut.contacts.value.map { it.publicKey }) + assertEquals(setOf(VALID_CONTACT_KEY_B), stored.contactProfileOverrides.keys) + verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).signOut() + } + + @Test + fun `unavailable contact read does not authorize profile deletion`() = test { + authenticateForTesting() + val error = TestAppError("Fetch failed: 404 missing session") + whenever(pubkyService.contactRecords()).thenAnswer { throw error } + clearInvocations(pubkyStore) + + val result = sut.deleteProfile() + + assertSame(error, result.exceptionOrNull()) + verify(pubkyStore, never()).update(any()) + verify(pubkyService, never()).removeContactsForProfile(any()) + verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).signOut() + } + + @Test + fun `uncertain contact cleanup preserves local evidence and stops profile deletion`() = test { + authenticateForTesting() + val record = createContactRecord(VALID_CONTACT_KEY_A, label = "Retained") + val records = listOf(record) + val error = TestAppError("Contact removal acknowledgement lost") + whenever(pubkyService.contactRecords()).thenReturn(records) + whenever(pubkyService.removeContactsForProfile(listOf(record.publicKey))).thenAnswer { throw error } + sut.loadContacts() + clearInvocations(pubkyStore) + + val result = sut.deleteProfile() + + assertSame(error, result.exceptionOrNull()) + assertEquals(listOf(VALID_CONTACT_KEY_A), sut.contacts.value.map { it.publicKey }) + verify(pubkyStore, never()).update(any()) + verify(pubkyService, never()).deletePaykitProfile() + verify(pubkyService, never()).signOut() + } + + @Test + fun `profile deletion errors mentioning missing data do not authorize sign out`() = test { + authenticateForTesting() + settingsFlow.value = SettingsData( + sharesPublicPaykitEndpoints = true, + sharesPrivatePaykitEndpoints = true, + ) + val error = TestAppError("Delete failed: HTTP 404 Not Found at session endpoint") + whenever(pubkyService.deletePaykitProfile()).thenAnswer { throw error } + + val result = sut.deleteProfile() + + assertSame(error, result.exceptionOrNull()) + assertTrue(sut.isAuthenticated.value) + assertTrue(settingsFlow.value.sharesPublicPaykitEndpoints) + assertTrue(settingsFlow.value.sharesPrivatePaykitEndpoints) + verify(pubkyService, never()).signOut() + } + @Test fun `deleteProfile should fail when signOut fails`() = test { authenticateForTesting() @@ -2259,36 +2419,46 @@ class PubkyRepoTest : BaseUnitTest() { } @Test - fun `deleteProfileWithSessionRetry should refresh session and retry delete`() = test { - val expiredSession = "expired_session" - val newSession = "new_session" + fun `profile deletion does not replay after an uncertain response`() = test { val secretKey = "local_secret" - authenticateForTesting(publicKey = VALID_SELF_KEY, secret = expiredSession) - whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn(expiredSession, newSession) + authenticateForTesting(publicKey = VALID_SELF_KEY, secret = "test_session") whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(secretKey) - whenever(pubkyService.deletePaykitProfile()).thenAnswer { throw TestAppError("Expired") }.thenReturn(Unit) - whenever(pubkyService.signIn(secretKey)).thenReturn(Unit) whenever(pubkyService.publicKeyFromSecret(secretKey)).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) + val uncertainResponse = TestAppError("Connection closed after profile deletion") + whenever(pubkyService.deletePaykitProfile()).thenAnswer { throw uncertainResponse }.thenReturn(Unit) - val result = sut.deleteProfileWithSessionRetry() + val result = sut.deleteProfile() - assertTrue(result.isSuccess) - verifyBlocking(pubkyService, times(2)) { deletePaykitProfile() } + assertSame(uncertainResponse, result.exceptionOrNull()) + verify(pubkyService).deletePaykitProfile() + verify(pubkyService, never()).signIn(any()) + verify(pubkyService, never()).signOut() } @Test - fun `deleteProfileWithSessionRetry should return failure when session cannot refresh`() = test { - val expiredSession = "expired_session" - authenticateForTesting(publicKey = VALID_SELF_KEY, secret = expiredSession) - whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn(expiredSession) - whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(null) - whenever(pubkyService.deletePaykitProfile()).thenAnswer { throw TestAppError("Expired") } - - val result = sut.deleteProfileWithSessionRetry() + fun `failed profile deletion does not restore an identity after sign out`() = test { + val secretKey = "local_secret" + authenticateForTesting(publicKey = VALID_SELF_KEY, secret = "test_session") + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(secretKey) + whenever(pubkyService.publicKeyFromSecret(secretKey)).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) + val deletionStarted = CompletableDeferred() + val finishDeletion = CompletableDeferred() + val uncertainResponse = TestAppError("Connection closed after profile deletion") + whenever(pubkyService.deletePaykitProfile()).doSuspendableAnswer { + deletionStarted.complete(Unit) + withContext(NonCancellable) { finishDeletion.await() } + throw uncertainResponse + } + val deletion = async { sut.deleteProfile() } + deletionStarted.await() + sut.signOut().getOrThrow() + finishDeletion.complete(Unit) - assertTrue(result.isFailure) - verifyBlocking(pubkyService) { deletePaykitProfile() } - verifyBlocking(pubkyService, never()) { signIn(any()) } + assertSame(uncertainResponse, deletion.await().exceptionOrNull()) + assertNull(sut.publicKey.value) + assertFalse(sut.isAuthenticated.value) + verify(pubkyService, never()).signIn(any()) + verify(pubkyService).deletePaykitProfile() } @Test @@ -4558,31 +4728,6 @@ class PubkyRepoTest : BaseUnitTest() { assertFalse(profileSetupPending.value) } - @Test - fun `refreshSessionIfPossible should refresh session when local secret key exists`() = test { - val secretKey = "local_secret" - whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(secretKey) - whenever(pubkyService.signIn(secretKey)).thenReturn(Unit) - whenever(pubkyService.publicKeyFromSecret(secretKey)).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) - - val result = sut.refreshSessionIfPossible() - - assertEquals(true, result.getOrNull()) - assertEquals(VALID_SELF_KEY, sut.publicKey.value) - assertTrue(sut.isAuthenticated.value) - } - - @Test - fun `refreshSessionIfPossible should return false when local secret key is missing`() = test { - whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn(null) - - val result = sut.refreshSessionIfPossible() - - assertEquals(false, result.getOrNull()) - assertNull(sut.publicKey.value) - assertFalse(sut.isAuthenticated.value) - } - @Test fun `restoreSessionBackupState should derive local secret key for local seed backups`() = test { whenever(keychain.loadString(Keychain.Key.BIP39_MNEMONIC.name)).thenReturn("test mnemonic") @@ -5486,7 +5631,7 @@ class PubkyRepoTest : BaseUnitTest() { } @Test - fun `a contact edit started before the session of its identity is refreshed still saves`() = test { + fun `a contact edit started before the session of its identity is restored still saves`() = test { val store = stubGatedPubkyStore() authenticateForTesting(publicKey = VALID_SELF_KEY) whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("local_secret") @@ -5494,7 +5639,7 @@ class PubkyRepoTest : BaseUnitTest() { whenever(pubkyService.publicKeyFromSecret("local_secret")).thenReturn(VALID_SELF_KEY.removePrefix("pubky")) val signIn = checkNotNull(sut.currentSignIn()) - assertEquals(true, sut.refreshSessionIfPossible().getOrNull()) + sut.initialize().getOrThrow() val result = sut.updateContact(signIn, VALID_CONTACT_KEY_A, "Alice", "", null, emptyList(), listOf("Friend")) assertTrue(result.isSuccess) @@ -5771,7 +5916,7 @@ class PubkyRepoTest : BaseUnitTest() { authenticateForTesting() whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("test_secret") val records = listOf(createContactRecord(VALID_CONTACT_KEY_A, "Saved")) - whenever(pubkyService.removeContacts(records.map { it.publicKey })).thenReturn(records) + whenever(pubkyService.removeContactsForProfile(records.map { it.publicKey })).thenReturn(records) whenever(pubkyService.deletePaykitProfile()).thenAnswer { throw TestAppError("Offline") } val newRead = createResolution(VALID_CONTACT_KEY_A, paykitProfile = createPaykitProfile("Alice", "New")) val oldRead = holdScreenLookup(VALID_CONTACT_KEY_A, laterRead = newRead) diff --git a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt index 9f723fd546..30b91b5481 100644 --- a/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt +++ b/app/src/test/java/to/bitkit/services/PaykitSdkServiceTest.kt @@ -16,6 +16,7 @@ import com.synonym.paykit.PaykitAppRegistry import com.synonym.paykit.PaykitException import com.synonym.paykit.PaykitIdentitySecretKey import com.synonym.paykit.PaykitNoiseKeyAuthorization +import com.synonym.paykit.PaykitProfileRecord import com.synonym.paykit.PaykitSdk import com.synonym.paykit.PaykitStateObservation import com.synonym.paykit.PaymentPayload @@ -98,6 +99,7 @@ import to.bitkit.repositories.PubkyContactError import to.bitkit.services.PaykitSdkOperationLock.Priority import to.bitkit.test.forEachCase import to.bitkit.utils.AppError +import java.time.Instant import kotlin.coroutines.cancellation.CancellationException import kotlin.test.assertContentEquals import kotlin.test.assertEquals @@ -2469,6 +2471,10 @@ class PaykitSdkServiceTest { val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } assertFailsWith { service.removeContact(RING_PUBKY) } assertTrue(service.removeContacts(listOf(RING_PUBKY)).isEmpty()) + assertFailsWith { service.checkProfileDeletionAllowed() } + assertFailsWith { + service.removeContactsForProfile(listOf(RING_PUBKY, "pubkyunrelated")) + } verify(sdk, never()).blockPeer(any()) verify(sdk, never()).removeContact(any()) verify(sdk, never()).removeContactsAndBlockPeers(any()) @@ -2482,9 +2488,174 @@ class PaykitSdkServiceTest { val removed = listOf(mock()) whenever(sdk.removeContactsAndBlockPeers(listOf(RING_PUBKY))).thenReturn(removed) assertEquals(removed, service.removeContacts(listOf(RING_PUBKY))) + service.checkProfileDeletionAllowed() + assertEquals(removed, service.removeContactsForProfile(listOf(RING_PUBKY))) + } + } + + @Test + fun `profile removal conservatively blocks unknown or future subscription expiry`() = runTest { + for (endsAt in listOf(null, "invalid", "2999-01-01T00:00:00Z")) { + val sdk = mock() + val recurrence = mock { on { this.endsAt } doReturn endsAt } + val requestTerms = mock { on { this.recurrence } doReturn recurrence } + val request = mock { + on { counterparty } doReturn RING_PUBKY + on { state } doReturn PaymentRequestLifecycleState.ACTIVE_RECURRING + on { terms } doReturn requestTerms + } + whenever(sdk.paymentRequests()).thenReturn(listOf(request)) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + + assertFailsWith { service.checkProfileDeletionAllowed() } + assertFailsWith { + service.removeContactsForProfile(listOf("pubkyunrelated")) + } + verify(sdk, never()).removeContactsAndBlockPeers(any()) } } + @Test + fun `profile refusal reports a date only when every blocking subscription has a finite end`() = runTest { + val earlier = "2999-01-01T00:00:00Z" + val later = "3000-01-01T00:00:00Z" + val cases = listOf( + listOf(earlier, later) to later, + listOf(later, earlier) to later, + listOf(earlier, null) to null, + listOf("invalid", later) to null, + listOf("2000-01-01T00:00:00Z", later) to later, + ) + for ((ends, expected) in cases) { + val sdk = mock() + val requests = ends.map { end -> + val recurrence = mock { on { endsAt } doReturn end } + val terms = mock { on { this.recurrence } doReturn recurrence } + mock { + on { state } doReturn PaymentRequestLifecycleState.ACTIVE_RECURRING + on { this.terms } doReturn terms + } + } + whenever(sdk.paymentRequests()).thenReturn(requests) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val refusal = assertFailsWith { + service.checkProfileDeletionAllowed() + } + assertEquals(expected?.let { Instant.parse(it).toEpochMilli() }, refusal.endsAtMillis) + val lateRefusal = assertFailsWith { + service.removeContactsForProfile(listOf(RING_PUBKY)) + } + assertEquals(refusal.endsAtMillis, lateRefusal.endsAtMillis) + verify(sdk, never()).removeContactsAndBlockPeers(any()) + } + } + + @Test + fun `profile deletion rejects a subscription received after preflight`() = runTest { + for (pubkyApp in listOf(false, true)) { + for (role in listOf(PaymentRequestLocalRole.PAYER, PaymentRequestLocalRole.PAYEE)) { + val sdk = mock() + val request = mock { + on { localRole } doReturn role + on { state } doReturn PaymentRequestLifecycleState.ACTIVE_RECURRING + } + val profile = mock { on { revision } doReturn "original" } + whenever(sdk.identityStatus()) + .thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + whenever(sdk.fetchPaykitProfile(RING_PUBKY)).thenReturn(profile) + val checking = CompletableDeferred() + val finishCheck = CompletableDeferred() + var requests = emptyList() + whenever(sdk.paymentRequests()).doSuspendableAnswer { + if (!checking.isCompleted) { + checking.complete(Unit) + finishCheck.await() + } + requests + } + whenever(sdk.receivePrivateMessagesFromLinkedPeers()).thenAnswer { + requests = listOf(request) + emptyList() + } + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + val preflight = async { service.checkProfileDeletionAllowed() } + checking.await() + val receive = async { service.receivePrivateMessagesFromLinkedPeers(Priority.Background) } + runCurrent() + val deletion = async { + runSuspendCatching { + if (pubkyApp) { + service.deletePubkyProfile("original", RING_PUBKY) + } else { + service.deletePaykitProfile() + } + } + } + runCurrent() + finishCheck.complete(Unit) + preflight.await() + receive.await() + + assertIs(deletion.await().exceptionOrNull()) + verify(sdk, never()).deletePaykitProfile(any()) + verify(sdk, never()).deletePubkyProfile(any()) + verify(sdk, never()).fetchPaykitProfile(any()) + } + } + } + + @Test + fun `profile deletion permits no active subscription`() = runTest { + for (ended in listOf(false, true)) { + val sdk = mock() + val recurrence = mock { on { endsAt } doReturn "2000-01-01T00:00:00Z" } + val terms = mock { on { this.recurrence } doReturn recurrence } + val request = mock { + on { state } doReturn PaymentRequestLifecycleState.ACTIVE_RECURRING + on { this.terms } doReturn terms + } + whenever(sdk.paymentRequests()).thenReturn(if (ended) listOf(request) else emptyList()) + whenever(sdk.identityStatus()) + .thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + val profile = mock { on { revision } doReturn "original" } + whenever(sdk.fetchPaykitProfile(RING_PUBKY)).thenReturn(profile) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + + service.deletePaykitProfile() + service.deletePubkyProfile("original", RING_PUBKY) + + verify(sdk).deletePaykitProfile("original") + verify(sdk).deletePubkyProfile("original") + } + } + + @Test + fun `profile removal fails closed when subscriptions cannot be read`() = runTest { + val sdk = mock() + val error = IllegalStateException("Subscription storage unavailable") + whenever(sdk.paymentRequests()).thenAnswer { throw error } + whenever(sdk.identityStatus()) + .thenReturn(IdentityStatus(RING_PUBKY, PubkyIdentityCapability.PRIVATE_LINK_CAPABLE)) + val service = PaykitSdkService(mock(), mock(), mock(), settingsStore = mock()) { sdk } + + assertSame(error, assertFailsWith { service.checkProfileDeletionAllowed() }) + assertSame(error, assertFailsWith { service.deletePaykitProfile() }) + assertSame( + error, + assertFailsWith { service.deletePubkyProfile("original", RING_PUBKY) } + ) + assertSame( + error, + assertFailsWith { + service.removeContactsForProfile(listOf(RING_PUBKY)) + } + ) + verify(sdk, never()).removeContactsAndBlockPeers(any()) + verify(sdk, never()).deletePaykitProfile(any()) + verify(sdk, never()).deletePubkyProfile(any()) + verify(sdk, never()).fetchPaykitProfile(any()) + } + @Test fun `unreadable profile cache stops activation`() = runTest { for (error in listOf( diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt index 83107c23de..26a4f9f760 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/EditProfileViewModelTest.kt @@ -22,13 +22,16 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.R +import to.bitkit.ext.toLocalizedTimestamp import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyProfileLink import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.ProfileEditBase +import to.bitkit.repositories.PubkyContactError import to.bitkit.repositories.PubkyRepo import to.bitkit.test.BaseUnitTest import to.bitkit.utils.AppError +import java.util.Locale import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -43,6 +46,90 @@ class EditProfileViewModelTest : BaseUnitTest() { private val pubkyRepo: PubkyRepo = mock() private val privatePaykitRepo: PrivatePaykitRepo = mock() + @Test + fun `active subscription stops profile deletion before private or contact cleanup`() = test { + val sut = createSut() + whenever( + pubkyRepo.checkProfileDeletionAllowed() + ).thenReturn(Result.failure(PubkyContactError.ActiveSubscription)) + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) + advanceUntilIdle() + + sut.deleteProfile() + advanceUntilIdle() + + verify(pubkyRepo).checkProfileDeletionAllowed() + verify(context).getString(R.string.profile__delete_active_subscription) + verify(privatePaykitRepo, never()).beginProfileDeletion() + verify(privatePaykitRepo, never()).endProfileDeletion() + verify(privatePaykitRepo, never()).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) + verify(privatePaykitRepo, never()).closeAndClear() + verify(pubkyRepo, never()).deleteProfile() + assertFalse(sut.uiState.value.showDeleteFailureDialog) + assertFalse(sut.uiState.value.isDeleting) + } + + @Test + fun `fixed term refusal displays the supplied expiry without starting cleanup`() = test { + val previousLocale = Locale.getDefault() + Locale.setDefault(Locale.US) + try { + val sut = createSut() + val endsAt = 1_800_000_000_000L + whenever(pubkyRepo.checkProfileDeletionAllowed()).thenReturn( + Result.failure(PubkyContactError.ActiveProfileSubscriptions(endsAt)), + ) + advanceUntilIdle() + + sut.deleteProfile() + advanceUntilIdle() + + verify(context).getString(R.string.profile__delete_active_subscription) + verify(context).getString(R.string.subscriptions__expires_date, endsAt.toLocalizedTimestamp()) + verify(privatePaykitRepo, never()).beginProfileDeletion() + verify(privatePaykitRepo, never()).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) + verify(pubkyRepo, never()).deleteProfile() + assertFalse(sut.uiState.value.showDeleteFailureDialog) + } finally { + Locale.setDefault(previousLocale) + } + } + + @Test + fun `unavailable subscription read retains cleanup and shows failure`() = test { + val sut = createSut() + whenever(pubkyRepo.checkProfileDeletionAllowed()).thenReturn(Result.failure(TestAppError("Unavailable"))) + advanceUntilIdle() + + sut.deleteProfile() + advanceUntilIdle() + + assertTrue(sut.uiState.value.showDeleteFailureDialog) + assertFalse(sut.uiState.value.isDeleting) + verify(privatePaykitRepo, never()).beginProfileDeletion() + verify(privatePaykitRepo, never()).endProfileDeletion() + verify(pubkyRepo, never()).deleteProfile() + } + + @Test + fun `cancellation during subscription read does not start or end private cleanup`() = test { + val sut = createSut() + val read = CompletableDeferred>() + whenever(pubkyRepo.checkProfileDeletionAllowed()).doSuspendableAnswer { read.await() } + advanceUntilIdle() + sut.deleteProfile() + advanceUntilIdle() + + sut.viewModelScope.cancel() + advanceUntilIdle() + + assertFalse(sut.uiState.value.isDeleting) + assertFalse(sut.uiState.value.showDeleteFailureDialog) + verify(privatePaykitRepo, never()).beginProfileDeletion() + verify(privatePaykitRepo, never()).endProfileDeletion() + verify(pubkyRepo, never()).deleteProfile() + } + @Test fun `disconnect finishes private cleanup after the screen is closed`() = test { val sut = createSut() @@ -62,7 +149,7 @@ class EditProfileViewModelTest : BaseUnitTest() { sut.showDeleteConfirmation() advanceUntilIdle() verify(pubkyRepo, times(1)).forgetUnrestoredIdentity() - verify(pubkyRepo, never()).deleteProfileWithSessionRetry() + verify(pubkyRepo, never()).deleteProfile() verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), anyOrNull(), any()) assertFalse(sut.uiState.value.showDeleteDialog) @@ -115,7 +202,7 @@ class EditProfileViewModelTest : BaseUnitTest() { val sut = createSut() advanceUntilIdle() val result = CompletableDeferred>() - whenever(pubkyRepo.deleteProfileWithSessionRetry()).doSuspendableAnswer { result.await() } + whenever(pubkyRepo.deleteProfile()).doSuspendableAnswer { result.await() } sut.showDeleteConfirmation() sut.deleteProfile() @@ -131,7 +218,7 @@ class EditProfileViewModelTest : BaseUnitTest() { sut.disconnectProfile() sut.showDeleteConfirmation() advanceUntilIdle() - verify(pubkyRepo, times(1)).deleteProfileWithSessionRetry() + verify(pubkyRepo, times(1)).deleteProfile() verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), anyOrNull(), any()) verify(pubkyRepo, never()).signOut() assertFalse(sut.uiState.value.showDeleteDialog) @@ -165,7 +252,7 @@ class EditProfileViewModelTest : BaseUnitTest() { sut.showDeleteConfirmation() advanceUntilIdle() verify(pubkyRepo, times(1)).saveProfile(any(), any(), any(), any(), anyOrNull(), any()) - verify(pubkyRepo, never()).deleteProfileWithSessionRetry() + verify(pubkyRepo, never()).deleteProfile() verify(pubkyRepo, never()).forgetUnrestoredIdentity() assertFalse(sut.uiState.value.showDeleteDialog) @@ -185,9 +272,52 @@ class EditProfileViewModelTest : BaseUnitTest() { assertEquals("https://updated.example.com", sut.uiState.value.links.first().url) } + @Test + fun `failed private cleanup stops deletion and preserves pending state`() = test { + val sut = createSut() + advanceUntilIdle() + whenever(privatePaykitRepo.removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true))) + .thenReturn(Result.failure(TestAppError("Withdrawal pending"))) + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) + + sut.effects.test { + sut.deleteProfile() + advanceUntilIdle() + expectNoEvents() + } + + assertTrue(sut.uiState.value.showDeleteFailureDialog) + assertFalse(sut.uiState.value.isDeleting) + verify(pubkyRepo, never()).deleteProfile() + verify(privatePaykitRepo, never()).closeAndClear() + verify(privatePaykitRepo).endProfileDeletion() + } + + @Test + fun `failed local finalization does not report deletion success`() = test { + val sut = createSut() + advanceUntilIdle() + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) + whenever( + privatePaykitRepo.closeAndClear() + ).thenReturn(Result.failure(TestAppError("Local storage unavailable"))) + + sut.effects.test { + sut.deleteProfile() + advanceUntilIdle() + expectNoEvents() + } + + assertFalse(sut.uiState.value.showDeleteFailureDialog) + assertFalse(sut.uiState.value.isDeleting) + verify(pubkyRepo).deleteProfile() + verify(privatePaykitRepo).closeAndClear() + verify(privatePaykitRepo).endProfileDeletion() + } + @Test fun `deleteProfile should emit success when repository delete succeeds`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) val sut = createSut() advanceUntilIdle() @@ -201,14 +331,14 @@ class EditProfileViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.showDeleteFailureDialog) inOrder(privatePaykitRepo, pubkyRepo).apply { verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) - verify(pubkyRepo).deleteProfileWithSessionRetry() + verify(pubkyRepo).deleteProfile() verify(privatePaykitRepo).closeAndClear() } } @Test fun `profile created in Bitkit keeps delete copy`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) val sut = createSut() advanceUntilIdle() @@ -222,7 +352,7 @@ class EditProfileViewModelTest : BaseUnitTest() { @Test fun `ring identity is unlinked with the same cleanup`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) val sut = createSut(isRingIdentity = true) advanceUntilIdle() @@ -238,7 +368,7 @@ class EditProfileViewModelTest : BaseUnitTest() { verify(context, never()).getString(R.string.profile__delete_success) inOrder(privatePaykitRepo, pubkyRepo).apply { verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) - verify(pubkyRepo).deleteProfileWithSessionRetry() + verify(pubkyRepo).deleteProfile() verify(privatePaykitRepo).closeAndClear() } } @@ -260,7 +390,7 @@ class EditProfileViewModelTest : BaseUnitTest() { @Test fun `retryDeleteProfile should emit success when repository delete succeeds`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) + whenever(pubkyRepo.deleteProfile()).thenReturn(Result.success(Unit)) val sut = createSut() advanceUntilIdle() @@ -274,14 +404,14 @@ class EditProfileViewModelTest : BaseUnitTest() { assertFalse(sut.uiState.value.showDeleteFailureDialog) inOrder(privatePaykitRepo, pubkyRepo).apply { verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) - verify(pubkyRepo).deleteProfileWithSessionRetry() + verify(pubkyRepo).deleteProfile() verify(privatePaykitRepo).closeAndClear() } } @Test fun `deleteProfile should show retry dialog when delete still fails`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn( + whenever(pubkyRepo.deleteProfile()).thenReturn( Result.failure(TestAppError("expired session")), ) @@ -299,7 +429,7 @@ class EditProfileViewModelTest : BaseUnitTest() { @Test fun `disconnectProfile should emit disconnect success`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn( + whenever(pubkyRepo.deleteProfile()).thenReturn( Result.failure(TestAppError("expired session")), ) whenever(pubkyRepo.signOut()).thenReturn(Result.success(Unit)) @@ -353,32 +483,9 @@ class EditProfileViewModelTest : BaseUnitTest() { verify(privatePaykitRepo, never()).closeAndClear() } - @Test - fun `deleteProfile should continue when private cleanup fails`() = test { - val sut = createSut() - whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) } - .thenReturn(Result.failure(TestAppError("cleanup failed"))) - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) - advanceUntilIdle() - - sut.effects.test { - sut.deleteProfile() - advanceUntilIdle() - - assertEquals(EditProfileEffect.DeleteSuccess, awaitItem()) - } - assertFalse(sut.uiState.value.showDeleteFailureDialog) - assertFalse(sut.uiState.value.isDeleting) - inOrder(privatePaykitRepo, pubkyRepo).apply { - verify(privatePaykitRepo).removePublishedEndpointsForCleanup(any(), deferAppSync = eq(true)) - verify(pubkyRepo).deleteProfileWithSessionRetry() - verify(privatePaykitRepo).closeAndClear() - } - } - @Test fun `dismissDeleteFailureDialog should hide retry dialog`() = test { - whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn( + whenever(pubkyRepo.deleteProfile()).thenReturn( Result.failure(TestAppError("expired session")), ) @@ -402,6 +509,7 @@ class EditProfileViewModelTest : BaseUnitTest() { } else { whenever { pubkyRepo.isRingAdoptedIdentity() }.thenReturn(isRingIdentity) } + whenever { pubkyRepo.checkProfileDeletionAllowed() }.thenReturn(Result.success(Unit)) whenever { pubkyRepo.forgetUnrestoredIdentity() }.thenReturn(Result.success(false)) whenever(pubkyRepo.profile).thenReturn(MutableStateFlow(createProfile())) whenever(pubkyRepo.profileEditBase()).thenReturn(ProfileEditBase(createProfile(), "revision")) diff --git a/changelog.d/next/1688.fixed.md b/changelog.d/next/1688.fixed.md new file mode 100644 index 0000000000..fb97b9ecd4 --- /dev/null +++ b/changelog.d/next/1688.fixed.md @@ -0,0 +1 @@ +Prevent uncertain profile deletion failures from automatically repeating contact cleanup and deletion. diff --git a/changelog.d/next/1690.fixed.md b/changelog.d/next/1690.fixed.md new file mode 100644 index 0000000000..2cae693deb --- /dev/null +++ b/changelog.d/next/1690.fixed.md @@ -0,0 +1 @@ +Preserve profile data when cleanup is incomplete or active subscriptions prevent removal, and show a known expiry instead of asking users to cancel fixed-term subscriptions. diff --git a/journeys/profile/delete-profile-uncertain-response.xml b/journeys/profile/delete-profile-uncertain-response.xml new file mode 100644 index 0000000000..fe825c36ff --- /dev/null +++ b/journeys/profile/delete-profile-uncertain-response.xml @@ -0,0 +1,17 @@ + + + Requires a disposable test identity and a controlled homeserver proxy; never use a personal profile. + Configure the proxy to accept one profile deletion but lose its acknowledgement, retaining a redacted + request counter. This is a fault-injection fixture requirement, not evidence that this journey has run. + Normal SDK recovery may retry an individual request only after a confirmed authentication rejection; + the app must not restart contact cleanup and profile deletion because a request has an uncertain outcome. + + + Open Edit Profile and confirm deletion + Drop the acknowledgement after the server accepts the profile deletion + Verify failure options are shown and no success notification or onboarding navigation occurs + Wait through the network timeout and verify the app starts no second contact cleanup, profile deletion or sign-in + Cancel the failure dialog and verify no mutation is retried + Restart the app without choosing Retry and verify it does not automatically repeat the deletion + + diff --git a/journeys/profile/profile-cleanup-failure.xml b/journeys/profile/profile-cleanup-failure.xml new file mode 100644 index 0000000000..9b7a6747e5 --- /dev/null +++ b/journeys/profile/profile-cleanup-failure.xml @@ -0,0 +1,27 @@ + + + Requires a disposable test identity with saved contacts and a controlled homeserver proxy. + Never use a personal profile. Inject a private-endpoint withdrawal failure, then in a fresh + fixture inject an unknown contact-removal response or a partial removal acknowledging only some contacts. + Separately prepare an active recurring subscription in each role (payer and payee), with an + unrelated saved contact, and record endpoint/contact state before confirming removal. Verify + the subscription warning appears before cleanup; cancel or expire the subscription in the + disposable fixture and confirm removal again to verify it can proceed. + Also inject a profile-deletion error whose message contains 404 Not Found, without confirming deletion. + These controls are not available in standard staging. This journey covers stopping on incomplete + cleanup, not cross-device conditional deletion or safe manual replay of an uncertain operation. + + + With an active subscription, confirm profile deletion or unlink and verify the localized refusal; show the latest expiry only when all blocking subscriptions have known finite ends, and no date for open-ended or unknown terms + Verify there is no generic Retry dialog, endpoint withdrawal, contact removal or profile deletion, including for the unrelated contact + After ending the subscription, explicitly confirm removal again and verify acknowledged cleanup succeeds + Open Edit Profile and confirm deletion with the cleanup fault enabled + Verify failure options appear without a success notification or onboarding navigation + Verify a failed private withdrawal is followed by no contact or profile deletion + Verify unknown contact removal keeps local contact data and prevents profile deletion + Verify partial contact removal preserves contacts and overrides not acknowledged as removed + Verify an uncertain profile-deletion error preserves the session and sharing settings without success feedback + Cancel the failure dialog and verify the app starts no second deletion + Restart the app and verify no profile deletion is automatically replayed + +