Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,7 @@ class _YourSSHAppState extends State<YourSSHApp> with WindowListener {
_hostProvider = HostProvider(_storage);
_keyProvider = KeyProvider();
_keyProvider.savePassphrase = _storage.savePassphrase;
_keyProvider.deletePassphrase = _storage.deletePassphrase;
_settingsProvider = SettingsProvider();
_ssh.isShellIntegrationEnabled =
() => _settingsProvider.shellIntegrationEnabled;
Expand Down
4 changes: 3 additions & 1 deletion app/lib/mobile/mobile_bootstrap.dart
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,9 @@ class MobileBootstrap {
storage = StorageService();
ssh = SshService(storage);
hostProvider = HostProvider(storage);
keyProvider = KeyProvider()..savePassphrase = storage.savePassphrase;
keyProvider = KeyProvider()
..savePassphrase = storage.savePassphrase
..deletePassphrase = storage.deletePassphrase;
settings = SettingsProvider();
knownHosts = KnownHostsProvider(storage)..load();
sessions = SessionProvider(ssh, TabMetadataService());
Expand Down
46 changes: 0 additions & 46 deletions app/lib/mobile/screens/mobile_add_host_screen.dart
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:yourssh_ui/yourssh_ui.dart';

import '../../models/host.dart';
import '../../models/ssh_key.dart';
import '../../providers/host_provider.dart';
import '../../providers/key_provider.dart';
import '../../providers/session_provider.dart';
import '../security/app_lock_gate.dart';
import '../theme/mobile_theme.dart';
import '../theme/mobile_tokens.dart';
import '../widgets/button_label.dart';
import '../widgets/list_group.dart';
import '../widgets/section_header.dart';
import '../widgets/settings_row.dart';

/// Grouped add/edit host form for mobile (Design 02).
///
Expand Down Expand Up @@ -348,7 +345,6 @@ class _MobileAddHostScreenState extends State<MobileAddHostScreen> {
hint: _isEdit ? 'Leave blank to keep current' : null,
textInputAction: TextInputAction.done,
),
const ListGroup(children: [_BiometricRow()]),
]);
}

Expand Down Expand Up @@ -560,45 +556,3 @@ class _CertAgentNoteRow extends StatelessWidget {
);
}
}

/// Toggle row for Face ID / biometric app-lock (reads/writes
/// [kAppLockPrefKey] in SharedPreferences — same key as AppLockGate).
class _BiometricRow extends StatefulWidget {
const _BiometricRow();

@override
State<_BiometricRow> createState() => _BiometricRowState();
}

class _BiometricRowState extends State<_BiometricRow> {
bool _enabled = true;
bool _loaded = false;

@override
void initState() {
super.initState();
SharedPreferences.getInstance().then((p) {
if (!mounted) return;
setState(() {
_enabled = p.getBool(kAppLockPrefKey) ?? true;
_loaded = true;
});
});
}

Future<void> _toggle(bool v) async {
setState(() => _enabled = v);
final p = await SharedPreferences.getInstance();
await p.setBool(kAppLockPrefKey, v);
}

@override
Widget build(BuildContext context) {
if (!_loaded) return const SizedBox.shrink();
return SettingsRow(
title: 'Unlock with biometrics',
toggle: _enabled,
onToggle: _toggle,
);
}
}
2 changes: 1 addition & 1 deletion app/lib/mobile/screens/mobile_settings_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ class _MobileSettingsScreenState extends State<MobileSettingsScreen> {
SettingsRow(
leading: const Icon(FLucideIcons.timer, color: MobileColors.textMuted, size: 20),
title: 'Auto-lock',
value: 'After 1 min',
value: 'Immediately when you leave the app',
),
],
);
Expand Down
6 changes: 3 additions & 3 deletions app/lib/mobile/screens/mobile_sync_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -271,11 +271,11 @@ class _MobileSyncScreenState extends State<MobileSyncScreen> {
Widget _buildHero() => Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Sync with Supabase', style: mobileHeading(size: 22)),
Text('Sync between devices', style: mobileHeading(size: 22)),
const SizedBox(height: MobileTokens.space2),
Text(
'No account needed. Your hosts, keys & snippets stay end-to-end '
'encrypted across devices.',
'No account needed. Syncs your hosts and their passwords. '
'Keys and snippets are not synced.',
style: mobileBody(size: 14, color: MobileColors.textMuted),
),
],
Expand Down
46 changes: 44 additions & 2 deletions app/lib/providers/key_provider.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import '../models/ssh_key.dart';

