diff --git a/Bitkit/Components/ProfileEditFormView.swift b/Bitkit/Components/ProfileEditFormView.swift index 4e579ddfa..ee655f773 100644 --- a/Bitkit/Components/ProfileEditFormView.swift +++ b/Bitkit/Components/ProfileEditFormView.swift @@ -20,8 +20,8 @@ struct ProfileEditFormView: View { var maxLinks: Int? /// Whether links must be http(s), as social v1 profiles require; contact links accept any text. var webLinksOnly = false - /// Links loaded with the profile; with `webLinksOnly`, only links added or edited here must be web links. - var storedLinkUrls: Set = [] + /// Links pubky.app would refuse, by index, shown under each link; any of them blocks the save. + var linkErrors: [Int: PubkyAppLinkError] = [:] /// Whether the name can be saved; contact edits accept any non-empty name. var isNameValid: (String) -> Bool = { !$0.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } let footerNote: String? @@ -39,10 +39,6 @@ struct ProfileEditFormView: View { @FocusState private var isBioFocused: Bool @State private var showAddTagSheet = false - private var hasOnlyWebLinks: Bool { - !webLinksOnly || links.allSatisfy { storedLinkUrls.contains($0.url) || $0.url.isWebLink } - } - var body: some View { ZStack(alignment: .bottom) { InsetHeaderScrollView( @@ -225,6 +221,12 @@ struct ProfileEditFormView: View { .padding(16) .background(Color.white10) .cornerRadius(8) + + if let linkError = linkErrors[index] { + BodySText(linkError.rowMessage, textColor: .redAccent) + .fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier("ProfileEditLinkError_\(index)") + } } } @@ -307,7 +309,7 @@ struct ProfileEditFormView: View { await onSave() } .accessibilityIdentifier("ProfileEditSave") - .disabled(!isNameValid(name) || !hasOnlyWebLinks) + .disabled(!isNameValid(name) || !linkErrors.isEmpty) } .padding(.horizontal, 16) .padding(.top, 16) diff --git a/Bitkit/Managers/PubkyAppProfileStore.swift b/Bitkit/Managers/PubkyAppProfileStore.swift index f14598d9b..fa0a14eaa 100644 --- a/Bitkit/Managers/PubkyAppProfileStore.swift +++ b/Bitkit/Managers/PubkyAppProfileStore.swift @@ -127,8 +127,8 @@ actor PubkyAppProfileStore { private static let nameMaxLength = 50 private static let bioMaxLength = 160 private static let linksMaxCount = 5 - private static let linkTitleMaxLength = 100 - private static let linkUrlMaxLength = 300 + private static let linkTitleMaxLength = PubkyAppProfileLimits.linkTitleMaxLength + private static let linkUrlMaxLength = PubkyAppProfileLimits.linkUrlMaxLength private static let avatarMaxBytes: UInt64 = 5 * 1024 * 1024 private static let pubkyAppProfileOwnersKey = "pubky_app_profile_owners" @@ -547,9 +547,24 @@ actor PubkyAppProfileStore { return data } - /// Social v1's own link rule: a lowercase `http://` or `https://` prefix; it drops other links on migration too. - private static func isSocialV1WebUrl(_ url: String) -> Bool { - url.hasPrefix("http://") || url.hasPrefix("https://") + /// 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. + static func isSocialV1WebUrl(_ url: String) -> Bool { + let rest: Substring + if url.hasPrefix("http://") { + rest = url.dropFirst("http://".count) + } else if url.hasPrefix("https://") { + rest = url.dropFirst("https://".count) + } else { + return false + } + guard !url.unicodeScalars.contains(where: { ($0.isASCII && $0.properties.generalCategory == .control) || $0.properties.isWhitespace }) + else { return false } + let authority = rest.prefix { !"/?#".contains($0) } + let hostAndPort = authority.split(separator: "@", omittingEmptySubsequences: false).last ?? "" + let host = hostAndPort.hasPrefix("[") ? hostAndPort : hostAndPort.prefix { $0 != ":" } + return !host.isEmpty } static func singleLine(_ text: String) -> String { @@ -562,13 +577,144 @@ actor PubkyAppProfileStore { String(String.UnicodeScalarView(text.unicodeScalars.prefix(maxScalars))) } + /// The first rule pubky.app's publisher would refuse `label` and `url` for, after the normalization a profile save + /// applies, or nil 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. + static func linkError(label: String, url: String, webOnly: Bool) -> PubkyAppLinkError? { + if singleLine(label).unicodeScalars.count > linkTitleMaxLength { + return .labelTooLong + } + if !url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + guard let normalized = normalizedLinkUrl(url), linkUrlHost(normalized) != nil else { return .urlInvalid } + if webOnly, !url.isWebLink { + return .urlInvalid + } + if normalized.unicodeScalars.count > linkUrlMaxLength { + return .urlTooLong + } + } + if singleLine(label).isEmpty { + return .labelEmpty + } + return nil + } + + /// 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. `rejectedLink` is a + /// link pubky.app already refused; it stays marked until it is edited or removed. + static func linkErrors( + links: [PubkyProfileData.Link], + storedLinks: [PubkyProfileData.Link], + rejectedLink: PubkyProfileData.Link? = nil + ) -> [Int: PubkyAppLinkError] { + let sentLinks = links.map { PubkyProfileData.Link(label: singleLine($0.label), url: linkUrl($0.url) ?? $0.url) } + guard sentLinks != storedLinks else { return [:] } + let storedUrls = Set(storedLinks.map(\.url)) + var errors: [Int: PubkyAppLinkError] = [:] + for (index, link) in links.enumerated() { + if link == rejectedLink || link.url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + errors[index] = .urlInvalid + } else if let error = linkError(label: link.label, url: link.url, webOnly: !storedUrls.contains(link.url)) { + errors[index] = error + } + } + return errors + } + + /// 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. + static let paykitNonWebLinkContext = "Pubky profile link URL must be a canonical http or https URL" + + /// The link pubky.app refused a social v1 profile for because it is not a web link: the first such link, as the others + /// passed. Any other refusal names no link. + static func rejectedLink(for error: Error, links: [PubkyProfileData.Link]) -> PubkyProfileData.Link? { + guard case let .Protocol(_, context)? = error as? PaykitError, context == paykitNonWebLinkContext else { return nil } + return links.first { link in + let url = linkUrl(link.url) ?? link.url + return !isSocialV1WebUrl(url) + } + } + /// Bitkit accepted links without a scheme (a site, an email address, a phone number); pubky.app needs full URLs. /// Free text that is none of these is not a link pubky.app can hold. static func linkUrl(_ value: String) -> String? { + guard let url = normalizedLinkUrl(value), url.unicodeScalars.count <= linkUrlMaxLength, linkUrlHost(url) != nil + else { return nil } + return url + } + + private static let specialSchemes: Set = ["http", "https", "ws", "wss", "ftp", "file"] + /// Characters `url::Url::parse` refuses in the host of a special URL, as WHATWG's forbidden domain code points. + private static let forbiddenHostCharacters = Set(" #%/:<>?@[\\]^|") + private static let maxPort = 65535 + + private static func urlScheme(_ value: String) -> String? { + guard let range = value.range(of: "^[A-Za-z][A-Za-z0-9+.-]*:", options: .regularExpression) else { return nil } + return String(value[range].dropLast()) + } + + /// The host `url::Url::parse`, which Paykit validates links with, reads from `url`, or nil when it would refuse it; + /// empty for a scheme without a host, such as `mailto`. 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. + static func linkUrlHost(_ url: String) -> String? { + guard !url.unicodeScalars.contains(where: { $0.properties.generalCategory == .control }), + let scheme = urlScheme(url)?.lowercased() + else { return nil } + guard specialSchemes.contains(scheme) else { return "" } + let afterScheme = url.dropFirst(scheme.count + 1).drop { $0 == "/" || $0 == "\\" } + let authority = afterScheme.prefix { !"/?#\\".contains($0) } + let hostAndPort = authority.split(separator: "@", omittingEmptySubsequences: false).last.map(String.init) ?? "" + guard let host = hostPart(hostAndPort), isValidPort(String(hostAndPort.dropFirst(host.count))) else { return nil } + if scheme == "file" { + return host + } + guard !host.isEmpty, host.hasPrefix("[") || !host.contains(where: forbiddenHostCharacters.contains), + isValidIpv4Ending(host) + else { return nil } + return host.lowercased() + } + + private static func hostPart(_ hostAndPort: String) -> String? { + guard hostAndPort.hasPrefix("[") else { return String(hostAndPort.prefix { $0 != ":" }) } + guard let end = hostAndPort.firstIndex(of: "]"), hostAndPort.distance(from: hostAndPort.startIndex, to: end) > 1 + else { return nil } + let address = hostAndPort[hostAndPort.index(after: hostAndPort.startIndex) ..< end] + guard address.allSatisfy({ $0.isHexDigit || $0 == ":" || $0 == "." }) else { return nil } + return String(hostAndPort[...end]) + } + + private static func isValidPort(_ rest: String) -> Bool { + if rest.isEmpty { + return true + } + guard rest.hasPrefix(":") else { return false } + let port = rest.dropFirst() + guard port.allSatisfy({ ("0" ... "9").contains($0) }) else { return false } + let digits = port.drop { $0 == "0" } + return digits.count <= String(maxPort).count && (Int(digits) ?? 0) <= maxPort + } + + private static func isValidIpv4Ending(_ host: String) -> Bool { + let name = host.hasSuffix(".") ? String(host.dropLast()) : host + guard !name.hasPrefix("["), let last = name.split(separator: ".", omittingEmptySubsequences: false).last, + last.allSatisfy(\.isNumber) + else { return true } + let parts = name.split(separator: ".", omittingEmptySubsequences: false).map { UInt64($0) } + guard (1 ... 4).contains(parts.count), parts.allSatisfy({ $0 != nil }) else { return false } + let numbers = parts.compactMap { $0 } + let lastLimit = (UInt64(1) << (8 * UInt64(5 - numbers.count))) - 1 + return numbers.dropLast().allSatisfy { $0 <= 255 } && numbers[numbers.count - 1] <= lastLimit + } + + private static func normalizedLinkUrl(_ value: String) -> String? { let value = value.trimmingCharacters(in: .whitespacesAndNewlines) guard !value.isEmpty, !value.contains(where: \.isWhitespace) || isPhoneNumber(value) else { return nil } let url: String - if let scheme = URL(string: value)?.scheme, !isPhoneNumber(value) { + if let scheme = urlScheme(value), !isPhoneNumber(value) { url = scheme.lowercased() + value.dropFirst(scheme.count) } else if isEmailAddress(value) { url = "mailto:\(value)" @@ -579,23 +725,9 @@ actor PubkyAppProfileStore { } else { return nil } - guard url.unicodeScalars.count <= linkUrlMaxLength, let parsed = URL(string: url), hasValidHost(parsed) else { return nil } return url } - /// 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 static func hasValidHost(_ url: URL) -> Bool { - guard ["http", "https", "ws", "wss", "ftp"].contains(url.scheme?.lowercased() ?? ""), - let host = url.host, let last = host.split(separator: ".").last, last.allSatisfy(\.isNumber) - else { return true } - let parts = host.split(separator: ".", omittingEmptySubsequences: false).map { UInt64($0) } - guard (1 ... 4).contains(parts.count), parts.allSatisfy({ $0 != nil }) else { return false } - let numbers = parts.compactMap { $0 } - let lastLimit = (UInt64(1) << (8 * UInt64(5 - numbers.count))) - 1 - return numbers.dropLast().allSatisfy { $0 <= 255 } && numbers[numbers.count - 1] <= lastLimit - } - private static func isEmailAddress(_ value: String) -> Bool { let parts = value.split(separator: "@", omittingEmptySubsequences: false) return parts.count == 2 && !parts[0].isEmpty && parts[1].contains(".") && !value.contains("/") diff --git a/Bitkit/Models/PubkyProfile.swift b/Bitkit/Models/PubkyProfile.swift index 7ac301090..41262c95d 100644 --- a/Bitkit/Models/PubkyProfile.swift +++ b/Bitkit/Models/PubkyProfile.swift @@ -245,6 +245,8 @@ enum PubkyAppProfileLimits { static let nameLength = 3 ... 50 static let bioMaxLength = 160 static let maxLinks = 5 + static let linkTitleMaxLength = 100 + static let linkUrlMaxLength = 300 /// pubky.app counts Unicode scalars, not characters. static func isValidName(_ name: String) -> Bool { @@ -257,3 +259,34 @@ enum PubkyAppProfileLimits { return String(String.UnicodeScalarView(text.unicodeScalars.prefix(maxLength))) } } + +/// Why pubky.app would refuse a profile link, checked on the label and URL a profile save sends. +enum PubkyAppLinkError: Equatable { + case labelEmpty + case labelTooLong + case urlTooLong + case urlInvalid + + var message: String { + switch self { + case .labelEmpty: + t("profile__link_error_label_stored") + case .labelTooLong: + t("profile__link_error_label_length") + case .urlTooLong: + t("profile__link_error_url_length") + case .urlInvalid: + t("profile__link_error_url_invalid") + } + } + + var isLabelError: Bool { + self == .labelEmpty || self == .labelTooLong + } + + /// The message under a profile form row, which edits only the URL: a label pubky.app refuses means adding the link + /// again. + var rowMessage: String { + isLabelError ? t("profile__link_error_label_stored") : message + } +} diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index 52e1b4ed8..56093dca4 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -1181,6 +1181,11 @@ "profile__edit_changed_error" = "تغيّر ملفك الشخصي في pubky.app. حمّل Bitkit أحدث نسخة، لذا أعد إجراء تعديلك."; "profile__edit_public_note" = "هذا هو ملفك الشخصي على pubky.app. إنه عام، والتغييرات التي تجريها هنا تظهر أيضًا على pubky.app."; "profile__edit_tags_error" = "تعذّر على Bitkit حفظ وسومك. حُفظت تغييراتك الأخرى، لذا حاول حفظ الوسوم مرة أخرى."; +"profile__edit_link_error" = "أصلح رابط {label} لحفظ ملفك الشخصي."; +"profile__link_error_label_length" = "يجب ألا يزيد التصنيف عن 100 حرفًا."; +"profile__link_error_label_stored" = "لا يمكن حفظ تصنيف هذا الرابط. احذف الرابط وأضفه مرة أخرى."; +"profile__link_error_url_invalid" = "أدخل رابط ويب صالحًا، مثل example.com."; +"profile__link_error_url_length" = "يجب ألا يزيد الرابط عن 300 حرفًا."; "profile__delete_title" = "حذف الملف الشخصي؟"; "profile__delete_description" = "يؤدي حذف ملفك الشخصي إلى إزالته من Pubky. قد تحتفظ جهات الاتصال بمعلومات الملف الشخصي والدفع التي شاركتها معهم سابقًا."; "profile__delete_confirm" = "نعم، احذف"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index 311a30660..75e2e4a62 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -1298,6 +1298,11 @@ "profile__edit_changed_error" = "El teu perfil ha canviat a pubky.app. Bitkit ha carregat la versió més recent, així que torna a fer la teva edició."; "profile__edit_public_note" = "Aquest és el teu perfil de pubky.app. És públic, i els canvis que hi facis aquí també es veuen a pubky.app."; "profile__edit_tags_error" = "Bitkit no ha pogut desar les teves etiquetes. Els altres canvis s'han desat, així que torna a provar amb les etiquetes."; +"profile__edit_link_error" = "Corregeix l'enllaç {label} per desar el teu perfil."; +"profile__link_error_label_length" = "L'etiqueta ha de tenir 100 caràcters o menys."; +"profile__link_error_label_stored" = "No es pot desar l'etiqueta d'aquest enllaç. Elimina l'enllaç i torna'l a afegir."; +"profile__link_error_url_invalid" = "Introdueix un enllaç web vàlid, com ara example.com."; +"profile__link_error_url_length" = "L'enllaç ha de tenir 300 caràcters o menys."; "profile__delete_title" = "Eliminar el perfil?"; "profile__delete_description" = "Eliminar el teu perfil l'esborra de Pubky. És possible que els contactes conservin la informació de perfil i de pagament que s'hi hagi compartit abans."; "profile__delete_confirm" = "Sí, elimina"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index 0f4390e98..b5950f509 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -1402,6 +1402,11 @@ "profile__edit_changed_error" = "Tvůj profil se v pubky.app změnil. Bitkit načetl nejnovější verzi, proveď proto úpravu znovu."; "profile__edit_public_note" = "Toto je tvůj profil na pubky.app. Je veřejný a změny, které zde provedeš, se zobrazí i na pubky.app."; "profile__edit_tags_error" = "Bitkit nemohl uložit vaše štítky. Ostatní změny byly uloženy, tak zkuste štítky znovu."; +"profile__edit_link_error" = "Opravte odkaz {label}, abyste mohli uložit profil."; +"profile__link_error_label_length" = "Popisek může mít nejvýše 100 znaků."; +"profile__link_error_label_stored" = "Popisek tohoto odkazu nelze uložit. Odkaz odstraňte a přidejte znovu."; +"profile__link_error_url_invalid" = "Zadejte platný webový odkaz, například example.com."; +"profile__link_error_url_length" = "Odkaz může mít nejvýše 300 znaků."; "profile__delete_title" = "Smazat profil?"; "profile__delete_description" = "Smazáním profilu ho odstraníte z Pubky. Kontakty si mohou ponechat informace o profilu a platbách, které jste s nimi dříve sdíleli."; "profile__delete_confirm" = "Ano, smazat"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 1c00c95d3..a389cedc0 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -1400,6 +1400,11 @@ "profile__edit_changed_error" = "Dein Profil wurde in pubky.app geändert. Bitkit hat die neueste Version geladen, nimm deine Änderung bitte erneut vor."; "profile__edit_public_note" = "Das ist dein pubky.app-Profil. Es ist öffentlich, und Änderungen, die du hier vornimmst, erscheinen auch auf pubky.app."; "profile__edit_tags_error" = "Bitkit konnte deine Tags nicht speichern. Deine anderen Änderungen wurden gespeichert, versuche es mit den Tags erneut."; +"profile__edit_link_error" = "Korrigiere den Link {label}, um dein Profil zu speichern."; +"profile__link_error_label_length" = "Die Bezeichnung darf höchstens 100 Zeichen lang sein."; +"profile__link_error_label_stored" = "Die Bezeichnung dieses Links kann nicht gespeichert werden. Entferne den Link und füge ihn erneut hinzu."; +"profile__link_error_url_invalid" = "Gib einen gültigen Weblink ein, z. B. example.com."; +"profile__link_error_url_length" = "Der Link darf höchstens 300 Zeichen lang sein."; "profile__delete_title" = "Profil löschen?"; "profile__delete_description" = "Durch das Löschen deines Profils wird es von Pubky entfernt. Kontakte können zuvor mit ihnen geteilte Profil- und Zahlungsinformationen weiterhin behalten."; "profile__delete_confirm" = "Ja, löschen"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 3b2e0e0d0..78047c215 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -1199,6 +1199,11 @@ "profile__edit_changed_error" = "Το προφίλ σου άλλαξε στο pubky.app. Το Bitkit φόρτωσε την πιο πρόσφατη έκδοση, οπότε κάνε ξανά την αλλαγή σου."; "profile__edit_public_note" = "Αυτό είναι το προφίλ σου στο pubky.app. Είναι δημόσιο, και οι αλλαγές που κάνεις εδώ εμφανίζονται και στο pubky.app."; "profile__edit_tags_error" = "Το Bitkit δεν μπόρεσε να αποθηκεύσει τις ετικέτες σου. Οι άλλες αλλαγές σου αποθηκεύτηκαν, οπότε δοκίμασε ξανά τις ετικέτες."; +"profile__edit_link_error" = "Διόρθωσε τον σύνδεσμο {label} για να αποθηκεύσεις το προφίλ σου."; +"profile__link_error_label_length" = "Η ετικέτα πρέπει να έχει έως 100 χαρακτήρες."; +"profile__link_error_label_stored" = "Η ετικέτα αυτού του συνδέσμου δεν μπορεί να αποθηκευτεί. Αφαίρεσε τον σύνδεσμο και πρόσθεσέ τον ξανά."; +"profile__link_error_url_invalid" = "Εισήγαγε έναν έγκυρο σύνδεσμο ιστού, όπως example.com."; +"profile__link_error_url_length" = "Ο σύνδεσμος πρέπει να έχει έως 300 χαρακτήρες."; "profile__delete_title" = "Διαγραφή Προφίλ;"; "profile__delete_description" = "Η διαγραφή του προφίλ σας το αφαιρεί από το Pubky. Οι επαφές μπορεί να διατηρούν ακόμα πληροφορίες προφίλ και πληρωμών που τους κοινοποιήθηκαν παλαιότερα."; "profile__delete_confirm" = "Ναι, Διαγραφή"; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index 455904ca4..004e972e8 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1415,6 +1415,11 @@ "profile__edit_changed_error" = "Your profile changed in pubky.app. Bitkit loaded the latest version, so make your edit again."; "profile__edit_public_note" = "This is your pubky.app profile. It is public, and changes you make here also show on pubky.app."; "profile__edit_tags_error" = "Bitkit could not save your tags. Your other changes were saved, so try the tags again."; +"profile__edit_link_error" = "Fix the {label} link to save your profile."; +"profile__link_error_label_length" = "Label must be 100 characters or fewer."; +"profile__link_error_label_stored" = "This link's label can't be saved. Remove the link and add it again."; +"profile__link_error_url_invalid" = "Enter a valid web link, such as example.com."; +"profile__link_error_url_length" = "Link must be 300 characters or fewer."; "profile__delete_title" = "Delete Profile?"; "profile__delete_description" = "Deleting your profile removes it from Pubky. Contacts may still retain profile and payment information previously shared with them."; "profile__delete_confirm" = "Yes, Delete"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index ea5caaaf9..c05d7c816 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -1405,6 +1405,11 @@ "profile__edit_changed_error" = "Tu perfil cambió en pubky.app. Bitkit cargó la versión más reciente, así que vuelve a hacer tu cambio."; "profile__edit_public_note" = "Este es tu perfil de pubky.app. Es público, y los cambios que hagas aquí también se ven en pubky.app."; "profile__edit_tags_error" = "Bitkit no pudo guardar tus etiquetas. Tus otros cambios se guardaron, así que vuelve a intentar con las etiquetas."; +"profile__edit_link_error" = "Corrige el enlace {label} para guardar tu perfil."; +"profile__link_error_label_length" = "La etiqueta debe tener 100 caracteres o menos."; +"profile__link_error_label_stored" = "No se puede guardar la etiqueta de este enlace. Elimina el enlace y vuelve a agregarlo."; +"profile__link_error_url_invalid" = "Ingresa un enlace web válido, como example.com."; +"profile__link_error_url_length" = "El enlace debe tener 300 caracteres o menos."; "profile__delete_title" = "¿Eliminar perfil?"; "profile__delete_description" = "Al eliminar su perfil, se borra de Pubky. Es posible que sus contactos conserven la información de perfil y de pago que compartió con ellos anteriormente."; "profile__delete_confirm" = "Sí, eliminar"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index 23daa0952..d15bfbaf6 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -1316,6 +1316,11 @@ "profile__edit_changed_error" = "Tu perfil cambió en pubky.app. Bitkit cargó la versión más reciente, así que vuelve a hacer tu cambio."; "profile__edit_public_note" = "Este es tu perfil de pubky.app. Es público, y los cambios que hagas aquí también se ven en pubky.app."; "profile__edit_tags_error" = "Bitkit no pudo guardar tus etiquetas. Tus otros cambios se guardaron, así que vuelve a intentar con las etiquetas."; +"profile__edit_link_error" = "Corrige el enlace {label} para guardar tu perfil."; +"profile__link_error_label_length" = "La etiqueta debe tener 100 caracteres o menos."; +"profile__link_error_label_stored" = "No se puede guardar la etiqueta de este enlace. Elimina el enlace y vuelve a añadirlo."; +"profile__link_error_url_invalid" = "Introduce un enlace web válido, como example.com."; +"profile__link_error_url_length" = "El enlace debe tener 300 caracteres o menos."; "profile__delete_title" = "¿Eliminar el perfil?"; "profile__delete_description" = "Al eliminar su perfil, se elimina de Pubky. Es posible que sus contactos conserven la información de perfil y de pago que compartió con ellos anteriormente."; "profile__delete_confirm" = "Sí, eliminar"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index 2d666b449..7ed144ff5 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -1413,6 +1413,11 @@ "profile__edit_changed_error" = "Ton profil a changé sur pubky.app. Bitkit a chargé la version la plus récente, refais donc ta modification."; "profile__edit_public_note" = "Voici ton profil pubky.app. Il est public, et les modifications que tu fais ici apparaissent aussi sur pubky.app."; "profile__edit_tags_error" = "Bitkit n'a pas pu enregistrer vos étiquettes. Vos autres modifications ont été enregistrées, réessayez pour les étiquettes."; +"profile__edit_link_error" = "Corrigez le lien {label} pour enregistrer votre profil."; +"profile__link_error_label_length" = "Le libellé doit contenir 100 caractères au maximum."; +"profile__link_error_label_stored" = "Le libellé de ce lien ne peut pas être enregistré. Supprimez le lien et ajoutez-le à nouveau."; +"profile__link_error_url_invalid" = "Saisissez un lien web valide, par exemple example.com."; +"profile__link_error_url_length" = "Le lien doit contenir 300 caractères au maximum."; "profile__delete_title" = "Supprimer le profil ?"; "profile__delete_description" = "La suppression de votre profil le retire de Pubky. Vos contacts peuvent encore conserver les informations de profil et de paiement que vous leur avez partagées."; "profile__delete_confirm" = "Oui, supprimer"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index 79d8bc9c7..4dfa6de41 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -1380,6 +1380,11 @@ "profile__edit_changed_error" = "Il tuo profilo è cambiato su pubky.app. Bitkit ha caricato la versione più recente, quindi ripeti la modifica."; "profile__edit_public_note" = "Questo è il tuo profilo pubky.app. È pubblico e le modifiche che fai qui compaiono anche su pubky.app."; "profile__edit_tags_error" = "Bitkit non è riuscito a salvare i tuoi tag. Le altre modifiche sono state salvate, quindi riprova con i tag."; +"profile__edit_link_error" = "Correggi il link {label} per salvare il tuo profilo."; +"profile__link_error_label_length" = "L'etichetta deve avere al massimo 100 caratteri."; +"profile__link_error_label_stored" = "L'etichetta di questo link non può essere salvata. Rimuovi il link e aggiungilo di nuovo."; +"profile__link_error_url_invalid" = "Inserisci un link web valido, ad esempio example.com."; +"profile__link_error_url_length" = "Il link deve avere al massimo 300 caratteri."; "profile__delete_title" = "Eliminare il Profilo?"; "profile__delete_description" = "Eliminando il profilo lo rimuovi da Pubky. I contatti potrebbero conservare le informazioni di profilo e di pagamento condivise in precedenza con loro."; "profile__delete_confirm" = "Sì, Elimina"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index 2e2471a21..0bf3c540c 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -1408,6 +1408,11 @@ "profile__edit_changed_error" = "Je profiel is gewijzigd in pubky.app. Bitkit heeft de nieuwste versie geladen, dus voer je wijziging opnieuw uit."; "profile__edit_public_note" = "Dit is je pubky.app-profiel. Het is openbaar, en wijzigingen die je hier maakt, verschijnen ook op pubky.app."; "profile__edit_tags_error" = "Bitkit kon je tags niet opslaan. Je andere wijzigingen zijn opgeslagen, dus probeer de tags opnieuw."; +"profile__edit_link_error" = "Corrigeer de link {label} om je profiel op te slaan."; +"profile__link_error_label_length" = "Het label mag maximaal 100 tekens bevatten."; +"profile__link_error_label_stored" = "Het label van deze link kan niet worden opgeslagen. Verwijder de link en voeg hem opnieuw toe."; +"profile__link_error_url_invalid" = "Voer een geldige weblink in, zoals example.com."; +"profile__link_error_url_length" = "De link mag maximaal 300 tekens bevatten."; "profile__delete_title" = "Profiel verwijderen?"; "profile__delete_description" = "Als u uw profiel verwijdert, wordt het van Pubky verwijderd. Contacten kunnen eerder gedeelde profiel- en betaalgegevens nog bewaren."; "profile__delete_confirm" = "Ja, verwijderen"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index ce220f7e5..bd986fc7a 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -1412,6 +1412,11 @@ "profile__edit_changed_error" = "Twój profil zmienił się w pubky.app. Bitkit wczytał najnowszą wersję, więc wprowadź zmianę ponownie."; "profile__edit_public_note" = "To jest Twój profil pubky.app. Jest publiczny, a zmiany wprowadzone tutaj pojawią się też w pubky.app."; "profile__edit_tags_error" = "Bitkit nie mógł zapisać Twoich tagów. Pozostałe zmiany zostały zapisane, więc spróbuj ponownie z tagami."; +"profile__edit_link_error" = "Popraw link {label}, aby zapisać profil."; +"profile__link_error_label_length" = "Etykieta może mieć maksymalnie 100 znaków."; +"profile__link_error_label_stored" = "Nie można zapisać etykiety tego linku. Usuń link i dodaj go ponownie."; +"profile__link_error_url_invalid" = "Wpisz prawidłowy link internetowy, np. example.com."; +"profile__link_error_url_length" = "Link może mieć maksymalnie 300 znaków."; "profile__delete_title" = "Usunąć profil?"; "profile__delete_description" = "Usunięcie profilu usuwa go z Pubky. Kontakty mogą nadal przechowywać udostępnione im wcześniej dane profilu i płatności."; "profile__delete_confirm" = "Tak, usuń"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index 03e5352af..990fad15f 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -1413,6 +1413,11 @@ "profile__edit_changed_error" = "Seu perfil mudou no pubky.app. O Bitkit carregou a versão mais recente, então faça sua alteração de novo."; "profile__edit_public_note" = "Este é o seu perfil do pubky.app. Ele é público, e as alterações que você faz aqui também aparecem no pubky.app."; "profile__edit_tags_error" = "O Bitkit não conseguiu salvar suas tags. Suas outras alterações foram salvas, então tente as tags novamente."; +"profile__edit_link_error" = "Corrija o link {label} para salvar seu perfil."; +"profile__link_error_label_length" = "O rótulo deve ter no máximo 100 caracteres."; +"profile__link_error_label_stored" = "Não é possível salvar o rótulo deste link. Remova o link e adicione-o novamente."; +"profile__link_error_url_invalid" = "Insira um link da web válido, como example.com."; +"profile__link_error_url_length" = "O link deve ter no máximo 300 caracteres."; "profile__delete_title" = "Excluir Perfil?"; "profile__delete_description" = "Excluir seu perfil o remove do Pubky. Os contatos ainda podem manter informações de perfil e de pagamento compartilhadas anteriormente com eles."; "profile__delete_confirm" = "Sim, Excluir"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index dafdbb0ad..3518d94b7 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -1175,6 +1175,11 @@ "profile__edit_changed_error" = "O teu perfil mudou no pubky.app. A Bitkit carregou a versão mais recente, por isso faz novamente a tua alteração."; "profile__edit_public_note" = "Este é o teu perfil do pubky.app. É público, e as alterações que fazes aqui também aparecem no pubky.app."; "profile__edit_tags_error" = "O Bitkit não conseguiu guardar as suas etiquetas. As outras alterações foram guardadas, por isso tente as etiquetas novamente."; +"profile__edit_link_error" = "Corrija a ligação {label} para guardar o seu perfil."; +"profile__link_error_label_length" = "A etiqueta deve ter no máximo 100 caracteres."; +"profile__link_error_label_stored" = "Não é possível guardar a etiqueta desta ligação. Remova a ligação e adicione-a novamente."; +"profile__link_error_url_invalid" = "Introduza uma ligação web válida, como example.com."; +"profile__link_error_url_length" = "A ligação deve ter no máximo 300 caracteres."; "profile__delete_title" = "Eliminar perfil?"; "profile__delete_description" = "Eliminar o seu perfil remove-o do Pubky. Os contactos podem manter as informações de perfil e pagamento partilhadas anteriormente com eles."; "profile__delete_confirm" = "Sim, Excluir"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index a5c4b51ac..0921f46ba 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -1399,6 +1399,11 @@ "profile__edit_changed_error" = "Ваш профиль изменился в pubky.app. Bitkit загрузил последнюю версию, поэтому внесите изменение снова."; "profile__edit_public_note" = "Это ваш профиль pubky.app. Он публичный, и изменения, которые вы вносите здесь, также видны в pubky.app."; "profile__edit_tags_error" = "Bitkit не удалось сохранить ваши теги. Остальные изменения сохранены, поэтому попробуйте сохранить теги ещё раз."; +"profile__edit_link_error" = "Исправьте ссылку {label}, чтобы сохранить профиль."; +"profile__link_error_label_length" = "Метка должна содержать не более 100 символов."; +"profile__link_error_label_stored" = "Не удаётся сохранить метку этой ссылки. Удалите ссылку и добавьте её снова."; +"profile__link_error_url_invalid" = "Введите корректную веб-ссылку, например example.com."; +"profile__link_error_url_length" = "Ссылка должна содержать не более 300 символов."; "profile__delete_title" = "Удалить Профиль?"; "profile__delete_description" = "Удаление профиля удалит его из Pubky. У контактов могут остаться данные профиля и платёжные данные, которыми вы делились ранее."; "profile__delete_confirm" = "Да, Удалить"; diff --git a/Bitkit/Views/Profile/AddLinkSheet.swift b/Bitkit/Views/Profile/AddLinkSheet.swift index 877e9ec56..dfb256952 100644 --- a/Bitkit/Views/Profile/AddLinkSheet.swift +++ b/Bitkit/Views/Profile/AddLinkSheet.swift @@ -3,6 +3,7 @@ import SwiftUI struct AddLinkSheet: View { @Environment(\.dismiss) private var dismiss + /// Marks a profile link, which pubky.app publishes: it must be a web link that meets its rules. var webLinksOnly = false let onSave: (String, String) -> Void @@ -10,10 +11,22 @@ struct AddLinkSheet: View { @State private var url: String = "" @State private var showSuggestionsSheet = false + private var linkError: PubkyAppLinkError? { + webLinksOnly ? PubkyAppProfileStore.linkError(label: label, url: url, webOnly: true) : nil + } + + private var labelError: String? { + linkError == .labelTooLong ? linkError?.message : nil + } + + private var urlError: String? { + linkError?.isLabelError == false ? linkError?.message : nil + } + private var canSave: Bool { !label.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty - && (!webLinksOnly || url.isWebLink) + && linkError == nil } var body: some View { @@ -25,6 +38,12 @@ struct AddLinkSheet: View { CaptionMText(t("profile__add_link_label"), textColor: .white64) labelFieldWithSuggestions + + if let labelError { + BodySText(labelError, textColor: .redAccent) + .fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier("AddLinkLabelError") + } } VStack(alignment: .leading, spacing: 8) { @@ -39,6 +58,12 @@ struct AddLinkSheet: View { .keyboardType(.URL) .textInputAutocapitalization(.never) .autocorrectionDisabled() + + if let urlError { + BodySText(urlError, textColor: .redAccent) + .fixedSize(horizontal: false, vertical: true) + .accessibilityIdentifier("AddLinkUrlError") + } } CaptionText(t("profile__add_link_note"), textColor: .white50) @@ -61,6 +86,14 @@ struct AddLinkSheet: View { .presentationDetents([.height(460)]) .presentationCornerRadius(32) .presentationDragIndicator(.visible) + .onChange(of: label) { _, value in + let printable = String(String.UnicodeScalarView(value.unicodeScalars.map { + $0.properties.generalCategory == .control ? " " : $0 + })) + if printable != value { + label = printable + } + } .sheet(isPresented: $showSuggestionsSheet) { LinkSuggestionsSheet(webLinksOnly: webLinksOnly) { suggestion in label = suggestion @@ -111,6 +144,7 @@ struct AddLinkSheet: View { extension String { /// 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. var isWebLink: Bool { let value = trimmingCharacters(in: .whitespacesAndNewlines) guard !value.isEmpty, !value.contains(where: \.isWhitespace) else { return false } @@ -118,10 +152,19 @@ extension String { if !hasScheme, value.prefix(while: { $0 != "/" }).contains("@") { return false } - guard let components = URLComponents(string: hasScheme ? value : "https://\(value)"), - let scheme = components.scheme?.lowercased(), ["http", "https"].contains(scheme), - let host = components.host, host.contains("."), - let topLabel = host.split(separator: ".").last, !topLabel.allSatisfy(\.isNumber) + let url = hasScheme ? value : "https://\(value)" + guard let colon = url.firstIndex(of: ":") else { return false } + let afterScheme = url[url.index(after: colon)...] + guard ["http", "https"].contains(url[.. = [] + @State private var storedLinks: [PubkyProfileData.Link] = [] + @State private var rejectedLink: PubkyProfileData.Link? @State private var tags: [String] = [] @State private var baseRevision: String? @State private var baseTagsUnread = false @@ -38,7 +39,7 @@ struct EditProfileView: View { isSaving: isSaving, maxLinks: PubkyAppProfileLimits.maxLinks, webLinksOnly: true, - storedLinkUrls: storedLinkUrls, + linkErrors: linkErrors, isNameValid: PubkyAppProfileLimits.isValidName, footerNote: t("profile__edit_public_note"), deleteLabel: copy.label, @@ -99,6 +100,14 @@ struct EditProfileView: View { } } + private var linkData: [PubkyProfileData.Link] { + links.map { PubkyProfileData.Link(label: $0.label, url: $0.url) } + } + + private var linkErrors: [Int: PubkyAppLinkError] { + PubkyAppProfileStore.linkErrors(links: linkData, storedLinks: storedLinks, rejectedLink: rejectedLink) + } + // MARK: - Avatar Picker private var avatarPicker: some View { @@ -161,7 +170,8 @@ struct EditProfileView: View { loadedBio = profile.bio bio = profile.bio links = profile.links.map { ProfileLinkInput(label: $0.label, url: $0.url) } - storedLinkUrls = Set(profile.links.map(\.url)) + storedLinks = profile.links.map { PubkyProfileData.Link(label: $0.label, url: $0.url) } + rejectedLink = nil tags = profile.tags baseRevision = profile.revision baseTagsUnread = profile.tagsUnread @@ -238,9 +248,8 @@ struct EditProfileView: View { /// or the profile publishes, it stops quietly, with no toast and no navigation. private func saveProfile() async { let trimmedName = username.trimmingCharacters(in: .whitespacesAndNewlines) - guard PubkyAppProfileLimits.isValidName(trimmedName), - links.allSatisfy({ storedLinkUrls.contains($0.url) || $0.url.isWebLink }) - else { return } + guard PubkyAppProfileLimits.isValidName(trimmedName), linkErrors.isEmpty else { return } + let savedLinks = linkData isSaving = true defer { isSaving = false } @@ -260,7 +269,12 @@ struct EditProfileView: View { navigation.navigateBack() } catch { Logger.error("Failed to save profile: \(error)", context: "EditProfileView") - app.toast(type: .error, title: t("profile__edit_error_title"), description: error.localizedDescription) + let rejected = PubkyAppProfileStore.rejectedLink(for: error, links: savedLinks) + let description = rejected.map { t("profile__edit_link_error", variables: ["label": $0.label]) } + app.toast(type: .error, title: t("profile__edit_error_title"), description: description ?? error.localizedDescription) + if linkData == savedLinks { + rejectedLink = rejected + } if case PubkyAppProfileError.changedElsewhere = error { await pubkyProfile.loadProfile() avatarImage = nil diff --git a/BitkitTests/PubkyAppLinkTests.swift b/BitkitTests/PubkyAppLinkTests.swift new file mode 100644 index 000000000..4a1b8b77f --- /dev/null +++ b/BitkitTests/PubkyAppLinkTests.swift @@ -0,0 +1,207 @@ +@testable import Bitkit +import Paykit +import XCTest + +final class PubkyAppLinkTests: XCTestCase { + private let emoji = "\u{1F680}" + + private func error(_ label: String, _ url: String, webOnly: Bool = true) -> PubkyAppLinkError? { + PubkyAppProfileStore.linkError(label: label, url: url, webOnly: webOnly) + } + + func testLabelsAreLimitedTo100ScalarsWithEmojiCountedOnce() { + XCTAssertNil(error(String(repeating: emoji, count: 100), "example.com")) + XCTAssertEqual(error(String(repeating: emoji, count: 101), "example.com"), .labelTooLong) + XCTAssertNil(error(" " + String(repeating: "a", count: 100) + "\n", "example.com")) + } + + func testUrlsAreLimitedTo300ScalarsAfterNormalization() { + let at300 = "https://example.com/" + String(repeating: "a", count: 280) + XCTAssertEqual(at300.unicodeScalars.count, 300) + XCTAssertNil(error("Site", at300)) + XCTAssertEqual(error("Site", at300 + "a"), .urlTooLong) + XCTAssertEqual(error("Site", "example.com/" + String(repeating: "a", count: 281)), .urlTooLong) + XCTAssertNil(error("Site", "https://example.com/" + String(repeating: emoji, count: 280))) + XCTAssertEqual(error("Site", "https://example.com/" + String(repeating: emoji, count: 281)), .urlTooLong) + } + + func testInvalidUrlsAreRefused() { + for url in ["not a url", "example", "https://exa mple.com", "https://1.2.3.999"] { + XCTAssertEqual(error("Site", url, webOnly: false), .urlInvalid, url) + } + } + + func testNormalizableInputsAreAccepted() { + for url in ["example.com", " www.example.com/path ", "https://Example.com", "HTTPS://example.com"] { + XCTAssertNil(error("Site", url), url) + } + for url in ["me@example.com", "+1 (234) 567-890", "mailto:me@example.com", "tel:+123456789"] { + XCTAssertNil(error("Contact", url, webOnly: false), url) + } + } + + func testWebOnlyLinksAcceptIdnUnderscoreAndQueryCharacters() { + for url in ["bücher.de", "my_site.example.com", "https://example.com/?q=a|b", "https://user:pass@example.com"] { + XCTAssertNil(error("Site", url), url) + } + } + + func testWebOnlyLinksRefuseEmailAndPhone() { + for url in ["me@example.com", "+1 234 567 890", "mailto:me@example.com", "ftp://example.com"] { + XCTAssertEqual(error("Contact", url), .urlInvalid, url) + } + } + + func testSocialV1WebUrlsFollowPaykitsRule() { + for url in ["https://example.com", "http://localhost", "https://[::1]", "https://user@host:8080/a"] { + XCTAssertTrue(PubkyAppProfileStore.isSocialV1WebUrl(url), url) + } + for url in [ + "https:///example.com", "https://", "https://@", "HTTPS://example.com", "mailto:a@example.com", + "https://exa mple.com", "https://example.com/\u{01}", "https://:80", + ] { + XCTAssertFalse(PubkyAppProfileStore.isSocialV1WebUrl(url), url) + } + } + + func testLinkRejectionSkipsStoredLocalhostForTheNonWebLink() { + let links = [ + PubkyProfileData.Link(label: "Local", url: "https://localhost"), + PubkyProfileData.Link(label: "Email", url: "mailto:me@example.com"), + ] + let rejection: PaykitError = .Protocol(code: "protocol_error", context: PubkyAppProfileStore.paykitNonWebLinkContext) + XCTAssertEqual(PubkyAppProfileStore.rejectedLink(for: rejection, links: links), links[1]) + } + + func testBlankUrlIsLeftToTheCaller() { + XCTAssertNil(error("Site", " ")) + } + + func testCharactersTheUrlParserAcceptsInAPathOrQueryAreAccepted() { + for url in [ + "https://example.com/?q=a|b", + "https://example.com/100%", + "https://example.com/a[1]{2}^\"x\"", + "https://my_site.example.com", + ] { + XCTAssertNil(error("Site", url, webOnly: false), url) + XCTAssertEqual(PubkyAppProfileStore.linkUrl(url), url, url) + } + XCTAssertEqual(PubkyAppProfileStore.linkUrl("example.com/?q=a|b"), "https://example.com/?q=a|b") + } + + func testHostsPortsAndControlCharactersTheUrlParserRefusesAreRefused() { + for url in [ + "https://exa|mple.com", + "https://exa%mple.com", + "https://", + "https://example.com:65536", + "https://example.com:port", + "https://[zz::1]", + "https://example.com/\u{01}", + "mailto:a\u{7F}@example.com", + ] { + XCTAssertEqual(error("Site", url, webOnly: false), .urlInvalid, url) + } + XCTAssertNil(error("Site", "https://example.com:65535", webOnly: false)) + XCTAssertNil(error("Site", "https://example.com.")) + XCTAssertNil(error("Site", "https://1.2.3.4.", webOnly: false)) + XCTAssertNil(error("Site", "https:example.com", webOnly: false)) + XCTAssertEqual(error("Site", "https:example.com"), .urlInvalid) + XCTAssertNil(error("Site", "https://[::1]:8080", webOnly: false)) + } + + func testLabelEmptyOnceOnOneLineIsRefusedAfterTheUrl() { + XCTAssertEqual(error("\u{01}\u{02}", "example.com"), .labelEmpty) + XCTAssertEqual(error("", "example.com"), .labelEmpty) + XCTAssertEqual(error("", "not a url"), .urlInvalid) + } + + func testStoredLinkWithoutHostIsRefusedOnceLinksChange() { + let stored = [PubkyProfileData.Link(label: "Site", url: "https://")] + let links = stored + [PubkyProfileData.Link(label: "Blog", url: "blog.example.com")] + XCTAssertEqual(PubkyAppProfileStore.linkErrors(links: links, storedLinks: stored), [0: .urlInvalid]) + } + + func testStoredUrlTheUrlParserAcceptsDoesNotBlockTheSave() { + let stored = [PubkyProfileData.Link(label: "Search", url: "https://example.com/?q=a|b")] + let links = stored + [PubkyProfileData.Link(label: "Blog", url: "blog.example.com")] + XCTAssertTrue(PubkyAppProfileStore.linkErrors(links: links, storedLinks: stored).isEmpty) + } + + func testOnlyTheNonWebLinkContextOfPaykit011rc9MarksARow() { + // Paykit 0.1.1-rc9, paykit-sdk/src/domain/contacts/pubky_app.rs; update with the Paykit version. + XCTAssertEqual( + PubkyAppProfileStore.paykitNonWebLinkContext, + "Pubky profile link URL must be a canonical http or https URL" + ) + let links = [PubkyProfileData.Link(label: "Email", url: "mailto:me@example.com")] + let invalidUri: PaykitError = .Protocol(code: "protocol_error", context: "Pubky profile link URL must be a valid URI") + XCTAssertNil(PubkyAppProfileStore.rejectedLink(for: invalidUri, links: links)) + } + + func testStoredLinksAreNotCheckedWhileUnchanged() { + let stored = [PubkyProfileData.Link(label: String(repeating: "x", count: 101), url: "https://example.com")] + XCTAssertTrue(PubkyAppProfileStore.linkErrors(links: stored, storedLinks: stored).isEmpty) + } + + func testUrlEditThatNormalizesToTheStoredLinkLeavesStoredLinksUnchecked() { + let label = String(repeating: "x", count: 101) + let stored = [PubkyProfileData.Link(label: label, url: "https://example.com")] + let links = [PubkyProfileData.Link(label: label, url: "example.com")] + XCTAssertTrue(PubkyAppProfileStore.linkErrors(links: links, storedLinks: stored).isEmpty) + } + + func testRefusalStaysOnItsLinkUntilThatLinkChanges() { + let site = PubkyProfileData.Link(label: "Site", url: "https://example.com") + let email = PubkyProfileData.Link(label: "Email", url: "mailto:a@example.com") + let blog = PubkyProfileData.Link(label: "Blog", url: "https://blog.example.org") + let stored = [site, email] + XCTAssertEqual( + PubkyAppProfileStore.linkErrors(links: [site, email, blog], storedLinks: stored, rejectedLink: email), + [1: .urlInvalid] + ) + XCTAssertEqual( + PubkyAppProfileStore.linkErrors(links: [email, blog], storedLinks: stored, rejectedLink: email), + [0: .urlInvalid] + ) + let edited = PubkyProfileData.Link(label: "Email", url: "https://example.org") + XCTAssertTrue(PubkyAppProfileStore.linkErrors(links: [edited, blog], storedLinks: stored, rejectedLink: email).isEmpty) + } + + func testStoredLinkIsCheckedOnceLinksChange() { + let stored = [ + PubkyProfileData.Link(label: String(repeating: "x", count: 101), url: "https://example.com"), + PubkyProfileData.Link(label: "Email", url: "mailto:me@example.com"), + ] + let links = stored + [PubkyProfileData.Link(label: "Blog", url: "blog.example.com")] + XCTAssertEqual(PubkyAppProfileStore.linkErrors(links: links, storedLinks: stored), [0: .labelTooLong]) + } + + func testAddedLinkIsHeldToThePublisherRules() { + let stored = [PubkyProfileData.Link(label: "Website", url: "https://example.com")] + let links = stored + [ + PubkyProfileData.Link(label: "Email", url: "me@example.com"), + PubkyProfileData.Link(label: "Site", url: "example.com/" + String(repeating: "a", count: 281)), + ] + XCTAssertEqual(PubkyAppProfileStore.linkErrors(links: links, storedLinks: stored), [1: .urlInvalid, 2: .urlTooLong]) + } + + func testLinkRejectionPointsToTheStoredNonWebLink() { + let links = [ + PubkyProfileData.Link(label: "Site", url: "https://example.com"), + PubkyProfileData.Link(label: "Email", url: "mailto:me@example.com"), + ] + let rejection: PaykitError = .Protocol( + code: "protocol_error", + context: "Pubky profile link URL must be a canonical http or https URL" + ) + XCTAssertEqual(PubkyAppProfileStore.rejectedLink(for: rejection, links: links), links[1]) + let other: PaykitError = .Protocol(code: "protocol_error", context: "Pubky profile name must be 3 to 50 characters") + XCTAssertNil(PubkyAppProfileStore.rejectedLink(for: other, links: links)) + XCTAssertEqual( + PubkyAppProfileStore.linkErrors(links: links + [], storedLinks: [], rejectedLink: links[1])[1], + .urlInvalid + ) + } +} diff --git a/BitkitTests/WebLinkTests.swift b/BitkitTests/WebLinkTests.swift index 417334eaa..a41d248dc 100644 --- a/BitkitTests/WebLinkTests.swift +++ b/BitkitTests/WebLinkTests.swift @@ -10,6 +10,14 @@ final class WebLinkTests: XCTestCase { " 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", ] { XCTAssertTrue(link.isWebLink, link) } @@ -19,6 +27,9 @@ final class WebLinkTests: XCTestCase { let links = [ "mailto:a@b.c", "a@b.c", "tel:+123456789", "+1 234 567 890", "123.456.7890", "ftp://example.com", "example.com:8080", "example", "two words.com", "", + "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\u{00A0}b", "example\u{2007}.com", "https://example.com/a\u{202F}b", ] for link in links { XCTAssertFalse(link.isWebLink, link) diff --git a/changelog.d/next/1301.fixed.md b/changelog.d/next/1301.fixed.md new file mode 100644 index 000000000..82b027b51 --- /dev/null +++ b/changelog.d/next/1301.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 eac5f412a..9b250cd0a 100644 --- a/journeys/profile/README.md +++ b/journeys/profile/README.md @@ -59,3 +59,5 @@ On iOS, open a saved contact's link while a stored identity's session restoratio `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 iOS, 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 000000000..ff954606f --- /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" + +