diff --git a/Bitkit/Models/PubkyAuthRequest.swift b/Bitkit/Models/PubkyAuthRequest.swift index 9645c1fcb..7469a3c55 100644 --- a/Bitkit/Models/PubkyAuthRequest.swift +++ b/Bitkit/Models/PubkyAuthRequest.swift @@ -1,4 +1,3 @@ -import BitkitCore import Foundation import Paykit @@ -287,23 +286,15 @@ struct PubkyAuthRequest { private static func parseSignup(url: String, components: URLComponents) throws -> PubkyAuthRequest { let values = Dictionary(grouping: components.queryItems ?? [], by: \.name) + // Sign-up that also authorizes an app must use `signup_grant`, so legacy Ring and `signup` links with + // relay/secret/caps are rejected. `direct_signup` ignores those values, as Pubky Ring does. + let isLegacyAuthorizingSignup = components.scheme?.lowercased() == "pubkyring" || + (components.host?.lowercased() == "signup" && ["relay", "secret", "caps"].contains { values[$0] != nil }) + guard !isLegacyAuthorizingSignup else { + throw PubkyAuthRequestError.invalidUrl + } let homeserver = try requiredQueryValue("hs", from: values) - let authorizesApp = components.scheme?.lowercased() == "pubkyring" || - ( - components.scheme?.lowercased() == "pubkyauth" && - components.host?.lowercased() == "signup" && - ["relay", "secret", "caps"].contains { values[$0] != nil } - ) - let relay = authorizesApp ? try requiredQueryValue("relay", from: values) : "" - let secret = authorizesApp ? try requiredQueryValue("secret", from: values) : "" - let capabilities = authorizesApp ? try requiredQueryValue("caps", from: values) : "" - let authorizationUrl = authorizesApp - ? ringAuthorizationUrl(relay: relay, secret: secret, capabilities: capabilities) - : nil do { - if let authorizationUrl { - _ = try BitkitCore.parsePubkyAuthUrl(authUrl: authorizationUrl) - } _ = try Paykit.normalizePubkyPublicKey(value: homeserver) } catch { throw PubkyAuthRequestError.invalidUrl @@ -312,11 +303,11 @@ struct PubkyAuthRequest { url: url, kind: .signUp, clientID: "", - relay: relay, - capabilities: capabilities, + relay: "", + capabilities: "", homeserverPublicKey: homeserver, signupToken: optionalQueryValue("st", from: values), - authorizationUrl: authorizationUrl + authorizationUrl: nil ) guard request.bitkitClaim == nil else { throw PubkyAuthRequestError.invalidUrl @@ -356,16 +347,6 @@ struct PubkyAuthRequest { ) } - private static func ringAuthorizationUrl(relay: String, secret: String, capabilities: String) -> String { - "pubkyauth:///?relay=\(encodeQueryComponent(relay))" + - "&secret=\(encodeQueryComponent(secret))&caps=\(encodeQueryComponent(capabilities))" - } - - private static func encodeQueryComponent(_ value: String) -> String { - let unreserved = CharacterSet.alphanumerics.union(CharacterSet(charactersIn: "-._~")) - return value.addingPercentEncoding(withAllowedCharacters: unreserved) ?? value - } - private static func requiredQueryValue( _ name: String, from values: [String: [URLQueryItem]] diff --git a/Bitkit/Services/PubkyService.swift b/Bitkit/Services/PubkyService.swift index 8eb721672..b9b4454b7 100644 --- a/Bitkit/Services/PubkyService.swift +++ b/Bitkit/Services/PubkyService.swift @@ -1,4 +1,3 @@ -import BitkitCore import Combine import Foundation import Paykit @@ -105,14 +104,6 @@ enum PubkyService { ) } - static func approveRingAuth(authUrl: String, secretKeyHex: String, sdkService: PaykitSdkService = .shared) async throws { - try await sdkService.republishIdentityBeforeApproval(publicKey: pubkyPublicKeyFromSecret(secretKeyHex: secretKeyHex)) - try Task.checkCancellation() - try await ServiceQueue.background(.core) { - try await BitkitCore.approvePubkyAuth(authUrl: authUrl, secretKeyHex: secretKeyHex) - } - } - static func approveAuthWithCompanionClaim( authUrl: String, approvedClientID: String, @@ -159,17 +150,10 @@ enum PubkyService { approvedClientID: clientID, secretKeyHex: secretKeyHex ) - }, - ringApproval: (String, String) async throws -> Void = { authUrl, secretKeyHex in - try await approveRingAuth(authUrl: authUrl, secretKeyHex: secretKeyHex) } ) async throws { - guard let authorizationUrl = request.authorizationUrl else { return } - if request.isGrantSignup { - try await ordinaryApproval(authorizationUrl, request.capabilities, request.clientID, secretKeyHex) - } else { - try await ringApproval(authorizationUrl, secretKeyHex) - } + guard request.isGrantSignup, let authorizationUrl = request.authorizationUrl else { return } + try await ordinaryApproval(authorizationUrl, request.capabilities, request.clientID, secretKeyHex) } typealias OrdinaryAuthApproval = (String, String, String, String) async throws -> Void diff --git a/Bitkit/Utilities/ClipboardPrompt.swift b/Bitkit/Utilities/ClipboardPrompt.swift index ace6e9b24..b2ff7c1e6 100644 --- a/Bitkit/Utilities/ClipboardPrompt.swift +++ b/Bitkit/Utilities/ClipboardPrompt.swift @@ -70,11 +70,9 @@ enum ClipboardPromptValidator { if SamRockSetupRequest.parse(uri) != nil { return true } - if PaykitFeatureFlags.isUIEnabled, - PubkyAuthRequest.isProtocolURL(uri), - (try? PubkyAuthRequest.parse(url: uri)) != nil - { - return true + // Core's scanner classifies any `pubkyauth:` string, so a recognised link the Pubky parser rejects must not reach it. + if PaykitFeatureFlags.isUIEnabled, PubkyAuthRequest.isProtocolURL(uri) { + return (try? PubkyAuthRequest.parse(url: uri)) != nil } let normalized = uri.removingLightningSchemes() diff --git a/BitkitTests/ClipboardPromptValidatorTests.swift b/BitkitTests/ClipboardPromptValidatorTests.swift index 5beb8a457..9a66d2ed3 100644 --- a/BitkitTests/ClipboardPromptValidatorTests.swift +++ b/BitkitTests/ClipboardPromptValidatorTests.swift @@ -230,6 +230,42 @@ final class ClipboardPromptValidatorTests: XCTestCase { } } + @MainActor + func testLegacyPubkySignupLinksAreNotOfferedEvenWhenCoreRecognisesThem() async { + snapshotAppDefaults(PaykitFeatureFlags.uiEnabledKey) + UserDefaults.standard.set(true, forKey: PaykitFeatureFlags.uiEnabledKey) + let legacyQuery = "signup?hs=\(pubkyHomeserver)&relay=https%3A%2F%2Frelay.example%2Finbox%2F" + + "&secret=\(pubkyAuthSecret)&caps=%2Fpub%2Fexample.app%2F%3Arw" + for uri in ["pubkyauth://\(legacyQuery)", "pubkyring://\(legacyQuery)", "pubkyring://signup?hs=\(pubkyHomeserver)"] { + let supported = await ClipboardPromptValidator.isSupportedURI(uri, ownPublicKey: nil, contacts: [], isUsdtEnabled: false) { _ in + XCTFail("A recognised Pubky link must not fall through to the core decoder") + return true + } + XCTAssertFalse(supported, uri) + } + } + + @MainActor + func testValidPubkySignupLinksAreOfferedWithoutDecoding() async { + snapshotAppDefaults(PaykitFeatureFlags.uiEnabledKey) + UserDefaults.standard.set(true, forKey: PaykitFeatureFlags.uiEnabledKey) + for uri in [ + "pubkyauth://signup?hs=\(pubkyHomeserver)", + "pubkyauth://direct_signup?hs=\(pubkyHomeserver)&st=invite", + "pubkyauth://signup_grant?caps=/pub/pubky.app/:rw&relay=https%3A%2F%2Fhttprelay.pubky.app%2Finbox%2F" + + "&secret=\(pubkyAuthSecret)&hs=\(pubkyHomeserver)&st=invite&cid=shop.pubky.app&cpk=\(pubkyHomeserver)", + ] { + let supported = await ClipboardPromptValidator.isSupportedURI(uri, ownPublicKey: nil, contacts: [], isUsdtEnabled: false) { _ in + XCTFail("A valid Pubky link must be accepted by the Pubky parser alone") + return false + } + XCTAssertTrue(supported, uri) + } + } + + private let pubkyHomeserver = "5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo" + private let pubkyAuthSecret = "e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3s" + private func wrappedLnurls(_ lnurl: String) -> [String] { [ lnurl, diff --git a/BitkitTests/PubkyAuthApprovalSheetTests.swift b/BitkitTests/PubkyAuthApprovalSheetTests.swift index d5e98448a..631d8eead 100644 --- a/BitkitTests/PubkyAuthApprovalSheetTests.swift +++ b/BitkitTests/PubkyAuthApprovalSheetTests.swift @@ -38,14 +38,31 @@ final class PubkyAuthApprovalSheetTests: XCTestCase { XCTAssertEqual(clientID, "paykit.test") XCTAssertEqual(secretKey, "derived-secret") approved = true - }, - ringApproval: { _, _ in XCTFail("Grant signup must use the grant API") } + } ) XCTAssertTrue(approved) XCTAssertEqual(PubkyAuthApprovalSheet.initialState(for: request), .authorize) } + @MainActor + func testPlainSignupDoesNotAuthorizeAnApp() async throws { + let strayAuthorization = "&relay=https%3A%2F%2Fhttprelay.pubky.app%2Finbox%2F" + + "&secret=e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3s&caps=%2Fpub%2Fexample%2F%3Arw" + let urls = ["direct_signup", "signup"].map { "pubkyauth://\($0)?hs=\(approvalTestClientPublicKey)&st=invite" } + + ["pubkyauth://direct_signup?hs=\(approvalTestClientPublicKey)&st=invite\(strayAuthorization)"] + for url in urls { + let request = try PubkyAuthRequest.parse(url: url) + XCTAssertNil(request.authorizationUrl, url) + + try await PubkyService.approveSignupAuthorization( + request: request, + secretKeyHex: "derived-secret", + ordinaryApproval: { _, _, _, _ in XCTFail("Plain signup must not authorize an app") } + ) + } + } + @MainActor func testReceivingDetailsShareExactlyTheRequestedAssets() async throws { let endpoint = try PaykitUsdt.endpoint(address: "0x1111111111111111111111111111111111111111") diff --git a/BitkitTests/PubkyAuthRequestTests.swift b/BitkitTests/PubkyAuthRequestTests.swift index 5082c0a4c..5adcab73f 100644 --- a/BitkitTests/PubkyAuthRequestTests.swift +++ b/BitkitTests/PubkyAuthRequestTests.swift @@ -11,7 +11,7 @@ final class PubkyAuthRequestTests: XCTestCase { XCTAssertTrue(PubkyAuthRequest.isProtocolURL("pubkyauth://signin?caps=/pub/bitkit.to/:rw")) XCTAssertTrue(PubkyAuthRequest.isProtocolURL("PUBKYAUTH://signin?caps=/pub/bitkit.to/:rw")) XCTAssertTrue(PubkyAuthRequest.isProtocolURL(" pubkyauth://signin?caps=/pub/bitkit.to/:rw\n")) - XCTAssertTrue(PubkyAuthRequest.isProtocolURL(ringSignupUrl())) + XCTAssertTrue(PubkyAuthRequest.isProtocolURL(legacyRingSignupUrl())) XCTAssertTrue(PubkyAuthRequest.isProtocolURL(directSignupUrl(action: "direct_signup"))) XCTAssertFalse(PubkyAuthRequest.isProtocolURL("lightning:lnbc1example")) } @@ -171,21 +171,38 @@ final class PubkyAuthRequestTests: XCTestCase { XCTAssertThrowsError(try PubkyAuthRequest.parse(url: url)) } - func testParseAuthorizedSignup() throws { + func testParseRejectsLegacyAuthorizingSignup() { + var urls: [String] = [] for scheme in ["pubkyring", "pubkyauth"] { - let request = try PubkyAuthRequest.parse(url: ringSignupUrl(signupToken: "invite code", scheme: scheme)) + urls.append(legacyRingSignupUrl(scheme: scheme)) + urls.append(legacyRingSignupUrl(signupToken: "invite code", scheme: scheme)) + } + urls.append("pubkyring://signup?hs=\(publicKey)") + for parameter in strayAuthorizationParameters { + urls.append(directSignupUrl(action: "signup") + "&\(parameter)") + } - XCTAssertTrue(request.isSignup) - XCTAssertEqual(request.kind, .signUp) - XCTAssertEqual(request.homeserverPublicKey, publicKey) - XCTAssertEqual(request.signupToken, "invite code") - XCTAssertEqual(request.relay, "https://relay.example/inbox/") - XCTAssertEqual(request.capabilities, "/pub/example.app/:rw") - XCTAssertEqual( - request.authorizationUrl, - "pubkyauth:///?relay=https%3A%2F%2Frelay.example%2Finbox%2F" + - "&secret=\(secret)&caps=%2Fpub%2Fexample.app%2F%3Arw" - ) + for url in urls { + XCTAssertTrue(PubkyAuthRequest.isProtocolURL(url), url) + XCTAssertThrowsError(try PubkyAuthRequest.parse(url: url), url) { error in + XCTAssertEqual(error as? PubkyAuthRequestError, .invalidUrl, url) + } + } + } + + func testParseDirectSignupIgnoresStrayAuthorizationValues() throws { + let suffixes = strayAuthorizationParameters + [strayAuthorizationParameters.joined(separator: "&")] + for suffix in suffixes { + let url = directSignupUrl(action: "direct_signup", signupToken: "invite code") + "&\(suffix)" + let request = try PubkyAuthRequest.parse(url: url) + + XCTAssertTrue(request.isSignup, suffix) + XCTAssertEqual(request.kind, .signUp, suffix) + XCTAssertEqual(request.homeserverPublicKey, publicKey, suffix) + XCTAssertEqual(request.signupToken, "invite code", suffix) + XCTAssertEqual(request.relay, "", suffix) + XCTAssertEqual(request.capabilities, "", suffix) + XCTAssertNil(request.authorizationUrl, suffix) } } @@ -229,11 +246,13 @@ final class PubkyAuthRequestTests: XCTestCase { } } - func testParseRingSignupRejectsMissingOrDuplicateRequiredValues() { + func testParseSignupRejectsMissingOrDuplicateRequiredValues() { let invalidUrls = [ - ringSignupUrl().replacingOccurrences(of: "&secret=\(secret)", with: ""), - "\(ringSignupUrl())&hs=other", - directSignupUrl(action: "signup") + "&relay=https%3A%2F%2Frelay.example", + "pubkyauth://signup", + "pubkyauth://direct_signup?st=invite", + "pubkyauth://direct_signup?hs=invalid", + directSignupUrl(action: "signup") + "&hs=\(publicKey)", + directSignupUrl(action: "direct_signup", signupToken: "one") + "&st=two", ] for url in invalidUrls { @@ -536,7 +555,11 @@ final class PubkyAuthRequestTests: XCTestCase { "&cid=paykit.test&cpk=\(publicKey)\(claims)" } - private func ringSignupUrl(signupToken: String? = nil, scheme: String = "pubkyring") -> String { + private var strayAuthorizationParameters: [String] { + ["relay=\(relay)", "secret=\(secret)", "caps=%2Fpub%2Fexample.app%2F%3Arw"] + } + + private func legacyRingSignupUrl(signupToken: String? = nil, scheme: String = "pubkyring") -> String { let token = signupToken.map { "&st=\($0.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? $0)" } ?? "" diff --git a/BitkitTests/PubkyIdentityRepublishTests.swift b/BitkitTests/PubkyIdentityRepublishTests.swift index f1f3d662b..0ee9eea63 100644 --- a/BitkitTests/PubkyIdentityRepublishTests.swift +++ b/BitkitTests/PubkyIdentityRepublishTests.swift @@ -180,7 +180,6 @@ final class PubkyIdentityRepublishTests: XCTestCase { await fulfillment(of: [started], timeout: 1) let caller = Task { - // The ring path then fails on its invalid URL, which still shows the approval went ahead. try? await approve(kind, using: service) proceeded.fulfill() } @@ -216,7 +215,7 @@ final class PubkyIdentityRepublishTests: XCTestCase { } func testAuthRepublishesSigningIdentityBeforeApprovalEvenWhenPublicationFails() async throws { - for kind in [Approval.ordinary, .companion] { + for kind in Approval.allCases { for result in [Result.success(true), .failure(PubkyServiceError.profileNotFound)] { let bootstrap = RepublishBootstrap(noPointer: .init()) let service = PaykitSdkService(bootstrapFactory: { _, _ in bootstrap }) @@ -263,7 +262,7 @@ final class PubkyIdentityRepublishTests: XCTestCase { } private enum Approval: CaseIterable { - case ordinary, companion, ring + case ordinary, companion } private func approve(_ kind: Approval, using service: PaykitSdkService) async throws { @@ -283,8 +282,6 @@ final class PubkyIdentityRepublishTests: XCTestCase { accountPayload: Data([1]) + Data(repeating: 0, count: 83), secretKeyHex: secretKeyHex, sdkService: service ) - case .ring: - try await PubkyService.approveRingAuth(authUrl: "invalid-auth-url", secretKeyHex: secretKeyHex, sdkService: service) } } } diff --git a/BitkitTests/ScannerManagerTests.swift b/BitkitTests/ScannerManagerTests.swift index 762c1fbdf..332bf40f1 100644 --- a/BitkitTests/ScannerManagerTests.swift +++ b/BitkitTests/ScannerManagerTests.swift @@ -343,6 +343,28 @@ final class ScannerManagerTests: XCTestCase { XCTAssertNil(sheets.activeSheetConfiguration) } + func testLegacyRingSignupScanShowsTheInvalidRequestToastAndNoSheet() async throws { + snapshotAppDefaultsDomain() + UserDefaults.standard.set(false, forKey: ToastWindowManager.disableAllToastsKey) + UserDefaults.standard.set(true, forKey: PaykitFeatureFlags.uiEnabledKey) + let previousToast = ToastWindowManager.shared.currentToast + defer { ToastWindowManager.shared.currentToast = previousToast } + let sheets = SheetViewModel() + let app = configure(ScannerManager {}, sheets: sheets) + let publicKey = "5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo" + + for scheme in ["pubkyring", "pubkyauth"] { + ToastWindowManager.shared.currentToast = nil + let url = "\(scheme)://signup?hs=\(publicKey)&relay=https%3A%2F%2Frelay.example%2Finbox%2F" + + "&secret=e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3s&caps=%2Fpub%2Fexample%2F%3Arw" + + try await app.handleScannedData(url) + + XCTAssertEqual(ToastWindowManager.shared.currentToast?.accessibilityIdentifier, "PubkyAuthInvalidRequestToast", scheme) + XCTAssertNil(sheets.activeSheetConfiguration, scheme) + } + } + private func imageTestLnurl(amount: UInt64) -> LnurlPayData { LnurlPayData(uri: "https://example.com/pay", callback: "https://example.com/callback", minSendable: amount, maxSendable: amount, diff --git a/BitkitTests/ShopPaymentRequestTests.swift b/BitkitTests/ShopPaymentRequestTests.swift index 1686d2f7c..fa00b9a0a 100644 --- a/BitkitTests/ShopPaymentRequestTests.swift +++ b/BitkitTests/ShopPaymentRequestTests.swift @@ -38,7 +38,7 @@ final class ShopPaymentRequestTests: XCTestCase { let app = AppViewModel() let requests = [ "https://btcpay.example/plugins/store123/samrock/protocol?setup=btc-chain&otp=abc123", - pubkySignupUrl, + legacyRingSignupUrl, directPubkySignupUrl, "lnurl:lightning:\(directPubkySignupUrl)", "bitkit://\(directPubkySignupUrl)", @@ -63,7 +63,7 @@ final class ShopPaymentRequestTests: XCTestCase { app.scannedLightningInvoice = lightningInvoice do { - try await app.handleScannedData(pubkySignupUrl, claimedContactPaymentContext: context) + try await app.handleScannedData(legacyRingSignupUrl, claimedContactPaymentContext: context) XCTFail("Expected contact payment to reject Pubky signup") } catch { XCTAssertTrue(error is ScanHandlingError) @@ -77,7 +77,7 @@ final class ShopPaymentRequestTests: XCTestCase { let sheets = SheetViewModel() let app = AppViewModel(sheetViewModel: sheets, navigationViewModel: NavigationViewModel()) let requests = [ - pubkySignupUrl, + legacyRingSignupUrl, directPubkySignupUrl, directPubkySignupUrl.replacingOccurrences(of: "direct_signup", with: "signup"), "pubkyauth://signin_grant?caps=/pub/example/:rw&relay=https://relay.example/inbox/" + @@ -165,7 +165,7 @@ final class ShopPaymentRequestTests: XCTestCase { AdoptedPubkyReference.current = nil XCTAssertFalse(try PubkyProfileManager.hasStoredIdentity()) - for url in [pubkySignupUrl, directPubkySignupUrl, directPubkySignupUrl.replacingOccurrences(of: "direct_signup", with: "signup")] { + for url in [directPubkySignupUrl, directPubkySignupUrl.replacingOccurrences(of: "direct_signup", with: "signup")] { let sheets = SheetViewModel() let app = AppViewModel( sheetViewModel: sheets, @@ -277,7 +277,7 @@ final class ShopPaymentRequestTests: XCTestCase { ) } - private var pubkySignupUrl: String { + private var legacyRingSignupUrl: String { "pubkyring://signup?hs=5jsjx1o6fzu6aeeo697r3i5rx15zq41kikcye8wtwdqm4nb4tryo" + "&relay=https%3A%2F%2Frelay.example%2Finbox%2F" + "&secret=e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3t7e3s" + diff --git a/changelog.d/next/1332.removed.md b/changelog.d/next/1332.removed.md new file mode 100644 index 000000000..e1df03a53 --- /dev/null +++ b/changelog.d/next/1332.removed.md @@ -0,0 +1 @@ +Sign-up links that use the old Pubky Ring format to also authorize an app are now rejected as invalid; apps need to send a sign-up grant link instead. diff --git a/journeys/profile/signup-create-profile.xml b/journeys/profile/signup-create-profile.xml index 827a3d8a0..869db6681 100644 --- a/journeys/profile/signup-create-profile.xml +++ b/journeys/profile/signup-create-profile.xml @@ -3,10 +3,10 @@ Precondition: a disposable, unfunded fresh wallet with Paykit enabled, no existing Pubky identity, a reachable staging Pubky signup site and an English device. Open the signup site in a browser and keep the app process alive throughout this journey. - This iOS journey checks profile creation after an external signup authorization. + This iOS journey checks profile creation after an external signup_grant authorization. - Open staging.pubky.app in the browser, begin signup and copy the pubkyauth://signup link + Open staging.pubky.app in the browser, begin signup and copy the pubkyauth://signup_grant link it offers (not a legacy pubkyauth://signup or pubkyring://signup link with relay, secret and caps, which Bitkit rejects) Open Bitkit Scan, paste the signup link and verify the signup authorization sheet appears Tap Authorize and wait for signup authorization to complete Return to the browser and verify the site has continued with the authorized public Pubky key; record that key