From a62abfdc45d12493e5ae1cc844d33d6fb77e5681 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 10:47:19 -0300 Subject: [PATCH 1/7] fix: validate profile links against pubky.app rules Co-Authored-By: Claude Opus 5.5 --- Bitkit/Components/ProfileEditFormView.swift | 16 ++-- Bitkit/Managers/PubkyAppProfileStore.swift | 63 ++++++++++++- Bitkit/Models/PubkyProfile.swift | 20 ++++ .../Localization/ar.lproj/Localizable.strings | 4 + .../Localization/ca.lproj/Localizable.strings | 4 + .../Localization/cs.lproj/Localizable.strings | 4 + .../Localization/de.lproj/Localizable.strings | 4 + .../Localization/el.lproj/Localizable.strings | 4 + .../Localization/en.lproj/Localizable.strings | 4 + .../es-419.lproj/Localizable.strings | 4 + .../Localization/es.lproj/Localizable.strings | 4 + .../Localization/fr.lproj/Localizable.strings | 4 + .../Localization/it.lproj/Localizable.strings | 4 + .../Localization/nl.lproj/Localizable.strings | 4 + .../Localization/pl.lproj/Localizable.strings | 4 + .../pt-BR.lproj/Localizable.strings | 4 + .../Localization/pt.lproj/Localizable.strings | 4 + .../Localization/ru.lproj/Localizable.strings | 4 + Bitkit/Views/Profile/AddLinkSheet.swift | 27 +++++- Bitkit/Views/Profile/EditProfileView.swift | 31 +++++-- BitkitTests/PubkyAppLinkTests.swift | 93 +++++++++++++++++++ changelog.d/next/1301.fixed.md | 1 + journeys/profile/README.md | 2 + journeys/profile/profile-link-validation.xml | 20 ++++ 24 files changed, 315 insertions(+), 18 deletions(-) create mode 100644 BitkitTests/PubkyAppLinkTests.swift create mode 100644 changelog.d/next/1301.fixed.md create mode 100644 journeys/profile/profile-link-validation.xml diff --git a/Bitkit/Components/ProfileEditFormView.swift b/Bitkit/Components/ProfileEditFormView.swift index 4e579ddfa4..71d3e32640 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.message, 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 f14598d9bf..449617bd64 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" @@ -562,9 +562,67 @@ 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 label or URL is left to the caller. `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 { + return nil + } + guard let normalized = normalizedLinkUrl(url), isParsableLinkUrl(normalized) else { return .urlInvalid } + if webOnly, !url.isWebLink { + return .urlInvalid + } + if normalized.unicodeScalars.count > linkUrlMaxLength { + return .urlTooLong + } + return nil + } + + /// The links pubky.app would refuse, by index. A save sends the links only once they change, and then pubky.app checks + /// every one, so a stored link is held to its rules too. Links added or edited here must also be web links, which + /// social v1 requires; stored ones keep their scheme. `rejectedIndex` is a link pubky.app already refused. + static func linkErrors( + links: [PubkyProfileData.Link], + storedLinks: [PubkyProfileData.Link], + rejectedIndex: Int? = nil + ) -> [Int: PubkyAppLinkError] { + guard links != storedLinks else { return [:] } + let storedUrls = Set(storedLinks.map(\.url)) + var errors: [Int: PubkyAppLinkError] = [:] + for (index, link) in links.enumerated() { + if index == rejectedIndex || 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 + } + + /// The link pubky.app refused a social v1 profile for: the first that is not a web link, as the others passed. + static func rejectedLinkIndex(for error: Error, links: [PubkyProfileData.Link]) -> Int? { + guard case let .Protocol(_, context)? = error as? PaykitError, context.contains("Pubky profile link") else { return nil } + return links.firstIndex { !$0.url.isWebLink } + } + /// 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, isParsableLinkUrl(url) + else { return nil } + return url + } + + private static func isParsableLinkUrl(_ url: String) -> Bool { + guard let parsed = URL(string: url) else { return false } + return hasValidHost(parsed) + } + + 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 @@ -579,7 +637,6 @@ actor PubkyAppProfileStore { } else { return nil } - guard url.unicodeScalars.count <= linkUrlMaxLength, let parsed = URL(string: url), hasValidHost(parsed) else { return nil } return url } diff --git a/Bitkit/Models/PubkyProfile.swift b/Bitkit/Models/PubkyProfile.swift index 7ac3010909..25cab97270 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,21 @@ 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 labelTooLong + case urlTooLong + case urlInvalid + + var message: String { + switch self { + case .labelTooLong: + t("profile__link_error_label_length") + case .urlTooLong: + t("profile__link_error_url_length") + case .urlInvalid: + t("profile__link_error_url_invalid") + } + } +} diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index 8843b0b0ed..d9ce57b656 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -1169,6 +1169,10 @@ "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_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 b57827a2bb..28afe3af17 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -1286,6 +1286,10 @@ "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_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 a1d8df37d6..1120d035da 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -1390,6 +1390,10 @@ "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_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 53e150e755..9eeab7ef18 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -1388,6 +1388,10 @@ "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_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 9e30774ded..95c65a7c30 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -1187,6 +1187,10 @@ "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_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 9c1eb9e59c..9ae0bd7a8b 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1403,6 +1403,10 @@ "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_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 7fd85218d8..3489006340 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -1393,6 +1393,10 @@ "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_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 b9f3a5c6b9..8537b83526 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -1304,6 +1304,10 @@ "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_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 cd930e6217..e4ba90226d 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -1401,6 +1401,10 @@ "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_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 6cff1d76e3..bb9dfb9a48 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -1368,6 +1368,10 @@ "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_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 0389e30ef3..d2b4a50b65 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -1396,6 +1396,10 @@ "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_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 89dbd098e0..ab85eff2d3 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -1400,6 +1400,10 @@ "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_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 62f17f3d7e..2a5f952e92 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -1401,6 +1401,10 @@ "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_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 561a186f10..a7cc545219 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -1163,6 +1163,10 @@ "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_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 a19e3a9759..2d13f453d1 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -1387,6 +1387,10 @@ "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_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 877e9ec56c..3b2553233d 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 != .labelTooLong ? 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) diff --git a/Bitkit/Views/Profile/EditProfileView.swift b/Bitkit/Views/Profile/EditProfileView.swift index 78dc75b1b8..ebe71a26a0 100644 --- a/Bitkit/Views/Profile/EditProfileView.swift +++ b/Bitkit/Views/Profile/EditProfileView.swift @@ -10,7 +10,8 @@ struct EditProfileView: View { @State private var username: String = "" @State private var bio: String = "" @State private var links: [ProfileLinkInput] = [] - @State private var storedLinkUrls: Set = [] + @State private var storedLinks: [PubkyProfileData.Link] = [] + @State private var rejectedLinkIndex: Int? @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, @@ -68,6 +69,9 @@ struct EditProfileView: View { .task { loadProfileData() } + .onChange(of: linkData) { + rejectedLinkIndex = nil + } .onChange(of: username) { _, value in if let capped = PubkyAppProfileLimits.capped(value, to: PubkyAppProfileLimits.nameLength.upperBound) { username = capped @@ -99,6 +103,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, rejectedIndex: rejectedLinkIndex) + } + // MARK: - Avatar Picker private var avatarPicker: some View { @@ -161,7 +173,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) } + rejectedLinkIndex = nil tags = profile.tags baseRevision = profile.revision baseTagsUnread = profile.tagsUnread @@ -238,9 +251,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 +272,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.rejectedLinkIndex(for: error, links: savedLinks) + let description = rejected.map { t("profile__edit_link_error", variables: ["label": savedLinks[$0].label]) } + app.toast(type: .error, title: t("profile__edit_error_title"), description: description ?? error.localizedDescription) + if linkData == savedLinks { + rejectedLinkIndex = 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 0000000000..4a3b7d10c8 --- /dev/null +++ b/BitkitTests/PubkyAppLinkTests.swift @@ -0,0 +1,93 @@ +@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 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 testBlankUrlIsLeftToTheCaller() { + XCTAssertNil(error("Site", " ")) + } + + 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 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.rejectedLinkIndex(for: rejection, links: links), 1) + let other: PaykitError = .Protocol(code: "protocol_error", context: "Pubky profile name must be 3 to 50 characters") + XCTAssertNil(PubkyAppProfileStore.rejectedLinkIndex(for: other, links: links)) + XCTAssertEqual( + PubkyAppProfileStore.linkErrors(links: links + [], storedLinks: [], rejectedIndex: 1)[1], + .urlInvalid + ) + } +} diff --git a/changelog.d/next/1301.fixed.md b/changelog.d/next/1301.fixed.md new file mode 100644 index 0000000000..82b027b519 --- /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 eac5f412a1..9b250cd0a9 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 0000000000..ff954606f7 --- /dev/null +++ b/journeys/profile/profile-link-validation.xml @@ -0,0 +1,20 @@ + + + Precondition: a disposable wallet signed in to a Pubky profile with at most four links, PIN off and an English + device. This checks that the Add Link sheet in Edit Profile refuses links pubky.app would refuse, with an error on + the field that needs fixing, and still accepts a bare domain. + + + Open Profile using "ProfileButton" and wait for "ProfileViewName" + Tap "ProfileEdit" and wait for "ProfileEditName" + Tap "ProfileEditAddLink" and wait for "AddLinkLabel" + Enter "Website" in "AddLinkLabel" and "not a url" in "AddLinkUrl" + Verify "AddLinkUrlError" says "Enter a valid web link, such as example.com." and "AddLinkSave" is disabled + Replace the text in "AddLinkUrl" with "me@example.com" + Verify "AddLinkUrlError" is shown and "AddLinkSave" is disabled + Replace the text in "AddLinkUrl" with "example.com" + Verify "AddLinkUrlError" is gone and "AddLinkSave" is enabled + Tap "AddLinkSave" and verify a "Website" link with "example.com" appears in Edit Profile + Tap "ProfileEditSave" and wait for "ProfileUpdatedToast" + + From 30c9c95781e2adf664de021445d4fd7271acacc4 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 13:31:32 -0300 Subject: [PATCH 2/7] fix: match link checks to the url parser paykit uses Co-Authored-By: Claude Opus 5.5 --- Bitkit/Components/ProfileEditFormView.swift | 2 +- Bitkit/Managers/PubkyAppProfileStore.swift | 114 +++++++++++++----- Bitkit/Models/PubkyProfile.swift | 13 ++ .../Localization/ar.lproj/Localizable.strings | 1 + .../Localization/ca.lproj/Localizable.strings | 1 + .../Localization/cs.lproj/Localizable.strings | 1 + .../Localization/de.lproj/Localizable.strings | 1 + .../Localization/el.lproj/Localizable.strings | 1 + .../Localization/en.lproj/Localizable.strings | 1 + .../es-419.lproj/Localizable.strings | 1 + .../Localization/es.lproj/Localizable.strings | 1 + .../Localization/fr.lproj/Localizable.strings | 1 + .../Localization/it.lproj/Localizable.strings | 1 + .../Localization/nl.lproj/Localizable.strings | 1 + .../Localization/pl.lproj/Localizable.strings | 1 + .../pt-BR.lproj/Localizable.strings | 1 + .../Localization/pt.lproj/Localizable.strings | 1 + .../Localization/ru.lproj/Localizable.strings | 1 + Bitkit/Views/Profile/AddLinkSheet.swift | 2 +- BitkitTests/PubkyAppLinkTests.swift | 59 +++++++++ 20 files changed, 173 insertions(+), 32 deletions(-) diff --git a/Bitkit/Components/ProfileEditFormView.swift b/Bitkit/Components/ProfileEditFormView.swift index 71d3e32640..ee655f773c 100644 --- a/Bitkit/Components/ProfileEditFormView.swift +++ b/Bitkit/Components/ProfileEditFormView.swift @@ -223,7 +223,7 @@ struct ProfileEditFormView: View { .cornerRadius(8) if let linkError = linkErrors[index] { - BodySText(linkError.message, textColor: .redAccent) + BodySText(linkError.rowMessage, textColor: .redAccent) .fixedSize(horizontal: false, vertical: true) .accessibilityIdentifier("ProfileEditLinkError_\(index)") } diff --git a/Bitkit/Managers/PubkyAppProfileStore.swift b/Bitkit/Managers/PubkyAppProfileStore.swift index 449617bd64..60ff613099 100644 --- a/Bitkit/Managers/PubkyAppProfileStore.swift +++ b/Bitkit/Managers/PubkyAppProfileStore.swift @@ -563,21 +563,24 @@ actor PubkyAppProfileStore { } /// 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 label or URL is left to the caller. `webOnly` also requires an - /// http(s) link, as a social v1 profile does. + /// 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 { - return nil - } - guard let normalized = normalizedLinkUrl(url), isParsableLinkUrl(normalized) else { return .urlInvalid } - if webOnly, !url.isWebLink { - return .urlInvalid + 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 normalized.unicodeScalars.count > linkUrlMaxLength { - return .urlTooLong + if singleLine(label).isEmpty { + return .labelEmpty } return nil } @@ -603,30 +606,94 @@ actor PubkyAppProfileStore { return errors } - /// The link pubky.app refused a social v1 profile for: the first that is not a web link, as the others passed. + /// 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 rejectedLinkIndex(for error: Error, links: [PubkyProfileData.Link]) -> Int? { - guard case let .Protocol(_, context)? = error as? PaykitError, context.contains("Pubky profile link") else { return nil } + guard case let .Protocol(_, context)? = error as? PaykitError, context == paykitNonWebLinkContext else { return nil } return links.firstIndex { !$0.url.isWebLink } } /// 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, isParsableLinkUrl(url) + guard let url = normalizedLinkUrl(value), url.unicodeScalars.count <= linkUrlMaxLength, linkUrlHost(url) != nil else { return nil } return url } - private static func isParsableLinkUrl(_ url: String) -> Bool { - guard let parsed = URL(string: url) else { return false } - return hasValidHost(parsed) + 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 { + guard !host.hasPrefix("["), let last = host.split(separator: ".", omittingEmptySubsequences: false).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 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)" @@ -640,19 +707,6 @@ actor PubkyAppProfileStore { 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 25cab97270..41262c95d3 100644 --- a/Bitkit/Models/PubkyProfile.swift +++ b/Bitkit/Models/PubkyProfile.swift @@ -262,12 +262,15 @@ enum PubkyAppProfileLimits { /// 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: @@ -276,4 +279,14 @@ enum PubkyAppLinkError: Equatable { 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 d9ce57b656..3d0557ee82 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -1171,6 +1171,7 @@ "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" = "حذف الملف الشخصي؟"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index 28afe3af17..b5dbe3b5a4 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -1288,6 +1288,7 @@ "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?"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index 1120d035da..5b03d23256 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -1392,6 +1392,7 @@ "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?"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 9eeab7ef18..30d7b1656c 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -1390,6 +1390,7 @@ "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?"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 95c65a7c30..77199ffddd 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -1189,6 +1189,7 @@ "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" = "Διαγραφή Προφίλ;"; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index 9ae0bd7a8b..f90d3a7989 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -1405,6 +1405,7 @@ "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?"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 3489006340..1c57ea7792 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -1395,6 +1395,7 @@ "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?"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index 8537b83526..daf4d31130 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -1306,6 +1306,7 @@ "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?"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index e4ba90226d..279e11b3a5 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -1403,6 +1403,7 @@ "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 ?"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index bb9dfb9a48..7d7bd565e5 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -1370,6 +1370,7 @@ "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?"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index d2b4a50b65..7224743f07 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -1398,6 +1398,7 @@ "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?"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index ab85eff2d3..f0317379b5 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -1402,6 +1402,7 @@ "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?"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index 2a5f952e92..b466ed42bf 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -1403,6 +1403,7 @@ "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?"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index a7cc545219..84ea421794 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -1165,6 +1165,7 @@ "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?"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index 2d13f453d1..15e473439b 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -1389,6 +1389,7 @@ "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" = "Удалить Профиль?"; diff --git a/Bitkit/Views/Profile/AddLinkSheet.swift b/Bitkit/Views/Profile/AddLinkSheet.swift index 3b2553233d..63897b593c 100644 --- a/Bitkit/Views/Profile/AddLinkSheet.swift +++ b/Bitkit/Views/Profile/AddLinkSheet.swift @@ -20,7 +20,7 @@ struct AddLinkSheet: View { } private var urlError: String? { - linkError != .labelTooLong ? linkError?.message : nil + linkError?.isLabelError == false ? linkError?.message : nil } private var canSave: Bool { diff --git a/BitkitTests/PubkyAppLinkTests.swift b/BitkitTests/PubkyAppLinkTests.swift index 4a3b7d10c8..5265cff1c7 100644 --- a/BitkitTests/PubkyAppLinkTests.swift +++ b/BitkitTests/PubkyAppLinkTests.swift @@ -50,6 +50,65 @@ final class PubkyAppLinkTests: XCTestCase { 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://[::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.rejectedLinkIndex(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) From 61978829b68eda3a13f3d8412abfeda29b0593cf Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 13:44:12 -0300 Subject: [PATCH 3/7] fix: require http(s):// for web links and accept trailing-dot hosts Co-Authored-By: Claude Opus 5.5 --- Bitkit/Managers/PubkyAppProfileStore.swift | 5 +++-- Bitkit/Views/Profile/AddLinkSheet.swift | 22 ++++++++++++++++++---- BitkitTests/PubkyAppLinkTests.swift | 10 ++++++++++ BitkitTests/WebLinkTests.swift | 9 +++++++++ 4 files changed, 40 insertions(+), 6 deletions(-) diff --git a/Bitkit/Managers/PubkyAppProfileStore.swift b/Bitkit/Managers/PubkyAppProfileStore.swift index 60ff613099..fb559ae9b8 100644 --- a/Bitkit/Managers/PubkyAppProfileStore.swift +++ b/Bitkit/Managers/PubkyAppProfileStore.swift @@ -679,10 +679,11 @@ actor PubkyAppProfileStore { } private static func isValidIpv4Ending(_ host: String) -> Bool { - guard !host.hasPrefix("["), let last = host.split(separator: ".", omittingEmptySubsequences: false).last, + 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 = host.split(separator: ".", omittingEmptySubsequences: false).map { UInt64($0) } + 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 diff --git a/Bitkit/Views/Profile/AddLinkSheet.swift b/Bitkit/Views/Profile/AddLinkSheet.swift index 63897b593c..a45faa5d2d 100644 --- a/Bitkit/Views/Profile/AddLinkSheet.swift +++ b/Bitkit/Views/Profile/AddLinkSheet.swift @@ -86,6 +86,12 @@ struct AddLinkSheet: View { .presentationDetents([.height(460)]) .presentationCornerRadius(32) .presentationDragIndicator(.visible) + .onChange(of: label) { _, value in + let printable = String(String.UnicodeScalarView(value.unicodeScalars.filter { $0.properties.generalCategory != .control })) + if printable != value { + label = printable + } + } .sheet(isPresented: $showSuggestionsSheet) { LinkSuggestionsSheet(webLinksOnly: webLinksOnly) { suggestion in label = suggestion @@ -136,6 +142,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 } @@ -143,10 +150,17 @@ 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[.. Date: Thu, 26 Nov 2026 14:21:32 -0300 Subject: [PATCH 4/7] fix: refuse web links with an empty authority Co-Authored-By: Claude Opus 5.5 --- Bitkit/Views/Profile/AddLinkSheet.swift | 12 ++++++++---- BitkitTests/WebLinkTests.swift | 1 + 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/Bitkit/Views/Profile/AddLinkSheet.swift b/Bitkit/Views/Profile/AddLinkSheet.swift index a45faa5d2d..dfb2569522 100644 --- a/Bitkit/Views/Profile/AddLinkSheet.swift +++ b/Bitkit/Views/Profile/AddLinkSheet.swift @@ -87,7 +87,9 @@ struct AddLinkSheet: View { .presentationCornerRadius(32) .presentationDragIndicator(.visible) .onChange(of: label) { _, value in - let printable = String(String.UnicodeScalarView(value.unicodeScalars.filter { $0.properties.generalCategory != .control })) + let printable = String(String.UnicodeScalarView(value.unicodeScalars.map { + $0.properties.generalCategory == .control ? " " : $0 + })) if printable != value { label = printable } @@ -153,9 +155,11 @@ extension String { 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[.. Date: Thu, 26 Nov 2026 14:56:18 -0300 Subject: [PATCH 5/7] fix: use paykit's social v1 link rule for migration and refusals Co-Authored-By: Claude Opus 5.5 --- Bitkit/Managers/PubkyAppProfileStore.swift | 26 ++++++++++++++++++---- BitkitTests/PubkyAppLinkTests.swift | 21 +++++++++++++++++ BitkitTests/WebLinkTests.swift | 1 + 3 files changed, 44 insertions(+), 4 deletions(-) diff --git a/Bitkit/Managers/PubkyAppProfileStore.swift b/Bitkit/Managers/PubkyAppProfileStore.swift index fb559ae9b8..38591c2986 100644 --- a/Bitkit/Managers/PubkyAppProfileStore.swift +++ b/Bitkit/Managers/PubkyAppProfileStore.swift @@ -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 { @@ -614,7 +629,10 @@ actor PubkyAppProfileStore { /// passed. Any other refusal names no link. static func rejectedLinkIndex(for error: Error, links: [PubkyProfileData.Link]) -> Int? { guard case let .Protocol(_, context)? = error as? PaykitError, context == paykitNonWebLinkContext else { return nil } - return links.firstIndex { !$0.url.isWebLink } + return links.firstIndex { 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. diff --git a/BitkitTests/PubkyAppLinkTests.swift b/BitkitTests/PubkyAppLinkTests.swift index 98e2a2429d..4b205c2877 100644 --- a/BitkitTests/PubkyAppLinkTests.swift +++ b/BitkitTests/PubkyAppLinkTests.swift @@ -52,6 +52,27 @@ final class PubkyAppLinkTests: XCTestCase { } } + 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.rejectedLinkIndex(for: rejection, links: links), 1) + } + func testBlankUrlIsLeftToTheCaller() { XCTAssertNil(error("Site", " ")) } diff --git a/BitkitTests/WebLinkTests.swift b/BitkitTests/WebLinkTests.swift index 6bd7f1723c..a41d248dc1 100644 --- a/BitkitTests/WebLinkTests.swift +++ b/BitkitTests/WebLinkTests.swift @@ -29,6 +29,7 @@ final class WebLinkTests: XCTestCase { "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) From c9c4924665a2cb5822d0ae69dc0fc1a5767180cc Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 17:00:16 -0300 Subject: [PATCH 6/7] fix: check stored links only when the normalized links change Co-Authored-By: Claude Opus 5.5 --- Bitkit/Managers/PubkyAppProfileStore.swift | 10 ++++++---- BitkitTests/PubkyAppLinkTests.swift | 7 +++++++ 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/Bitkit/Managers/PubkyAppProfileStore.swift b/Bitkit/Managers/PubkyAppProfileStore.swift index 38591c2986..e12ee990b1 100644 --- a/Bitkit/Managers/PubkyAppProfileStore.swift +++ b/Bitkit/Managers/PubkyAppProfileStore.swift @@ -600,15 +600,17 @@ actor PubkyAppProfileStore { return nil } - /// The links pubky.app would refuse, by index. A save sends the links only once they change, and then pubky.app checks - /// every one, so a stored link is held to its rules too. Links added or edited here must also be web links, which - /// social v1 requires; stored ones keep their scheme. `rejectedIndex` is a link pubky.app already refused. + /// 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. `rejectedIndex` is a + /// link pubky.app already refused. static func linkErrors( links: [PubkyProfileData.Link], storedLinks: [PubkyProfileData.Link], rejectedIndex: Int? = nil ) -> [Int: PubkyAppLinkError] { - guard links != storedLinks else { return [:] } + 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() { diff --git a/BitkitTests/PubkyAppLinkTests.swift b/BitkitTests/PubkyAppLinkTests.swift index 4b205c2877..cdec9d02d8 100644 --- a/BitkitTests/PubkyAppLinkTests.swift +++ b/BitkitTests/PubkyAppLinkTests.swift @@ -145,6 +145,13 @@ final class PubkyAppLinkTests: XCTestCase { 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 testStoredLinkIsCheckedOnceLinksChange() { let stored = [ PubkyProfileData.Link(label: String(repeating: "x", count: 101), url: "https://example.com"), From db99adb2c5dbba2a029a58bd695ca9f952e62fa4 Mon Sep 17 00:00:00 2001 From: jvsena42 Date: Thu, 26 Nov 2026 17:00:51 -0300 Subject: [PATCH 7/7] fix: keep a pubky.app link refusal on its link until it changes Co-Authored-By: Claude Opus 5.5 --- Bitkit/Managers/PubkyAppProfileStore.swift | 12 +++++----- Bitkit/Views/Profile/EditProfileView.swift | 15 +++++------- BitkitTests/PubkyAppLinkTests.swift | 27 ++++++++++++++++++---- 3 files changed, 34 insertions(+), 20 deletions(-) diff --git a/Bitkit/Managers/PubkyAppProfileStore.swift b/Bitkit/Managers/PubkyAppProfileStore.swift index e12ee990b1..fa0a14eaa6 100644 --- a/Bitkit/Managers/PubkyAppProfileStore.swift +++ b/Bitkit/Managers/PubkyAppProfileStore.swift @@ -602,19 +602,19 @@ actor PubkyAppProfileStore { /// 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. `rejectedIndex` is a - /// link pubky.app already refused. + /// 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], - rejectedIndex: Int? = nil + 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 index == rejectedIndex || link.url.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + 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 @@ -629,9 +629,9 @@ actor PubkyAppProfileStore { /// 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 rejectedLinkIndex(for error: Error, links: [PubkyProfileData.Link]) -> Int? { + 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.firstIndex { link in + return links.first { link in let url = linkUrl(link.url) ?? link.url return !isSocialV1WebUrl(url) } diff --git a/Bitkit/Views/Profile/EditProfileView.swift b/Bitkit/Views/Profile/EditProfileView.swift index ebe71a26a0..003a3f6fdc 100644 --- a/Bitkit/Views/Profile/EditProfileView.swift +++ b/Bitkit/Views/Profile/EditProfileView.swift @@ -11,7 +11,7 @@ struct EditProfileView: View { @State private var bio: String = "" @State private var links: [ProfileLinkInput] = [] @State private var storedLinks: [PubkyProfileData.Link] = [] - @State private var rejectedLinkIndex: Int? + @State private var rejectedLink: PubkyProfileData.Link? @State private var tags: [String] = [] @State private var baseRevision: String? @State private var baseTagsUnread = false @@ -69,9 +69,6 @@ struct EditProfileView: View { .task { loadProfileData() } - .onChange(of: linkData) { - rejectedLinkIndex = nil - } .onChange(of: username) { _, value in if let capped = PubkyAppProfileLimits.capped(value, to: PubkyAppProfileLimits.nameLength.upperBound) { username = capped @@ -108,7 +105,7 @@ struct EditProfileView: View { } private var linkErrors: [Int: PubkyAppLinkError] { - PubkyAppProfileStore.linkErrors(links: linkData, storedLinks: storedLinks, rejectedIndex: rejectedLinkIndex) + PubkyAppProfileStore.linkErrors(links: linkData, storedLinks: storedLinks, rejectedLink: rejectedLink) } // MARK: - Avatar Picker @@ -174,7 +171,7 @@ struct EditProfileView: View { bio = profile.bio links = profile.links.map { ProfileLinkInput(label: $0.label, url: $0.url) } storedLinks = profile.links.map { PubkyProfileData.Link(label: $0.label, url: $0.url) } - rejectedLinkIndex = nil + rejectedLink = nil tags = profile.tags baseRevision = profile.revision baseTagsUnread = profile.tagsUnread @@ -272,11 +269,11 @@ struct EditProfileView: View { navigation.navigateBack() } catch { Logger.error("Failed to save profile: \(error)", context: "EditProfileView") - let rejected = PubkyAppProfileStore.rejectedLinkIndex(for: error, links: savedLinks) - let description = rejected.map { t("profile__edit_link_error", variables: ["label": savedLinks[$0].label]) } + 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 { - rejectedLinkIndex = rejected + rejectedLink = rejected } if case PubkyAppProfileError.changedElsewhere = error { await pubkyProfile.loadProfile() diff --git a/BitkitTests/PubkyAppLinkTests.swift b/BitkitTests/PubkyAppLinkTests.swift index cdec9d02d8..4a1b8b77fc 100644 --- a/BitkitTests/PubkyAppLinkTests.swift +++ b/BitkitTests/PubkyAppLinkTests.swift @@ -70,7 +70,7 @@ final class PubkyAppLinkTests: XCTestCase { PubkyProfileData.Link(label: "Email", url: "mailto:me@example.com"), ] let rejection: PaykitError = .Protocol(code: "protocol_error", context: PubkyAppProfileStore.paykitNonWebLinkContext) - XCTAssertEqual(PubkyAppProfileStore.rejectedLinkIndex(for: rejection, links: links), 1) + XCTAssertEqual(PubkyAppProfileStore.rejectedLink(for: rejection, links: links), links[1]) } func testBlankUrlIsLeftToTheCaller() { @@ -137,7 +137,7 @@ final class PubkyAppLinkTests: XCTestCase { ) 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.rejectedLinkIndex(for: invalidUri, links: links)) + XCTAssertNil(PubkyAppProfileStore.rejectedLink(for: invalidUri, links: links)) } func testStoredLinksAreNotCheckedWhileUnchanged() { @@ -152,6 +152,23 @@ final class PubkyAppLinkTests: XCTestCase { 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"), @@ -179,11 +196,11 @@ final class PubkyAppLinkTests: XCTestCase { code: "protocol_error", context: "Pubky profile link URL must be a canonical http or https URL" ) - XCTAssertEqual(PubkyAppProfileStore.rejectedLinkIndex(for: rejection, links: links), 1) + 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.rejectedLinkIndex(for: other, links: links)) + XCTAssertNil(PubkyAppProfileStore.rejectedLink(for: other, links: links)) XCTAssertEqual( - PubkyAppProfileStore.linkErrors(links: links + [], storedLinks: [], rejectedIndex: 1)[1], + PubkyAppProfileStore.linkErrors(links: links + [], storedLinks: [], rejectedLink: links[1])[1], .urlInvalid ) }