diff --git a/app/lib/application/pipelines_root.dart b/app/lib/application/pipelines_root.dart index 09075b90..65974169 100644 --- a/app/lib/application/pipelines_root.dart +++ b/app/lib/application/pipelines_root.dart @@ -77,20 +77,37 @@ class _PipelinesRootState extends State { _chatPool = widget.chatPoolFactory?.call(_servers) ?? ChatServerPool(_servers, web: widget.web); + // Settings asks each new machine for its own password through the pool. + _servers.authenticator = _chatPool; } } + ServerProbe get _probe => identical(widget.check, ServerSession.check) + ? ServerSession.probe + : probeFromCheck(widget.check); + late final ServerConnections _servers = ServerConnections( store: widget.catalogStore, onSelected: _selectServer, + replaceRemovedPrimary: !widget.web, ); @override void initState() { super.initState(); + _servers.addListener(_onServersChanged); _loadServers(); } + /// A native host with no saved machine left has nothing to connect to, so + /// it returns to Add server however the last profile went away. Removing a + /// profile that was not the primary never activated anything before, which + /// stranded the app on "Server endpoint not configured". + void _onServersChanged() { + if (widget.web || _booting || _onboarding) return; + if (_servers.catalog.servers.isEmpty) unawaited(_activate(null)); + } + Future _loadServers() async { await _servers.load(legacyEndpoint: widget.server.uri?.toString() ?? ''); if (!mounted) return; @@ -211,7 +228,7 @@ class _PipelinesRootState extends State { .map(Uri.parse) .where((uri) => uri != endpoint), ], - check: widget.check, + probe: _probe, isCurrent: () => mounted && token == _activation, ); if (!mounted || @@ -247,7 +264,11 @@ class _PipelinesRootState extends State { }); } - Future _saveOnboardingServer(String url, {String? name}) async { + Future _saveOnboardingServer( + String url, { + String? name, + Iterable aliases = const [], + }) async { final token = _activation; SavedServer? target; for (final server in _servers.catalog.servers) { @@ -258,7 +279,7 @@ class _PipelinesRootState extends State { name: name?.trim().isNotEmpty == true ? name!.trim() : Uri.parse(url).host, - endpoints: [url], + endpoints: [url, ...aliases], ); if (!await _servers.save(target, activate: false) || !await _servers.select(target.id, activate: false)) { @@ -278,6 +299,7 @@ class _PipelinesRootState extends State { @override void dispose() { _activation++; + _servers.removeListener(_onServersChanged); _chatPool?.dispose(); _servers.dispose(); super.dispose(); @@ -326,8 +348,14 @@ class _PipelinesRootState extends State { final flow = OnboardingFlow( initialServer: _server.uri?.toString() ?? widget.buildDefault, startAtPassword: _refused, + probe: _probe, saveServer: _saveOnboardingServer, saveServerProfile: (url, name) => _saveOnboardingServer(url, name: name), + saveMachine: (endpoints, name) => _saveOnboardingServer( + endpoints.first, + name: name, + aliases: endpoints.skip(1), + ), onDone: _done, savedServers: SavedServersSection(connections: _servers), discovery: platformServerDiscovery(web: widget.web), diff --git a/app/lib/core/servers/chat/browser_peer.dart b/app/lib/core/servers/chat/browser_peer.dart index 36fcafc0..c0e689cb 100644 --- a/app/lib/core/servers/chat/browser_peer.dart +++ b/app/lib/core/servers/chat/browser_peer.dart @@ -3,7 +3,10 @@ import 'browser_peer_stub.dart' if (dart.library.js_interop) 'browser_peer_web.dart' as impl; -Future<({bool connected, String? error})> registerBrowserPeer( +/// Registers [server] with the same-origin relay. [needsPassword] is the +/// relay's own verdict, distinct from an unreachable machine. +Future<({bool connected, bool needsPassword, String? error})> +registerBrowserPeer( SavedServer server, { String? password, }) => impl.register(server, password: password); diff --git a/app/lib/core/servers/chat/browser_peer_stub.dart b/app/lib/core/servers/chat/browser_peer_stub.dart index ab524e1e..065a63a9 100644 --- a/app/lib/core/servers/chat/browser_peer_stub.dart +++ b/app/lib/core/servers/chat/browser_peer_stub.dart @@ -1,8 +1,11 @@ import '../server_catalog.dart'; -Future<({bool connected, String? error})> register( +Future<({bool connected, bool needsPassword, String? error})> register( SavedServer server, { String? password, -}) async => - (connected: false, error: 'Browser relay is unavailable on this platform.'); +}) async => ( + connected: false, + needsPassword: false, + error: 'Browser relay is unavailable on this platform.', +); Future remove(String id) async {} diff --git a/app/lib/core/servers/chat/browser_peer_web.dart b/app/lib/core/servers/chat/browser_peer_web.dart index 43813231..f7282408 100644 --- a/app/lib/core/servers/chat/browser_peer_web.dart +++ b/app/lib/core/servers/chat/browser_peer_web.dart @@ -20,7 +20,7 @@ extension type _Response._(JSObject _) implements JSObject { external JSPromise text(); } -Future<({bool connected, String? error})> register( +Future<({bool connected, bool needsPassword, String? error})> register( SavedServer server, { String? password, }) async { @@ -39,12 +39,16 @@ Future<({bool connected, String? error})> register( ).toDart.timeout(const Duration(seconds: 20)); final body = jsonDecode((await response.text().toDart).toDart); if (response.status == 200 && body is Map && body['connected'] == true) { - return (connected: true, error: null); + return (connected: true, needsPassword: false, error: null); } + final needsPassword = body is Map && body['needs_password'] == true; return ( connected: false, - error: body is Map && body['needs_password'] == true - ? 'Sign in to this machine.' + needsPassword: needsPassword, + error: needsPassword + ? (password == null + ? 'Sign in to this machine.' + : 'Wrong password for this machine.') : body is Map ? '${body['error'] ?? 'Could not connect to this machine.'}' : 'Could not connect to this machine.', diff --git a/app/lib/core/servers/chat/chat_machine_connection.dart b/app/lib/core/servers/chat/chat_machine_connection.dart index e286d380..6218b9fb 100644 --- a/app/lib/core/servers/chat/chat_machine_connection.dart +++ b/app/lib/core/servers/chat/chat_machine_connection.dart @@ -6,6 +6,14 @@ import '../../transport/pipelines_client.dart'; import '../server_catalog.dart'; import 'browser_peer.dart'; +/// The machine answered and wants its own password; it is not unreachable. +class MachineSignInRequired implements Exception { + const MachineSignInRequired(this.message); + final String message; + @override + String toString() => message; +} + class ChatMachineConnection { ChatMachineConnection({ required this.gateway, @@ -46,7 +54,10 @@ Future connectChatMachine( } else { final result = await registerBrowserPeer(server); if (!result.connected) { - throw StateError(result.error ?? 'Sign in to this machine.'); + if (result.needsPassword) { + throw MachineSignInRequired(result.error ?? 'Sign in to this machine.'); + } + throw StateError(result.error ?? 'Could not connect to this machine.'); } endpoints = actual .map((uri) => browserPeerEndpoint(server.id, uri)) diff --git a/app/lib/core/servers/chat/chat_server_pool.dart b/app/lib/core/servers/chat/chat_server_pool.dart index 3a9b4e82..d68b0a1c 100644 --- a/app/lib/core/servers/chat/chat_server_pool.dart +++ b/app/lib/core/servers/chat/chat_server_pool.dart @@ -8,6 +8,7 @@ export 'chat_machine_connection.dart'; import '../../session/server_session.dart'; import '../../transport/pipelines_client.dart'; import '../../../features/settings/server_connections.dart'; +import '../machine_access.dart'; import '../server_catalog.dart'; import 'browser_peer.dart'; import 'chat_server_gateway.dart'; @@ -23,12 +24,28 @@ class ChatMachineStatus { StreamSubscription? frames; StreamSubscription? states; int generation = 0; + + /// Why the machine is not connected, once classified; null while unknown. + MachineAccessResult? access; } +/// Probes one saved machine with its own kept sign-in (see +/// [ServerSession.probeProfile]); injectable so pool tests stay offline. +typedef ProfileProbe = + Future Function({ + required String id, + required Iterable endpoints, + }); + /// One independent authenticated socket per saved machine. Aliases are failover /// addresses of that machine, never a fallback to another machine's identity. -class ChatServerPool extends ChangeNotifier { - ChatServerPool(this.servers, {this.connect, this.web = kIsWeb}) { +class ChatServerPool extends ChangeNotifier implements MachineAuthenticator { + ChatServerPool( + this.servers, { + this.connect, + this.web = kIsWeb, + this.probeProfile = ServerSession.probeProfile, + }) { gateway = FederatedChatGateway( () => { for (final item in _machines.values) @@ -56,7 +73,9 @@ class ChatServerPool extends ChangeNotifier { final ServerConnections servers; final bool web; final Future Function(SavedServer)? connect; + final ProfileProbe probeProfile; final _machines = {}; + final _classifying = {}; final _frames = StreamController.broadcast(); late final FederatedChatGateway gateway; late final AttentionAckSync ackSync; @@ -116,6 +135,7 @@ class ChatServerPool extends ChangeNotifier { item.connecting = true; item.connected = false; item.error = null; + item.access = null; notifyListeners(); try { final connection = @@ -156,23 +176,119 @@ class ChatServerPool extends ChangeNotifier { item.connected = state.kind == ConnectionKind.connected; item.connecting = state.kind == ConnectionKind.connecting; item.error = item.connected ? null : state.reason; + if (item.connected) item.access = null; if (item.connected && !was) { revision++; unawaited(ackSync.connected()); } + if (!item.connected && !item.connecting && item.access == null) { + unawaited(_classify(item, generation)); + } notifyListeners(); }); revision++; - if (item.connected) unawaited(ackSync.connected()); + if (item.connected) { + unawaited(ackSync.connected()); + } else { + unawaited(_classify(item, generation)); + } } catch (error) { if (_disposed || generation != item.generation) return; item.connecting = false; item.connected = false; item.error = '$error'; + item.access = error is MachineSignInRequired + ? MachineAccessResult( + MachineAccess.needsPassword, + detail: error.message, + ) + : MachineAccessResult(MachineAccess.unreachable, detail: '$error'); } if (!_disposed) notifyListeners(); } + /// A native socket that did not open says nothing about why. Ask the web + /// login with this machine's own kept sign-in: a form means it wants its + /// password, a redirect means the sign-in is fine and the socket failed. + Future _classify(ChatMachineStatus item, int generation) async { + final id = item.server.id; + if (web || !_classifying.add(id)) return; + try { + final result = await probeProfile( + id: id, + endpoints: item.server.endpoints.map(Uri.parse), + ); + if (_disposed || generation != item.generation || item.connected) return; + item.access = switch (result.state) { + SessionState.signedOut => MachineAccessResult( + MachineAccess.needsPassword, + detail: '${item.server.name} asks for its password.', + ), + SessionState.signedIn => MachineAccessResult( + MachineAccess.unreachable, + detail: + 'Signed in, but the connection did not open: ' + '${item.error ?? 'unknown reason'}.', + ), + SessionState.unreachable => MachineAccessResult( + MachineAccess.unreachable, + detail: result.reason ?? item.error, + ), + }; + notifyListeners(); + } finally { + _classifying.remove(id); + } + } + + @override + MachineAccessResult? status(String id) { + final item = _machines[id]; + if (item == null || item.connecting) return null; + if (item.connected) { + return const MachineAccessResult(MachineAccess.connected); + } + return item.access ?? + MachineAccessResult(MachineAccess.unreachable, detail: item.error); + } + + @override + Future probe(SavedServer server) async { + if (web) { + final result = await registerBrowserPeer(server); + if (result.connected) { + return const MachineAccessResult(MachineAccess.connected); + } + return MachineAccessResult( + result.needsPassword + ? MachineAccess.needsPassword + : MachineAccess.unreachable, + detail: result.error, + ); + } + final result = await probeProfile( + id: server.id, + endpoints: server.endpoints.map(Uri.parse), + ); + return switch (result.state) { + SessionState.signedIn => const MachineAccessResult( + MachineAccess.connected, + ), + SessionState.signedOut => MachineAccessResult( + MachineAccess.needsPassword, + detail: '${server.name} asks for its password.', + ), + SessionState.unreachable => MachineAccessResult( + MachineAccess.unreachable, + detail: result.reason, + ), + }; + } + + @override + Future authenticate(SavedServer server, String password) => + signIn(server.id, password); + Future retry(String id) async { final item = _machines[id]; if (item != null) await _open(item); diff --git a/app/lib/core/servers/chat/chat_server_status.dart b/app/lib/core/servers/chat/chat_server_status.dart index 70f3f1f5..83e13a1d 100644 --- a/app/lib/core/servers/chat/chat_server_status.dart +++ b/app/lib/core/servers/chat/chat_server_status.dart @@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../ui/adaptive/host.dart'; import 'chat_server_pool.dart'; +import 'machine_sign_in_dialog.dart'; /// Connection problems on one machine never hide healthy machines' chats. class ChatServerStatusBar extends StatelessWidget { @@ -12,13 +13,10 @@ class ChatServerStatusBar extends StatelessWidget { '${machine.server.name} · ${machine.connecting ? 'Connecting' : 'Sign in'}'; final action = machine.connecting ? null - : () => _showMachineSignIn( + : () => showMachineSignIn( context, - _MachineSignIn( - pool: pool, - id: machine.server.id, - name: machine.server.name, - ), + name: machine.server.name, + signIn: (password) => pool.signIn(machine.server.id, password), ); if (usesCupertinoHost(context)) { return CupertinoButton( @@ -80,106 +78,3 @@ class ChatServerStatusBar extends StatelessWidget { ], ); } - -class _MachineSignIn extends StatefulWidget { - const _MachineSignIn({ - required this.pool, - required this.id, - required this.name, - }); - final ChatServerPool pool; - final String id, name; - @override - State<_MachineSignIn> createState() => _MachineSignInState(); -} - -class _MachineSignInState extends State<_MachineSignIn> { - final password = TextEditingController(); - bool busy = false; - String? error; - @override - void dispose() { - password.dispose(); - super.dispose(); - } - - Future submit() async { - setState(() { - busy = true; - error = null; - }); - try { - final problem = await widget.pool.signIn(widget.id, password.text); - if (!mounted) return; - if (problem == null) { - Navigator.pop(context); - return; - } - setState(() => error = problem); - } catch (_) { - if (mounted) { - setState( - () => error = 'Could not sign in. Check the password and connection.', - ); - } - } finally { - if (mounted) setState(() => busy = false); - } - } - - @override - Widget build(BuildContext context) { - final cupertino = usesCupertinoHost(context); - final field = cupertino - ? CupertinoTextField( - controller: password, - obscureText: true, - placeholder: 'Password', - onSubmitted: busy ? null : (_) => submit(), - ) - : TextField( - controller: password, - obscureText: true, - decoration: const InputDecoration(labelText: 'Password'), - onSubmitted: busy ? null : (_) => submit(), - ); - final content = Column( - mainAxisSize: MainAxisSize.min, - children: [field, if (error != null) Text(error!)], - ); - return cupertino - ? CupertinoAlertDialog( - title: Text('Sign in to ${widget.name}'), - content: content, - actions: [ - CupertinoDialogAction( - onPressed: busy ? null : () => Navigator.pop(context), - child: const Text('Cancel'), - ), - CupertinoDialogAction( - onPressed: busy ? null : submit, - child: Text(busy ? 'Signing in…' : 'Sign in'), - ), - ], - ) - : AlertDialog( - title: Text('Sign in to ${widget.name}'), - content: content, - actions: [ - TextButton( - onPressed: busy ? null : () => Navigator.pop(context), - child: const Text('Cancel'), - ), - FilledButton( - onPressed: busy ? null : submit, - child: Text(busy ? 'Signing in…' : 'Sign in'), - ), - ], - ); - } -} - -Future _showMachineSignIn(BuildContext context, Widget dialog) => - usesCupertinoHost(context) - ? showCupertinoDialog(context: context, builder: (_) => dialog) - : showDialog(context: context, builder: (_) => dialog); diff --git a/app/lib/core/servers/chat/machine_sign_in_dialog.dart b/app/lib/core/servers/chat/machine_sign_in_dialog.dart new file mode 100644 index 00000000..4768dbf4 --- /dev/null +++ b/app/lib/core/servers/chat/machine_sign_in_dialog.dart @@ -0,0 +1,138 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; + +/// Asks for one machine's own password. [signIn] returns null on success, +/// otherwise the sentence to show; the dialog stays open for a retry. +Future showMachineSignIn( + BuildContext context, { + required String name, + required Future Function(String password) signIn, +}) { + final dialog = MachineSignInDialog(name: name, signIn: signIn); + return usesCupertinoHost(context) + ? showCupertinoDialog(context: context, builder: (_) => dialog) + : showDialog(context: context, builder: (_) => dialog); +} + +class MachineSignInDialog extends StatefulWidget { + const MachineSignInDialog({ + super.key, + required this.name, + required this.signIn, + }); + + final String name; + final Future Function(String password) signIn; + + @override + State createState() => _MachineSignInDialogState(); +} + +class _MachineSignInDialogState extends State { + final password = TextEditingController(); + bool busy = false; + String? error; + + @override + void dispose() { + password.dispose(); + super.dispose(); + } + + Future submit() async { + if (password.text.isEmpty) return; + setState(() { + busy = true; + error = null; + }); + try { + final problem = await widget.signIn(password.text); + if (!mounted) return; + if (problem == null) { + Navigator.pop(context); + return; + } + setState(() => error = problem); + } catch (_) { + if (mounted) { + setState( + () => error = 'Could not sign in. Check the password and connection.', + ); + } + } finally { + if (mounted) setState(() => busy = false); + } + } + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + final field = cupertino + ? CupertinoTextField( + key: const Key('machine-password'), + controller: password, + obscureText: true, + autofocus: true, + placeholder: 'Password', + onSubmitted: busy ? null : (_) => submit(), + ) + : TextField( + key: const Key('machine-password'), + controller: password, + obscureText: true, + autofocus: true, + decoration: const InputDecoration(labelText: 'Password'), + onSubmitted: busy ? null : (_) => submit(), + ); + final content = Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + 'Enter the password chosen when Pipelines was installed on ' + '${widget.name}. Each machine keeps its own sign-in.', + ), + const SizedBox(height: 12), + field, + if (error != null) ...[ + const SizedBox(height: 8), + Text(error!, key: const Key('machine-sign-in-error')), + ], + ], + ); + final title = Text('Sign in to ${widget.name}'); + return cupertino + ? CupertinoAlertDialog( + title: title, + content: content, + actions: [ + CupertinoDialogAction( + onPressed: busy ? null : () => Navigator.pop(context), + child: const Text('Cancel'), + ), + CupertinoDialogAction( + key: const Key('machine-sign-in'), + onPressed: busy ? null : submit, + child: Text(busy ? 'Signing in…' : 'Sign in'), + ), + ], + ) + : AlertDialog( + title: title, + content: content, + actions: [ + TextButton( + onPressed: busy ? null : () => Navigator.pop(context), + child: const Text('Cancel'), + ), + FilledButton( + key: const Key('machine-sign-in'), + onPressed: busy ? null : submit, + child: Text(busy ? 'Signing in…' : 'Sign in'), + ), + ], + ); + } +} diff --git a/app/lib/core/servers/machine_access.dart b/app/lib/core/servers/machine_access.dart new file mode 100644 index 00000000..58fd9a44 --- /dev/null +++ b/app/lib/core/servers/machine_access.dart @@ -0,0 +1,41 @@ +import 'package:flutter/foundation.dart'; + +import 'server_catalog.dart'; + +/// Whether this device can use one saved machine right now. +enum MachineAccess { + /// Its connection is open, or its kept sign-in is accepted. + connected, + + /// The machine wants its own password; no other machine's sign-in applies. + needsPassword, + + /// Nothing answered, or what answered is not a Pipelines server. + unreachable, +} + +/// One access verdict with the sentence to show for it. +class MachineAccessResult { + const MachineAccessResult(this.access, {this.detail}); + + final MachineAccess access; + final String? detail; + + bool get needsPassword => access == MachineAccess.needsPassword; + bool get connected => access == MachineAccess.connected; +} + +/// Authenticates saved machines independently of one another. Settings and +/// the server editor use it to ask a new machine for its own password and to +/// show each machine's live state; the chat pool implements it. +abstract interface class MachineAuthenticator implements Listenable { + /// The live verdict for a saved machine, null while it is still connecting + /// or unknown to the pool. + MachineAccessResult? status(String id); + + /// Asks [server] whether this device may use it without a new password. + Future probe(SavedServer server); + + /// Signs in to [server] with its own password; null on success. + Future authenticate(SavedServer server, String password); +} diff --git a/app/lib/core/servers/server_probe.dart b/app/lib/core/servers/server_probe.dart index 37b655c3..c1dfa141 100644 --- a/app/lib/core/servers/server_probe.dart +++ b/app/lib/core/servers/server_probe.dart @@ -1,23 +1,41 @@ import '../session/server_session.dart'; +/// Probes one address and reports its session state with a reason. +typedef ServerProbe = Future Function(Uri endpoint); + +/// Adapts a plain state check to a [ServerProbe] without reasons. +ServerProbe probeFromCheck(Future Function(Uri) check) => + (uri) async => ServerProbeResult(await check(uri)); + /// Probe only the selected profile's explicit aliases, with a bounded wait. -/// Never send a mutation or discover/switch logical servers. -Future<({Uri endpoint, SessionState state})> probeServerAddresses( +/// Never send a mutation or discover/switch logical servers. When every +/// address is unreachable the first address and its reason are returned. +Future<({Uri endpoint, SessionState state, String? reason})> +probeServerAddresses( List addresses, { - required Future Function(Uri) check, + required ServerProbe probe, required bool Function() isCurrent, }) async { if (addresses.isEmpty) throw ArgumentError('No server addresses to probe.'); + String? reason; for (final endpoint in addresses) { if (!isCurrent()) break; - final state = await check(endpoint).timeout( - const Duration(seconds: 5), - onTimeout: () => SessionState.unreachable, + final result = await probe(endpoint).timeout( + const Duration(seconds: 12), + onTimeout: () => ServerProbeResult( + SessionState.unreachable, + reason: 'Could not reach ${endpoint.host}: no answer in time.', + ), ); if (!isCurrent()) break; - if (state != SessionState.unreachable) { - return (endpoint: endpoint, state: state); + if (result.state != SessionState.unreachable) { + return (endpoint: endpoint, state: result.state, reason: null); } + reason ??= result.reason; } - return (endpoint: addresses.first, state: SessionState.unreachable); + return ( + endpoint: addresses.first, + state: SessionState.unreachable, + reason: reason, + ); } diff --git a/app/lib/core/session/login_probe.dart b/app/lib/core/session/login_probe.dart new file mode 100644 index 00000000..79c55079 --- /dev/null +++ b/app/lib/core/session/login_probe.dart @@ -0,0 +1,17 @@ +/// What one GET of a server's web login page found. +/// +/// [status] is the HTTP status when the page answered, null when the request +/// failed; [failure] then says why in words. [loginPage] is true when a 200 +/// body is the Pipelines sign-in form rather than some other service on that +/// port. +class LoginProbe { + const LoginProbe({this.status, this.failure, this.loginPage = false}); + + final int? status; + final String? failure; + final bool loginPage; + + /// The Pipelines sign-in form's markers (web/serve.mjs loginPage). + static bool isPipelinesLogin(String body) => + body.contains('action="/login"') && body.contains('name="password"'); +} diff --git a/app/lib/core/session/server_session.dart b/app/lib/core/session/server_session.dart index eb5579e9..1a829199 100644 --- a/app/lib/core/session/server_session.dart +++ b/app/lib/core/session/server_session.dart @@ -1,9 +1,13 @@ 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. /// @@ -250,38 +254,47 @@ class ServerSession { } /// Whether [endpoint]'s server accepts the kept session. - static Future check(Uri endpoint) async { + static Future check(Uri endpoint) async => + (await probe(endpoint)).state; + + /// [check] with the reason an address could not be used. + static Future probe(Uri endpoint) async { final login = loginUriFor(endpoint); - if (login == null) return SessionState.unreachable; + 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}; - 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; + 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 probeProfile({ + required String id, + required Iterable 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); } -/// 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', - ); -} diff --git a/app/lib/core/session/server_session_io.dart b/app/lib/core/session/server_session_io.dart index 383057c6..6f68cd75 100644 --- a/app/lib/core/session/server_session_io.dart +++ b/app/lib/core/session/server_session_io.dart @@ -1,5 +1,8 @@ +import 'dart:async'; import 'dart:io'; +import 'login_probe.dart'; + /// Posts the password to the web login and returns its session cookie. Future<({String? cookie, String? error})> postLogin( Uri login, @@ -29,11 +32,13 @@ Future<({String? cookie, String? error})> postLogin( error: switch (response.statusCode) { 401 => 'Wrong password.', 429 => 'Too many attempts. Wait 30 seconds.', - _ => 'Sign-in failed (HTTP ${response.statusCode}).', + _ => + 'Sign-in failed (HTTP ${response.statusCode}). ' + '${login.host}:${login.port} may not be the Pipelines web port.', }, ); } on IOException catch (error) { - return (cookie: null, error: 'Could not reach the server: $error'); + return (cookie: null, error: describeFailure(login, error)); } on FormatException catch (error) { return (cookie: null, error: error.message); } finally { @@ -41,21 +46,75 @@ Future<({String? cookie, String? error})> postLogin( } } -/// The status the web login answers with this session: a redirect away from -/// the login page when signed in, the page itself when not; null when the -/// server cannot be reached. -Future probeLogin(Uri login, Map headers) async { +/// Fetches the web login with this session: a redirect away from the login +/// page when signed in, the page itself when not. A failure to connect, a TLS +/// problem or a non-Pipelines answer is described in words. +Future probeLogin(Uri login, Map headers) async { final client = HttpClient()..connectionTimeout = const Duration(seconds: 8); try { final request = await client.getUrl(login); request.followRedirects = false; headers.forEach(request.headers.set); final response = await request.close().timeout(const Duration(seconds: 10)); - await response.drain(); - return response.statusCode; - } on Exception { - return null; + if (response.statusCode != 200) { + await response.drain(); + return LoginProbe(status: response.statusCode); + } + final body = await _head(response, 65536); + return LoginProbe(status: 200, loginPage: LoginProbe.isPipelinesLogin(body)); + } on Exception catch (error) { + return LoginProbe(failure: describeFailure(login, error)); } finally { client.close(force: true); } } + +Future _head(HttpClientResponse response, int limit) async { + final buffer = StringBuffer(); + await for (final chunk in response.transform(const SystemEncoding().decoder)) { + buffer.write(chunk); + if (buffer.length > limit) break; + } + return buffer.toString(); +} + +/// Turns a transport failure against [login] into the sentence the connect +/// screen shows. A TLS failure against an IP address gets the Tailscale +/// explanation: its certificates only cover the machine's tailnet name. +String describeFailure(Uri login, Object error) { + final where = '${login.host}:${login.port}'; + final isIp = + Uri.tryParse('ws://${login.host}')?.host == login.host && + (InternetAddress.tryParse(login.host) != null); + if (error is HandshakeException || + error is CertificateException || + error is TlsException) { + if (isIp) { + return 'The HTTPS certificate of $where does not cover an IP address. ' + 'Tailscale certificates are issued for the machine\'s tailnet name, ' + 'so use wss://.ts.net:${login.port}/connect, or ws:// with ' + 'this IP and the plain web port.'; + } + return 'The HTTPS connection to $where failed: ${_detail(error)}. ' + 'Check that this port serves HTTPS, or use ws:// for a plain port.'; + } + if (error is TimeoutException) { + return 'Could not reach $where: no answer within 10 seconds.'; + } + if (error is SocketException) { + final detail = error.osError?.message.trim(); + return 'Could not reach $where' + '${detail == null || detail.isEmpty ? '' : ': $detail'}.'; + } + return 'Could not reach $where: ${_detail(error)}.'; +} + +String _detail(Object error) { + if (error is TlsException) { + final os = error.osError?.message.trim(); + if (os != null && os.isNotEmpty) return os; + return error.message.isEmpty ? 'TLS handshake failed' : error.message; + } + final text = error.toString().trim(); + return text.isEmpty ? error.runtimeType.toString() : text; +} diff --git a/app/lib/core/session/server_session_stub.dart b/app/lib/core/session/server_session_stub.dart index 10f3b06e..7bb1fa0b 100644 --- a/app/lib/core/session/server_session_stub.dart +++ b/app/lib/core/session/server_session_stub.dart @@ -1,3 +1,5 @@ +import 'login_probe.dart'; + /// The browser keeps its own login cookie, so there is nothing to post here. Future<({String? cookie, String? error})> postLogin( Uri login, @@ -5,4 +7,5 @@ Future<({String? cookie, String? error})> postLogin( ) async => (cookie: null, error: 'Sign in through the browser page.'); /// A browser page is already behind its own login. -Future probeLogin(Uri login, Map headers) async => 302; +Future probeLogin(Uri login, Map headers) async => + const LoginProbe(status: 302); diff --git a/app/lib/core/session/session_probe.dart b/app/lib/core/session/session_probe.dart new file mode 100644 index 00000000..426f72fa --- /dev/null +++ b/app/lib/core/session/session_probe.dart @@ -0,0 +1,58 @@ +import 'login_probe.dart'; + +/// What a server says about this device's session. +enum SessionState { signedIn, signedOut, unreachable } + +/// What a probe of one server address found; [reason] explains an +/// unreachable address in words the operator can act on. +class ServerProbeResult { + const ServerProbeResult(this.state, {this.reason}); + + final SessionState state; + final String? reason; +} + +/// 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', + ); +} + +/// The web login sends a signed-in visitor on and shows its form otherwise; +/// anything else on that port is not a Pipelines server. +ServerProbeResult interpretLoginProbe(Uri login, LoginProbe probe) { + final where = '${login.host}:${login.port}'; + final status = probe.status; + if (status == null) { + return ServerProbeResult( + SessionState.unreachable, + reason: probe.failure ?? 'Could not reach $where.', + ); + } + if (status >= 300 && status < 400) { + return const ServerProbeResult(SessionState.signedIn); + } + if (status == 200 && probe.loginPage) { + return const ServerProbeResult(SessionState.signedOut); + } + return ServerProbeResult( + SessionState.unreachable, + reason: status == 200 + ? '$where answered, but not with the Pipelines sign-in page. ' + 'Check the port: use the one in the web app\'s address bar.' + : '$where answered HTTP $status instead of the Pipelines sign-in ' + 'page. Check the address and port.', + ); +} diff --git a/app/lib/features/onboarding/discovery/browser_server_discovery.dart b/app/lib/features/onboarding/discovery/browser_server_discovery.dart index 48bf6ab4..541f7286 100644 --- a/app/lib/features/onboarding/discovery/browser_server_discovery.dart +++ b/app/lib/features/onboarding/discovery/browser_server_discovery.dart @@ -49,6 +49,7 @@ class BrowserServerDiscovery implements ServerDiscovery { path: uri.path, passwordRequired: item['auth'] != 'none', version: item['version'] is String ? item['version'] as String : null, + addresses: _routes(uri, item['addresses']), ); } on FormatException { // One malformed announcement must not hide other machines. @@ -56,4 +57,28 @@ class BrowserServerDiscovery implements ServerDiscovery { } yield servers.values.toList(); } + + /// Every advertised route, the LAN [primary] first; older servers send none. + static List _routes(Uri primary, Object? raw) { + final routes = [ + DiscoveredAddress(route: DiscoveredRoute.lan, endpoint: primary), + ]; + if (raw is! List) return routes; + for (final item in raw.take(8)) { + if (item is! Map || item['endpoint'] is! String) continue; + final route = DiscoveredAddress.routeNamed(item['kind'] as String?); + if (route == null) continue; + try { + final uri = Uri.parse( + ServerUrl.validate(item['endpoint'] as String).wsUrl, + ); + if (uri.hasQuery || uri.hasFragment) continue; + final address = DiscoveredAddress(route: route, endpoint: uri); + if (!routes.contains(address) && uri != primary) routes.add(address); + } on FormatException { + // Skip one malformed route; the machine is still reachable by others. + } + } + return routes; + } } diff --git a/app/lib/features/onboarding/discovery/discovered_server.dart b/app/lib/features/onboarding/discovery/discovered_server.dart index 63b244c1..0e46ecf3 100644 --- a/app/lib/features/onboarding/discovery/discovered_server.dart +++ b/app/lib/features/onboarding/discovery/discovered_server.dart @@ -1,7 +1,57 @@ /// The DNS-SD service type the server advertises (internal/discovery). const pipelinesServiceType = '_pipelines._tcp'; +/// How one route reaches a discovered machine. +enum DiscoveredRoute { + /// An address on the network the browsing host shares with the machine. + lan, + + /// The machine's tailnet IP; the same port, encrypted by Tailscale. + tailscale, + + /// An HTTPS origin fronting the same server, usually its tailnet DNS name. + public, +} + +/// One way to dial a discovered machine. +class DiscoveredAddress { + const DiscoveredAddress({required this.route, required this.endpoint}); + + final DiscoveredRoute route; + final Uri endpoint; + + /// What the choice list calls this route. + String get label => switch (route) { + DiscoveredRoute.lan => 'Local network', + DiscoveredRoute.tailscale => 'Tailscale IP', + DiscoveredRoute.public => + endpoint.scheme == 'wss' ? 'Tailscale name (HTTPS)' : 'Public name', + }; + + static DiscoveredRoute? routeNamed(String? kind) => switch (kind) { + 'lan' => DiscoveredRoute.lan, + 'tailscale' => DiscoveredRoute.tailscale, + 'public' => DiscoveredRoute.public, + _ => null, + }; + + @override + bool operator ==(Object other) => + other is DiscoveredAddress && + other.route == route && + other.endpoint == endpoint; + + @override + int get hashCode => Object.hash(route, endpoint); + + @override + String toString() => '$label: $endpoint'; +} + /// A Pipelines server found on the local network. +/// +/// [endpoint] is the first route; [addresses] lists every advertised route to +/// this same machine so the operator can choose which ones to save. class DiscoveredServer { const DiscoveredServer({ required this.name, @@ -11,7 +61,8 @@ class DiscoveredServer { this.path = '/connect', this.passwordRequired = true, this.version, - }); + List? addresses, + }) : _routes = addresses; /// Builds a server from a resolved DNS-SD record: the service [instance] /// name, the resolved [addresses] (and SRV [hostname] when no address is @@ -28,14 +79,49 @@ class DiscoveredServer { if (host == null || port <= 0 || port > 65535) return null; final path = attributes['path'] ?? ''; final name = attributes['name'] ?? ''; + final secure = attributes['tls'] == '1'; + final cleanPath = path.startsWith('/') ? path : '/connect'; + final routes = [ + DiscoveredAddress( + route: DiscoveredRoute.lan, + endpoint: Uri( + scheme: secure ? 'wss' : 'ws', + host: host, + port: port, + path: cleanPath, + ), + ), + ]; + for (final value in (attributes['ts'] ?? '').split(',')) { + final ip = value.trim(); + if (!isTailscaleIPv4(ip) || routes.length > 5) continue; + routes.add( + DiscoveredAddress( + route: DiscoveredRoute.tailscale, + endpoint: Uri( + scheme: secure ? 'wss' : 'ws', + host: ip, + port: port, + path: cleanPath, + ), + ), + ); + } + final public = publicEndpoint(attributes['public'], path: cleanPath); + if (public != null) { + routes.add( + DiscoveredAddress(route: DiscoveredRoute.public, endpoint: public), + ); + } return DiscoveredServer( name: name.isEmpty ? instance : name, host: host, port: port, - secure: attributes['tls'] == '1', - path: path.startsWith('/') ? path : '/connect', + secure: secure, + path: cleanPath, passwordRequired: attributes['auth'] != 'none', version: attributes['v'], + addresses: routes, ); } @@ -46,14 +132,39 @@ class DiscoveredServer { final String path; final bool passwordRequired; final String? version; + final List? _routes; /// The websocket endpoint the connect screen dials. Uri get endpoint => Uri(scheme: secure ? 'wss' : 'ws', host: host, port: port, path: path); + /// Every advertised route to this machine, the primary first. + List get addresses => + _routes ?? + [DiscoveredAddress(route: DiscoveredRoute.lan, endpoint: endpoint)]; + + /// The routes' endpoints, in order. + List get endpoints => [for (final a in addresses) a.endpoint]; + /// "host:port" as shown under the name. String get address => endpoint.authority; + /// The same machine with only the [chosen] routes, the first one primary. + DiscoveredServer choosing(List chosen) { + if (chosen.isEmpty) return this; + final first = chosen.first.endpoint; + return DiscoveredServer( + name: name, + host: first.host, + port: first.hasPort ? first.port : (first.scheme == 'wss' ? 443 : 80), + secure: first.scheme == 'wss', + path: first.path, + passwordRequired: passwordRequired, + version: version, + addresses: List.unmodifiable(chosen), + ); + } + /// Picks the address a phone can dial: IPv4 first, then a routable IPv6 /// address. Link-local IPv6 needs a zone the URL cannot carry. static String? preferredHost(List addresses) { @@ -73,6 +184,35 @@ class DiscoveredServer { return null; } + /// Tailscale assigns IPv4 addresses from 100.64.0.0/10. + static bool isTailscaleIPv4(String value) { + final bytes = _ipv4(value); + return bytes != null && bytes[0] == 100 && (bytes[1] & 0xc0) == 0x40; + } + + /// The ws(s) endpoint for an advertised HTTP(S) origin, or null when the + /// value is not a bare origin. + static Uri? publicEndpoint(String? raw, {String path = '/connect'}) { + final value = raw?.trim() ?? ''; + if (value.isEmpty || value.length > 200) return null; + final uri = Uri.tryParse(value); + if (uri == null || + (uri.scheme != 'https' && uri.scheme != 'http') || + uri.host.isEmpty || + uri.userInfo.isNotEmpty || + (uri.path.isNotEmpty && uri.path != '/') || + uri.hasQuery || + uri.hasFragment) { + return null; + } + return Uri( + scheme: uri.scheme == 'https' ? 'wss' : 'ws', + host: uri.host, + port: uri.hasPort ? uri.port : null, + path: path, + ); + } + static List? _ipv4(String value) { if (!RegExp(r'^\d{1,3}(\.\d{1,3}){3}$').hasMatch(value)) return null; try { @@ -102,8 +242,18 @@ class DiscoveredServer { other.name == name && other.endpoint == endpoint && other.passwordRequired == passwordRequired && - other.version == version; + other.version == version && + _sameRoutes(other.addresses); + + bool _sameRoutes(List other) { + if (other.length != addresses.length) return false; + for (var i = 0; i < other.length; i++) { + if (other[i] != addresses[i]) return false; + } + return true; + } @override - int get hashCode => Object.hash(name, endpoint, passwordRequired, version); + int get hashCode => + Object.hash(name, endpoint, passwordRequired, version, addresses.length); } diff --git a/app/lib/features/onboarding/discovery/discovered_server_row.dart b/app/lib/features/onboarding/discovery/discovered_server_row.dart new file mode 100644 index 00000000..6aed4751 --- /dev/null +++ b/app/lib/features/onboarding/discovery/discovered_server_row.dart @@ -0,0 +1,162 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/adaptive/host.dart'; +import 'discovered_server.dart'; + +/// One discovered machine. A machine with one route is used by tapping it. A +/// machine with several routes (LAN, Tailscale IP, Tailscale name) expands to +/// a checklist so the operator chooses which of them to save; the first +/// checked route is dialled first and the rest are backups to the same machine. +class DiscoveredServerRow extends StatefulWidget { + const DiscoveredServerRow({ + super.key, + required this.server, + required this.onSelect, + this.enabled = true, + }); + + final DiscoveredServer server; + final ValueChanged onSelect; + final bool enabled; + + @override + State createState() => _DiscoveredServerRowState(); +} + +class _DiscoveredServerRowState extends State { + bool _expanded = false; + late final Set _chosen = {widget.server.addresses.first}; + + bool get _multiple => widget.server.addresses.length > 1; + + void _tap() { + if (!_multiple) { + widget.onSelect(widget.server); + return; + } + setState(() => _expanded = !_expanded); + } + + void _use() { + final ordered = [ + for (final address in widget.server.addresses) + if (_chosen.contains(address)) address, + ]; + widget.onSelect(widget.server.choosing(ordered)); + } + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + final server = widget.server; + final detail = _multiple + ? '${server.addresses.length} addresses' + : server.address; + final subtitle = Text( + server.passwordRequired ? '$detail · password' : detail, + ); + final onTap = widget.enabled ? _tap : null; + final Widget head = cupertino + ? CupertinoListTile( + key: Key('discovered-${server.address}'), + leading: const Icon(CupertinoIcons.desktopcomputer), + title: Text(server.name), + subtitle: subtitle, + trailing: _multiple + ? Icon( + _expanded + ? CupertinoIcons.chevron_up + : CupertinoIcons.chevron_down, + ) + : const CupertinoListTileChevron(), + onTap: onTap, + ) + : ListTile( + key: Key('discovered-${server.address}'), + leading: const Icon(Icons.dns_outlined), + title: Text(server.name), + subtitle: subtitle, + trailing: Icon( + _multiple + ? (_expanded ? Icons.expand_less : Icons.expand_more) + : Icons.chevron_right, + ), + enabled: widget.enabled, + onTap: onTap, + ); + if (!_multiple || !_expanded) return head; + final useLabel = 'Use ${server.name}'; + final use = cupertino + ? CupertinoButton.filled( + key: Key('discovered-use-${server.address}'), + onPressed: widget.enabled && _chosen.isNotEmpty ? _use : null, + child: Text(useLabel), + ) + : FilledButton( + key: Key('discovered-use-${server.address}'), + onPressed: widget.enabled && _chosen.isNotEmpty ? _use : null, + child: Text(useLabel), + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + head, + Padding( + padding: const EdgeInsetsDirectional.only(start: 16, end: 16), + child: Text( + 'Choose how to reach ${server.name}. Checked addresses are saved ' + 'as routes to this one machine; the first is tried first.', + ), + ), + for (final address in server.addresses) + _choice(context, cupertino, address), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), + child: Align( + alignment: AlignmentDirectional.centerStart, + child: use, + ), + ), + ], + ); + } + + Widget _choice( + BuildContext context, + bool cupertino, + DiscoveredAddress address, + ) { + final checked = _chosen.contains(address); + void toggle(bool? value) => setState(() { + if (value ?? false) { + _chosen.add(address); + } else { + _chosen.remove(address); + } + }); + final key = Key('discovered-route-${address.endpoint}'); + final title = Text(address.label); + final subtitle = Text(address.endpoint.toString()); + if (cupertino) { + return CupertinoListTile( + key: key, + title: title, + subtitle: subtitle, + trailing: CupertinoCheckbox( + value: checked, + onChanged: widget.enabled ? toggle : null, + ), + onTap: widget.enabled ? () => toggle(!checked) : null, + ); + } + return CheckboxListTile( + key: key, + value: checked, + onChanged: widget.enabled ? toggle : null, + title: title, + subtitle: subtitle, + controlAffinity: ListTileControlAffinity.leading, + ); + } +} diff --git a/app/lib/features/onboarding/discovery/discovery_panel.dart b/app/lib/features/onboarding/discovery/discovery_panel.dart index 67597227..04f673cd 100644 --- a/app/lib/features/onboarding/discovery/discovery_panel.dart +++ b/app/lib/features/onboarding/discovery/discovery_panel.dart @@ -4,8 +4,9 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../../../ui/adaptive/host.dart'; -import 'discovered_server.dart'; import 'browser_server_discovery.dart'; +import 'discovered_server.dart'; +import 'discovered_server_row.dart'; import 'server_discovery.dart'; enum _Phase { idle, scanning, done, failed } @@ -136,7 +137,13 @@ class _DiscoveryPanelState extends State { if (widget.discovery is BrowserServerDiscovery) const Text('Searches this server’s local network.'), ?status, - for (final server in _servers) _row(context, cupertino, server), + for (final server in _servers) + DiscoveredServerRow( + key: ValueKey('discovered-row-${server.address}'), + server: server, + enabled: widget.enabled, + onSelect: widget.onSelect, + ), ], ); } @@ -175,32 +182,4 @@ class _DiscoveryPanelState extends State { ), ); } - - Widget _row(BuildContext context, bool cupertino, DiscoveredServer server) { - final key = Key('discovered-${server.address}'); - final subtitle = Text( - server.passwordRequired ? '${server.address} · password' : server.address, - ); - void tap() => widget.onSelect(server); - final onTap = widget.enabled ? tap : null; - if (cupertino) { - return CupertinoListTile( - key: key, - leading: const Icon(CupertinoIcons.desktopcomputer), - title: Text(server.name), - subtitle: subtitle, - trailing: const CupertinoListTileChevron(), - onTap: onTap, - ); - } - return ListTile( - key: key, - leading: const Icon(Icons.dns_outlined), - title: Text(server.name), - subtitle: subtitle, - trailing: const Icon(Icons.chevron_right), - enabled: widget.enabled, - onTap: onTap, - ); - } } diff --git a/app/lib/features/onboarding/onboarding_flow.dart b/app/lib/features/onboarding/onboarding_flow.dart index 228084d4..22a00b7d 100644 --- a/app/lib/features/onboarding/onboarding_flow.dart +++ b/app/lib/features/onboarding/onboarding_flow.dart @@ -23,10 +23,12 @@ class OnboardingFlow extends StatefulWidget { required this.onDone, this.initialServer = '', this.startAtPassword = false, - this.check = ServerSession.check, + this.check, + this.probe, this.signIn = ServerSession.signIn, this.saveServer, this.saveServerProfile, + this.saveMachine, this.savedServers, this.serverAddresses = const [], this.discovery, @@ -40,10 +42,18 @@ class OnboardingFlow extends StatefulWidget { /// The saved session was refused: only the password is asked again. final bool startAtPassword; - final ServerCheck check; + + /// Reaches an address; [probe] also says why one could not be used. With + /// neither, the device's own session probe is used. + final ServerCheck? check; + final ServerProbe? probe; final ServerSignIn signIn; final Future Function(String url)? saveServer; final Future Function(String url, String name)? saveServerProfile; + + /// Saves every chosen route to one machine, the reached one first. Takes + /// precedence over [saveServerProfile] when set. + final Future Function(List endpoints, String name)? saveMachine; final Widget? savedServers; final List serverAddresses; @@ -65,6 +75,15 @@ class _OnboardingFlowState extends State { bool _busy = false; String? _error; + /// The routes a discovered machine was chosen with; empty when typed. + List _discoveredRoutes = const []; + + ServerProbe get _probe => + widget.probe ?? + (widget.check == null + ? ServerSession.probe + : probeFromCheck(widget.check!)); + @override void initState() { super.initState(); @@ -103,14 +122,19 @@ class _OnboardingFlowState extends State { _busy = true; _error = null; }); + // Typing another address drops the discovered machine's other routes. + final routes = _discoveredRoutes.contains(endpoint) + ? _discoveredRoutes + : const []; final candidates = [ endpoint, + ...routes.where((candidate) => candidate != endpoint), if (widget.serverAddresses.contains(endpoint)) ...widget.serverAddresses.where((candidate) => candidate != endpoint), ]; final result = await probeServerAddresses( candidates, - check: widget.check, + probe: _probe, isCurrent: () => mounted, ); endpoint = result.endpoint; @@ -119,16 +143,22 @@ class _OnboardingFlowState extends State { if (state == SessionState.unreachable) { setState(() { _busy = false; - _error = 'Could not reach that server. Check the address and network.'; + _error = + result.reason ?? + 'Could not reach that server. Check the address and network.'; }); return; } + final name = _name.text.trim().isEmpty ? endpoint.host : _name.text.trim(); try { - if (widget.saveServerProfile != null) { - await widget.saveServerProfile!( + if (widget.saveMachine != null) { + await widget.saveMachine!([ endpoint.toString(), - _name.text.trim().isEmpty ? endpoint.host : _name.text.trim(), - ); + for (final route in routes) + if (route != endpoint) route.toString(), + ], name); + } else if (widget.saveServerProfile != null) { + await widget.saveServerProfile!(endpoint.toString(), name); } else { await widget.saveServer?.call(endpoint.toString()); } @@ -156,6 +186,7 @@ class _OnboardingFlowState extends State { void _useDiscovered(DiscoveredServer server) { setState(() { _server.text = server.endpoint.toString(); + _discoveredRoutes = server.endpoints; _name.text = server.name; _error = null; }); @@ -264,6 +295,14 @@ class _OnboardingFlowState extends State { hint: 'Machine name', onSubmitted: _continue, ), + if (_discoveredRoutes.length > 1) ...[ + const SizedBox(height: 8), + Text( + 'Also saved as backup routes to this machine: ' + '${_discoveredRoutes.where((r) => r.toString() != _server.text).join(', ')}', + key: const Key('onboarding-routes'), + ), + ], ], if (_error != null) ...[ const SizedBox(height: 8), diff --git a/app/lib/features/settings/saved_server_editor.dart b/app/lib/features/settings/saved_server_editor.dart index c2728eab..e116cbe6 100644 --- a/app/lib/features/settings/saved_server_editor.dart +++ b/app/lib/features/settings/saved_server_editor.dart @@ -1,24 +1,30 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; -import '../../ui/adaptive/segmented_bar.dart'; +import '../../core/servers/machine_access.dart'; import '../../core/servers/server_catalog.dart'; import '../../ui/adaptive/host.dart'; +import '../../ui/adaptive/segmented_bar.dart'; import '../onboarding/discovery/discovered_server.dart'; import '../onboarding/discovery/discovery_panel.dart'; import '../onboarding/discovery/server_discovery.dart'; +import 'saved_server_sign_in_step.dart'; /// When supplied, [onSave] must finish successfully before the route closes. -/// Throwing keeps the draft open and displays the error for a retry. +/// Throwing keeps the draft open and displays the error for a retry. With an +/// [authenticator], a new machine (or one whose addresses changed) is then +/// asked for its own password before the route closes. Future editSavedServer( BuildContext context, { SavedServer? server, ServerDiscovery? discovery, Future Function(SavedServer)? onSave, + MachineAuthenticator? authenticator, }) { final page = _ServerEditor( server: server, onSave: onSave, + authenticator: authenticator, discovery: discovery ?? platformServerDiscovery(), ); return Navigator.of(context).push( @@ -29,10 +35,16 @@ Future editSavedServer( } class _ServerEditor extends StatefulWidget { - const _ServerEditor({this.server, this.onSave, this.discovery}); + const _ServerEditor({ + this.server, + this.onSave, + this.discovery, + this.authenticator, + }); final ServerDiscovery? discovery; final SavedServer? server; final Future Function(SavedServer)? onSave; + final MachineAuthenticator? authenticator; @override State<_ServerEditor> createState() => _ServerEditorState(); @@ -50,10 +62,13 @@ class _ServerEditorState extends State<_ServerEditor> { String? _error; bool _saving = false; + /// Set once the profile is persisted and the machine must now be asked. + SavedServer? _saved; + void _useDiscovered(DiscoveredServer server) { setState(() { _name.text = server.name; - _addresses.text = server.endpoint.toString(); + _addresses.text = server.endpoints.join('\n'); _error = null; }); } @@ -75,7 +90,15 @@ class _ServerEditorState extends State<_ServerEditor> { }); await widget.onSave?.call(server); if (!mounted) return; - Navigator.of(context).pop(server); + final authenticator = widget.authenticator; + final changed = + widget.server == null || + !_sameEndpoints(widget.server!.endpoints, server.endpoints); + if (authenticator == null || !changed) { + Navigator.of(context).pop(server); + return; + } + setState(() => _saved = server); } catch (error) { if (mounted) { setState(() { @@ -86,6 +109,9 @@ class _ServerEditorState extends State<_ServerEditor> { } } + static bool _sameEndpoints(List a, List b) => + a.length == b.length && a.indexed.every((e) => b[e.$1] == e.$2); + @override void dispose() { _name.dispose(); @@ -149,6 +175,22 @@ class _ServerEditorState extends State<_ServerEditor> { onPressed: _saving ? null : _save, child: Text(saveLabel), ); + final saved = _saved; + if (saved != null && widget.authenticator != null) { + final step = SafeArea( + child: ListView( + padding: const EdgeInsets.all(16), + children: [ + SavedServerSignInStep( + server: saved, + authenticator: widget.authenticator!, + onDone: () => Navigator.of(context).pop(saved), + ), + ], + ), + ); + return _scaffold(cupertino, 'Sign in to ${saved.name}', step); + } final body = SafeArea( child: ListView( padding: const EdgeInsets.all(16), @@ -165,19 +207,22 @@ class _ServerEditorState extends State<_ServerEditor> { const SizedBox(height: 16), _field( _addresses, - 'Addresses, in preferred order', + 'Addresses of this machine', key: 'server-profile-addresses', multiline: true, ), const SizedBox(height: 8), const Text( - 'One ws:// or wss:// address per line. The first is preferred; ' - 'the others are backups for this same server, such as its Tailscale and LAN addresses.', + 'One ws:// or wss:// address per line, all for this one machine: ' + 'for example its LAN address, its Tailscale IP and its Tailscale ' + 'name. The first is tried first; the others are backups. A ' + 'different machine is a separate entry with its own password.', ), const SizedBox(height: 8), const Text( - 'Only group addresses you trust as the same server. They share its saved sign-in. ' - 'ws:// is unencrypted; use it only on a trusted LAN/VPN.', + 'Tailscale HTTPS (wss://) works with the machine\'s tailnet name ' + 'and the web port, not with its IP. ws:// is unencrypted; use it ' + 'only on a trusted LAN or VPN.', ), if (_error != null) Padding( @@ -199,18 +244,17 @@ class _ServerEditorState extends State<_ServerEditor> { ], ), ); - return PopScope( - canPop: !_saving, - child: cupertino - ? CupertinoPageScaffold( - navigationBar: SegmentedBar(cupertino: true, title: title), - child: body, - ) - : Scaffold( - extendBodyBehindAppBar: true, - appBar: SegmentedBar(cupertino: false, title: title), - body: body, - ), - ); + return PopScope(canPop: !_saving, child: _scaffold(cupertino, title, body)); } + + Widget _scaffold(bool cupertino, String title, Widget body) => cupertino + ? CupertinoPageScaffold( + navigationBar: SegmentedBar(cupertino: true, title: title), + child: body, + ) + : Scaffold( + extendBodyBehindAppBar: true, + appBar: SegmentedBar(cupertino: false, title: title), + body: body, + ); } diff --git a/app/lib/features/settings/saved_server_row.dart b/app/lib/features/settings/saved_server_row.dart index b86722b4..e224f2b1 100644 --- a/app/lib/features/settings/saved_server_row.dart +++ b/app/lib/features/settings/saved_server_row.dart @@ -1,21 +1,22 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; +import '../../core/servers/machine_access.dart'; import '../../core/servers/server_catalog.dart'; import 'settings_row.dart'; import 'settings_theme.dart'; /// What a saved server's menu can do. -enum SavedServerAction { use, edit, remove } +enum SavedServerAction { use, edit, remove, signIn } /// The key of a saved server's actions menu button. ValueKey savedServerMenuKey(String id) => ValueKey('settings.server.$id.menu'); -/// One saved server: a selection mark, the name, "Selected server" on the -/// active one and each address (preferred, then backups) as subtitle lines. -/// Tapping another server uses it; the trailing menu offers Use, Edit and -/// Remove. +/// One saved machine: a selection mark, the name, its live state (connected, +/// sign-in required, unreachable), "Pipelines and runs server" on the primary +/// and each address as a subtitle line. The trailing menu offers Sign in when +/// the machine wants its own password, plus Use, Edit and Remove. class SavedServerRow extends StatelessWidget { const SavedServerRow({ super.key, @@ -23,6 +24,7 @@ class SavedServerRow extends StatelessWidget { required this.selected, required this.busy, required this.onAction, + this.status, this.allowSelection = true, this.primaryContext = false, }); @@ -31,6 +33,7 @@ class SavedServerRow extends StatelessWidget { final SavedServer server; final bool selected; final bool busy; + final MachineAccessResult? status; final ValueChanged onAction; String _label(SavedServerAction action) => switch (action) { @@ -40,14 +43,27 @@ class SavedServerRow extends StatelessWidget { : 'Use ${server.name}', SavedServerAction.edit => 'Edit ${server.name}', SavedServerAction.remove => 'Remove ${server.name}', + SavedServerAction.signIn => 'Sign in to ${server.name}', }; List get _actions => [ + if (status?.needsPassword ?? false) SavedServerAction.signIn, if (allowSelection && !selected) SavedServerAction.use, SavedServerAction.edit, SavedServerAction.remove, ]; + /// The state line: a tap on it signs in when that is what is missing. + String? get _stateText => switch (status?.access) { + null => null, + MachineAccess.connected => 'Connected', + MachineAccess.needsPassword => 'Sign in required', + MachineAccess.unreachable => + status?.detail == null || status!.detail!.isEmpty + ? 'Unreachable' + : 'Unreachable: ${status!.detail}', + }; + Future _cupertinoMenu(BuildContext context) async { final action = await showCupertinoModalPopup( context: context, @@ -111,22 +127,36 @@ class SavedServerRow extends StatelessWidget { ? CupertinoColors.tertiaryLabel.resolveFrom(context) : null, ); + final needsPassword = status?.needsPassword ?? false; + final state = _stateText; return SettingsRow( leading: mark, title: Text(server.name), subtitle: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ + if (state != null) + Text( + state, + key: Key('settings.server.${server.id}.state'), + style: status?.access == MachineAccess.unreachable + ? TextStyle(color: settingsErrorColor(context)) + : null, + ), if (selected) Text( primaryContext ? 'Pipelines and runs server' : 'Selected server', ), for (final (index, address) in server.endpoints.indexed) - Text('${index == 0 ? 'Preferred' : 'Backup $index'}: $address'), + Text('${index == 0 ? 'Address' : 'Backup address'}: $address'), ], ), trailing: menu, - onTap: !allowSelection || selected || busy + onTap: busy + ? null + : needsPassword + ? () => onAction(SavedServerAction.signIn) + : !allowSelection || selected ? null : () => onAction(SavedServerAction.use), ); diff --git a/app/lib/features/settings/saved_server_sign_in_step.dart b/app/lib/features/settings/saved_server_sign_in_step.dart new file mode 100644 index 00000000..48589daf --- /dev/null +++ b/app/lib/features/settings/saved_server_sign_in_step.dart @@ -0,0 +1,211 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../core/servers/machine_access.dart'; +import '../../core/servers/server_catalog.dart'; +import '../../ui/adaptive/host.dart'; + +/// What the editor does once a machine is saved: ask it whether this device +/// may use it, then either sign in with its own password or explain why it +/// could not be reached. The machine stays saved whatever happens here. +class SavedServerSignInStep extends StatefulWidget { + const SavedServerSignInStep({ + super.key, + required this.server, + required this.authenticator, + required this.onDone, + }); + + final SavedServer server; + final MachineAuthenticator authenticator; + final VoidCallback onDone; + + @override + State createState() => _SavedServerSignInStepState(); +} + +class _SavedServerSignInStepState extends State { + final _password = TextEditingController(); + MachineAccessResult? _result; + bool _busy = true; + String? _error; + + @override + void initState() { + super.initState(); + _probe(); + } + + @override + void dispose() { + _password.dispose(); + super.dispose(); + } + + Future _probe() async { + setState(() { + _busy = true; + _error = null; + }); + MachineAccessResult result; + try { + result = await widget.authenticator.probe(widget.server); + } catch (error) { + result = MachineAccessResult(MachineAccess.unreachable, detail: '$error'); + } + if (!mounted) return; + if (result.connected) { + widget.onDone(); + return; + } + setState(() { + _result = result; + _busy = false; + }); + } + + Future _signIn() async { + if (_password.text.isEmpty) return; + setState(() { + _busy = true; + _error = null; + }); + String? problem; + try { + problem = await widget.authenticator.authenticate( + widget.server, + _password.text, + ); + } catch (error) { + problem = 'Could not sign in: $error'; + } + if (!mounted) return; + if (problem == null) { + widget.onDone(); + return; + } + setState(() { + _busy = false; + _error = problem; + }); + } + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + final name = widget.server.name; + final errorColor = cupertino + ? CupertinoColors.systemRed.resolveFrom(context) + : Theme.of(context).colorScheme.error; + final result = _result; + if (result == null) { + return Row( + children: [ + cupertino + ? const CupertinoActivityIndicator() + : const SizedBox.square( + dimension: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ), + const SizedBox(width: 12), + Expanded(child: Text('Saved. Checking whether $name needs a sign-in…')), + ], + ); + } + final later = cupertino + ? CupertinoButton( + key: const Key('server-sign-in-later'), + onPressed: _busy ? null : widget.onDone, + child: const Text('Later'), + ) + : TextButton( + key: const Key('server-sign-in-later'), + onPressed: _busy ? null : widget.onDone, + child: const Text('Later'), + ); + if (result.needsPassword) { + final field = cupertino + ? CupertinoTextField( + key: const Key('server-profile-password'), + controller: _password, + obscureText: true, + autofocus: true, + enabled: !_busy, + placeholder: 'Password', + onSubmitted: (_) => _signIn(), + ) + : TextField( + key: const Key('server-profile-password'), + controller: _password, + obscureText: true, + autofocus: true, + enabled: !_busy, + decoration: const InputDecoration( + labelText: 'Password', + border: OutlineInputBorder(), + ), + onSubmitted: (_) => _signIn(), + ); + final signIn = cupertino + ? CupertinoButton.filled( + key: const Key('server-profile-sign-in'), + onPressed: _busy ? null : _signIn, + child: Text(_busy ? 'Signing in…' : 'Sign in'), + ) + : FilledButton( + key: const Key('server-profile-sign-in'), + onPressed: _busy ? null : _signIn, + child: Text(_busy ? 'Signing in…' : 'Sign in'), + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + '$name is saved and asks for its own password: the one chosen ' + 'when Pipelines was installed there. Other machines\' sign-ins ' + 'are never reused.', + ), + const SizedBox(height: 12), + field, + if (_error != null) ...[ + const SizedBox(height: 8), + Text( + _error!, + key: const Key('server-profile-error'), + style: TextStyle(color: errorColor), + ), + ], + const SizedBox(height: 16), + Row(children: [signIn, const SizedBox(width: 8), later]), + ], + ); + } + final retry = cupertino + ? CupertinoButton.filled( + key: const Key('server-profile-retry'), + onPressed: _busy ? null : _probe, + child: const Text('Try again'), + ) + : FilledButton( + key: const Key('server-profile-retry'), + onPressed: _busy ? null : _probe, + child: const Text('Try again'), + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text('$name is saved, but could not be reached.'), + if (result.detail != null && result.detail!.isNotEmpty) ...[ + const SizedBox(height: 8), + Text( + result.detail!, + key: const Key('server-profile-error'), + style: TextStyle(color: errorColor), + ), + ], + const SizedBox(height: 16), + Row(children: [retry, const SizedBox(width: 8), later]), + ], + ); + } +} diff --git a/app/lib/features/settings/saved_servers_section.dart b/app/lib/features/settings/saved_servers_section.dart index bd265fbb..a6d96b6b 100644 --- a/app/lib/features/settings/saved_servers_section.dart +++ b/app/lib/features/settings/saved_servers_section.dart @@ -4,6 +4,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import '../../core/servers/chat/machine_sign_in_dialog.dart'; import '../../core/servers/server_catalog.dart'; import '../../ui/adaptive/host.dart'; import 'saved_server_editor.dart'; @@ -34,6 +35,7 @@ class SavedServersSection extends StatelessWidget { await editSavedServer( context, server: server, + authenticator: connections.authenticator, onSave: (edited) async { if (!await connections.save(edited)) { throw _ServerSaveFailure( @@ -97,12 +99,22 @@ class SavedServersSection extends StatelessWidget { unawaited(_edit(context, server)); case SavedServerAction.remove: unawaited(_remove(context, server)); + case SavedServerAction.signIn: + final authenticator = connections.authenticator; + if (authenticator == null) return; + unawaited( + showMachineSignIn( + context, + name: server.name, + signIn: (password) => authenticator.authenticate(server, password), + ), + ); } } @override Widget build(BuildContext context) => ListenableBuilder( - listenable: connections, + listenable: Listenable.merge([connections, ?connections.authenticator]), builder: (context, _) { final cupertino = usesCupertinoHost(context); final error = connections.error; @@ -113,7 +125,11 @@ class SavedServersSection extends StatelessWidget { footer: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - const Text('All saved machines connect for chat.'), + const Text( + 'Each entry is a separate machine with its own password; all of ' + 'them connect for chat. Addresses inside one entry are routes ' + 'to that same machine.', + ), if (allowSelection) const Text('The primary machine is used for pipelines and runs.'), if (error != null) @@ -124,6 +140,7 @@ class SavedServersSection extends StatelessWidget { for (final server in connections.catalog.servers) SavedServerRow( server: server, + status: connections.authenticator?.status(server.id), selected: server.id == connections.catalog.active?.id, allowSelection: allowSelection, primaryContext: true, diff --git a/app/lib/features/settings/server_connections.dart b/app/lib/features/settings/server_connections.dart index 79a4c2ed..4160e915 100644 --- a/app/lib/features/settings/server_connections.dart +++ b/app/lib/features/settings/server_connections.dart @@ -1,15 +1,29 @@ import 'package:flutter/foundation.dart'; +import '../../core/servers/machine_access.dart'; import '../../core/servers/server_catalog.dart'; import '../../core/servers/server_catalog_store.dart'; /// Saved configurations are committed before switching the app's connection. /// A failed save leaves the old selection and its live socket unchanged. class ServerConnections extends ChangeNotifier { - ServerConnections({required this.store, required this.onSelected}); + ServerConnections({ + required this.store, + required this.onSelected, + this.replaceRemovedPrimary = false, + }); final ServerCatalogStore store; final Future Function(SavedServer?) onSelected; + + /// Native hosts need a pipelines/runs machine: removing the primary hands + /// that role to the next saved machine instead of leaving the app without + /// an endpoint. Browsers keep following their page origin instead. + final bool replaceRemovedPrimary; + + /// Signs saved machines in independently; set by the app root when the + /// chat pool exists. Settings asks a new machine for its own password. + MachineAuthenticator? authenticator; ServerCatalog _catalog = ServerCatalog(); bool _busy = false; String? _error; @@ -102,8 +116,14 @@ class ServerConnections extends ChangeNotifier { ); } - Future remove(String id) => - _change(() => _catalog.remove(id), activate: _catalog.active?.id == id); + Future remove(String id) => _change(() { + final removedPrimary = _catalog.active?.id == id; + var next = _catalog.remove(id); + if (replaceRemovedPrimary && removedPrimary && next.servers.isNotEmpty) { + next = next.select(next.servers.first.id); + } + return next; + }, activate: _catalog.active?.id == id); Future _change( ServerCatalog Function() change, { diff --git a/app/notes/connection-recovery.md b/app/notes/connection-recovery.md new file mode 100644 index 00000000..ced3e915 --- /dev/null +++ b/app/notes/connection-recovery.md @@ -0,0 +1,111 @@ +# Connection recovery: zero servers, independent sign-in, address choice + +Three real failures from the first multi-machine delivery, and what changed. + +## Removing servers stranded the app + +Removing a profile that was not the primary never activated anything, and +removing the primary left no pipelines/runs machine, so the native app sat on +"Server endpoint not configured" with no way out. Now: + +- `ServerConnections(replaceRemovedPrimary: true)` (native only) hands the + primary role to the next saved machine when the primary is removed. +- `PipelinesRoot` listens to the catalog: a native host with no saved machine + left returns to the connect screen (Add server, discovery, saved list) + however the last profile went away. Nothing is deleted; each machine's kept + sign-in survives for when it is added again. +- Browsers keep following their page origin; they never switch machines. + +## A new machine asks for its own password + +`MachineAuthenticator` (`core/servers/machine_access.dart`) is implemented by +`ChatServerPool` and handed to Settings through `ServerConnections.authenticator`. + +- Add server → Save now probes the machine (`probe`): connected, needs its + password, or unreachable with the reason. A machine that needs its password + gets a sign-in step in the same page (`SavedServerSignInStep`); "Later" keeps + it saved. Editing only the name does not re-ask. +- Each Settings row shows its live state: Connected, Sign in required (tap or + the menu's "Sign in to X" opens the shared `showMachineSignIn` dialog) or + Unreachable with the reason. Address lines read "Address" / "Backup address"; + the footer says entries are separate machines with their own passwords and + that addresses inside one entry are routes to that same machine. +- Native: a socket that fails to open is classified by probing `/login` with + that machine's own kept cookie (`ServerSession.probeProfile`): the form means + it wants its password, a redirect means the sign-in is fine and the socket + failed. Browsers get the relay's `needs_password` verdict directly + (`MachineSignInRequired`). No other machine's credential is ever reused. + +## Unreachable addresses say why + +`ServerSession.probe` returns `ServerProbeResult(state, reason)`; +`probeServerAddresses` and the connect screen show the reason instead of a +generic "Could not reach that server": + +- TLS failure against an IP: Tailscale certificates only cover the tailnet + name, so use `wss://.ts.net:/connect` or `ws://` with the IP and + the plain web port. +- A 200 that is not the Pipelines sign-in page (another service on that + port, for example `:443` when the web app is on `:8443`): check the port. +- Other statuses, refused connections and timeouts name the host and port. + +## Discovery offers every route + +The server advertises its tailnet IPv4 addresses (`ts=`) and the installer's +public HTTPS origin (`public=`, from `PIPELINES_WEB_PUBLIC_URL`) in TXT; browse +returns `addresses` with kinds `lan`, `tailscale`, `public`. `DiscoveredServer` +carries them; a discovered machine with several routes expands to a checklist +(`DiscoveredServerRow`) and the checked routes are saved together as one +machine, the first checked tried first. Onboarding saves them through +`saveMachine`. Typing a different address drops the discovered routes. + +## Diagnosing from a terminal + +`dart run tool/connection_probe.dart [--sign-in]
...` (from `app/`) +runs the native login probe, the sign-in and the websocket exactly as the app +does, printing each address's verdict and reason. The password is read from the +web auth file and never printed. + +## Verification + +- Flutter: settings 158, onboarding 24, core/servers 49, core/session 18, + zero-server recovery 2, sign-in 5, root/selection/chat destination 7: all + pass under the watchdog. Analyzer clean. The full suite has 44 failures in + `test/application` (pending `LaunchUpdateChecker` timer) that fail + identically on untouched main `c2d8d6d7`; they are unrelated to this change. +- Go: `internal/discovery`, `internal/protocol`, `internal/server` pass with + the new route tests. `internal/claude` and `internal/opencode` fail on + untouched main too (environment-dependent tests). +- Node: `web/test` passes unchanged (the proxy forwards the discovery body). +- Live, with the app's own native code (`tool/connection_probe.dart`): + `wss://alans-macbook-pro.tail6bf4dc.ts.net:8443/connect` is the sign-in page, + sign-in returns a cookie, the kept session is accepted and the websocket + upgrades (101). `wss://100.85.25.33:8443` fails TLS with the IP explanation; + `wss://alans-macbook-pro.tail6bf4dc.ts.net/connect` (port 443) answers 502 + from another service and is reported as not the Pipelines page. + `ws://100.85.25.33:8083`, `ws://10.0.0.75:8083`, `ws://100.97.159.92:8082` + and `ws://tank.tail6bf4dc.ts.net:8082` all show the sign-in page. + `ws://10.0.0.100:8082` (tank's LAN address as advertised over mDNS) times + out from this Mac while tank's tailnet addresses work: tank itself appears to + block LAN access to its web port, which the Tailscale route choice now works + around. +- Browser captures: see the capture section appended below. + +### Browser captures (real Chrome, capture kit, full-app fixture `machines=1`) + +The fixture served the controlled discovery JSON at `/api/discovery` (tank +with LAN, Tailscale IP and Tailscale name routes; the Mac with one) and a +fixture authenticator (Mac connected, Linux desktop needing its password, new +machines accepting `fixture-pass`). Inspected PNGs under +`/tmp/review/connection-recovery/`: + +- `material/01` Settings: "Alan’s Mac · Connected · Pipelines and runs server", + "Linux desktop · Sign in required", footer explaining machines vs addresses. +- `material/04` Add server: tank expanded to "Local network", "Tailscale IP", + "Tailscale name (HTTPS)" checkboxes with their addresses and "Use tank". +- `material/05` name and both chosen addresses prefilled, editable. +- `material/06` "Sign in to tank" step after Save with Password, Sign in, Later. +- `material/07` list with tank "Connected", Address + Backup address lines. +- `cupertino/02`, `cupertino/04` (dark, 560px): the same route checklist and a + "Wrong password." retry in the sign-in step. +- `menu/02`: the row menu's "Sign in to Linux desktop" opens the shared dialog. diff --git a/app/test/application/zero_server_recovery_test.dart b/app/test/application/zero_server_recovery_test.dart new file mode 100644 index 00000000..b2029059 --- /dev/null +++ b/app/test/application/zero_server_recovery_test.dart @@ -0,0 +1,185 @@ +import 'dart:async'; + +import 'package:flutter/material.dart' hide ConnectionState; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/pipelines_app.dart'; +import 'package:pipelines_app/application/pipelines_root.dart'; +import 'package:pipelines_app/application/server_endpoint.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/core/servers/chat/chat_server_pool.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/servers/server_catalog_store.dart'; +import 'package:pipelines_app/core/session/server_session.dart'; +import 'package:pipelines_app/core/transport/pipelines_client.dart'; +import 'package:pipelines_app/features/onboarding/onboarding_flow.dart'; +import 'package:pipelines_app/features/settings/settings_store.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +import '../core/transport/pipelines_client_test.dart' show FakeChannel; + +class _Gateway implements ApiGateway { + final events = StreamController.broadcast(); + @override + Stream get frames => events.stream; + @override + Future call(String type, [JsonMap fields = const {}]) async => + switch (type) { + 'attention_acks' || 'ack_attention' => { + 'type': 'attention_acks', + 'attention_acks': {'chat_seen': {}, 'dismissed': []}, + }, + _ => {'type': 'chat_sessions', 'chat_sessions': []}, + }; +} + +ChatMachineConnection _connection(SavedServer server) { + final states = StreamController.broadcast(); + return ChatMachineConnection( + gateway: _Gateway(), + endpoint: () => server.endpoints.first, + connected: () => true, + states: states.stream, + close: states.close, + retry: () async {}, + ); +} + +SavedServer saved(String id) => SavedServer.validated( + id: id, + name: id, + endpoints: ['wss://$id.test/connect'], +); + +Future frames(WidgetTester tester) async { + for (var frame = 0; frame < 12; frame++) { + await tester.pump(const Duration(milliseconds: 20)); + } +} + +void main() { + setUp(() async { + SharedPreferences.setMockInitialValues({ + 'pipelines.session.v2.mac.cookie': 'pipelines_session=mac', + 'pipelines.session.v2.tank.cookie': 'pipelines_session=tank', + }); + await ServerSession.load(); + }); + + testWidgets( + 'removing the primary, then the last machine, returns to Add server', + (tester) async { + final store = MemoryServerCatalogStore( + catalog: ServerCatalog( + servers: [saved('mac'), saved('tank')], + selectedId: 'mac', + ), + ); + PipelinesClient factory() => PipelinesClient( + channelFactory: (_) => FakeChannel()..readyCompleter.complete(), + ); + await tester.pumpWidget( + PipelinesRoot( + nativeUpdatesSupported: false, + server: ServerEndpoint.resolve( + base: Uri.parse('file:///'), + web: false, + configured: 'wss://mac.test/connect', + ), + signedIn: true, + catalogStore: store, + clientFactory: factory, + settingsStore: MemorySettingsStore(), + check: (_) async => SessionState.signedIn, + chatPoolFactory: (servers) => ChatServerPool( + servers, + web: false, + connect: (server) async => _connection(server), + probeProfile: ({required id, required endpoints}) async => + const ServerProbeResult(SessionState.signedIn), + ), + ), + ); + await frames(tester); + final app = tester.widget(find.byType(PipelinesApp)); + expect(app.serverId, 'mac'); + expect(app.servers!.authenticator, isNotNull); + + // The primary goes: the other machine takes over pipelines and runs + // instead of the app losing its endpoint. + // Activation waits for a frame, so pump while the removal runs. + final removedPrimary = app.servers!.remove('mac'); + await frames(tester); + expect(await removedPrimary, isTrue); + final remaining = tester.widget(find.byType(PipelinesApp)); + expect(remaining.serverId, 'tank'); + expect(remaining.server.uri, Uri.parse('wss://tank.test/connect')); + expect(remaining.server.requiresConfiguration, isFalse); + expect(find.text('Server endpoint not configured'), findsNothing); + + // The last machine goes: Add server comes back, nothing is deleted. + final removedLast = remaining.servers!.remove('tank'); + await frames(tester); + expect(await removedLast, isTrue); + expect(find.byType(PipelinesApp), findsNothing); + expect(find.byType(OnboardingFlow), findsOneWidget); + expect(find.byKey(const Key('onboarding-server')), findsOneWidget); + expect(find.byKey(const Key('discovery-scan')), findsOneWidget); + expect(store.catalog?.servers, isEmpty); + // Both sign-ins survive for when the machines are added again. + final preferences = await SharedPreferences.getInstance(); + expect( + preferences.getString('pipelines.session.v2.mac.cookie'), + 'pipelines_session=mac', + ); + await tester.pumpWidget(const SizedBox.shrink()); + }, + ); + + testWidgets('removing a non-primary last machine also recovers', ( + tester, + ) async { + // The pre-fix path: the catalog ends up with a machine that is not the + // primary (a browser-aligned or stale selection), and removing it never + // activated anything. + final store = MemoryServerCatalogStore( + catalog: ServerCatalog(servers: [saved('mac'), saved('tank')]), + ); + PipelinesClient factory() => PipelinesClient( + channelFactory: (_) => FakeChannel()..readyCompleter.complete(), + ); + await tester.pumpWidget( + PipelinesRoot( + nativeUpdatesSupported: false, + server: ServerEndpoint.resolve( + base: Uri.parse('file:///'), + web: false, + configured: '', + ), + signedIn: true, + catalogStore: store, + clientFactory: factory, + settingsStore: MemorySettingsStore(), + check: (_) async => SessionState.signedIn, + chatPoolFactory: (servers) => ChatServerPool( + servers, + web: false, + connect: (server) async => _connection(server), + probeProfile: ({required id, required endpoints}) async => + const ServerProbeResult(SessionState.signedIn), + ), + ), + ); + await frames(tester); + final app = tester.widget(find.byType(PipelinesApp)); + expect(app.serverId, isNull); + final removedFirst = app.servers!.remove('mac'); + await frames(tester); + expect(await removedFirst, isTrue); + final removedLast = app.servers!.remove('tank'); + await frames(tester); + expect(await removedLast, isTrue); + expect(find.byType(OnboardingFlow), findsOneWidget); + expect(find.text('Server endpoint not configured'), findsNothing); + await tester.pumpWidget(const SizedBox.shrink()); + }); +} diff --git a/app/test/core/servers/chat/chat_server_pool_test.dart b/app/test/core/servers/chat/chat_server_pool_test.dart index 9054769a..e640f0a8 100644 --- a/app/test/core/servers/chat/chat_server_pool_test.dart +++ b/app/test/core/servers/chat/chat_server_pool_test.dart @@ -6,6 +6,7 @@ import 'package:pipelines_app/core/session/server_session.dart'; import 'package:pipelines_app/core/servers/server_catalog.dart'; import 'package:pipelines_app/core/servers/server_catalog_store.dart'; import 'package:pipelines_app/core/servers/chat/chat_server_pool.dart'; +import 'package:pipelines_app/core/servers/machine_access.dart'; import 'package:pipelines_app/core/transport/connection_state.dart'; import 'package:pipelines_app/features/settings/server_connections.dart'; @@ -279,4 +280,77 @@ void main() { } }, ); + + test('a socket that did not open is classified with the machine\'s own login', () async { + final profile = _server('tank'); + final servers = await _servers([profile]); + final probed = []; + var verdict = SessionState.signedOut; + late _Machine machine; + final pool = ChatServerPool( + servers, + web: false, + connect: (server) async { + machine = _Machine(server); + machine.connection = ChatMachineConnection( + gateway: machine.gateway, + endpoint: () => server.endpoints.first, + connected: () => false, + states: machine.states.stream, + close: () async {}, + retry: () async {}, + ); + return machine.connection; + }, + probeProfile: ({required id, required endpoints}) async { + probed.add('$id:${endpoints.map((u) => u.host).join(',')}'); + return ServerProbeResult(verdict, reason: 'no route'); + }, + ); + try { + await _flush(); + expect(probed, ['tank:tank.test']); + expect(pool.status('tank')?.access, MachineAccess.needsPassword); + expect(pool.status('tank')?.detail, 'tank asks for its password.'); + verdict = SessionState.unreachable; + await pool.retry('tank'); + await _flush(); + expect(pool.status('tank')?.access, MachineAccess.unreachable); + expect(pool.status('tank')?.detail, 'no route'); + // The editor's own probe uses the same per-machine login, not the pool. + verdict = SessionState.signedIn; + final access = await pool.probe(profile); + expect(access.access, MachineAccess.connected); + expect(probed, hasLength(3)); + expect(pool.status('missing'), isNull); + } finally { + pool.dispose(); + servers.dispose(); + await _flush(); + await machine.finish(); + } + }); + + test('a relay that wants a password is not reported as unreachable', () async { + final profile = _server('tank'); + final servers = await _servers([profile]); + final pool = ChatServerPool( + servers, + web: true, + connect: (server) async => + throw const MachineSignInRequired('Sign in to this machine.'), + probeProfile: ({required id, required endpoints}) async => + fail('browsers never probe the login page directly'), + ); + try { + await _flush(); + expect(pool.status('tank')?.access, MachineAccess.needsPassword); + expect(pool.status('tank')?.detail, 'Sign in to this machine.'); + expect(pool.machines.single.error, 'Sign in to this machine.'); + } finally { + pool.dispose(); + servers.dispose(); + await _flush(); + } + }); } diff --git a/app/test/core/session/server_probe_reason_test.dart b/app/test/core/session/server_probe_reason_test.dart new file mode 100644 index 00000000..bc9d0fe1 --- /dev/null +++ b/app/test/core/session/server_probe_reason_test.dart @@ -0,0 +1,104 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/servers/server_probe.dart'; +import 'package:pipelines_app/core/session/login_probe.dart'; +import 'package:pipelines_app/core/session/server_session.dart'; +import 'package:pipelines_app/core/session/server_session_io.dart' as io; + +void main() { + final login = Uri.parse('https://mac.tail1.ts.net:8443/login'); + + test('the login page, a redirect and other answers are told apart', () { + expect( + ServerSession.interpret( + login, + const LoginProbe(status: 200, loginPage: true), + ).state, + SessionState.signedOut, + ); + expect( + ServerSession.interpret(login, const LoginProbe(status: 302)).state, + SessionState.signedIn, + ); + final other = ServerSession.interpret( + login, + const LoginProbe(status: 200, loginPage: false), + ); + expect(other.state, SessionState.unreachable); + expect(other.reason, contains('not with the Pipelines sign-in page')); + expect(other.reason, contains('mac.tail1.ts.net:8443')); + final missing = ServerSession.interpret( + login, + const LoginProbe(status: 404), + ); + expect(missing.state, SessionState.unreachable); + expect(missing.reason, contains('HTTP 404')); + final failed = ServerSession.interpret( + login, + const LoginProbe(failure: 'Could not reach mac.tail1.ts.net:8443: down.'), + ); + expect(failed.state, SessionState.unreachable); + expect(failed.reason, 'Could not reach mac.tail1.ts.net:8443: down.'); + expect( + LoginProbe.isPipelinesLogin( + '
', + ), + isTrue, + ); + expect(LoginProbe.isPipelinesLogin('

Some other app

'), isFalse); + }); + + test('TLS against a Tailscale IP explains the name requirement', () { + final byIp = io.describeFailure( + Uri.parse('https://100.85.25.33:8443/login'), + const HandshakeException('alert internal error'), + ); + expect(byIp, contains('does not cover an IP address')); + expect(byIp, contains('wss://.ts.net:8443/connect')); + final byName = io.describeFailure( + login, + const HandshakeException('certificate verify failed'), + ); + expect(byName, contains('HTTPS connection to mac.tail1.ts.net:8443 failed')); + expect(byName, contains('certificate verify failed')); + expect( + io.describeFailure( + login, + const SocketException('refused', osError: OSError('Connection refused', 61)), + ), + 'Could not reach mac.tail1.ts.net:8443: Connection refused.', + ); + expect( + io.describeFailure(login, TimeoutException('slow')), + contains('no answer within 10 seconds'), + ); + }); + + test('probing several addresses reports the first reason when all fail', () async { + final result = await probeServerAddresses( + [Uri.parse('wss://a.test/connect'), Uri.parse('ws://b.test/connect')], + probe: (uri) async => ServerProbeResult( + SessionState.unreachable, + reason: 'no ${uri.host}', + ), + isCurrent: () => true, + ); + expect(result.state, SessionState.unreachable); + expect(result.endpoint, Uri.parse('wss://a.test/connect')); + expect(result.reason, 'no a.test'); + final reached = await probeServerAddresses( + [Uri.parse('wss://a.test/connect'), Uri.parse('ws://b.test/connect')], + probe: (uri) async => uri.host == 'b.test' + ? const ServerProbeResult(SessionState.signedOut) + : const ServerProbeResult(SessionState.unreachable, reason: 'x'), + isCurrent: () => true, + ); + expect(reached.endpoint, Uri.parse('ws://b.test/connect')); + expect(reached.state, SessionState.signedOut); + expect(reached.reason, isNull); + final plain = probeFromCheck((_) async => SessionState.signedIn); + expect((await plain(login)).state, SessionState.signedIn); + }); +} diff --git a/app/test/features/onboarding/discovery/browser_server_discovery_test.dart b/app/test/features/onboarding/discovery/browser_server_discovery_test.dart index 3c22d0f0..48950fb9 100644 --- a/app/test/features/onboarding/discovery/browser_server_discovery_test.dart +++ b/app/test/features/onboarding/discovery/browser_server_discovery_test.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/features/onboarding/discovery/browser_server_discovery.dart'; +import 'package:pipelines_app/features/onboarding/discovery/discovered_server.dart'; void main() { test( @@ -57,4 +58,36 @@ void main() { ); }, ); + + test('advertised routes are listed; older servers yield the LAN only', () async { + final discovery = BrowserServerDiscovery( + fetch: () async => jsonEncode({ + 'discovered_servers': [ + { + 'name': 'box', + 'endpoint': 'ws://10.0.0.75:8083/connect', + 'auth': 'password', + 'addresses': [ + {'kind': 'lan', 'endpoint': 'ws://10.0.0.75:8083/connect'}, + {'kind': 'tailscale', 'endpoint': 'ws://100.85.25.33:8083/connect'}, + {'kind': 'public', 'endpoint': 'wss://box.tail1.ts.net:8443/connect'}, + {'kind': 'mystery', 'endpoint': 'ws://1.2.3.4:1/connect'}, + {'kind': 'public', 'endpoint': 'http://bad.example'}, + ], + }, + {'name': 'old', 'endpoint': 'ws://10.0.0.100:8082/connect', 'auth': 'password'}, + ], + }), + ); + final servers = await discovery.scan().first; + expect(servers, hasLength(2)); + expect(servers.first.endpoints.map((u) => u.toString()), [ + 'ws://10.0.0.75:8083/connect', + 'ws://100.85.25.33:8083/connect', + 'wss://box.tail1.ts.net:8443/connect', + ]); + expect(servers.first.addresses[2].route, DiscoveredRoute.public); + expect(servers.last.addresses, hasLength(1)); + expect(servers.last.addresses.single.route, DiscoveredRoute.lan); + }); } diff --git a/app/test/features/onboarding/discovery/discovered_server_test.dart b/app/test/features/onboarding/discovery/discovered_server_test.dart index e3bc3412..2ea08e5a 100644 --- a/app/test/features/onboarding/discovery/discovered_server_test.dart +++ b/app/test/features/onboarding/discovery/discovered_server_test.dart @@ -65,4 +65,64 @@ void main() { expect(platformServerDiscovery(web: true), isNotNull); expect(platformServerDiscovery(web: false), isNotNull); }); + + test('TXT ts/public list every route to the same machine', () { + final server = DiscoveredServer.fromRecord( + instance: 'Pipelines-box', + addresses: ['10.0.0.75'], + port: 8083, + attributes: { + 'name': 'box', + 'path': '/connect', + 'tls': '0', + 'auth': 'password', + 'ts': '100.85.25.33, 10.0.0.9,100.70.1.1', + 'public': 'https://box.tail1.ts.net:8443', + }, + )!; + expect(server.endpoint, Uri.parse('ws://10.0.0.75:8083/connect')); + expect(server.addresses.map((a) => a.route), [ + DiscoveredRoute.lan, + DiscoveredRoute.tailscale, + DiscoveredRoute.tailscale, + DiscoveredRoute.public, + ]); + expect(server.endpoints.map((u) => u.toString()), [ + 'ws://10.0.0.75:8083/connect', + 'ws://100.85.25.33:8083/connect', + 'ws://100.70.1.1:8083/connect', + 'wss://box.tail1.ts.net:8443/connect', + ]); + expect(server.addresses.last.label, 'Tailscale name (HTTPS)'); + expect(server.addresses[1].label, 'Tailscale IP'); + + final chosen = server.choosing([server.addresses.last, server.addresses[1]]); + expect(chosen.endpoint, Uri.parse('wss://box.tail1.ts.net:8443/connect')); + expect(chosen.secure, isTrue); + expect(chosen.endpoints, hasLength(2)); + expect(chosen.name, 'box'); + expect(chosen.passwordRequired, isTrue); + expect(server.choosing(const []), server); + + final unsafe = DiscoveredServer.fromRecord( + instance: 'Pipelines-box', + addresses: ['10.0.0.75'], + port: 8083, + attributes: { + 'ts': 'evil.example,10.0.0.9', + 'public': 'javascript:alert(1)', + }, + )!; + expect(unsafe.addresses, hasLength(1)); + expect( + DiscoveredServer.publicEndpoint('https://user@box.ts.net/app?x=1'), + isNull, + ); + expect( + DiscoveredServer.publicEndpoint('http://10.0.0.5:8083/'), + Uri.parse('ws://10.0.0.5:8083/connect'), + ); + expect(DiscoveredServer.isTailscaleIPv4('100.127.0.1'), isTrue); + expect(DiscoveredServer.isTailscaleIPv4('100.128.0.1'), isFalse); + }); } diff --git a/app/test/features/onboarding/discovery/discovery_panel_test.dart b/app/test/features/onboarding/discovery/discovery_panel_test.dart index 8dbb2780..4e7f78cd 100644 --- a/app/test/features/onboarding/discovery/discovery_panel_test.dart +++ b/app/test/features/onboarding/discovery/discovery_panel_test.dart @@ -169,4 +169,109 @@ void main() { await tester.pumpWidget(host(const SizedBox())); expect(discovery.cancelled, 1); }); + + testWidgets('a machine with several routes lets the operator choose them', ( + tester, + ) async { + final lan = Uri.parse('ws://10.0.0.75:8083/connect'); + final ts = Uri.parse('ws://100.85.25.33:8083/connect'); + final name = Uri.parse('wss://mac.tail1.ts.net:8443/connect'); + final mac = DiscoveredServer( + name: 'mac', + host: '10.0.0.75', + port: 8083, + addresses: [ + DiscoveredAddress(route: DiscoveredRoute.lan, endpoint: lan), + DiscoveredAddress(route: DiscoveredRoute.tailscale, endpoint: ts), + DiscoveredAddress(route: DiscoveredRoute.public, endpoint: name), + ], + ); + final machines = <(List, String)>[]; + await tester.pumpWidget( + host( + OnboardingFlow( + discovery: discovery, + check: (uri) async { + checked.add(uri); + return SessionState.signedOut; + }, + saveMachine: (endpoints, name) async => machines.add((endpoints, name)), + onDone: (_) {}, + ), + ), + ); + await tester.tap(find.byKey(const Key('discovery-scan'))); + await tester.pump(); + discovery.current.add([mac]); + await tester.pump(); + expect(find.text('3 addresses · password'), findsOneWidget); + // Tapping a multi-route machine expands its routes instead of choosing one. + await tester.tap(find.byKey(const Key('discovered-10.0.0.75:8083'))); + await tester.pumpAndSettle(); + expect(find.text('Local network'), findsOneWidget); + expect(find.text('Tailscale IP'), findsOneWidget); + expect(find.text('Tailscale name (HTTPS)'), findsOneWidget); + expect(find.text(name.toString()), findsOneWidget); + await tester.ensureVisible(find.byKey(Key('discovered-route-$name'))); + await tester.tap(find.byKey(Key('discovered-route-$name'))); + await tester.pump(); + await tester.ensureVisible(find.byKey(const Key('discovered-use-10.0.0.75:8083'))); + await tester.tap(find.byKey(const Key('discovered-use-10.0.0.75:8083'))); + await tester.pumpAndSettle(); + expect( + tester.widget(find.byKey(const Key('onboarding-server'))).controller!.text, + lan.toString(), + ); + expect(find.byKey(const Key('onboarding-routes')), findsOneWidget); + await tester.ensureVisible(find.byKey(const Key('onboarding-next'))); + await tester.tap(find.byKey(const Key('onboarding-next'))); + await tester.pumpAndSettle(); + expect(checked, [lan]); + expect(machines.single.$1, [lan.toString(), name.toString()]); + expect(machines.single.$2, 'mac'); + expect(find.byKey(const Key('onboarding-password')), findsOneWidget); + }); + + testWidgets('a typed address drops the discovered routes', (tester) async { + final lan = Uri.parse('ws://10.0.0.75:8083/connect'); + final ts = Uri.parse('ws://100.85.25.33:8083/connect'); + final mac = DiscoveredServer( + name: 'mac', + host: '10.0.0.75', + port: 8083, + addresses: [ + DiscoveredAddress(route: DiscoveredRoute.lan, endpoint: lan), + DiscoveredAddress(route: DiscoveredRoute.tailscale, endpoint: ts), + ], + ); + final machines = <(List, String)>[]; + await tester.pumpWidget( + host( + OnboardingFlow( + discovery: discovery, + check: (uri) async => SessionState.signedOut, + saveMachine: (endpoints, name) async => machines.add((endpoints, name)), + onDone: (_) {}, + ), + ), + ); + await tester.tap(find.byKey(const Key('discovery-scan'))); + await tester.pump(); + discovery.current.add([mac]); + await tester.pump(); + await tester.tap(find.byKey(const Key('discovered-10.0.0.75:8083'))); + await tester.pumpAndSettle(); + await tester.ensureVisible(find.byKey(const Key('discovered-use-10.0.0.75:8083'))); + await tester.tap(find.byKey(const Key('discovered-use-10.0.0.75:8083'))); + await tester.pumpAndSettle(); + await tester.enterText( + find.byKey(const Key('onboarding-server')), + 'ws://10.0.0.200:8083/connect', + ); + await tester.ensureVisible(find.byKey(const Key('onboarding-next'))); + await tester.tap(find.byKey(const Key('onboarding-next'))); + await tester.pumpAndSettle(); + expect(machines.single.$1, ['ws://10.0.0.200:8083/connect']); + expect(machines.single.$2, 'mac'); + }); } diff --git a/app/test/features/onboarding/onboarding_flow_test.dart b/app/test/features/onboarding/onboarding_flow_test.dart index 871b7780..bb160720 100644 --- a/app/test/features/onboarding/onboarding_flow_test.dart +++ b/app/test/features/onboarding/onboarding_flow_test.dart @@ -169,4 +169,36 @@ void main() { expect(find.byKey(const Key('onboarding-server')), findsNothing); expect(find.text('Change server'), findsNothing); }); + + testWidgets('an unreachable address shows the probe\'s own reason', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: OnboardingFlow( + probe: (uri) async => ServerProbeResult( + SessionState.unreachable, + reason: + 'The HTTPS certificate of ${uri.host}:${uri.port} does not ' + 'cover an IP address.', + ), + onDone: (_) {}, + ), + ), + ); + await tester.enterText( + find.byKey(const Key('onboarding-server')), + 'wss://100.85.25.33:8443/connect', + ); + await tester.tap(find.byKey(const Key('onboarding-next'))); + await tester.pumpAndSettle(); + expect( + find.text( + 'The HTTPS certificate of 100.85.25.33:8443 does not cover an IP ' + 'address.', + ), + findsOneWidget, + ); + expect(find.byKey(const Key('onboarding-password')), findsNothing); + }); } diff --git a/app/test/features/settings/saved_server_discovery_test.dart b/app/test/features/settings/saved_server_discovery_test.dart index dedeae7f..b89945ad 100644 --- a/app/test/features/settings/saved_server_discovery_test.dart +++ b/app/test/features/settings/saved_server_discovery_test.dart @@ -116,7 +116,12 @@ void main() { find.byKey(const Key('server-profile-name')), 'My Linux', ); - await tester.ensureVisible(find.text('Save server')); + await tester.scrollUntilVisible( + find.text('Save server'), + 120, + scrollable: find.byType(Scrollable).last, + ); + await tester.pumpAndSettle(); await tester.tap(find.text('Save server')); await tester.pumpAndSettle(); expect(saved!.name, 'My Linux'); diff --git a/app/test/features/settings/saved_server_sign_in_test.dart b/app/test/features/settings/saved_server_sign_in_test.dart new file mode 100644 index 00000000..f6fbb283 --- /dev/null +++ b/app/test/features/settings/saved_server_sign_in_test.dart @@ -0,0 +1,280 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/servers/machine_access.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/servers/server_catalog_store.dart'; +import 'package:pipelines_app/features/settings/saved_server_editor.dart'; +import 'package:pipelines_app/features/settings/saved_server_row.dart'; +import 'package:pipelines_app/features/settings/saved_servers_section.dart'; +import 'package:pipelines_app/features/settings/server_connections.dart'; + +/// A machine authenticator the test scripts: what each probe answers and +/// which password each machine accepts. +class FakeAuthenticator extends ChangeNotifier implements MachineAuthenticator { + final verdicts = {}; + final passwords = {}; + final probes = []; + final signIns = <(String, String)>[]; + + @override + MachineAccessResult? status(String id) => verdicts[id]; + + @override + Future probe(SavedServer server) async { + probes.add(server.id); + return verdicts[server.id] ?? + const MachineAccessResult(MachineAccess.connected); + } + + @override + Future authenticate(SavedServer server, String password) async { + signIns.add((server.id, password)); + if (passwords[server.id] != password) return 'Wrong password.'; + verdicts[server.id] = const MachineAccessResult(MachineAccess.connected); + notifyListeners(); + return null; + } +} + +Future revealSave(WidgetTester tester) async { + await tester.scrollUntilVisible( + find.text('Save server'), + 120, + scrollable: find.byType(Scrollable).last, + ); + await tester.pumpAndSettle(); +} + +Future addServer( + WidgetTester tester, { + required String name, + required String address, +}) async { + await tester.tap(find.text('Add server')); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(const Key('server-profile-name')), name); + await tester.enterText( + find.byKey(const Key('server-profile-addresses')), + address, + ); + await revealSave(tester); + await tester.tap(find.text('Save server')); + await tester.pumpAndSettle(); +} + +void main() { + for (final cupertino in [false, true]) { + testWidgets('a new machine asks for its own password ($cupertino)', ( + tester, + ) async { + final connections = ServerConnections( + store: MemoryServerCatalogStore( + catalog: ServerCatalog( + servers: [ + SavedServer.validated( + id: 'mac', + name: 'Mac', + endpoints: ['ws://10.0.0.75:8083/connect'], + ), + ], + selectedId: 'mac', + ), + ), + onSelected: (_) async {}, + ); + addTearDown(connections.dispose); + await connections.load(); + final auth = FakeAuthenticator() + ..verdicts['mac'] = const MachineAccessResult(MachineAccess.connected); + connections.authenticator = auth; + final body = SingleChildScrollView( + child: SavedServersSection(connections: connections), + ); + await tester.pumpWidget( + cupertino + ? CupertinoApp( + home: CupertinoPageScaffold(child: SafeArea(child: body)), + ) + : MaterialApp(home: Scaffold(body: body)), + ); + expect(find.text('Connected'), findsOneWidget); + // The new machine is unknown to the authenticator until saved; a + // password verdict arrives for whatever id the editor assigned. + auth.verdicts.addAll({ + for (final id in ['pending']) id: const MachineAccessResult( + MachineAccess.needsPassword, + ), + }); + await tester.tap(find.text('Add server')); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(const Key('server-profile-name')), 'tank'); + await tester.enterText( + find.byKey(const Key('server-profile-addresses')), + 'ws://10.0.0.100:8082/connect', + ); + // Whatever id the editor chose, that machine wants a password. + connections.addListener(() { + for (final server in connections.catalog.servers) { + auth.verdicts.putIfAbsent( + server.id, + () => const MachineAccessResult(MachineAccess.needsPassword), + ); + auth.passwords.putIfAbsent(server.id, () => 'tank-secret'); + } + }); + await revealSave(tester); + await tester.tap(find.text('Save server')); + await tester.pumpAndSettle(); + final tank = connections.catalog.servers.firstWhere((s) => s.name == 'tank'); + expect(auth.probes, [tank.id]); + // Saved, and the editor now asks this machine's password; the first + // machine's sign-in is not reused. + expect(find.byKey(const Key('server-profile-password')), findsOneWidget); + expect(find.textContaining('asks for its own password'), findsOneWidget); + await tester.enterText( + find.byKey(const Key('server-profile-password')), + 'wrong', + ); + await tester.tap(find.byKey(const Key('server-profile-sign-in'))); + await tester.pumpAndSettle(); + expect(find.text('Wrong password.'), findsOneWidget); + expect(find.byKey(const Key('server-profile-password')), findsOneWidget); + await tester.enterText( + find.byKey(const Key('server-profile-password')), + 'tank-secret', + ); + await tester.tap(find.byKey(const Key('server-profile-sign-in'))); + await tester.pumpAndSettle(); + expect(auth.signIns, [(tank.id, 'wrong'), (tank.id, 'tank-secret')]); + // Back on the list: both machines connected, each on its own sign-in. + expect(find.byKey(const Key('server-profile-password')), findsNothing); + expect(find.text('Connected'), findsNWidgets(2)); + expect(find.text('Address: ws://10.0.0.100:8082/connect'), findsOneWidget); + expect(connections.catalog.active?.id, 'mac'); + }); + } + + testWidgets('an unreachable machine stays saved with the reason shown', ( + tester, + ) async { + final connections = ServerConnections( + store: MemoryServerCatalogStore(), + onSelected: (_) async {}, + ); + addTearDown(connections.dispose); + await connections.load(); + final auth = FakeAuthenticator(); + connections.authenticator = auth; + connections.addListener(() { + for (final server in connections.catalog.servers) { + auth.verdicts.putIfAbsent( + server.id, + () => const MachineAccessResult( + MachineAccess.unreachable, + detail: 'The HTTPS certificate of 100.85.25.33:8443 does not ' + 'cover an IP address.', + ), + ); + } + }); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: SingleChildScrollView( + child: SavedServersSection(connections: connections), + ), + ), + ), + ); + await addServer( + tester, + name: 'Mac by IP', + address: 'wss://100.85.25.33:8443/connect', + ); + expect(find.textContaining('could not be reached'), findsOneWidget); + expect(find.textContaining('does not cover an IP address'), findsOneWidget); + expect(find.byKey(const Key('server-profile-password')), findsNothing); + await tester.tap(find.byKey(const Key('server-sign-in-later'))); + await tester.pumpAndSettle(); + expect(connections.catalog.servers.single.name, 'Mac by IP'); + expect(find.textContaining('Unreachable: The HTTPS certificate'), findsOneWidget); + }); + + testWidgets('a saved machine that wants a password offers Sign in', ( + tester, + ) async { + final tank = SavedServer.validated( + id: 'tank', + name: 'tank', + endpoints: ['ws://10.0.0.100:8082/connect'], + ); + final connections = ServerConnections( + store: MemoryServerCatalogStore( + catalog: ServerCatalog(servers: [tank], selectedId: 'tank'), + ), + onSelected: (_) async {}, + ); + addTearDown(connections.dispose); + await connections.load(); + final auth = FakeAuthenticator() + ..verdicts['tank'] = const MachineAccessResult(MachineAccess.needsPassword) + ..passwords['tank'] = 'tank-secret'; + connections.authenticator = auth; + await tester.pumpWidget( + MaterialApp( + home: Scaffold(body: SavedServersSection(connections: connections)), + ), + ); + expect(find.text('Sign in required'), findsOneWidget); + await tester.tap(find.byKey(savedServerMenuKey('tank'))); + await tester.pumpAndSettle(); + await tester.tap(find.text('Sign in to tank')); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(const Key('machine-password')), 'tank-secret'); + await tester.tap(find.byKey(const Key('machine-sign-in'))); + await tester.pumpAndSettle(); + expect(auth.signIns, [('tank', 'tank-secret')]); + expect(find.text('Connected'), findsOneWidget); + expect(find.text('Sign in required'), findsNothing); + }); + + testWidgets('editing a name alone does not re-ask the password', ( + tester, + ) async { + final mac = SavedServer.validated( + id: 'mac', + name: 'Mac', + endpoints: ['ws://10.0.0.75:8083/connect'], + ); + final auth = FakeAuthenticator() + ..verdicts['mac'] = const MachineAccessResult(MachineAccess.needsPassword); + SavedServer? saved; + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) => Scaffold( + body: TextButton( + onPressed: () => editSavedServer( + context, + server: mac, + authenticator: auth, + onSave: (value) async => saved = value, + ), + child: const Text('Edit'), + ), + ), + ), + ), + ); + await tester.tap(find.text('Edit')); + await tester.pumpAndSettle(); + await tester.enterText(find.byKey(const Key('server-profile-name')), 'Studio'); + await revealSave(tester); + await tester.tap(find.text('Save server')); + await tester.pumpAndSettle(); + expect(saved?.name, 'Studio'); + expect(auth.probes, isEmpty); + expect(find.text('Edit'), findsOneWidget); + }); +} diff --git a/app/test/features/settings/saved_servers_test.dart b/app/test/features/settings/saved_servers_test.dart index c303ea94..9d7302e9 100644 --- a/app/test/features/settings/saved_servers_test.dart +++ b/app/test/features/settings/saved_servers_test.dart @@ -11,6 +11,16 @@ import 'saved_server_menu.dart'; SavedServer profile(String id, List urls) => SavedServer.validated(id: id, name: id, endpoints: urls); +/// The editor's list builds lazily; scroll its Save button into view. +Future revealSave(WidgetTester tester) async { + await tester.scrollUntilVisible( + find.text('Save server'), + 120, + scrollable: find.byType(Scrollable).last, + ); + await tester.pumpAndSettle(); +} + void main() { test( 'browser Back aligns active identity with the actual page; failed switch restores selection', @@ -129,8 +139,7 @@ void main() { find.byKey(const Key('server-profile-addresses')), 'wss://tail.example/connect\nws://192.168.1.2:8083/connect', ); - await tester.ensureVisible(find.text('Save server')); - await tester.pumpAndSettle(); + await revealSave(tester); await tester.tap(find.text('Save server')); await tester.pumpAndSettle(); expect(connections.catalog.active?.name, 'Home'); @@ -139,7 +148,7 @@ void main() { 'ws://192.168.1.2:8083/connect', ]); expect( - find.text('Backup 1: ws://192.168.1.2:8083/connect'), + find.text('Backup address: ws://192.168.1.2:8083/connect'), findsOneWidget, ); await openSavedServerMenu(tester); @@ -149,8 +158,7 @@ void main() { find.byKey(const Key('server-profile-name')), 'My home', ); - await tester.ensureVisible(find.text('Save server')); - await tester.pumpAndSettle(); + await revealSave(tester); await tester.tap(find.text('Save server')); await tester.pumpAndSettle(); expect(connections.catalog.active?.name, 'My home'); @@ -183,8 +191,7 @@ void main() { find.byKey(const Key('server-profile-addresses')), 'not-a-url', ); - await tester.ensureVisible(find.text('Save server')); - await tester.pumpAndSettle(); + await revealSave(tester); await tester.tap(find.text('Save server')); await tester.pumpAndSettle(); expect(find.byKey(const Key('server-profile-addresses')), findsOneWidget); diff --git a/app/test/features/settings/server_connections_recovery_test.dart b/app/test/features/settings/server_connections_recovery_test.dart new file mode 100644 index 00000000..1eeca140 --- /dev/null +++ b/app/test/features/settings/server_connections_recovery_test.dart @@ -0,0 +1,77 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/servers/server_catalog.dart'; +import 'package:pipelines_app/core/servers/server_catalog_store.dart'; +import 'package:pipelines_app/features/settings/server_connections.dart'; + +SavedServer profile(String id) => SavedServer.validated( + id: id, + name: id, + endpoints: ['wss://$id.test/connect'], +); + +void main() { + test('a native host hands the primary role to the next machine', () async { + final store = MemoryServerCatalogStore( + catalog: ServerCatalog( + servers: [profile('mac'), profile('tank')], + selectedId: 'mac', + ), + ); + final activated = []; + final connections = ServerConnections( + store: store, + onSelected: (server) async => activated.add(server?.id), + replaceRemovedPrimary: true, + ); + addTearDown(connections.dispose); + await connections.load(); + expect(await connections.remove('mac'), isTrue); + expect(connections.catalog.active?.id, 'tank'); + expect(store.catalog?.selectedId, 'tank'); + expect(activated, ['tank']); + // Removing the last machine activates "nothing" so the root can recover. + expect(await connections.remove('tank'), isTrue); + expect(connections.catalog.servers, isEmpty); + expect(activated, ['tank', null]); + }); + + test('removing a non-primary machine keeps the primary', () async { + final store = MemoryServerCatalogStore( + catalog: ServerCatalog( + servers: [profile('mac'), profile('tank')], + selectedId: 'mac', + ), + ); + final activated = []; + final connections = ServerConnections( + store: store, + onSelected: (server) async => activated.add(server?.id), + replaceRemovedPrimary: true, + ); + addTearDown(connections.dispose); + await connections.load(); + expect(await connections.remove('tank'), isTrue); + expect(connections.catalog.active?.id, 'mac'); + expect(activated, isEmpty); + }); + + test('browsers never switch machines when the primary is removed', () async { + final store = MemoryServerCatalogStore( + catalog: ServerCatalog( + servers: [profile('mac'), profile('tank')], + selectedId: 'mac', + ), + ); + final activated = []; + final connections = ServerConnections( + store: store, + onSelected: (server) async => activated.add(server?.id), + ); + addTearDown(connections.dispose); + await connections.load(); + expect(await connections.remove('mac'), isTrue); + expect(connections.catalog.active, isNull); + expect(connections.catalog.servers.map((s) => s.id), ['tank']); + expect(activated, [null]); + }); +} diff --git a/app/test/features/settings/settings_layout_test.dart b/app/test/features/settings/settings_layout_test.dart index 33b2bbe8..36c0889c 100644 --- a/app/test/features/settings/settings_layout_test.dart +++ b/app/test/features/settings/settings_layout_test.dart @@ -188,7 +188,7 @@ void main() { ), findsOneWidget, ); - expect(find.text('Preferred: wss://work.test/connect'), findsOneWidget); + expect(find.text('Address: wss://work.test/connect'), findsOneWidget); expect(find.byKey(savedServerMenuKey('Home')), findsOneWidget); expect(find.text('Add server'), findsOneWidget); // Tapping another server's row uses it. diff --git a/app/tool/connection_probe.dart b/app/tool/connection_probe.dart new file mode 100644 index 00000000..91536a8d --- /dev/null +++ b/app/tool/connection_probe.dart @@ -0,0 +1,74 @@ +// Probes Pipelines addresses exactly as the native app does, for diagnosing +// a connection that the app reports as unreachable. From app/: +// +// dart run tool/connection_probe.dart wss://box.tail1.ts.net:8443/connect [more...] +// +// With PIPELINES_WEB_AUTH_FILE (or ~/.config/pipelines/web-auth.json) present +// and --sign-in, it also posts that file's password to the first address and +// opens the websocket with the resulting cookie. The password is never printed. +import 'dart:convert'; +import 'dart:io'; + +import 'package:pipelines_app/core/session/server_session_io.dart' as native; +import 'package:pipelines_app/core/session/session_probe.dart'; +import 'package:pipelines_app/core/transport/server_url.dart'; + +Future main(List args) async { + final signIn = args.contains('--sign-in'); + final addresses = args.where((a) => !a.startsWith('--')).toList(); + if (addresses.isEmpty) { + stderr.writeln('usage: connection_probe.dart [--sign-in] ...'); + exit(2); + } + var failures = 0; + for (final raw in addresses) { + final Uri endpoint; + try { + endpoint = Uri.parse(ServerUrl.validate(raw).wsUrl); + } on FormatException catch (error) { + stdout.writeln('$raw: invalid: ${error.message}'); + failures++; + continue; + } + final login = loginUriFor(endpoint)!; + final probe = await native.probeLogin(login, const {}); + final result = interpretLoginProbe(login, probe); + stdout.writeln( + '$endpoint: ${result.state.name}' + '${result.reason == null ? '' : ' — ${result.reason}'}' + ' (HTTP ${probe.status ?? 'none'}, login page: ${probe.loginPage})', + ); + if (result.state == SessionState.unreachable) failures++; + } + if (!signIn) exit(failures == 0 ? 0 : 1); + final endpoint = Uri.parse(ServerUrl.validate(addresses.first).wsUrl); + final login = loginUriFor(endpoint)!; + final file = File( + Platform.environment['PIPELINES_WEB_AUTH_FILE'] ?? + '${Platform.environment['HOME']}/.config/pipelines/web-auth.json', + ); + final password = (jsonDecode(await file.readAsString()) as Map)['password'] as String; + final signedIn = await native.postLogin(login, password); + if (signedIn.cookie == null) { + stdout.writeln('sign-in: FAILED — ${signedIn.error}'); + exit(1); + } + stdout.writeln('sign-in: cookie received'); + final kept = interpretLoginProbe( + login, + await native.probeLogin(login, {'Cookie': signedIn.cookie!}), + ); + stdout.writeln('kept session: ${kept.state.name}'); + try { + final socket = await WebSocket.connect( + endpoint.toString(), + headers: {'Cookie': signedIn.cookie!}, + ).timeout(const Duration(seconds: 15)); + stdout.writeln('websocket: connected (ready state ${socket.readyState})'); + await socket.close(); + } catch (error) { + stdout.writeln('websocket: FAILED — $error'); + exit(1); + } + stdout.writeln('done'); +} diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index 1101ffaf..d33ea846 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -1,4 +1,5 @@ import 'package:pipelines_app/core/servers/chat/chat_server_pool.dart'; +import 'package:pipelines_app/core/servers/machine_access.dart'; import 'package:pipelines_app/core/servers/server_catalog.dart'; import 'package:pipelines_app/core/servers/server_catalog_store.dart'; import 'package:pipelines_app/features/settings/server_connections.dart'; @@ -630,6 +631,36 @@ JsonMap? probeReply(JsonMap request) { /// An in-process websocket channel: every frame the client sends is decoded /// and answered asynchronously with [probeReply], as the server would over the /// wire. `ready` completes at once so the shared client reports connected. +/// The capture fixture's stand-in for the chat pool: the Mac is connected, +/// the Linux desktop still wants its password, and any machine added during +/// the capture asks for `fixture-pass`. +class _FixtureAuthenticator extends ChangeNotifier + implements MachineAuthenticator { + final _verdicts = { + 'mac': const MachineAccessResult(MachineAccess.connected), + 'linux': const MachineAccessResult(MachineAccess.needsPassword), + }; + + @override + MachineAccessResult? status(String id) => _verdicts[id]; + + @override + Future probe(SavedServer server) async { + await Future.delayed(const Duration(milliseconds: 400)); + return _verdicts[server.id] ??= + const MachineAccessResult(MachineAccess.needsPassword); + } + + @override + Future authenticate(SavedServer server, String password) async { + await Future.delayed(const Duration(milliseconds: 400)); + if (password != 'fixture-pass') return 'Wrong password.'; + _verdicts[server.id] = const MachineAccessResult(MachineAccess.connected); + notifyListeners(); + return null; + } +} + class _FixtureChannel implements WebSocketChannel { _FixtureChannel(); @@ -820,6 +851,9 @@ Future main() async { onSelected: (_) async {}, ); await machines.load(); + // Settings shows each machine's own sign-in state; a new machine asks + // for its password (`fixture-pass`) like the real chat pool does. + machines.authenticator = _FixtureAuthenticator(); } final pool = params['federated'] == '1' && machines != null ? ChatServerPool(