288 lines
10 KiB
Dart
288 lines
10 KiB
Dart
import 'dart:async';
|
|
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;
|
|
static final _credentialChanges = StreamController<String>.broadcast();
|
|
static Stream<String> 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<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)) {
|
|
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<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 final Map<Object, Map<String, String> Function(Uri)> _readers = {};
|
|
static void registerReader(
|
|
Object owner,
|
|
Map<String, String> Function(Uri) reader,
|
|
) => _readers[owner] = reader;
|
|
static void removeReader(Object owner) => _readers.remove(owner);
|
|
|
|
static final Map<String, int> _profileSignIns = {};
|
|
static Future<String?> signInProfile({
|
|
required String id,
|
|
required Iterable<Uri> endpoints,
|
|
required String password,
|
|
bool Function()? isCurrent,
|
|
}) async {
|
|
final candidates = endpoints.map(loginUriFor).whereType<Uri>().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<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, {
|
|
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<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 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<void> 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<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',
|
|
);
|
|
}
|