Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
ab59838
fix: stop automatic profile deletion replay
ben-kaufman Oct 24, 2026
99b446a
docs: associate deletion fix with PR 1688
ben-kaufman Oct 24, 2026
618087a
fix: stop profile deletion after incomplete cleanup
ben-kaufman Oct 25, 2026
479c530
chore: rename changelog fragment
ben-kaufman Oct 25, 2026
2daec90
fix: preserve sessions after uncertain profile deletion
ben-kaufman Oct 25, 2026
5fe0bf6
fix: integrate current restore recovery parent
ben-kaufman Oct 28, 2026
f72e0c0
fix: integrate current restore recovery parent
ben-kaufman Oct 28, 2026
7afdd3e
fix: block profile removal with active subscriptions
ben-kaufman Oct 29, 2026
2aac53e
Merge current identity recovery into profile session recovery
ben-kaufman Oct 29, 2026
98797f2
fix: explain fixed-term profile removal restrictions
ben-kaufman Oct 29, 2026
815e85c
Merge current profile session recovery into cleanup outcomes
ben-kaufman Oct 29, 2026
ff5aa32
Merge restored identity guards into profile deletion recovery
ben-kaufman Oct 30, 2026
3001faf
test: report Pubky alias state on routing failures
ben-kaufman Oct 30, 2026
7ef3432
Merge current deletion recovery parent into cleanup guards
ben-kaufman Oct 30, 2026
e3384ed
chore: merge validated restore identity parent
ben-kaufman Oct 31, 2026
55afaad
Merge queued allowance admission fix
ben-kaufman Nov 1, 2026
3f4b19f
Merge stable allowance activation into profile recovery
ben-kaufman Nov 1, 2026
6e02af2
Merge current profile recovery into local cleanup
ben-kaufman Nov 1, 2026
9bf19f1
Merge current profile recovery into local cleanup
ben-kaufman Nov 1, 2026
2621f81
Merge guarded identity and allowance recovery parent
ben-kaufman Nov 1, 2026
120553f
Merge current session recovery parent into cleanup outcomes
ben-kaufman Nov 1, 2026
9c145d9
Merge current allowance resume fix into recovery branch
ben-kaufman Nov 1, 2026
2efaff0
merge: include final identity recovery parent
ben-kaufman Nov 1, 2026
7040c89
fix: compose validated profile cleanup parent
ben-kaufman Nov 1, 2026
3d8a328
merge: integrate current identity recovery
ben-kaufman Nov 3, 2026
2e79e10
merge: integrate current profile recovery parent
ben-kaufman Nov 3, 2026
916c6d5
fix: compose original-wallet VSS ownership with profile deletion
ben-kaufman Nov 4, 2026
84c803d
fix: compose vss ownership with profile cleanup
ben-kaufman Nov 4, 2026
5cf930f
merge: compose queued backup status
ben-kaufman Nov 4, 2026
97dbdff
merge: compose queued backup status
ben-kaufman Nov 4, 2026
a8c3fd3
merge: compose admitted backup status
ben-kaufman Nov 4, 2026
b2c4b9e
merge: compose admitted backup status
ben-kaufman Nov 4, 2026
8ceaca2
fix: recheck subscriptions before profile deletion
ben-kaufman Nov 4, 2026
dc9a981
fix: preserve explicit profile deletion recovery
ben-kaufman Nov 11, 2026
97b3c8d
fix: guard profile removal after subscription changes
ben-kaufman Nov 11, 2026
8a96806
fix: preserve profile ownership during recovery
ben-kaufman Nov 11, 2026
0bda04a
fix: preserve profile ownership during recovery
ben-kaufman Nov 11, 2026
8d10218
fix: retain recovery guards in the composed parent
ben-kaufman Nov 12, 2026
9a53355
fix: retain recovery guards in the composed parent
ben-kaufman Nov 12, 2026
5f0a8ad
fix: preserve recovery with spark balance and result updates
ben-kaufman Nov 12, 2026
ac4dcf2
fix: preserve recovery with spark balance and result updates
ben-kaufman Nov 12, 2026
46d5901
fix: preserve recovery with startup cache loading
ben-kaufman Nov 12, 2026
430588b
fix: preserve recovery with startup cache loading
ben-kaufman Nov 12, 2026
f270a9e
fix: preserve recovery with node timeout balance updates
ben-kaufman Nov 12, 2026
bacf2b6
fix: preserve recovery with node timeout balance updates
ben-kaufman Nov 12, 2026
172851d
fix: preserve recovery across parent changes
ben-kaufman Nov 12, 2026
1bc89c1
fix: preserve recovery with finished-exit balance updates
ben-kaufman Nov 12, 2026
274bb68
fix: preserve recovery with finished-exit balance updates
ben-kaufman Nov 12, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 28 additions & 51 deletions app/src/main/java/to/bitkit/repositories/PubkyRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}

Expand Down Expand Up @@ -1257,35 +1258,29 @@ class PubkyRepo @Inject constructor(
}
}

suspend fun deleteProfileWithSessionRetry(): Result<Unit> = 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<Unit> = runSuspendCatching {
withContext(ioDispatcher) { pubkyService.checkProfileDeletionAllowed() }
}.recoverCatching {
generateSequence(it) { error -> error.cause }
.filterIsInstance<PubkyContactError.ActiveProfileSubscriptions>()
.firstOrNull()?.let { error -> throw error }
if (it.hasCause(PubkyContactError.ActiveSubscription)) throw PubkyContactError.ActiveSubscription
throw it
}

