Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

fix(mobile): reuse Safari's Google sign-ins on iOS

tony642370a48c8d
diff --git a/mobile/ios/Runner/AppDelegate.swift b/mobile/ios/Runner/AppDelegate.swift
index 2cfa7df10..95a5cb67c 100644
--- a/mobile/ios/Runner/AppDelegate.swift
+++ b/mobile/ios/Runner/AppDelegate.swift
@@ -1,5 +1,5 @@
+import AuthenticationServices
import Flutter
-import SafariServices
import UIKit
import UserNotifications
@@ -96,23 +96,32 @@ enum DeviceNameChannel {
}
}
-/// `harness/sign_in_page` — the SSO page, in an SFSafariViewController over the app (Dart:
-/// `lib/viewer/sign_in_browser.dart`). url_launcher's in-app page tells Dart nothing once its first
-/// load is over, so a page closed with Done left its sign-in waiting out five minutes behind
-/// "Waiting for Google…" and a Cancel. Here Done — or a swipe down — is said back: `closed`, with the
-/// id Dart opened the page with.
+/// `harness/sign_in_page` — the SSO page, in an ASWebAuthenticationSession over the app (Dart:
+/// `lib/viewer/sign_in_browser.dart`).
+///
+/// Not an SFSafariViewController, as it was: since iOS 11 that keeps cookies of its own, apart from
+/// Safari's, so the Google accounts the phone was signed in to were never there and every "Continue
+/// with Google" began on an empty sign-in form. This session shares Safari's — not ephemeral — at
+/// the price of iOS's "“Harness” Wants to Use … to Sign In" before the page.
+///
+/// The page's last screen goes on to [returnScheme] (Dart: `signInReturnUrl`), and the session takes
+/// the page down there by itself. Cancel — the alert's or the page's — is said back: `closed`, with
+/// the id Dart opened the page with.
///
/// `open` answers once the page is on its way up; `close` takes it down and says nothing, since Dart
/// asked.
-final class SignInPageChannel: NSObject, SFSafariViewControllerDelegate,
- UIAdaptivePresentationControllerDelegate
-{
+final class SignInPageChannel: NSObject, ASWebAuthenticationPresentationContextProviding {
private static var shared: SignInPageChannel?
+ /// Dart's `signInReturnUrl`: the loopback's last page goes there once the redirect is in.
+ private static let returnScheme = "ai.autonomous.harness.signin"
+
private let registrar: FlutterPluginRegistrar
private let channel: FlutterMethodChannel
- /// The page up now, and the id Dart opened it with; nil once it is closed or taken down.
- private var page: (controller: SFSafariViewController, id: Int)?
+ /// The page up now, the id Dart opened it with, and its own number here, which is what its session
+ /// ends with — Dart's ids start over on a hot restart. Nil once it is closed or taken down.
+ private var page: (session: ASWebAuthenticationSession, id: Int, serial: Int)?
+ private var serial = 0
static func register(with registry: FlutterPluginRegistry) {
guard let registrar = registry.registrar(forPlugin: "HarnessSignInPage") else { return }
@@ -142,7 +151,7 @@ final class SignInPageChannel: NSObject, SFSafariViewControllerDelegate,
}
open(url, id: id, result: result)
case "close":
- if let controller = take() { Self.takeDown(controller, animated: true) }
+ take()?.cancel()
result(nil)
default:
result(FlutterMethodNotImplemented)
@@ -151,67 +160,51 @@ final class SignInPageChannel: NSObject, SFSafariViewControllerDelegate,
private func open(_ url: URL, id: Int, result: @escaping FlutterResult) {
// One page at a time: one an earlier sign-in left up goes first, without a word to Dart.
- guard let old = take(), old.presentingViewController != nil else {
- present(url, id: id, result: result)
+ take()?.cancel()
+ guard window() != nil else {
+ result(FlutterError(code: "no-ui", message: "Nothing on screen to open it over", details: nil))
return
}
- Self.takeDown(old, animated: false) { self.present(url, id: id, result: result) }
- }
-
- private func present(_ url: URL, id: Int, result: @escaping FlutterResult) {
- var presenter = registrar.viewController
- while let presented = presenter?.presentedViewController, !presented.isBeingDismissed {
- presenter = presented
+ serial += 1
+ let serial = serial
+ let session = ASWebAuthenticationSession(
+ url: url, callbackURLScheme: Self.returnScheme
+ ) { [weak self] _, error in
+ DispatchQueue.main.async { self?.ended(serial, cancelled: error != nil) }
}
- guard let presenter else {
- result(FlutterError(code: "no-ui", message: "Nothing on screen to open it over", details: nil))
+ session.presentationContextProvider = self
+ // Safari's cookies, and with them the accounts the phone is already signed in to.
+ session.prefersEphemeralWebBrowserSession = false
+ page = (session, id, serial)
+ guard session.start() else {
+ page = nil
+ result(FlutterError(code: "no-ui", message: "The sign-in page would not open", details: nil))
return
}
- let controller = SFSafariViewController(url: url)
- controller.delegate = self
- // Shown as a sheet, it can also be swiped away, which its own delegate does not hear.
- controller.presentationController?.delegate = self
- page = (controller, id)
- presenter.present(controller, animated: true)
result(nil)
}
/// The page, no longer this channel's to watch.
- private func take() -> SFSafariViewController? {
- let controller = page?.controller
+ private func take() -> ASWebAuthenticationSession? {
+ let session = page?.session
page = nil
- return controller
- }
-
- /// Dismisses [controller] — once it is up, when it is still animating in: UIKit drops a dismiss
- /// made during a presentation, and the page would stay up over a sign-in that had ended.
- private static func takeDown(
- _ controller: UIViewController, animated: Bool, then: (() -> Void)? = nil
- ) {
- if controller.isBeingPresented, let coordinator = controller.transitionCoordinator,
- coordinator.animate(
- alongsideTransition: nil,
- completion: { _ in controller.dismiss(animated: animated, completion: then) })
- {
- return
- }
- controller.dismiss(animated: animated, completion: then)
+ return session
}
- /// The person closed [controller] — if it is still the page up, Dart is told.
- private func closedByPerson(_ controller: UIViewController) {
- guard let page, page.controller === controller else { return }
+ /// Session [serial] is over. Only a cancel by the person — or an error, which leaves no page either
+ /// — is Dart's to hear: at [returnScheme] the redirect is already in, and a `close` was Dart's own.
+ private func ended(_ serial: Int, cancelled: Bool) {
+ guard let page, page.serial == serial else { return }
self.page = nil
- channel.invokeMethod("closed", arguments: page.id)
+ if cancelled { channel.invokeMethod("closed", arguments: page.id) }
}
- // Done. The dismiss is url_launcher's own: harmless when the page has already gone by itself.
- func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
- closedByPerson(controller)
- controller.dismiss(animated: true)
+ /// The app's window, for the page to come up over.
+ private func window() -> UIWindow? {
+ registrar.viewController?.view.window
}
- func presentationControllerDidDismiss(_ presentationController: UIPresentationController) {
- closedByPerson(presentationController.presentedViewController)
+ func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {
+ window() ?? ASPresentationAnchor()
}
}
diff --git a/mobile/lib/viewer/direct_login.dart b/mobile/lib/viewer/direct_login.dart
index 295209538..bbedcd58e 100644
--- a/mobile/lib/viewer/direct_login.dart
+++ b/mobile/lib/viewer/direct_login.dart
@@ -247,8 +247,9 @@ class _LoopbackCallback {
}
}
-/// What the in-app page shows once the redirect lands. iOS takes it down by itself
-/// (`closeSignInPage`), so it only ever flashes there.
+/// What the in-app page shows once the redirect lands. On iOS it only ever flashes: the script goes
+/// on to [signInReturnUrl], where the auth session takes the page down (`SignInPageChannel`), and
+/// `closeSignInPage` does it anyway once the sign-in is in.
///
/// Android's Custom Tab stays up over the app, and nothing in the app can close it — so there the
/// page goes back to the app itself, through [signInReturnUrl] (`SignInReturnActivity`), which
@@ -261,7 +262,8 @@ String _page(String title) {
'text-decoration:none;font-weight:600">Back to Harness</a></p>'
'<p style="color:#666;font-size:14px">or close this page</p>'
'<script>location.replace("$signInReturnUrl")</script>'
- : '<p>Close this page to go back to Harness.</p>';
+ : '<p>Close this page to go back to Harness.</p>'
+ '<script>location.replace("$signInReturnUrl")</script>';
return '<!doctype html><meta charset="utf-8">'
'<meta name="viewport" content="width=device-width,initial-scale=1">'
'<title>$title</title>'
diff --git a/mobile/lib/viewer/sign_in_browser.dart b/mobile/lib/viewer/sign_in_browser.dart
index 6933c8bdc..d7c027b00 100644
--- a/mobile/lib/viewer/sign_in_browser.dart
+++ b/mobile/lib/viewer/sign_in_browser.dart
@@ -5,11 +5,14 @@ import 'package:flutter/services.dart';
import 'package:flutter/widgets.dart';
import 'package:url_launcher/url_launcher.dart';
-/// Where the SSO page opens: in the app — SFSafariViewController on iOS, a Custom Tab on Android —
-/// as the desktop's viewer build opens it on a phone (`desktop/lib/viewer/sign_in_browser.dart`).
+/// Where the SSO page opens: in the app — an ASWebAuthenticationSession on iOS, a Custom Tab on
+/// Android — each with the browser's own sign-ins (Safari's; the default browser's), so Google
+/// offers the accounts the phone is already signed in to.
///
/// Never the Safari or Chrome app: handing the person over suspends this app, and with it the
-/// loopback listener the page redirects back to (`direct_login.dart`).
+/// loopback listener the page redirects back to (`direct_login.dart`). Nor iOS's
+/// SFSafariViewController, url_launcher's in-app page there: its cookies are its own, apart from
+/// Safari's, and every "Continue with Google" began on an empty Google sign-in.
///
/// ⚠️ **Android is the weak side.** A Custom Tab covers the app, the process behind it can be
/// frozen, and the redirect then finds nobody listening — the Play review's "127.0.0.1 took too
@@ -17,7 +20,7 @@ import 'package:url_launcher/url_launcher.dart';
/// ([closeSignInPage]): on Android the page's last screen goes back to the app through
/// [signInReturnUrl] instead.
///
-/// [onClosed]: the person closed the page themselves — iOS's Done, Android's ✕ — before
+/// [onClosed]: the person closed the page themselves — iOS's Cancel, Android's ✕ — before
/// [closeSignInPage] took it down. url_launcher says nothing of it, and the sign-in the page was
/// for waited out its five minutes behind "Waiting for Google…" and a Cancel nobody had pressed.
/// Not told once the page has been taken down, nor once another page has been opened.
@@ -54,6 +57,9 @@ Future<void> openSignInPage(Uri url, {required VoidCallback onClosed}) async {
/// Where the Custom Tab's last page sends the person back to the app on Android: the scheme
/// `SignInReturnActivity` takes (`android/app/src/main/AndroidManifest.xml`), which brings the app
/// back over the tab and takes the tab down — the one thing [closeSignInPage] cannot do there.
+///
+/// On iOS it is where the auth session ends (`SignInPageChannel`): the page goes there and the
+/// session takes it down at once, ahead of [closeSignInPage].
const signInReturnUrl = 'ai.autonomous.harness.signin://signed-in';
/// Takes down what [openSignInPage] put up, where the platform can. Best effort.
@@ -68,8 +74,8 @@ Future<void> closeSignInPage() async {
} catch (_) {}
}
-/// iOS's page (`SignInPageChannel`, `ios/Runner/AppDelegate.swift`): url_launcher's
-/// SFSafariViewController cannot say when Done was pressed.
+/// iOS's page (`SignInPageChannel`, `ios/Runner/AppDelegate.swift`): an ASWebAuthenticationSession,
+/// which url_launcher does not offer, and which says when Cancel was pressed.
const _iosPage = MethodChannel('harness/sign_in_page');
/// The page [openSignInPage] last opened; bumped when it is let go, so what its platform says
diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml
index dbdb59678..504cd7ff6 100644
--- a/mobile/pubspec.yaml
+++ b/mobile/pubspec.yaml
@@ -30,9 +30,9 @@ dependencies:
dio: ^5.11.0
# The relay socket every machine is reached over (`ws/`).
web_socket_channel: ^3.0.3
- # "Continue with Google / Apple" opens the SSO page in the app — SFSafariViewController,
- # a Custom Tab (`viewer/sign_in_browser.dart`) — and the terminal opens links a program
- # printed (`terminal/terminal_link_opener.dart`).
+ # "Continue with Google / Apple" opens the SSO page in an Android Custom Tab
+ # (`viewer/sign_in_browser.dart`; iOS's is native, `SignInPageChannel`), and the terminal
+ # opens links a program printed (`terminal/terminal_link_opener.dart`).
url_launcher: ^6.3.2
# X25519/HKDF/ChaCha20-Poly1305 for the end-to-end encryption this app
# terminates itself, being a viewer (`e2ee/`).