From b81df6d52b3998a4ebdfd903fb8888f0e7eba10d Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 12:24:07 +0100 Subject: [PATCH 01/12] feat(rust/invite): add qr code to cli --- rust/Cargo.lock | 50 +++++++++++++++++++ rust/crates/keygo-server/Cargo.toml | 1 + .../src/cli/commands/invite/create.rs | 37 ++++++++++++++ 3 files changed, 88 insertions(+) diff --git a/rust/Cargo.lock b/rust/Cargo.lock index 3265e9bbd..df0df6209 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -406,12 +406,24 @@ version = "3.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + [[package]] name = "byteorder" version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + [[package]] name = "bytes" version = "1.12.1" @@ -1530,6 +1542,18 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -1731,6 +1755,7 @@ dependencies = [ "keygo-dpop", "keygo-opaque", "moka", + "qrcode", "secrecy", "serde", "serde_json", @@ -1913,6 +1938,16 @@ dependencies = [ "uuid", ] +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "nom" version = "7.1.3" @@ -2259,6 +2294,21 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51315bca45305dd8aa64b831b33e71abac528ca8058c0651346a39b8d3009498" +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "qrcode" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ace1a365f55004297f2cf24acfd96d02966246ca423385273b58a7dc873ee14d" +dependencies = [ + "image", +] + [[package]] name = "quote" version = "1.0.47" diff --git a/rust/crates/keygo-server/Cargo.toml b/rust/crates/keygo-server/Cargo.toml index 8cd3a07b1..d994e718c 100644 --- a/rust/crates/keygo-server/Cargo.toml +++ b/rust/crates/keygo-server/Cargo.toml @@ -43,6 +43,7 @@ humantime = "2.4.0" time = { version = "0.3.55", features = ["formatting", "macros"] } moka = { version = "0.12.16", features = ["sync"] } ed25519-dalek = "3.0.0" +qrcode = "0.15.0" [dev-dependencies] keygo-dpop = { path = "../keygo-dpop", features = ["test-support"] } diff --git a/rust/crates/keygo-server/src/cli/commands/invite/create.rs b/rust/crates/keygo-server/src/cli/commands/invite/create.rs index f71fafdf7..b9ee5ae1c 100644 --- a/rust/crates/keygo-server/src/cli/commands/invite/create.rs +++ b/rust/crates/keygo-server/src/cli/commands/invite/create.rs @@ -1,8 +1,12 @@ use super::{Connection, format_utc, with_db}; +use crate::domain::InviteCode; use crate::service::invite::{self, Created}; use anyhow::ensure; use clap::Args; +use qrcode::QrCode; +use qrcode::render::unicode::Dense1x2; use std::time::Duration; +use url::Url; const MIN_TTL: Duration = Duration::from_hours(24); const MAX_TTL: Duration = Duration::from_hours(30 * 24); @@ -12,6 +16,9 @@ pub struct CreateInviteArgs { /// How long the invite stays redeemable, from 1 to 30 days, e.g. "72h" or "2weeks". #[arg(short, long, default_value = "1d", value_parser = parse_ttl)] ttl: Duration, + /// URL that clients reach the server at, encoded into the invite's QR code. + #[arg(long, env = "KEYGO_PUBLIC_URL", default_value = "http://localhost")] + public_url: String, #[command(flatten)] connection: Connection, } @@ -39,6 +46,10 @@ pub fn run(args: &CreateInviteArgs) -> anyhow::Result<()> { })?; println!("{}", summary(&created)); + println!( + "{}", + qr_code(&invite_link(&args.public_url, &created.code))? + ); Ok(()) } @@ -51,6 +62,22 @@ fn summary(created: &Created) -> String { ) } +fn invite_link(public_url: &str, code: &InviteCode) -> Url { + Url::parse_with_params( + "keygo://invite", + [("s", public_url), ("c", &code.to_string())], + ) + .expect("keygo://invite is a valid base URL") +} + +fn qr_code(link: &Url) -> anyhow::Result { + Ok(QrCode::new(link.as_str())? + .render::() + .dark_color(Dense1x2::Dark) + .light_color(Dense1x2::Light) + .build()) +} + #[cfg(test)] mod tests { use super::*; @@ -91,4 +118,14 @@ mod tests { "Invite 7KQ2-M9XD-4HPA expires 2026-10-18 08:30 UTC id a3a3a" ); } + + #[test] + fn invite_link_encodes_server_and_code() { + let code = "7KQ2M9XD4HPA".parse().unwrap(); + + assert_eq!( + invite_link("https://keygo.example.com/sync?x=1&y=2", &code).as_str(), + "keygo://invite?s=https%3A%2F%2Fkeygo.example.com%2Fsync%3Fx%3D1%26y%3D2&c=7KQ2-M9XD-4HPA", + ); + } } From 6795a5f803b5d161e2879ccd1823edc726fb313b Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 16:58:41 +0100 Subject: [PATCH 02/12] feat(core-scanner): add dedicated qr code scanner module --- core/qr-scanner/build.gradle.kts | 10 ++++++++++ core/qr-scanner/consumer-rules.pro | 0 .../keygo/core/qr_scanner/di/CoreQrScannerModule.kt | 10 ++++++++++ settings.gradle.kts | 1 + 4 files changed, 21 insertions(+) create mode 100644 core/qr-scanner/build.gradle.kts create mode 100644 core/qr-scanner/consumer-rules.pro create mode 100644 core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/di/CoreQrScannerModule.kt diff --git a/core/qr-scanner/build.gradle.kts b/core/qr-scanner/build.gradle.kts new file mode 100644 index 000000000..c140e305d --- /dev/null +++ b/core/qr-scanner/build.gradle.kts @@ -0,0 +1,10 @@ +plugins { + alias(libs.plugins.keygo.android.compose) +} + +android { + namespace = "de.davis.keygo.core.qr_scanner" +} + +dependencies { +} diff --git a/core/qr-scanner/consumer-rules.pro b/core/qr-scanner/consumer-rules.pro new file mode 100644 index 000000000..e69de29bb diff --git a/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/di/CoreQrScannerModule.kt b/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/di/CoreQrScannerModule.kt new file mode 100644 index 000000000..9efefb3bf --- /dev/null +++ b/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/di/CoreQrScannerModule.kt @@ -0,0 +1,10 @@ +package de.davis.keygo.core.qr_scanner.di + +import org.koin.core.annotation.ComponentScan +import org.koin.core.annotation.Configuration +import org.koin.core.annotation.Module + +@Module +@Configuration +@ComponentScan("de.davis.keygo.core.qr_scanner") +object CoreQrScannerModule diff --git a/settings.gradle.kts b/settings.gradle.kts index 9d3eed612..9dbe93e16 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -38,6 +38,7 @@ include(":core:biometrics") include(":core:ui") include(":core:rust") include(":core:sync") +include(":core:qr-scanner") include(":feature:credentials") include(":feature:list_screen") include(":feature:item:core") From c329fdc91d9e74cd7a732905664cc15c85816671 Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 17:24:06 +0100 Subject: [PATCH 03/12] refactor(core-scanner): move totp qr code scanner --- app/build.gradle.kts | 1 + core/qr-scanner/build.gradle.kts | 21 +++++++++++++++++++ core/qr-scanner/consumer-rules.pro | 2 ++ .../qr_scanner}/data/qr/FdroidQRScanner.kt | 6 +++--- .../qr-scanner}/src/main/AndroidManifest.xml | 0 .../qr_scanner}/domain/model/camera/Frame.kt | 2 +- .../core/qr_scanner/domain/qr/QRScanner.kt | 10 +++++++++ .../qr_scanner/presentation}/QRScanner.kt | 10 ++++----- .../src/main/res/values-de/strings.xml | 13 ++++++++++++ .../src/main/res/values/strings.xml | 13 ++++++++++++ .../src/playStore/AndroidManifest.xml | 0 .../core/qr_scanner}/data/qr/GmsQRScanner.kt | 6 +++--- feature/item/create/build.gradle.kts | 1 + .../create/presentation/login/LoginContent.kt | 2 +- feature/item/view/build.gradle.kts | 1 + .../item/view/login/ViewLoginContent.kt | 3 +-- feature/totp/build.gradle.kts | 20 ------------------ feature/totp/consumer-rules.pro | 2 -- .../keygo/feature/totp/domain/qr/QRScanner.kt | 10 --------- .../totp/src/main/res/values-de/strings.xml | 11 +--------- feature/totp/src/main/res/values/strings.xml | 9 -------- 21 files changed, 76 insertions(+), 67 deletions(-) rename {feature/totp/src/fdroid/kotlin/de/davis/keygo/feature/totp => core/qr-scanner/src/fdroid/kotlin/de/davis/keygo/core/qr_scanner}/data/qr/FdroidQRScanner.kt (87%) rename {feature/totp => core/qr-scanner}/src/main/AndroidManifest.xml (100%) rename {feature/totp/src/main/kotlin/de/davis/keygo/feature/totp => core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner}/domain/model/camera/Frame.kt (92%) create mode 100644 core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/domain/qr/QRScanner.kt rename {feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/component => core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/presentation}/QRScanner.kt (96%) create mode 100644 core/qr-scanner/src/main/res/values-de/strings.xml create mode 100644 core/qr-scanner/src/main/res/values/strings.xml rename {feature/totp => core/qr-scanner}/src/playStore/AndroidManifest.xml (100%) rename {feature/totp/src/playStore/kotlin/de/davis/keygo/feature/totp => core/qr-scanner/src/playStore/kotlin/de/davis/keygo/core/qr_scanner}/data/qr/GmsQRScanner.kt (89%) delete mode 100644 feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/domain/qr/QRScanner.kt diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 8c176e6f0..e94e145e2 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -133,6 +133,7 @@ dependencies { implementation(projects.core.identity) implementation(projects.core.ui) implementation(projects.core.sync) + implementation(projects.core.qrScanner) implementation(projects.feature.auth) implementation(projects.feature.listScreen) implementation(projects.feature.credentials) diff --git a/core/qr-scanner/build.gradle.kts b/core/qr-scanner/build.gradle.kts index c140e305d..aa1f79fa9 100644 --- a/core/qr-scanner/build.gradle.kts +++ b/core/qr-scanner/build.gradle.kts @@ -4,7 +4,28 @@ plugins { android { namespace = "de.davis.keygo.core.qr_scanner" + + flavorDimensions += listOf("store") + productFlavors { + create("playStore") { + dimension = "store" + } + + create("fdroid") { + dimension = "store" + } + } } dependencies { + implementation(libs.com.google.accompanist.permissions) + + implementation(libs.androidx.camera.camera2) + implementation(libs.androidx.camera.compose) + implementation(libs.androidx.camera.lifecycle) + + "playStoreImplementation"(libs.gms.mlkit.barcode.scanning) + "fdroidImplementation"(libs.zxing.barcode.scanning) + + implementation(projects.core.security) } diff --git a/core/qr-scanner/consumer-rules.pro b/core/qr-scanner/consumer-rules.pro index e69de29bb..d8efd7c81 100644 --- a/core/qr-scanner/consumer-rules.pro +++ b/core/qr-scanner/consumer-rules.pro @@ -0,0 +1,2 @@ +-keep class com.google.mlkit.** { *; } +-keep class com.google.android.gms.internal.mlkit.** { *; } \ No newline at end of file diff --git a/feature/totp/src/fdroid/kotlin/de/davis/keygo/feature/totp/data/qr/FdroidQRScanner.kt b/core/qr-scanner/src/fdroid/kotlin/de/davis/keygo/core/qr_scanner/data/qr/FdroidQRScanner.kt similarity index 87% rename from feature/totp/src/fdroid/kotlin/de/davis/keygo/feature/totp/data/qr/FdroidQRScanner.kt rename to core/qr-scanner/src/fdroid/kotlin/de/davis/keygo/core/qr_scanner/data/qr/FdroidQRScanner.kt index 65edfdd47..579275b6f 100644 --- a/feature/totp/src/fdroid/kotlin/de/davis/keygo/feature/totp/data/qr/FdroidQRScanner.kt +++ b/core/qr-scanner/src/fdroid/kotlin/de/davis/keygo/core/qr_scanner/data/qr/FdroidQRScanner.kt @@ -1,4 +1,4 @@ -package de.davis.keygo.feature.totp.data.qr +package de.davis.keygo.core.qr_scanner.data.qr import com.google.zxing.BarcodeFormat import com.google.zxing.BinaryBitmap @@ -6,8 +6,8 @@ import com.google.zxing.DecodeHintType import com.google.zxing.MultiFormatReader import com.google.zxing.PlanarYUVLuminanceSource import com.google.zxing.common.HybridBinarizer -import de.davis.keygo.feature.totp.domain.model.camera.Frame -import de.davis.keygo.feature.totp.domain.qr.QRScanner +import de.davis.keygo.core.qr_scanner.domain.model.camera.Frame +import de.davis.keygo.core.qr_scanner.domain.qr.QRScanner import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import org.koin.core.annotation.Single diff --git a/feature/totp/src/main/AndroidManifest.xml b/core/qr-scanner/src/main/AndroidManifest.xml similarity index 100% rename from feature/totp/src/main/AndroidManifest.xml rename to core/qr-scanner/src/main/AndroidManifest.xml diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/domain/model/camera/Frame.kt b/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/domain/model/camera/Frame.kt similarity index 92% rename from feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/domain/model/camera/Frame.kt rename to core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/domain/model/camera/Frame.kt index c8249d4f8..ee257cd52 100644 --- a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/domain/model/camera/Frame.kt +++ b/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/domain/model/camera/Frame.kt @@ -1,4 +1,4 @@ -package de.davis.keygo.feature.totp.domain.model.camera +package de.davis.keygo.core.qr_scanner.domain.model.camera data class Frame( val dataNv21: ByteArray, diff --git a/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/domain/qr/QRScanner.kt b/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/domain/qr/QRScanner.kt new file mode 100644 index 000000000..d3c9d73f0 --- /dev/null +++ b/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/domain/qr/QRScanner.kt @@ -0,0 +1,10 @@ +package de.davis.keygo.core.qr_scanner.domain.qr + +import de.davis.keygo.core.qr_scanner.domain.model.camera.Frame + +interface QRScanner { + + suspend fun scan(frame: Frame): List + + fun close() +} \ No newline at end of file diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/component/QRScanner.kt b/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/presentation/QRScanner.kt similarity index 96% rename from feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/component/QRScanner.kt rename to core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/presentation/QRScanner.kt index c3cb88c29..8c97f2066 100644 --- a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/presentation/component/QRScanner.kt +++ b/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/presentation/QRScanner.kt @@ -1,4 +1,4 @@ -package de.davis.keygo.feature.totp.presentation.component +package de.davis.keygo.core.qr_scanner.presentation import android.Manifest import android.content.Intent @@ -21,7 +21,6 @@ import androidx.compose.material.icons.filled.Camera import androidx.compose.material.icons.filled.Close import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button -import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedButton @@ -46,11 +45,11 @@ import com.google.accompanist.permissions.ExperimentalPermissionsApi import com.google.accompanist.permissions.isGranted import com.google.accompanist.permissions.rememberPermissionState import com.google.accompanist.permissions.shouldShowRationale +import de.davis.keygo.core.qr_scanner.R +import de.davis.keygo.core.qr_scanner.domain.model.camera.Frame +import de.davis.keygo.core.qr_scanner.domain.qr.QRScanner import de.davis.keygo.core.security.presentation.rememberHandoffStarter import de.davis.keygo.core.util.onFailure -import de.davis.keygo.feature.totp.R -import de.davis.keygo.feature.totp.domain.model.camera.Frame -import de.davis.keygo.feature.totp.domain.qr.QRScanner import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.asExecutor import kotlinx.coroutines.launch @@ -194,7 +193,6 @@ private fun PermissionDeniedDialog( ) } -@OptIn(ExperimentalMaterial3Api::class) @Composable private fun ScannerContent( onClose: () -> Unit, diff --git a/core/qr-scanner/src/main/res/values-de/strings.xml b/core/qr-scanner/src/main/res/values-de/strings.xml new file mode 100644 index 000000000..8353b7b2c --- /dev/null +++ b/core/qr-scanner/src/main/res/values-de/strings.xml @@ -0,0 +1,13 @@ + + + QR-Code scannen + + Um QR-Codes zu scannen, braucht KeyGo Zugriff auf deine Kamera. + Erlauben + Abbrechen + + Kamerazugriff + Der Kamerazugriff wurde verweigert. Um QR-Codes zu scannen, erlaube ihn in den App-Einstellungen. + Einstellungen öffnen + OK + \ No newline at end of file diff --git a/core/qr-scanner/src/main/res/values/strings.xml b/core/qr-scanner/src/main/res/values/strings.xml new file mode 100644 index 000000000..e7c11a2be --- /dev/null +++ b/core/qr-scanner/src/main/res/values/strings.xml @@ -0,0 +1,13 @@ + + + Scan QR Code + + Camera access is required to scan QR codes. + Grant + Cancel + + Camera permission + Camera permission was denied. To scan QR codes, please enable it in your app settings. + Open Settings + OK + \ No newline at end of file diff --git a/feature/totp/src/playStore/AndroidManifest.xml b/core/qr-scanner/src/playStore/AndroidManifest.xml similarity index 100% rename from feature/totp/src/playStore/AndroidManifest.xml rename to core/qr-scanner/src/playStore/AndroidManifest.xml diff --git a/feature/totp/src/playStore/kotlin/de/davis/keygo/feature/totp/data/qr/GmsQRScanner.kt b/core/qr-scanner/src/playStore/kotlin/de/davis/keygo/core/qr_scanner/data/qr/GmsQRScanner.kt similarity index 89% rename from feature/totp/src/playStore/kotlin/de/davis/keygo/feature/totp/data/qr/GmsQRScanner.kt rename to core/qr-scanner/src/playStore/kotlin/de/davis/keygo/core/qr_scanner/data/qr/GmsQRScanner.kt index 91ad9af02..79598e9e9 100644 --- a/feature/totp/src/playStore/kotlin/de/davis/keygo/feature/totp/data/qr/GmsQRScanner.kt +++ b/core/qr-scanner/src/playStore/kotlin/de/davis/keygo/core/qr_scanner/data/qr/GmsQRScanner.kt @@ -1,11 +1,11 @@ -package de.davis.keygo.feature.totp.data.qr +package de.davis.keygo.core.qr_scanner.data.qr import com.google.mlkit.vision.barcode.BarcodeScannerOptions import com.google.mlkit.vision.barcode.BarcodeScanning import com.google.mlkit.vision.barcode.common.Barcode import com.google.mlkit.vision.common.InputImage -import de.davis.keygo.feature.totp.domain.model.camera.Frame -import de.davis.keygo.feature.totp.domain.qr.QRScanner +import de.davis.keygo.core.qr_scanner.domain.model.camera.Frame +import de.davis.keygo.core.qr_scanner.domain.qr.QRScanner import kotlinx.coroutines.suspendCancellableCoroutine import org.koin.core.annotation.Factory import kotlin.coroutines.resume diff --git a/feature/item/create/build.gradle.kts b/feature/item/create/build.gradle.kts index 68df073a3..aa128fcd5 100644 --- a/feature/item/create/build.gradle.kts +++ b/feature/item/create/build.gradle.kts @@ -15,6 +15,7 @@ dependencies { implementation(projects.core.ui) implementation(projects.core.item) implementation(projects.core.security) + implementation(projects.core.qrScanner) implementation(projects.feature.item.core) implementation(projects.feature.listScreen) implementation(projects.feature.totp) diff --git a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginContent.kt b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginContent.kt index 3c04eb60a..23613f5c0 100644 --- a/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginContent.kt +++ b/feature/item/create/src/main/kotlin/de/davis/keygo/feature/item/create/presentation/login/LoginContent.kt @@ -43,6 +43,7 @@ import de.davis.keygo.core.item.domain.model.Vault import de.davis.keygo.core.item.domain.model.VaultMetadata import de.davis.keygo.core.item.generated.domain.model.VaultItemType import de.davis.keygo.core.item.presentation.StrengthIndicator +import de.davis.keygo.core.qr_scanner.presentation.QRScanner import de.davis.keygo.core.ui.text.transformation.rememberSchemeStrippingTransformation import de.davis.keygo.core.ui.theme.KeyGoTheme import de.davis.keygo.core.ui.theme.secretTextStyle @@ -68,7 +69,6 @@ import de.davis.keygo.feature.item.create.presentation.model.ItemUiState import de.davis.keygo.feature.item.create.presentation.model.SharedItemState import de.davis.keygo.feature.item.create.presentation.model.VaultsState import de.davis.keygo.feature.item.create.presentation.password.GeneratePasswordModalBottomSheet -import de.davis.keygo.feature.totp.presentation.component.QRScanner import de.davis.keygo.feature.totp.presentation.component.TotpParseErrorDialog import de.davis.keygo.core.item.R as CoreItemR import de.davis.keygo.feature.item.core.R as ItemCoreR diff --git a/feature/item/view/build.gradle.kts b/feature/item/view/build.gradle.kts index 96f685495..7cabb18a3 100644 --- a/feature/item/view/build.gradle.kts +++ b/feature/item/view/build.gradle.kts @@ -14,6 +14,7 @@ dependencies { implementation(projects.core.ui) implementation(projects.core.item) implementation(projects.core.security) + implementation(projects.core.qrScanner) implementation(projects.feature.item.core) implementation(projects.feature.totp) diff --git a/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/ViewLoginContent.kt b/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/ViewLoginContent.kt index e84076504..4551d0ef9 100644 --- a/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/ViewLoginContent.kt +++ b/feature/item/view/src/main/kotlin/de/davis/keygo/feature/item/view/login/ViewLoginContent.kt @@ -75,6 +75,7 @@ import androidx.compose.ui.unit.dp import de.davis.keygo.core.item.domain.model.PasswordScore import de.davis.keygo.core.item.presentation.StrengthIndicator import de.davis.keygo.core.item.presentation.toImageVector +import de.davis.keygo.core.qr_scanner.presentation.QRScanner import de.davis.keygo.core.ui.components.VisibilityButton import de.davis.keygo.core.ui.composition.LocalIsInSinglePaneMode import de.davis.keygo.core.ui.text.transformation.rememberSchemeStrippingTransformation @@ -94,7 +95,6 @@ import de.davis.keygo.feature.item.view.login.model.TotpState import de.davis.keygo.feature.item.view.login.model.ViewLoginState import de.davis.keygo.feature.item.view.login.model.ViewLoginUiEvent import de.davis.keygo.feature.totp.domain.model.TotpValue -import de.davis.keygo.feature.totp.presentation.component.QRScanner import de.davis.keygo.feature.totp.presentation.component.TotpParseErrorDialog import kotlin.math.ceil import kotlin.time.Duration.Companion.milliseconds @@ -102,7 +102,6 @@ import de.davis.keygo.core.item.R as CoreItemR import de.davis.keygo.core.ui.R as CoreUiR import de.davis.keygo.feature.item.core.R as ItemCoreR -@OptIn(ExperimentalMaterial3ExpressiveApi::class, ExperimentalMaterial3Api::class) @Composable fun ViewLoginContent(state: ViewLoginState, onEvent: (ViewLoginUiEvent) -> Unit) { val scrollBehavior = TopAppBarDefaults.enterAlwaysScrollBehavior() diff --git a/feature/totp/build.gradle.kts b/feature/totp/build.gradle.kts index c7b7aeeeb..9e36830c7 100644 --- a/feature/totp/build.gradle.kts +++ b/feature/totp/build.gradle.kts @@ -5,22 +5,9 @@ plugins { android { namespace = "de.davis.keygo.feature.totp" - - flavorDimensions += listOf("store") - productFlavors { - create("playStore") { - dimension = "store" - } - - create("fdroid") { - dimension = "store" - } - } } dependencies { - implementation(libs.com.google.accompanist.permissions) - implementation(projects.core.rust) implementation(projects.core.ui) implementation(projects.core.security) @@ -28,13 +15,6 @@ dependencies { implementation(projects.core.util) implementation(projects.feature.listScreen) - implementation(libs.androidx.camera.camera2) - implementation(libs.androidx.camera.compose) - implementation(libs.androidx.camera.lifecycle) - - "playStoreImplementation"(libs.gms.mlkit.barcode.scanning) - "fdroidImplementation"(libs.zxing.barcode.scanning) - testImplementation(testFixtures(projects.core.security)) testImplementation(testFixtures(projects.core.item)) testImplementation(testFixtures(projects.core.util)) diff --git a/feature/totp/consumer-rules.pro b/feature/totp/consumer-rules.pro index d8efd7c81..e69de29bb 100644 --- a/feature/totp/consumer-rules.pro +++ b/feature/totp/consumer-rules.pro @@ -1,2 +0,0 @@ --keep class com.google.mlkit.** { *; } --keep class com.google.android.gms.internal.mlkit.** { *; } \ No newline at end of file diff --git a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/domain/qr/QRScanner.kt b/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/domain/qr/QRScanner.kt deleted file mode 100644 index 2f6bfd117..000000000 --- a/feature/totp/src/main/kotlin/de/davis/keygo/feature/totp/domain/qr/QRScanner.kt +++ /dev/null @@ -1,10 +0,0 @@ -package de.davis.keygo.feature.totp.domain.qr - -import de.davis.keygo.feature.totp.domain.model.camera.Frame - -interface QRScanner { - - suspend fun scan(frame: Frame): List - - fun close() -} \ No newline at end of file diff --git a/feature/totp/src/main/res/values-de/strings.xml b/feature/totp/src/main/res/values-de/strings.xml index b7e06c768..ad9332bfa 100644 --- a/feature/totp/src/main/res/values-de/strings.xml +++ b/feature/totp/src/main/res/values-de/strings.xml @@ -1,16 +1,7 @@ - QR-Code scannen - - Um QR-Codes für die TOTP-Einrichtung zu scannen, braucht KeyGo Zugriff auf deine Kamera. - Erlauben - Abbrechen - - Kamerazugriff - Der Kamerazugriff wurde verweigert. Um QR-Codes zu scannen, erlaube ihn in den App-Einstellungen. - Einstellungen öffnen OK - + Ungültiger TOTP-Code Der TOTP-Code konnte nicht gelesen werden. diff --git a/feature/totp/src/main/res/values/strings.xml b/feature/totp/src/main/res/values/strings.xml index 57cb6710d..4c1a1b8db 100644 --- a/feature/totp/src/main/res/values/strings.xml +++ b/feature/totp/src/main/res/values/strings.xml @@ -1,14 +1,5 @@ - Scan QR Code - - Camera access is required to scan TOTP-setup QR codes. - Grant - Cancel - - Camera permission - Camera permission was denied. To scan QR codes, please enable it in your app settings. - Open Settings OK TOTP Parse Error From c06cc7646d098d59284bb24951c07b0cc807b25e Mon Sep 17 00:00:00 2001 From: Davis Date: Tue, 1 Dec 2026 17:47:44 +0100 Subject: [PATCH 04/12] feat(feature-account): wire up code scanner button --- .../de/davis/keygo/core/util/Combine.kt | 35 ++++++++++--------- feature/account/build.gradle.kts | 5 +++ .../presentation/setup/ConnectServerScreen.kt | 9 +++-- .../setup/ConnectServerViewModel.kt | 9 ++++- .../setup/model/ConnectServerEvent.kt | 1 - .../setup/model/ConnectServerUiEvent.kt | 3 ++ .../setup/model/ConnectServerUiState.kt | 1 + 7 files changed, 43 insertions(+), 20 deletions(-) diff --git a/core/util/src/main/kotlin/de/davis/keygo/core/util/Combine.kt b/core/util/src/main/kotlin/de/davis/keygo/core/util/Combine.kt index 11719a0f3..ba6d78c43 100644 --- a/core/util/src/main/kotlin/de/davis/keygo/core/util/Combine.kt +++ b/core/util/src/main/kotlin/de/davis/keygo/core/util/Combine.kt @@ -69,7 +69,7 @@ fun combine( ) } -fun combine( +fun combine( flow1: Flow, flow2: Flow, flow3: Flow, @@ -79,18 +79,21 @@ fun combine( flow7: Flow, flow8: Flow, flow9: Flow, - transform: (T1, T2, T3, T4, T5, T6, T7, T8, T9) -> R, -): Flow = combineArray(flow1, flow2, flow3, flow4, flow5, flow6, flow7, flow8, flow9) { values -> - @Suppress("UNCHECKED_CAST") - transform( - values[0] as T1, - values[1] as T2, - values[2] as T3, - values[3] as T4, - values[4] as T5, - values[5] as T6, - values[6] as T7, - values[7] as T8, - values[8] as T9, - ) -} + flow10: Flow, + transform: (T1, T2, T3, T4, T5, T6, T7, T8, T9, T10) -> R, +): Flow = + combineArray(flow1, flow2, flow3, flow4, flow5, flow6, flow7, flow8, flow9, flow10) { values -> + @Suppress("UNCHECKED_CAST") + transform( + values[0] as T1, + values[1] as T2, + values[2] as T3, + values[3] as T4, + values[4] as T5, + values[5] as T6, + values[6] as T7, + values[7] as T8, + values[8] as T9, + values[9] as T10, + ) + } diff --git a/feature/account/build.gradle.kts b/feature/account/build.gradle.kts index c37f02ba2..fb9aafa70 100644 --- a/feature/account/build.gradle.kts +++ b/feature/account/build.gradle.kts @@ -5,6 +5,10 @@ plugins { android { namespace = "de.davis.keygo.feature.account" + + defaultConfig { + missingDimensionStrategy("store", "playStore") + } } dependencies { @@ -13,6 +17,7 @@ dependencies { implementation(projects.core.identity) implementation(projects.core.item) implementation(projects.core.sync) + implementation(projects.core.qrScanner) testImplementation(testFixtures(projects.core.biometrics)) testImplementation(testFixtures(projects.core.identity)) diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerScreen.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerScreen.kt index 545eed5da..80f6dbaf7 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerScreen.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerScreen.kt @@ -3,8 +3,10 @@ package de.davis.keygo.feature.account.presentation.setup import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.davis.keygo.core.qr_scanner.presentation.QRScanner import de.davis.keygo.core.util.presentation.ObserveAsEvents import de.davis.keygo.feature.account.presentation.setup.model.ConnectServerEvent +import de.davis.keygo.feature.account.presentation.setup.model.ConnectServerUiEvent import de.davis.keygo.feature.account.presentation.setup.transformation.rememberUsernameInputTransformation import org.koin.androidx.compose.koinViewModel @@ -17,8 +19,6 @@ internal fun ConnectServerScreen(navigateUp: () -> Unit) { when (it) { ConnectServerEvent.AccountCreated, ConnectServerEvent.SignedIn -> navigateUp() - - ConnectServerEvent.OpenInviteScanner -> Unit // TODO } } @@ -30,4 +30,9 @@ internal fun ConnectServerScreen(navigateUp: () -> Unit) { onEvent = viewModel::onEvent, navigateUp = navigateUp, ) + + if (state.scanInvite) QRScanner( + onClose = { viewModel.onEvent(ConnectServerUiEvent.AbortScan) }, + success = { viewModel.onEvent(ConnectServerUiEvent.CodesScanned(it)) }, + ) } diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModel.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModel.kt index bd6d0acbf..e9cc51e7e 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModel.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModel.kt @@ -129,6 +129,7 @@ internal class ConnectServerViewModel( // --- Rejected by the server on register --- private val _rejection = MutableStateFlow(null) private val _inviteRequiredBy = MutableStateFlow(null) + private val _scanInvite = MutableStateFlow(false) private fun fields() = Fields( address = addressTextFieldState.text.toString(), @@ -151,6 +152,7 @@ internal class ConnectServerViewModel( _fields, _rejection, _inviteRequiredBy, + _scanInvite, ::uiState, ).stateIn( scope = viewModelScope, @@ -165,6 +167,7 @@ internal class ConnectServerViewModel( fields = fields(), rejection = null, inviteRequiredBy = null, + scanInvite = false, ), ) @@ -178,6 +181,7 @@ internal class ConnectServerViewModel( fields: Fields, rejection: Rejection?, inviteRequiredBy: String?, + scanInvite: Boolean, ) = ConnectServerUiState( enterDomainState = EnterDomainState( addressTextFieldState = addressTextFieldState, @@ -221,6 +225,7 @@ internal class ConnectServerViewModel( rejection, inviteRequiredBy, ), + scanInvite = scanInvite, ) private fun canContinue( @@ -303,7 +308,9 @@ internal class ConnectServerViewModel( is ConnectServerUiEvent.SchemeChanged -> _detectedScheme.update { event.scheme } - ConnectServerUiEvent.ScanInvite -> _event.trySend(ConnectServerEvent.OpenInviteScanner) + ConnectServerUiEvent.ScanInvite -> _scanInvite.update { true } + ConnectServerUiEvent.AbortScan -> _scanInvite.update { false } + is ConnectServerUiEvent.CodesScanned -> {} } } diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerEvent.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerEvent.kt index b9c7d057c..1fca88105 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerEvent.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerEvent.kt @@ -1,7 +1,6 @@ package de.davis.keygo.feature.account.presentation.setup.model internal sealed interface ConnectServerEvent { - data object OpenInviteScanner : ConnectServerEvent data object AccountCreated : ConnectServerEvent data object SignedIn : ConnectServerEvent } diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiEvent.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiEvent.kt index b31d651d1..4852a653b 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiEvent.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiEvent.kt @@ -7,5 +7,8 @@ internal sealed interface ConnectServerUiEvent { data class ChooseAccount(val choice: AccountChoice) : ConnectServerUiEvent data class SchemeChanged(val scheme: String?) : ConnectServerUiEvent data object ScanInvite : ConnectServerUiEvent + data object AbortScan : ConnectServerUiEvent + data class CodesScanned(val codes: List) : ConnectServerUiEvent + data object UseAnotherServer : ConnectServerUiEvent } diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt index 4221a60f9..81b1cbe8f 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt @@ -14,6 +14,7 @@ internal data class ConnectServerUiState( val step: ConnectServerStep = ConnectServerStep.EnterDomain, val steps: List = stepsFor(choice = null), val canContinue: Boolean = false, + val scanInvite: Boolean = false, ) @Stable From 543d5717e5c5f2603a2807ba60d367cdedb93888 Mon Sep 17 00:00:00 2001 From: Davis Date: Wed, 2 Dec 2026 11:31:36 +0100 Subject: [PATCH 05/12] feat(rust): add invite link parser --- .../de/davis/keygo/rust/di/RustModule.kt | 5 + .../de/davis/keygo/rust/invite/InviteLink.kt | 28 +++ .../keygo/rust/invite/ParseWithResultTest.kt | 35 ++++ .../davis/keygo/rust/FakeInviteLinkParser.kt | 16 ++ rust/Cargo.lock | 1 + rust/crates/keygo-api/Cargo.toml | 1 + .../src/domain/invite_code.rs | 74 +++---- .../keygo-api/src/domain/invite_link.rs | 192 ++++++++++++++++++ rust/crates/keygo-api/src/domain/mod.rs | 4 + .../src/cli/commands/invite/create.rs | 22 +- .../keygo-server/src/domain/invite_pepper.rs | 55 +++++ rust/crates/keygo-server/src/domain/mod.rs | 8 +- rust/crates/keygo-uniffi/src/invite.rs | 74 +++++++ rust/crates/keygo-uniffi/src/lib.rs | 1 + 14 files changed, 455 insertions(+), 61 deletions(-) create mode 100644 core/rust/src/main/kotlin/de/davis/keygo/rust/invite/InviteLink.kt create mode 100644 core/rust/src/test/kotlin/de/davis/keygo/rust/invite/ParseWithResultTest.kt create mode 100644 core/rust/src/testFixtures/kotlin/de/davis/keygo/rust/FakeInviteLinkParser.kt rename rust/crates/{keygo-server => keygo-api}/src/domain/invite_code.rs (60%) create mode 100644 rust/crates/keygo-api/src/domain/invite_link.rs create mode 100644 rust/crates/keygo-server/src/domain/invite_pepper.rs create mode 100644 rust/crates/keygo-uniffi/src/invite.rs diff --git a/core/rust/src/main/kotlin/de/davis/keygo/rust/di/RustModule.kt b/core/rust/src/main/kotlin/de/davis/keygo/rust/di/RustModule.kt index cf045be34..ec5433aae 100644 --- a/core/rust/src/main/kotlin/de/davis/keygo/rust/di/RustModule.kt +++ b/core/rust/src/main/kotlin/de/davis/keygo/rust/di/RustModule.kt @@ -4,6 +4,8 @@ import de.davisalessandro.keygo.rust.CardFormatter import de.davisalessandro.keygo.rust.CardFormatterInterface import de.davisalessandro.keygo.rust.CsvBackupManager import de.davisalessandro.keygo.rust.CsvBackupManagerInterface +import de.davisalessandro.keygo.rust.InviteLinkParser +import de.davisalessandro.keygo.rust.InviteLinkParserInterface import de.davisalessandro.keygo.rust.ItemManager import de.davisalessandro.keygo.rust.ItemManagerInterface import de.davisalessandro.keygo.rust.JsonBackupManager @@ -52,4 +54,7 @@ object RustModule { @Single internal fun provideUsernameValidator(): UsernameValidatorInterface = UsernameValidator() + + @Single + internal fun provideInviteLinkParser(): InviteLinkParserInterface = InviteLinkParser() } \ No newline at end of file diff --git a/core/rust/src/main/kotlin/de/davis/keygo/rust/invite/InviteLink.kt b/core/rust/src/main/kotlin/de/davis/keygo/rust/invite/InviteLink.kt new file mode 100644 index 000000000..d8a99b93a --- /dev/null +++ b/core/rust/src/main/kotlin/de/davis/keygo/rust/invite/InviteLink.kt @@ -0,0 +1,28 @@ +package de.davis.keygo.rust.invite + +import de.davis.keygo.core.util.Result +import de.davisalessandro.keygo.rust.InviteLink +import de.davisalessandro.keygo.rust.InviteLinkException +import de.davisalessandro.keygo.rust.InviteLinkParserInterface + +typealias InviteLinkParser = InviteLinkParserInterface + +enum class InviteLinkError { + NotAnInvite, + InvalidServer, + InvalidCode, +} + +fun InviteLinkParserInterface.parseWithResult( + link: String, +): Result = try { + Result.Success(parse(link)) +} catch (e: InviteLinkException) { + Result.Failure(e.toInviteLinkError()) +} + +private fun InviteLinkException.toInviteLinkError(): InviteLinkError = when (this) { + is InviteLinkException.NotAnInvite -> InviteLinkError.NotAnInvite + is InviteLinkException.InvalidServer -> InviteLinkError.InvalidServer + is InviteLinkException.InvalidCode -> InviteLinkError.InvalidCode +} diff --git a/core/rust/src/test/kotlin/de/davis/keygo/rust/invite/ParseWithResultTest.kt b/core/rust/src/test/kotlin/de/davis/keygo/rust/invite/ParseWithResultTest.kt new file mode 100644 index 000000000..cdc81b6de --- /dev/null +++ b/core/rust/src/test/kotlin/de/davis/keygo/rust/invite/ParseWithResultTest.kt @@ -0,0 +1,35 @@ +package de.davis.keygo.rust.invite + +import de.davis.keygo.core.util.Result +import de.davis.keygo.rust.FakeInviteLinkParser +import de.davisalessandro.keygo.rust.InviteLink +import de.davisalessandro.keygo.rust.InviteLinkException +import kotlin.test.Test +import kotlin.test.assertEquals + +class ParseWithResultTest { + + private val parser = FakeInviteLinkParser() + + @Test + fun returns_the_invite() { + val invite = InviteLink(serverUrl = "https://vault.example.org", code = "7KQ2M9XD4HPA") + parser.links = mapOf("link" to invite) + + assertEquals(Result.Success(invite), parser.parseWithResult("link")) + } + + @Test + fun maps_every_exception_to_its_error() { + val cases = mapOf( + InviteLinkException.NotAnInvite() to InviteLinkError.NotAnInvite, + InviteLinkException.InvalidServer() to InviteLinkError.InvalidServer, + InviteLinkException.InvalidCode() to InviteLinkError.InvalidCode, + ) + + for ((exception, error) in cases) { + parser.errors = mapOf("x" to exception) + assertEquals(Result.Failure(error), parser.parseWithResult("x")) + } + } +} diff --git a/core/rust/src/testFixtures/kotlin/de/davis/keygo/rust/FakeInviteLinkParser.kt b/core/rust/src/testFixtures/kotlin/de/davis/keygo/rust/FakeInviteLinkParser.kt new file mode 100644 index 000000000..29bec905f --- /dev/null +++ b/core/rust/src/testFixtures/kotlin/de/davis/keygo/rust/FakeInviteLinkParser.kt @@ -0,0 +1,16 @@ +package de.davis.keygo.rust + +import de.davisalessandro.keygo.rust.InviteLink +import de.davisalessandro.keygo.rust.InviteLinkException +import de.davisalessandro.keygo.rust.InviteLinkParserInterface + +class FakeInviteLinkParser : InviteLinkParserInterface { + + var links: Map = emptyMap() + var errors: Map = emptyMap() + + override fun parse(link: String): InviteLink { + errors[link]?.let { throw it } + return links[link] ?: throw InviteLinkException.NotAnInvite() + } +} diff --git a/rust/Cargo.lock b/rust/Cargo.lock index df0df6209..22592f06d 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1632,6 +1632,7 @@ dependencies = [ "thiserror", "unicode-normalization", "unicode-properties", + "url", "uuid", "zeroize", ] diff --git a/rust/crates/keygo-api/Cargo.toml b/rust/crates/keygo-api/Cargo.toml index 5549f424b..af29045f4 100644 --- a/rust/crates/keygo-api/Cargo.toml +++ b/rust/crates/keygo-api/Cargo.toml @@ -19,6 +19,7 @@ getrandom = { workspace = true, optional = true } sha2 = { workspace = true, optional = true, features = ["zeroize"] } zeroize = { workspace = true, features = ["derive"] } unicode-normalization = "0.1.25" +url = "2.5.8" unicode-properties = { version = "0.1.4", default-features = false, features = ["general-category"] } [dev-dependencies] diff --git a/rust/crates/keygo-server/src/domain/invite_code.rs b/rust/crates/keygo-api/src/domain/invite_code.rs similarity index 60% rename from rust/crates/keygo-server/src/domain/invite_code.rs rename to rust/crates/keygo-api/src/domain/invite_code.rs index 398cf5b47..4b37a6e8c 100644 --- a/rust/crates/keygo-server/src/domain/invite_code.rs +++ b/rust/crates/keygo-api/src/domain/invite_code.rs @@ -1,32 +1,15 @@ -use super::InviteHash; -use hmac::{Hmac, KeyInit, Mac}; -use sha2::Sha256; use std::fmt::{Display, Formatter}; use std::str::FromStr; use thiserror::Error; -use zeroize::{Zeroize, ZeroizeOnDrop}; +#[cfg(feature = "server")] const ALPHABET: &[u8; 32] = b"0123456789ABCDEFGHJKMNPQRSTVWXYZ"; // no I, L, O, U -#[derive(Zeroize, ZeroizeOnDrop)] -pub struct InvitePepper([u8; 32]); - -impl InvitePepper { - pub fn new(bytes: &[u8; 32]) -> Self { - Self(*bytes) - } - - pub fn hash(&self, code: &InviteCode) -> InviteHash { - let mut mac = Hmac::::new_from_slice(&self.0).expect("HMAC accepts any key length"); - mac.update(&code.0); - <[u8; 32]>::from(mac.finalize().into_bytes()).into() - } -} - #[derive(Clone, Copy, PartialEq, Eq, Hash)] pub struct InviteCode([u8; 12]); impl InviteCode { + #[cfg(feature = "server")] pub fn generate() -> Self { let mut code = [0; 12]; getrandom::fill(&mut code).expect("getrandom failed"); @@ -41,7 +24,7 @@ impl InviteCode { } } -#[derive(Debug, Error)] +#[derive(Debug, PartialEq, Eq, Error)] pub enum ParseInviteCodeError { #[error("too short: {0} of 12 characters")] TooShort(usize), @@ -93,34 +76,51 @@ impl Display for InviteCode { mod tests { use super::*; - fn pepper(byte: u8) -> InvitePepper { - InvitePepper::new(&[byte; 32]) + fn parse(s: &str) -> Result { + s.parse::().map(|code| code.as_str().to_owned()) } #[test] - fn spellings_of_one_code_hash_alike() { - let a: InviteCode = "7KQ2M9XD4HPA".parse().unwrap(); - let b: InviteCode = "7kq2-m9xd 4hpa".parse().unwrap(); + fn spellings_of_one_code_parse_alike() { + for s in ["7KQ2M9XD4HPA", "7kq2-m9xd 4hpa", "7KQ2-M9XD-4HPA"] { + assert_eq!(parse(s), Ok("7KQ2M9XD4HPA".to_owned()), "{s}"); + } + } - assert_eq!(pepper(1).hash(&a), pepper(1).hash(&b)); + #[test] + fn maps_look_alikes() { + assert_eq!(parse("OIL2M9XD4HPA"), Ok("0112M9XD4HPA".to_owned())); } #[test] - fn hash_depends_on_the_pepper() { - let code = InviteCode::generate(); + fn rejects_malformed_codes() { + assert_eq!( + parse("7KQ2M9XD4HP"), + Err(ParseInviteCodeError::TooShort(11)) + ); + assert_eq!(parse("7KQ2M9XD4HPAB"), Err(ParseInviteCodeError::TooLong)); + assert_eq!( + parse("7KQ2M9XD4HPU"), + Err(ParseInviteCodeError::InvalidCharacter('U')) + ); + assert_eq!( + parse("7KQ2M9XD4HP!"), + Err(ParseInviteCodeError::InvalidCharacter('!')) + ); + } - assert_ne!(pepper(1).hash(&code), pepper(2).hash(&code)); + #[test] + fn displays_in_groups_of_four() { + let code: InviteCode = "7KQ2M9XD4HPA".parse().unwrap(); + assert_eq!(code.to_string(), "7KQ2-M9XD-4HPA"); } + #[cfg(feature = "server")] #[test] - fn hash_is_hmac_sha256_of_the_canonical_code() { - let code: InviteCode = "7KQ2-M9XD-4HPA".parse().unwrap(); - let mut mac = Hmac::::new_from_slice(&[1; 32]).unwrap(); - mac.update(b"7KQ2M9XD4HPA"); + fn generated_codes_round_trip() { + let code = InviteCode::generate(); - assert_eq!( - pepper(1).hash(&code).as_bytes(), - &<[u8; 32]>::from(mac.finalize().into_bytes()) - ); + assert_eq!(parse(code.as_str()).as_deref(), Ok(code.as_str())); + assert_eq!(parse(&code.to_string()).as_deref(), Ok(code.as_str())); } } diff --git a/rust/crates/keygo-api/src/domain/invite_link.rs b/rust/crates/keygo-api/src/domain/invite_link.rs new file mode 100644 index 000000000..bbe111d0a --- /dev/null +++ b/rust/crates/keygo-api/src/domain/invite_link.rs @@ -0,0 +1,192 @@ +use super::InviteCode; +use std::str::FromStr; +use thiserror::Error; +use url::Url; + +#[derive(Debug, PartialEq, Eq, Error)] +pub enum InviteLinkError { + #[error("not a keygo://invite link")] + NotAnInvite, + #[error("the invite's server is not an http(s) url")] + InvalidServer, + #[error("the invite's code is not valid")] + InvalidCode, +} + +#[derive(Clone, PartialEq, Eq)] +pub struct InviteLink { + pub server: String, + pub code: InviteCode, +} + +impl InviteLink { + const SCHEME: &str = "keygo"; + const HOST: &str = "invite"; + const SERVER_KEY: &str = "s"; + const CODE_KEY: &str = "c"; + + pub fn new(server: impl Into, code: InviteCode) -> Self { + Self { + server: server.into(), + code, + } + } + + pub fn to_url(&self) -> Url { + Url::parse_with_params( + &format!("{}://{}", Self::SCHEME, Self::HOST), + [ + (Self::SERVER_KEY, self.server.as_str()), + (Self::CODE_KEY, &self.code.to_string()), + ], + ) + .expect("keygo://invite is a valid base URL") + } +} + +impl FromStr for InviteLink { + type Err = InviteLinkError; + + fn from_str(s: &str) -> Result { + let url = Url::parse(s.trim()).map_err(|_| InviteLinkError::NotAnInvite)?; + let is_invite = url.scheme() == Self::SCHEME + && url + .host_str() + .is_some_and(|host| host.eq_ignore_ascii_case(Self::HOST)) + && matches!(url.path(), "" | "/") + && url.fragment().is_none(); + if !is_invite { + return Err(InviteLinkError::NotAnInvite); + } + + let mut server = None; + let mut code = None; + for (key, value) in url.query_pairs() { + let slot = match key.as_ref() { + Self::SERVER_KEY => &mut server, + Self::CODE_KEY => &mut code, + _ => continue, + }; + if slot.replace(value).is_some() { + return Err(InviteLinkError::NotAnInvite); + } + } + let (Some(server), Some(code)) = (server, code) else { + return Err(InviteLinkError::NotAnInvite); + }; + + let is_http = Url::parse(&server).is_ok_and(|url| matches!(url.scheme(), "http" | "https")); + if !is_http { + return Err(InviteLinkError::InvalidServer); + } + let code = code.parse().map_err(|_| InviteLinkError::InvalidCode)?; + Ok(Self::new(server, code)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn code() -> InviteCode { + "7KQ2M9XD4HPA".parse().unwrap() + } + + #[test] + fn link_is_pinned() { + assert_eq!( + InviteLink::new("https://keygo.example.com", code()) + .to_url() + .as_str(), + "keygo://invite?s=https%3A%2F%2Fkeygo.example.com&c=7KQ2-M9XD-4HPA", + ); + } + + #[test] + fn round_trips() { + for server in [ + "https://keygo.example.com", + "https://keygo.example.com/", + "http://localhost:8000", + "http://[::1]:8443", + "https://keygo.example.com/sync?x=1&y=2", + ] { + let link = InviteLink::new(server, code()); + assert!(link.to_url().as_str().parse() == Ok(link), "{server}"); + } + } + + #[test] + fn normalises_the_code() { + let link: InviteLink = "keygo://invite?s=https%3A%2F%2Fkeygo.example.com&c=7kq2+m9xd-4hpa" + .parse() + .unwrap(); + assert_eq!(link.code.as_str(), "7KQ2M9XD4HPA"); + } + + #[test] + fn ignores_order_case_and_unknown_keys() { + let link: InviteLink = + "KEYGO://INVITE?v=2&c=7KQ2M9XD4HPA&s=https%3A%2F%2Fkeygo.example.com" + .parse() + .unwrap(); + assert_eq!(link.server, "https://keygo.example.com"); + } + + #[test] + fn rejects_what_is_not_an_invite() { + for s in [ + "otpauth://totp/Acme:ada?secret=JBSWY3DP", + "https://keygo.example.com", + "keygo://vault?s=x&c=y", + "just some text", + "", + "keygo://invite", + "keygo://invite?c=7KQ2M9XD4HPA", + "keygo://invite?s=https%3A%2F%2Fkeygo.example.com", + "keygo://invite/x?s=https%3A%2F%2Fkeygo.example.com&c=7KQ2M9XD4HPA", + "keygo://invite?s=https%3A%2F%2Fkeygo.example.com&c=7KQ2M9XD4HPA#x", + "keygo://invite?s=https%3A%2F%2Fkeygo.example.com&s=https%3A%2F%2Fevil.example&c=7KQ2M9XD4HPA", + "keygo://invite?s=https%3A%2F%2Fkeygo.example.com&c=7KQ2M9XD4HPA&c=0000M9XD4HPA", + ] { + assert_eq!( + s.parse::().err(), + Some(InviteLinkError::NotAnInvite), + "{s}" + ); + } + } + + #[test] + fn rejects_a_server_that_is_no_http_url() { + for s in [ + "keygo://invite?s=ftp%3A%2F%2Fkeygo.example.com&c=7KQ2M9XD4HPA", + "keygo://invite?s=&c=7KQ2M9XD4HPA", + "keygo://invite?s=keygo.example.com&c=7KQ2M9XD4HPA", + ] { + assert_eq!( + s.parse::().err(), + Some(InviteLinkError::InvalidServer), + "{s}" + ); + } + } + + #[test] + fn rejects_an_invalid_code() { + let server = "keygo://invite?s=https%3A%2F%2Fkeygo.example.com"; + for code in [ + "7KQ2M9XD4HP", + "7KQ2M9XD4HPAB", + "7KQ2M9XD4HPU", + "7KQ2M9XD4HP%21", + "", + ] { + assert_eq!( + format!("{server}&c={code}").parse::().err(), + Some(InviteLinkError::InvalidCode), + "{code}" + ); + } + } +} diff --git a/rust/crates/keygo-api/src/domain/mod.rs b/rust/crates/keygo-api/src/domain/mod.rs index 65cb28d17..3aa54920d 100644 --- a/rust/crates/keygo-api/src/domain/mod.rs +++ b/rust/crates/keygo-api/src/domain/mod.rs @@ -1,6 +1,8 @@ mod access_token; mod device; mod ids; +mod invite_code; +mod invite_link; mod key_bundle; mod sealed_blob; mod session; @@ -13,6 +15,8 @@ pub use device::{ Platform, }; pub use ids::{InvalidId, LoginId, RegistrationId}; +pub use invite_code::{InviteCode, ParseInviteCodeError}; +pub use invite_link::{InviteLink, InviteLinkError}; pub use key_bundle::KeyBundle; pub use sealed_blob::{InvalidBlob, check_wrapped_ark}; pub use session::{ParseRefreshTokenError, RefreshToken, RevokeReason}; diff --git a/rust/crates/keygo-server/src/cli/commands/invite/create.rs b/rust/crates/keygo-server/src/cli/commands/invite/create.rs index b9ee5ae1c..4de18893e 100644 --- a/rust/crates/keygo-server/src/cli/commands/invite/create.rs +++ b/rust/crates/keygo-server/src/cli/commands/invite/create.rs @@ -1,8 +1,8 @@ use super::{Connection, format_utc, with_db}; -use crate::domain::InviteCode; use crate::service::invite::{self, Created}; use anyhow::ensure; use clap::Args; +use keygo_api::domain::InviteLink; use qrcode::QrCode; use qrcode::render::unicode::Dense1x2; use std::time::Duration; @@ -48,7 +48,7 @@ pub fn run(args: &CreateInviteArgs) -> anyhow::Result<()> { println!("{}", summary(&created)); println!( "{}", - qr_code(&invite_link(&args.public_url, &created.code))? + qr_code(&InviteLink::new(&args.public_url, created.code).to_url())? ); Ok(()) } @@ -62,14 +62,6 @@ fn summary(created: &Created) -> String { ) } -fn invite_link(public_url: &str, code: &InviteCode) -> Url { - Url::parse_with_params( - "keygo://invite", - [("s", public_url), ("c", &code.to_string())], - ) - .expect("keygo://invite is a valid base URL") -} - fn qr_code(link: &Url) -> anyhow::Result { Ok(QrCode::new(link.as_str())? .render::() @@ -118,14 +110,4 @@ mod tests { "Invite 7KQ2-M9XD-4HPA expires 2026-10-18 08:30 UTC id a3a3a" ); } - - #[test] - fn invite_link_encodes_server_and_code() { - let code = "7KQ2M9XD4HPA".parse().unwrap(); - - assert_eq!( - invite_link("https://keygo.example.com/sync?x=1&y=2", &code).as_str(), - "keygo://invite?s=https%3A%2F%2Fkeygo.example.com%2Fsync%3Fx%3D1%26y%3D2&c=7KQ2-M9XD-4HPA", - ); - } } diff --git a/rust/crates/keygo-server/src/domain/invite_pepper.rs b/rust/crates/keygo-server/src/domain/invite_pepper.rs new file mode 100644 index 000000000..480c4b947 --- /dev/null +++ b/rust/crates/keygo-server/src/domain/invite_pepper.rs @@ -0,0 +1,55 @@ +use super::{InviteCode, InviteHash}; +use hmac::{Hmac, KeyInit, Mac}; +use sha2::Sha256; +use zeroize::{Zeroize, ZeroizeOnDrop}; + +#[derive(Zeroize, ZeroizeOnDrop)] +pub struct InvitePepper([u8; 32]); + +impl InvitePepper { + pub fn new(bytes: &[u8; 32]) -> Self { + Self(*bytes) + } + + pub fn hash(&self, code: &InviteCode) -> InviteHash { + let mut mac = Hmac::::new_from_slice(&self.0).expect("HMAC accepts any key length"); + mac.update(code.as_str().as_bytes()); + <[u8; 32]>::from(mac.finalize().into_bytes()).into() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn pepper(byte: u8) -> InvitePepper { + InvitePepper::new(&[byte; 32]) + } + + #[test] + fn spellings_of_one_code_hash_alike() { + let a: InviteCode = "7KQ2M9XD4HPA".parse().unwrap(); + let b: InviteCode = "7kq2-m9xd 4hpa".parse().unwrap(); + + assert_eq!(pepper(1).hash(&a), pepper(1).hash(&b)); + } + + #[test] + fn hash_depends_on_the_pepper() { + let code = InviteCode::generate(); + + assert_ne!(pepper(1).hash(&code), pepper(2).hash(&code)); + } + + #[test] + fn hash_is_hmac_sha256_of_the_canonical_code() { + let code: InviteCode = "7KQ2-M9XD-4HPA".parse().unwrap(); + let mut mac = Hmac::::new_from_slice(&[1; 32]).unwrap(); + mac.update(b"7KQ2M9XD4HPA"); + + assert_eq!( + pepper(1).hash(&code).as_bytes(), + &<[u8; 32]>::from(mac.finalize().into_bytes()) + ); + } +} diff --git a/rust/crates/keygo-server/src/domain/mod.rs b/rust/crates/keygo-server/src/domain/mod.rs index 702585eef..6671b65dd 100644 --- a/rust/crates/keygo-server/src/domain/mod.rs +++ b/rust/crates/keygo-server/src/domain/mod.rs @@ -1,8 +1,8 @@ mod access_token; mod ids; -mod invite_code; mod invite_hash; mod invite_id; +mod invite_pepper; mod session; mod time; @@ -10,12 +10,12 @@ mod time; pub use access_token::FRESH_AUTH_WINDOW; pub use access_token::{ACCESS_TOKEN_LIFETIME, AccessTokenKey, Claims, TokenIssuer}; pub use ids::opaque_identifier; -pub use invite_code::{InviteCode, InvitePepper}; pub use invite_hash::InviteHash; pub use invite_id::InviteId; +pub use invite_pepper::InvitePepper; pub use keygo_api::domain::{ - AccessToken, Device, DeviceClaim, DeviceInfo, InvalidBlob, KeyBundle, LoginId, RefreshToken, - RegistrationId, RevokeReason, Username, UsernameError, check_wrapped_ark, + AccessToken, Device, DeviceClaim, DeviceInfo, InvalidBlob, InviteCode, KeyBundle, LoginId, + RefreshToken, RegistrationId, RevokeReason, Username, UsernameError, check_wrapped_ark, }; pub use keygo_core::{DeviceId, SessionId, UserId}; pub use session::{REFRESH_TTL, SESSION_LIFETIME, SESSION_RETENTION}; diff --git a/rust/crates/keygo-uniffi/src/invite.rs b/rust/crates/keygo-uniffi/src/invite.rs new file mode 100644 index 000000000..f0ac08c3f --- /dev/null +++ b/rust/crates/keygo-uniffi/src/invite.rs @@ -0,0 +1,74 @@ +use std::str::FromStr; +use std::sync::Arc; + +use keygo_api::domain::{InviteLink as CoreInviteLink, InviteLinkError as CoreInviteLinkError}; + +#[derive(Debug, PartialEq, Eq, thiserror::Error, uniffi::Error)] +pub enum InviteLinkError { + #[error("not a keygo invite link")] + NotAnInvite, + #[error("the invite's server is not an http(s) url")] + InvalidServer, + #[error("the invite's code is not valid")] + InvalidCode, +} + +impl From for InviteLinkError { + fn from(value: CoreInviteLinkError) -> Self { + match value { + CoreInviteLinkError::NotAnInvite => Self::NotAnInvite, + CoreInviteLinkError::InvalidServer => Self::InvalidServer, + CoreInviteLinkError::InvalidCode => Self::InvalidCode, + } + } +} + +#[derive(Debug, PartialEq, Eq, uniffi::Record)] +pub struct InviteLink { + pub server_url: String, + pub code: String, +} + +impl From for InviteLink { + fn from(value: CoreInviteLink) -> Self { + Self { + server_url: value.server, + code: value.code.as_str().to_owned(), + } + } +} + +#[derive(uniffi::Object)] +pub struct InviteLinkParser; + +#[uniffi::export] +impl InviteLinkParser { + #[uniffi::constructor] + pub fn new() -> Arc { + Arc::new(Self) + } + + pub fn parse(&self, link: String) -> Result { + Ok(CoreInviteLink::from_str(&link)?.into()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn parse(link: &str) -> Result { + InviteLinkParser.parse(link.to_owned()) + } + + #[test] + fn returns_the_server_and_canonical_code() { + assert_eq!( + parse("keygo://invite?s=https%3A%2F%2Fkeygo.example.com&c=7kq2-m9xd-4hpa"), + Ok(InviteLink { + server_url: "https://keygo.example.com".to_owned(), + code: "7KQ2M9XD4HPA".to_owned(), + }), + ); + } +} diff --git a/rust/crates/keygo-uniffi/src/lib.rs b/rust/crates/keygo-uniffi/src/lib.rs index cddd8962b..9bc8c9602 100644 --- a/rust/crates/keygo-uniffi/src/lib.rs +++ b/rust/crates/keygo-uniffi/src/lib.rs @@ -1,6 +1,7 @@ mod ark_session; mod backup; mod card; +mod invite; mod item; mod key_wrap; mod passkey; From 488bd93e367f22062416a1155ee0197d83089950 Mon Sep 17 00:00:00 2001 From: Davis Date: Wed, 2 Dec 2026 12:46:38 +0100 Subject: [PATCH 06/12] refactor(qr-scanner): add permission dedicated composables --- .../core/qr_scanner/presentation/QRScanner.kt | 74 +++++++++++-------- 1 file changed, 45 insertions(+), 29 deletions(-) diff --git a/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/presentation/QRScanner.kt b/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/presentation/QRScanner.kt index 8c97f2066..2048949c5 100644 --- a/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/presentation/QRScanner.kt +++ b/core/qr-scanner/src/main/kotlin/de/davis/keygo/core/qr_scanner/presentation/QRScanner.kt @@ -13,9 +13,9 @@ import androidx.camera.core.ImageProxy import androidx.camera.core.Preview import androidx.camera.core.SurfaceRequest import androidx.camera.lifecycle.ProcessCameraProvider -import androidx.compose.foundation.layout.Box 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.Camera import androidx.compose.material.icons.filled.Close @@ -24,6 +24,7 @@ import androidx.compose.material3.Button import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.OutlinedButton +import androidx.compose.material3.Scaffold import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable @@ -33,8 +34,8 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope +import androidx.compose.runtime.rememberUpdatedState import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalFocusManager @@ -57,7 +58,6 @@ import org.koin.compose.koinInject private const val TAG = "QRScanner" -@OptIn(ExperimentalPermissionsApi::class) @Composable fun QRScanner( onClose: () -> Unit, @@ -74,25 +74,43 @@ fun QRScanner( focusManager.clearFocus() } + CameraPermissionGate(onDenied = onClose) { + ScannerContent(onClose = onClose, success = success) + } +} + +@Composable +fun RequestCameraPermission( + onGranted: () -> Unit, + onDenied: () -> Unit, +) { + val currentOnGranted by rememberUpdatedState(onGranted) + + CameraPermissionGate(onDenied = onDenied) { + LaunchedEffect(Unit) { currentOnGranted() } + } +} + +@OptIn(ExperimentalPermissionsApi::class) +@Composable +fun CameraPermissionGate( + onDenied: () -> Unit, + content: @Composable () -> Unit, +) { var permissionRequested by remember { mutableStateOf(false) } val permissionState = rememberPermissionState(Manifest.permission.CAMERA) { permissionRequested = true } when { - permissionState.status.isGranted -> { - ScannerContent(onClose = onClose, success = success) - } + permissionState.status.isGranted -> content() - permissionState.status.shouldShowRationale -> { - ExplainPermissionDialog( - onGrant = { permissionState.launchPermissionRequest() }, - onClose = onClose - ) - } + permissionState.status.shouldShowRationale -> ExplainPermissionDialog( + onGrant = { permissionState.launchPermissionRequest() }, + onClose = onDenied, + ) permissionRequested -> { - // Permission was denied permanently (no rationale, not granted, already requested) val context = LocalContext.current val openSystemScreen = rememberHandoffStarter() PermissionDeniedDialog( @@ -106,15 +124,12 @@ fun QRScanner( Log.w(TAG, "No activity found to handle the app details settings", it) } }, - onClose = onClose + onClose = onDenied, ) } - else -> { - // First time: request immediately - LaunchedEffect(Unit) { - permissionState.launchPermissionRequest() - } + else -> LaunchedEffect(Unit) { + permissionState.launchPermissionRequest() } } } @@ -254,16 +269,8 @@ private fun ScannerContent( } } - surfaceRequest?.let { - Box( - modifier = Modifier.fillMaxSize(), - contentAlignment = Alignment.TopEnd - ) { - CameraXViewfinder( - surfaceRequest = it, - modifier = Modifier.fillMaxSize() - ) - + Scaffold( + topBar = { TopAppBar( title = { Text(text = stringResource(R.string.scan_qr_code)) @@ -279,6 +286,15 @@ private fun ScannerContent( } } ) + }, + ) { padding -> + surfaceRequest?.let { + CameraXViewfinder( + surfaceRequest = it, + modifier = Modifier + .padding(padding) + .fillMaxSize(), + ) } } } From 9443df307d53719763f6425f31205e9be8a2e12f Mon Sep 17 00:00:00 2001 From: Davis Date: Wed, 2 Dec 2026 12:54:07 +0100 Subject: [PATCH 07/12] feat(feature-account): request camera permission when scan clicked --- .../account/presentation/AccountEntries.kt | 4 +-- .../account/presentation/AccountScreen.kt | 15 +++++++-- .../account/presentation/AccountViewModel.kt | 12 +++++-- .../presentation/models/AccountEvent.kt | 2 +- .../presentation/models/AccountUiEvent.kt | 2 ++ .../presentation/models/AccountUiState.kt | 1 + .../presentation/AccountViewModelTest.kt | 33 +++++++++++++++++++ 7 files changed, 60 insertions(+), 9 deletions(-) diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountEntries.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountEntries.kt index fbb8a98ae..a2f444caf 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountEntries.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountEntries.kt @@ -14,7 +14,7 @@ object AccountRoute : NavKey object ChangePasswordRoute : NavKey @Serializable -object ConnectServerRoute : NavKey +data class ConnectServerRoute(val scanInvite: Boolean = false) : NavKey @Serializable object DevicesRoute : NavKey @@ -22,7 +22,7 @@ object DevicesRoute : NavKey fun EntryProviderScope.accountEntries( metadata: Map = emptyMap(), onOpenChangePassword: () -> Unit, - onOpenConnectServer: () -> Unit, + onOpenConnectServer: (ConnectServerRoute) -> Unit, onOpenDevices: () -> Unit, navigateUp: () -> Unit, ) { diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountScreen.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountScreen.kt index 603bb8eec..d81230def 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountScreen.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountScreen.kt @@ -3,14 +3,16 @@ package de.davis.keygo.feature.account.presentation import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue import androidx.lifecycle.compose.collectAsStateWithLifecycle +import de.davis.keygo.core.qr_scanner.presentation.RequestCameraPermission import de.davis.keygo.core.util.presentation.ObserveAsEvents import de.davis.keygo.feature.account.presentation.models.AccountEvent +import de.davis.keygo.feature.account.presentation.models.AccountUiEvent import org.koin.androidx.compose.koinViewModel @Composable internal fun AccountScreen( onOpenChangePassword: () -> Unit, - onOpenConnectServer: () -> Unit, + onOpenConnectServer: (ConnectServerRoute) -> Unit, onOpenDevices: () -> Unit, navigateUp: () -> Unit, ) { @@ -20,7 +22,9 @@ internal fun AccountScreen( ObserveAsEvents(flow = viewModel.event) { when (it) { AccountEvent.NavigateToChangePassword -> onOpenChangePassword() - AccountEvent.NavigateToConnectServer -> onOpenConnectServer() + is AccountEvent.NavigateToConnectServer -> + onOpenConnectServer(ConnectServerRoute(scanInvite = it.scanInvite)) + AccountEvent.NavigateToDevices -> onOpenDevices() AccountEvent.NavigateBack -> navigateUp() } @@ -30,4 +34,9 @@ internal fun AccountScreen( state = state, onEvent = viewModel::onEvent ) -} \ No newline at end of file + + if (state.requestingCameraPermission) RequestCameraPermission( + onGranted = { viewModel.onEvent(AccountUiEvent.OnCameraGranted) }, + onDenied = { viewModel.onEvent(AccountUiEvent.OnCameraDenied) }, + ) +} diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModel.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModel.kt index 16b84044d..4ac6c3422 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModel.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModel.kt @@ -32,6 +32,7 @@ internal class AccountViewModel( ) : ViewModel() { private val _logoutDialog = MutableStateFlow(LogoutDialogState.Hidden) + private val _requestingCameraPermission = MutableStateFlow(false) @OptIn(ExperimentalCoroutinesApi::class) private val devices = serverLinkRepository.observeLink() @@ -56,6 +57,7 @@ internal class AccountViewModel( serverLinkRepository.observeLink(), _logoutDialog, devices, + _requestingCameraPermission, ::AccountUiState, ).stateIn( scope = viewModelScope, @@ -69,12 +71,16 @@ internal class AccountViewModel( fun onEvent(event: AccountUiEvent) { when (event) { AccountUiEvent.OnBackClicked -> _event.trySend(AccountEvent.NavigateBack) - AccountUiEvent.OnConnectClicked -> _event.trySend(AccountEvent.NavigateToConnectServer) + AccountUiEvent.OnConnectClicked -> _event.trySend(AccountEvent.NavigateToConnectServer()) - AccountUiEvent.OnScanInviteClicked -> { - // TODO + AccountUiEvent.OnScanInviteClicked -> _requestingCameraPermission.update { true } + AccountUiEvent.OnCameraGranted -> if (_requestingCameraPermission.value) { + _requestingCameraPermission.update { false } + _event.trySend(AccountEvent.NavigateToConnectServer(scanInvite = true)) } + AccountUiEvent.OnCameraDenied -> _requestingCameraPermission.update { false } + AccountUiEvent.OnDevicesClicked -> _event.trySend(AccountEvent.NavigateToDevices) AccountUiEvent.OnLogoutClicked -> _logoutDialog.update { LogoutDialogState.Confirming } diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountEvent.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountEvent.kt index f96b7dec3..d44707e9f 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountEvent.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountEvent.kt @@ -3,7 +3,7 @@ package de.davis.keygo.feature.account.presentation.models internal sealed interface AccountEvent { data object NavigateToChangePassword : AccountEvent - data object NavigateToConnectServer : AccountEvent + data class NavigateToConnectServer(val scanInvite: Boolean = false) : AccountEvent data object NavigateToDevices : AccountEvent data object NavigateBack : AccountEvent } \ No newline at end of file diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiEvent.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiEvent.kt index 4ac5d6aae..439a332ad 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiEvent.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiEvent.kt @@ -3,6 +3,8 @@ package de.davis.keygo.feature.account.presentation.models internal sealed interface AccountUiEvent { data object OnBackClicked : AccountUiEvent data object OnScanInviteClicked : AccountUiEvent + data object OnCameraGranted : AccountUiEvent + data object OnCameraDenied : AccountUiEvent data object OnConnectClicked : AccountUiEvent data object OnDevicesClicked : AccountUiEvent data object OnLogoutClicked : AccountUiEvent diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiState.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiState.kt index aeacd92ac..9247694d6 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiState.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/models/AccountUiState.kt @@ -6,4 +6,5 @@ internal data class AccountUiState( val link: ServerLink = ServerLink.None, val logoutDialog: LogoutDialogState = LogoutDialogState.Hidden, val devices: DevicesSummary = DevicesSummary.Loading, + val requestingCameraPermission: Boolean = false, ) diff --git a/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModelTest.kt b/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModelTest.kt index 816d96bc9..7c807c61f 100644 --- a/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModelTest.kt +++ b/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/AccountViewModelTest.kt @@ -9,12 +9,14 @@ import de.davis.keygo.core.sync.domain.model.SyncAccount import de.davis.keygo.core.sync.domain.model.SyncError import de.davis.keygo.core.sync.domain.repository.SyncRepository import de.davis.keygo.core.util.Result +import de.davis.keygo.feature.account.presentation.models.AccountEvent import de.davis.keygo.feature.account.presentation.models.AccountUiEvent import de.davis.keygo.feature.account.presentation.models.DevicesSummary import de.davis.keygo.feature.account.presentation.models.LogoutDialogState import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.launchIn import kotlinx.coroutines.test.UnconfinedTestDispatcher import kotlinx.coroutines.test.resetMain @@ -25,7 +27,9 @@ import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertIs +import kotlin.test.assertTrue import kotlin.time.Instant @OptIn(ExperimentalCoroutinesApi::class) @@ -43,6 +47,35 @@ class AccountViewModelTest { private fun viewModel() = AccountViewModel(syncRepository, repository) + @Test + fun `scan invite asks for the camera before opening the scanner`() = runTest(dispatcher) { + val vm = viewModel() + vm.uiState.launchIn(backgroundScope) + + vm.onEvent(AccountUiEvent.OnScanInviteClicked) + assertTrue(vm.uiState.value.requestingCameraPermission) + + vm.onEvent(AccountUiEvent.OnCameraGranted) + + assertFalse(vm.uiState.value.requestingCameraPermission) + assertEquals(AccountEvent.NavigateToConnectServer(scanInvite = true), vm.event.first()) + } + + @Test + fun `a denied camera stays on the account screen`() = runTest(dispatcher) { + val vm = viewModel() + vm.uiState.launchIn(backgroundScope) + + vm.onEvent(AccountUiEvent.OnScanInviteClicked) + vm.onEvent(AccountUiEvent.OnCameraDenied) + // A grant without a pending request opens nothing. + vm.onEvent(AccountUiEvent.OnCameraGranted) + vm.onEvent(AccountUiEvent.OnBackClicked) + + assertFalse(vm.uiState.value.requestingCameraPermission) + assertEquals(AccountEvent.NavigateBack, vm.event.first()) + } + @Test fun `without a link the state is none`() = runTest(dispatcher) { val vm = viewModel() From 6f0b00a440e7e2330bcdf4a28c3ced0d1b301cf9 Mon Sep 17 00:00:00 2001 From: Davis Date: Wed, 2 Dec 2026 13:11:20 +0100 Subject: [PATCH 08/12] feat(feature-account): open connect server on the invite scanner via route --- .../presentation/navigation/EntryProvider.kt | 3 +- .../account/presentation/AccountEntries.kt | 4 +-- .../presentation/setup/ConnectServerScreen.kt | 11 ++++-- .../setup/ConnectServerViewModel.kt | 35 +++++++++++++------ .../setup/model/ConnectServerUiEvent.kt | 2 +- .../setup/model/ConnectServerUiState.kt | 1 + 6 files changed, 38 insertions(+), 18 deletions(-) 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..fc6d3e670 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 @@ -25,7 +25,6 @@ import de.davis.keygo.core.presentation.model.RouteDestination import de.davis.keygo.dashboard.presentation.dashboardEntries import de.davis.keygo.feature.account.presentation.AccountRoute 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 @@ -110,7 +109,7 @@ fun keyGoEntryProvider(navigator: AppNavigator, hasAccess: Boolean): (NavKey) -> accountEntries( metadata = WindowOwning, onOpenChangePassword = { navigator.navigate(ChangePasswordRoute) }, - onOpenConnectServer = { navigator.navigate(ConnectServerRoute) }, + onOpenConnectServer = { navigator.navigate(it) }, onOpenDevices = { navigator.navigate(DevicesRoute) }, navigateUp = { navigator.goBack() }, ) diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountEntries.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountEntries.kt index a2f444caf..5ed26cc83 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountEntries.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/AccountEntries.kt @@ -39,8 +39,8 @@ fun EntryProviderScope.accountEntries( ChangePasswordScreen(onUp = navigateUp) } - entry(metadata = metadata) { - ConnectServerScreen(navigateUp = navigateUp) + entry(metadata = metadata) { route -> + ConnectServerScreen(route = route, navigateUp = navigateUp) } entry(metadata = metadata) { diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerScreen.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerScreen.kt index 80f6dbaf7..faa316dc3 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerScreen.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerScreen.kt @@ -5,14 +5,19 @@ import androidx.compose.runtime.getValue import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.davis.keygo.core.qr_scanner.presentation.QRScanner import de.davis.keygo.core.util.presentation.ObserveAsEvents +import de.davis.keygo.feature.account.presentation.ConnectServerRoute import de.davis.keygo.feature.account.presentation.setup.model.ConnectServerEvent import de.davis.keygo.feature.account.presentation.setup.model.ConnectServerUiEvent import de.davis.keygo.feature.account.presentation.setup.transformation.rememberUsernameInputTransformation import org.koin.androidx.compose.koinViewModel +import org.koin.core.parameter.parametersOf @Composable -internal fun ConnectServerScreen(navigateUp: () -> Unit) { - val viewModel = koinViewModel() +internal fun ConnectServerScreen( + route: ConnectServerRoute, + navigateUp: () -> Unit, +) { + val viewModel = koinViewModel { parametersOf(route) } val state by viewModel.state.collectAsStateWithLifecycle() ObserveAsEvents(flow = viewModel.event) { @@ -32,7 +37,7 @@ internal fun ConnectServerScreen(navigateUp: () -> Unit) { ) if (state.scanInvite) QRScanner( - onClose = { viewModel.onEvent(ConnectServerUiEvent.AbortScan) }, + onClose = { viewModel.onEvent(ConnectServerUiEvent.CloseScan) }, success = { viewModel.onEvent(ConnectServerUiEvent.CodesScanned(it)) }, ) } diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModel.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModel.kt index e9cc51e7e..018ddbbc9 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModel.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModel.kt @@ -16,6 +16,7 @@ import de.davis.keygo.core.util.getOrNull import de.davis.keygo.core.util.onFailure import de.davis.keygo.core.util.onSuccess import de.davis.keygo.feature.account.domain.model.ServerAddress +import de.davis.keygo.feature.account.presentation.ConnectServerRoute import de.davis.keygo.feature.account.presentation.setup.mapper.toFound import de.davis.keygo.feature.account.presentation.setup.mapper.toPasswordCheck import de.davis.keygo.feature.account.presentation.setup.mapper.toServerCheck @@ -53,11 +54,13 @@ import kotlinx.coroutines.flow.stateIn import kotlinx.coroutines.flow.transformLatest import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch +import org.koin.core.annotation.InjectedParam import org.koin.core.annotation.KoinViewModel import kotlin.time.Duration.Companion.milliseconds @KoinViewModel internal class ConnectServerViewModel( + @InjectedParam route: ConnectServerRoute, private val syncRepository: SyncRepository, private val usernameValidator: UsernameValidator, private val register: RegisterUseCase, @@ -129,7 +132,9 @@ internal class ConnectServerViewModel( // --- Rejected by the server on register --- private val _rejection = MutableStateFlow(null) private val _inviteRequiredBy = MutableStateFlow(null) - private val _scanInvite = MutableStateFlow(false) + private val _inviteScan = MutableStateFlow( + if (route.scanInvite) InviteScan.Scanning else InviteScan.Closed, + ) private fun fields() = Fields( address = addressTextFieldState.text.toString(), @@ -152,7 +157,7 @@ internal class ConnectServerViewModel( _fields, _rejection, _inviteRequiredBy, - _scanInvite, + _inviteScan, ::uiState, ).stateIn( scope = viewModelScope, @@ -167,7 +172,7 @@ internal class ConnectServerViewModel( fields = fields(), rejection = null, inviteRequiredBy = null, - scanInvite = false, + inviteScan = _inviteScan.value, ), ) @@ -181,7 +186,7 @@ internal class ConnectServerViewModel( fields: Fields, rejection: Rejection?, inviteRequiredBy: String?, - scanInvite: Boolean, + inviteScan: InviteScan, ) = ConnectServerUiState( enterDomainState = EnterDomainState( addressTextFieldState = addressTextFieldState, @@ -197,8 +202,8 @@ internal class ConnectServerViewModel( usernameTextFieldState = usernameTextFieldState, inviteTextFieldState = inviteTextFieldState, serverHost = fields.address, - serverInviteRequired = inviteRequired(check, inviteRequiredBy), - inviteEditable = true, + serverInviteRequired = route.fromInvite || inviteRequired(check, inviteRequiredBy), + inviteEditable = !route.fromInvite, allowedUsernameChars = allowedUsernameChars, usernameCheck = rejection.usernameCheck(fields.username) ?: usernameCheck, inviteError = inviteError(check, fields.invite, rejection, inviteRequiredBy), @@ -225,7 +230,8 @@ internal class ConnectServerViewModel( rejection, inviteRequiredBy, ), - scanInvite = scanInvite, + scanInvite = inviteScan == InviteScan.Scanning || inviteScan == InviteScan.Verifying, + inviteScanError = (inviteScan as? InviteScan.Failed)?.error, ) private fun canContinue( @@ -308,9 +314,9 @@ internal class ConnectServerViewModel( is ConnectServerUiEvent.SchemeChanged -> _detectedScheme.update { event.scheme } - ConnectServerUiEvent.ScanInvite -> _scanInvite.update { true } - ConnectServerUiEvent.AbortScan -> _scanInvite.update { false } - is ConnectServerUiEvent.CodesScanned -> {} + ConnectServerUiEvent.ScanInvite -> _inviteScan.update { InviteScan.Scanning } + ConnectServerUiEvent.CloseScan -> {} // closeScan() + is ConnectServerUiEvent.CodesScanned -> {} // onCodesScanned(event.codes) } } @@ -436,6 +442,14 @@ internal class ConnectServerViewModel( onFailure = { ServerCheck.Failed(it) }, ) + private sealed interface InviteScan { + data object Closed : InviteScan + data object Scanning : InviteScan + + data object Verifying : InviteScan + data class Failed(val error: InviteScanError) : InviteScan + } + private sealed interface Rejection { data class Username(val username: String, val error: SyncError) : Rejection data class Invite(val invite: String) : Rejection @@ -448,6 +462,7 @@ internal class ConnectServerViewModel( private data class Route( val step: ConnectServerStep = ConnectServerStep.EnterDomain, val choice: AccountChoice? = null, + val fromInvite: Boolean = false, ) { val steps: List = stepsFor(choice) diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiEvent.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiEvent.kt index 4852a653b..7b8c550f3 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiEvent.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiEvent.kt @@ -7,7 +7,7 @@ internal sealed interface ConnectServerUiEvent { data class ChooseAccount(val choice: AccountChoice) : ConnectServerUiEvent data class SchemeChanged(val scheme: String?) : ConnectServerUiEvent data object ScanInvite : ConnectServerUiEvent - data object AbortScan : ConnectServerUiEvent + data object CloseScan : ConnectServerUiEvent data class CodesScanned(val codes: List) : ConnectServerUiEvent data object UseAnotherServer : ConnectServerUiEvent diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt index 81b1cbe8f..6160ff0a4 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt @@ -15,6 +15,7 @@ internal data class ConnectServerUiState( val steps: List = stepsFor(choice = null), val canContinue: Boolean = false, val scanInvite: Boolean = false, + val inviteScanError: InviteScanError? = null, ) @Stable From c58211fbaa188739d0e64838627f5252bc075750 Mon Sep 17 00:00:00 2001 From: Davis Date: Wed, 2 Dec 2026 13:19:15 +0100 Subject: [PATCH 09/12] feat(feature-account): add trust this server step --- .../setup/ConnectServerContent.kt | 4 ++++ .../setup/ConnectServerViewModel.kt | 10 +++++--- .../presentation/setup/TrustServerContent.kt | 23 +++++++++++++++++++ .../setup/model/ConnectServerStep.kt | 19 +++++++++++---- 4 files changed, 49 insertions(+), 7 deletions(-) create mode 100644 feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/TrustServerContent.kt diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerContent.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerContent.kt index 874da07af..4d64bcdc8 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerContent.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerContent.kt @@ -82,6 +82,8 @@ internal fun ConnectServerContent( onEvent = onEvent, ) + ConnectServerStep.TrustServer -> TrustServerContent() + ConnectServerStep.ChooseUsername -> ChooseUsernameContent( state = state.chooseUsernameState, usernameInputTransformation = usernameInputTransformation, @@ -128,6 +130,7 @@ private val ConnectServerStep.secondaryAction: SecondaryAction? ) ConnectServerStep.SignInOrOut, + ConnectServerStep.TrustServer, ConnectServerStep.ChooseUsername, ConnectServerStep.ConfirmPassword, ConnectServerStep.SignIn -> null @@ -192,6 +195,7 @@ private class ConnectServerUiStateProvider : PreviewParameterProvider check is ServerCheck.Found && + ConnectServerStep.EnterDomain, + ConnectServerStep.TrustServer -> check is ServerCheck.Found && check.serverUrl == address(fields.address, scheme).getOrNull()?.origin // The step has no continue button: picking an option moves on. @@ -433,7 +434,10 @@ internal class ConnectServerViewModel( _route.update { it.moveBy(-1) } if (leaving == ConnectServerStep.ConfirmPassword || leaving == ConnectServerStep.SignIn) clearPassword() - if (_route.value.step == ConnectServerStep.EnterDomain) _rejection.update { null } + if (_route.value.step == ConnectServerStep.EnterDomain) { + _rejection.update { null } + if (_route.value.fromInvite) _route.update { Route() } + } } private suspend fun check(address: ServerAddress): ServerCheck = @@ -464,7 +468,7 @@ internal class ConnectServerViewModel( val choice: AccountChoice? = null, val fromInvite: Boolean = false, ) { - val steps: List = stepsFor(choice) + val steps: List = stepsFor(choice, fromInvite) fun moveBy(offset: Int): Route = copy(step = steps.getOrNull(steps.indexOf(step) + offset) ?: step) diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/TrustServerContent.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/TrustServerContent.kt new file mode 100644 index 000000000..33d8eb852 --- /dev/null +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/TrustServerContent.kt @@ -0,0 +1,23 @@ +package de.davis.keygo.feature.account.presentation.setup + +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.Surface +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.tooling.preview.Preview + +@Composable +internal fun TrustServerContent() { + +} + +@Preview +@Composable +private fun TrustServerContentPreview() { + MaterialTheme { + Surface(modifier = Modifier.fillMaxSize()) { + TrustServerContent() + } + } +} diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerStep.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerStep.kt index ce80caec9..e09ef5f1c 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerStep.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerStep.kt @@ -5,6 +5,7 @@ internal enum class ConnectServerStep { //ConfirmServer, SignInOrOut, + TrustServer, ChooseUsername, ConfirmPassword, SignIn, @@ -23,8 +24,18 @@ private val createAccountSteps = listOf( ConnectServerStep.ConfirmPassword, ) -internal fun stepsFor(choice: AccountChoice?): List = when (choice) { - AccountChoice.SignIn -> signInSteps - AccountChoice.CreateAccount, - null -> createAccountSteps +private val createAccountWithInviteSteps = listOf( + ConnectServerStep.EnterDomain, + ConnectServerStep.TrustServer, + ConnectServerStep.ChooseUsername, + ConnectServerStep.ConfirmPassword, +) + +internal fun stepsFor( + choice: AccountChoice?, + fromInvite: Boolean = false, +): List = when { + fromInvite -> createAccountWithInviteSteps + choice == AccountChoice.SignIn -> signInSteps + else -> createAccountSteps } From 0ce76e0dde98adb593638d3c49637bb205a0adbb Mon Sep 17 00:00:00 2001 From: Davis Date: Wed, 2 Dec 2026 13:32:41 +0100 Subject: [PATCH 10/12] feat(feature-account): verify scanned invite link --- .../keygo/core/sync/FakeSyncRepository.kt | 11 +- .../account/domain/model/InviteError.kt | 9 + .../usecase/VerifyInviteLinksUseCase.kt | 37 +++ .../presentation/setup/ConnectServerScreen.kt | 8 + .../setup/ConnectServerViewModel.kt | 39 +++- .../setup/components/InviteScanErrorDialog.kt | 74 ++++++ .../setup/model/ConnectServerUiState.kt | 3 +- .../src/main/res/values-de/strings.xml | 10 + .../account/src/main/res/values/strings.xml | 10 + .../usecase/VerifyInviteLinksUseCaseTest.kt | 97 ++++++++ .../setup/ConnectServerViewModelTest.kt | 214 +++++++++++++++++- 11 files changed, 501 insertions(+), 11 deletions(-) create mode 100644 feature/account/src/main/kotlin/de/davis/keygo/feature/account/domain/model/InviteError.kt create mode 100644 feature/account/src/main/kotlin/de/davis/keygo/feature/account/domain/usecase/VerifyInviteLinksUseCase.kt create mode 100644 feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/components/InviteScanErrorDialog.kt create mode 100644 feature/account/src/test/kotlin/de/davis/keygo/feature/account/domain/usecase/VerifyInviteLinksUseCaseTest.kt diff --git a/core/sync/src/testFixtures/kotlin/de/davis/keygo/core/sync/FakeSyncRepository.kt b/core/sync/src/testFixtures/kotlin/de/davis/keygo/core/sync/FakeSyncRepository.kt index bfe7197da..d7355762c 100644 --- a/core/sync/src/testFixtures/kotlin/de/davis/keygo/core/sync/FakeSyncRepository.kt +++ b/core/sync/src/testFixtures/kotlin/de/davis/keygo/core/sync/FakeSyncRepository.kt @@ -29,8 +29,15 @@ class FakeSyncRepository : SyncRepository { var stepUpGate: CompletableDeferred? = null - override suspend fun checkServer(serverUrl: String): Result = - error("checkServer is not faked") + /** When unset, checkServer fails the test: most callers never reach a server. */ + var checkServerResult: Result? = null + val checkedServers = mutableListOf() + + override suspend fun checkServer(serverUrl: String): Result { + val result = checkNotNull(checkServerResult) { "checkServer is not faked" } + checkedServers += serverUrl + return result + } override suspend fun register( serverUrl: String, diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/domain/model/InviteError.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/domain/model/InviteError.kt new file mode 100644 index 000000000..d4f3043ba --- /dev/null +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/domain/model/InviteError.kt @@ -0,0 +1,9 @@ +package de.davis.keygo.feature.account.domain.model + +import de.davis.keygo.core.sync.domain.model.SyncError +import de.davis.keygo.rust.invite.InviteLinkError + +internal sealed interface InviteError { + data class Invalid(val error: InviteLinkError) : InviteError + data class Unreachable(val error: SyncError) : InviteError +} diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/domain/usecase/VerifyInviteLinksUseCase.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/domain/usecase/VerifyInviteLinksUseCase.kt new file mode 100644 index 000000000..2de1fd46d --- /dev/null +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/domain/usecase/VerifyInviteLinksUseCase.kt @@ -0,0 +1,37 @@ +package de.davis.keygo.feature.account.domain.usecase + +import de.davis.keygo.core.sync.domain.repository.SyncRepository +import de.davis.keygo.core.util.Result +import de.davis.keygo.core.util.fold +import de.davis.keygo.core.util.getOrNull +import de.davis.keygo.feature.account.domain.model.InviteError +import de.davis.keygo.feature.account.domain.model.ServerAddress +import de.davis.keygo.rust.invite.InviteLinkError +import de.davis.keygo.rust.invite.InviteLinkParser +import de.davis.keygo.rust.invite.parseWithResult +import de.davisalessandro.keygo.rust.InviteLink +import org.koin.core.annotation.Single + +@Single +internal class VerifyInviteLinksUseCase( + private val inviteLinkParser: InviteLinkParser, + private val syncRepository: SyncRepository, +) { + + suspend operator fun invoke(links: List): Result { + val results = links.map(inviteLinkParser::parseWithResult) + val invite = results.firstNotNullOfOrNull { it.getOrNull() } ?: return Result.Failure( + InviteError.Invalid( + (results.firstOrNull() as? Result.Failure)?.error ?: InviteLinkError.NotAnInvite, + ), + ) + + val address = ServerAddress.parse(invite.serverUrl).getOrNull() + ?: return Result.Failure(InviteError.Invalid(InviteLinkError.InvalidServer)) + + return syncRepository.checkServer(address.origin).fold( + onSuccess = { Result.Success(invite) }, + onFailure = { Result.Failure(InviteError.Unreachable(it)) }, + ) + } +} diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerScreen.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerScreen.kt index faa316dc3..666b24674 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerScreen.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerScreen.kt @@ -6,6 +6,7 @@ import androidx.lifecycle.compose.collectAsStateWithLifecycle import de.davis.keygo.core.qr_scanner.presentation.QRScanner import de.davis.keygo.core.util.presentation.ObserveAsEvents import de.davis.keygo.feature.account.presentation.ConnectServerRoute +import de.davis.keygo.feature.account.presentation.setup.components.InviteScanErrorDialog import de.davis.keygo.feature.account.presentation.setup.model.ConnectServerEvent import de.davis.keygo.feature.account.presentation.setup.model.ConnectServerUiEvent import de.davis.keygo.feature.account.presentation.setup.transformation.rememberUsernameInputTransformation @@ -40,4 +41,11 @@ internal fun ConnectServerScreen( onClose = { viewModel.onEvent(ConnectServerUiEvent.CloseScan) }, success = { viewModel.onEvent(ConnectServerUiEvent.CodesScanned(it)) }, ) + + state.inviteScanError?.let { + InviteScanErrorDialog( + error = it, + onDismiss = { viewModel.onEvent(ConnectServerUiEvent.CloseScan) }, + ) + } } diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModel.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModel.kt index 949443581..d45a6e544 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModel.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModel.kt @@ -1,6 +1,7 @@ package de.davis.keygo.feature.account.presentation.setup import androidx.compose.foundation.text.input.TextFieldState +import androidx.compose.foundation.text.input.setTextAndPlaceCursorAtEnd import androidx.compose.runtime.snapshotFlow import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope @@ -15,7 +16,9 @@ import de.davis.keygo.core.util.fold import de.davis.keygo.core.util.getOrNull import de.davis.keygo.core.util.onFailure import de.davis.keygo.core.util.onSuccess +import de.davis.keygo.feature.account.domain.model.InviteError import de.davis.keygo.feature.account.domain.model.ServerAddress +import de.davis.keygo.feature.account.domain.usecase.VerifyInviteLinksUseCase import de.davis.keygo.feature.account.presentation.ConnectServerRoute import de.davis.keygo.feature.account.presentation.setup.mapper.toFound import de.davis.keygo.feature.account.presentation.setup.mapper.toPasswordCheck @@ -37,8 +40,10 @@ import de.davis.keygo.feature.account.presentation.setup.model.UsernameCheck import de.davis.keygo.feature.account.presentation.setup.model.stepsFor import de.davis.keygo.rust.username.UsernameValidator import de.davis.keygo.rust.username.validateWithResult +import de.davisalessandro.keygo.rust.InviteLink import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.FlowPreview +import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel import kotlinx.coroutines.flow.MutableSharedFlow import kotlinx.coroutines.flow.MutableStateFlow @@ -63,6 +68,7 @@ internal class ConnectServerViewModel( @InjectedParam route: ConnectServerRoute, private val syncRepository: SyncRepository, private val usernameValidator: UsernameValidator, + private val verifyInvite: VerifyInviteLinksUseCase, private val register: RegisterUseCase, private val session: Session, ) : ViewModel() { @@ -316,8 +322,8 @@ internal class ConnectServerViewModel( is ConnectServerUiEvent.SchemeChanged -> _detectedScheme.update { event.scheme } ConnectServerUiEvent.ScanInvite -> _inviteScan.update { InviteScan.Scanning } - ConnectServerUiEvent.CloseScan -> {} // closeScan() - is ConnectServerUiEvent.CodesScanned -> {} // onCodesScanned(event.codes) + ConnectServerUiEvent.CloseScan -> closeScan() + is ConnectServerUiEvent.CodesScanned -> onCodesScanned(event.codes) } } @@ -327,6 +333,33 @@ internal class ConnectServerViewModel( } } + private var inviteVerification: Job? = null + private fun onCodesScanned(codes: List) { + if (_inviteScan.value != InviteScan.Scanning) return + + _inviteScan.update { InviteScan.Verifying } + inviteVerification = viewModelScope.launch { + verifyInvite(codes).onSuccess { invite -> + _inviteScan.update { InviteScan.Closed } + useInvite(invite) + }.onFailure { error -> _inviteScan.update { InviteScan.Failed(error) } } + } + } + + private fun closeScan() { + inviteVerification?.cancel() + inviteVerification = null + _inviteScan.update { InviteScan.Closed } + } + + private fun useInvite(invite: InviteLink) { + val scheme = invite.serverUrl.substringBefore("://") + _detectedScheme.update { "$scheme://" } + addressTextFieldState.setTextAndPlaceCursorAtEnd(invite.serverUrl.substringAfter("://")) + inviteTextFieldState.setTextAndPlaceCursorAtEnd(invite.code) + _route.update { Route(step = ConnectServerStep.TrustServer, fromInvite = true) } + } + private fun continueStep() = when (_route.value.step) { ConnectServerStep.ConfirmPassword -> confirmPassword() ConnectServerStep.SignIn -> signIn() @@ -451,7 +484,7 @@ internal class ConnectServerViewModel( data object Scanning : InviteScan data object Verifying : InviteScan - data class Failed(val error: InviteScanError) : InviteScan + data class Failed(val error: InviteError) : InviteScan } private sealed interface Rejection { diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/components/InviteScanErrorDialog.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/components/InviteScanErrorDialog.kt new file mode 100644 index 000000000..c6cf23fe2 --- /dev/null +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/components/InviteScanErrorDialog.kt @@ -0,0 +1,74 @@ +package de.davis.keygo.feature.account.presentation.setup.components + +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.tooling.preview.Preview +import de.davis.keygo.core.sync.domain.model.NetworkFailure +import de.davis.keygo.core.sync.domain.model.SyncError +import de.davis.keygo.core.sync.presentation.messageRes +import de.davis.keygo.feature.account.R +import de.davis.keygo.feature.account.domain.model.InviteError +import de.davis.keygo.rust.invite.InviteLinkError + +@Composable +internal fun InviteScanErrorDialog( + error: InviteError, + onDismiss: () -> Unit, + modifier: Modifier = Modifier, +) { + AlertDialog( + onDismissRequest = onDismiss, + confirmButton = { + TextButton(onClick = onDismiss) { + Text(text = stringResource(R.string.invite_scan_error_dismiss)) + } + }, + modifier = modifier, + title = { Text(text = stringResource(error.titleRes)) }, + text = { Text(text = error.message()) }, + ) +} + +private val InviteError.titleRes: Int + get() = when (this) { + is InviteError.Invalid -> R.string.invite_scan_error_title + is InviteError.Unreachable -> R.string.invite_scan_error_unreachable_title + } + +@Composable +private fun InviteError.message(): String = when (this) { + is InviteError.Invalid -> stringResource(error.messageRes) + is InviteError.Unreachable -> stringResource( + R.string.invite_scan_error_unreachable, + stringResource(error.messageRes), + ) +} + +private val InviteLinkError.messageRes: Int + get() = when (this) { + InviteLinkError.NotAnInvite -> R.string.invite_scan_error_not_an_invite + InviteLinkError.InvalidServer -> R.string.invite_scan_error_invalid_server + InviteLinkError.InvalidCode -> R.string.invite_scan_error_invalid_code + } + +@Preview +@Composable +private fun InviteScanErrorDialogPreview() { + InviteScanErrorDialog( + error = InviteError.Invalid(InviteLinkError.NotAnInvite), + onDismiss = {}, + ) +} + +@Preview +@Composable +private fun InviteScanErrorDialogUnreachablePreview() { + InviteScanErrorDialog( + error = InviteError.Unreachable(SyncError.Network(NetworkFailure.Timeout)), + onDismiss = {}, + ) +} diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt index 6160ff0a4..ce89c338f 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt @@ -3,6 +3,7 @@ package de.davis.keygo.feature.account.presentation.setup.model import androidx.compose.foundation.text.input.TextFieldState import androidx.compose.runtime.Stable import de.davis.keygo.core.sync.domain.model.SyncError +import de.davis.keygo.feature.account.domain.model.InviteError @Stable internal data class ConnectServerUiState( @@ -15,7 +16,7 @@ internal data class ConnectServerUiState( val steps: List = stepsFor(choice = null), val canContinue: Boolean = false, val scanInvite: Boolean = false, - val inviteScanError: InviteScanError? = null, + val inviteScanError: InviteError? = null, ) @Stable diff --git a/feature/account/src/main/res/values-de/strings.xml b/feature/account/src/main/res/values-de/strings.xml index 06544d111..fc662dec2 100644 --- a/feature/account/src/main/res/values-de/strings.xml +++ b/feature/account/src/main/res/values-de/strings.xml @@ -68,6 +68,16 @@ Offene Registrierung Hast du eine Einladung? Scannen + QR-Code nicht verwendbar + Das ist keine KeyGo-Einladung. Scanne den Code, den du von der Person bekommen hast, die den Server betreibt. + Diese Einladung verweist auf eine Serveradresse, mit der sich KeyGo nicht verbinden kann. Bitte die Person, die den Server betreibt, um eine neue Einladung. + Der Einladungscode in diesem QR-Code ist ungültig. Bitte die Person, die den Server betreibt, um eine neue Einladung. + OK + Server nicht erreichbar + KeyGo konnte sich nicht mit dem Server aus dieser Einladung verbinden. %1$s + + Vertraust du diesem Server? + Hast du einen Account auf diesem Server? KeyGo-Server Anmelden diff --git a/feature/account/src/main/res/values/strings.xml b/feature/account/src/main/res/values/strings.xml index a8a2415d9..8e86cc138 100644 --- a/feature/account/src/main/res/values/strings.xml +++ b/feature/account/src/main/res/values/strings.xml @@ -69,6 +69,16 @@ Open signups Have an invite? Scan it + Can\'t use this QR code + This isn\'t a KeyGo invite. Scan the code you got from whoever runs the server. + This invite points to a server address KeyGo can\'t connect to. Ask whoever runs the server for a new invite. + The invite code in this QR code isn\'t valid. Ask whoever runs the server for a new invite. + OK + Can\'t reach the server + KeyGo couldn\'t connect to the server in this invite. %1$s + + Do you trust this server? + Do you have an account on this server? KeyGo server Sign in diff --git a/feature/account/src/test/kotlin/de/davis/keygo/feature/account/domain/usecase/VerifyInviteLinksUseCaseTest.kt b/feature/account/src/test/kotlin/de/davis/keygo/feature/account/domain/usecase/VerifyInviteLinksUseCaseTest.kt new file mode 100644 index 000000000..0de05b4a9 --- /dev/null +++ b/feature/account/src/test/kotlin/de/davis/keygo/feature/account/domain/usecase/VerifyInviteLinksUseCaseTest.kt @@ -0,0 +1,97 @@ +package de.davis.keygo.feature.account.domain.usecase + +import de.davis.keygo.core.sync.FakeSyncRepository +import de.davis.keygo.core.sync.domain.model.NetworkFailure +import de.davis.keygo.core.sync.domain.model.ServerInfo +import de.davis.keygo.core.sync.domain.model.SyncError +import de.davis.keygo.core.util.Result +import de.davis.keygo.feature.account.domain.model.InviteError +import de.davis.keygo.rust.FakeInviteLinkParser +import de.davis.keygo.rust.invite.InviteLinkError +import de.davisalessandro.keygo.rust.InviteLink +import de.davisalessandro.keygo.rust.InviteLinkException +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals + +class VerifyInviteLinksUseCaseTest { + + private val invite = InviteLink(serverUrl = "https://vault.example.org", code = "7KQ2M9XD4HPA") + private val parser = FakeInviteLinkParser().apply { + links = mapOf( + INVITE_LINK to invite, + BAD_SERVER_LINK to InviteLink( + serverUrl = "https://vault.example.org/path", + code = "7KQ2M9XD4HPA" + ), + ) + errors = mapOf(BAD_CODE_LINK to InviteLinkException.InvalidCode()) + } + private val repository = FakeSyncRepository().apply { + checkServerResult = Result.Success( + ServerInfo( + version = "0.4.0", + publicUrl = "https://vault.example.org", + allowSignups = false + ), + ) + } + private val verifyInvite = VerifyInviteLinksUseCase(parser, repository) + + @Test + fun an_invite_to_a_reachable_server_is_accepted() = runTest { + assertEquals(Result.Success(invite), verifyInvite(listOf(INVITE_LINK))) + assertEquals(listOf("https://vault.example.org"), repository.checkedServers) + } + + @Test + fun the_invite_is_picked_out_of_several_codes() = runTest { + assertEquals( + Result.Success(invite), + verifyInvite(listOf("otpauth://totp/x?secret=A", INVITE_LINK)), + ) + } + + @Test + fun a_code_that_is_no_invite_is_rejected_unchecked() = runTest { + assertEquals( + Result.Failure(InviteError.Invalid(InviteLinkError.NotAnInvite)), + verifyInvite(listOf("otpauth://totp/x?secret=A")), + ) + assertEquals(emptyList(), repository.checkedServers) + } + + @Test + fun an_invite_with_a_bad_code_reports_the_code() = runTest { + assertEquals( + Result.Failure(InviteError.Invalid(InviteLinkError.InvalidCode)), + verifyInvite(listOf(BAD_CODE_LINK)), + ) + assertEquals(emptyList(), repository.checkedServers) + } + + @Test + fun an_invite_whose_server_is_not_an_origin_is_rejected_unchecked() = runTest { + assertEquals( + Result.Failure(InviteError.Invalid(InviteLinkError.InvalidServer)), + verifyInvite(listOf(BAD_SERVER_LINK)), + ) + assertEquals(emptyList(), repository.checkedServers) + } + + @Test + fun an_invite_to_an_unreachable_server_is_rejected() = runTest { + val failure = SyncError.Network(NetworkFailure.Timeout) + repository.checkServerResult = Result.Failure(failure) + + assertEquals( + Result.Failure(InviteError.Unreachable(failure)), + verifyInvite(listOf(INVITE_LINK)), + ) + } +} + +private const val INVITE_LINK = "keygo://invite?s=https%3A%2F%2Fvault.example.org&c=7KQ2-M9XD-4HPA" +private const val BAD_CODE_LINK = "keygo://invite?s=https%3A%2F%2Fvault.example.org&c=SHORT" +private const val BAD_SERVER_LINK = + "keygo://invite?s=https%3A%2F%2Fvault.example.org%2Fpath&c=7KQ2-M9XD-4HPA" diff --git a/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModelTest.kt b/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModelTest.kt index 5fc7cc220..ee707af9f 100644 --- a/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModelTest.kt +++ b/feature/account/src/test/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerViewModelTest.kt @@ -18,16 +18,23 @@ import de.davis.keygo.core.sync.domain.usecase.RegisterUseCase import de.davis.keygo.core.ui.text.transformation.SchemeStrippingTransformation import de.davis.keygo.core.util.Result import de.davis.keygo.core.util.getOrNull -import de.davis.keygo.feature.account.presentation.setup.model.ConnectServerEvent +import de.davis.keygo.feature.account.domain.model.InviteError +import de.davis.keygo.feature.account.domain.usecase.VerifyInviteLinksUseCase +import de.davis.keygo.feature.account.presentation.ConnectServerRoute import de.davis.keygo.feature.account.presentation.setup.model.AccountChoice +import de.davis.keygo.feature.account.presentation.setup.model.ConnectServerEvent import de.davis.keygo.feature.account.presentation.setup.model.ConnectServerStep import de.davis.keygo.feature.account.presentation.setup.model.ConnectServerUiEvent import de.davis.keygo.feature.account.presentation.setup.model.PasswordCheck import de.davis.keygo.feature.account.presentation.setup.model.ServerCheck import de.davis.keygo.feature.account.presentation.setup.model.SignInCheck import de.davis.keygo.feature.account.presentation.setup.model.UsernameCheck +import de.davis.keygo.feature.account.presentation.setup.model.stepsFor +import de.davis.keygo.rust.FakeInviteLinkParser import de.davis.keygo.rust.FakeUsernameValidator +import de.davis.keygo.rust.invite.InviteLinkError import de.davis.keygo.rust.username.UsernameError +import de.davisalessandro.keygo.rust.InviteLink import de.davisalessandro.keygo.rust.UsernameException import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.Dispatchers @@ -47,6 +54,7 @@ import kotlin.test.AfterTest import kotlin.test.BeforeTest import kotlin.test.Test import kotlin.test.assertEquals +import kotlin.test.assertFalse import kotlin.test.assertIs import kotlin.test.assertTrue @@ -62,8 +70,12 @@ class ConnectServerViewModelTest { var gate: CompletableDeferred? = null val checked = mutableListOf() + /** When set, checkServer suspends until it completes. */ + var checkGate: CompletableDeferred? = null + override suspend fun checkServer(serverUrl: String): Result { checked += serverUrl + checkGate?.await() return result } @@ -110,6 +122,14 @@ class ConnectServerViewModelTest { private val dispatcher = StandardTestDispatcher() private val repository = FakeSyncRepository() private val usernameValidator = FakeUsernameValidator() + private val inviteLinkParser = FakeInviteLinkParser().apply { + links = mapOf( + INVITE_LINK to InviteLink( + serverUrl = "https://vault.example.org", + code = "7KQ2M9XD4HPA" + ), + ) + } private val session = FakeSession() private val accountRepository = FakeAccountRepository() @@ -119,9 +139,13 @@ class ConnectServerViewModelTest { @AfterTest fun tearDown() = Dispatchers.resetMain() - private fun unobservedViewModel() = ConnectServerViewModel( + private fun unobservedViewModel( + route: ConnectServerRoute = ConnectServerRoute(), + ) = ConnectServerViewModel( + route = route, syncRepository = repository, usernameValidator = usernameValidator, + verifyInvite = VerifyInviteLinksUseCase(inviteLinkParser, repository), register = RegisterUseCase( syncRepository = repository, accountRepository = accountRepository, @@ -130,8 +154,8 @@ class ConnectServerViewModelTest { session = session, ) - private fun TestScope.viewModel() = - unobservedViewModel().also { it.state.launchIn(backgroundScope) } + private fun TestScope.viewModel(route: ConnectServerRoute = ConnectServerRoute()) = + unobservedViewModel(route).also { it.state.launchIn(backgroundScope) } private val ConnectServerViewModel.check get() = state.value.enterDomainState.check @@ -952,7 +976,10 @@ class ConnectServerViewModelTest { submit(vm) assertEquals(ConnectServerStep.ConfirmPassword, vm.state.value.step) - assertEquals(PasswordCheck.RegisterFailed(SyncError.Network(NetworkFailure.Timeout)), vm.passwordCheck) + assertEquals( + PasswordCheck.RegisterFailed(SyncError.Network(NetworkFailure.Timeout)), + vm.passwordCheck + ) } private companion object { @@ -1008,4 +1035,181 @@ class ConnectServerViewModelTest { assertEquals(ConnectServerStep.ChooseUsername, vm.state.value.step) assertTrue(vm.state.value.step in vm.state.value.steps) } + + // --- Invite scan --- + + @Test + fun the_route_can_open_the_wizard_on_the_scanner() = runTest(dispatcher) { + assertFalse(viewModel().state.value.scanInvite) + assertTrue(viewModel(ConnectServerRoute(scanInvite = true)).state.value.scanInvite) + } + + @Test + fun a_scanned_invite_fills_the_wizard_and_asks_to_trust_the_server() = runTest(dispatcher) { + val vm = viewModel() + vm.onEvent(ConnectServerUiEvent.ScanInvite) + runCurrent() + assertTrue(vm.state.value.scanInvite) + + vm.onEvent(ConnectServerUiEvent.CodesScanned(listOf(INVITE_LINK))) + runCurrent() + + val state = vm.state.value + assertFalse(state.scanInvite) + assertEquals(null, state.inviteScanError) + assertEquals(ConnectServerStep.TrustServer, state.step) + assertEquals( + "vault.example.org", + state.enterDomainState.addressTextFieldState.text.toString() + ) + assertEquals("https://", state.enterDomainState.typedScheme) + assertEquals("7KQ2M9XD4HPA", state.chooseUsernameState.inviteTextFieldState.text.toString()) + assertFalse(state.chooseUsernameState.inviteEditable) + assertTrue(state.chooseUsernameState.serverInviteRequired) + } + + @Test + fun the_trust_step_continues_once_the_invited_server_is_found() = runTest(dispatcher) { + val vm = viewModel() + vm.onEvent(ConnectServerUiEvent.ScanInvite) + vm.onEvent(ConnectServerUiEvent.CodesScanned(listOf(INVITE_LINK))) + runCurrent() + assertFalse(vm.state.value.canContinue) + + advanceUntilIdle() + + // Once to verify the scanned invite, once more by the address step's own check. + assertEquals( + listOf("https://vault.example.org", "https://vault.example.org"), + repository.checked + ) + assertTrue(vm.state.value.canContinue) + vm.onEvent(ConnectServerUiEvent.Continue) + runCurrent() + assertEquals(ConnectServerStep.ChooseUsername, vm.state.value.step) + } + + @Test + fun a_code_that_is_no_invite_closes_the_scanner_with_an_error() = runTest(dispatcher) { + val vm = viewModel(ConnectServerRoute(scanInvite = true)) + + vm.onEvent(ConnectServerUiEvent.CodesScanned(listOf("otpauth://totp/x?secret=A"))) + runCurrent() + + assertFalse(vm.state.value.scanInvite) + assertEquals( + InviteError.Invalid(InviteLinkError.NotAnInvite), + vm.state.value.inviteScanError + ) + assertEquals(ConnectServerStep.EnterDomain, vm.state.value.step) + assertEquals("", vm.state.value.enterDomainState.addressTextFieldState.text.toString()) + + vm.onEvent(ConnectServerUiEvent.CloseScan) + runCurrent() + assertEquals(null, vm.state.value.inviteScanError) + } + + @Test + fun the_scanner_stays_up_while_the_invited_server_is_checked() = runTest(dispatcher) { + val gate = CompletableDeferred().also { repository.checkGate = it } + val vm = viewModel(ConnectServerRoute(scanInvite = true)) + + vm.onEvent(ConnectServerUiEvent.CodesScanned(listOf(INVITE_LINK))) + runCurrent() + + assertTrue(vm.state.value.scanInvite) + assertEquals(ConnectServerStep.EnterDomain, vm.state.value.step) + assertEquals(listOf("https://vault.example.org"), repository.checked) + + // Frames keep arriving while the check runs; none starts another check. + vm.onEvent(ConnectServerUiEvent.CodesScanned(listOf(INVITE_LINK))) + runCurrent() + assertEquals(listOf("https://vault.example.org"), repository.checked) + + gate.complete(Unit) + runCurrent() + + assertFalse(vm.state.value.scanInvite) + assertEquals(ConnectServerStep.TrustServer, vm.state.value.step) + } + + @Test + fun an_invite_to_an_unreachable_server_is_rejected() = runTest(dispatcher) { + val failure = SyncError.Network(NetworkFailure.Timeout) + repository.result = Result.Failure(failure) + val vm = viewModel(ConnectServerRoute(scanInvite = true)) + + vm.onEvent(ConnectServerUiEvent.CodesScanned(listOf(INVITE_LINK))) + runCurrent() + + val state = vm.state.value + assertFalse(state.scanInvite) + assertEquals(InviteError.Unreachable(failure), state.inviteScanError) + assertEquals(ConnectServerStep.EnterDomain, state.step) + assertEquals("", state.enterDomainState.addressTextFieldState.text.toString()) + assertEquals("", state.chooseUsernameState.inviteTextFieldState.text.toString()) + + vm.onEvent(ConnectServerUiEvent.CloseScan) + runCurrent() + assertEquals(null, vm.state.value.inviteScanError) + } + + @Test + fun closing_the_scanner_abandons_the_server_check() = runTest(dispatcher) { + val gate = CompletableDeferred().also { repository.checkGate = it } + val vm = viewModel(ConnectServerRoute(scanInvite = true)) + vm.onEvent(ConnectServerUiEvent.CodesScanned(listOf(INVITE_LINK))) + runCurrent() + + vm.onEvent(ConnectServerUiEvent.CloseScan) + gate.complete(Unit) + advanceUntilIdle() + + val state = vm.state.value + assertFalse(state.scanInvite) + assertEquals(null, state.inviteScanError) + assertEquals(ConnectServerStep.EnterDomain, state.step) + assertEquals("", state.enterDomainState.addressTextFieldState.text.toString()) + } + + /** The analyzer keeps delivering frames until the scanner leaves composition. */ + @Test + fun codes_after_the_scanner_closed_are_ignored() = runTest(dispatcher) { + val vm = viewModel(ConnectServerRoute(scanInvite = true)) + + vm.onEvent(ConnectServerUiEvent.CodesScanned(listOf(INVITE_LINK))) + vm.onEvent(ConnectServerUiEvent.CodesScanned(listOf("not an invite"))) + runCurrent() + + assertEquals(ConnectServerStep.TrustServer, vm.state.value.step) + assertEquals(null, vm.state.value.inviteScanError) + } + + @Test + fun aborting_the_scan_stays_on_the_address() = runTest(dispatcher) { + val vm = viewModel(ConnectServerRoute(scanInvite = true)) + + vm.onEvent(ConnectServerUiEvent.CloseScan) + runCurrent() + + assertFalse(vm.state.value.scanInvite) + assertEquals(ConnectServerStep.EnterDomain, vm.state.value.step) + } + + @Test + fun back_from_the_trust_step_leaves_the_invite_path() = runTest(dispatcher) { + val vm = viewModel(ConnectServerRoute(scanInvite = true)) + vm.onEvent(ConnectServerUiEvent.CodesScanned(listOf(INVITE_LINK))) + runCurrent() + + vm.onEvent(ConnectServerUiEvent.Back) + runCurrent() + + val state = vm.state.value + assertEquals(ConnectServerStep.EnterDomain, state.step) + assertEquals(stepsFor(choice = null), state.steps) + assertTrue(state.chooseUsernameState.inviteEditable) + } } + +private const val INVITE_LINK = "keygo://invite?s=https%3A%2F%2Fvault.example.org&c=7KQ2-M9XD-4HPA" From 238f2521b10cd336eeca528176d271be442d9cc8 Mon Sep 17 00:00:00 2001 From: Davis Date: Wed, 2 Dec 2026 15:31:53 +0100 Subject: [PATCH 11/12] feat(feature-account): add server verification UI --- .../setup/ConnectServerContent.kt | 18 +- .../setup/ConnectServerViewModel.kt | 7 + .../presentation/setup/TrustServerContent.kt | 170 +++++++++++++++++- .../setup/model/ConnectServerUiState.kt | 9 + .../src/main/res/values-de/strings.xml | 7 + .../account/src/main/res/values/strings.xml | 7 + 6 files changed, 213 insertions(+), 5 deletions(-) diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerContent.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerContent.kt index 4d64bcdc8..839a37ed3 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerContent.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/ConnectServerContent.kt @@ -39,6 +39,7 @@ import de.davis.keygo.feature.account.presentation.setup.model.ServerCheck import de.davis.keygo.feature.account.presentation.setup.model.SignInCheck import de.davis.keygo.feature.account.presentation.setup.model.SignInOrOutState import de.davis.keygo.feature.account.presentation.setup.model.SignInState +import de.davis.keygo.feature.account.presentation.setup.model.TrustServerState import de.davis.keygo.feature.account.presentation.setup.model.stepsFor import de.davis.keygo.feature.account.presentation.setup.transformation.UsernameInputTransformation @@ -82,7 +83,9 @@ internal fun ConnectServerContent( onEvent = onEvent, ) - ConnectServerStep.TrustServer -> TrustServerContent() + ConnectServerStep.TrustServer -> TrustServerContent( + state = state.trustServerState, + ) ConnectServerStep.ChooseUsername -> ChooseUsernameContent( state = state.chooseUsernameState, @@ -112,6 +115,7 @@ private val ConnectServerStep.continueLabel: Int get() = when (this) { ConnectServerStep.ConfirmPassword -> R.string.create_account ConnectServerStep.SignIn -> R.string.sign_in + ConnectServerStep.TrustServer -> R.string.trust_server_continue else -> R.string.continue_step } @@ -129,8 +133,12 @@ private val ConnectServerStep.secondaryAction: SecondaryAction? icon = Icons.Default.QrCodeScanner, ) + ConnectServerStep.TrustServer -> SecondaryAction( + label = R.string.trust_server_abort, + event = ConnectServerUiEvent.Back, + ) + ConnectServerStep.SignInOrOut, - ConnectServerStep.TrustServer, ConnectServerStep.ChooseUsername, ConnectServerStep.ConfirmPassword, ConnectServerStep.SignIn -> null @@ -176,6 +184,12 @@ private class ConnectServerUiStateProvider : PreviewParameterProvider + Text( + text = detail.label, + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Text( + text = detail.value, + style = MaterialTheme.typography.bodyMedium, + fontFamily = if (detail.monospace) FontFamily.Monospace else null, + ) + } + } +} + +private data class ServerDetail( + val label: String, + val value: String, + val monospace: Boolean = false, +) +private class TrustServerStateProvider : PreviewParameterProvider { + override val values = sequenceOf( + TrustServerState( + serverHost = "vault.example.org", + serverUrl = "https://vault.example.org", + serverVersion = "0.4.0", + signupsOpen = false, + ), + // Still checking the server: the details show a loading indicator. + TrustServerState( + serverHost = "a-rather-long-subdomain.vault.example.org", + serverUrl = "https://a-rather-long-subdomain.vault.example.org", + ), + ) } @Preview @Composable -private fun TrustServerContentPreview() { +private fun TrustServerContentPreview( + @PreviewParameter(TrustServerStateProvider::class) state: TrustServerState, +) { MaterialTheme { Surface(modifier = Modifier.fillMaxSize()) { - TrustServerContent() + TrustServerContent(state = state) } } } diff --git a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt index ce89c338f..38e3bc09e 100644 --- a/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt +++ b/feature/account/src/main/kotlin/de/davis/keygo/feature/account/presentation/setup/model/ConnectServerUiState.kt @@ -9,6 +9,7 @@ import de.davis.keygo.feature.account.domain.model.InviteError internal data class ConnectServerUiState( val enterDomainState: EnterDomainState, val signInOrOutState: SignInOrOutState, + val trustServerState: TrustServerState, val chooseUsernameState: ChooseUsernameState, val confirmPasswordState: ConfirmPasswordState, val signInState: SignInState, @@ -33,6 +34,14 @@ internal data class SignInOrOutState( val signupsOpen: Boolean, ) +@Stable +internal data class TrustServerState( + val serverHost: String, + val serverUrl: String, + val serverVersion: String? = null, + val signupsOpen: Boolean? = null, +) + @Stable internal data class ChooseUsernameState( val usernameTextFieldState: TextFieldState, diff --git a/feature/account/src/main/res/values-de/strings.xml b/feature/account/src/main/res/values-de/strings.xml index fc662dec2..18233a1ce 100644 --- a/feature/account/src/main/res/values-de/strings.xml +++ b/feature/account/src/main/res/values-de/strings.xml @@ -77,6 +77,13 @@ KeyGo konnte sich nicht mit dem Server aus dieser Einladung verbinden. %1$s Vertraust du diesem Server? + Fahre nur fort, wenn du dem Betreiber vertraust. Der Server kann deinen Tresor nicht lesen. Wer ihn kontrolliert oder in ihn eindringt, kann aber beliebig oft Passwörter durchprobieren. Ein starkes Passwort ist dein Schutz. + Du erstellst gleich ein Konto auf + Adresse + Neue Konten + Serverversion + Ich vertraue ihm + Nein, ich vertraue ihm nicht Hast du einen Account auf diesem Server? KeyGo-Server diff --git a/feature/account/src/main/res/values/strings.xml b/feature/account/src/main/res/values/strings.xml index 8e86cc138..b0ed382a0 100644 --- a/feature/account/src/main/res/values/strings.xml +++ b/feature/account/src/main/res/values/strings.xml @@ -78,6 +78,13 @@ KeyGo couldn\'t connect to the server in this invite. %1$s Do you trust this server? + Only continue if you trust whoever runs it. The server can\'t read your vault. But whoever controls it, or anyone who breaks into it, can test guesses of your password as often as they like. A strong password is what protects you. + You\'re about to create an account on + Address + New accounts + Server version + I trust it + No, I do not trust it Do you have an account on this server? KeyGo server From 58677325f9bbc03755afea472bbe70fd0a429beb Mon Sep 17 00:00:00 2001 From: Davis Date: Wed, 2 Dec 2026 15:38:36 +0100 Subject: [PATCH 12/12] feat(rust/invite): make output more appealing --- .../src/cli/commands/invite/create.rs | 70 +++++++++++++++---- 1 file changed, 56 insertions(+), 14 deletions(-) diff --git a/rust/crates/keygo-server/src/cli/commands/invite/create.rs b/rust/crates/keygo-server/src/cli/commands/invite/create.rs index 4de18893e..03f3d4b9e 100644 --- a/rust/crates/keygo-server/src/cli/commands/invite/create.rs +++ b/rust/crates/keygo-server/src/cli/commands/invite/create.rs @@ -1,16 +1,25 @@ use super::{Connection, format_utc, with_db}; use crate::service::invite::{self, Created}; +use anstream::{eprintln, println}; +use anstyle::{AnsiColor, Style}; use anyhow::ensure; use clap::Args; use keygo_api::domain::InviteLink; use qrcode::QrCode; use qrcode::render::unicode::Dense1x2; +use std::fmt::{self, Display}; use std::time::Duration; use url::Url; const MIN_TTL: Duration = Duration::from_hours(24); const MAX_TTL: Duration = Duration::from_hours(30 * 24); +const SHOWN_ONCE_WARNING: [&str; 3] = [ + "This is the only time this invite code and its QR code are shown.", + "They are not stored and can never be displayed again: hand them over now,", + "or revoke the invite later and create a new one.", +]; + #[derive(Args)] pub struct CreateInviteArgs { /// How long the invite stays redeemable, from 1 to 30 days, e.g. "72h" or "2weeks". @@ -45,21 +54,46 @@ pub fn run(args: &CreateInviteArgs) -> anyhow::Result<()> { Ok(invite::create(db, &pepper, args.ttl).await?) })?; - println!("{}", summary(&created)); - println!( - "{}", - qr_code(&InviteLink::new(&args.public_url, created.code).to_url())? - ); + let qr = qr_code(&InviteLink::new(&args.public_url, created.code).to_url())?; + println!(); + println!("{}", details(&created, &args.public_url)); + // The QR code's own quiet zone spaces it from the details and the warning. + println!("{qr}"); + eprintln!("{}", warning()); Ok(()) } -fn summary(created: &Created) -> String { +fn details(created: &Created, public_url: &str) -> String { let Created { code, invite } = created; - format!( - "Invite {code} expires {} id {}", - format_utc(invite.expires_at), - invite.id, - ) + let label = Style::new().dimmed(); + let code_style = Style::new().fg_color(Some(AnsiColor::Green.into())).bold(); + [ + ("Invite code", format!("{code_style}{code}{code_style:#}")), + ("Expires", format_utc(invite.expires_at)), + ("ID", invite.id.to_string()), + ("Server", public_url.to_owned()), + ] + .map(|(name, value)| format!(" {label}{name:<12}{label:#} {value}")) + .join("\n") +} + +fn warning() -> impl Display { + const STYLE: Style = Style::new() + .fg_color(Some(anstyle::Color::Ansi(AnsiColor::Yellow))) + .bold(); + fmt::from_fn(|f| { + for (i, line) in SHOWN_ONCE_WARNING.iter().enumerate() { + let marker = if i == 0 { "! " } else { " " }; + + let newline = if i + 1 < SHOWN_ONCE_WARNING.len() { + "\n" + } else { + "" + }; + write!(f, " {STYLE}{marker}{line}{STYLE:#}{newline}")?; + } + Ok(()) + }) } fn qr_code(link: &Url) -> anyhow::Result { @@ -95,7 +129,7 @@ mod tests { } #[test] - fn summary_shows_code_expiry_and_id() { + fn details_show_code_expiry_id_and_server() { let created = Created { code: "7KQ2M9XD4HPA".parse().unwrap(), invite: Invite { @@ -105,9 +139,17 @@ mod tests { }, }; + let details = details(&created, "https://keygo.example.com"); + assert_eq!( - summary(&created), - "Invite 7KQ2-M9XD-4HPA expires 2026-10-18 08:30 UTC id a3a3a" + anstream::adapter::strip_str(&details).to_string(), + [ + " Invite code 7KQ2-M9XD-4HPA", + " Expires 2026-10-18 08:30 UTC", + " ID a3a3a", + " Server https://keygo.example.com", + ] + .join("\n"), ); } }