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 @@ 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..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,8 +3,13 @@ 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.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 import kotlinx.coroutines.flow.MutableStateFlow @@ -20,6 +25,7 @@ internal class AppViewModel( private val hasV1Password: HasMainPasswordUseCase, session: Session, passwordHealthAttention: PasswordHealthAttention, + private val linkMatchers: List, ) : ViewModel() { private val _isReturningUser = MutableStateFlow(null) @@ -36,6 +42,21 @@ 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() + + /** 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() } @@ -50,4 +71,47 @@ internal class AppViewModel( fun onTopLevelRouteRequestHandled() { _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(request: DeepLinkRequest?) { + if (isLaunchLinkChecked) return + isLaunchLinkChecked = true + + matchLink(request, closesApp = true) { launchLink = it } + } + + fun onDeepLink(request: DeepLinkRequest?) { + matchLink(request, closesApp = false) { _incomingDeepLink.value = it } + } + + /** + * 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() { + _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 4fa494c89..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 @@ -22,13 +22,16 @@ 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.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 import de.davis.keygo.app.presentation.navigation.resolveAppShell +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 @@ -38,10 +41,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 @@ -56,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.toDeepLinkRequest()) splashScreen.setKeepOnScreenCondition { viewModel.isReturningUser.value == null @@ -68,20 +68,36 @@ 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() + 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() CompositionLocalProvider( LocalSnackbarManager provides snackbarManager, ) { - App( - hasAccess = hasAccess, - launchRoute = launchRoute(hasAccess), + // Started only to take a link that cannot be read: no gate, just the report. + if (rejectedLink?.closesApp != true) App( + launchStack = launchStack, isSessionActive = isSessionActive, needsAttentionCount = needsAttentionCount, requestedTopLevelRoute = requestedTopLevelRoute, onTopLevelRouteRequestHandled = viewModel::onTopLevelRouteRequestHandled, + incomingDeepLink = incomingDeepLink, + onDeepLinkHandled = viewModel::onDeepLinkHandled, ) + + rejectedLink?.let { rejected -> + RejectedLinkDialog( + pending = rejected.pending, + onDismiss = { + if (rejected.closesApp) finish() + else viewModel.onRejectedLinkDismissed() + }, + ) + } } } } @@ -90,30 +106,23 @@ class MainActivity : FragmentActivity() { override fun onNewIntent(intent: Intent) { super.onNewIntent(intent) viewModel.onIntentAction(intent.action) + viewModel.onDeepLink(intent.toDeepLinkRequest()) } - - 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 } @OptIn(ExperimentalMaterial3AdaptiveApi::class) @Composable private fun App( - hasAccess: Boolean, - launchRoute: NavKey, + launchStack: List, isSessionActive: Boolean, needsAttentionCount: Int, requestedTopLevelRoute: NavKey?, onTopLevelRouteRequestHandled: () -> Unit, + incomingDeepLink: DeepLink?, + onDeepLinkHandled: () -> Unit, ) { val navigationState = rememberAppNavigationState( - launchRoute = launchRoute, + launchStack = launchStack, startRoute = RouteDestination.Home, topLevelRoutes = TopLevelRoutes, ) @@ -128,6 +137,12 @@ private fun App( onTopLevelRouteRequestHandled() } + LaunchedEffect(incomingDeepLink) { + if (incomingDeepLink == null) return@LaunchedEffect + navigator.openDeepLink(incomingDeepLink, isSessionActive) + onDeepLinkHandled() + } + val windowAdaptiveInfo = currentWindowAdaptiveInfoV2() val directive = remember(windowAdaptiveInfo) { calculatePaneScaffoldDirective(windowAdaptiveInfo) @@ -136,7 +151,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 +189,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 ccb7828fa..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 @@ -15,19 +15,21 @@ 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.feature.onboarding.presentation.OnboardingRoute 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 { @@ -38,7 +40,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) { @@ -53,8 +55,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. */ @@ -70,6 +72,24 @@ 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 + + /** + * 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) @@ -97,8 +117,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 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 { + 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 671d4e70d..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 @@ -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 @@ -18,27 +17,9 @@ 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 - * 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, is TotpImportRedirect -> true - else -> false - } - /** 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 { @@ -66,17 +47,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 @@ -85,9 +55,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) } @@ -98,13 +67,50 @@ 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()) } - /** 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 (!isGated) return + if (!state.isGated) return + state.overlayStack.removeLastOrNull() + } + + /** + * 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. + * + * 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 + if (state.isCovered) { + overlay.subList(0, overlay.lastIndex).clear() + overlay.add(0, link.destination) + return + } + + overlay.clear() + overlay.add(link.destination) + if (!isSessionActive) 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. + */ + fun finishFirstRun() { + if (state.overlayStack.lastOrNull() !is OnboardingRoute) return state.overlayStack.removeLastOrNull() } @@ -144,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/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..8efd076c6 --- /dev/null +++ b/app/src/main/kotlin/de/davis/keygo/app/presentation/navigation/DeepLinks.kt @@ -0,0 +1,41 @@ +package de.davis.keygo.app.presentation.navigation + +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 + +/** 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) + +/** + * 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) + +/** 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 + * 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, isSessionActive: Boolean): List { + if (link != null && isSessionActive) return listOf(link.destination) + + 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..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 @@ -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,31 @@ 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)) }, + // 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() }, ) assignTotpEntries( @@ -78,12 +61,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 +138,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/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/AppNavigatorTest.kt b/app/src/test/kotlin/de/davis/keygo/app/presentation/navigation/AppNavigatorTest.kt index f37c4fb88..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.feature.totp.presentation.TotpImportRedirect 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,210 @@ 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, isSessionActive = false), + ) + } - 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, isSessionActive = false), + ) + } - assertEquals(listOf(AuthRoute(uri = DEEP_LINK_URI)), navigator.shown) + @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 validated code sends an account without access to first run`() { - val navigator = navigator() + 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, 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 = linkLaunched(hasAccess = true) + + assertEquals(listOf(AuthRoute(pending = PendingLink.TotpImport)), navigator.displayed) + + navigator.unlock() + + assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.displayed) + } + + @Test + fun `back on a link's gate cannot reach the link`() { + val navigator = linkLaunched(hasAccess = true) + + 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 = linkLaunched(hasAccess = true) + + navigator.lock() + + assertEquals(2, navigator.shown.size) + } + + @Test + fun `finishing first run reveals the link that waited under it`() { + val navigator = linkLaunched(hasAccess = false) + + navigator.finishFirstRun() + + 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 = linkLaunched(hasAccess = false) + + 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 = linkLaunched(hasAccess = false) + + navigator.goBack() + + assertEquals( + listOf(SelectItemForTotpRoute(DEEP_LINK_URI), OnboardingRoute(pending = PendingLink.TotpImport)), + navigator.shown, + ) + } + + @Test + 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, isSessionActive = false) + + 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 earlier link's flow replaces it under a fresh gate`() { + val navigator = navigator( + OTHER_LINK_ROUTE, + 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(OTHER_LINK_ROUTE) - navigator.openGateFor(hasAccess = false, uri = DEEP_LINK_URI) + navigator.openDeepLink(TOTP_LINK, isSessionActive = true) - assertEquals(listOf(OnboardingRoute(uri = DEEP_LINK_URI)), navigator.shown) + assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.shown) } @Test - fun `the picker replaces the gate, so back leaves the app`() { + fun `a second link under the gate replaces the one already waiting`() { + val navigator = navigator( + OTHER_LINK_ROUTE, + AuthRoute(pending = PendingLink.TotpImport), + ) + + navigator.openDeepLink(TOTP_LINK, isSessionActive = false) + + assertEquals( + listOf(SelectItemForTotpRoute(DEEP_LINK_URI), AuthRoute(pending = PendingLink.TotpImport)), + navigator.shown, + ) + + navigator.unlock() + navigator.goBack() + + assertEquals(listOf(SelectItemForTotpRoute(DEEP_LINK_URI)), navigator.shown) + } + + @Test + fun `a link arriving while the gate is up slides in under it, without a second gate`() { val navigator = navigator() - navigator.replaceOverlay(SelectItemForTotpRoute(DEEP_LINK_URI)) + navigator.openDeepLink(TOTP_LINK, isSessionActive = false) + + 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, 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 = linkLaunched(hasAccess = true) + navigator.unlock() + + 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 +275,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 +512,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 +535,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 +557,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 +567,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 +671,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 +710,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( @@ -622,8 +765,52 @@ 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(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(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() } + /** 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, @@ -634,6 +821,11 @@ 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) + + /** An earlier link's destination, which a newer one replaces. */ + val OTHER_LINK_ROUTE = SelectItemForTotpRoute("otpauth://totp/Other?secret=ABC") } } 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/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/AuthContent.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthContent.kt index fa90e36e6..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,5 +1,6 @@ package de.davis.keygo.feature.auth.presentation +import androidx.annotation.StringRes import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -56,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 @@ -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/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/AuthScreen.kt b/feature/auth/src/main/kotlin/de/davis/keygo/feature/auth/presentation/AuthScreen.kt index c69db890e..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, - hasPendingTotpImport = viewModel.hasPendingTotpImport, + 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 3d0dc5561..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 @@ -45,8 +45,6 @@ internal class AuthViewModel( private val unlockWithPassword: UnlockWithPasswordUseCase, private val createAllAccesses: CreateAccessUseCase, ) : ViewModel() { - val hasPendingTotpImport: Boolean = authRoute.uri != null - private val passwordTextFieldState = TextFieldState() private val _uiState = MutableStateFlow(AuthState.Loading) 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/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..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 @@ -2,17 +2,18 @@ package de.davis.keygo.feature.onboarding.presentation 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( 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..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,8 +51,6 @@ internal class OnboardingViewModel( private val createAccess: CreateAccessUseCase, ) : ViewModel() { - private val hasPendingTotpImport = onboardingRoute.uri != null - private val stepsToSkip = MutableStateFlow>(emptySet()) private fun calculateStepsToSkip() { @@ -150,7 +148,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..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 @@ -15,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 @@ -24,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( @@ -35,14 +37,20 @@ 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(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/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 152d0c95d..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 @@ -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(pendingLink = PendingLink.TotpImport), vm.state.value) + } + + @Test + fun `a plain first run welcomes without an import`() = runTest(dispatcher) { + assertEquals(OnboardingUiState.Welcome(pendingLink = null), 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/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() +} 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..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,26 +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. + * Matches the `otpauth://totp` links the app registers an intent filter for, straight to the + * 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 @@ -33,10 +33,22 @@ 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 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 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/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/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 55% 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 8e02c3657..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,37 +1,45 @@ -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.TotpImportRedirect +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 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 { +class TotpImportDeepLinkMatcherTest { - private fun match(uri: String): TotpImportRedirect? = - TotpImportDeepLinkMatcher.match(DeepLinkRequest(uri.toUri()))?.key + private val totpService = FakeTotpService() + private val matcher = TotpImportDeepLinkMatcher(IsReadableTotpUriUseCase(totpService)) + + private fun match(uri: String): SelectItemForTotpRoute? = + matcher.match(DeepLinkRequest(uri.toUri()))?.key as SelectItemForTotpRoute? @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 +50,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 +61,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 +76,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 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 carries nothing to import`() { + 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")) - 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, to be rejected`() { 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 @@ -98,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) @@ -107,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, + ) } } 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" - } -}