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): a phone signs in with an emailed code, never the browser

Dev jacob084262adb7c5
diff --git a/mobile/lib/auth/auth_session.dart b/mobile/lib/auth/auth_session.dart
index 8c379b3d2..cddeaf184 100644
--- a/mobile/lib/auth/auth_session.dart
+++ b/mobile/lib/auth/auth_session.dart
@@ -1,6 +1,20 @@
import '../core/harness_file_store.dart';
import '../core/local_key_value_store.dart';
+/// Who issued a session — and therefore who renews it.
+///
+/// Both hand out the SAME kind of token, an Autonomous account's access token
+/// (the Harness backend checks either against `apiv2`'s `/me` endpoints), but
+/// their refresh tokens only work where they came from.
+enum SessionIssuer {
+ /// The browser SSO flow, renewed through the Harness backend's `/api/auth/refresh`.
+ sso,
+
+ /// A code emailed to the person, renewed through the Autonomous account API
+ /// itself — see `viewer/email_code_api.dart`.
+ emailCode,
+}
+
/// Persists the SSO access + refresh tokens in the Desktop Harness state file.
class AuthSession {
final LocalKeyValueStore _storage;
@@ -8,6 +22,7 @@ class AuthSession {
static const _refresh = 'auth_refresh_token';
static const _env = 'auth_autonomous_env';
static const _expiresAt = 'auth_access_token_expires_at';
+ static const _issuer = 'auth_session_issuer';
AuthSession({LocalKeyValueStore? storage})
: _storage = storage ?? HarnessFileStore.shared;
@@ -19,8 +34,10 @@ class AuthSession {
String? refreshToken,
String autonomousEnv = 'prod',
int? expiresIn,
+ SessionIssuer issuer = SessionIssuer.sso,
}) async {
await _storage.write(_access, token);
+ await _storage.write(_issuer, issuer.name);
if (refreshToken != null && refreshToken.isNotEmpty) {
await _storage.write(_refresh, refreshToken);
} else {
@@ -49,6 +66,15 @@ class AuthSession {
Future<String?> accessToken() => _storage.read(_access);
Future<String?> refreshToken() => _storage.read(_refresh);
Future<String> autonomousEnv() async => (await _storage.read(_env)) ?? 'prod';
+
+ /// A session saved before this was recorded came from the SSO flow — the only
+ /// one there was.
+ Future<SessionIssuer> issuer() async {
+ final saved = await _storage.read(_issuer);
+ return SessionIssuer.values.where((i) => i.name == saved).firstOrNull ??
+ SessionIssuer.sso;
+ }
+
Future<DateTime?> accessTokenExpiresAt() async =>
_expiryFrom(await _storage.read(_expiresAt));
@@ -95,5 +121,6 @@ class AuthSession {
await _storage.delete(_refresh);
await _storage.delete(_env);
await _storage.delete(_expiresAt);
+ await _storage.delete(_issuer);
}
}
diff --git a/mobile/lib/screens/email_code_form.dart b/mobile/lib/screens/email_code_form.dart
new file mode 100644
index 000000000..684ed9a43
--- /dev/null
+++ b/mobile/lib/screens/email_code_form.dart
@@ -0,0 +1,216 @@
+import 'dart:async';
+
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../theme/app_theme.dart' show AppColors;
+import 'login_text_field.dart';
+
+/// A phone's sign-in: an email, then the code sent to it — both in the app.
+///
+/// Replaces the "Sign in" button that handed a phone to the browser, which could not always bring
+/// it back (Google Play review: "127.0.0.1 took too long to respond") — see
+/// `viewer/email_code_api.dart`. One field at a time, in the login card, so the step the person is
+/// on is the only thing asking for input.
+class EmailCodeForm extends StatefulWidget {
+ const EmailCodeForm({
+ super.key,
+ required this.sendCode,
+ required this.signIn,
+ });
+
+ /// Emails a code to the address given — `AppNotifier.sendLoginCode`.
+ final Future<void> Function(String email) sendCode;
+
+ /// Trades the code for a session and goes in — `AppNotifier.signInWithCode`.
+ /// Both throw a reason fit to show under the field.
+ final Future<void> Function(String email, String code) signIn;
+
+ /// How long before the same address can be sent another code — long enough
+ /// that a slow inbox is not answered with a second email, short enough that
+ /// a lost one is not a wait.
+ static const resendAfter = Duration(seconds: 30);
+
+ /// The account API's codes are four digits (the companion app's pin field).
+ static const codeLength = 4;
+
+ @override
+ State<EmailCodeForm> createState() => _EmailCodeFormState();
+}
+
+class _EmailCodeFormState extends State<EmailCodeForm> {
+ final _email = TextEditingController();
+ final _code = TextEditingController();
+
+ /// The address the code went to; null while the email is still being asked.
+ String? _sentTo;
+ bool _busy = false;
+ String? _error;
+ int _resendIn = 0;
+ Timer? _resendTimer;
+
+ @override
+ void dispose() {
+ _resendTimer?.cancel();
+ _email.dispose();
+ _code.dispose();
+ super.dispose();
+ }
+
+ Future<void> _sendCode() async {
+ final email = _email.text.trim();
+ if (!email.contains('@')) {
+ setState(() => _error = 'Enter the email of your Autonomous account.');
+ return;
+ }
+ await _run(
+ () => widget.sendCode(email),
+ onDone: () {
+ _sentTo = email;
+ _code.clear();
+ _startResendCountdown();
+ },
+ );
+ }
+
+ Future<void> _signIn() async {
+ final email = _sentTo, code = _code.text.trim();
+ if (email == null) return;
+ if (code.isEmpty) {
+ setState(() => _error = 'Enter the code from the email.');
+ return;
+ }
+ await _run(() => widget.signIn(email, code));
+ }
+
+ /// One request at a time, its failure shown under the field in the
+ /// service's own words.
+ Future<void> _run(
+ Future<void> Function() request, {
+ VoidCallback? onDone,
+ }) async {
+ if (_busy) return;
+ setState(() {
+ _busy = true;
+ _error = null;
+ });
+ String? error;
+ try {
+ await request();
+ } catch (e) {
+ error = e.toString();
+ }
+ if (!mounted) return;
+ setState(() {
+ _busy = false;
+ _error = error;
+ if (error == null) onDone?.call();
+ });
+ }
+
+ void _startResendCountdown() {
+ _resendTimer?.cancel();
+ _resendIn = EmailCodeForm.resendAfter.inSeconds;
+ _resendTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
+ if (!mounted) return timer.cancel();
+ setState(() => _resendIn--);
+ if (_resendIn <= 0) timer.cancel();
+ });
+ }
+
+ void _changeEmail() => setState(() {
+ _resendTimer?.cancel();
+ _sentTo = null;
+ _error = null;
+ _code.clear();
+ });
+
+ @override
+ Widget build(BuildContext context) {
+ grid.AppTheme.watch(context);
+ final sentTo = _sentTo;
+ final text = Theme.of(context).textTheme;
+ return AutofillGroup(
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ if (sentTo == null) ...[
+ Text(
+ 'Sign in with the email of your Autonomous account.',
+ textAlign: TextAlign.center,
+ style: text.bodySmall,
+ ),
+ const SizedBox(height: 12),
+ LoginTextField(
+ key: const Key('login-email'),
+ controller: _email,
+ keyboard: TextInputType.emailAddress,
+ autofill: AutofillHints.email,
+ enabled: !_busy,
+ onSubmitted: _sendCode,
+ ),
+ ] else ...[
+ Text(
+ 'We emailed a sign-in code to $sentTo.',
+ textAlign: TextAlign.center,
+ style: text.bodySmall,
+ ),
+ const SizedBox(height: 12),
+ LoginTextField(
+ key: const Key('login-code'),
+ controller: _code,
+ hint: 'Sign-in code',
+ keyboard: TextInputType.number,
+ autofill: AutofillHints.oneTimeCode,
+ enabled: !_busy,
+ onSubmitted: _signIn,
+ maxDigits: EmailCodeForm.codeLength,
+ ),
+ ],
+ if (_error case final error?) ...[
+ const SizedBox(height: 8),
+ Semantics(
+ liveRegion: true,
+ child: Text(
+ error,
+ textAlign: TextAlign.center,
+ style: text.bodySmall?.copyWith(color: AppColors.danger),
+ ),
+ ),
+ ],
+ const SizedBox(height: 12),
+ FilledButton(
+ onPressed: _busy ? null : (sentTo == null ? _sendCode : _signIn),
+ child: _busy
+ ? const SizedBox.square(
+ dimension: grid.AppControl.iconSize,
+ child: CircularProgressIndicator(strokeWidth: 2),
+ )
+ : Text(sentTo == null ? 'Email me a code' : 'Sign in'),
+ ),
+ if (sentTo != null) _codeActions(),
+ ],
+ ),
+ );
+ }
+
+ Widget _codeActions() => Wrap(
+ alignment: WrapAlignment.center,
+ children: [
+ TextButton(
+ onPressed: _busy || _resendIn > 0
+ ? null
+ : () => _run(
+ () => widget.sendCode(_sentTo!),
+ onDone: _startResendCountdown,
+ ),
+ child: Text(_resendIn > 0 ? 'Resend in ${_resendIn}s' : 'Resend code'),
+ ),
+ TextButton(
+ onPressed: _busy ? null : _changeEmail,
+ child: const Text('Use a different email'),
+ ),
+ ],
+ );
+}
diff --git a/mobile/lib/screens/login_screen.dart b/mobile/lib/screens/login_screen.dart
index 5f930754b..0099c0379 100644
--- a/mobile/lib/screens/login_screen.dart
+++ b/mobile/lib/screens/login_screen.dart
@@ -5,6 +5,7 @@ import '../shared/theme/app_theme.dart' as grid;
import '../state/app_state.dart';
import '../widgets/login_relay_diagram.dart';
import '../widgets/welcome_workspace_preview.dart';
+import 'email_code_form.dart';
/// The sign-in screen.
///
@@ -92,12 +93,28 @@ class LoginScreen extends StatelessWidget {
SizedBox(height: gap),
const WelcomeWorkspacePreview(),
SizedBox(height: gap),
- _Action(notifier: notifier, waiting: waiting),
+ // A phone never goes to the browser to sign in — see
+ // `viewer/email_code_api.dart` for the review that
+ // failed on it.
+ if (notifier.signsInWithEmailCode)
+ EmailCodeForm(
+ sendCode: notifier.sendLoginCode,
+ signIn: (email, code) => notifier.signInWithCode(
+ email: email,
+ code: code,
+ ),
+ )
+ else
+ _Action(notifier: notifier, waiting: waiting),
if (notifier.lastError != null) ...[
const SizedBox(height: 16),
_ErrorTile(
message: notifier.lastError!,
- onRetry: notifier.login,
+ // The form above IS the way on for a phone; a retry
+ // here would start the browser sign-in it replaced.
+ onRetry: notifier.signsInWithEmailCode
+ ? null
+ : notifier.login,
),
],
SizedBox(height: gap),
@@ -291,7 +308,9 @@ class _ErrorTile extends StatelessWidget {
const _ErrorTile({required this.message, required this.onRetry});
final String message;
- final VoidCallback onRetry;
+
+ /// Null leaves the button off — see where the tile is built.
+ final VoidCallback? onRetry;
@override
Widget build(BuildContext context) {
@@ -330,14 +349,16 @@ class _ErrorTile extends StatelessWidget {
),
const SizedBox(height: 4),
SelectableText(message, style: Theme.of(context).textTheme.bodySmall),
- const SizedBox(height: 12),
- Align(
- alignment: Alignment.centerLeft,
- child: OutlinedButton(
- onPressed: onRetry,
- child: const Text('Try again'),
+ if (onRetry case final retry?) ...[
+ const SizedBox(height: 12),
+ Align(
+ alignment: Alignment.centerLeft,
+ child: OutlinedButton(
+ onPressed: retry,
+ child: const Text('Try again'),
+ ),
),
- ),
+ ],
],
),
);
diff --git a/mobile/lib/screens/login_text_field.dart b/mobile/lib/screens/login_text_field.dart
new file mode 100644
index 000000000..82173e18f
--- /dev/null
+++ b/mobile/lib/screens/login_text_field.dart
@@ -0,0 +1,55 @@
+import 'package:flutter/material.dart';
+import 'package:flutter/services.dart';
+
+/// One field of the phone's sign-in form — the email, or the emailed code.
+///
+/// [maxDigits] makes it a code field: digits only, no more than that many, and
+/// the last one typed submits — there is nothing left to wait for.
+class LoginTextField extends StatelessWidget {
+ const LoginTextField({
+ super.key,
+ required this.controller,
+ required this.hint,
+ required this.keyboard,
+ required this.autofill,
+ required this.enabled,
+ required this.onSubmitted,
+ this.maxDigits,
+ });
+
+ final TextEditingController controller;
+ final String hint;
+ final TextInputType keyboard;
+ final String autofill;
+ final bool enabled;
+ final VoidCallback onSubmitted;
+ final int? maxDigits;
+
+ @override
+ Widget build(BuildContext context) {
+ final digits = maxDigits;
+ return TextField(
+ controller: controller,
+ autofocus: true,
+ enabled: enabled,
+ keyboardType: keyboard,
+ autofillHints: [autofill],
+ autocorrect: false,
+ textAlign: TextAlign.center,
+ textInputAction: TextInputAction.go,
+ inputFormatters: [
+ if (digits != null) ...[
+ FilteringTextInputFormatter.digitsOnly,
+ LengthLimitingTextInputFormatter(digits),
+ ],
+ ],
+ decoration: InputDecoration(hintText: hint),
+ onChanged: digits == null
+ ? null
+ : (value) {
+ if (value.length == digits) onSubmitted();
+ },
+ onSubmitted: (_) => onSubmitted(),
+ );
+ }
+}
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index f29223eb1..4a12fb3a4 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -2704,15 +2704,7 @@ class AppNotifier extends ChangeNotifier {
pendingAuthorizeUrl = null;
_resetLoginBrowser();
notifyListeners();
- await _finishBootstrapSignedIn();
- if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {
- return;
- }
- analytics.signedIn();
- // Restarts the clock even if `_trackAppOpened` already started one: this
- // person met the login screen, so their wait begins where the launch's
- // did not.
- _armFirstMessage('sign_in');
+ await _enterSignedIn(revision);
} catch (error) {
if (!_authWorkCurrent(revision)) return;
status = AppStatus.unauthenticated;
@@ -2742,6 +2734,71 @@ class AppNotifier extends ChangeNotifier {
if (_authWorkCurrent(revision)) notifyListeners();
}
+ /// A session was just saved: load everything behind the login screen, and
+ /// count the sign-in. The one road in for every way of signing in.
+ Future<void> _enterSignedIn(int revision) async {
+ await _finishBootstrapSignedIn();
+ if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {
+ return;
+ }
+ analytics.signedIn();
+ // Restarts the clock even if `_trackAppOpened` already started one: this
+ // person met the login screen, so their wait begins where the launch's
+ // did not.
+ _armFirstMessage('sign_in');
+ }
+
+ /// Whether this build signs in with an emailed code rather than the browser
+ /// — a phone. See `viewer/email_code_api.dart`.
+ bool get signsInWithEmailCode => viewer != null;
+
+ /// The phone's sign-in, first step: email [email] a one-time code. Throws the
+ /// service's own reason ("Email is invalid") for the form to show.
+ Future<void> sendLoginCode(String email) {
+ final login = viewer?.emailLogin;
+ if (login == null) throw StateError('This build signs in with a browser.');
+ return login.sendCode(email);
+ }
+
+ /// The phone's sign-in, second step: trade the emailed [code] for a session
+ /// and go in.
+ ///
+ /// A wrong or expired code is thrown for the form to show beside the field —
+ /// never raised to [lastError], which would put a second, generic error under
+ /// the one the person is already reading. The login card stays up throughout:
+ /// [signingIn] keeps it there (see `RootShell`), so the form keeps what was
+ /// typed into it.
+ Future<void> signInWithCode({
+ required String email,
+ required String code,
+ }) async {
+ final login = viewer?.emailLogin;
+ if (_disposed || signingIn || login == null) return;
+ final revision = _invalidateAuthWork();
+ _closedHistory.clear();
+ _lastError = null;
+ signingIn = true;
+ notifyListeners();
+ try {
+ await login.signIn(email: email, code: code);
+ if (!_authWorkCurrent(revision)) return;
+ status = AppStatus.bootstrapping;
+ notifyListeners();
+ await _enterSignedIn(revision);
+ } catch (_) {
+ if (_authWorkCurrent(revision)) {
+ status = AppStatus.unauthenticated;
+ analytics.signInFailed('failed');
+ }
+ rethrow;
+ } finally {
+ if (_authWorkCurrent(revision)) {
+ signingIn = false;
+ notifyListeners();
+ }
+ }
+ }
+
void _resetLoginBrowser() {
++_loginBrowserRevision;
openingLoginBrowser = false;
diff --git a/mobile/lib/viewer/direct_auth.dart b/mobile/lib/viewer/direct_auth.dart
index f3baf97b9..49e13afe8 100644
--- a/mobile/lib/viewer/direct_auth.dart
+++ b/mobile/lib/viewer/direct_auth.dart
@@ -1,15 +1,23 @@
import '../api/access_token_source.dart';
import '../auth/auth_session.dart';
import 'direct_auth_api.dart';
+import 'email_code_api.dart';
/// A viewer build's SSO session — authSession.ts's `AuthSessionManager`, moved into the app because
/// a device with no harness CLI has nobody else to hold it: the tokens `/api/auth/exchange` issued,
/// kept in [AuthSession], refreshed [_refreshSkew] before they lapse, one refresh at a time.
class DirectAuth implements AccessTokenSource {
- DirectAuth({required this.session, required this.api});
+ DirectAuth({
+ required this.session,
+ required this.api,
+ EmailCodeApi? emailCodes,
+ }) : emailCodes = emailCodes ?? EmailCodeApi(config: api.config);
final AuthSession session;
final DirectAuthApi api;
+
+ /// Where a session signed in with an emailed code is renewed — see [SessionIssuer].
+ final EmailCodeApi emailCodes;
Future<String>? _refreshing;
static const _refreshSkew = Duration(seconds: 60);
@@ -17,11 +25,15 @@ class DirectAuth implements AccessTokenSource {
Future<bool> hasSession() async =>
((await session.accessToken()) ?? '').isNotEmpty;
- Future<void> signIn(IssuedTokens tokens) => session.saveLogin(
+ Future<void> signIn(
+ IssuedTokens tokens, {
+ SessionIssuer issuer = SessionIssuer.sso,
+ }) => session.saveLogin(
token: tokens.token,
refreshToken: tokens.refreshToken,
autonomousEnv: tokens.autonomousEnv ?? api.config.autonomousEnv,
expiresIn: tokens.expiresIn,
+ issuer: issuer,
);
Future<void> signOut() => session.clear();
@@ -62,7 +74,14 @@ class DirectAuth implements AccessTokenSource {
}
try {
final autonomousEnv = await session.autonomousEnv();
- final tokens = await api.refresh(refreshToken, autonomousEnv: autonomousEnv);
+ // A refresh token only renews where it was issued.
+ final tokens = switch (await session.issuer()) {
+ SessionIssuer.emailCode => await emailCodes.refresh(refreshToken),
+ SessionIssuer.sso => await api.refresh(
+ refreshToken,
+ autonomousEnv: autonomousEnv,
+ ),
+ };
await session.saveRefresh(
token: tokens.token,
refreshToken: tokens.refreshToken,
diff --git a/mobile/lib/viewer/email_code_api.dart b/mobile/lib/viewer/email_code_api.dart
new file mode 100644
index 000000000..8db34351a
--- /dev/null
+++ b/mobile/lib/viewer/email_code_api.dart
@@ -0,0 +1,136 @@
+import 'package:dio/dio.dart';
+
+import '../core/config.dart';
+import '../logging/http_log.dart';
+import 'direct_auth_api.dart';
+
+/// Signing in with a code emailed to the person — the Autonomous account API's own sign-in, the
+/// 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 (`direct_login.dart`), 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.
+///
+/// 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
+/// (`backend/src/lib/ssoAuth.ts` `fetchSsoProfile`), so nothing downstream can tell the two apart.
+/// Its refresh token, though, only renews HERE — see [refresh].
+class EmailCodeApi {
+ EmailCodeApi({required this.config, Dio? dio})
+ : _dio =
+ dio ??
+ attachHttpLog(
+ Dio(
+ BaseOptions(
+ baseUrl: accountApiUrl(config.autonomousEnv),
+ connectTimeout: const Duration(seconds: 15),
+ receiveTimeout: const Duration(seconds: 30),
+ headers: const {
+ 'Accept': 'application/json',
+ 'Content-Type': 'application/json',
+ // The account API reads its language from this header; the
+ // companion app sends it on every call.
+ 'Location': 'en-US',
+ },
+ validateStatus: (status) => status != null && status < 600,
+ ),
+ ),
+ );
+
+ final AppConfig config;
+ final Dio _dio;
+
+ /// The Autonomous account API for [autonomousEnv] — the hosts the backend validates tokens
+ /// against (`backend/src/config/env.ts`, `SSO_PROFILE_URL` / `STAGING_SSO_PROFILE_URL`).
+ static String accountApiUrl(String autonomousEnv) => autonomousEnv == 'stag'
+ ? 'https://apiv2.staging.autonomousdev.xyz'
+ : 'https://apiv2.autonomous.ai';
+
+ static const _sendPath = '/api/v1/customers/send-login-verification';
+ static const _signInPath = '/api/v1/customers/sign-in';
+
+ static const _unreachable =
+ 'Could not reach the sign-in service. Check your connection and try again.';
+
+ /// Emails a one-time sign-in code to [email].
+ Future<void> sendCode(String email) async {
+ await _call(_sendPath, {'email': email});
+ }
+
+ /// Trades the emailed [code] for a session.
+ Future<IssuedTokens> signIn({
+ required String email,
+ required String code,
+ }) async {
+ final data = await _call(_signInPath, {
+ 'email': email,
+ 'otp': code,
+ 'grant_type': 'otp',
+ });
+ return _tokens(data) ??
+ (throw const DirectAuthException('Sign-in returned no access token.'));
+ }
+
+ /// Renews a session this API issued.
+ ///
+ /// Held to the rule `DirectAuthApi.refresh` keeps: only the service ANSWERING that the token is
+ /// no good ends the session. A network failure or a 5xx is an outage, and reading an outage as
+ /// dead would delete a refresh token nothing can bring back — on a blip.
+ Future<IssuedTokens> refresh(String refreshToken) async {
+ final Response<dynamic> res;
+ try {
+ res = await _dio.post(
+ _signInPath,
+ data: {'refresh_token': refreshToken, 'grant_type': 'refresh_token'},
+ );
+ } on DioException {
+ throw const DirectAuthException(_unreachable);
+ }
+ if ((res.statusCode ?? 500) >= 500) {
+ throw const DirectAuthException(_unreachable);
+ }
+ final body = res.data is Map ? res.data as Map : const {};
+ final tokens = body['status'] == 1 ? _tokens(body['data']) : null;
+ return tokens ??
+ (throw const DirectAuthException(
+ 'Your sign-in expired. Sign in again.',
+ signedOut: true,
+ ));
+ }
+
+ /// POSTs [body] and returns the envelope's `data` — `{status, error_code, message, data}`,
+ /// where `status` 1 is success. Anything else is thrown with the service's own message, which
+ /// is written for the person ("Invalid OTP", "Email is invalid").
+ Future<Object?> _call(String path, Map<String, Object?> body) async {
+ final Response<dynamic> res;
+ try {
+ res = await _dio.post(path, data: body);
+ } on DioException {
+ throw const DirectAuthException(_unreachable);
+ }
+ final envelope = res.data is Map ? res.data as Map : const {};
+ if (envelope['status'] == 1) return envelope['data'];
+ final message = envelope['message'];
+ throw DirectAuthException(
+ message is String && message.trim().isNotEmpty
+ ? message.trim()
+ : _unreachable,
+ );
+ }
+
+ IssuedTokens? _tokens(Object? data) {
+ if (data is! Map) return null;
+ final token = data['access_token'];
+ if (token is! String || token.isEmpty) return null;
+ final refresh = data['refresh_token'], expiresIn = data['expire_in'];
+ return IssuedTokens(
+ token: token,
+ refreshToken: refresh is String && refresh.isNotEmpty ? refresh : null,
+ expiresIn: expiresIn is num && expiresIn > 0 ? expiresIn.toInt() : null,
+ autonomousEnv: config.autonomousEnv,
+ );
+ }
+}
diff --git a/mobile/lib/viewer/email_code_login.dart b/mobile/lib/viewer/email_code_login.dart
new file mode 100644
index 000000000..ac57a7893
--- /dev/null
+++ b/mobile/lib/viewer/email_code_login.dart
@@ -0,0 +1,24 @@
+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.
+///
+/// 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
+/// emailed-code session so it is renewed where it was issued.
+class EmailCodeLogin {
+ EmailCodeLogin({required this.auth});
+
+ final DirectAuth auth;
+
+ EmailCodeApi get _api => auth.emailCodes;
+
+ Future<void> sendCode(String email) => _api.sendCode(email);
+
+ Future<void> signIn({required String email, required String code}) async {
+ final tokens = await _api.signIn(email: email, code: code);
+ await auth.signIn(tokens, issuer: SessionIssuer.emailCode);
+ }
+}
diff --git a/mobile/lib/viewer/viewer_services.dart b/mobile/lib/viewer/viewer_services.dart
index d99814709..48c58f9d7 100644
--- a/mobile/lib/viewer/viewer_services.dart
+++ b/mobile/lib/viewer/viewer_services.dart
@@ -6,6 +6,7 @@ import 'direct_auth.dart';
import 'direct_auth_api.dart';
import 'direct_link.dart';
import 'direct_login.dart';
+import 'email_code_login.dart';
import 'e2ee_relay_codec.dart';
import 'viewer_key_store.dart';
@@ -25,6 +26,7 @@ class ViewerServices {
required this.keys,
required this.auth,
required this.login,
+ required this.emailLogin,
required this.links,
required this.relayCodecs,
required this.transportPlugins,
@@ -45,6 +47,7 @@ class ViewerServices {
keys: store,
auth: auth,
login: DirectLogin(auth: auth),
+ emailLogin: EmailCodeLogin(auth: auth),
links: DirectLink(keys: store, auth: auth, config: config),
relayCodecs: viewerRelayCodecs(store),
transportPlugins: transportPlugins ?? harnessTransportPlugins,
@@ -54,6 +57,9 @@ class ViewerServices {
final ViewerKeyStore keys;
final DirectAuth auth;
final DirectLogin login;
+
+ /// How a phone signs in — an emailed code, never the browser. See `email_code_api.dart`.
+ final EmailCodeLogin emailLogin;
final DirectLink links;
final RelayCodecFactory relayCodecs;
final TerminalTransportPluginFactory? transportPlugins;
diff --git a/mobile/test/screens_email_code_form_test.dart b/mobile/test/screens_email_code_form_test.dart
new file mode 100644
index 000000000..83ddd15bb
--- /dev/null
+++ b/mobile/test/screens_email_code_form_test.dart
@@ -0,0 +1,98 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/screens/email_code_form.dart';
+
+/// The phone's sign-in form: an email, then the four-digit code — no browser.
+void main() {
+ late List<String> sentTo;
+ late List<(String, String)> signedIn;
+ Object? refuseCode;
+
+ Future<void> pumpForm(WidgetTester tester) async {
+ sentTo = [];
+ signedIn = [];
+ refuseCode = null;
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: EmailCodeForm(
+ sendCode: (email) async => sentTo.add(email),
+ signIn: (email, code) async {
+ if (refuseCode case final error?) throw error;
+ signedIn.add((email, code));
+ },
+ ),
+ ),
+ ),
+ );
+ }
+
+ Future<void> askForCode(WidgetTester tester) async {
+ await tester.enterText(find.byKey(const Key('login-email')), ' [email protected] ');
+ await tester.tap(find.text('Email me a code'));
+ await tester.pump();
+ }
+
+ testWidgets('an email is asked for, then its code signs in', (tester) async {
+ await pumpForm(tester);
+ await askForCode(tester);
+
+ expect(sentTo, ['[email protected]']);
+ expect(find.text('We emailed a sign-in code to [email protected].'), findsOneWidget);
+
+ // The fourth digit signs in on its own.
+ await tester.enterText(find.byKey(const Key('login-code')), '1234');
+ await tester.pump();
+ expect(signedIn, [('[email protected]', '1234')]);
+ await tester.pump(EmailCodeForm.resendAfter);
+ });
+
+ testWidgets('something that is not an email is not sent', (tester) async {
+ await pumpForm(tester);
+ await tester.enterText(find.byKey(const Key('login-email')), 'nope');
+ await tester.tap(find.text('Email me a code'));
+ await tester.pump();
+
+ expect(sentTo, isEmpty);
+ expect(
+ find.text('Enter the email of your Autonomous account.'),
+ findsOneWidget,
+ );
+ });
+
+ testWidgets('a wrong code is said under the field, which stays', (
+ tester,
+ ) async {
+ await pumpForm(tester);
+ await askForCode(tester);
+ refuseCode = 'Invalid OTP';
+
+ await tester.enterText(find.byKey(const Key('login-code')), '9999');
+ await tester.pump();
+
+ expect(find.text('Invalid OTP'), findsOneWidget);
+ expect(find.byKey(const Key('login-code')), findsOneWidget);
+ await tester.pump(EmailCodeForm.resendAfter);
+ });
+
+ testWidgets('a code can be sent again only after the wait', (tester) async {
+ await pumpForm(tester);
+ await askForCode(tester);
+ expect(find.text('Resend in 30s'), findsOneWidget);
+
+ await tester.pump(EmailCodeForm.resendAfter);
+ await tester.tap(find.text('Resend code'));
+ await tester.pump();
+ expect(sentTo, ['[email protected]', '[email protected]']);
+ await tester.pump(EmailCodeForm.resendAfter);
+ });
+
+ testWidgets('a different email goes back to the first step', (tester) async {
+ await pumpForm(tester);
+ await askForCode(tester);
+ await tester.tap(find.text('Use a different email'));
+ await tester.pump();
+ expect(find.byKey(const Key('login-email')), findsOneWidget);
+ });
+}
diff --git a/mobile/test/viewer/direct_auth_issuer_test.dart b/mobile/test/viewer/direct_auth_issuer_test.dart
new file mode 100644
index 000000000..efa8dc6dd
--- /dev/null
+++ b/mobile/test/viewer/direct_auth_issuer_test.dart
@@ -0,0 +1,86 @@
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/viewer/direct_auth.dart';
+import 'package:harness_mobile/viewer/direct_auth_api.dart';
+import 'package:harness_mobile/viewer/email_code_api.dart';
+import 'package:harness_mobile/viewer/email_code_login.dart';
+
+import '../voice_fakes.dart' show MemoryKeyValueStore;
+import 'fake_http.dart';
+
+/// A refresh token only renews where it was issued: a session signed in with
+/// an emailed code goes back to the account API, an SSO one to the backend.
+void main() {
+ const config = AppConfig(apiBaseUrl: 'https://h.invalid');
+ const accountRenewal = {
+ 'status': 1,
+ 'data': {'access_token': 'from-account-api', 'expire_in': 3600},
+ };
+ const backendRenewal = {
+ 'success': true,
+ 'data': {'token': 'from-backend', 'expiresIn': 3600},
+ };
+
+ late FakeHttp backend, account;
+ late AuthSession session;
+ late DirectAuth auth;
+
+ setUp(() {
+ backend = FakeHttp({
+ '/api/auth/refresh': (status: 200, body: backendRenewal),
+ });
+ account = FakeHttp({
+ '/api/v1/customers/sign-in': (status: 200, body: accountRenewal),
+ });
+ session = AuthSession(storage: MemoryKeyValueStore());
+ auth = DirectAuth(
+ session: session,
+ api: DirectAuthApi(config: config, dio: backend.dio()),
+ emailCodes: EmailCodeApi(config: config, dio: account.dio()),
+ );
+ });
+
+ test('an emailed-code session renews through the account API', () async {
+ account.replies['/api/v1/customers/sign-in'] = (
+ status: 200,
+ body: {
+ 'status': 1,
+ 'data': {'access_token': 'first', 'refresh_token': 'r1'},
+ },
+ );
+ await EmailCodeLogin(auth: auth).signIn(email: '[email protected]', code: '1234');
+ expect(await session.issuer(), SessionIssuer.emailCode);
+
+ account.replies['/api/v1/customers/sign-in'] = (
+ status: 200,
+ body: accountRenewal,
+ );
+ expect(await auth.accessToken(force: true), 'from-account-api');
+ expect(backend.sent, isEmpty);
+ });
+
+ test('an SSO session still renews through the backend', () async {
+ await auth.signIn(const IssuedTokens(token: 'first', refreshToken: 'r1'));
+ expect(await session.issuer(), SessionIssuer.sso);
+
+ expect(await auth.accessToken(force: true), 'from-backend');
+ expect(account.sent, isEmpty);
+ });
+
+ test('a session saved before issuers were recorded is an SSO one', () async {
+ final storage = MemoryKeyValueStore();
+ await storage.write('auth_access_token', 'old');
+ expect(await AuthSession(storage: storage).issuer(), SessionIssuer.sso);
+ });
+
+ test('signing out forgets the issuer with the tokens', () async {
+ await auth.signIn(
+ const IssuedTokens(token: 't', refreshToken: 'r'),
+ issuer: SessionIssuer.emailCode,
+ );
+ await session.clear();
+ expect(await session.issuer(), SessionIssuer.sso);
+ });
+}
diff --git a/mobile/test/viewer/email_code_api_test.dart b/mobile/test/viewer/email_code_api_test.dart
new file mode 100644
index 000000000..4704d6fb2
--- /dev/null
+++ b/mobile/test/viewer/email_code_api_test.dart
@@ -0,0 +1,120 @@
+import 'package:flutter_test/flutter_test.dart';
+
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/viewer/direct_auth_api.dart';
+import 'package:harness_mobile/viewer/email_code_api.dart';
+
+import 'fake_http.dart';
+
+/// The Autonomous account API's own sign-in, as the companion app speaks it:
+/// snake_case bodies, a `{status, message, data}` envelope, status 1 for yes.
+void main() {
+ const send = '/api/v1/customers/send-login-verification';
+ const signIn = '/api/v1/customers/sign-in';
+ const issued = {
+ 'status': 1,
+ 'data': {
+ 'access_token': 'access-1',
+ 'refresh_token': 'refresh-1',
+ 'expire_in': 3600,
+ 'first_time': false,
+ 'epp_user': false,
+ },
+ };
+
+ EmailCodeApi api(FakeHttp http, {String env = 'prod'}) => EmailCodeApi(
+ config: AppConfig(apiBaseUrl: 'https://h.invalid', autonomousEnv: env),
+ dio: http.dio(),
+ );
+
+ test('each environment signs in against its own account API', () {
+ expect(EmailCodeApi.accountApiUrl('prod'), 'https://apiv2.autonomous.ai');
+ expect(
+ EmailCodeApi.accountApiUrl('stag'),
+ 'https://apiv2.staging.autonomousdev.xyz',
+ );
+ });
+
+ test('a code is asked for with the address alone', () async {
+ final http = FakeHttp({
+ send: (status: 200, body: {'status': 1, 'data': null}),
+ });
+ await api(http).sendCode('[email protected]');
+ expect(http.sent.single.path, send);
+ expect(http.sent.single.body, {'email': '[email protected]'});
+ });
+
+ test('a refusal is thrown in the service\'s own words', () async {
+ final http = FakeHttp({
+ send: (status: 200, body: {'status': 0, 'message': 'Email is invalid'}),
+ });
+ await expectLater(
+ api(http).sendCode('nope'),
+ throwsA(
+ isA<DirectAuthException>().having(
+ (e) => e.message,
+ 'message',
+ 'Email is invalid',
+ ),
+ ),
+ );
+ });
+
+ test('the code trades for a session, env and expiry kept', () async {
+ final http = FakeHttp({signIn: (status: 200, body: issued)});
+ final tokens = await api(
+ http,
+ env: 'stag',
+ ).signIn(email: '[email protected]', code: '1234');
+
+ expect(http.sent.single.body, {
+ 'email': '[email protected]',
+ 'otp': '1234',
+ 'grant_type': 'otp',
+ });
+ expect(tokens.token, 'access-1');
+ expect(tokens.refreshToken, 'refresh-1');
+ expect(tokens.expiresIn, 3600);
+ expect(tokens.autonomousEnv, 'stag');
+ });
+
+ group('refresh', () {
+ test('renews with the refresh grant', () async {
+ final http = FakeHttp({signIn: (status: 200, body: issued)});
+ final tokens = await api(http).refresh('refresh-0');
+ expect(http.sent.single.body, {
+ 'refresh_token': 'refresh-0',
+ 'grant_type': 'refresh_token',
+ });
+ expect(tokens.token, 'access-1');
+ });
+
+ test('a refusal ends the session', () async {
+ final http = FakeHttp({
+ signIn: (status: 200, body: {'status': 0, 'message': 'expired'}),
+ });
+ await expectLater(
+ api(http).refresh('refresh-0'),
+ throwsA(
+ isA<DirectAuthException>().having((e) => e.signedOut, 'out', true),
+ ),
+ );
+ });
+
+ test('an outage does not — the refresh token survives it', () async {
+ for (final http in [
+ FakeHttp({
+ signIn: (status: 503, body: {'status': 0}),
+ }),
+ FakeHttp({}), // offline
+ ]) {
+ await expectLater(
+ api(http).refresh('refresh-0'),
+ throwsA(
+ isA<DirectAuthException>().having((e) => e.signedOut, 'out', false),
+ ),
+ );
+ }
+ });
+ });
+}
diff --git a/mobile/test/viewer/fake_http.dart b/mobile/test/viewer/fake_http.dart
new file mode 100644
index 000000000..4b43c1725
--- /dev/null
+++ b/mobile/test/viewer/fake_http.dart
@@ -0,0 +1,53 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:dio/dio.dart';
+
+/// One canned answer: a status and a JSON body, or a failure to connect.
+typedef FakeReply = ({int status, Object? body});
+
+/// A Dio adapter that answers from [replies] by path, and remembers what was sent.
+class FakeHttp implements HttpClientAdapter {
+ FakeHttp(this.replies);
+
+ /// Path → reply. A path with no entry fails the way a dropped network does.
+ final Map<String, FakeReply> replies;
+ final sent = <({String path, Map<String, Object?> body})>[];
+
+ Dio dio() => Dio(
+ BaseOptions(
+ baseUrl: 'https://fake.invalid',
+ validateStatus: (status) => status != null && status < 600,
+ ),
+ )..httpClientAdapter = this;
+
+ @override
+ Future<ResponseBody> fetch(
+ RequestOptions options,
+ Stream<Uint8List>? requestStream,
+ Future<void>? cancelFuture,
+ ) async {
+ final data = options.data;
+ sent.add((
+ path: options.path,
+ body: data is Map ? Map<String, Object?>.from(data) : const {},
+ ));
+ final reply = replies[options.path];
+ if (reply == null) {
+ throw DioException.connectionError(
+ requestOptions: options,
+ reason: 'offline',
+ );
+ }
+ return ResponseBody.fromString(
+ jsonEncode(reply.body),
+ reply.status,
+ headers: {
+ Headers.contentTypeHeader: [Headers.jsonContentType],
+ },
+ );
+ }
+
+ @override
+ void close({bool force = false}) {}
+}