mirror of
https://github.com/block/buzz.git
synced 2026-11-25 18:52:52 +00:00
fix(mobile): wait for app activation before browser auth (#8647)
## Summary Opening an invite from Safari can deliver the login request while iOS still considers Buzz inactive. `ASWebAuthenticationSession.start()` then returns false, showing a connection error until the user retries. Wait for app activation before starting the retained session, with a ten-second timeout and cancellation cleanup. Extract the existing browser-auth bridge from the size-limited AppDelegate and add one native journey test through its Flutter method channel. URL validation, callback fencing, and normal active-app login retain their existing behavior. Temporary diagnostic logging and generated dependency changes are excluded. ### Related issue No duplicate found in the open handoff/authentication search. Related invite-consent work: #8601; this fixes the subsequent iOS authentication presentation race. ### Testing - Focused `RunnerTests/BrowserAuthBridgeTests` passed on an iPhone 18 Pro / iOS 27 simulator. Covers inactive handoff, cancellation before activation, retry, duplicate activation notifications, and immediate active-app start. - A local build reproduced the original inactive-app `start=false` failure; the fixed build opened authentication on the first background-to-app attempt. The same fixed build subsequently completed an existing-account staging flow. - Mutation check passed in isolated source, Git metadata, and build outputs: clean control passed; bypassing the production activation wait failed the inactive-handoff assertion; restored source passed again, with its SHA-256 verified against the committed file. - Self-review found no blocking issue. CI and final review remain pending. Mandatory pre-commit and pre-push hooks passed, including mobile analysis and the hook-run Flutter suite. No full local suite was manually invoked. - Human acceptance: from Safari, tap **Accept invite in Buzz** and confirm sign-in opens on the first attempt without **Try again**. Final acceptance of this PR remains pending. The separately reported callback failure may have involved production rather than staging. That cause is unconfirmed and is outside this change. Signed-off-by: Wes <wesbillman@users.noreply.github.com> Co-authored-by: Brain <1a02c72794dcd0f07058a353bc3a81f4028b8c77c92c87fce6d5c8b85970a20b@buzz.block.builderlab.xyz>
This commit is contained in:
@@ -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 = "<group>"; };
|
||||
BC0010000000000000000002 /* BuzzBrowserAuthBridge.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = BuzzBrowserAuthBridge.swift; sourceTree = "<group>"; };
|
||||
F84380010000000000000002 /* ProfileSetupRecoveryTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProfileSetupRecoveryTests.swift; sourceTree = "<group>"; };
|
||||
BBAA00000000000000000012 /* IdentityFilePlugin.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = IdentityFilePlugin.swift; sourceTree = "<group>"; };
|
||||
BBAA00000000000000000002 /* HostedHpkeBackup.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HostedHpkeBackup.swift; sourceTree = "<group>"; };
|
||||
@@ -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 */,
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
}
|
||||
|
||||
110
mobile/ios/Runner/BuzzBrowserAuthBridge.swift
Normal file
110
mobile/ios/Runner/BuzzBrowserAuthBridge.swift
Normal file
@@ -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()
|
||||
}
|
||||
}
|
||||
65
mobile/ios/RunnerTests/BrowserAuthBridgeTests.swift
Normal file
65
mobile/ios/RunnerTests/BrowserAuthBridgeTests.swift
Normal file
@@ -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) })
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user