diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index da3c2018..c067b9f2 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -79,6 +79,7 @@ body: - AdGuard Home - Cleanuparr - Gotify + - Docker Host (terminal) - Unraid - Something else validations: diff --git a/README.md b/README.md index c5175364..f3e62f2e 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,11 @@ external URLs. - **Wake-on-LAN.** Store your machines (MAC / broadcast / port) in the profile and wake them from Settings; magic packets are sent with pure Dart UDP. +- **Terminal.** Add your server as a Docker Host to get a Termux-style SSH + terminal (password or private key, host keys pinned on first use). Give a + service its container name - or pick it from `docker ps` - and long-press + it in the sidebar to open a shell inside that container. Every shell is a + tab on the host's one SSH connection, kept alive while you use the app. - **Reverse-proxy friendly.** Global and per-instance custom HTTP headers (Authelia / Cloudflare Access style) ride every request. See [Behind a reverse proxy](docs/REVERSE_PROXY.md). @@ -90,6 +95,7 @@ each one covers: | AdGuard Home | protection switch and timed pause, statistics, top clients and domains, query log with block and unblock, blocklists, custom rules, blocked services and rewrites, persistent and runtime clients, DNS, cache, access and retention settings, dashboard widget | | Cleanuparr | system status, operational metrics, active strikes ledger & reset, audit events feed, background cleaner job triggers, dashboard widget (beta) | | Unraid | array and disk health, system with per-core load, Docker, VM control | +| Docker Host | SSH terminal (tabs, extra-keys row, host-key pinning) and a shell inside each service's container over one shared connection (beta) | ## Install diff --git a/STATUS.md b/STATUS.md index 3575200b..2565559e 100644 --- a/STATUS.md +++ b/STATUS.md @@ -44,6 +44,14 @@ Atrium is a **controller** app. Video playback was removed by design over pure Dart UDP), **custom HTTP headers** (global + per-instance, for reverse-proxy auth, kept intact when an instance's own form is saved), all carried by profile export/import +- **Docker Host terminal** (beta): a Termux-style SSH terminal to the + server (password or private key, kept in the keystore; host keys pinned + on first use), with tabs, an extra-keys row and copy/paste. A service + given its container name - typed or picked from `docker ps` - opens a + shell inside that container from its sidebar long-press. Every shell is a + channel on the host's one SSH connection, which closes once the last + shell exits, after 5 minutes in the background, or when the app closes. + Plain `docker` only for now (no `sudo docker` / podman) - **Shares and links**: a magnet or `.torrent` shared to Atrium goes to a torrent client; a movie or show shared from another app (an IMDb, TMDB, Letterboxd or Trakt link, Showly's text, or a bare title) is looked up on diff --git a/app/lib/src/health_providers.dart b/app/lib/src/health_providers.dart index 0e54c9e2..f1ab0dcc 100644 --- a/app/lib/src/health_providers.dart +++ b/app/lib/src/health_providers.dart @@ -3,6 +3,9 @@ import 'package:core_networking/core_networking.dart'; import 'package:core_profile/core_profile.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'terminal/ssh_host_status.dart'; +import 'terminal/terminal_hub.dart'; + /// The shared [HealthProbe], built from the networking [DioFactory]. final Provider healthProbeProvider = Provider(( Ref ref, @@ -15,9 +18,26 @@ final Provider healthProbeProvider = Provider(( /// Keyed by `instanceId` (String) so Riverpod caches results across instance /// object recreations and avoids redundant health probes when scrolling. final instanceHealthProvider = - FutureProvider.family((Ref ref, String instanceId) { + FutureProvider.family((Ref ref, String instanceId) async { final Instance? instance = ref.watch(instanceByIdProvider(instanceId)); if (instance == null) return Health.unknown; + if (instance.kind == ServiceKind.dockerHost) { + // Rebuilt when a real login succeeds or is refused, so the dot follows + // at once rather than at the next poll. + final SshLoginRecord? lastLogin = ref.watch( + sshLoginRecordsProvider + .select((Map m) => m[instanceId]), + ); + if (ref.read(terminalHubProvider).session(instanceId).status == + SshStatus.connected) { + // No need to probe a server we are logged in to right now. + return Health.ok; + } + return dockerHostHealth( + probe: await ref.watch(healthProbeProvider).check(instance), + lastLogin: lastLogin, + ); + } return ref.watch(healthProbeProvider).check(instance); }); diff --git a/app/lib/src/screens/dashboard_screen.dart b/app/lib/src/screens/dashboard_screen.dart index d94d85e1..f49be9c5 100644 --- a/app/lib/src/screens/dashboard_screen.dart +++ b/app/lib/src/screens/dashboard_screen.dart @@ -12,6 +12,10 @@ import 'package:go_router/go_router.dart'; import '../dashboard/dashboard_board.dart'; import '../health_providers.dart'; +import '../terminal/docker_host_status_tile.dart'; +import '../terminal/docker_shell.dart'; +import '../terminal/terminal_hub.dart'; +import '../terminal/terminal_screen.dart'; import 'reorder_sidebar_screen.dart'; /// Home screen. Services live in the navigation drawer (the sidebar); the @@ -517,6 +521,10 @@ class _HealthAwareTile extends ConsumerWidget { child: Column( mainAxisSize: MainAxisSize.min, children: [ + if (instance.kind == ServiceKind.dockerHost) ...[ + DockerHostStatusTile(host: instance), + const Divider(), + ], ListTile( leading: const Icon(Icons.open_in_new), title: const Text('Open service'), @@ -532,6 +540,37 @@ class _HealthAwareTile extends ConsumerWidget { ); }, ), + if (instance.kind != ServiceKind.dockerHost && + dockerHostFor( + instance, + ref.read(activeInstancesProvider), + ) != + null) + ListTile( + leading: const Icon(Icons.terminal_rounded), + title: const Text('Open shell in container'), + subtitle: _ContainerShellSubtitle(instance: instance), + onTap: () { + Navigator.pop(sheetContext); + if (instance.dockerContainer.isEmpty) { + final GoRouter router = GoRouter.of(context); + Navigator.of(context).pop(); + router.goNamed( + AtriumRoutes.editInstanceName, + pathParameters: { + 'instanceId': instance.id, + }, + ); + return; + } + openServiceShell( + context, + ref, + instance, + beforeNavigate: () => Navigator.of(context).pop(), + ); + }, + ), ListTile( leading: const Icon(Icons.edit), title: const Text('Edit connection settings'), @@ -557,6 +596,41 @@ class _HealthAwareTile extends ConsumerWidget { } } +/// The container a service's shell opens in, or the last Docker problem +/// seen on its host - shown here rather than on the host's own dot, since +/// the server itself is fine. +class _ContainerShellSubtitle extends ConsumerWidget { + const _ContainerShellSubtitle({required this.instance}); + + final Instance instance; + + @override + Widget build(BuildContext context, WidgetRef ref) { + if (instance.dockerContainer.isEmpty) { + return const Text('Set the container in its settings'); + } + final Instance? host = + dockerHostFor(instance, ref.watch(activeInstancesProvider)); + if (host == null) { + return Text(instance.dockerContainer); + } + final HostSession session = ref.watch(terminalHubProvider).session(host.id); + return ListenableBuilder( + listenable: session, + builder: (BuildContext context, Widget? _) { + final String? issue = session.dockerIssue; + if (issue == null) { + return Text(instance.dockerContainer); + } + return Text( + '${instance.dockerContainer} - $issue', + style: TextStyle(color: Theme.of(context).colorScheme.error), + ); + }, + ); + } +} + /// Bottom pill showing the active profile; opens profile management. class _ProfilePill extends StatelessWidget { const _ProfilePill({required this.label, required this.onTap}); diff --git a/app/lib/src/screens/instance_form_screen.dart b/app/lib/src/screens/instance_form_screen.dart index 0d525850..0ac91a86 100644 --- a/app/lib/src/screens/instance_form_screen.dart +++ b/app/lib/src/screens/instance_form_screen.dart @@ -1,8 +1,13 @@ +import 'dart:convert'; + import 'package:core_models/core_models.dart'; import 'package:core_profile/core_profile.dart'; import 'package:core_router/core_router.dart'; import 'package:core_ui/core_ui.dart'; +import 'package:dartssh2/dartssh2.dart' show SSHClient; +import 'package:file_picker/file_picker.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:go_router/go_router.dart'; import 'package:service_plex/service_plex.dart'; @@ -13,6 +18,11 @@ import '../connection_test/connection_test_result.dart'; import '../connection_test/connection_tester.dart'; import '../plex_client_identifier.dart'; import '../service_icon.dart'; +import '../terminal/docker_shell.dart'; +import '../terminal/ssh_connector.dart'; +import '../terminal/ssh_host_status.dart'; +import '../terminal/terminal_hub.dart'; +import '../terminal/terminal_screen.dart'; const String speedtestConnectionSuccessMessage = 'Connected with results:read. Run permission cannot be verified until used.'; @@ -66,6 +76,13 @@ class _InstanceFormScreenState extends ConsumerState { final TextEditingController _apiKey = TextEditingController(); final TextEditingController _username = TextEditingController(); final TextEditingController _password = TextEditingController(); + final TextEditingController _privateKey = TextEditingController(); + final TextEditingController _passphrase = TextEditingController(); + final TextEditingController _dockerContainer = TextEditingController(); + + /// The Docker host this service's container runs on; empty = the first. + String _dockerHostId = ''; + bool _loadingContainers = false; /// qBittorrent 5.2+ supports both username/password and API-key auth; this /// tracks which the user picked (qBit only). @@ -94,6 +111,8 @@ class _InstanceFormScreenState extends ConsumerState { bool get _isEdit => widget.instanceId != null; + bool get _isSsh => _kind == ServiceKind.dockerHost; + @override void initState() { super.initState(); @@ -110,6 +129,9 @@ class _InstanceFormScreenState extends ConsumerState { _apiKey.dispose(); _username.dispose(); _password.dispose(); + _privateKey.dispose(); + _passphrase.dispose(); + _dockerContainer.dispose(); _pollingInterval.dispose(); super.dispose(); } @@ -127,6 +149,8 @@ class _InstanceFormScreenState extends ConsumerState { _allowSelfSigned = instance.allowSelfSignedCerts; _pollingInterval.text = instance.pollingIntervalSeconds.toString(); _customHeaders = instance.customHeaders; + _dockerHostId = instance.dockerHostId; + _dockerContainer.text = instance.dockerContainer; switch (instance.auth) { case InstanceAuthApiKey(:final String apiKey): _apiKey.text = apiKey; @@ -138,6 +162,16 @@ class _InstanceFormScreenState extends ConsumerState { case InstanceAuthCookie(:final String username, :final String password): _username.text = username; _password.text = password; + case InstanceAuthSsh( + :final String username, + :final String password, + :final String privateKey, + :final String passphrase, + ): + _username.text = username; + _password.text = password; + _privateKey.text = privateKey; + _passphrase.text = passphrase; } // A qBittorrent instance saved with key auth reopens on the API-key tab. _qbitUseApiKey = instance.kind == ServiceKind.qbittorrent && @@ -173,6 +207,12 @@ class _InstanceFormScreenState extends ConsumerState { username: _username.text.trim(), password: _password.text, ), + AuthStyle.ssh => InstanceAuth.ssh( + username: _username.text.trim(), + password: _password.text, + privateKey: _privateKey.text.trim(), + passphrase: _passphrase.text, + ), AuthStyle.none => const InstanceAuth.apiKey(apiKey: ''), }; } @@ -188,6 +228,8 @@ class _InstanceFormScreenState extends ConsumerState { allowSelfSignedCerts: _allowSelfSigned, pollingIntervalSeconds: int.tryParse(_pollingInterval.text.trim()) ?? 5, customHeaders: _customHeaders, + dockerHostId: _isSsh ? '' : _dockerHostId, + dockerContainer: _isSsh ? '' : _dockerContainer.text.trim(), ); void _clearConnectionTest(String _) { @@ -320,6 +362,13 @@ class _InstanceFormScreenState extends ConsumerState { final String id = widget.instanceId ?? ref.read(profileRepositoryProvider).newInstanceId(); final Instance instance = _buildInstance(id); + final Instance? before = + _isEdit ? ref.read(instanceByIdProvider(widget.instanceId!)) : null; + if (_isSsh && before != null && !_sameSshLogin(before, instance)) { + // The last login was made with the old details; forget it so a host + // that refused a wrong password is not still amber after the fix. + await ref.read(sshLoginRecordsProvider.notifier).clear(id); + } await controller.upsertInstance(profile.id, instance); if (mounted) { if (context.canPop()) { @@ -342,18 +391,17 @@ class _InstanceFormScreenState extends ConsumerState { widget.instanceId ?? 'connection-test', ); final ConnectionTester tester = ref.read(connectionTesterProvider); + final Future Function(UrlMode) testOne = _isSsh + ? (UrlMode url) => _testSsh(candidate.copyWith(urlMode: url)) + : (UrlMode url) => tester.test(candidate: candidate, url: url); final Map results = {}; try { if (_localUrl.text.trim().isNotEmpty) { - results['Local'] = - await tester.test(candidate: candidate, url: UrlMode.forceLocal); + results['Local'] = await testOne(UrlMode.forceLocal); } if (_externalUrl.text.trim().isNotEmpty) { - results['External'] = await tester.test( - candidate: candidate, - url: UrlMode.forceExternal, - ); + results['External'] = await testOne(UrlMode.forceExternal); } } finally { if (mounted) { @@ -554,10 +602,12 @@ class _InstanceFormScreenState extends ConsumerState { controller: _localUrl, decoration: InputDecoration( border: const OutlineInputBorder(), - labelText: 'Local URL', - hintText: _kind.defaultPort == null - ? 'http://192.168.1.10' - : 'http://192.168.1.10:${_kind.defaultPort}', + labelText: _isSsh ? 'Local address' : 'Local URL', + hintText: _isSsh + ? 'ssh://192.168.1.10:22' + : _kind.defaultPort == null + ? 'http://192.168.1.10' + : 'http://192.168.1.10:${_kind.defaultPort}', ), keyboardType: TextInputType.url, autocorrect: false, @@ -569,10 +619,12 @@ class _InstanceFormScreenState extends ConsumerState { controller: _externalUrl, decoration: InputDecoration( border: const OutlineInputBorder(), - labelText: 'External URL', - hintText: _kind == ServiceKind.speedtestTracker - ? 'https://speedtest.example.com' - : 'https://sonarr.example.com', + labelText: _isSsh ? 'External address' : 'External URL', + hintText: _isSsh + ? 'ssh://home.example.com:2222' + : _kind == ServiceKind.speedtestTracker + ? 'https://speedtest.example.com' + : 'https://sonarr.example.com', ), keyboardType: TextInputType.url, autocorrect: false, @@ -645,51 +697,58 @@ class _InstanceFormScreenState extends ConsumerState { ), const SizedBox(height: Insets.lg), - // Preferences Card - _FormSectionCard( - title: 'Preferences', - icon: Icons.tune_outlined, - children: [ - SwitchListTile( - contentPadding: EdgeInsets.zero, - title: const Text('Allow self-signed certificates'), - subtitle: const Text( - 'Skip TLS validation for this instance only.', - ), - value: _allowSelfSigned, - onChanged: (bool v) => setState(() { - _allowSelfSigned = v; - _connectionResults = {}; - }), - ), - if (_kind == ServiceKind.glances || - _kind == ServiceKind.dashdot || - _kind == ServiceKind.gluetun || - _kind == ServiceKind.qbittorrent || - _kind == ServiceKind.slskd || - _kind == ServiceKind.gotify) ...[ - const SizedBox(height: Insets.md), - TextFormField( - controller: _pollingInterval, - decoration: const InputDecoration( - border: OutlineInputBorder(), - labelText: 'Polling Interval (seconds)', - hintText: '5', - suffixText: 'sec', + if (_containerSection() case final Widget section) ...[ + section, + const SizedBox(height: Insets.lg), + ], + + // Preferences Card (nothing applies to an SSH host) + if (!_isSsh) ...[ + _FormSectionCard( + title: 'Preferences', + icon: Icons.tune_outlined, + children: [ + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text('Allow self-signed certificates'), + subtitle: const Text( + 'Skip TLS validation for this instance only.', ), - keyboardType: TextInputType.number, - validator: (String? v) { - final int? val = int.tryParse(v?.trim() ?? ''); - if (val == null || val < 1) { - return 'Must be at least 1 second'; - } - return null; - }, + value: _allowSelfSigned, + onChanged: (bool v) => setState(() { + _allowSelfSigned = v; + _connectionResults = {}; + }), ), + if (_kind == ServiceKind.glances || + _kind == ServiceKind.dashdot || + _kind == ServiceKind.gluetun || + _kind == ServiceKind.qbittorrent || + _kind == ServiceKind.slskd || + _kind == ServiceKind.gotify) ...[ + const SizedBox(height: Insets.md), + TextFormField( + controller: _pollingInterval, + decoration: const InputDecoration( + border: OutlineInputBorder(), + labelText: 'Polling Interval (seconds)', + hintText: '5', + suffixText: 'sec', + ), + keyboardType: TextInputType.number, + validator: (String? v) { + final int? val = int.tryParse(v?.trim() ?? ''); + if (val == null || val < 1) { + return 'Must be at least 1 second'; + } + return null; + }, + ), + ], ], - ], - ), - const SizedBox(height: Insets.lg), + ), + const SizedBox(height: Insets.lg), + ], // Connection Test Card _FormSectionCard( @@ -1096,6 +1155,8 @@ class _InstanceFormScreenState extends ConsumerState { else ...userPass, ]; + case AuthStyle.ssh: + return _sshAuthFields(); case AuthStyle.none: return [ Padding( @@ -1121,15 +1182,331 @@ class _InstanceFormScreenState extends ConsumerState { } } + List _sshAuthFields() { + const TextStyle mono = TextStyle(fontFamily: 'JetBrainsMono Nerd Font'); + return [ + TextFormField( + controller: _username, + decoration: const InputDecoration( + border: OutlineInputBorder(), + labelText: 'Username', + ), + autocorrect: false, + textInputAction: TextInputAction.next, + onChanged: _clearConnectionTest, + validator: (String? v) => + (v == null || v.trim().isEmpty) ? 'Required' : null, + ), + const SizedBox(height: Insets.md), + TextFormField( + controller: _password, + decoration: const InputDecoration( + border: OutlineInputBorder(), + labelText: 'Password (optional with a key)', + ), + obscureText: true, + onChanged: _clearConnectionTest, + validator: (String? v) => + (v ?? '').isEmpty && _privateKey.text.trim().isEmpty + ? 'Enter a password or a private key' + : null, + ), + const SizedBox(height: Insets.md), + TextFormField( + controller: _privateKey, + decoration: InputDecoration( + border: const OutlineInputBorder(), + labelText: 'Private key (optional)', + hintText: '-----BEGIN OPENSSH PRIVATE KEY-----', + helperText: 'Paste an OpenSSH / PEM key. Stored in the keystore.', + alignLabelWithHint: true, + suffixIcon: IconButton( + tooltip: 'Load key file', + icon: const Icon(Icons.file_open_outlined), + onPressed: _loadKeyFile, + ), + ), + style: mono.copyWith(fontSize: 12), + minLines: 2, + maxLines: 5, + autocorrect: false, + enableSuggestions: false, + keyboardType: TextInputType.multiline, + onChanged: _clearConnectionTest, + validator: (String? v) { + final String key = (v ?? '').trim(); + if (key.isNotEmpty && !key.contains('PRIVATE KEY')) { + return 'Not a private key (expected a BEGIN ... PRIVATE KEY block)'; + } + return null; + }, + ), + const SizedBox(height: Insets.md), + TextFormField( + controller: _passphrase, + decoration: const InputDecoration( + border: OutlineInputBorder(), + labelText: 'Key passphrase (optional)', + ), + obscureText: true, + onChanged: _clearConnectionTest, + ), + ]; + } + + Future _loadKeyFile() async { + final ScaffoldMessengerState messenger = ScaffoldMessenger.of(context); + FilePickerResult? picked; + try { + picked = await FilePicker.pickFiles(dialogTitle: 'Private key'); + } on PlatformException catch (e) { + messenger.showSnackBar( + SnackBar(content: Text('Could not open file picker: ${e.message}')), + ); + return; + } + final PlatformFile? file = + picked == null || picked.files.isEmpty ? null : picked.files.single; + if (file == null) { + return; + } + String text; + try { + text = utf8.decode(await file.readAsBytes(), allowMalformed: true).trim(); + } on Object { + text = ''; + } + if (!text.contains('PRIVATE KEY')) { + messenger.showSnackBar( + const SnackBar(content: Text('That file is not a private key.')), + ); + return; + } + if (mounted) { + setState(() { + _privateKey.text = text; + _connectionResults = {}; + }); + } + } + + /// Logs in over SSH for real, so a wrong password or key shows up here. + Future _testSsh(Instance forced) async { + try { + final ({SSHClient client, SshEndpoint endpoint}) result = await connectSsh( + forced, + knownHosts: ref.read(terminalHubProvider).knownHosts, + onHostKey: (HostKeyPrompt p) => + mounted ? confirmHostKey(context, p) : Future.value(false), + ); + result.client.close(); + _recordTestLogin(forced, null); + return const ConnectionTestResult( + ConnectionOutcome.connected, + 'Connected and logged in', + ); + } on SshConnectException catch (e) { + if (e.authFailed) { + _recordTestLogin(forced, e.message); + } + return ConnectionTestResult( + e.authFailed + ? ConnectionOutcome.authFailed + : ConnectionOutcome.unreachable, + e.message, + ); + } + } + + /// A test login counts towards the saved host's status only when it used + /// the saved address and login - not unsaved edits still on the form. + void _recordTestLogin(Instance tested, String? refusal) { + final String? id = widget.instanceId; + final Instance? saved = id == null ? null : ref.read(instanceByIdProvider(id)); + if (id == null || saved == null || !_sameSshLogin(saved, tested)) { + return; + } + final InstanceAuth auth = tested.auth; + ref.read(sshLoginRecordsProvider.notifier).record( + id, + SshLoginRecord( + ok: refusal == null, + at: DateTime.now(), + username: auth is InstanceAuthSsh ? auth.username : '', + message: refusal, + ), + ); + } + + static bool _sameSshLogin(Instance a, Instance b) => + a.localUrl == b.localUrl && + a.externalUrl == b.externalUrl && + a.auth == b.auth; + + List get _dockerHosts => ref + .watch(activeInstancesProvider) + .where((Instance i) => i.kind == ServiceKind.dockerHost) + .toList(); + + Instance? get _selectedDockerHost { + final List hosts = _dockerHosts; + for (final Instance h in hosts) { + if (h.id == _dockerHostId) return h; + } + return hosts.isEmpty ? null : hosts.first; + } + + /// Which container this service runs in, for the in-container shell. + /// Only shown once the profile has a Docker host. + Widget? _containerSection() { + if (_isSsh) { + return null; + } + final List hosts = _dockerHosts; + if (hosts.isEmpty) { + return null; + } + final Instance host = _selectedDockerHost!; + final Instance? saved = _isEdit + ? ref.watch(instanceByIdProvider(widget.instanceId!)) + : null; + return _FormSectionCard( + title: 'Container shell', + icon: Icons.terminal_rounded, + subtitle: 'Open a shell inside this service\'s Docker container, over ' + 'the Docker host\'s SSH connection.', + children: [ + if (hosts.length > 1) ...[ + DropdownMenu( + initialSelection: host.id, + label: const Text('Docker host'), + expandedInsets: EdgeInsets.zero, + dropdownMenuEntries: >[ + for (final Instance h in hosts) + DropdownMenuEntry(value: h.id, label: h.name), + ], + onSelected: (String? id) => + setState(() => _dockerHostId = id ?? _dockerHostId), + ), + const SizedBox(height: Insets.md), + ], + TextFormField( + controller: _dockerContainer, + decoration: InputDecoration( + border: const OutlineInputBorder(), + labelText: 'Container name', + hintText: _kind.name.toLowerCase(), + helperText: 'Leave empty to turn the container shell off.', + suffixIcon: _loadingContainers + ? const Padding( + padding: EdgeInsets.all(14), + child: SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ) + : IconButton( + tooltip: 'Pick a running container', + icon: const Icon(Icons.manage_search_rounded), + onPressed: () => _pickContainer(host), + ), + ), + autocorrect: false, + enableSuggestions: false, + ), + _DockerIssueNote(hostId: host.id), + if (saved != null && saved.dockerContainer.isNotEmpty) ...[ + const SizedBox(height: Insets.md), + OutlinedButton.icon( + onPressed: () => openServiceShell(context, ref, saved), + icon: const Icon(Icons.terminal_rounded), + label: const Text('Open shell'), + ), + ], + ], + ); + } + + /// Lists the host's running containers over the shared SSH connection, + /// likely matches for this service first. + Future _pickContainer(Instance host) async { + final ScaffoldMessengerState messenger = ScaffoldMessenger.of(context); + setState(() => _loadingContainers = true); + List containers; + try { + final List all = + await ref.read(terminalHubProvider).session(host.id).fetchContainers( + host, + (HostKeyPrompt p) => mounted + ? confirmHostKey(context, p) + : Future.value(false), + ); + containers = rankContainersFor(_kind, all); + } on Object catch (e) { + messenger.showSnackBar( + SnackBar(content: Text('Could not list containers: $e')), + ); + return; + } finally { + if (mounted) setState(() => _loadingContainers = false); + } + if (!mounted) return; + if (containers.isEmpty) { + messenger.showSnackBar( + SnackBar(content: Text('No running containers on ${host.name}.')), + ); + return; + } + final DockerContainer? picked = await showModalBottomSheet( + context: context, + useRootNavigator: true, + showDragHandle: true, + isScrollControlled: true, + builder: (BuildContext sheetContext) => SafeArea( + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(sheetContext).height * 0.7, + ), + child: ListView( + shrinkWrap: true, + children: [ + for (final DockerContainer c in containers) + ListTile( + leading: Icon( + containerMatchesKind(c, _kind) + ? Icons.star_rounded + : Icons.inventory_2_outlined, + ), + title: Text(c.name), + subtitle: Text( + c.status.isEmpty ? c.image : '${c.image} - ${c.status}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + onTap: () => Navigator.pop(sheetContext, c), + ), + ], + ), + ), + ), + ); + if (picked != null && mounted) { + setState(() => _dockerContainer.text = picked.name); + } + } + /// At least one of local / external must be a valid URL, and any entered URL must be valid. String? _validateUrlsTogether(String? value) { final bool localOk = _isValidUrl(_localUrl.text); final bool externalOk = _isValidUrl(_externalUrl.text); if (!localOk && !externalOk) { - return 'Enter at least one valid URL (local or external)'; + return _isSsh + ? 'Enter at least one SSH address (local or external)' + : 'Enter at least one valid URL (local or external)'; } if (value != null && value.trim().isNotEmpty && !_isValidUrl(value)) { - return 'Enter a valid URL'; + return _isSsh ? 'Enter host, host:port or ssh://host:port' : 'Enter a valid URL'; } return null; } @@ -1138,11 +1515,56 @@ class _InstanceFormScreenState extends ConsumerState { if (raw.trim().isEmpty) { return false; } + if (_isSsh) { + return SshEndpoint.tryParse(raw) != null; + } final Uri? uri = Uri.tryParse(raw.trim()); return uri != null && uri.hasScheme && uri.host.isNotEmpty; } } +/// The last Docker problem seen on the host, if any. It lives here rather +/// than on the host's status dot because the server itself is reachable. +class _DockerIssueNote extends ConsumerWidget { + const _DockerIssueNote({required this.hostId}); + + final String hostId; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final HostSession session = ref.watch(terminalHubProvider).session(hostId); + return ListenableBuilder( + listenable: session, + builder: (BuildContext context, Widget? _) { + final String? issue = session.dockerIssue; + if (issue == null) { + return const SizedBox.shrink(); + } + final ColorScheme cs = Theme.of(context).colorScheme; + return Padding( + padding: const EdgeInsets.only(top: Insets.sm), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(Icons.warning_amber_rounded, size: 18, color: cs.error), + const SizedBox(width: Insets.sm), + Expanded( + child: Text( + issue, + style: Theme.of(context) + .textTheme + .bodySmall + ?.copyWith(color: cs.error), + ), + ), + ], + ), + ); + }, + ); + } +} + class _FormSectionCard extends StatelessWidget { const _FormSectionCard({ required this.title, diff --git a/app/lib/src/screens/service_detail_screen.dart b/app/lib/src/screens/service_detail_screen.dart index 9ceb6129..d40f2437 100644 --- a/app/lib/src/screens/service_detail_screen.dart +++ b/app/lib/src/screens/service_detail_screen.dart @@ -37,6 +37,7 @@ import 'package:service_aria2/service_aria2.dart'; import 'package:service_cleanuparr/service_cleanuparr.dart'; import 'package:service_slskd/service_slskd.dart'; +import '../terminal/terminal_screen.dart'; import 'dashboard_screen.dart'; /// Routes an instance to its service-specific screen, dispatching on @@ -183,6 +184,16 @@ class _ServiceDetailScreenState extends ConsumerState { ), ); } + if (instance.kind == ServiceKind.dockerHost) { + return TerminalScreen( + key: ValueKey(instance.id), + host: instance, + drawer: ServicesDrawer( + instances: ref.watch(activeInstancesProvider), + profile: ref.watch(activeProfileProvider), + ), + ); + } if (instance.kind == ServiceKind.slskd) { return SlskdHome( instance: instance, @@ -418,6 +429,8 @@ class _ServiceDetailScreenState extends ConsumerState { // Owns its own scaffold, handled above. ServiceKind.slskd => const SizedBox.shrink(), ServiceKind.gotify => GotifyHome(instance: instance), + // Owns its own scaffold, handled above. + ServiceKind.dockerHost => const SizedBox.shrink(), }; } } diff --git a/app/lib/src/terminal/docker_host_status_tile.dart b/app/lib/src/terminal/docker_host_status_tile.dart new file mode 100644 index 00000000..9e911b7a --- /dev/null +++ b/app/lib/src/terminal/docker_host_status_tile.dart @@ -0,0 +1,95 @@ +import 'package:clock/clock.dart'; +import 'package:core_models/core_models.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../health_providers.dart'; +import 'ssh_host_status.dart'; +import 'terminal_hub.dart'; + +/// Says why a Docker host's dot is the colour it is, for its long-press +/// sheet. Docker trouble is deliberately not part of it; see the note. +class DockerHostStatusTile extends ConsumerWidget { + const DockerHostStatusTile({required this.host, super.key}); + + final Instance host; + + @override + Widget build(BuildContext context, WidgetRef ref) { + final ThemeData theme = Theme.of(context); + final ColorScheme cs = theme.colorScheme; + final Health health = + ref.watch(instanceHealthProvider(host.id)).value ?? Health.unknown; + final SshLoginRecord? lastLogin = ref.watch( + sshLoginRecordsProvider + .select((Map m) => m[host.id]), + ); + final HostSession session = ref.watch(terminalHubProvider).session(host.id); + + return ListenableBuilder( + listenable: session, + builder: (BuildContext context, Widget? _) { + final bool connected = session.status == SshStatus.connected; + final Health shown = connected ? Health.ok : health; + final bool refused = lastLogin != null && !lastLogin.ok; + final (IconData icon, Color color) = switch (shown) { + Health.ok => (Icons.check_circle_outline, cs.primary), + Health.warning => (Icons.warning_amber_rounded, cs.tertiary), + Health.error => (Icons.error_outline, cs.error), + Health.unknown => (Icons.help_outline, cs.outline), + }; + return Padding( + padding: const EdgeInsets.fromLTRB( + Insets.lg, + 0, + Insets.lg, + Insets.sm, + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Icon(icon, color: color), + const SizedBox(width: Insets.md), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + describeDockerHost( + health: shown, + session: session.status, + endpoint: session.endpoint, + lastLogin: lastLogin, + now: clock.now(), + ), + style: theme.textTheme.bodyMedium, + ), + if (refused && + !connected && + lastLogin.message != null) ...[ + const SizedBox(height: Insets.xxs), + Text( + lastLogin.message!, + style: theme.textTheme.bodySmall + ?.copyWith(color: cs.tertiary), + ), + ], + const SizedBox(height: Insets.xxs), + Text( + 'This covers the SSH connection only. Docker problems ' + '(not installed, needs sudo) show on each service\'s ' + 'container shell instead.', + style: theme.textTheme.bodySmall + ?.copyWith(color: cs.onSurfaceVariant), + ), + ], + ), + ), + ], + ), + ); + }, + ); + } +} diff --git a/app/lib/src/terminal/docker_shell.dart b/app/lib/src/terminal/docker_shell.dart new file mode 100644 index 00000000..ea09d5c6 --- /dev/null +++ b/app/lib/src/terminal/docker_shell.dart @@ -0,0 +1,148 @@ +import 'package:collection/collection.dart'; +import 'package:core_models/core_models.dart'; +import 'package:flutter/foundation.dart'; + +/// Pure helpers for running Docker commands over SSH. + +/// Quotes [value] as a single POSIX shell word. +String shellQuote(String value) => "'${value.replaceAll("'", r"'\''")}'"; + +/// Wraps [command] in a login shell so the host's profile sets `PATH` - +/// NAS distros (Synology, QNAP) keep `docker` in `/usr/local/bin`, which a +/// non-login exec channel does not see. +String loginShell(String command) => 'sh -lc ${shellQuote(command)}'; + +/// The exec command for an interactive shell inside [container]: bash when +/// the image has it, plain sh otherwise. +String dockerExecShellCommand(String container) { + const String pickShell = + 'if command -v bash >/dev/null 2>&1; then exec bash; else exec sh; fi'; + return loginShell( + 'docker exec -it ${shellQuote(container)} sh -c ${shellQuote(pickShell)}', + ); +} + +/// Lists running containers, one `nameimagestatus` per line. +final String dockerPsCommand = + loginShell(r"docker ps --format '{{.Names}}\t{{.Image}}\t{{.Status}}'"); + +/// A running container as reported by `docker ps`. +@immutable +class DockerContainer { + const DockerContainer({ + required this.name, + required this.image, + this.status = '', + }); + + final String name; + final String image; + final String status; + + @override + bool operator ==(Object other) => + other is DockerContainer && + other.name == name && + other.image == image && + other.status == status; + + @override + int get hashCode => Object.hash(name, image, status); +} + +/// Parses the output of [dockerPsCommand]. +List parseDockerPs(String output) { + final List result = []; + for (final String line in output.split('\n')) { + final List parts = line.trimRight().split('\t'); + if (parts.first.trim().isEmpty) { + continue; + } + result.add( + DockerContainer( + name: parts[0].trim(), + image: parts.length > 1 ? parts[1].trim() : '', + status: parts.length > 2 ? parts[2].trim() : '', + ), + ); + } + return result; +} + +String _normalize(String s) => + s.toLowerCase().replaceAll(RegExp('[^a-z0-9]'), ''); + +/// Whether [container] looks like it runs [kind] (by name or image). +bool containerMatchesKind(DockerContainer container, ServiceKind kind) { + final String token = _normalize(kind.name); + return _normalize(container.name).contains(token) || + _normalize(container.image).contains(token); +} + +/// [containers] with the ones that look like [kind] first, otherwise by name. +List rankContainersFor( + ServiceKind kind, + List containers, +) { + return containers.sorted((DockerContainer a, DockerContainer b) { + final int am = containerMatchesKind(a, kind) ? 0 : 1; + final int bm = containerMatchesKind(b, kind) ? 0 : 1; + return am != bm ? am - bm : a.name.compareTo(b.name); + }); +} + +/// The Docker host [service]'s container runs on: the one it names, else the +/// profile's first Docker host. Null when the profile has none. +Instance? dockerHostFor(Instance service, List instances) { + final List hosts = instances + .where((Instance i) => i.kind == ServiceKind.dockerHost) + .toList(); + if (service.dockerHostId.isNotEmpty) { + final Instance? named = + hosts.firstWhereOrNull((Instance h) => h.id == service.dockerHostId); + if (named != null) { + return named; + } + } + return hosts.firstOrNull; +} + +/// Plain words for a failed `docker` call, from its exit code and message. +String dockerIssueFor(int exitCode, String message) { + final String m = message.toLowerCase(); + if (exitCode == 127 || m.contains('command not found')) { + return 'Docker was not found on the host'; + } + if (m.contains('permission denied') || exitCode == 126) { + return 'This SSH user is not allowed to use Docker (needs sudo or ' + 'the docker group)'; + } + if (m.contains('cannot connect to the docker daemon') || + m.contains('is the docker daemon running')) { + return 'Docker is installed but its daemon is not running'; + } + return message.isEmpty ? 'Docker failed (exit $exitCode)' : message; +} + +/// Applies the on-screen Ctrl / Alt modifiers to one chunk of terminal input, +/// the way a hardware keyboard would encode them. +String applyModifiers(String data, {bool ctrl = false, bool alt = false}) { + String out = data; + if (ctrl && out.length == 1) { + final int c = out.codeUnitAt(0); + if (c >= 0x61 && c <= 0x7a) { + out = String.fromCharCode(c - 0x60); + } else if (c >= 0x40 && c <= 0x5f) { + // @ A-Z [ \ ] ^ _ + out = String.fromCharCode(c - 0x40); + } else if (c == 0x20) { + out = '\x00'; + } else if (c == 0x3f) { + out = '\x7f'; + } + } + if (alt && out.isNotEmpty) { + out = '\x1b$out'; + } + return out; +} diff --git a/app/lib/src/terminal/ssh_connector.dart b/app/lib/src/terminal/ssh_connector.dart new file mode 100644 index 00000000..dc5acc65 --- /dev/null +++ b/app/lib/src/terminal/ssh_connector.dart @@ -0,0 +1,176 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:core_models/core_models.dart'; +import 'package:core_networking/core_networking.dart'; +import 'package:core_storage/core_storage.dart'; +import 'package:dartssh2/dartssh2.dart'; + +/// A server key the user has not seen before, or one that changed. +class HostKeyPrompt { + const HostKeyPrompt({ + required this.endpoint, + required this.entry, + this.previous, + }); + + final SshEndpoint endpoint; + + /// ` ` as presented by the server. + final String entry; + + /// The pinned entry when the key changed; null on first contact. + final String? previous; + + bool get changed => previous != null; +} + +/// Asks the user whether to trust a host key. Returns true to trust it. +typedef HostKeyPrompter = Future Function(HostKeyPrompt prompt); + +/// Trust-on-first-use pins of SSH host keys, like `~/.ssh/known_hosts`. +/// +/// Kept in the settings box keyed by `host:port` rather than on the instance, +/// so the pin follows the server and survives editing or re-adding it. +class KnownHostsStore { + KnownHostsStore(this._box); + + final Box _box; + + static String _key(SshEndpoint e) => 'sshKnownHost:$e'; + + String? lookup(SshEndpoint endpoint) => _box.get(_key(endpoint)); + + Future remember(SshEndpoint endpoint, String entry) => + _box.put(_key(endpoint), entry); +} + +/// Why an SSH connection could not be made, worded for the user. +class SshConnectException implements Exception { + const SshConnectException(this.message, {this.authFailed = false}); + + final String message; + + /// The server was reached but refused the login (or its key). + final bool authFailed; + + @override + String toString() => message; +} + +/// Connects and authenticates to [host] (a [ServiceKind.dockerHost]), +/// trying its endpoints in [UrlMode] order. Only an unreachable endpoint +/// falls through to the next one; a refused login or host key does not. +Future<({SSHClient client, SshEndpoint endpoint})> connectSsh( + Instance host, { + required KnownHostsStore knownHosts, + required HostKeyPrompter onHostKey, + void Function(String stage)? onProgress, + Duration timeout = const Duration(seconds: 8), + Duration fallbackTimeout = const Duration(seconds: 3), +}) async { + final InstanceAuth auth = host.auth; + if (auth is! InstanceAuthSsh || auth.username.trim().isEmpty) { + throw const SshConnectException('No SSH username is set for this host.'); + } + final List endpoints = sshEndpointsFor(host); + if (endpoints.isEmpty) { + throw const SshConnectException('No SSH address is set for this host.'); + } + + List? identities; + if (auth.privateKey.trim().isNotEmpty) { + try { + identities = SSHKeyPair.fromPem( + auth.privateKey.trim(), + auth.passphrase.isEmpty ? null : auth.passphrase, + ); + } on Object catch (e) { + throw SshConnectException( + e is SSHKeyDecryptError || SSHKeyPair.isEncryptedPem(auth.privateKey) + ? 'Could not decrypt the private key - check the passphrase.' + : 'Could not read the private key.', + authFailed: true, + ); + } + } + + Object? lastError; + for (final SshEndpoint endpoint in endpoints) { + onProgress?.call('Connecting to $endpoint...'); + // A LAN address that is not answering (away from home) should not hold + // up the external one for the full timeout. + final bool hasFallback = endpoint != endpoints.last; + final SSHSocket socket; + try { + socket = await SSHSocket.connect( + endpoint.host, + endpoint.port, + timeout: hasFallback ? fallbackTimeout : timeout, + ); + } on Object catch (e) { + lastError = e; + continue; + } + + onProgress?.call('Securing the connection...'); + bool hostKeyRejected = false; + final SSHClient client = SSHClient( + socket, + username: auth.username.trim(), + identities: identities, + onPasswordRequest: + auth.password.isEmpty ? null : () => auth.password, + onUserInfoRequest: auth.password.isEmpty + ? null + : (SSHUserInfoRequest request) => request.prompts + .map((SSHUserInfoPrompt _) => auth.password) + .toList(), + onVerifyHostKey: (String type, Uint8List fingerprint) async { + final String entry = '$type ${utf8.decode(fingerprint)}'; + final String? pinned = knownHosts.lookup(endpoint); + if (pinned == entry) { + onProgress?.call('Logging in as ${auth.username.trim()}...'); + return true; + } + onProgress?.call('Waiting for you to check the host key...'); + final bool trusted = await onHostKey( + HostKeyPrompt(endpoint: endpoint, entry: entry, previous: pinned), + ); + if (trusted) { + await knownHosts.remember(endpoint, entry); + onProgress?.call('Logging in as ${auth.username.trim()}...'); + } else { + hostKeyRejected = true; + } + return trusted; + }, + keepAliveInterval: const Duration(seconds: 15), + ); + try { + await client.authenticated; + return (client: client, endpoint: endpoint); + } on Object catch (e) { + client.close(); + if (hostKeyRejected) { + throw const SshConnectException( + 'The server\'s host key was not trusted.', + authFailed: true, + ); + } + if (e is SSHAuthError) { + throw SshConnectException( + 'Reachable, but the server refused the login for ' + '"${auth.username.trim()}".', + authFailed: true, + ); + } + throw SshConnectException('SSH handshake with $endpoint failed: $e'); + } + } + throw SshConnectException( + 'Could not reach ${endpoints.join(' or ')}' + '${lastError == null ? '' : ' ($lastError)'}.', + ); +} diff --git a/app/lib/src/terminal/ssh_host_status.dart b/app/lib/src/terminal/ssh_host_status.dart new file mode 100644 index 00000000..cded3a17 --- /dev/null +++ b/app/lib/src/terminal/ssh_host_status.dart @@ -0,0 +1,142 @@ +import 'dart:convert'; + +import 'package:core_models/core_models.dart'; +import 'package:core_storage/core_storage.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; + +import '../preferences.dart'; +import 'terminal_hub.dart'; + +/// The outcome of the last real login to a Docker host - from the terminal, +/// the container picker or Test connection. Only real logins count: the +/// health probe never logs in, so this is how a refused password reaches the +/// status dot without the probe hammering the server with attempts. +@immutable +class SshLoginRecord { + const SshLoginRecord({ + required this.ok, + required this.at, + required this.username, + this.message, + }); + + factory SshLoginRecord.fromJson(Map json) => SshLoginRecord( + ok: json['ok'] == true, + at: DateTime.tryParse(json['at'] as String? ?? '') ?? + DateTime.fromMillisecondsSinceEpoch(0), + username: json['username'] as String? ?? '', + message: json['message'] as String?, + ); + + final bool ok; + final DateTime at; + final String username; + + /// Why the login was refused; null when it worked. + final String? message; + + Map toJson() => { + 'ok': ok, + 'at': at.toIso8601String(), + 'username': username, + if (message != null) 'message': message, + }; +} + +/// Last login per Docker host id, kept in the settings box so a refused +/// login still shows after a restart. Holds no secrets. +final NotifierProvider> + sshLoginRecordsProvider = + NotifierProvider>( + SshLoginRecords.new, +); + +class SshLoginRecords extends Notifier> { + static const String _prefix = 'sshLastLogin:'; + + @override + Map build() { + final Map out = {}; + final Box box = ref.read(settingsBoxProvider); + for (final dynamic key in box.keys) { + final String? raw = key is String && key.startsWith(_prefix) + ? box.get(key) + : null; + if (raw != null) { + try { + out[(key as String).substring(_prefix.length)] = + SshLoginRecord.fromJson(jsonDecode(raw) as Map); + } on Object { + // A record that does not parse is just forgotten. + } + } + } + return out; + } + + Future record(String hostId, SshLoginRecord login) async { + state = {...state, hostId: login}; + await ref + .read(settingsBoxProvider) + .put('$_prefix$hostId', jsonEncode(login.toJson())); + } + + /// Forgets the host's last login, after its address or login is edited. + Future clear(String hostId) async { + if (!state.containsKey(hostId)) return; + state = Map.of(state)..remove(hostId); + await ref.read(settingsBoxProvider).delete('$_prefix$hostId'); + } +} + +/// The dot for a Docker host, from the SSH banner probe and what the app +/// knows from real logins. +/// +/// A server that answers but refused the last login is amber, like a service +/// whose API key is rejected; otherwise the probe decides. (An open terminal +/// session is green before this is asked.) +Health dockerHostHealth({ + required Health probe, + SshLoginRecord? lastLogin, +}) { + if (probe == Health.ok && lastLogin != null && !lastLogin.ok) { + return Health.warning; + } + return probe; +} + +/// One line saying why a Docker host's dot is the colour it is, from the +/// dot's own [health] (see [dockerHostHealth]) and the last login. +String describeDockerHost({ + required Health health, + required SshStatus session, + SshEndpoint? endpoint, + SshLoginRecord? lastLogin, + required DateTime now, +}) { + if (session == SshStatus.connected) { + return endpoint == null ? 'Connected now' : 'Connected now to $endpoint'; + } + final bool refused = lastLogin != null && !lastLogin.ok; + return switch (health) { + Health.ok => lastLogin == null + ? 'SSH answering - not logged in yet' + : 'SSH answering - last login OK ${timeAgo(lastLogin.at, now)}', + Health.warning when refused => + 'SSH answering - login refused for ${lastLogin.username} ' + '${timeAgo(lastLogin.at, now)}', + Health.warning => + 'Something answers on that port, but it is not an SSH server', + Health.error => 'Not reachable', + Health.unknown => 'Not checked yet', + }; +} + +String timeAgo(DateTime at, DateTime now) { + final Duration d = now.difference(at); + if (d.inMinutes < 1) return 'just now'; + if (d.inHours < 1) return '${d.inMinutes} min ago'; + if (d.inDays < 1) return '${d.inHours} h ago'; + return '${d.inDays} d ago'; +} diff --git a/app/lib/src/terminal/terminal_hub.dart b/app/lib/src/terminal/terminal_hub.dart new file mode 100644 index 00000000..2a133094 --- /dev/null +++ b/app/lib/src/terminal/terminal_hub.dart @@ -0,0 +1,672 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:collection/collection.dart'; +import 'package:core_models/core_models.dart'; +import 'package:core_profile/core_profile.dart'; +import 'package:dartssh2/dartssh2.dart'; +import 'package:flutter/widgets.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:xterm/xterm.dart'; + +import '../preferences.dart'; +import 'docker_shell.dart'; +import 'ssh_connector.dart'; +import 'ssh_host_status.dart'; + +enum SshStatus { disconnected, connecting, connected, failed } + +/// One terminal tab: the host's own shell, or a shell inside a service's +/// container. Every tab is a channel on its host's single SSH connection. +class TerminalTab { + TerminalTab._({ + required this.id, + required this.title, + required this.container, + }) : terminal = Terminal(maxLines: 5000); + + /// Id of the host shell tab; service tabs use the service instance id. + static const String hostTabId = '__host__'; + + final String id; + String title; + + /// The container the tab execs into; null for the host shell. + String? container; + + final Terminal terminal; + + /// Selection state for copy, kept per tab so it matches the buffer. + final TerminalController controller = TerminalController(); + + SSHSession? _session; + StreamSubscription? _stdout; + StreamSubscription? _stderr; + + /// A channel is being opened. Guards against starting the tab twice while + /// `execute` / `shell` is still in flight. + bool _starting = false; + + /// The remote process ended on its own (`exit`, Ctrl+D). Such a tab is not + /// restarted behind the user's back - only by Enter or by opening it again. + bool finished = false; + + bool get isHost => id == hostTabId; + bool get isRunning => _session != null; + bool get isStarting => _starting; + + /// Running, starting, or waiting to be started on the next connect. + bool get _wantsShell => isRunning || _starting || !finished; + + void _detach() { + _stdout?.cancel(); + _stderr?.cancel(); + _stdout = null; + _stderr = null; + _session = null; + } +} + +/// The shared SSH connection to one Docker host and the tabs on it. +/// +/// Lives for the app session (owned by [TerminalHub]), so leaving the +/// terminal screen keeps shells and scrollback alive, Termux-style. The +/// connection itself is only held while some shell needs it: once the last +/// one exits or is closed, it is closed too. +class HostSession extends ChangeNotifier { + HostSession(this.hostId, this._knownHosts); + + final String hostId; + final KnownHostsStore _knownHosts; + + SSHClient? _client; + Future? _connecting; + bool _disposed = false; + + /// Last host / prompter used, so opening a tab or pressing Enter on a + /// finished one can reconnect without the screen's help. + Instance? _host; + HostKeyPrompter? _onHostKey; + + /// The user chose Disconnect; don't reconnect just because the screen + /// was opened again. + bool _manuallyDisconnected = false; + + /// Closed by the app going to the background; the screen reconnects on + /// resume. + bool suspended = false; + + /// One-off uses of the connection outside any tab (`docker ps`). + int _busy = 0; + + SshStatus status = SshStatus.disconnected; + + /// Why the session is not connected (error or explanation), for the banner. + String? error; + + /// What the connection attempt is doing right now, for the loading UI. + String? stage; + + /// Called with the outcome of every real login (not unreachable hosts - + /// reachability is the health probe's business). + void Function(SshLoginRecord login)? onLogin; + + /// The last Docker problem seen on this host (`docker ps` failing, or + /// `docker exec` not found / not allowed). Kept apart from the connection + /// status: the server itself is fine. + String? dockerIssue; + SshEndpoint? endpoint; + + final List tabs = []; + int _active = 0; + + /// One-shot on-screen modifiers, cleared after the next key. + bool ctrl = false; + bool alt = false; + + TerminalTab? get activeTab => + tabs.isEmpty ? null : tabs[_active.clamp(0, tabs.length - 1)]; + + int get activeIndex => tabs.isEmpty ? 0 : _active.clamp(0, tabs.length - 1); + + /// Whether opening the terminal screen should connect by itself. + bool get shouldAutoConnect => + status != SshStatus.connected && + status != SshStatus.failed && + !_manuallyDisconnected && + (tabs.isEmpty || tabs.any((TerminalTab t) => t._wantsShell)); + + void select(int index) { + if (index >= 0 && index < tabs.length && index != _active) { + _active = index; + _notify(); + } + } + + void toggleCtrl() { + ctrl = !ctrl; + _notify(); + } + + void toggleAlt() { + alt = !alt; + _notify(); + } + + /// Returns and clears the pending modifiers, for keys the screen encodes + /// itself (arrows, Esc, ...). + ({bool ctrl, bool alt}) takeModifiers() { + final ({bool ctrl, bool alt}) mods = (ctrl: ctrl, alt: alt); + if (ctrl || alt) { + ctrl = false; + alt = false; + _notify(); + } + return mods; + } + + /// Connects (once; concurrent callers share the attempt) and starts every + /// tab that wants a shell and is not already running or starting. + Future connect(Instance host, HostKeyPrompter onHostKey) { + _host = host; + _onHostKey = onHostKey; + _manuallyDisconnected = false; + if (status == SshStatus.connected) { + return _startPending(); + } + return _connecting ??= _connect(host, onHostKey).whenComplete(() { + _connecting = null; + }); + } + + Future _connect(Instance host, HostKeyPrompter onHostKey) async { + status = SshStatus.connecting; + error = null; + suspended = false; + stage = 'Connecting...'; + _notify(); + try { + final ({SSHClient client, SshEndpoint endpoint}) result = await connectSsh( + host, + knownHosts: _knownHosts, + onHostKey: onHostKey, + onProgress: (String s) { + stage = s; + _notify(); + }, + ); + if (_disposed) { + result.client.close(); + return; + } + _client = result.client; + endpoint = result.endpoint; + status = SshStatus.connected; + onLogin?.call( + SshLoginRecord(ok: true, at: DateTime.now(), username: _username(host)), + ); + stage = null; + final SSHClient client = result.client; + unawaited( + client.done.then((_) {}, onError: (Object _) {}).whenComplete( + () => _onClosed(client), + ), + ); + _notify(); + await _startPending(); + } on Object catch (e) { + status = SshStatus.failed; + stage = null; + error = e.toString(); + if (e is SshConnectException && e.authFailed) { + onLogin?.call( + SshLoginRecord( + ok: false, + at: DateTime.now(), + username: _username(host), + message: e.message, + ), + ); + } + _notify(); + } + } + + static String _username(Instance host) => switch (host.auth) { + InstanceAuthSsh(:final String username) => username.trim(), + _ => '', + }; + + void _onClosed(SSHClient client) { + if (!identical(client, _client)) { + return; + } + _client = null; + if (status == SshStatus.connected) { + status = SshStatus.disconnected; + error = 'Connection lost.'; + } + for (final TerminalTab tab in tabs) { + if (tab.isRunning) { + tab._detach(); + tab.terminal.write('\r\n\x1b[31m[Connection lost]\x1b[0m\r\n'); + } + } + _notify(); + } + + /// Closes the connection at the user's request; tabs and scrollback stay. + void disconnect() { + _manuallyDisconnected = true; + _close(null); + } + + /// Closes the connection because the app went to the background; the + /// screen reconnects on resume and running tabs start again. + void suspend(String reason) { + if (_client == null) return; + for (final TerminalTab tab in tabs) { + if (tab.isRunning) { + tab.terminal.write('\r\n\x1b[33m[$reason]\x1b[0m\r\n'); + } + } + _close(reason); + suspended = true; + _notify(); + } + + void _close(String? reason) { + final SSHClient? client = _client; + _client = null; + status = SshStatus.disconnected; + error = reason; + stage = null; + for (final TerminalTab tab in tabs) { + tab._session?.close(); + tab._detach(); + } + client?.close(); + _notify(); + } + + /// Closes the connection once nothing uses it any more: every tab has + /// exited or been closed, and no `docker ps` is in flight. + void _closeIfIdle() { + if (_client == null || _busy > 0) return; + if (tabs.any((TerminalTab t) => t.isRunning || t.isStarting)) return; + _close( + tabs.isEmpty + ? 'No shells open, so the SSH connection was closed.' + : 'All shells exited, so the SSH connection was closed.', + ); + } + + /// Focuses the host shell, creating or restarting it. + TerminalTab openHostTab(Instance host) => + _open(TerminalTab.hostTabId, host.name, null); + + /// Focuses [service]'s container shell, reusing its tab when it exists. + TerminalTab openServiceTab(Instance service) => + _open(service.id, service.name, service.dockerContainer.trim()); + + TerminalTab _open(String id, String title, String? container) { + TerminalTab? tab = tabs.firstWhereOrNull((TerminalTab t) => t.id == id); + if (tab == null) { + tab = _newTab(id, title, container); + tabs.add(tab); + } else { + tab.title = title; + if (tab.container != container && tab.isRunning) { + // The service now points at another container; reopen there. + tab._session?.close(); + tab._detach(); + } + tab.container = container; + } + tab.finished = false; + _active = tabs.indexOf(tab); + _notify(); + _ensureStarted(tab); + return tab; + } + + /// Starts [tab] now if connected, otherwise reconnects (when the screen + /// has connected before) and lets the connect start it. + void _ensureStarted(TerminalTab tab) { + if (status == SshStatus.connected) { + unawaited(_start(tab)); + } else if (status != SshStatus.connecting && + _host != null && + _onHostKey != null) { + unawaited(connect(_host!, _onHostKey!)); + } + } + + /// Marks the active tab as wanted again (after `exit`), for the Connect + /// button. + void reviveActive() { + activeTab?.finished = false; + } + + void closeTab(TerminalTab tab) { + tab._session?.close(); + tab._detach(); + final int index = tabs.indexOf(tab); + tabs.remove(tab); + if (_active >= index && _active > 0) { + _active--; + } + _notify(); + _closeIfIdle(); + } + + /// Connects if needed and lists the host's running containers, keeping + /// the connection busy throughout so it is not closed as idle mid-way. + Future> fetchContainers( + Instance host, + HostKeyPrompter onHostKey, + ) async { + _busy++; + try { + await connect(host, onHostKey); + if (status != SshStatus.connected) { + throw StateError(error ?? 'Could not connect to ${host.name}'); + } + return await listContainers(); + } finally { + _busy--; + _closeIfIdle(); + } + } + + /// Runs `docker ps` on the host over the shared connection. + Future> listContainers() async { + final SSHClient? client = _client; + if (client == null) { + throw StateError('Not connected'); + } + _busy++; + try { + final SSHRunResult result = await client.runWithResult(dockerPsCommand); + final String out = utf8.decode(result.stdout, allowMalformed: true); + if (result.exitCode != null && result.exitCode != 0) { + final String err = utf8.decode(result.stderr, allowMalformed: true); + final String reason = + (err.trim().isEmpty ? out : err).trim().split('\n').first; + _setDockerIssue(dockerIssueFor(result.exitCode!, reason)); + throw StateError(reason); + } + _setDockerIssue(null); + return parseDockerPs(out); + } finally { + _busy--; + _closeIfIdle(); + } + } + + TerminalTab _newTab(String id, String title, String? container) { + final TerminalTab tab = + TerminalTab._(id: id, title: title, container: container); + tab.terminal.onOutput = (String data) { + if (!tab.isRunning) { + // Termux-style: Enter on a finished tab starts it again. + if (!tab.isStarting && data.contains('\r')) { + tab.finished = false; + _ensureStarted(tab); + } + return; + } + final ({bool ctrl, bool alt}) mods = takeModifiers(); + final String out = applyModifiers(data, ctrl: mods.ctrl, alt: mods.alt); + tab._session?.write(utf8.encode(out)); + }; + tab.terminal.onResize = (int w, int h, int pw, int ph) { + tab._session?.resizeTerminal(w, h, pw, ph); + }; + return tab; + } + + Future _startPending() async { + for (final TerminalTab tab in List.of(tabs)) { + if (!tab.finished) { + await _start(tab); + } + } + _closeIfIdle(); + } + + Future _start(TerminalTab tab) async { + final SSHClient? client = _client; + if (client == null || tab.isRunning || tab.isStarting) { + return; + } + final Terminal term = tab.terminal; + final String? container = tab.container; + if (container != null && container.isEmpty) { + term.write( + '\r\n\x1b[33m[No container set for ${tab.title}. Edit the service ' + 'to pick one.]\x1b[0m\r\n', + ); + tab.finished = true; + _closeIfIdle(); + return; + } + tab._starting = true; + _notify(); + final SSHPtyConfig pty = SSHPtyConfig( + width: term.viewWidth, + height: term.viewHeight, + ); + final SSHSession session; + try { + if (container == null) { + session = await client.shell(pty: pty); + } else { + term.write('\x1b[2m[docker exec into $container]\x1b[0m\r\n'); + session = await client.execute( + dockerExecShellCommand(container), + pty: pty, + ); + } + } on Object catch (e) { + tab._starting = false; + if (identical(client, _client)) { + term.write('\r\n\x1b[31m[Could not open a shell: $e]\x1b[0m\r\n'); + tab.finished = true; + } + _notify(); + _closeIfIdle(); + return; + } + tab._starting = false; + if (!tabs.contains(tab) || _disposed || !identical(client, _client)) { + session.close(); + _notify(); + return; + } + tab._session = session; + final DateTime startedAt = DateTime.now(); + const Utf8Decoder decoder = Utf8Decoder(allowMalformed: true); + tab._stdout = session.stdout.cast>().transform(decoder).listen( + term.write, + ); + tab._stderr = session.stderr.cast>().transform(decoder).listen( + term.write, + ); + unawaited( + session.done.then((_) {}, onError: (Object _) {}).whenComplete(() { + if (!identical(tab._session, session)) { + return; + } + tab._detach(); + if (identical(client, _client)) { + // The remote process ended by itself (exit / Ctrl+D). + tab.finished = true; + final int? code = session.exitCode; + // `docker exec` that dies at once with 126/127 never got a shell: + // docker is missing or not allowed. Later, the same codes are just + // the user's last command inside the container. + if (tab.container != null && + code != null && + DateTime.now().difference(startedAt) < + const Duration(seconds: 3)) { + if (code == 126 || code == 127) { + _setDockerIssue(dockerIssueFor(code, '')); + } + } else if (tab.container != null) { + _setDockerIssue(null); + } + term.write( + '\r\n\x1b[2m[Process completed${code == null ? '' : ' ($code)'}' + ' - press Enter to restart]\x1b[0m\r\n', + ); + } + _notify(); + _closeIfIdle(); + }), + ); + _notify(); + } + + void _setDockerIssue(String? issue) { + if (dockerIssue != issue) { + dockerIssue = issue; + _notify(); + } + } + + void _notify() { + if (!_disposed) { + notifyListeners(); + } + } + + @override + void dispose() { + _disposed = true; + _close(null); + super.dispose(); + } +} + +/// Owns one [HostSession] per Docker host for the app's lifetime, and closes +/// their connections when the app is closed or left in the background. +class TerminalHub { + TerminalHub(this._knownHosts, {DateTime Function()? now, this.onLogin}) + : _now = now ?? DateTime.now; + + /// Receives every host's login outcomes (see [HostSession.onLogin]). + final void Function(String hostId, SshLoginRecord login)? onLogin; + + /// How long the app may sit in the background before SSH connections are + /// closed. Long enough to switch apps to copy something, short enough not + /// to leave sessions open on the server indefinitely. + static const Duration backgroundGrace = Duration(minutes: 5); + + final KnownHostsStore _knownHosts; + final DateTime Function() _now; + final Map _sessions = {}; + final Map _hostConnections = {}; + + Timer? _backgroundTimer; + DateTime? _backgroundedAt; + + KnownHostsStore get knownHosts => _knownHosts; + + HostSession session(String hostId) => _sessions.putIfAbsent( + hostId, + () => HostSession(hostId, _knownHosts) + ..onLogin = (SshLoginRecord login) => onLogin?.call(hostId, login), + ); + + /// Closes sessions whose host left the active profile, or whose address + /// or login was edited - their connection was made with the old details. + /// A rename keeps the session. + void syncHosts(Iterable hosts) { + final Map next = { + for (final Instance h in hosts) + if (h.kind == ServiceKind.dockerHost) + h.id: (h.localUrl, h.externalUrl, h.urlMode, h.auth), + }; + final List stale = _sessions.keys + .where( + (String id) => + !next.containsKey(id) || + (_hostConnections.containsKey(id) && + _hostConnections[id] != next[id]), + ) + .toList(); + for (final String id in stale) { + _sessions.remove(id)?.dispose(); + } + _hostConnections + ..clear() + ..addAll(next); + } + + void handleLifecycle(AppLifecycleState state) { + switch (state) { + case AppLifecycleState.resumed: + _backgroundTimer?.cancel(); + _backgroundTimer = null; + // The timer cannot fire while Android has the process frozen, so + // check the wall clock as well. + final DateTime? since = _backgroundedAt; + _backgroundedAt = null; + if (since != null && _now().difference(since) >= backgroundGrace) { + _suspendAll(); + } + case AppLifecycleState.hidden || AppLifecycleState.paused: + _backgroundedAt ??= _now(); + _backgroundTimer ??= Timer(backgroundGrace, _suspendAll); + case AppLifecycleState.detached: + _backgroundTimer?.cancel(); + _backgroundTimer = null; + for (final HostSession s in _sessions.values) { + s.suspend('App closed'); + } + case AppLifecycleState.inactive: + break; + } + } + + void _suspendAll() { + _backgroundTimer = null; + for (final HostSession s in _sessions.values) { + s.suspend( + 'Disconnected after ${backgroundGrace.inMinutes} minutes in the ' + 'background', + ); + } + } + + void dispose() { + _backgroundTimer?.cancel(); + for (final HostSession s in _sessions.values) { + s.dispose(); + } + _sessions.clear(); + } +} + +final Provider terminalHubProvider = Provider(( + Ref ref, +) { + final TerminalHub hub = TerminalHub( + KnownHostsStore(ref.watch(settingsBoxProvider)), + onLogin: (String hostId, SshLoginRecord login) => + ref.read(sshLoginRecordsProvider.notifier).record(hostId, login), + ); + final AppLifecycleListener lifecycle = + AppLifecycleListener(onStateChange: hub.handleLifecycle); + hub.syncHosts(ref.read(activeInstancesProvider)); + ref.listen>( + activeInstancesProvider, + (_, List next) => hub.syncHosts(next), + ); + ref.onDispose(() { + lifecycle.dispose(); + hub.dispose(); + }); + return hub; +}); diff --git a/app/lib/src/terminal/terminal_screen.dart b/app/lib/src/terminal/terminal_screen.dart new file mode 100644 index 00000000..64a7ec67 --- /dev/null +++ b/app/lib/src/terminal/terminal_screen.dart @@ -0,0 +1,644 @@ +import 'dart:async'; + +import 'package:core_models/core_models.dart'; +import 'package:core_profile/core_profile.dart'; +import 'package:core_router/core_router.dart'; +import 'package:core_ui/core_ui.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:go_router/go_router.dart'; +import 'package:xterm/xterm.dart'; + +import 'docker_shell.dart'; +import 'ssh_connector.dart'; +import 'terminal_hub.dart'; + +/// Asks whether to trust an SSH host key, warning loudly when it changed. +Future confirmHostKey(BuildContext context, HostKeyPrompt prompt) async { + final ThemeData theme = Theme.of(context); + final bool? trusted = await showDialog( + context: context, + barrierDismissible: false, + builder: (BuildContext context) => AlertDialog( + icon: Icon( + prompt.changed ? Icons.gpp_bad_outlined : Icons.key_outlined, + color: prompt.changed ? theme.colorScheme.error : null, + ), + title: Text(prompt.changed ? 'Host key changed' : 'Trust this host?'), + content: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + prompt.changed + ? 'The key presented by ${prompt.endpoint} does not match ' + 'the one saved earlier. This can mean the server was ' + 'reinstalled - or that someone is intercepting the ' + 'connection.' + : 'First connection to ${prompt.endpoint}. Check the ' + 'fingerprint matches the server before trusting it.', + ), + const SizedBox(height: Insets.md), + if (prompt.changed) ...[ + Text('Saved', style: theme.textTheme.labelMedium), + SelectableText( + prompt.previous!, + style: const TextStyle(fontFamily: 'JetBrainsMono Nerd Font'), + ), + const SizedBox(height: Insets.sm), + Text('Presented', style: theme.textTheme.labelMedium), + ], + SelectableText( + prompt.entry, + style: const TextStyle(fontFamily: 'JetBrainsMono Nerd Font'), + ), + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.of(context).pop(false), + child: const Text('Cancel'), + ), + FilledButton( + style: prompt.changed + ? FilledButton.styleFrom( + backgroundColor: theme.colorScheme.error, + foregroundColor: theme.colorScheme.onError, + ) + : null, + onPressed: () => Navigator.of(context).pop(true), + child: Text(prompt.changed ? 'Trust new key' : 'Trust'), + ), + ], + ), + ); + return trusted ?? false; +} + +/// Opens (or focuses) [service]'s container shell on its Docker host's +/// shared connection and navigates to that host's terminal. +/// +/// [beforeNavigate] runs after the router is captured, for callers that +/// must close a drawer or sheet first. +void openServiceShell( + BuildContext context, + WidgetRef ref, + Instance service, { + VoidCallback? beforeNavigate, +}) { + final GoRouter router = GoRouter.of(context); + final Instance? host = + dockerHostFor(service, ref.read(activeInstancesProvider)); + if (host == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Add a Docker Host service first to open shells.'), + ), + ); + return; + } + ref.read(terminalHubProvider).session(host.id).openServiceTab(service); + beforeNavigate?.call(); + router.go(AtriumRoutes.servicePath(host.kind.name, host.id)); +} + +/// The Docker host's terminal: a tab per shell, all multiplexed over one SSH +/// connection that outlives this screen. +class TerminalScreen extends ConsumerStatefulWidget { + const TerminalScreen({required this.host, required this.drawer, super.key}); + + final Instance host; + final Widget drawer; + + @override + ConsumerState createState() => _TerminalScreenState(); +} + +class _TerminalScreenState extends ConsumerState { + final GlobalKey _scaffoldKey = GlobalKey(); + double _fontSize = 13; + late final AppLifecycleListener _lifecycle; + + HostSession get _session => + ref.read(terminalHubProvider).session(widget.host.id); + + @override + void initState() { + super.initState(); + // After the hub's own lifecycle handling, which may just have closed the + // connection for being in the background too long. + _lifecycle = AppLifecycleListener( + onResume: () => WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _session.suspended) { + _connect(); + } + }), + ); + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _session.shouldAutoConnect) { + _connect(); + } + }); + } + + @override + void didUpdateWidget(TerminalScreen oldWidget) { + super.didUpdateWidget(oldWidget); + // An edited address or login replaces the session (see + // TerminalHub.syncHosts); bring the fresh one up like on first open. + if (oldWidget.host != widget.host) { + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _session.shouldAutoConnect) { + _connect(); + } + }); + } + } + + @override + void dispose() { + _lifecycle.dispose(); + super.dispose(); + } + + void _connect() { + final HostSession session = _session; + if (session.tabs.isEmpty) { + session.openHostTab(widget.host); + } else { + session.reviveActive(); + } + unawaited( + session.connect( + widget.host, + (HostKeyPrompt p) => + mounted ? confirmHostKey(context, p) : Future.value(false), + ), + ); + } + + @override + Widget build(BuildContext context) { + final HostSession session = + ref.watch(terminalHubProvider).session(widget.host.id); + return PopScope( + canPop: false, + onPopInvokedWithResult: (bool didPop, Object? result) { + if (didPop) return; + final ScaffoldState? scaffold = _scaffoldKey.currentState; + if (scaffold?.isDrawerOpen ?? false) { + scaffold!.closeDrawer(); + return; + } + context.goNamed(AtriumRoutes.dashboardName); + }, + child: ListenableBuilder( + listenable: session, + builder: (BuildContext context, Widget? _) => Scaffold( + key: _scaffoldKey, + drawerEdgeDragWidth: 24, + drawer: widget.drawer, + appBar: AppBar( + leading: Builder( + builder: (BuildContext context) => IconButton( + icon: const Icon(Icons.menu), + onPressed: () => Scaffold.of(context).openDrawer(), + ), + ), + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(widget.host.name, overflow: TextOverflow.ellipsis), + Text( + _statusLabel(session), + style: Theme.of(context).textTheme.labelSmall, + ), + ], + ), + actions: [ + IconButton( + tooltip: 'Open shell', + icon: const Icon(Icons.add), + onPressed: () => _showOpenMenu(session), + ), + PopupMenuButton( + onSelected: (String v) => _onMenu(v, session), + itemBuilder: (BuildContext context) => + >[ + const PopupMenuItem( + value: 'paste', + child: Text('Paste'), + ), + const PopupMenuItem( + value: 'copy', + child: Text('Copy selection'), + ), + const PopupMenuItem( + value: 'bigger', + child: Text('Larger text'), + ), + const PopupMenuItem( + value: 'smaller', + child: Text('Smaller text'), + ), + const PopupMenuDivider(), + if (session.status == SshStatus.connected) + const PopupMenuItem( + value: 'disconnect', + child: Text('Disconnect'), + ) + else + const PopupMenuItem( + value: 'connect', + child: Text('Connect'), + ), + ], + ), + ], + ), + body: SafeArea( + top: false, + child: Column( + children: [ + if (session.status != SshStatus.connected) + _StatusBanner(session: session, onRetry: _connect), + if (session.tabs.isNotEmpty) _TabStrip(session: session), + Expanded(child: _body(session)), + _ExtraKeys(session: session), + ], + ), + ), + ), + ), + ); + } + + Widget _body(HostSession session) { + final TerminalTab? tab = session.activeTab; + if (tab == null) { + return EmptyView( + icon: Icons.terminal_rounded, + title: 'No shells open', + message: 'Open a shell on the host or inside a service container.', + action: FilledButton.icon( + onPressed: () => _showOpenMenu(session), + icon: const Icon(Icons.add), + label: const Text('Open shell'), + ), + ); + } + final bool loading = !tab.isRunning && + (session.status == SshStatus.connecting || tab.isStarting); + return Stack( + children: [ + Positioned.fill(child: _terminalView(tab)), + if (loading) + Center( + child: _LoadingCard( + text: session.status == SshStatus.connecting + ? (session.stage ?? 'Connecting...') + : tab.container == null + ? 'Opening shell...' + : 'Opening a shell in ${tab.container}...', + ), + ), + ], + ); + } + + Widget _terminalView(TerminalTab tab) { + return TerminalView( + tab.terminal, + key: ValueKey(tab.id), + controller: tab.controller, + autofocus: true, + theme: TerminalThemes.defaultTheme, + textStyle: TerminalStyle( + fontSize: _fontSize, + fontFamily: 'JetBrainsMono Nerd Font', + ), + padding: const EdgeInsets.all(Insets.xs), + keyboardType: TextInputType.visiblePassword, + deleteDetection: true, + ); + } + + String _statusLabel(HostSession s) => switch (s.status) { + SshStatus.connected => 'Connected to ${s.endpoint}', + SshStatus.connecting => s.stage ?? 'Connecting...', + SshStatus.failed => 'Connection failed', + SshStatus.disconnected => 'Disconnected', + }; + + Future _showOpenMenu(HostSession session) async { + final List services = ref + .read(activeInstancesProvider) + .where( + (Instance i) => + i.kind != ServiceKind.dockerHost && + dockerHostFor(i, ref.read(activeInstancesProvider))?.id == + widget.host.id, + ) + .toList(); + await showModalBottomSheet( + context: context, + useRootNavigator: true, + showDragHandle: true, + isScrollControlled: true, + builder: (BuildContext sheetContext) => SafeArea( + child: ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(sheetContext).height * 0.7, + ), + child: ListView( + shrinkWrap: true, + children: [ + ListTile( + leading: const Icon(Icons.terminal_rounded), + title: const Text('Host shell'), + subtitle: Text(widget.host.name), + onTap: () { + Navigator.pop(sheetContext); + session.openHostTab(widget.host); + }, + ), + if (services.isNotEmpty) const Divider(), + for (final Instance s in services) + ListTile( + leading: Icon( + ServiceVisuals.icon(s.kind), + color: ServiceVisuals.accent(s.kind), + ), + title: Text(s.name), + subtitle: Text( + s.dockerContainer.isEmpty + ? 'No container set - edit the service to pick one' + : 'docker exec ${s.dockerContainer}', + ), + enabled: s.dockerContainer.trim().isNotEmpty, + onTap: () { + Navigator.pop(sheetContext); + session.openServiceTab(s); + }, + ), + ], + ), + ), + ), + ); + } + + Future _onMenu(String value, HostSession session) async { + final TerminalTab? tab = session.activeTab; + switch (value) { + case 'paste': + final ClipboardData? data = await Clipboard.getData('text/plain'); + final String? text = data?.text; + if (tab != null && text != null && text.isNotEmpty) { + tab.terminal.paste(text); + } + case 'copy': + final BufferRange? range = tab?.controller.selection; + if (tab != null && range != null) { + await Clipboard.setData( + ClipboardData(text: tab.terminal.buffer.getText(range)), + ); + tab.controller.clearSelection(); + } + case 'bigger': + setState(() => _fontSize = (_fontSize + 1).clamp(8, 28)); + case 'smaller': + setState(() => _fontSize = (_fontSize - 1).clamp(8, 28)); + case 'disconnect': + session.disconnect(); + case 'connect': + _connect(); + } + } +} + +class _StatusBanner extends StatelessWidget { + const _StatusBanner({required this.session, required this.onRetry}); + + final HostSession session; + final VoidCallback onRetry; + + @override + Widget build(BuildContext context) { + final ColorScheme cs = Theme.of(context).colorScheme; + if (session.status == SshStatus.connecting) { + return const LinearProgressIndicator(minHeight: 3); + } + final bool failed = session.status == SshStatus.failed; + return Material( + color: failed ? cs.errorContainer : cs.surfaceContainerHigh, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: Insets.md, + vertical: Insets.xs, + ), + child: Row( + children: [ + Icon( + failed ? Icons.error_outline : Icons.link_off, + size: 18, + color: failed ? cs.onErrorContainer : cs.onSurfaceVariant, + ), + const SizedBox(width: Insets.sm), + Expanded( + child: Text( + session.error ?? 'Not connected.', + style: Theme.of(context).textTheme.bodySmall?.copyWith( + color: failed ? cs.onErrorContainer : null, + ), + ), + ), + TextButton( + onPressed: onRetry, + child: Text(failed ? 'Retry' : 'Connect'), + ), + ], + ), + ), + ); + } +} + +class _LoadingCard extends StatelessWidget { + const _LoadingCard({required this.text}); + + final String text; + + @override + Widget build(BuildContext context) { + final ThemeData theme = Theme.of(context); + return Card( + elevation: 4, + color: theme.colorScheme.surfaceContainerHigh, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: Insets.lg, + vertical: Insets.md, + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2.5), + ), + const SizedBox(width: Insets.md), + Flexible(child: Text(text, style: theme.textTheme.bodyMedium)), + ], + ), + ), + ); + } +} + +class _TabStrip extends StatelessWidget { + const _TabStrip({required this.session}); + + final HostSession session; + + @override + Widget build(BuildContext context) { + return SizedBox( + height: 44, + child: ListView.separated( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric( + horizontal: Insets.sm, + vertical: Insets.xs, + ), + itemCount: session.tabs.length, + separatorBuilder: (_, __) => const SizedBox(width: Insets.xs), + itemBuilder: (BuildContext context, int i) { + final TerminalTab tab = session.tabs[i]; + return InputChip( + avatar: tab.isStarting + ? const SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : Icon( + tab.isHost + ? Icons.dns_outlined + : Icons.inventory_2_outlined, + size: 16, + ), + label: Text(tab.title), + selected: i == session.activeIndex, + showCheckmark: false, + onPressed: () => session.select(i), + onDeleted: () => session.closeTab(tab), + deleteButtonTooltipMessage: 'Close', + ); + }, + ), + ); + } +} + +/// Termux-style row of keys a phone keyboard lacks. Ctrl / Alt are one-shot +/// modifiers applied to the next key, from this row or the soft keyboard. +class _ExtraKeys extends StatelessWidget { + const _ExtraKeys({required this.session}); + + final HostSession session; + + void _key(TerminalKey key) { + final TerminalTab? tab = session.activeTab; + if (tab == null) return; + final ({bool ctrl, bool alt}) mods = session.takeModifiers(); + tab.terminal.keyInput(key, ctrl: mods.ctrl, alt: mods.alt); + } + + void _text(String text) => session.activeTab?.terminal.textInput(text); + + @override + Widget build(BuildContext context) { + final ColorScheme cs = Theme.of(context).colorScheme; + final List keys = [ + _KeyButton(label: 'ESC', onTap: () => _key(TerminalKey.escape)), + _KeyButton(label: 'TAB', onTap: () => _key(TerminalKey.tab)), + _KeyButton( + label: 'CTRL', + active: session.ctrl, + onTap: session.toggleCtrl, + ), + _KeyButton(label: 'ALT', active: session.alt, onTap: session.toggleAlt), + _KeyButton(label: '←', onTap: () => _key(TerminalKey.arrowLeft)), + _KeyButton(label: '↓', onTap: () => _key(TerminalKey.arrowDown)), + _KeyButton(label: '↑', onTap: () => _key(TerminalKey.arrowUp)), + _KeyButton(label: '→', onTap: () => _key(TerminalKey.arrowRight)), + _KeyButton(label: 'HOME', onTap: () => _key(TerminalKey.home)), + _KeyButton(label: 'END', onTap: () => _key(TerminalKey.end)), + _KeyButton(label: 'PGUP', onTap: () => _key(TerminalKey.pageUp)), + _KeyButton(label: 'PGDN', onTap: () => _key(TerminalKey.pageDown)), + for (final String c in const ['-', '/', '|', '~', '_']) + _KeyButton(label: c, onTap: () => _text(c)), + ]; + return Material( + color: cs.surfaceContainer, + child: SizedBox( + height: 44, + child: ListView( + scrollDirection: Axis.horizontal, + padding: const EdgeInsets.symmetric(horizontal: Insets.xs), + children: keys, + ), + ), + ); + } +} + +class _KeyButton extends StatelessWidget { + const _KeyButton({ + required this.label, + required this.onTap, + this.active = false, + }); + + final String label; + final VoidCallback onTap; + final bool active; + + @override + Widget build(BuildContext context) { + final ColorScheme cs = Theme.of(context).colorScheme; + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 2, vertical: 4), + child: Material( + color: active ? cs.primary : cs.surfaceContainerHighest, + borderRadius: BorderRadius.circular(Radii.sm), + child: InkWell( + borderRadius: BorderRadius.circular(Radii.sm), + onTap: onTap, + child: ConstrainedBox( + constraints: const BoxConstraints(minWidth: 40), + child: Center( + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: Insets.sm), + child: Text( + label, + style: TextStyle( + fontFamily: 'JetBrainsMono Nerd Font', + fontWeight: FontWeight.w600, + fontSize: 13, + color: active ? cs.onPrimary : cs.onSurface, + ), + ), + ), + ), + ), + ), + ), + ); + } +} diff --git a/app/pubspec.yaml b/app/pubspec.yaml index 0e0a119c..e7b97601 100644 --- a/app/pubspec.yaml +++ b/app/pubspec.yaml @@ -20,6 +20,7 @@ dependencies: core_ui: cached_network_image: ^3.4.1 cupertino_icons: ^1.0.8 + dartssh2: ^4.2.0 dio: ^5.7.0 file_picker: ^12.0.0-beta.7 palette_generator_plus: ^1.0.0 @@ -67,6 +68,7 @@ dependencies: service_cleanuparr: service_slskd: url_launcher: ^6.3.2 + xterm: ^4.0.0 dev_dependencies: flutter_launcher_icons: ^0.14.3 flutter_lints: ^6.0.0 diff --git a/app/test/instance_form_docker_host_test.dart b/app/test/instance_form_docker_host_test.dart new file mode 100644 index 00000000..737eb278 --- /dev/null +++ b/app/test/instance_form_docker_host_test.dart @@ -0,0 +1,162 @@ +import 'dart:io'; + +import 'package:atrium/src/preferences.dart'; +import 'package:atrium/src/screens/instance_form_screen.dart'; +import 'package:core_models/core_models.dart'; +import 'package:core_profile/core_profile.dart'; +import 'package:core_storage/core_storage.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:go_router/go_router.dart'; + +/// The Docker Host form takes SSH addresses and credentials, and once a +/// profile has one, every other service can name its container. +void main() { + const Instance dockerHost = Instance( + id: 'host', + name: 'NAS', + kind: ServiceKind.dockerHost, + localUrl: 'ssh://192.168.1.10', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.ssh(username: 'admin', password: 'pw'), + ); + const Instance sonarr = Instance( + id: 'sonarr', + name: 'Sonarr', + kind: ServiceKind.sonarr, + localUrl: 'http://sonarr.example.test', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.apiKey(apiKey: 'k'), + ); + + late _Profiles profiles; + late Box settings; + + setUpAll(() async { + final Directory dir = await Directory.systemTemp.createTemp('form'); + Hive.init(dir.path); + settings = await Hive.openBox('settings'); + }); + + tearDownAll(() async { + await Hive.close(); + }); + + Future edit(WidgetTester tester, String instanceId) async { + tester.view.physicalSize = const Size(900, 1600); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + profiles = _Profiles([dockerHost, sonarr]); + final GoRouter router = GoRouter( + initialLocation: '/edit', + routes: [ + GoRoute( + path: '/', + builder: (BuildContext _, GoRouterState __) => + const Scaffold(body: Text('home')), + routes: [ + GoRoute( + path: 'edit', + builder: (BuildContext _, GoRouterState __) => + InstanceFormScreen(instanceId: instanceId), + ), + ], + ), + ], + ); + addTearDown(router.dispose); + await tester.pumpWidget( + ProviderScope( + overrides: [ + profileListProvider.overrideWith(() => profiles), + activeProfileIdProvider.overrideWith(_Active.new), + settingsBoxProvider.overrideWithValue(settings), + ], + child: MaterialApp.router(routerConfig: router), + ), + ); + await tester.pumpAndSettle(); + } + + Finder field(String label) => find.ancestor( + of: find.text(label), + matching: find.byType(TextFormField), + ); + + Future save(WidgetTester tester) async { + await tester.scrollUntilVisible( + find.text('Save changes'), + 200, + scrollable: find.byType(Scrollable).first, + ); + await tester.tap(find.text('Save changes')); + await tester.pumpAndSettle(); + } + + testWidgets('a Docker host takes an SSH address and keeps its SSH login', + (WidgetTester tester) async { + await edit(tester, dockerHost.id); + expect(find.text('Private key (optional)'), findsOneWidget); + expect(find.text('Container shell'), findsNothing); + // Nothing in Preferences applies to SSH, so the card is left out. + expect(find.text('Preferences'), findsNothing); + + await tester.enterText(field('Local address'), 'http://nas.lan'); + await save(tester); + expect(profiles.saved, isEmpty); + expect(find.text('Enter at least one SSH address (local or external)'), + findsWidgets,); + + await tester.enterText(field('Local address'), 'nas.lan:2222'); + await save(tester); + final Instance saved = profiles.saved.single; + expect(saved.localUrl, 'nas.lan:2222'); + expect( + saved.auth, + const InstanceAuth.ssh(username: 'admin', password: 'pw'), + ); + }); + + testWidgets('a service names the container its shell opens in', + (WidgetTester tester) async { + await edit(tester, sonarr.id); + await tester.scrollUntilVisible( + find.text('Container name'), + 200, + scrollable: find.byType(Scrollable).first, + ); + await tester.enterText(field('Container name'), ' sonarr '); + await save(tester); + expect(profiles.saved.single.dockerContainer, 'sonarr'); + }); +} + +class _Profiles extends ProfileListController { + _Profiles(this.instances); + + final List instances; + final List saved = []; + + @override + Future> build() async => [ + Profile(id: 'p', name: 'Default', instances: instances), + ]; + + @override + Future upsertInstance(String profileId, Instance instance) async { + saved.add(instance); + } +} + +class _Active extends ActiveProfileIdController { + @override + String? build() => 'p'; + + @override + Future select(String? id) async => state = id; +} diff --git a/app/test/ssh_host_status_test.dart b/app/test/ssh_host_status_test.dart new file mode 100644 index 00000000..b9c0fb7a --- /dev/null +++ b/app/test/ssh_host_status_test.dart @@ -0,0 +1,129 @@ +import 'dart:io'; + +import 'package:atrium/src/preferences.dart'; +import 'package:atrium/src/terminal/docker_shell.dart'; +import 'package:atrium/src/terminal/ssh_host_status.dart'; +import 'package:atrium/src/terminal/terminal_hub.dart'; +import 'package:core_models/core_models.dart'; +import 'package:core_storage/core_storage.dart'; +import 'package:flutter_riverpod/flutter_riverpod.dart'; +import 'package:flutter_riverpod/misc.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + final DateTime now = DateTime(2026, 11, 26, 12); + SshLoginRecord login({required bool ok, Duration ago = Duration.zero}) => + SshLoginRecord( + ok: ok, + at: now.subtract(ago), + username: 'admin', + message: ok ? null : 'refused', + ); + + group('dockerHostHealth', () { + test('a refused last login turns an answering server amber', () { + expect( + dockerHostHealth( + probe: Health.ok, + lastLogin: login(ok: false), + ), + Health.warning, + ); + expect( + dockerHostHealth( + probe: Health.ok, + lastLogin: login(ok: true), + ), + Health.ok, + ); + }); + + test('an unreachable server stays red whatever the last login', () { + expect( + dockerHostHealth( + probe: Health.error, + lastLogin: login(ok: false), + ), + Health.error, + ); + }); + }); + + test('describeDockerHost says why, in words', () { + String say(Health h, {SshLoginRecord? last, SshStatus? s}) => + describeDockerHost( + health: h, + session: s ?? SshStatus.disconnected, + endpoint: const SshEndpoint('nas.lan'), + lastLogin: last, + now: now, + ); + expect( + say(Health.ok, s: SshStatus.connected), + 'Connected now to nas.lan:22', + ); + expect(say(Health.ok), 'SSH answering - not logged in yet'); + expect( + say(Health.ok, last: login(ok: true, ago: const Duration(hours: 2))), + 'SSH answering - last login OK 2 h ago', + ); + expect( + say( + Health.warning, + last: login(ok: false, ago: const Duration(minutes: 5)), + ), + 'SSH answering - login refused for admin 5 min ago', + ); + expect( + say(Health.warning), + 'Something answers on that port, but it is not an SSH server', + ); + expect(say(Health.error), 'Not reachable'); + }); + + test('dockerIssueFor names the usual Docker problems', () { + expect(dockerIssueFor(127, ''), 'Docker was not found on the host'); + expect( + dockerIssueFor( + 1, + 'permission denied while trying to connect to the Docker daemon socket', + ), + contains('not allowed to use Docker'), + ); + expect( + dockerIssueFor(1, 'Cannot connect to the Docker daemon at unix://...'), + 'Docker is installed but its daemon is not running', + ); + }); + + test('login records survive a restart and can be cleared', () async { + final Directory dir = await Directory.systemTemp.createTemp('records'); + Hive.init(dir.path); + final Box box = await Hive.openBox('settings'); + addTearDown(() async { + await Hive.close(); + await dir.delete(recursive: true); + }); + ProviderContainer container() => ProviderContainer( + overrides: [settingsBoxProvider.overrideWithValue(box)], + ); + + final ProviderContainer first = container(); + await first + .read(sshLoginRecordsProvider.notifier) + .record('h1', login(ok: false)); + first.dispose(); + + final ProviderContainer second = container(); + addTearDown(second.dispose); + final SshLoginRecord? restored = second.read(sshLoginRecordsProvider)['h1']; + expect(restored?.ok, isFalse); + expect(restored?.username, 'admin'); + expect(restored?.message, 'refused'); + + await second.read(sshLoginRecordsProvider.notifier).clear('h1'); + expect(second.read(sshLoginRecordsProvider), isEmpty); + expect(box.keys.where((dynamic k) => '$k'.startsWith('sshLastLogin:')), + isEmpty); + }); +} diff --git a/app/test/terminal_docker_shell_test.dart b/app/test/terminal_docker_shell_test.dart new file mode 100644 index 00000000..06867e98 --- /dev/null +++ b/app/test/terminal_docker_shell_test.dart @@ -0,0 +1,88 @@ +import 'package:atrium/src/terminal/docker_shell.dart'; +import 'package:core_models/core_models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Instance _instance(String id, ServiceKind kind, {String hostId = ''}) => + Instance( + id: id, + name: id, + kind: kind, + localUrl: 'ssh://10.0.0.2', + externalUrl: '', + urlMode: UrlMode.auto, + auth: const InstanceAuth.apiKey(apiKey: ''), + dockerHostId: hostId, + ); + +void main() { + test('container names are quoted so the host shell cannot split them', () { + expect(shellQuote("it's"), r"'it'\''s'"); + final String cmd = dockerExecShellCommand("a'b; rm -rf /"); + expect(cmd, startsWith('sh -lc ')); + // The hostile name never appears unquoted at the top level. + expect(cmd, isNot(contains(" a'b; rm"))); + expect(cmd, contains('docker exec -it')); + }); + + test('parseDockerPs reads name, image and status per line', () { + expect( + parseDockerPs( + 'sonarr\tlscr.io/linuxserver/sonarr:latest\tUp 2 days\n' + '\n' + 'qbit\tlinuxserver/qbittorrent\n', + ), + const [ + DockerContainer( + name: 'sonarr', + image: 'lscr.io/linuxserver/sonarr:latest', + status: 'Up 2 days', + ), + DockerContainer(name: 'qbit', image: 'linuxserver/qbittorrent'), + ], + ); + }); + + test('containers that look like the service rank first', () { + const List all = [ + DockerContainer(name: 'aaa', image: 'postgres'), + DockerContainer(name: 'torrent', image: 'linuxserver/qbittorrent'), + DockerContainer(name: 'speedtest', image: 'speedtest-tracker'), + ]; + expect( + rankContainersFor(ServiceKind.qbittorrent, all).first.name, + 'torrent', + ); + expect( + rankContainersFor(ServiceKind.speedtestTracker, all).first.name, + 'speedtest', + ); + }); + + test('dockerHostFor prefers the named host, else the first one', () { + final List instances = [ + _instance('sonarr', ServiceKind.sonarr), + _instance('h1', ServiceKind.dockerHost), + _instance('h2', ServiceKind.dockerHost), + ]; + expect(dockerHostFor(instances.first, instances)?.id, 'h1'); + expect( + dockerHostFor(_instance('s', ServiceKind.sonarr, hostId: 'h2'), instances) + ?.id, + 'h2', + ); + expect( + dockerHostFor(instances.first, [instances.first]), + isNull, + ); + }); + + test('on-screen Ctrl and Alt encode like a hardware keyboard', () { + expect(applyModifiers('c', ctrl: true), '\x03'); + expect(applyModifiers('C', ctrl: true), '\x03'); + expect(applyModifiers('[', ctrl: true), '\x1b'); + expect(applyModifiers('b', alt: true), '\x1bb'); + expect(applyModifiers('x'), 'x'); + // Multi-char input (paste, escape sequences) is left alone by Ctrl. + expect(applyModifiers('ls', ctrl: true), 'ls'); + }); +} diff --git a/app/test/terminal_hub_test.dart b/app/test/terminal_hub_test.dart new file mode 100644 index 00000000..6808b1eb --- /dev/null +++ b/app/test/terminal_hub_test.dart @@ -0,0 +1,62 @@ +import 'dart:io'; + +import 'package:atrium/src/terminal/ssh_connector.dart'; +import 'package:atrium/src/terminal/terminal_hub.dart'; +import 'package:core_models/core_models.dart'; +import 'package:core_storage/core_storage.dart'; +import 'package:flutter_test/flutter_test.dart'; + +const Instance _host = Instance( + id: 'h1', + name: 'NAS', + kind: ServiceKind.dockerHost, + localUrl: 'ssh://10.0.0.2', + externalUrl: '', + urlMode: UrlMode.auto, + auth: InstanceAuth.ssh(username: 'admin', password: 'pw'), +); + +void main() { + late TerminalHub hub; + + setUp(() async { + final Directory dir = await Directory.systemTemp.createTemp('hub'); + Hive.init(dir.path); + final Box box = await Hive.openBox('settings'); + hub = TerminalHub(KnownHostsStore(box)); + addTearDown(() async { + hub.dispose(); + await Hive.close(); + await dir.delete(recursive: true); + }); + }); + + test('a renamed host keeps its session', () { + hub.syncHosts([_host]); + final HostSession session = hub.session('h1'); + hub.syncHosts([_host.copyWith(name: 'Server')]); + expect(hub.session('h1'), same(session)); + }); + + test('an edited login or address replaces the session', () { + hub.syncHosts([_host]); + final HostSession first = hub.session('h1'); + hub.syncHosts([ + _host.copyWith( + auth: const InstanceAuth.ssh(username: 'admin', password: 'new'), + ), + ]); + final HostSession second = hub.session('h1'); + expect(second, isNot(same(first))); + + hub.syncHosts([_host.copyWith(localUrl: 'ssh://10.0.0.3')]); + expect(hub.session('h1'), isNot(same(second))); + }); + + test('a host that leaves the profile loses its session', () { + hub.syncHosts([_host]); + final HostSession session = hub.session('h1'); + hub.syncHosts(const []); + expect(hub.session('h1'), isNot(same(session))); + }); +} diff --git a/packages/core_models/lib/core_models.dart b/packages/core_models/lib/core_models.dart index 364e3ec4..c91d9bb2 100644 --- a/packages/core_models/lib/core_models.dart +++ b/packages/core_models/lib/core_models.dart @@ -9,5 +9,6 @@ export 'src/instance.dart'; export 'src/instance_auth.dart'; export 'src/profile.dart'; export 'src/service_kind.dart'; +export 'src/ssh_endpoint.dart'; export 'src/url_mode.dart'; export 'src/wol_device.dart'; diff --git a/packages/core_models/lib/src/instance.dart b/packages/core_models/lib/src/instance.dart index ba046a18..c6e78d81 100644 --- a/packages/core_models/lib/src/instance.dart +++ b/packages/core_models/lib/src/instance.dart @@ -57,6 +57,14 @@ abstract class Instance with _$Instance { /// over the profile's global headers (instance wins on key collision). /// Values live in the profile JSON like URLs do; they are not secrets. @Default({}) Map customHeaders, + + /// Id of the [ServiceKind.dockerHost] instance this service's container + /// runs on. Empty means "the profile's only / first Docker host". + @Default('') String dockerHostId, + + /// Name (or id) of the Docker container this service runs in. Empty + /// disables the in-container shell. + @Default('') String dockerContainer, }) = _Instance; factory Instance.fromJson(Map json) => @@ -75,7 +83,9 @@ abstract class Instance with _$Instance { 'auth: $auth, ' 'allowSelfSignedCerts: $allowSelfSignedCerts, ' 'pollingIntervalSeconds: $pollingIntervalSeconds, ' - 'customHeaderNames: ${customHeaders.keys.toList(growable: false)}' + 'customHeaderNames: ${customHeaders.keys.toList(growable: false)}, ' + 'dockerHostId: $dockerHostId, ' + 'dockerContainer: $dockerContainer' ')'; } diff --git a/packages/core_models/lib/src/instance_auth.dart b/packages/core_models/lib/src/instance_auth.dart index 083d76d5..9e1cd570 100644 --- a/packages/core_models/lib/src/instance_auth.dart +++ b/packages/core_models/lib/src/instance_auth.dart @@ -48,6 +48,16 @@ sealed class InstanceAuth with _$InstanceAuth { required String password, }) = InstanceAuthCookie; + /// SSH login for a [ServiceKind.dockerHost]. [privateKey] (PEM / OpenSSH, + /// optionally encrypted with [passphrase]) is offered first when set; + /// [password] covers password and keyboard-interactive auth. + const factory InstanceAuth.ssh({ + required String username, + @Default('') String password, + @Default('') String privateKey, + @Default('') String passphrase, + }) = InstanceAuthSsh; + factory InstanceAuth.fromJson(Map json) => _$InstanceAuthFromJson(json); @@ -60,5 +70,7 @@ sealed class InstanceAuth with _$InstanceAuth { InstanceAuthPlex() => 'InstanceAuth.plexToken(***redacted***)', InstanceAuthCookie(:final String username) => 'InstanceAuth.cookieLogin(username: $username, password: ***redacted***)', + InstanceAuthSsh(:final String username) => + 'InstanceAuth.ssh(username: $username, secrets: ***redacted***)', }; } diff --git a/packages/core_models/lib/src/service_kind.dart b/packages/core_models/lib/src/service_kind.dart index 5ab1bbdf..b695f7fe 100644 --- a/packages/core_models/lib/src/service_kind.dart +++ b/packages/core_models/lib/src/service_kind.dart @@ -34,7 +34,8 @@ enum ServiceKind { aria2, cleanuparr, slskd, - gotify; + gotify, + dockerHost; /// All [ServiceKind] entries sorted alphabetically by their display name. static List get sortedValues => @@ -84,6 +85,7 @@ extension ServiceKindX on ServiceKind { ServiceKind.cleanuparr => 'Cleanuparr', ServiceKind.slskd => 'slskd', ServiceKind.gotify => 'Gotify', + ServiceKind.dockerHost => 'Docker Host', }; /// One-line role description. @@ -119,6 +121,7 @@ extension ServiceKindX on ServiceKind { ServiceKind.cleanuparr => 'Malware blocker & cleaner', ServiceKind.slskd => 'Soulseek client', ServiceKind.gotify => 'Notifications', + ServiceKind.dockerHost => 'Container terminal', }; /// Whether this service's integration is still in beta. Surfaced as a @@ -132,6 +135,7 @@ extension ServiceKindX on ServiceKind { ServiceKind.slskd || ServiceKind.gotify => true, + ServiceKind.dockerHost => true, _ => false, }; @@ -180,6 +184,7 @@ extension ServiceKindX on ServiceKind { ServiceKind.slskd => 5030, // The port the official Docker image listens on. ServiceKind.gotify => 80, + ServiceKind.dockerHost => 22, }; /// What auth flow the service uses by default. Some services (Jellyfin) can @@ -202,6 +207,7 @@ extension ServiceKindX on ServiceKind { // A client token; an application token can only post messages. ServiceKind.gotify => AuthStyle.apiKey, + ServiceKind.dockerHost => AuthStyle.ssh, // aria2's credential is its `--rpc-secret`, which is sent as the // first RPC parameter rather than as a header. It is optional - a // daemon with no secret answers anyone - so the form must not @@ -266,7 +272,10 @@ extension ServiceKindX on ServiceKind { ServiceKind.gluetun => ServiceRole.analytics, ServiceKind.myspeed => ServiceRole.analytics, ServiceKind.adguardHome => ServiceRole.analytics, - ServiceKind.cleanuparr || ServiceKind.gotify => ServiceRole.extra, + ServiceKind.cleanuparr || + ServiceKind.gotify || + ServiceKind.dockerHost => + ServiceRole.extra, }; /// Whether this service can be handed a torrent - a magnet URI, a link to a @@ -306,6 +315,9 @@ enum AuthStyle { /// requests (qBittorrent). cookieLogin, + /// SSH login (password and/or private key) for a Docker host. + ssh, + /// No authentication required. none, } diff --git a/packages/core_models/lib/src/ssh_endpoint.dart b/packages/core_models/lib/src/ssh_endpoint.dart new file mode 100644 index 00000000..5e03220d --- /dev/null +++ b/packages/core_models/lib/src/ssh_endpoint.dart @@ -0,0 +1,49 @@ +import 'package:meta/meta.dart'; + +/// Host and port of an SSH server, parsed from an instance URL field. +/// +/// A `ServiceKind.dockerHost` stores its addresses in the same local / +/// external URL fields every other service uses, so they may be written as +/// `ssh://host:port`, `host:port` or just `host`. +@immutable +class SshEndpoint { + const SshEndpoint(this.host, [this.port = defaultPort]); + + static const int defaultPort = 22; + + final String host; + final int port; + + /// Parses [raw], or returns null when it is empty or not an SSH address. + static SshEndpoint? tryParse(String raw) { + final String text = raw.trim(); + if (text.isEmpty) { + return null; + } + final Uri? uri = Uri.tryParse(text.contains('://') ? text : 'ssh://$text'); + if (uri == null || uri.scheme.toLowerCase() != 'ssh' || uri.host.isEmpty) { + return null; + } + if (uri.path.isNotEmpty && uri.path != '/') { + return null; + } + // Read the port from the text: Uri drops an explicit `:0`. + final RegExpMatch? explicit = RegExp(r':(\d+)/?$').firstMatch(text); + final int port = + explicit == null ? defaultPort : int.parse(explicit.group(1)!); + if (port < 1 || port > 65535) { + return null; + } + return SshEndpoint(uri.host, port); + } + + @override + bool operator ==(Object other) => + other is SshEndpoint && other.host == host && other.port == port; + + @override + int get hashCode => Object.hash(host, port); + + @override + String toString() => host.contains(':') ? '[$host]:$port' : '$host:$port'; +} diff --git a/packages/core_models/test/service_kind_test.dart b/packages/core_models/test/service_kind_test.dart index a4f1e0ec..8dc8cd99 100644 --- a/packages/core_models/test/service_kind_test.dart +++ b/packages/core_models/test/service_kind_test.dart @@ -40,10 +40,19 @@ void main() { 'cleanuparr', 'slskd', 'gotify', + 'dockerHost', ], ); }); + test('Docker Host is registered as an SSH extra service', () { + expect(ServiceKind.dockerHost.displayName, 'Docker Host'); + expect(ServiceKind.dockerHost.authStyle, AuthStyle.ssh); + expect(ServiceKind.dockerHost.role, ServiceRole.extra); + expect(ServiceKind.dockerHost.defaultPort, 22); + expect(ServiceKind.dockerHost.isBeta, isTrue); + }); + test('Gotify is registered as an apiKey extra service', () { expect(ServiceKind.gotify.displayName, 'Gotify'); expect(ServiceKind.gotify.tagline, 'Notifications'); diff --git a/packages/core_models/test/ssh_test.dart b/packages/core_models/test/ssh_test.dart new file mode 100644 index 00000000..d68489e8 --- /dev/null +++ b/packages/core_models/test/ssh_test.dart @@ -0,0 +1,63 @@ +import 'package:core_models/core_models.dart'; +import 'package:flutter_test/flutter_test.dart'; + +void main() { + group('SshEndpoint.tryParse', () { + test('accepts ssh URLs, host:port and bare hosts', () { + expect( + SshEndpoint.tryParse('ssh://192.168.1.10:2222'), + const SshEndpoint('192.168.1.10', 2222), + ); + expect( + SshEndpoint.tryParse(' nas.local:2200 '), + const SshEndpoint('nas.local', 2200), + ); + expect(SshEndpoint.tryParse('nas.local'), const SshEndpoint('nas.local')); + expect( + SshEndpoint.tryParse('ssh://root@host'), + const SshEndpoint('host'), + ); + expect(SshEndpoint.tryParse('[::1]:22'), const SshEndpoint('::1')); + }); + + test('rejects empty, non-ssh schemes, paths and bad ports', () { + expect(SshEndpoint.tryParse(''), isNull); + expect(SshEndpoint.tryParse('http://host:22'), isNull); + expect(SshEndpoint.tryParse('host/path'), isNull); + expect(SshEndpoint.tryParse('host:0'), isNull); + }); + }); + + test('instances saved before container shells load with empty fields', () { + final Instance instance = Instance.fromJson({ + 'id': 'i1', + 'name': 'Sonarr', + 'kind': 'sonarr', + 'localUrl': 'http://192.168.1.10:8989', + 'externalUrl': '', + 'urlMode': 'auto', + 'auth': {'runtimeType': 'apiKey', 'apiKey': ''}, + }); + expect(instance.dockerHostId, ''); + expect(instance.dockerContainer, ''); + }); + + test('ssh auth round-trips and redacts every secret in toString', () { + const InstanceAuth auth = InstanceAuth.ssh( + username: 'admin', + password: 'pw-secret', + privateKey: 'key-secret', + passphrase: 'pass-secret', + ); + expect(InstanceAuth.fromJson(auth.toJson()), auth); + final String text = auth.toString(); + expect(text, contains('admin')); + for (final String secret in [ + 'pw-secret', + 'key-secret', + 'pass-secret', + ]) { + expect(text, isNot(contains(secret))); + } + }); +} diff --git a/packages/core_networking/lib/core_networking.dart b/packages/core_networking/lib/core_networking.dart index 75eed1bb..a4981756 100644 --- a/packages/core_networking/lib/core_networking.dart +++ b/packages/core_networking/lib/core_networking.dart @@ -19,4 +19,5 @@ export 'src/self_path.dart'; export 'src/self_signed_cert_trust.dart'; export 'src/service_auth_headers.dart'; export 'src/service_health.dart'; +export 'src/ssh_probe.dart'; export 'src/wol.dart'; diff --git a/packages/core_networking/lib/src/auth_interceptor.dart b/packages/core_networking/lib/src/auth_interceptor.dart index 974f2c1d..a27c3646 100644 --- a/packages/core_networking/lib/src/auth_interceptor.dart +++ b/packages/core_networking/lib/src/auth_interceptor.dart @@ -163,6 +163,9 @@ class AuthInterceptor extends Interceptor { // Token / cookie auth is handled by the service's session manager, // not here. break; + case InstanceAuthSsh(): + // SSH credentials never travel over HTTP. + break; } handler.next(options); } diff --git a/packages/core_networking/lib/src/service_auth_headers.dart b/packages/core_networking/lib/src/service_auth_headers.dart index 04ab4a1b..2b9e5679 100644 --- a/packages/core_networking/lib/src/service_auth_headers.dart +++ b/packages/core_networking/lib/src/service_auth_headers.dart @@ -54,9 +54,9 @@ Set serviceAuthHeaderNames(ServiceKind kind, InstanceAuth auth) { return username.isEmpty && password.isEmpty ? const {} : const {'Authorization'}; - case InstanceAuthUserPass() || InstanceAuthCookie(): + case InstanceAuthUserPass() || InstanceAuthCookie() || InstanceAuthSsh(): // Token and cookie flows are handled by the service's own session - // manager rather than by a static header. + // manager rather than by a static header; SSH never uses HTTP. return const {}; } } diff --git a/packages/core_networking/lib/src/service_health.dart b/packages/core_networking/lib/src/service_health.dart index 22f963e4..a6132d15 100644 --- a/packages/core_networking/lib/src/service_health.dart +++ b/packages/core_networking/lib/src/service_health.dart @@ -6,6 +6,7 @@ import 'package:dio/dio.dart'; import 'auth_interceptor.dart'; import 'dio_factory.dart'; import 'self_path.dart'; +import 'ssh_probe.dart'; /// How a service's health endpoint should be interpreted. enum _HealthMode { @@ -146,6 +147,9 @@ enum _HealthMode { // `health` and `version` answer anyone; `current/user` refuses a wrong // token, and an application token too, which cannot read messages. return (path: 'current/user', mode: _HealthMode.authed); + case ServiceKind.dockerHost: + // Not HTTP: [HealthProbe.check] hands it to [probeSshHost]. + return (path: '', mode: _HealthMode.reachable); } } @@ -188,7 +192,8 @@ String _aria2ProbeBody(Instance instance) { InstanceAuthApiKey(:final String apiKey) => apiKey, InstanceAuthUserPass() || InstanceAuthPlex() || - InstanceAuthCookie() => + InstanceAuthCookie() || + InstanceAuthSsh() => '', }; return jsonEncode({ @@ -234,6 +239,9 @@ class HealthProbe { /// Probes [instance]; see [interpretServiceHealthResponse] for /// [connectionOnly]. Future check(Instance instance, {bool connectionOnly = false}) async { + if (instance.kind == ServiceKind.dockerHost) { + return probeSshHost(instance); + } final ({String path, _HealthMode mode}) cfg = _config(instance.kind); Dio? dio; try { diff --git a/packages/core_networking/lib/src/ssh_probe.dart b/packages/core_networking/lib/src/ssh_probe.dart new file mode 100644 index 00000000..29547d0d --- /dev/null +++ b/packages/core_networking/lib/src/ssh_probe.dart @@ -0,0 +1,62 @@ +import 'dart:async'; +import 'dart:convert'; +import 'dart:io'; + +import 'package:core_models/core_models.dart'; + +/// The SSH endpoints to try for a Docker host, in order, per its [UrlMode]. +List sshEndpointsFor(Instance instance) { + final SshEndpoint? local = SshEndpoint.tryParse(instance.localUrl); + final SshEndpoint? external = SshEndpoint.tryParse(instance.externalUrl); + final List ordered = switch (instance.urlMode) { + UrlMode.forceLocal => [local], + UrlMode.forceExternal => [external], + UrlMode.auto => [local, external], + }; + return ordered.whereType().toSet().toList(); +} + +/// Liveness of an SSH server without logging in: connects and waits for the +/// `SSH-` identification banner every server sends first (RFC 4253 §4.2). +/// +/// No credentials are sent, so a dashboard refresh can never trip a +/// fail2ban-style lockout. Something that accepts the connection but is not +/// an SSH server (wrong port) reads as [Health.warning]. +Future probeSshHost( + Instance instance, { + Duration timeout = const Duration(seconds: 4), +}) async { + Health result = Health.error; + for (final SshEndpoint endpoint in sshEndpointsFor(instance)) { + final Health health = await _probe(endpoint, timeout); + if (health == Health.ok) { + return health; + } + if (health == Health.warning) { + result = health; + } + } + return result; +} + +Future _probe(SshEndpoint endpoint, Duration timeout) async { + Socket? socket; + try { + socket = await Socket.connect( + endpoint.host, + endpoint.port, + timeout: timeout, + ); + final List first = await socket.first.timeout(timeout); + return latin1.decode(first, allowInvalid: true).startsWith('SSH-') + ? Health.ok + : Health.warning; + } on TimeoutException { + // Connected but silent: something listens there, but not sshd. + return socket == null ? Health.error : Health.warning; + } on Object { + return Health.error; + } finally { + socket?.destroy(); + } +} diff --git a/packages/core_networking/test/ssh_probe_test.dart b/packages/core_networking/test/ssh_probe_test.dart new file mode 100644 index 00000000..4002bc59 --- /dev/null +++ b/packages/core_networking/test/ssh_probe_test.dart @@ -0,0 +1,77 @@ +import 'dart:io'; + +import 'package:core_models/core_models.dart'; +import 'package:core_networking/core_networking.dart'; +import 'package:flutter_test/flutter_test.dart'; + +Instance _host(String local, {String external = '', UrlMode mode = UrlMode.auto}) => + Instance( + id: 'h', + name: 'Host', + kind: ServiceKind.dockerHost, + localUrl: local, + externalUrl: external, + urlMode: mode, + auth: const InstanceAuth.ssh(username: 'u'), + ); + +/// A one-shot TCP server that writes [greeting] (or nothing) on connect. +Future _server(String? greeting) async { + final ServerSocket server = + await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + server.listen((Socket s) { + if (greeting != null) { + s.write(greeting); + } + }); + return server; +} + +void main() { + test('sshEndpointsFor follows the URL mode', () { + final Instance host = _host('10.0.0.2', external: 'ssh://ex.com:2222'); + expect(sshEndpointsFor(host), const [ + SshEndpoint('10.0.0.2'), + SshEndpoint('ex.com', 2222), + ]); + expect( + sshEndpointsFor(host.copyWith(urlMode: UrlMode.forceExternal)), + const [SshEndpoint('ex.com', 2222)], + ); + }); + + test('an SSH banner is ok, another protocol a warning, nothing an error', + () async { + final ServerSocket ssh = await _server('SSH-2.0-OpenSSH_9.6\r\n'); + final ServerSocket http = await _server('HTTP/1.1 400 Bad Request\r\n'); + final ServerSocket closed = + await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + final int closedPort = closed.port; + await closed.close(); + addTearDown(() async { + await ssh.close(); + await http.close(); + }); + + expect(await probeSshHost(_host('127.0.0.1:${ssh.port}')), Health.ok); + expect( + await probeSshHost(_host('127.0.0.1:${http.port}')), + Health.warning, + ); + expect( + await probeSshHost( + _host('127.0.0.1:$closedPort'), + timeout: const Duration(seconds: 1), + ), + Health.error, + ); + // Auto mode falls back to the external address when the LAN one is down. + expect( + await probeSshHost( + _host('127.0.0.1:$closedPort', external: '127.0.0.1:${ssh.port}'), + timeout: const Duration(seconds: 1), + ), + Health.ok, + ); + }); +} diff --git a/packages/core_profile/lib/src/profile_repository.dart b/packages/core_profile/lib/src/profile_repository.dart index 6962b4bb..9ece5c9b 100644 --- a/packages/core_profile/lib/src/profile_repository.dart +++ b/packages/core_profile/lib/src/profile_repository.dart @@ -153,10 +153,19 @@ class ProfileRepository { Future importProfile(String json) async { final Profile incoming = Profile.fromJson(jsonDecode(json) as Map); + final Map newIds = { + for (final Instance i in incoming.instances) i.id: _uuid.v4(), + }; final Profile reIded = incoming.copyWith( id: _uuid.v4(), instances: incoming.instances - .map((Instance i) => i.copyWith(id: _uuid.v4())) + .map( + (Instance i) => i.copyWith( + id: newIds[i.id]!, + // Keep a service pointing at the same Docker host. + dockerHostId: newIds[i.dockerHostId] ?? '', + ), + ) .toList(), ); await saveProfile(reIded); @@ -200,5 +209,7 @@ class ProfileRepository { InstanceAuthPlex() => const InstanceAuth.plexToken(token: ''), InstanceAuthCookie(:final String username) => InstanceAuth.cookieLogin(username: username, password: ''), + InstanceAuthSsh(:final String username) => + InstanceAuth.ssh(username: username), }; } diff --git a/packages/core_ui/lib/src/service_visuals.dart b/packages/core_ui/lib/src/service_visuals.dart index 84f2990c..df1c67d6 100644 --- a/packages/core_ui/lib/src/service_visuals.dart +++ b/packages/core_ui/lib/src/service_visuals.dart @@ -39,6 +39,7 @@ abstract final class ServiceVisuals { ServiceKind.cleanuparr => Icons.cleaning_services_outlined, ServiceKind.slskd => Icons.library_music_outlined, ServiceKind.gotify => Icons.notifications_active_outlined, + ServiceKind.dockerHost => Icons.terminal_rounded, }; static Color accent(ServiceKind kind) => switch (kind) { @@ -73,6 +74,7 @@ abstract final class ServiceVisuals { ServiceKind.cleanuparr => const Color(0xFF7C3AED), ServiceKind.slskd => const Color(0xFF007ACC), ServiceKind.gotify => const Color(0xFF71CAEE), + ServiceKind.dockerHost => const Color(0xFF1D63ED), }; /// Human label for a [ServiceRole] section header. diff --git a/pubspec.lock b/pubspec.lock index ec2668ff..841bc3a8 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -41,6 +41,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.7.0" + asn1lib: + dependency: transitive + description: + name: asn1lib + sha256: ee77cac69a65f809e24c902f68c0e7c733312d301b367cc698cc3aed8b6c884a + url: "https://pub.dev" + source: hosted + version: "1.6.9" async: dependency: transitive description: @@ -257,6 +265,14 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.7" + dartssh2: + dependency: transitive + description: + name: dartssh2 + sha256: ea87fd9d8ef39556d9f9302fde82a7002d3e326fccf247ff4399c907f521dbda + url: "https://pub.dev" + source: hosted + version: "4.2.0" dbus: dependency: transitive description: @@ -943,6 +959,14 @@ packages: url: "https://pub.dev" source: hosted version: "7.0.2" + pinenacl: + dependency: transitive + description: + name: pinenacl + sha256: "57e907beaacbc3c024a098910b6240758e899674de07d6949a67b52fd984cbdf" + url: "https://pub.dev" + source: hosted + version: "0.6.0" platform: dependency: transitive description: @@ -959,6 +983,14 @@ packages: url: "https://pub.dev" source: hosted version: "2.1.8" + pointycastle: + dependency: transitive + description: + name: pointycastle + sha256: "92aa3841d083cc4b0f4709b5c74fd6409a3e6ba833ffc7dc6a8fee096366acf5" + url: "https://pub.dev" + source: hosted + version: "4.0.0" pool: dependency: transitive description: @@ -998,6 +1030,14 @@ packages: url: "https://pub.dev" source: hosted version: "1.5.0" + quiver: + dependency: transitive + description: + name: quiver + sha256: ea0b925899e64ecdfbf9c7becb60d5b50e706ade44a85b2363be2a22d88117d2 + url: "https://pub.dev" + source: hosted + version: "3.2.2" record_use: dependency: transitive description: @@ -1411,6 +1451,14 @@ packages: url: "https://pub.dev" source: hosted version: "6.6.1" + xterm: + dependency: transitive + description: + name: xterm + sha256: "168dfedca77cba33fdb6f52e2cd001e9fde216e398e89335c19b524bb22da3a2" + url: "https://pub.dev" + source: hosted + version: "4.0.0" yaml: dependency: transitive description: @@ -1419,6 +1467,15 @@ packages: url: "https://pub.dev" source: hosted version: "3.1.3" + zmodem: + dependency: transitive + description: + name: zmodem + sha256: "3b7e5b29f3a7d8aee472029b05165a68438eff2f3f7766edf13daba1e297adbf" + url: "https://pub.dev" + source: hosted + version: "0.0.6" + sdks: dart: ">=3.11.0 <4.0.0" flutter: ">=3.38.4" diff --git a/services/service_aria2/lib/src/aria2_providers.dart b/services/service_aria2/lib/src/aria2_providers.dart index f9f6ccc5..0615646d 100644 --- a/services/service_aria2/lib/src/aria2_providers.dart +++ b/services/service_aria2/lib/src/aria2_providers.dart @@ -27,7 +27,11 @@ final aria2ApiProvider = FutureProvider.family(( final dio = await ref.watch(instanceDioProvider(instance).future); final String secret = switch (instance.auth) { InstanceAuthApiKey(:final String apiKey) => apiKey, - InstanceAuthUserPass() || InstanceAuthPlex() || InstanceAuthCookie() => '', + InstanceAuthUserPass() || + InstanceAuthPlex() || + InstanceAuthCookie() || + InstanceAuthSsh() => + '', }; return Aria2Api(dio, secret: secret); }, retry: (_, _) => null); diff --git a/services/service_seerr/lib/src/seerr_session.dart b/services/service_seerr/lib/src/seerr_session.dart index 831dc240..aafb6828 100644 --- a/services/service_seerr/lib/src/seerr_session.dart +++ b/services/service_seerr/lib/src/seerr_session.dart @@ -49,7 +49,8 @@ class SeerrSignIn { username: username, password: password, ), - InstanceAuthApiKey() || InstanceAuthPlex() => null, + InstanceAuthApiKey() || InstanceAuthPlex() || InstanceAuthSsh() => + null, }; /// The auth to store for this account.