diff --git a/CHANGELOG.md b/CHANGELOG.md index 3b06b7a..a4bc385 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,20 @@ uses semantic versioning (`MAJOR.MINOR.PATCH`). ### Added +- **Sign in with a passkey.** On servers that offer passkeys (1.7.0 or later, + with the operator having turned them on), the sign-in screen gains a "Sign in + with a passkey" button: one tap, your fingerprint, face or screen lock, and no + email to type. Settings, Account gains a Passkeys screen to add one (your + password, plus your two-factor code if you have one), rename it, or remove it, + which never asks for anything. Your password keeps working, and deleting a + member or publishing your profile still asks for it, because whoever is holding + the phone can unlock a passkey. A key made under an old address of the server + is marked as no longer working. The Play build supports passkeys from Android + 9; the GitHub and IzzyOnDroid build needs Android 14, because older versions + only get passkeys through a Google Play Services component that build leaves + out. Self-hosters: the app can only use passkeys on an instance that lists it + in `PASSKEY_ANDROID_APPS`, and says so when that is the problem. + - **Show technical error details.** Settings, About gains an Error reporting switch, off by default. On, a failed request says which status came back and what the server actually said, instead of a short summary: "[404] Field not diff --git a/sheaf/app/build.gradle.kts b/sheaf/app/build.gradle.kts index 41e31a6..f05de78 100644 --- a/sheaf/app/build.gradle.kts +++ b/sheaf/app/build.gradle.kts @@ -185,6 +185,12 @@ dependencies { // Biometric / device credential auth (app lock) implementation(libs.androidx.biometric) + // Passkeys. The core library talks to the platform credential manager on + // Android 14+; below that it needs the Play Services provider, which is + // proprietary, so only .play gets it and .open needs Android 14 for passkeys. + implementation(libs.androidx.credentials) + "playImplementation"(libs.androidx.credentials.play.services.auth) + // EXIF parsing — used by the avatar cropper so portrait photos // (which JPEG-encode with a rotation flag rather than rotated // pixels) come into the cropper right-side-up. diff --git a/sheaf/app/proguard-rules.pro b/sheaf/app/proguard-rules.pro index 23d78ff..d8b12dc 100644 --- a/sheaf/app/proguard-rules.pro +++ b/sheaf/app/proguard-rules.pro @@ -13,3 +13,9 @@ # OkHttp -dontwarn okhttp3.** -dontwarn okio.** + +# Credential Manager loads its Play Services provider by reflection +-if class androidx.credentials.CredentialManager +-keep class androidx.credentials.playservices.** { + *; +} diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/data/api/RawJsonAdapter.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/data/api/RawJsonAdapter.kt new file mode 100644 index 0000000..9526fd8 --- /dev/null +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/data/api/RawJsonAdapter.kt @@ -0,0 +1,27 @@ +package systems.lupine.sheaf.data.api + +import com.squareup.moshi.JsonAdapter +import com.squareup.moshi.JsonReader +import com.squareup.moshi.JsonWriter +import systems.lupine.sheaf.data.model.RawJson + +/** + * Copies a JSON value byte for byte in both directions. + * + * Moshi's generic Map decoding turns every number into a Double, so a WebAuthn + * `alg: -7` would come back out as `-7.0` and the authenticator would reject + * the options. Streaming the source untouched avoids that. + */ +class RawJsonAdapter : JsonAdapter() { + + override fun fromJson(reader: JsonReader): RawJson = + reader.nextSource().use { RawJson(it.readUtf8()) } + + override fun toJson(writer: JsonWriter, value: RawJson?) { + if (value == null) { + writer.nullValue() + return + } + writer.valueSink().use { it.writeUtf8(value.json) } + } +} diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/data/api/SheafApiService.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/data/api/SheafApiService.kt index dc82239..41be0eb 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/data/api/SheafApiService.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/data/api/SheafApiService.kt @@ -67,6 +67,29 @@ interface SheafApiService { @POST("/v1/auth/cancel-deletion") suspend fun cancelAccountDeletion() + // ── Passkeys ────────────────────────────────────────────────────────────── + + @GET("/v1/auth/passkeys") + suspend fun listPasskeys(): List + + @POST("/v1/auth/passkeys/register/begin") + suspend fun beginPasskeyRegistration(@Body body: PasskeyRegisterBegin): PasskeyOptions + + @POST("/v1/auth/passkeys/register/complete") + suspend fun completePasskeyRegistration(@Body body: PasskeyRegisterComplete): PasskeyRead + + @PATCH("/v1/auth/passkeys/{id}") + suspend fun renamePasskey(@Path("id") id: String, @Body body: PasskeyUpdate): PasskeyRead + + @DELETE("/v1/auth/passkeys/{id}") + suspend fun deletePasskey(@Path("id") id: String) + + @POST("/v1/auth/passkeys/sign-in/begin") + suspend fun beginPasskeySignIn(): PasskeyOptions + + @POST("/v1/auth/passkeys/sign-in/complete") + suspend fun completePasskeySignIn(@Body body: PasskeySignInComplete): TokenResponse + // ── API Keys ────────────────────────────────────────────────────────────── @GET("/v1/auth/keys") diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/data/model/Models.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/data/model/Models.kt index f21bfa1..ced1035 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/data/model/Models.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/data/model/Models.kt @@ -27,6 +27,8 @@ data class AuthConfig( @Json(name = "status_url") val statusUrl: String? = null, @Json(name = "terms_url") val termsUrl: String? = null, @Json(name = "privacy_url") val privacyUrl: String? = null, + // False on servers older than 1.7 too, since the field is simply absent. + @Json(name = "passkeys_available") val passkeysAvailable: Boolean = false, ) /** @@ -114,6 +116,52 @@ data class TokenResponse( @Json(name = "token_type") val tokenType: String = "bearer", ) +// ── Passkeys ───────────────────────────────────────────────────────────────── + +/** A JSON value carried verbatim. Serialised by [systems.lupine.sheaf.data.api.RawJsonAdapter]. */ +data class RawJson(val json: String) + +@JsonClass(generateAdapter = true) +data class PasskeyRead( + val id: String, + val nickname: String? = null, + @Json(name = "rp_id") val rpId: String, + // False for a key created under a previous address of the instance. + val usable: Boolean = true, + @Json(name = "backup_eligible") val backupEligible: Boolean = false, + @Json(name = "created_at") val createdAt: String, + @Json(name = "last_used_at") val lastUsedAt: String? = null, +) + +@JsonClass(generateAdapter = true) +data class PasskeyRegisterBegin( + val password: String, + @Json(name = "totp_code") val totpCode: String? = null, +) + +/** The creation or request options, handed to Credential Manager as they are. */ +@JsonClass(generateAdapter = true) +data class PasskeyOptions( + val options: RawJson, +) + +@JsonClass(generateAdapter = true) +data class PasskeyRegisterComplete( + val credential: RawJson, + val nickname: String? = null, +) + +@JsonClass(generateAdapter = true) +data class PasskeyUpdate( + val nickname: String?, +) + +@JsonClass(generateAdapter = true) +data class PasskeySignInComplete( + val credential: RawJson, + val captcha: String? = null, +) + @JsonClass(generateAdapter = true) data class TokenRefresh( @Json(name = "refresh_token") val refreshToken: String, diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/di/NetworkModule.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/di/NetworkModule.kt index e123572..d8ea5d2 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/di/NetworkModule.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/di/NetworkModule.kt @@ -11,6 +11,8 @@ import systems.lupine.sheaf.data.api.GroupUpdateJsonAdapter import systems.lupine.sheaf.data.api.MemberUpdateJsonAdapter import systems.lupine.sheaf.data.api.FrontUpdateJsonAdapter import systems.lupine.sheaf.data.model.FrontUpdate +import systems.lupine.sheaf.data.api.RawJsonAdapter +import systems.lupine.sheaf.data.model.RawJson import systems.lupine.sheaf.data.api.SheafApiService import systems.lupine.sheaf.data.api.TokenAuthenticator import systems.lupine.sheaf.data.api.TrustedDeviceCookieJar @@ -47,6 +49,7 @@ object NetworkModule { fun provideMoshi(): Moshi = Moshi.Builder() .add(Date::class.java, Rfc3339DateJsonAdapter().nullSafe()) .add(FrontUpdate::class.java, FrontUpdateJsonAdapter()) + .add(RawJson::class.java, RawJsonAdapter()) // Bodies whose optional fields clear on an explicit null. Moshi drops // those nulls, so without these the field is simply absent from the // request and the old value survives. diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/passkey/PasskeyAuthenticator.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/passkey/PasskeyAuthenticator.kt new file mode 100644 index 0000000..16dbb79 --- /dev/null +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/passkey/PasskeyAuthenticator.kt @@ -0,0 +1,88 @@ +package systems.lupine.sheaf.passkey + +import android.content.Context +import androidx.credentials.CreatePublicKeyCredentialRequest +import androidx.credentials.CreatePublicKeyCredentialResponse +import androidx.credentials.CredentialManager +import androidx.credentials.GetCredentialRequest +import androidx.credentials.GetPublicKeyCredentialOption +import androidx.credentials.PublicKeyCredential +import androidx.credentials.exceptions.CreateCredentialCancellationException +import androidx.credentials.exceptions.CreateCredentialException +import androidx.credentials.exceptions.CreateCredentialProviderConfigurationException +import androidx.credentials.exceptions.GetCredentialCancellationException +import androidx.credentials.exceptions.GetCredentialException +import androidx.credentials.exceptions.GetCredentialProviderConfigurationException +import androidx.credentials.exceptions.NoCredentialException +import androidx.credentials.exceptions.domerrors.InvalidStateError +import androidx.credentials.exceptions.domerrors.SecurityError +import androidx.credentials.exceptions.publickeycredential.CreatePublicKeyCredentialDomException +import androidx.credentials.exceptions.publickeycredential.GetPublicKeyCredentialDomException +import javax.inject.Inject +import javax.inject.Singleton + +/** A passkey ceremony failed for a reason worth showing; [message] is user-facing. */ +class PasskeyException(message: String) : Exception(message) + +/** + * The device side of a passkey ceremony, over Credential Manager. + * + * Both calls take the server's options JSON as-is and return the credential's + * JSON as-is, or null when the person backed out of the system sheet, which is + * not an error. [context] has to be an Activity, since the sheet is shown on it. + */ +@Singleton +class PasskeyAuthenticator @Inject constructor() { + + suspend fun create(context: Context, optionsJson: String): String? { + val response = try { + CredentialManager.create(context) + .createCredential(context, CreatePublicKeyCredentialRequest(optionsJson)) + } catch (e: CreateCredentialCancellationException) { + return null + } catch (e: CreateCredentialException) { + throw PasskeyException(createMessage(e)) + } + return (response as? CreatePublicKeyCredentialResponse)?.registrationResponseJson + ?: throw PasskeyException(GENERIC_CREATE) + } + + suspend fun get(context: Context, optionsJson: String): String? { + val request = GetCredentialRequest(listOf(GetPublicKeyCredentialOption(optionsJson))) + val response = try { + CredentialManager.create(context).getCredential(context, request) + } catch (e: GetCredentialCancellationException) { + return null + } catch (e: GetCredentialException) { + throw PasskeyException(getMessage(e)) + } + return (response.credential as? PublicKeyCredential)?.authenticationResponseJson + ?: throw PasskeyException(GENERIC_GET) + } + + private fun createMessage(e: CreateCredentialException): String = when { + e is CreateCredentialProviderConfigurationException -> NO_PROVIDER + e is CreatePublicKeyCredentialDomException && e.domError is InvalidStateError -> + "This device already has a passkey for your account" + e is CreatePublicKeyCredentialDomException && e.domError is SecurityError -> NOT_VOUCHED + else -> GENERIC_CREATE + } + + private fun getMessage(e: GetCredentialException): String = when { + e is NoCredentialException -> "No passkey for this server was found on this device" + e is GetCredentialProviderConfigurationException -> NO_PROVIDER + e is GetPublicKeyCredentialDomException && e.domError is SecurityError -> NOT_VOUCHED + else -> GENERIC_GET + } + + private companion object { + const val NO_PROVIDER = "Passkeys aren't supported on this device" + // The platform checks the server's /.well-known/assetlinks.json before it + // lets the app use a passkey for that domain. Self-hosted instances only + // publish one when the operator sets PASSKEY_ANDROID_APPS. + const val NOT_VOUCHED = "This server hasn't approved this app for passkeys. " + + "Its operator needs to add the app to PASSKEY_ANDROID_APPS" + const val GENERIC_CREATE = "Couldn't create a passkey" + const val GENERIC_GET = "Couldn't use a passkey" + } +} diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/SheafApp.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/SheafApp.kt index bb3a84a..ee7056b 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/SheafApp.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/SheafApp.kt @@ -80,6 +80,7 @@ import systems.lupine.sheaf.ui.importflow.importSources import systems.lupine.sheaf.ui.importflow.ImportSourcePickerScreen import systems.lupine.sheaf.ui.fields.CustomFieldsScreen import systems.lupine.sheaf.ui.apikeys.ApiKeysScreen +import systems.lupine.sheaf.ui.passkeys.PasskeysScreen import systems.lupine.sheaf.ui.sessions.SessionsScreen import systems.lupine.sheaf.ui.admin.AdminPanelScreen import systems.lupine.sheaf.ui.settings.SettingsScreen @@ -112,6 +113,7 @@ object Routes { const val CUSTOM_FIELDS = "settings/fields" const val API_KEYS = "settings/keys" const val SESSIONS = "settings/sessions" + const val PASSKEYS = "settings/passkeys" const val ADMIN_PANEL = "settings/admin" const val ADMIN_AUDIT = "settings/admin/audit" const val ADMIN_JOBS = "settings/admin/jobs" @@ -541,6 +543,7 @@ fun SheafApp( onNavigateUp = { navController.navigateUp() }, onNavigateToApiKeys = { navController.navigate(Routes.API_KEYS) }, onNavigateToSessions = { navController.navigate(Routes.SESSIONS) }, + onNavigateToPasskeys = { navController.navigate(Routes.PASSKEYS) }, onNavigateToAdminActivity = { navController.navigate(Routes.SETTINGS_ADMIN_ACTIVITY) }, ) } @@ -767,6 +770,9 @@ fun SheafApp( composable(Routes.SESSIONS) { SessionsScreen(onNavigateUp = { navController.navigateUp() }) } + composable(Routes.PASSKEYS) { + PasskeysScreen(onNavigateUp = { navController.navigateUp() }) + } composable(Routes.ADMIN_PANEL) { AdminPanelScreen( onNavigateUp = { navController.navigateUp() }, diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/auth/AuthViewModel.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/auth/AuthViewModel.kt index 4ca6f29..fb36f72 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/auth/AuthViewModel.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/auth/AuthViewModel.kt @@ -8,6 +8,8 @@ import systems.lupine.sheaf.data.api.SheafApiService import systems.lupine.sheaf.data.api.sameConfiguredOrigin import kotlinx.coroutines.flow.firstOrNull import systems.lupine.sheaf.data.model.AuthConfig +import systems.lupine.sheaf.data.model.PasskeySignInComplete +import systems.lupine.sheaf.data.model.RawJson import systems.lupine.sheaf.data.model.TokenResponse import systems.lupine.sheaf.data.model.UserLogin import systems.lupine.sheaf.data.model.UserRegister @@ -17,6 +19,8 @@ import systems.lupine.sheaf.ui.components.resolveDisplayZoneId import java.time.ZoneId import systems.lupine.sheaf.data.repository.WatchSessionRepository import systems.lupine.sheaf.datalayer.PhoneDataLayerService +import systems.lupine.sheaf.passkey.PasskeyAuthenticator +import systems.lupine.sheaf.passkey.PasskeyException import systems.lupine.sheaf.push.PushDeviceRegistrar import android.content.Context import dagger.hilt.android.lifecycle.HiltViewModel @@ -55,6 +59,7 @@ class AuthViewModel @Inject constructor( private val watchSession: WatchSessionRepository, private val pushRegistrar: PushDeviceRegistrar, private val accountDataWiper: AccountDataWiper, + private val passkeys: PasskeyAuthenticator, @ApplicationContext private val appContext: Context, ) : ViewModel() { @@ -189,6 +194,38 @@ class AuthViewModel @Inject constructor( } } + /** [activity] hosts the system passkey sheet; it is not kept. */ + fun signInWithPasskey(activity: Context) { + viewModelScope.launch { + val captcha = if (authConfig.value?.captchaOnLogin == true) { + _uiState.value = AuthUiState.SolvingCaptcha + solveCaptcha() ?: run { + _uiState.value = AuthUiState.Error("Couldn't complete captcha, please try again") + return@launch + } + } else null + _uiState.value = AuthUiState.Loading + runCatching { + val options = api.beginPasskeySignIn().options + val credential = passkeys.get(activity, options.json) ?: return@runCatching null + api.completePasskeySignIn(PasskeySignInComplete(RawJson(credential), captcha)) + } + .onSuccess { tokens -> + if (tokens == null) _uiState.value = AuthUiState.Idle + else handleLoginSuccess(tokens) + } + .onFailure { e -> + authInterceptor.pendingToken = null + // Every refusal on this path (bad credential, expired + // challenge, lockout, suspension) comes with a detail + // written for the person signing in. + val message = if (e is PasskeyException) e.message!! + else e.toUserMessage("Passkey sign-in failed", preferDetail = true) + _uiState.value = AuthUiState.Error(message) + } + } + } + fun submitTotp(code: String, rememberDevice: Boolean = false) { val email = pendingEmail ?: return val password = pendingPassword ?: return diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/auth/LoginScreen.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/auth/LoginScreen.kt index d8c490c..2d34772 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/auth/LoginScreen.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/auth/LoginScreen.kt @@ -8,6 +8,7 @@ import androidx.compose.foundation.text.KeyboardActions import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.foundation.verticalScroll import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.Key import androidx.compose.material.icons.filled.Visibility import androidx.compose.material.icons.filled.VisibilityOff import androidx.compose.material3.* @@ -19,6 +20,7 @@ import androidx.compose.ui.focus.FocusRequester import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.focus.FocusDirection import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.LocalFocusManager import androidx.compose.ui.semantics.contentType import androidx.compose.ui.semantics.semantics @@ -58,6 +60,7 @@ fun LoginScreen( var passwordVisible by remember { mutableStateOf(false) } var mode by remember { mutableStateOf("login") } val focusManager = LocalFocusManager.current + val context = LocalContext.current val isLoading = uiState is AuthUiState.Loading var logoTapCount by remember { mutableIntStateOf(0) } @@ -170,6 +173,11 @@ fun LoginScreen( if (mode == "login") viewModel.login(email, password) else viewModel.register(email, password, inviteCode) }, + showPasskey = mode == "login" && authConfig?.passkeysAvailable == true, + onPasskey = { + focusManager.clearFocus() + viewModel.signInWithPasskey(context) + }, ) "totp" -> TotpStep( isLoading = isLoading, @@ -331,6 +339,8 @@ private fun AuthStep( isSolvingCaptcha: Boolean, error: String?, onSubmit: () -> Unit, + showPasskey: Boolean, + onPasskey: () -> Unit, ) { val focusManager = LocalFocusManager.current Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { @@ -393,6 +403,17 @@ private fun AuthStep( } } else Text(if (mode == "login") "Sign In" else "Create Account") } + if (showPasskey) { + OutlinedButton( + onClick = onPasskey, + enabled = !isLoading, + modifier = Modifier.fillMaxWidth().height(48.dp), + ) { + Icon(Icons.Default.Key, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text("Sign in with a passkey") + } + } } } diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/passkeys/PasskeysScreen.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/passkeys/PasskeysScreen.kt new file mode 100644 index 0000000..df6b301 --- /dev/null +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/passkeys/PasskeysScreen.kt @@ -0,0 +1,295 @@ +package systems.lupine.sheaf.ui.passkeys + +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.automirrored.filled.ArrowBack +import androidx.compose.material.icons.outlined.Add +import androidx.compose.material.icons.outlined.Delete +import androidx.compose.material.icons.outlined.Edit +import androidx.compose.material.icons.outlined.Key +import androidx.compose.material.icons.outlined.KeyOff +import androidx.compose.material3.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.text.input.PasswordVisualTransformation +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.dp +import androidx.hilt.navigation.compose.hiltViewModel +import systems.lupine.sheaf.data.model.PasskeyRead +import systems.lupine.sheaf.ui.components.ErrorBanner +import systems.lupine.sheaf.ui.components.SheafTopAppBar + +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun PasskeysScreen( + onNavigateUp: () -> Unit, + viewModel: PasskeysViewModel = hiltViewModel(), +) { + val state by viewModel.state.collectAsState() + var showAdd by remember { mutableStateOf(false) } + var renameTarget by remember { mutableStateOf(null) } + var deleteTarget by remember { mutableStateOf(null) } + + LaunchedEffect(state.addCompleted) { showAdd = false } + + Scaffold( + contentWindowInsets = WindowInsets(0), + topBar = { + SheafTopAppBar( + title = { Text("Passkeys") }, + navigationIcon = { + IconButton(onClick = onNavigateUp) { + Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back") + } + }, + ) + }, + ) { padding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .verticalScroll(rememberScrollState()), + ) { + if (state.error != null) { + ErrorBanner(state.error!!, modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) + } + + when { + state.isLoading -> Box(Modifier.fillMaxWidth().height(120.dp), contentAlignment = Alignment.Center) { + CircularProgressIndicator() + } + !state.available -> Text( + "This server doesn't offer passkeys.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(16.dp), + ) + else -> { + Text( + "Sign in with your fingerprint, face, screen lock, or a hardware key " + + "instead of typing your password. Your password keeps working, and " + + "deleting a member or publishing your profile will still ask for it.", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(16.dp), + ) + state.passkeys.forEach { passkey -> + PasskeyListItem( + passkey = passkey, + onRename = { renameTarget = passkey }, + onDelete = { deleteTarget = passkey }, + ) + HorizontalDivider() + } + if (state.passkeys.isEmpty()) { + Text( + "No passkeys yet", + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp), + ) + } + Spacer(Modifier.height(8.dp)) + Button( + onClick = { viewModel.clearAddError(); showAdd = true }, + modifier = Modifier.padding(horizontal = 16.dp), + ) { + Icon(Icons.Outlined.Add, contentDescription = null, modifier = Modifier.size(18.dp)) + Spacer(Modifier.width(8.dp)) + Text("Add a passkey") + } + } + } + + Spacer(Modifier.height(24.dp)) + } + } + + if (showAdd) { + AddPasskeyDialog( + totpEnabled = state.totpEnabled, + isAdding = state.isAdding, + error = state.addError, + onAdd = { activity, password, code, nickname -> + viewModel.addPasskey(activity, password, code, nickname) + }, + onDismiss = { showAdd = false }, + ) + } + + renameTarget?.let { passkey -> + var nickname by remember(passkey.id) { mutableStateOf(passkey.nickname ?: "") } + AlertDialog( + onDismissRequest = { renameTarget = null }, + title = { Text("Rename passkey") }, + text = { + OutlinedTextField( + value = nickname, + onValueChange = { nickname = it.take(128) }, + label = { Text("Name") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + }, + confirmButton = { + TextButton(onClick = { + viewModel.rename(passkey.id, nickname) + renameTarget = null + }) { Text("Save") } + }, + dismissButton = { TextButton(onClick = { renameTarget = null }) { Text("Cancel") } }, + ) + } + + deleteTarget?.let { passkey -> + AlertDialog( + onDismissRequest = { deleteTarget = null }, + title = { Text("Remove passkey?") }, + text = { + Text( + "${passkey.nickname ?: "This passkey"} will no longer sign in to your account. " + + "Your password is not affected." + ) + }, + confirmButton = { + TextButton( + onClick = { viewModel.delete(passkey.id); deleteTarget = null }, + colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.error), + ) { Text("Remove") } + }, + dismissButton = { TextButton(onClick = { deleteTarget = null }) { Text("Cancel") } }, + ) + } +} + +@Composable +private fun AddPasskeyDialog( + totpEnabled: Boolean, + isAdding: Boolean, + error: String?, + onAdd: (activity: android.content.Context, password: String, code: String?, nickname: String) -> Unit, + onDismiss: () -> Unit, +) { + val context = LocalContext.current + var password by remember { mutableStateOf("") } + var code by remember { mutableStateOf("") } + var nickname by remember { mutableStateOf("") } + val canSubmit = password.isNotBlank() && (!totpEnabled || code.isNotBlank()) && !isAdding + + AlertDialog( + onDismissRequest = { if (!isAdding) onDismiss() }, + title = { Text("Add a passkey") }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text( + if (totpEnabled) "Confirm it's you with your password and two-factor code." + else "Confirm it's you with your password.", + style = MaterialTheme.typography.bodyMedium, + ) + if (error != null) ErrorBanner(error) + OutlinedTextField( + value = password, + onValueChange = { password = it }, + label = { Text("Password") }, + singleLine = true, + visualTransformation = PasswordVisualTransformation(), + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), + modifier = Modifier.fillMaxWidth(), + ) + if (totpEnabled) { + OutlinedTextField( + value = code, + onValueChange = { code = it.trim() }, + label = { Text("Two-factor or recovery code") }, + singleLine = true, + keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Password), + modifier = Modifier.fillMaxWidth(), + ) + } + OutlinedTextField( + value = nickname, + onValueChange = { nickname = it.take(128) }, + label = { Text("Name (optional)") }, + placeholder = { Text("e.g. My phone") }, + singleLine = true, + modifier = Modifier.fillMaxWidth(), + ) + } + }, + confirmButton = { + TextButton( + onClick = { onAdd(context, password, code.takeIf { totpEnabled }, nickname) }, + enabled = canSubmit, + ) { + if (isAdding) CircularProgressIndicator(Modifier.size(18.dp), strokeWidth = 2.dp) + else Text("Continue") + } + }, + dismissButton = { + TextButton(onClick = onDismiss, enabled = !isAdding) { Text("Cancel") } + }, + ) +} + +@Composable +private fun PasskeyListItem( + passkey: PasskeyRead, + onRename: () -> Unit, + onDelete: () -> Unit, +) { + ListItem( + headlineContent = { + Text(passkey.nickname ?: "Passkey", maxLines = 1, overflow = TextOverflow.Ellipsis) + }, + supportingContent = { + Column(verticalArrangement = Arrangement.spacedBy(2.dp)) { + val small = MaterialTheme.typography.bodySmall + val muted = MaterialTheme.colorScheme.onSurfaceVariant + Text( + if (passkey.backupEligible) "Synced passkey" else "Single-device key", + style = small, + color = muted, + ) + Text( + "Added ${passkey.createdAt.take(10)} · " + + (passkey.lastUsedAt?.let { "last used ${it.take(10)}" } ?: "never used"), + style = small, + color = muted, + ) + if (!passkey.usable) { + Text( + "Created for ${passkey.rpId}, a previous address of this server, so it " + + "no longer works. Remove it and add a new one.", + style = small, + color = MaterialTheme.colorScheme.error, + ) + } + } + }, + leadingContent = { + Icon( + if (passkey.usable) Icons.Outlined.Key else Icons.Outlined.KeyOff, + contentDescription = null, + tint = if (passkey.usable) MaterialTheme.colorScheme.primary + else MaterialTheme.colorScheme.error, + ) + }, + trailingContent = { + Row { + IconButton(onClick = onRename) { + Icon(Icons.Outlined.Edit, contentDescription = "Rename") + } + IconButton(onClick = onDelete) { + Icon(Icons.Outlined.Delete, contentDescription = "Remove", tint = MaterialTheme.colorScheme.error) + } + } + }, + ) +} diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/passkeys/PasskeysViewModel.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/passkeys/PasskeysViewModel.kt new file mode 100644 index 0000000..7f89a29 --- /dev/null +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/passkeys/PasskeysViewModel.kt @@ -0,0 +1,135 @@ +package systems.lupine.sheaf.ui.passkeys + +import android.content.Context +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +import dagger.hilt.android.lifecycle.HiltViewModel +import kotlinx.coroutines.flow.* +import kotlinx.coroutines.launch +import retrofit2.HttpException +import systems.lupine.sheaf.data.api.SheafApiService +import systems.lupine.sheaf.data.model.PasskeyRead +import systems.lupine.sheaf.data.model.PasskeyRegisterBegin +import systems.lupine.sheaf.data.model.PasskeyRegisterComplete +import systems.lupine.sheaf.data.model.PasskeyUpdate +import systems.lupine.sheaf.data.model.RawJson +import systems.lupine.sheaf.passkey.PasskeyAuthenticator +import systems.lupine.sheaf.passkey.PasskeyException +import systems.lupine.sheaf.util.errorDetail +import systems.lupine.sheaf.util.toUserMessage +import javax.inject.Inject + +data class PasskeysUiState( + val isLoading: Boolean = true, + // False when the server can't offer passkeys at all (off, plain http, pre-1.7). + val available: Boolean = true, + val passkeys: List = emptyList(), + val totpEnabled: Boolean = false, + val error: String? = null, + val isAdding: Boolean = false, + // Shown inside the add dialog so a wrong password doesn't close it. + val addError: String? = null, + // Bumped when an add finishes, so the screen knows to close the dialog. + val addCompleted: Int = 0, +) + +@HiltViewModel +class PasskeysViewModel @Inject constructor( + private val api: SheafApiService, + private val passkeys: PasskeyAuthenticator, +) : ViewModel() { + + private val _state = MutableStateFlow(PasskeysUiState()) + val state: StateFlow = _state.asStateFlow() + + init { load() } + + fun load() { + viewModelScope.launch { + _state.update { it.copy(isLoading = true, error = null) } + val available = runCatching { api.getAuthConfig().passkeysAvailable }.getOrDefault(true) + if (!available) { + _state.update { it.copy(isLoading = false, available = false) } + return@launch + } + runCatching { api.listPasskeys() to api.getMe().totpEnabled } + .onSuccess { (list, totp) -> + _state.update { it.copy(isLoading = false, passkeys = list, totpEnabled = totp) } + } + .onFailure { e -> + if (e is HttpException && e.code() == 404) { + _state.update { it.copy(isLoading = false, available = false) } + } else { + _state.update { it.copy(isLoading = false, error = e.toUserMessage("Failed to load passkeys")) } + } + } + } + } + + /** [activity] hosts the system passkey sheet; it is not kept. */ + fun addPasskey(activity: Context, password: String, totpCode: String?, nickname: String) { + viewModelScope.launch { + _state.update { it.copy(isAdding = true, addError = null) } + runCatching { + val options = api.beginPasskeyRegistration( + PasskeyRegisterBegin(password, totpCode?.ifBlank { null }) + ).options + val credential = passkeys.create(activity, options.json) ?: return@runCatching null + api.completePasskeyRegistration( + PasskeyRegisterComplete(RawJson(credential), nickname.trim().ifBlank { null }) + ) + } + .onSuccess { created -> + if (created == null) { + _state.update { it.copy(isAdding = false) } + } else { + _state.update { + it.copy( + isAdding = false, + passkeys = it.passkeys + created, + addCompleted = it.addCompleted + 1, + ) + } + } + } + .onFailure { e -> _state.update { it.copy(isAdding = false, addError = addMessage(e)) } } + } + } + + private fun addMessage(e: Throwable): String { + if (e is PasskeyException) return e.message!! + // A 401 here is the step-up prompt answering, so it keeps prompt wording. + // Everything else (expired challenge, duplicate key, lockout) carries a + // server detail that already says what to do next. + if (e is HttpException && e.code() == 401) { + return when (e.errorDetail()) { + "Invalid password" -> "Incorrect password" + "TOTP code required" -> "Enter your two-factor code" + else -> "Invalid two-factor code" + } + } + return e.toUserMessage("Couldn't add the passkey", preferDetail = true) + } + + fun clearAddError() { _state.update { it.copy(addError = null) } } + + fun rename(id: String, nickname: String) { + viewModelScope.launch { + runCatching { api.renamePasskey(id, PasskeyUpdate(nickname.trim().ifBlank { null })) } + .onSuccess { updated -> + _state.update { s -> s.copy(passkeys = s.passkeys.map { if (it.id == id) updated else it }) } + } + .onFailure { e -> _state.update { it.copy(error = e.toUserMessage("Failed to rename passkey")) } } + } + } + + fun delete(id: String) { + viewModelScope.launch { + runCatching { api.deletePasskey(id) } + .onSuccess { _state.update { s -> s.copy(passkeys = s.passkeys.filter { it.id != id }) } } + .onFailure { e -> _state.update { it.copy(error = e.toUserMessage("Failed to remove passkey")) } } + } + } + + fun clearError() { _state.update { it.copy(error = null) } } +} diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/SettingsCategoryScreens.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/SettingsCategoryScreens.kt index c3d0b9d..6325b46 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/SettingsCategoryScreens.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/SettingsCategoryScreens.kt @@ -912,6 +912,7 @@ fun AccountSettingsScreen( onNavigateUp: () -> Unit, onNavigateToApiKeys: () -> Unit, onNavigateToSessions: () -> Unit, + onNavigateToPasskeys: () -> Unit, onNavigateToAdminActivity: () -> Unit = {}, viewModel: SettingsViewModel = hiltViewModel(), ) { @@ -968,6 +969,15 @@ fun AccountSettingsScreen( onClick = { viewModel.startTotpSetup(); showTotpSheet = true }, ) } + if (state.passkeysAvailable) { + HorizontalDivider(modifier = Modifier.padding(start = 56.dp)) + SettingItem( + icon = Icons.Outlined.Fingerprint, + title = "Passkeys", + subtitle = "Sign in without typing your password", + onClick = onNavigateToPasskeys, + ) + } HorizontalDivider(modifier = Modifier.padding(start = 56.dp)) SettingItem( icon = Icons.Outlined.Key, diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/SettingsViewModel.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/SettingsViewModel.kt index d4421ea..102e0b9 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/SettingsViewModel.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/SettingsViewModel.kt @@ -75,6 +75,7 @@ data class SettingsUiState( val watchRepairing: Boolean = false, val watchRepairError: String? = null, val watchRepairCompleted: Boolean = false, + val passkeysAvailable: Boolean = false, ) private const val CLIENT_ID = "android" @@ -126,6 +127,8 @@ class SettingsViewModel @Inject constructor( user to system }.onSuccess { (user, system) -> _state.update { it.copy(user = user, system = system, isLoading = false) } + runCatching { api.getAuthConfig() } + .onSuccess { config -> _state.update { it.copy(passkeysAvailable = config.passkeysAvailable) } } // Only pull theme + palette down when sync is on. With // sync off, the local DataStore values are the device's // explicit pin and we shouldn't surprise the user by diff --git a/sheaf/app/src/test/java/systems/lupine/sheaf/data/api/RawJsonAdapterTest.kt b/sheaf/app/src/test/java/systems/lupine/sheaf/data/api/RawJsonAdapterTest.kt new file mode 100644 index 0000000..f66262e --- /dev/null +++ b/sheaf/app/src/test/java/systems/lupine/sheaf/data/api/RawJsonAdapterTest.kt @@ -0,0 +1,32 @@ +package systems.lupine.sheaf.data.api + +import com.squareup.moshi.Moshi +import systems.lupine.sheaf.data.model.PasskeyOptions +import systems.lupine.sheaf.data.model.PasskeySignInComplete +import systems.lupine.sheaf.data.model.RawJson +import kotlin.test.Test +import kotlin.test.assertEquals + +/** + * WebAuthn options go from the server to Credential Manager, and the + * credential comes back, without the app reading either. Decoding them as a + * Map would turn `alg: -7` into `-7.0` and the authenticator would refuse the + * options, so the bytes have to survive untouched. + */ +class RawJsonAdapterTest { + + private val moshi = Moshi.Builder().add(RawJson::class.java, RawJsonAdapter()).build() + + @Test fun `options keep integer numbers as integers`() { + val options = """{"challenge":"abc","pubKeyCredParams":[{"type":"public-key","alg":-7}],"timeout":60000}""" + val parsed = moshi.adapter(PasskeyOptions::class.java).fromJson("""{"options":$options}""")!! + assertEquals(options, parsed.options.json) + } + + @Test fun `a credential is embedded as an object, not a string`() { + val credential = """{"id":"x","response":{"clientDataJSON":"y"},"type":"public-key"}""" + val body = moshi.adapter(PasskeySignInComplete::class.java) + .toJson(PasskeySignInComplete(RawJson(credential))) + assertEquals("""{"credential":$credential}""", body) + } +} diff --git a/sheaf/app/src/test/java/systems/lupine/sheaf/ui/passkeys/PasskeysViewModelTest.kt b/sheaf/app/src/test/java/systems/lupine/sheaf/ui/passkeys/PasskeysViewModelTest.kt new file mode 100644 index 0000000..be1e92f --- /dev/null +++ b/sheaf/app/src/test/java/systems/lupine/sheaf/ui/passkeys/PasskeysViewModelTest.kt @@ -0,0 +1,141 @@ +package systems.lupine.sheaf.ui.passkeys + +import android.content.Context +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.mockk +import io.mockk.slot +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import okhttp3.MediaType.Companion.toMediaType +import okhttp3.ResponseBody.Companion.toResponseBody +import org.junit.Rule +import retrofit2.HttpException +import retrofit2.Response +import systems.lupine.sheaf.MainDispatcherRule +import systems.lupine.sheaf.data.api.SheafApiService +import systems.lupine.sheaf.data.model.AuthConfig +import systems.lupine.sheaf.data.model.PasskeyOptions +import systems.lupine.sheaf.data.model.PasskeyRead +import systems.lupine.sheaf.data.model.PasskeyRegisterComplete +import systems.lupine.sheaf.data.model.RawJson +import systems.lupine.sheaf.data.model.UserRead +import systems.lupine.sheaf.passkey.PasskeyAuthenticator +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertNull + +class PasskeysViewModelTest { + + @get:Rule val dispatcher = MainDispatcherRule() + + private val activity = mockk() + + private fun config(available: Boolean) = AuthConfig( + registrationMode = "open", + inviteCodesEnabled = false, + emailVerification = "none", + emailEnabled = false, + baseUrl = "https://sheaf.example", + passkeysAvailable = available, + ) + + private val user = UserRead( + id = "u1", + email = "a@example.com", + totpEnabled = true, + isAdmin = false, + tier = "free", + accountStatus = "active", + emailVerified = true, + createdAt = "2026-01-01T00:00:00Z", + lastLoginAt = null, + ) + + private fun passkey(id: String) = PasskeyRead( + id = id, + rpId = "sheaf.example", + createdAt = "2026-10-01T00:00:00Z", + ) + + private fun api(available: Boolean = true): SheafApiService = mockk { + coEvery { getAuthConfig() } returns config(available) + coEvery { listPasskeys() } returns listOf(passkey("p1")) + coEvery { getMe() } returns user + coEvery { beginPasskeyRegistration(any()) } returns PasskeyOptions(RawJson("""{"o":1}""")) + } + + private fun httpError(code: Int, detail: String) = HttpException( + Response.error(code, """{"detail":"$detail"}""".toResponseBody("application/json".toMediaType())) + ) + + @Test fun `an instance without passkeys never lists them`() = runTest { + val service = api(available = false) + val vm = PasskeysViewModel(service, mockk()) + advanceUntilIdle() + + assertFalse(vm.state.value.available) + coVerify(exactly = 0) { service.listPasskeys() } + } + + @Test fun `a new passkey is sent with the device's credential and joins the list`() = runTest { + val service = api() + val body = slot() + coEvery { service.completePasskeyRegistration(capture(body)) } returns passkey("p2") + val device = mockk { + coEvery { create(activity, """{"o":1}""") } returns """{"id":"cred"}""" + } + val vm = PasskeysViewModel(service, device) + advanceUntilIdle() + + vm.addPasskey(activity, "pw", "123456", " My phone ") + advanceUntilIdle() + + assertEquals("""{"id":"cred"}""", body.captured.credential.json) + assertEquals("My phone", body.captured.nickname) + assertEquals(listOf("p1", "p2"), vm.state.value.passkeys.map { it.id }) + assertEquals(1, vm.state.value.addCompleted) + } + + @Test fun `backing out of the system sheet is not an error`() = runTest { + val service = api() + val device = mockk { coEvery { create(any(), any()) } returns null } + val vm = PasskeysViewModel(service, device) + advanceUntilIdle() + + vm.addPasskey(activity, "pw", "123456", "") + advanceUntilIdle() + + assertNull(vm.state.value.addError) + assertFalse(vm.state.value.isAdding) + coVerify(exactly = 0) { service.completePasskeyRegistration(any()) } + } + + @Test fun `a wrong password is reported in the dialog`() = runTest { + val service = api() + coEvery { service.beginPasskeyRegistration(any()) } throws httpError(401, "Invalid password") + val vm = PasskeysViewModel(service, mockk()) + advanceUntilIdle() + + vm.addPasskey(activity, "wrong", "123456", "") + advanceUntilIdle() + + assertEquals("Incorrect password", vm.state.value.addError) + assertEquals(0, vm.state.value.addCompleted) + } + + @Test fun `a key already on another account says so in the server's words`() = runTest { + val service = api() + coEvery { service.completePasskeyRegistration(any()) } throws + httpError(409, "That passkey is already registered on an account.") + val device = mockk { coEvery { create(any(), any()) } returns "{}" } + val vm = PasskeysViewModel(service, device) + advanceUntilIdle() + + vm.addPasskey(activity, "pw", "123456", "") + advanceUntilIdle() + + assertEquals("That passkey is already registered on an account.", vm.state.value.addError) + } +} diff --git a/sheaf/gradle/libs.versions.toml b/sheaf/gradle/libs.versions.toml index 402b432..449c5d7 100644 --- a/sheaf/gradle/libs.versions.toml +++ b/sheaf/gradle/libs.versions.toml @@ -31,6 +31,7 @@ room = "2.6.1" work = "2.9.1" hilt-work = "1.2.0" biometric = "1.1.0" +credentials = "1.5.0" securityCrypto = "1.1.0-alpha06" exifinterface = "1.3.7" firebaseBom = "33.7.0" @@ -95,6 +96,8 @@ work-runtime-ktx = { group = "androidx.work", name = "work-runtime-ktx", version hilt-work = { group = "androidx.hilt", name = "hilt-work", version.ref = "hilt-work" } hilt-work-compiler = { group = "androidx.hilt", name = "hilt-compiler", version.ref = "hilt-work" } androidx-biometric = { group = "androidx.biometric", name = "biometric", version.ref = "biometric" } +androidx-credentials = { group = "androidx.credentials", name = "credentials", version.ref = "credentials" } +androidx-credentials-play-services-auth = { group = "androidx.credentials", name = "credentials-play-services-auth", version.ref = "credentials" } androidx-security-crypto = { group = "androidx.security", name = "security-crypto", version.ref = "securityCrypto" } androidx-exifinterface = { group = "androidx.exifinterface", name = "exifinterface", version.ref = "exifinterface" } firebase-bom = { group = "com.google.firebase", name = "firebase-bom", version.ref = "firebaseBom" }