Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 86 additions & 12 deletions Bitkit/Models/PubkyAuthRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -189,19 +189,90 @@ struct PubkyAuthRequest {
isSignup && (!isGrantSignup || !hasIdentity)
}

/// The network origin that receives the authorization. This is a delivery destination, not a service identity.
var relayOrigin: String? {
guard let components = URLComponents(string: relay),
let scheme = components.scheme?.lowercased(),
["http", "https"].contains(scheme),
let host = components.host?.lowercased(),
!host.isEmpty
else {
return nil
/// The relay URL that receives the authorization, without user info or fragment so the host cannot be disguised.
/// This is a delivery destination, not a service identity. Nil only when the request has no relay.
var relayDisplayUrl: String? {
Self.displayRelay(relay)
}

/// The relay as shown on the approval sheet: scheme, host, port, path and query, exactly as the Pubky SDK's URL parser
/// keeps them. Nil when `relay` is not already in that form apart from letter case, user info, the fragment and a
/// missing root path: a space, control or non-ASCII characters, a backslash before the query, characters the parser
/// percent-encodes in the path or in the query, a missing, percent-encoded or non-canonical host, a default, padded
/// or out-of-range port, or a `.` or `..` path segment.
static func displayRelay(_ relay: String) -> String? {
// rust-url 2.5.8 (`url/src/parser.rs`): the `PATH` set is percent-encoded in a path and a backslash becomes a
// slash; a query of an http(s) URL percent-encodes the `SPECIAL_QUERY` set.
let pathRewritten = "\\\"<>`{}"
let queryRewritten = "\"<>'"
guard relay.unicodeScalars.allSatisfy({ $0.value > 0x20 && $0.value < 0x7F }),
let schemeEnd = relay.range(of: "://"), schemeEnd.lowerBound > relay.startIndex
else { return nil }
let scheme = relay[..<schemeEnd.lowerBound].lowercased()
guard let defaultPort = ["http": 80, "https": 443][scheme] else { return nil }
let rest = relay[schemeEnd.upperBound...]
let authorityEnd = rest.firstIndex { "/?#".contains($0) } ?? rest.endIndex
let authority = rest[..<authorityEnd]
let hostPort = authority[(authority.lastIndex(of: "@").map { authority.index(after: $0) } ?? authority.startIndex)...]
.lowercased()
let pathAndQuery = rest[authorityEnd...].prefix { $0 != "#" }
let path = pathAndQuery.prefix { $0 != "?" }
let query = pathAndQuery[path.endIndex...].dropFirst()
let hasDotSegment = path.split(separator: "/", omittingEmptySubsequences: false)
.contains { [".", ".."].contains($0.lowercased().replacingOccurrences(of: "%2e", with: ".")) }
let isRewritten = authority.contains("\\") || path.contains { pathRewritten.contains($0) }
|| query.contains { queryRewritten.contains($0) } || hasDotSegment
guard !isRewritten, isUnchangedRelayHostPort(hostPort, defaultPort: defaultPort) else { return nil }
return "\(scheme)://\(hostPort)\(pathAndQuery.hasPrefix("/") ? "" : "/")\(pathAndQuery)"
}

private static func isUnchangedRelayHostPort(_ hostPort: String, defaultPort: Int) -> Bool {
let matches = { (pattern: String, value: String) in
value.range(of: "^(?:\(pattern))$", options: .regularExpression) != nil && !value.contains("\n")
}
guard matches(#"(\[[0-9a-f:.]+\]|[a-z0-9._~-]+)(:[0-9]{1,5})?"#, hostPort) else { return false }
let portStart = hostPort.hasSuffix("]") ? nil : hostPort.lastIndex(of: ":")
let host = String(hostPort[..<(portStart ?? hostPort.endIndex)])
if let portStart {
let portText = String(hostPort[hostPort.index(after: portStart)...])
guard let port = Int(portText), String(port) == portText, port <= 65535, port != defaultPort else { return false }
}
if host.hasPrefix("[") {
return isCanonicalIpv6(String(host.dropFirst().dropLast()))
}
// A last label that reads as a number makes the SDK's URL parser treat the whole host as an IPv4 address.
let trimmedHost = host.hasSuffix(".") ? String(host.dropLast()) : host
let lastLabel = String(trimmedHost.split(separator: ".", omittingEmptySubsequences: false).last ?? "")
let octet = "(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])"
return !matches("[0-9]+|0x[0-9a-f]*", lastLabel) || matches("(\(octet)\\.){3}\(octet)", host)
}

private static func isCanonicalIpv6(_ address: String) -> Bool {
let halves = address.components(separatedBy: "::")
let head = halves[0].split(separator: ":").map(String.init)
let tail = halves.count > 1 ? halves[1].split(separator: ":").map(String.init) : []
let missing = 8 - head.count - tail.count
let isComplete = halves.count == 1 ? missing == 0 : halves.count == 2 && missing >= 1
guard isComplete, !address.contains(".") else { return false }
let parsed = (head + Array(repeating: "0", count: missing) + tail).map { Int($0, radix: 16) }
let groups = parsed.compactMap { $0 }
guard groups.count == 8, groups.allSatisfy({ $0 <= 0xFFFF }) else { return false }
var runStart = 0
var runLength = 0
var index = 0
while index < groups.count {
let end = groups[index...].firstIndex { $0 != 0 } ?? groups.count
if end - index > runLength {
runStart = index
runLength = end - index
}
index = max(end, index + 1)
}

let port = components.port.map { ":\($0)" } ?? ""
return "\(scheme)://\(host)\(port)"
let hex = { (part: ArraySlice<Int>) in part.map { String($0, radix: 16) }.joined(separator: ":") }
let canonical = runLength < 2
? hex(groups[...])
: "\(hex(groups[..<runStart]))::\(hex(groups[(runStart + runLength)...]))"
return canonical == address
}

static func isProtocolURL(_ value: String) -> Bool {
Expand Down Expand Up @@ -344,6 +415,9 @@ struct PubkyAuthRequest {
.compactMap { extractServiceName($0.path) }
.filter { seenServiceNames.insert($0).inserted }
let bitkitClaim = try parseBitkitClaim(url: url, capabilities: capabilities, requiresBitkitClaim: requiresBitkitClaim)
guard relay.isEmpty || displayRelay(relay) != nil else {
throw PubkyAuthRequestError.invalidUrl
}
let expectedSigner = try parseExpectedSigner(url: url)
return PubkyAuthRequest(
rawUrl: url,
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Resources/Localization/ar.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -764,7 +764,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>اربح BITCOIN</accent>\nمن\nمحتواك";
"pubky_auth__watch_only_account_xpub_error" = "تعذر على Bitkit إنشاء xpub صالح للحساب.";
"pubky_auth__trust_warning" = "تأكد من أنك تثق بالخدمة والمتصفح والجهاز قبل التفويض باستخدام pubky الخاص بك.";
"pubky_auth__authorization_relay" = "مُرحّل التفويض";
"pubky_auth__authorization_relay" = "المُرحّل";
"pubky_auth__authorizing" = "جارٍ التفويض...";
"pubky_auth__success_title" = "تم التفويض بنجاح";
"pubky_auth__success_prefix" = "لقد فوّضت باستخدام pubky ";
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Resources/Localization/ca.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -848,7 +848,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>GUANYA BITCOIN</accent>\nAMB EL TEU\nCONTINGUT";
"pubky_auth__watch_only_account_xpub_error" = "Bitkit no ha pogut crear un xpub de compte vàlid.";
"pubky_auth__trust_warning" = "Assegura't que confies en el servei, el navegador i el dispositiu abans d'autoritzar amb el teu pubky.";
"pubky_auth__authorization_relay" = "RELÉ D'AUTORITZACIÓ";
"pubky_auth__authorization_relay" = "RELÉ";
"pubky_auth__authorizing" = "Autoritzant...";
"pubky_auth__success_title" = "Autorització correcta";
"pubky_auth__success_prefix" = "T'has autoritzat amb el pubky ";
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Resources/Localization/cs.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -907,7 +907,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>VYDĚLÁVEJTE BITCOIN</accent>\nZE SVÉHO\nOBSAHU";
"pubky_auth__watch_only_account_xpub_error" = "Bitkit nemohl vytvořit platný xpub účtu.";
"pubky_auth__trust_warning" = "Než se autorizujete pomocí svého pubky, ujistěte se, že službě, prohlížeči a zařízení důvěřujete.";
"pubky_auth__authorization_relay" = "AUTORIZAČNÍ RELAY";
"pubky_auth__authorization_relay" = "RELAY";
"pubky_auth__authorizing" = "Autorizování...";
"pubky_auth__success_title" = "Autorizace proběhla úspěšně";
"pubky_auth__success_prefix" = "Autorizovali jste se pomocí pubky ";
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Resources/Localization/de.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -905,7 +905,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>VERDIENE BITCOIN</accent>\nMIT DEINEN\nINHALTEN";
"pubky_auth__watch_only_account_xpub_error" = "Bitkit konnte keinen gültigen Konto-xpub erstellen.";
"pubky_auth__trust_warning" = "Stelle sicher, dass du dem Dienst, dem Browser und dem Gerät vertraust, bevor du dich mit deinem pubky autorisierst.";
"pubky_auth__authorization_relay" = "AUTORISIERUNGS-RELAY";
"pubky_auth__authorization_relay" = "RELAY";
"pubky_auth__authorizing" = "Autorisiere...";
"pubky_auth__success_title" = "Autorisierung erfolgreich";
"pubky_auth__success_prefix" = "Du hast dich mit dem pubky ";
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Resources/Localization/el.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -795,7 +795,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>ΚΕΡΔΙΣΤΕ BITCOIN</accent>\nΑΠΟ ΤΟ\nΠΕΡΙΕΧΟΜΕΝΟ ΣΑΣ";
"pubky_auth__watch_only_account_xpub_error" = "Το Bitkit δεν μπόρεσε να δημιουργήσει έγκυρο xpub λογαριασμού.";
"pubky_auth__trust_warning" = "Βεβαιωθείτε ότι εμπιστεύεστε την υπηρεσία, τον browser και τη συσκευή πριν εξουσιοδοτήσετε με το pubky σας.";
"pubky_auth__authorization_relay" = "ΑΝΑΜΕΤΑΔΟΤΗΣ ΕΞΟΥΣΙΟΔΟΤΗΣΗΣ";
"pubky_auth__authorization_relay" = "ΑΝΑΜΕΤΑΔΟΤΗΣ";
"pubky_auth__authorizing" = "Εξουσιοδότηση...";
"pubky_auth__success_title" = "Επιτυχής Εξουσιοδότηση";
"pubky_auth__success_prefix" = "Εξουσιοδοτήσατε με το pubky ";
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Resources/Localization/en.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -895,7 +895,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>EARN MONEY</accent>\nFROM YOUR\nCONTENT";
"pubky_auth__watch_only_account_xpub_error" = "Bitkit could not create a valid account xpub.";
"pubky_auth__trust_warning" = "Make sure you trust the service, browser, and device before authorizing with your pubky.";
"pubky_auth__authorization_relay" = "AUTHORIZATION RELAY";
"pubky_auth__authorization_relay" = "RELAY";
"pubky_auth__authorizing" = "Authorizing...";
"pubky_auth__success_title" = "Authorization Successful";
"pubky_auth__success_prefix" = "You authorized with pubky ";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -908,7 +908,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>GANE BITCOIN</accent>\nCON SU\nCONTENIDO";
"pubky_auth__watch_only_account_xpub_error" = "Bitkit no pudo crear un xpub de cuenta válido.";
"pubky_auth__trust_warning" = "Asegúrese de confiar en el servicio, el navegador y el dispositivo antes de autorizar con su pubky.";
"pubky_auth__authorization_relay" = "RELAY DE AUTORIZACIÓN";
"pubky_auth__authorization_relay" = "RELAY";
"pubky_auth__authorizing" = "Autorizando...";
"pubky_auth__success_title" = "Autorización exitosa";
"pubky_auth__success_prefix" = "Autorizó con el pubky ";
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Resources/Localization/es.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -856,7 +856,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>GANE BITCOIN</accent>\nCON SU\nCONTENIDO";
"pubky_auth__watch_only_account_xpub_error" = "Bitkit no pudo crear un xpub de cuenta válido.";
"pubky_auth__trust_warning" = "Asegúrese de que confía en el servicio, el navegador y el dispositivo antes de autorizar con su pubky.";
"pubky_auth__authorization_relay" = "RELÉ DE AUTORIZACIÓN";
"pubky_auth__authorization_relay" = "RELÉ";
"pubky_auth__authorizing" = "Autorizando...";
"pubky_auth__success_title" = "Autorización correcta";
"pubky_auth__success_prefix" = "Ha autorizado con el pubky ";
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Resources/Localization/fr.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -908,7 +908,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>GAGNEZ DES BITCOINS</accent>\nGRÂCE À VOTRE\nCONTENU";
"pubky_auth__watch_only_account_xpub_error" = "Bitkit n'a pas pu créer de xpub de compte valide.";
"pubky_auth__trust_warning" = "Assurez-vous de faire confiance au service, au navigateur et à l'appareil avant de vous authentifier avec votre pubky.";
"pubky_auth__authorization_relay" = "RELAIS D'AUTORISATION";
"pubky_auth__authorization_relay" = "RELAIS";
"pubky_auth__authorizing" = "Autorisation…";
"pubky_auth__success_title" = "Autorisation réussie";
"pubky_auth__success_prefix" = "Vous vous êtes authentifié avec le pubky ";
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Resources/Localization/it.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -889,7 +889,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>GUADAGNA BITCOIN</accent>\nCON I TUOI\nCONTENUTI";
"pubky_auth__watch_only_account_xpub_error" = "Bitkit non è riuscito a creare un xpub valido per l'account.";
"pubky_auth__trust_warning" = "Assicurati di fidarti del servizio, del browser e del dispositivo prima di autorizzare con il tuo pubky.";
"pubky_auth__authorization_relay" = "RELAY DI AUTORIZZAZIONE";
"pubky_auth__authorization_relay" = "RELAY";
"pubky_auth__authorizing" = "Autorizzazione...";
"pubky_auth__success_title" = "Autorizzazione Riuscita";
"pubky_auth__success_prefix" = "Hai autorizzato con il pubky ";
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Resources/Localization/nl.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -905,7 +905,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>VERDIEN BITCOIN</accent>\nMET UW\nCONTENT";
"pubky_auth__watch_only_account_xpub_error" = "Bitkit kon geen geldige account-xpub aanmaken.";
"pubky_auth__trust_warning" = "Zorg dat u de service, browser en het apparaat vertrouwt voordat u met uw pubky autoriseert.";
"pubky_auth__authorization_relay" = "AUTORISATIERELAY";
"pubky_auth__authorization_relay" = "RELAY";
"pubky_auth__authorizing" = "Autoriseren...";
"pubky_auth__success_title" = "Autorisatie geslaagd";
"pubky_auth__success_prefix" = "U hebt geautoriseerd met pubky ";
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Resources/Localization/pl.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -907,7 +907,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>ZARABIAJ BITCOINY</accent>\nNA SWOICH\nTREŚCIACH";
"pubky_auth__watch_only_account_xpub_error" = "Bitkit nie mógł utworzyć prawidłowego xpub konta.";
"pubky_auth__trust_warning" = "Upewnij się, że ufasz usłudze, przeglądarce i urządzeniu, zanim autoryzujesz za pomocą swojego pubky.";
"pubky_auth__authorization_relay" = "PRZEKAŹNIK AUTORYZACJI";
"pubky_auth__authorization_relay" = "PRZEKAŹNIK";
"pubky_auth__authorizing" = "Autoryzowanie...";
"pubky_auth__success_title" = "Autoryzacja zakończona";
"pubky_auth__success_prefix" = "Autoryzowano za pomocą pubky ";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -907,7 +907,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>GANHE BITCOIN</accent>\nCOM O SEU\nCONTEÚDO";
"pubky_auth__watch_only_account_xpub_error" = "A Bitkit não conseguiu criar um xpub de conta válido.";
"pubky_auth__trust_warning" = "Certifique-se de que confia no serviço, no navegador e no dispositivo antes de autorizar com sua pubky.";
"pubky_auth__authorization_relay" = "RELAY DE AUTORIZAÇÃO";
"pubky_auth__authorization_relay" = "RELAY";
"pubky_auth__authorizing" = "Autorizando...";
"pubky_auth__success_title" = "Autorização Concluída";
"pubky_auth__success_prefix" = "Você autorizou com a pubky ";
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Resources/Localization/pt.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -813,7 +813,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>GANHE BITCOIN</accent>\nCOM O SEU\nCONTEÚDO";
"pubky_auth__watch_only_account_xpub_error" = "A Bitkit não conseguiu criar uma xpub de conta válida.";
"pubky_auth__trust_warning" = "Confirme que confia no serviço, no navegador e no dispositivo antes de autorizar com o seu pubky.";
"pubky_auth__authorization_relay" = "RELAY DE AUTORIZAÇÃO";
"pubky_auth__authorization_relay" = "RELAY";
"pubky_auth__authorizing" = "A autorizar...";
"pubky_auth__success_title" = "Autorização concluída";
"pubky_auth__success_prefix" = "Autorizou com o pubky ";
Expand Down
2 changes: 1 addition & 1 deletion Bitkit/Resources/Localization/ru.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -903,7 +903,7 @@
"pubky_auth__watch_only_intro_title" = "<accent>ЗАРАБАТЫВАЙТЕ БИТКОИН</accent>\nНА СВОЁМ\nКОНТЕНТЕ";
"pubky_auth__watch_only_account_xpub_error" = "Bitkit не смог создать действительный xpub аккаунта.";
"pubky_auth__trust_warning" = "Убедитесь, что вы доверяете сервису, браузеру и устройству, прежде чем авторизоваться с вашим pubky.";
"pubky_auth__authorization_relay" = "РЕТРАНСЛЯТОР АВТОРИЗАЦИИ";
"pubky_auth__authorization_relay" = "РЕТРАНСЛЯТОР";
"pubky_auth__authorizing" = "Авторизация...";
"pubky_auth__success_title" = "Авторизация Выполнена";
"pubky_auth__success_prefix" = "Вы авторизовались с pubky ";
Expand Down
47 changes: 36 additions & 11 deletions Bitkit/Views/Sheets/PubkyAuthApproval/PubkyAuthApprovalSheet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -438,22 +438,29 @@ struct PubkyAuthApprovalSheet: View {
.padding(.bottom, 32)
}

if let relayOrigin = config.request.relayOrigin {
relayOriginSection(relayOrigin)
.padding(.bottom, 32)
}
let relayUrl = config.request.relayDisplayUrl
let showsPaykitAccess = config.request.bitkitClaim?.includesPaykitAccess == true

if !config.request.permissions.isEmpty {
permissionsSection
if relayUrl != nil || showsPaykitAccess {
sectionDivider
}
}

if let relayUrl {
relaySection(relayUrl)
if showsPaykitAccess {
sectionDivider
}
}

if config.request.bitkitClaim?.includesPaykitAccess == true {
if showsPaykitAccess {
VStack(alignment: .leading, spacing: 8) {
CaptionMText(t("pubky_auth__details"), textColor: .white64).frame(minHeight: 18)
BodySText(t("pubky_auth__paykit_access_description"), textColor: .textPrimary, kerning: 0, lineHeight: 20)
.fixedSize(horizontal: false, vertical: true)
}
.padding(.top, 32)
.accessibilityElement(children: .contain)
.accessibilityIdentifier("PubkyAuthPaykitAccess")
}
Expand Down Expand Up @@ -539,15 +546,33 @@ struct PubkyAuthApprovalSheet: View {
}
}

private func relayOriginSection(_ relayOrigin: String) -> some View {
private func relaySection(_ relayUrl: String) -> some View {
VStack(alignment: .leading, spacing: 8) {
CaptionMText(t("pubky_auth__authorization_relay"), textColor: .white64)
BodySSBText(relayOrigin)
.accessibilityIdentifier("PubkyAuthRelayOrigin")
CustomDivider(color: .white10)
CaptionMText(t("pubky_auth__authorization_relay"), textColor: .white64).frame(minHeight: 18)
HStack(alignment: .top, spacing: 4) {
Image("globe")
.resizable()
.scaledToFit()
.foregroundColor(.white)
.frame(width: 16, height: 16)
.padding(.top, 2)
.accessibilityHidden(true)

BodySSBText(pubkyAuthLiteralText(relayUrl))
.fixedSize(horizontal: false, vertical: true)
.textSelection(.enabled)
.accessibilityIdentifier("PubkyAuthRelayOrigin")

Spacer(minLength: 0)
}
}
}

private var sectionDivider: some View {
CustomDivider(color: .white10)
.padding(.vertical, 12)
}

private var successDescriptionText: some View {
let authorization = requesterText.isEmpty
? t("pubky_auth__success_prefix") + "<accent>" + truncatedPublicKey + "</accent>"
Expand Down
Loading
Loading