From 8cb6c162792fc0e271f1d2b48cb2b89376a4f073 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 13:55:49 +0100 Subject: [PATCH 01/11] fix(app): draw only the gate while it is up A back gesture on the gate previewed the overlay entry under it, so locking over the TOTP picker showed the picker during the swipe (verified on device). The display now receives the gate alone; everything under it stays decorated. Co-Authored-By: Claude Opus 5.5 --- .../navigation/AppNavigationState.kt | 24 ++++++++++- .../presentation/navigation/AppNavigator.kt | 11 +---- .../navigation/AppNavigatorTest.kt | 42 +++++++++++++++++++ 3 files changed, 66 insertions(+), 11 deletions(-) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigationState.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigationState.kt index ccb7828fa..2337e2451 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigationState.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigationState.kt @@ -15,6 +15,7 @@ import androidx.navigation3.runtime.rememberNavBackStack import androidx.navigation3.runtime.serialization.NavKeySerializer import androidx.savedstate.compose.serialization.serializers.MutableStateSerializer import de.davis.keygo.core.presentation.model.RouteDestination +import de.davis.keygo.feature.auth.presentation.AuthRoute import de.davis.keygo.core.ui.navigation.rememberNavEntryDecorators /** @@ -70,6 +71,13 @@ class AppNavigationState( /** Whether the overlay owns the window, hiding the app proper underneath. */ val isOverlaid: Boolean get() = overlayStack.isNotEmpty() + /** + * True while the unlock gate is the overlay's top entry. Derived, so a restored gate reports + * itself. The type is what decides it: deep link destinations share this stack, so neither + * emptiness nor depth tells a gate from a screen back may legitimately pop. + */ + val isGated: Boolean get() = overlayStack.lastOrNull() is AuthRoute + /** The stack destinations are currently pushed onto and popped from. */ val currentStack: NavBackStack get() = if (isOverlaid) overlayStack else backStacks.getValue(topLevelRoute) @@ -97,8 +105,20 @@ class AppNavigationState( rememberDecoratedEntries(stack, entryProvider) } - return if (isOverlaid) overlayEntries - else topLevelEntries.getValue(topLevelRoute) + return visible(overlayEntries, topLevelEntries) + } + + /** + * Picks what the display is handed. While the gate is up that is the gate alone: everything + * under it stays decorated, holding its state, but the display never learns it exists. It + * would otherwise draw it on its own - a back gesture previews the entry under the top one - + * showing a screen the lock was meant to hide. With a single entry, back on the gate exits the + * app, the same as on a cold start. + */ + fun visible(overlay: List, tabs: Map>): List = when { + isGated -> listOf(overlay.last()) + isOverlaid -> overlay + else -> tabs.getValue(topLevelRoute) } } diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt index 671d4e70d..3d6ba7d50 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt @@ -18,13 +18,6 @@ import de.davis.keygo.feature.totp.presentation.TotpImportRedirect */ class AppNavigator(val state: AppNavigationState) { - /** - * True while [lock]'s gate is the overlay's top entry. Derived, so a restored gate reports - * itself. The type is what decides it: the `otpauth://` import shares this stack, so neither - * emptiness nor depth tells a gate from an import screen back may legitimately pop. - */ - private val isGated: Boolean get() = state.overlayStack.lastOrNull() is AuthRoute - /** * True while the overlay is showing a screen that runs before there is a session, so a locked * session is what it is there for rather than a reason to gate it. The import flow is not one @@ -38,7 +31,7 @@ class AppNavigator(val state: AppNavigationState) { /** The one choke point every gated mutator below shares, so none can forget the check. */ private inline fun whenUnlocked(action: () -> Unit) { - if (!isGated) action() + if (!state.isGated) action() } fun navigate(route: NavKey) = whenUnlocked { @@ -104,7 +97,7 @@ class AppNavigator(val state: AppNavigationState) { /** Lifts the gate. Only gates reach here; first run is taken down with [clearOverlay]. */ fun unlock() { - if (!isGated) return + if (!state.isGated) return state.overlayStack.removeLastOrNull() } diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt index f37c4fb88..765bca55b 100644 --- a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt +++ b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt @@ -622,6 +622,48 @@ class AppNavigatorTest { assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.shown) } + // ---- what the display is handed ---- + + private val AppNavigator.displayed: List + get() = state.visible(state.overlayStack.toList(), state.backStacks) + + @Test + fun `a gate over a preserved picker is displayed alone, so nothing peeks out under it`() { + // A back gesture previews the entry under the top one. Handing the display only the gate + // leaves it nothing to preview, and back on the gate exits the app as on a cold start. + val navigator = navigator() + navigator.replaceOverlay(SelectItemForTotpRoute(DEEP_LINK_URI)) + navigator.lock() + + assertEquals(listOf(AuthRoute()), navigator.displayed) + } + + @Test + fun `a cold start gate is displayed alone`() { + assertEquals(listOf(AuthRoute()), navigator().displayed) + } + + @Test + fun `an overlay flow without a gate is displayed whole, so back steps through it`() { + val navigator = navigator() + navigator.replaceOverlay(SelectItemForTotpRoute(DEEP_LINK_URI)) + navigator.pushOntoOverlay(TestAssignRoute) + + assertEquals( + listOf(SelectItemForTotpRoute(DEEP_LINK_URI), TestAssignRoute), + navigator.displayed, + ) + } + + @Test + fun `without an overlay the active tab's stack is displayed`() { + val navigator = unlocked() + navigator.navigate(SettingsRoute) + navigator.navigate(ChangePasswordRoute) + + assertEquals(listOf(SettingsRoute, ChangePasswordRoute), navigator.displayed) + } + private fun unlocked(): AppNavigator = navigator().apply { unlock() } private companion object { From fe220a784be73ad9755d5bca74a65a4673e6fd16 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 14:08:47 +0100 Subject: [PATCH 02/11] refactor(app): deep links wait under the gate A deep link now becomes its destination, placed on the overlay under the unlock gate or first run. Unlocking or finishing first run pops only the gate and reveals it; back can never reach it. The gates carry a PendingLink reason for their wording instead of the link itself. The pre-gate TotpImportRedirect screen is gone: the TOTP picker parses the link and reports one it cannot read. openGateFor, replaceOverlay and the uri threading through finishUnlock/finishFirstRun go with it. Co-Authored-By: Claude Opus 5.5 --- .../keygo/app/presentation/MainActivity.kt | 32 ++-- .../navigation/AppNavigationState.kt | 12 +- .../presentation/navigation/AppNavigator.kt | 34 ++--- .../app/presentation/navigation/DeepLinks.kt | 36 +++++ .../presentation/navigation/EntryProvider.kt | 50 +------ .../navigation/AppNavigatorTest.kt | 141 ++++++++++-------- .../navigation/TotpImportDeepLinkTest.kt | 32 ++-- .../keygo/core/ui/navigation/PendingLink.kt | 12 ++ .../feature/auth/presentation/AuthEntries.kt | 4 +- .../auth/presentation/AuthViewModel.kt | 3 +- .../auth/presentation/RouteDestination.kt | 5 +- .../auth/presentation/AuthViewModelTest.kt | 11 ++ .../presentation/OnboardingEntries.kt | 9 +- .../presentation/OnboardingViewModel.kt | 3 +- .../presentation/OnboardingViewModelTest.kt | 17 ++- .../presentation/SelectItemForTotpEntries.kt | 2 + .../presentation/SelectItemForTotpScreen.kt | 10 ++ .../presentation/SelectItemForTotpUiState.kt | 1 + .../SelectItemForTotpViewModel.kt | 1 + .../presentation/TotpImportDeepLinkMatcher.kt | 18 ++- .../totp/presentation/TotpImportRedirect.kt | 48 ------ .../presentation/TotpImportRedirectState.kt | 11 -- .../TotpImportRedirectViewModel.kt | 46 ------ .../SelectItemForTotpViewModelTest.kt | 23 +++ .../TotpImportRedirectViewModelTest.kt | 66 -------- 25 files changed, 271 insertions(+), 356 deletions(-) create mode 100644 app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinks.kt create mode 100644 core/ui/src/main/kotlin/de/davis/keygo/core/ui/navigation/PendingLink.kt delete mode 100644 feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirect.kt delete mode 100644 feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirectState.kt delete mode 100644 feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirectViewModel.kt delete mode 100644 feature/totp/src/test/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirectViewModelTest.kt diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt index 4fa494c89..7b24649ae 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt @@ -22,13 +22,15 @@ import androidx.compose.runtime.setValue import androidx.core.splashscreen.SplashScreen.Companion.installSplashScreen import androidx.fragment.app.FragmentActivity import androidx.navigation3.runtime.NavKey -import androidx.navigation3.runtime.deeplink.DeepLinkRequest import androidx.navigation3.scene.DialogSceneStrategy import de.davis.keygo.app.presentation.component.KeyGoNavigationWrapper import de.davis.keygo.app.presentation.navigation.AppNavigator +import de.davis.keygo.app.presentation.navigation.DeepLink import de.davis.keygo.app.presentation.navigation.keyGoEntryProvider +import de.davis.keygo.app.presentation.navigation.launchStack import de.davis.keygo.app.presentation.navigation.rememberAppNavigationState import de.davis.keygo.app.presentation.navigation.resolveAppShell +import de.davis.keygo.app.presentation.navigation.toDeepLink import de.davis.keygo.core.presentation.model.RouteDestination import de.davis.keygo.core.sync.domain.stepup.StepUpPrompter import de.davis.keygo.core.ui.composition.LocalIsInSinglePaneMode @@ -38,10 +40,6 @@ import de.davis.keygo.core.util.domain.snackbar.SnackbarManager import de.davis.keygo.core.util.presentation.snackbar.LocalSnackbarManager import de.davis.keygo.core.util.presentation.snackbar.SnackbarHandler import de.davis.keygo.core.sync.presentation.stepup.StepUpDialogHost -import de.davis.keygo.feature.auth.presentation.AuthRoute -import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute -import de.davis.keygo.feature.totp.presentation.TotpImportDeepLinkMatcher -import de.davis.keygo.feature.totp.presentation.TotpImportRedirect import org.koin.androidx.viewmodel.ext.android.viewModel import org.koin.compose.koinInject @@ -75,8 +73,7 @@ class MainActivity : FragmentActivity() { LocalSnackbarManager provides snackbarManager, ) { App( - hasAccess = hasAccess, - launchRoute = launchRoute(hasAccess), + launchStack = launchStack(intent.deepLink(), hasAccess), isSessionActive = isSessionActive, needsAttentionCount = needsAttentionCount, requestedTopLevelRoute = requestedTopLevelRoute, @@ -91,29 +88,22 @@ class MainActivity : FragmentActivity() { super.onNewIntent(intent) viewModel.onIntentAction(intent.action) } - - private fun launchRoute(hasAccess: Boolean): NavKey = - intent.totpImportRedirect() ?: if (hasAccess) AuthRoute() else OnboardingRoute() } -private fun Intent.totpImportRedirect(): TotpImportRedirect? { - // A DeepLinkRequest with neither a uri nor extras throws, and the launcher intent has no data. - val uri = data ?: return null - return TotpImportDeepLinkMatcher.match(DeepLinkRequest(uri))?.key -} +// A DeepLinkRequest with neither a uri nor extras throws, and the launcher intent has no data. +private fun Intent.deepLink(): DeepLink? = data?.toDeepLink() @OptIn(ExperimentalMaterial3AdaptiveApi::class) @Composable private fun App( - hasAccess: Boolean, - launchRoute: NavKey, + launchStack: List, isSessionActive: Boolean, needsAttentionCount: Int, requestedTopLevelRoute: NavKey?, onTopLevelRouteRequestHandled: () -> Unit, ) { val navigationState = rememberAppNavigationState( - launchRoute = launchRoute, + launchStack = launchStack, startRoute = RouteDestination.Home, topLevelRoutes = TopLevelRoutes, ) @@ -136,7 +126,7 @@ private fun App( DropAutoSelectedDetailWhenListLeaves(listPaneVisible, navigator) - val entries = navigationState.toDecoratedEntries(keyGoEntryProvider(navigator, hasAccess)) + val entries = navigationState.toDecoratedEntries(keyGoEntryProvider(navigator)) val shell = entries.resolveAppShell(listPaneVisible) val listDetailStrategy = rememberListDetailSceneStrategy(directive = directive) @@ -174,8 +164,8 @@ private fun App( /** * No ARK means the user has to authenticate again, so the session's own state is the whole rule - * a session that just ended and a restored process that never had one are the same thing here. - * [AppNavigator.lock] is what knows when a gate would be wrong, so onboarding and the deep link - * redirect need no special case. Keyed on what the overlay is showing as well, so it re-decides + * [AppNavigator.lock] is what knows when a gate would be wrong, so onboarding and a link waiting + * under a gate need no special case. Keyed on what the overlay is showing as well, so it re-decides * when that changes under a session that is still ended. */ @Composable diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigationState.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigationState.kt index 2337e2451..366083903 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigationState.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigationState.kt @@ -21,14 +21,14 @@ import de.davis.keygo.core.ui.navigation.rememberNavEntryDecorators /** * Creates the app's navigation state. It survives configuration changes and process death. * - * @param launchRoute what the overlay starts on. Only used the first time the state is created; - * after that the saved stack wins. + * @param launchStack what the overlay starts as, bottom first. Only used the first time the state + * is created; after that the saved stack wins. * @param startRoute the top level route the app opens on. Must be one of [topLevelRoutes]. * @param topLevelRoutes the navigation bar's destinations, one back stack each. */ @Composable fun rememberAppNavigationState( - launchRoute: NavKey, + launchStack: List, startRoute: NavKey, topLevelRoutes: Set, ): AppNavigationState { @@ -39,7 +39,7 @@ fun rememberAppNavigationState( mutableStateOf(startRoute) } - val overlayStack = rememberNavBackStack(launchRoute) + val overlayStack = rememberNavBackStack(*launchStack.toTypedArray()) val backStacks = topLevelRoutes.associateWith { key -> rememberNavBackStack(key) } return remember(startRoute, topLevelRoutes) { @@ -54,8 +54,8 @@ fun rememberAppNavigationState( /** * The app's navigation state, modified through [AppNavigator]. It holds two things: * - * - The **overlay stack**: the unlock gate, first run, or an incoming `otpauth://` link. While it - * holds anything it is all that shows. + * - The **overlay stack**: the unlock gate, first run, and a deep link's destination, which waits + * under the gate until it goes. While it holds anything it is all that shows. * - One **back stack per top level route**, each keeping its own history. Only the selected one is * shown, with nothing underneath it, so back out of its base leaves the app. */ diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt index 3d6ba7d50..f97d81d1f 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt @@ -5,7 +5,6 @@ import androidx.navigation3.runtime.NavKey import de.davis.keygo.core.presentation.model.RouteDestination import de.davis.keygo.feature.auth.presentation.AuthRoute import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute -import de.davis.keygo.feature.totp.presentation.TotpImportRedirect /** * Handles navigation events by updating [AppNavigationState]. Everything the UI can do to the back @@ -25,7 +24,7 @@ class AppNavigator(val state: AppNavigationState) { */ private val runsWithoutSession: Boolean get() = when (state.overlayStack.lastOrNull()) { - is AuthRoute, is OnboardingRoute, is TotpImportRedirect -> true + is AuthRoute, is OnboardingRoute -> true else -> false } @@ -59,17 +58,6 @@ class AppNavigator(val state: AppNavigationState) { else state.topLevelRoute = route } - /** - * Replaces the overlay with [route], so back from it leaves the app. Deliberately not gated, - * unlike [pushOntoOverlay]: it clears whatever is on top first - including a gate - rather - * than stacking above it, so it also doubles as how a gate is legitimately swapped for another - * (see `AppNavigator.openGateFor`). - */ - fun replaceOverlay(route: NavKey) { - state.overlayStack.clear() - state.overlayStack.add(route) - } - /** * Clears the overlay and hands the window to the app proper. Refused while the gate is up: * this is the one path that would drop a gate without anything having authenticated, and the @@ -78,9 +66,8 @@ class AppNavigator(val state: AppNavigationState) { fun clearOverlay() = whenUnlocked { state.overlayStack.clear() } /** - * Adds [route] to the overlay without disturbing whatever is already on it. Gated, unlike - * [replaceOverlay]: stacking on top of an existing gate would show [route] unauthenticated - * above it. + * Adds [route] to the overlay without disturbing whatever is already on it. Gated: stacking on + * top of an existing gate would show [route] unauthenticated above it. */ fun pushOntoOverlay(route: NavKey) = whenUnlocked { state.overlayStack.add(route) } @@ -95,12 +82,25 @@ class AppNavigator(val state: AppNavigationState) { pushOntoOverlay(AuthRoute()) } - /** Lifts the gate. Only gates reach here; first run is taken down with [clearOverlay]. */ + /** + * Lifts the gate, revealing whatever waited under it: a deep link's destination, or, with + * nothing on the overlay any more, the app proper. Only gates reach here; first run is taken + * down with [finishFirstRun]. + */ fun unlock() { if (!state.isGated) return state.overlayStack.removeLastOrNull() } + /** + * Takes first run down the same way: only first run itself goes, so a deep link's destination + * that waited under it is what shows next. + */ + fun finishFirstRun() { + if (state.overlayStack.lastOrNull() !is OnboardingRoute) return + state.overlayStack.removeLastOrNull() + } + /** * Shows [detail] in the dashboard's detail pane, replacing any detail already open, so back * from a detail always lands on the list. diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinks.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinks.kt new file mode 100644 index 000000000..18c694c97 --- /dev/null +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinks.kt @@ -0,0 +1,36 @@ +package de.davis.keygo.app.presentation.navigation + +import android.net.Uri +import androidx.navigation3.runtime.NavKey +import androidx.navigation3.runtime.deeplink.DeepLinkRequest +import de.davis.keygo.core.ui.navigation.PendingLink +import de.davis.keygo.feature.auth.presentation.AuthRoute +import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute +import de.davis.keygo.feature.totp.presentation.TotpImportDeepLinkMatcher + +/** A link the app was opened with: where it leads, and what the gate in front of it says. */ +data class DeepLink(val destination: NavKey, val pending: PendingLink) + +/** Every link the app accepts, each with its manifest intent filter. The first match wins. */ +private val deepLinkMatchers: List<(DeepLinkRequest) -> DeepLink?> = listOf( + { request -> + TotpImportDeepLinkMatcher.match(request)?.key + ?.let { DeepLink(it, PendingLink.TotpImport) } + }, +) + +fun Uri.toDeepLink(): DeepLink? { + val request = DeepLinkRequest(this) + return deepLinkMatchers.firstNotNullOfOrNull { match -> match(request) } +} + +/** + * The overlay the app opens on: a gate, with the link's destination waiting under it. Every link + * needs the gate, and the destination is only revealed by the gate going, never by back. + */ +fun launchStack(link: DeepLink?, hasAccess: Boolean): List { + val gate = if (hasAccess) AuthRoute(pending = link?.pending) + else OnboardingRoute(pending = link?.pending) + + return listOfNotNull(link?.destination, gate) +} diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/EntryProvider.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/EntryProvider.kt index acd1364f6..71216e1dd 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/EntryProvider.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/EntryProvider.kt @@ -1,7 +1,5 @@ package de.davis.keygo.app.presentation.navigation -import android.util.Log -import androidx.activity.compose.LocalActivity import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.material3.MaterialTheme @@ -28,46 +26,30 @@ import de.davis.keygo.feature.account.presentation.ChangePasswordRoute import de.davis.keygo.feature.account.presentation.ConnectServerRoute import de.davis.keygo.feature.account.presentation.DevicesRoute import de.davis.keygo.feature.account.presentation.accountEntries -import de.davis.keygo.feature.auth.presentation.AuthRoute import de.davis.keygo.feature.auth.presentation.authEntries import de.davis.keygo.feature.backup.presentation.BackupHubRoute import de.davis.keygo.feature.backup.presentation.backupEntries import de.davis.keygo.feature.item.create.presentation.totp.AssignTotpRoute import de.davis.keygo.feature.item.create.presentation.totp.assignTotpEntries -import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute import de.davis.keygo.feature.onboarding.presentation.onboardingEntries import de.davis.keygo.feature.password_health.presentation.component.PasswordHealthDetailPlaceholder import de.davis.keygo.feature.password_health.presentation.passwordHealthEntries import de.davis.keygo.feature.settings.presentation.settingsEntries -import de.davis.keygo.feature.totp.presentation.SelectItemForTotpRoute import de.davis.keygo.feature.totp.presentation.selectItemForTotpEntries -import de.davis.keygo.feature.totp.presentation.totpImportRedirectEntries import de.davis.keygo.item.dialog.SelectItemContent -private const val TAG = "KeyGoEntryProvider" - @OptIn(ExperimentalMaterial3AdaptiveApi::class) @Composable -fun keyGoEntryProvider(navigator: AppNavigator, hasAccess: Boolean): (NavKey) -> NavEntry { - val activity = LocalActivity.current - +fun keyGoEntryProvider(navigator: AppNavigator): (NavKey) -> NavEntry { return entryProvider { - totpImportRedirectEntries( - metadata = WindowOwning, - onValidated = { uri -> navigator.openGateFor(hasAccess, uri) }, - // The app was launched only to import this code, so the Activity is what closes. - onRejected = { - if (activity != null) activity.finish() - else Log.w(TAG, "No activity to finish after rejecting an invalid TOTP deep link") - }, - ) - selectItemForTotpEntries( metadata = WindowOwning, onItemSelected = { totpUri, itemId -> navigator.navigate(AssignTotpRoute(totpUri, itemId.toString())) }, onCreateNew = { totpUri -> navigator.navigate(AssignTotpRoute(totpUri)) }, + // Shown after the unlock, so the user lands in the app rather than leaving it. + onRejected = { navigator.clearOverlay() }, ) assignTotpEntries( @@ -78,12 +60,12 @@ fun keyGoEntryProvider(navigator: AppNavigator, hasAccess: Boolean): (NavKey) -> authEntries( metadata = WindowOwning, - onSuccess = { totpUri -> navigator.finishUnlock(totpUri) }, + onSuccess = { navigator.unlock() }, ) onboardingEntries( metadata = WindowOwning, - onSuccess = { totpUri -> navigator.finishFirstRun(totpUri) }, + onSuccess = { navigator.finishFirstRun() }, ) dashboardEntries(navigator = navigator) @@ -155,25 +137,3 @@ fun keyGoEntryProvider(navigator: AppNavigator, hasAccess: Boolean): (NavKey) -> ) } } - -/** Replaces the overlay, so back from the gate leaves the app rather than a consumed link. */ -internal fun AppNavigator.openGateFor(hasAccess: Boolean, uri: String) { - replaceOverlay(if (hasAccess) AuthRoute(uri = uri) else OnboardingRoute(uri = uri)) -} - -/** Lifts the gate that just authenticated, revealing a picker preserved under it. */ -internal fun AppNavigator.finishUnlock(totpUri: String?) { - unlock() - startImport(totpUri) -} - -/** Takes first run down. It is on the overlay as the launch route, not as a gate. */ -internal fun AppNavigator.finishFirstRun(totpUri: String?) { - clearOverlay() - startImport(totpUri) -} - -/** A code this run carried replaces whatever the dismissal revealed. */ -private fun AppNavigator.startImport(totpUri: String?) { - if (totpUri != null) pushOntoOverlay(SelectItemForTotpRoute(totpUri)) -} diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt index 765bca55b..c625a8475 100644 --- a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt +++ b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt @@ -12,7 +12,7 @@ import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute import de.davis.keygo.feature.password_health.presentation.PasswordHealthRoute import de.davis.keygo.feature.settings.presentation.SettingsRoute import de.davis.keygo.feature.totp.presentation.SelectItemForTotpRoute -import de.davis.keygo.feature.totp.presentation.TotpImportRedirect +import de.davis.keygo.core.ui.navigation.PendingLink import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -20,9 +20,11 @@ import kotlin.test.assertTrue class AppNavigatorTest { - private fun navigator(launchRoute: NavKey = AuthRoute()): AppNavigator { + /** A navigator whose overlay starts as [overlay], bottom first; a cold start gate by default. */ + private fun navigator(vararg overlay: NavKey): AppNavigator { + val launch = if (overlay.isEmpty()) arrayOf(AuthRoute()) else overlay val state = AppNavigationState( - overlayStack = NavBackStack(launchRoute), + overlayStack = NavBackStack(*launch), topLevelRoute = mutableStateOf(RouteDestination.Home), backStacks = TOP_LEVEL_ROUTES.associateWith { NavBackStack(it) }, ) @@ -38,7 +40,7 @@ class AppNavigatorTest { @Test fun `the overlay owns the window until it is cleared`() { // Cleared with a first run overlay: a gate refuses clearOverlay and is popped by unlock. - val navigator = navigator(launchRoute = OnboardingRoute()) + val navigator = navigator(OnboardingRoute()) assertTrue(navigator.state.isOverlaid) assertEquals(listOf(OnboardingRoute()), navigator.shown) @@ -49,38 +51,84 @@ class AppNavigatorTest { assertEquals(listOf(RouteDestination.Home), navigator.shown) } + // ---- deep links ---- + @Test - fun `a validated code sends an account with access to the unlock gate`() { - val navigator = navigator(launchRoute = OnboardingRoute()) + fun `a link opened with an account waits under the unlock gate`() { + assertEquals( + listOf(SelectItemForTotpRoute(DEEP_LINK_URI), AuthRoute(pending = PendingLink.TotpImport)), + launchStack(TOTP_LINK, hasAccess = true), + ) + } - navigator.openGateFor(hasAccess = true, uri = DEEP_LINK_URI) + @Test + fun `a link opened without an account waits under first run`() { + assertEquals( + listOf(SelectItemForTotpRoute(DEEP_LINK_URI), OnboardingRoute(pending = PendingLink.TotpImport)), + launchStack(TOTP_LINK, hasAccess = false), + ) + } - assertEquals(listOf(AuthRoute(uri = DEEP_LINK_URI)), navigator.shown) + @Test + fun `a plain launch opens on the gate alone`() { + assertEquals(listOf(AuthRoute()), launchStack(link = null, hasAccess = true)) + assertEquals(listOf(OnboardingRoute()), launchStack(link = null, hasAccess = false)) } @Test - fun `a validated code sends an account without access to first run`() { - val navigator = navigator() + fun `a link waiting under the gate is not displayed until the unlock`() { + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true).toTypedArray()) - navigator.openGateFor(hasAccess = false, uri = DEEP_LINK_URI) + assertEquals(listOf(AuthRoute(pending = PendingLink.TotpImport)), navigator.displayed) + + navigator.unlock() - assertEquals(listOf(OnboardingRoute(uri = DEEP_LINK_URI)), navigator.shown) + assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.displayed) } @Test - fun `the picker replaces the gate, so back leaves the app`() { - val navigator = navigator() + fun `back on a link's gate cannot reach the link`() { + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true).toTypedArray()) + + navigator.goBack() + + assertEquals( + listOf(SelectItemForTotpRoute(DEEP_LINK_URI), AuthRoute(pending = PendingLink.TotpImport)), + navigator.shown, + ) + } + + @Test + fun `a link's gate is not gated a second time when the session is still ended`() { + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true).toTypedArray()) + + navigator.lock() + + assertEquals(2, navigator.shown.size) + } + + @Test + fun `finishing first run reveals the link that waited under it`() { + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = false).toTypedArray()) + + navigator.finishFirstRun() + + assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.shown) + } + + @Test + fun `back from a revealed link leaves the app instead of reaching the gate it waited under`() { + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true).toTypedArray()) + navigator.unlock() - navigator.replaceOverlay(SelectItemForTotpRoute(DEEP_LINK_URI)) + navigator.goBack() assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.shown) - assertEquals(1, navigator.shown.size) } @Test fun `assigning a code pushes onto the overlay and back returns to the picker`() { - val navigator = navigator() - navigator.replaceOverlay(SelectItemForTotpRoute(DEEP_LINK_URI)) + val navigator = navigator(SelectItemForTotpRoute(DEEP_LINK_URI)) navigator.navigate(TestAssignRoute) assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI), TestAssignRoute), navigator.shown) @@ -101,13 +149,13 @@ class AppNavigatorTest { @Test fun `a top level route is not switched to while the overlay owns the window`() { - val navigator = navigator(launchRoute = TotpImportRedirect(DEEP_LINK_URI)) + val navigator = navigator(SelectItemForTotpRoute(DEEP_LINK_URI)) navigator.navigate(SettingsRoute) assertTrue(navigator.state.isOverlaid) assertEquals( - listOf(TotpImportRedirect(DEEP_LINK_URI), SettingsRoute), + listOf(SelectItemForTotpRoute(DEEP_LINK_URI), SettingsRoute), navigator.shown, ) } @@ -338,8 +386,7 @@ class AppNavigatorTest { @Test fun `locking pushes the gate without clearing what was already on the overlay`() { - val navigator = navigator() - navigator.replaceOverlay(SelectItemForTotpRoute(DEEP_LINK_URI)) + val navigator = navigator(SelectItemForTotpRoute(DEEP_LINK_URI)) navigator.lock() @@ -362,22 +409,13 @@ class AppNavigatorTest { @Test fun `locking is refused while first run is showing`() { - val navigator = navigator(launchRoute = OnboardingRoute()) + val navigator = navigator(OnboardingRoute()) navigator.lock() assertEquals(listOf(OnboardingRoute()), navigator.shown) } - @Test - fun `locking is refused while the deep link redirect is showing`() { - val navigator = navigator(launchRoute = TotpImportRedirect(DEEP_LINK_URI)) - - navigator.lock() - - assertEquals(listOf(TotpImportRedirect(DEEP_LINK_URI)), navigator.shown) - } - @Test fun `unlocking reveals the active tab exactly as it was`() { val navigator = unlocked() @@ -393,8 +431,7 @@ class AppNavigatorTest { @Test fun `unlocking reveals a picker that was preserved under the gate`() { - val navigator = navigator() - navigator.replaceOverlay(SelectItemForTotpRoute(DEEP_LINK_URI)) + val navigator = navigator(SelectItemForTotpRoute(DEEP_LINK_URI)) navigator.lock() navigator.unlock() @@ -404,8 +441,7 @@ class AppNavigatorTest { @Test fun `back cannot pop the gate away, even over a picker underneath it`() { - val navigator = navigator() - navigator.replaceOverlay(SelectItemForTotpRoute(DEEP_LINK_URI)) + val navigator = navigator(SelectItemForTotpRoute(DEEP_LINK_URI)) navigator.lock() navigator.goBack() @@ -509,8 +545,7 @@ class AppNavigatorTest { @Test fun `the gate is not cleared away by a flow finishing underneath it`() { - val navigator = navigator() - navigator.replaceOverlay(SelectItemForTotpRoute(DEEP_LINK_URI)) + val navigator = navigator(SelectItemForTotpRoute(DEEP_LINK_URI)) navigator.lock() navigator.clearOverlay() @@ -549,32 +584,14 @@ class AppNavigatorTest { @Test fun `finishing first run hands the window to the app proper`() { // First run is not a gate, so unlock() would refuse it. It is cleared instead. - val navigator = navigator(launchRoute = OnboardingRoute()) + val navigator = navigator(OnboardingRoute()) - navigator.finishFirstRun(totpUri = null) + navigator.finishFirstRun() assertFalse(navigator.state.isOverlaid) assertEquals(listOf(RouteDestination.Home), navigator.shown) } - @Test - fun `a code carried through first run opens its picker`() { - val navigator = navigator(launchRoute = OnboardingRoute(uri = DEEP_LINK_URI)) - - navigator.finishFirstRun(DEEP_LINK_URI) - - assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.shown) - } - - @Test - fun `a code carried through the unlock opens its picker`() { - val navigator = navigator(launchRoute = AuthRoute(uri = DEEP_LINK_URI)) - - navigator.finishUnlock(DEEP_LINK_URI) - - assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.shown) - } - @Test fun `a gate restored from saved state is not pushed a second time`() { val state = AppNavigationState( @@ -631,8 +648,7 @@ class AppNavigatorTest { fun `a gate over a preserved picker is displayed alone, so nothing peeks out under it`() { // A back gesture previews the entry under the top one. Handing the display only the gate // leaves it nothing to preview, and back on the gate exits the app as on a cold start. - val navigator = navigator() - navigator.replaceOverlay(SelectItemForTotpRoute(DEEP_LINK_URI)) + val navigator = navigator(SelectItemForTotpRoute(DEEP_LINK_URI)) navigator.lock() assertEquals(listOf(AuthRoute()), navigator.displayed) @@ -645,8 +661,7 @@ class AppNavigatorTest { @Test fun `an overlay flow without a gate is displayed whole, so back steps through it`() { - val navigator = navigator() - navigator.replaceOverlay(SelectItemForTotpRoute(DEEP_LINK_URI)) + val navigator = navigator(SelectItemForTotpRoute(DEEP_LINK_URI)) navigator.pushOntoOverlay(TestAssignRoute) assertEquals( @@ -676,6 +691,8 @@ class AppNavigatorTest { const val DEEP_LINK_URI = "otpauth://totp/GitHub:me@github.com?secret=JBSWY3DPEHPK3PXP&issuer=github.com" + + val TOTP_LINK = DeepLink(SelectItemForTotpRoute(DEEP_LINK_URI), PendingLink.TotpImport) } } diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/TotpImportDeepLinkTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/TotpImportDeepLinkTest.kt index 8e02c3657..a7fe89dca 100644 --- a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/TotpImportDeepLinkTest.kt +++ b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/TotpImportDeepLinkTest.kt @@ -3,7 +3,7 @@ package de.davis.keygo.app.presentation.navigation import androidx.core.net.toUri import androidx.navigation3.runtime.deeplink.DeepLinkRequest import de.davis.keygo.feature.totp.presentation.TotpImportDeepLinkMatcher -import de.davis.keygo.feature.totp.presentation.TotpImportRedirect +import de.davis.keygo.feature.totp.presentation.SelectItemForTotpRoute import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config @@ -12,26 +12,26 @@ import kotlin.test.assertEquals import kotlin.test.assertNotNull import kotlin.test.assertNull -/** An `otpauth://` link has to reach the import gate whole: label and query parameters intact. */ +/** An `otpauth://` link has to reach the import picker whole: label and query parameters intact. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [34]) class TotpImportDeepLinkTest { - private fun match(uri: String): TotpImportRedirect? = + private fun match(uri: String): SelectItemForTotpRoute? = TotpImportDeepLinkMatcher.match(DeepLinkRequest(uri.toUri()))?.key @Test fun `a single query parameter round trips`() { val key = assertNotNull(match("otpauth://totp/Example:me@example.com?secret=ABC")) - assertEquals("otpauth://totp/Example:me@example.com?secret=ABC", key.uri) + assertEquals("otpauth://totp/Example:me@example.com?secret=ABC", key.totpUri) } @Test fun `every query parameter survives, not just the ones we know about`() { val key = assertNotNull(match(DEEP_LINK_URI)) - assertEquals(DEEP_LINK_URI, key.uri) + assertEquals(DEEP_LINK_URI, key.totpUri) } /** @@ -42,7 +42,7 @@ class TotpImportDeepLinkTest { fun `a percent encoded label is passed on still encoded`() { val key = assertNotNull(match("otpauth://totp/GitHub%3Ame%40github.com?secret=ABC")) - assertEquals("otpauth://totp/GitHub%3Ame%40github.com?secret=ABC", key.uri) + assertEquals("otpauth://totp/GitHub%3Ame%40github.com?secret=ABC", key.totpUri) } /** @@ -53,14 +53,14 @@ class TotpImportDeepLinkTest { fun `an escaped delimiter stays escaped instead of becoming a real one`() { val key = assertNotNull(match("otpauth://totp/Acme%23EU:me@acme.com?secret=ABC")) - assertEquals("otpauth://totp/Acme%23EU:me@acme.com?secret=ABC", key.uri) + assertEquals("otpauth://totp/Acme%23EU:me@acme.com?secret=ABC", key.totpUri) } @Test fun `an escaped ampersand in a query value does not split the query`() { val key = assertNotNull(match("otpauth://totp/Example?secret=ABC&issuer=A%26B")) - assertEquals("otpauth://totp/Example?secret=ABC&issuer=A%26B", key.uri) + assertEquals("otpauth://totp/Example?secret=ABC&issuer=A%26B", key.totpUri) } /** A bare "+" is a space to the parser, so one that arrived escaped has to stay escaped. */ @@ -68,28 +68,32 @@ class TotpImportDeepLinkTest { fun `an escaped plus in a query value does not become a space`() { val key = assertNotNull(match("otpauth://totp/Example?secret=ABC&issuer=A%2BB")) - assertEquals("otpauth://totp/Example?secret=ABC&issuer=A%2BB", key.uri) + assertEquals("otpauth://totp/Example?secret=ABC&issuer=A%2BB", key.totpUri) } + /** + * An incomplete link still opens the picker, carrying the link as it arrived, so the picker's + * own parse reports it after the unlock instead of the app opening as if nothing was sent. + */ @Test - fun `a link with no query carries nothing to import`() { + fun `a link with no query is passed on as it arrived, for the picker to reject`() { val key = assertNotNull(match("otpauth://totp/Example:me@example.com")) - assertNull(key.uri) + assertEquals("otpauth://totp/Example:me@example.com", key.totpUri) } @Test - fun `a link with no label carries nothing to import`() { + fun `a link with no label is passed on as it arrived, for the picker to reject`() { val key = assertNotNull(match("otpauth://totp?secret=ABC")) - assertNull(key.uri) + assertEquals("otpauth://totp?secret=ABC", key.totpUri) } @Test fun `the scheme and host are matched without regard to case`() { val key = assertNotNull(match("OTPAUTH://TOTP/Example?secret=ABC")) - assertEquals("otpauth://totp/Example?secret=ABC", key.uri) + assertEquals("otpauth://totp/Example?secret=ABC", key.totpUri) } @Test diff --git a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/navigation/PendingLink.kt b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/navigation/PendingLink.kt new file mode 100644 index 000000000..ab2532a01 --- /dev/null +++ b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/navigation/PendingLink.kt @@ -0,0 +1,12 @@ +package de.davis.keygo.core.ui.navigation + +import kotlinx.serialization.Serializable + +/** + * Why a gate is up: a deep link is waiting under it. The gate only words itself after this; the + * link's own destination sits on the back stack beneath it and is revealed once the gate goes. + */ +@Serializable +enum class PendingLink { + TotpImport, +} diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthEntries.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthEntries.kt index 8db12c974..69eb4808a 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthEntries.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthEntries.kt @@ -5,9 +5,9 @@ import androidx.navigation3.runtime.NavKey fun EntryProviderScope.authEntries( metadata: Map = emptyMap(), - onSuccess: (String?) -> Unit, + onSuccess: () -> Unit, ) { entry(metadata = metadata) { route -> - AuthScreen(route = route, onSuccess = { onSuccess(route.uri) }) + AuthScreen(route = route, onSuccess = onSuccess) } } diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt index 3d0dc5561..f5e0cf78c 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt @@ -1,5 +1,6 @@ package de.davis.keygo.feature.auth.presentation +import de.davis.keygo.core.ui.navigation.PendingLink import androidx.compose.foundation.text.input.TextFieldState import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -45,7 +46,7 @@ internal class AuthViewModel( private val unlockWithPassword: UnlockWithPasswordUseCase, private val createAllAccesses: CreateAccessUseCase, ) : ViewModel() { - val hasPendingTotpImport: Boolean = authRoute.uri != null + val hasPendingTotpImport: Boolean = authRoute.pending == PendingLink.TotpImport private val passwordTextFieldState = TextFieldState() diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/RouteDestination.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/RouteDestination.kt index 7d877b4d5..c54d0dfaf 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/RouteDestination.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/RouteDestination.kt @@ -1,11 +1,12 @@ package de.davis.keygo.feature.auth.presentation import androidx.navigation3.runtime.NavKey +import de.davis.keygo.core.ui.navigation.PendingLink import kotlinx.serialization.Serializable -/** The import travels whole: back stack keys are saved with kotlinx.serialization. */ +/** [pending] names a deep link waiting under this gate, so the gate can say what it unlocks. */ @Serializable data class AuthRoute( - val uri: String? = null, + val pending: PendingLink? = null, val showBiometricPromptIfPossible: Boolean = true, ) : NavKey diff --git a/feature/auth/src/test/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModelTest.kt b/feature/auth/src/test/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModelTest.kt index 8a3283803..34bd3c552 100644 --- a/feature/auth/src/test/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModelTest.kt +++ b/feature/auth/src/test/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModelTest.kt @@ -19,6 +19,7 @@ import de.davis.keygo.core.security.crypto.FakeKeyStoreManager import de.davis.keygo.core.security.domain.model.CryptographicMode import de.davis.keygo.core.security.domain.model.CipherKeyId import de.davis.keygo.core.ui.model.UiFieldError +import de.davis.keygo.core.ui.navigation.PendingLink import de.davis.keygo.core.util.isSuccess import de.davis.keygo.feature.auth.presentation.model.AuthState import de.davis.keygo.feature.auth.presentation.model.AuthUIEvent @@ -186,6 +187,16 @@ class AuthViewModelTest { biometricCrypto.prompts.clear() } + @Test + fun `a gate holding back an import says so`() = runTest(dispatcher) { + assertTrue(viewModel(authRoute = AuthRoute(pending = PendingLink.TotpImport)).hasPendingTotpImport) + } + + @Test + fun `a plain gate mentions no import`() = runTest(dispatcher) { + assertFalse(viewModel().hasPendingTotpImport) + } + @Test fun `an enrolled account opens the prompt on arrival and continues once unlocked`() = runTest(dispatcher) { diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingEntries.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingEntries.kt index dbe771634..b3dcf8b94 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingEntries.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingEntries.kt @@ -1,18 +1,19 @@ package de.davis.keygo.feature.onboarding.presentation +import de.davis.keygo.core.ui.navigation.PendingLink import androidx.navigation3.runtime.EntryProviderScope import androidx.navigation3.runtime.NavKey import kotlinx.serialization.Serializable fun EntryProviderScope.onboardingEntries( metadata: Map = emptyMap(), - onSuccess: (String?) -> Unit, + onSuccess: () -> Unit, ) { entry(metadata = metadata) { route -> - OnboardingScreen(route = route, onSuccess = { onSuccess(route.uri) }) + OnboardingScreen(route = route, onSuccess = onSuccess) } } -/** The import travels whole: back stack keys are saved with kotlinx.serialization. */ +/** [pending] names a deep link waiting under first run, so the welcome can mention it. */ @Serializable -data class OnboardingRoute(val uri: String? = null) : NavKey +data class OnboardingRoute(val pending: PendingLink? = null) : NavKey diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt index 73b75a2d9..11ea059cb 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt @@ -1,5 +1,6 @@ package de.davis.keygo.feature.onboarding.presentation +import de.davis.keygo.core.ui.navigation.PendingLink import android.util.Log import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.runtime.snapshotFlow @@ -51,7 +52,7 @@ internal class OnboardingViewModel( private val createAccess: CreateAccessUseCase, ) : ViewModel() { - private val hasPendingTotpImport = onboardingRoute.uri != null + private val hasPendingTotpImport = onboardingRoute.pending == PendingLink.TotpImport private val stepsToSkip = MutableStateFlow>(emptySet()) diff --git a/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModelTest.kt b/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModelTest.kt index 152d0c95d..c4cacd1a3 100644 --- a/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModelTest.kt +++ b/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModelTest.kt @@ -32,6 +32,7 @@ import kotlinx.coroutines.test.setMain import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config +import de.davis.keygo.core.ui.navigation.PendingLink import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test @@ -65,8 +66,8 @@ class OnboardingViewModelTest { @AfterTest fun tearDown() = Dispatchers.resetMain() - private fun TestScope.viewModel() = OnboardingViewModel( - onboardingRoute = OnboardingRoute(), + private fun TestScope.viewModel(route: OnboardingRoute = OnboardingRoute()) = OnboardingViewModel( + onboardingRoute = route, biometricAvailabilityRepository = biometricAvailability, chromeAutofillRepository = chromeAutofillRepository, autofillActivationStatus = AutofillActivationStatusUseCase( @@ -111,6 +112,18 @@ class OnboardingViewModelTest { assertEquals(OnboardingUiState.EnableBiometrics, awaitStepAfterPasswordForm(vm)) } + @Test + fun `first run holding back an import welcomes with it`() = runTest(dispatcher) { + val vm = viewModel(OnboardingRoute(pending = PendingLink.TotpImport)) + + assertEquals(OnboardingUiState.Welcome(pendingTotpImport = true), vm.state.value) + } + + @Test + fun `a plain first run welcomes without an import`() = runTest(dispatcher) { + assertEquals(OnboardingUiState.Welcome(pendingTotpImport = false), viewModel().state.value) + } + @Test fun `enabling biometrics creates an account enrolled for them and moves on`() = runTest(dispatcher) { diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpEntries.kt b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpEntries.kt index fe5922b1e..2b991fb81 100644 --- a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpEntries.kt +++ b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpEntries.kt @@ -12,12 +12,14 @@ fun EntryProviderScope.selectItemForTotpEntries( metadata: Map = emptyMap(), onItemSelected: (totpUri: String, itemId: ItemId) -> Unit, onCreateNew: (totpUri: String) -> Unit, + onRejected: () -> Unit, ) { entry(metadata = metadata) { route -> SelectItemForTotpScreen( totpUri = route.totpUri, onItemSelected = { itemId -> onItemSelected(route.totpUri, itemId) }, onCreateNew = { onCreateNew(route.totpUri) }, + onRejected = onRejected, ) } } diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpScreen.kt b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpScreen.kt index 07b48eb28..1c0bf8ca0 100644 --- a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpScreen.kt +++ b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpScreen.kt @@ -2,6 +2,7 @@ package de.davis.keygo.feature.totp.presentation import androidx.compose.foundation.layout.consumeWindowInsets import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Add @@ -21,6 +22,7 @@ import de.davis.keygo.core.item.generated.domain.model.VaultItemType import de.davis.keygo.feature.list_screen.presentation.ItemListScreen import de.davis.keygo.feature.list_screen.presentation.NoItemStrategy import de.davis.keygo.feature.totp.R +import de.davis.keygo.feature.totp.presentation.component.TotpParseErrorDialog import org.koin.androidx.compose.koinViewModel import org.koin.core.parameter.parametersOf @@ -29,11 +31,19 @@ fun SelectItemForTotpScreen( totpUri: String, onItemSelected: (ItemId) -> Unit, onCreateNew: () -> Unit, + onRejected: () -> Unit, modifier: Modifier = Modifier, ) { val viewModel: SelectItemForTotpViewModel = koinViewModel { parametersOf(totpUri) } val state by viewModel.state.collectAsStateWithLifecycle() + if (state.invalidUri) + TotpParseErrorDialog( + onDismiss = onRejected, + modifier = Modifier.fillMaxWidth(), + onDismissRequest = onRejected, + ) + SelectItemForTotpContent( state = state, onItemSelected = onItemSelected, diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpUiState.kt b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpUiState.kt index 660c22f06..357a2f7d5 100644 --- a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpUiState.kt +++ b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpUiState.kt @@ -4,4 +4,5 @@ import de.davis.keygo.core.item.domain.alias.ItemId internal data class SelectItemForTotpUiState( val suggestedItemIds: Set = emptySet(), + val invalidUri: Boolean = false, ) diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpViewModel.kt b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpViewModel.kt index 5d0f5905a..534aa2068 100644 --- a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpViewModel.kt +++ b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpViewModel.kt @@ -32,6 +32,7 @@ internal class SelectItemForTotpViewModel( init { totpService.getInfoFromUriWithResult(totpUri).onFailure { failure -> Log.e(TAG, "Error parsing TOTP URI: $failure") + _state.update { it.copy(invalidUri = true) } }.onSuccess { info -> viewModelScope.launch { val suggested = suggestedItemIdsFor(info) diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcher.kt b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcher.kt index 268101899..b49653fce 100644 --- a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcher.kt +++ b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcher.kt @@ -4,14 +4,15 @@ import androidx.navigation3.runtime.deeplink.DeepLinkMatcher import androidx.navigation3.runtime.deeplink.DeepLinkRequest /** - * Matches the `otpauth://totp` links the app registers an intent filter for. + * Matches the `otpauth://totp` links the app registers an intent filter for, straight to the + * picker that imports them. The picker parses the link itself and reports one it cannot read. * * `UriDeepLinkMatcher` cannot stand in for this. It percent-decodes every value it extracts, and * its unnamed query parameter only collects parts that carry no "=", so a real otpauth query is * dropped whole. Both matter here, because the link has to reach the parser exactly as it arrived. */ object TotpImportDeepLinkMatcher : - DeepLinkMatcher>() { + DeepLinkMatcher>() { const val SCHEME = "otpauth" const val HOST = "totp" @@ -20,7 +21,7 @@ object TotpImportDeepLinkMatcher : override fun matchRequest( request: DeepLinkRequest, - ): MatchResult? { + ): MatchResult? { val uri = request.uri ?: return null if (!uri.scheme.equals(SCHEME, ignoreCase = true)) return null if (!uri.host.equals(HOST, ignoreCase = true)) return null @@ -33,10 +34,11 @@ object TotpImportDeepLinkMatcher : val label = uri.encodedPath?.removePrefix("/")?.takeIf { it.isNotBlank() } val query = uri.encodedQuery?.takeIf { it.isNotBlank() } - return MatchResult( - TotpImportRedirect( - uri = if (label != null && query != null) "$BASE_PATH/$label?$query" else null, - ), - ) + // An incomplete link is passed on as it arrived rather than dropped, so the picker's + // parse rejects it in front of the user instead of the app opening as if nothing was sent. + val totpUri = if (label != null && query != null) "$BASE_PATH/$label?$query" + else uri.toString() + + return MatchResult(SelectItemForTotpRoute(totpUri)) } } diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirect.kt b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirect.kt deleted file mode 100644 index fbdecf607..000000000 --- a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirect.kt +++ /dev/null @@ -1,48 +0,0 @@ -package de.davis.keygo.feature.totp.presentation - -import androidx.compose.foundation.layout.fillMaxWidth -import androidx.compose.runtime.LaunchedEffect -import androidx.compose.runtime.getValue -import androidx.compose.ui.Modifier -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.navigation3.runtime.EntryProviderScope -import androidx.navigation3.runtime.NavKey -import de.davis.keygo.feature.totp.presentation.component.TotpParseErrorDialog -import kotlinx.serialization.Serializable -import org.koin.androidx.compose.koinViewModel -import org.koin.core.parameter.parametersOf - -/** - * The link travels whole: back stack keys are saved with kotlinx.serialization, and the parser it - * is handed to wants the uri rather than its parts. - * - * Null when [TotpImportDeepLinkMatcher] matched a link that carried no complete uri, which the - * redirect screen reports as a parse error instead of swallowing. - */ -@Serializable -data class TotpImportRedirect(val uri: String? = null) : NavKey - -fun EntryProviderScope.totpImportRedirectEntries( - metadata: Map = emptyMap(), - onValidated: (String) -> Unit, - onRejected: () -> Unit, -) { - entry(metadata = metadata) { route -> - val viewModel: TotpImportRedirectViewModel = koinViewModel { parametersOf(route) } - val state by viewModel.state.collectAsStateWithLifecycle() - - when (val current = state) { - TotpImportRedirectState.Validating -> Unit - - is TotpImportRedirectState.Valid -> LaunchedEffect(route) { - onValidated(current.uri) - } - - TotpImportRedirectState.Invalid -> TotpParseErrorDialog( - onDismiss = onRejected, - modifier = Modifier.fillMaxWidth(), - onDismissRequest = onRejected, - ) - } - } -} diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirectState.kt b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirectState.kt deleted file mode 100644 index 9e9c888a9..000000000 --- a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirectState.kt +++ /dev/null @@ -1,11 +0,0 @@ -package de.davis.keygo.feature.totp.presentation - -internal sealed interface TotpImportRedirectState { - - data object Validating : TotpImportRedirectState - - /** Carries the uri that parsed, so the screen does not have to re-derive it from the route. */ - data class Valid(val uri: String) : TotpImportRedirectState - - data object Invalid : TotpImportRedirectState -} diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirectViewModel.kt b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirectViewModel.kt deleted file mode 100644 index bafe05dbf..000000000 --- a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirectViewModel.kt +++ /dev/null @@ -1,46 +0,0 @@ -package de.davis.keygo.feature.totp.presentation - -import android.util.Log -import androidx.lifecycle.ViewModel -import de.davis.keygo.core.util.fold -import de.davis.keygo.rust.totp.TotpService -import de.davis.keygo.rust.totp.getInfoFromUriWithResult -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import org.koin.core.annotation.InjectedParam -import org.koin.core.annotation.KoinViewModel - -@KoinViewModel -internal class TotpImportRedirectViewModel( - @InjectedParam private val route: TotpImportRedirect, - private val totpService: TotpService, -) : ViewModel() { - - private val _state = - MutableStateFlow(TotpImportRedirectState.Validating) - val state: StateFlow = _state.asStateFlow() - - init { - _state.value = validate() - } - - private fun validate(): TotpImportRedirectState { - val uri = route.uri ?: run { - Log.e(TAG, "Deep link carried no complete otpauth uri") - return TotpImportRedirectState.Invalid - } - - return totpService.getInfoFromUriWithResult(uri).fold( - onSuccess = { TotpImportRedirectState.Valid(uri) }, - onFailure = { failure -> - Log.e(TAG, "Error parsing TOTP URI: $failure") - TotpImportRedirectState.Invalid - }, - ) - } - - companion object { - private const val TAG = "TotpImportRedirectVM" - } -} diff --git a/feature/totp/src/test/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpViewModelTest.kt b/feature/totp/src/test/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpViewModelTest.kt index e8facfd5d..096b6c3fd 100644 --- a/feature/totp/src/test/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpViewModelTest.kt +++ b/feature/totp/src/test/kotlin/de/davis/keygo/feature/totp/presentation/SelectItemForTotpViewModelTest.kt @@ -28,6 +28,8 @@ import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue @OptIn(ExperimentalCoroutinesApi::class) @RunWith(RobolectricTestRunner::class) @@ -96,6 +98,27 @@ class SelectItemForTotpViewModelTest { assertEquals(emptySet(), viewModel.state.value.suggestedItemIds) } + /** No screen validates the link before the gate any more; the picker is where it is refused. */ + @Test + fun `an unreadable code is reported as invalid`() = runVmTest { + totpService.infoFromUriResult = null + + val viewModel = buildViewModel() + advanceUntilIdle() + + assertTrue(viewModel.state.value.invalidUri) + } + + @Test + fun `a readable code is not reported as invalid`() = runVmTest { + totpService.infoFromUriResult = totpInfo(issuer = "github.com") + + val viewModel = buildViewModel() + advanceUntilIdle() + + assertFalse(viewModel.state.value.invalidUri) + } + // Helpers private fun runVmTest(body: suspend TestScope.() -> Unit) = diff --git a/feature/totp/src/test/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirectViewModelTest.kt b/feature/totp/src/test/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirectViewModelTest.kt deleted file mode 100644 index 37a3d90d8..000000000 --- a/feature/totp/src/test/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportRedirectViewModelTest.kt +++ /dev/null @@ -1,66 +0,0 @@ -package de.davis.keygo.feature.totp.presentation - -import de.davis.keygo.rust.FakeTotpService -import de.davisalessandro.keygo.rust.Algorithm -import de.davisalessandro.keygo.rust.TotpInfo -import org.junit.runner.RunWith -import org.robolectric.RobolectricTestRunner -import org.robolectric.annotation.Config -import kotlin.test.Test -import kotlin.test.assertEquals - -@RunWith(RobolectricTestRunner::class) -@Config(sdk = [34]) -class TotpImportRedirectViewModelTest { - - private val totpService = FakeTotpService() - - @Test - fun `a readable code is valid, and carries the uri that parsed`() { - totpService.infoFromUriResult = totpInfo() - - val viewModel = buildViewModel(TotpImportRedirect(DEEP_LINK_URI)) - - assertEquals(TotpImportRedirectState.Valid(DEEP_LINK_URI), viewModel.state.value) - } - - @Test - fun `an unreadable code is invalid`() { - totpService.infoFromUriResult = null - - val viewModel = buildViewModel(TotpImportRedirect(DEEP_LINK_URI)) - - assertEquals(TotpImportRedirectState.Invalid, viewModel.state.value) - } - - /** The matcher leaves the uri null for a link missing its label or its query. */ - @Test - fun `a link that carried no complete uri is invalid`() { - totpService.infoFromUriResult = totpInfo() - - val viewModel = buildViewModel(TotpImportRedirect()) - - assertEquals(TotpImportRedirectState.Invalid, viewModel.state.value) - } - - // Helpers - - private fun buildViewModel(route: TotpImportRedirect) = TotpImportRedirectViewModel( - route = route, - totpService = totpService, - ) - - private fun totpInfo() = TotpInfo( - secret = "JBSWY3DPEHPK3PXP", - issuer = "github.com", - accountName = "me@github.com", - algorithm = Algorithm.SHA1, - digits = 6, - period = 30, - ) - - companion object { - private const val DEEP_LINK_URI = - "otpauth://totp/GitHub:me@github.com?secret=JBSWY3DPEHPK3PXP&issuer=github.com" - } -} From 989612d9ef0497a9974c49b9156a2033556c28cf Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 14:11:45 +0100 Subject: [PATCH 03/11] feat(app): handle deep links while the app runs onNewIntent used to read only the intent's action, so a link that reached the running activity was dropped. It now goes through the same matchers and AppNavigator.openDeepLink, which slides the destination under a gate already up, or pushes a fresh gate over it: every link has to pass the gate, even under a live session. Co-Authored-By: Claude Opus 5.5 --- .../keygo/app/presentation/AppViewModel.kt | 14 +++++ .../keygo/app/presentation/MainActivity.kt | 12 +++++ .../presentation/navigation/AppNavigator.kt | 17 ++++++ .../navigation/AppNavigatorTest.kt | 52 +++++++++++++++++++ 4 files changed, 95 insertions(+) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt index 2cb69f427..754f67a64 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt @@ -1,5 +1,6 @@ package de.davis.keygo.app.presentation +import de.davis.keygo.app.presentation.navigation.DeepLink import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation3.runtime.NavKey @@ -36,6 +37,11 @@ internal class AppViewModel( private val _requestedTopLevelRoute = MutableStateFlow(null) val requestedTopLevelRoute = _requestedTopLevelRoute.asStateFlow() + private val _incomingDeepLink = MutableStateFlow(null) + + /** A link that arrived while the app was running, until the navigation has taken it. */ + val incomingDeepLink = _incomingDeepLink.asStateFlow() + init { viewModelScope.launch { _isReturningUser.update { accountRepository.getOrNull() != null || hasV1Password() } @@ -50,4 +56,12 @@ internal class AppViewModel( fun onTopLevelRouteRequestHandled() { _requestedTopLevelRoute.value = null } + + fun onDeepLink(link: DeepLink?) { + if (link != null) _incomingDeepLink.value = link + } + + fun onDeepLinkHandled() { + _incomingDeepLink.value = null + } } diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt index 7b24649ae..d6700f74c 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt @@ -66,6 +66,7 @@ class MainActivity : FragmentActivity() { val isSessionActive by viewModel.isSessionActive.collectAsState() val needsAttentionCount by viewModel.needsAttentionCount.collectAsState() val requestedTopLevelRoute by viewModel.requestedTopLevelRoute.collectAsState() + val incomingDeepLink by viewModel.incomingDeepLink.collectAsState() KeyGoTheme { val snackbarManager = koinInject() @@ -78,6 +79,8 @@ class MainActivity : FragmentActivity() { needsAttentionCount = needsAttentionCount, requestedTopLevelRoute = requestedTopLevelRoute, onTopLevelRouteRequestHandled = viewModel::onTopLevelRouteRequestHandled, + incomingDeepLink = incomingDeepLink, + onDeepLinkHandled = viewModel::onDeepLinkHandled, ) } } @@ -87,6 +90,7 @@ class MainActivity : FragmentActivity() { override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) viewModel.onIntentAction(intent.action) + viewModel.onDeepLink(intent.deepLink()) } } @@ -101,6 +105,8 @@ private fun App( needsAttentionCount: Int, requestedTopLevelRoute: NavKey?, onTopLevelRouteRequestHandled: () -> Unit, + incomingDeepLink: DeepLink?, + onDeepLinkHandled: () -> Unit, ) { val navigationState = rememberAppNavigationState( launchStack = launchStack, @@ -118,6 +124,12 @@ private fun App( onTopLevelRouteRequestHandled() } + LaunchedEffect(incomingDeepLink) { + if (incomingDeepLink == null) return@LaunchedEffect + navigator.openDeepLink(incomingDeepLink) + onDeepLinkHandled() + } + val windowAdaptiveInfo = currentWindowAdaptiveInfoV2() val directive = remember(windowAdaptiveInfo) { calculatePaneScaffoldDirective(windowAdaptiveInfo) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt index f97d81d1f..990e25306 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt @@ -92,6 +92,23 @@ class AppNavigator(val state: AppNavigationState) { state.overlayStack.removeLastOrNull() } + /** + * Opens a link that arrived while the app was already running. Every link has to pass the + * gate, even under a live session: a gate or first run already up gets the destination slid in + * under it, anything else gets a fresh gate pushed over the destination. Deliberately not + * gated itself - it never puts anything above a gate. + */ + fun openDeepLink(link: DeepLink) { + val overlay = state.overlayStack + when (overlay.lastOrNull()) { + is AuthRoute, is OnboardingRoute -> overlay.add(overlay.lastIndex, link.destination) + else -> { + overlay.add(link.destination) + overlay.add(AuthRoute(pending = link.pending)) + } + } + } + /** * Takes first run down the same way: only first run itself goes, so a deep link's destination * that waited under it is what shows next. diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt index c625a8475..f776b8137 100644 --- a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt +++ b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt @@ -116,6 +116,58 @@ class AppNavigatorTest { assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.shown) } + @Test + fun `a link arriving while unlocked on a tab still has to pass the gate`() { + val navigator = unlocked() + navigator.navigate(SettingsRoute) + + navigator.openDeepLink(TOTP_LINK) + + assertEquals( + listOf(SelectItemForTotpRoute(DEEP_LINK_URI), AuthRoute(pending = PendingLink.TotpImport)), + navigator.shown, + ) + assertEquals(listOf(AuthRoute(pending = PendingLink.TotpImport)), navigator.displayed) + } + + @Test + fun `a link arriving during an overlay flow waits under a gate pushed over it`() { + val navigator = navigator(SelectItemForTotpRoute("otpauth://totp/Other?secret=ABC")) + + navigator.openDeepLink(TOTP_LINK) + + assertEquals( + listOf( + SelectItemForTotpRoute("otpauth://totp/Other?secret=ABC"), + SelectItemForTotpRoute(DEEP_LINK_URI), + AuthRoute(pending = PendingLink.TotpImport), + ), + navigator.shown, + ) + } + + @Test + fun `a link arriving while the gate is up slides in under it, without a second gate`() { + val navigator = navigator() + + navigator.openDeepLink(TOTP_LINK) + + assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI), AuthRoute()), navigator.shown) + + navigator.unlock() + + assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.shown) + } + + @Test + fun `a link arriving during first run slides in under it`() { + val navigator = navigator(OnboardingRoute()) + + navigator.openDeepLink(TOTP_LINK) + + assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI), OnboardingRoute()), navigator.shown) + } + @Test fun `back from a revealed link leaves the app instead of reaching the gate it waited under`() { val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true).toTypedArray()) From 79ec02692a50e1d90e66ebd1b6031d550679eb8a Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 14:18:14 +0100 Subject: [PATCH 04/11] fix(app): first run hides a waiting link like the gate does With a link waiting under first run, Welcome hands back to the display, so a back gesture previewed the picker and then popped first run, leaving a user with no account on a lock screen for an account that does not exist. First run now counts as covering the overlay: it is displayed alone and back never pops it. Co-Authored-By: Claude Opus 5.5 --- .../navigation/AppNavigationState.kt | 16 ++++++++++++-- .../presentation/navigation/AppNavigator.kt | 13 +++++------ .../navigation/AppNavigatorTest.kt | 22 +++++++++++++++++++ 3 files changed, 41 insertions(+), 10 deletions(-) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigationState.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigationState.kt index 366083903..88aeac9d4 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigationState.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigationState.kt @@ -16,6 +16,7 @@ import androidx.navigation3.runtime.serialization.NavKeySerializer import androidx.savedstate.compose.serialization.serializers.MutableStateSerializer import de.davis.keygo.core.presentation.model.RouteDestination import de.davis.keygo.feature.auth.presentation.AuthRoute +import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute import de.davis.keygo.core.ui.navigation.rememberNavEntryDecorators /** @@ -78,6 +79,17 @@ class AppNavigationState( */ val isGated: Boolean get() = overlayStack.lastOrNull() is AuthRoute + /** + * True while the overlay's top entry is one a deep link can wait under: the gate, or first run + * for a user with no account yet. Both run before there is a session, and both hide what is + * under them completely - nothing under them is displayed, and back never pops them to it. + */ + val isCovered: Boolean + get() = when (overlayStack.lastOrNull()) { + is AuthRoute, is OnboardingRoute -> true + else -> false + } + /** The stack destinations are currently pushed onto and popped from. */ val currentStack: NavBackStack get() = if (isOverlaid) overlayStack else backStacks.getValue(topLevelRoute) @@ -109,14 +121,14 @@ class AppNavigationState( } /** - * Picks what the display is handed. While the gate is up that is the gate alone: everything + * Picks what the display is handed. While the gate or first run is up that is it alone: everything * under it stays decorated, holding its state, but the display never learns it exists. It * would otherwise draw it on its own - a back gesture previews the entry under the top one - * showing a screen the lock was meant to hide. With a single entry, back on the gate exits the * app, the same as on a cold start. */ fun visible(overlay: List, tabs: Map>): List = when { - isGated -> listOf(overlay.last()) + isCovered -> listOf(overlay.last()) isOverlaid -> overlay else -> tabs.getValue(topLevelRoute) } diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt index 990e25306..0aed94b45 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt @@ -22,11 +22,7 @@ class AppNavigator(val state: AppNavigationState) { * session is what it is there for rather than a reason to gate it. The import flow is not one * of these: it only ever runs after an unlock, so a session that ends under it does gate it. */ - private val runsWithoutSession: Boolean - get() = when (state.overlayStack.lastOrNull()) { - is AuthRoute, is OnboardingRoute -> true - else -> false - } + private val runsWithoutSession: Boolean get() = state.isCovered /** The one choke point every gated mutator below shares, so none can forget the check. */ private inline fun whenUnlocked(action: () -> Unit) { @@ -154,10 +150,11 @@ class AppNavigator(val state: AppNavigationState) { } /** - * Goes back one destination, never down to nothing, and never while the gate is up: the - * overlay can be deeper than one entry then, so a depth check alone would pop the gate. + * Goes back one destination, never down to nothing, and never off the gate or first run: a + * deep link can wait under either, so a depth check alone would pop them to reveal it. */ - fun goBack() = whenUnlocked { + fun goBack() { + if (state.isCovered) return val stack = state.currentStack if (stack.size > 1) stack.removeLastOrNull() } diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt index f776b8137..7b0071d33 100644 --- a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt +++ b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt @@ -116,6 +116,28 @@ class AppNavigatorTest { assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.shown) } + @Test + fun `first run holding back a link is displayed alone, so nothing peeks out under it`() { + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = false).toTypedArray()) + + assertEquals(listOf(OnboardingRoute(pending = PendingLink.TotpImport)), navigator.displayed) + } + + @Test + fun `back on first run cannot skip it to reach the link under it`() { + // Welcome hands back to the display. Popping first run here would land a user who has no + // account yet on the picker, and the lock would then ask them to unlock an account that + // does not exist. + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = false).toTypedArray()) + + navigator.goBack() + + assertEquals( + listOf(SelectItemForTotpRoute(DEEP_LINK_URI), OnboardingRoute(pending = PendingLink.TotpImport)), + navigator.shown, + ) + } + @Test fun `a link arriving while unlocked on a tab still has to pass the gate`() { val navigator = unlocked() From ca5612d900d080ae7cf3da600a5d7bb1834007e2 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 15:46:10 +0100 Subject: [PATCH 05/11] fix(app): reject an unreadable link before the gate Dropping the pre-gate TotpImportRedirect meant a broken QR code asked the user to unlock first, only to report the error after, and left them in the app instead of back in the scanner. DeepLinkChecker now reads every matched link before the gate goes up. An unreadable link started by an external app shows only the error and finishes the Activity; one arriving while the app runs is reported over whatever is showing. The `when` over PendingLink is exhaustive, so a new link kind has to say how it is checked. Co-Authored-By: Claude Opus 5.5 --- app/build.gradle.kts | 1 + .../keygo/app/presentation/AppViewModel.kt | 51 ++++++++++++++++++- .../keygo/app/presentation/MainActivity.kt | 18 ++++++- .../navigation/DeepLinkChecker.kt | 36 +++++++++++++ .../presentation/navigation/EntryProvider.kt | 3 +- .../navigation/RejectedLinkDialog.kt | 22 ++++++++ .../navigation/DeepLinkCheckerTest.kt | 41 +++++++++++++++ .../usecase/IsReadableTotpUriUseCase.kt | 19 +++++++ 8 files changed, 186 insertions(+), 5 deletions(-) create mode 100644 app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkChecker.kt create mode 100644 app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/RejectedLinkDialog.kt create mode 100644 app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkCheckerTest.kt create mode 100644 feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/domain/usecase/IsReadableTotpUriUseCase.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 8c176e6f0..ae7734ac2 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -169,6 +169,7 @@ dependencies { testImplementation(libs.kotlin.test) testImplementation(libs.robolectric) testImplementation(libs.androidx.junit) + testImplementation(testFixtures(projects.core.rust)) androidTestImplementation(libs.androidx.junit) androidTestImplementation(libs.androidx.espresso.core) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt index 754f67a64..d9417c903 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt @@ -1,11 +1,14 @@ package de.davis.keygo.app.presentation -import de.davis.keygo.app.presentation.navigation.DeepLink import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation3.runtime.NavKey +import de.davis.keygo.app.presentation.navigation.CheckedLink +import de.davis.keygo.app.presentation.navigation.DeepLink +import de.davis.keygo.app.presentation.navigation.DeepLinkChecker import de.davis.keygo.core.identity.domain.repository.AccountRepository import de.davis.keygo.core.security.domain.Session +import de.davis.keygo.core.ui.navigation.PendingLink import de.davis.keygo.feature.password_health.domain.PasswordHealthAttention import de.davis.keygo.legacy_migration.domain.usecase.HasMainPasswordUseCase import kotlinx.coroutines.flow.MutableStateFlow @@ -21,6 +24,7 @@ internal class AppViewModel( private val hasV1Password: HasMainPasswordUseCase, session: Session, passwordHealthAttention: PasswordHealthAttention, + private val deepLinkChecker: DeepLinkChecker, ) : ViewModel() { private val _isReturningUser = MutableStateFlow(null) @@ -42,6 +46,16 @@ internal class AppViewModel( /** A link that arrived while the app was running, until the navigation has taken it. */ val incomingDeepLink = _incomingDeepLink.asStateFlow() + /** The readable link this Activity was started with, which its launch stack opens. */ + var launchLink: DeepLink? = null + private set + private var isLaunchLinkChecked = false + + private val _rejectedLink = MutableStateFlow(null) + + /** A link that could not be read, until the user has dismissed the report. */ + val rejectedLink = _rejectedLink.asStateFlow() + init { viewModelScope.launch { _isReturningUser.update { accountRepository.getOrNull() != null || hasV1Password() } @@ -57,11 +71,44 @@ internal class AppViewModel( _requestedTopLevelRoute.value = null } + /** + * Checks the link the Activity was started with. Only the first call counts: a recreated + * Activity hands in the same intent, and its navigation is restored rather than relaunched. + */ + fun onLaunchLink(link: DeepLink?) { + if (isLaunchLinkChecked) return + isLaunchLinkChecked = true + + when (val checked = link?.let(deepLinkChecker::check)) { + is CheckedLink.Accepted -> launchLink = checked.link + is CheckedLink.Rejected -> + _rejectedLink.value = RejectedLink(checked.pending, closesApp = true) + + null -> Unit + } + } + fun onDeepLink(link: DeepLink?) { - if (link != null) _incomingDeepLink.value = link + when (val checked = link?.let(deepLinkChecker::check)) { + is CheckedLink.Accepted -> _incomingDeepLink.value = checked.link + is CheckedLink.Rejected -> + _rejectedLink.value = RejectedLink(checked.pending, closesApp = false) + + null -> Unit + } + } + + fun onRejectedLinkDismissed() { + _rejectedLink.value = null } fun onDeepLinkHandled() { _incomingDeepLink.value = null } } + +/** + * A link that could not be read. [closesApp] when the Activity was started only to take it: there + * is nothing else to show, so dismissing the report hands back to the app that sent it. + */ +internal data class RejectedLink(val pending: PendingLink, val closesApp: Boolean) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt index d6700f74c..5600d2e91 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt @@ -26,6 +26,7 @@ import androidx.navigation3.scene.DialogSceneStrategy import de.davis.keygo.app.presentation.component.KeyGoNavigationWrapper import de.davis.keygo.app.presentation.navigation.AppNavigator import de.davis.keygo.app.presentation.navigation.DeepLink +import de.davis.keygo.app.presentation.navigation.RejectedLinkDialog import de.davis.keygo.app.presentation.navigation.keyGoEntryProvider import de.davis.keygo.app.presentation.navigation.launchStack import de.davis.keygo.app.presentation.navigation.rememberAppNavigationState @@ -54,6 +55,7 @@ class MainActivity : FragmentActivity() { // A recreated Activity already restored the tab the request selected. if (savedInstanceState == null) viewModel.onIntentAction(intent.action) + viewModel.onLaunchLink(intent.deepLink()) splashScreen.setKeepOnScreenCondition { viewModel.isReturningUser.value == null @@ -67,14 +69,16 @@ class MainActivity : FragmentActivity() { val needsAttentionCount by viewModel.needsAttentionCount.collectAsState() val requestedTopLevelRoute by viewModel.requestedTopLevelRoute.collectAsState() val incomingDeepLink by viewModel.incomingDeepLink.collectAsState() + val rejectedLink by viewModel.rejectedLink.collectAsState() KeyGoTheme { val snackbarManager = koinInject() CompositionLocalProvider( LocalSnackbarManager provides snackbarManager, ) { - App( - launchStack = launchStack(intent.deepLink(), hasAccess), + // Started only to take a link that cannot be read: no gate, just the report. + if (rejectedLink?.closesApp != true) App( + launchStack = launchStack(viewModel.launchLink, hasAccess), isSessionActive = isSessionActive, needsAttentionCount = needsAttentionCount, requestedTopLevelRoute = requestedTopLevelRoute, @@ -82,6 +86,16 @@ class MainActivity : FragmentActivity() { incomingDeepLink = incomingDeepLink, onDeepLinkHandled = viewModel::onDeepLinkHandled, ) + + rejectedLink?.let { rejected -> + RejectedLinkDialog( + pending = rejected.pending, + onDismiss = { + if (rejected.closesApp) finish() + else viewModel.onRejectedLinkDismissed() + }, + ) + } } } } diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkChecker.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkChecker.kt new file mode 100644 index 000000000..d2ce7feb8 --- /dev/null +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkChecker.kt @@ -0,0 +1,36 @@ +package de.davis.keygo.app.presentation.navigation + +import de.davis.keygo.core.ui.navigation.PendingLink +import de.davis.keygo.feature.totp.domain.usecase.IsReadableTotpUriUseCase +import de.davis.keygo.feature.totp.presentation.SelectItemForTotpRoute +import org.koin.core.annotation.Factory + +/** What a matched link turned out to be once its content was read. */ +sealed interface CheckedLink { + + /** Readable: its destination goes onto the overlay, behind the gate. */ + data class Accepted(val link: DeepLink) : CheckedLink + + /** Unreadable: reported straight away, without a gate, and nothing is opened. */ + data class Rejected(val pending: PendingLink) : CheckedLink +} + +/** + * Reads a link's content before the gate goes up, so a broken one is reported without asking the + * user to unlock for nothing. The `when` is exhaustive over [PendingLink], so a new kind of link + * cannot be registered without saying how it is checked. + */ +@Factory +class DeepLinkChecker( + private val isReadableTotpUri: IsReadableTotpUriUseCase, +) { + + fun check(link: DeepLink): CheckedLink = + if (isReadable(link)) CheckedLink.Accepted(link) + else CheckedLink.Rejected(link.pending) + + private fun isReadable(link: DeepLink): Boolean = when (link.pending) { + PendingLink.TotpImport -> (link.destination as? SelectItemForTotpRoute) + ?.let { isReadableTotpUri(it.totpUri) } == true + } +} diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/EntryProvider.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/EntryProvider.kt index 71216e1dd..d69519bb3 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/EntryProvider.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/EntryProvider.kt @@ -48,7 +48,8 @@ fun keyGoEntryProvider(navigator: AppNavigator): (NavKey) -> NavEntry { navigator.navigate(AssignTotpRoute(totpUri, itemId.toString())) }, onCreateNew = { totpUri -> navigator.navigate(AssignTotpRoute(totpUri)) }, - // Shown after the unlock, so the user lands in the app rather than leaving it. + // A backstop: DeepLinkChecker rejects an unreadable link before the gate. Shown + // after the unlock, so the user lands in the app rather than leaving it. onRejected = { navigator.clearOverlay() }, ) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/RejectedLinkDialog.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/RejectedLinkDialog.kt new file mode 100644 index 000000000..3ce63323d --- /dev/null +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/RejectedLinkDialog.kt @@ -0,0 +1,22 @@ +package de.davis.keygo.app.presentation.navigation + +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import de.davis.keygo.core.ui.navigation.PendingLink +import de.davis.keygo.feature.totp.presentation.component.TotpParseErrorDialog + +/** Reports a link that could not be read, in the words of the feature it was meant for. */ +@Composable +fun RejectedLinkDialog( + pending: PendingLink, + onDismiss: () -> Unit, +) { + when (pending) { + PendingLink.TotpImport -> TotpParseErrorDialog( + onDismiss = onDismiss, + modifier = Modifier.fillMaxWidth(), + onDismissRequest = onDismiss, + ) + } +} diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkCheckerTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkCheckerTest.kt new file mode 100644 index 000000000..f0a81bedd --- /dev/null +++ b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkCheckerTest.kt @@ -0,0 +1,41 @@ +package de.davis.keygo.app.presentation.navigation + +import de.davis.keygo.core.ui.navigation.PendingLink +import de.davis.keygo.feature.totp.domain.usecase.IsReadableTotpUriUseCase +import de.davis.keygo.feature.totp.presentation.SelectItemForTotpRoute +import de.davis.keygo.rust.FakeTotpService +import de.davisalessandro.keygo.rust.Algorithm +import de.davisalessandro.keygo.rust.TotpInfo +import kotlin.test.Test +import kotlin.test.assertEquals + +/** A link is read before the gate goes up, so a broken one never asks the user to unlock. */ +class DeepLinkCheckerTest { + + private val totpService = FakeTotpService() + private val checker = DeepLinkChecker(IsReadableTotpUriUseCase(totpService)) + + private val totpLink = + DeepLink(SelectItemForTotpRoute("otpauth://totp/Example?secret=ABC"), PendingLink.TotpImport) + + @Test + fun `a readable otpauth link is accepted as it is`() { + totpService.infoFromUriResult = TotpInfo( + secret = "JBSWY3DPEHPK3PXP", + issuer = "Example", + accountName = "me@example.com", + algorithm = Algorithm.SHA1, + digits = 6, + period = 30, + ) + + assertEquals(CheckedLink.Accepted(totpLink), checker.check(totpLink)) + } + + @Test + fun `an unreadable otpauth link is rejected under its own kind`() { + totpService.infoFromUriResult = null + + assertEquals(CheckedLink.Rejected(PendingLink.TotpImport), checker.check(totpLink)) + } +} diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/domain/usecase/IsReadableTotpUriUseCase.kt b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/domain/usecase/IsReadableTotpUriUseCase.kt new file mode 100644 index 000000000..f1bcdbd15 --- /dev/null +++ b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/domain/usecase/IsReadableTotpUriUseCase.kt @@ -0,0 +1,19 @@ +package de.davis.keygo.feature.totp.domain.usecase + +import de.davis.keygo.core.util.isSuccess +import de.davis.keygo.rust.totp.TotpService +import de.davis.keygo.rust.totp.getInfoFromUriWithResult +import org.koin.core.annotation.Single + +/** + * Whether an `otpauth://` uri parses into something the import can work with. Checked before the + * unlock gate goes up, so a broken QR code is reported without asking the user to unlock for it. + */ +@Single +class IsReadableTotpUriUseCase( + private val totpService: TotpService, +) { + + operator fun invoke(uri: String): Boolean = + totpService.getInfoFromUriWithResult(uri).isSuccess() +} From 399b6353bc98989083ba795f80e1f2679c86a11d Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 15:47:05 +0100 Subject: [PATCH 06/11] feat(app): open a link directly under a live session Every link pushed a fresh gate, even right after the user unlocked. With auto-lock set to anything but "immediately" that asked for a second unlock the setting had just promised to skip. A link now goes straight to its destination while the session is live, both when it starts the Activity and when it reaches a running one; without a session it still waits under the gate. A plain launch keeps opening on the gate as before. Co-Authored-By: Claude Opus 5.5 --- .../keygo/app/presentation/MainActivity.kt | 4 +- .../presentation/navigation/AppNavigator.kt | 14 +++-- .../app/presentation/navigation/DeepLinks.kt | 10 +++- .../navigation/AppNavigatorTest.kt | 56 +++++++++++++------ 4 files changed, 57 insertions(+), 27 deletions(-) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt index 5600d2e91..96e68b6d1 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt @@ -78,7 +78,7 @@ class MainActivity : FragmentActivity() { ) { // Started only to take a link that cannot be read: no gate, just the report. if (rejectedLink?.closesApp != true) App( - launchStack = launchStack(viewModel.launchLink, hasAccess), + launchStack = launchStack(viewModel.launchLink, hasAccess, isSessionActive), isSessionActive = isSessionActive, needsAttentionCount = needsAttentionCount, requestedTopLevelRoute = requestedTopLevelRoute, @@ -140,7 +140,7 @@ private fun App( LaunchedEffect(incomingDeepLink) { if (incomingDeepLink == null) return@LaunchedEffect - navigator.openDeepLink(incomingDeepLink) + navigator.openDeepLink(incomingDeepLink, isSessionActive) onDeepLinkHandled() } diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt index 0aed94b45..4b7c4c500 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt @@ -89,15 +89,17 @@ class AppNavigator(val state: AppNavigationState) { } /** - * Opens a link that arrived while the app was already running. Every link has to pass the - * gate, even under a live session: a gate or first run already up gets the destination slid in - * under it, anything else gets a fresh gate pushed over the destination. Deliberately not + * Opens a link that arrived while the app was already running. Under a live session it opens + * directly: the user already unlocked, and the auto-lock setting decides how long that holds. + * Otherwise it has to pass the gate: a gate or first run already up gets the destination slid + * in under it, anything else gets a fresh gate pushed over the destination. Deliberately not * gated itself - it never puts anything above a gate. */ - fun openDeepLink(link: DeepLink) { + fun openDeepLink(link: DeepLink, isSessionActive: Boolean) { val overlay = state.overlayStack - when (overlay.lastOrNull()) { - is AuthRoute, is OnboardingRoute -> overlay.add(overlay.lastIndex, link.destination) + when { + state.isCovered -> overlay.add(overlay.lastIndex, link.destination) + isSessionActive -> overlay.add(link.destination) else -> { overlay.add(link.destination) overlay.add(AuthRoute(pending = link.pending)) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinks.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinks.kt index 18c694c97..27496f72e 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinks.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinks.kt @@ -25,10 +25,14 @@ fun Uri.toDeepLink(): DeepLink? { } /** - * The overlay the app opens on: a gate, with the link's destination waiting under it. Every link - * needs the gate, and the destination is only revealed by the gate going, never by back. + * The overlay the app opens on. A link opened under a live session goes straight to its + * destination: the user already unlocked, and the auto-lock setting is what decides how long that + * holds. Otherwise the gate sits on top, with the link's destination waiting under it, revealed + * only by the gate going and never by back. */ -fun launchStack(link: DeepLink?, hasAccess: Boolean): List { +fun launchStack(link: DeepLink?, hasAccess: Boolean, isSessionActive: Boolean): List { + if (link != null && isSessionActive) return listOf(link.destination) + val gate = if (hasAccess) AuthRoute(pending = link?.pending) else OnboardingRoute(pending = link?.pending) diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt index 7b0071d33..113c660c9 100644 --- a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt +++ b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt @@ -57,7 +57,7 @@ class AppNavigatorTest { fun `a link opened with an account waits under the unlock gate`() { assertEquals( listOf(SelectItemForTotpRoute(DEEP_LINK_URI), AuthRoute(pending = PendingLink.TotpImport)), - launchStack(TOTP_LINK, hasAccess = true), + launchStack(TOTP_LINK, hasAccess = true, isSessionActive = false), ) } @@ -65,19 +65,32 @@ class AppNavigatorTest { fun `a link opened without an account waits under first run`() { assertEquals( listOf(SelectItemForTotpRoute(DEEP_LINK_URI), OnboardingRoute(pending = PendingLink.TotpImport)), - launchStack(TOTP_LINK, hasAccess = false), + launchStack(TOTP_LINK, hasAccess = false, isSessionActive = false), ) } + @Test + fun `a link opened under a live session goes straight to its destination`() { + assertEquals( + listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), + launchStack(TOTP_LINK, hasAccess = true, isSessionActive = true), + ) + } + + @Test + fun `a plain launch under a live session still opens on the gate`() { + assertEquals(listOf(AuthRoute()), launchStack(link = null, hasAccess = true, isSessionActive = true)) + } + @Test fun `a plain launch opens on the gate alone`() { - assertEquals(listOf(AuthRoute()), launchStack(link = null, hasAccess = true)) - assertEquals(listOf(OnboardingRoute()), launchStack(link = null, hasAccess = false)) + assertEquals(listOf(AuthRoute()), launchStack(link = null, hasAccess = true, isSessionActive = false)) + assertEquals(listOf(OnboardingRoute()), launchStack(link = null, hasAccess = false, isSessionActive = false)) } @Test fun `a link waiting under the gate is not displayed until the unlock`() { - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true).toTypedArray()) + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true, isSessionActive = false).toTypedArray()) assertEquals(listOf(AuthRoute(pending = PendingLink.TotpImport)), navigator.displayed) @@ -88,7 +101,7 @@ class AppNavigatorTest { @Test fun `back on a link's gate cannot reach the link`() { - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true).toTypedArray()) + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true, isSessionActive = false).toTypedArray()) navigator.goBack() @@ -100,7 +113,7 @@ class AppNavigatorTest { @Test fun `a link's gate is not gated a second time when the session is still ended`() { - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true).toTypedArray()) + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true, isSessionActive = false).toTypedArray()) navigator.lock() @@ -109,7 +122,7 @@ class AppNavigatorTest { @Test fun `finishing first run reveals the link that waited under it`() { - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = false).toTypedArray()) + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = false, isSessionActive = false).toTypedArray()) navigator.finishFirstRun() @@ -118,7 +131,7 @@ class AppNavigatorTest { @Test fun `first run holding back a link is displayed alone, so nothing peeks out under it`() { - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = false).toTypedArray()) + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = false, isSessionActive = false).toTypedArray()) assertEquals(listOf(OnboardingRoute(pending = PendingLink.TotpImport)), navigator.displayed) } @@ -128,7 +141,7 @@ class AppNavigatorTest { // Welcome hands back to the display. Popping first run here would land a user who has no // account yet on the picker, and the lock would then ask them to unlock an account that // does not exist. - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = false).toTypedArray()) + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = false, isSessionActive = false).toTypedArray()) navigator.goBack() @@ -139,11 +152,22 @@ class AppNavigatorTest { } @Test - fun `a link arriving while unlocked on a tab still has to pass the gate`() { + fun `a link arriving under a live session opens without a gate`() { + val navigator = unlocked() + navigator.navigate(SettingsRoute) + + navigator.openDeepLink(TOTP_LINK, isSessionActive = true) + + assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.shown) + assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.displayed) + } + + @Test + fun `a link arriving on a tab after the session ended has to pass the gate`() { val navigator = unlocked() navigator.navigate(SettingsRoute) - navigator.openDeepLink(TOTP_LINK) + navigator.openDeepLink(TOTP_LINK, isSessionActive = false) assertEquals( listOf(SelectItemForTotpRoute(DEEP_LINK_URI), AuthRoute(pending = PendingLink.TotpImport)), @@ -156,7 +180,7 @@ class AppNavigatorTest { fun `a link arriving during an overlay flow waits under a gate pushed over it`() { val navigator = navigator(SelectItemForTotpRoute("otpauth://totp/Other?secret=ABC")) - navigator.openDeepLink(TOTP_LINK) + navigator.openDeepLink(TOTP_LINK, isSessionActive = false) assertEquals( listOf( @@ -172,7 +196,7 @@ class AppNavigatorTest { fun `a link arriving while the gate is up slides in under it, without a second gate`() { val navigator = navigator() - navigator.openDeepLink(TOTP_LINK) + navigator.openDeepLink(TOTP_LINK, isSessionActive = false) assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI), AuthRoute()), navigator.shown) @@ -185,14 +209,14 @@ class AppNavigatorTest { fun `a link arriving during first run slides in under it`() { val navigator = navigator(OnboardingRoute()) - navigator.openDeepLink(TOTP_LINK) + navigator.openDeepLink(TOTP_LINK, isSessionActive = false) assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI), OnboardingRoute()), navigator.shown) } @Test fun `back from a revealed link leaves the app instead of reaching the gate it waited under`() { - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true).toTypedArray()) + val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true, isSessionActive = false).toTypedArray()) navigator.unlock() navigator.goBack() From 5a05ac1ff0ab9485019654a35b85c4579fbb9a15 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 15:47:52 +0100 Subject: [PATCH 07/11] fix(app): a new link replaces the one already waiting Two links arriving one after another stacked their destinations, so after the unlock back from the newer one landed on the older. The overlay below the gate or first run only ever holds a link's flow, so a new link now replaces it, under a live session as well. The tabs underneath are untouched. Co-Authored-By: Claude Opus 5.5 --- .../presentation/navigation/AppNavigator.kt | 19 +++++---- .../navigation/AppNavigatorTest.kt | 40 ++++++++++++++++--- 2 files changed, 46 insertions(+), 13 deletions(-) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt index 4b7c4c500..f57812795 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt @@ -94,17 +94,22 @@ class AppNavigator(val state: AppNavigationState) { * Otherwise it has to pass the gate: a gate or first run already up gets the destination slid * in under it, anything else gets a fresh gate pushed over the destination. Deliberately not * gated itself - it never puts anything above a gate. + * + * The newest link replaces an earlier one rather than queueing behind it. Below the gate or + * first run, the overlay only ever holds a link's flow, so that flow is what gives way; the + * tabs underneath are not touched. */ fun openDeepLink(link: DeepLink, isSessionActive: Boolean) { val overlay = state.overlayStack - when { - state.isCovered -> overlay.add(overlay.lastIndex, link.destination) - isSessionActive -> overlay.add(link.destination) - else -> { - overlay.add(link.destination) - overlay.add(AuthRoute(pending = link.pending)) - } + if (state.isCovered) { + repeat(overlay.lastIndex) { overlay.removeAt(0) } + overlay.add(0, link.destination) + return } + + overlay.clear() + overlay.add(link.destination) + if (!isSessionActive) overlay.add(AuthRoute(pending = link.pending)) } /** diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt index 113c660c9..cbc538475 100644 --- a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt +++ b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt @@ -177,19 +177,47 @@ class AppNavigatorTest { } @Test - fun `a link arriving during an overlay flow waits under a gate pushed over it`() { + fun `a link arriving during an earlier link's flow replaces it under a fresh gate`() { + val navigator = navigator( + SelectItemForTotpRoute("otpauth://totp/Other?secret=ABC"), + TestAssignRoute, + ) + + navigator.openDeepLink(TOTP_LINK, isSessionActive = false) + + assertEquals( + listOf(SelectItemForTotpRoute(DEEP_LINK_URI), AuthRoute(pending = PendingLink.TotpImport)), + navigator.shown, + ) + } + + @Test + fun `a link arriving during an earlier link's flow under a live session replaces it`() { val navigator = navigator(SelectItemForTotpRoute("otpauth://totp/Other?secret=ABC")) + navigator.openDeepLink(TOTP_LINK, isSessionActive = true) + + assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.shown) + } + + @Test + fun `a second link under the gate replaces the one already waiting`() { + val navigator = navigator( + SelectItemForTotpRoute("otpauth://totp/Other?secret=ABC"), + AuthRoute(pending = PendingLink.TotpImport), + ) + navigator.openDeepLink(TOTP_LINK, isSessionActive = false) assertEquals( - listOf( - SelectItemForTotpRoute("otpauth://totp/Other?secret=ABC"), - SelectItemForTotpRoute(DEEP_LINK_URI), - AuthRoute(pending = PendingLink.TotpImport), - ), + listOf(SelectItemForTotpRoute(DEEP_LINK_URI), AuthRoute(pending = PendingLink.TotpImport)), navigator.shown, ) + + navigator.unlock() + navigator.goBack() + + assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.shown) } @Test From 96218a7bbcd4359f3198cdfbf9edcd9bc99c6ce9 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 15:55:39 +0100 Subject: [PATCH 08/11] refactor(auth,onboarding): word the gate by the pending link kind The gate and the welcome screen collapsed PendingLink into a TOTP-only flag (hasPendingTotpImport, pendingTotpImport). They now carry the PendingLink itself and pick their wording with an exhaustive `when`, so adding a link kind such as a server invite fails to compile until both screens say something for it. Co-Authored-By: Claude Opus 5.5 --- .../feature/auth/presentation/AuthContent.kt | 20 +++++++++++++------ .../feature/auth/presentation/AuthScreen.kt | 2 +- .../auth/presentation/AuthViewModel.kt | 3 ++- .../auth/presentation/AuthViewModelTest.kt | 7 +++++-- .../presentation/OnboardingViewModel.kt | 4 +--- .../onboarding/presentation/WelcomeContent.kt | 15 ++++++++++++-- .../presentation/model/OnboardingUiState.kt | 4 +++- .../presentation/OnboardingViewModelTest.kt | 4 ++-- 8 files changed, 41 insertions(+), 18 deletions(-) diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt index fa90e36e6..012047076 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt @@ -1,5 +1,7 @@ package de.davis.keygo.feature.auth.presentation +import androidx.annotation.StringRes +import de.davis.keygo.core.ui.navigation.PendingLink import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -67,7 +69,7 @@ import de.davis.keygo.core.item.R as CoreItemR fun AuthContent( state: AuthState, onEvent: (AuthUIEvent) -> Unit, - hasPendingTotpImport: Boolean = false, + pendingLink: PendingLink? = null, ) { when (state) { is AuthState.Loading -> { @@ -158,7 +160,7 @@ fun AuthContent( is AuthState.Interactable -> InteractableAuthContent( state = state, onEvent = onEvent, - hasPendingTotpImport = hasPendingTotpImport, + pendingLink = pendingLink, ) } } @@ -168,7 +170,7 @@ fun AuthContent( private fun InteractableAuthContent( state: AuthState.Interactable, onEvent: (AuthUIEvent) -> Unit, - hasPendingTotpImport: Boolean, + pendingLink: PendingLink?, ) { Surface(modifier = Modifier.fillMaxSize()) { Box( @@ -213,9 +215,9 @@ private fun InteractableAuthContent( textAlign = TextAlign.Center, ) - if (hasPendingTotpImport) + if (pendingLink != null) Text( - text = stringResource(R.string.pending_totp_import_subtitle), + text = stringResource(pendingLink.subtitle()), modifier = Modifier.fillMaxWidth(), textAlign = TextAlign.Center, style = MaterialTheme.typography.bodyMedium, @@ -442,4 +444,10 @@ private fun AuthContentPreview(@PreviewParameter(AuthStateProvider::class) state onEvent = {} ) } -} \ No newline at end of file +} + +/** What the gate adds under its title while a deep link waits under it. */ +@StringRes +private fun PendingLink.subtitle(): Int = when (this) { + PendingLink.TotpImport -> R.string.pending_totp_import_subtitle +} diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt index c69db890e..1a566d4a7 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt @@ -22,6 +22,6 @@ fun AuthScreen(route: AuthRoute, onSuccess: () -> Unit) { AuthContent( state = state, onEvent = viewModel::onEvent, - hasPendingTotpImport = viewModel.hasPendingTotpImport, + pendingLink = viewModel.pendingLink, ) } \ No newline at end of file diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt index f5e0cf78c..59c9179a7 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt @@ -46,7 +46,8 @@ internal class AuthViewModel( private val unlockWithPassword: UnlockWithPasswordUseCase, private val createAllAccesses: CreateAccessUseCase, ) : ViewModel() { - val hasPendingTotpImport: Boolean = authRoute.pending == PendingLink.TotpImport + /** The deep link waiting under this gate, so the gate can say what it unlocks. */ + val pendingLink: PendingLink? = authRoute.pending private val passwordTextFieldState = TextFieldState() diff --git a/feature/auth/src/test/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModelTest.kt b/feature/auth/src/test/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModelTest.kt index 34bd3c552..499dbd00f 100644 --- a/feature/auth/src/test/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModelTest.kt +++ b/feature/auth/src/test/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModelTest.kt @@ -189,12 +189,15 @@ class AuthViewModelTest { @Test fun `a gate holding back an import says so`() = runTest(dispatcher) { - assertTrue(viewModel(authRoute = AuthRoute(pending = PendingLink.TotpImport)).hasPendingTotpImport) + assertEquals( + PendingLink.TotpImport, + viewModel(authRoute = AuthRoute(pending = PendingLink.TotpImport)).pendingLink, + ) } @Test fun `a plain gate mentions no import`() = runTest(dispatcher) { - assertFalse(viewModel().hasPendingTotpImport) + assertNull(viewModel().pendingLink) } @Test diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt index 11ea059cb..473831063 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt @@ -1,6 +1,5 @@ package de.davis.keygo.feature.onboarding.presentation -import de.davis.keygo.core.ui.navigation.PendingLink import android.util.Log import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.runtime.snapshotFlow @@ -52,7 +51,6 @@ internal class OnboardingViewModel( private val createAccess: CreateAccessUseCase, ) : ViewModel() { - private val hasPendingTotpImport = onboardingRoute.pending == PendingLink.TotpImport private val stepsToSkip = MutableStateFlow>(emptySet()) @@ -151,7 +149,7 @@ internal class OnboardingViewModel( @OptIn(ExperimentalCoroutinesApi::class) val state = _step.flatMapLatest { when (it) { - OnboardingStep.Welcome -> flowOf(OnboardingUiState.Welcome(pendingTotpImport = hasPendingTotpImport)) + OnboardingStep.Welcome -> flowOf(OnboardingUiState.Welcome(pendingLink = onboardingRoute.pending)) OnboardingStep.SetMainPassword -> _mainPasswordState OnboardingStep.EnableBiometrics -> _enableBiometricsState diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt index 60544754b..9a20aaca3 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt @@ -1,5 +1,6 @@ package de.davis.keygo.feature.onboarding.presentation +import de.davis.keygo.core.ui.navigation.PendingLink import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.SharedTransitionLayout import androidx.compose.foundation.layout.fillMaxSize @@ -35,8 +36,18 @@ internal fun WelcomeContent(state: OnboardingUiState.Welcome) { ) } }, - title = stringResource(if (state.pendingTotpImport) R.string.welcome_totp_import_title else R.string.welcome_title), - description = stringResource(if (state.pendingTotpImport) R.string.welcome_totp_import_subtitle else R.string.welcome_subtitle), + title = stringResource( + when (state.pendingLink) { + PendingLink.TotpImport -> R.string.welcome_totp_import_title + null -> R.string.welcome_title + }, + ), + description = stringResource( + when (state.pendingLink) { + PendingLink.TotpImport -> R.string.welcome_totp_import_subtitle + null -> R.string.welcome_subtitle + }, + ), contentHorizontalAlignment = Alignment.CenterHorizontally ) { // No content for Welcome diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt index f4d1ac3a3..d645c8d4c 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/model/OnboardingUiState.kt @@ -3,12 +3,14 @@ package de.davis.keygo.feature.onboarding.presentation.model import androidx.compose.foundation.text.input.TextFieldState import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.ui.model.UiFieldError +import de.davis.keygo.core.ui.navigation.PendingLink import de.davis.keygo.feature.autofill.domain.model.AutofillActivationStatus import de.davis.keygo.feature.backup.domain.model.BackupDestinationUri internal sealed interface OnboardingUiState { - data class Welcome(val pendingTotpImport: Boolean = false) : OnboardingUiState + /** [pendingLink] names a deep link waiting under first run, so the welcome can mention it. */ + data class Welcome(val pendingLink: PendingLink? = null) : OnboardingUiState data class SetMainPassword( val passwordTextFieldState: TextFieldState, diff --git a/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModelTest.kt b/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModelTest.kt index c4cacd1a3..1d85fa0c2 100644 --- a/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModelTest.kt +++ b/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModelTest.kt @@ -116,12 +116,12 @@ class OnboardingViewModelTest { fun `first run holding back an import welcomes with it`() = runTest(dispatcher) { val vm = viewModel(OnboardingRoute(pending = PendingLink.TotpImport)) - assertEquals(OnboardingUiState.Welcome(pendingTotpImport = true), vm.state.value) + assertEquals(OnboardingUiState.Welcome(pendingLink = PendingLink.TotpImport), vm.state.value) } @Test fun `a plain first run welcomes without an import`() = runTest(dispatcher) { - assertEquals(OnboardingUiState.Welcome(pendingTotpImport = false), viewModel().state.value) + assertEquals(OnboardingUiState.Welcome(pendingLink = null), viewModel().state.value) } @Test From 2b3628d14dbbb4e1186779fea309c2772c053d06 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 16:31:16 +0100 Subject: [PATCH 09/11] feat(app): launch MainActivity singleTop A link or notification sent with FLAG_ACTIVITY_NEW_TASK to a task whose top is already MainActivity now reaches that instance through onNewIntent instead of stacking a second one with its own navigation state and gate. A scanner that opens a link inside its own task still gets a fresh instance there; only singleTask would change that, and it is not needed for the gate to hold. Co-Authored-By: Claude Opus 5.5 --- app/src/main/AndroidManifest.xml | 1 + 1 file changed, 1 insertion(+) diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xml index e7ccf3bbf..961510e21 100644 --- a/app/src/main/AndroidManifest.xml +++ b/app/src/main/AndroidManifest.xml @@ -16,6 +16,7 @@ From f8299a81b8361da7fc1354d69766e05d985df5bf Mon Sep 17 00:00:00 2001 From: Davis Date: Fri, 4 Dec 2026 10:20:23 +0100 Subject: [PATCH 10/11] refactor(app,auth,onboarding): simplify the deep link gate - DeepLinkChecker answers isReadable instead of wrapping the link back - AppViewModel checks launch and incoming links through one helper - AppNavigator reads state.isCovered directly and clears in one call - MainActivity builds the launch stack once - AuthScreen reads the pending link from its route - WelcomeContent maps the pending link once, comments and tests tidied Co-Authored-By: Claude Opus 5.5 --- .../keygo/app/presentation/AppViewModel.kt | 22 +++++--------- .../keygo/app/presentation/MainActivity.kt | 4 ++- .../presentation/navigation/AppNavigator.kt | 11 ++----- .../navigation/DeepLinkChecker.kt | 16 +--------- .../navigation/AppNavigatorTest.kt | 29 ++++++++++++------- .../navigation/DeepLinkCheckerTest.kt | 11 +++---- .../navigation/TotpImportDeepLinkTest.kt | 8 ++--- .../feature/auth/presentation/AuthContent.kt | 2 +- .../feature/auth/presentation/AuthScreen.kt | 2 +- .../auth/presentation/AuthViewModel.kt | 4 --- .../auth/presentation/AuthViewModelTest.kt | 14 --------- .../presentation/OnboardingEntries.kt | 2 +- .../presentation/OnboardingViewModel.kt | 1 - .../onboarding/presentation/WelcomeContent.kt | 23 +++++++-------- .../presentation/OnboardingViewModelTest.kt | 2 +- .../presentation/TotpImportDeepLinkMatcher.kt | 6 ++-- 16 files changed, 59 insertions(+), 98 deletions(-) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt index d9417c903..51cedb8f9 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt @@ -3,7 +3,6 @@ package de.davis.keygo.app.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation3.runtime.NavKey -import de.davis.keygo.app.presentation.navigation.CheckedLink import de.davis.keygo.app.presentation.navigation.DeepLink import de.davis.keygo.app.presentation.navigation.DeepLinkChecker import de.davis.keygo.core.identity.domain.repository.AccountRepository @@ -79,23 +78,18 @@ internal class AppViewModel( if (isLaunchLinkChecked) return isLaunchLinkChecked = true - when (val checked = link?.let(deepLinkChecker::check)) { - is CheckedLink.Accepted -> launchLink = checked.link - is CheckedLink.Rejected -> - _rejectedLink.value = RejectedLink(checked.pending, closesApp = true) - - null -> Unit - } + checkLink(link, closesApp = true) { launchLink = it } } fun onDeepLink(link: DeepLink?) { - when (val checked = link?.let(deepLinkChecker::check)) { - is CheckedLink.Accepted -> _incomingDeepLink.value = checked.link - is CheckedLink.Rejected -> - _rejectedLink.value = RejectedLink(checked.pending, closesApp = false) + checkLink(link, closesApp = false) { _incomingDeepLink.value = it } + } - null -> Unit - } + /** Hands a readable [link] to [onAccepted], and reports an unreadable one instead. */ + private inline fun checkLink(link: DeepLink?, closesApp: Boolean, onAccepted: (DeepLink) -> Unit) { + if (link == null) return + if (deepLinkChecker.isReadable(link)) onAccepted(link) + else _rejectedLink.value = RejectedLink(link.pending, closesApp) } fun onRejectedLinkDismissed() { diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt index 96e68b6d1..9e7ea566f 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt @@ -70,6 +70,8 @@ class MainActivity : FragmentActivity() { val requestedTopLevelRoute by viewModel.requestedTopLevelRoute.collectAsState() val incomingDeepLink by viewModel.incomingDeepLink.collectAsState() val rejectedLink by viewModel.rejectedLink.collectAsState() + // Only read when the navigation state is first created; after that the saved stack wins. + val launchStack = remember { launchStack(viewModel.launchLink, hasAccess, isSessionActive) } KeyGoTheme { val snackbarManager = koinInject() @@ -78,7 +80,7 @@ class MainActivity : FragmentActivity() { ) { // Started only to take a link that cannot be read: no gate, just the report. if (rejectedLink?.closesApp != true) App( - launchStack = launchStack(viewModel.launchLink, hasAccess, isSessionActive), + launchStack = launchStack, isSessionActive = isSessionActive, needsAttentionCount = needsAttentionCount, requestedTopLevelRoute = requestedTopLevelRoute, diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt index f57812795..3b5dade67 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigator.kt @@ -17,13 +17,6 @@ import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute */ class AppNavigator(val state: AppNavigationState) { - /** - * True while the overlay is showing a screen that runs before there is a session, so a locked - * session is what it is there for rather than a reason to gate it. The import flow is not one - * of these: it only ever runs after an unlock, so a session that ends under it does gate it. - */ - private val runsWithoutSession: Boolean get() = state.isCovered - /** The one choke point every gated mutator below shares, so none can forget the check. */ private inline fun whenUnlocked(action: () -> Unit) { if (!state.isGated) action() @@ -74,7 +67,7 @@ class AppNavigator(val state: AppNavigationState) { * session is already up, which covers both a gate already in place and the caller re-firing. */ fun lock() { - if (runsWithoutSession) return + if (state.isCovered) return pushOntoOverlay(AuthRoute()) } @@ -102,7 +95,7 @@ class AppNavigator(val state: AppNavigationState) { fun openDeepLink(link: DeepLink, isSessionActive: Boolean) { val overlay = state.overlayStack if (state.isCovered) { - repeat(overlay.lastIndex) { overlay.removeAt(0) } + overlay.subList(0, overlay.lastIndex).clear() overlay.add(0, link.destination) return } diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkChecker.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkChecker.kt index d2ce7feb8..9f6d41e76 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkChecker.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkChecker.kt @@ -5,16 +5,6 @@ import de.davis.keygo.feature.totp.domain.usecase.IsReadableTotpUriUseCase import de.davis.keygo.feature.totp.presentation.SelectItemForTotpRoute import org.koin.core.annotation.Factory -/** What a matched link turned out to be once its content was read. */ -sealed interface CheckedLink { - - /** Readable: its destination goes onto the overlay, behind the gate. */ - data class Accepted(val link: DeepLink) : CheckedLink - - /** Unreadable: reported straight away, without a gate, and nothing is opened. */ - data class Rejected(val pending: PendingLink) : CheckedLink -} - /** * Reads a link's content before the gate goes up, so a broken one is reported without asking the * user to unlock for nothing. The `when` is exhaustive over [PendingLink], so a new kind of link @@ -25,11 +15,7 @@ class DeepLinkChecker( private val isReadableTotpUri: IsReadableTotpUriUseCase, ) { - fun check(link: DeepLink): CheckedLink = - if (isReadable(link)) CheckedLink.Accepted(link) - else CheckedLink.Rejected(link.pending) - - private fun isReadable(link: DeepLink): Boolean = when (link.pending) { + fun isReadable(link: DeepLink): Boolean = when (link.pending) { PendingLink.TotpImport -> (link.destination as? SelectItemForTotpRoute) ?.let { isReadableTotpUri(it.totpUri) } == true } diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt index cbc538475..9191cdbe1 100644 --- a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt +++ b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt @@ -6,13 +6,13 @@ import androidx.navigation3.runtime.NavKey import de.davis.keygo.core.item.domain.alias.newItemId import de.davis.keygo.core.item.generated.domain.model.VaultItemType import de.davis.keygo.core.presentation.model.RouteDestination +import de.davis.keygo.core.ui.navigation.PendingLink import de.davis.keygo.feature.account.presentation.ChangePasswordRoute import de.davis.keygo.feature.auth.presentation.AuthRoute import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute import de.davis.keygo.feature.password_health.presentation.PasswordHealthRoute import de.davis.keygo.feature.settings.presentation.SettingsRoute import de.davis.keygo.feature.totp.presentation.SelectItemForTotpRoute -import de.davis.keygo.core.ui.navigation.PendingLink import kotlin.test.Test import kotlin.test.assertEquals import kotlin.test.assertFalse @@ -90,7 +90,7 @@ class AppNavigatorTest { @Test fun `a link waiting under the gate is not displayed until the unlock`() { - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true, isSessionActive = false).toTypedArray()) + val navigator = linkLaunched(hasAccess = true) assertEquals(listOf(AuthRoute(pending = PendingLink.TotpImport)), navigator.displayed) @@ -101,7 +101,7 @@ class AppNavigatorTest { @Test fun `back on a link's gate cannot reach the link`() { - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true, isSessionActive = false).toTypedArray()) + val navigator = linkLaunched(hasAccess = true) navigator.goBack() @@ -113,7 +113,7 @@ class AppNavigatorTest { @Test fun `a link's gate is not gated a second time when the session is still ended`() { - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true, isSessionActive = false).toTypedArray()) + val navigator = linkLaunched(hasAccess = true) navigator.lock() @@ -122,7 +122,7 @@ class AppNavigatorTest { @Test fun `finishing first run reveals the link that waited under it`() { - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = false, isSessionActive = false).toTypedArray()) + val navigator = linkLaunched(hasAccess = false) navigator.finishFirstRun() @@ -131,7 +131,7 @@ class AppNavigatorTest { @Test fun `first run holding back a link is displayed alone, so nothing peeks out under it`() { - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = false, isSessionActive = false).toTypedArray()) + val navigator = linkLaunched(hasAccess = false) assertEquals(listOf(OnboardingRoute(pending = PendingLink.TotpImport)), navigator.displayed) } @@ -141,7 +141,7 @@ class AppNavigatorTest { // Welcome hands back to the display. Popping first run here would land a user who has no // account yet on the picker, and the lock would then ask them to unlock an account that // does not exist. - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = false, isSessionActive = false).toTypedArray()) + val navigator = linkLaunched(hasAccess = false) navigator.goBack() @@ -179,7 +179,7 @@ class AppNavigatorTest { @Test fun `a link arriving during an earlier link's flow replaces it under a fresh gate`() { val navigator = navigator( - SelectItemForTotpRoute("otpauth://totp/Other?secret=ABC"), + OTHER_LINK_ROUTE, TestAssignRoute, ) @@ -193,7 +193,7 @@ class AppNavigatorTest { @Test fun `a link arriving during an earlier link's flow under a live session replaces it`() { - val navigator = navigator(SelectItemForTotpRoute("otpauth://totp/Other?secret=ABC")) + val navigator = navigator(OTHER_LINK_ROUTE) navigator.openDeepLink(TOTP_LINK, isSessionActive = true) @@ -203,7 +203,7 @@ class AppNavigatorTest { @Test fun `a second link under the gate replaces the one already waiting`() { val navigator = navigator( - SelectItemForTotpRoute("otpauth://totp/Other?secret=ABC"), + OTHER_LINK_ROUTE, AuthRoute(pending = PendingLink.TotpImport), ) @@ -244,7 +244,7 @@ class AppNavigatorTest { @Test fun `back from a revealed link leaves the app instead of reaching the gate it waited under`() { - val navigator = navigator(*launchStack(TOTP_LINK, hasAccess = true, isSessionActive = false).toTypedArray()) + val navigator = linkLaunched(hasAccess = true) navigator.unlock() navigator.goBack() @@ -807,6 +807,10 @@ class AppNavigatorTest { private fun unlocked(): AppNavigator = navigator().apply { unlock() } + /** A cold start with [TOTP_LINK] and no session: the link waits under the gate or first run. */ + private fun linkLaunched(hasAccess: Boolean): AppNavigator = + navigator(*launchStack(TOTP_LINK, hasAccess, isSessionActive = false).toTypedArray()) + private companion object { val TOP_LEVEL_ROUTES: Set = linkedSetOf( RouteDestination.Home, @@ -819,6 +823,9 @@ class AppNavigatorTest { "otpauth://totp/GitHub:me@github.com?secret=JBSWY3DPEHPK3PXP&issuer=github.com" val TOTP_LINK = DeepLink(SelectItemForTotpRoute(DEEP_LINK_URI), PendingLink.TotpImport) + + /** An earlier link's destination, which a newer one replaces. */ + val OTHER_LINK_ROUTE = SelectItemForTotpRoute("otpauth://totp/Other?secret=ABC") } } diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkCheckerTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkCheckerTest.kt index f0a81bedd..53f1137ac 100644 --- a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkCheckerTest.kt +++ b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkCheckerTest.kt @@ -7,7 +7,8 @@ import de.davis.keygo.rust.FakeTotpService import de.davisalessandro.keygo.rust.Algorithm import de.davisalessandro.keygo.rust.TotpInfo import kotlin.test.Test -import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertTrue /** A link is read before the gate goes up, so a broken one never asks the user to unlock. */ class DeepLinkCheckerTest { @@ -19,7 +20,7 @@ class DeepLinkCheckerTest { DeepLink(SelectItemForTotpRoute("otpauth://totp/Example?secret=ABC"), PendingLink.TotpImport) @Test - fun `a readable otpauth link is accepted as it is`() { + fun `a readable otpauth link is accepted`() { totpService.infoFromUriResult = TotpInfo( secret = "JBSWY3DPEHPK3PXP", issuer = "Example", @@ -29,13 +30,13 @@ class DeepLinkCheckerTest { period = 30, ) - assertEquals(CheckedLink.Accepted(totpLink), checker.check(totpLink)) + assertTrue(checker.isReadable(totpLink)) } @Test - fun `an unreadable otpauth link is rejected under its own kind`() { + fun `an unreadable otpauth link is rejected`() { totpService.infoFromUriResult = null - assertEquals(CheckedLink.Rejected(PendingLink.TotpImport), checker.check(totpLink)) + assertFalse(checker.isReadable(totpLink)) } } diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/TotpImportDeepLinkTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/TotpImportDeepLinkTest.kt index a7fe89dca..200d3b385 100644 --- a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/TotpImportDeepLinkTest.kt +++ b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/TotpImportDeepLinkTest.kt @@ -72,18 +72,18 @@ class TotpImportDeepLinkTest { } /** - * An incomplete link still opens the picker, carrying the link as it arrived, so the picker's - * own parse reports it after the unlock instead of the app opening as if nothing was sent. + * An incomplete link still matches, carrying the link as it arrived, so the app's check reports + * it instead of the app opening as if nothing was sent. */ @Test - fun `a link with no query is passed on as it arrived, for the picker to reject`() { + fun `a link with no query is passed on as it arrived, to be rejected`() { val key = assertNotNull(match("otpauth://totp/Example:me@example.com")) assertEquals("otpauth://totp/Example:me@example.com", key.totpUri) } @Test - fun `a link with no label is passed on as it arrived, for the picker to reject`() { + fun `a link with no label is passed on as it arrived, to be rejected`() { val key = assertNotNull(match("otpauth://totp?secret=ABC")) assertEquals("otpauth://totp?secret=ABC", key.totpUri) diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt index 012047076..25843433d 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt @@ -1,7 +1,6 @@ package de.davis.keygo.feature.auth.presentation import androidx.annotation.StringRes -import de.davis.keygo.core.ui.navigation.PendingLink import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -58,6 +57,7 @@ import androidx.compose.ui.tooling.preview.PreviewParameterProvider import androidx.compose.ui.unit.dp import de.davis.keygo.core.ui.components.VisibilityButton import de.davis.keygo.core.ui.model.error +import de.davis.keygo.core.ui.navigation.PendingLink import de.davis.keygo.core.ui.theme.KeyGoTheme import de.davis.keygo.feature.auth.R import de.davis.keygo.feature.auth.presentation.model.AuthState diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt index 1a566d4a7..96ec7c15b 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt @@ -22,6 +22,6 @@ fun AuthScreen(route: AuthRoute, onSuccess: () -> Unit) { AuthContent( state = state, onEvent = viewModel::onEvent, - pendingLink = viewModel.pendingLink, + pendingLink = route.pending, ) } \ No newline at end of file diff --git a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt index 59c9179a7..77ef9e6d5 100644 --- a/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt +++ b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModel.kt @@ -1,6 +1,5 @@ package de.davis.keygo.feature.auth.presentation -import de.davis.keygo.core.ui.navigation.PendingLink import androidx.compose.foundation.text.input.TextFieldState import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -46,9 +45,6 @@ internal class AuthViewModel( private val unlockWithPassword: UnlockWithPasswordUseCase, private val createAllAccesses: CreateAccessUseCase, ) : ViewModel() { - /** The deep link waiting under this gate, so the gate can say what it unlocks. */ - val pendingLink: PendingLink? = authRoute.pending - private val passwordTextFieldState = TextFieldState() private val _uiState = MutableStateFlow(AuthState.Loading) diff --git a/feature/auth/src/test/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModelTest.kt b/feature/auth/src/test/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModelTest.kt index 499dbd00f..8a3283803 100644 --- a/feature/auth/src/test/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModelTest.kt +++ b/feature/auth/src/test/kotlin/de/davis/keygo/feature/auth/presentation/AuthViewModelTest.kt @@ -19,7 +19,6 @@ import de.davis.keygo.core.security.crypto.FakeKeyStoreManager import de.davis.keygo.core.security.domain.model.CryptographicMode import de.davis.keygo.core.security.domain.model.CipherKeyId import de.davis.keygo.core.ui.model.UiFieldError -import de.davis.keygo.core.ui.navigation.PendingLink import de.davis.keygo.core.util.isSuccess import de.davis.keygo.feature.auth.presentation.model.AuthState import de.davis.keygo.feature.auth.presentation.model.AuthUIEvent @@ -187,19 +186,6 @@ class AuthViewModelTest { biometricCrypto.prompts.clear() } - @Test - fun `a gate holding back an import says so`() = runTest(dispatcher) { - assertEquals( - PendingLink.TotpImport, - viewModel(authRoute = AuthRoute(pending = PendingLink.TotpImport)).pendingLink, - ) - } - - @Test - fun `a plain gate mentions no import`() = runTest(dispatcher) { - assertNull(viewModel().pendingLink) - } - @Test fun `an enrolled account opens the prompt on arrival and continues once unlocked`() = runTest(dispatcher) { diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingEntries.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingEntries.kt index b3dcf8b94..a1b959e39 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingEntries.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingEntries.kt @@ -1,8 +1,8 @@ package de.davis.keygo.feature.onboarding.presentation -import de.davis.keygo.core.ui.navigation.PendingLink import androidx.navigation3.runtime.EntryProviderScope import androidx.navigation3.runtime.NavKey +import de.davis.keygo.core.ui.navigation.PendingLink import kotlinx.serialization.Serializable fun EntryProviderScope.onboardingEntries( diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt index 473831063..96fbc699f 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModel.kt @@ -51,7 +51,6 @@ internal class OnboardingViewModel( private val createAccess: CreateAccessUseCase, ) : ViewModel() { - private val stepsToSkip = MutableStateFlow>(emptySet()) private fun calculateStepsToSkip() { diff --git a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt index 9a20aaca3..29fadb702 100644 --- a/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt +++ b/feature/onboarding/src/main/kotlin/de/davis/keygo/feature/onboarding/presentation/WelcomeContent.kt @@ -1,6 +1,5 @@ package de.davis.keygo.feature.onboarding.presentation -import de.davis.keygo.core.ui.navigation.PendingLink import androidx.compose.animation.AnimatedVisibility import androidx.compose.animation.SharedTransitionLayout import androidx.compose.foundation.layout.fillMaxSize @@ -16,6 +15,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.tooling.preview.Preview +import de.davis.keygo.core.ui.navigation.PendingLink import de.davis.keygo.feature.onboarding.R import de.davis.keygo.feature.onboarding.presentation.component.LargeIconContainer import de.davis.keygo.feature.onboarding.presentation.component.OnboardingScaffold @@ -25,6 +25,7 @@ import de.davis.keygo.core.ui.R as CoreUiR @OptIn(ExperimentalMaterial3ExpressiveApi::class) @Composable internal fun WelcomeContent(state: OnboardingUiState.Welcome) { + val (title, description) = welcomeText(state.pendingLink) OnboardingScaffold( iconContainer = { LargeIconContainer( @@ -36,24 +37,20 @@ internal fun WelcomeContent(state: OnboardingUiState.Welcome) { ) } }, - title = stringResource( - when (state.pendingLink) { - PendingLink.TotpImport -> R.string.welcome_totp_import_title - null -> R.string.welcome_title - }, - ), - description = stringResource( - when (state.pendingLink) { - PendingLink.TotpImport -> R.string.welcome_totp_import_subtitle - null -> R.string.welcome_subtitle - }, - ), + title = stringResource(title), + description = stringResource(description), contentHorizontalAlignment = Alignment.CenterHorizontally ) { // No content for Welcome } } +/** The welcome's title and description, worded after the link waiting under first run. */ +private fun welcomeText(pendingLink: PendingLink?): Pair = when (pendingLink) { + PendingLink.TotpImport -> R.string.welcome_totp_import_title to R.string.welcome_totp_import_subtitle + null -> R.string.welcome_title to R.string.welcome_subtitle +} + @Preview @Composable private fun WelcomeContentPreview() { diff --git a/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModelTest.kt b/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModelTest.kt index 1d85fa0c2..1e3b5612b 100644 --- a/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModelTest.kt +++ b/feature/onboarding/src/test/kotlin/de/davis/keygo/feature/onboarding/presentation/OnboardingViewModelTest.kt @@ -15,6 +15,7 @@ import de.davis.keygo.core.item.domain.estimator.PasswordStrengthEstimator import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.security.FakeSession import de.davis.keygo.core.security.domain.model.CryptographicMode +import de.davis.keygo.core.ui.navigation.PendingLink import de.davis.keygo.feature.autofill.domain.usecase.AutofillActivationStatusUseCase import de.davis.keygo.feature.onboarding.presentation.model.OnboardingUiState import kotlinx.coroutines.CompletableDeferred @@ -32,7 +33,6 @@ import kotlinx.coroutines.test.setMain import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config -import de.davis.keygo.core.ui.navigation.PendingLink import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcher.kt b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcher.kt index b49653fce..9e6610a1a 100644 --- a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcher.kt +++ b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcher.kt @@ -5,7 +5,7 @@ import androidx.navigation3.runtime.deeplink.DeepLinkRequest /** * Matches the `otpauth://totp` links the app registers an intent filter for, straight to the - * picker that imports them. The picker parses the link itself and reports one it cannot read. + * picker that imports them. The app reads the link before opening it and reports one it cannot read. * * `UriDeepLinkMatcher` cannot stand in for this. It percent-decodes every value it extracts, and * its unnamed query parameter only collects parts that carry no "=", so a real otpauth query is @@ -34,8 +34,8 @@ object TotpImportDeepLinkMatcher : val label = uri.encodedPath?.removePrefix("/")?.takeIf { it.isNotBlank() } val query = uri.encodedQuery?.takeIf { it.isNotBlank() } - // An incomplete link is passed on as it arrived rather than dropped, so the picker's - // parse rejects it in front of the user instead of the app opening as if nothing was sent. + // An incomplete link is passed on as it arrived rather than dropped, so the app's check + // rejects it in front of the user instead of the app opening as if nothing was sent. val totpUri = if (label != null && query != null) "$BASE_PATH/$label?$query" else uri.toString() From d475cc4f94af820656ce7acdf51997724db55af1 Mon Sep 17 00:00:00 2001 From: Davis Date: Fri, 4 Dec 2026 10:46:07 +0100 Subject: [PATCH 11/11] refactor(app,totp): features contribute their deep link matchers Following nav3-recipes (modular/koin, usecases/matcher): each feature binds a LinkMatcher in Koin and the app asks all of them, so the app no longer lists links or knows what any of them carries. - core:ui adds LinkMatcher / LinkMatch (key, kind, isReadable) - TotpImportDeepLinkMatcher reads the link itself and is a @Single - AppViewModel matches DeepLinkRequest(intent) against List - DeepLinkChecker and its cast are gone; the matcher test moves to totp Co-Authored-By: Claude Opus 5.5 --- app/build.gradle.kts | 1 - .../keygo/app/presentation/AppViewModel.kt | 31 +++++++----- .../keygo/app/presentation/MainActivity.kt | 9 ++-- .../navigation/DeepLinkChecker.kt | 22 --------- .../app/presentation/navigation/DeepLinks.kt | 29 +++++------ .../presentation/navigation/EntryProvider.kt | 2 +- .../navigation/DeepLinkCheckerTest.kt | 42 ---------------- .../keygo/core/ui/navigation/LinkMatcher.kt | 29 +++++++++++ .../presentation/TotpImportDeepLinkMatcher.kt | 40 ++++++++++------ .../TotpImportDeepLinkMatcherTest.kt | 48 +++++++++++++++++-- 10 files changed, 136 insertions(+), 117 deletions(-) delete mode 100644 app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkChecker.kt delete mode 100644 app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkCheckerTest.kt create mode 100644 core/ui/src/main/kotlin/de/davis/keygo/core/ui/navigation/LinkMatcher.kt rename app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/TotpImportDeepLinkTest.kt => feature/totp/src/test/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcherTest.kt (71%) diff --git a/app/build.gradle.kts b/app/build.gradle.kts index ae7734ac2..8c176e6f0 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -169,7 +169,6 @@ dependencies { testImplementation(libs.kotlin.test) testImplementation(libs.robolectric) testImplementation(libs.androidx.junit) - testImplementation(testFixtures(projects.core.rust)) androidTestImplementation(libs.androidx.junit) androidTestImplementation(libs.androidx.espresso.core) diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt index 51cedb8f9..7254fc700 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/AppViewModel.kt @@ -3,10 +3,12 @@ package de.davis.keygo.app.presentation import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import androidx.navigation3.runtime.NavKey +import androidx.navigation3.runtime.deeplink.DeepLinkRequest import de.davis.keygo.app.presentation.navigation.DeepLink -import de.davis.keygo.app.presentation.navigation.DeepLinkChecker +import de.davis.keygo.app.presentation.navigation.match import de.davis.keygo.core.identity.domain.repository.AccountRepository import de.davis.keygo.core.security.domain.Session +import de.davis.keygo.core.ui.navigation.LinkMatcher import de.davis.keygo.core.ui.navigation.PendingLink import de.davis.keygo.feature.password_health.domain.PasswordHealthAttention import de.davis.keygo.legacy_migration.domain.usecase.HasMainPasswordUseCase @@ -23,7 +25,7 @@ internal class AppViewModel( private val hasV1Password: HasMainPasswordUseCase, session: Session, passwordHealthAttention: PasswordHealthAttention, - private val deepLinkChecker: DeepLinkChecker, + private val linkMatchers: List, ) : ViewModel() { private val _isReturningUser = MutableStateFlow(null) @@ -74,22 +76,29 @@ internal class AppViewModel( * Checks the link the Activity was started with. Only the first call counts: a recreated * Activity hands in the same intent, and its navigation is restored rather than relaunched. */ - fun onLaunchLink(link: DeepLink?) { + fun onLaunchLink(request: DeepLinkRequest?) { if (isLaunchLinkChecked) return isLaunchLinkChecked = true - checkLink(link, closesApp = true) { launchLink = it } + matchLink(request, closesApp = true) { launchLink = it } } - fun onDeepLink(link: DeepLink?) { - checkLink(link, closesApp = false) { _incomingDeepLink.value = it } + fun onDeepLink(request: DeepLinkRequest?) { + matchLink(request, closesApp = false) { _incomingDeepLink.value = it } } - /** Hands a readable [link] to [onAccepted], and reports an unreadable one instead. */ - private inline fun checkLink(link: DeepLink?, closesApp: Boolean, onAccepted: (DeepLink) -> Unit) { - if (link == null) return - if (deepLinkChecker.isReadable(link)) onAccepted(link) - else _rejectedLink.value = RejectedLink(link.pending, closesApp) + /** + * Hands a link the app accepts to [onAccepted] if it could be read, and reports it otherwise. + * A request no feature recognises is not a link at all and is ignored. + */ + private inline fun matchLink( + request: DeepLinkRequest?, + closesApp: Boolean, + onAccepted: (DeepLink) -> Unit, + ) { + val match = request?.let(linkMatchers::match) ?: return + if (match.isReadable) onAccepted(DeepLink(match.key, match.kind)) + else _rejectedLink.value = RejectedLink(match.kind, closesApp) } fun onRejectedLinkDismissed() { diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt index 9e7ea566f..32e13f420 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/MainActivity.kt @@ -31,7 +31,7 @@ import de.davis.keygo.app.presentation.navigation.keyGoEntryProvider import de.davis.keygo.app.presentation.navigation.launchStack import de.davis.keygo.app.presentation.navigation.rememberAppNavigationState import de.davis.keygo.app.presentation.navigation.resolveAppShell -import de.davis.keygo.app.presentation.navigation.toDeepLink +import de.davis.keygo.app.presentation.navigation.toDeepLinkRequest import de.davis.keygo.core.presentation.model.RouteDestination import de.davis.keygo.core.sync.domain.stepup.StepUpPrompter import de.davis.keygo.core.ui.composition.LocalIsInSinglePaneMode @@ -55,7 +55,7 @@ class MainActivity : FragmentActivity() { // A recreated Activity already restored the tab the request selected. if (savedInstanceState == null) viewModel.onIntentAction(intent.action) - viewModel.onLaunchLink(intent.deepLink()) + viewModel.onLaunchLink(intent.toDeepLinkRequest()) splashScreen.setKeepOnScreenCondition { viewModel.isReturningUser.value == null @@ -106,13 +106,10 @@ class MainActivity : FragmentActivity() { override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) viewModel.onIntentAction(intent.action) - viewModel.onDeepLink(intent.deepLink()) + viewModel.onDeepLink(intent.toDeepLinkRequest()) } } -// A DeepLinkRequest with neither a uri nor extras throws, and the launcher intent has no data. -private fun Intent.deepLink(): DeepLink? = data?.toDeepLink() - @OptIn(ExperimentalMaterial3AdaptiveApi::class) @Composable private fun App( diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkChecker.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkChecker.kt deleted file mode 100644 index 9f6d41e76..000000000 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkChecker.kt +++ /dev/null @@ -1,22 +0,0 @@ -package de.davis.keygo.app.presentation.navigation - -import de.davis.keygo.core.ui.navigation.PendingLink -import de.davis.keygo.feature.totp.domain.usecase.IsReadableTotpUriUseCase -import de.davis.keygo.feature.totp.presentation.SelectItemForTotpRoute -import org.koin.core.annotation.Factory - -/** - * Reads a link's content before the gate goes up, so a broken one is reported without asking the - * user to unlock for nothing. The `when` is exhaustive over [PendingLink], so a new kind of link - * cannot be registered without saying how it is checked. - */ -@Factory -class DeepLinkChecker( - private val isReadableTotpUri: IsReadableTotpUriUseCase, -) { - - fun isReadable(link: DeepLink): Boolean = when (link.pending) { - PendingLink.TotpImport -> (link.destination as? SelectItemForTotpRoute) - ?.let { isReadableTotpUri(it.totpUri) } == true - } -} diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinks.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinks.kt index 27496f72e..8efd076c6 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinks.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinks.kt @@ -1,28 +1,29 @@ package de.davis.keygo.app.presentation.navigation -import android.net.Uri +import android.content.Intent import androidx.navigation3.runtime.NavKey import androidx.navigation3.runtime.deeplink.DeepLinkRequest +import androidx.navigation3.runtime.deeplink.invoke +import de.davis.keygo.core.ui.navigation.LinkMatch +import de.davis.keygo.core.ui.navigation.LinkMatcher import de.davis.keygo.core.ui.navigation.PendingLink import de.davis.keygo.feature.auth.presentation.AuthRoute import de.davis.keygo.feature.onboarding.presentation.OnboardingRoute -import de.davis.keygo.feature.totp.presentation.TotpImportDeepLinkMatcher -/** A link the app was opened with: where it leads, and what the gate in front of it says. */ +/** A readable link the app was opened with: where it leads, and what the gate in front of it says. */ data class DeepLink(val destination: NavKey, val pending: PendingLink) -/** Every link the app accepts, each with its manifest intent filter. The first match wins. */ -private val deepLinkMatchers: List<(DeepLinkRequest) -> DeepLink?> = listOf( - { request -> - TotpImportDeepLinkMatcher.match(request)?.key - ?.let { DeepLink(it, PendingLink.TotpImport) } - }, -) +/** + * The request an [Intent] carries, or null for one with nothing to match: a plain launch has no + * data, and a [DeepLinkRequest] with neither a uri nor extras throws. + */ +fun Intent.toDeepLinkRequest(): DeepLinkRequest? = + if (data == null && extras == null) null + else DeepLinkRequest(this) -fun Uri.toDeepLink(): DeepLink? { - val request = DeepLinkRequest(this) - return deepLinkMatchers.firstNotNullOfOrNull { match -> match(request) } -} +/** Asks every feature's matcher in turn, first match wins. */ +fun List.match(request: DeepLinkRequest): LinkMatch? = + firstNotNullOfOrNull { matcher -> matcher.match(request) } /** * The overlay the app opens on. A link opened under a live session goes straight to its diff --git a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/EntryProvider.kt b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/EntryProvider.kt index d69519bb3..fe4518eff 100644 --- a/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/EntryProvider.kt +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/EntryProvider.kt @@ -48,7 +48,7 @@ fun keyGoEntryProvider(navigator: AppNavigator): (NavKey) -> NavEntry { navigator.navigate(AssignTotpRoute(totpUri, itemId.toString())) }, onCreateNew = { totpUri -> navigator.navigate(AssignTotpRoute(totpUri)) }, - // A backstop: DeepLinkChecker rejects an unreadable link before the gate. Shown + // A backstop: the link's matcher rejects an unreadable one before the gate. Shown // after the unlock, so the user lands in the app rather than leaving it. onRejected = { navigator.clearOverlay() }, ) diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkCheckerTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkCheckerTest.kt deleted file mode 100644 index 53f1137ac..000000000 --- a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinkCheckerTest.kt +++ /dev/null @@ -1,42 +0,0 @@ -package de.davis.keygo.app.presentation.navigation - -import de.davis.keygo.core.ui.navigation.PendingLink -import de.davis.keygo.feature.totp.domain.usecase.IsReadableTotpUriUseCase -import de.davis.keygo.feature.totp.presentation.SelectItemForTotpRoute -import de.davis.keygo.rust.FakeTotpService -import de.davisalessandro.keygo.rust.Algorithm -import de.davisalessandro.keygo.rust.TotpInfo -import kotlin.test.Test -import kotlin.test.assertFalse -import kotlin.test.assertTrue - -/** A link is read before the gate goes up, so a broken one never asks the user to unlock. */ -class DeepLinkCheckerTest { - - private val totpService = FakeTotpService() - private val checker = DeepLinkChecker(IsReadableTotpUriUseCase(totpService)) - - private val totpLink = - DeepLink(SelectItemForTotpRoute("otpauth://totp/Example?secret=ABC"), PendingLink.TotpImport) - - @Test - fun `a readable otpauth link is accepted`() { - totpService.infoFromUriResult = TotpInfo( - secret = "JBSWY3DPEHPK3PXP", - issuer = "Example", - accountName = "me@example.com", - algorithm = Algorithm.SHA1, - digits = 6, - period = 30, - ) - - assertTrue(checker.isReadable(totpLink)) - } - - @Test - fun `an unreadable otpauth link is rejected`() { - totpService.infoFromUriResult = null - - assertFalse(checker.isReadable(totpLink)) - } -} diff --git a/core/ui/src/main/kotlin/de/davis/keygo/core/ui/navigation/LinkMatcher.kt b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/navigation/LinkMatcher.kt new file mode 100644 index 000000000..b914579e7 --- /dev/null +++ b/core/ui/src/main/kotlin/de/davis/keygo/core/ui/navigation/LinkMatcher.kt @@ -0,0 +1,29 @@ +package de.davis.keygo.core.ui.navigation + +import androidx.navigation3.runtime.NavKey +import androidx.navigation3.runtime.deeplink.DeepLinkMatcher + +/** + * A link one feature accepts. Each feature contributes its own through Koin, bound as + * [LinkMatcher], and the app asks every one of them, first match wins: the app holds no list of + * links and knows nothing about what any of them carries. + * + * @param filters checked against the request before [matchRequest] runs. + */ +abstract class LinkMatcher( + filters: List = emptyList(), +) : DeepLinkMatcher(filters) + +/** + * A request a [LinkMatcher] recognised. + * + * @param key where the link leads. + * @param kind what the gate in front of it says while it waits. + * @param isReadable whether its content could be read. The matcher reads it straight away, so a + * broken link is reported before the gate goes up rather than after the user unlocks for it. + */ +class LinkMatch( + key: NavKey, + val kind: PendingLink, + val isReadable: Boolean, +) : DeepLinkMatcher.MatchResult(key) diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcher.kt b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcher.kt index 9e6610a1a..b9551e90f 100644 --- a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcher.kt +++ b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcher.kt @@ -1,27 +1,26 @@ package de.davis.keygo.feature.totp.presentation -import androidx.navigation3.runtime.deeplink.DeepLinkMatcher import androidx.navigation3.runtime.deeplink.DeepLinkRequest +import de.davis.keygo.core.ui.navigation.LinkMatch +import de.davis.keygo.core.ui.navigation.LinkMatcher +import de.davis.keygo.core.ui.navigation.PendingLink +import de.davis.keygo.feature.totp.domain.usecase.IsReadableTotpUriUseCase +import org.koin.core.annotation.Single /** * Matches the `otpauth://totp` links the app registers an intent filter for, straight to the - * picker that imports them. The app reads the link before opening it and reports one it cannot read. + * picker that imports them, and reads each one on the way so a broken link is reported up front. * * `UriDeepLinkMatcher` cannot stand in for this. It percent-decodes every value it extracts, and * its unnamed query parameter only collects parts that carry no "=", so a real otpauth query is * dropped whole. Both matter here, because the link has to reach the parser exactly as it arrived. */ -object TotpImportDeepLinkMatcher : - DeepLinkMatcher>() { +@Single(binds = [LinkMatcher::class]) +class TotpImportDeepLinkMatcher( + private val isReadableTotpUri: IsReadableTotpUriUseCase, +) : LinkMatcher() { - const val SCHEME = "otpauth" - const val HOST = "totp" - - private const val BASE_PATH = "$SCHEME://$HOST" - - override fun matchRequest( - request: DeepLinkRequest, - ): MatchResult? { + override fun matchRequest(request: DeepLinkRequest): LinkMatch? { val uri = request.uri ?: return null if (!uri.scheme.equals(SCHEME, ignoreCase = true)) return null if (!uri.host.equals(HOST, ignoreCase = true)) return null @@ -34,11 +33,22 @@ object TotpImportDeepLinkMatcher : val label = uri.encodedPath?.removePrefix("/")?.takeIf { it.isNotBlank() } val query = uri.encodedQuery?.takeIf { it.isNotBlank() } - // An incomplete link is passed on as it arrived rather than dropped, so the app's check - // rejects it in front of the user instead of the app opening as if nothing was sent. + // An incomplete link is passed on as it arrived rather than dropped, so it is reported as + // unreadable in front of the user instead of the app opening as if nothing was sent. val totpUri = if (label != null && query != null) "$BASE_PATH/$label?$query" else uri.toString() - return MatchResult(SelectItemForTotpRoute(totpUri)) + return LinkMatch( + key = SelectItemForTotpRoute(totpUri), + kind = PendingLink.TotpImport, + isReadable = isReadableTotpUri(totpUri), + ) + } + + companion object { + const val SCHEME = "otpauth" + const val HOST = "totp" + + private const val BASE_PATH = "$SCHEME://$HOST" } } diff --git a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/TotpImportDeepLinkTest.kt b/feature/totp/src/test/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcherTest.kt similarity index 71% rename from app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/TotpImportDeepLinkTest.kt rename to feature/totp/src/test/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcherTest.kt index 200d3b385..10a2adecf 100644 --- a/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/TotpImportDeepLinkTest.kt +++ b/feature/totp/src/test/kotlin/de/davis/keygo/feature/totp/presentation/TotpImportDeepLinkMatcherTest.kt @@ -1,24 +1,32 @@ -package de.davis.keygo.app.presentation.navigation +package de.davis.keygo.feature.totp.presentation import androidx.core.net.toUri import androidx.navigation3.runtime.deeplink.DeepLinkRequest -import de.davis.keygo.feature.totp.presentation.TotpImportDeepLinkMatcher -import de.davis.keygo.feature.totp.presentation.SelectItemForTotpRoute +import de.davis.keygo.core.ui.navigation.PendingLink +import de.davis.keygo.feature.totp.domain.usecase.IsReadableTotpUriUseCase +import de.davis.keygo.rust.FakeTotpService +import de.davisalessandro.keygo.rust.Algorithm +import de.davisalessandro.keygo.rust.TotpInfo import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.annotation.Config import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertNotNull import kotlin.test.assertNull +import kotlin.test.assertTrue /** An `otpauth://` link has to reach the import picker whole: label and query parameters intact. */ @RunWith(RobolectricTestRunner::class) @Config(sdk = [34]) -class TotpImportDeepLinkTest { +class TotpImportDeepLinkMatcherTest { + + private val totpService = FakeTotpService() + private val matcher = TotpImportDeepLinkMatcher(IsReadableTotpUriUseCase(totpService)) private fun match(uri: String): SelectItemForTotpRoute? = - TotpImportDeepLinkMatcher.match(DeepLinkRequest(uri.toUri()))?.key + matcher.match(DeepLinkRequest(uri.toUri()))?.key as SelectItemForTotpRoute? @Test fun `a single query parameter round trips`() { @@ -102,6 +110,27 @@ class TotpImportDeepLinkTest { assertNull(match("otpauth://hotp/Example?secret=ABC&counter=1")) } + @Test + fun `a link the parser reads is matched as a readable import`() { + totpService.infoFromUriResult = TOTP_INFO + + val match = assertNotNull(matcher.match(DeepLinkRequest(DEEP_LINK_URI.toUri()))) + + assertTrue(match.isReadable) + assertEquals(PendingLink.TotpImport, match.kind) + } + + /** Still a match, so the app reports it as a broken import rather than opening as normal. */ + @Test + fun `a link the parser rejects is matched as unreadable`() { + totpService.infoFromUriResult = null + + val match = assertNotNull(matcher.match(DeepLinkRequest(DEEP_LINK_URI.toUri()))) + + assertFalse(match.isReadable) + assertEquals(PendingLink.TotpImport, match.kind) + } + @Test fun `the manifest's intent filter and the parser agree`() { assertEquals("otpauth", TotpImportDeepLinkMatcher.SCHEME) @@ -111,5 +140,14 @@ class TotpImportDeepLinkTest { private companion object { const val DEEP_LINK_URI = "otpauth://totp/GitHub:me@github.com?secret=JBSWY3DPEHPK3PXP&issuer=github.com" + + val TOTP_INFO = TotpInfo( + secret = "JBSWY3DPEHPK3PXP", + issuer = "github.com", + accountName = "me@github.com", + algorithm = Algorithm.SHA1, + digits = 6, + period = 30, + ) } }