diff --git a/mobile/ios/Runner.xcodeproj/project.pbxproj b/mobile/ios/Runner.xcodeproj/project.pbxproj index 5f420fcbcf..e5e9678f91 100644 --- a/mobile/ios/Runner.xcodeproj/project.pbxproj +++ b/mobile/ios/Runner.xcodeproj/project.pbxproj @@ -7,6 +7,8 @@ objects = { /* Begin PBXBuildFile section */ + BC0010000000000000000003 /* BrowserAuthBridgeTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC0010000000000000000004 /* BrowserAuthBridgeTests.swift */; }; + BC0010000000000000000001 /* BuzzBrowserAuthBridge.swift in Sources */ = {isa = PBXBuildFile; fileRef = BC0010000000000000000002 /* BuzzBrowserAuthBridge.swift */; }; F84380010000000000000001 /* ProfileSetupRecoveryTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = F84380010000000000000002 /* ProfileSetupRecoveryTests.swift */; }; BBAA00000000000000000011 /* IdentityFilePlugin.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBAA00000000000000000012 /* IdentityFilePlugin.swift */; }; BBAA00000000000000000001 /* HostedHpkeBackup.swift in Sources */ = {isa = PBXBuildFile; fileRef = BBAA00000000000000000002 /* HostedHpkeBackup.swift */; }; @@ -101,6 +103,8 @@ /* End PBXCopyFilesBuildPhase section */ /* Begin PBXFileReference section */ + BC0010000000000000000004 /* BrowserAuthBridgeTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BrowserAuthBridgeTests.swift; sourceTree = ""; }; + BC0010000000000000000002 /* BuzzBrowserAuthBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BuzzBrowserAuthBridge.swift; sourceTree = ""; }; F84380010000000000000002 /* ProfileSetupRecoveryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProfileSetupRecoveryTests.swift; sourceTree = ""; }; BBAA00000000000000000012 /* IdentityFilePlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IdentityFilePlugin.swift; sourceTree = ""; }; BBAA00000000000000000002 /* HostedHpkeBackup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostedHpkeBackup.swift; sourceTree = ""; }; @@ -208,6 +212,7 @@ isa = PBXGroup; children = ( 331C807B294A618700263BE5 /* RunnerTests.swift */, + BC0010000000000000000004 /* BrowserAuthBridgeTests.swift */, F84380010000000000000002 /* ProfileSetupRecoveryTests.swift */, AB1200132F40400100A17E01 /* NativeMessageImageLoaderTests.swift */, AB1200132F40400100A17E09 /* IdentityFilePluginTests.swift */, @@ -288,6 +293,7 @@ AB1200112F40400100A17E01 /* NativeMessageMenu.swift */, AB1200122F40400100A17E01 /* NativeReactionDetails.swift */, 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + BC0010000000000000000002 /* BuzzBrowserAuthBridge.swift */, BBAA00000000000000000002 /* HostedHpkeBackup.swift */, BBAA00000000000000000012 /* IdentityFilePlugin.swift */, BZZ00000000000000000024 /* PushNativeState.swift */, @@ -618,6 +624,7 @@ buildActionMask = 2147483647; files = ( 331C808B294A63AB00263BE5 /* RunnerTests.swift in Sources */, + BC0010000000000000000003 /* BrowserAuthBridgeTests.swift in Sources */, F84380010000000000000001 /* ProfileSetupRecoveryTests.swift in Sources */, AB1200032F40400100A17E01 /* NativeMessageImageLoaderTests.swift in Sources */, AB1200032F40400100A17E09 /* IdentityFilePluginTests.swift in Sources */, @@ -633,6 +640,7 @@ AB1200012F40400100A17E01 /* NativeMessageMenu.swift in Sources */, AB1200022F40400100A17E01 /* NativeReactionDetails.swift in Sources */, 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + BC0010000000000000000001 /* BuzzBrowserAuthBridge.swift in Sources */, BBAA00000000000000000001 /* HostedHpkeBackup.swift in Sources */, BBAA00000000000000000011 /* IdentityFilePlugin.swift in Sources */, BZZ00000000000000000023 /* PushNativeState.swift in Sources */, diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift index 4e59478ad6..9a49b26dbe 100644 --- a/mobile/ios/Runner/AppDelegate.swift +++ b/mobile/ios/Runner/AppDelegate.swift @@ -1141,66 +1141,3 @@ extension BuzzPushNavigationTarget { return arguments } } - - -/// Keeps the authentication callback scoped to the system browser session. -private final class BuzzBrowserAuthBridge: NSObject, ASWebAuthenticationPresentationContextProviding { - private let channel: FlutterMethodChannel - private var session: ASWebAuthenticationSession? - private var pending: FlutterResult? - private var attemptID: UUID? - - init(messenger: FlutterBinaryMessenger) { - channel = FlutterMethodChannel(name: "buzz/browser_auth", binaryMessenger: messenger) - super.init() - channel.setMethodCallHandler { [weak self] call, result in - guard let self else { return } - if call.method == "cancel" { - self.session?.cancel() - self.finish(nil, code: "cancelled") - result(nil) - return - } - guard call.method == "start" else { result(FlutterMethodNotImplemented); return } - guard self.session == nil, - let args = call.arguments as? [String: String], - let raw = args["url"], let url = URL(string: raw), - url.scheme == "https", - ["app.builderlab.xyz", "app.builderlabstaging.xyz"].contains(url.host ?? ""), - url.path == "/api/goose/v1/auth/login", url.user == nil, url.password == nil, - url.port == nil, url.fragment == nil - else { result(FlutterError(code: "unavailable", message: nil, details: nil)); return } - self.pending = result - let attemptID = UUID() - self.attemptID = attemptID - let session = ASWebAuthenticationSession(url: url, callbackURLScheme: "xyz.block.buzz.mobile") { [weak self] callback, error in - DispatchQueue.main.async { - guard self?.attemptID == attemptID else { return } - let cancelled = (error as? ASWebAuthenticationSessionError)?.code == .canceledLogin - self?.finish(callback?.absoluteString, code: cancelled ? "cancelled" : "unavailable") - } - } - session.presentationContextProvider = self - session.prefersEphemeralWebBrowserSession = false - #if DEBUG - session.prefersEphemeralWebBrowserSession = args["ephemeral"] == "true" - #endif - self.session = session - if !session.start() { self.finish(nil, code: "unavailable") } - } - } - - private func finish(_ callback: String?, code: String) { - let result = pending - attemptID = nil - pending = nil - session = nil - if let callback { result?(callback) } - else { result?(FlutterError(code: code, message: nil, details: nil)) } - } - - func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { - UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } - .flatMap { $0.windows }.first(where: { $0.isKeyWindow }) ?? ASPresentationAnchor() - } -} diff --git a/mobile/ios/Runner/BuzzBrowserAuthBridge.swift b/mobile/ios/Runner/BuzzBrowserAuthBridge.swift new file mode 100644 index 0000000000..40c85a4c79 --- /dev/null +++ b/mobile/ios/Runner/BuzzBrowserAuthBridge.swift @@ -0,0 +1,110 @@ +import AuthenticationServices +import Flutter +import UIKit + +/// Keeps the authentication callback scoped to the system browser session. +final class BuzzBrowserAuthBridge: NSObject, ASWebAuthenticationPresentationContextProviding { + private let channel: FlutterMethodChannel + private var session: ASWebAuthenticationSession? + private var pending: FlutterResult? + private var attemptID: UUID? + + private let isActive: () -> Bool + private let startSession: (ASWebAuthenticationSession) -> Bool + private var activationObserver: NSObjectProtocol? + private var activationTimeout: DispatchWorkItem? + + init( + messenger: FlutterBinaryMessenger, + isActive: @escaping () -> Bool = { UIApplication.shared.applicationState == .active }, + startSession: @escaping (ASWebAuthenticationSession) -> Bool = { $0.start() } + ) { + self.isActive = isActive + self.startSession = startSession + channel = FlutterMethodChannel(name: "buzz/browser_auth", binaryMessenger: messenger) + super.init() + channel.setMethodCallHandler { [weak self] call, result in + guard let self else { return } + if call.method == "cancel" { + self.session?.cancel() + self.finish(nil, code: "cancelled") + result(nil) + return + } + guard call.method == "start" else { result(FlutterMethodNotImplemented); return } + guard self.session == nil, + let args = call.arguments as? [String: String], + let raw = args["url"], let url = URL(string: raw), + url.scheme == "https", + ["app.builderlab.xyz", "app.builderlabstaging.xyz"].contains(url.host ?? ""), + url.path == "/api/goose/v1/auth/login", url.user == nil, url.password == nil, + url.port == nil, url.fragment == nil + else { result(FlutterError(code: "unavailable", message: nil, details: nil)); return } + self.pending = result + let attemptID = UUID() + self.attemptID = attemptID + let session = ASWebAuthenticationSession(url: url, callbackURLScheme: "xyz.block.buzz.mobile") { [weak self] callback, error in + DispatchQueue.main.async { + guard self?.attemptID == attemptID else { return } + let cancelled = (error as? ASWebAuthenticationSessionError)?.code == .canceledLogin + self?.finish(callback?.absoluteString, code: cancelled ? "cancelled" : "unavailable") + } + } + session.presentationContextProvider = self + session.prefersEphemeralWebBrowserSession = false + #if DEBUG + session.prefersEphemeralWebBrowserSession = args["ephemeral"] == "true" + #endif + self.session = session + self.startWhenActive(attemptID) + + } + } + + // Safari delivers a deep link before UIKit finishes activating our app. + // ASWebAuthenticationSession.start() rejects presentation during that handoff. + private func startWhenActive(_ id: UUID) { + guard attemptID == id, let session else { return } + if isActive() { + clearActivationWait() + if !startSession(session) { finish(nil, code: "unavailable") } + return + } + activationObserver = NotificationCenter.default.addObserver( + forName: UIApplication.didBecomeActiveNotification, object: nil, queue: .main + ) { [weak self] _ in + guard let self, self.attemptID == id, self.isActive() else { return } + self.startWhenActive(id) + } + let timeout = DispatchWorkItem { [weak self] in + guard let self, self.attemptID == id else { return } + self.finish(nil, code: "unavailable") + } + activationTimeout = timeout + DispatchQueue.main.asyncAfter(deadline: .now() + 10, execute: timeout) + } + + private func clearActivationWait() { + if let activationObserver { NotificationCenter.default.removeObserver(activationObserver) } + activationObserver = nil + activationTimeout?.cancel() + activationTimeout = nil + } + + deinit { clearActivationWait() } + + private func finish(_ callback: String?, code: String) { + clearActivationWait() + let result = pending + attemptID = nil + pending = nil + session = nil + if let callback { result?(callback) } + else { result?(FlutterError(code: code, message: nil, details: nil)) } + } + + func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { + UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + .flatMap { $0.windows }.first(where: { $0.isKeyWindow }) ?? ASPresentationAnchor() + } +} diff --git a/mobile/ios/RunnerTests/BrowserAuthBridgeTests.swift b/mobile/ios/RunnerTests/BrowserAuthBridgeTests.swift new file mode 100644 index 0000000000..cce8b3b36b --- /dev/null +++ b/mobile/ios/RunnerTests/BrowserAuthBridgeTests.swift @@ -0,0 +1,65 @@ +import Flutter +import UIKit +import XCTest +@testable import Buzz + +final class BrowserAuthBridgeTests: XCTestCase { + @MainActor + func testInviteHandoffWaitsForActivationAndCancelledAttemptCannotReopen() { + let messenger = BrowserAuthTestMessenger() + var active = false + var starts = 0 + let bridge = BuzzBrowserAuthBridge(messenger: messenger, isActive: { active }, + startSession: { _ in starts += 1; return true }) + defer { withExtendedLifetime(bridge) {} } + let arguments = ["url": "https://app.builderlabstaging.xyz/api/goose/v1/auth/login"] + var results: [String] = [] + messenger.invoke("start", arguments: arguments) { + results.append(($0 as? FlutterError)?.code ?? "success") + } + XCTAssertEqual(starts, 0, "An incoming invite must not present auth while inactive") + XCTAssertTrue(results.isEmpty) + messenger.invoke("cancel", arguments: [:]) { _ in } + XCTAssertEqual(results, ["cancelled"]) + active = true + NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil) + XCTAssertEqual(starts, 0, "Cancelled handoffs must not reopen sign-in") + + active = false + messenger.invoke("start", arguments: arguments) { + results.append(($0 as? FlutterError)?.code ?? "success") + } + XCTAssertEqual(starts, 0) + active = true + NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil) + XCTAssertEqual(starts, 1, "Activation must present the original request without a retry") + NotificationCenter.default.post(name: UIApplication.didBecomeActiveNotification, object: nil) + XCTAssertEqual(starts, 1) + XCTAssertEqual(results, ["cancelled"]) + messenger.invoke("cancel", arguments: [:]) { _ in } + XCTAssertEqual(results, ["cancelled", "cancelled"]) + messenger.invoke("start", arguments: arguments) { _ in } + XCTAssertEqual(starts, 2, "Ordinary active-app login should start immediately") + messenger.invoke("cancel", arguments: [:]) { _ in } + } +} + +private final class BrowserAuthTestMessenger: NSObject, FlutterBinaryMessenger { + private var handler: FlutterBinaryMessageHandler? + func send(onChannel channel: String, message: Data?) {} + func send(onChannel channel: String, message: Data?, binaryReply callback: FlutterBinaryReply?) { + callback?(nil) + } + func setMessageHandlerOnChannel(_ channel: String, + binaryMessageHandler handler: FlutterBinaryMessageHandler?) -> FlutterBinaryMessengerConnection { + self.handler = handler + return 1 + } + func cleanUpConnection(_ connection: FlutterBinaryMessengerConnection) { handler = nil } + func invoke(_ method: String, arguments: [String: String], reply: @escaping (Any?) -> Void) { + let codec = FlutterStandardMethodCodec.sharedInstance() + handler?(codec.encode(FlutterMethodCall(methodName: method, arguments: arguments))) { + reply($0.flatMap { codec.decodeEnvelope($0) }) + } + } +}