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.

feat(mobile): sign in with Google or Apple

tonya3c4ca575d5a
diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xml
index 45e4e68c6..91a212ed5 100644
--- a/mobile/android/app/src/main/AndroidManifest.xml
+++ b/mobile/android/app/src/main/AndroidManifest.xml
@@ -49,6 +49,26 @@
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
+ <!-- "Back to Harness" on the last page of "Continue with Google / Apple": brings the app
+ back over the Custom Tab the sign-in ran in, and takes the tab down with it (see
+ SignInReturnActivity.kt). It carries nothing and does nothing else, so being
+ reachable by any link that names its scheme costs nothing. Its own empty affinity,
+ no history and no Recents entry: it is a hop, never a screen. The scheme is
+ `signInReturnUrl` in lib/viewer/sign_in_browser.dart. -->
+ <activity
+ android:name=".SignInReturnActivity"
+ android:exported="true"
+ android:excludeFromRecents="true"
+ android:noHistory="true"
+ android:taskAffinity=""
+ android:theme="@android:style/Theme.Translucent.NoTitleBar">
+ <intent-filter>
+ <action android:name="android.intent.action.VIEW" />
+ <category android:name="android.intent.category.DEFAULT" />
+ <category android:name="android.intent.category.BROWSABLE" />
+ <data android:scheme="ai.autonomous.harness.signin" />
+ </intent-filter>
+ </activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
diff --git a/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/SignInReturnActivity.kt b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/SignInReturnActivity.kt
new file mode 100644
index 000000000..63f868e38
--- /dev/null
+++ b/mobile/android/app/src/main/kotlin/ai/autonomous/harness/android/SignInReturnActivity.kt
@@ -0,0 +1,36 @@
+package ai.autonomous.harness.android
+
+import android.app.Activity
+import android.content.Intent
+import android.os.Bundle
+
+/**
+ * Where "Continue with Google / Apple" comes back to the app on Android (Dart:
+ * `lib/viewer/direct_login.dart`, `lib/viewer/sign_in_browser.dart`).
+ *
+ * The sign-in page runs in a Custom Tab, which is Chrome's and which this app cannot close: once the
+ * redirect has reached the app's loopback listener and the session is saved, the tab's last page
+ * ("Signed in to Harness") still sits over the app. Its "Back to Harness" opens
+ * `ai.autonomous.harness.signin://`, which lands here.
+ *
+ * ⚠️ **Why a hop through here and not straight to [MainActivity].** The Custom Tab lives in
+ * MainActivity's own task, ABOVE it. Started directly, MainActivity would come up as a second
+ * instance — a second Flutter engine — on top of the tab. From here it is started with
+ * NEW_TASK | CLEAR_TOP | SINGLE_TOP instead: NEW_TASK finds the task MainActivity already roots,
+ * CLEAR_TOP finishes what is above it (the tab), and SINGLE_TOP hands the running instance the intent
+ * rather than recreating it. The intent carries no data, so Flutter pushes no route. This is AppAuth's
+ * redirect pattern, for a redirect this app receives on 127.0.0.1 rather than on a scheme.
+ */
+class SignInReturnActivity : Activity() {
+ override fun onCreate(savedInstanceState: Bundle?) {
+ super.onCreate(savedInstanceState)
+ startActivity(
+ Intent(this, MainActivity::class.java).addFlags(
+ Intent.FLAG_ACTIVITY_NEW_TASK or
+ Intent.FLAG_ACTIVITY_CLEAR_TOP or
+ Intent.FLAG_ACTIVITY_SINGLE_TOP
+ )
+ )
+ finish()
+ }
+}
diff --git a/mobile/assets/sign-in/2.0x/apple.png b/mobile/assets/sign-in/2.0x/apple.png
new file mode 100644
index 000000000..9fcc7cba8
Binary files /dev/null and b/mobile/assets/sign-in/2.0x/apple.png differ
diff --git a/mobile/assets/sign-in/2.0x/google.png b/mobile/assets/sign-in/2.0x/google.png
new file mode 100644
index 000000000..7074e2622
Binary files /dev/null and b/mobile/assets/sign-in/2.0x/google.png differ
diff --git a/mobile/assets/sign-in/3.0x/apple.png b/mobile/assets/sign-in/3.0x/apple.png
new file mode 100644
index 000000000..9048ed0f4
Binary files /dev/null and b/mobile/assets/sign-in/3.0x/apple.png differ
diff --git a/mobile/assets/sign-in/3.0x/google.png b/mobile/assets/sign-in/3.0x/google.png
new file mode 100644
index 000000000..f677e4de2
Binary files /dev/null and b/mobile/assets/sign-in/3.0x/google.png differ
diff --git a/mobile/assets/sign-in/apple.png b/mobile/assets/sign-in/apple.png
new file mode 100644
index 000000000..4c040cf5a
Binary files /dev/null and b/mobile/assets/sign-in/apple.png differ
diff --git a/mobile/assets/sign-in/google.png b/mobile/assets/sign-in/google.png
new file mode 100644
index 000000000..7d75816eb
Binary files /dev/null and b/mobile/assets/sign-in/google.png differ
diff --git a/mobile/lib/auth/auth_session.dart b/mobile/lib/auth/auth_session.dart
index bd15a0591..c8bee3f58 100644
--- a/mobile/lib/auth/auth_session.dart
+++ b/mobile/lib/auth/auth_session.dart
@@ -30,6 +30,7 @@ class AuthSession {
static const _env = 'auth_autonomous_env';
static const _expiresAt = 'auth_access_token_expires_at';
static const _issuer = 'auth_session_issuer';
+ static const _ssoClientId = 'auth_sso_client_id';
AuthSession({LocalKeyValueStore? storage})
: _storage = storage ?? HarnessFileStore.shared;
@@ -42,6 +43,7 @@ class AuthSession {
String autonomousEnv = 'prod',
int? expiresIn,
SessionIssuer issuer = SessionIssuer.sso,
+ String? ssoClientId,
}) async {
await _storage.write(_access, token);
await _storage.write(_issuer, issuer.name);
@@ -51,6 +53,12 @@ class AuthSession {
await _storage.delete(_refresh);
}
await _storage.write(_env, autonomousEnv);
+ // Belongs to this sign-in alone: one that names no client must not inherit the last one's.
+ if (ssoClientId != null && ssoClientId.isNotEmpty) {
+ await _storage.write(_ssoClientId, ssoClientId);
+ } else {
+ await _storage.delete(_ssoClientId);
+ }
await _saveExpiry(expiresIn);
}
@@ -74,6 +82,11 @@ class AuthSession {
Future<String?> refreshToken() => _storage.read(_refresh);
Future<String> autonomousEnv() async => (await _storage.read(_env)) ?? 'prod';
+ /// The auth-service client this session was issued to, which a refresh names again. Null is
+ /// the backend's configured one: every session saved before the clients were split, and any
+ /// session that did not come from the SSO page.
+ Future<String?> ssoClientId() => _storage.read(_ssoClientId);
+
/// A session saved before this was recorded came from the SSO flow — the only
/// one there was.
Future<SessionIssuer> issuer() async {
@@ -126,5 +139,6 @@ class AuthSession {
await _storage.delete(_env);
await _storage.delete(_expiresAt);
await _storage.delete(_issuer);
+ await _storage.delete(_ssoClientId);
}
}
diff --git a/mobile/lib/auth/sign_in_client.dart b/mobile/lib/auth/sign_in_client.dart
index 030cca8be..4bcab1eaf 100644
--- a/mobile/lib/auth/sign_in_client.dart
+++ b/mobile/lib/auth/sign_in_client.dart
@@ -5,7 +5,8 @@ import 'cli_login.dart';
///
/// The phone holds its own session (`viewer/direct_login.dart`); a desktop build asks the local
/// harness CLI instead, which holds it there. How a phone signs IN is not here: an emailed code or
-/// a scanned one (`viewer/email_code_login.dart`), which no CLI build has.
+/// a scanned one (`viewer/email_code_login.dart`), or a Google or Apple account through the SSO
+/// page (`viewer/direct_login.dart` `login`).
abstract interface class SignInClient {
Future<CliAuthStatus> checkStatus();
diff --git a/mobile/lib/auth/sign_in_provider.dart b/mobile/lib/auth/sign_in_provider.dart
new file mode 100644
index 000000000..02c12e501
--- /dev/null
+++ b/mobile/lib/auth/sign_in_provider.dart
@@ -0,0 +1,14 @@
+/// The account a sign-in goes straight to: the welcome screen's two buttons, the backend's
+/// `provider` (`SIGN_IN_PROVIDERS` in `backend/src/lib/sso.ts`) — the desktop's
+/// `auth/sign_in_provider.dart`, the same two in the same order.
+///
+/// [name] is the wire form.
+enum SignInProvider {
+ google('Google'),
+ apple('Apple');
+
+ const SignInProvider(this.label);
+
+ /// How the provider is written for a person.
+ final String label;
+}
diff --git a/mobile/lib/phone/agent_home.dart b/mobile/lib/phone/agent_home.dart
index 6116f64f6..b945c32c2 100644
--- a/mobile/lib/phone/agent_home.dart
+++ b/mobile/lib/phone/agent_home.dart
@@ -574,9 +574,17 @@ class _AgentHomeState extends State<AgentHome> {
// that agent is genuinely on its way.
if (machines.any(phoneMachineListsAgents)) return null;
// Then each machine's own socket. `connecting` covers both the dial and the handshake after it.
+ //
+ // ⚠️ A machine locked while the device key log is still being read counts as connecting: on a
+ // phone just signed in, every machine is locked until the log vouches for it, which it does a
+ // few seconds later and opens the machine by itself — see [AppNotifier.deviceTrustSettling].
+ // Drawn as the machines list meanwhile, it said "locked · scan its code" and then jumped away.
if (machines.any(
- (machine) =>
- phoneMachineStatusOf(machine) == PhoneMachineStatus.connecting,
+ (machine) => switch (phoneMachineStatusOf(machine)) {
+ PhoneMachineStatus.connecting => true,
+ PhoneMachineStatus.needsPassword => notifier.deviceTrustSettling,
+ PhoneMachineStatus.ready || PhoneMachineStatus.offline => false,
+ },
)) {
return 'Connecting to your machine…';
}
diff --git a/mobile/lib/phone/welcome/phone_welcome.dart b/mobile/lib/phone/welcome/phone_welcome.dart
index 4a4253f89..b00780e07 100644
--- a/mobile/lib/phone/welcome/phone_welcome.dart
+++ b/mobile/lib/phone/welcome/phone_welcome.dart
@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:lucide_icons_flutter/lucide_icons.dart';
+import 'package:harness_mobile/auth/sign_in_provider.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/state/app_state.dart';
@@ -13,9 +14,10 @@ import '../tty_controls.dart';
import 'connect_code.dart';
import 'scan_to_connect.dart';
import 'set_up_computer.dart';
+import 'sign_in_provider_button.dart';
-/// The phone's first screen, signed out: what Harness is in one breath, and one question anyone
-/// can answer — is Harness on your computer?
+/// The phone's first screen, signed out: what Harness is in one breath, one question anyone can
+/// answer — is Harness on your computer? — and the account, for whoever would rather start there.
///
/// ```
/// harness▌
@@ -31,6 +33,13 @@ import 'set_up_computer.dart';
/// ┌──────────────────────────────┐
/// │ Not yet — set it up › │
/// └──────────────────────────────┘
+/// ──────── or sign in with ────────
+/// ┌──────────────────────────────┐
+/// │ G Continue with Google │
+/// └──────────────────────────────┘
+/// ┌──────────────────────────────┐
+/// │ Continue with Apple │
+/// └──────────────────────────────┘
/// ```
///
/// **Yes** scans the code the desktop app shows ([ScanToConnectPage]), and the scan signs the phone
@@ -38,8 +47,11 @@ import 'set_up_computer.dart';
/// ([AppNotifier.signInWithScan]). A QR without one — an older computer — or one that has expired
/// names the account instead: the email is filled in and its code sent, so signing in is the four
/// digits (`viewer/email_code_api.dart`, no browser). **Not yet** gets Harness onto the computer ([SetUpComputerPage]). Both
-/// buttons weigh the same: the question decides, not us. Nothing else is on the screen — no
-/// pretend agents, no diagram — for someone who has never seen Harness.
+/// buttons weigh the same: the question decides, not us.
+///
+/// Under them, the two accounts the desktop and web sign in with ([SignInProviderButton]): the
+/// SSO page opens in the app on that account ([AppNotifier.signInWithProvider]). Nothing else is
+/// on the screen — no pretend agents, no diagram — for someone who has never seen Harness.
class PhoneWelcome extends StatefulWidget {
const PhoneWelcome({
super.key,
@@ -136,7 +148,23 @@ class _PhoneWelcomeState extends State<PhoneWelcome> {
unawaited(_sendCode());
}
+ /// "Continue with Google / Apple": the account's own sign-in page, in the app. Its failure is
+ /// said here, under the buttons; a cancel says nothing ([AppNotifier.signInWithProvider]).
+ Future<void> _signInWith(SignInProvider provider) async {
+ if (widget.notifier.signingIn) return;
+ setState(() => _error = null);
+ try {
+ await widget.notifier.signInWithProvider(provider);
+ } catch (e) {
+ if (!mounted) return;
+ setState(() => _error = _plain(e.toString()));
+ }
+ }
+
void _go(_Step step) {
+ // Leaving for another way in takes the account's page with it: whatever it came back with
+ // would sign the phone in behind the step the person chose instead.
+ if (step != _Step.hello) widget.notifier.cancelProviderSignIn();
setState(() {
_step = step;
_error = null;
@@ -237,6 +265,17 @@ class _PhoneWelcomeState extends State<PhoneWelcome> {
onSample: widget.onTrySample == null
? null
: () => unawaited(_trySample()),
+ onProvider: signingIn
+ ? null
+ : (provider) => unawaited(_signInWith(provider)),
+ waitingOn: widget.notifier.signInProvider,
+ // Past the page and the exchange, the session is saved and the machines are on
+ // their way: nothing is waited on in the browser any more, and nothing to cancel.
+ entering:
+ signingIn &&
+ widget.notifier.status == AppStatus.bootstrapping,
+ onCancel: widget.notifier.cancelProviderSignIn,
+ error: _error,
),
_Step.setUp => SetUpComputerPage(
onScan: () => _go(_Step.scan),
@@ -328,9 +367,19 @@ class _PhoneWelcomeState extends State<PhoneWelcome> {
}
}
-/// The first thing anyone sees: the headline, the question and its two answers.
+/// The first thing anyone sees: the headline, the question and its two answers, and the two
+/// accounts under them.
class _Hello extends StatelessWidget {
- const _Hello({required this.onScan, required this.onSetUp, this.onSample});
+ const _Hello({
+ required this.onScan,
+ required this.onSetUp,
+ required this.onProvider,
+ required this.onCancel,
+ this.onSample,
+ this.waitingOn,
+ this.entering = false,
+ this.error,
+ });
final VoidCallback onScan;
final VoidCallback onSetUp;
@@ -338,6 +387,20 @@ class _Hello extends StatelessWidget {
/// Behind a long press on the wordmark — see `_PhoneWelcomeState._trySample`.
final VoidCallback? onSample;
+ /// "Continue with …" pressed. Null while any sign-in is in flight, which both buttons wait out.
+ final ValueChanged<SignInProvider>? onProvider;
+
+ /// The account whose page is up — its button says so, and [onCancel] is offered under it.
+ final SignInProvider? waitingOn;
+
+ /// The page is done with and the phone is going in: the button says so, and there is nothing
+ /// left to cancel.
+ final bool entering;
+ final VoidCallback onCancel;
+
+ /// Why the last account's sign-in did not finish.
+ final String? error;
+
@override
Widget build(BuildContext context) {
final tty = Tty.of(context);
@@ -392,6 +455,41 @@ class _Hello extends StatelessWidget {
_Answer(label: 'Yes — scan to connect', onTap: onScan),
const SizedBox(height: 10),
_Answer(label: 'Not yet — set it up', onTap: onSetUp),
+ const SizedBox(height: 18),
+ const _OrDivider(label: 'or sign in with'),
+ const SizedBox(height: 14),
+ for (final provider in SignInProvider.values) ...[
+ if (provider != SignInProvider.values.first)
+ const SizedBox(height: 10),
+ SignInProviderButton(
+ provider: provider,
+ onPressed: onProvider == null
+ ? null
+ : () => onProvider!(provider),
+ busyLabel: provider == waitingOn
+ ? (entering
+ ? 'Signing in…'
+ : 'Waiting for ${provider.label}…')
+ : null,
+ ),
+ ],
+ if (error case final error?)
+ Padding(
+ padding: const EdgeInsets.only(top: 10),
+ child: Text(
+ '✗ $error',
+ style: tty.style(size: TtySize.meta, color: tty.red),
+ ),
+ ),
+ if (waitingOn != null && !entering) ...[
+ const SizedBox(height: 4),
+ Center(
+ child: TtyTextButton(
+ label: 'Cancel',
+ onPressed: onCancel,
+ ),
+ ),
+ ],
if (onSample != null) ...[
const SizedBox(height: 8),
TtyTextButton(label: 'Try the sample', onPressed: onSample),
@@ -452,6 +550,32 @@ class _Answer extends StatelessWidget {
}
}
+/// The line between the question's answers and the accounts: a rule each side of a few faint
+/// words, in the terminal's own furniture colour.
+class _OrDivider extends StatelessWidget {
+ const _OrDivider({required this.label});
+
+ final String label;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final rule = Expanded(child: Container(height: 1, color: tty.dim));
+ return Row(
+ children: [
+ rule,
+ // Its own width: at the app's largest text size (2x) it is still well inside a 375pt
+ // phone, and the rules give way around it.
+ Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 10),
+ child: TtyText(label, color: tty.faint, size: TtySize.meta),
+ ),
+ rule,
+ ],
+ );
+ }
+}
+
/// One step of signing in: back, a title, a line or two, a field, the button.
class _Form extends StatelessWidget {
const _Form({
diff --git a/mobile/lib/phone/welcome/sign_in_provider_button.dart b/mobile/lib/phone/welcome/sign_in_provider_button.dart
new file mode 100644
index 000000000..e02dda83a
--- /dev/null
+++ b/mobile/lib/phone/welcome/sign_in_provider_button.dart
@@ -0,0 +1,149 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+import 'package:harness_mobile/auth/sign_in_provider.dart';
+
+import '../tty.dart';
+import '../tty_controls.dart';
+
+/// One of the welcome screen's two accounts: "Continue with Google", "Continue with Apple" — the
+/// desktop's login buttons (`desktop/lib/widgets/sign_in_provider_button.dart`), on a phone.
+///
+/// Each wears its provider's own colours rather than the terminal's — Google's white with its
+/// four-colour mark, Apple's black with a white one — because that is how a person recognises
+/// them, and what both providers ask of a button that signs in with them. The shape and the type
+/// stay the phone's: the welcome rows' height and corners, the terminal's face.
+///
+/// The marks are `assets/sign-in/`, drawn from the desktop's `assets/sign-in/*.svg` by
+/// `scripts/render_svg.swift` at 1x, 2x and 3x — this app draws no SVG (see `pubspec.yaml`).
+class SignInProviderButton extends StatefulWidget {
+ const SignInProviderButton({
+ super.key,
+ required this.provider,
+ required this.onPressed,
+ this.busyLabel,
+ });
+
+ final SignInProvider provider;
+
+ /// Null while a sign-in is in flight, on this button or on the other.
+ final VoidCallback? onPressed;
+
+ /// What this button says while ITS sign-in is in flight; a spinner takes the mark's place.
+ /// Disabled without one is the other button's sign-in, and this one steps back.
+ final String? busyLabel;
+
+ /// The welcome rows' own height: the two accounts sit under the question's two answers.
+ static const double height = 52;
+
+ static const double _markSize = 18;
+
+ @override
+ State<SignInProviderButton> createState() => _SignInProviderButtonState();
+}
+
+class _SignInProviderButtonState extends State<SignInProviderButton> {
+ bool _down = false;
+
+ @override
+ Widget build(BuildContext context) {
+ final tty = Tty.of(context);
+ final look = _look(widget.provider, light: tty.isLight);
+ final busy = widget.busyLabel != null;
+ final enabled = widget.onPressed != null;
+ final label = widget.busyLabel ?? 'Continue with ${widget.provider.label}';
+ return Semantics(
+ button: true,
+ enabled: enabled,
+ label: label,
+ excludeSemantics: true,
+ child: Opacity(
+ // The button that is working stays itself; only the one that cannot be pressed steps back.
+ opacity: !enabled && !busy ? .5 : 1,
+ child: GestureDetector(
+ key: Key('welcome-continue-${widget.provider.name}'),
+ behavior: HitTestBehavior.opaque,
+ onTapDown: enabled ? (_) => setState(() => _down = true) : null,
+ onTapCancel: enabled ? () => setState(() => _down = false) : null,
+ onTapUp: enabled ? (_) => setState(() => _down = false) : null,
+ onTap: enabled
+ ? () {
+ HapticFeedback.lightImpact();
+ widget.onPressed!();
+ }
+ : null,
+ child: Container(
+ // At least this tall, and taller when the text is larger — never clipped.
+ constraints: const BoxConstraints(
+ minHeight: SignInProviderButton.height,
+ ),
+ padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
+ decoration: BoxDecoration(
+ // Pressed, it darkens on the finger's way DOWN, as the phone's other buttons do.
+ color: _down
+ ? Color.alphaBlend(look.ink.withValues(alpha: .12), look.fill)
+ : look.fill,
+ border: Border.all(color: look.rim),
+ borderRadius: BorderRadius.circular(10),
+ ),
+ child: Row(
+ mainAxisAlignment: MainAxisAlignment.center,
+ children: [
+ SizedBox.square(
+ dimension: SignInProviderButton._markSize,
+ child: busy
+ ? CircularProgressIndicator(
+ strokeWidth: 2,
+ color: look.ink,
+ )
+ : _mark(look),
+ ),
+ const SizedBox(width: 10),
+ Flexible(
+ child: TtyText(
+ label,
+ color: look.ink,
+ weight: FontWeight.w600,
+ size: TtySize.row,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+
+ Widget _mark(_ProviderLook look) => Image.asset(
+ 'assets/sign-in/${widget.provider.name}.png',
+ width: SignInProviderButton._markSize,
+ height: SignInProviderButton._markSize,
+ filterQuality: FilterQuality.medium,
+ // Google's mark is its four colours; Apple's is one shape in the button's ink.
+ color: look.tintMark ? look.ink : null,
+ colorBlendMode: look.tintMark ? BlendMode.srcIn : null,
+ );
+}
+
+/// A provider's own colours. Not the terminal's: they are the providers' brands, the same on a
+/// light ground and a dark one — except the rim, which each wears only on the ground it would
+/// otherwise melt into: Google's white on a light one, Apple's black on a dark one. Where the fill
+/// already stands apart the rim is the fill's own colour, so neither reads a line larger.
+typedef _ProviderLook = ({Color fill, Color ink, Color rim, bool tintMark});
+
+_ProviderLook _look(SignInProvider provider, {required bool light}) =>
+ switch (provider) {
+ SignInProvider.google => (
+ fill: Colors.white,
+ ink: const Color(0xFF1F1F1F),
+ rim: light ? const Color(0xFFDADCE0) : Colors.white,
+ tintMark: false,
+ ),
+ SignInProvider.apple => (
+ fill: Colors.black,
+ ink: Colors.white,
+ rim: light ? Colors.black : const Color(0x3DFFFFFF),
+ tintMark: true,
+ ),
+ };
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 4d1f55b5e..186ca678a 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -10,11 +10,14 @@ import '../teams/team_controller.dart';
import '../api/api_client.dart';
import '../viewer/direct_auth_api.dart';
import '../viewer/direct_link.dart';
+import '../viewer/direct_login.dart';
import '../viewer/group_sync.dart';
+import '../viewer/sign_in_browser.dart';
import '../viewer/viewer_services.dart';
import '../auth/auth_session.dart';
import '../auth/peer_link_client.dart';
import '../auth/sign_in_client.dart';
+import '../auth/sign_in_provider.dart';
import '../auth/cli_link.dart';
import '../core/config.dart';
import '../core/agent_git_context.dart';
@@ -360,6 +363,10 @@ class AppNotifier extends ChangeNotifier {
_profileInFlight = null;
_retryInFlight = null;
machinesLoading = false;
+ _registeringDevice = false;
+ _deviceRegisteredAt = null;
+ _awaitingVouched.clear();
+ _vouchedRedials.clear();
return ++_authRevision;
}
@@ -953,6 +960,10 @@ class AppNotifier extends ChangeNotifier {
/// while it is set, rather than dropping them onto a bare full-screen spinner.
bool signingIn = false;
+ /// The account whose sign-in page is up, from the press of its button until the flow settles —
+ /// so the welcome screen's pressed button says what it is waiting on, and only it.
+ SignInProvider? signInProvider;
+
AppNotifier({
required AppConfig config,
required AuthSession authSession,
@@ -1417,6 +1428,7 @@ class AppNotifier extends ChangeNotifier {
_invalidateAuthWork();
currentUser = null;
signingIn = false;
+ signInProvider = null;
// The code was scanned into the session that just ended — see [logout].
pendingPairing = null;
_desk.reset();
@@ -1512,6 +1524,76 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// Sign in with [provider]'s account — "Continue with Google", "Continue with Apple" — through
+ /// the SSO page, opened in the app (`viewer/direct_login.dart`, `viewer/sign_in_browser.dart`),
+ /// and go in.
+ ///
+ /// Thrown and kept like [signInWithCode], for the welcome screen to show — except a cancel
+ /// ([cancelProviderSignIn]), which the person chose and needs no sentence.
+ Future<void> signInWithProvider(SignInProvider provider) async {
+ final login = viewer.login;
+ if (_disposed || signingIn) return;
+ final revision = _invalidateAuthWork();
+ _closedHistory.clear();
+ _lastError = null;
+ signingIn = true;
+ signInProvider = provider;
+ notifyListeners();
+ try {
+ await login.login(
+ provider: provider,
+ onAuthorizeUrl: (url) =>
+ unawaited(_openSignInPage(url, login, revision)),
+ );
+ // iOS takes its sheet down here; Android's Custom Tab is the person's to close.
+ unawaited(closeSignInPage());
+ if (!_authWorkCurrent(revision)) return;
+ status = AppStatus.bootstrapping;
+ notifyListeners();
+ await _enterSignedIn(revision);
+ } on SignInCancelled {
+ unawaited(closeSignInPage());
+ if (_authWorkCurrent(revision)) status = AppStatus.unauthenticated;
+ } catch (_) {
+ unawaited(closeSignInPage());
+ if (_authWorkCurrent(revision)) status = AppStatus.unauthenticated;
+ rethrow;
+ } finally {
+ if (_authWorkCurrent(revision)) {
+ signingIn = false;
+ signInProvider = null;
+ notifyListeners();
+ }
+ }
+ }
+
+ /// The page [signInWithProvider] waits on, shown. One that cannot be shown ends that sign-in
+ /// with the reason — it would otherwise wait out its timeout on a page nobody can see — but
+ /// only while it is still the sign-in in flight: a later one is not this failure's to end.
+ Future<void> _openSignInPage(Uri url, DirectLogin login, int revision) async {
+ DirectAuthException reason;
+ try {
+ if (await openSignInPage(url)) return;
+ // iOS answers false for a page closed before it had loaded: the person's own cancel.
+ reason = const SignInCancelled();
+ } catch (error) {
+ debugPrint('signInWithProvider: could not open the sign-in page: $error');
+ reason = const DirectAuthException(
+ 'Could not open the sign-in page. Check your connection and try again.',
+ );
+ }
+ if (_authWorkCurrent(revision) && signInProvider != null) {
+ login.cancel(reason);
+ }
+ }
+
+ /// Stop the sign-in [signInWithProvider] is waiting on — the person closed the page, or chose
+ /// another way in. The welcome screen settles back with nothing to report.
+ void cancelProviderSignIn() {
+ if (signInProvider == null) return;
+ viewer.login.cancel();
+ }
+
Future<void> logout() async {
// Signing out takes this phone's key out of the account's devices, while the sign-in still works
// to say so. Best effort, and brief.
@@ -1522,6 +1604,7 @@ class AppNotifier extends ChangeNotifier {
}
final revision = _invalidateAuthWork();
signingIn = false;
+ signInProvider = null;
// A scanned code belongs to the session it was scanned into. Held past this,
// the next sign-in — perhaps another account's — would spend it on the first
// locked machine of that id and show a pairing error where its password form
@@ -1590,6 +1673,9 @@ class AppNotifier extends ChangeNotifier {
// few seconds for a `harness link connect` run elsewhere, which a phone's links never come from.
machine.needsLink = true;
machine.agentLoadStatus = AgentLoadStatus.needsLink;
+ // …unless the log already vouches for it and this phone's key is new to it: then the machine
+ // has only not read that key yet — see [_redialOnceVouched].
+ unawaited(_redialOnceVouched(machineId));
// A 4404 can also arrive MID-SESSION ("peer revoked trust" in the CLI's
// remoteRelay.ts) with terminals open on this machine. The disconnect
// that follows deliberately no longer marks the node offline (see the
@@ -1645,6 +1731,8 @@ class AppNotifier extends ChangeNotifier {
if (nextStatus == ConnectionStatus.connected) {
_refreshDeviceLogAfterReconnect();
machine.needsLink = false;
+ // Let in: a later refusal is a new story ([_redialOnceVouched]).
+ _vouchedRedials.remove(machineId);
// A relay socket reports `connected` only after the machine's welcome
// proved the link (`WsConn._markReady`), so a code held to pair this
// machine has nothing left to do. Kept, it would be spent the next time
@@ -1720,7 +1808,9 @@ class AppNotifier extends ChangeNotifier {
// before the log existed), and every machine it names is reached with no password.
if (_authWorkCurrent(revision) && status == AppStatus.authenticated && _deviceLogRegistered != revision) {
_deviceLogRegistered = revision;
- unawaited(_deviceLog?.register(freshSignIn: viewer.auth.consumeFreshSignIn()));
+ if (_deviceLog case final log?) {
+ unawaited(_registerDevice(log, revision));
+ }
}
} finally {
// Said out loud: the list's own notify fires before this, so a flag
@@ -2095,6 +2185,104 @@ class AppNotifier extends ChangeNotifier {
if (links is DirectLink) links.deviceLog = log;
}
+ /// True while trust between this phone and the account's machines is still being settled by the
+ /// device key log: this phone reading the log and putting its own key into it
+ /// ([ViewerDeviceLog.register]), or a machine the log vouches for being dialled again because it
+ /// had not caught up with this phone's key yet ([_redialOnceVouched]).
+ ///
+ /// ⚠️ **A machine is "locked" the moment a fresh phone dials it, and that is not yet an answer.**
+ /// With nothing pinned, the relay codec refuses the dial on the spot (`NO_PEER_LINK`, 16ms in), long
+ /// before the log has been read and verified — seconds on a phone; and once it is, the machine
+ /// itself still has to read this phone's new key before it stops answering `e2e_denied`. The home
+ /// screen fell through to the machines list, "locked · scan its code", in between. While this is
+ /// set it waits on a locked machine instead (`phone/agent_home.dart` `_loadingMessage`); once it
+ /// clears, a machine still locked really wants its password.
+ bool get deviceTrustSettling =>
+ _registeringDevice || _awaitingVouched.isNotEmpty;
+
+ bool _registeringDevice = false;
+
+ /// When this phone's key last went into the log, in this sign-in — see [_vouchedRedialWindow].
+ DateTime? _deviceRegisteredAt;
+
+ /// Machines waiting out a [_vouchedRedialDelays] step, and how many each has been through.
+ final Set<String> _awaitingVouched = {};
+ final Map<String, int> _vouchedRedials = {};
+
+ /// [_deviceTrustSettleCap]: a log that never answers still lets the screen move on.
+ static const _deviceTrustSettleCap = Duration(seconds: 20);
+
+ /// How long after this phone's key went into the log a machine the log vouches for may still not
+ /// have read it — its CLI hears `device_keys_changed` and reads the log itself, a few seconds.
+ static const _vouchedRedialWindow = Duration(minutes: 1);
+ static const _vouchedRedialDelays = [
+ Duration(milliseconds: 1500),
+ Duration(seconds: 3),
+ Duration(seconds: 5),
+ Duration(seconds: 8),
+ Duration(seconds: 12),
+ ];
+
+ Future<void> _registerDevice(ViewerDeviceLog log, int revision) async {
+ _registeringDevice = true;
+ notifyListeners();
+ try {
+ await log
+ .register(freshSignIn: viewer.auth.consumeFreshSignIn())
+ .timeout(_deviceTrustSettleCap);
+ } catch (_) {
+ // Timed out: the register goes on by itself, and a machine it vouches for is still redialled.
+ } finally {
+ if (_authWorkCurrent(revision)) {
+ _registeringDevice = false;
+ _deviceRegisteredAt = DateTime.now();
+ notifyListeners();
+ }
+ }
+ }
+
+ /// A machine refused this phone ([_onLocalFailure]) although the device key log vouches for it —
+ /// this phone pins it — while this phone's own key is new to the log: the machine has most likely
+ /// just not read that key yet, so it is dialled again, a few times, a little later each time.
+ ///
+ /// ⚠️ **Nothing else would ever dial it again.** [_redialNewlyTrusted] runs when the log CHANGES,
+ /// and from this phone's side it already has: the pin landed, the dial went out, and THEN the
+ /// phone's key went in — so the machine, still behind, answered `e2e_denied` to a dial nobody
+ /// retried, and a fresh sign-in sat on "locked" over a machine that would have let it in seconds
+ /// later. Outside [_vouchedRedialWindow] a refusal stands: that is trust revoked, not trust late.
+ Future<void> _redialOnceVouched(String machineId) async {
+ final revision = _authRevision;
+ final attempt = _vouchedRedials[machineId] ?? 0;
+ if (attempt >= _vouchedRedialDelays.length) return;
+ final registeredAt = _deviceRegisteredAt;
+ final keyIsNew =
+ _registeringDevice ||
+ (registeredAt != null &&
+ DateTime.now().difference(registeredAt) < _vouchedRedialWindow);
+ if (!keyIsNew) return;
+ if (await viewer.keys.peer(machineId) == null) return;
+ if (!_authWorkCurrent(revision) || _awaitingVouched.contains(machineId)) {
+ return;
+ }
+ _vouchedRedials[machineId] = attempt + 1;
+ _awaitingVouched.add(machineId);
+ notifyListeners();
+ await Future<void>.delayed(_vouchedRedialDelays[attempt]);
+ // A sign-out meanwhile emptied the set and moved the revision on: nothing here is ours.
+ if (!_authWorkCurrent(revision)) return;
+ _awaitingVouched.remove(machineId);
+ final state = machineStates[machineId];
+ if (state != null && state.needsLink && state.nodeOnline != false) {
+ // Unlocked before the socket goes, as [_redialNewlyTrusted] does: the screen reads it as
+ // connecting from here on, never as locked in between.
+ state.needsLink = false;
+ state.agentLoadStatus = AgentLoadStatus.idle;
+ await _pool?.closeMachine(machineId);
+ _connectMachine(state);
+ }
+ notifyListeners();
+ }
+
/// A machine waiting for its password that the device key log now vouches for: dial it again.
Future<void> _redialNewlyTrusted() async {
for (final state in [...machineStates.values]) {
@@ -6446,6 +6634,8 @@ class AppNotifier extends ChangeNotifier {
}
_channelControllers.clear();
_disposed = true;
+ // A sign-in page still up has nobody left to come back to: its listener goes.
+ if (signInProvider != null) viewer.login.cancel();
_closedHistory.clear();
_stopAllOfflineRetries();
_stopAllAgentSyncTimers();
diff --git a/mobile/lib/viewer/direct_auth.dart b/mobile/lib/viewer/direct_auth.dart
index 3b79a523b..45a5e5246 100644
--- a/mobile/lib/viewer/direct_auth.dart
+++ b/mobile/lib/viewer/direct_auth.dart
@@ -53,6 +53,7 @@ class DirectAuth implements AccessTokenSource {
autonomousEnv: tokens.autonomousEnv ?? api.config.autonomousEnv,
expiresIn: tokens.expiresIn,
issuer: issuer,
+ ssoClientId: tokens.clientId,
);
}
@@ -124,7 +125,13 @@ class DirectAuth implements AccessTokenSource {
// A refresh token only renews where it was issued.
final tokens = switch (await session.issuer()) {
SessionIssuer.emailCode => await emailCodes.refresh(refreshToken),
- SessionIssuer.sso || SessionIssuer.harness => await api.refresh(
+ // An SSO session names the client it was issued to, or auth-service refuses it.
+ SessionIssuer.sso => await api.refresh(
+ refreshToken,
+ autonomousEnv: autonomousEnv,
+ clientId: await session.ssoClientId(),
+ ),
+ SessionIssuer.harness => await api.refresh(
refreshToken,
autonomousEnv: autonomousEnv,
),
diff --git a/mobile/lib/viewer/direct_auth_api.dart b/mobile/lib/viewer/direct_auth_api.dart
index bbc60e051..e2eba28fb 100644
--- a/mobile/lib/viewer/direct_auth_api.dart
+++ b/mobile/lib/viewer/direct_auth_api.dart
@@ -1,28 +1,38 @@
import 'package:dio/dio.dart';
+import '../auth/sign_in_provider.dart';
import '../core/config.dart';
import '../logging/http_log.dart';
/// A sign-in or refresh that produced no usable session.
class DirectAuthException implements Exception {
- const DirectAuthException(this.message, {this.signedOut = false});
+ const DirectAuthException(
+ this.message, {
+ this.signedOut = false,
+ this.unreachable = false,
+ });
final String message;
/// The session is gone for good: retrying cannot help, only signing in again.
final bool signedOut;
+ /// The request never reached the backend — no connection, no name lookup — so nothing it
+ /// carried was spent, and the same request may be sent again.
+ final bool unreachable;
+
@override
String toString() => message;
}
-/// What `/api/auth/refresh` and `/api/auth/handoff/redeem` hand back.
+/// What `/api/auth/exchange`, `/api/auth/refresh` and `/api/auth/handoff/redeem` hand back.
class IssuedTokens {
const IssuedTokens({
required this.token,
this.refreshToken,
this.expiresIn,
this.autonomousEnv,
+ this.clientId,
});
final String token;
@@ -32,16 +42,23 @@ class IssuedTokens {
final int? expiresIn;
final String? autonomousEnv;
+ /// The auth-service client an exchange issued these to, which every refresh must name again.
+ /// Null is the backend's configured one — and what a backend from before the clients were
+ /// split answers, so this is kept as answered, never assumed from what was asked for.
+ final String? clientId;
+
static IssuedTokens? fromData(Object? data) {
if (data is! Map) return null;
final token = data['token'], refresh = data['refreshToken'];
final expiresIn = data['expiresIn'], env = data['autonomousEnv'];
+ final clientId = data['clientId'];
if (token is! String || token.isEmpty) return null;
return IssuedTokens(
token: token,
refreshToken: refresh is String && refresh.isNotEmpty ? refresh : null,
expiresIn: expiresIn is int && expiresIn > 0 ? expiresIn : null,
autonomousEnv: env is String ? env : null,
+ clientId: clientId is String && clientId.isNotEmpty ? clientId : null,
);
}
}
@@ -67,10 +84,104 @@ class DirectAuthApi {
final AppConfig config;
final Dio _dio;
+ /// auth-service's client for this app (backend `SSO_CLIENT_IDS`), as the desktop's
+ /// `auth/sso_client.dart` names it on a phone: the sign-in is made as the phone. What the
+ /// tokens are actually issued to comes back from [exchange] ([IssuedTokens.clientId]).
+ static const ssoClientId = 'harness-mobile';
+
static const _unavailable =
'Could not renew your sign-in. That is usually the sign-in service having a moment — '
'if it keeps happening, sign out and sign in again.';
+ static const _unreachable =
+ 'Could not reach Harness. Check your connection and try again.';
+
+ /// The SSO page to show for a sign-in that redirects back to [redirectUri] — a loopback
+ /// address, the only kind `/api/auth/authorize-native` takes — and the transaction [exchange]
+ /// names. [provider] is the account the page opens on.
+ Future<({String authorizeUrl, String tx})> authorizeNative(
+ String redirectUri, {
+ required SignInProvider provider,
+ }) async {
+ final Response<dynamic> res;
+ try {
+ res = await _dio.post(
+ '/api/auth/authorize-native',
+ data: {
+ 'redirectUri': redirectUri,
+ 'autonomousEnv': config.autonomousEnv,
+ 'clientId': ssoClientId,
+ 'provider': provider.name,
+ },
+ );
+ } on DioException {
+ throw const DirectAuthException(_unreachable);
+ }
+ final body = res.data is Map ? res.data as Map : const {};
+ final data = body['success'] == true && body['data'] is Map
+ ? body['data'] as Map
+ : const {};
+ final url = data['authorizeUrl'], tx = data['tx'];
+ if (url is! String || url.isEmpty || tx is! String || tx.isEmpty) {
+ throw const DirectAuthException(
+ 'Could not start signing in. Try again in a moment.',
+ );
+ }
+ return (authorizeUrl: _openingOn(url, provider), tx: tx);
+ }
+
+ /// [authorizeUrl], naming [provider]. The backend writes it into the page it hands back — but
+ /// only one that knows the field does. It is the browser's to carry and changes nothing the
+ /// backend holds (state, PKCE, client), so it is set here as well — as the desktop does.
+ static String _openingOn(String authorizeUrl, SignInProvider provider) {
+ final uri = Uri.tryParse(authorizeUrl);
+ if (uri == null) return authorizeUrl;
+ return uri
+ .replace(
+ queryParameters: {...uri.queryParameters, 'provider': provider.name},
+ )
+ .toString();
+ }
+
+ /// Trade the code the SSO page redirected back with for this phone's tokens. The backend checks
+ /// [state] against the transaction [tx] it started, which works once.
+ Future<IssuedTokens> exchange({
+ required String code,
+ required String state,
+ required String tx,
+ }) async {
+ final Response<dynamic> res;
+ try {
+ res = await _dio.post(
+ '/api/auth/exchange',
+ data: {'code': code, 'state': state, 'tx': tx},
+ );
+ } on DioException catch (error) {
+ // Only a request that never left: the backend spends [tx] on the first exchange that
+ // reaches it, so one that may have arrived is not one to send twice.
+ throw DirectAuthException(
+ _unreachable,
+ unreachable:
+ error.type == DioExceptionType.connectionError ||
+ error.type == DioExceptionType.connectionTimeout,
+ );
+ }
+ final body = res.data is Map ? res.data as Map : const {};
+ final tokens = body['success'] == true
+ ? IssuedTokens.fromData(body['data'])
+ : null;
+ if (tokens != null) return tokens;
+ final error = body['error'] is Map ? body['error'] as Map : const {};
+ final message = error['message'];
+ // Its own words only where they are written for a person: the account is not allowed on
+ // this environment. The rest (`invalid_state`, a token endpoint's status) are not.
+ final forPerson =
+ res.statusCode == 403 && message is String && message.isNotEmpty;
+ throw DirectAuthException(
+ forPerson ? message : 'Sign-in didn’t finish. Try again.',
+ );
+ }
+
/// Trade the one-time code in a signed-in computer's Add Phone QR for a
/// session of this phone's own — scan to sign in, no emailed code. [label]
/// is what the phone calls itself, for the account's list of devices.
@@ -115,15 +226,23 @@ class DirectAuthApi {
/// `REFRESH_TOKEN_INVALID` means the session is dead. An unusable refresh token and a real outage
/// both come back as the same 503, and reading that as dead would delete a refresh token nothing
/// can bring back — on a blip.
+ ///
+ /// [clientId] is the client the session was issued to ([IssuedTokens.clientId]): a refresh
+ /// under any other is refused.
Future<IssuedTokens> refresh(
String refreshToken, {
required String autonomousEnv,
+ String? clientId,
}) async {
final Response<dynamic> res;
try {
res = await _dio.post(
'/api/auth/refresh',
- data: {'refreshToken': refreshToken, 'autonomousEnv': autonomousEnv},
+ data: {
+ 'refreshToken': refreshToken,
+ 'autonomousEnv': autonomousEnv,
+ 'clientId': ?clientId,
+ },
);
} on DioException {
throw const DirectAuthException(_unavailable);
diff --git a/mobile/lib/viewer/direct_login.dart b/mobile/lib/viewer/direct_login.dart
index 8bdebddd9..af9778fb5 100644
--- a/mobile/lib/viewer/direct_login.dart
+++ b/mobile/lib/viewer/direct_login.dart
@@ -1,22 +1,259 @@
+import 'dart:async';
+import 'dart:io';
+
+import 'package:flutter/widgets.dart';
+
import '../auth/cli_login.dart';
import '../auth/sign_in_client.dart';
+import '../auth/sign_in_provider.dart';
import 'direct_auth.dart';
+import 'direct_auth_api.dart';
+import 'sign_in_browser.dart' show signInReturnUrl;
+
+/// A browser sign-in that stopped because the person — or a newer sign-in — stopped it. Not a
+/// failure to show: the screen they are looking at already says what they chose.
+class SignInCancelled extends DirectAuthException {
+ const SignInCancelled() : super('Sign-in was cancelled.');
+}
-/// Whether this app is signed in, and signing it out, with no harness CLI to ask — the session is
-/// the app's own ([DirectAuth]).
+/// Whether this app is signed in, signing it in through the SSO page, and signing it out, with no
+/// harness CLI to ask — the session is the app's own ([DirectAuth]).
+///
+/// The SSO sign-in is the desktop viewer build's (`desktop/lib/viewer/direct_login_native.dart`),
+/// itself cli.ts `loginCommand` run by the app: a loopback listener for the redirect,
+/// `authorize-native` for the page to show, `exchange` for the tokens. The page opens in the app
+/// (`sign_in_browser.dart`), and the person goes straight to [SignInProvider]'s account.
///
-/// There is no browser sign-in here. The desktop's is cli.ts `loginCommand` — a loopback listener
-/// for the SSO redirect — and a phone that hands the person to Safari is suspended along with that
-/// listener. A phone signs in with a code instead (`email_code_login.dart`).
+/// ⚠️ It skips the CLI's closing `resolve-computer`, which registers a computer as a Harness
+/// machine. A phone is not one.
class DirectLogin implements SignInClient {
DirectLogin({required this.auth});
final DirectAuth auth;
+ _LoopbackCallback? _pending;
+ int _loginRevision = 0;
+
+ static const _callbackTimeout = Duration(minutes: 5);
@override
Future<CliAuthStatus> checkStatus() async =>
CliAuthStatus(loggedIn: await auth.hasSession());
+ /// Sign in with [provider]'s account. [onAuthorizeUrl] is handed the page to show once there is
+ /// a listener for it to come back to; completes when the session is saved.
+ ///
+ /// Throws a [DirectAuthException] fit to show — a [SignInCancelled] when [cancel] stopped it.
+ Future<void> login({
+ required SignInProvider provider,
+ required void Function(Uri url) onAuthorizeUrl,
+ }) async {
+ cancel();
+ final revision = _loginRevision;
+ final HttpServer server;
+ try {
+ server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);
+ } on SocketException {
+ throw const DirectAuthException(
+ 'Could not start signing in on this phone. Try again.',
+ );
+ }
+ _LoopbackCallback? callback;
+ try {
+ _requireCurrent(revision);
+ callback = _pending = _LoopbackCallback(server);
+ final start = await auth.api.authorizeNative(
+ 'http://127.0.0.1:${server.port}/callback',
+ provider: provider,
+ );
+ _requireCurrent(revision);
+ final page = Uri.tryParse(start.authorizeUrl);
+ if (page == null) {
+ throw const DirectAuthException(
+ 'Could not start signing in. Try again in a moment.',
+ );
+ }
+ onAuthorizeUrl(page);
+ final redirect = await callback.result.timeout(
+ _callbackTimeout,
+ onTimeout: () =>
+ throw const DirectAuthException('Sign-in timed out. Try again.'),
+ );
+ // Its own reason first: a cancel, or the page's error, is what the person needs to read.
+ if (redirect == null) throw callback.error!;
+ _requireCurrent(revision);
+ final tokens = await _exchange(redirect, start.tx, revision, callback);
+ _requireCurrent(revision);
+ // Saved from here on: a cancel that lands during the write is too late to take it back,
+ // and the caller goes in with it.
+ await auth.signIn(tokens);
+ } finally {
+ if (identical(_pending, callback)) _pending = null;
+ await server.close(force: true);
+ }
+ }
+
+ /// The redirect's code traded for tokens — sent again, up to [_exchangeRetries] times, when it
+ /// never reached the backend.
+ ///
+ /// ⚠️ **On Android the first try usually cannot leave the phone.** The redirect lands while the
+ /// Custom Tab still covers the app, and Android cuts a backgrounded app off the network — the
+ /// loopback the redirect came in on excepted — so the exchange died on its name lookup ("Failed
+ /// host lookup: 'harness-api.autonomous.ai'", 24ms) every time, and every Android sign-in ended
+ /// on "Could not reach Harness" behind a page that said it had worked. So a try that never left
+ /// waits for the app to be back in front (the page's "Back to Harness", `SignInReturnActivity`),
+ /// gives the network a moment, and goes again. Its [tx] is unspent: the backend only spends it
+ /// on an exchange that reaches it.
+ Future<IssuedTokens> _exchange(
+ ({String code, String state}) redirect,
+ String tx,
+ int revision,
+ _LoopbackCallback callback,
+ ) async {
+ for (var attempt = 0; ; attempt++) {
+ try {
+ return await auth.api.exchange(
+ code: redirect.code,
+ state: redirect.state,
+ tx: tx,
+ );
+ } on DirectAuthException catch (error) {
+ if (!error.unreachable || attempt >= _exchangeRetries) rethrow;
+ }
+ await Future.any([_untilForeground(), callback.stopped]);
+ _requireCurrent(revision);
+ await Future<void>.delayed(Duration(milliseconds: 500 * (attempt + 1)));
+ _requireCurrent(revision);
+ }
+ }
+
+ static const _exchangeRetries = 3;
+
+ /// Completes once the app is in front — at once when it already is, or off Android, where the
+ /// page is a sheet over an app that never left the network (`sign_in_browser.dart`).
+ static Future<void> _untilForeground() {
+ if (!Platform.isAndroid) return Future.value();
+ final state = WidgetsBinding.instance.lifecycleState;
+ if (state == null || state == AppLifecycleState.resumed) {
+ return Future.value();
+ }
+ final resumed = Completer<void>();
+ final listener = AppLifecycleListener(
+ onResume: () {
+ if (!resumed.isCompleted) resumed.complete();
+ },
+ );
+ // Not forever: a person who never comes back still gets an answer, from one last try.
+ return resumed.future
+ .timeout(_callbackTimeout, onTimeout: () {})
+ .whenComplete(listener.dispose);
+ }
+
+ /// Stop the sign-in in flight, if there is one: [login] throws [error] — a [SignInCancelled]
+ /// unless the caller has a reason of its own (the page could not be opened).
+ void cancel([DirectAuthException error = const SignInCancelled()]) {
+ ++_loginRevision;
+ final callback = _pending;
+ _pending = null;
+ callback?.cancel(error);
+ }
+
+ void _requireCurrent(int revision) {
+ if (revision != _loginRevision) throw const SignInCancelled();
+ }
+
@override
- Future<void> logout() => auth.signOut();
+ Future<void> logout() {
+ cancel();
+ return auth.signOut();
+ }
+}
+
+/// The loopback end of the redirect: the first `/callback` carrying `code` and `state` completes
+/// it and an `error` fails it; anything else the browser asks for (a favicon) is turned away.
+class _LoopbackCallback {
+ _LoopbackCallback(this._server) {
+ _server.listen(_onRequest, onError: (Object _) {});
+ }
+
+ final HttpServer _server;
+
+ // Cancellation can precede the redirect and anyone waiting on it: the outcome is kept as data
+ // until [DirectLogin.login] reads it, never as an error nobody handles.
+ final _completer = Completer<({String code, String state})?>();
+ final _stopped = Completer<void>();
+ DirectAuthException? error;
+
+ Future<({String code, String state})?> get result => _completer.future;
+
+ /// Completes when [cancel] stops this sign-in — also after its redirect has landed, for an
+ /// exchange that is waiting to try again ([DirectLogin._exchange]).
+ Future<void> get stopped => _stopped.future;
+
+ Future<void> _onRequest(HttpRequest request) async {
+ final response = request.response;
+ try {
+ if (request.uri.path != '/callback') {
+ response.statusCode = HttpStatus.notFound;
+ await response.close();
+ return;
+ }
+ final query = request.uri.queryParameters;
+ final code = query['code'],
+ state = query['state'],
+ error = query['error'];
+ final signedIn = error == null && code != null && state != null;
+ response
+ ..statusCode = signedIn ? HttpStatus.ok : HttpStatus.badRequest
+ ..headers.contentType = ContentType.html
+ ..write(
+ _page(signedIn ? 'Signed in to Harness' : 'Harness sign-in failed'),
+ );
+ await response.close();
+ if (_completer.isCompleted) return;
+ if (signedIn) {
+ _completer.complete((code: code, state: state));
+ } else {
+ this.error = DirectAuthException(
+ error == 'access_denied'
+ ? 'Sign-in was declined.'
+ : 'Sign-in didn’t finish. Try again.',
+ );
+ _completer.complete(null);
+ }
+ } catch (_) {
+ // The browser hung up mid-answer. The redirect, if it carried one, is already taken.
+ }
+ }
+
+ void cancel(DirectAuthException reason) {
+ if (!_completer.isCompleted) {
+ error = reason;
+ _completer.complete(null);
+ }
+ if (!_stopped.isCompleted) _stopped.complete();
+ unawaited(_server.close(force: true));
+ }
+}
+
+/// What the in-app page shows once the redirect lands. iOS takes it down by itself
+/// (`closeSignInPage`), so it only ever flashes there.
+///
+/// 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
+/// takes the tab down on the way. The script tries at once; Chrome may hold a jump to an app that
+/// no tap asked for, so "Back to Harness" is the tap, and closing the tab still works too.
+String _page(String title) {
+ final back = Platform.isAndroid
+ ? '<p style="margin:2em 0 1em"><a href="$signInReturnUrl" style="display:inline-block;'
+ 'padding:14px 32px;border-radius:10px;background:#111;color:#fff;'
+ '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>';
+ return '<!doctype html><meta charset="utf-8">'
+ '<meta name="viewport" content="width=device-width,initial-scale=1">'
+ '<title>$title</title>'
+ '<body style="font:16px system-ui,sans-serif;text-align:center;padding:4em 1em">'
+ '<h1 style="font-weight:600;font-size:22px">$title</h1>'
+ '$back</body>';
}
diff --git a/mobile/lib/viewer/email_code_api.dart b/mobile/lib/viewer/email_code_api.dart
index d4049d78d..0fe8f974d 100644
--- a/mobile/lib/viewer/email_code_api.dart
+++ b/mobile/lib/viewer/email_code_api.dart
@@ -8,11 +8,12 @@ import 'direct_auth_api.dart';
/// one the Autonomous companion app uses (`ecm-sds-mobile`, `features/auth`), called straight from
/// the app.
///
-/// Why a phone signs in this way and not through the browser: the SSO flow redirects back to a
-/// loopback listener inside the app (the desktop CLI's `loginCommand`), and a phone is not obliged
-/// to keep that listener alive while a browser is in front of it. Google Play's review saw exactly that —
-/// "127.0.0.1 took too long to respond" — and rejected the build for a sign-in that could not
-/// finish. A code typed into the app never leaves it.
+/// Why a phone keeps this way beside the browser's "Continue with Google / Apple"
+/// (`direct_login.dart`): the SSO flow redirects back to a loopback listener inside the app (the
+/// desktop CLI's `loginCommand`), and a phone is not obliged to keep that listener alive while a
+/// browser is in front of it. Google Play's review saw exactly that — "127.0.0.1 took too long to
+/// respond" — and rejected a build whose ONLY sign-in it was. A code typed into the app never
+/// leaves it.
///
/// The token it returns is an ordinary Autonomous access token: the Harness backend checks it
/// against the same account API's `/me` endpoints it checks an SSO token against
diff --git a/mobile/lib/viewer/email_code_login.dart b/mobile/lib/viewer/email_code_login.dart
index 0577f64ad..dfac9d3f1 100644
--- a/mobile/lib/viewer/email_code_login.dart
+++ b/mobile/lib/viewer/email_code_login.dart
@@ -2,8 +2,8 @@ import '../auth/auth_session.dart';
import 'direct_auth.dart';
import 'email_code_api.dart';
-/// A phone's sign-in: an emailed code, typed into the app — see [EmailCodeApi] for why a phone
-/// does not go through the browser.
+/// A phone's sign-in by an emailed code, typed into the app — see [EmailCodeApi] for why this way
+/// needs no browser. The other way, "Continue with Google / Apple", is `direct_login.dart`'s.
///
/// Two steps the login screen drives in turn, each throwing a `DirectAuthException` whose message
/// is fit to show. The session lands in the same [DirectAuth] the SSO flow fills, marked as an
diff --git a/mobile/lib/viewer/sign_in_browser.dart b/mobile/lib/viewer/sign_in_browser.dart
new file mode 100644
index 000000000..7e50635db
--- /dev/null
+++ b/mobile/lib/viewer/sign_in_browser.dart
@@ -0,0 +1,48 @@
+import 'package:flutter/services.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`).
+///
+/// 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`).
+///
+/// ⚠️ **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
+/// long to respond" (`email_code_api.dart`). And only iOS can take the page down by itself
+/// ([closeSignInPage]): on Android the page's last screen goes back to the app through
+/// [signInReturnUrl] instead.
+///
+/// True once the page is up; false when iOS's sheet was closed before its first page loaded.
+Future<bool> openSignInPage(Uri url) async {
+ try {
+ return await launchUrl(url, mode: LaunchMode.inAppBrowserView);
+ } on PlatformException catch (error) {
+ // ⚠️ **The sheet is up — this is the sign-in page working, not failing.** Named a provider,
+ // auth-service's page replaces itself with Google's or Apple's (`location.replace`) before
+ // its own load finishes, so SFSafariViewController reports the first load as failed, and
+ // url_launcher_ios throws exactly this (`_failedSafariViewControllerLoadException`) while
+ // leaving the sheet where it is. Taking it as "could not open" cancelled every iOS sign-in
+ // and pulled the sheet out from under Google's account picker. A page that truly failed to
+ // load is still on screen, saying so, for the person to close.
+ if (error.code == 'Error' &&
+ (error.message ?? '').startsWith('Error while launching')) {
+ return true;
+ }
+ rethrow;
+ }
+}
+
+/// 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.
+const signInReturnUrl = 'ai.autonomous.harness.signin://signed-in';
+
+/// Takes down what [openSignInPage] put up, where the platform can. Best effort.
+Future<void> closeSignInPage() async {
+ try {
+ if (await supportsCloseForLaunchMode(LaunchMode.inAppBrowserView)) {
+ await closeInAppWebView();
+ }
+ } catch (_) {}
+}
diff --git a/mobile/lib/viewer/viewer_services.dart b/mobile/lib/viewer/viewer_services.dart
index dfcc4d362..b8504d4db 100644
--- a/mobile/lib/viewer/viewer_services.dart
+++ b/mobile/lib/viewer/viewer_services.dart
@@ -56,9 +56,13 @@ class ViewerServices {
final ViewerKeyStore keys;
final DirectAuth auth;
+
+ /// The session's state and sign-out, and the welcome screen's "Continue with Google" and
+ /// "Continue with Apple": the SSO page, opened in the app (`direct_login.dart`).
final DirectLogin login;
- /// How a phone signs in — an emailed code, never the browser. See `email_code_api.dart`.
+ /// The other ways a phone signs in — an emailed code, or a scanned one. See
+ /// `email_code_api.dart`.
final EmailCodeLogin emailLogin;
final DirectLink links;
final RelayCodecFactory relayCodecs;
diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yaml
index 25ebe65f1..4b81aaee4 100644
--- a/mobile/pubspec.yaml
+++ b/mobile/pubspec.yaml
@@ -30,8 +30,9 @@ dependencies:
dio: ^5.11.0
# The relay socket every machine is reached over (`ws/`).
web_socket_channel: ^3.0.3
- # Sign-in hands the SSO URL to the system browser (`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 the app — SFSafariViewController,
+ # a Custom Tab (`viewer/sign_in_browser.dart`) — 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/`).
@@ -115,6 +116,10 @@ flutter:
# NOT listed: Flutter cannot draw an SVG without a package this app does not
# depend on, so bundling it would only add its weight to every install.
- assets/app_icon.png
+ # The marks on the welcome screen's two accounts (`phone/welcome/sign_in_provider_button.dart`),
+ # PNG at 1x/2x/3x for the reason above: drawn from `desktop/assets/sign-in/*.svg` by
+ # `scripts/render_svg.swift` (Apple's 814x1000 mark centred in a square tile first).
+ - assets/sign-in/
# "See how it works" — recorded from the sample on a simulator by
# `integration_test/demo_video_test.dart`, trimmed and encoded at 604px, ~630 KB.
- assets/video/how_it_works.mp4