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
50 changes: 49 additions & 1 deletion Bitkit/Models/PubkyAuthRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ enum PubkyAuthRequestError: Error, Equatable {
case duplicateSecret
case unsupportedBitkitClaim(String)
case invalidBitkitClaimCapabilities
case signerMismatch(expectedSigner: String)
}

// MARK: - PubkyAuth Permission
Expand Down Expand Up @@ -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)
Expand Down Expand Up @@ -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,
Expand All @@ -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))"
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/ar.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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" = "فشل التفويض";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/ca.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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ó";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/cs.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/de.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/el.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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" = "Η Εξουσιοδότηση Απέτυχε";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/en.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/es.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/fr.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/it.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/nl.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/pl.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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ę";
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/pt.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down
1 change: 1 addition & 0 deletions Bitkit/Resources/Localization/ru.lproj/Localizable.strings
Original file line number Diff line number Diff line change
Expand Up @@ -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" = "Ошибка Авторизации";
Expand Down
4 changes: 4 additions & 0 deletions Bitkit/Services/PubkyService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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
Expand Down Expand Up @@ -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,
Expand All @@ -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
}
Expand Down
23 changes: 22 additions & 1 deletion Bitkit/ViewModels/AppViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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 = ""
Expand Down
Loading
Loading