import 'dart:async'; import 'package:shared_preferences/shared_preferences.dart'; import 'login_probe.dart'; import 'server_session_stub.dart' if (dart.library.io) 'server_session_io.dart' as impl; import 'session_probe.dart'; export 'session_probe.dart'; /// The web sign-in the app carries on a phone. /// /// A browser keeps the server's login cookie itself. The native app signs in /// with the same password, keeps the returned session cookie, and sends it on /// the websocket and on file downloads, so it can reach a server that sits /// behind the web login (for example over Tailscale). A server with no login /// needs none of this. class ServerSession { ServerSession._(); static const _key = 'pipelines.session.cookie'; static String? _serverId; static Set _origins = {}; static int _generation = 0; static final Map _versions = {}; static String? get serverId => _serverId; static final _credentialChanges = StreamController.broadcast(); static Stream get credentialChanges => _credentialChanges.stream; /// Drop the active trust selection without deleting any server's sign-in. static void clearSelection() { _generation++; _serverId = null; _origins = {}; cookie = null; } static String _scopeKey(String id) => 'pipelines.session.v2.${Uri.encodeComponent(id)}.cookie'; /// Selects one logical server. Aliases explicitly trust the same credential. /// Clears the previous cookie synchronously, before loading this profile. static Future activateServer({ required String id, required Iterable endpoints, bool migrateLegacy = false, }) async { final origins = endpoints.map(loginUriFor).toSet(); if (id.isEmpty || origins.isEmpty || origins.contains(null)) { throw ArgumentError('A server needs an id and valid trusted endpoints.'); } final generation = ++_generation; _serverId = id; _origins = origins.cast(); cookie = null; final key = _scopeKey(id); final version = _versions[key]; try { final prefs = await SharedPreferences.getInstance(); if (_versions[key] != version) return; var value = prefs.getString(key); if (value == null && migrateLegacy && prefs.containsKey(_key)) { value = prefs.getString(_key) ?? ''; await prefs.setString(key, value); } if (_generation == generation && _versions[key] == version) { cookie = value == null || value.isEmpty ? null : value; } } catch (_) { // The newly selected profile stays signed out if storage is unavailable. } } /// The `name=value` session cookie, or null when signed out. static String? cookie; /// Headers that carry the session, empty when signed out. static Map get headers { final value = cookie; return value == null || value.isEmpty ? const {} : {'Cookie': value}; } /// Credentials are only sent to the selected profile's exact HTTP origins. /// Legacy callers bind their single origin by checking or signing in first. static Map headersFor(Uri endpoint) { final origin = loginUriFor(endpoint); if (origin == null || !_origins.contains(origin)) { for (final reader in _readers.values) { final scoped = reader(endpoint); if (scoped.isNotEmpty) return scoped; } return const {}; } return headers; } /// Read one profile without changing the selected socket or credentials. static Future Function(Uri)> credentialReader({ required String id, required Iterable endpoints, }) async { final origins = endpoints.map(loginUriFor).whereType().toSet(); final key = _scopeKey(id); final version = _versions[key]; final value = id == _serverId ? cookie : (await SharedPreferences.getInstance()).getString(key); return (Uri uri) { if (_versions[key] != version || !origins.contains(loginUriFor(uri)) || value == null || value.isEmpty) { return const {}; } return {'Cookie': value}; }; } static final Map Function(Uri)> _readers = {}; static void registerReader( Object owner, Map Function(Uri) reader, ) => _readers[owner] = reader; static void removeReader(Object owner) => _readers.remove(owner); static final Map _profileSignIns = {}; static Future signInProfile({ required String id, required Iterable endpoints, required String password, bool Function()? isCurrent, }) async { final candidates = endpoints.map(loginUriFor).whereType().toList(); if (candidates.isEmpty) return 'This machine has no valid address.'; final key = _scopeKey(id), version = _versions[_scopeKey(id)]; final attempt = (_profileSignIns[id] ?? 0) + 1; _profileSignIns[id] = attempt; String? problem; for (final login in candidates) { final result = await impl.postLogin(login, password); if (_profileSignIns[id] != attempt || _versions[key] != version || !(isCurrent?.call() ?? true)) { return 'The sign-in changed. Retry.'; } if (result.cookie != null) { final prefs = await SharedPreferences.getInstance(); if (_profileSignIns[id] != attempt || _versions[key] != version || !(isCurrent?.call() ?? true)) { return 'The sign-in changed. Retry.'; } final committedVersion = (version ?? 0) + 1; _versions[key] = committedVersion; await prefs.setString(key, result.cookie!); if (_versions[key] != committedVersion) { return 'The sign-in changed. Retry.'; } if (!(isCurrent?.call() ?? true)) { _versions[key] = committedVersion + 1; await prefs.setString(key, ''); return 'The machine changed. Retry signing in.'; } if (_serverId == id) cookie = result.cookie; _credentialChanges.add(id); return null; } problem = result.error ?? 'Sign-in failed.'; if (!problem.startsWith('Could not reach')) return problem; } return problem; } static Future load() async { final generation = ++_generation; _serverId = null; _origins = {}; cookie = null; try { final prefs = await SharedPreferences.getInstance(); if (_generation == generation) cookie = prefs.getString(_key); } catch (_) {} } static Future _save( String? value, String key, int generation, int version, { String? profileId, }) async { if (_versions[key] != version) return; if (_generation == generation) cookie = value; try { final prefs = await SharedPreferences.getInstance(); if (_versions[key] != version) return; if (value == null && key == _key) { await prefs.remove(_key); } else { // An empty scoped value records an intentional sign-out and prevents // subsequent legacy migration from reviving the old credential. await prefs.setString(key, value ?? ''); } } catch (_) {} if (profileId != null && _versions[key] == version) { _credentialChanges.add(profileId); } } /// Signs in at the web login beside [endpoint] (its `/login` page) with /// [password] and keeps the session. Returns null on success, otherwise /// what went wrong in words. static Future signIn(Uri endpoint, String password) async { final login = loginUriFor(endpoint); if (login == null) return 'The server address has no web login.'; if (_serverId != null && !_origins.contains(login)) { return 'The server address is not a trusted alias of the selected server.'; } final generation = _generation; final profileId = _serverId; final key = profileId == null ? _key : _scopeKey(profileId); final previous = _versions[key]; final version = (previous ?? 0) + 1; _versions[key] = version; final result = await impl.postLogin(login, password); if (result.cookie != null) { if (_serverId == null && _generation == generation) _origins = {login}; await _save( result.cookie, key, generation, version, profileId: profileId, ); return null; } if (_versions[key] == version) { if (previous == null) { _versions.remove(key); } else { _versions[key] = previous; } } return result.error ?? 'Sign-in failed.'; } static Future signOut() { final key = _serverId == null ? _key : _scopeKey(_serverId!); final version = (_versions[key] ?? 0) + 1; _versions[key] = version; return _save(null, key, _generation, version, profileId: _serverId); } /// Whether [endpoint]'s server accepts the kept session. static Future check(Uri endpoint) async => (await probe(endpoint)).state; /// [check] with the reason an address could not be used. static Future probe(Uri endpoint) async { final login = loginUriFor(endpoint); if (login == null) { return const ServerProbeResult( SessionState.unreachable, reason: 'The address has no web login; use ws:// or wss://.', ); } // A pre-profile client supplies its sole server through this API. Bind // once, not on every probe, so probing another host cannot leak its cookie. if (_serverId == null && _origins.isEmpty) _origins = {login}; return interpret(login, await impl.probeLogin(login, headersFor(login))); } /// Probes one saved machine with its own kept sign-in, without changing the /// selected server or its credentials. static Future probeProfile({ required String id, required Iterable endpoints, }) async { final reader = await credentialReader(id: id, endpoints: endpoints); ServerProbeResult? last; for (final endpoint in endpoints) { final login = loginUriFor(endpoint); if (login == null) continue; last = interpret(login, await impl.probeLogin(login, reader(login))); if (last.state != SessionState.unreachable) return last; } return last ?? const ServerProbeResult( SessionState.unreachable, reason: 'This machine has no valid address.', ); } /// See [interpretLoginProbe]. static ServerProbeResult interpret(Uri login, LoginProbe probe) => interpretLoginProbe(login, probe); }