fdc730422d
Phase 2.3 and 2.4 of docs/plans/floating-windows.md. A floating chat is a window of the chat kind over the app's WindowManager, built from the app-lifetime ChatRuntime, so it shows over every destination and at start without the Chat destination being built. Float and Dock move the same keyed view between the tiling and the window host. The pipelines app keeps one runtime and one ChatWindows; saved chatFloat records (v1 and v2) are brought over once. ChatFloatHost, ChatFloatWindow, the float frames and binding, the controller's float list and FloatingFocusRoot are gone; the workspace only asks whether a chat is out in a window. Every MenuAnchor targets the root overlay (guarded by a test), and menus and tooltips name the Alt chords.
300 lines
10 KiB
Dart
300 lines
10 KiB
Dart
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<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 =>
|
|
(await probe(endpoint)).state;
|
|
|
|
/// [check] with the reason an address could not be used.
|
|
static Future<ServerProbeResult> 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<ServerProbeResult> probeProfile({
|
|
required String id,
|
|
required Iterable<Uri> 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);
|
|
}
|