From 641abd9cbe12844c71127cb6b1ce5f98e2821790 Mon Sep 17 00:00:00 2001 From: involvex <39644169+involvex@users.noreply.github.com> Date: Mon, 16 Nov 2026 05:57:51 +0100 Subject: [PATCH] feat: reach Windows hosts via kbd-interactive, agent tunnel, and ssh config import Add keyboard-interactive auth, optional OpenCode SSH local forward, and OpenSSH config import with profile search/favorites/duplicate for the 1.4.0 host-access batch. Co-authored-by: Cursor --- CHANGELOG.md | 6 + docs/features.md | 12 +- lib/main.dart | 1 + lib/models/agent_connection.dart | 8 + lib/models/ssh_profile.dart | 17 ++ lib/providers/agent_provider.dart | 66 ++++- lib/providers/ssh_provider.dart | 39 ++- lib/screens/home_screen.dart | 7 + lib/services/ssh_config_import_service.dart | 131 +++++++++ lib/services/ssh_local_forward.dart | 144 ++++++++++ lib/utils/ssh_config_parser.dart | 207 ++++++++++++++ lib/widgets/keyboard_interactive_dialog.dart | 112 ++++++++ lib/widgets/profile_manager.dart | 253 ++++++++++++++++-- suggestions.md | 15 +- test/models/ssh_profile_agent_auth_test.dart | 24 ++ .../ssh_config_import_service_test.dart | 52 ++++ test/services/ssh_local_forward_test.dart | 34 +++ test/utils/ssh_config_parser_test.dart | 71 +++++ .../keyboard_interactive_dialog_test.dart | 93 +++++++ 19 files changed, 1260 insertions(+), 32 deletions(-) create mode 100644 lib/services/ssh_config_import_service.dart create mode 100644 lib/services/ssh_local_forward.dart create mode 100644 lib/utils/ssh_config_parser.dart create mode 100644 lib/widgets/keyboard_interactive_dialog.dart create mode 100644 test/services/ssh_config_import_service_test.dart create mode 100644 test/services/ssh_local_forward_test.dart create mode 100644 test/utils/ssh_config_parser_test.dart create mode 100644 test/widgets/keyboard_interactive_dialog_test.dart diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b8971a..df3a23f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +### Added + +- SSH keyboard-interactive authentication (2FA/TOTP prompts) with secure dialog. +- Opt-in OpenCode agent tunnel over SSH local forward to remote `127.0.0.1:agentPort`. +- Import OpenSSH `~/.ssh/config` from the connected host into profiles. +- Profile search, favorites pin, and duplicate in the profile manager. ## [1.3.0] - 2026-11-15 diff --git a/docs/features.md b/docs/features.md index de0b496..00dd797 100644 --- a/docs/features.md +++ b/docs/features.md @@ -2,9 +2,11 @@ ## SSH client -Connect to remote hosts with password or private-key auth. The built-in xterm -terminal supports colors, scrollback, and a shortcut bar for Ctrl, Alt, arrows, -and custom snippets. +Connect to remote hosts with password, private-key, or keyboard-interactive +(2FA/TOTP) auth. The built-in xterm terminal supports colors, scrollback, and a +shortcut bar for Ctrl, Alt, arrows, and custom snippets. Profiles can be +searched, pinned as favorites, duplicated, or imported from the host’s +`~/.ssh/config` over an active SFTP session. ### SFTP (Client + Agents) @@ -24,6 +26,10 @@ The **Agents** tab talks to an OpenCode HTTP API on the connected host. Sessions are scoped by project directory; slash commands handle model and provider configuration (`/model`, `/models`, `/connect`, `/agent`). +When OpenCode listens only on the Windows host loopback, enable **Tunnel agent +over SSH** on the profile: the app opens an SSH local forward to +`127.0.0.1:agentPort` and connects Agents through that tunnel. + ## Android extras - **Foreground service** keeps SSH and agent sessions alive in the background diff --git a/lib/main.dart b/lib/main.dart index 0c95945..d06ebcd 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -33,6 +33,7 @@ class MyApp extends StatelessWidget { update: (context, ssh, agent) { final provider = agent ?? AgentProvider(); provider.onLog = ssh.addLog; + provider.ssh = ssh; return provider; }, ), diff --git a/lib/models/agent_connection.dart b/lib/models/agent_connection.dart index a84e1f5..aefdce9 100644 --- a/lib/models/agent_connection.dart +++ b/lib/models/agent_connection.dart @@ -5,6 +5,7 @@ import 'package:opencode_api/opencode_api.dart'; import '../models/agent_model_option.dart'; import '../models/ssh_profile.dart'; import '../services/opencode_connection_service.dart'; +import '../services/ssh_local_forward.dart'; class AgentConnection { AgentConnection({ @@ -30,11 +31,14 @@ class AgentConnection { this.sessionInputTokens = 0, this.sessionOutputTokens = 0, this.sessionCost, + this.agentTunnel, }); final String id; final SSHProfile profile; final OpenCodeConnectionService service; + /// Active SSH local forward when [SSHProfile.tunnelAgent] is enabled. + final SshLocalForward? agentTunnel; List sessions; String? activeSessionId; List messages; @@ -74,5 +78,9 @@ class AgentConnection { unawaited(connectionEventSub?.cancel()); eventSub = null; connectionEventSub = null; + final tunnel = agentTunnel; + if (tunnel != null && !tunnel.isClosed) { + unawaited(tunnel.close()); + } } } diff --git a/lib/models/ssh_profile.dart b/lib/models/ssh_profile.dart index ed3676d..3fc3e77 100644 --- a/lib/models/ssh_profile.dart +++ b/lib/models/ssh_profile.dart @@ -22,6 +22,13 @@ class SSHProfile { final String? agentPassword; final SessionManager sessionManager; + /// When true, Agents HTTP goes through an SSH local forward to + /// `127.0.0.1:agentPort` on the remote host (for OpenCode bound to loopback). + final bool tunnelAgent; + + /// Pinned to the top of the profile list when true. + final bool isFavorite; + SSHProfile({ required this.name, required this.host, @@ -38,6 +45,8 @@ class SSHProfile { this.agentUsername = 'opencode', this.agentPassword, this.sessionManager = SessionManager.none, + this.tunnelAgent = false, + this.isFavorite = false, }) : id = id ?? const Uuid().v4(); String get agentBaseUrl => @@ -72,6 +81,8 @@ class SSHProfile { String? agentUsername, String? agentPassword, SessionManager? sessionManager, + bool? tunnelAgent, + bool? isFavorite, }) { return SSHProfile( id: id ?? this.id, @@ -89,6 +100,8 @@ class SSHProfile { agentUsername: agentUsername ?? this.agentUsername, agentPassword: agentPassword ?? this.agentPassword, sessionManager: sessionManager ?? this.sessionManager, + tunnelAgent: tunnelAgent ?? this.tunnelAgent, + isFavorite: isFavorite ?? this.isFavorite, ); } @@ -110,6 +123,8 @@ class SSHProfile { 'agentUsername': agentUsername, if (includePassword) 'agentPassword': agentPassword, 'sessionManager': sessionManager.name, + 'tunnelAgent': tunnelAgent, + 'isFavorite': isFavorite, }; } @@ -132,6 +147,8 @@ class SSHProfile { sessionManager: SessionManagerX.fromStorage( json['sessionManager'] as String?, ), + tunnelAgent: json['tunnelAgent'] as bool? ?? false, + isFavorite: json['isFavorite'] as bool? ?? false, ); } } diff --git a/lib/providers/agent_provider.dart b/lib/providers/agent_provider.dart index c44c1e1..2c9d068 100644 --- a/lib/providers/agent_provider.dart +++ b/lib/providers/agent_provider.dart @@ -8,9 +8,11 @@ import '../models/agent_connection.dart'; import '../models/agent_permission_request.dart'; import '../models/agent_prompt_attachment.dart'; import '../models/ssh_profile.dart'; +import '../providers/ssh_provider.dart'; import '../services/config_repository.dart'; import '../services/opencode_connection_service.dart'; import '../services/opencode_v2_mappers.dart'; +import '../services/ssh_local_forward.dart'; import '../utils/agent_prompt_utils.dart'; import '../utils/agent_session_utils.dart'; @@ -19,6 +21,10 @@ class AgentProvider extends ChangeNotifier { : _config = config ?? ConfigServiceRepository(); final ConfigRepository _config; + SSHProvider? _ssh; + + /// Wired from [ChangeNotifierProxyProvider] so agent tunnels can reuse SSH. + set ssh(SSHProvider value) => _ssh = value; final List _connections = []; String? _activeConnectionId; @@ -49,8 +55,17 @@ class AgentProvider extends ChangeNotifier { } Future connectFromProfile(SSHProfile profile) async { + SshLocalForward? tunnel; + var baseUrl = profile.agentBaseUrl; + + if (profile.tunnelAgent) { + final prepared = await _prepareAgentTunnel(profile); + tunnel = prepared.tunnel; + baseUrl = prepared.baseUrl; + } + final service = OpenCodeConnectionService( - baseUrl: profile.agentBaseUrl, + baseUrl: baseUrl, username: profile.effectiveAgentUsername, password: profile.effectiveAgentPassword, allowInsecureTls: profile.useHttps && profile.allowSelfSignedCerts, @@ -72,6 +87,7 @@ class AgentProvider extends ChangeNotifier { sessions: sessions, isConnected: true, selectedDirectory: directory, + agentTunnel: tunnel, ); _wireConnection(connection); @@ -79,7 +95,7 @@ class AgentProvider extends ChangeNotifier { _connections.add(connection); _activeConnectionId = connection.id; onLog?.call( - 'Agent connected: ${profile.name} (${profile.agentBaseUrl})', + 'Agent connected: ${profile.name} ($baseUrl)', ); notifyListeners(); // ignore: unawaited_futures @@ -87,10 +103,56 @@ class AgentProvider extends ChangeNotifier { return connection; } catch (e) { service.dispose(); + if (tunnel != null && !tunnel.isClosed) { + await tunnel.close(); + } rethrow; } } + /// Ensures an SSH session exists and opens a loopback forward to the agent. + Future<({SshLocalForward tunnel, String baseUrl})> _prepareAgentTunnel( + SSHProfile profile, + ) async { + final ssh = _ssh; + if (ssh == null) { + throw StateError( + 'SSH provider unavailable. Cannot tunnel agent without SSH.', + ); + } + + var session = ssh.findConnectedSessionForProfile(profile); + if (session == null) { + onLog?.call( + 'Agent tunnel: connecting SSH session for ${profile.name}...', + ); + session = ssh.createSessionFromProfile(profile, name: profile.name); + await ssh.connectSession(session.id); + session = ssh.findConnectedSessionForProfile(profile); + } + + final client = session?.client; + if (session == null || client == null || !session.isConnected) { + throw StateError( + 'No SSH session for ${profile.host}. Connect Client first, ' + 'or check credentials, then retry Agents with "Tunnel agent" enabled.', + ); + } + + final tunnel = await SshLocalForward.start( + client: client, + remoteHost: '127.0.0.1', + remotePort: profile.agentPort, + ); + final scheme = profile.useHttps ? 'https' : 'http'; + final baseUrl = '$scheme://127.0.0.1:${tunnel.localPort}'; + onLog?.call( + 'Agent tunnel ready: $baseUrl -> ' + '${profile.host} 127.0.0.1:${profile.agentPort}', + ); + return (tunnel: tunnel, baseUrl: baseUrl); + } + Future connectFromUrl({ required String url, String username = 'opencode', diff --git a/lib/providers/ssh_provider.dart b/lib/providers/ssh_provider.dart index 5aac007..f7d3ba4 100644 --- a/lib/providers/ssh_provider.dart +++ b/lib/providers/ssh_provider.dart @@ -135,6 +135,11 @@ class SSHProvider extends ChangeNotifier { required String presentedFingerprint, })? onHostKeyMismatch; + /// UI hook for SSH keyboard-interactive prompts (2FA/TOTP). Return null to + /// cancel / skip the method. When null, keyboard-interactive is not offered. + Future?> Function(SSHUserInfoRequest request)? + onUserInfoRequest; + Future loadConfig() async { var profileData = await _config.getProfiles(); final migratedProfiles = @@ -294,6 +299,17 @@ class SSHProvider extends ChangeNotifier { return null; } + /// Prefers a connected session for [profile.id], else any session to the host. + SessionEntry? findConnectedSessionForProfile(SSHProfile profile) { + for (final session in sessions) { + if (!session.isConnected || session.client == null) continue; + if (session.profile.id == profile.id) { + return session; + } + } + return findConnectedSessionForHost(profile.host); + } + bool _hostsMatch(String a, String b) { final na = a.toLowerCase(); final nb = b.toLowerCase(); @@ -309,7 +325,10 @@ class SSHProvider extends ChangeNotifier { try { addLog('Connecting to ${profile.host}:${profile.port}...'); final auth = await resolveSshAuthMaterial(profile); - if (!auth.hasKeyAuth && !auth.hasPasswordAuth) { + final canKeyboardInteractive = onUserInfoRequest != null; + if (!auth.hasKeyAuth && + !auth.hasPasswordAuth && + !canKeyboardInteractive) { throw StateError( 'No credentials: set a password or select an SSH key for this profile', ); @@ -325,6 +344,24 @@ class SSHProvider extends ChangeNotifier { username: profile.username, identities: auth.identities, onPasswordRequest: auth.hasPasswordAuth ? () => auth.password! : null, + onUserInfoRequest: canKeyboardInteractive + ? (request) async { + final hook = onUserInfoRequest; + if (hook == null) { + return null; + } + addLog( + 'Keyboard-interactive auth for ${profile.host}:${profile.port}', + ); + return hook(request); + } + : null, + onUserauthBanner: (banner) { + final trimmed = banner.trim(); + if (trimmed.isNotEmpty) { + addLog('SSH banner: $trimmed'); + } + }, keepAliveInterval: const Duration(seconds: 15), onVerifyHostKey: (type, fingerprintBytes) async { final fingerprint = String.fromCharCodes(fingerprintBytes); diff --git a/lib/screens/home_screen.dart b/lib/screens/home_screen.dart index f01d7a7..19c1f9c 100644 --- a/lib/screens/home_screen.dart +++ b/lib/screens/home_screen.dart @@ -12,6 +12,7 @@ import '../providers/settings_provider.dart'; import '../providers/ssh_provider.dart'; import '../widgets/log_viewer.dart'; import '../widgets/host_key_dialog.dart'; +import '../widgets/keyboard_interactive_dialog.dart'; import '../widgets/profile_manager.dart'; import '../widgets/key_manager.dart'; import '../widgets/keyboard_shortcut_bar.dart'; @@ -104,6 +105,12 @@ class _HomeScreenState extends State { presentedFingerprint: presentedFingerprint, ); }; + ssh.onUserInfoRequest = (request) { + if (!mounted) { + return Future?>.value(null); + } + return showKeyboardInteractiveDialog(context, request); + }; }); } diff --git a/lib/services/ssh_config_import_service.dart b/lib/services/ssh_config_import_service.dart new file mode 100644 index 0000000..5a845fd --- /dev/null +++ b/lib/services/ssh_config_import_service.dart @@ -0,0 +1,131 @@ +import 'package:dartssh2/dartssh2.dart'; + +import 'package:ssh_app/models/ssh_profile.dart'; +import 'package:ssh_app/services/sftp_helper.dart'; +import 'package:ssh_app/utils/ssh_config_parser.dart'; + +/// Outcome of importing OpenSSH config hosts into app profiles. +class SshConfigImportResult { + const SshConfigImportResult({ + required this.sourcePath, + required this.created, + required this.updated, + required this.skipped, + required this.identityHints, + required this.skippedDirectives, + }); + + final String sourcePath; + final int created; + final int updated; + final int skipped; + final List identityHints; + final List skippedDirectives; +} + +/// Reads remote OpenSSH config over SFTP and maps hosts to [SSHProfile]s. +class SshConfigImportService { + const SshConfigImportService(); + + /// Loads config from Windows then POSIX paths on [client]. + Future<({String path, String contents})?> readRemoteConfig({ + required SSHClient client, + required String username, + }) async { + final helper = SftpHelper(client); + try { + final candidates = [ + 'C:/Users/$username/.ssh/config', + '/home/$username/.ssh/config', + '/Users/$username/.ssh/config', + ]; + for (final path in candidates) { + try { + final text = await helper.readRemoteText(path); + if (text != null && text.trim().isNotEmpty) { + return (path: path, contents: text); + } + } catch (_) { + // Try next candidate. + } + } + return null; + } finally { + await helper.close(); + } + } + + /// Parses [contents] and merges into [existing] without touching passwords. + /// + /// Match key is host + port + user (case-insensitive host/user). + /// Returns updated profile list and a summary. + ({List profiles, SshConfigImportResult result}) mergeIntoProfiles({ + required List existing, + required String sourcePath, + required String contents, + required String fallbackUsername, + }) { + final parsed = parseSshConfig(contents); + final profiles = List.from(existing); + var created = 0; + var updated = 0; + var skipped = 0; + final identityHints = []; + final skippedDirectives = { + ...parsed.skippedDirectives, + }; + + for (final host in parsed.hosts) { + skippedDirectives.addAll(host.skippedDirectives); + final user = + host.user.isNotEmpty ? host.user : fallbackUsername; + if (host.hostName.isEmpty) { + skipped++; + continue; + } + + final identity = host.identityFile; + if (identity != null && identity.isNotEmpty) { + identityHints.add('${host.alias}: $identity'); + } + + final matchIndex = profiles.indexWhere( + (p) => + p.host.toLowerCase() == host.hostName.toLowerCase() && + p.port == host.port && + p.username.toLowerCase() == user.toLowerCase(), + ); + + if (matchIndex >= 0) { + final current = profiles[matchIndex]; + profiles[matchIndex] = current.copyWith( + name: host.alias.isNotEmpty ? host.alias : current.name, + ); + updated++; + } else { + profiles.add( + SSHProfile( + name: host.alias, + host: host.hostName, + port: host.port, + username: user, + ), + ); + created++; + } + } + + final sortedSkipped = skippedDirectives.toList()..sort(); + return ( + profiles: profiles, + result: SshConfigImportResult( + sourcePath: sourcePath, + created: created, + updated: updated, + skipped: skipped, + identityHints: identityHints, + skippedDirectives: sortedSkipped, + ), + ); + } +} diff --git a/lib/services/ssh_local_forward.dart b/lib/services/ssh_local_forward.dart new file mode 100644 index 0000000..16bc09a --- /dev/null +++ b/lib/services/ssh_local_forward.dart @@ -0,0 +1,144 @@ +import 'dart:async'; +import 'dart:io'; +import 'dart:typed_data'; + +import 'package:dartssh2/dartssh2.dart'; + +/// Dial callback used by [SshLocalForward] (defaults to [SSHClient.forwardLocal]). +typedef SshForwardDial = Future Function( + String remoteHost, + int remotePort, +); + +/// Listens on loopback and tunnels each accepted socket through SSH +/// `direct-tcpip` to a fixed remote host:port (agent OpenCode serve). +class SshLocalForward { + SshLocalForward._({ + required ServerSocket server, + required StreamSubscription acceptSub, + }) : _server = server, + _acceptSub = acceptSub, + localPort = server.port; + + final ServerSocket _server; + final StreamSubscription _acceptSub; + final List _localSockets = []; + final List _channels = []; + bool _closed = false; + + /// Bound local TCP port on 127.0.0.1. + final int localPort; + + /// Whether [close] has already been called. + bool get isClosed => _closed; + + /// Binds `127.0.0.1:0` and forwards each connection to + /// [remoteHost]:[remotePort] via [dial] (or [client.forwardLocal]). + static Future start({ + required SSHClient client, + required int remotePort, + String remoteHost = '127.0.0.1', + SshForwardDial? dial, + }) async { + final SshForwardDial effectiveDial = + dial ?? (host, port) => client.forwardLocal(host, port); + final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + late final SshLocalForward forward; + // Subscription lifetime is owned by [close]. + // ignore: cancel_subscriptions + final acceptSub = server.listen( + (Socket socket) { + // ignore: unawaited_futures + forward._handleClient(socket, effectiveDial, remoteHost, remotePort); + }, + onError: (_) {}, + cancelOnError: false, + ); + forward = SshLocalForward._(server: server, acceptSub: acceptSub); + return forward; + } + + /// Test helper: bind loopback only (no SSH dial). Accepted sockets are dropped. + static Future bindLoopbackForTest() async { + final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0); + late final SshLocalForward forward; + // Subscription lifetime is owned by [close]. + // ignore: cancel_subscriptions + final acceptSub = server.listen( + (Socket socket) { + forward._localSockets.add(socket); + socket.destroy(); + forward._localSockets.remove(socket); + }, + onError: (_) {}, + cancelOnError: false, + ); + forward = SshLocalForward._(server: server, acceptSub: acceptSub); + return forward; + } + + Future _handleClient( + Socket socket, + SshForwardDial dial, + String remoteHost, + int remotePort, + ) async { + if (_closed) { + socket.destroy(); + return; + } + _localSockets.add(socket); + SSHForwardChannel? channel; + try { + channel = await dial(remoteHost, remotePort); + _channels.add(channel); + socket.listen( + (List data) { + channel?.sink.add(data); + }, + onDone: () { + // ignore: unawaited_futures + channel?.close(); + }, + onError: (_) { + channel?.destroy(); + }, + cancelOnError: true, + ); + channel.stream.listen( + (Uint8List data) { + socket.add(data); + }, + onDone: () { + socket.destroy(); + }, + onError: (_) { + socket.destroy(); + }, + cancelOnError: true, + ); + } catch (_) { + socket.destroy(); + // ignore: unawaited_futures + channel?.close(); + } + } + + /// Stops accepting connections and closes active sockets/channels. + Future close() async { + if (_closed) { + return; + } + _closed = true; + await _acceptSub.cancel(); + await _server.close(); + for (final socket in List.from(_localSockets)) { + socket.destroy(); + } + _localSockets.clear(); + for (final channel in List.from(_channels)) { + channel.destroy(); + } + _channels.clear(); + } +} diff --git a/lib/utils/ssh_config_parser.dart b/lib/utils/ssh_config_parser.dart new file mode 100644 index 0000000..393ccaf --- /dev/null +++ b/lib/utils/ssh_config_parser.dart @@ -0,0 +1,207 @@ +/// One Host block extracted from an OpenSSH client config. +class SshConfigHostEntry { + const SshConfigHostEntry({ + required this.alias, + required this.hostName, + required this.user, + required this.port, + this.identityFile, + this.skippedDirectives = const [], + }); + + /// First pattern from the `Host` line (used as profile name). + final String alias; + + /// `HostName` or [alias] when HostName is omitted. + final String hostName; + + /// `User` directive, empty when unset. + final String user; + + /// `Port` directive, defaults to 22. + final int port; + + /// Optional `IdentityFile` path (hint only — never downloaded). + final String? identityFile; + + /// Directives that were present but not applied (ProxyJump, etc.). + final List skippedDirectives; +} + +/// Result of parsing an OpenSSH config document. +class SshConfigParseResult { + const SshConfigParseResult({ + required this.hosts, + this.skippedDirectives = const [], + }); + + final List hosts; + + /// Global / unmatched skipped directive names across the file. + final List skippedDirectives; +} + +/// Parses OpenSSH `~/.ssh/config` text into host entries. +/// +/// Supports `Host`, `HostName`, `User`, `Port`, and records `IdentityFile` +/// as a hint. `ProxyJump`, `ProxyCommand`, and other directives are collected +/// in [SshConfigHostEntry.skippedDirectives] / [SshConfigParseResult.skippedDirectives]. +/// Wildcards (`*`, `?`) in Host patterns are skipped. No secrets are returned. +SshConfigParseResult parseSshConfig(String contents) { + final hosts = []; + final globalSkipped = {}; + + _HostBuilder? current; + final pendingSkipped = []; + + void flush() { + final builder = current; + if (builder == null) { + return; + } + if (builder.alias.isEmpty || _isWildcardHost(builder.alias)) { + current = null; + pendingSkipped.clear(); + return; + } + hosts.add( + SshConfigHostEntry( + alias: builder.alias, + hostName: builder.hostName?.isNotEmpty == true + ? builder.hostName! + : builder.alias, + user: builder.user ?? '', + port: builder.port ?? 22, + identityFile: builder.identityFile, + skippedDirectives: List.from(builder.skipped), + ), + ); + current = null; + pendingSkipped.clear(); + } + + for (final rawLine in contents.split('\n')) { + final line = _stripComment(rawLine).trim(); + if (line.isEmpty) { + continue; + } + + final parts = line.split(RegExp(r'\s+')); + if (parts.isEmpty) { + continue; + } + final key = parts.first.toLowerCase(); + final value = parts.length > 1 ? parts.sublist(1).join(' ').trim() : ''; + + if (key == 'host') { + flush(); + final alias = value.split(RegExp(r'\s+')).firstWhere( + (p) => p.isNotEmpty, + orElse: () => '', + ); + if (alias.isEmpty || _isWildcardHost(alias)) { + current = null; + for (final token in value.split(RegExp(r'\s+'))) { + if (token.isNotEmpty) { + globalSkipped.add('Host $token'); + } + } + continue; + } + current = _HostBuilder(alias: alias); + current!.skipped.addAll(pendingSkipped); + pendingSkipped.clear(); + continue; + } + + final builder = current; + if (builder == null) { + if (_isKnownSkipDirective(key)) { + globalSkipped.add(_canonicalDirective(key)); + } + continue; + } + + switch (key) { + case 'hostname': + builder.hostName = value; + break; + case 'user': + builder.user = value; + break; + case 'port': + builder.port = int.tryParse(value) ?? builder.port; + break; + case 'identityfile': + builder.identityFile = value; + break; + default: + if (_isKnownSkipDirective(key) || key.isNotEmpty) { + builder.skipped.add(_canonicalDirective(key)); + } + } + } + flush(); + + return SshConfigParseResult( + hosts: hosts, + skippedDirectives: globalSkipped.toList()..sort(), + ); +} + +bool _isWildcardHost(String alias) => + alias.contains('*') || alias.contains('?') || alias.contains('!'); + +bool _isKnownSkipDirective(String key) { + const skipped = { + 'proxyjump', + 'proxycommand', + 'match', + 'include', + 'localforward', + 'remoteforward', + 'dynamicforward', + 'canonicaldomains', + 'canonicalizehostname', + }; + return skipped.contains(key); +} + +String _canonicalDirective(String key) { + switch (key) { + case 'proxyjump': + return 'ProxyJump'; + case 'proxycommand': + return 'ProxyCommand'; + case 'localforward': + return 'LocalForward'; + case 'remoteforward': + return 'RemoteForward'; + case 'dynamicforward': + return 'DynamicForward'; + default: + if (key.isEmpty) { + return key; + } + return key[0].toUpperCase() + key.substring(1); + } +} + +String _stripComment(String line) { + final hash = line.indexOf('#'); + if (hash < 0) { + return line; + } + return line.substring(0, hash); +} + +class _HostBuilder { + _HostBuilder({required this.alias}); + + final String alias; + String? hostName; + String? user; + int? port; + String? identityFile; + final List skipped = []; +} diff --git a/lib/widgets/keyboard_interactive_dialog.dart b/lib/widgets/keyboard_interactive_dialog.dart new file mode 100644 index 0000000..c546336 --- /dev/null +++ b/lib/widgets/keyboard_interactive_dialog.dart @@ -0,0 +1,112 @@ +import 'package:dartssh2/dartssh2.dart'; +import 'package:material_ui/material_ui.dart'; + +/// Collects answers for an SSH keyboard-interactive ([SSHUserInfoRequest]) prompt. +/// +/// Returns `null` when the user cancels so dartssh2 can skip the method or fail auth. +Future?> showKeyboardInteractiveDialog( + BuildContext context, + SSHUserInfoRequest request, +) async { + if (request.prompts.isEmpty) { + return []; + } + + return showDialog?>( + context: context, + barrierDismissible: false, + builder: (dialogContext) { + return _KeyboardInteractiveDialog(request: request); + }, + ); +} + +class _KeyboardInteractiveDialog extends StatefulWidget { + const _KeyboardInteractiveDialog({required this.request}); + + final SSHUserInfoRequest request; + + @override + State<_KeyboardInteractiveDialog> createState() => + _KeyboardInteractiveDialogState(); +} + +class _KeyboardInteractiveDialogState extends State<_KeyboardInteractiveDialog> { + late final List _controllers; + + @override + void initState() { + super.initState(); + _controllers = List.generate( + widget.request.prompts.length, + (_) => TextEditingController(), + ); + } + + @override + void dispose() { + for (final controller in _controllers) { + controller.dispose(); + } + super.dispose(); + } + + void _submit() { + Navigator.pop( + context, + _controllers.map((c) => c.text).toList(), + ); + } + + @override + Widget build(BuildContext context) { + final request = widget.request; + final title = request.name.trim().isEmpty + ? 'Authentication required' + : request.name.trim(); + final instruction = request.instruction.trim(); + + return AlertDialog( + title: Text(title), + content: SingleChildScrollView( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + if (instruction.isNotEmpty) ...[ + Text(instruction), + const SizedBox(height: 12), + ], + for (var i = 0; i < request.prompts.length; i++) ...[ + if (i > 0) const SizedBox(height: 8), + TextField( + controller: _controllers[i], + autofocus: i == 0, + obscureText: !request.prompts[i].echo, + decoration: InputDecoration( + labelText: request.prompts[i].promptText.trim().isEmpty + ? 'Response' + : request.prompts[i].promptText.trim(), + border: const OutlineInputBorder(), + ), + onSubmitted: i == request.prompts.length - 1 + ? (_) => _submit() + : null, + ), + ], + ], + ), + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(context, null), + child: const Text('Cancel'), + ), + ElevatedButton( + onPressed: _submit, + child: const Text('Continue'), + ), + ], + ); + } +} diff --git a/lib/widgets/profile_manager.dart b/lib/widgets/profile_manager.dart index 180aae2..212cda0 100644 --- a/lib/widgets/profile_manager.dart +++ b/lib/widgets/profile_manager.dart @@ -4,6 +4,7 @@ import '../providers/ssh_provider.dart'; import '../models/ssh_key.dart'; import '../models/ssh_profile.dart'; import '../services/config_service.dart'; +import '../services/ssh_config_import_service.dart'; import '../utils/session_manager.dart'; import '../utils/ssh_auth_utils.dart'; @@ -15,6 +16,36 @@ class ProfileManager extends StatefulWidget { } class _ProfileManagerState extends State { + final TextEditingController _searchController = TextEditingController(); + String _query = ''; + bool _importing = false; + + @override + void dispose() { + _searchController.dispose(); + super.dispose(); + } + + List _filteredSorted(List profiles) { + final q = _query.trim().toLowerCase(); + final filtered = q.isEmpty + ? List.from(profiles) + : profiles + .where((p) { + return p.name.toLowerCase().contains(q) || + p.host.toLowerCase().contains(q) || + p.username.toLowerCase().contains(q); + }) + .toList(); + filtered.sort((a, b) { + if (a.isFavorite != b.isFavorite) { + return a.isFavorite ? -1 : 1; + } + return a.name.toLowerCase().compareTo(b.name.toLowerCase()); + }); + return filtered; + } + @override Widget build(BuildContext context) { return DraggableScrollableSheet( @@ -38,14 +69,30 @@ class _ProfileManagerState extends State { ), ), Padding( - padding: const EdgeInsets.all(16.0), + padding: const EdgeInsets.symmetric(horizontal: 16.0), child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - const Text( - 'SSH Profiles', - style: - TextStyle(fontSize: 20, fontWeight: FontWeight.bold), + const Expanded( + child: Text( + 'SSH Profiles', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.bold, + ), + ), + ), + IconButton( + tooltip: 'Import ~/.ssh/config from connected host', + icon: _importing + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.download, color: Colors.orange), + onPressed: _importing + ? null + : () => _importSshConfig(context), ), IconButton( icon: const Icon(Icons.add, color: Colors.green), @@ -54,6 +101,19 @@ class _ProfileManagerState extends State { ], ), ), + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 8), + child: TextField( + controller: _searchController, + decoration: const InputDecoration( + prefixIcon: Icon(Icons.search), + hintText: 'Search name, host, user', + border: OutlineInputBorder(), + isDense: true, + ), + onChanged: (value) => setState(() => _query = value), + ), + ), Expanded( child: Consumer( builder: (context, ssh, child) { @@ -62,31 +122,66 @@ class _ProfileManagerState extends State { child: Text('No profiles saved yet'), ); } + final visible = _filteredSorted(ssh.profiles); + if (visible.isEmpty) { + return const Center( + child: Text('No profiles match the search'), + ); + } return ListView.builder( controller: scrollController, - itemCount: ssh.profiles.length, + itemCount: visible.length, itemBuilder: (context, index) { - final profile = ssh.profiles[index]; + final profile = visible[index]; return ListTile( - leading: const Icon( - Icons.computer, - color: Colors.blue, + leading: IconButton( + tooltip: profile.isFavorite + ? 'Unpin favorite' + : 'Pin favorite', + icon: Icon( + profile.isFavorite + ? Icons.star + : Icons.star_border, + color: profile.isFavorite + ? Colors.amber + : Colors.blue, + ), + onPressed: () { + ssh.saveProfile( + profile.copyWith( + isFavorite: !profile.isFavorite, + ), + ); + }, ), title: Text(profile.name), subtitle: Text( - 'SSH ${profile.host}:${profile.port} · Agent ${profile.agentBaseUrl}', + 'SSH ${profile.host}:${profile.port} · ' + 'Agent ${profile.agentBaseUrl}' + '${profile.tunnelAgent ? ' · tunnel' : ''}', ), trailing: Row( mainAxisSize: MainAxisSize.min, children: [ + IconButton( + tooltip: 'Duplicate', + icon: const Icon(Icons.copy, size: 20), + onPressed: () => + _duplicateProfile(context, profile), + ), IconButton( icon: const Icon(Icons.edit, size: 20), - onPressed: () => _showProfileDialog(context, - profile: profile), + onPressed: () => _showProfileDialog( + context, + profile: profile, + ), ), IconButton( - icon: const Icon(Icons.delete, - size: 20, color: Colors.red), + icon: const Icon( + Icons.delete, + size: 20, + color: Colors.red, + ), onPressed: () => _deleteProfile(context, profile.id), ), @@ -106,6 +201,104 @@ class _ProfileManagerState extends State { ); } + Future _importSshConfig(BuildContext context) async { + final ssh = Provider.of(context, listen: false); + final session = ssh.activeSession; + if (session == null || !session.isConnected || session.client == null) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Connect an SSH session first, then import config.'), + backgroundColor: Colors.orange, + ), + ); + return; + } + + setState(() => _importing = true); + try { + const importer = SshConfigImportService(); + final remote = await importer.readRemoteConfig( + client: session.client!, + username: session.profile.username, + ); + if (remote == null) { + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('No OpenSSH config found on the host.'), + backgroundColor: Colors.orange, + ), + ); + } + return; + } + + final merged = importer.mergeIntoProfiles( + existing: ssh.profiles, + sourcePath: remote.path, + contents: remote.contents, + fallbackUsername: session.profile.username, + ); + + for (final profile in merged.profiles) { + await ssh.saveProfile(profile); + } + + if (!context.mounted) { + return; + } + final r = merged.result; + final hint = r.identityHints.isEmpty + ? '' + : '\nIdentityFile hints: ${r.identityHints.take(3).join('; ')}'; + final skipped = r.skippedDirectives.isEmpty + ? '' + : '\nSkipped: ${r.skippedDirectives.take(5).join(', ')}'; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + 'Imported from ${r.sourcePath}: ' + '${r.created} created, ${r.updated} updated.$hint$skipped', + ), + ), + ); + } catch (e) { + if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Import failed: $e'), + backgroundColor: Colors.red, + ), + ); + } + } finally { + if (mounted) { + setState(() => _importing = false); + } + } + } + + void _duplicateProfile(BuildContext context, SSHProfile profile) { + final copy = SSHProfile( + name: '${profile.name} (copy)', + host: profile.host, + port: profile.port, + username: profile.username, + password: profile.password, + privateKey: profile.privateKey, + startupCommand: profile.startupCommand, + agentPort: profile.agentPort, + useHttps: profile.useHttps, + allowSelfSignedCerts: profile.allowSelfSignedCerts, + agentUsername: profile.agentUsername, + agentPassword: profile.agentPassword, + sessionManager: profile.sessionManager, + tunnelAgent: profile.tunnelAgent, + isFavorite: false, + ); + Provider.of(context, listen: false).saveProfile(copy); + } + void _showProfileDialog(BuildContext context, {SSHProfile? profile}) { final nameController = TextEditingController(text: profile?.name ?? ''); final hostController = TextEditingController(text: profile?.host ?? ''); @@ -128,6 +321,8 @@ class _ProfileManagerState extends State { TextEditingController(text: profile?.startupCommand ?? ''); var useHttps = profile?.useHttps ?? false; var allowSelfSignedCerts = profile?.allowSelfSignedCerts ?? false; + var tunnelAgent = profile?.tunnelAgent ?? false; + var isFavorite = profile?.isFavorite ?? false; var sessionManager = profile?.sessionManager ?? SessionManager.none; String? selectedKeyId = profile?.privateKey != null && !looksLikePemPrivateKey(profile!.privateKey!) @@ -227,7 +422,8 @@ class _ProfileManagerState extends State { (k) => DropdownMenuItem( value: k.id, child: Text( - '${k.name} (${k.keyType.displayName})'), + '${k.name} (${k.keyType.displayName})', + ), ), ), ], @@ -262,6 +458,22 @@ class _ProfileManagerState extends State { ), ), const SizedBox(height: 8), + SwitchListTile( + title: const Text('Favorite'), + value: isFavorite, + onChanged: (value) => + setDialogState(() => isFavorite = value), + ), + SwitchListTile( + title: const Text('Tunnel agent over SSH'), + subtitle: const Text( + 'Forward to 127.0.0.1:agentPort on the host ' + '(OpenCode bound to loopback). Requires SSH session.', + ), + value: tunnelAgent, + onChanged: (value) => + setDialogState(() => tunnelAgent = value), + ), SwitchListTile( title: const Text('Use HTTPS for Agent'), value: useHttps, @@ -325,6 +537,8 @@ class _ProfileManagerState extends State { ? null : agentPasswordController.text, sessionManager: sessionManager, + tunnelAgent: tunnelAgent, + isFavorite: isFavorite, ); Provider.of(context, listen: false) .saveProfile(newProfile); @@ -381,8 +595,9 @@ class _ProfileManagerState extends State { if (context.mounted) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( - content: Text('Connection failed: $e'), - backgroundColor: Colors.red), + content: Text('Connection failed: $e'), + backgroundColor: Colors.red, + ), ); } } diff --git a/suggestions.md b/suggestions.md index 0aad4ac..0b2b9d2 100644 --- a/suggestions.md +++ b/suggestions.md @@ -43,7 +43,7 @@ Proposal: - Zero out / drop decrypted key bytes after auth; never include private material in logs or `toJson()` (audit `SSHKey.toJson`, `SSHProfile.toJson`). - Add "Require passphrase to use key" setting. -### 1.5 Keyboard-interactive / 2FA and SSH-certificate auth (P0, M) +### 1.5 Keyboard-interactive / 2FA and SSH-certificate auth (P0, M) — **SHIPPED** (keyboard-interactive; certificates still open) Problem: password + static private key only. Many Windows hosts (primary target) and corporate servers require keyboard-interactive (2FA/TOTP) or certificates. Proposal: - Handle `dartssh2` keyboard-interactive prompts with a secure dialog (no echo, per-prompt labels). @@ -57,13 +57,13 @@ Proposal: ## 2. SSH connection core (P1) -### 2.1 SSH config import (`~/.ssh/config`) (P1, M) +### 2.1 SSH config import (`~/.ssh/config`) (P1, M) — **SHIPPED** (Host/HostName/User/Port + IdentityFile hints; ProxyJump still open) Import host, hostname, user, port, identity file, jump host from desktop/server `~/.ssh/config` over existing SFTP channel or file picker. Map to `SSHProfile` fields; report skipped directives. Reduces manual profile setup, the top onboarding friction. ### 2.2 Jump host / bastion support (P1, M) Add `jumpProfileId` to `SSHProfile`; `SSHProvider.connectClient()` dials bastion first, then tunnels (TCP forward via `dartssh2`) to target. UI: "Via jump host" picker in `ssh_client_form.dart`. Essential for Windows lab + cloud setups. -### 2.3 Local/remote port forwarding UI (P1, M) +### 2.3 Local/remote port forwarding UI (P1, M) — **PARTIAL** (agent tunnel opt-in via `tunnelAgent` + SSH local forward to remote loopback agent port; general forward rules UI still open) Problem: no forwarding found in codebase. Users cannot reach RDP, DBs, or OpenCode behind NAT. Proposal: per-profile forward rules (local port → remote host:port, reverse optional); active-forwards list with stop/start; conflict detection on local port bind. Persist in profile JSON. @@ -118,10 +118,10 @@ Open text preview → edit → save back with atomic rename + backup (`.bak`) op ## 5. Profiles, keys, snippets organization (P1–P2) -### 5.1 Folders, tags, favorites, search (P1, M) +### 5.1 Folders, tags, favorites, search (P1, M) — **SHIPPED** (search + favorites; folders/tags still open) Flat profile list does not scale. Add folders/tags + favorites pin + search bar in `ProfileManager`. Persist `folderId`, `tags`, `isFavorite` in profile JSON (backward compatible via nullable fields). -### 5.2 Duplicate, QR share, deep-link connect (P1, S) +### 5.2 Duplicate, QR share, deep-link connect (P1, S) — **SHIPPED** (duplicate; QR/`ssh://` still open) Duplicate-profile action; share a profile (host/port/username only, never secrets) via QR or `ssh://user@host:port` link; handle incoming links. Complements existing `sshapp://widget/ssh?profileId=` scheme. ### 5.3 `.ppk` (PuTTY) + OpenSSH import/export (P1, S) @@ -198,8 +198,9 @@ Profile long-scrollback rendering and large SFTP directories (1k+ entries); virt ## Suggested build order (if resourced as 3 milestones) 1. **Trust release (1.1, 1.3, 1.4, 2.4):** host-key trust, encrypted backup, key hygiene, keepalive/reconnect. Ships as 1.3.0. -2. **Daily-driver release (2.5, 3.1, 4.1–4.3, 5.1):** multi-session tabs, scrollback search, transfer queue + checksums, profile folders/search. Ships as 1.4.0. -3. **Agent-power release (6.1, 6.2, 6.4, 8.1, 8.5):** attachments, diff review, cost footer, first locale, onboarding wizard. Ships as 1.5.0. +2. **Daily-driver release (2.5, 3.1, 4.1–4.3, 5.1):** multi-session tabs, scrollback search, transfer queue + checksums, profile folders/search. (Core shipped across 1.2–1.3; search/favorites in 1.4.) +3. **Host-access release (1.5 kbd-interactive, 2.1 config import, 2.3 agent tunnel):** Windows OpenSSH reachability. Ships as 1.4.0. +4. **Agent-power / polish (8.1, 8.5, 2.2 jump, certificates):** first locale, onboarding wizard, jump host. Ships as 1.5.0. ## Out of scope (deliberately not suggested) diff --git a/test/models/ssh_profile_agent_auth_test.dart b/test/models/ssh_profile_agent_auth_test.dart index da2e7d3..3285799 100644 --- a/test/models/ssh_profile_agent_auth_test.dart +++ b/test/models/ssh_profile_agent_auth_test.dart @@ -77,5 +77,29 @@ void main() { expect(profile.useHttps, isTrue); expect(profile.allowSelfSignedCerts, isTrue); }); + + test('fromJson defaults tunnelAgent and isFavorite when missing', () { + final profile = SSHProfile.fromJson({ + 'id': 'legacy', + 'name': 'n', + 'host': 'h', + 'username': 'u', + }); + expect(profile.tunnelAgent, isFalse); + expect(profile.isFavorite, isFalse); + }); + + test('toJson round-trips tunnelAgent and isFavorite', () { + final profile = SSHProfile( + name: 'n', + host: 'h', + username: 'u', + tunnelAgent: true, + isFavorite: true, + ); + final restored = SSHProfile.fromJson(profile.toJson()); + expect(restored.tunnelAgent, isTrue); + expect(restored.isFavorite, isTrue); + }); }); } diff --git a/test/services/ssh_config_import_service_test.dart b/test/services/ssh_config_import_service_test.dart new file mode 100644 index 0000000..8f6cf59 --- /dev/null +++ b/test/services/ssh_config_import_service_test.dart @@ -0,0 +1,52 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:ssh_app/models/ssh_profile.dart'; +import 'package:ssh_app/services/ssh_config_import_service.dart'; + +void main() { + group('SshConfigImportService.mergeIntoProfiles', () { + test('creates and updates without overwriting passwords', () { + const importer = SshConfigImportService(); + final existing = [ + SSHProfile( + id: 'keep-id', + name: 'Old Name', + host: '192.168.1.10', + port: 2222, + username: 'lukas', + password: '<>', + ), + ]; + + const raw = ''' +Host lab + HostName 192.168.1.10 + User lukas + Port 2222 + +Host other + HostName 10.0.0.2 + User admin +'''; + + final merged = importer.mergeIntoProfiles( + existing: existing, + sourcePath: 'C:/Users/lukas/.ssh/config', + contents: raw, + fallbackUsername: 'lukas', + ); + + expect(merged.result.created, 1); + expect(merged.result.updated, 1); + expect(merged.profiles, hasLength(2)); + + final updated = merged.profiles.firstWhere((p) => p.id == 'keep-id'); + expect(updated.name, 'lab'); + expect(updated.password, '<>'); + + final created = merged.profiles.firstWhere((p) => p.name == 'other'); + expect(created.host, '10.0.0.2'); + expect(created.username, 'admin'); + expect(created.password, isNull); + }); + }); +} diff --git a/test/services/ssh_local_forward_test.dart b/test/services/ssh_local_forward_test.dart new file mode 100644 index 0000000..c955157 --- /dev/null +++ b/test/services/ssh_local_forward_test.dart @@ -0,0 +1,34 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:ssh_app/services/ssh_local_forward.dart'; + +void main() { + group('SshLocalForward', () { + test('bindLoopbackForTest listens on 127.0.0.1 and close frees the port', + () async { + final forward = await SshLocalForward.bindLoopbackForTest(); + expect(forward.isClosed, isFalse); + expect(forward.localPort, greaterThan(0)); + + final probe = await Socket.connect( + InternetAddress.loopbackIPv4, + forward.localPort, + ); + await probe.close(); + + await forward.close(); + expect(forward.isClosed, isTrue); + + await forward.close(); // idempotent + + expect( + () => Socket.connect( + InternetAddress.loopbackIPv4, + forward.localPort, + ), + throwsA(isA()), + ); + }); + }); +} diff --git a/test/utils/ssh_config_parser_test.dart b/test/utils/ssh_config_parser_test.dart new file mode 100644 index 0000000..eaaa997 --- /dev/null +++ b/test/utils/ssh_config_parser_test.dart @@ -0,0 +1,71 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:ssh_app/utils/ssh_config_parser.dart'; + +void main() { + group('parseSshConfig', () { + test('parses multiple hosts with HostName Port User defaults', () { + const raw = ''' +# comment +Host lab + HostName 192.168.1.10 + User lukas + Port 2222 + IdentityFile ~/.ssh/id_ed25519 + +Host bare + User admin + +Host * + Compression yes +'''; + final result = parseSshConfig(raw); + expect(result.hosts, hasLength(2)); + + final lab = result.hosts.first; + expect(lab.alias, 'lab'); + expect(lab.hostName, '192.168.1.10'); + expect(lab.user, 'lukas'); + expect(lab.port, 2222); + expect(lab.identityFile, '~/.ssh/id_ed25519'); + + final bare = result.hosts[1]; + expect(bare.alias, 'bare'); + expect(bare.hostName, 'bare'); + expect(bare.user, 'admin'); + expect(bare.port, 22); + }); + + test('records skipped ProxyJump and does not leak secrets', () { + const raw = ''' +Host jumpbox + HostName bastion.example + User ops + ProxyJump jump@gateway + ProxyCommand ssh -W %h:%p gateway + PasswordAuthentication yes +'''; + final result = parseSshConfig(raw); + expect(result.hosts, hasLength(1)); + final host = result.hosts.single; + expect(host.skippedDirectives, contains('ProxyJump')); + expect(host.skippedDirectives, contains('ProxyCommand')); + final encoded = '${host.alias}|${host.hostName}|${host.user}|' + '${host.port}|${host.identityFile}|${host.skippedDirectives}'; + expect(encoded.contains('password'), isFalse); + expect(encoded.toLowerCase().contains('secret'), isFalse); + }); + + test('skips wildcard Host patterns', () { + const raw = ''' +Host *.internal + User nobody + +Host real + HostName 10.0.0.5 +'''; + final result = parseSshConfig(raw); + expect(result.hosts, hasLength(1)); + expect(result.hosts.single.alias, 'real'); + }); + }); +} diff --git a/test/widgets/keyboard_interactive_dialog_test.dart b/test/widgets/keyboard_interactive_dialog_test.dart new file mode 100644 index 0000000..84a6265 --- /dev/null +++ b/test/widgets/keyboard_interactive_dialog_test.dart @@ -0,0 +1,93 @@ +import 'package:dartssh2/dartssh2.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:material_ui/material_ui.dart'; +import 'package:ssh_app/widgets/keyboard_interactive_dialog.dart'; + +void main() { + group('showKeyboardInteractiveDialog', () { + testWidgets('masks echo=false and returns answers', (tester) async { + List? answers; + + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) { + return TextButton( + onPressed: () async { + answers = await showKeyboardInteractiveDialog( + context, + SSHUserInfoRequest( + '2FA', + 'Enter codes', + [ + SSHUserInfoPrompt('Visible: ', true), + SSHUserInfoPrompt('TOTP: ', false), + ], + ), + ); + }, + child: const Text('Open'), + ); + }, + ), + ), + ); + + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + + expect(find.text('2FA'), findsOneWidget); + expect(find.text('Enter codes'), findsOneWidget); + + final fields = find.byType(TextField); + expect(fields, findsNWidgets(2)); + + final visible = tester.widget(fields.at(0)); + final secret = tester.widget(fields.at(1)); + expect(visible.obscureText, isFalse); + expect(secret.obscureText, isTrue); + + await tester.enterText(fields.at(0), 'alice'); + await tester.enterText(fields.at(1), '123456'); + await tester.tap(find.text('Continue')); + await tester.pumpAndSettle(); + + expect(answers, ['alice', '123456']); + }); + + testWidgets('cancel returns null', (tester) async { + List? answers = ['sentinel']; + + await tester.pumpWidget( + MaterialApp( + home: Builder( + builder: (context) { + return TextButton( + onPressed: () async { + answers = await showKeyboardInteractiveDialog( + context, + SSHUserInfoRequest( + '', + '', + [ + SSHUserInfoPrompt('Password: ', false), + ], + ), + ); + }, + child: const Text('Open'), + ); + }, + ), + ), + ); + + await tester.tap(find.text('Open')); + await tester.pumpAndSettle(); + await tester.tap(find.text('Cancel')); + await tester.pumpAndSettle(); + + expect(answers, isNull); + }); + }); +}