class KeyProvider extends ChangeNotifier {
static const _prefsKey = 'yourssh.keys';
static const _dismissedKey = 'yourssh.keys.dismissed';
List<SshKeyEntry> _keys = [];

List<SshKeyEntry> get keys => _keys;
Expand All @@ -18,7 +19,11 @@ class KeyProvider extends ChangeNotifier {
/// read the real home directory.
final bool discoverSshKeys;

KeyProvider({this.discoverSshKeys = true}) {
/// Directory scanned by auto-discovery; defaults to `~/.ssh`. Tests inject a
/// temp dir.
final String? sshDirPath;

KeyProvider({this.discoverSshKeys = true, this.sshDirPath}) {
ready = _load();
}

Expand All @@ -40,8 +45,10 @@ class KeyProvider extends ChangeNotifier {
}

Future<void> _discoverSshKeys() async {
final sshDir = Directory(p.join(Platform.environment['HOME'] ?? '', '.ssh'));
final sshDir = Directory(
sshDirPath ?? p.join(Platform.environment['HOME'] ?? '', '.ssh'));
if (!sshDir.existsSync()) return;
final dismissed = await _loadDismissed();

final knownPrivate = {'id_ed25519', 'id_rsa', 'id_ecdsa', 'id_dsa'};
for (final name in knownPrivate) {
Expand All @@ -50,6 +57,8 @@ class KeyProvider extends ChangeNotifier {
if (!keyFile.existsSync()) continue;
// Skip already registered keys
if (_keys.any((k) => k.privateKeyPath == keyFile.path)) continue;
// Skip keys the user removed earlier
if (dismissed.contains(keyFile.path)) continue;

final algo = _algorithmFrom(name);
final pubKey = pubFile.existsSync() ? pubFile.readAsStringSync().trim() : '';
Expand Down Expand Up @@ -78,6 +87,24 @@ class KeyProvider extends ChangeNotifier {
/// main.dart — StorageService is not in the provider tree).
Future<void> Function(String keyId, String passphrase)? savePassphrase;

/// Deletes a key's stored passphrase (wired to
/// StorageService.deletePassphrase in main.dart / mobile bootstrap).
Future<void> Function(String keyId)? deletePassphrase;

Future<Set<String>> _loadDismissed() async {
final prefs = await SharedPreferences.getInstance();
return (prefs.getStringList(_dismissedKey) ?? const []).toSet();
}

Future<void> _saveDismissed(Set<String> paths) async {
final prefs = await SharedPreferences.getInstance();
if (paths.isEmpty) {
await prefs.remove(_dismissedKey);
} else {
await prefs.setStringList(_dismissedKey, paths.toList());
}
}

Future<SshKeyEntry> addKeyFromFile(String path, String label) async {
final file = File(path);
if (!file.existsSync()) throw Exception('Key file not found: $path');
Expand All @@ -93,6 +120,9 @@ class KeyProvider extends ChangeNotifier {
privateKeyPath: path,
);
_keys.add(entry);
// Explicit re-import clears an earlier dismissal of this path.
final dismissed = await _loadDismissed();
if (dismissed.remove(path)) await _saveDismissed(dismissed);
final certFile = File('$path-cert.pub');
if (certFile.existsSync()) {
_keys.last.certificatePath = certFile.path;
Expand All @@ -103,8 +133,20 @@ class KeyProvider extends ChangeNotifier {
}

Future<void> deleteKey(String id) async {
final removed = findById(id);
_keys.removeWhere((k) => k.id == id);
await _save();
// Remember the path so auto-discovery doesn't re-add it next launch.
final path = removed?.privateKeyPath;
if (path != null && path.isNotEmpty) {
final dismissed = await _loadDismissed();
if (dismissed.add(path)) await _saveDismissed(dismissed);
}
try {
await deletePassphrase?.call(id);
} catch (e) {
debugPrint('[KeyProvider] failed to delete passphrase for $id: $e');
}
notifyListeners();
}

Expand Down
2 changes: 2 additions & 0 deletions app/lib/services/storage_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,8 @@ class StorageService {

Future<String?> loadPassphrase(String keyId) => _loadSecret('pp_$keyId');

Future<void> deletePassphrase(String keyId) => _deleteSecret('pp_$keyId');

/// Generic secret store for app-scoped secrets (e.g., sync passphrase).
/// Caller is responsible for key namespacing.
Future<void> saveGenericSecret(String key, String value) =>
Expand Down
4 changes: 2 additions & 2 deletions app/test/mobile/mobile_settings_screen_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ void main() {
await tester.pump(const Duration(milliseconds: 200));

// MobileSyncScreen heading must be visible.
expect(find.text('Sync with Supabase'), findsOneWidget);
expect(find.text('Sync between devices'), findsOneWidget);
expect(find.byType(MobileSyncScreen), findsOneWidget);
});

Expand All @@ -79,6 +79,6 @@ void main() {
await tester.pump();
await tester.pump(const Duration(milliseconds: 200));
expect(find.byType(MobileSyncScreen), findsOneWidget);
expect(find.text('Sync with Supabase'), findsOneWidget);
expect(find.text('Sync between devices'), findsOneWidget);
});
}
25 changes: 4 additions & 21 deletions app/test/mobile/screens/add_host_screen_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'package:yourssh/mobile/screens/mobile_add_host_screen.dart';
import 'package:yourssh/mobile/security/app_lock_gate.dart';
import 'package:yourssh/mobile/theme/mobile_theme.dart';
import 'package:yourssh/models/app_session.dart';
import 'package:yourssh/theme/app_theme.dart';
Expand Down Expand Up @@ -222,32 +221,16 @@ void main() {
expect(_editable(tester, snippetField).controller.text, 'tmux attach');
});

// ── Fix 1: biometric toggle uses the shared kAppLockPrefKey ─────────────
// The app lock lives in Settings -> Security, not in the per-host form.

testWidgets('biometric toggle persists under shared kAppLockPrefKey',
(tester) async {
testWidgets('host form has no app-lock / biometric switch', (tester) async {
SharedPreferences.setMockInitialValues({});
final hosts = HostProvider(StorageService());
await tester.pumpWidget(_wrap(hosts, const MobileAddHostScreen()));
await tester.pumpAndSettle();

// The switch should be present and enabled by default (kAppLockPrefKey
// absent → defaults to true).
final switchFinder = find.byType(FSwitch);
expect(switchFinder, findsOneWidget);
expect(tester.widget<FSwitch>(switchFinder).value, isTrue);

// Toggle it off.
await tester.ensureVisible(switchFinder);
await tester.pumpAndSettle();
await tester.tap(switchFinder);
await tester.pumpAndSettle();

final prefs = await SharedPreferences.getInstance();
// Must write under the SHARED key, not a local orphan key.
expect(prefs.getBool(kAppLockPrefKey), isFalse);
// The old orphan key must not exist.
expect(prefs.getBool('yourssh.app_lock_enabled'), isNull);
expect(find.byType(FSwitch), findsNothing);
expect(find.text('Unlock with biometrics'), findsNothing);
});

// ── Fix 2: "Save & connect" wires connectAny; plain "Save" does not ─────
Expand Down
2 changes: 1 addition & 1 deletion app/test/mobile/screens/settings_screen_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ void main() {
for (final t in [
'Biometric unlock',
'Auto-lock',
'After 1 min',
'Immediately when you leave the app',
'Shortcut key bar',
'Supabase sync',
'Pair new device',
Expand Down
6 changes: 4 additions & 2 deletions app/test/mobile/screens/sync_screen_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,9 +64,11 @@ Future<SyncProvider> _pump(
void main() {
setUp(() => SharedPreferences.setMockInitialValues({}));

testWidgets('renders heading "Sync with Supabase"', (tester) async {
testWidgets('renders heading "Sync between devices"', (tester) async {
await _pump(tester);
expect(find.text('Sync with Supabase'), findsOneWidget);
expect(find.text('Sync between devices'), findsOneWidget);
expect(find.textContaining('Keys and snippets are not synced'), findsOneWidget);
expect(find.textContaining('end-to-end'), findsNothing);
});

testWidgets('renders "Scan QR code" button', (tester) async {
Expand Down
70 changes: 70 additions & 0 deletions app/test/providers/key_provider_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ void main() {
TestWidgetsFlutterBinding.ensureInitialized();

setUp(() => SharedPreferences.setMockInitialValues({}));
_keyRemovalTests();

group('KeyProvider certificate methods', () {
test('setCertificate persists certificatePath on the key entry', () async {
Expand Down Expand Up @@ -58,3 +59,72 @@ String _tmpKeyFile() {
f.writeAsStringSync('placeholder');
return f.path;
}

void _keyRemovalTests() {
group('KeyProvider removal', () {
late Directory sshDir;
setUp(() {
SharedPreferences.setMockInitialValues({});
sshDir = Directory.systemTemp.createTempSync('ssh_dir_');
File('${sshDir.path}/id_ed25519').writeAsStringSync('k');
File('${sshDir.path}/id_ed25519.pub').writeAsStringSync('pub');
});
tearDown(() => sshDir.deleteSync(recursive: true));

test('deleteKey deletes the stored passphrase', () async {
final provider = KeyProvider(discoverSshKeys: false);
await provider.ready;
final deleted = <String>[];
provider.deletePassphrase = (id) async => deleted.add(id);
final entry = await provider.addKeyFromFile(_tmpKeyFile(), 'k');

await provider.deleteKey(entry.id);

expect(deleted, [entry.id]);
});

test('a failing passphrase delete does not break removal', () async {
final provider = KeyProvider(discoverSshKeys: false);
await provider.ready;
provider.deletePassphrase = (id) async => throw Exception('boom');
final entry = await provider.addKeyFromFile(_tmpKeyFile(), 'k');

await provider.deleteKey(entry.id);

expect(provider.keys, isEmpty);
});

test('removed auto-discovered key is not re-added on next launch', () async {
final first = KeyProvider(sshDirPath: sshDir.path);
await first.ready;
expect(first.keys, hasLength(1));
await first.deleteKey(first.keys.first.id);

final second = KeyProvider(sshDirPath: sshDir.path);
await second.ready;

expect(second.keys, isEmpty);
});

test('explicit re-import clears the dismissal', () async {
final first = KeyProvider(sshDirPath: sshDir.path);
await first.ready;
await first.deleteKey(first.keys.first.id);

final second = KeyProvider(sshDirPath: sshDir.path);
await second.ready;
await second.addKeyFromFile('${sshDir.path}/id_ed25519', 'again');
expect(second.keys, hasLength(1));
await second.deleteKey(second.keys.first.id);

// Re-import then (no) removal: dismissal was cleared, so re-importing
// and relaunching keeps the key.
final third = KeyProvider(sshDirPath: sshDir.path);
await third.ready;
await third.addKeyFromFile('${sshDir.path}/id_ed25519', 'again');
final fourth = KeyProvider(sshDirPath: sshDir.path);
await fourth.ready;
expect(fourth.keys, hasLength(1));
});
});
}
Loading