From d10a5187053f5011158466090665e3eabe118b0a Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 12:51:31 -0300 Subject: [PATCH 1/7] fix: validate profile links against pubky.app rules Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/ext/PaykitExceptionExt.kt | 6 ++ .../java/to/bitkit/models/PubkyAppLink.kt | 88 +++++++++++++++++++ .../java/to/bitkit/repositories/PubkyRepo.kt | 56 +----------- .../to/bitkit/ui/components/AddLinkSheet.kt | 49 ++++++++++- .../bitkit/ui/components/ProfileEditForm.kt | 14 +++ .../ui/screens/profile/EditProfileScreen.kt | 7 +- .../screens/profile/EditProfileViewModel.kt | 51 +++++++++-- app/src/main/res/values-ar/strings.xml | 4 + app/src/main/res/values-b+es+419/strings.xml | 4 + app/src/main/res/values-ca/strings.xml | 4 + app/src/main/res/values-cs/strings.xml | 4 + app/src/main/res/values-de/strings.xml | 4 + app/src/main/res/values-el/strings.xml | 4 + app/src/main/res/values-es-rES/strings.xml | 4 + app/src/main/res/values-es/strings.xml | 4 + app/src/main/res/values-fr/strings.xml | 4 + app/src/main/res/values-it/strings.xml | 4 + app/src/main/res/values-nl/strings.xml | 4 + app/src/main/res/values-pl/strings.xml | 4 + app/src/main/res/values-pt-rBR/strings.xml | 4 + app/src/main/res/values-pt/strings.xml | 4 + app/src/main/res/values-ru/strings.xml | 4 + app/src/main/res/values/strings.xml | 4 + .../java/to/bitkit/models/PubkyAppLinkTest.kt | 74 ++++++++++++++++ .../profile/EditProfileViewModelTest.kt | 76 +++++++++++++++- changelog.d/next/1882.fixed.md | 1 + journeys/profile/README.md | 2 + journeys/profile/profile-link-validation.xml | 20 +++++ 28 files changed, 443 insertions(+), 65 deletions(-) create mode 100644 app/src/main/java/to/bitkit/models/PubkyAppLink.kt create mode 100644 app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt create mode 100644 changelog.d/next/1882.fixed.md create mode 100644 journeys/profile/profile-link-validation.xml diff --git a/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt b/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt index 0676c1c624..8b5d9fe499 100644 --- a/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt +++ b/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt @@ -11,6 +11,9 @@ private const val SIGNUP_CODE_REJECTED_CODE = "signup_code_rejected" /** Storage error code Paykit uses for local and shared state failures. */ private const val STORAGE_ERROR_CODE = "storage_error" +/** Start of the Protocol error contexts Paykit raises when a profile link breaks a pubky.app rule. */ +private const val PROFILE_LINK_CONTEXT = "Pubky profile link" + /** Storage error contexts Paykit raises when the identity's shared state was saved by a newer Paykit. */ private val NEWER_STATE_CONTEXTS = listOf( "SDK state blob contains trailing bytes", @@ -36,6 +39,9 @@ fun Throwable.isPaykitTemporarilyUnavailable(): Boolean = fun Throwable.isPaykitMessageTooLarge(): Boolean = generateSequence(this) { it.cause }.any { it is PaykitException.Protocol && it.code == MESSAGE_TOO_LARGE_CODE } +fun Throwable.isPaykitProfileLinkRejected(): Boolean = + generateSequence(this) { it.cause }.any { it is PaykitException.Protocol && PROFILE_LINK_CONTEXT in it.context } + fun Throwable.isPaykitSignupCodeRejected(): Boolean = generateSequence(this) { it.cause }.any { it is PaykitException.Identity && it.code == SIGNUP_CODE_REJECTED_CODE } diff --git a/app/src/main/java/to/bitkit/models/PubkyAppLink.kt b/app/src/main/java/to/bitkit/models/PubkyAppLink.kt new file mode 100644 index 0000000000..68898203d0 --- /dev/null +++ b/app/src/main/java/to/bitkit/models/PubkyAppLink.kt @@ -0,0 +1,88 @@ +package to.bitkit.models + +import to.bitkit.ext.isWebLink +import java.net.URI + +/** pubky.app link limits from pubky-app-specs, as Paykit checks them when it publishes a profile. */ +const val PUBKY_APP_LINK_TITLE_MAX_LENGTH = 100 +const val PUBKY_APP_LINK_URL_MAX_LENGTH = 300 + +private val ISO_DATE = Regex("""\d{4}-\d{2}-\d{2}""") +private val WEB_SCHEMES = setOf("http", "https", "ws", "wss", "ftp") +private val IPV4 = Regex("""\d{1,3}(\.\d{1,3}){3}""") + +/** Why pubky.app would refuse a profile link, checked on the label and URL a profile save sends. */ +enum class PubkyAppLinkError { LABEL_TOO_LONG, URL_TOO_LONG, URL_INVALID } + +/** + * The first rule pubky.app's publisher would refuse [label] and [url] for, after the normalization a profile save + * applies, or null when it accepts them. A blank label or URL is left to the caller. [webOnly] also requires an + * http(s) link, as a social v1 profile does. + */ +fun pubkyAppLinkError(label: String, url: String, webOnly: Boolean): PubkyAppLinkError? { + val title = label.singleLine() + if (title.codePointCount(0, title.length) > PUBKY_APP_LINK_TITLE_MAX_LENGTH) return PubkyAppLinkError.LABEL_TOO_LONG + if (url.isBlank()) return null + val normalized = url.normalizedLinkUrl()?.takeIf { it.isParsableLinkUrl() } ?: return PubkyAppLinkError.URL_INVALID + if (webOnly && !url.isWebLink()) return PubkyAppLinkError.URL_INVALID + if (normalized.codePointCount(0, normalized.length) > PUBKY_APP_LINK_URL_MAX_LENGTH) { + return PubkyAppLinkError.URL_TOO_LONG + } + return null +} + +/** One line of text as pubky.app keeps it: control characters become spaces and the ends are trimmed. */ +fun String.singleLine() = map { if (it.isISOControl()) ' ' else it }.joinToString("").trim() + +/** + * This link as the full URL pubky.app needs, or null when pubky.app cannot hold it. Bitkit accepted links without a + * scheme (a site, an email address, a phone number), which gain one here. + */ +fun String.toPubkyAppLinkUrl(): String? = normalizedLinkUrl()?.takeIf { + it.codePointCount(0, it.length) <= PUBKY_APP_LINK_URL_MAX_LENGTH && it.isParsableLinkUrl() +} + +private fun String.normalizedLinkUrl(): String? { + val value = trim().takeIf { it.isNotEmpty() } ?: return null + val isPhone = value.isPhoneNumber() + if (!isPhone && value.any { it.isWhitespace() }) return null + val scheme = if (isPhone) null else runCatching { URI(value).scheme }.getOrNull() + return when { + scheme != null -> scheme.lowercase() + value.substring(scheme.length) + value.isEmailAddress() -> "mailto:$value" + isPhone -> "tel:" + value.filterNot { it in " -()." } + '.' in value && !value.startsWith('.') -> "https://$value" + else -> null + } +} + +private fun String.isParsableLinkUrl(): Boolean { + val parsed = runCatching { URI(this) }.getOrNull() ?: return false + return parsed.scheme != null && parsed.hasValidHost() +} + +/** + * Paykit's URL parser reads a web URL's host that ends in an all-digit label as an IPv4 address (one to four + * numbers, as in `127.1`) and rejects it when it is not one; other schemes keep such hosts as they are. + */ +private fun URI.hasValidHost(): Boolean { + if (scheme?.lowercase() !in WEB_SCHEMES) return true + // java.net.URI leaves the host null when the name is not a valid hostname, so fall back to the authority. + val host = host ?: rawAuthority?.substringAfterLast('@')?.substringBefore(':') ?: return true + if (!host.substringAfterLast('.').all { it.isDigit() }) return true + val numbers = host.split('.').map { it.toLongOrNull() ?: return false } + if (numbers.size !in 1..4) return false + val lastLimit = (1L shl (8 * (5 - numbers.size))) - 1 + return numbers.dropLast(1).all { it <= 255 } && numbers.last() <= lastLimit +} + +private fun String.isEmailAddress(): Boolean { + val parts = split('@') + return parts.size == 2 && parts[0].isNotEmpty() && '.' in parts[1] && '/' !in this +} + +private fun String.isPhoneNumber(): Boolean { + val digits = count { it.isDigit() } + return (startsWith('+') || digits >= 7) && digits >= 5 && all { it in "+0123456789 -()." } && '+' !in drop(1) && + !ISO_DATE.matches(this) && !IPV4.matches(this) +} diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index 1efe4815aa..a35bb9bb08 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -63,6 +63,8 @@ import to.bitkit.ext.isPaykitTemporarilyUnavailable import to.bitkit.ext.nowMs import to.bitkit.ext.runSuspendCatching import to.bitkit.models.HomegateResponse +import to.bitkit.models.PUBKY_APP_LINK_TITLE_MAX_LENGTH +import to.bitkit.models.PUBKY_APP_LINK_URL_MAX_LENGTH import to.bitkit.models.PubkyAuthClaim import to.bitkit.models.PubkyAuthRequest import to.bitkit.models.PubkyAuthRequestError @@ -73,14 +75,15 @@ import to.bitkit.models.PubkyProfileLink import to.bitkit.models.PubkyPublicKeyFormat import to.bitkit.models.PubkySessionBackupKind import to.bitkit.models.PubkySessionBackupV1 +import to.bitkit.models.singleLine import to.bitkit.models.takeCodePoints +import to.bitkit.models.toPubkyAppLinkUrl import to.bitkit.services.PaykitReadLane import to.bitkit.services.PaykitReadTimeoutError import to.bitkit.services.PubkyService import to.bitkit.utils.AppError import to.bitkit.utils.Logger import java.io.ByteArrayOutputStream -import java.net.URI import java.util.concurrent.atomic.AtomicInteger import java.util.concurrent.atomic.AtomicLong import javax.inject.Inject @@ -211,11 +214,6 @@ class PubkyRepo @Inject constructor( private const val PUBKY_APP_NAME_MAX_LENGTH = 50 private const val PUBKY_APP_BIO_MAX_LENGTH = 160 private const val PUBKY_APP_LINKS_MAX_COUNT = 5 - private val ISO_DATE = Regex("""\d{4}-\d{2}-\d{2}""") - private val WEB_SCHEMES = setOf("http", "https", "ws", "wss", "ftp") - private val IPV4 = Regex("""\d{1,3}(\.\d{1,3}){3}""") - private const val PUBKY_APP_LINK_TITLE_MAX_LENGTH = 100 - private const val PUBKY_APP_LINK_URL_MAX_LENGTH = 300 private const val PUBKY_APP_AVATAR_MAX_BYTES = 5_242_880uL } @@ -1573,52 +1571,6 @@ class PubkyRepo @Inject constructor( private fun Throwable.isConcurrentUpdate() = generateSequence(this) { it.cause }.any { it is PaykitException.ConcurrentUpdate } - private fun String.singleLine() = map { if (it.isISOControl()) ' ' else it }.joinToString("").trim() - - private fun String.toPubkyAppLinkUrl(): String? { - val value = trim().takeIf { it.isNotEmpty() } ?: return null - val isPhone = value.isPhoneNumber() - if (!isPhone && value.any { it.isWhitespace() }) return null - val scheme = if (isPhone) null else runCatching { URI(value).scheme }.getOrNull() - val url = when { - scheme != null -> scheme.lowercase() + value.substring(scheme.length) - value.isEmailAddress() -> "mailto:$value" - isPhone -> "tel:" + value.filterNot { it in " -()." } - '.' in value && !value.startsWith('.') -> "https://$value" - else -> return null - } - val parsed = runCatching { URI(url) }.getOrNull() - val valid = url.codePointCount(0, url.length) <= PUBKY_APP_LINK_URL_MAX_LENGTH && - parsed?.scheme != null && parsed.hasValidHost() - return url.takeIf { valid } - } - - /** - * Paykit's URL parser reads a web URL's host that ends in an all-digit label as an IPv4 address (one to four - * numbers, as in `127.1`) and rejects it when it is not one; other schemes keep such hosts as they are. - */ - private fun URI.hasValidHost(): Boolean { - if (scheme?.lowercase() !in WEB_SCHEMES) return true - // java.net.URI leaves the host null when the name is not a valid hostname, so fall back to the authority. - val host = host ?: rawAuthority?.substringAfterLast('@')?.substringBefore(':') ?: return true - if (!host.substringAfterLast('.').all { it.isDigit() }) return true - val numbers = host.split('.').map { it.toLongOrNull() ?: return false } - if (numbers.size !in 1..4) return false - val lastLimit = (1L shl (8 * (5 - numbers.size))) - 1 - return numbers.dropLast(1).all { it <= 255 } && numbers.last() <= lastLimit - } - - private fun String.isEmailAddress(): Boolean { - val parts = split('@') - return parts.size == 2 && parts[0].isNotEmpty() && '.' in parts[1] && '/' !in this - } - - private fun String.isPhoneNumber(): Boolean { - val digits = count { it.isDigit() } - return (startsWith('+') || digits >= 7) && digits >= 5 && all { it in "+0123456789 -()." } && '+' !in drop(1) && - !ISO_DATE.matches(this) && !IPV4.matches(this) - } - /** Social v1's own link rule: a lowercase `http://` or `https://` prefix; it drops other links on migration too. */ private fun String.isSocialV1WebUrl() = startsWith("http://") || startsWith("https://") diff --git a/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt b/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt index c55e14e11c..348bd6091e 100644 --- a/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt +++ b/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt @@ -29,7 +29,8 @@ import kotlinx.collections.immutable.ImmutableList import kotlinx.collections.immutable.persistentListOf import kotlinx.collections.immutable.toImmutableList import to.bitkit.R -import to.bitkit.ext.isWebLink +import to.bitkit.models.PubkyAppLinkError +import to.bitkit.models.pubkyAppLinkError import to.bitkit.ui.scaffold.SheetTopBar import to.bitkit.ui.shared.modifiers.sheetHeight import to.bitkit.ui.shared.util.gradientBackground @@ -45,6 +46,7 @@ private val LINK_SUGGESTIONS = persistentListOf( /** Suggestions whose links are not web links, which social v1 profiles reject. */ private val NON_WEB_SUGGESTIONS = setOf("Email", "Phone") +/** [webLinksOnly] marks a profile link, which pubky.app publishes: it must be a web link that meets its rules. */ @OptIn(ExperimentalMaterial3Api::class) @Composable fun AddLinkSheet( @@ -55,6 +57,8 @@ fun AddLinkSheet( var label by remember { mutableStateOf("") } var url by remember { mutableStateOf("") } var showSuggestions by remember { mutableStateOf(false) } + val linkError = if (webLinksOnly) pubkyAppLinkError(label, url, webOnly = true) else null + val linkErrorText = linkError?.let { pubkyAppLinkErrorText(it) } val focusManager = LocalFocusManager.current val keyboardController = LocalSoftwareKeyboardController.current @@ -97,7 +101,9 @@ fun AddLinkSheet( dismissKeyboard() onSave(label, url) }, - isSaveEnabled = label.isNotBlank() && url.isNotBlank() && (!webLinksOnly || url.isWebLink()), + labelError = linkErrorText.takeIf { linkError == PubkyAppLinkError.LABEL_TOO_LONG }, + urlError = linkErrorText.takeIf { linkError != PubkyAppLinkError.LABEL_TOO_LONG }, + isSaveEnabled = label.isNotBlank() && url.isNotBlank() && linkError == null, ) } } @@ -112,6 +118,8 @@ private fun LinkFormContent( onShowSuggestions: () -> Unit, onSave: () -> Unit, isSaveEnabled: Boolean, + labelError: String? = null, + urlError: String? = null, ) { Column( modifier = Modifier @@ -130,6 +138,8 @@ private fun LinkFormContent( placeholder = stringResource(R.string.profile__add_link_label_placeholder), trailingIcon = { SuggestionsButton(onClick = onShowSuggestions) }, singleLine = true, + isError = labelError != null, + supportingText = labelError?.let { { FieldError(text = it, testTag = "AddLinkLabelError") } }, modifier = Modifier .fillMaxWidth() .testTag("AddLinkLabel"), @@ -142,6 +152,8 @@ private fun LinkFormContent( onValueChange = onUrlChange, placeholder = stringResource(R.string.profile__add_link_url_placeholder), singleLine = true, + isError = urlError != null, + supportingText = urlError?.let { { FieldError(text = it, testTag = "AddLinkUrlError") } }, modifier = Modifier .fillMaxWidth() .testTag("AddLinkUrl"), @@ -162,6 +174,22 @@ private fun LinkFormContent( } } +@Composable +fun pubkyAppLinkErrorText(error: PubkyAppLinkError): String = when (error) { + PubkyAppLinkError.LABEL_TOO_LONG -> stringResource(R.string.profile__link_error_label_length) + PubkyAppLinkError.URL_TOO_LONG -> stringResource(R.string.profile__link_error_url_length) + PubkyAppLinkError.URL_INVALID -> stringResource(R.string.profile__link_error_url_invalid) +} + +@Composable +private fun FieldError(text: String, testTag: String) { + BodyS( + text = text, + color = Colors.Red, + modifier = Modifier.testTag(testTag) + ) +} + @OptIn(ExperimentalLayoutApi::class) @Composable internal fun SuggestionsContent( @@ -236,3 +264,20 @@ private fun Preview() { ) } } + +@Preview +@Composable +private fun PreviewError() { + AppThemeSurface { + LinkFormContent( + label = "Website", + url = "not a url", + onLabelChange = {}, + onUrlChange = {}, + onShowSuggestions = {}, + onSave = {}, + isSaveEnabled = false, + urlError = pubkyAppLinkErrorText(PubkyAppLinkError.URL_INVALID), + ) + } +} diff --git a/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt b/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt index 8d4f534d38..6a67454fd5 100644 --- a/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt +++ b/app/src/main/java/to/bitkit/ui/components/ProfileEditForm.kt @@ -49,7 +49,9 @@ import androidx.compose.ui.unit.dp import dev.chrisbanes.haze.hazeSource import dev.chrisbanes.haze.rememberHazeState import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.ImmutableMap import kotlinx.collections.immutable.persistentListOf +import kotlinx.collections.immutable.persistentMapOf import to.bitkit.R import to.bitkit.models.takeCodePoints import to.bitkit.ui.theme.AppTextFieldDefaults @@ -83,6 +85,7 @@ fun ProfileEditForm( isSaving: Boolean = false, isDeleting: Boolean = false, maxLinks: Int? = null, + linkErrors: ImmutableMap = persistentMapOf(), avatarContent: @Composable () -> Unit = {}, publicKeyLabel: String? = null, bioPlaceholder: String? = null, @@ -146,6 +149,7 @@ fun ProfileEditForm( HorizontalDivider() links.forEachIndexed { index, link -> + val linkError = linkErrors[index] FieldLabel(text = link.label) { TextInput( enabled = !isBusy, @@ -153,6 +157,16 @@ fun ProfileEditForm( onValueChange = { onLinkUrlChange(index, it) }, placeholder = stringResource(R.string.profile__add_link_url_placeholder), singleLine = true, + isError = linkError != null, + supportingText = linkError?.let { message -> + { + BodyS( + text = message, + color = Colors.Red, + modifier = Modifier.testTag("ProfileEditLinkError_$index") + ) + } + }, trailingIcon = { IconButton( onClick = { onRemoveLink(index) }, diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt index 20712a3abc..f038ec2432 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt @@ -29,6 +29,7 @@ import androidx.compose.ui.window.DialogProperties import androidx.lifecycle.compose.collectAsStateWithLifecycle import coil3.compose.AsyncImage import kotlinx.collections.immutable.persistentListOf +import kotlinx.collections.immutable.toImmutableMap import to.bitkit.R import to.bitkit.models.PROFILE_LINKS_MAX_COUNT import to.bitkit.models.isValidProfileName @@ -38,6 +39,7 @@ import to.bitkit.ui.components.GradientCircularProgressIndicator import to.bitkit.ui.components.ProfileEditForm import to.bitkit.ui.components.ProfileEditLink import to.bitkit.ui.components.PubkyImage +import to.bitkit.ui.components.pubkyAppLinkErrorText import to.bitkit.ui.scaffold.AppAlertDialog import to.bitkit.ui.scaffold.AppTopBar import to.bitkit.ui.scaffold.DrawerNavIcon @@ -161,6 +163,9 @@ private fun Content( onBioChange = onBioChange, links = uiState.links, onLinkUrlChange = onLinkUrlChange, + linkErrors = uiState.linkErrors + .mapValues { (_, error) -> pubkyAppLinkErrorText(error) } + .toImmutableMap(), onRemoveLink = onRemoveLink, onAddLink = onAddLink, tags = uiState.tags, @@ -168,7 +173,7 @@ private fun Content( onAddTag = onAddTag, onSave = onSave, onCancel = onBackClick, - isSaveEnabled = isValidProfileName(uiState.name) && uiState.hasOnlyWebLinks && !uiState.isBusy, + isSaveEnabled = isValidProfileName(uiState.name) && uiState.linkErrors.isEmpty() && !uiState.isBusy, topBar = topBar, isSaving = uiState.isSaving, isDeleting = uiState.isDeleting, 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 0f4901a66b..12ad1482e4 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 @@ -10,10 +10,13 @@ import androidx.lifecycle.viewModelScope import dagger.hilt.android.lifecycle.HiltViewModel import dagger.hilt.android.qualifiers.ApplicationContext import kotlinx.collections.immutable.ImmutableList +import kotlinx.collections.immutable.ImmutableMap import kotlinx.collections.immutable.ImmutableSet import kotlinx.collections.immutable.persistentListOf +import kotlinx.collections.immutable.persistentMapOf import kotlinx.collections.immutable.persistentSetOf import kotlinx.collections.immutable.toImmutableList +import kotlinx.collections.immutable.toImmutableMap import kotlinx.collections.immutable.toImmutableSet import kotlinx.coroutines.NonCancellable import kotlinx.coroutines.flow.MutableSharedFlow @@ -24,11 +27,14 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import to.bitkit.R +import to.bitkit.ext.isPaykitProfileLinkRejected import to.bitkit.ext.isWebLink import to.bitkit.ext.runSuspendCatching import to.bitkit.models.PROFILE_NAME_MAX_LENGTH +import to.bitkit.models.PubkyAppLinkError import to.bitkit.models.PubkyProfileLink import to.bitkit.models.Toast +import to.bitkit.models.pubkyAppLinkError import to.bitkit.models.takeCodePoints import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.ProfileEditBase @@ -80,6 +86,9 @@ class EditProfileViewModel @Inject constructor( links = profile.links.map { link -> ProfileEditLink(label = link.label, url = link.url) }.toImmutableList(), + storedLinks = profile.links.map { link -> + ProfileEditLink(label = link.label, url = link.url) + }.toImmutableList(), storedLinkUrls = profile.links.map { it.url }.toImmutableSet(), tags = profile.tags.toImmutableList(), imageUrl = profile.imageUrl, @@ -129,6 +138,7 @@ class EditProfileViewModel @Inject constructor( _uiState.update { it.copy( links = (it.links + ProfileEditLink(label = label, url = url)).toImmutableList(), + rejectedLinkIndex = null, showAddLinkSheet = false, ) } @@ -140,13 +150,17 @@ class EditProfileViewModel @Inject constructor( links = it.links.mapIndexed { i, link -> if (i == index) link.copy(url = url) else link }.toImmutableList(), + rejectedLinkIndex = null, ) } } fun removeLink(index: Int) { _uiState.update { - it.copy(links = it.links.filterIndexed { i, _ -> i != index }.toImmutableList()) + it.copy( + links = it.links.filterIndexed { i, _ -> i != index }.toImmutableList(), + rejectedLinkIndex = null, + ) } } @@ -192,7 +206,7 @@ class EditProfileViewModel @Inject constructor( fun save() { viewModelScope.launch { - if (_uiState.value.isBusy || !_uiState.value.hasOnlyWebLinks) return@launch + if (_uiState.value.isBusy || _uiState.value.linkErrors.isNotEmpty()) return@launch _uiState.update { it.copy(isSaving = true) } val state = _uiState.value @@ -228,12 +242,15 @@ class EditProfileViewModel @Inject constructor( _effects.emit(EditProfileEffect.SaveSuccess) }.onFailure { Logger.error("Failed to save profile", it, context = TAG) - _uiState.update { it.copy(isSaving = false) } + val rejectedLink = it.rejectedLinkIndex(state.links) + _uiState.update { it.copy(isSaving = false, rejectedLinkIndex = rejectedLink) } val changed = it is PubkyProfileChangedError ToastEventBus.send( type = Toast.ToastType.ERROR, title = context.getString(R.string.profile__edit_save_error), - description = it.profileSaveErrorText(context), + description = rejectedLink?.let { index -> + context.getString(R.string.profile__edit_link_error, state.links[index].label) + } ?: it.profileSaveErrorText(context), ) if (changed) reloadAfterExternalEdit() // The other fields are on pubky.app, so a retry starts from their revision. @@ -326,7 +343,9 @@ data class EditProfileUiState( val name: String = "", val bio: String = "", val links: ImmutableList = persistentListOf(), + val storedLinks: ImmutableList = persistentListOf(), val storedLinkUrls: ImmutableSet = persistentSetOf(), + val rejectedLinkIndex: Int? = null, val tags: ImmutableList = persistentListOf(), val imageUrl: String? = null, val newAvatarUri: Uri? = null, @@ -341,8 +360,23 @@ data class EditProfileUiState( ) { val isBusy: Boolean get() = isSaving || isDeleting - /** Links added or edited here must be web links, which social v1 requires; stored ones are left as they are. */ - val hasOnlyWebLinks: Boolean get() = links.all { it.url in storedLinkUrls || it.url.isWebLink() } + /** + * The links pubky.app would refuse, by index. A save sends the links only once they change, and then pubky.app + * checks every one, so a stored link is held to its rules too. Links added or edited here must also be web + * links, which social v1 requires; stored ones keep their scheme. + */ + val linkErrors: ImmutableMap + get() { + if (links == storedLinks) return persistentMapOf() + return links.withIndex().mapNotNull { (index, link) -> + val error = when { + index == rejectedLinkIndex -> PubkyAppLinkError.URL_INVALID + link.url.isBlank() -> PubkyAppLinkError.URL_INVALID + else -> pubkyAppLinkError(link.label, link.url, webOnly = link.url !in storedLinkUrls) + } + error?.let { index to it } + }.toMap().toImmutableMap() + } } enum class ProfileRemoval( @@ -386,6 +420,11 @@ sealed interface EditProfileEffect { data object DisconnectSuccess : EditProfileEffect } +private fun Throwable.rejectedLinkIndex(links: List): Int? { + if (!isPaykitProfileLinkRejected()) return null + return links.indexOfFirst { !it.url.isWebLink() }.takeIf { it >= 0 } +} + internal fun Throwable.profileSaveErrorText(context: Context): String? = when (this) { is PubkyProfileChangedError -> context.getString(R.string.profile__edit_changed_error) is PubkyProfileTagsNotSavedError -> context.getString(R.string.profile__edit_tags_error) diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 77614b84c1..0d24768ed7 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1538,6 +1538,7 @@ ملاحظة قصيرة. أخبرنا قليلاً عن نفسك. تغيّر ملفك الشخصي في pubky.app. حمّل Bitkit أحدث نسخة، لذا أعد إجراء تعديلك. حذف + أصلح رابط %1$s لحفظ ملفك الشخصي. اسمك تعديل الملف الشخصي هذا هو ملفك الشخصي على pubky.app. إنه عام، والتغييرات التي تجريها هنا تظهر أيضًا على pubky.app. @@ -1549,6 +1550,9 @@ تعذر تحميل ملفك الشخصي. مع ملفك الشخصي المحمول، يمكن لجهات اتصالك الوصول إليك والدفع لك في أي مكان. ملف شخصي\n<accent>محمول</accent> + يجب ألا يزيد التصنيف عن 100 حرفًا. + أدخل رابط ويب صالحًا، مثل example.com. + يجب ألا يزيد الرابط عن 300 حرفًا. استخدم Bitkit مع جهات اتصالك لإرسال المدفوعات مباشرةً، في أي وقت وفي أي مكان. دع\nجهات اتصالك\n<accent>تدفع لك</accent> الدفع لجهات الاتصال 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 06b95bfe98..af6fa294be 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1564,6 +1564,7 @@ Nota breve. Cuente un poco sobre usted. Tu perfil cambió en pubky.app. Bitkit cargó la versión más reciente, así que vuelve a hacer tu cambio. ELIMINAR + Corrige el enlace %1$s para guardar tu perfil. SU NOMBRE Este es tu perfil de pubky.app. Es público, y los cambios que hagas aquí también se ven en pubky.app. No se pudo guardar el perfil @@ -1574,6 +1575,9 @@ No se pudo cargar su perfil. Con su perfil portátil, sus contactos pueden encontrarlo y pagarle en cualquier lugar. PERFIL\n<accent>PORTÁTIL</accent> + La etiqueta debe tener 100 caracteres o menos. + Ingresa un enlace web válido, como example.com. + El enlace debe tener 300 caracteres o menos. Use Bitkit con sus contactos para enviar pagos directamente, en cualquier momento y lugar. Deje que sus\ncontactos\n<accent>le paguen</accent> Pagar a contactos diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index d6d4a9f2cb..e72eac839b 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1560,6 +1560,7 @@ Nota breu. Explica una mica sobre tu. El teu perfil ha canviat a pubky.app. Bitkit ha carregat la versió més recent, així que torna a fer la teva edició. ELIMINAR + Corregeix l\'enllaç %1$s per desar el teu perfil. EL TEU NOM Aquest és el teu perfil de pubky.app. És públic, i els canvis que hi facis aquí també es veuen a pubky.app. No s\'ha pogut desar el perfil @@ -1570,6 +1571,9 @@ No s\'ha pogut carregar el teu perfil. Amb el teu perfil portable, els teus contactes et poden trobar i pagar a qualsevol lloc. PERFIL\n<accent>PORTABLE</accent> + L\'etiqueta ha de tenir 100 caràcters o menys. + Introdueix un enllaç web vàlid, com ara example.com. + L\'enllaç ha de tenir 300 caràcters o menys. Utilitza Bitkit amb els teus contactes per enviar pagaments directament, en qualsevol moment i a qualsevol lloc. Deixa que els\nteus contactes\n<accent>et paguin</accent> Pagar contactes diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 82f4fd4833..a6a2ccc0ae 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1562,6 +1562,7 @@ Krátká poznámka. Řekněte něco o sobě. Tvůj profil se v pubky.app změnil. Bitkit načetl nejnovější verzi, proveď proto úpravu znovu. SMAZAT + Opravte odkaz %1$s, abyste mohli uložit profil. VAŠE JMÉNO Toto je tvůj profil na pubky.app. Je veřejný a změny, které zde provedeš, se zobrazí i na pubky.app. Profil se nepodařilo uložit @@ -1572,6 +1573,9 @@ Váš profil nelze načíst. Díky přenosnému profilu vás kontakty mohou kdekoli zastihnout a zaplatit vám. PŘENOSNÝ\n<accent>PROFIL</accent> + Popisek může mít nejvýše 100 znaků. + Zadejte platný webový odkaz, například example.com. + Odkaz může mít nejvýše 300 znaků. Používejte Bitkit se svými kontakty a posílejte platby přímo, kdykoli a kdekoli. Nechte své\nkontakty\n<accent>platit vám</accent> Platby kontaktům diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index b596372ffc..3273d7432d 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1560,6 +1560,7 @@ Kurze Notiz. Erzähl ein bisschen über dich. Dein Profil wurde in pubky.app geändert. Bitkit hat die neueste Version geladen, nimm deine Änderung bitte erneut vor. LÖSCHEN + Korrigiere den Link %1$s, um dein Profil zu speichern. DEIN NAME Das ist dein pubky.app-Profil. Es ist öffentlich, und Änderungen, die du hier vornimmst, erscheinen auch auf pubky.app. Profil konnte nicht gespeichert werden @@ -1570,6 +1571,9 @@ Dein Profil kann nicht geladen werden. Mit deinem portablen Profil können deine Kontakte dich überall erreichen und bezahlen. PORTABLES\n<accent>PROFIL</accent> + Die Bezeichnung darf höchstens 100 Zeichen lang sein. + Gib einen gültigen Weblink ein, z. B. example.com. + Der Link darf höchstens 300 Zeichen lang sein. Nutze Bitkit mit deinen Kontakten, um Zahlungen direkt zu senden, jederzeit und überall. Lass deine\nKontakte\n<accent>dich bezahlen</accent> Kontakte bezahlen diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 42a34f22fe..044ef3ddae 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1544,6 +1544,7 @@ Σύντομη σημείωση. Πες λίγα λόγια για τον εαυτό σου. Το προφίλ σου άλλαξε στο pubky.app. Το Bitkit φόρτωσε την πιο πρόσφατη έκδοση, οπότε κάνε ξανά την αλλαγή σου. ΔΙΑΓΡΑΦΗ + Διόρθωσε τον σύνδεσμο %1$s για να αποθηκεύσεις το προφίλ σου. ΤΟ ΟΝΟΜΑ ΣΟΥ Επεξεργασία προφίλ Αυτό είναι το προφίλ σου στο pubky.app. Είναι δημόσιο, και οι αλλαγές που κάνεις εδώ εμφανίζονται και στο pubky.app. @@ -1555,6 +1556,9 @@ Δεν ήταν δυνατή η φόρτωση του προφίλ σου. Με το φορητό προφίλ σου, οι επαφές σου μπορούν να σε βρουν και να σε πληρώσουν οπουδήποτε. ΦΟΡΗΤΟ\n<accent>ΠΡΟΦΙΛ</accent> + Η ετικέτα πρέπει να έχει έως 100 χαρακτήρες. + Εισήγαγε έναν έγκυρο σύνδεσμο ιστού, όπως example.com. + Ο σύνδεσμος πρέπει να έχει έως 300 χαρακτήρες. Χρησιμοποίησε το Bitkit με τις επαφές σου για να στέλνεις πληρωμές απευθείας, οποτεδήποτε, οπουδήποτε. Άφησε τις\nεπαφές σου\n<accent>να σε πληρώνουν</accent> Πληρωμή επαφών diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 6dc0e1e3d2..a9a1574c94 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1558,6 +1558,7 @@ Nota breve. Cuenta algo sobre ti. Tu perfil ha cambiado en pubky.app. Bitkit ha cargado la versión más reciente, así que vuelve a hacer tu cambio. ELIMINAR + Corrige el enlace %1$s para guardar tu perfil. TU NOMBRE Este es tu perfil de pubky.app. Es público, y los cambios que hagas aquí también se ven en pubky.app. No se pudo guardar el perfil @@ -1568,6 +1569,9 @@ No se pudo cargar tu perfil. Con tu perfil portátil, tus contactos pueden localizarte y pagarte en cualquier lugar. PERFIL\n<accent>PORTÁTIL</accent> + La etiqueta debe tener 100 caracteres o menos. + Introduce un enlace web válido, como example.com. + El enlace debe tener 300 caracteres o menos. Usa Bitkit con tus contactos para enviar pagos directamente, en cualquier momento y lugar. Deja que\ntus contactos\n<accent>te paguen</accent> Pagar a contactos diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 263394119f..716c0bcf1d 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1557,6 +1557,7 @@ Nota breve. Cuente algo sobre usted. Tu perfil cambió en pubky.app. Bitkit cargó la versión más reciente, así que vuelve a hacer tu cambio. ELIMINAR + Corrige el enlace %1$s para guardar tu perfil. SU NOMBRE Este es tu perfil de pubky.app. Es público, y los cambios que hagas aquí también se ven en pubky.app. No se pudo guardar el perfil @@ -1567,6 +1568,9 @@ No se pudo cargar su perfil. Con su perfil portátil, sus contactos pueden localizarle y pagarle en cualquier lugar. PERFIL\n<accent>PORTÁTIL</accent> + La etiqueta debe tener 100 caracteres o menos. + Introduce un enlace web válido, como example.com. + El enlace debe tener 300 caracteres o menos. Use Bitkit con sus contactos para enviar pagos directamente, en cualquier momento y lugar. Deje que\nsus contactos\n<accent>le paguen</accent> Pagar a contactos diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index f5a04008e8..26a0eb17be 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1558,6 +1558,7 @@ Courte note. Parlez un peu de vous. Ton profil a changé sur pubky.app. Bitkit a chargé la version la plus récente, refais donc ta modification. SUPPRIMER + Corrigez le lien %1$s pour enregistrer votre profil. VOTRE NOM Voici ton profil pubky.app. Il est public, et les modifications que tu fais ici apparaissent aussi sur pubky.app. Échec de l\'enregistrement du profil @@ -1568,6 +1569,9 @@ Impossible de charger votre profil. Grâce à votre profil portable, vos contacts peuvent vous joindre et vous payer partout. PROFIL\n<accent>PORTABLE</accent> + Le libellé doit contenir 100 caractères au maximum. + Saisissez un lien web valide, par exemple example.com. + Le lien doit contenir 300 caractères au maximum. Utilisez Bitkit avec vos contacts pour envoyer des paiements directement, à tout moment, partout. Laissez vos\ncontacts\n<accent>vous payer</accent> Payer des contacts diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 93b5988584..4b36afac68 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1563,6 +1563,7 @@ Breve nota. Racconta qualcosa di te. Il tuo profilo è cambiato su pubky.app. Bitkit ha caricato la versione più recente, quindi ripeti la modifica. ELIMINA + Correggi il link %1$s per salvare il tuo profilo. IL TUO NOME Questo è il tuo profilo pubky.app. È pubblico e le modifiche che fai qui compaiono anche su pubky.app. Impossibile salvare il profilo @@ -1573,6 +1574,9 @@ Impossibile caricare il tuo profilo. Con il tuo profilo portatile i tuoi contatti possono raggiungerti e pagarti ovunque. PROFILO\n<accent>PORTATILE</accent> + L\'etichetta deve avere al massimo 100 caratteri. + Inserisci un link web valido, ad esempio example.com. + Il link deve avere al massimo 300 caratteri. Usa Bitkit con i tuoi contatti per inviare pagamenti direttamente, in qualsiasi momento, ovunque. Lascia che\ni tuoi contatti\n<accent>ti paghino</accent> Paga Contatti diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index da06deedb7..8802b3b1a6 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1560,6 +1560,7 @@ Korte notitie. Vertel iets over uzelf. Je profiel is gewijzigd in pubky.app. Bitkit heeft de nieuwste versie geladen, dus voer je wijziging opnieuw uit. VERWIJDEREN + Corrigeer de link %1$s om je profiel op te slaan. UW NAAM Dit is je pubky.app-profiel. Het is openbaar, en wijzigingen die je hier maakt, verschijnen ook op pubky.app. Profiel opslaan mislukt @@ -1570,6 +1571,9 @@ Kan uw profiel niet laden. Met uw draagbare profiel kunnen uw contacten u overal bereiken en betalen. DRAAGBAAR\n<accent>PROFIEL</accent> + Het label mag maximaal 100 tekens bevatten. + Voer een geldige weblink in, zoals example.com. + De link mag maximaal 300 tekens bevatten. Gebruik Bitkit met uw contacten om direct betalingen te versturen, altijd en overal. Laat uw\ncontacten\n<accent>u betalen</accent> Contacten betalen diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 2eca3d9717..a614e31368 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1561,6 +1561,7 @@ Krótka notatka. Napisz coś o sobie. Twój profil zmienił się w pubky.app. Bitkit wczytał najnowszą wersję, więc wprowadź zmianę ponownie. USUWANIE + Popraw link %1$s, aby zapisać profil. TWOJE IMIĘ To jest Twój profil pubky.app. Jest publiczny, a zmiany wprowadzone tutaj pojawią się też w pubky.app. Nie udało się zapisać profilu @@ -1571,6 +1572,9 @@ Nie można wczytać Twojego profilu. Dzięki przenośnemu profilowi Twoje kontakty mogą skontaktować się z Tobą i zapłacić Ci w dowolnym miejscu. PRZENOŚNY\n<accent>PROFIL</accent> + Etykieta może mieć maksymalnie 100 znaków. + Wpisz prawidłowy link internetowy, np. example.com. + Link może mieć maksymalnie 300 znaków. Używaj Bitkit ze swoimi kontaktami, aby wysyłać płatności bezpośrednio, zawsze i wszędzie. Pozwól\nkontaktom\n<accent>płacić Ci</accent> Płać kontaktom diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index ecf958ac73..550930bfbb 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1563,6 +1563,7 @@ Nota curta. Conte um pouco sobre você. Seu perfil mudou no pubky.app. O Bitkit carregou a versão mais recente, então faça sua alteração de novo. EXCLUIR + Corrija o link %1$s para salvar seu perfil. SEU NOME Este é o seu perfil do pubky.app. Ele é público, e as alterações que você faz aqui também aparecem no pubky.app. Falha ao salvar perfil @@ -1573,6 +1574,9 @@ Não foi possível carregar seu perfil. Com seu perfil portátil, seus contatos podem encontrar você e pagar você em qualquer lugar. PERFIL\n<accent>PORTÁTIL</accent> + O rótulo deve ter no máximo 100 caracteres. + Insira um link da web válido, como example.com. + O link deve ter no máximo 300 caracteres. Use a Bitkit com seus contatos para enviar pagamentos diretamente, a qualquer hora, em qualquer lugar. Deixe seus\ncontatos\n<accent>pagarem você</accent> Pagar Contatos diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index fe167db418..fe14eedc15 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1537,6 +1537,7 @@ Nota breve. Fale um pouco sobre si. O teu perfil mudou no pubky.app. A Bitkit carregou a versão mais recente, por isso faz novamente a tua alteração. ELIMINAR + Corrija a ligação %1$s para guardar o seu perfil. O SEU NOME Editar perfil Este é o teu perfil do pubky.app. É público, e as alterações que fazes aqui também aparecem no pubky.app. @@ -1548,6 +1549,9 @@ Não foi possível carregar o seu perfil. Com o seu perfil portátil, os seus contactos podem encontrá-lo e pagar-lhe em qualquer lugar. PERFIL\n<accent>PORTÁTIL</accent> + A etiqueta deve ter no máximo 100 caracteres. + Introduza uma ligação web válida, como example.com. + A ligação deve ter no máximo 300 caracteres. Use a Bitkit com os seus contactos para enviar pagamentos diretamente, a qualquer hora, em qualquer lugar. Deixe os seus\ncontactos\n<accent>pagar-lhe</accent> Pagar a contactos diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 08e92af37c..92a47f7832 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1576,6 +1576,7 @@ Короткая заметка. Расскажите немного о себе. Ваш профиль изменился в pubky.app. Bitkit загрузил последнюю версию, поэтому внесите изменение снова. УДАЛЕНИЕ + Исправьте ссылку %1$s, чтобы сохранить профиль. ВАШЕ ИМЯ Это ваш профиль pubky.app. Он публичный, и изменения, которые вы вносите здесь, также видны в pubky.app. Не удалось сохранить профиль @@ -1586,6 +1587,9 @@ Не удалось загрузить ваш профиль. С переносимым профилем ваши контакты смогут связаться с вами и заплатить вам где угодно. ПЕРЕНОСИМЫЙ\n<accent>ПРОФИЛЬ</accent> + Метка должна содержать не более 100 символов. + Введите корректную веб-ссылку, например example.com. + Ссылка должна содержать не более 300 символов. Используйте Bitkit, чтобы отправлять платежи контактам напрямую — когда угодно и где угодно. Пусть ваши\nконтакты\n<accent>платят вам</accent> Платежи Контактам diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 47968335dd..07756c15c9 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -845,6 +845,7 @@ Short note. Tell a bit about yourself. Your profile changed in pubky.app. Bitkit loaded the latest version, so make your edit again. DELETE + Fix the %1$s link to save your profile. YOUR NAME Edit Profile This is your pubky.app profile. It is public, and changes you make here also show on pubky.app. @@ -856,6 +857,9 @@ Unable to load your profile. With your portable profile your contacts can reach you and pay you anywhere. PORTABLE\n<accent>PROFILE</accent> + Label must be 100 characters or fewer. + Enter a valid web link, such as example.com. + Link must be 300 characters or fewer. Profile Use Bitkit with your contacts to send payments directly, anytime, anywhere. Let your\ncontacts\n<accent>pay you</accent> diff --git a/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt b/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt new file mode 100644 index 0000000000..609fe3db10 --- /dev/null +++ b/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt @@ -0,0 +1,74 @@ +package to.bitkit.models + +import org.junit.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull + +class PubkyAppLinkTest { + @Test + fun `labels are limited to 100 code points, emoji counted once`() { + val emoji = "🚀" + + assertNull(pubkyAppLinkError(emoji.repeat(100), "example.com", webOnly = true)) + assertEquals( + PubkyAppLinkError.LABEL_TOO_LONG, + pubkyAppLinkError(emoji.repeat(101), "example.com", webOnly = true), + ) + assertNull(pubkyAppLinkError(" " + "a".repeat(100) + "\n", "example.com", webOnly = true)) + } + + @Test + fun `urls are limited to 300 code points after normalization`() { + val emoji = "🚀" + val at300 = "https://example.com/" + "a".repeat(280) + val bareAt301 = "example.com/" + "a".repeat(281) + + assertEquals(300, at300.length) + assertNull(pubkyAppLinkError("Site", at300, webOnly = true)) + assertEquals(PubkyAppLinkError.URL_TOO_LONG, pubkyAppLinkError("Site", "${at300}a", webOnly = true)) + assertEquals(PubkyAppLinkError.URL_TOO_LONG, pubkyAppLinkError("Site", bareAt301, webOnly = true)) + assertNull(pubkyAppLinkError("Site", "https://example.com/" + emoji.repeat(280), webOnly = true)) + assertEquals( + PubkyAppLinkError.URL_TOO_LONG, + pubkyAppLinkError("Site", "https://example.com/" + emoji.repeat(281), webOnly = true), + ) + } + + @Test + fun `invalid urls are refused`() { + listOf("not a url", "example", "https://", "https://exa mple.com", "https://1.2.3.999").forEach { + assertEquals(PubkyAppLinkError.URL_INVALID, pubkyAppLinkError("Site", it, webOnly = false), it) + } + } + + @Test + fun `normalizable inputs are accepted`() { + listOf("example.com", " www.example.com/path ", "https://Example.com", "HTTPS://example.com").forEach { + assertNull(pubkyAppLinkError("Site", it, webOnly = true), it) + } + listOf("me@example.com", "+1 (234) 567-890", "mailto:me@example.com", "tel:+123456789").forEach { + assertNull(pubkyAppLinkError("Contact", it, webOnly = false), it) + } + } + + @Test + fun `web only links refuse email and phone`() { + listOf("me@example.com", "+1 234 567 890", "mailto:me@example.com", "ftp://example.com").forEach { + assertEquals(PubkyAppLinkError.URL_INVALID, pubkyAppLinkError("Contact", it, webOnly = true), it) + } + } + + @Test + fun `a blank url is left to the caller`() { + assertNull(pubkyAppLinkError("Site", " ", webOnly = true)) + } + + @Test + fun `links normalize to the url pubky app stores`() { + assertEquals("https://example.com", "example.com".toPubkyAppLinkUrl()) + assertEquals("mailto:me@example.com", "me@example.com".toPubkyAppLinkUrl()) + assertEquals("tel:+1234567890", "+1 (234) 567-890".toPubkyAppLinkUrl()) + assertEquals("https://Example.com", "HTTPS://Example.com".toPubkyAppLinkUrl()) + assertNull("not a url".toPubkyAppLinkUrl()) + } +} 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 156bbd3735..affeae50bd 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 @@ -3,6 +3,7 @@ package to.bitkit.ui.screens.profile import android.content.Context import androidx.lifecycle.viewModelScope import app.cash.turbine.test +import com.synonym.paykit.PaykitException import kotlinx.collections.immutable.toImmutableList import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.ExperimentalCoroutinesApi @@ -22,6 +23,7 @@ import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.R +import to.bitkit.models.PubkyAppLinkError import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyProfileLink import to.bitkit.repositories.PrivatePaykitRepo @@ -200,6 +202,71 @@ class EditProfileViewModelTest : BaseUnitTest() { verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), anyOrNull(), any()) } + @Test + fun `stored links are not checked while they are unchanged`() = test { + val sut = createSut(links = listOf(PubkyProfileLink("x".repeat(101), "https://example.com"))) + advanceUntilIdle() + whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), anyOrNull(), any())) + .thenReturn(Result.success(Unit)) + + sut.onNameChange("Alice Renamed") + sut.save() + advanceUntilIdle() + + assertTrue(sut.uiState.value.linkErrors.isEmpty()) + verify(pubkyRepo).saveProfile(any(), any(), any(), any(), anyOrNull(), any()) + } + + @Test + fun `a stored link pubky app refuses blocks the save once links change`() = test { + val sut = createSut(links = listOf(PubkyProfileLink("x".repeat(101), "https://example.com"))) + advanceUntilIdle() + + sut.addLink("Blog", "blog.example.com") + sut.save() + advanceUntilIdle() + + assertEquals(mapOf(0 to PubkyAppLinkError.LABEL_TOO_LONG), sut.uiState.value.linkErrors) + verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), anyOrNull(), any()) + + sut.removeLink(0) + + assertTrue(sut.uiState.value.linkErrors.isEmpty()) + } + + @Test + fun `an added link is held to the publisher limits`() = test { + val sut = createSut() + advanceUntilIdle() + + sut.addLink("Site", "example.com/" + "a".repeat(281)) + + assertEquals(mapOf(1 to PubkyAppLinkError.URL_TOO_LONG), sut.uiState.value.linkErrors) + } + + @Test + fun `a link rejection from pubky app points to the stored non-web link`() = test { + val sut = createSut(links = listOf(PubkyProfileLink("Email", "mailto:a@example.com"))) + advanceUntilIdle() + whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), anyOrNull(), any())).thenReturn( + Result.failure( + PaykitException.Protocol( + "protocol_error", + "Pubky profile link URL must be a canonical http or https URL", + ) + ) + ) + + sut.addLink("Site", "https://example.com") + assertTrue(sut.uiState.value.linkErrors.isEmpty()) + sut.save() + advanceUntilIdle() + + assertEquals(0, sut.uiState.value.rejectedLinkIndex) + assertEquals(mapOf(0 to PubkyAppLinkError.URL_INVALID), sut.uiState.value.linkErrors) + verify(context).getString(R.string.profile__edit_link_error, "Email") + } + @Test fun `deleteProfile should emit success when repository delete succeeds`() = test { whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) @@ -410,6 +477,7 @@ class EditProfileViewModelTest : BaseUnitTest() { private fun createSut( isRingIdentity: Boolean = false, ringCheck: CompletableDeferred? = null, + links: List = listOf(PubkyProfileLink("Website", "https://example.com")), ): EditProfileViewModel { whenever(context.getString(any())).thenReturn("") if (ringCheck != null) { @@ -418,8 +486,8 @@ class EditProfileViewModelTest : BaseUnitTest() { whenever { pubkyRepo.isRingAdoptedIdentity() }.thenReturn(isRingIdentity) } whenever { pubkyRepo.forgetUnrestoredIdentity() }.thenReturn(Result.success(false)) - whenever(pubkyRepo.profile).thenReturn(MutableStateFlow(createProfile())) - whenever(pubkyRepo.profileEditBase()).thenReturn(ProfileEditBase(createProfile(), "revision")) + whenever(pubkyRepo.profile).thenReturn(MutableStateFlow(createProfile(links))) + whenever(pubkyRepo.profileEditBase()).thenReturn(ProfileEditBase(createProfile(links), "revision")) whenever(pubkyRepo.publicKey).thenReturn(MutableStateFlow(TEST_PUBLIC_KEY)) whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any()) } .thenReturn(Result.success(Unit)) @@ -434,12 +502,12 @@ class EditProfileViewModelTest : BaseUnitTest() { ) } - private fun createProfile() = PubkyProfile( + private fun createProfile(links: List) = PubkyProfile( publicKey = TEST_PUBLIC_KEY, name = "Alice", bio = "Hello", imageUrl = "https://example.com/avatar.jpg", - links = listOf(PubkyProfileLink("Website", "https://example.com")), + links = links, tags = listOf("friend").toImmutableList(), status = null, ) diff --git a/changelog.d/next/1882.fixed.md b/changelog.d/next/1882.fixed.md new file mode 100644 index 0000000000..82b027b519 --- /dev/null +++ b/changelog.d/next/1882.fixed.md @@ -0,0 +1 @@ +Fixed profile links that pubky.app would refuse blocking the profile save: the link sheet now shows what to fix before saving, and Edit Profile points to an existing link that needs fixing. diff --git a/journeys/profile/README.md b/journeys/profile/README.md index 05c335007b..82662e5476 100644 --- a/journeys/profile/README.md +++ b/journeys/profile/README.md @@ -53,3 +53,5 @@ For controlled fault testing, interrupt deletion after private withdrawal but be `edit-pubky-app-profile.xml` checks that Edit Profile presents the profile as the public pubky.app profile and that a name edit is saved and survives a relaunch. Use an identity whose pubky.app profile you can open on pubky.app; checking the edit there, and an edit made in pubky.app while Bitkit is open, are manual checks beyond journey-runner capabilities. On Android, the restart check waits for the full profile (`ProfileViewName`). A matching `ProfileCachedName` during loading does not complete that check. Record an unfinished load separately from a loaded profile with a missing or incorrect name. + +`profile-link-validation.xml` checks that Add Link in Edit Profile shows an inline error and keeps Save disabled for a link pubky.app would refuse, and accepts a bare domain. The 100-code-point label and 300-code-point URL limits, and an already-stored invalid link blocking the profile save, are manual checks: long values cannot be typed reliably on a device, and an invalid stored link needs a profile written outside the current app. diff --git a/journeys/profile/profile-link-validation.xml b/journeys/profile/profile-link-validation.xml new file mode 100644 index 0000000000..ff954606f7 --- /dev/null +++ b/journeys/profile/profile-link-validation.xml @@ -0,0 +1,20 @@ + + + Precondition: a disposable wallet signed in to a Pubky profile with at most four links, PIN off and an English + device. This checks that the Add Link sheet in Edit Profile refuses links pubky.app would refuse, with an error on + the field that needs fixing, and still accepts a bare domain. + + + Open Profile using "ProfileButton" and wait for "ProfileViewName" + Tap "ProfileEdit" and wait for "ProfileEditName" + Tap "ProfileEditAddLink" and wait for "AddLinkLabel" + Enter "Website" in "AddLinkLabel" and "not a url" in "AddLinkUrl" + Verify "AddLinkUrlError" says "Enter a valid web link, such as example.com." and "AddLinkSave" is disabled + Replace the text in "AddLinkUrl" with "me@example.com" + Verify "AddLinkUrlError" is shown and "AddLinkSave" is disabled + Replace the text in "AddLinkUrl" with "example.com" + Verify "AddLinkUrlError" is gone and "AddLinkSave" is enabled + Tap "AddLinkSave" and verify a "Website" link with "example.com" appears in Edit Profile + Tap "ProfileEditSave" and wait for "ProfileUpdatedToast" + + From 6593d03ac5d33f0348bb75b328429bcffa0a0a39 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 13:26:08 -0300 Subject: [PATCH 2/7] fix: match link checks to the url parser paykit uses Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/ext/PaykitExceptionExt.kt | 13 ++- app/src/main/java/to/bitkit/ext/String.kt | 11 +- .../java/to/bitkit/models/PubkyAppLink.kt | 109 +++++++++++++----- .../to/bitkit/ui/components/AddLinkSheet.kt | 3 +- .../ui/screens/profile/EditProfileScreen.kt | 9 +- .../screens/profile/EditProfileViewModel.kt | 4 +- app/src/main/res/values-ar/strings.xml | 1 + app/src/main/res/values-b+es+419/strings.xml | 1 + app/src/main/res/values-ca/strings.xml | 1 + app/src/main/res/values-cs/strings.xml | 1 + app/src/main/res/values-de/strings.xml | 1 + app/src/main/res/values-el/strings.xml | 1 + app/src/main/res/values-es-rES/strings.xml | 1 + app/src/main/res/values-es/strings.xml | 1 + app/src/main/res/values-fr/strings.xml | 1 + app/src/main/res/values-it/strings.xml | 1 + app/src/main/res/values-nl/strings.xml | 1 + app/src/main/res/values-pl/strings.xml | 1 + app/src/main/res/values-pt-rBR/strings.xml | 1 + app/src/main/res/values-pt/strings.xml | 1 + app/src/main/res/values-ru/strings.xml | 1 + app/src/main/res/values/strings.xml | 1 + .../to/bitkit/ext/PaykitExceptionExtTest.kt | 14 +++ .../test/java/to/bitkit/ext/WebLinkTest.kt | 3 + .../java/to/bitkit/models/PubkyAppLinkTest.kt | 39 +++++++ .../profile/EditProfileViewModelTest.kt | 26 +++++ 26 files changed, 201 insertions(+), 46 deletions(-) diff --git a/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt b/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt index 8b5d9fe499..76f9da4a3a 100644 --- a/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt +++ b/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt @@ -11,8 +11,11 @@ private const val SIGNUP_CODE_REJECTED_CODE = "signup_code_rejected" /** Storage error code Paykit uses for local and shared state failures. */ private const val STORAGE_ERROR_CODE = "storage_error" -/** Start of the Protocol error contexts Paykit raises when a profile link breaks a pubky.app rule. */ -private const val PROFILE_LINK_CONTEXT = "Pubky profile link" +/** + * Protocol error context Paykit 0.1.1-rc9 raises when a social v1 profile holds a link that is not an http(s) URL + * (`paykit-sdk/src/domain/contacts/pubky_app.rs`). Check it again when Paykit is updated. + */ +internal const val PAYKIT_NON_WEB_PROFILE_LINK_CONTEXT = "Pubky profile link URL must be a canonical http or https URL" /** Storage error contexts Paykit raises when the identity's shared state was saved by a newer Paykit. */ private val NEWER_STATE_CONTEXTS = listOf( @@ -39,8 +42,10 @@ fun Throwable.isPaykitTemporarilyUnavailable(): Boolean = fun Throwable.isPaykitMessageTooLarge(): Boolean = generateSequence(this) { it.cause }.any { it is PaykitException.Protocol && it.code == MESSAGE_TOO_LARGE_CODE } -fun Throwable.isPaykitProfileLinkRejected(): Boolean = - generateSequence(this) { it.cause }.any { it is PaykitException.Protocol && PROFILE_LINK_CONTEXT in it.context } +fun Throwable.isPaykitNonWebProfileLinkRejected(): Boolean = + generateSequence(this) { it.cause }.any { + it is PaykitException.Protocol && it.context == PAYKIT_NON_WEB_PROFILE_LINK_CONTEXT + } fun Throwable.isPaykitSignupCodeRejected(): Boolean = generateSequence(this) { it.cause }.any { it is PaykitException.Identity && it.code == SIGNUP_CODE_REJECTED_CODE } diff --git a/app/src/main/java/to/bitkit/ext/String.kt b/app/src/main/java/to/bitkit/ext/String.kt index 81660c152f..aaabc2163a 100644 --- a/app/src/main/java/to/bitkit/ext/String.kt +++ b/app/src/main/java/to/bitkit/ext/String.kt @@ -2,8 +2,8 @@ package to.bitkit.ext import android.icu.text.MessageFormat import to.bitkit.env.Defaults +import to.bitkit.models.linkUrlParts import to.bitkit.utils.Logger -import java.net.URI private const val TAG = "StringExt" @@ -64,9 +64,8 @@ fun String.isWebLink(): Boolean { if (value.isEmpty() || value.any { it.isWhitespace() }) return false val hasScheme = URI_SCHEME.containsMatchIn(value) if (!hasScheme && '@' in value.substringBefore('/')) return false - val uri = runCatching { URI(if (hasScheme) value else "https://$value") }.getOrNull() ?: return false - val host = uri.host ?: return false - return uri.scheme.lowercase() in WEB_LINK_SCHEMES && - '.' in host && - !host.substringAfterLast('.').all { it.isDigit() } + val parts = (if (hasScheme) value else "https://$value").linkUrlParts() ?: return false + return parts.scheme in WEB_LINK_SCHEMES && + '.' in parts.host && + !parts.host.substringAfterLast('.').all { it.isDigit() } } diff --git a/app/src/main/java/to/bitkit/models/PubkyAppLink.kt b/app/src/main/java/to/bitkit/models/PubkyAppLink.kt index 68898203d0..14f9bb9b1e 100644 --- a/app/src/main/java/to/bitkit/models/PubkyAppLink.kt +++ b/app/src/main/java/to/bitkit/models/PubkyAppLink.kt @@ -1,33 +1,50 @@ package to.bitkit.models import to.bitkit.ext.isWebLink -import java.net.URI /** pubky.app link limits from pubky-app-specs, as Paykit checks them when it publishes a profile. */ const val PUBKY_APP_LINK_TITLE_MAX_LENGTH = 100 const val PUBKY_APP_LINK_URL_MAX_LENGTH = 300 +/** Highest port `url::Url::parse` accepts. */ +private const val MAX_PORT = 65_535 + +/** Characters `url::Url::parse` refuses in the host of a special URL, as WHATWG's forbidden domain code points. */ +private const val FORBIDDEN_HOST_CHARS = " #%/:<>?@[\\]^|" + private val ISO_DATE = Regex("""\d{4}-\d{2}-\d{2}""") -private val WEB_SCHEMES = setOf("http", "https", "ws", "wss", "ftp") +private val URL_SCHEME = Regex("""^([A-Za-z][A-Za-z0-9+.-]*):""") +private val SPECIAL_SCHEMES = setOf("http", "https", "ws", "wss", "ftp", "file") private val IPV4 = Regex("""\d{1,3}(\.\d{1,3}){3}""") /** Why pubky.app would refuse a profile link, checked on the label and URL a profile save sends. */ -enum class PubkyAppLinkError { LABEL_TOO_LONG, URL_TOO_LONG, URL_INVALID } +enum class PubkyAppLinkError { + LABEL_EMPTY, + LABEL_TOO_LONG, + URL_TOO_LONG, + URL_INVALID; + + val isLabelError: Boolean get() = this == LABEL_EMPTY || this == LABEL_TOO_LONG +} /** * The first rule pubky.app's publisher would refuse [label] and [url] for, after the normalization a profile save - * applies, or null when it accepts them. A blank label or URL is left to the caller. [webOnly] also requires an - * http(s) link, as a social v1 profile does. + * applies, or null when it accepts them. A blank URL is left to the caller; a label that is empty once on one line is + * reported last, so a URL error shows while the label is still blank. [webOnly] also requires an http(s) link, as a + * social v1 profile does. */ fun pubkyAppLinkError(label: String, url: String, webOnly: Boolean): PubkyAppLinkError? { val title = label.singleLine() if (title.codePointCount(0, title.length) > PUBKY_APP_LINK_TITLE_MAX_LENGTH) return PubkyAppLinkError.LABEL_TOO_LONG - if (url.isBlank()) return null - val normalized = url.normalizedLinkUrl()?.takeIf { it.isParsableLinkUrl() } ?: return PubkyAppLinkError.URL_INVALID - if (webOnly && !url.isWebLink()) return PubkyAppLinkError.URL_INVALID - if (normalized.codePointCount(0, normalized.length) > PUBKY_APP_LINK_URL_MAX_LENGTH) { - return PubkyAppLinkError.URL_TOO_LONG + if (url.isNotBlank()) { + val normalized = url.normalizedLinkUrl()?.takeIf { it.linkUrlParts() != null } + ?: return PubkyAppLinkError.URL_INVALID + if (webOnly && !url.isWebLink()) return PubkyAppLinkError.URL_INVALID + if (normalized.codePointCount(0, normalized.length) > PUBKY_APP_LINK_URL_MAX_LENGTH) { + return PubkyAppLinkError.URL_TOO_LONG + } } + if (title.isEmpty()) return PubkyAppLinkError.LABEL_EMPTY return null } @@ -39,14 +56,62 @@ fun String.singleLine() = map { if (it.isISOControl()) ' ' else it }.joinToStrin * scheme (a site, an email address, a phone number), which gain one here. */ fun String.toPubkyAppLinkUrl(): String? = normalizedLinkUrl()?.takeIf { - it.codePointCount(0, it.length) <= PUBKY_APP_LINK_URL_MAX_LENGTH && it.isParsableLinkUrl() + it.codePointCount(0, it.length) <= PUBKY_APP_LINK_URL_MAX_LENGTH && it.linkUrlParts() != null +} + +/** The lowercase scheme and the host of a URL; the host is empty for a scheme without one, such as `mailto`. */ +class LinkUrlParts(val scheme: String, val host: String) + +/** + * The scheme and host `url::Url::parse`, which Paykit validates links with, reads from this URL, or null when it + * would refuse it. A WHATWG-style check of what that parser rejects: a control character, a special URL (http, https, + * ws, wss, ftp) with an empty host, a forbidden host character or a port over 65535, and a host ending in an + * all-digit label that is not an IPv4 address (one to four numbers, as in `127.1`). Paths, queries and other + * schemes are accepted, as the parser accepts them. + */ +fun String.linkUrlParts(): LinkUrlParts? { + if (any { it.isISOControl() }) return null + val scheme = URL_SCHEME.find(this)?.groupValues?.get(1)?.lowercase() ?: return null + if (scheme !in SPECIAL_SCHEMES) return LinkUrlParts(scheme, host = "") + val authority = substring(scheme.length + 1).trimStart('/', '\\').takeWhile { it !in "/?#\\" } + val hostAndPort = authority.substringAfterLast('@') + val host = hostAndPort.hostPart() ?: return null + if (!hostAndPort.substring(host.length).isValidPort()) return null + if (scheme == "file") return LinkUrlParts(scheme, host) + if (host.isEmpty() || (!host.startsWith('[') && host.any { it in FORBIDDEN_HOST_CHARS })) return null + if (!host.isValidIpv4Ending()) return null + return LinkUrlParts(scheme, host.lowercase()) +} + +private fun String.hostPart(): String? { + if (!startsWith('[')) return substringBefore(':') + val end = indexOf(']').takeIf { it > 1 } ?: return null + val address = substring(1, end) + if (!address.all { it.isDigit() || it.lowercaseChar() in 'a'..'f' || it == ':' || it == '.' }) return null + return substring(0, end + 1) +} + +private fun String.isValidPort(): Boolean { + if (isEmpty()) return true + val port = removePrefix(":").takeIf { startsWith(':') } ?: return false + if (!port.all { it in '0'..'9' }) return false + val digits = port.trimStart('0') + return digits.length <= MAX_PORT.toString().length && (digits.toIntOrNull() ?: 0) <= MAX_PORT +} + +private fun String.isValidIpv4Ending(): Boolean { + if (startsWith('[') || !substringAfterLast('.').all { it.isDigit() }) return true + val numbers = split('.').map { it.toLongOrNull() ?: return false } + if (numbers.size !in 1..4) return false + val lastLimit = (1L shl (8 * (5 - numbers.size))) - 1 + return numbers.dropLast(1).all { it <= 255 } && numbers.last() <= lastLimit } private fun String.normalizedLinkUrl(): String? { val value = trim().takeIf { it.isNotEmpty() } ?: return null val isPhone = value.isPhoneNumber() if (!isPhone && value.any { it.isWhitespace() }) return null - val scheme = if (isPhone) null else runCatching { URI(value).scheme }.getOrNull() + val scheme = if (isPhone) null else URL_SCHEME.find(value)?.groupValues?.get(1) return when { scheme != null -> scheme.lowercase() + value.substring(scheme.length) value.isEmailAddress() -> "mailto:$value" @@ -56,26 +121,6 @@ private fun String.normalizedLinkUrl(): String? { } } -private fun String.isParsableLinkUrl(): Boolean { - val parsed = runCatching { URI(this) }.getOrNull() ?: return false - return parsed.scheme != null && parsed.hasValidHost() -} - -/** - * Paykit's URL parser reads a web URL's host that ends in an all-digit label as an IPv4 address (one to four - * numbers, as in `127.1`) and rejects it when it is not one; other schemes keep such hosts as they are. - */ -private fun URI.hasValidHost(): Boolean { - if (scheme?.lowercase() !in WEB_SCHEMES) return true - // java.net.URI leaves the host null when the name is not a valid hostname, so fall back to the authority. - val host = host ?: rawAuthority?.substringAfterLast('@')?.substringBefore(':') ?: return true - if (!host.substringAfterLast('.').all { it.isDigit() }) return true - val numbers = host.split('.').map { it.toLongOrNull() ?: return false } - if (numbers.size !in 1..4) return false - val lastLimit = (1L shl (8 * (5 - numbers.size))) - 1 - return numbers.dropLast(1).all { it <= 255 } && numbers.last() <= lastLimit -} - private fun String.isEmailAddress(): Boolean { val parts = split('@') return parts.size == 2 && parts[0].isNotEmpty() && '.' in parts[1] && '/' !in this diff --git a/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt b/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt index 348bd6091e..e01b3f55ee 100644 --- a/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt +++ b/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt @@ -102,7 +102,7 @@ fun AddLinkSheet( onSave(label, url) }, labelError = linkErrorText.takeIf { linkError == PubkyAppLinkError.LABEL_TOO_LONG }, - urlError = linkErrorText.takeIf { linkError != PubkyAppLinkError.LABEL_TOO_LONG }, + urlError = linkErrorText.takeIf { linkError?.isLabelError == false }, isSaveEnabled = label.isNotBlank() && url.isNotBlank() && linkError == null, ) } @@ -176,6 +176,7 @@ private fun LinkFormContent( @Composable fun pubkyAppLinkErrorText(error: PubkyAppLinkError): String = when (error) { + PubkyAppLinkError.LABEL_EMPTY -> stringResource(R.string.profile__link_error_label_stored) PubkyAppLinkError.LABEL_TOO_LONG -> stringResource(R.string.profile__link_error_label_length) PubkyAppLinkError.URL_TOO_LONG -> stringResource(R.string.profile__link_error_url_length) PubkyAppLinkError.URL_INVALID -> stringResource(R.string.profile__link_error_url_invalid) diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt index f038ec2432..686c569e53 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt @@ -164,7 +164,14 @@ private fun Content( links = uiState.links, onLinkUrlChange = onLinkUrlChange, linkErrors = uiState.linkErrors - .mapValues { (_, error) -> pubkyAppLinkErrorText(error) } + .mapValues { (_, error) -> + // A form row edits only the URL, so a label pubky.app refuses means adding the link again. + if (error.isLabelError) { + stringResource(R.string.profile__link_error_label_stored) + } else { + pubkyAppLinkErrorText(error) + } + } .toImmutableMap(), onRemoveLink = onRemoveLink, onAddLink = onAddLink, 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 12ad1482e4..87ac1e922f 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 @@ -27,7 +27,7 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import to.bitkit.R -import to.bitkit.ext.isPaykitProfileLinkRejected +import to.bitkit.ext.isPaykitNonWebProfileLinkRejected import to.bitkit.ext.isWebLink import to.bitkit.ext.runSuspendCatching import to.bitkit.models.PROFILE_NAME_MAX_LENGTH @@ -421,7 +421,7 @@ sealed interface EditProfileEffect { } private fun Throwable.rejectedLinkIndex(links: List): Int? { - if (!isPaykitProfileLinkRejected()) return null + if (!isPaykitNonWebProfileLinkRejected()) return null return links.indexOfFirst { !it.url.isWebLink() }.takeIf { it >= 0 } } diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 0d24768ed7..b6c04c9d69 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -1551,6 +1551,7 @@ مع ملفك الشخصي المحمول، يمكن لجهات اتصالك الوصول إليك والدفع لك في أي مكان. ملف شخصي\n<accent>محمول</accent> يجب ألا يزيد التصنيف عن 100 حرفًا. + لا يمكن حفظ تصنيف هذا الرابط. احذف الرابط وأضفه مرة أخرى. أدخل رابط ويب صالحًا، مثل example.com. يجب ألا يزيد الرابط عن 300 حرفًا. استخدم 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 af6fa294be..faafb178ef 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -1576,6 +1576,7 @@ Con su perfil portátil, sus contactos pueden encontrarlo y pagarle en cualquier lugar. PERFIL\n<accent>PORTÁTIL</accent> La etiqueta debe tener 100 caracteres o menos. + No se puede guardar la etiqueta de este enlace. Elimina el enlace y vuelve a agregarlo. Ingresa un enlace web válido, como example.com. El enlace debe tener 300 caracteres o menos. Use Bitkit con sus contactos para enviar pagos directamente, en cualquier momento y lugar. diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index e72eac839b..b2387ee04c 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -1572,6 +1572,7 @@ Amb el teu perfil portable, els teus contactes et poden trobar i pagar a qualsevol lloc. PERFIL\n<accent>PORTABLE</accent> L\'etiqueta ha de tenir 100 caràcters o menys. + No es pot desar l\'etiqueta d\'aquest enllaç. Elimina l\'enllaç i torna\'l a afegir. Introdueix un enllaç web vàlid, com ara example.com. L\'enllaç ha de tenir 300 caràcters o menys. Utilitza Bitkit amb els teus contactes per enviar pagaments directament, en qualsevol moment i a qualsevol lloc. diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index a6a2ccc0ae..e51efbbf48 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -1574,6 +1574,7 @@ Díky přenosnému profilu vás kontakty mohou kdekoli zastihnout a zaplatit vám. PŘENOSNÝ\n<accent>PROFIL</accent> Popisek může mít nejvýše 100 znaků. + Popisek tohoto odkazu nelze uložit. Odkaz odstraňte a přidejte znovu. Zadejte platný webový odkaz, například example.com. Odkaz může mít nejvýše 300 znaků. Používejte Bitkit se svými kontakty a posílejte platby přímo, kdykoli a kdekoli. diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 3273d7432d..3335dfd8fc 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -1572,6 +1572,7 @@ Mit deinem portablen Profil können deine Kontakte dich überall erreichen und bezahlen. PORTABLES\n<accent>PROFIL</accent> Die Bezeichnung darf höchstens 100 Zeichen lang sein. + Die Bezeichnung dieses Links kann nicht gespeichert werden. Entferne den Link und füge ihn erneut hinzu. Gib einen gültigen Weblink ein, z. B. example.com. Der Link darf höchstens 300 Zeichen lang sein. Nutze Bitkit mit deinen Kontakten, um Zahlungen direkt zu senden, jederzeit und überall. diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 044ef3ddae..e9e4116e40 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -1557,6 +1557,7 @@ Με το φορητό προφίλ σου, οι επαφές σου μπορούν να σε βρουν και να σε πληρώσουν οπουδήποτε. ΦΟΡΗΤΟ\n<accent>ΠΡΟΦΙΛ</accent> Η ετικέτα πρέπει να έχει έως 100 χαρακτήρες. + Η ετικέτα αυτού του συνδέσμου δεν μπορεί να αποθηκευτεί. Αφαίρεσε τον σύνδεσμο και πρόσθεσέ τον ξανά. Εισήγαγε έναν έγκυρο σύνδεσμο ιστού, όπως example.com. Ο σύνδεσμος πρέπει να έχει έως 300 χαρακτήρες. Χρησιμοποίησε το Bitkit με τις επαφές σου για να στέλνεις πληρωμές απευθείας, οποτεδήποτε, οπουδήποτε. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index a9a1574c94..6c5eced35e 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -1570,6 +1570,7 @@ Con tu perfil portátil, tus contactos pueden localizarte y pagarte en cualquier lugar. PERFIL\n<accent>PORTÁTIL</accent> La etiqueta debe tener 100 caracteres o menos. + No se puede guardar la etiqueta de este enlace. Elimina el enlace y vuelve a añadirlo. Introduce un enlace web válido, como example.com. El enlace debe tener 300 caracteres o menos. Usa Bitkit con tus contactos para enviar pagos directamente, en cualquier momento y lugar. diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 716c0bcf1d..31ad0078a7 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -1569,6 +1569,7 @@ Con su perfil portátil, sus contactos pueden localizarle y pagarle en cualquier lugar. PERFIL\n<accent>PORTÁTIL</accent> La etiqueta debe tener 100 caracteres o menos. + No se puede guardar la etiqueta de este enlace. Elimina el enlace y vuelve a añadirlo. Introduce un enlace web válido, como example.com. El enlace debe tener 300 caracteres o menos. Use Bitkit con sus contactos para enviar pagos directamente, en cualquier momento y lugar. diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 26a0eb17be..35be6af4f3 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -1570,6 +1570,7 @@ Grâce à votre profil portable, vos contacts peuvent vous joindre et vous payer partout. PROFIL\n<accent>PORTABLE</accent> Le libellé doit contenir 100 caractères au maximum. + Le libellé de ce lien ne peut pas être enregistré. Supprimez le lien et ajoutez-le à nouveau. Saisissez un lien web valide, par exemple example.com. Le lien doit contenir 300 caractères au maximum. Utilisez Bitkit avec vos contacts pour envoyer des paiements directement, à tout moment, partout. diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 4b36afac68..e2a05efc22 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -1575,6 +1575,7 @@ Con il tuo profilo portatile i tuoi contatti possono raggiungerti e pagarti ovunque. PROFILO\n<accent>PORTATILE</accent> L\'etichetta deve avere al massimo 100 caratteri. + L\'etichetta di questo link non può essere salvata. Rimuovi il link e aggiungilo di nuovo. Inserisci un link web valido, ad esempio example.com. Il link deve avere al massimo 300 caratteri. Usa Bitkit con i tuoi contatti per inviare pagamenti direttamente, in qualsiasi momento, ovunque. diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index 8802b3b1a6..6eaf7c9004 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -1572,6 +1572,7 @@ Met uw draagbare profiel kunnen uw contacten u overal bereiken en betalen. DRAAGBAAR\n<accent>PROFIEL</accent> Het label mag maximaal 100 tekens bevatten. + Het label van deze link kan niet worden opgeslagen. Verwijder de link en voeg hem opnieuw toe. Voer een geldige weblink in, zoals example.com. De link mag maximaal 300 tekens bevatten. Gebruik Bitkit met uw contacten om direct betalingen te versturen, altijd en overal. diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index a614e31368..086d6f833f 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -1573,6 +1573,7 @@ Dzięki przenośnemu profilowi Twoje kontakty mogą skontaktować się z Tobą i zapłacić Ci w dowolnym miejscu. PRZENOŚNY\n<accent>PROFIL</accent> Etykieta może mieć maksymalnie 100 znaków. + Nie można zapisać etykiety tego linku. Usuń link i dodaj go ponownie. Wpisz prawidłowy link internetowy, np. example.com. Link może mieć maksymalnie 300 znaków. Używaj Bitkit ze swoimi kontaktami, aby wysyłać płatności bezpośrednio, zawsze i wszędzie. diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index 550930bfbb..632f2e49dd 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -1575,6 +1575,7 @@ Com seu perfil portátil, seus contatos podem encontrar você e pagar você em qualquer lugar. PERFIL\n<accent>PORTÁTIL</accent> O rótulo deve ter no máximo 100 caracteres. + Não é possível salvar o rótulo deste link. Remova o link e adicione-o novamente. Insira um link da web válido, como example.com. O link deve ter no máximo 300 caracteres. Use a Bitkit com seus contatos para enviar pagamentos diretamente, a qualquer hora, em qualquer lugar. diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index fe14eedc15..8d2908715a 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -1550,6 +1550,7 @@ Com o seu perfil portátil, os seus contactos podem encontrá-lo e pagar-lhe em qualquer lugar. PERFIL\n<accent>PORTÁTIL</accent> A etiqueta deve ter no máximo 100 caracteres. + Não é possível guardar a etiqueta desta ligação. Remova a ligação e adicione-a novamente. Introduza uma ligação web válida, como example.com. A ligação deve ter no máximo 300 caracteres. Use a Bitkit com os seus contactos para enviar pagamentos diretamente, a qualquer hora, em qualquer lugar. diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 92a47f7832..08c905c697 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -1588,6 +1588,7 @@ С переносимым профилем ваши контакты смогут связаться с вами и заплатить вам где угодно. ПЕРЕНОСИМЫЙ\n<accent>ПРОФИЛЬ</accent> Метка должна содержать не более 100 символов. + Не удаётся сохранить метку этой ссылки. Удалите ссылку и добавьте её снова. Введите корректную веб-ссылку, например example.com. Ссылка должна содержать не более 300 символов. Используйте Bitkit, чтобы отправлять платежи контактам напрямую — когда угодно и где угодно. diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index 07756c15c9..bb3dbc3ea6 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -858,6 +858,7 @@ With your portable profile your contacts can reach you and pay you anywhere. PORTABLE\n<accent>PROFILE</accent> Label must be 100 characters or fewer. + This link\'s label can\'t be saved. Remove the link and add it again. Enter a valid web link, such as example.com. Link must be 300 characters or fewer. Profile diff --git a/app/src/test/java/to/bitkit/ext/PaykitExceptionExtTest.kt b/app/src/test/java/to/bitkit/ext/PaykitExceptionExtTest.kt index 869e83ce67..c18f771aea 100644 --- a/app/src/test/java/to/bitkit/ext/PaykitExceptionExtTest.kt +++ b/app/src/test/java/to/bitkit/ext/PaykitExceptionExtTest.kt @@ -3,6 +3,7 @@ package to.bitkit.ext import com.synonym.paykit.PaykitException import org.junit.Test import to.bitkit.utils.AppError +import kotlin.test.assertEquals import kotlin.test.assertFalse import kotlin.test.assertTrue @@ -14,6 +15,19 @@ class PaykitExceptionExtTest { assertTrue(error.isPaykitError()) } + @Test + fun `only the non-web profile link context of paykit 0_1_1-rc9 is a non-web link rejection`() { + // Paykit 0.1.1-rc9, paykit-sdk/src/domain/contacts/pubky_app.rs; update with the Paykit version. + val context = "Pubky profile link URL must be a canonical http or https URL" + assertEquals(context, PAYKIT_NON_WEB_PROFILE_LINK_CONTEXT) + assertTrue(AppError(PaykitException.Protocol("protocol_error", context)).isPaykitNonWebProfileLinkRejected()) + assertFalse( + PaykitException.Protocol("protocol_error", "Pubky profile link URL must be a valid URI") + .isPaykitNonWebProfileLinkRejected() + ) + assertFalse(PaykitException.Storage("protocol_error", context).isPaykitNonWebProfileLinkRejected()) + } + @Test fun `generic failures are not paykit errors`() { assertFalse(AppError("Native load failed").isPaykitError()) diff --git a/app/src/test/java/to/bitkit/ext/WebLinkTest.kt b/app/src/test/java/to/bitkit/ext/WebLinkTest.kt index 3304a56f43..447bab3315 100644 --- a/app/src/test/java/to/bitkit/ext/WebLinkTest.kt +++ b/app/src/test/java/to/bitkit/ext/WebLinkTest.kt @@ -14,6 +14,9 @@ class WebLinkTest { " www.example.com/path ", "medium.com/@alice", "example.com/a@b", + "bücher.de", + "my_site.example.com", + "https://example.com/?q=a|b", ).forEach { assertTrue(it.isWebLink(), it) } diff --git a/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt b/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt index 609fe3db10..42ceefeb3f 100644 --- a/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt +++ b/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt @@ -63,6 +63,45 @@ class PubkyAppLinkTest { assertNull(pubkyAppLinkError("Site", " ", webOnly = true)) } + @Test + fun `characters the url parser accepts in a path or query are accepted`() { + listOf( + "https://example.com/?q=a|b", + "https://example.com/100%", + "https://example.com/a[1]{2}^\"x\"", + "https://bücher.de", + "https://my_site.example.com", + ).forEach { + assertNull(pubkyAppLinkError("Site", it, webOnly = true), it) + assertEquals(it, it.toPubkyAppLinkUrl(), it) + } + assertEquals("https://example.com/?q=a|b", "example.com/?q=a|b".toPubkyAppLinkUrl()) + } + + @Test + fun `hosts and ports the url parser refuses are refused`() { + listOf( + "https://exa|mple.com", + "https://exa%mple.com", + "https://", + "https://example.com:65536", + "https://example.com:port", + "https://[zz::1]", + "https://example.com/\u0001", + ).forEach { + assertEquals(PubkyAppLinkError.URL_INVALID, pubkyAppLinkError("Site", it, webOnly = false), it) + } + assertNull(pubkyAppLinkError("Site", "https://example.com:65535", webOnly = false)) + assertNull(pubkyAppLinkError("Site", "https://[::1]:8080", webOnly = false)) + } + + @Test + fun `a label empty once on one line is refused after the url`() { + assertEquals(PubkyAppLinkError.LABEL_EMPTY, pubkyAppLinkError("\u0001\u0002", "example.com", webOnly = true)) + assertEquals(PubkyAppLinkError.LABEL_EMPTY, pubkyAppLinkError("", "example.com", webOnly = true)) + assertEquals(PubkyAppLinkError.URL_INVALID, pubkyAppLinkError("", "not a url", webOnly = true)) + } + @Test fun `links normalize to the url pubky app stores`() { assertEquals("https://example.com", "example.com".toPubkyAppLinkUrl()) 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 affeae50bd..3c5b2f9bc2 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 @@ -267,6 +267,32 @@ class EditProfileViewModelTest : BaseUnitTest() { verify(context).getString(R.string.profile__edit_link_error, "Email") } + @Test + fun `another link refusal from pubky app marks no row`() = test { + val sut = createSut(links = listOf(PubkyProfileLink("Email", "mailto:a@example.com"))) + advanceUntilIdle() + whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), anyOrNull(), any())).thenReturn( + Result.failure(PaykitException.Protocol("protocol_error", "Pubky profile link URL must be a valid URI")) + ) + + sut.addLink("Site", "https://example.com") + sut.save() + advanceUntilIdle() + + assertEquals(null, sut.uiState.value.rejectedLinkIndex) + assertTrue(sut.uiState.value.linkErrors.isEmpty()) + } + + @Test + fun `a stored url the url parser accepts does not block the save`() = test { + val sut = createSut(links = listOf(PubkyProfileLink("Search", "https://example.com/?q=a|b"))) + advanceUntilIdle() + + sut.addLink("Blog", "blog.example.com") + + assertTrue(sut.uiState.value.linkErrors.isEmpty()) + } + @Test fun `deleteProfile should emit success when repository delete succeeds`() = test { whenever(pubkyRepo.deleteProfileWithSessionRetry()).thenReturn(Result.success(Unit)) From b7acee00aeab2a05259b30df8b56f804626ceec7 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 14:15:36 -0300 Subject: [PATCH 3/7] fix: require http(s):// for web links and accept trailing-dot hosts Co-Authored-By: Claude Opus 5.5 --- app/src/main/java/to/bitkit/ext/String.kt | 15 +++++++++++---- .../main/java/to/bitkit/models/PubkyAppLink.kt | 11 ++++++----- .../java/to/bitkit/ui/components/AddLinkSheet.kt | 2 +- .../ui/screens/profile/EditProfileScreen.kt | 1 - app/src/test/java/to/bitkit/ext/WebLinkTest.kt | 6 ++++++ .../java/to/bitkit/models/PubkyAppLinkTest.kt | 4 ++++ 6 files changed, 28 insertions(+), 11 deletions(-) diff --git a/app/src/main/java/to/bitkit/ext/String.kt b/app/src/main/java/to/bitkit/ext/String.kt index aaabc2163a..0753d41927 100644 --- a/app/src/main/java/to/bitkit/ext/String.kt +++ b/app/src/main/java/to/bitkit/ext/String.kt @@ -53,19 +53,26 @@ fun String.formatPlural(argMap: Map): String = } private val WEB_LINK_SCHEMES = setOf("http", "https") -private val URI_SCHEME = Regex("^[A-Za-z][A-Za-z0-9+.-]*:") + +/** A URI scheme and its colon at the start of a value. */ +internal val URI_SCHEME = Regex("^[A-Za-z][A-Za-z0-9+.-]*:") /** * Whether this is an http(s) link, with or without its scheme: the only links a social v1 profile accepts. * A value with any other scheme, including a bare `host:port`, is refused, as the profile write keeps it unchanged. + * Paykit needs the literal `http://` or `https://`, so a scheme without `//`, or a `\` in the authority, is refused. */ fun String.isWebLink(): Boolean { val value = trim() if (value.isEmpty() || value.any { it.isWhitespace() }) return false val hasScheme = URI_SCHEME.containsMatchIn(value) if (!hasScheme && '@' in value.substringBefore('/')) return false - val parts = (if (hasScheme) value else "https://$value").linkUrlParts() ?: return false + val url = if (hasScheme) value else "https://$value" + val afterScheme = url.substringAfter(':') + if (!afterScheme.startsWith("//") || '\\' in afterScheme.drop(2).takeWhile { it !in "/?#" }) return false + val parts = url.linkUrlParts() ?: return false + val host = parts.host.removeSuffix(".") return parts.scheme in WEB_LINK_SCHEMES && - '.' in parts.host && - !parts.host.substringAfterLast('.').all { it.isDigit() } + '.' in host && + !host.substringAfterLast('.').all { it.isDigit() } } diff --git a/app/src/main/java/to/bitkit/models/PubkyAppLink.kt b/app/src/main/java/to/bitkit/models/PubkyAppLink.kt index 14f9bb9b1e..6eaededad4 100644 --- a/app/src/main/java/to/bitkit/models/PubkyAppLink.kt +++ b/app/src/main/java/to/bitkit/models/PubkyAppLink.kt @@ -1,5 +1,6 @@ package to.bitkit.models +import to.bitkit.ext.URI_SCHEME import to.bitkit.ext.isWebLink /** pubky.app link limits from pubky-app-specs, as Paykit checks them when it publishes a profile. */ @@ -13,7 +14,6 @@ private const val MAX_PORT = 65_535 private const val FORBIDDEN_HOST_CHARS = " #%/:<>?@[\\]^|" private val ISO_DATE = Regex("""\d{4}-\d{2}-\d{2}""") -private val URL_SCHEME = Regex("""^([A-Za-z][A-Za-z0-9+.-]*):""") private val SPECIAL_SCHEMES = setOf("http", "https", "ws", "wss", "ftp", "file") private val IPV4 = Regex("""\d{1,3}(\.\d{1,3}){3}""") @@ -71,7 +71,7 @@ class LinkUrlParts(val scheme: String, val host: String) */ fun String.linkUrlParts(): LinkUrlParts? { if (any { it.isISOControl() }) return null - val scheme = URL_SCHEME.find(this)?.groupValues?.get(1)?.lowercase() ?: return null + val scheme = URI_SCHEME.find(this)?.value?.dropLast(1)?.lowercase() ?: return null if (scheme !in SPECIAL_SCHEMES) return LinkUrlParts(scheme, host = "") val authority = substring(scheme.length + 1).trimStart('/', '\\').takeWhile { it !in "/?#\\" } val hostAndPort = authority.substringAfterLast('@') @@ -100,8 +100,9 @@ private fun String.isValidPort(): Boolean { } private fun String.isValidIpv4Ending(): Boolean { - if (startsWith('[') || !substringAfterLast('.').all { it.isDigit() }) return true - val numbers = split('.').map { it.toLongOrNull() ?: return false } + val name = removeSuffix(".") + if (startsWith('[') || !name.substringAfterLast('.').all { it.isDigit() }) return true + val numbers = name.split('.').map { it.toLongOrNull() ?: return false } if (numbers.size !in 1..4) return false val lastLimit = (1L shl (8 * (5 - numbers.size))) - 1 return numbers.dropLast(1).all { it <= 255 } && numbers.last() <= lastLimit @@ -111,7 +112,7 @@ private fun String.normalizedLinkUrl(): String? { val value = trim().takeIf { it.isNotEmpty() } ?: return null val isPhone = value.isPhoneNumber() if (!isPhone && value.any { it.isWhitespace() }) return null - val scheme = if (isPhone) null else URL_SCHEME.find(value)?.groupValues?.get(1) + val scheme = if (isPhone) null else URI_SCHEME.find(value)?.value?.dropLast(1) return when { scheme != null -> scheme.lowercase() + value.substring(scheme.length) value.isEmailAddress() -> "mailto:$value" diff --git a/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt b/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt index e01b3f55ee..c993c96fed 100644 --- a/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt +++ b/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt @@ -94,7 +94,7 @@ fun AddLinkSheet( LinkFormContent( label = label, url = url, - onLabelChange = { label = it }, + onLabelChange = { label = it.filterNot(Char::isISOControl) }, onUrlChange = { url = it }, onShowSuggestions = { showSuggestions = true }, onSave = { diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt index 686c569e53..be27899857 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/EditProfileScreen.kt @@ -165,7 +165,6 @@ private fun Content( onLinkUrlChange = onLinkUrlChange, linkErrors = uiState.linkErrors .mapValues { (_, error) -> - // A form row edits only the URL, so a label pubky.app refuses means adding the link again. if (error.isLabelError) { stringResource(R.string.profile__link_error_label_stored) } else { diff --git a/app/src/test/java/to/bitkit/ext/WebLinkTest.kt b/app/src/test/java/to/bitkit/ext/WebLinkTest.kt index 447bab3315..3e28f5bd2e 100644 --- a/app/src/test/java/to/bitkit/ext/WebLinkTest.kt +++ b/app/src/test/java/to/bitkit/ext/WebLinkTest.kt @@ -17,6 +17,11 @@ class WebLinkTest { "bücher.de", "my_site.example.com", "https://example.com/?q=a|b", + "https://example.com.", + "example.com.", + "https://user:pass@example.com", + "EXAMPLE.COM", + "HTTPS://Example.COM/Path", ).forEach { assertTrue(it.isWebLink(), it) } @@ -27,6 +32,7 @@ class WebLinkTest { listOf( "mailto:a@b.c", "a@b.c", "tel:+123456789", "+1 234 567 890", "123.456.7890", "ftp://example.com", "example", "two words.com", "example.com:8080", "", + "https:example.com", "https:/example.com", "https:\\\\example.com", "https://\\example.com", ).forEach { assertFalse(it.isWebLink(), it) } diff --git a/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt b/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt index 42ceefeb3f..72f54d926e 100644 --- a/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt +++ b/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt @@ -92,6 +92,10 @@ class PubkyAppLinkTest { assertEquals(PubkyAppLinkError.URL_INVALID, pubkyAppLinkError("Site", it, webOnly = false), it) } assertNull(pubkyAppLinkError("Site", "https://example.com:65535", webOnly = false)) + assertNull(pubkyAppLinkError("Site", "https://example.com.", webOnly = true)) + assertNull(pubkyAppLinkError("Site", "https://1.2.3.4.", webOnly = false)) + assertNull(pubkyAppLinkError("Site", "https:example.com", webOnly = false)) + assertEquals(PubkyAppLinkError.URL_INVALID, pubkyAppLinkError("Site", "https:example.com", webOnly = true)) assertNull(pubkyAppLinkError("Site", "https://[::1]:8080", webOnly = false)) } From 406a4aba2d34e43af56a5af68a049e2e95cefe23 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 14:35:10 -0300 Subject: [PATCH 4/7] fix: refuse web links with an empty authority Co-Authored-By: Claude Opus 5.5 --- app/src/main/java/to/bitkit/ext/String.kt | 6 +++++- app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt | 2 +- app/src/test/java/to/bitkit/ext/WebLinkTest.kt | 2 ++ 3 files changed, 8 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/to/bitkit/ext/String.kt b/app/src/main/java/to/bitkit/ext/String.kt index 0753d41927..530264c1cd 100644 --- a/app/src/main/java/to/bitkit/ext/String.kt +++ b/app/src/main/java/to/bitkit/ext/String.kt @@ -69,7 +69,11 @@ fun String.isWebLink(): Boolean { if (!hasScheme && '@' in value.substringBefore('/')) return false val url = if (hasScheme) value else "https://$value" val afterScheme = url.substringAfter(':') - if (!afterScheme.startsWith("//") || '\\' in afterScheme.drop(2).takeWhile { it !in "/?#" }) return false + if (!afterScheme.startsWith("//")) return false + val authority = afterScheme.drop(2).takeWhile { it !in "/?#" } + val hostAndPort = authority.substringAfterLast('@') + val rawHost = if (hostAndPort.startsWith('[')) hostAndPort else hostAndPort.substringBefore(':') + if ('\\' in authority || rawHost.isEmpty()) return false val parts = url.linkUrlParts() ?: return false val host = parts.host.removeSuffix(".") return parts.scheme in WEB_LINK_SCHEMES && diff --git a/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt b/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt index c993c96fed..74717c31c4 100644 --- a/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt +++ b/app/src/main/java/to/bitkit/ui/components/AddLinkSheet.kt @@ -94,7 +94,7 @@ fun AddLinkSheet( LinkFormContent( label = label, url = url, - onLabelChange = { label = it.filterNot(Char::isISOControl) }, + onLabelChange = { label = it.map { char -> if (char.isISOControl()) ' ' else char }.joinToString("") }, onUrlChange = { url = it }, onShowSuggestions = { showSuggestions = true }, onSave = { diff --git a/app/src/test/java/to/bitkit/ext/WebLinkTest.kt b/app/src/test/java/to/bitkit/ext/WebLinkTest.kt index 3e28f5bd2e..d6f7722c31 100644 --- a/app/src/test/java/to/bitkit/ext/WebLinkTest.kt +++ b/app/src/test/java/to/bitkit/ext/WebLinkTest.kt @@ -33,6 +33,8 @@ class WebLinkTest { "mailto:a@b.c", "a@b.c", "tel:+123456789", "+1 234 567 890", "123.456.7890", "ftp://example.com", "example", "two words.com", "example.com:8080", "", "https:example.com", "https:/example.com", "https:\\\\example.com", "https://\\example.com", + "https:///example.com", "https:////example.com", "/example.com", "https://.", "https://..", + "example.com/a\u00A0b", "example\u2007.com", "https://example.com/a\u202Fb", ).forEach { assertFalse(it.isWebLink(), it) } From 381aca948945a3f65c402b3fe88f63a089181286 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 14:54:36 -0300 Subject: [PATCH 5/7] fix: use paykit's social v1 link rule for migration and refusals Co-Authored-By: Claude Opus 5.5 --- .../java/to/bitkit/models/PubkyAppLink.kt | 20 ++++++++++++++++++ .../java/to/bitkit/repositories/PubkyRepo.kt | 6 ++---- .../screens/profile/EditProfileViewModel.kt | 5 +++-- .../java/to/bitkit/models/PubkyAppLinkTest.kt | 21 +++++++++++++++++++ .../profile/EditProfileViewModelTest.kt | 11 +++++++--- 5 files changed, 54 insertions(+), 9 deletions(-) diff --git a/app/src/main/java/to/bitkit/models/PubkyAppLink.kt b/app/src/main/java/to/bitkit/models/PubkyAppLink.kt index 6eaededad4..486b96572a 100644 --- a/app/src/main/java/to/bitkit/models/PubkyAppLink.kt +++ b/app/src/main/java/to/bitkit/models/PubkyAppLink.kt @@ -7,6 +7,12 @@ import to.bitkit.ext.isWebLink const val PUBKY_APP_LINK_TITLE_MAX_LENGTH = 100 const val PUBKY_APP_LINK_URL_MAX_LENGTH = 300 +/** First printable ASCII code; lower codes are control characters. */ +private const val ASCII_SPACE = 0x20 + +/** The ASCII delete control character. */ +private const val ASCII_DELETE = 0x7F + /** Highest port `url::Url::parse` accepts. */ private const val MAX_PORT = 65_535 @@ -59,6 +65,20 @@ fun String.toPubkyAppLinkUrl(): String? = normalizedLinkUrl()?.takeIf { it.codePointCount(0, it.length) <= PUBKY_APP_LINK_URL_MAX_LENGTH && it.linkUrlParts() != null } +/** + * Paykit's social v1 link rule (`is_social_v1_web_uri`): a lowercase `http://` or `https://` prefix, no control or + * whitespace character, and a non-empty host, read up to the first `/`, `?` or `#`, after the last `@`, and up to `:` + * unless it starts with `[`. Social v1 drops other links on migration too. + */ +fun String.isSocialV1WebUri(): Boolean { + val rest = removePrefix("http://").takeIf { it != this } ?: removePrefix("https://").takeIf { it != this } + ?: return false + if (any { it.code < ASCII_SPACE || it.code == ASCII_DELETE || it.isWhitespace() }) return false + val hostAndPort = rest.takeWhile { it !in "/?#" }.substringAfterLast('@') + val host = if (hostAndPort.startsWith('[')) hostAndPort else hostAndPort.substringBefore(':') + return host.isNotEmpty() +} + /** The lowercase scheme and the host of a URL; the host is empty for a scheme without one, such as `mailto`. */ class LinkUrlParts(val scheme: String, val host: String) diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index a35bb9bb08..179cc78d25 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -75,6 +75,7 @@ import to.bitkit.models.PubkyProfileLink import to.bitkit.models.PubkyPublicKeyFormat import to.bitkit.models.PubkySessionBackupKind import to.bitkit.models.PubkySessionBackupV1 +import to.bitkit.models.isSocialV1WebUri import to.bitkit.models.singleLine import to.bitkit.models.takeCodePoints import to.bitkit.models.toPubkyAppLinkUrl @@ -1461,7 +1462,7 @@ class PubkyRepo @Inject constructor( links = links .mapNotNull { link -> val title = link.label.singleLine().takeIf { it.isNotEmpty() } ?: return@mapNotNull null - val url = link.url.toPubkyAppLinkUrl()?.takeIf { it.isSocialV1WebUrl() } ?: return@mapNotNull null + val url = link.url.toPubkyAppLinkUrl()?.takeIf { it.isSocialV1WebUri() } ?: return@mapNotNull null PubkyProfileLink(label = title.takeCodePoints(PUBKY_APP_LINK_TITLE_MAX_LENGTH), url = url) } .take(PUBKY_APP_LINKS_MAX_COUNT), @@ -1571,9 +1572,6 @@ class PubkyRepo @Inject constructor( private fun Throwable.isConcurrentUpdate() = generateSequence(this) { it.cause }.any { it is PaykitException.ConcurrentUpdate } - /** Social v1's own link rule: a lowercase `http://` or `https://` prefix; it drops other links on migration too. */ - private fun String.isSocialV1WebUrl() = startsWith("http://") || startsWith("https://") - private fun String.isPaykitStorage() = "/pub/paykit/" in this private fun String.isPubkyAppFile() = 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 87ac1e922f..0b0100f8eb 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 @@ -28,14 +28,15 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import to.bitkit.R import to.bitkit.ext.isPaykitNonWebProfileLinkRejected -import to.bitkit.ext.isWebLink import to.bitkit.ext.runSuspendCatching import to.bitkit.models.PROFILE_NAME_MAX_LENGTH import to.bitkit.models.PubkyAppLinkError import to.bitkit.models.PubkyProfileLink import to.bitkit.models.Toast +import to.bitkit.models.isSocialV1WebUri import to.bitkit.models.pubkyAppLinkError import to.bitkit.models.takeCodePoints +import to.bitkit.models.toPubkyAppLinkUrl import to.bitkit.repositories.PrivatePaykitRepo import to.bitkit.repositories.ProfileEditBase import to.bitkit.repositories.PubkyProfileChangedError @@ -422,7 +423,7 @@ sealed interface EditProfileEffect { private fun Throwable.rejectedLinkIndex(links: List): Int? { if (!isPaykitNonWebProfileLinkRejected()) return null - return links.indexOfFirst { !it.url.isWebLink() }.takeIf { it >= 0 } + return links.indexOfFirst { !(it.url.toPubkyAppLinkUrl() ?: it.url).isSocialV1WebUri() }.takeIf { it >= 0 } } internal fun Throwable.profileSaveErrorText(context: Context): String? = when (this) { diff --git a/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt b/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt index 72f54d926e..557ef3f813 100644 --- a/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt +++ b/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt @@ -2,7 +2,9 @@ package to.bitkit.models import org.junit.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertNull +import kotlin.test.assertTrue class PubkyAppLinkTest { @Test @@ -58,6 +60,25 @@ class PubkyAppLinkTest { } } + @Test + fun `social v1 web uris follow paykit's rule`() { + listOf("https://example.com", "http://localhost", "https://[::1]", "https://user@host:8080/a").forEach { + assertTrue(it.isSocialV1WebUri(), it) + } + listOf( + "https:///example.com", + "https://", + "https://@", + "HTTPS://example.com", + "mailto:a@example.com", + "https://exa mple.com", + "https://example.com/\u0001", + "https://:80", + ).forEach { + assertFalse(it.isSocialV1WebUri(), it) + } + } + @Test fun `a blank url is left to the caller`() { assertNull(pubkyAppLinkError("Site", " ", webOnly = true)) 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 3c5b2f9bc2..f2eea7e819 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 @@ -246,7 +246,12 @@ class EditProfileViewModelTest : BaseUnitTest() { @Test fun `a link rejection from pubky app points to the stored non-web link`() = test { - val sut = createSut(links = listOf(PubkyProfileLink("Email", "mailto:a@example.com"))) + val sut = createSut( + links = listOf( + PubkyProfileLink("Local", "https://localhost"), + PubkyProfileLink("Email", "mailto:a@example.com"), + ) + ) advanceUntilIdle() whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), anyOrNull(), any())).thenReturn( Result.failure( @@ -262,8 +267,8 @@ class EditProfileViewModelTest : BaseUnitTest() { sut.save() advanceUntilIdle() - assertEquals(0, sut.uiState.value.rejectedLinkIndex) - assertEquals(mapOf(0 to PubkyAppLinkError.URL_INVALID), sut.uiState.value.linkErrors) + assertEquals(1, sut.uiState.value.rejectedLinkIndex) + assertEquals(mapOf(1 to PubkyAppLinkError.URL_INVALID), sut.uiState.value.linkErrors) verify(context).getString(R.string.profile__edit_link_error, "Email") } From b503a4229d9e6fb81d44ee921d461655943e54d1 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 16:57:09 -0300 Subject: [PATCH 6/7] fix: check stored links only when the normalized links change Co-Authored-By: Claude Opus 5.5 --- .../bitkit/ui/screens/profile/EditProfileViewModel.kt | 10 ++++++---- .../ui/screens/profile/EditProfileViewModelTest.kt | 10 ++++++++++ 2 files changed, 16 insertions(+), 4 deletions(-) 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 0b0100f8eb..0863b3f0ef 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 @@ -35,6 +35,7 @@ import to.bitkit.models.PubkyProfileLink import to.bitkit.models.Toast import to.bitkit.models.isSocialV1WebUri import to.bitkit.models.pubkyAppLinkError +import to.bitkit.models.singleLine import to.bitkit.models.takeCodePoints import to.bitkit.models.toPubkyAppLinkUrl import to.bitkit.repositories.PrivatePaykitRepo @@ -362,13 +363,14 @@ data class EditProfileUiState( val isBusy: Boolean get() = isSaving || isDeleting /** - * The links pubky.app would refuse, by index. A save sends the links only once they change, and then pubky.app - * checks every one, so a stored link is held to its rules too. Links added or edited here must also be web - * links, which social v1 requires; stored ones keep their scheme. + * The links pubky.app would refuse, by index. A save sends the links only once they differ from the stored ones + * after its normalization, and then pubky.app checks every one, so a stored link is held to its rules too. Links + * added or edited here must also be web links, which social v1 requires; stored ones keep their scheme. */ val linkErrors: ImmutableMap get() { - if (links == storedLinks) return persistentMapOf() + val sentLinks = links.map { ProfileEditLink(it.label.singleLine(), it.url.toPubkyAppLinkUrl() ?: it.url) } + if (sentLinks == storedLinks) return persistentMapOf() return links.withIndex().mapNotNull { (index, link) -> val error = when { index == rejectedLinkIndex -> PubkyAppLinkError.URL_INVALID 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 f2eea7e819..cd9e176413 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 @@ -234,6 +234,16 @@ class EditProfileViewModelTest : BaseUnitTest() { assertTrue(sut.uiState.value.linkErrors.isEmpty()) } + @Test + fun `a url edit that normalizes to the stored link leaves stored links unchecked`() = test { + val sut = createSut(links = listOf(PubkyProfileLink("x".repeat(101), "https://example.com"))) + advanceUntilIdle() + + sut.updateLinkUrl(0, "example.com") + + assertTrue(sut.uiState.value.linkErrors.isEmpty()) + } + @Test fun `an added link is held to the publisher limits`() = test { val sut = createSut() From c53b977dab03d2ee869decef7b7034f26715e22c Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 16:57:38 -0300 Subject: [PATCH 7/7] fix: keep a pubky.app link refusal on its link until it changes Co-Authored-By: Claude Opus 5.5 --- .../screens/profile/EditProfileViewModel.kt | 25 ++++++------- .../profile/EditProfileViewModelTest.kt | 35 +++++++++++++++++-- 2 files changed, 44 insertions(+), 16 deletions(-) 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 0863b3f0ef..226709f9ab 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 @@ -82,6 +82,7 @@ class EditProfileViewModel @Inject constructor( it.copy( isLoading = false, publicKey = publicKey, + rejectedLink = null, removal = removal, name = profile.name, bio = profile.bio, @@ -140,7 +141,6 @@ class EditProfileViewModel @Inject constructor( _uiState.update { it.copy( links = (it.links + ProfileEditLink(label = label, url = url)).toImmutableList(), - rejectedLinkIndex = null, showAddLinkSheet = false, ) } @@ -152,17 +152,13 @@ class EditProfileViewModel @Inject constructor( links = it.links.mapIndexed { i, link -> if (i == index) link.copy(url = url) else link }.toImmutableList(), - rejectedLinkIndex = null, ) } } fun removeLink(index: Int) { _uiState.update { - it.copy( - links = it.links.filterIndexed { i, _ -> i != index }.toImmutableList(), - rejectedLinkIndex = null, - ) + it.copy(links = it.links.filterIndexed { i, _ -> i != index }.toImmutableList()) } } @@ -244,14 +240,14 @@ class EditProfileViewModel @Inject constructor( _effects.emit(EditProfileEffect.SaveSuccess) }.onFailure { Logger.error("Failed to save profile", it, context = TAG) - val rejectedLink = it.rejectedLinkIndex(state.links) - _uiState.update { it.copy(isSaving = false, rejectedLinkIndex = rejectedLink) } + val rejectedLink = it.rejectedLink(state.links) + _uiState.update { it.copy(isSaving = false, rejectedLink = rejectedLink) } val changed = it is PubkyProfileChangedError ToastEventBus.send( type = Toast.ToastType.ERROR, title = context.getString(R.string.profile__edit_save_error), - description = rejectedLink?.let { index -> - context.getString(R.string.profile__edit_link_error, state.links[index].label) + description = rejectedLink?.let { link -> + context.getString(R.string.profile__edit_link_error, link.label) } ?: it.profileSaveErrorText(context), ) if (changed) reloadAfterExternalEdit() @@ -347,7 +343,8 @@ data class EditProfileUiState( val links: ImmutableList = persistentListOf(), val storedLinks: ImmutableList = persistentListOf(), val storedLinkUrls: ImmutableSet = persistentSetOf(), - val rejectedLinkIndex: Int? = null, + /** The link pubky.app last refused; it stays marked until that link is edited or removed. */ + val rejectedLink: ProfileEditLink? = null, val tags: ImmutableList = persistentListOf(), val imageUrl: String? = null, val newAvatarUri: Uri? = null, @@ -373,7 +370,7 @@ data class EditProfileUiState( if (sentLinks == storedLinks) return persistentMapOf() return links.withIndex().mapNotNull { (index, link) -> val error = when { - index == rejectedLinkIndex -> PubkyAppLinkError.URL_INVALID + link == rejectedLink -> PubkyAppLinkError.URL_INVALID link.url.isBlank() -> PubkyAppLinkError.URL_INVALID else -> pubkyAppLinkError(link.label, link.url, webOnly = link.url !in storedLinkUrls) } @@ -423,9 +420,9 @@ sealed interface EditProfileEffect { data object DisconnectSuccess : EditProfileEffect } -private fun Throwable.rejectedLinkIndex(links: List): Int? { +private fun Throwable.rejectedLink(links: List): ProfileEditLink? { if (!isPaykitNonWebProfileLinkRejected()) return null - return links.indexOfFirst { !(it.url.toPubkyAppLinkUrl() ?: it.url).isSocialV1WebUri() }.takeIf { it >= 0 } + return links.firstOrNull { !(it.url.toPubkyAppLinkUrl() ?: it.url).isSocialV1WebUri() } } internal fun Throwable.profileSaveErrorText(context: Context): String? = when (this) { 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 cd9e176413..c341830802 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 @@ -244,6 +244,37 @@ class EditProfileViewModelTest : BaseUnitTest() { assertTrue(sut.uiState.value.linkErrors.isEmpty()) } + @Test + fun `a pubky app refusal stays on its link until that link changes`() = test { + val sut = createSut( + links = listOf( + PubkyProfileLink("Site", "https://example.com"), + PubkyProfileLink("Email", "mailto:a@example.com"), + ) + ) + advanceUntilIdle() + whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), anyOrNull(), any())).thenReturn( + Result.failure( + PaykitException.Protocol( + "protocol_error", + "Pubky profile link URL must be a canonical http or https URL", + ) + ) + ) + sut.addLink("Blog", "https://blog.example.com") + sut.save() + advanceUntilIdle() + + sut.updateLinkUrl(2, "https://blog.example.org") + assertEquals(mapOf(1 to PubkyAppLinkError.URL_INVALID), sut.uiState.value.linkErrors) + + sut.removeLink(0) + assertEquals(mapOf(0 to PubkyAppLinkError.URL_INVALID), sut.uiState.value.linkErrors) + + sut.updateLinkUrl(0, "https://example.org") + assertTrue(sut.uiState.value.linkErrors.isEmpty()) + } + @Test fun `an added link is held to the publisher limits`() = test { val sut = createSut() @@ -277,7 +308,7 @@ class EditProfileViewModelTest : BaseUnitTest() { sut.save() advanceUntilIdle() - assertEquals(1, sut.uiState.value.rejectedLinkIndex) + assertEquals("mailto:a@example.com", sut.uiState.value.rejectedLink?.url) assertEquals(mapOf(1 to PubkyAppLinkError.URL_INVALID), sut.uiState.value.linkErrors) verify(context).getString(R.string.profile__edit_link_error, "Email") } @@ -294,7 +325,7 @@ class EditProfileViewModelTest : BaseUnitTest() { sut.save() advanceUntilIdle() - assertEquals(null, sut.uiState.value.rejectedLinkIndex) + assertEquals(null, sut.uiState.value.rejectedLink) assertTrue(sut.uiState.value.linkErrors.isEmpty()) }