What changed, and why it matters
This commit is a routine code reorganization: it moves the app's lock/unlock logic out of the wallet's main screen files and into a shared 'wallet-core' component. The actual behavior of the lock screen, password checks, and biometric unlock appears unchanged; only which file contains the code has changed. There is no indication this fixes or introduces a security vulnerability.
No security action required. Treat as a normal maintainability refactor. If reviewing, verify that the moved helpers in wallet_fhse preserve the original behavior (password recheck, wallet unlock, security-key handoff, and error handling).
Security signals we found
No strong security signals were identified.
Evidence from the diff
The patch refactors Flutter/Dart code in Skylight Wallet. In lib/main.dart, the AppRootState no longer directly manages AppLockTimer, SecurityKeyFullLock, DesktopAutoLock, lifecycle observers, and cover logic; instead it mixes in AppLockLifecycle and delegates to buildAppLock(). In lib/screens/unlock.dart, the inline biometric prompt, password recheck, wallet open, and navigation logic is replaced by calls to wallet_fhse helpers: unlockAppLockWithDevice(), unlockAppLockWithPassword(), and an AppLockUnlock outcome enum. In lib/wallet_core_glue.dart, the local recheckPasswordIfOpen() and unlockWithPassword() helpers are removed because they now live in wallet_fhse. Imports are updated accordingly. No functional security change is visible in the diff.
Changed components
lib/main.dartlib/screens/unlock.dartlib/wallet_core_glue.dartInspect captured patch +68 / −308
### lib/main.dart
@@ -3,7 +3,6 @@ import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
-import 'package:flutter/services.dart' show HardwareKeyboard, KeyEvent;
import 'package:provider/provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:skeletonizer/skeletonizer.dart';
@@ -53,7 +52,7 @@ import 'package:skylight_wallet/wallet_core_glue.dart';
import 'package:wallet_backup_platform/backup_ui.dart';
import 'package:wallet_domain/wallet_domain.dart' show AppSession, WalletManager, parsePaymentUri;
import 'package:wallet_fhse/security_keys_ui.dart';
-import 'package:wallet_infra/wallet_infra.dart' show BiometricAuth, HostPlatform;
+import 'package:wallet_infra/wallet_infra.dart' show HostPlatform;
void main() async {
// Catch all uncaught async errors
@@ -143,7 +142,8 @@ class _AppRoot extends StatefulWidget {
State<_AppRoot> createState() => _AppRootState();
}
-class _AppRootState extends State<_AppRoot> with WidgetsBindingObserver {
+class _AppRootState extends State<_AppRoot>
+ with WidgetsBindingObserver, AppLockLifecycle<_AppRoot> {
// Started once, on the first build. Building it inside the builder would
// re-run it on every theme/language change, opening the wallet again — a
// second wallet on the same file, with its own sync loop, while the first is
@@ -162,32 +162,13 @@ class _AppRootState extends State<_AppRoot> with WidgetsBindingObserver {
final _CurrentRouteObserver _routeObserver = _CurrentRouteObserver();
Brightness? _lastBrightness;
- // App Lock over the screens the user left (a relock): drawn above the
- // navigator ([AppLockCover]), so a screen finishing something under it
- // cannot pop it the way it could pop a route.
- final _cover = ValueNotifier<bool>(false);
-
// Every route the platform pushes is dropped; payment links (monero:) come
// over PaymentLinkChannel instead and wait in the gate until the user is past
// every lock (AppSession) and on a screen behind them.
final _routeLinkBlocker = RouteLinkBlocker();
late final PaymentLinkGate _paymentLinks;
static const _paymentUriSchemes = {'monero'};
- // App Lock (always on): its "Lock after" time in the background, on mobile.
- final _appLock = AppLockTimer();
- // Set when the app reaches `paused`, so the way back is noticed at its first
- // step (`hidden`), before a link that resumed it could land.
- bool _wasPaused = false;
-
- // "Fully lock after", with security keys on.
- final _fullLock = SecurityKeyFullLock();
-
- // "Lock after" a time without use, on a desktop OS: the full close.
- final _desktopLock = DesktopAutoLock();
- // App Lock's shorter time without use, on a desktop OS: covers the app.
- final _desktopAppLock = DesktopAutoLock.appLock();
-
static void _markSubtreeDirty(Element element) {
element.markNeedsBuild();
element.visitChildren(_markSubtreeDirty);
@@ -269,21 +250,10 @@ class _AppRootState extends State<_AppRoot> with WidgetsBindingObserver {
open: _openPaymentUri,
);
unawaited(PaymentLinkChannel.listen(_paymentLinks.offer));
- if (isDesktopOS) {
- HardwareKeyboard.instance.addHandler(_onKey);
- _desktopLock.start(_lockDesktop);
- _desktopAppLock.start(_coverDesktop);
- }
}
@override
void dispose() {
- _cover.dispose();
- _appLock.dispose();
- _fullLock.dispose();
- _desktopLock.dispose();
- _desktopAppLock.dispose();
- if (isDesktopOS) HardwareKeyboard.instance.removeHandler(_onKey);
WidgetsBinding.instance.removeObserver(this);
WidgetsBinding.instance.removeObserver(_routeLinkBlocker);
_paymentLinks.dispose();
@@ -319,156 +289,24 @@ class _AppRootState extends State<_AppRoot> with WidgetsBindingObserver {
);
}
- /// The system back button, while App Lock covers the app: swallowed. It
- /// would otherwise pop a screen out of sight under the cover. Asked before
- /// the MaterialApp's own handler, which registers after this one.
+ // App Lock and the full locks (AppLockLifecycle) run on this navigator.
@override
- Future<bool> didPopRoute() async => _cover.value;
-
- /// App Lock over the screens the user left.
- void _showCover() => _cover.value = true;
-
- void _hideCover() => _cover.value = false;
-
- /// From the cover: the wallet closed meanwhile and a key comes next.
- void _coverNeedsKey() => _replaceStack('/security_key_unlock');
-
- /// A lock screen replaces the stack. A cover that is up stays until that
- /// screen is fully in, so nothing it covered shows on the way.
- void _replaceStack(String lockRoute) {
- _navigatorKey.currentState?.pushNamedAndRemoveUntil(lockRoute, (route) => false);
- if (!_cover.value) return;
- final top = _routeObserver.top;
- final animation = top is ModalRoute ? top.animation : null;
- if (animation == null || animation.isCompleted) return _hideCover();
- void settled(AnimationStatus status) {
- if (status.isAnimating) return;
- animation.removeStatusListener(settled);
- _hideCover();
- }
-
- animation.addStatusListener(settled);
- }
+ NavigatorState? get appLockNavigator => _navigatorKey.currentState;
@override
- void didChangeAppLifecycleState(AppLifecycleState state) {
- if (isDesktopOS) {
- _onDesktopLifecycle(state);
- return;
- }
- if (!isMobile) return;
-
- if (state == AppLifecycleState.paused) {
- _wasPaused = true;
- // App Lock has to cover backgrounding, not just a cold start: once its
- // time is up the password goes and the way back shows the lock. Not
- // while it is showing: the device's own prompt can background the app.
- if (_routeObserver.currentName != '/unlock' && !_cover.value) {
- unawaited(_appLock.onBackground(context));
- }
- unawaited(_fullLock.onBackground(context));
-
- // Leaving the app marks everything on screen as seen so a background
- // isolate won't re-notify a tx the user just watched arrive. Desktop has
- // no background isolate — and doing this would pre-empt its foreground
- // announce. Marks only synced history (hash-based), so an unsynced
- // receipt is still announced later.
- unawaited(appWalletOf(context, listen: false).notifyNewIncomingTxs(announce: false));
- } else if (_wasPaused) {
- // The first step back (`hidden`, then `inactive`, then `resumed`):
- // before a payment link that brought the app back gets a frame to land.
- _wasPaused = false;
- _onReturn();
- }
- }
-
- void _onReturn() {
- // Both decided at once, before anything is awaited; App Lock's locks the
- // session ([AppSession]) as it decides.
- final appLockDue = _appLock.takeDueOnReturn();
- // Past "Fully lock after" (or locked by its timer while away): the lock
- // screens replace the stack *before* the wallets close, which takes a
- // while, so the screen being left is never usable with the password still
- // in memory. App Lock comes first when its time is up too.
- if (_fullLock.takeDueOnResume()) {
- // App Lock first when it was showing too (its cover, or its screen):
- // the way in still starts with the device's own check.
- final appLockShowing = _cover.value || _routeObserver.currentName == '/unlock';
- _replaceStack(appLockDue || appLockShowing ? '/unlock' : '/security_key_unlock');
- unawaited(_fullLock.lock(context));
- return;
- }
-
- if (appLockDue) {
- // Over the current stack rather than replacing it, so unlocking returns
- // straight to the screen the user left; not again over a lock screen.
- if (_routeObserver.currentName != '/unlock') _showCover();
- unawaited(_appLock.lock(context));
- }
- }
+ String? get appLockTopRouteName => _routeObserver.currentName;
- /// A desktop OS. App Lock covers the app after its time without use, or as
- /// the window is hidden for "Immediately" (macOS reports `hidden` when no
- /// window is visible: hidden, minimised, covered, or the screen locked).
- /// Both "without use" clocks are checked as the app comes back, since their
- /// timers can stall while the computer sleeps.
- void _onDesktopLifecycle(AppLifecycleState state) {
- if (state == AppLifecycleState.hidden) {
- unawaited(_coverDesktopIfImmediate());
- } else if (state == AppLifecycleState.resumed) {
- unawaited(_onDesktopResumed());
- }
- }
-
- Future<void> _coverDesktopIfImmediate() async {
- if (await AppLockPreferences.minutes() == 0) await _coverDesktop();
- }
-
- Future<void> _onDesktopResumed() async {
- // The full close first: it may replace the stack with the unlock screen,
- // and then there is nothing left to cover.
- await _desktopLock.check();
- await _desktopAppLock.check();
- }
-
- /// App Lock on a desktop OS: the unlock screen goes over whatever is open,
- /// and the wallet stays open and syncing behind it. Linux and Windows ask
- /// for the password again; macOS asks for Touch ID or the Mac's password,
- /// and drops the keychain password meanwhile ([lockAppLock]).
- Future<void> _coverDesktop() async {
- // Already at a lock screen, or onboarding with no wallet yet.
- if (!mounted || !AppSession.isUnlocked) return;
- // A Mac with no way to confirm its owner has nothing to ask.
- if (usesDeviceLock && !await BiometricAuth.isAvailable()) return;
- if (!mounted || !AppSession.isUnlocked) return;
- AppSession.lock();
- if (_routeObserver.currentName != '/unlock') _showCover();
- await lockAppLock(context);
- }
-
- /// "Lock after" ran out on a desktop OS. The unlock screen replaces the stack
- /// first, then the wallet closes and its password is forgotten.
- Future<void> _lockDesktop() async {
- if (!mounted || !await desktopAutoLockApplies(context)) return;
- if (!mounted) return;
- // App Lock first (the typed password on Linux and Windows); a key follows
- // when keys are on.
- _replaceStack('/unlock');
- await _desktopLock.lock(context);
- }
-
- // Use, for both "without use" clocks: any key or pointer input reaching the
- // app.
- bool _onKey(KeyEvent event) {
- _recordUse();
- return false;
- }
-
- void _onPointer(PointerEvent event) => _recordUse();
+ @override
+ Route<dynamic>? get appLockTopRoute => _routeObserver.top;
- void _recordUse() {
- _desktopLock.recordUse();
- _desktopAppLock.recordUse();
+ /// Leaving the app marks everything on screen as seen so a background
+ /// isolate won't re-notify a tx the user just watched arrive. Desktop has
+ /// no background isolate — and doing this would pre-empt its foreground
+ /// announce. Marks only synced history (hash-based), so an unsynced
+ /// receipt is still announced later.
+ @override
+ void onMobilePaused() {
+ unawaited(appWalletOf(context, listen: false).notifyNewIncomingTxs(announce: false));
}
// Desktop has no background isolate to announce incoming txs, so the
@@ -569,28 +407,22 @@ class _AppRootState extends State<_AppRoot> with WidgetsBindingObserver {
});
}
_lastBrightness = brightness;
- // Brand-tone skeletons (the default grey clashes with the
- // navy/orange scheme); tokens resolve to the current theme.
- final app = AppLockCover(
- shown: _cover,
- cover: (_) => UnlockScreen(onUnlocked: _hideCover, onKeyNeeded: _coverNeedsKey),
+ // App Lock's cover above the navigator; on a desktop OS,
+ // input anywhere counts as use for "Lock after".
+ return buildAppLock(
+ cover: (_) => UnlockScreen(
+ onUnlocked: hideAppLockCover,
+ onKeyNeeded: appLockCoverNeedsKey,
+ ),
+ // Brand-tone skeletons (the default grey clashes with the
+ // navy/orange scheme); tokens resolve to the current theme.
child: SkeletonizerConfig(
data: SkeletonizerConfigData(
effect: SoldColorEffect(color: BrandColors.surfaceMuted),
),
child: child ?? const SizedBox.shrink(),
),
);
- if (!isDesktopOS) return app;
- // Pointer input anywhere counts as use for "Lock after".
- return Listener(
- behavior: HitTestBehavior.translucent,
- onPointerDown: _onPointer,
- onPointerHover: _onPointer,
- onPointerMove: _onPointer,
- onPointerSignal: _onPointer,
- child: app,
- );
},
initialRoute: initialRoute,
// Always boot through the resolved initial route. Whatever the
### lib/screens/unlock.dart
@@ -6,19 +6,15 @@ import 'package:package_info_plus/package_info_plus.dart';
import 'package:skylight_wallet/l10n/app_localizations.dart';
import 'package:skylight_wallet/util/platform.dart' show typesWalletPassword;
-import 'package:skylight_wallet/wallet_core_glue.dart';
import 'package:skylight_wallet/widgets/floating_bob.dart';
import 'package:skylight_wallet/widgets/ui/ui.dart';
-import 'package:wallet_domain/wallet_domain.dart' show AppSession;
import 'package:wallet_fhse/security_keys_ui.dart'
show
+ AppLockUnlock,
FhseLocalizations,
- reopenAfterAppLock,
showAppLockRecoveryPhrase,
- waitForFullLock,
- walletNeedsSecurityKey;
-import 'package:wallet_infra/wallet_infra.dart'
- show BiometricAuth, BiometricAuthResult, BoundToAnotherPcException;
+ unlockAppLockWithDevice,
+ unlockAppLockWithPassword;
class UnlockScreen extends StatefulWidget {
const UnlockScreen({super.key, this.onUnlocked, this.onKeyNeeded});
@@ -100,58 +96,14 @@ class _UnlockScreenState extends State<UnlockScreen> {
Future<void> _promptUnlock() async {
final i18n = AppLocalizations.of(context)!;
- // Always asks (App Lock is always on); a device with no lock at all has
- // nothing to ask and passes, and Settings warns about it.
- final result = await BiometricAuth.confirmOwner(reason: i18n.unlockReason);
-
- // Auto-prompted: stay silent on a decline (the button asks again), report
- // only a real error, and offer the recovery phrase for it.
- if (result == BiometricAuthResult.authenticated) {
- // A full lock still closing the wallets decides what comes next.
- await waitForFullLock();
- if (!mounted) return;
- // With security keys on and the wallet closed, a key comes next.
- final needsKey = await walletNeedsSecurityKey(context);
- if (!mounted) return;
- // Otherwise the keystore password comes back (a relock dropped it) and,
- // after a full lock, the wallet opens again. Without one it stays shut.
- if (!needsKey && !await reopenAfterAppLock(context)) {
- if (mounted) {
- setState(() => _offerRecoveryPhrase = true);
- showBrandToast(context, i18n.unlockUnableToAuthError);
- }
- return;
- }
- if (mounted) _unlocked(needsKey: needsKey);
- } else if (result == BiometricAuthResult.error) {
- if (mounted) {
- setState(() => _offerRecoveryPhrase = true);
- showBrandToast(context, i18n.unlockUnableToAuthError);
- }
- }
+ final outcome = await unlockAppLockWithDevice(context, reason: i18n.unlockReason);
+ if (mounted) _show(outcome);
}
/// The device could not confirm its owner: the recovery phrase opens the
/// wallet instead (and stands in for a security key, when keys are on).
Future<void> _useRecoveryPhrase() async {
- if (await showAppLockRecoveryPhrase(context) && mounted) _unlocked(needsKey: false);
- }
-
- /// Past App Lock. A key comes next when keys are on and the wallet is
- /// closed; otherwise this was the last lock ([AppSession]). A relock covers
- /// the screen the user left, and the app uncovers it; at a launch or after
- /// a full lock this is the base route, and home comes next.
- void _unlocked({required bool needsKey}) {
- if (needsKey) {
- final onKeyNeeded = widget.onKeyNeeded;
- if (onKeyNeeded != null) return onKeyNeeded();
- Navigator.of(context).pushNamedAndRemoveUntil('/security_key_unlock', (route) => false);
- return;
- }
- AppSession.markUnlocked();
- final onUnlocked = widget.onUnlocked;
- if (onUnlocked != null) return onUnlocked();
- Navigator.of(context).pushReplacementNamed('/wallet_home');
+ if (await showAppLockRecoveryPhrase(context) && mounted) _show(AppLockUnlock.unlocked);
}
Future<void> _unlockWithPassword() async {
@@ -164,42 +116,42 @@ class _UnlockScreenState extends State<UnlockScreen> {
_isLoading = true;
_error = null;
});
+ final outcome = await unlockAppLockWithPassword(context, _passwordController.text);
+ if (!mounted) return;
+ _passwordController.clear();
+ setState(() => _isLoading = false);
+ _show(outcome);
+ }
- try {
- // App Lock after a time without use: the wallet stayed open, so the
- // password is only checked again and the screen left comes back.
- final rechecked = await recheckPasswordIfOpen(context, _passwordController.text);
- if (rechecked != null) {
- if (!rechecked) throw Exception('Incorrect wallet password.');
- if (mounted) {
- _passwordController.clear();
- _unlocked(needsKey: false);
+ /// Shows what App Lock's unlock decided (wallet_fhse's [AppLockUnlock]):
+ /// where to go, or what to say.
+ void _show(AppLockUnlock outcome) {
+ final i18n = AppLocalizations.of(context)!;
+ switch (outcome) {
+ case AppLockUnlock.unlocked:
+ // A relock covers the screen the user left, and the app uncovers it.
+ // At a launch or after a full lock this is the base route: home next.
+ final onUnlocked = widget.onUnlocked;
+ if (onUnlocked != null) return onUnlocked();
+ Navigator.of(context).pushNamedAndRemoveUntil('/wallet_home', (route) => false);
+ case AppLockUnlock.needsKey:
+ final onKeyNeeded = widget.onKeyNeeded;
+ if (onKeyNeeded != null) return onKeyNeeded();
+ Navigator.of(context).pushNamedAndRemoveUntil('/security_key_unlock', (route) => false);
+ case AppLockUnlock.declined:
+ // Auto-prompted: stay quiet; the button asks again.
+ break;
+ case AppLockUnlock.failed:
+ if (typesWalletPassword) {
+ setState(() => _error = i18n.unlockUnableToAuthError);
+ return;
}
- return;
- }
- if (!mounted) return;
- final needsKey = await unlockWithPassword(context, _passwordController.text);
- if (mounted) {
- if (widget.onUnlocked != null) return _unlocked(needsKey: needsKey);
- // No key to follow: the password was the last lock.
- if (!needsKey) AppSession.markUnlocked();
- Navigator.pushNamedAndRemoveUntil(
- context,
- needsKey ? '/security_key_unlock' : '/wallet_home',
- (route) => false,
- );
- }
- } catch (e) {
- if (mounted) {
- _passwordController.clear();
- setState(() {
- // The files are bound to a PC whose TPM this one cannot use.
- _error = e is BoundToAnotherPcException
- ? FhseLocalizations.of(context).unlockBoundToAnotherPc
- : i18n.unlockIncorrectPasswordError;
- _isLoading = false;
- });
- }
+ setState(() => _offerRecoveryPhrase = true);
+ showBrandToast(context, i18n.unlockUnableToAuthError);
+ case AppLockUnlock.wrongPassword:
+ setState(() => _error = i18n.unlockIncorrectPasswordError);
+ case AppLockUnlock.boundToAnotherPc:
+ setState(() => _error = FhseLocalizations.of(context).unlockBoundToAnotherPc);
}
}
### lib/wallet_core_glue.dart
@@ -158,8 +158,9 @@ Future<bool> startupWalletManager(BuildContext context) =>
Future<bool> _loadExistingWalletManager(WalletManager manager) async {
if (await manager.hasAnyExistingWallet()) {
// App Lock is always on, so nothing is decrypted before the user gets past
- // it: the unlock screen opens the wallet (reopenAfterAppLock). Linux and
- // Windows wait for the typed password the same way.
+ // it: the unlock screen opens the wallet (wallet_fhse's
+ // unlockAppLockWithDevice). Linux and Windows wait for the typed password
+ // the same way (unlockAppLockWithPassword).
if (wcore.WalletSecrets.holdsWalletPassword) await manager.loadCachedDisplayState();
return true;
}
@@ -255,31 +256,6 @@ Future<String?> existingWalletRoute(BuildContext context) async {
return await manager.hasAnyExistingWallet() ? '/unlock' : null;
}
-/// App Lock on Linux and Windows after a time without use: the wallet stayed
-/// open, so the password is only checked again ([WalletManager.checkTypedPassword]).
-/// Null when the wallet is not open: [unlockWithPassword] opens it.
-Future<bool?> recheckPasswordIfOpen(BuildContext context, String password) async {
- final manager = Provider.of<WalletManager>(context, listen: false);
- if (!manager.hasPassword) return null;
- return manager.checkTypedPassword(password);
-}
-
-/// Opens the wallet with a desktop-entered password, then syncs. Throws on a
-/// wrong password (the unlock screen shows the error).
-///
-/// Returns true when security keys are on: the password was right, and a key
-/// comes next, so the caller shows the security-key unlock instead.
-Future<bool> unlockWithPassword(BuildContext context, String password) async {
- final manager = Provider.of<WalletManager>(context, listen: false);
- if (!await manager.unlockWithTypedPassword(password)) {
- throw Exception('Incorrect wallet password.');
- }
- if (!manager.hasPassword) return true;
- await manager.openAll();
- manager.syncInBackground();
- return false;
-}
-
/// Deletes the wallet and everything derived from it.
///
/// Through wallet-core's teardown rather than a bare `deleteAll`: theWhy this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.