Files
pipelines/app/lib/core/session/server_session.dart
T

207 lines
7.2 KiB
Dart

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';
static String? _serverId;
static Set<Uri> _origins = {};
static int _generation = 0;
static final Map<String, int> _versions = {};
static String? get serverId => _serverId;
/// 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<void> activateServer({
required String id,
required Iterable<Uri> 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<Uri>();
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<String, String> 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<String, String> headersFor(Uri endpoint) {
final origin = loginUriFor(endpoint);
if (origin == null || !_origins.contains(origin)) {
return const {};
}
return headers;
}
/// Read one profile without changing the selected socket or credentials.
static Future<Map<String, String> Function(Uri)> credentialReader({
required String id,
required Iterable<Uri> endpoints,
}) async {
final origins = endpoints.map(loginUriFor).whereType<Uri>().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 <String, String>{};
}
return <String, String>{'Cookie': value};
};
}
static Future<void> 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<void> _save(
String? value,
String key,
int generation,
int version,
) 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 (_) {}
}
/// 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<String?> 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 key = _serverId == null ? _key : _scopeKey(_serverId!);
final version = (_versions[key] ?? 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);
return null;
}
return result.error ?? 'Sign-in failed.';
}
static Future<void> signOut() {
final key = _serverId == null ? _key : _scopeKey(_serverId!);
final version = (_versions[key] ?? 0) + 1;
_versions[key] = version;
return _save(null, key, _generation, version);
}
/// Whether [endpoint]'s server accepts the kept session.
static Future<SessionState> check(Uri endpoint) async {
final login = loginUriFor(endpoint);
if (login == null) return SessionState.unreachable;
// 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};
final status = await impl.probeLogin(login, headersFor(login));
if (status == null) return SessionState.unreachable;
// The web login sends a signed-in visitor on; it shows its form otherwise.
if (status >= 300 && status < 400) return SessionState.signedIn;
if (status == 200) return SessionState.signedOut;
return SessionState.unreachable;
}
}
/// What a server says about this device's session.
enum SessionState { signedIn, signedOut, unreachable }
/// 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 || endpoint.userInfo.isNotEmpty) {
return null;
}
return Uri(
scheme: scheme,
host: endpoint.host,
port: endpoint.hasPort ? endpoint.port : null,
path: '/login',
);
}