suspend fun deleteProfile(): Result<Unit> = runSuspendCatching {
withContext(ioDispatcher) {
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()
}
Expand All @@ -1294,42 +1289,40 @@ class PubkyRepo @Inject constructor(
}
settingsStore.update { it.paykitDisabled(markPublicCleanupPending = it.hasPaykitState()) }
signOut().getOrThrow()
}.recoverCatching {
generateSequence(it) { error -> error.cause }
.filterIsInstance<PubkyContactError.ActiveProfileSubscriptions>()
.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
Comment thread
ben-kaufman marked this conversation as resolved.
Resolved
Logger.info("Deleted all contacts", context = TAG)
}

Expand Down Expand Up @@ -2344,7 +2337,7 @@ class PubkyRepo @Inject constructor(
}
}

suspend fun refreshSessionIfPossible(): Result<Boolean> = runSuspendCatching {
private suspend fun refreshSessionIfPossible(): Result<Boolean> = runSuspendCatching {
withContext(ioDispatcher) {
val storedSecretKeyHex = activeSecretKeyHex() ?: return@withContext false

Expand Down Expand Up @@ -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
}
65 changes: 52 additions & 13 deletions app/src/main/java/to/bitkit/services/PaykitSdkService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -694,6 +695,7 @@ class PaykitSdkService @Inject constructor(
isSetup.await()
operationLock.withLock {
requireProfileIdentity(currentIdentity(), expectedIdentity)
requireNoActiveSubscriptions(handle())
completeSdkCall { handle().deletePubkyProfile(expectedRevision) }
}
}
Expand Down Expand Up @@ -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<PaymentRequestRecord>) {
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)
Comment thread
ovitrif marked this conversation as resolved.
Resolved
}

suspend fun removeContact(publicKey: String): ContactRecord? {
isSetup.await()
return operationLock.withLock {
Expand All @@ -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 {
Expand All @@ -847,18 +875,29 @@ class PaykitSdkService @Inject constructor(
}
}

suspend fun removeContacts(publicKeys: List<String>): List<ContactRecord> {
suspend fun removeContacts(publicKeys: List<String>): List<ContactRecord> =
removeContacts(publicKeys, requireAll = false)

suspend fun removeContactsForProfile(publicKeys: List<String>): List<ContactRecord> =
removeContacts(publicKeys, requireAll = true)

private suspend fun removeContacts(publicKeys: List<String>, requireAll: Boolean): List<ContactRecord> {
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) }
Expand Down
9 changes: 9 additions & 0 deletions app/src/main/java/to/bitkit/services/PubkyService.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>): List<ContactRecord> =
ServiceQueue.PUBKY.background {
paykitSdkService.removeContactsForProfile(publicKeys)
}

suspend fun deletePaykitProfile() = ServiceQueue.PUBKY.background {
paykitSdkService.deletePaykitProfile()
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -264,7 +266,7 @@ class EditProfileViewModel @Inject constructor(
privatePaykitRepo.removePublishedEndpointsForCleanup(TAG).getOrThrow()
pubkyRepo.signOut().getOrThrow()
}
privatePaykitRepo.closeAndClear()
privatePaykitRepo.closeAndClear().getOrThrow()
}
}
if (result.isSuccess) {
Expand All @@ -291,24 +293,51 @@ 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()
Comment thread
jvsena42 marked this conversation as resolved.
Resolved
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),
)
_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) }
}
}
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-ar/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1455,6 +1455,7 @@
<string name="profile__choice_loading_profile">جارٍ تحميل ملفك الشخصي…</string>
<string name="profile__choice_title">ادخل إلى\n&lt;accent&gt;ويب الحرية&lt;/accent&gt;</string>
<string name="profile__create_error">فشل إنشاء الملف الشخصي</string>
<string name="profile__delete_active_subscription">تمنع الاشتراكات النشطة إزالة هذا الملف الشخصي.</string>
<string name="profile__delete_confirm_description">يؤدي حذف ملفك الشخصي إلى إزالته من Pubky. قد تحتفظ جهات الاتصال بمعلومات الملف الشخصي والدفع التي شاركتها معهم سابقًا.</string>
<string name="profile__delete_confirm_title">حذف الملف الشخصي؟</string>
<string name="profile__delete_error_description">تعذر علينا حذف بيانات ملفك الشخصي. أعد المحاولة، أو افصل هذا الـ pubky عن Bitkit.</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-b+es+419/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1481,6 +1481,7 @@
<string name="profile__choice_loading_profile">Cargando su perfil…</string>
<string name="profile__choice_title">Entre a la\n&lt;accent&gt;web de la libertad&lt;/accent&gt;</string>
<string name="profile__create_error">No se pudo crear el perfil</string>
<string name="profile__delete_active_subscription">Las suscripciones activas impiden eliminar este perfil.</string>
<string name="profile__delete_confirm_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.</string>
<string name="profile__delete_confirm_title">¿Eliminar perfil?</string>
<string name="profile__delete_error_description">No pudimos eliminar los datos de su perfil. Vuelva a intentarlo o desconecte este pubky de Bitkit.</string>
Expand Down
1 change: 1 addition & 0 deletions app/src/main/res/values-ca/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -1477,6 +1477,7 @@
<string name="profile__choice_loading_profile">Carregant el teu perfil…</string>
<string name="profile__choice_title">Entra a la\n&lt;accent&gt;web de la llibertat&lt;/accent&gt;</string>
<string name="profile__create_error">No s\'ha pogut crear el perfil</string>
<string name="profile__delete_active_subscription">Les subscripcions actives impedeixen eliminar aquest perfil.</string>
<string name="profile__delete_confirm_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.</string>
<string name="profile__delete_confirm_title">Eliminar el perfil?</string>
<string name="profile__delete_error_description">No hem pogut eliminar les dades del teu perfil. Torna-ho a provar o desconnecta aquest pubky de Bitkit.</string>
Expand Down
Loading
Loading