Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions sheaf/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
6 changes: 6 additions & 0 deletions sheaf/app/proguard-rules.pro
Original file line number Diff line number Diff line change
Expand Up @@ -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.** {
*;
}
Original file line number Diff line number Diff line change
@@ -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<RawJson>() {

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) }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,29 @@ interface SheafApiService {
@POST("/v1/auth/cancel-deletion")
suspend fun cancelAccountDeletion()

// ── Passkeys ──────────────────────────────────────────────────────────────

@GET("/v1/auth/passkeys")
suspend fun listPasskeys(): List<PasskeyRead>

@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")
Expand Down
48 changes: 48 additions & 0 deletions sheaf/app/src/main/java/systems/lupine/sheaf/data/model/Models.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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,
)

/**
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
Original file line number Diff line number Diff line change
@@ -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"
}
}
6 changes: 6 additions & 0 deletions sheaf/app/src/main/java/systems/lupine/sheaf/ui/SheafApp.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
Expand Down Expand Up @@ -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) },
)
}
Expand Down Expand Up @@ -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() },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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() {

Expand Down Expand Up @@ -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
Expand Down
Loading
Loading