import 'package:shared_preferences/shared_preferences.dart'; import 'server_session_stub.dart' if (dart.library.io) 'server_session_io.dart' as impl; /// 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'; /// 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}; } static Future load() async { try { final prefs = await SharedPreferences.getInstance(); cookie = prefs.getString(_key); } catch (_) { cookie = null; } } static Future _save(String? value) async { cookie = value; try { final prefs = await SharedPreferences.getInstance(); if (value == null) { await prefs.remove(_key); } else { await prefs.setString(_key, value); } } catch (_) {} } /// 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.'; final result = await impl.postLogin(login, password); if (result.cookie != null) { await _save(result.cookie); return null; } return result.error ?? 'Sign-in failed.'; } static Future signOut() => _save(null); } /// The web login page for a websocket endpoint: same host and port, http(s). Uri? loginUriFor(Uri endpoint) { final scheme = switch (endpoint.scheme) { 'wss' || 'https' => 'https', 'ws' || 'http' => 'http', _ => null, }; if (scheme == null || endpoint.host.isEmpty) return null; return Uri( scheme: scheme, host: endpoint.host, port: endpoint.hasPort ? endpoint.port : null, path: '/login', ); }