diff --git a/Bitkit/Models/PubkyAuthRequest.swift b/Bitkit/Models/PubkyAuthRequest.swift index 9645c1fcb3..c5c31bfe1c 100644 --- a/Bitkit/Models/PubkyAuthRequest.swift +++ b/Bitkit/Models/PubkyAuthRequest.swift @@ -129,6 +129,7 @@ enum PubkyAuthRequestError: Error, Equatable { case duplicateSecret case unsupportedBitkitClaim(String) case invalidBitkitClaimCapabilities + case signerMismatch(expectedSigner: String) } // MARK: - PubkyAuth Permission @@ -172,6 +173,8 @@ struct PubkyAuthRequest { let homeserverPublicKey: String? let signupToken: String? let authorizationUrl: String? + /// The only pubky that may approve this request (`spk`), as bare z-base-32. Nil when the request names none. + let expectedSigner: String? var isSignup: Bool { Self.isSignupURL(rawUrl) @@ -341,6 +344,7 @@ struct PubkyAuthRequest { .compactMap { extractServiceName($0.path) } .filter { seenServiceNames.insert($0).inserted } let bitkitClaim = try parseBitkitClaim(url: url, capabilities: capabilities, requiresBitkitClaim: requiresBitkitClaim) + let expectedSigner = try parseExpectedSigner(url: url) return PubkyAuthRequest( rawUrl: url, kind: kind, @@ -352,10 +356,54 @@ struct PubkyAuthRequest { bitkitClaim: bitkitClaim, homeserverPublicKey: homeserverPublicKey, signupToken: signupToken, - authorizationUrl: authorizationUrl + authorizationUrl: authorizationUrl, + expectedSigner: expectedSigner ) } + /// Reads the pubky a sign-in request must be approved with. Absent is fine; a repeated value or anything other than + /// a bare canonical z-base-32 key makes the request invalid, as in the Pubky SDK parser for `signin_grant`. Only + /// signup requests ignore the parameter, so a sign-in this parser reads differently from the SDK is still held to it. + /// Upstream reads `spk` for `signin_grant` alone (pubky/pubky-homeserver at d95161af3e: + /// `pubky-sdk/src/actors/auth/deep_links/signin_grant.rs:106` is the only caller of `parse_expected_signer`, + /// `deep_link.rs:211` tests that `signin` and `signup_grant` ignore it, `docs/AUTH.md:81`). + static func parseExpectedSigner(url: String) throws -> String? { + // The SDK's URL parser drops tabs and line breaks, while `URLComponents` percent-encodes them, so a control + // character could hide `spk` from this parser only. + guard !url.unicodeScalars.contains(where: { $0.value < 0x20 || $0.value == 0x7F }), + let components = URLComponents(string: url) + else { + throw PubkyAuthRequestError.invalidUrl + } + guard !isSignupURL(components) else { return nil } + let values = components.queryItems?.filter { $0.name == "spk" }.map { $0.value ?? "" } ?? [] + guard let value = values.first else { return nil } + // 52 z-base-32 symbols encode 260 bits, so the last symbol of a 32-byte key carries a single bit. + guard values.count == 1, + value.range(of: "^[ybndrfg8ejkmcpqxot1uwisza345h769]{51}[yo]$", options: .regularExpression) != nil, + value.utf8.count == 52, + (try? Paykit.normalizePubkyPublicKey(value: value)) != nil + else { + throw PubkyAuthRequestError.invalidUrl + } + return value + } + + /// Whether `publicKey`, bare or with the `pubky` prefix, may approve a request naming `expectedSigner`. + static func isExpectedSigner(_ expectedSigner: String?, publicKey: String) -> Bool { + guard let expectedSigner else { return true } + let isPrefixed = publicKey.count == 57 && publicKey.hasPrefix("pubky") + return expectedSigner == (isPrefixed ? String(publicKey.dropFirst(5)) : publicKey) + } + + /// Throws before anything is signed when `authUrl` names a pubky other than the one `secretKeyHex` signs with. + static func requireExpectedSigner(authUrl: String, signerPublicKey: () throws -> String) throws { + guard let expectedSigner = try parseExpectedSigner(url: authUrl) else { return } + guard try isExpectedSigner(expectedSigner, publicKey: signerPublicKey()) else { + throw PubkyAuthRequestError.signerMismatch(expectedSigner: expectedSigner) + } + } + private static func ringAuthorizationUrl(relay: String, secret: String, capabilities: String) -> String { "pubkyauth:///?relay=\(encodeQueryComponent(relay))" + "&secret=\(encodeQueryComponent(secret))&caps=\(encodeQueryComponent(capabilities))" diff --git a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings index 8843b0b0ed..d8e0c16e47 100644 --- a/Bitkit/Resources/Localization/ar.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ar.lproj/Localizable.strings @@ -768,6 +768,7 @@ "pubky_auth__use_ring" = "استخدام Pubky Ring"; "pubky_auth__use_ring_desc" = "لا يستطيع Bitkit قراءة مفتاح هذا الـ pubky من Pubky Ring. افتح Pubky Ring للموافقة على هذا الطلب."; "pubky_auth__invalid_request" = "طلب مصادقة غير صالح"; +"pubky_auth__other_pubky" = "هذا الطلب موجّه إلى {pubky}، وليس إلى pubky هذه المحفظة."; "pubky_auth__homeserver" = "الخادم الرئيسي"; "pubky_auth__signup_description" = "أنشئ هوية Pubky جديدة على هذا الخادم الرئيسي. تابع فقط إذا كنت تثق به."; "pubky_auth__approval_failed" = "فشل التفويض"; diff --git a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings index b57827a2bb..0bba190aba 100644 --- a/Bitkit/Resources/Localization/ca.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ca.lproj/Localizable.strings @@ -852,6 +852,7 @@ "pubky_auth__use_ring" = "Utilitzar Pubky Ring"; "pubky_auth__use_ring_desc" = "Bitkit no pot llegir la clau d'aquest pubky des de Pubky Ring. Obre Pubky Ring per aprovar aquesta sol·licitud."; "pubky_auth__invalid_request" = "Sol·licitud d'autenticació no vàlida"; +"pubky_auth__other_pubky" = "Aquesta sol·licitud és per a {pubky}, no per al pubky d'aquesta cartera."; "pubky_auth__homeserver" = "Homeserver"; "pubky_auth__signup_description" = "Crea una nova identitat Pubky en aquest homeserver. Continua només si hi confies."; "pubky_auth__approval_failed" = "Ha fallat l'autorització"; diff --git a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings index a1d8df37d6..a86e9a388b 100644 --- a/Bitkit/Resources/Localization/cs.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/cs.lproj/Localizable.strings @@ -911,6 +911,7 @@ "pubky_auth__use_ring" = "Použít Pubky Ring"; "pubky_auth__use_ring_desc" = "Bitkit nemůže z Pubky Ring načíst klíč pro tento pubky. Pro schválení tohoto požadavku otevřete Pubky Ring."; "pubky_auth__invalid_request" = "Neplatný požadavek na ověření"; +"pubky_auth__other_pubky" = "Tento požadavek je určen pro {pubky}, ne pro pubky této peněženky."; "pubky_auth__homeserver" = "Homeserver"; "pubky_auth__signup_description" = "Vytvořte si na tomto homeserveru novou identitu Pubky. Pokračujte, jen pokud mu důvěřujete."; "pubky_auth__approval_failed" = "Autorizace se nezdařila"; diff --git a/Bitkit/Resources/Localization/de.lproj/Localizable.strings b/Bitkit/Resources/Localization/de.lproj/Localizable.strings index 53e150e755..1289046d33 100644 --- a/Bitkit/Resources/Localization/de.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/de.lproj/Localizable.strings @@ -909,6 +909,7 @@ "pubky_auth__use_ring" = "Pubky Ring verwenden"; "pubky_auth__use_ring_desc" = "Bitkit kann den Schlüssel für diesen pubky nicht aus Pubky Ring lesen. Öffne Pubky Ring, um diese Anfrage zu genehmigen."; "pubky_auth__invalid_request" = "Ungültige Autorisierungsanfrage"; +"pubky_auth__other_pubky" = "Diese Anfrage ist für {pubky} bestimmt, nicht für den Pubky dieses Wallets."; "pubky_auth__homeserver" = "Homeserver"; "pubky_auth__signup_description" = "Erstelle eine neue Pubky-Identität auf diesem Homeserver. Fahre nur fort, wenn du ihm vertraust."; "pubky_auth__approval_failed" = "Autorisierung fehlgeschlagen"; diff --git a/Bitkit/Resources/Localization/el.lproj/Localizable.strings b/Bitkit/Resources/Localization/el.lproj/Localizable.strings index 9e30774ded..a96ac45b64 100644 --- a/Bitkit/Resources/Localization/el.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/el.lproj/Localizable.strings @@ -799,6 +799,7 @@ "pubky_auth__use_ring" = "Χρήση Pubky Ring"; "pubky_auth__use_ring_desc" = "Το Bitkit δεν μπορεί να διαβάσει το κλειδί αυτού του pubky από το Pubky Ring. Άνοιξε το Pubky Ring για να εγκρίνεις αυτό το αίτημα."; "pubky_auth__invalid_request" = "Μη έγκυρο αίτημα εξουσιοδότησης"; +"pubky_auth__other_pubky" = "Αυτό το αίτημα προορίζεται για το {pubky}, όχι για το pubky αυτού του πορτοφολιού."; "pubky_auth__homeserver" = "Homeserver"; "pubky_auth__signup_description" = "Δημιούργησε μια νέα ταυτότητα Pubky σε αυτόν τον homeserver. Συνέχισε μόνο αν τον εμπιστεύεσαι."; "pubky_auth__approval_failed" = "Η Εξουσιοδότηση Απέτυχε"; diff --git a/Bitkit/Resources/Localization/en.lproj/Localizable.strings b/Bitkit/Resources/Localization/en.lproj/Localizable.strings index 9c1eb9e59c..fc2537145e 100644 --- a/Bitkit/Resources/Localization/en.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/en.lproj/Localizable.strings @@ -899,6 +899,7 @@ "pubky_auth__use_ring" = "Use Pubky Ring"; "pubky_auth__use_ring_desc" = "Bitkit can't read the key for this pubky from Pubky Ring. Open Pubky Ring to approve this request."; "pubky_auth__invalid_request" = "Invalid auth request"; +"pubky_auth__other_pubky" = "This request is for {pubky}, not this wallet's pubky."; "pubky_auth__homeserver" = "Homeserver"; "pubky_auth__signup_description" = "Create a new Pubky identity on this homeserver. Only continue if you trust it."; "pubky_auth__approval_failed" = "Authorization Failed"; diff --git a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings index 7fd85218d8..6801f2c660 100644 --- a/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es-419.lproj/Localizable.strings @@ -912,6 +912,7 @@ "pubky_auth__use_ring" = "Usar Pubky Ring"; "pubky_auth__use_ring_desc" = "Bitkit no puede leer la clave de este pubky desde Pubky Ring. Abra Pubky Ring para aprobar esta solicitud."; "pubky_auth__invalid_request" = "Solicitud de autenticación no válida"; +"pubky_auth__other_pubky" = "Esta solicitud es para {pubky}, no para el pubky de esta billetera."; "pubky_auth__homeserver" = "Homeserver"; "pubky_auth__signup_description" = "Cree una nueva identidad Pubky en este homeserver. Continúe solo si confía en él."; "pubky_auth__approval_failed" = "Falló la autorización"; diff --git a/Bitkit/Resources/Localization/es.lproj/Localizable.strings b/Bitkit/Resources/Localization/es.lproj/Localizable.strings index b9f3a5c6b9..d16741cd25 100644 --- a/Bitkit/Resources/Localization/es.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/es.lproj/Localizable.strings @@ -860,6 +860,7 @@ "pubky_auth__use_ring" = "Usar Pubky Ring"; "pubky_auth__use_ring_desc" = "Bitkit no puede leer la clave de este pubky desde Pubky Ring. Abra Pubky Ring para aprobar esta solicitud."; "pubky_auth__invalid_request" = "Solicitud de autenticación no válida"; +"pubky_auth__other_pubky" = "Esta solicitud es para {pubky}, no para el pubky de este monedero."; "pubky_auth__homeserver" = "Servidor principal"; "pubky_auth__signup_description" = "Cree una nueva identidad Pubky en este servidor principal. Continúe solo si confía en él."; "pubky_auth__approval_failed" = "Error de autorización"; diff --git a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings index cd930e6217..c8dd26753a 100644 --- a/Bitkit/Resources/Localization/fr.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/fr.lproj/Localizable.strings @@ -912,6 +912,7 @@ "pubky_auth__use_ring" = "Utiliser Pubky Ring"; "pubky_auth__use_ring_desc" = "Bitkit ne peut pas lire la clé de ce pubky depuis Pubky Ring. Ouvrez Pubky Ring pour approuver cette demande."; "pubky_auth__invalid_request" = "Demande d'authentification non valide"; +"pubky_auth__other_pubky" = "Cette demande est destinée à {pubky}, pas au pubky de ce portefeuille."; "pubky_auth__homeserver" = "Serveur domestique"; "pubky_auth__signup_description" = "Créez une nouvelle identité Pubky sur ce serveur domestique. Ne continuez que si vous lui faites confiance."; "pubky_auth__approval_failed" = "Échec de l'autorisation"; diff --git a/Bitkit/Resources/Localization/it.lproj/Localizable.strings b/Bitkit/Resources/Localization/it.lproj/Localizable.strings index 6cff1d76e3..d269bd703b 100644 --- a/Bitkit/Resources/Localization/it.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/it.lproj/Localizable.strings @@ -893,6 +893,7 @@ "pubky_auth__use_ring" = "Usa Pubky Ring"; "pubky_auth__use_ring_desc" = "Bitkit non può leggere la chiave di questo pubky da Pubky Ring. Apri Pubky Ring per approvare questa richiesta."; "pubky_auth__invalid_request" = "Richiesta di autorizzazione non valida"; +"pubky_auth__other_pubky" = "Questa richiesta è per {pubky}, non per il pubky di questo portafoglio."; "pubky_auth__homeserver" = "Homeserver"; "pubky_auth__signup_description" = "Crea una nuova identità Pubky su questo homeserver. Continua solo se ti fidi."; "pubky_auth__approval_failed" = "Autorizzazione Non Riuscita"; diff --git a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings index 0389e30ef3..46e8070b7f 100644 --- a/Bitkit/Resources/Localization/nl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/nl.lproj/Localizable.strings @@ -909,6 +909,7 @@ "pubky_auth__use_ring" = "Pubky Ring gebruiken"; "pubky_auth__use_ring_desc" = "Bitkit kan de sleutel voor deze pubky niet uit Pubky Ring lezen. Open Pubky Ring om dit verzoek goed te keuren."; "pubky_auth__invalid_request" = "Ongeldig autorisatieverzoek"; +"pubky_auth__other_pubky" = "Dit verzoek is voor {pubky}, niet voor de pubky van deze wallet."; "pubky_auth__homeserver" = "Homeserver"; "pubky_auth__signup_description" = "Maak een nieuwe Pubky-identiteit aan op deze homeserver. Ga alleen verder als u deze vertrouwt."; "pubky_auth__approval_failed" = "Autorisatie mislukt"; diff --git a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings index 89dbd098e0..0afbef353c 100644 --- a/Bitkit/Resources/Localization/pl.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pl.lproj/Localizable.strings @@ -911,6 +911,7 @@ "pubky_auth__use_ring" = "Użyj Pubky Ring"; "pubky_auth__use_ring_desc" = "Bitkit nie może odczytać klucza tego pubky z Pubky Ring. Otwórz Pubky Ring, aby zatwierdzić to żądanie."; "pubky_auth__invalid_request" = "Nieprawidłowe żądanie autoryzacji"; +"pubky_auth__other_pubky" = "To żądanie jest przeznaczone dla {pubky}, a nie dla pubky tego portfela."; "pubky_auth__homeserver" = "Serwer domowy"; "pubky_auth__signup_description" = "Utwórz nową tożsamość Pubky na tym serwerze domowym. Kontynuuj tylko, jeśli mu ufasz."; "pubky_auth__approval_failed" = "Autoryzacja nie powiodła się"; diff --git a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings index 62f17f3d7e..d56f294334 100644 --- a/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt-BR.lproj/Localizable.strings @@ -911,6 +911,7 @@ "pubky_auth__use_ring" = "Usar Pubky Ring"; "pubky_auth__use_ring_desc" = "A Bitkit não consegue ler a chave desta pubky no Pubky Ring. Abra o Pubky Ring para aprovar esta solicitação."; "pubky_auth__invalid_request" = "Solicitação de autenticação inválida"; +"pubky_auth__other_pubky" = "Esta solicitação é para {pubky}, não para o pubky desta carteira."; "pubky_auth__homeserver" = "Homeserver"; "pubky_auth__signup_description" = "Crie uma nova identidade Pubky neste homeserver. Só continue se você confiar nele."; "pubky_auth__approval_failed" = "Falha na Autorização"; diff --git a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings index 561a186f10..2d69482aaf 100644 --- a/Bitkit/Resources/Localization/pt.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/pt.lproj/Localizable.strings @@ -817,6 +817,7 @@ "pubky_auth__use_ring" = "Usar o Pubky Ring"; "pubky_auth__use_ring_desc" = "A Bitkit não consegue ler a chave deste pubky a partir do Pubky Ring. Abra o Pubky Ring para aprovar este pedido."; "pubky_auth__invalid_request" = "Pedido de autenticação inválido"; +"pubky_auth__other_pubky" = "Este pedido destina-se a {pubky}, não ao pubky desta carteira."; "pubky_auth__homeserver" = "Homeserver"; "pubky_auth__signup_description" = "Crie uma nova identidade Pubky neste homeserver. Continue apenas se confiar nele."; "pubky_auth__approval_failed" = "Falha na autorização"; diff --git a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings index a19e3a9759..9fa1a95605 100644 --- a/Bitkit/Resources/Localization/ru.lproj/Localizable.strings +++ b/Bitkit/Resources/Localization/ru.lproj/Localizable.strings @@ -907,6 +907,7 @@ "pubky_auth__use_ring" = "Использовать Pubky Ring"; "pubky_auth__use_ring_desc" = "Bitkit не может прочитать ключ этого pubky из Pubky Ring. Откройте Pubky Ring, чтобы одобрить этот запрос."; "pubky_auth__invalid_request" = "Недействительный запрос авторизации"; +"pubky_auth__other_pubky" = "Этот запрос предназначен для {pubky}, а не для pubky этого кошелька."; "pubky_auth__homeserver" = "Домашний сервер"; "pubky_auth__signup_description" = "Создайте новый идентификатор Pubky на этом домашнем сервере. Продолжайте, только если доверяете ему."; "pubky_auth__approval_failed" = "Ошибка Авторизации"; diff --git a/Bitkit/Services/PubkyService.swift b/Bitkit/Services/PubkyService.swift index 8eb7216729..51c15f0171 100644 --- a/Bitkit/Services/PubkyService.swift +++ b/Bitkit/Services/PubkyService.swift @@ -95,6 +95,7 @@ enum PubkyService { secretKeyHex: String, sdkService: PaykitSdkService = .shared ) async throws { + try PubkyAuthRequest.requireExpectedSigner(authUrl: authUrl) { try pubkyPublicKeyFromSecret(secretKeyHex: secretKeyHex) } try await sdkService.republishIdentityBeforeApproval(publicKey: pubkyPublicKeyFromSecret(secretKeyHex: secretKeyHex)) try Task.checkCancellation() try await sdkService.approveAuth( @@ -121,6 +122,7 @@ enum PubkyService { secretKeyHex: String, sdkService: PaykitSdkService = .shared ) async throws { + try PubkyAuthRequest.requireExpectedSigner(authUrl: authUrl) { try pubkyPublicKeyFromSecret(secretKeyHex: secretKeyHex) } try await sdkService.republishIdentityBeforeApproval(publicKey: pubkyPublicKeyFromSecret(secretKeyHex: secretKeyHex)) try Task.checkCancellation() let paykitKey = claim.includesPaykitAccess @@ -185,6 +187,7 @@ enum PubkyService { approvedUsdtAddress: String? = nil, usdtEndpoint: (() async throws -> PublicPaykitService.Endpoint)? = nil, isUsdtEnabled: () -> Bool = { Env.isUsdtEnabled && UsdtPreference.isEnabled() }, + signerPublicKey: (String) throws -> String = { try pubkyPublicKeyFromSecret(secretKeyHex: $0) }, ordinaryApproval: @escaping OrdinaryAuthApproval = { authUrl, capabilities, clientID, secretKeyHex in try await approveAuth( authUrl: authUrl, @@ -204,6 +207,7 @@ enum PubkyService { } ) async throws { guard authUrl == request.rawUrl else { throw PubkyServiceError.invalidAuthUrl } + try PubkyAuthRequest.requireExpectedSigner(authUrl: authUrl) { try signerPublicKey(secretKeyHex) } if request.bitkitClaim?.requiresUsdtAddress == true, !isUsdtEnabled() { throw PubkyAuthRequestError.invalidPaymentDetails } diff --git a/Bitkit/ViewModels/AppViewModel.swift b/Bitkit/ViewModels/AppViewModel.swift index 1f41a72518..dc1e85468b 100644 --- a/Bitkit/ViewModels/AppViewModel.swift +++ b/Bitkit/ViewModels/AppViewModel.swift @@ -1515,7 +1515,28 @@ extension AppViewModel { toast(type: .warning, title: t("pubky_auth__no_identity"), description: t("pubky_auth__no_identity_desc")) return } - guard PubkyProfileManager.activeSecretKeyHex() != nil else { + let secretKeyHex = PubkyProfileManager.activeSecretKeyHex() + let signerPublicKey = secretKeyHex.flatMap { try? PubkyService.pubkyPublicKeyFromSecret(secretKeyHex: $0) } + ?? AdoptedPubkyReference.current?.pubky + presentPubkyAuthApproval(request, signerPublicKey: signerPublicKey, hasSecretKey: secretKeyHex != nil) + } + + /// Opens the approval sheet for a sign-in, unless it names a pubky other than this wallet's or the key is out of reach. + func presentPubkyAuthApproval(_ request: PubkyAuthRequest, signerPublicKey: String?, hasSecretKey: Bool) { + if let expectedSigner = request.expectedSigner, let signerPublicKey, + !PubkyAuthRequest.isExpectedSigner(expectedSigner, publicKey: signerPublicKey) + { + Logger.warn("Refused pubky auth request for another pubky", context: "AppViewModel") + sheetViewModel.hideSheetIfActive(.scanner, reason: "Pubky auth request names another pubky") + toast( + type: .error, + title: t("pubky_auth__approval_failed"), + description: pubkyAuthOtherPubkyDescription(expectedSigner), + accessibilityIdentifier: "PubkyAuthOtherPubkyToast" + ) + return + } + guard hasSecretKey else { sheetViewModel.hideSheetIfActive(.scanner, reason: "Pubky identity requires Ring") toast(type: .warning, title: t("pubky_auth__use_ring"), description: t("pubky_auth__use_ring_desc")) return diff --git a/Bitkit/Views/Sheets/PubkyAuthApproval/PubkyAuthApprovalSheet.swift b/Bitkit/Views/Sheets/PubkyAuthApproval/PubkyAuthApprovalSheet.swift index 5de86a6689..66974ac406 100644 --- a/Bitkit/Views/Sheets/PubkyAuthApproval/PubkyAuthApprovalSheet.swift +++ b/Bitkit/Views/Sheets/PubkyAuthApproval/PubkyAuthApprovalSheet.swift @@ -49,6 +49,8 @@ func pubkyAuthLiteralText(_ value: String) -> String { /// A homeserver that refuses the signup code and a failed connection get their own messages, since retrying is safe for both. func pubkyAuthApprovalFailureDescription(_ error: Error) -> String { switch error { + case let PubkyAuthRequestError.signerMismatch(expectedSigner): + pubkyAuthOtherPubkyDescription(expectedSigner) case let PaykitError.Identity(code, _) where code == "signup_code_rejected": t("profile__auth_error_signup_code_rejected") case PaykitError.Transport: @@ -58,6 +60,11 @@ func pubkyAuthApprovalFailureDescription(_ error: Error) -> String { } } +/// Names the pubky a refused request is for. `expectedSigner` is always a bare 52-character key. +func pubkyAuthOtherPubkyDescription(_ expectedSigner: String) -> String { + t("pubky_auth__other_pubky", variables: ["pubky": "\(expectedSigner.prefix(4))...\(expectedSigner.suffix(4))"]) +} + /// Fills each `{placeholder}` from the template only, so request data that itself contains a placeholder stays as it is. func pubkyAuthFilledText(_ template: String, variables: [String: String]) -> String { var result = "" diff --git a/BitkitTests/PubkyAuthApprovalSheetTests.swift b/BitkitTests/PubkyAuthApprovalSheetTests.swift index d5e98448a0..077a59b729 100644 --- a/BitkitTests/PubkyAuthApprovalSheetTests.swift +++ b/BitkitTests/PubkyAuthApprovalSheetTests.swift @@ -7,6 +7,7 @@ private let approvalTestXpub = "tpubDDWohsp5dx2iMJ9N7iHbgAEDhH4BJB9NWW1fEW3yA3AFNDREmpzteCXNqppMLUmKFY5q5e3" + "PXtS5CuqWCQbYcGhpPqYAgQSYdwknW9J6sQv" private let approvalTestClientPublicKey = "5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo" +private let approvalTestSignerPublicKey = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" private func approvalTestAuthUrl(secret: String = "e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3s") -> String { "pubkyauth://signin_grant?caps=\(PubkyAuthClaim.requiredCapabilities)" + @@ -46,6 +47,147 @@ final class PubkyAuthApprovalSheetTests: XCTestCase { XCTAssertEqual(PubkyAuthApprovalSheet.initialState(for: request), .authorize) } + @MainActor + func testRequestNamingAnotherPubkyIsNeverSigned() async throws { + let defaults = try XCTUnwrap(UserDefaults(suiteName: "ExpectedSigner.\(UUID().uuidString)")) + let manager = Bitkit.WatchOnlyAccountManager(defaults: defaults, node: ApprovalFakeWatchOnlyAccountNode()) + let other = approvalTestClientPublicKey + for url in [ordinaryApprovalTestAuthUrl(), approvalTestAuthUrl()].map({ "\($0)&spk=\(other)" }) { + let request = try PubkyAuthRequest.parse(url: url) + XCTAssertEqual(request.expectedSigner, other) + do { + try await PubkyService.approveAuthRequest( + request: request, authUrl: url, accountName: "Earn", secretKeyHex: "secret", accountManager: manager, + signerPublicKey: { _ in approvalTestSignerPublicKey }, + ordinaryApproval: { _, _, _, _ in XCTFail("A request for another pubky must not be signed") }, + companionApproval: { _, _, _, _, _ in XCTFail("A request for another pubky must not be signed") } + ) + XCTFail("Expected the request to be refused") + } catch { + XCTAssertEqual(error as? PubkyAuthRequestError, .signerMismatch(expectedSigner: other)) + } + } + XCTAssertTrue(manager.accounts.isEmpty) + } + + @MainActor + func testRequestNamingThisPubkyIsApproved() async throws { + let url = "\(ordinaryApprovalTestAuthUrl())&spk=\(approvalTestSignerPublicKey)" + var approved = false + + try await PubkyService.approveAuthRequest( + request: PubkyAuthRequest.parse(url: url), authUrl: url, accountName: "", secretKeyHex: "secret", + signerPublicKey: { _ in "pubky\(approvalTestSignerPublicKey)" }, + ordinaryApproval: { authUrl, _, _, _ in + XCTAssertEqual(authUrl, url) + approved = true + } + ) + + XCTAssertTrue(approved) + } + + func testSigningEntryPointsRefuseAnotherPubkyBeforeAnythingElse() async throws { + let secretKeyHex = String(repeating: "11", count: 32) + let own = try PubkyService.pubkyPublicKeyFromSecret(secretKeyHex: secretKeyHex) + let other = approvalTestClientPublicKey + XCTAssertFalse(PubkyAuthRequest.isExpectedSigner(other, publicKey: own)) + let ordinaryUrl = "\(ordinaryApprovalTestAuthUrl())&spk=\(other)" + let companionUrl = "\(approvalTestAuthUrl())&spk=\(other)" + + do { + try await PubkyService.approveAuth( + authUrl: ordinaryUrl, expectedCapabilities: "/pub/example/:rw", approvedClientID: "paykit.test", + secretKeyHex: secretKeyHex + ) + XCTFail("Expected the request to be refused") + } catch { + XCTAssertEqual(error as? PubkyAuthRequestError, .signerMismatch(expectedSigner: other)) + } + do { + try await PubkyService.approveAuthWithCompanionClaim( + authUrl: companionUrl, approvedClientID: "paykit.test", claim: .watchOnlyAccountV1, accountPayload: nil, + secretKeyHex: secretKeyHex + ) + XCTFail("Expected the request to be refused") + } catch { + XCTAssertEqual(error as? PubkyAuthRequestError, .signerMismatch(expectedSigner: other)) + } + do { + try await PubkyService.approveAuth( + authUrl: "\(ordinaryUrl)&spk=\(other)", expectedCapabilities: "/pub/example/:rw", + approvedClientID: "paykit.test", secretKeyHex: secretKeyHex + ) + XCTFail("Expected the request to be invalid") + } catch { + XCTAssertEqual(error as? PubkyAuthRequestError, .invalidUrl) + } + } + + @MainActor + func testRequestNamingAnotherPubkyShowsTheRefusalInsteadOfTheSheet() throws { + let other = approvalTestClientPublicKey + let request = try PubkyAuthRequest.parse(url: "\(ordinaryApprovalTestAuthUrl())&spk=\(other)") + // The refusal comes first even when the key is out of reach, as on Android. + for hasSecretKey in [true, false] { + let sheets = SheetViewModel() + let app = AppViewModel(sheetViewModel: sheets, navigationViewModel: NavigationViewModel()) + ToastWindowManager.shared.hideToast() + var shownToasts: [Bitkit.Toast] = [] + let subscription = ToastWindowManager.shared.$currentToast.compactMap { $0 }.sink { shownToasts.append($0) } + defer { subscription.cancel() } + + app.presentPubkyAuthApproval(request, signerPublicKey: "pubky\(approvalTestSignerPublicKey)", hasSecretKey: hasSecretKey) + + XCTAssertNil(sheets.pubkyAuthApprovalSheetItem) + XCTAssertEqual(shownToasts.map(\.accessibilityIdentifier), ["PubkyAuthOtherPubkyToast"]) + XCTAssertEqual(shownToasts.first?.description, pubkyAuthOtherPubkyDescription(other)) + } + ToastWindowManager.shared.hideToast() + } + + @MainActor + func testRequestNamingThisPubkyOpensTheSheet() throws { + let request = try PubkyAuthRequest.parse(url: "\(ordinaryApprovalTestAuthUrl())&spk=\(approvalTestSignerPublicKey)") + let sheets = SheetViewModel() + let app = AppViewModel(sheetViewModel: sheets, navigationViewModel: NavigationViewModel()) + + app.presentPubkyAuthApproval(request, signerPublicKey: approvalTestSignerPublicKey, hasSecretKey: true) + + XCTAssertEqual(sheets.pubkyAuthApprovalSheetItem?.request.rawUrl, request.rawUrl) + } + + @MainActor + func testGrantSignupWithAnExistingIdentityIgnoresTheExpectedSigner() async throws { + for spk in [approvalTestClientPublicKey, "not-a-public-key", "a&spk=b"] { + let url = ordinaryApprovalTestAuthUrl().replacingOccurrences(of: "signin_grant", with: "signup_grant") + + "&hs=\(approvalTestClientPublicKey)&st=invite&spk=\(spk)" + let request = try PubkyAuthRequest.parse(url: url) + XCTAssertNil(request.expectedSigner) + var approved = false + + try await PubkyService.approveAuthRequest( + request: request, authUrl: url, accountName: "", secretKeyHex: "secret", + signerPublicKey: { _ in approvalTestSignerPublicKey }, + ordinaryApproval: { authUrl, _, _, _ in + XCTAssertEqual(authUrl, url) + approved = true + } + ) + + XCTAssertTrue(approved, spk) + } + } + + func testRefusalNamesThePubkyTheRequestIsFor() { + let description = pubkyAuthApprovalFailureDescription( + PubkyAuthRequestError.signerMismatch(expectedSigner: approvalTestClientPublicKey) + ) + + XCTAssertTrue(description.contains("5jsj...tryo"), description) + XCTAssertFalse(description.contains("{pubky}"), description) + } + @MainActor func testReceivingDetailsShareExactlyTheRequestedAssets() async throws { let endpoint = try PaykitUsdt.endpoint(address: "0x1111111111111111111111111111111111111111") diff --git a/BitkitTests/PubkyAuthRequestTests.swift b/BitkitTests/PubkyAuthRequestTests.swift index 5082c0a4cf..bfbe3ee325 100644 --- a/BitkitTests/PubkyAuthRequestTests.swift +++ b/BitkitTests/PubkyAuthRequestTests.swift @@ -1,4 +1,5 @@ @testable import Bitkit +import Paykit import XCTest /// Tests for PubkyAuthRequest capability parsing and permission display. @@ -6,6 +7,12 @@ final class PubkyAuthRequestTests: XCTestCase { private let relay = "https%3A%2F%2Fhttprelay.pubky.app%2Finbox%2F" private let secret = "e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3s" private let publicKey = "5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo" + private let signer = "8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty" + + private func grantSigninUrl(_ extraQuery: String = "") -> String { + "pubkyauth://signin_grant?caps=/pub/example/:rw&relay=\(relay)&secret=\(secret)" + + "&cid=paykit.test&cpk=\(publicKey)\(extraQuery)" + } func testProtocolUrlRecognizesPubkyAuthSchemeCaseInsensitively() { XCTAssertTrue(PubkyAuthRequest.isProtocolURL("pubkyauth://signin?caps=/pub/bitkit.to/:rw")) @@ -340,6 +347,106 @@ final class PubkyAuthRequestTests: XCTestCase { XCTAssertNil(try PubkyAuthRequest.parse(url: url).bitkitClaim) } + func testGrantSigninReadsThePubkyItMustBeApprovedWith() throws { + XCTAssertEqual(signer.count, 52) + XCTAssertNil(try PubkyAuthRequest.parse(url: grantSigninUrl()).expectedSigner) + XCTAssertEqual(try PubkyAuthRequest.parse(url: grantSigninUrl("&spk=\(signer)")).expectedSigner, signer) + XCTAssertEqual(try PubkyAuthRequest.parseExpectedSigner(url: grantSigninUrl("&%73pk=\(signer)#spk=x")), signer) + + let handoff = grantSigninUrl("&spk=\(signer)") + .replacingOccurrences(of: "pubkyauth://signin_grant", with: "bitkit://pubky-auth/signin") + XCTAssertEqual(try PubkyAuthRequest.parse(url: handoff).expectedSigner, signer) + } + + func testGrantSigninWithRepeatedOrMalformedExpectedSignerIsInvalid() { + let invalidQueries = [ + "&spk", + "&spk=", + "&spk=not-a-public-key", + "&spk=pubky\(signer)", + "&spk=pk:\(signer)", + "&spk=https://\(signer)/", + "&spk=\(signer.uppercased())", + "&spk=%20\(signer)", + "&spk=\(signer)%20", + "&spk=\(signer)%0A", + "&spk=\(signer)/", + "&spk=\(signer.dropLast())", + "&spk=\(signer.dropLast())b", + "&spk=\(signer)&spk=\(signer)", + "&spk=\(signer)&spk=\(publicKey)", + "&spk=\(signer)&%73pk=\(signer)", + "&spk=\(signer)&spk=", + ] + + for query in invalidQueries { + XCTAssertThrowsError(try PubkyAuthRequest.parseExpectedSigner(url: grantSigninUrl(query)), query) { + XCTAssertEqual($0 as? PubkyAuthRequestError, .invalidUrl, query) + } + XCTAssertThrowsError(try PubkyAuthRequest.parse(url: grantSigninUrl(query)), query) { + XCTAssertEqual($0 as? PubkyAuthRequestError, .invalidUrl, query) + } + } + } + + func testSigninReadDifferentlyFromTheSdkIsStillHeldToItsExpectedSigner() throws { + for prefix in ["pubkyauth://user@signin_grant:80", "pubkyauth://signin_grant/", "pubkyauth://signin"] { + XCTAssertEqual(try PubkyAuthRequest.parseExpectedSigner(url: "\(prefix)?spk=\(signer)"), signer, prefix) + XCTAssertThrowsError(try PubkyAuthRequest.parseExpectedSigner(url: "\(prefix)?spk=\(signer)&spk=\(signer)"), prefix) { + XCTAssertEqual($0 as? PubkyAuthRequestError, .invalidUrl, prefix) + } + } + let split = "\(signer.prefix(26))\t\(signer.suffix(26))" + XCTAssertThrowsError(try PubkyAuthRequest.parseExpectedSigner(url: grantSigninUrl("&spk=\(split)"))) { + XCTAssertEqual($0 as? PubkyAuthRequestError, .invalidUrl) + } + } + + func testControlCharactersCannotHideTheExpectedSigner() { + for hidden in ["&s\tpk=\(signer)", "&sp\nk=\(signer)", "&spk\r=\(signer)", "&spk=\(signer)\u{7F}", "\t&spk=\(signer)"] { + XCTAssertThrowsError(try PubkyAuthRequest.parseExpectedSigner(url: grantSigninUrl(hidden)), hidden) { + XCTAssertEqual($0 as? PubkyAuthRequestError, .invalidUrl, hidden) + } + XCTAssertThrowsError(try PubkyAuthRequest.parse(url: grantSigninUrl(hidden)), hidden) { + XCTAssertEqual($0 as? PubkyAuthRequestError, .invalidUrl, hidden) + } + } + } + + func testExpectedSignerThatIsNotAPublicKeyIsInvalid() throws { + let alphabet = "ybndrfg8ejkmcpqxot1uwisza345h769" + let notAKey = try XCTUnwrap( + alphabet.lazy.map { "\($0)\(self.signer.dropFirst())" } + .first { (try? Paykit.normalizePubkyPublicKey(value: $0)) == nil }, + "expected a canonical z-base-32 value that is not an Ed25519 point" + ) + + XCTAssertThrowsError(try PubkyAuthRequest.parseExpectedSigner(url: grantSigninUrl("&spk=\(notAKey)"))) { + XCTAssertEqual($0 as? PubkyAuthRequestError, .invalidUrl) + } + } + + func testSignupRequestsIgnoreTheExpectedSigner() throws { + for prefix in ["pubkyauth://signup_grant", "pubkyauth://signup", "pubkyauth://direct_signup", "pubkyring://signup"] { + let url = "\(prefix)?caps=/pub/example/:rw&hs=homeserver&spk=not-a-public-key&spk=other" + + XCTAssertNil(try PubkyAuthRequest.parseExpectedSigner(url: url), prefix) + } + } + + func testExpectedSignerMatchesOnlyThisPubkyWithOrWithoutItsPrefix() { + let bareKeyStartingWithPrefix = "pubky" + signer.dropFirst(5) + + XCTAssertTrue(PubkyAuthRequest.isExpectedSigner(nil, publicKey: signer)) + XCTAssertTrue(PubkyAuthRequest.isExpectedSigner(signer, publicKey: signer)) + XCTAssertTrue(PubkyAuthRequest.isExpectedSigner(signer, publicKey: "pubky\(signer)")) + XCTAssertTrue(PubkyAuthRequest.isExpectedSigner(bareKeyStartingWithPrefix, publicKey: bareKeyStartingWithPrefix)) + XCTAssertFalse(PubkyAuthRequest.isExpectedSigner(publicKey, publicKey: signer)) + XCTAssertFalse(PubkyAuthRequest.isExpectedSigner(publicKey, publicKey: "pubky\(signer)")) + XCTAssertFalse(PubkyAuthRequest.isExpectedSigner(String(signer.dropFirst(5)), publicKey: bareKeyStartingWithPrefix)) + XCTAssertFalse(PubkyAuthRequest.isExpectedSigner(signer, publicKey: "")) + } + func testParseUrlRejectsDuplicateBitkitClaim() { let url = authUrl( capabilities: PubkyAuthClaim.requiredCapabilities, diff --git a/changelog.d/next/1195.fixed.md b/changelog.d/next/1195.fixed.md new file mode 100644 index 0000000000..fa9b7527fe --- /dev/null +++ b/changelog.d/next/1195.fixed.md @@ -0,0 +1 @@ +Fixed Pubky sign-in requests meant for another pubky being signed; Bitkit now refuses them and names the pubky they are for. diff --git a/journeys/pubky-auth/README.md b/journeys/pubky-auth/README.md index 66e388e298..3c0b66b804 100644 --- a/journeys/pubky-auth/README.md +++ b/journeys/pubky-auth/README.md @@ -4,6 +4,7 @@ This suite covers the uniquely targetable `bitkit://pubky-auth/setup` and `bitki It stops at explicit watch-only consent and never authorizes or exports account material. Bitkit retains links delivered during startup, restoration, or PIN entry and presents consent only after the main wallet UI is available. A sign-in link keeps its place when another link arrives: `signin-with-second-link.xml` checks that a payment link opened on the PIN screen in either order, or over the open authorization sheet, opens only after that sheet closes. +`signin-expected-pubky.xml` checks a sign-in link that names the pubky it must be approved with (`spk`): this wallet's pubky opens the authorization sheet, another pubky is refused with a message naming it, and a repeated or malformed `spk` is an invalid request. Nothing is authorized. ## Preconditions diff --git a/journeys/pubky-auth/signin-expected-pubky.xml b/journeys/pubky-auth/signin-expected-pubky.xml new file mode 100644 index 0000000000..c28a8fd007 --- /dev/null +++ b/journeys/pubky-auth/signin-expected-pubky.xml @@ -0,0 +1,29 @@ + + + Verifies that a grant sign-in link naming the pubky that must approve it (spk) opens the authorization sheet only + when it names this wallet's pubky, is refused with a message naming the other pubky otherwise, and is invalid when + spk is repeated or malformed. Precondition: an unlocked regtest wallet with a locally managed Pubky identity. The + links are local-only dummy requests and nothing is authorized; never tap Authorize. BASE is + pubkyauth://signin_grant?caps=/pub/locks.app/:rw&relay=https%3A%2F%2Fhttprelay.pubky.app%2Finbox%2F&secret=e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3s&cid=locks.test&cpk=5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo + and OTHER is 8um71us3fyw6h8wbcxb5ar3rwusy1a6u49956ikzojg3gcwd1dty. Android opens each link with + adb shell "am start -a android.intent.action.VIEW -d '<link>' to.bitkit.dev" and reads toasts from a + screenshot; iOS opens the same query through bitkit://pubky-auth/signin and its toasts carry the ids + PubkyAuthOtherPubkyToast and PubkyAuthInvalidRequestToast. + + + Open the Profile screen and read this wallet's pubky: tap Share (id "ProfileShare") and read the text preview, then close the share sheet (iOS: tap Copy (id "ProfileCopy") and run xcrun simctl pbpaste) + Set OWN to that pubky without its leading "pubky" prefix; it is 52 characters long + Open BASE&spk=OWN + Verify the authorize button (id "PubkyAuthAuthorize") is visible and the profile card (id "PubkyAuthProfile") shows the first and last four characters of OWN + Tap Cancel + Open BASE&spk=OTHER + Verify an error toast reads "This request is for 8um7...1dty, not this wallet's pubky." + Wait 5 seconds, then verify the authorize button (id "PubkyAuthAuthorize") is not visible + Open BASE&spk=OWN&spk=OWN + Verify the invalid request toast is shown and the authorize button (id "PubkyAuthAuthorize") is not visible + Open BASE&spk=pubkyOWN + Verify the invalid request toast is shown and the authorize button (id "PubkyAuthAuthorize") is not visible + Open BASE&spk=not-a-public-key + Verify the invalid request toast is shown and the authorize button (id "PubkyAuthAuthorize") is not visible + +