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.

6.1 KB
Raw Blame
import '../core/harness_file_store.dart';
import '../core/local_key_value_store.dart';

/// Who issued a session — and therefore who renews it.
///
/// The first two 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. The
/// third is Harness's own.
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,

  /// The Harness backend itself, for a phone signed in by scanning a signed-in
  /// computer's Add Phone QR (backend `lib/harnessSession.ts`). Renewed through
  /// the backend's `/api/auth/refresh`, as [sso] is, and revoked there on sign
  /// out.
  harness,
}

/// Persists the SSO access + refresh tokens in the Desktop Harness state file.
class AuthSession {
  final LocalKeyValueStore _storage;
  static const _access = 'auth_access_token';
  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';
  static const _ssoClientId = 'auth_sso_client_id';
  static const _accountId = 'auth_account_id';

  AuthSession({LocalKeyValueStore? storage})
    : _storage = storage ?? HarnessFileStore.shared;

  /// Store a newly authenticated session. A missing refresh token clears any
  /// stale token left by a previous account/environment.
  Future<void> saveLogin({
    required String token,
    String? refreshToken,
    String autonomousEnv = 'prod',
    int? expiresIn,
    SessionIssuer issuer = SessionIssuer.sso,
    String? ssoClientId,
  }) async {
    // First: a new token must never be found beside the last account's id.
    await _storage.delete(_accountId);
    await _storage.write(_access, token);
    await _storage.write(_issuer, issuer.name);
    if (refreshToken != null && refreshToken.isNotEmpty) {
      await _storage.write(_refresh, refreshToken);
    } else {
      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);
  }

  /// Store a refreshed access token. Identity providers do not always rotate
  /// the refresh token, so retain the current one when it is omitted.
  Future<void> saveRefresh({
    required String token,
    String? refreshToken,
    required String autonomousEnv,
    int? expiresIn,
  }) async {
    await _storage.write(_access, token);
    if (refreshToken != null && refreshToken.isNotEmpty) {
      await _storage.write(_refresh, refreshToken);
    }
    await _storage.write(_env, autonomousEnv);
    await _saveExpiry(expiresIn);
  }

  Future<String?> accessToken() => _storage.read(_access);
  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 {
    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));

  /// The token and its expiry as ONE read.
  ///
  /// The launch asks both questions back to back — is there a session, and is it
  /// still good — and asking them separately costs two exclusive locks on
  /// `state.json` and two full parses of it (see [HarnessFileStore]), in series,
  /// before the app can so much as decide which screen to show.
  ///
  /// Reading them together also makes the pair coherent: taken separately, a
  /// refresh landing between the two reads returns the OLD token with the NEW
  /// expiry — a token that then looks fresh and is not, which is a sign-in
  /// failure several round-trips later rather than a refresh here.
  Future<({String? token, DateTime? expiresAt})> accessTokenWithExpiry() async {
    final saved = await _storage.readMany([_access, _expiresAt]);
    return (token: saved[_access], expiresAt: _expiryFrom(saved[_expiresAt]));
  }

  static DateTime? _expiryFrom(String? raw) {
    final milliseconds = int.tryParse(raw ?? '');
    return milliseconds == null
        ? null
        : DateTime.fromMillisecondsSinceEpoch(milliseconds, isUtc: true);
  }

  Future<void> _saveExpiry(int? expiresIn) async {
    if (expiresIn == null || expiresIn <= 0) {
      await _storage.delete(_expiresAt);
      return;
    }
    final expiresAt = DateTime.now().toUtc().add(Duration(seconds: expiresIn));
    await _storage.write(
      _expiresAt,
      expiresAt.millisecondsSinceEpoch.toString(),
    );
  }

  /// Whose this sign-in is, as the account last said: what lets a launch open
  /// what it kept for that account before the account has answered again. Null
  /// until then. A renewal keeps it, being the same sign-in; a new sign-in and a
  /// sign-out forget it.
  Future<String?> accountId() => _storage.read(_accountId);
  Future<void> saveAccountId(String id) => _storage.write(_accountId, id);

  Future<void> clear() async {
    await _storage.delete(_accountId);
    await _storage.delete(_access);
    await _storage.delete(_refresh);
    await _storage.delete(_env);
    await _storage.delete(_expiresAt);
    await _storage.delete(_issuer);
    await _storage.delete(_ssoClientId);
  }
}