Files
pipelines/app/lib/core/session/server_session.dart
T
alan 079924d19a Recover from zero servers, sign each machine in on its own, offer every route
- Removing the primary machine hands pipelines/runs to the next saved machine
  on native hosts; removing the last machine returns to the connect screen
  instead of stranding the app on "Server endpoint not configured".
- Add server probes the new machine and asks for its own password in the same
  page; Settings rows show Connected / Sign in required / Unreachable with the
  reason and offer Sign in; no other machine's credential is ever reused.
- Unreachable addresses explain why: a TLS failure against an IP points at the
  Tailscale name, a non-Pipelines answer points at the port.
- Discovered machines list every advertised route (LAN, Tailscale IP, Tailscale
  name) as a checklist; chosen routes are saved as one machine.
- tool/connection_probe.dart replays the native login and websocket against
  real addresses for diagnosis.
2026-11-08 23:59:20 +00:00

301 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);
}