diff --git a/Bitkit/Managers/ContactsManager.swift b/Bitkit/Managers/ContactsManager.swift index 5a45427de..3074defda 100644 --- a/Bitkit/Managers/ContactsManager.swift +++ b/Bitkit/Managers/ContactsManager.swift @@ -193,7 +193,7 @@ class ContactsManager: ObservableObject { _ = try await PubkyService.removeContact(publicKey: $0) }, removeContactRecords: @escaping @Sendable (_ publicKeys: [String]) async throws -> [ContactRecord] = { - try await PubkyService.removeContacts(publicKeys: $0) + try await PubkyService.removeContactsForProfile(publicKeys: $0) }, forgetRemovedContacts: @escaping @Sendable (_ publicKeys: [String]) async -> Void = { await PrivatePaykitService.shared.removeSavedContacts(publicKeys: $0) @@ -972,22 +972,7 @@ class ContactsManager: ObservableObject { stopPendingProfileLookups() let contactRecords = contactRecords let removeContactRecords = removeContactRecords - let records: [ContactRecord] - do { - records = try await Task.detached { - try await contactRecords() - }.value - } catch { - guard Self.isMissingContactsDataError(error) else { - throw error - } - - Self.clearContactProfileOverrides() - await PrivatePaykitService.shared.pruneUnsavedContactState(savedPublicKeys: []) - contacts.removeAll() - Logger.info("Contacts storage missing, treating delete-all as empty", context: "ContactsManager") - return - } + let records = try await Task.detached { try await contactRecords() }.value let keys = records.compactMap { PubkyPublicKeyFormat.normalized($0.publicKey) } let removed = try await Task.detached { try await removeContactRecords(keys) }.value @@ -1006,17 +991,6 @@ class ContactsManager: ObservableObject { Logger.info("Deleted all contacts", context: "ContactsManager") } - func deleteAllContactsBestEffort() async { - do { - try await deleteAllContacts() - } catch { - Logger.warn("Continuing after contact cleanup failed: \(error)", context: "ContactsManager") - Self.clearContactProfileOverrides() - await PrivatePaykitService.shared.pruneUnsavedContactState(savedPublicKeys: []) - contacts.removeAll() - } - } - // MARK: - Remote Contact Discovery /// Looks every follow's profile up on the interactive read lane: the user waits on the choice screen until the import diff --git a/Bitkit/Managers/PubkyProfileManager.swift b/Bitkit/Managers/PubkyProfileManager.swift index 3534cad89..a5075b567 100644 --- a/Bitkit/Managers/PubkyProfileManager.swift +++ b/Bitkit/Managers/PubkyProfileManager.swift @@ -122,6 +122,7 @@ class PubkyProfileManager: ObservableObject { private let remoteProfileResolver: RemoteProfileResolver private let profilePublisher: ProfilePublisher private let avatarUploader: AvatarUploader + private let profileDeletionValidator: ProfileDeleter private let profileDeleter: ProfileDeleter /// Bumped whenever a profile save starts, `profile` is written or the identity changes, so a remote read that started /// earlier is dropped. @@ -169,6 +170,9 @@ class PubkyProfileManager: ObservableObject { avatarUploader: @escaping AvatarUploader = { try await PubkyAppProfileStore.shared.uploadAvatar($0, expectedIdentity: $1) }, + profileDeletionValidator: @escaping ProfileDeleter = { + try await PubkyService.requireNoActiveSubscriptions(expectedIdentity: $0) + }, profileDeleter: @escaping ProfileDeleter = { // A Ring identity's profile belongs to Ring, so unlinking it leaves its pubky.app profile in place. try await PubkyAppProfileStore.shared.deleteProfile( @@ -180,6 +184,7 @@ class PubkyProfileManager: ObservableObject { self.remoteProfileResolver = remoteProfileResolver self.profilePublisher = profilePublisher self.avatarUploader = avatarUploader + self.profileDeletionValidator = profileDeletionValidator self.profileDeleter = profileDeleter cachedName = UserDefaults.standard.string(forKey: Self.cachedNameKey) cachedImageUri = UserDefaults.standard.string(forKey: Self.cachedImageUriKey) @@ -1136,6 +1141,12 @@ class PubkyProfileManager: ObservableObject { await PrivatePaykitService.shared.endProfileDeletion() } + func validateProfileDeletion(for session: SignedInSession) async throws { + try requireCurrentSession(session) + try await profileDeletionValidator(session.publicKey) + try requireCurrentSession(session) + } + func deleteProfile(cleanPrivatePaykitEndpoints: Bool = true, expectedSession: SignedInSession? = nil) async throws { guard let session = expectedSession ?? currentSession else { throw PubkyServiceError.sessionNotActive } try requireCurrentSession(session) @@ -1151,26 +1162,18 @@ class PubkyProfileManager: ObservableObject { } private func deleteProfile(for session: SignedInSession, cleanPrivatePaykitEndpoints: Bool) async throws { - try requireCurrentSession(session) + try await validateProfileDeletion(for: session) if cleanPrivatePaykitEndpoints { - await Self.removePrivatePaykitEndpointsBestEffort( + try await Self.removePrivatePaykitEndpoints( context: "PubkyProfileManager.deleteProfile", deferAppSync: true, isSessionCurrent: { self.currentSession == session } ) } try requireCurrentSession(session) let delete = profileDeleter - do { - try await Task.detached { - try await delete(session.publicKey) - }.value - } catch { - guard Self.isMissingBitkitProfileStorageError(error) else { - throw error - } - - Logger.info("Bitkit profile storage already missing, continuing sign out", context: "PubkyProfileManager") - } + try await Task.detached { + try await delete(session.publicKey) + }.value try requireCurrentSession(session) invalidateProfileLoads() @@ -2090,31 +2093,6 @@ class PubkyProfileManager: ObservableObject { return normalized } - nonisolated static func isMissingBitkitProfileStorageError(_ error: Error) -> Bool { - if case .profileNotFound = error as? PubkyServiceError { - return true - } - - let errorText = [ - (error as? AppError)?.debugMessage, - error.localizedDescription, - String(describing: error), - ] - .compactMap { $0?.lowercased() } - - if errorText.contains(where: { $0.contains("404 not found") || $0.contains("directory not found") }) { - return true - } - - let nsError = error as NSError - if nsError.domain == NSCocoaErrorDomain { - let cocoaCode = CocoaError.Code(rawValue: nsError.code) - return cocoaCode == .fileNoSuchFile || cocoaCode == .fileReadNoSuchFile - } - - return false - } - nonisolated static func resolveSessionInitialization( savedSessionSecret: String?, storedSecretKeyHex: String?, diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index 3c6736f85..fbda9edd3 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -1117,6 +1117,7 @@ "profile__edit_changed_error" = "تغيّر ملفك الشخصي في pubky.app. حمّل Bitkit أحدث نسخة، لذا أعد إجراء تعديلك."; "profile__edit_public_note" = "هذا هو ملفك الشخصي على pubky.app. إنه عام، والتغييرات التي تجريها هنا تظهر أيضًا على pubky.app."; "profile__edit_tags_error" = "تعذّر على Bitkit حفظ وسومك. حُفظت تغييراتك الأخرى، لذا حاول حفظ الوسوم مرة أخرى."; +"profile__delete_active_subscription" = "تمنع الاشتراكات النشطة إزالة هذا الملف الشخصي."; "profile__delete_title" = "حذف الملف الشخصي؟"; "profile__delete_description" = "يؤدي حذف ملفك الشخصي إلى إزالته من Pubky. قد تحتفظ جهات الاتصال بمعلومات الملف الشخصي والدفع التي شاركتها معهم سابقًا."; "profile__delete_confirm" = "نعم، احذف"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index d0d4122cb..65e05f224 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -1233,6 +1233,7 @@ "profile__edit_changed_error" = "El teu perfil ha canviat a pubky.app. Bitkit ha carregat la versió més recent, així que torna a fer la teva edició."; "profile__edit_public_note" = "Aquest és el teu perfil de pubky.app. És públic, i els canvis que hi facis aquí també es veuen a pubky.app."; "profile__edit_tags_error" = "Bitkit no ha pogut desar les teves etiquetes. Els altres canvis s'han desat, així que torna a provar amb les etiquetes."; +"profile__delete_active_subscription" = "Les subscripcions actives impedeixen eliminar aquest perfil."; "profile__delete_title" = "Eliminar el perfil?"; "profile__delete_description" = "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."; "profile__delete_confirm" = "Sí, elimina"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index 0bdf79f47..f5c4f52ce 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -1338,6 +1338,7 @@ "profile__edit_changed_error" = "Tvůj profil se v pubky.app změnil. Bitkit načetl nejnovější verzi, proveď proto úpravu znovu."; "profile__edit_public_note" = "Toto je tvůj profil na pubky.app. Je veřejný a změny, které zde provedeš, se zobrazí i na pubky.app."; "profile__edit_tags_error" = "Bitkit nemohl uložit vaše štítky. Ostatní změny byly uloženy, tak zkuste štítky znovu."; +"profile__delete_active_subscription" = "Aktivní předplatná brání odstranění tohoto profilu."; "profile__delete_title" = "Smazat profil?"; "profile__delete_description" = "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."; "profile__delete_confirm" = "Ano, smazat"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 703d383c7..4f12e6c69 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -1336,6 +1336,7 @@ "profile__edit_changed_error" = "Dein Profil wurde in pubky.app geändert. Bitkit hat die neueste Version geladen, nimm deine Änderung bitte erneut vor."; "profile__edit_public_note" = "Das ist dein pubky.app-Profil. Es ist öffentlich, und Änderungen, die du hier vornimmst, erscheinen auch auf pubky.app."; "profile__edit_tags_error" = "Bitkit konnte deine Tags nicht speichern. Deine anderen Änderungen wurden gespeichert, versuche es mit den Tags erneut."; +"profile__delete_active_subscription" = "Aktive Abonnements verhindern das Entfernen dieses Profils."; "profile__delete_title" = "Profil löschen?"; "profile__delete_description" = "Durch das Löschen deines Profils wird es von Pubky entfernt. Kontakte können zuvor mit ihnen geteilte Profil- und Zahlungsinformationen weiterhin behalten."; "profile__delete_confirm" = "Ja, löschen"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 636fad0bc..4258654bf 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -1134,6 +1134,7 @@ "profile__edit_changed_error" = "Το προφίλ σου άλλαξε στο pubky.app. Το Bitkit φόρτωσε την πιο πρόσφατη έκδοση, οπότε κάνε ξανά την αλλαγή σου."; "profile__edit_public_note" = "Αυτό είναι το προφίλ σου στο pubky.app. Είναι δημόσιο, και οι αλλαγές που κάνεις εδώ εμφανίζονται και στο pubky.app."; "profile__edit_tags_error" = "Το Bitkit δεν μπόρεσε να αποθηκεύσει τις ετικέτες σου. Οι άλλες αλλαγές σου αποθηκεύτηκαν, οπότε δοκίμασε ξανά τις ετικέτες."; +"profile__delete_active_subscription" = "Οι ενεργές συνδρομές εμποδίζουν την αφαίρεση αυτού του προφίλ."; "profile__delete_title" = "Διαγραφή Προφίλ;"; "profile__delete_description" = "Η διαγραφή του προφίλ σας το αφαιρεί από το Pubky. Οι επαφές μπορεί να διατηρούν ακόμα πληροφορίες προφίλ και πληρωμών που τους κοινοποιήθηκαν παλαιότερα."; "profile__delete_confirm" = "Ναι, Διαγραφή"; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index 39207d68b..36ba4b736 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1382,6 +1382,7 @@ "profile__edit_changed_error" = "Your profile changed in pubky.app. Bitkit loaded the latest version, so make your edit again."; "profile__edit_public_note" = "This is your pubky.app profile. It is public, and changes you make here also show on pubky.app."; "profile__edit_tags_error" = "Bitkit could not save your tags. Your other changes were saved, so try the tags again."; +"profile__delete_active_subscription" = "Active subscriptions prevent removing this profile."; "profile__delete_title" = "Delete Profile?"; "profile__delete_description" = "Deleting your profile removes it from Pubky. Contacts may still retain profile and payment information previously shared with them."; "profile__delete_confirm" = "Yes, Delete"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 3496976a6..3fef18314 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -1341,6 +1341,7 @@ "profile__edit_changed_error" = "Tu perfil cambió en pubky.app. Bitkit cargó la versión más reciente, así que vuelve a hacer tu cambio."; "profile__edit_public_note" = "Este es tu perfil de pubky.app. Es público, y los cambios que hagas aquí también se ven en pubky.app."; "profile__edit_tags_error" = "Bitkit no pudo guardar tus etiquetas. Tus otros cambios se guardaron, así que vuelve a intentar con las etiquetas."; +"profile__delete_active_subscription" = "Las suscripciones activas impiden eliminar este perfil."; "profile__delete_title" = "¿Eliminar perfil?"; "profile__delete_description" = "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."; "profile__delete_confirm" = "Sí, eliminar"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index 84565f8f1..ccbc2f230 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -1251,6 +1251,7 @@ "profile__edit_changed_error" = "Tu perfil cambió en pubky.app. Bitkit cargó la versión más reciente, así que vuelve a hacer tu cambio."; "profile__edit_public_note" = "Este es tu perfil de pubky.app. Es público, y los cambios que hagas aquí también se ven en pubky.app."; "profile__edit_tags_error" = "Bitkit no pudo guardar tus etiquetas. Tus otros cambios se guardaron, así que vuelve a intentar con las etiquetas."; +"profile__delete_active_subscription" = "Las suscripciones activas impiden eliminar este perfil."; "profile__delete_title" = "¿Eliminar el perfil?"; "profile__delete_description" = "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."; "profile__delete_confirm" = "Sí, eliminar"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index 63a31e945..57735fe7e 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -1349,6 +1349,7 @@ "profile__edit_changed_error" = "Ton profil a changé sur pubky.app. Bitkit a chargé la version la plus récente, refais donc ta modification."; "profile__edit_public_note" = "Voici ton profil pubky.app. Il est public, et les modifications que tu fais ici apparaissent aussi sur pubky.app."; "profile__edit_tags_error" = "Bitkit n'a pas pu enregistrer vos étiquettes. Vos autres modifications ont été enregistrées, réessayez pour les étiquettes."; +"profile__delete_active_subscription" = "Les abonnements actifs empêchent la suppression de ce profil."; "profile__delete_title" = "Supprimer le profil ?"; "profile__delete_description" = "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."; "profile__delete_confirm" = "Oui, supprimer"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index 15279da98..998346c2c 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -1315,6 +1315,7 @@ "profile__edit_changed_error" = "Il tuo profilo è cambiato su pubky.app. Bitkit ha caricato la versione più recente, quindi ripeti la modifica."; "profile__edit_public_note" = "Questo è il tuo profilo pubky.app. È pubblico e le modifiche che fai qui compaiono anche su pubky.app."; "profile__edit_tags_error" = "Bitkit non è riuscito a salvare i tuoi tag. Le altre modifiche sono state salvate, quindi riprova con i tag."; +"profile__delete_active_subscription" = "Gli abbonamenti attivi impediscono la rimozione di questo profilo."; "profile__delete_title" = "Eliminare il Profilo?"; "profile__delete_description" = "Eliminando il profilo lo rimuovi da Pubky. I contatti potrebbero conservare le informazioni di profilo e di pagamento condivise in precedenza con loro."; "profile__delete_confirm" = "Sì, Elimina"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index 818c1d9a0..ef7e2dc79 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -1344,6 +1344,7 @@ "profile__edit_changed_error" = "Je profiel is gewijzigd in pubky.app. Bitkit heeft de nieuwste versie geladen, dus voer je wijziging opnieuw uit."; "profile__edit_public_note" = "Dit is je pubky.app-profiel. Het is openbaar, en wijzigingen die je hier maakt, verschijnen ook op pubky.app."; "profile__edit_tags_error" = "Bitkit kon je tags niet opslaan. Je andere wijzigingen zijn opgeslagen, dus probeer de tags opnieuw."; +"profile__delete_active_subscription" = "Actieve abonnementen verhinderen het verwijderen van dit profiel."; "profile__delete_title" = "Profiel verwijderen?"; "profile__delete_description" = "Als u uw profiel verwijdert, wordt het van Pubky verwijderd. Contacten kunnen eerder gedeelde profiel- en betaalgegevens nog bewaren."; "profile__delete_confirm" = "Ja, verwijderen"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index b0a449adc..cbc29d3dd 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -1348,6 +1348,7 @@ "profile__edit_changed_error" = "Twój profil zmienił się w pubky.app. Bitkit wczytał najnowszą wersję, więc wprowadź zmianę ponownie."; "profile__edit_public_note" = "To jest Twój profil pubky.app. Jest publiczny, a zmiany wprowadzone tutaj pojawią się też w pubky.app."; "profile__edit_tags_error" = "Bitkit nie mógł zapisać Twoich tagów. Pozostałe zmiany zostały zapisane, więc spróbuj ponownie z tagami."; +"profile__delete_active_subscription" = "Aktywne subskrypcje uniemożliwiają usunięcie tego profilu."; "profile__delete_title" = "Usunąć profil?"; "profile__delete_description" = "Usunięcie profilu usuwa go z Pubky. Kontakty mogą nadal przechowywać udostępnione im wcześniej dane profilu i płatności."; "profile__delete_confirm" = "Tak, usuń"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index 5f26f8da9..d13474250 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -1349,6 +1349,7 @@ "profile__edit_changed_error" = "Seu perfil mudou no pubky.app. O Bitkit carregou a versão mais recente, então faça sua alteração de novo."; "profile__edit_public_note" = "Este é o seu perfil do pubky.app. Ele é público, e as alterações que você faz aqui também aparecem no pubky.app."; "profile__edit_tags_error" = "O Bitkit não conseguiu salvar suas tags. Suas outras alterações foram salvas, então tente as tags novamente."; +"profile__delete_active_subscription" = "As assinaturas ativas impedem a remoção deste perfil."; "profile__delete_title" = "Excluir Perfil?"; "profile__delete_description" = "Excluir seu perfil o remove do Pubky. Os contatos ainda podem manter informações de perfil e de pagamento compartilhadas anteriormente com eles."; "profile__delete_confirm" = "Sim, Excluir"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index 7f3d95514..fbb3fccaa 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -1109,6 +1109,7 @@ "profile__edit_changed_error" = "O teu perfil mudou no pubky.app. A Bitkit carregou a versão mais recente, por isso faz novamente a tua alteração."; "profile__edit_public_note" = "Este é o teu perfil do pubky.app. É público, e as alterações que fazes aqui também aparecem no pubky.app."; "profile__edit_tags_error" = "O Bitkit não conseguiu guardar as suas etiquetas. As outras alterações foram guardadas, por isso tente as etiquetas novamente."; +"profile__delete_active_subscription" = "As subscrições ativas impedem a remoção deste perfil."; "profile__delete_title" = "Eliminar perfil?"; "profile__delete_description" = "Eliminar o seu perfil remove-o do Pubky. Os contactos podem manter as informações de perfil e pagamento partilhadas anteriormente com eles."; "profile__delete_confirm" = "Sim, Excluir"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index a6946a0a0..4b84db822 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -1334,6 +1334,7 @@ "profile__edit_changed_error" = "Ваш профиль изменился в pubky.app. Bitkit загрузил последнюю версию, поэтому внесите изменение снова."; "profile__edit_public_note" = "Это ваш профиль pubky.app. Он публичный, и изменения, которые вы вносите здесь, также видны в pubky.app."; "profile__edit_tags_error" = "Bitkit не удалось сохранить ваши теги. Остальные изменения сохранены, поэтому попробуйте сохранить теги ещё раз."; +"profile__delete_active_subscription" = "Активные подписки не позволяют удалить этот профиль."; "profile__delete_title" = "Удалить Профиль?"; "profile__delete_description" = "Удаление профиля удалит его из Pubky. У контактов могут остаться данные профиля и платёжные данные, которыми вы делились ранее."; "profile__delete_confirm" = "Да, Удалить"; diff --git a/Bitkit/Services/PubkyService.swift b/Bitkit/Services/PubkyService.swift index 03c3cdc79..9ad254489 100644 --- a/Bitkit/Services/PubkyService.swift +++ b/Bitkit/Services/PubkyService.swift @@ -362,6 +362,10 @@ enum PubkyService { try await PaykitSdkService.shared.uploadAvatar(bytes: bytes, contentType: contentType, expectedIdentity: expectedIdentity) } + static func requireNoActiveSubscriptions(expectedIdentity: String) async throws { + try await PaykitSdkService.shared.requireNoActiveSubscriptions(expectedIdentity: expectedIdentity) + } + static func deletePaykitProfile(expectedIdentity: String? = nil) async throws { try await PaykitSdkService.shared.deletePaykitProfile(expectedIdentity: expectedIdentity) } @@ -431,6 +435,10 @@ enum PubkyService { try await PaykitSdkService.shared.removeContact(publicKey: publicKey) } + static func removeContactsForProfile(publicKeys: [String]) async throws -> [Paykit.ContactRecord] { + try await PaykitSdkService.shared.removeContactsForProfile(publicKeys: publicKeys) + } + static func removeContacts(publicKeys: [String]) async throws -> [Paykit.ContactRecord] { try await PaykitSdkService.shared.removeContacts(publicKeys: publicKeys) } @@ -874,11 +882,35 @@ actor PaykitSdkService { return record.uri } + func requireNoActiveSubscriptions(expectedIdentity: String) async throws { + try await withStateRevisionTracking { sdk in + try await Self.requireSignedInIdentity(expectedIdentity, in: sdk) + try await Self.requireNoActiveSubscriptions(in: sdk) + } + } + + private static func requireNoActiveSubscriptions(in sdk: PaykitSdk) async throws { + let requests = try await sdk.paymentRequests() + try Task.checkCancellation() + let now = Date() + let activeSubscriptions = requests.filter { + $0.state == .activeRecurring && + ($0.terms?.recurrence?.endsAt.flatMap(PaykitPaymentRequest.parseDate).map { $0 > now } ?? true) + } + guard !activeSubscriptions.isEmpty else { return } + let endDates = activeSubscriptions.compactMap { + $0.terms?.recurrence?.endsAt.flatMap(PaykitPaymentRequest.parseDate) + } + let latestEndDate = endDates.count == activeSubscriptions.count ? endDates.max() : nil + throw PubkyServiceError.activeSubscription(endsAt: latestEndDate) + } + func deletePaykitProfile(expectedIdentity: String? = nil) async throws { try await withStateRevisionTracking { sdk in if let expectedIdentity { try await Self.requireSignedInIdentity(expectedIdentity, in: sdk) } + try await Self.requireNoActiveSubscriptions(in: sdk) guard let publicKey = try await sdk.identityStatus()?.publicKey else { throw PubkyServiceError.sessionNotActive } guard let current = try await sdk.fetchPaykitProfile(publicKey: publicKey) else { return } try await sdk.deletePaykitProfile(expectedRevision: current.revision) @@ -1035,6 +1067,14 @@ actor PaykitSdkService { } } + func removeContactsForProfile(publicKeys: [String]) async throws -> [Paykit.ContactRecord] { + try await withStateRevisionTracking { sdk in + try await Self.requireNoActiveSubscriptions(in: sdk) + guard !publicKeys.isEmpty else { return [] } + return try await sdk.removeContactsAndBlockPeers(publicKeys: publicKeys) + } + } + func removeContacts(publicKeys: [String]) async throws -> [Paykit.ContactRecord] { guard !publicKeys.isEmpty else { return [] } return try await withStateRevisionTracking { sdk in @@ -2184,7 +2224,7 @@ final class PaykitSdkOperationLock: @unchecked Sendable { } private enum Waiter { - case uncancellable(Priority, CheckedContinuation) + case uncancellable(Priority, CheckedContinuation) case cancellable(UUID, Priority, CheckedContinuation) var priority: Priority { @@ -2204,6 +2244,14 @@ final class PaykitSdkOperationLock: @unchecked Sendable { private var activeWipeID: UUID? @TaskLocal private static var walletWipeOwner: UUID? + #if DEBUG + private let beforeAcquireForTesting: (@Sendable () async -> Void)? + + init(beforeAcquireForTesting: (@Sendable () async -> Void)? = nil) { + self.beforeAcquireForTesting = beforeAcquireForTesting + } + #endif + func withLock( priority: Priority = .ordered, generation expectedGeneration: Int? = nil, @@ -2213,7 +2261,10 @@ final class PaykitSdkOperationLock: @unchecked Sendable { return try await operation() } let admittedGeneration = try admit() - await acquire(priority: priority) + #if DEBUG + await beforeAcquireForTesting?() + #endif + guard await acquire(priority: priority, generation: admittedGeneration) else { throw wipeError() } defer { release() } try validate(expectedGeneration ?? admittedGeneration) try Task.checkCancellation() @@ -2247,7 +2298,7 @@ final class PaykitSdkOperationLock: @unchecked Sendable { if let acquireTimeout { try await acquire(within: acquireTimeout) } else { - await acquire(priority: .ordered) + _ = await acquire(priority: .ordered) } defer { release() } try Task.checkCancellation() @@ -2312,23 +2363,30 @@ final class PaykitSdkOperationLock: @unchecked Sendable { return try await operation() } let admittedGeneration = try admit() - try await acquireCancellable() + #if DEBUG + await beforeAcquireForTesting?() + #endif + try await acquireCancellable(generation: admittedGeneration) defer { release() } try validate(admittedGeneration) try Task.checkCancellation() return try await operation() } - private func acquire(priority: Priority) async { + private func acquire(priority: Priority, generation expectedGeneration: Int? = nil) async -> Bool { await withCheckedContinuation { continuation in lock.lock() - if isLocked { + // Recheck while inserting: an old outer owner must not queue behind a wipe draining it. + if let expectedGeneration, isWiping || generation != expectedGeneration { + lock.unlock() + continuation.resume(returning: false) + } else if isLocked { waiters.append(.uncancellable(priority, continuation)) lock.unlock() } else { isLocked = true lock.unlock() - continuation.resume() + continuation.resume(returning: true) } } } @@ -2352,7 +2410,7 @@ final class PaykitSdkOperationLock: @unchecked Sendable { } } - private func acquireCancellable() async throws { + private func acquireCancellable(generation admittedGeneration: Int) async throws { let id = UUID() try await withTaskCancellationHandler { try await withCheckedThrowingContinuation { (continuation: CheckedContinuation) in @@ -2360,6 +2418,9 @@ final class PaykitSdkOperationLock: @unchecked Sendable { if Task.isCancelled { lock.unlock() continuation.resume(throwing: CancellationError()) + } else if isWiping || generation != admittedGeneration { + lock.unlock() + continuation.resume(throwing: wipeError()) } else if isLocked { waiters.append(.cancellable(id, .ordered, continuation)) lock.unlock() @@ -2405,7 +2466,7 @@ final class PaykitSdkOperationLock: @unchecked Sendable { lock.unlock() switch nextWaiter { case let .uncancellable(_, continuation): - continuation.resume() + continuation.resume(returning: true) case let .cancellable(_, _, continuation): continuation.resume() case nil: diff --git a/Bitkit/Views/Profile/EditProfileView.swift b/Bitkit/Views/Profile/EditProfileView.swift index ecc93ae09..06bc1999b 100644 --- a/Bitkit/Views/Profile/EditProfileView.swift +++ b/Bitkit/Views/Profile/EditProfileView.swift @@ -178,6 +178,12 @@ struct EditProfileView: View { try await pubkyProfile.performProfileDeletion { do { try await performDeleteProfile(session: session) + } catch let PubkyServiceError.activeSubscription(endsAt) { + guard !Task.isCancelled, pubkyProfile.currentSession == session else { return } + let description = endsAt.map { + t("subscriptions__expires_date", variables: ["date": $0.formatted(date: .long, time: .omitted)]) + } + app.toast(type: .error, title: t("profile__delete_active_subscription"), description: description) } catch { guard !Task.isCancelled, pubkyProfile.publicKey == session.publicKey else { return } Logger.error("Failed to delete profile: \(error)", context: "EditProfileView") @@ -192,16 +198,27 @@ struct EditProfileView: View { } private func performDeleteProfile(session: PubkyProfileManager.SignedInSession) async throws { + try await Self.performDeleteProfile(session: session, pubkyProfile: pubkyProfile, contactsManager: contactsManager) { + try await PubkyProfileManager.removePrivatePaykitEndpoints( + context: "EditProfileView.deleteProfile", deferAppSync: true, + isSessionCurrent: { pubkyProfile.currentSession == session } + ) + } + navigation.path = [app.hasSeenProfileIntro ? .pubkyChoice : .profileIntro] + } + + static func performDeleteProfile( + session: PubkyProfileManager.SignedInSession, + pubkyProfile: PubkyProfileManager, + contactsManager: ContactsManager, + removePrivateEndpoints: () async throws -> Void + ) async throws { + try await pubkyProfile.validateProfileDeletion(for: session) + try await removePrivateEndpoints() try pubkyProfile.requireCurrentSession(session) - await PubkyProfileManager.removePrivatePaykitEndpointsBestEffort( - context: "EditProfileView.deleteProfile", deferAppSync: true, - isSessionCurrent: { pubkyProfile.currentSession == session } - ) - try pubkyProfile.requireCurrentSession(session) - await contactsManager.deleteAllContactsBestEffort() + try await contactsManager.deleteAllContacts() try pubkyProfile.requireCurrentSession(session) try await pubkyProfile.deleteProfile(cleanPrivatePaykitEndpoints: false, expectedSession: session) - navigation.path = [app.hasSeenProfileIntro ? .pubkyChoice : .profileIntro] } private func disconnectAfterFailedDelete() async { diff --git a/BitkitTests/ContactsManagerTests.swift b/BitkitTests/ContactsManagerTests.swift index b10f6bf15..5e0f656e9 100644 --- a/BitkitTests/ContactsManagerTests.swift +++ b/BitkitTests/ContactsManagerTests.swift @@ -2271,6 +2271,28 @@ final class ContactsManagerTests: XCTestCase { XCTAssertTrue(manager.contacts.isEmpty) } + func testDeleteAllContactsPreservesEvidenceWhenTheContactReadFails() async throws { + snapshotAppDefaults("pubkyContactProfileOverrides") + let contact = makeContact(publicKey: contactProfileKey) + ContactsManager.restoreContactProfileOverrides([contact.publicKey: PubkyProfileData.from(profile: contact.profile)]) + let unavailable = AppError(message: "App Error", debugMessage: "Fetch failed: 404 missing session") + let manager = ContactsManager(contactRecords: { throw unavailable }, removeContactRecords: { _ in + XCTFail("An unavailable read must not authorize a removal") + return [] + }) + manager.contacts = [contact] + + do { + try await manager.deleteAllContacts() + XCTFail("An unavailable read is not an empty contact list") + } catch { + XCTAssertEqual(error.localizedDescription, unavailable.localizedDescription) + } + + XCTAssertEqual(manager.contacts, [contact]) + XCTAssertNotNil(ContactsManager.backupContactProfileOverrides()?[contact.publicKey]) + } + func testDeleteAllContactsPreservesContactsNotRemovedByTheBulkOperation() async throws { snapshotAppDefaults("pubkyContactProfileOverrides") let removed = contactRecord(key: contactProfileKey, name: "Removed") diff --git a/BitkitTests/HwConnectViewModelTests.swift b/BitkitTests/HwConnectViewModelTests.swift index 78eadbbc3..11ed47c25 100644 --- a/BitkitTests/HwConnectViewModelTests.swift +++ b/BitkitTests/HwConnectViewModelTests.swift @@ -702,7 +702,10 @@ final class HwConnectViewModelTests: XCTestCase { connectService.cancelPendingConnection(to: jadeDevice) - await waitUntil { self.jadeLog.contains("service.disconnect.done") } + await waitUntil { + self.jadeLog.contains("service.disconnect.done") && + self.jadeLog.contains("transport.disconnect:\(JadeFixtures.blePath)") + } XCTAssertTrue(jadeLog.contains("service.cancel")) XCTAssertTrue(jadeLog.contains("transport.disconnect:\(JadeFixtures.blePath)")) } diff --git a/BitkitTests/PaykitSdkIdentityCheckTests.swift b/BitkitTests/PaykitSdkIdentityCheckTests.swift index 585c24904..ddc6c4dd7 100644 --- a/BitkitTests/PaykitSdkIdentityCheckTests.swift +++ b/BitkitTests/PaykitSdkIdentityCheckTests.swift @@ -469,6 +469,114 @@ final class PaykitSdkIdentityCheckTests: XCTestCase { XCTAssertEqual(sdk.writes, ["upload"]) } + func testProfileDeletionRefusesActiveSubscriptionsInEitherRoleWithoutContacts() async throws { + for role in [PaymentRequestLocalRole.payer, .payee] { + let sdk = IdentitySwitchingSdk(noPointer: .init()) + sdk.identity = identityA + sdk.profileExists = true + var request = try paymentRequestRecord(appId: "another-app") + request.localRole = role + request.state = .activeRecurring + sdk.rawPaymentRequests = { [request] } + let service = PaykitSdkService(sdkFactory: { sdk }) + + do { + try await service.deletePaykitProfile(expectedIdentity: identityA) + XCTFail("An active subscription must prevent profile deletion even without a contact") + } catch PubkyServiceError.activeSubscription {} + XCTAssertTrue(sdk.writes.isEmpty) + } + } + + func testProfileCleanupChecksAllSubscriptionsBeforeRemovingAnyContact() async throws { + for endsAt in [nil, "invalid", "9999-01-01T00:00:00Z", "2000-01-01T00:00:00Z"] as [String?] { + let sdk = IdentitySwitchingSdk(noPointer: .init()) + sdk.identity = identityA + sdk.profileExists = true + var request = try paymentRequestRecord(appId: "another-app") + request.state = .activeRecurring + request.terms?.recurrence = PaymentRequestRecurrence( + every: 1, unit: "month", startsAt: "1999-01-01T00:00:00Z", anchor: "1999-01-01T00:00:00Z", endsAt: endsAt + ) + sdk.rawPaymentRequests = { [request] } + let service = PaykitSdkService(sdkFactory: { sdk }) + let blocked = endsAt != "2000-01-01T00:00:00Z" + let operations: [() async throws -> Void] = [ + { try await service.requireNoActiveSubscriptions(expectedIdentity: identityA) }, + { _ = try await service.removeContactsForProfile(publicKeys: [identityB]) }, + { _ = try await service.removeContactsForProfile(publicKeys: []) }, + { try await service.deletePaykitProfile(expectedIdentity: identityA) }, + ] + for operation in operations { + do { + try await operation() + XCTAssertFalse(blocked) + } catch let PubkyServiceError.activeSubscription(actualEnd) { + XCTAssertTrue(blocked) + XCTAssertEqual(actualEnd, endsAt.flatMap(PaykitPaymentRequest.parseDate)) + } + } + XCTAssertEqual(sdk.writes, blocked ? [] : ["remove-contacts:1", "delete-profile:test"]) + } + } + + func testProfileRemovalOnlyReportsAnEndWhenEveryBlockingSubscriptionHasOne() async throws { + let earlier = "2999-01-01T00:00:00Z" + let later = "3000-01-01T00:00:00Z" + let cases: [(ends: [String?], expected: String?)] = [ + ([earlier, later], later), + ([later, earlier], later), + ([earlier, nil], nil), + (["invalid", later], nil), + (["2000-01-01T00:00:00Z", later], later), + ] + for testCase in cases { + let sdk = IdentitySwitchingSdk(noPointer: .init()) + sdk.identity = identityA + let requests = try testCase.ends.map { endsAt in + var request = try paymentRequestRecord(appId: "another-app") + request.state = .activeRecurring + request.terms?.recurrence = PaymentRequestRecurrence( + every: 1, unit: "month", startsAt: "1999-01-01T00:00:00Z", anchor: "1999-01-01T00:00:00Z", endsAt: endsAt + ) + return request + } + sdk.rawPaymentRequests = { requests } + let service = PaykitSdkService(sdkFactory: { sdk }) + do { + try await service.requireNoActiveSubscriptions(expectedIdentity: identityA) + XCTFail("Every case contains a blocking subscription") + } catch let PubkyServiceError.activeSubscription(endsAt) { + XCTAssertEqual(endsAt, testCase.expected.flatMap(PaykitPaymentRequest.parseDate)) + } + XCTAssertTrue(sdk.writes.isEmpty) + } + } + + func testSubscriptionReadFailureAndCancellationNeverAuthorizeProfileCleanup() async throws { + for failure: Error in [sharedStateBusy, CancellationError()] { + let sdk = IdentitySwitchingSdk(noPointer: .init()) + sdk.identity = identityA + sdk.profileExists = true + sdk.rawPaymentRequests = { throw failure } + let service = PaykitSdkService(sdkFactory: { sdk }) + let operations: [() async throws -> Void] = [ + { try await service.requireNoActiveSubscriptions(expectedIdentity: identityA) }, + { _ = try await service.removeContactsForProfile(publicKeys: [contactKey]) }, + { try await service.deletePaykitProfile(expectedIdentity: identityA) }, + ] + for operation in operations { + do { + try await operation() + XCTFail("An unavailable subscription read must stop cleanup") + } catch { + XCTAssertEqual(error.localizedDescription, failure.localizedDescription) + } + } + XCTAssertTrue(sdk.writes.isEmpty) + } + } + func testProfileDeletionChecksItsOwnerBeforeReadingOrRemovingTheProfile() async throws { for signedIn in [identityA, identityB, nil] { let sdk = IdentitySwitchingSdk(noPointer: .init()) @@ -1151,6 +1259,8 @@ private final class IdentitySwitchingSdk: PaykitSdk, @unchecked Sendable { PaymentRequestRead(identityStatus: nil, paymentRequests: []) } + var rawPaymentRequests: () async throws -> [PaymentRequestRecord] = { [] } + var schedulingRead: () async throws -> Paykit.PrivateMessageSchedulingSnapshot = { Paykit.PrivateMessageSchedulingSnapshot(linkedPeers: [], pendingOutboundCounterparties: []) } @@ -1226,6 +1336,10 @@ private final class IdentitySwitchingSdk: PaykitSdk, @unchecked Sendable { } } + override func paymentRequests() async throws -> [PaymentRequestRecord] { + try await rawPaymentRequests() + } + override func readPaymentRequests(counterparty: String, expectedIdentity: String?) async throws -> PaymentRequestRead { try await paymentRequestRead(counterparty, expectedIdentity) } @@ -1295,6 +1409,11 @@ private final class IdentitySwitchingSdk: PaykitSdk, @unchecked Sendable { return [] } + override func removeContactsAndBlockPeers(publicKeys: [String]) async throws -> [ContactRecord] { + recordWrite("remove-contacts:\(publicKeys.count)") + return publicKeys.map { Self.record(publicKey: $0, label: nil) } + } + override func contactRecord(publicKey: String) async throws -> ContactRecord? { lock.withLock { recordedContactReads += 1 } return Self.record(publicKey: publicKey, label: "Contact") diff --git a/BitkitTests/PaykitSdkOperationLockTests.swift b/BitkitTests/PaykitSdkOperationLockTests.swift index 9874ab1f5..cf28674a8 100644 --- a/BitkitTests/PaykitSdkOperationLockTests.swift +++ b/BitkitTests/PaykitSdkOperationLockTests.swift @@ -1028,6 +1028,50 @@ final class PaykitSdkOperationLockTests: XCTestCase { } catch is CancellationError {} } + func testWipeRejectsPreviouslyAdmittedOuterOwnerBeforeQueueInsertion() async throws { + for cancellable in [false, true] { + let (outerFinished, finishOuter) = AsyncStream.makeStream() + let admitted = expectation(description: "Ordinary operation admitted before SDK enqueue") + let finished = expectation(description: "Old outer owner rejected without waiting behind wipe") + let wipeEntered = expectation(description: "Wipe waits on original outer owner") + let (gate, release) = AsyncStream.makeStream() + let sdk = PaykitSdkOperationLock(beforeAcquireForTesting: { + admitted.fulfill() + for await _ in gate {} + }) + let ordinary = Task { + defer { + finishOuter.finish() + finished.fulfill() + } + do { + if cancellable { + try await sdk.withCancellableLock { XCTFail("Stale SDK operation executed") } + } else { + try await sdk.withLock { XCTFail("Stale SDK operation executed") } + } + XCTFail("Expected wipe rejection") + } catch let PaykitError.Storage(code, _) { + XCTAssertEqual(code, "wallet_wipe_in_progress") + } + } + await fulfillment(of: [admitted], timeout: 2) + let wipe = Task { + try await sdk.withWalletWipe { + wipeEntered.fulfill() + // Allow cleanup after a failed assertion without leaving either task suspended. + for await _ in outerFinished {} + } + } + await fulfillment(of: [wipeEntered], timeout: 2) + release.finish() + await fulfillment(of: [finished], timeout: 1) + wipe.cancel() + do { try await wipe.value } catch is CancellationError {} + try await ordinary.value + } + } + func testWipeDrainsActiveWorkRejectsQueuedWorkAndAllowsCleanupAndFreshWork() async throws { let lock = PaykitSdkOperationLock() let recorder = Recorder() diff --git a/BitkitTests/PubkyProfileManagerTests.swift b/BitkitTests/PubkyProfileManagerTests.swift index ba11544be..ac7fa5245 100644 --- a/BitkitTests/PubkyProfileManagerTests.swift +++ b/BitkitTests/PubkyProfileManagerTests.swift @@ -12,6 +12,89 @@ final class PubkyProfileManagerTests: XCTestCase { case signOut } + @MainActor + func testActiveSubscriptionStopsProfileRemovalBeforePrivateOrContactCleanup() async throws { + try await withEmptyIdentityStorage { + for entry in ["screen", "manager"] { + let key = "pubky" + String(repeating: "y", count: 52) + let manager = PubkyProfileManager(profileDeletionValidator: { expectedIdentity in + XCTAssertEqual(expectedIdentity, key) + throw PubkyServiceError.activeSubscription(endsAt: nil) + }, profileDeleter: { _ in + XCTFail("An active subscription must preserve the profile") + }) + manager.publicKey = key + manager.authState = .authenticated + let session = try XCTUnwrap(manager.currentSession) + let contacts = ContactsManager(contactRecords: { + XCTFail("An active subscription must stop before contact cleanup") + return [] + }) + UserDefaults.standard.set(true, forKey: PublicPaykitService.publishingEnabledKey) + UserDefaults.standard.set(true, forKey: PrivatePaykitService.publishingEnabledKey) + do { + if entry == "screen" { + try await manager.performProfileDeletion { + try await EditProfileView.performDeleteProfile( + session: session, pubkyProfile: manager, contactsManager: contacts + ) { XCTFail("An active subscription must preserve private endpoints") } + } + } else { + try await manager.deleteProfile() + } + XCTFail("Expected subscription refusal") + } catch PubkyServiceError.activeSubscription {} + XCTAssertEqual(manager.currentSession, session) + XCTAssertFalse(manager.isDeletingProfile) + XCTAssertTrue(UserDefaults.standard.bool(forKey: PublicPaykitService.publishingEnabledKey)) + XCTAssertTrue(UserDefaults.standard.bool(forKey: PrivatePaykitService.publishingEnabledKey)) + } + } + } + + @MainActor + func testProfileRemovalStopsBeforeDeletingWhenCleanupIsIncomplete() async throws { + snapshotAppDefaultsDomain() + for failure in ["private endpoints", "contacts"] { + let key = "pubky" + String(repeating: "y", count: 52) + let originalError = KeychainError.failedToDelete + let manager = PubkyProfileManager(profileDeletionValidator: { _ in }, profileDeleter: { _ in + XCTFail("Incomplete cleanup must not delete the profile") + throw PublicPaykitError.publicationFailed + }) + manager.publicKey = key + manager.authState = .authenticated + let session = try XCTUnwrap(manager.currentSession) + let contact = Bitkit.PubkyProfile.placeholder(publicKey: key) + ContactsManager.restoreContactProfileOverrides([key: PubkyProfileData.from(profile: contact)]) + let contacts = ContactsManager(contactRecords: { + XCTAssertEqual(failure, "contacts", "Private withdrawal failure must stop before contact removal") + throw originalError + }) + contacts.contacts = [PubkyContact(publicKey: key, profile: contact)] + + do { + try await manager.performProfileDeletion { + try await EditProfileView.performDeleteProfile( + session: session, pubkyProfile: manager, contactsManager: contacts + ) { + if failure == "private endpoints" { + throw originalError + } + } + } + XCTFail("Incomplete cleanup must fail") + } catch { + XCTAssertTrue(error is KeychainError, "Preserve the cleanup failure, got \(error)") + } + + XCTAssertEqual(contacts.contacts.map(\.publicKey), [key]) + XCTAssertEqual(Set(ContactsManager.backupContactProfileOverrides()?.keys ?? [:].keys), [key]) + XCTAssertEqual(manager.currentSession, session) + XCTAssertFalse(manager.isDeletingProfile) + } + } + @MainActor func testProfileDeletionPausesAutomaticWorkWithoutEndingTheSession() async throws { for outcome in ["success", "failure", "cancellation"] { @@ -201,7 +284,7 @@ final class PubkyProfileManagerTests: XCTestCase { let started = expectation(description: "Profile delete admitted") let (resume, continuation) = AsyncStream.makeStream() defer { continuation.finish() } - let manager = PubkyProfileManager(profileDeleter: { expectedIdentity in + let manager = PubkyProfileManager(profileDeletionValidator: { _ in }, profileDeleter: { expectedIdentity in XCTAssertEqual(expectedIdentity, original) started.fulfill() for await _ in resume {} @@ -280,6 +363,43 @@ final class PubkyProfileManagerTests: XCTestCase { } } + @MainActor + func testProfileDeletionRequiresAcknowledgedCompletionBeforeSignOut() async throws { + try await withEmptyIdentityStorage { + let errors: [NSError?] = [ + nil, + NSError(domain: "ProfileDeleteFixture", code: 404, + userInfo: [NSLocalizedDescriptionKey: "Delete failed: HTTP 404 Not Found at session endpoint"]), + NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue), + ] + for failure in errors { + let manager = PubkyProfileManager(profileDeletionValidator: { _ in }, profileDeleter: { _ in + if let failure { + throw failure + } + }) + manager.publicKey = "pubky" + String(repeating: "y", count: 52) + manager.authState = .authenticated + let session = try XCTUnwrap(manager.currentSession) + UserDefaults.standard.set(true, forKey: PublicPaykitService.publishingEnabledKey) + UserDefaults.standard.set(true, forKey: PrivatePaykitService.publishingEnabledKey) + + do { + try await manager.deleteProfile(cleanPrivatePaykitEndpoints: false) + XCTAssertNil(failure, "An unavailable profile does not confirm its deletion") + } catch { + XCTAssertEqual((error as NSError).domain, failure?.domain) + XCTAssertEqual((error as NSError).code, failure?.code) + } + + XCTAssertEqual(manager.currentSession, failure == nil ? nil : session) + XCTAssertEqual(UserDefaults.standard.bool(forKey: PublicPaykitService.publishingEnabledKey), failure != nil) + XCTAssertEqual(UserDefaults.standard.bool(forKey: PrivatePaykitService.publishingEnabledKey), failure != nil) + XCTAssertFalse(manager.isDeletingProfile) + } + } + } + @MainActor func testAutomaticPaykitSessionAppearsWhenTheSessionChangeEndsAndIsAnnounced() async throws { try await withEmptyIdentityStorage { @@ -308,7 +428,7 @@ final class PubkyProfileManagerTests: XCTestCase { try await withEmptyIdentityStorage { let secret = String(repeating: "01", count: 32) let original = try PubkyProfileManager.publicKeyFromSecretKey(secret) - let manager = PubkyProfileManager(profileDeleter: { _ in + let manager = PubkyProfileManager(profileDeletionValidator: { _ in }, profileDeleter: { _ in XCTFail("A stale deletion must not reach profile storage") }) manager.publicKey = original @@ -3604,24 +3724,6 @@ final class PubkyProfileManagerTests: XCTestCase { XCTAssertNil(resolved) } - func testIsMissingBitkitProfileStorageErrorRecognizes404DeleteFailure() { - let error = AppError( - message: "App Error", - debugMessage: #"BitkitCore.PubkyError.WriteFailed(reason: "delete failed: Request failed: Server responded with an error: 404 Not Found - Not Found")"# - ) - - XCTAssertTrue(PubkyProfileManager.isMissingBitkitProfileStorageError(error)) - } - - func testIsMissingBitkitProfileStorageErrorRejectsNonMissingErrors() { - let error = AppError( - message: "App Error", - debugMessage: #"BitkitCore.PubkyError.AuthFailed(reason: "Request failed: HTTP transport error")"# - ) - - XCTAssertFalse(PubkyProfileManager.isMissingBitkitProfileStorageError(error)) - } - // MARK: - Session backup state func testSnapshotSessionBackupStatePrefersLocalSeedOverSessionSecret() throws { diff --git a/changelog.d/next/1124.fixed.md b/changelog.d/next/1124.fixed.md new file mode 100644 index 000000000..64a4e1001 --- /dev/null +++ b/changelog.d/next/1124.fixed.md @@ -0,0 +1 @@ +Preserve session and contact data after incomplete profile cleanup, and explain when active subscriptions prevent profile removal. diff --git a/changelog.d/next/1125.fixed.md b/changelog.d/next/1125.fixed.md new file mode 100644 index 000000000..67503a93b --- /dev/null +++ b/changelog.d/next/1125.fixed.md @@ -0,0 +1 @@ +Prevent wallet reset from waiting indefinitely for an older Paykit operation queued during teardown. diff --git a/journeys/profile/profile-cleanup-failure.xml b/journeys/profile/profile-cleanup-failure.xml new file mode 100644 index 000000000..9b7a6747e --- /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 + +