diff --git a/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt b/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt index 0676c1c624..76f9da4a3a 100644 --- a/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt +++ b/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt @@ -11,6 +11,12 @@ 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" +/** + * 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( "SDK state blob contains trailing bytes", @@ -36,6 +42,11 @@ 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.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..530264c1cd 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" @@ -53,20 +53,30 @@ 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 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 && + val url = if (hasScheme) value else "https://$value" + val afterScheme = url.substringAfter(':') + 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 && '.' 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 new file mode 100644 index 0000000000..486b96572a --- /dev/null +++ b/app/src/main/java/to/bitkit/models/PubkyAppLink.kt @@ -0,0 +1,154 @@ +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. */ +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 + +/** 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 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_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 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.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 +} + +/** 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.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) + +/** + * 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 = 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('@') + 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 { + 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 +} + +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 URI_SCHEME.find(value)?.value?.dropLast(1) + 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.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..179cc78d25 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,16 @@ 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 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 +215,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 } @@ -1463,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), @@ -1573,55 +1572,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://") - private fun String.isPaykitStorage() = "/pub/paykit/" in this private fun String.isPubkyAppFile() = 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..74717c31c4 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 @@ -90,14 +94,16 @@ fun AddLinkSheet( LinkFormContent( label = label, url = url, - onLabelChange = { label = it }, + onLabelChange = { label = it.map { char -> if (char.isISOControl()) ' ' else char }.joinToString("") }, onUrlChange = { url = it }, onShowSuggestions = { showSuggestions = true }, onSave = { dismissKeyboard() onSave(label, url) }, - isSaveEnabled = label.isNotBlank() && url.isNotBlank() && (!webLinksOnly || url.isWebLink()), + labelError = linkErrorText.takeIf { linkError == PubkyAppLinkError.LABEL_TOO_LONG }, + urlError = linkErrorText.takeIf { linkError?.isLabelError == false }, + 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,23 @@ 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) +} + +@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 +265,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..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 @@ -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,15 @@ private fun Content( onBioChange = onBioChange, links = uiState.links, onLinkUrlChange = onLinkUrlChange, + linkErrors = uiState.linkErrors + .mapValues { (_, error) -> + if (error.isLabelError) { + stringResource(R.string.profile__link_error_label_stored) + } else { + pubkyAppLinkErrorText(error) + } + } + .toImmutableMap(), onRemoveLink = onRemoveLink, onAddLink = onAddLink, tags = uiState.tags, @@ -168,7 +179,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..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 @@ -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,12 +27,17 @@ import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import to.bitkit.R -import to.bitkit.ext.isWebLink +import to.bitkit.ext.isPaykitNonWebProfileLinkRejected 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.singleLine 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 @@ -74,12 +82,16 @@ class EditProfileViewModel @Inject constructor( it.copy( isLoading = false, publicKey = publicKey, + rejectedLink = null, removal = removal, name = profile.name, bio = profile.bio, 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, @@ -192,7 +204,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 +240,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.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 = it.profileSaveErrorText(context), + description = rejectedLink?.let { link -> + context.getString(R.string.profile__edit_link_error, link.label) + } ?: it.profileSaveErrorText(context), ) if (changed) reloadAfterExternalEdit() // The other fields are on pubky.app, so a retry starts from their revision. @@ -326,7 +341,10 @@ data class EditProfileUiState( val name: String = "", val bio: String = "", val links: ImmutableList = persistentListOf(), + val storedLinks: ImmutableList = persistentListOf(), val storedLinkUrls: ImmutableSet = persistentSetOf(), + /** 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, @@ -341,8 +359,24 @@ 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 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() { + 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 { + link == rejectedLink -> 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.rejectedLink(links: List): ProfileEditLink? { + if (!isPaykitNonWebProfileLinkRejected()) return null + return links.firstOrNull { !(it.url.toPubkyAppLinkUrl() ?: it.url).isSocialV1WebUri() } +} + 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..b6c04c9d69 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,10 @@ تعذر تحميل ملفك الشخصي. مع ملفك الشخصي المحمول، يمكن لجهات اتصالك الوصول إليك والدفع لك في أي مكان. ملف شخصي\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..faafb178ef 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,10 @@ 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. + 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. 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..b2387ee04c 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,10 @@ 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. + 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. 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..e51efbbf48 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,10 @@ 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ů. + 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. 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..3335dfd8fc 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,10 @@ 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. + 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. 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..e9e4116e40 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,10 @@ Δεν ήταν δυνατή η φόρτωση του προφίλ σου. Με το φορητό προφίλ σου, οι επαφές σου μπορούν να σε βρουν και να σε πληρώσουν οπουδήποτε. ΦΟΡΗΤΟ\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..6c5eced35e 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,10 @@ 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. + 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. 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..31ad0078a7 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,10 @@ 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. + 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. 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..35be6af4f3 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,10 @@ 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. + 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. 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..e2a05efc22 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,10 @@ 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. + 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. 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..6eaf7c9004 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,10 @@ 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. + 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. 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..086d6f833f 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,10 @@ 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. + 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. 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..632f2e49dd 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,10 @@ 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. + 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. 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..8d2908715a 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,10 @@ 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. + 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. 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..08c905c697 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,10 @@ Не удалось загрузить ваш профиль. С переносимым профилем ваши контакты смогут связаться с вами и заплатить вам где угодно. ПЕРЕНОСИМЫЙ\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..bb3dbc3ea6 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,10 @@ 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. + 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 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/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..d6f7722c31 100644 --- a/app/src/test/java/to/bitkit/ext/WebLinkTest.kt +++ b/app/src/test/java/to/bitkit/ext/WebLinkTest.kt @@ -14,6 +14,14 @@ 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", + "https://example.com.", + "example.com.", + "https://user:pass@example.com", + "EXAMPLE.COM", + "HTTPS://Example.COM/Path", ).forEach { assertTrue(it.isWebLink(), it) } @@ -24,6 +32,9 @@ 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", + "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) } 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..557ef3f813 --- /dev/null +++ b/app/src/test/java/to/bitkit/models/PubkyAppLinkTest.kt @@ -0,0 +1,138 @@ +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 + 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 `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)) + } + + @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://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)) + } + + @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()) + 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..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 @@ -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,143 @@ 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 `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 `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() + 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("Local", "https://localhost"), + 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("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") + } + + @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.rejectedLink) + 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)) @@ -410,6 +549,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 +558,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 +574,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" + +