diff --git a/android/README.md b/android/README.md index d51afd0c..d70e7389 100644 --- a/android/README.md +++ b/android/README.md @@ -134,6 +134,56 @@ Temporary authentication refresh failures (network/5xx) keep paired credentials. A rejected access token or a second 401 after a successful refresh requires re-pairing. See the [auth contract](../docs/api/client-contract/auth.md#silent-re-auth-401-handling). +### Passkeys + +After pairing with the access token, **Settings → Passkeys** registers a +passkey for the active hub through Credential Manager +(`androidx.credentials` + `credentials-play-services-auth`). On another +device, **Sign in with a passkey** on the pairing screen needs only the hub +URL: the hub returns a JWT plus a `passkeySession`, which is stored in +`EncryptedSharedPreferences` instead of an access token and exchanged by the +normal silent re-auth loop (`POST /api/auth {"passkeySession": …}`; a 401 +there signs the device out with a "sign in again" notice). App passkeys use +the fixed RP ID `hapi.run`; the app refuses options for any other RP ID, and +passkeys created in the web app are listed but cannot sign in to the app. +See the [native passkey contract](../docs/api/client-contract/auth.md#passkeys-native). + +Ceremonies only work when two things match the APK's **signing +certificate**: + +1. `https://hapi.run/.well-known/assetlinks.json` + (`website/public/.well-known/assetlinks.json`) lists package + `run.hapi.companion` with the certificate's SHA-256 fingerprint + (colon-separated hex). Otherwise Credential Manager rejects the `hapi.run` + request before the hub is involved. +2. The hub accepts the origin `android:apk-key-hash:`, where `` is + the same SHA-256 digest as **base64url without padding**. Official hashes + live in `OFFICIAL_ANDROID_PASSKEY_ORIGINS` (`hub/src/web/routes/passkey.ts`); + other builds need `HAPI_PASSKEY_NATIVE_ORIGINS=android:apk-key-hash:` + on the hub. + +To compute both values for a keystore (debug: `~/.android/debug.keystore`, +alias `androiddebugkey`, password `android`; `./gradlew :app:signingReport` +prints the same SHA-256): + +```sh +keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey \ + -storepass android | grep 'SHA256:' +# SHA256: AB:CD:… → assetlinks.json sha256_cert_fingerprints +echo 'AB:CD:…' | tr -d ':' | xxd -r -p | base64 | tr '+/' '-_' | tr -d '=' +# → android:apk-key-hash: +``` + +Play-distributed builds are re-signed by **Play App Signing**: use the *app +signing key* certificate SHA-256 from Play Console → Test and release → App +integrity, not the upload key. That fingerprint goes into `assetlinks.json` +and its base64url form into `OFFICIAL_ANDROID_PASSKEY_ORIGINS`. Debug builds +and self-signed release builds each have their own certificate, so a passkey +ceremony from a debug build only works if its fingerprint is also published +in an `assetlinks.json` served from the RP ID — for local testing, that means +a fork with its own domain (`HAPI_PASSKEY_NATIVE_RP_ID`) and a matching app +build, since only the hapi.run maintainers can change the official file. + ## Firebase / push **Official Firebase builds:** pair an updated hub and allow diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index b39ed872..21fa2a02 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -188,6 +188,10 @@ dependencies { implementation(libs.kotlinx.coroutines.android) implementation(libs.kotlinx.serialization.json) + // Passkey sign-in + management (Credential Manager; RP ID hapi.run). + implementation(libs.androidx.credentials) + implementation(libs.androidx.credentials.play.services.auth) + // QR pairing (ScanContract activity-result API; no Play Services). implementation(libs.zxing.android.embedded) diff --git a/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt b/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt index 9d08fd9a..b7bc1363 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt @@ -58,6 +58,9 @@ import app.hapi.companion.feature.newsession.NewSessionStrings import app.hapi.companion.feature.newsession.NewSessionViewModel import app.hapi.companion.feature.pairing.ManualEntryScreen import app.hapi.companion.feature.pairing.PairingScreen +import app.hapi.companion.feature.pairing.PasskeySignInScreen +import app.hapi.companion.feature.passkey.CredentialManagerPasskeyPlatform +import app.hapi.companion.feature.passkey.findActivity import app.hapi.companion.feature.pairing.PairingUiState import app.hapi.companion.feature.pairing.PairingViewModel import app.hapi.companion.feature.pairing.QrScanScreen @@ -72,6 +75,9 @@ import app.hapi.companion.feature.share.ShareScreen import app.hapi.companion.feature.share.ShareSessionGateway import app.hapi.companion.feature.share.ShareTarget import app.hapi.companion.feature.share.ShareTargetController +import app.hapi.companion.feature.settings.PasskeysGateway +import app.hapi.companion.feature.settings.PasskeysScreen +import app.hapi.companion.feature.settings.PasskeysViewModel import app.hapi.companion.feature.settings.SettingsGeneralScreen import app.hapi.companion.feature.settings.SettingsHubScreen import app.hapi.companion.feature.settings.SettingsViewModel @@ -81,7 +87,9 @@ import app.hapi.companion.feature.settings.UsageScreen import app.hapi.companion.feature.settings.UsageViewModel import app.hapi.data.auth.AuthTerminalReason import app.hapi.data.sse.SseSubscriptionKey +import app.hapi.protocol.wire.PasskeySummary import app.hapi.protocol.wire.SessionListOrder +import kotlinx.serialization.json.JsonObject import java.util.Base64 import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -152,6 +160,7 @@ object Routes { const val PAIRING_LANDING = "pairing/landing" const val PAIRING_SCAN = "pairing/scan" const val PAIRING_MANUAL = "pairing/manual" + const val PAIRING_PASSKEY = "pairing/passkey" /** * Settings hub (category directory) + flat subpage routes (B-M4e → P2 @@ -162,6 +171,7 @@ object Routes { const val SETTINGS_GENERAL = "settings/general" const val SETTINGS_USAGE = "settings/usage" const val SETTINGS_STORAGE = "settings/storage" + const val SETTINGS_PASSKEYS = "settings/passkeys" } /** @@ -402,6 +412,18 @@ fun HapiNavigation() { ) } + composable(Routes.SETTINGS_PASSKEYS) { + val hubGraph = activeHubGraph ?: return@composable + val holder = viewModel( + key = "settingsPasskeys:${hubGraph.hubUrl}", + factory = viewModelFactory { PasskeysViewModelHolder(hubGraph) }, + ) + PasskeysScreen( + viewModel = holder.viewModel, + onBack = { navController.popBackStack() }, + ) + } + composable(Routes.SETTINGS_USAGE) { val hubGraph = activeHubGraph ?: return@composable val holder = viewModel( @@ -700,6 +722,7 @@ fun HapiNavigation() { }, onScanQr = { navController.navigate(Routes.PAIRING_SCAN) }, onManualEntry = { navController.navigate(Routes.PAIRING_MANUAL) }, + onPasskeySignIn = { navController.navigate(Routes.PAIRING_PASSKEY) }, onPairPrefill = viewModel::pairFromPrefill, onSwitchToPrefilledHub = viewModel::switchToPrefilledHub, onDismissPrefill = viewModel::dismissPrefill, @@ -733,6 +756,27 @@ fun HapiNavigation() { onDismissError = viewModel::dismissError, ) } + + composable(Routes.PAIRING_PASSKEY) { entry -> + val viewModel = pairingViewModel(navController, entry) + val state by viewModel.state.collectAsState() + val prefill by viewModel.prefill.collectAsState() + val context = LocalContext.current + NavigateHomeOnSuccess(navController, state) + + PasskeySignInScreen( + state = state, + initialHubUrl = prefill?.hubUrl.orEmpty(), + onSignIn = { hubUrl -> + // The system sheet needs the hosting Activity. + context.findActivity()?.let { activity -> + viewModel.signInWithPasskey(hubUrl, CredentialManagerPasskeyPlatform(activity)) + } + }, + onBack = { navController.popBackStack() }, + onDismissError = viewModel::dismissError, + ) + } } } } @@ -951,6 +995,26 @@ private class SettingsViewModelHolder( } } +private class PasskeysViewModelHolder(hubGraph: HubGraph) : ViewModel() { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) + + val viewModel = PasskeysViewModel( + gateway = object : PasskeysGateway { + private val api = hubGraph.session.api + override suspend fun list(): List = api.getPasskeys().passkeys + override suspend fun registerOptions(): String = api.passkeyRegisterOptions() + override suspend fun registerVerify(response: JsonObject, name: String?) = + api.passkeyRegisterVerify(response, name) + override suspend fun delete(id: String) = api.deletePasskey(id) + }, + scope = scope, + ) + + override fun onCleared() { + scope.cancel() + } +} + private class UsageViewModelHolder(hubGraph: HubGraph) : ViewModel() { private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default) @@ -1067,6 +1131,7 @@ private fun NavHostController.navigateClearingBackStack(route: String) { /** Why the app fell back to pairing (resolved with a Context at the emit site). */ private fun terminalNoticeRes(reason: AuthTerminalReason): Int = when (reason) { AuthTerminalReason.ACCESS_TOKEN_REJECTED -> R.string.pairing_notice_token_revoked + AuthTerminalReason.PASSKEY_SESSION_INVALID -> R.string.pairing_notice_passkey_session_invalid AuthTerminalReason.RETRY_EXHAUSTED -> R.string.pairing_notice_retry_exhausted AuthTerminalReason.MISSING_CREDENTIALS -> R.string.pairing_notice_missing_credentials } diff --git a/android/app/src/main/kotlin/app/hapi/companion/di/AppGraph.kt b/android/app/src/main/kotlin/app/hapi/companion/di/AppGraph.kt index 43fd615a..578bd6a7 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/di/AppGraph.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/di/AppGraph.kt @@ -34,6 +34,7 @@ import app.hapi.protocol.pairing.BindLink import app.hapi.protocol.wire.AuthResponse import app.hapi.protocol.wire.HapiJson import app.hapi.protocol.wire.HubHealthResponse +import app.hapi.protocol.wire.PasskeyLoginResponse import java.util.concurrent.TimeUnit import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers @@ -53,6 +54,7 @@ import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import kotlinx.coroutines.withTimeoutOrNull import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonObject import okhttp3.OkHttpClient /** One terminal auth failure, re-emitted off OkHttp threads as a flow. */ @@ -179,8 +181,9 @@ class AppGraph(context: Context) { val pairingNotice = MutableStateFlow(null) /** - * Bare client for the two pre-pairing endpoints (`GET /health`, - * `POST /api/auth`) — no interceptors: there are no credentials yet. + * Bare client for the pre-pairing endpoints (`GET /health`, + * `POST /api/auth`, passkey sign-in) — no interceptors: there are no + * credentials yet. */ private val pairingHttpClient: OkHttpClient = OkHttpClient.Builder() .connectTimeout(10, TimeUnit.SECONDS) @@ -194,6 +197,9 @@ class AppGraph(context: Context) { override suspend fun health(): HubHealthResponse = api.health() override suspend fun authenticate(accessToken: String): AuthResponse = api.authenticate(accessToken) + override suspend fun passkeyLoginOptions(): String = api.passkeyLoginOptions() + override suspend fun passkeyLoginVerify(response: JsonObject): PasskeyLoginResponse = + api.passkeyLoginVerify(response) } } diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PairingClient.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PairingClient.kt index 56302292..117bc45e 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PairingClient.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PairingClient.kt @@ -2,9 +2,11 @@ package app.hapi.companion.feature.pairing import app.hapi.protocol.wire.AuthResponse import app.hapi.protocol.wire.HubHealthResponse +import app.hapi.protocol.wire.PasskeyLoginResponse +import kotlinx.serialization.json.JsonObject /** - * The two unauthenticated endpoints pairing needs, as a seam so + * The unauthenticated endpoints pairing needs, as a seam so * [PairingViewModel] is unit-testable without OkHttp. Production adapts * `HapiApi` (see `AppGraph.pairingClientFactory`); both methods throw * `ApiError` on non-2xx and `IOException` when the hub is unreachable. @@ -15,6 +17,12 @@ interface PairingClient { /** `POST /api/auth` — access-token → JWT exchange; 401 = token rejected. */ suspend fun authenticate(accessToken: String): AuthResponse + + /** `POST /api/passkey/login/options` `{"client":"native"}` — raw options JSON; 404 `no_passkeys`. */ + suspend fun passkeyLoginOptions(): String + + /** `POST /api/passkey/login/verify` — JWT + passkey session; 401 on a bad assertion. */ + suspend fun passkeyLoginVerify(response: JsonObject): PasskeyLoginResponse } /** Builds a [PairingClient] for one candidate hub (normalized origin). */ diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PairingScreen.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PairingScreen.kt index f6296ae5..a8d76bb9 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PairingScreen.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PairingScreen.kt @@ -27,10 +27,11 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import app.hapi.companion.R +import app.hapi.companion.feature.passkey.passkeyIssueText /** * Pairing landing: explains the self-hosted model, offers Scan QR / Manual - * entry, renders the deep-link confirm card ([prefill]) and the "why am I + * entry / passkey sign-in, renders the deep-link confirm card ([prefill]) and the "why am I * here" [notice] banner (auth-terminal sign-outs, bad links). */ @Composable @@ -41,6 +42,7 @@ fun PairingScreen( onDismissNotice: () -> Unit, onScanQr: () -> Unit, onManualEntry: () -> Unit, + onPasskeySignIn: () -> Unit, onPairPrefill: () -> Unit, onSwitchToPrefilledHub: () -> Unit, onDismissPrefill: () -> Unit, @@ -106,6 +108,14 @@ fun PairingScreen( ) { Text(stringResource(R.string.pairing_manual_entry)) } + Spacer(modifier = Modifier.height(8.dp)) + TextButton( + onClick = onPasskeySignIn, + enabled = state !is PairingUiState.Validating, + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(R.string.pairing_passkey_entry)) + } app.hapi.companion.ui.components.PrivacyPolicyLink() } } @@ -242,4 +252,5 @@ internal fun pairingErrorText(error: PairingError): String = when (error) { error.supportedVersion, ) is PairingError.AuthFailed -> stringResource(R.string.pairing_error_auth_failed, error.httpStatus) + is PairingError.Passkey -> passkeyIssueText(error.issue) } diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PairingViewModel.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PairingViewModel.kt index 269c1d51..5c9960fc 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PairingViewModel.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PairingViewModel.kt @@ -2,12 +2,16 @@ package app.hapi.companion.feature.pairing import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope +import app.hapi.companion.feature.passkey.PasskeyIssue +import app.hapi.companion.feature.passkey.PasskeyPlatform +import app.hapi.companion.feature.passkey.passkeyIssueOf import app.hapi.data.api.ApiError import app.hapi.data.auth.CredentialStore import app.hapi.data.auth.HubCredentials import app.hapi.data.auth.HubRegistry import app.hapi.data.auth.HubUrls import app.hapi.protocol.pairing.BindLink +import app.hapi.protocol.wire.NativePasskeys import app.hapi.protocol.wire.SUPPORTED_PROTOCOL_VERSION import java.io.IOException import kotlin.coroutines.cancellation.CancellationException @@ -45,6 +49,9 @@ sealed interface PairingError { data class NotAHub(val hubUrl: String) : PairingError data class ProtocolMismatch(val hubVersion: Int, val supportedVersion: Int) : PairingError data class AuthFailed(val httpStatus: Int) : PairingError + + /** Passkey sign-in failed (user cancellations never land here). */ + data class Passkey(val issue: PasskeyIssue) : PairingError } /** A `hapicompanion://bind` deep link waiting for user confirmation. */ @@ -62,6 +69,11 @@ data class BindPrefill( * `POST /api/auth` exchange → persist [HubCredentials] → register + activate * in the [HubRegistry] → [PairingUiState.Success]. * + * [signInWithPasskey] is the token-free alternative + * (`docs/api/client-contract/auth.md#passkeys-native`): same probe, then + * login options → RP-ID check → platform ceremony → verify, storing the + * returned passkey session (no access token) as the hub's credential. + * * Shared by the landing / QR-scan / manual-entry destinations (scoped to the * pairing nav graph), so an attempt started from a scan result reports into * the same state the other screens render. @@ -144,9 +156,62 @@ class PairingViewModel( } } - private suspend fun runPairing(hubUrl: String, accessToken: String): PairingUiState { - val client = clientFactory.create(hubUrl) + /** + * Signs in to [hubUrl] with a passkey instead of an access token; no-op + * while an attempt is validating. A dismissed system sheet returns to + * [PairingUiState.Idle] silently. [platform] wraps the hosting Activity + * and is only held for the duration of the attempt. + */ + fun signInWithPasskey(hubUrl: String, platform: PasskeyPlatform) { + if (mutableState.value == PairingUiState.Validating) return + val normalized = HubUrls.normalize(hubUrl) + if (normalized == null) { + mutableState.value = PairingUiState.Error(PairingError.InvalidUrl) + return + } + mutableState.value = PairingUiState.Validating + viewModelScope.launch { + mutableState.value = runPasskeySignIn(normalized, platform) + } + } + private suspend fun runPasskeySignIn(hubUrl: String, platform: PasskeyPlatform): PairingUiState { + val client = clientFactory.create(hubUrl) + probeHub(client, hubUrl)?.let { return it } + + val login = try { + val options = client.passkeyLoginOptions() + NativePasskeys.requireRequestRpId(options) + val assertion = platform.getPasskey(options) + client.passkeyLoginVerify(NativePasskeys.credentialResponse(assertion)) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (error: Exception) { + val issue = passkeyIssueOf(error) ?: return PairingUiState.Idle + return PairingUiState.Error( + if (issue == PasskeyIssue.Unreachable) PairingError.Unreachable(hubUrl) else PairingError.Passkey(issue), + ) + } + + // A passkey sign-in replaces any previous pairing secret for this hub: + // the stored entry authenticates by passkey session from now on. + withContext(ioDispatcher) { + credentialStore.set( + HubCredentials( + hubUrl = hubUrl, + passkeySession = login.passkeySession, + jwt = login.token, + jwtObtainedAtMs = nowMs(), + ) + ) + } + registry.addHub(hubUrl, makeActive = true) + mutablePrefill.value = null + return PairingUiState.Success(hubUrl) + } + + /** `GET /health` reachability + protocol check; null when the hub is usable. */ + private suspend fun probeHub(client: PairingClient, hubUrl: String): PairingUiState.Error? { val health = try { client.health() } catch (cancellation: CancellationException) { @@ -163,6 +228,12 @@ class PairingViewModel( PairingError.ProtocolMismatch(health.protocolVersion, SUPPORTED_PROTOCOL_VERSION), ) } + return null + } + + private suspend fun runPairing(hubUrl: String, accessToken: String): PairingUiState { + val client = clientFactory.create(hubUrl) + probeHub(client, hubUrl)?.let { return it } val auth = try { client.authenticate(accessToken) diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PasskeySignInScreen.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PasskeySignInScreen.kt new file mode 100644 index 00000000..f7f45558 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/pairing/PasskeySignInScreen.kt @@ -0,0 +1,101 @@ +package app.hapi.companion.feature.pairing + +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.height +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.safeDrawingPadding +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.Button +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.runtime.Composable +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +import androidx.compose.runtime.setValue +import androidx.compose.ui.Modifier +import androidx.compose.ui.res.stringResource +import androidx.compose.ui.text.input.KeyboardCapitalization +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import app.hapi.companion.R + +/** + * Passkey sign-in: only the hub URL is needed — the system sheet offers this + * hub's passkeys (`allowCredentials`), and the hub returns a JWT plus a + * passkey session that replaces the access token for this hub. + */ +@Composable +fun PasskeySignInScreen( + state: PairingUiState, + initialHubUrl: String, + onSignIn: (hubUrl: String) -> Unit, + onBack: () -> Unit, + onDismissError: () -> Unit, +) { + var hubUrl by rememberSaveable { mutableStateOf(initialHubUrl) } + val validating = state is PairingUiState.Validating + + Surface(modifier = Modifier.fillMaxSize()) { + Column( + modifier = Modifier + .fillMaxSize() + .safeDrawingPadding() + .verticalScroll(rememberScrollState()) + .padding(24.dp), + verticalArrangement = Arrangement.Center, + ) { + Text( + text = stringResource(R.string.pairing_passkey_title), + style = MaterialTheme.typography.headlineMedium, + color = MaterialTheme.colorScheme.primary, + ) + Spacer(modifier = Modifier.height(8.dp)) + Text( + text = stringResource(R.string.pairing_passkey_hint), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + Spacer(modifier = Modifier.height(24.dp)) + + OutlinedTextField( + value = hubUrl, + onValueChange = { hubUrl = it }, + label = { Text(stringResource(R.string.pairing_hub_url_label)) }, + placeholder = { Text(stringResource(R.string.pairing_hub_url_placeholder)) }, + singleLine = true, + enabled = !validating, + keyboardOptions = KeyboardOptions( + capitalization = KeyboardCapitalization.None, + autoCorrectEnabled = false, + keyboardType = KeyboardType.Uri, + ), + modifier = Modifier.fillMaxWidth(), + ) + Spacer(modifier = Modifier.height(24.dp)) + + PairingStatus(state = state, onDismissError = onDismissError) + + Button( + onClick = { onSignIn(hubUrl) }, + enabled = !validating && hubUrl.isNotBlank(), + modifier = Modifier.fillMaxWidth(), + ) { + Text(stringResource(R.string.pairing_passkey_button)) + } + Spacer(modifier = Modifier.height(8.dp)) + TextButton(onClick = onBack, enabled = !validating, modifier = Modifier.fillMaxWidth()) { + Text(stringResource(R.string.pairing_back)) + } + } + } +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/passkey/CredentialManagerPasskeyPlatform.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/passkey/CredentialManagerPasskeyPlatform.kt new file mode 100644 index 00000000..1f1b93a6 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/passkey/CredentialManagerPasskeyPlatform.kt @@ -0,0 +1,93 @@ +package app.hapi.companion.feature.passkey + +import android.app.Activity +import android.content.Context +import android.content.ContextWrapper +import android.os.Build +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.CreateCredentialNoCreateOptionException +import androidx.credentials.exceptions.CreateCredentialProviderConfigurationException +import androidx.credentials.exceptions.CreateCredentialUnsupportedException +import androidx.credentials.exceptions.GetCredentialCancellationException +import androidx.credentials.exceptions.GetCredentialException +import androidx.credentials.exceptions.GetCredentialProviderConfigurationException +import androidx.credentials.exceptions.GetCredentialUnsupportedException +import androidx.credentials.exceptions.NoCredentialException + +/** + * [PasskeyPlatform] over Jetpack Credential Manager. The hub's options JSON + * goes in as `requestJson` untouched; `registrationResponseJson` / + * `authenticationResponseJson` come back for the verify call. + * + * Passkeys need Android 9+ (API 28); older devices get + * [PasskeyCeremonyException.Unavailable]. Needs an [Activity]: the system sheet is launched on top of it. Ceremonies + * for RP ID `hapi.run` only succeed when `https://hapi.run/.well-known/assetlinks.json` + * lists this build's package + signing-certificate SHA-256 (see the Android + * README, "Passkeys"). + */ +class CredentialManagerPasskeyPlatform(private val activity: Activity) : PasskeyPlatform { + + private val manager: CredentialManager = CredentialManager.create(activity) + + override suspend fun createPasskey(requestJson: String): String { + // Credential Manager supports passkeys from Android 9 (minSdk is 26). + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { + throw PasskeyCeremonyException.Unavailable("Passkeys require Android 9 or newer") + } + val result = try { + manager.createCredential(activity, CreatePublicKeyCredentialRequest(requestJson)) + } catch (_: CreateCredentialCancellationException) { + throw PasskeyCeremonyException.Cancelled() + } catch (e: CreateCredentialNoCreateOptionException) { + throw PasskeyCeremonyException.Unavailable(e.errorMessage?.toString()) + } catch (e: CreateCredentialProviderConfigurationException) { + throw PasskeyCeremonyException.Unavailable(e.errorMessage?.toString()) + } catch (e: CreateCredentialUnsupportedException) { + throw PasskeyCeremonyException.Unavailable(e.errorMessage?.toString()) + } catch (e: CreateCredentialException) { + throw PasskeyCeremonyException.Failed(e.errorMessage?.toString() ?: e.type) + } + val response = result as? CreatePublicKeyCredentialResponse + ?: throw PasskeyCeremonyException.Failed("Unexpected credential type: ${result.type}") + return response.registrationResponseJson + } + + override suspend fun getPasskey(requestJson: String): String { + if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) { + throw PasskeyCeremonyException.Unavailable("Passkeys require Android 9 or newer") + } + val result = try { + manager.getCredential( + activity, + GetCredentialRequest(listOf(GetPublicKeyCredentialOption(requestJson))), + ) + } catch (_: GetCredentialCancellationException) { + throw PasskeyCeremonyException.Cancelled() + } catch (_: NoCredentialException) { + throw PasskeyCeremonyException.NoCredential() + } catch (e: GetCredentialProviderConfigurationException) { + throw PasskeyCeremonyException.Unavailable(e.errorMessage?.toString()) + } catch (e: GetCredentialUnsupportedException) { + throw PasskeyCeremonyException.Unavailable(e.errorMessage?.toString()) + } catch (e: GetCredentialException) { + throw PasskeyCeremonyException.Failed(e.errorMessage?.toString() ?: e.type) + } + val credential = result.credential as? PublicKeyCredential + ?: throw PasskeyCeremonyException.Failed("Unexpected credential type: ${result.credential.type}") + return credential.authenticationResponseJson + } +} + +/** The hosting [Activity] behind a (possibly wrapped) Compose context, or null. */ +tailrec fun Context.findActivity(): Activity? = when (this) { + is Activity -> this + is ContextWrapper -> baseContext.findActivity() + else -> null +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/passkey/PasskeyPlatform.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/passkey/PasskeyPlatform.kt new file mode 100644 index 00000000..40483616 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/passkey/PasskeyPlatform.kt @@ -0,0 +1,95 @@ +package app.hapi.companion.feature.passkey + +import app.hapi.data.api.ApiError +import app.hapi.protocol.wire.PasskeyRpMismatchException +import java.io.IOException + +/** + * Platform passkey ceremony seam. Production is + * [CredentialManagerPasskeyPlatform] (needs an Activity); JVM tests script a + * fake. Both methods take the hub's WebAuthn options JSON verbatim and return + * the platform's response JSON, or throw [PasskeyCeremonyException]. + */ +interface PasskeyPlatform { + /** `PublicKeyCredentialCreationOptionsJSON` → `RegistrationResponseJSON`. */ + suspend fun createPasskey(requestJson: String): String + + /** `PublicKeyCredentialRequestOptionsJSON` → `AuthenticationResponseJSON`. */ + suspend fun getPasskey(requestJson: String): String +} + +/** Platform ceremony failures, normalized away from Credential Manager types. */ +sealed class PasskeyCeremonyException(message: String?) : Exception(message) { + /** The user dismissed the sheet — silent, not an error. */ + class Cancelled : PasskeyCeremonyException("cancelled") + + /** No passkey on this device matches the hub's `allowCredentials`. */ + class NoCredential : PasskeyCeremonyException("no credential") + + /** No passkey provider / unsupported device configuration. */ + class Unavailable(message: String?) : PasskeyCeremonyException(message) + + /** Anything else the provider reported (incl. WebAuthn DOM errors). */ + class Failed(message: String?) : PasskeyCeremonyException(message) +} + +/** + * User-facing passkey failure, shared by pairing (sign-in) and settings + * (add/delete). String-free so ViewModel tests assert it directly; screens + * localize via `passkeyIssueText`. + */ +sealed interface PasskeyIssue { + /** `404 no_passkeys` — the hub has no app passkeys yet. */ + data object NoneRegistered : PasskeyIssue + + /** The device has no passkey for this hub. */ + data object NoCredentialOnDevice : PasskeyIssue + + /** No passkey provider is available on this device. */ + data object Unavailable : PasskeyIssue + + /** The hub's options target another relying party; ceremony refused. */ + data class RpMismatch(val actual: String?) : PasskeyIssue + + /** `401 passkey_revoked` — registered under a rotated `CLI_API_TOKEN`. */ + data object Revoked : PasskeyIssue + + /** Challenge expired / unknown passkey / signature check failed: retry. */ + data object VerificationFailed : PasskeyIssue + + /** `409` — this authenticator is already registered with the hub. */ + data object AlreadyRegistered : PasskeyIssue + + /** The hub could not be reached. */ + data object Unreachable : PasskeyIssue + + /** Other HTTP failure. */ + data class Http(val status: Int) : PasskeyIssue + + /** Platform ceremony failure with the provider's message, if any. */ + data class Failed(val message: String?) : PasskeyIssue +} + +/** + * Maps a failure of any passkey step (options → ceremony → verify) to a + * [PasskeyIssue]; null for a user cancellation, which must stay silent. + */ +fun passkeyIssueOf(error: Throwable): PasskeyIssue? = when (error) { + is PasskeyCeremonyException.Cancelled -> null + is PasskeyCeremonyException.NoCredential -> PasskeyIssue.NoCredentialOnDevice + is PasskeyCeremonyException.Unavailable -> PasskeyIssue.Unavailable + is PasskeyCeremonyException.Failed -> PasskeyIssue.Failed(error.message) + is PasskeyRpMismatchException -> PasskeyIssue.RpMismatch(error.actual) + is ApiError -> when { + error.status == 404 && error.code == NO_PASSKEYS -> PasskeyIssue.NoneRegistered + error.status == 401 && error.code == PASSKEY_REVOKED -> PasskeyIssue.Revoked + error.status == 401 || error.status == 400 -> PasskeyIssue.VerificationFailed + error.status == 409 -> PasskeyIssue.AlreadyRegistered + else -> PasskeyIssue.Http(error.status) + } + is IOException -> PasskeyIssue.Unreachable + else -> PasskeyIssue.Failed(error.message) +} + +private const val NO_PASSKEYS = "no_passkeys" +private const val PASSKEY_REVOKED = "passkey_revoked" diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/passkey/PasskeyStrings.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/passkey/PasskeyStrings.kt new file mode 100644 index 00000000..33e455cb --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/passkey/PasskeyStrings.kt @@ -0,0 +1,27 @@ +package app.hapi.companion.feature.passkey + +import androidx.compose.runtime.Composable +import androidx.compose.ui.res.stringResource +import app.hapi.companion.R +import app.hapi.protocol.wire.NativePasskeys + +/** Localize a [PasskeyIssue] (pairing sign-in + settings management). */ +@Composable +fun passkeyIssueText(issue: PasskeyIssue): String = when (issue) { + PasskeyIssue.NoneRegistered -> stringResource(R.string.passkey_error_none_registered) + PasskeyIssue.NoCredentialOnDevice -> stringResource(R.string.passkey_error_no_credential) + PasskeyIssue.Unavailable -> stringResource(R.string.passkey_error_unavailable) + is PasskeyIssue.RpMismatch -> stringResource( + R.string.passkey_error_rp_mismatch, + issue.actual ?: "?", + NativePasskeys.RP_ID, + ) + PasskeyIssue.Revoked -> stringResource(R.string.passkey_error_revoked) + PasskeyIssue.VerificationFailed -> stringResource(R.string.passkey_error_verification_failed) + PasskeyIssue.AlreadyRegistered -> stringResource(R.string.passkey_error_already_registered) + PasskeyIssue.Unreachable -> stringResource(R.string.passkey_error_unreachable) + is PasskeyIssue.Http -> stringResource(R.string.passkey_error_http, issue.status) + is PasskeyIssue.Failed -> issue.message?.takeIf { it.isNotBlank() } + ?.let { stringResource(R.string.passkey_error_failed_detail, it) } + ?: stringResource(R.string.passkey_error_failed) +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/settings/PasskeysScreen.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/settings/PasskeysScreen.kt new file mode 100644 index 00000000..97ee85d6 --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/settings/PasskeysScreen.kt @@ -0,0 +1,363 @@ +package app.hapi.companion.feature.settings + +import android.os.Build +import android.text.format.DateUtils +import androidx.compose.foundation.layout.Arrangement +import androidx.compose.foundation.layout.Box +import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.Row +import androidx.compose.foundation.layout.fillMaxSize +import androidx.compose.foundation.layout.fillMaxWidth +import androidx.compose.foundation.layout.padding +import androidx.compose.foundation.layout.size +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.filled.Delete +import androidx.compose.material3.AlertDialog +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.CardDefaults +import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.ExperimentalMaterial3Api +import androidx.compose.material3.HorizontalDivider +import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton +import androidx.compose.material3.MaterialTheme +import androidx.compose.material3.OutlinedTextField +import androidx.compose.material3.Scaffold +import androidx.compose.material3.Surface +import androidx.compose.material3.Text +import androidx.compose.material3.TextButton +import androidx.compose.material3.TopAppBar +import androidx.compose.runtime.Composable +import androidx.compose.runtime.LaunchedEffect +import androidx.compose.runtime.collectAsState +import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.saveable.rememberSaveable +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.res.stringResource +import androidx.compose.ui.unit.dp +import app.hapi.companion.R +import app.hapi.companion.feature.passkey.CredentialManagerPasskeyPlatform +import app.hapi.companion.feature.passkey.findActivity +import app.hapi.companion.feature.passkey.passkeyIssueText +import app.hapi.protocol.wire.NativePasskeys +import app.hapi.protocol.wire.PasskeySummary + +/** + * Settings → Passkeys (hub-scoped): this namespace's passkeys with + * created/last-used dates, an "inactive" tag for passkeys invalidated by a + * `CLI_API_TOKEN` rotation, and a "web" tag for passkeys of another RP ID + * (usable in the web app only). Add registers a `hapi.run` passkey through + * Credential Manager; delete asks for confirmation first. + */ +@OptIn(ExperimentalMaterial3Api::class) +@Composable +fun PasskeysScreen( + viewModel: PasskeysViewModel, + onBack: () -> Unit, +) { + LaunchedEffect(viewModel) { viewModel.start() } + val state by viewModel.state.collectAsState() + val busy by viewModel.busy.collectAsState() + val notice by viewModel.notice.collectAsState() + val context = LocalContext.current + + var showAddDialog by rememberSaveable { mutableStateOf(false) } + var pendingDeleteId by rememberSaveable { mutableStateOf(null) } + + Scaffold( + topBar = { + TopAppBar( + title = { Text(stringResource(R.string.settings_passkeys)) }, + navigationIcon = { + IconButton(onClick = onBack) { + Icon( + Icons.AutoMirrored.Filled.ArrowBack, + contentDescription = stringResource(R.string.settings_back), + ) + } + }, + ) + }, + ) { padding -> + Column( + modifier = Modifier + .fillMaxSize() + .padding(padding) + .verticalScroll(rememberScrollState()) + .padding(16.dp), + verticalArrangement = Arrangement.spacedBy(16.dp), + ) { + Text( + text = stringResource(R.string.settings_passkeys_description), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + + notice?.let { current -> + PasskeysNoticeCard(notice = current, onDismiss = viewModel::dismissNotice) + } + + Button( + onClick = { showAddDialog = true }, + enabled = busy == null, + modifier = Modifier.fillMaxWidth(), + ) { + if (busy == PasskeysBusy.Adding) { + CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp) + } else { + Text(stringResource(R.string.settings_passkeys_add)) + } + } + + when (val current = state) { + is PasskeysUiState.Loading -> Box( + modifier = Modifier + .fillMaxWidth() + .padding(vertical = 48.dp), + contentAlignment = Alignment.Center, + ) { CircularProgressIndicator() } + + is PasskeysUiState.Error -> DashboardError( + isForbidden = false, + message = current.message, + onRetry = viewModel::refresh, + ) + + is PasskeysUiState.Data -> if (current.passkeys.isEmpty()) { + Text( + text = stringResource(R.string.settings_passkeys_empty), + style = MaterialTheme.typography.bodyMedium, + color = MaterialTheme.colorScheme.onSurfaceVariant, + ) + } else { + Surface( + shape = MaterialTheme.shapes.medium, + color = MaterialTheme.colorScheme.surfaceContainerLow, + modifier = Modifier.fillMaxWidth(), + ) { + Column { + current.passkeys.forEachIndexed { index, passkey -> + if (index > 0) { + HorizontalDivider( + color = MaterialTheme.colorScheme.outlineVariant, + modifier = Modifier.padding(horizontal = 16.dp), + ) + } + PasskeyRow( + passkey = passkey, + deleting = busy == PasskeysBusy.Deleting(passkey.id), + enabled = busy == null, + onDelete = { pendingDeleteId = passkey.id }, + ) + } + } + } + } + } + } + } + + if (showAddDialog) { + AddPasskeyDialog( + onConfirm = { name -> + showAddDialog = false + // The system sheet needs the hosting Activity. + context.findActivity()?.let { activity -> + viewModel.addPasskey(name, CredentialManagerPasskeyPlatform(activity)) + } + }, + onDismiss = { showAddDialog = false }, + ) + } + + val deleteTarget = pendingDeleteId?.let { id -> + (state as? PasskeysUiState.Data)?.passkeys?.firstOrNull { it.id == id } + } + if (deleteTarget != null) { + AlertDialog( + onDismissRequest = { pendingDeleteId = null }, + title = { Text(stringResource(R.string.settings_passkeys_delete_title)) }, + text = { + Text( + stringResource( + R.string.settings_passkeys_delete_message, + passkeyDisplayName(deleteTarget), + ), + ) + }, + confirmButton = { + TextButton( + onClick = { + pendingDeleteId = null + viewModel.deletePasskey(deleteTarget.id) + }, + ) { + Text( + stringResource(R.string.settings_passkeys_delete_confirm), + color = MaterialTheme.colorScheme.error, + ) + } + }, + dismissButton = { + TextButton(onClick = { pendingDeleteId = null }) { + Text(stringResource(R.string.settings_cancel)) + } + }, + ) + } +} + +@Composable +private fun PasskeyRow( + passkey: PasskeySummary, + deleting: Boolean, + enabled: Boolean, + onDelete: () -> Unit, +) { + val context = LocalContext.current + Row( + modifier = Modifier + .fillMaxWidth() + .padding(start = 16.dp, end = 4.dp, top = 12.dp, bottom = 12.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(modifier = Modifier.weight(1f)) { + Text(text = passkeyDisplayName(passkey), style = MaterialTheme.typography.bodyLarge) + val created = DateUtils.formatDateTime(context, passkey.createdAt, DATE_FLAGS) + val lastUsed = passkey.lastUsedAt?.let { DateUtils.formatDateTime(context, it, DATE_FLAGS) } + Text( + text = if (lastUsed != null) { + stringResource(R.string.settings_passkeys_dates, created, lastUsed) + } else { + stringResource(R.string.settings_passkeys_dates_unused, created) + }, + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 2.dp), + ) + val tags = buildList { + if (!passkey.isAppPasskey) add(stringResource(R.string.settings_passkeys_tag_web)) + if (!passkey.valid) add(stringResource(R.string.settings_passkeys_tag_inactive)) + } + if (tags.isNotEmpty()) { + Text( + text = tags.joinToString(" · "), + style = MaterialTheme.typography.labelMedium, + color = if (!passkey.valid) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.tertiary, + modifier = Modifier.padding(top = 4.dp), + ) + } + if (!passkey.isAppPasskey) { + Text( + text = stringResource(R.string.settings_passkeys_web_note), + style = MaterialTheme.typography.bodySmall, + color = MaterialTheme.colorScheme.onSurfaceVariant, + modifier = Modifier.padding(top = 2.dp), + ) + } + } + if (deleting) { + Box(modifier = Modifier.size(48.dp), contentAlignment = Alignment.Center) { + CircularProgressIndicator(modifier = Modifier.size(20.dp), strokeWidth = 2.dp) + } + } else { + IconButton(onClick = onDelete, enabled = enabled) { + Icon( + Icons.Default.Delete, + contentDescription = stringResource(R.string.settings_passkeys_delete_title), + ) + } + } + } +} + +@Composable +private fun AddPasskeyDialog( + onConfirm: (String) -> Unit, + onDismiss: () -> Unit, +) { + var name by rememberSaveable { mutableStateOf(defaultPasskeyName()) } + AlertDialog( + onDismissRequest = onDismiss, + title = { Text(stringResource(R.string.settings_passkeys_add)) }, + text = { + Column(verticalArrangement = Arrangement.spacedBy(8.dp)) { + Text( + text = stringResource(R.string.settings_passkeys_add_message), + style = MaterialTheme.typography.bodyMedium, + ) + OutlinedTextField( + value = name, + onValueChange = { name = it.take(NativePasskeys.MAX_NAME_LENGTH) }, + label = { Text(stringResource(R.string.settings_passkeys_name_label)) }, + singleLine = true, + keyboardOptions = KeyboardOptions(autoCorrectEnabled = false), + modifier = Modifier.fillMaxWidth(), + ) + } + }, + confirmButton = { + TextButton(onClick = { onConfirm(name) }) { + Text(stringResource(R.string.settings_passkeys_add_confirm)) + } + }, + dismissButton = { + TextButton(onClick = onDismiss) { + Text(stringResource(R.string.settings_cancel)) + } + }, + ) +} + +@Composable +private fun PasskeysNoticeCard(notice: PasskeysNotice, onDismiss: () -> Unit) { + val isError = notice is PasskeysNotice.Failed + Card( + modifier = Modifier.fillMaxWidth(), + colors = CardDefaults.cardColors( + containerColor = if (isError) { + MaterialTheme.colorScheme.errorContainer + } else { + MaterialTheme.colorScheme.secondaryContainer + }, + contentColor = if (isError) { + MaterialTheme.colorScheme.onErrorContainer + } else { + MaterialTheme.colorScheme.onSecondaryContainer + }, + ), + ) { + Column(modifier = Modifier.padding(16.dp)) { + Text( + text = when (notice) { + PasskeysNotice.Added -> stringResource(R.string.settings_passkeys_added) + PasskeysNotice.Deleted -> stringResource(R.string.settings_passkeys_deleted) + is PasskeysNotice.Failed -> passkeyIssueText(notice.issue) + }, + style = MaterialTheme.typography.bodyMedium, + ) + TextButton(onClick = onDismiss, modifier = Modifier.align(Alignment.End)) { + Text(stringResource(R.string.pairing_notice_dismiss)) + } + } + } +} + +@Composable +private fun passkeyDisplayName(passkey: PasskeySummary): String = + passkey.name?.takeIf { it.isNotBlank() } ?: stringResource(R.string.settings_passkeys_unnamed) + +/** Default passkey name: the device model (e.g. "Pixel 9"), clamped to the hub limit. */ +internal fun defaultPasskeyName(model: String? = Build.MODEL): String = + model?.trim()?.take(NativePasskeys.MAX_NAME_LENGTH).orEmpty() + +private const val DATE_FLAGS = DateUtils.FORMAT_SHOW_DATE or DateUtils.FORMAT_SHOW_YEAR or DateUtils.FORMAT_ABBREV_MONTH diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/settings/PasskeysViewModel.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/settings/PasskeysViewModel.kt new file mode 100644 index 00000000..2839f83d --- /dev/null +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/settings/PasskeysViewModel.kt @@ -0,0 +1,152 @@ +package app.hapi.companion.feature.settings + +import app.hapi.companion.feature.passkey.PasskeyIssue +import app.hapi.companion.feature.passkey.PasskeyPlatform +import app.hapi.companion.feature.passkey.passkeyIssueOf +import app.hapi.protocol.wire.NativePasskeys +import app.hapi.protocol.wire.PasskeySummary +import kotlin.coroutines.cancellation.CancellationException +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Job +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.launch +import kotlinx.serialization.json.JsonObject + +/** Transport seam over the authed `HapiApi` passkey endpoints (JVM-testable). */ +interface PasskeysGateway { + /** `GET /api/passkeys`. */ + suspend fun list(): List + + /** `POST /api/passkey/register/options` `{"client":"native"}` — raw options JSON. */ + suspend fun registerOptions(): String + + /** `POST /api/passkey/register/verify`. */ + suspend fun registerVerify(response: JsonObject, name: String?) + + /** `DELETE /api/passkeys/:id`. */ + suspend fun delete(id: String) +} + +sealed interface PasskeysUiState { + data object Loading : PasskeysUiState + data class Error(val message: String?) : PasskeysUiState + data class Data(val passkeys: List) : PasskeysUiState +} + +/** The single in-flight mutation (buttons disable while non-null). */ +sealed interface PasskeysBusy { + data object Adding : PasskeysBusy + data class Deleting(val id: String) : PasskeysBusy +} + +/** One-shot outcome banner for the last add/delete. */ +sealed interface PasskeysNotice { + data object Added : PasskeysNotice + data object Deleted : PasskeysNotice + data class Failed(val issue: PasskeyIssue) : PasskeysNotice +} + +/** True for passkeys the app can sign in with (registered for the native RP ID). */ +val PasskeySummary.isAppPasskey: Boolean get() = rpId == NativePasskeys.RP_ID + +/** + * Settings → Passkeys: list this namespace's passkeys, register one for the + * native RP ID (`hapi.run`), and delete with the screen's confirmation. + * + * Register: options (`{"client":"native"}`) → refuse unless `rp.id` is the + * compiled RP ID → platform ceremony → verify with the chosen name → reload. + * A dismissed sheet is silent. Web passkeys (any other `rpId`) are listed for + * completeness but cannot sign in to the app. + */ +class PasskeysViewModel( + private val gateway: PasskeysGateway, + private val scope: CoroutineScope, +) { + private val mutableState = MutableStateFlow(PasskeysUiState.Loading) + val state: StateFlow = mutableState.asStateFlow() + + private val mutableBusy = MutableStateFlow(null) + val busy: StateFlow = mutableBusy.asStateFlow() + + private val mutableNotice = MutableStateFlow(null) + val notice: StateFlow = mutableNotice.asStateFlow() + + private var loadJob: Job? = null + + fun start() { + if (loadJob == null) refresh() + } + + fun refresh() { + loadJob?.cancel() + if (mutableState.value !is PasskeysUiState.Data) mutableState.value = PasskeysUiState.Loading + loadJob = scope.launch { reload() } + } + + fun dismissNotice() { + mutableNotice.value = null + } + + /** Registers a new app passkey named [name] (trimmed/clamped; blank → unnamed). */ + fun addPasskey(name: String, platform: PasskeyPlatform) { + if (mutableBusy.value != null) return + mutableBusy.value = PasskeysBusy.Adding + mutableNotice.value = null + scope.launch { + try { + val options = gateway.registerOptions() + NativePasskeys.requireCreationRpId(options) + val registration = platform.createPasskey(options) + gateway.registerVerify( + NativePasskeys.credentialResponse(registration), + NativePasskeys.normalizeName(name), + ) + mutableNotice.value = PasskeysNotice.Added + reload() + } catch (cancellation: CancellationException) { + throw cancellation + } catch (error: Exception) { + passkeyIssueOf(error)?.let { mutableNotice.value = PasskeysNotice.Failed(it) } + } finally { + mutableBusy.value = null + } + } + } + + /** Deletes [id] (the screen confirms first); revokes its sessions hub-side. */ + fun deletePasskey(id: String) { + if (mutableBusy.value != null) return + mutableBusy.value = PasskeysBusy.Deleting(id) + mutableNotice.value = null + scope.launch { + try { + gateway.delete(id) + mutableNotice.value = PasskeysNotice.Deleted + reload() + } catch (cancellation: CancellationException) { + throw cancellation + } catch (error: Exception) { + passkeyIssueOf(error)?.let { mutableNotice.value = PasskeysNotice.Failed(it) } + } finally { + mutableBusy.value = null + } + } + } + + private suspend fun reload() { + mutableState.value = try { + PasskeysUiState.Data( + gateway.list().sortedWith( + compareByDescending { it.isAppPasskey }.thenByDescending { it.createdAt }, + ), + ) + } catch (cancellation: CancellationException) { + throw cancellation + } catch (error: Exception) { + // A failed background reload keeps the last good list on screen. + mutableState.value as? PasskeysUiState.Data ?: PasskeysUiState.Error(error.message) + } + } +} diff --git a/android/app/src/main/kotlin/app/hapi/companion/feature/settings/SettingsHubCatalog.kt b/android/app/src/main/kotlin/app/hapi/companion/feature/settings/SettingsHubCatalog.kt index 77d0dbb2..7e50d588 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/feature/settings/SettingsHubCatalog.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/feature/settings/SettingsHubCatalog.kt @@ -4,6 +4,7 @@ import androidx.annotation.StringRes import androidx.compose.material.icons.Icons import androidx.compose.material.icons.automirrored.filled.List import androidx.compose.material.icons.filled.DateRange +import androidx.compose.material.icons.filled.Lock import androidx.compose.material.icons.filled.Settings import androidx.compose.ui.graphics.vector.ImageVector import app.hapi.companion.R @@ -39,8 +40,8 @@ class SettingsHubEntry( /** * Declarative category list behind the settings hub. Mirrors the web's * `web/src/routes/settings/categories.ts` where the branch has content: - * general (appearance/language/about) plus the owner-only usage and storage - * dashboards. Display/Chat/Voice/Machines join here in later slices. + * general (appearance/language/about), passkeys, plus the owner-only usage + * and storage dashboards. Display/Chat/Voice/Machines join here in later slices. */ object SettingsHubCatalog { @@ -51,6 +52,14 @@ object SettingsHubCatalog { descriptionRes = R.string.settings_category_general_summary, icon = Icons.Default.Settings, ), + // Namespace-scoped, not owner-only: every signed-in namespace manages + // its own passkeys (web twin: Settings → Passkeys). + SettingsHubEntry( + route = Routes.SETTINGS_PASSKEYS, + titleRes = R.string.settings_passkeys, + descriptionRes = R.string.settings_passkeys_summary, + icon = Icons.Default.Lock, + ), SettingsHubEntry( route = Routes.SETTINGS_USAGE, titleRes = R.string.settings_usage, diff --git a/android/app/src/main/res/values-ru/strings.xml b/android/app/src/main/res/values-ru/strings.xml index 9d2da25b..d2aa0235 100644 --- a/android/app/src/main/res/values-ru/strings.xml +++ b/android/app/src/main/res/values-ru/strings.xml @@ -656,6 +656,11 @@ Сопряжение этого устройства отозвано — токен доступа хаба изменился. Сопрягите заново, чтобы продолжить. Хаб продолжал отклонять сессию этого устройства. Сопрягите заново, чтобы продолжить. Сохранённые учётные данные для этого хаба пропали. Сопрягите заново, чтобы продолжить. + Войти с ключом доступа + Вход с ключом доступа + Введите адрес хаба и выберите ключ доступа, сохранённый для него этим приложением (Настройки → Ключи доступа на сопряжённом устройстве). Ключи, созданные в веб-приложении, работают только там. + Продолжить с ключом доступа + Вход по ключу доступа завершён — ключ удалён, токен доступа хаба изменился или сессия истекла. Войдите снова, чтобы продолжить. Для сессий worktree нужен существующий каталог репозитория. @@ -794,4 +799,36 @@ (на диске уже более новая версия CLI — раннер скоро перезапустится сам) (на диске ещё нет более новой версии CLI — установите/обновите на этом хосте) Не удалось перезапустить раннер + + + У этого хаба ещё нет ключей доступа приложения. Сначала выполните сопряжение по токену доступа, затем добавьте ключ в разделе Настройки → Ключи доступа. + На этом устройстве нет ключа доступа для этого хаба. + Ключи доступа недоступны на этом устройстве. Убедитесь, что настроен менеджер паролей, например Google Password Manager. + Хаб запросил ключ доступа для %1$s, а приложение использует только %2$s. Обновите хаб и попробуйте снова. + Этот ключ доступа перестал работать, так как токен доступа хаба изменился. Выполните сопряжение с новым токеном и добавьте новый ключ. + Хаб не смог проверить ключ доступа. Попробуйте снова. + Этот ключ доступа уже зарегистрирован в хабе. + Не удалось связаться с хабом. Проверьте сеть и попробуйте снова. + Запрос ключа доступа не удался (HTTP %1$d). Попробуйте снова через мгновение. + Запрос ключа доступа не удался. + Запрос ключа доступа не удался: %1$s + Ключи доступа + Вход в этот хаб без токена доступа + Ключи доступа позволяют приложению входить в этот хаб без токена доступа. Они привязаны к текущему токену доступа хаба: после его смены ключи становятся неактивными. + Добавить ключ доступа + Назовите ключ, чтобы потом его узнать. + Название + Продолжить + Ключей доступа пока нет. + Создан %1$s · Использован %2$s + Создан %1$s · Не использовался + Веб + Неактивен + Создан в веб-приложении; для входа в это приложение не подходит. + Ключ без названия + Удалить ключ доступа + Удалить «%1$s»? Всем, кто вошёл с ним, придётся войти снова. Ключ может остаться в менеджере паролей — удалите его там отдельно. + Удалить + Ключ доступа добавлен. + Ключ доступа удалён. diff --git a/android/app/src/main/res/values-zh-rCN/strings.xml b/android/app/src/main/res/values-zh-rCN/strings.xml index 7f45b2de..9af0f64c 100644 --- a/android/app/src/main/res/values-zh-rCN/strings.xml +++ b/android/app/src/main/res/values-zh-rCN/strings.xml @@ -642,6 +642,11 @@ 此设备的配对已被撤销 — hub 的访问令牌已更改。请重新配对以继续。 Hub 持续拒绝此设备的会话。请重新配对以继续。 此 hub 的存储凭据已丢失。请重新配对以继续。 + 使用通行密钥登录 + 使用通行密钥登录 + 输入 hub 地址,然后选择本应用为其保存的通行密钥(在已配对设备的 设置 → 通行密钥 中添加)。在网页应用中创建的通行密钥只能在网页中使用。 + 使用通行密钥继续 + 通行密钥登录已失效 — 通行密钥已被删除、hub 的访问令牌已更改或会话已过期。请重新登录以继续。 工作树会话需要已存在的仓库目录。 @@ -780,4 +785,36 @@ (磁盘上已有更新 CLI — 运行器应很快自行重启) (磁盘尚无更新 CLI — 请先在该主机安装/升级) 重启运行器失败 + + + 此 hub 尚无应用通行密钥。请先使用访问令牌配对,然后在 设置 → 通行密钥 中添加。 + 此设备上没有该 hub 的通行密钥。 + 此设备无法使用通行密钥。请确认已设置密码管理器(例如 Google 密码管理工具)。 + Hub 请求的是 %1$s 的通行密钥,但本应用仅使用 %2$s。请更新 hub 后重试。 + 由于 hub 的访问令牌已更改,此通行密钥已失效。请使用新的访问令牌配对并添加新的通行密钥。 + Hub 无法验证该通行密钥。请重试。 + 此通行密钥已在 hub 上注册。 + 无法连接到 hub。请检查网络后重试。 + 通行密钥请求失败(HTTP %1$d)。请稍后重试。 + 通行密钥请求失败。 + 通行密钥请求失败:%1$s + 通行密钥 + 无需访问令牌即可登录此 hub + 通行密钥让本应用无需访问令牌即可登录此 hub。它们与 hub 当前的访问令牌绑定:轮换令牌后会失效。 + 添加通行密钥 + 为此通行密钥命名,方便日后识别。 + 名称 + 继续 + 还没有通行密钥。 + 创建于 %1$s · 上次使用 %2$s + 创建于 %1$s · 从未使用 + 网页 + 已失效 + 在网页应用中创建,无法用于登录本应用。 + 未命名的通行密钥 + 删除通行密钥 + 删除“%1$s”?使用它登录的设备需要重新登录。它可能仍保留在密码管理器中,请另行删除。 + 删除 + 已添加通行密钥。 + 已删除通行密钥。 diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml index cb588991..2e2e3ce4 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -642,6 +642,11 @@ This device’s pairing was revoked — the hub’s access token changed. Pair again to continue. The hub kept rejecting this device’s session. Pair again to continue. The stored credentials for this hub went missing. Pair again to continue. + Sign in with a passkey + Sign in with a passkey + Enter your hub URL, then pick the passkey this app saved for it (Settings → Passkeys on a paired device). Passkeys created in the web app only work there. + Continue with passkey + Your passkey sign-in ended — the passkey was deleted, the hub’s access token changed, or the session expired. Sign in again to continue. Worktree sessions require an existing repository directory. @@ -780,4 +785,36 @@ (newer CLI on disk — runner should self-restart soon) (no newer CLI on disk yet — install/upgrade on that host) Failed to restart runner + + + This hub has no app passkeys yet. Pair with the access token first, then add one under Settings → Passkeys. + This device has no passkey for this hub. + Passkeys aren’t available on this device. Make sure a password manager such as Google Password Manager is set up. + The hub asked for a passkey for %1$s, but this app only uses %2$s. Update the hub and try again. + This passkey stopped working because the hub’s access token changed. Pair with the new access token and add a new passkey. + The hub couldn’t verify the passkey. Try again. + This passkey is already registered with the hub. + Could not reach the hub. Check your network and try again. + The passkey request failed (HTTP %1$d). Try again in a moment. + The passkey request failed. + The passkey request failed: %1$s + Passkeys + Sign in to this hub without the access token + Passkeys let this app sign in to this hub without the access token. They are tied to the hub’s current access token: rotating it makes them inactive. + Add passkey + Name this passkey so you can recognize it later. + Name + Continue + No passkeys yet. + Created %1$s · Last used %2$s + Created %1$s · Never used + Web + Inactive + Created in the web app; it can’t sign in to this app. + Unnamed passkey + Delete passkey + Delete “%1$s”? Anyone signed in with it will have to sign in again. It may stay in your password manager; remove it there separately. + Delete + Passkey added. + Passkey deleted. diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/pairing/PairingViewModelTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/pairing/PairingViewModelTest.kt index a994881d..2ee70985 100644 --- a/android/app/src/test/kotlin/app/hapi/companion/feature/pairing/PairingViewModelTest.kt +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/pairing/PairingViewModelTest.kt @@ -3,6 +3,9 @@ package app.hapi.companion.feature.pairing +import app.hapi.companion.feature.passkey.FakePasskeyPlatform +import app.hapi.companion.feature.passkey.PasskeyCeremonyException +import app.hapi.companion.feature.passkey.PasskeyIssue import app.hapi.data.api.ApiError import app.hapi.data.auth.HubRegistry import app.hapi.data.auth.InMemoryCredentialStore @@ -11,6 +14,7 @@ import app.hapi.protocol.pairing.BindLink import app.hapi.protocol.wire.AuthResponse import app.hapi.protocol.wire.AuthUser import app.hapi.protocol.wire.HubHealthResponse +import app.hapi.protocol.wire.PasskeyLoginResponse import app.hapi.protocol.wire.SUPPORTED_PROTOCOL_VERSION import java.io.IOException import kotlin.test.Test @@ -25,6 +29,8 @@ import kotlinx.coroutines.test.advanceUntilIdle import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.runTest import kotlinx.coroutines.test.setMain +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonPrimitive import org.junit.After import org.junit.Before @@ -45,6 +51,19 @@ private class FakePairingClient : PairingClient { authCalls += accessToken return authResult(accessToken) } + + var loginOptionsResult: () -> String = { """{"challenge":"Y2g","rpId":"hapi.run","allowCredentials":[]}""" } + var loginVerifyResult: (JsonObject) -> PasskeyLoginResponse = { + PasskeyLoginResponse(token = "jwt-passkey", user = AuthUser(id = 1), passkeySession = "ps-1") + } + val verifyBodies = mutableListOf() + + override suspend fun passkeyLoginOptions(): String = loginOptionsResult() + + override suspend fun passkeyLoginVerify(response: JsonObject): PasskeyLoginResponse { + verifyBodies += response + return loginVerifyResult(response) + } } class PairingViewModelTest { @@ -224,4 +243,124 @@ class PairingViewModelTest { assertEquals("jwt-2", credentials?.jwt) assertEquals(listOf(HUB), registry.state.value.hubs) } + + // ------------------------------------------------------------ passkeys -- + + @Test + fun `passkey sign-in stores only the passkey session and activates the hub`() = runVmTest { + val platform = FakePasskeyPlatform() + val vm = viewModel() + + vm.signInWithPasskey("https://LocalHost:3006/", platform) + assertEquals(PairingUiState.Validating, vm.state.value) + advanceUntilIdle() + + assertEquals(PairingUiState.Success(HUB), vm.state.value) + assertEquals(1, platform.getRequests.size, "options are handed to the platform verbatim") + assertEquals(client.loginOptionsResult(), platform.getRequests.single()) + assertTrue(client.authCalls.isEmpty(), "no access-token exchange on the passkey path") + + val verified = client.verifyBodies.single() + assertEquals("Y3JlZA", verified["rawId"]?.jsonPrimitive?.content) + + val credentials = credentialStore.get(HUB) + assertNull(credentials?.accessToken) + assertEquals("ps-1", credentials?.passkeySession) + assertEquals("jwt-passkey", credentials?.jwt) + assertEquals(1_234L, credentials?.jwtObtainedAtMs) + assertEquals(HUB, registry.activeHubUrl) + } + + @Test + fun `passkey sign-in replaces an earlier access-token pairing`() = runVmTest { + val vm = viewModel() + vm.pair(HUB, "tok") + advanceUntilIdle() + + vm.signInWithPasskey(HUB, FakePasskeyPlatform()) + advanceUntilIdle() + + val credentials = credentialStore.get(HUB) + assertNull(credentials?.accessToken) + assertEquals("ps-1", credentials?.passkeySession) + } + + @Test + fun `foreign relying party is refused before the platform ceremony`() = runVmTest { + client.loginOptionsResult = { """{"challenge":"Y2g","rpId":"evil.example"}""" } + val platform = FakePasskeyPlatform() + val vm = viewModel() + + vm.signInWithPasskey(HUB, platform) + advanceUntilIdle() + + assertEquals( + PairingUiState.Error(PairingError.Passkey(PasskeyIssue.RpMismatch("evil.example"))), + vm.state.value, + ) + assertTrue(platform.getRequests.isEmpty()) + assertNull(credentialStore.get(HUB)) + } + + @Test + fun `hub without passkeys reports NoneRegistered`() = runVmTest { + client.loginOptionsResult = { throw ApiError.from(404, """{"error":"no_passkeys"}""") } + val vm = viewModel() + + vm.signInWithPasskey(HUB, FakePasskeyPlatform()) + advanceUntilIdle() + + assertEquals(PairingUiState.Error(PairingError.Passkey(PasskeyIssue.NoneRegistered)), vm.state.value) + assertTrue(registry.state.value.hubs.isEmpty()) + } + + @Test + fun `dismissed system sheet returns to idle silently`() = runVmTest { + val platform = FakePasskeyPlatform().apply { + getResult = { throw PasskeyCeremonyException.Cancelled() } + } + val vm = viewModel() + + vm.signInWithPasskey(HUB, platform) + advanceUntilIdle() + + assertEquals(PairingUiState.Idle, vm.state.value) + assertTrue(client.verifyBodies.isEmpty()) + assertNull(credentialStore.get(HUB)) + } + + @Test + fun `no matching passkey on the device gets a friendly error`() = runVmTest { + val platform = FakePasskeyPlatform().apply { + getResult = { throw PasskeyCeremonyException.NoCredential() } + } + val vm = viewModel() + + vm.signInWithPasskey(HUB, platform) + advanceUntilIdle() + + assertEquals( + PairingUiState.Error(PairingError.Passkey(PasskeyIssue.NoCredentialOnDevice)), + vm.state.value, + ) + } + + @Test + fun `revoked passkey is distinguished from a failed verification`() = runVmTest { + client.loginVerifyResult = { throw ApiError.from(401, """{"error":"passkey_revoked"}""") } + val vm = viewModel() + vm.signInWithPasskey(HUB, FakePasskeyPlatform()) + advanceUntilIdle() + assertEquals(PairingUiState.Error(PairingError.Passkey(PasskeyIssue.Revoked)), vm.state.value) + + client.loginVerifyResult = { throw ApiError.from(401, """{"error":"Passkey challenge expired"}""") } + vm.dismissError() + vm.signInWithPasskey(HUB, FakePasskeyPlatform()) + advanceUntilIdle() + assertEquals( + PairingUiState.Error(PairingError.Passkey(PasskeyIssue.VerificationFailed)), + vm.state.value, + ) + assertNull(credentialStore.get(HUB)) + } } diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/passkey/FakePasskeyPlatform.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/passkey/FakePasskeyPlatform.kt new file mode 100644 index 00000000..711c3024 --- /dev/null +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/passkey/FakePasskeyPlatform.kt @@ -0,0 +1,26 @@ +package app.hapi.companion.feature.passkey + +/** Scripted [PasskeyPlatform]: records the options it was handed. */ +class FakePasskeyPlatform : PasskeyPlatform { + val createRequests = mutableListOf() + val getRequests = mutableListOf() + + var createResult: (String) -> String = { + """{"id":"Y3JlZA","rawId":"Y3JlZA","type":"public-key","authenticatorAttachment":null,""" + + """"response":{"clientDataJSON":"e30","attestationObject":"e30"},"clientExtensionResults":{}}""" + } + var getResult: (String) -> String = { + """{"id":"Y3JlZA","rawId":"Y3JlZA","type":"public-key",""" + + """"response":{"clientDataJSON":"e30","authenticatorData":"e30","signature":"e30"}}""" + } + + override suspend fun createPasskey(requestJson: String): String { + createRequests += requestJson + return createResult(requestJson) + } + + override suspend fun getPasskey(requestJson: String): String { + getRequests += requestJson + return getResult(requestJson) + } +} diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/settings/PasskeysViewModelTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/settings/PasskeysViewModelTest.kt new file mode 100644 index 00000000..7216f533 --- /dev/null +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/settings/PasskeysViewModelTest.kt @@ -0,0 +1,160 @@ +@file:OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) + +package app.hapi.companion.feature.settings + +import app.hapi.companion.feature.passkey.FakePasskeyPlatform +import app.hapi.companion.feature.passkey.PasskeyCeremonyException +import app.hapi.companion.feature.passkey.PasskeyIssue +import app.hapi.data.api.ApiError +import app.hapi.protocol.wire.PasskeySummary +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.test.StandardTestDispatcher +import kotlinx.coroutines.test.TestScope +import kotlinx.coroutines.test.advanceUntilIdle +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** Settings → Passkeys: list ordering, add ceremony wiring, delete, failures. */ +class PasskeysViewModelTest { + + private fun TestScope.newVmScope(): CoroutineScope = + CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)) + + private class FakeGateway : PasskeysGateway { + var passkeys = mutableListOf() + var options: () -> String = { + """{"rp":{"id":"hapi.run","name":"HAPI"},"user":{"id":"dXNlcg","name":"hapi@hub"},"challenge":"Y2g"}""" + } + var verifyError: Exception? = null + val verified = mutableListOf>() + val deleted = mutableListOf() + + override suspend fun list(): List = passkeys.toList() + override suspend fun registerOptions(): String = options() + override suspend fun registerVerify(response: JsonObject, name: String?) { + verifyError?.let { throw it } + verified += response to name + passkeys += PasskeySummary(id = "new", name = name, rpId = "hapi.run", createdAt = 99) + } + override suspend fun delete(id: String) { + deleted += id + passkeys.removeAll { it.id == id } + } + } + + private fun passkey(id: String, rpId: String = "hapi.run", createdAt: Long = 1, valid: Boolean = true) = + PasskeySummary(id = id, name = id, rpId = rpId, createdAt = createdAt, valid = valid) + + @Test + fun `lists app passkeys first, newest first`() = runTest { + val gateway = FakeGateway().apply { + passkeys += passkey("web-new", rpId = "hub.example", createdAt = 30) + passkeys += passkey("app-old", createdAt = 10) + passkeys += passkey("app-new", createdAt = 20, valid = false) + } + val vm = PasskeysViewModel(gateway, newVmScope()) + + vm.start() + advanceUntilIdle() + + val data = vm.state.value as PasskeysUiState.Data + assertEquals(listOf("app-new", "app-old", "web-new"), data.passkeys.map { it.id }) + assertEquals(listOf(true, true, false), data.passkeys.map { it.isAppPasskey }) + } + + @Test + fun `add hands the options to the platform and verifies with the trimmed name`() = runTest { + val gateway = FakeGateway() + val platform = FakePasskeyPlatform() + val vm = PasskeysViewModel(gateway, newVmScope()) + vm.start() + advanceUntilIdle() + + vm.addPasskey(" Pixel 9 ", platform) + assertEquals(PasskeysBusy.Adding, vm.busy.value) + advanceUntilIdle() + + assertEquals(listOf(gateway.options()), platform.createRequests) + val (response, name) = gateway.verified.single() + assertEquals("Pixel 9", name) + assertEquals("public-key", response["type"]?.jsonPrimitive?.content) + assertTrue("authenticatorAttachment" !in response.keys, "null members are stripped") + assertEquals(PasskeysNotice.Added, vm.notice.value) + assertNull(vm.busy.value) + assertEquals(listOf("new"), (vm.state.value as PasskeysUiState.Data).passkeys.map { it.id }) + } + + @Test + fun `add refuses options for a foreign relying party`() = runTest { + val gateway = FakeGateway().apply { + options = { """{"rp":{"id":"evil.example"},"challenge":"Y2g"}""" } + } + val platform = FakePasskeyPlatform() + val vm = PasskeysViewModel(gateway, newVmScope()) + + vm.addPasskey("x", platform) + advanceUntilIdle() + + assertTrue(platform.createRequests.isEmpty()) + assertTrue(gateway.verified.isEmpty()) + assertEquals(PasskeysNotice.Failed(PasskeyIssue.RpMismatch("evil.example")), vm.notice.value) + } + + @Test + fun `cancelled ceremony is silent`() = runTest { + val gateway = FakeGateway() + val platform = FakePasskeyPlatform().apply { + createResult = { throw PasskeyCeremonyException.Cancelled() } + } + val vm = PasskeysViewModel(gateway, newVmScope()) + + vm.addPasskey("x", platform) + advanceUntilIdle() + + assertNull(vm.notice.value) + assertNull(vm.busy.value) + assertTrue(gateway.verified.isEmpty()) + } + + @Test + fun `duplicate registration surfaces AlreadyRegistered`() = runTest { + val gateway = FakeGateway().apply { + verifyError = ApiError.from(409, """{"error":"Passkey already registered"}""") + } + val vm = PasskeysViewModel(gateway, newVmScope()) + + vm.addPasskey("x", FakePasskeyPlatform()) + advanceUntilIdle() + + assertEquals(PasskeysNotice.Failed(PasskeyIssue.AlreadyRegistered), vm.notice.value) + } + + @Test + fun `delete removes the passkey and reloads`() = runTest { + val gateway = FakeGateway().apply { passkeys += passkey("a"); passkeys += passkey("b") } + val vm = PasskeysViewModel(gateway, newVmScope()) + vm.start() + advanceUntilIdle() + + vm.deletePasskey("a") + assertEquals(PasskeysBusy.Deleting("a"), vm.busy.value) + advanceUntilIdle() + + assertEquals(listOf("a"), gateway.deleted) + assertEquals(PasskeysNotice.Deleted, vm.notice.value) + assertEquals(listOf("b"), (vm.state.value as PasskeysUiState.Data).passkeys.map { it.id }) + } + + @Test + fun `default name is the device model clamped to the hub limit`() { + assertEquals("Pixel 9", defaultPasskeyName(" Pixel 9 ")) + assertEquals(64, defaultPasskeyName("x".repeat(100)).length) + assertEquals("", defaultPasskeyName(null)) + } +} diff --git a/android/app/src/test/kotlin/app/hapi/companion/feature/settings/SettingsHubCatalogTest.kt b/android/app/src/test/kotlin/app/hapi/companion/feature/settings/SettingsHubCatalogTest.kt index ddf66ba9..a807406e 100644 --- a/android/app/src/test/kotlin/app/hapi/companion/feature/settings/SettingsHubCatalogTest.kt +++ b/android/app/src/test/kotlin/app/hapi/companion/feature/settings/SettingsHubCatalogTest.kt @@ -14,22 +14,27 @@ import kotlin.test.assertTrue class SettingsHubCatalogTest { @Test - fun `owners see general usage and storage in catalog order`() { + fun `owners see general passkeys usage and storage in catalog order`() { val routes = SettingsHubCatalog.visibleEntries(SettingsHubState(isOwner = true)) .map { it.route } assertEquals( - listOf(Routes.SETTINGS_GENERAL, Routes.SETTINGS_USAGE, Routes.SETTINGS_STORAGE), + listOf( + Routes.SETTINGS_GENERAL, + Routes.SETTINGS_PASSKEYS, + Routes.SETTINGS_USAGE, + Routes.SETTINGS_STORAGE, + ), routes, ) } @Test - fun `non-owners see only the ungated general category`() { + fun `non-owners see only the ungated general and passkeys categories`() { val routes = SettingsHubCatalog.visibleEntries(SettingsHubState(isOwner = false)) .map { it.route } - assertEquals(listOf(Routes.SETTINGS_GENERAL), routes) + assertEquals(listOf(Routes.SETTINGS_GENERAL, Routes.SETTINGS_PASSKEYS), routes) } @Test diff --git a/android/core/data/src/main/kotlin/app/hapi/data/api/HapiApi.kt b/android/core/data/src/main/kotlin/app/hapi/data/api/HapiApi.kt index 1b55d163..a903f92b 100644 --- a/android/core/data/src/main/kotlin/app/hapi/data/api/HapiApi.kt +++ b/android/core/data/src/main/kotlin/app/hapi/data/api/HapiApi.kt @@ -28,6 +28,11 @@ import app.hapi.protocol.wire.MachinePathsExistsRequest import app.hapi.protocol.wire.MachinePathsExistsResponse import app.hapi.protocol.wire.MachinesResponse import app.hapi.protocol.wire.MessagesResponse +import app.hapi.protocol.wire.PasskeyListResponse +import app.hapi.protocol.wire.PasskeyLoginResponse +import app.hapi.protocol.wire.PasskeyLoginVerifyRequest +import app.hapi.protocol.wire.PasskeyOptionsRequest +import app.hapi.protocol.wire.PasskeyRegisterVerifyRequest import app.hapi.protocol.wire.QueuedStateRequest import app.hapi.protocol.wire.QueuedStateResponse import app.hapi.protocol.wire.RegisterDeviceRequest @@ -67,6 +72,7 @@ import kotlinx.coroutines.suspendCancellableCoroutine import kotlinx.serialization.encodeToString import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive import kotlinx.serialization.json.buildJsonObject import kotlinx.serialization.json.put @@ -167,6 +173,21 @@ class HapiApi internal constructor( } } + /** [request] without decoding: the 2xx body text verbatim (WebAuthn options pass-through). */ + private suspend fun requestText( + method: String, + url: HttpUrl, + body: RequestBody? = null, + client: OkHttpClient = this.client, + ): String { + val request = Request.Builder().url(url).method(method, body).build() + return client.newCall(request).await().use { response -> + val text = response.body?.string().orEmpty() + if (!response.isSuccessful) throw ApiError.from(response.code, text) + text + } + } + /** URL builder; each segment is percent-encoded (`encodeURIComponent` twin). */ private fun url(vararg segments: String): HttpUrl.Builder = baseUrl.newBuilder().apply { segments.forEach(::addPathSegment) } @@ -189,7 +210,66 @@ class HapiApi internal constructor( * `TokenAuthenticator`. 401 here means the token was rejected (re-pair). */ suspend fun authenticate(accessToken: String): AuthResponse = - request("POST", url("api", "auth").build(), AuthRequest(accessToken).toJsonBody(), authClient) + request("POST", url("api", "auth").build(), AuthRequest(accessToken = accessToken).toJsonBody(), authClient) + + // ------------------------------------------------------------ passkeys -- + // Native passkeys use the fixed RP ID `hapi.run`; every call sends + // `{"client":"native"}` and exchanges base64url WebAuthn JSON with the + // platform credential provider. Hub: `hub/src/web/routes/passkey.ts`. + + /** + * `POST /api/passkey/register/options` (JWT required) — `PublicKeyCredentialCreationOptionsJSON`. + * Returned verbatim: Credential Manager takes it as `requestJson`. + */ + suspend fun passkeyRegisterOptions(): String = + requestText( + "POST", + url("api", "passkey", "register", "options").build(), + PasskeyOptionsRequest.Native.toJsonBody(), + ) + + /** + * `POST /api/passkey/register/verify` — stores the credential under the + * caller's namespace. Errors: 400 `Passkey challenge expired` / + * `Passkey verification failed`, 409 `Passkey already registered`. + */ + suspend fun passkeyRegisterVerify(response: JsonObject, name: String?): Unit = + request( + "POST", + url("api", "passkey", "register", "verify").build(), + PasskeyRegisterVerifyRequest(response = response, name = name).toJsonBody(), + ) + + /** + * `POST /api/passkey/login/options` (no JWT) — `PublicKeyCredentialRequestOptionsJSON` + * with `allowCredentials` limited to this hub's native passkeys. + * 404 `no_passkeys` means none are registered: use the access token. + */ + suspend fun passkeyLoginOptions(): String = + requestText( + "POST", + url("api", "passkey", "login", "options").build(), + PasskeyOptionsRequest.Native.toJsonBody(), + authClient, + ) + + /** `POST /api/passkey/login/verify` (no JWT) — JWT + passkey session. */ + suspend fun passkeyLoginVerify(response: JsonObject): PasskeyLoginResponse = + request( + "POST", + url("api", "passkey", "login", "verify").build(), + PasskeyLoginVerifyRequest(response = response).toJsonBody(), + authClient, + ) + + /** `GET /api/passkeys` — the caller's namespace passkeys, native and web. */ + suspend fun getPasskeys(): PasskeyListResponse = + request("GET", url("api", "passkeys").build()) + + /** `DELETE /api/passkeys/:id` — revokes the passkey and its sessions; 404 when gone. */ + suspend fun deletePasskey(id: String) { + request("DELETE", url("api", "passkeys", id).build()) + } // ------------------------------------------------------------ sessions -- diff --git a/android/core/data/src/main/kotlin/app/hapi/data/auth/AuthEvents.kt b/android/core/data/src/main/kotlin/app/hapi/data/auth/AuthEvents.kt index 57fe153c..47726803 100644 --- a/android/core/data/src/main/kotlin/app/hapi/data/auth/AuthEvents.kt +++ b/android/core/data/src/main/kotlin/app/hapi/data/auth/AuthEvents.kt @@ -5,6 +5,13 @@ enum class AuthTerminalReason { /** `POST /api/auth` answered 401 — the access token was rotated/revoked. */ ACCESS_TOKEN_REJECTED, + /** + * `POST /api/auth` answered 401 `passkey_session_invalid` — the passkey + * was deleted, `CLI_API_TOKEN` rotated, or the session expired. Sign in + * with a passkey (or the access token) again. + */ + PASSKEY_SESSION_INVALID, + /** The retried request 401'd again with a freshly-exchanged JWT. */ RETRY_EXHAUSTED, diff --git a/android/core/data/src/main/kotlin/app/hapi/data/auth/CredentialStore.kt b/android/core/data/src/main/kotlin/app/hapi/data/auth/CredentialStore.kt index 49d3f236..1a3837b2 100644 --- a/android/core/data/src/main/kotlin/app/hapi/data/auth/CredentialStore.kt +++ b/android/core/data/src/main/kotlin/app/hapi/data/auth/CredentialStore.kt @@ -1,5 +1,6 @@ package app.hapi.data.auth +import app.hapi.protocol.wire.AuthRequest import java.util.concurrent.ConcurrentHashMap import kotlinx.serialization.Serializable @@ -7,24 +8,57 @@ import kotlinx.serialization.Serializable * Credentials for one paired hub, keyed by normalized hub origin * ([HubUrls.normalize]). * - * The **access token** is the durable secret from pairing - * (`hapicompanion://bind?...&code=`), exchanged for a 4-hour [jwt] via - * `POST /api/auth`. It is opaque — never split client-side; the optional - * `:namespace` suffix is interpreted by the hub only - * (`docs/api/client-contract/auth.md`). The JWT is a cache: persisting it just - * saves one exchange round-trip on cold start. + * A hub is authenticated by **one of two durable secrets**: + * + * - the **access token** from pairing (`hapicompanion://bind?...&code=`), or + * - the **passkey session** minted by `POST /api/passkey/login/verify` + * (`docs/api/client-contract/auth.md#passkeys-native`) — signing in with a + * passkey never requires the access token. + * + * Either is exchanged for a 4-hour [jwt] via `POST /api/auth`; the body + * carries whichever one exists ([authRequest]). An access token is opaque — + * never split client-side; the optional `:namespace` suffix is interpreted by + * the hub only. The JWT is a cache: persisting it just saves one exchange + * round-trip on cold start. + * + * Both fields are nullable because the two sign-in paths populate different + * ones; at least one is always set for a usable entry ([hasCredential]). */ @Serializable data class HubCredentials( /** Normalized hub origin, e.g. `https://hub.example:8443`. */ val hubUrl: String, - /** Opaque pairing secret (`CLI_API_TOKEN[:namespace]`). */ - val accessToken: String, + /** Opaque pairing secret (`CLI_API_TOKEN[:namespace]`), when paired. */ + val accessToken: String? = null, + /** Passkey refresh credential, when signed in with a passkey. */ + val passkeySession: String? = null, /** Last JWT from `POST /api/auth`, or null before the first exchange. */ val jwt: String? = null, /** Epoch ms when [jwt] was obtained, or null. */ val jwtObtainedAtMs: Long? = null, -) +) { + + /** + * The durable secret this entry authenticates with: the access token when + * both exist (pairing is the user's explicit, revocable choice; its 401 also + * tells the UI to re-pair), else the passkey session. + */ + val authRequest: AuthRequest? + get() = when { + accessToken != null -> AuthRequest(accessToken = accessToken) + passkeySession != null -> AuthRequest(passkeySession = passkeySession) + else -> null + } + + /** The secret string matched against a remembered rejected credential. */ + val secret: String? get() = accessToken ?: passkeySession + + /** True while this entry can still exchange for a JWT. */ + val hasCredential: Boolean get() = secret != null + + /** Only signed in by passkey (no access token): 401 means sign in again. */ + val passkeyOnly: Boolean get() = accessToken == null && passkeySession != null +} /** * Per-hub credential storage. Production uses [EncryptedPrefsCredentialStore] diff --git a/android/core/data/src/main/kotlin/app/hapi/data/auth/TokenAuthenticator.kt b/android/core/data/src/main/kotlin/app/hapi/data/auth/TokenAuthenticator.kt index 40f40e93..3c9bfa09 100644 --- a/android/core/data/src/main/kotlin/app/hapi/data/auth/TokenAuthenticator.kt +++ b/android/core/data/src/main/kotlin/app/hapi/data/auth/TokenAuthenticator.kt @@ -1,6 +1,5 @@ package app.hapi.data.auth -import app.hapi.protocol.wire.AuthRequest import app.hapi.protocol.wire.AuthResponse import app.hapi.protocol.wire.HapiJson import java.io.IOException @@ -24,7 +23,7 @@ import okhttp3.Route * * The JWT expires every 4 hours, so 401s are routine. As an OkHttp * [Authenticator] this reacts to any middleware 401 by re-exchanging the - * stored access token (`POST /api/auth`) and retrying the request **exactly + * stored credential (`POST /api/auth`) and retrying the request **exactly * once**. The refresh is single-flighted through a [Mutex]: * * - If, once inside the lock, the current JWT already differs from the one the @@ -34,10 +33,15 @@ import okhttp3.Route * persist the new JWT into the [CredentialStore], and retry. * - A response that already has a [Response.priorResponse] is the retry * itself failing again → give up and emit [AuthTerminalReason.RETRY_EXHAUSTED]. - * - A 401 from `POST /api/auth` means the access token was rotated/revoked → - * emit [AuthTerminalReason.ACCESS_TOKEN_REJECTED]; the rejected token is - * remembered so concurrent/subsequent failures don't storm the endpoint - * (a re-pair storing a *different* token clears the block). + * - The exchange body carries whichever durable secret the entry has — the + * access token or, for passkey sign-ins, the passkey session — so the same + * loop serves both sign-in paths. + * - A 401 from `POST /api/auth` means that secret was rotated/revoked → + * emit [AuthTerminalReason.ACCESS_TOKEN_REJECTED] (access token) or + * [AuthTerminalReason.PASSKEY_SESSION_INVALID] (`passkey_session_invalid`), + * both asking the user to sign in again; the rejected secret is remembered + * so concurrent/subsequent failures don't storm the endpoint (a new pairing + * or passkey sign-in storing a *different* secret clears the block). * - Transient exchange failures (I/O, 5xx) fail the call without a terminal * event: the original 401 surfaces and the caller may retry later. * @@ -63,8 +67,9 @@ class TokenAuthenticator( @Volatile private var cachedJwt: String? = null + /** Durable secret (access token or passkey session) the hub already refused. */ @Volatile - private var rejectedAccessToken: String? = null + private var rejectedSecret: String? = null /** The JWT requests should carry right now (memory first, then store). */ fun currentJwt(): String? { @@ -125,10 +130,13 @@ class TokenAuthenticator( authEvents?.onAuthTerminal(hubUrl, AuthTerminalReason.MISSING_CREDENTIALS) return null } - if (credentials.accessToken == rejectedAccessToken) return null + val authRequest = credentials.authRequest ?: run { + authEvents?.onAuthTerminal(hubUrl, AuthTerminalReason.MISSING_CREDENTIALS) + return null + } + if (credentials.secret == rejectedSecret) return null - val body = HapiJson.encodeToString(AuthRequest(credentials.accessToken)) - .toRequestBody(JSON_MEDIA_TYPE) + val body = HapiJson.encodeToString(authRequest).toRequestBody(JSON_MEDIA_TYPE) val response = try { authClient.newCall(Request.Builder().url(authUrl).post(body).build()).execute() } catch (_: IOException) { @@ -137,8 +145,8 @@ class TokenAuthenticator( response.use { val text = it.body?.string().orEmpty() if (it.code == 401) { - rejectedAccessToken = credentials.accessToken - authEvents?.onAuthTerminal(hubUrl, AuthTerminalReason.ACCESS_TOKEN_REJECTED) + rejectedSecret = credentials.secret + authEvents?.onAuthTerminal(hubUrl, terminalReason(credentials)) return null } if (!it.isSuccessful) return null // transient (5xx): no terminal event @@ -147,13 +155,26 @@ class TokenAuthenticator( } catch (_: Exception) { return null } - rejectedAccessToken = null + rejectedSecret = null credentialStore.set(credentials.copy(jwt = auth.token, jwtObtainedAtMs = nowMs())) cachedJwt = auth.token return auth.token } } + /** + * `passkey_session_invalid` (or any `/api/auth` 401 on a passkey-only + * entry) means the passkey was deleted, its `CLI_API_TOKEN` rotated, or + * the session expired → sign in again; the access-token path keeps its + * historical reason (re-pair). + */ + private fun terminalReason(credentials: HubCredentials): AuthTerminalReason = + if (credentials.passkeyOnly) { + AuthTerminalReason.PASSKEY_SESSION_INVALID + } else { + AuthTerminalReason.ACCESS_TOKEN_REJECTED + } + companion object { /** Refresh proactively when less than this much lifetime remains. */ const val FRESH_WINDOW_MS: Long = 10 * 60 * 1000 diff --git a/android/core/data/src/test/kotlin/app/hapi/data/api/PasskeyApiTest.kt b/android/core/data/src/test/kotlin/app/hapi/data/api/PasskeyApiTest.kt new file mode 100644 index 00000000..34da8da6 --- /dev/null +++ b/android/core/data/src/test/kotlin/app/hapi/data/api/PasskeyApiTest.kt @@ -0,0 +1,139 @@ +package app.hapi.data.api + +import app.hapi.data.HubSession +import app.hapi.data.auth.HubCredentials +import app.hapi.data.auth.InMemoryCredentialStore +import app.hapi.data.fakeJwt +import app.hapi.protocol.wire.NativePasskeys +import kotlin.test.AfterTest +import kotlin.test.BeforeTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull +import kotlinx.coroutines.runBlocking +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import okhttp3.mockwebserver.MockResponse +import okhttp3.mockwebserver.MockWebServer + +/** + * Native passkey endpoints of [HapiApi] (`docs/api/client-contract/auth.md` + * §Native passkeys) against MockWebServer, wired through [HubSession]. + */ +class PasskeyApiTest { + + private lateinit var server: MockWebServer + private lateinit var session: HubSession + private val jwt = fakeJwt(expSeconds = 4_000_000_000) + + private val creationOptions = + """{"rp":{"id":"hapi.run","name":"HAPI"},"user":{"id":"dXNlcg","name":"hapi@hub"},"challenge":"Y2g"}""" + private val assertion = + """{"id":"Y3JlZA","rawId":"Y3JlZA","type":"public-key","response":{"clientDataJSON":"e30"}}""" + + @BeforeTest + fun setUp() { + server = MockWebServer() + server.start() + val hubUrl = server.url("/").toString().removeSuffix("/") + val store = InMemoryCredentialStore() + store.set(HubCredentials(hubUrl = hubUrl, accessToken = "token", jwt = jwt)) + session = HubSession(server.url("/"), store) + } + + @AfterTest + fun tearDown() { + session.close() + server.shutdown() + } + + private fun ok(body: String) = MockResponse() + .setHeader("Content-Type", "application/json") + .setBody(body) + + @Test + fun `register options posts client native with the jwt and returns the json verbatim`() { + server.enqueue(ok(creationOptions)) + + val options = runBlocking { session.api.passkeyRegisterOptions() } + + assertEquals(creationOptions, options) + val request = server.takeRequest() + assertEquals("POST", request.method) + assertEquals("/api/passkey/register/options", request.path) + assertEquals("Bearer $jwt", request.getHeader("Authorization")) + assertEquals("""{"client":"native"}""", request.body.readUtf8()) + } + + @Test + fun `register verify posts the response object and name`() { + server.enqueue(ok("""{"ok":true,"id":"Y3JlZA"}""")) + + runBlocking { + session.api.passkeyRegisterVerify(NativePasskeys.credentialResponse(assertion), "Pixel 9") + } + + val request = server.takeRequest() + assertEquals("/api/passkey/register/verify", request.path) + val body = Json.parseToJsonElement(request.body.readUtf8()).jsonObject + assertEquals("Pixel 9", body.getValue("name").jsonPrimitive.content) + assertEquals("public-key", body.getValue("response").jsonObject.getValue("type").jsonPrimitive.content) + } + + @Test + fun `login options and verify go out without a bearer header`() { + server.enqueue(ok("""{"challenge":"Y2g","rpId":"hapi.run","allowCredentials":[]}""")) + server.enqueue( + ok("""{"token":"jwt-2","user":{"id":1,"firstName":"Web User"},"passkeySession":"ps-1"}"""), + ) + + val options = runBlocking { session.api.passkeyLoginOptions() } + val login = runBlocking { session.api.passkeyLoginVerify(NativePasskeys.credentialResponse(assertion)) } + + assertEquals("hapi.run", NativePasskeys.requestRpId(options)) + assertEquals("ps-1", login.passkeySession) + assertEquals("jwt-2", login.token) + + val optionsRequest = server.takeRequest() + assertEquals("/api/passkey/login/options", optionsRequest.path) + assertNull(optionsRequest.getHeader("Authorization")) + assertEquals("""{"client":"native"}""", optionsRequest.body.readUtf8()) + + val verifyRequest = server.takeRequest() + assertEquals("/api/passkey/login/verify", verifyRequest.path) + assertNull(verifyRequest.getHeader("Authorization")) + val body = Json.parseToJsonElement(verifyRequest.body.readUtf8()).jsonObject + assertEquals(setOf("response"), body.keys) + } + + @Test + fun `no registered passkeys surfaces 404 no_passkeys`() { + server.enqueue(MockResponse().setResponseCode(404).setBody("""{"error":"no_passkeys"}""")) + + val error = assertFailsWith { runBlocking { session.api.passkeyLoginOptions() } } + + assertEquals(404, error.status) + assertEquals("no_passkeys", error.code) + } + + @Test + fun `list and delete hit the management endpoints`() { + server.enqueue( + ok( + """{"passkeys":[{"id":"a/b","name":null,"rpId":"hapi.run","createdAt":1,"lastUsedAt":null,"valid":true}]}""", + ), + ) + server.enqueue(ok("""{"ok":true}""")) + + val list = runBlocking { session.api.getPasskeys() } + runBlocking { session.api.deletePasskey("a/b") } + + assertEquals(listOf("a/b"), list.passkeys.map { it.id }) + assertEquals("/api/passkeys", server.takeRequest().path) + val delete = server.takeRequest() + assertEquals("DELETE", delete.method) + assertEquals("/api/passkeys/a%2Fb", delete.path, "credential ids are path-encoded") + } +} diff --git a/android/core/data/src/test/kotlin/app/hapi/data/auth/TokenAuthenticatorTest.kt b/android/core/data/src/test/kotlin/app/hapi/data/auth/TokenAuthenticatorTest.kt index cba4bc86..7da23d98 100644 --- a/android/core/data/src/test/kotlin/app/hapi/data/auth/TokenAuthenticatorTest.kt +++ b/android/core/data/src/test/kotlin/app/hapi/data/auth/TokenAuthenticatorTest.kt @@ -42,6 +42,7 @@ class TokenAuthenticatorTest { private val jwt1 = fakeJwt(expSeconds = 4_000_000_000) private val jwt2 = fakeJwt(expSeconds = 4_100_000_000) private val accessToken = "base-token:default" + private val passkeySession = "passkey-session-1" private lateinit var hubUrl: String @@ -237,6 +238,97 @@ class TokenAuthenticatorTest { assertTrue(events.events.isEmpty(), "5xx exchange failures are transient, not terminal") } + // ------------------------------------------------------- passkey session -- + + private fun startPasskeySession(jwt: String? = jwt1): HubSession { + store.set(HubCredentials(hubUrl = hubUrl, passkeySession = passkeySession, jwt = jwt)) + return HubSession(server.url("/"), store, events).also { session = it } + } + + @Test + fun `passkey-only credentials exchange the passkey session`() { + val hub = startPasskeySession() + server.enqueue(unauthorized()) + server.enqueue(authOk(jwt2)) + server.enqueue(sessionsOk()) + + runBlocking { hub.api.getSessions() } + + server.takeRequest() + val auth = server.takeRequest() + assertEquals("/api/auth", auth.path) + val authBody = Json.parseToJsonElement(auth.body.readUtf8()).jsonObject + assertEquals(setOf("passkeySession"), authBody.keys, "no accessToken key on a passkey exchange") + assertEquals(passkeySession, authBody.getValue("passkeySession").jsonPrimitive.content) + assertEquals("Bearer $jwt2", server.takeRequest().getHeader("Authorization")) + + val stored = store.get(hubUrl) + assertEquals(jwt2, stored?.jwt) + assertEquals(passkeySession, stored?.passkeySession, "the refresh credential survives the exchange") + assertNull(stored?.accessToken) + } + + @Test + fun `access-token exchange sends only the access token`() { + store.set(HubCredentials(hubUrl, accessToken, jwt = "garbage")) + server.enqueue(authOk(jwt2)) + val authenticator = TokenAuthenticator(hubUrl, store, OkHttpClient(), events) + + runBlocking { authenticator.ensureFreshToken() } + + val authBody = Json.parseToJsonElement(server.takeRequest().body.readUtf8()).jsonObject + assertEquals(setOf("accessToken"), authBody.keys) + } + + @Test + fun `invalid passkey session is terminal and never re-exchanged`() { + val hub = startPasskeySession() + val authCalls = AtomicInteger() + server.dispatcher = object : Dispatcher() { + override fun dispatch(request: RecordedRequest): MockResponse = when (request.path) { + "/api/auth" -> { + authCalls.incrementAndGet() + unauthorized("passkey_session_invalid") + } + else -> unauthorized() + } + } + + val error = assertFailsWith { runBlocking { hub.api.getSessions() } } + assertEquals(401, error.status) + assertEquals(listOf(AuthTerminalReason.PASSKEY_SESSION_INVALID), events.reasons) + + assertFailsWith { runBlocking { hub.api.getSessions() } } + assertEquals(1, authCalls.get(), "rejected passkey session must not be re-exchanged") + assertEquals(1, events.events.size) + } + + @Test + fun `a new passkey sign-in clears the rejected-session block`() { + store.set(HubCredentials(hubUrl, passkeySession = "old-session", jwt = "garbage")) + server.enqueue(unauthorized("passkey_session_invalid")) + val authenticator = TokenAuthenticator(hubUrl, store, OkHttpClient(), events) + assertNull(runBlocking { authenticator.ensureFreshToken() }) + + store.set(HubCredentials(hubUrl, passkeySession = "new-session", jwt = "garbage")) + server.enqueue(authOk(jwt2)) + + assertEquals(jwt2, runBlocking { authenticator.ensureFreshToken() }) + server.takeRequest() + val second = Json.parseToJsonElement(server.takeRequest().body.readUtf8()).jsonObject + assertEquals("new-session", second.getValue("passkeySession").jsonPrimitive.content) + } + + @Test + fun `an entry without any durable secret reports MISSING_CREDENTIALS`() { + store.set(HubCredentials(hubUrl, jwt = "garbage")) + val authenticator = TokenAuthenticator(hubUrl, store, OkHttpClient(), events) + + assertNull(runBlocking { authenticator.ensureFreshToken() }) + assertEquals(listOf(AuthTerminalReason.MISSING_CREDENTIALS), events.reasons) + assertEquals(0, server.requestCount) + } + // ------------------------------------------------------- proactive refresh -- @Test diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/ApiRequests.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/ApiRequests.kt index 8559bd6a..2566722f 100644 --- a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/ApiRequests.kt +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/ApiRequests.kt @@ -15,11 +15,23 @@ import kotlinx.serialization.json.JsonElement * `HapiApi` instead of living here. */ -/** `POST /api/auth` (`AuthRequestSchema`, accessToken variant — natives never use `initData`). */ +/** + * `POST /api/auth` (`AuthRequestSchema`). Natives send exactly one of + * [accessToken] (pairing secret) or [passkeySession] (refresh credential from + * `POST /api/passkey/login/verify`); never `initData`. Null fields are + * omitted on the wire ([HapiJson] skips defaults). + */ @Serializable data class AuthRequest( - val accessToken: String, -) + val accessToken: String? = null, + val passkeySession: String? = null, +) { + init { + require((accessToken == null) != (passkeySession == null)) { + "AuthRequest needs exactly one of accessToken / passkeySession" + } + } +} /** * `POST /api/sessions/:id/messages` (`SendMessageRequestSchema`). diff --git a/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/PasskeyApi.kt b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/PasskeyApi.kt new file mode 100644 index 00000000..cdec5062 --- /dev/null +++ b/android/core/protocol/src/main/kotlin/app/hapi/protocol/wire/PasskeyApi.kt @@ -0,0 +1,139 @@ +package app.hapi.protocol.wire + +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject + +/** + * Native passkey wire types (`docs/api/client-contract/auth.md#passkeys-native`; + * `PasskeyOptionsRequestSchema`, `PasskeyRegisterVerifyRequestSchema`, + * `PasskeyLoginVerifyRequestSchema`, `PasskeySummary` in + * `shared/src/apiTypes.ts`). + * + * The WebAuthn options and credential responses are passed through as raw + * JSON: Credential Manager consumes `PublicKeyCredential*OptionsJSON` as-is + * and produces `RegistrationResponseJSON` / `AuthenticationResponseJSON`, so + * the app never models their (base64url) fields. + */ + +/** + * Body of `POST /api/passkey/{register,login}/options`. [client] has no + * default on purpose: [HapiJson] does not encode defaults, and the hub falls + * back to the web (Origin-derived) relying party when the field is absent. + */ +@Serializable +data class PasskeyOptionsRequest( + val client: String, +) { + companion object { + const val CLIENT_NATIVE: String = "native" + + val Native: PasskeyOptionsRequest = PasskeyOptionsRequest(CLIENT_NATIVE) + } +} + +/** `POST /api/passkey/register/verify`. [name] is trimmed/≤64 chars hub-side. */ +@Serializable +data class PasskeyRegisterVerifyRequest( + /** `RegistrationResponseJSON` from the platform authenticator. */ + val response: JsonElement, + val name: String? = null, +) + +/** `POST /api/passkey/login/verify`. */ +@Serializable +data class PasskeyLoginVerifyRequest( + /** `AuthenticationResponseJSON` from the platform authenticator. */ + val response: JsonElement, +) + +/** + * `POST /api/passkey/login/verify` success: a 4-hour JWT plus the durable + * [passkeySession] refresh credential (exchanged via `POST /api/auth`). + */ +@Serializable +data class PasskeyLoginResponse( + val token: String, + val user: AuthUser, + val passkeySession: String, +) + +/** One row of `GET /api/passkeys` (`PasskeySummary`). */ +@Serializable +data class PasskeySummary( + val id: String, + val name: String? = null, + /** `hapi.run` for app passkeys; any other value is a web passkey. */ + val rpId: String, + val createdAt: Long, + val lastUsedAt: Long? = null, + /** False once `CLI_API_TOKEN` was rotated after registration. */ + val valid: Boolean = true, +) + +@Serializable +data class PasskeyListResponse( + val passkeys: List = emptyList(), +) + +/** The relying-party rules native apps must enforce before a ceremony. */ +object NativePasskeys { + /** RP ID compiled into the official apps (asset links on `hapi.run`). */ + const val RP_ID: String = "hapi.run" + + /** Hub-side limit on passkey names (`PasskeyRegisterVerifyRequestSchema`). */ + const val MAX_NAME_LENGTH: Int = 64 + + /** `rp.id` of `PublicKeyCredentialCreationOptionsJSON`, or null if absent/unparsable. */ + fun creationRpId(optionsJson: String): String? = + parseObject(optionsJson)?.get("rp").objOrNull?.get("id").stringOrNull + + /** `rpId` of `PublicKeyCredentialRequestOptionsJSON`, or null if absent/unparsable. */ + fun requestRpId(optionsJson: String): String? = + parseObject(optionsJson)?.get("rpId").stringOrNull + + /** + * Throws [PasskeyRpMismatchException] unless the creation options target + * [expected]. Refusing a mismatch keeps a hub from steering the app into + * a ceremony for a relying party it does not own. + */ + fun requireCreationRpId(optionsJson: String, expected: String = RP_ID) { + val actual = creationRpId(optionsJson) + if (actual != expected) throw PasskeyRpMismatchException(expected, actual) + } + + /** As [requireCreationRpId], for request (sign-in) options. */ + fun requireRequestRpId(optionsJson: String, expected: String = RP_ID) { + val actual = requestRpId(optionsJson) + if (actual != expected) throw PasskeyRpMismatchException(expected, actual) + } + + /** + * Parses a platform credential response for embedding as `response`. + * Top-level JSON `null`s are dropped: the hub schema allows optional + * fields (e.g. `authenticatorAttachment`) to be absent but not `null`, + * and some providers serialize unset members as `null`. + */ + fun credentialResponse(responseJson: String): JsonObject { + val parsed = parseObject(responseJson) + ?: throw IllegalArgumentException("Credential response is not a JSON object") + return JsonObject(parsed.filterValues { it !is JsonNull }) + } + + /** Clamps a user-entered name to what the hub accepts; blank → null. */ + fun normalizeName(name: String?): String? = + name?.trim()?.take(MAX_NAME_LENGTH)?.trim()?.takeIf { it.isNotEmpty() } + + private fun parseObject(json: String): JsonObject? = try { + HapiJson.parseToJsonElement(json) as? JsonObject + } catch (_: Exception) { + null + } +} + +/** The hub's WebAuthn options target a relying party other than the compiled one. */ +class PasskeyRpMismatchException( + val expected: String, + val actual: String?, +) : IllegalStateException("Passkey RP ID mismatch: expected $expected, got ${actual ?: "none"}") diff --git a/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/PasskeyApiTest.kt b/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/PasskeyApiTest.kt new file mode 100644 index 00000000..dd933cb1 --- /dev/null +++ b/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/PasskeyApiTest.kt @@ -0,0 +1,177 @@ +package app.hapi.protocol.wire + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertNull +import kotlin.test.assertTrue +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +/** + * Wire shapes of the native passkey flow (`docs/api/client-contract/auth.md` + * §Native passkeys) and the RP-ID guard every ceremony runs first. + */ +class PasskeyApiTest { + + private val creationOptions = """ + { + "rp": {"id": "hapi.run", "name": "HAPI"}, + "user": {"id": "dXNlcg", "name": "hapi@hub.example", "displayName": "HAPI"}, + "challenge": "Y2hhbGxlbmdl", + "pubKeyCredParams": [{"type": "public-key", "alg": -7}, {"type": "public-key", "alg": -257}], + "attestation": "none" + } + """.trimIndent() + + private val requestOptions = """ + { + "challenge": "Y2hhbGxlbmdl", + "rpId": "hapi.run", + "allowCredentials": [{"type": "public-key", "id": "Y3JlZA"}], + "userVerification": "required" + } + """.trimIndent() + + // ------------------------------------------------------------ requests -- + + @Test + fun `options request sends client native as the only field`() { + val body = HapiJson.parseToJsonElement( + HapiJson.encodeToString(PasskeyOptionsRequest.Native), + ).jsonObject + + assertEquals(setOf("client"), body.keys) + assertEquals("native", body.getValue("client").jsonPrimitive.content) + } + + @Test + fun `register verify body carries the raw response and an optional name`() { + val response = HapiJson.parseToJsonElement( + """{"id":"Y3JlZA","rawId":"Y3JlZA","type":"public-key",""" + + """"response":{"clientDataJSON":"e30","attestationObject":"e30"}}""", + ) + val body = HapiJson.parseToJsonElement( + HapiJson.encodeToString(PasskeyRegisterVerifyRequest(response)), + ).jsonObject + + assertEquals(setOf("response"), body.keys, "unnamed registration omits name") + assertEquals( + "Y3JlZA", + body.getValue("response").jsonObject.getValue("rawId").jsonPrimitive.content, + ) + + val named = HapiJson.parseToJsonElement( + HapiJson.encodeToString(PasskeyRegisterVerifyRequest(response, name = "Pixel 9")), + ).jsonObject + assertEquals("Pixel 9", named.getValue("name").jsonPrimitive.content) + } + + @Test + fun `login verify body carries only the assertion`() { + val response = HapiJson.parseToJsonElement( + """{"id":"Y3JlZA","rawId":"Y3JlZA","type":"public-key",""" + + """"response":{"clientDataJSON":"e30","authenticatorData":"e30",""" + + """"signature":"e30","userHandle":"dXNlcg"}}""", + ) + val body = HapiJson.parseToJsonElement( + HapiJson.encodeToString(PasskeyLoginVerifyRequest(response)), + ).jsonObject + + assertEquals(setOf("response"), body.keys) + } + + // ----------------------------------------------------------- responses -- + + @Test + fun `login verify response exposes the jwt and refresh credential`() { + val parsed = HapiJson.decodeFromString( + """{"token":"jwt-1","user":{"id":1,"firstName":"Web User"},"passkeySession":"session-1"}""", + ) + + assertEquals("jwt-1", parsed.token) + assertEquals(1, parsed.user.id) + assertEquals("session-1", parsed.passkeySession) + } + + @Test + fun `passkey list decodes nulls and tracks validity`() { + val list = HapiJson.decodeFromString( + """ + {"passkeys":[ + {"id":"native-1","name":"Pixel 9","rpId":"hapi.run","createdAt":1750000000000, + "lastUsedAt":null,"valid":true}, + {"id":"web-1","name":null,"rpId":"hub.example","createdAt":1750000000001,"valid":false} + ]} + """.trimIndent(), + ) + + assertEquals(2, list.passkeys.size) + val native = list.passkeys[0] + assertEquals("Pixel 9", native.name) + assertEquals(NativePasskeys.RP_ID, native.rpId) + assertNull(native.lastUsedAt) + assertTrue(native.valid) + val web = list.passkeys[1] + assertNull(web.name) + assertEquals(false, web.valid) + assertNull(web.lastUsedAt, "absent lastUsedAt decodes to null") + } + + // ------------------------------------------------------------- rp guard -- + + @Test + fun `reads the declared relying party from both option shapes`() { + assertEquals("hapi.run", NativePasskeys.creationRpId(creationOptions)) + assertEquals("hapi.run", NativePasskeys.requestRpId(requestOptions)) + NativePasskeys.requireCreationRpId(creationOptions) + NativePasskeys.requireRequestRpId(requestOptions) + } + + @Test + fun `rejects options for a different or missing relying party`() { + val foreign = creationOptions.replace("\"hapi.run\"", "\"evil.example\"") + val mismatch = assertFailsWith { + NativePasskeys.requireCreationRpId(foreign) + } + assertEquals("hapi.run", mismatch.expected) + assertEquals("evil.example", mismatch.actual) + + val missing = assertFailsWith { + NativePasskeys.requireRequestRpId("""{"challenge":"e30"}""") + } + assertNull(missing.actual) + + assertFailsWith { + NativePasskeys.requireRequestRpId("not json") + } + } + + @Test + fun `credential response drops top-level nulls the hub schema rejects`() { + val sanitized = NativePasskeys.credentialResponse( + """ + {"id":"Y3JlZA","rawId":"Y3JlZA","type":"public-key", + "authenticatorAttachment":null,"clientExtensionResults":{}, + "response":{"clientDataJSON":"e30"}} + """.trimIndent(), + ) + + assertNull(sanitized["authenticatorAttachment"]) + assertTrue("authenticatorAttachment" !in sanitized.keys) + assertEquals(setOf("id", "rawId", "type", "clientExtensionResults", "response"), sanitized.keys) + assertFailsWith { NativePasskeys.credentialResponse("[]") } + } + + @Test + fun `names are trimmed and clamped to the hub limit`() { + assertNull(NativePasskeys.normalizeName(" ")) + assertNull(NativePasskeys.normalizeName(null)) + assertEquals("Pixel 9", NativePasskeys.normalizeName(" Pixel 9 ")) + assertEquals( + NativePasskeys.MAX_NAME_LENGTH, + NativePasskeys.normalizeName("x".repeat(200))?.length, + ) + } +} diff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.toml index 55066c70..103db862 100644 --- a/android/gradle/libs.versions.toml +++ b/android/gradle/libs.versions.toml @@ -42,6 +42,10 @@ fragment = "1.8.5" # Per-app locales (B-M5a): AppCompatDelegate.setApplicationLocales back to # API 26 (appcompat 1.7.1, 2025-06, on Google Maven). appcompat = "1.7.1" +# Passkeys (native RP ID hapi.run): Credential Manager 1.6.0 (stable, +# Google Maven; kotlin-stdlib 2.1.20 metadata, readable by this Kotlin 2.1 +# build). play-services-auth backs passkeys on API < 34. +credentials = "1.6.0" # Visual specimens (JVM screenshots, see README "Visual specimens"): # Robolectric 4.17 renders SDK 36 with native graphics; Roborazzi captures. robolectric = "4.17" @@ -59,6 +63,8 @@ androidx-datastore-preferences = { group = "androidx.datastore", name = "datasto androidx-navigation-compose = { group = "androidx.navigation", name = "navigation-compose", version.ref = "navigationCompose" } androidx-lifecycle-viewmodel-compose = { group = "androidx.lifecycle", name = "lifecycle-viewmodel-compose", version.ref = "lifecycle" } androidx-lifecycle-process = { group = "androidx.lifecycle", name = "lifecycle-process", version.ref = "lifecycle" } +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" } # Compose (versions come from the BOM) androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" } diff --git a/docs/api/client-contract/auth.md b/docs/api/client-contract/auth.md index 028e1dbd..763cdc56 100644 --- a/docs/api/client-contract/auth.md +++ b/docs/api/client-contract/auth.md @@ -119,13 +119,36 @@ Implementation notes: Source of truth: `hub/src/web/routes/passkey.ts`, `hub/src/web/authTokens.ts`, `web/src/lib/passkey.ts`. -The web app can sign in with a WebAuthn passkey instead of pasting the access token. Native clients keep using the access token: passkeys are bound to a web origin, and self-hosted hubs cannot rely on associated domains. +The web app can sign in with a WebAuthn passkey instead of pasting the access token. Native apps use the same endpoints with a fixed RP ID; see [Native passkeys](#passkeys-native). - **Registration needs an existing session.** `POST /api/passkey/register/{options,verify}` require a JWT, so the first sign-in still uses the access token (or Telegram). The passkey is stored with the JWT's namespace and an HMAC fingerprint of the current `CLI_API_TOKEN`. - **Relying party.** The RP ID is the hostname of the request's `Origin`. The origin must use HTTPS, or HTTP on `localhost`, and must be a domain name rather than an IP address. It must also be trusted: either the same host as the request (the hub-served web app) or an entry in the hub's CORS origins (a wildcard does not count). A passkey only works on the RP ID where it was registered. - **Sign-in.** `POST /api/passkey/login/options` returns a one-time challenge that expires after 5 minutes. `POST /api/passkey/login/verify` with `{ "response": }` requires user verification and returns `{ token, user, passkeySession }`. The web stores `passkeySession` under `hapi_passkey_session::` instead of an access token, then refreshes with `POST /api/auth { "passkeySession": "..." }`. - **Revocation.** Rotating `CLI_API_TOKEN` invalidates every passkey and passkey session registered under the old token (`GET /api/passkeys` reports `valid: false`). Deleting a passkey (`DELETE /api/passkeys/:id`) revokes its sessions immediately. +## Native passkeys {#passkeys-native} + +Source of truth: `hub/src/web/routes/passkey.ts` (`nativePasskeyConfigFromEnv`), `website/public/.well-known/`. + +iOS entitlements and Android asset links are fixed at build time, so they cannot follow a self-hosted hub's domain. The official apps therefore use one shared RP ID, **`hapi.run`**: + +- `https://hapi.run/.well-known/apple-app-site-association` lists `webcredentials` for `XJB862F92W.run.hapi.app`. The iOS/macOS app declares `webcredentials:hapi.run` in its Associated Domains entitlement. +- `https://hapi.run/.well-known/assetlinks.json` grants `delegate_permission/common.get_login_creds` to `run.hapi.companion` with its signing-certificate SHA-256. +- Every hub accepts assertions for `hapi.run` only from exact app origins: + - iOS/macOS (AuthenticationServices): `https://hapi.run`. + - Android (Credential Manager): `android:apk-key-hash:`. Official hashes live in `OFFICIAL_ANDROID_PASSKEY_ORIGINS`. + - `HAPI_PASSKEY_NATIVE_ORIGINS` (comma-separated) adds origins, e.g. for debug builds. `HAPI_PASSKEY_NATIVE_RP_ID` changes the RP ID for forks that ship their own apps and domain. + + Pages on other `*.hapi.run` hosts can request `hapi.run` assertions, but the hub rejects their origins. + +Client flow (same endpoints as the web; natives send no `Origin` header): + +1. **Register** (needs a JWT from the normal access-token exchange): `POST /api/passkey/register/options` with `{ "client": "native" }`. The response is WebAuthn `PublicKeyCredentialCreationOptionsJSON` with `rp.id == "hapi.run"`, a base64url `user.id`, and `user.name` of the form `hapi[:]@` so the system picker can tell hubs apart. Create the credential with the platform API, then `POST /api/passkey/register/verify` with `{ "response": , "name": "" }`. +2. **Sign in** (no JWT): `POST /api/passkey/login/options` with `{ "client": "native" }`. The response is `PublicKeyCredentialRequestOptionsJSON` whose `allowCredentials` lists this hub's valid native passkeys, so the sheet does not offer other hubs' passkeys. `404 {"error":"no_passkeys"}` means none are registered; fall back to the access token. Then `POST /api/passkey/login/verify` with `{ "response": }` returns `{ token, user, passkeySession }`. +3. **Refresh**: store `passkeySession` in secure storage, keyed per hub like the access token. Exchange it with `POST /api/auth { "passkeySession": "..." }` in the normal silent re-auth loop. `401 passkey_session_invalid` is terminal: ask the user to sign in again. + +All binary fields are base64url without padding. Registration and sign-in require user verification. Clients should check `rp.id` / `rpId` against their compiled RP ID and refuse a mismatch. + ## Namespaces Source of truth: `hub/src/web/middleware/auth.ts` (sets `namespace` from `ns`), `hub/src/web/routes/guards.ts`, `hub/src/web/routes/{usage,storage,hubSettings,voice}.ts`. diff --git a/docs/guide/native-apps.md b/docs/guide/native-apps.md index d341a517..ec54a3f2 100644 --- a/docs/guide/native-apps.md +++ b/docs/guide/native-apps.md @@ -68,6 +68,11 @@ working connection. Prefer HTTPS on both platforms. Camera pairing is optional. Use manual entry on an iOS Simulator or any device without a usable scanner. +After you pair a device with the access token, you can add a passkey for that hub in **Settings → Passkeys**. iOS syncs it through iCloud Keychain, and Android 9+ through Google Password Manager. On another device, choose **Sign in with a passkey** on the pairing screen and enter only the hub URL. + +- App passkeys use the shared `hapi.run` relying party. Passkeys created in the web app cannot sign in to the apps; the list shows them so you can manage them. +- Rotating the hub's access token, or deleting the passkey, signs out every device that signed in with it. + ## Sessions and everyday use Start an agent on your computer with `hapi` and choose an installed agent, or diff --git a/hub/src/store/passkeyStore.ts b/hub/src/store/passkeyStore.ts index 41716dab..1c537f12 100644 --- a/hub/src/store/passkeyStore.ts +++ b/hub/src/store/passkeyStore.ts @@ -113,7 +113,14 @@ export class PasskeyStore { return rows.map(toStored) } - recordUse(id: string, counter: number, usedAt: number): void { + listByRpId(rpId: string): StoredPasskeyCredential[] { + const rows = this.db.prepare( + 'SELECT * FROM passkey_credentials WHERE rp_id = ? ORDER BY created_at ASC' + ).all(rpId) as DbPasskeyRow[] + return rows.map(toStored) + } + + recordUse(id: string, counter: number, usedAt: number): void { this.db.prepare( 'UPDATE passkey_credentials SET counter = ?, last_used_at = ? WHERE id = ?' ).run(counter, usedAt, id) diff --git a/hub/src/web/routes/passkey.test.ts b/hub/src/web/routes/passkey.test.ts index ae676769..95bb0b6b 100644 --- a/hub/src/web/routes/passkey.test.ts +++ b/hub/src/web/routes/passkey.test.ts @@ -13,6 +13,7 @@ import { createAuthRoutes } from './auth' import { createPasskeyLoginRoutes, createPasskeyManagementRoutes, + nativePasskeyConfigFromEnv, PasskeyChallengeStore, resolveRelyingParty } from './passkey' @@ -20,6 +21,7 @@ import { const JWT_SECRET = new Uint8Array(randomBytes(32)) const ORIGIN = 'https://hub.example.com' const HOST = 'hub.example.com' +const ANDROID_ORIGIN = 'android:apk-key-hash:test-hash' const b64url = (bytes: Uint8Array | Buffer) => Buffer.from(bytes).toString('base64url') const sha256 = (data: Uint8Array | string) => createHash('sha256').update(data).digest() @@ -67,7 +69,8 @@ class SoftAuthenticator { attestationObject: b64url(attestationObject), transports: ['internal'] }, - clientExtensionResults: {} + clientExtensionResults: {}, + authenticatorAttachment: null } } @@ -95,7 +98,13 @@ class SoftAuthenticator { function createApp(store: Store) { const app = new Hono() - const deps = { jwtSecret: JWT_SECRET, store, corsOrigins: () => [], challenges: new PasskeyChallengeStore() } + const deps = { + jwtSecret: JWT_SECRET, + store, + corsOrigins: () => [], + challenges: new PasskeyChallengeStore(), + native: { rpId: 'hapi.run', origins: ['https://hapi.run', ANDROID_ORIGIN] } + } app.route('/api', createAuthRoutes(JWT_SECRET, store)) app.route('/api', createPasskeyLoginRoutes(deps)) app.use('/api/*', createAuthMiddleware(JWT_SECRET)) @@ -219,9 +228,9 @@ describe('passkey routes', () => { describe('resolveRelyingParty', () => { it('requires a trusted, secure, domain-name origin', () => { - expect(resolveRelyingParty('https://hub.example.com', 'hub.example.com', [])).toEqual({ origin: 'https://hub.example.com', rpId: 'hub.example.com' }) - expect(resolveRelyingParty('http://localhost:3006', 'localhost:3006', [])).toEqual({ origin: 'http://localhost:3006', rpId: 'localhost' }) - expect(resolveRelyingParty('https://app.hapi.run', 'abc.relay.hapi.run', ['https://app.hapi.run'])).toEqual({ origin: 'https://app.hapi.run', rpId: 'app.hapi.run' }) + expect(resolveRelyingParty('https://hub.example.com', 'hub.example.com', [])).toEqual({ origins: ['https://hub.example.com'], rpId: 'hub.example.com' }) + expect(resolveRelyingParty('http://localhost:3006', 'localhost:3006', [])).toEqual({ origins: ['http://localhost:3006'], rpId: 'localhost' }) + expect(resolveRelyingParty('https://app.hapi.run', 'abc.relay.hapi.run', ['https://app.hapi.run'])).toEqual({ origins: ['https://app.hapi.run'], rpId: 'app.hapi.run' }) expect(resolveRelyingParty('https://app.hapi.run', 'abc.relay.hapi.run', ['*'])).toHaveProperty('error') expect(resolveRelyingParty('http://hub.example.com', 'hub.example.com', [])).toHaveProperty('error') expect(resolveRelyingParty('http://192.168.1.2:3006', '192.168.1.2:3006', [])).toHaveProperty('error') @@ -233,7 +242,7 @@ describe('PasskeyChallengeStore', () => { it('is one-time, expires, and evicts the oldest entry instead of refusing new ones', () => { let now = 0 const store = new PasskeyChallengeStore(() => now) - const entry = (expiresAt: number) => ({ kind: 'login' as const, rpId: 'r', origin: 'o', expiresAt }) + const entry = (expiresAt: number) => ({ kind: 'login' as const, rpId: 'r', origins: ['o'], expiresAt }) store.put('a', entry(100)) expect(store.take('a')).not.toBeNull() expect(store.take('a')).toBeNull() @@ -247,3 +256,72 @@ describe('PasskeyChallengeStore', () => { expect(store.take('c299')).not.toBeNull() }) }) + +/** Native clients send no Origin header and ask for the fixed native RP. */ +function postNative(app: Hono, path: string, body: unknown, extra: Record = {}) { + return app.request(path, { + method: 'POST', + headers: { host: HOST, 'content-type': 'application/json', ...extra }, + body: JSON.stringify(body) + }) +} + +describe('native passkeys', () => { + async function registerNative(app: Hono, authenticator: SoftAuthenticator) { + const auth = await bearer() + const options = await (await postNative(app, '/api/passkey/register/options', { client: 'native' }, auth)).json() as { + challenge: string; rp: { id: string }; user: { id: string; name: string } + } + expect(options.rp.id).toBe('hapi.run') + expect(options.user.name).toBe(`hapi@${HOST}`) + const res = await postNative(app, '/api/passkey/register/verify', { response: authenticator.create(options) }, auth) + expect(res.status).toBe(200) + } + + async function loginNative(app: Hono, authenticator: SoftAuthenticator) { + const optionsRes = await postNative(app, '/api/passkey/login/options', { client: 'native' }) + if (optionsRes.status !== 200) return optionsRes + const options = await optionsRes.json() as { challenge: string; rpId: string; allowCredentials: Array<{ id: string }> } + expect(options.rpId).toBe('hapi.run') + expect(options.allowCredentials.map((c) => c.id)).toEqual([b64url(authenticator.credentialId)]) + return await postNative(app, '/api/passkey/login/verify', { response: authenticator.get(options) }) + } + + it('registers and signs in from iOS and Android app origins on the shared RP ID', async () => { + const store = new Store(':memory:') + const app = createApp(store) + expect(await (await postNative(app, '/api/passkey/login/options', { client: 'native' })).json()).toEqual({ error: 'no_passkeys' }) + + for (const origin of ['https://hapi.run', ANDROID_ORIGIN]) { + const authenticator = new SoftAuthenticator('hapi.run', origin) + await registerNative(app, authenticator) + const res = await loginNative(app, authenticator) + expect(res.status).toBe(200) + expect(await res.json()).toHaveProperty('passkeySession') + store.passkeys.remove(b64url(authenticator.credentialId), 'default') + } + store.close() + }) + + it('rejects assertions for the native RP ID from any other origin', async () => { + const store = new Store(':memory:') + const app = createApp(store) + const authenticator = new SoftAuthenticator('hapi.run', 'https://hapi.run') + await registerNative(app, authenticator) + // e.g. a page on another hapi.run subdomain may request hapi.run passkeys. + for (const origin of ['https://evil.relay.hapi.run', 'android:apk-key-hash:other-app']) { + const forged = new SoftAuthenticator('hapi.run', origin) + Object.assign(forged, { credentialId: authenticator.credentialId }) + expect((await loginNative(app, forged)).status).toBe(401) + } + store.close() + }) + + it('reads the native RP and extra origins from the environment', () => { + expect(nativePasskeyConfigFromEnv({})).toEqual({ rpId: 'hapi.run', origins: ['https://hapi.run'] }) + expect(nativePasskeyConfigFromEnv({ + HAPI_PASSKEY_NATIVE_RP_ID: 'fork.example', + HAPI_PASSKEY_NATIVE_ORIGINS: ' android:apk-key-hash:debug , https://fork.example' + })).toEqual({ rpId: 'fork.example', origins: ['https://fork.example', 'android:apk-key-hash:debug'] }) + }) +}) diff --git a/hub/src/web/routes/passkey.ts b/hub/src/web/routes/passkey.ts index 8689b19e..32a49be5 100644 --- a/hub/src/web/routes/passkey.ts +++ b/hub/src/web/routes/passkey.ts @@ -10,6 +10,7 @@ import type { AuthenticationResponseJSON, RegistrationResponseJSON } from '@simp import { decodeClientDataJSON } from '@simplewebauthn/server/helpers' import { PasskeyLoginVerifyRequestSchema, + PasskeyOptionsRequestSchema, PasskeyRegisterVerifyRequestSchema, type PasskeyListResponse } from '@hapi/protocol' @@ -30,8 +31,47 @@ const MAX_PENDING_CHALLENGES = 256 const RP_NAME = 'HAPI' type ChallengeEntry = - | { kind: 'register'; rpId: string; origin: string; namespace: string; expiresAt: number } - | { kind: 'login'; rpId: string; origin: string; expiresAt: number } + | { kind: 'register'; rpId: string; origins: string[]; namespace: string; expiresAt: number } + | { kind: 'login'; rpId: string; origins: string[]; expiresAt: number } + +/** + * Relying party used by the official native apps. Their entitlements / asset + * links are compiled in, so they cannot follow a self-hosted hub's domain; + * instead every hub accepts this fixed RP ID, restricted to exact app origins: + * `https://` for iOS/macOS (AuthenticationServices) and + * `android:apk-key-hash:` for Android. + */ +export type NativePasskeyConfig = { + rpId: string + origins: string[] +} + +export const DEFAULT_NATIVE_PASSKEY_RP_ID = 'hapi.run' + +/** + * `android:apk-key-hash:` origins of official Android builds. + * TODO(passkey): add the Play App Signing certificate hash (base64url, no + * padding, of the SHA-256 shown in Play Console → App signing). Until then + * Android passkeys only work when HAPI_PASSKEY_NATIVE_ORIGINS lists the hash. + */ +export const OFFICIAL_ANDROID_PASSKEY_ORIGINS: readonly string[] = [] + +function parseList(value: string | undefined): string[] { + return (value ?? '').split(',').map((item) => item.trim()).filter(Boolean) +} + +/** + * HAPI_PASSKEY_NATIVE_RP_ID overrides the RP ID (forks shipping their own + * apps). HAPI_PASSKEY_NATIVE_ORIGINS adds origins, e.g. a debug build's + * `android:apk-key-hash:...`. + */ +export function nativePasskeyConfigFromEnv(env: Record = process.env): NativePasskeyConfig { + const rpId = env.HAPI_PASSKEY_NATIVE_RP_ID?.trim() || DEFAULT_NATIVE_PASSKEY_RP_ID + const defaults = rpId === DEFAULT_NATIVE_PASSKEY_RP_ID + ? [`https://${rpId}`, ...OFFICIAL_ANDROID_PASSKEY_ORIGINS] + : [`https://${rpId}`] + return { rpId, origins: [...new Set([...defaults, ...parseList(env.HAPI_PASSKEY_NATIVE_ORIGINS)])] } +} /** * One-time WebAuthn challenges. Entries are removed on first lookup, so a @@ -88,7 +128,7 @@ export function resolveRelyingParty( originHeader: string | undefined, hostHeader: string | undefined, corsOrigins: string[] -): { origin: string; rpId: string } | { error: string } { +): { origins: string[]; rpId: string } | { error: string } { if (!originHeader) { return { error: 'Missing Origin header' } } @@ -113,11 +153,18 @@ export function resolveRelyingParty( if (!sameHost && !listed) { return { error: 'Origin is not allowed to use passkeys' } } - return { origin, rpId: hostname } + return { origins: [origin], rpId: hostname } } -function relyingPartyFor(c: Context, corsOrigins: () => string[]) { - return resolveRelyingParty(c.req.header('origin'), c.req.header('host'), corsOrigins()) +/** Web clients use the Origin header; native apps ask for the fixed native RP. */ +async function relyingPartyFor(c: Context, deps: PasskeyRouteDeps) { + const body = PasskeyOptionsRequestSchema.safeParse(await c.req.json().catch(() => ({}))) + const client = body.success ? body.data.client : 'web' + if (client === 'native') { + return { ...deps.native, client } + } + const rp = resolveRelyingParty(c.req.header('origin'), c.req.header('host'), deps.corsOrigins()) + return 'error' in rp ? rp : { ...rp, client } } function currentFingerprint(jwtSecret: Uint8Array): string { @@ -137,6 +184,7 @@ export type PasskeyRouteDeps = { store: Store corsOrigins: () => string[] challenges: PasskeyChallengeStore + native: NativePasskeyConfig } /** Unauthenticated: exchange a passkey assertion for a web JWT + passkey session. */ @@ -145,18 +193,30 @@ export function createPasskeyLoginRoutes(deps: PasskeyRouteDeps): Hono { - const rp = relyingPartyFor(c, deps.corsOrigins) + const rp = await relyingPartyFor(c, deps) if ('error' in rp) { return c.json({ error: rp.error }, 400) } + // The native RP ID is shared by every hub, so the platform sheet would + // otherwise offer passkeys of other hubs; restrict it to this hub's. + const fingerprint = currentFingerprint(jwtSecret) + const allowCredentials = rp.client === 'native' + ? store.passkeys.listByRpId(rp.rpId) + .filter((p) => constantTimeEquals(p.tokenFingerprint, fingerprint)) + .map((p) => ({ id: p.id, transports: p.transports })) + : undefined + if (allowCredentials && allowCredentials.length === 0) { + return c.json({ error: 'no_passkeys' }, 404) + } const options = await generateAuthenticationOptions({ rpID: rp.rpId, + allowCredentials, userVerification: 'required' }) challenges.put(options.challenge, { kind: 'login', rpId: rp.rpId, - origin: rp.origin, + origins: rp.origins, expiresAt: Date.now() + CHALLENGE_TTL_MS }) return c.json(options) @@ -187,7 +247,7 @@ export function createPasskeyLoginRoutes(deps: PasskeyRouteDeps): Hono { - const rp = relyingPartyFor(c, deps.corsOrigins) + const rp = await relyingPartyFor(c, deps) if ('error' in rp) { return c.json({ error: rp.error }, 400) } const namespace = c.get('namespace') const existing = store.passkeys.listByNamespace(namespace).filter((p) => p.rpId === rp.rpId) + const account = namespace === 'default' ? 'hapi' : `hapi:${namespace}` + // Native passkeys share one RP ID across hubs: name them after the hub + // so the platform account picker can tell them apart. + const hubHost = c.req.header('host') ?? 'hub' const options = await generateRegistrationOptions({ rpName: RP_NAME, rpID: rp.rpId, userID: passkeyUserHandle(jwtSecret, namespace), - userName: namespace === 'default' ? 'hapi' : `hapi:${namespace}`, - userDisplayName: namespace === 'default' ? 'HAPI' : `HAPI (${namespace})`, + userName: rp.client === 'native' ? `${account}@${hubHost}` : account, + userDisplayName: rp.client === 'native' + ? `HAPI · ${hubHost}${namespace === 'default' ? '' : ` (${namespace})`}` + : namespace === 'default' ? 'HAPI' : `HAPI (${namespace})`, attestationType: 'none', excludeCredentials: existing.map((p) => ({ id: p.id, transports: p.transports })), authenticatorSelection: { @@ -245,7 +311,7 @@ export function createPasskeyManagementRoutes(deps: PasskeyRouteDeps): Hono corsOrigins, - challenges: new PasskeyChallengeStore() + challenges: new PasskeyChallengeStore(), + native: nativePasskeyConfigFromEnv() } app.route('/api', createPasskeyLoginRoutes(passkeyDeps)) diff --git a/ios/Hapi/Features/Pairing/ManualEntryView.swift b/ios/Hapi/Features/Pairing/ManualEntryView.swift index e97579b9..246b2bbf 100644 --- a/ios/Hapi/Features/Pairing/ManualEntryView.swift +++ b/ios/Hapi/Features/Pairing/ManualEntryView.swift @@ -3,20 +3,36 @@ import SwiftUI /// Manual pairing path for hubs without `--relay` (nothing to scan): type or /// paste the hub URL and the access token the hub prints at startup, then -/// pair directly with inline progress and error states. +/// pair directly with inline progress and error states. The `.passkey` mode +/// asks only for the hub URL and signs in with a native passkey. struct ManualEntryView: View { + enum Mode { + case accessToken + case passkey + } + + var mode: Mode = .accessToken + @Environment(\.dismiss) private var dismiss @Environment(AppModel.self) private var model @State private var attempt = PairingAttempt() var body: some View { NavigationStack { - ManualPairingFormView(isPairing: attempt.isPairing, failure: attempt.failure) { + ManualPairingFormView( + isPairing: attempt.isPairing, + failure: attempt.failure, + passkeyOnly: mode == .passkey + ) { attempt.failure = nil } onPair: { submission in attempt.pair(model, hubUrl: submission.hubURL, accessToken: submission.accessToken) + } onPasskeySignIn: { hubURL in + attempt.signInWithPasskey(model, hubUrl: hubURL) } - .navigationTitle("Enter Hub Details") + .navigationTitle(mode == .passkey + ? String(localized: "Sign in with a Passkey") + : String(localized: "Enter Hub Details")) .navigationBarTitleDisplayMode(.inline) .toolbar { ToolbarItem(placement: .cancellationAction) { @@ -36,8 +52,13 @@ struct ManualEntryView: View { struct ManualPairingFormView: View { let isPairing: Bool let failure: PairingFailure? + /// Hub URL only: hides the access token and Pair button, and makes the + /// passkey button the submit action. + var passkeyOnly = false var onEdit: () -> Void var onPair: (ManualPairingForm.Submission) -> Void + /// URL-only native passkey sign-in (shown in `passkeyOnly` mode). + var onPasskeySignIn: ((String) -> Void)? = nil @Environment(\.dynamicTypeSize) private var typeSize @Environment(\.locale) private var locale @@ -93,44 +114,83 @@ struct ManualPairingFormView: View { } } - Section { - input(.accessToken) - inputError(for: .accessToken) - } header: { - Text("Access token") - } footer: { - Text("Printed by the hub at startup, or available in web Settings → Companion Pairing. You can also paste a pairing link here.") - } - - if form.didImportLink { - Section { - Label("Pairing details filled in. Review them, then tap Pair.", systemImage: "checkmark.circle") - .foregroundStyle(.secondary) - .accessibilityIdentifier("pairing.imported") - } + if !passkeyOnly { + tokenSections } if let failure { Section { PairingErrorView(failure: failure) } } - Section { - Button(action: pairNow) { - if isPairing { - HStack(spacing: 8) { - ProgressView() - .progressViewStyle(.circular) - Text("Pairing…") - } - .frame(maxWidth: .infinity) - } else { - Text(failure == nil ? LocalizedStringKey("Pair") : LocalizedStringKey("Try Again")) - .frame(maxWidth: .infinity) - } - } - .accessibilityIdentifier("pairing.submit") - .disabled(form.submission == nil || isPairing) + if !passkeyOnly { + pairSection } + + if passkeyOnly, onPasskeySignIn != nil { + passkeySection + } + } + } + + @ViewBuilder + private var tokenSections: some View { + Section { + input(.accessToken) + inputError(for: .accessToken) + } header: { + Text("Access token") + } footer: { + Text("Printed by the hub at startup, or available in web Settings → Companion Pairing. You can also paste a pairing link here.") + } + + if form.didImportLink { + Section { + Label("Pairing details filled in. Review them, then tap Pair.", systemImage: "checkmark.circle") + .foregroundStyle(.secondary) + .accessibilityIdentifier("pairing.imported") + } + } + } + + private var pairSection: some View { + Section { + Button(action: pairNow) { + if isPairing { + HStack(spacing: 8) { + ProgressView() + .progressViewStyle(.circular) + Text("Pairing…") + } + .frame(maxWidth: .infinity) + } else { + Text(failure == nil ? LocalizedStringKey("Pair") : LocalizedStringKey("Try Again")) + .frame(maxWidth: .infinity) + } + } + .accessibilityIdentifier("pairing.submit") + .disabled(form.submission == nil || isPairing) + } + } + + private var passkeySection: some View { + Section { + Button(action: signInWithPasskey) { + if isPairing { + HStack(spacing: 8) { + ProgressView() + .progressViewStyle(.circular) + Text("Signing in…") + } + .frame(maxWidth: .infinity) + } else { + Label("Sign in with a Passkey", systemImage: "person.badge.key") + .frame(maxWidth: .infinity) + } + } + .accessibilityIdentifier("pairing.passkey") + .disabled(form.passkeyHubURL == nil || isPairing) + } footer: { + Text("Uses a passkey you added for this hub in Settings → Passkeys. No access token needed.") } } @@ -162,7 +222,9 @@ struct ManualPairingFormView: View { }, onReturn: { guard !isPairing else { return } - if field == .address { + if field == .address && passkeyOnly { + signInWithPasskey() + } else if field == .address { form.finishEditing(field) focusedField = .accessToken } else { @@ -187,6 +249,14 @@ struct ManualPairingFormView: View { } } + private func signInWithPasskey() { + guard !isPairing else { return } + form.finishEditing(.address) + guard let hubURL = form.passkeyHubURL else { return } + focusedField = nil + onPasskeySignIn?(hubURL) + } + private func pairNow() { guard !isPairing else { return } form.finishEditing(.address) diff --git a/ios/Hapi/Features/Pairing/ManualPairingForm.swift b/ios/Hapi/Features/Pairing/ManualPairingForm.swift index 4e98ee41..5e114328 100644 --- a/ios/Hapi/Features/Pairing/ManualPairingForm.swift +++ b/ios/Hapi/Features/Pairing/ManualPairingForm.swift @@ -37,6 +37,13 @@ struct ManualPairingForm { return Submission(hubURL: origin, accessToken: trimmed(accessToken)) } + /// Hub origin for a URL-only passkey sign-in: the address alone must be + /// valid (the access token is not needed). + var passkeyHubURL: String? { + guard validationError(for: .address) == nil else { return nil } + return normalizedAddress(address) + } + func text(for field: Field) -> String { field == .address ? address : accessToken } diff --git a/ios/Hapi/Features/Pairing/PairingAttempt.swift b/ios/Hapi/Features/Pairing/PairingAttempt.swift index 55670aff..90870acb 100644 --- a/ios/Hapi/Features/Pairing/PairingAttempt.swift +++ b/ios/Hapi/Features/Pairing/PairingAttempt.swift @@ -1,8 +1,8 @@ import HapiClient import Observation -/// Inline pairing progress/error state shared by manual entry, QR scan, -/// and the deep-link confirm step. +/// Inline pairing progress/error state shared by manual entry (token or +/// passkey), QR scan, and the deep-link confirm step. @Observable @MainActor final class PairingAttempt { private(set) var isPairing = false @@ -25,4 +25,24 @@ final class PairingAttempt { isPairing = false } } + + /// URL-only passkey sign-in. Dismissing the system sheet is not an + /// error: the form simply returns to its idle state. + func signInWithPasskey(_ model: AppModel, hubUrl: String) { + guard !isPairing else { return } + isPairing = true + failure = nil + Task { + do { + try await model.signInWithPasskey(hubUrl: hubUrl) + } catch PasskeyError.canceled { + // Silent. + } catch let pairingFailure as PairingFailure { + failure = pairingFailure + } catch { + failure = .unreachable + } + isPairing = false + } + } } diff --git a/ios/Hapi/Features/Pairing/PairingConfirmView.swift b/ios/Hapi/Features/Pairing/PairingConfirmView.swift index 62399272..fabfe830 100644 --- a/ios/Hapi/Features/Pairing/PairingConfirmView.swift +++ b/ios/Hapi/Features/Pairing/PairingConfirmView.swift @@ -94,6 +94,7 @@ struct PairingErrorView: View { case .invalidAccessToken: "key" case .hubError: "exclamationmark.triangle" case .storageFailure: "externaldrive.badge.xmark" + case .noPasskeys, .passkeyRejected, .passkeyUnavailable: "person.badge.key" } } @@ -105,6 +106,9 @@ struct PairingErrorView: View { case .invalidAccessToken: String(localized: "Token rejected") case .hubError: String(localized: "Hub error") case .storageFailure: String(localized: "Could not save") + case .noPasskeys: String(localized: "No passkeys for this hub") + case .passkeyRejected: String(localized: "Passkey rejected") + case .passkeyUnavailable: String(localized: "Passkey unavailable") } } @@ -129,6 +133,12 @@ struct PairingErrorView: View { ) case .storageFailure: String(localized: "Pairing succeeded but the credentials could not be stored on this device. Try again.") + case .noPasskeys: + String(localized: "This hub has no passkeys for the app yet. Pair with the access token, then add a passkey in Settings → Passkeys.") + case .passkeyRejected: + String(localized: "The hub did not accept this passkey. It may have been deleted, or the hub's access token was rotated. Pair with the access token instead.") + case .passkeyUnavailable: + String(localized: "This device could not use a passkey for this hub. Try again, or pair with the access token.") } } } diff --git a/ios/Hapi/Features/Pairing/PairingFlowView.swift b/ios/Hapi/Features/Pairing/PairingFlowView.swift index 8c8a2bc1..61755ec5 100644 --- a/ios/Hapi/Features/Pairing/PairingFlowView.swift +++ b/ios/Hapi/Features/Pairing/PairingFlowView.swift @@ -27,6 +27,7 @@ struct PairingFlowView: View { #endif } @State private var showManualEntry = false + @State private var showPasskeySignIn = false private static let docsURL = URL(string: "https://hapi.run/docs/guide/quick-start") @@ -70,6 +71,8 @@ struct PairingFlowView: View { } .buttonStyle(.borderedProminent) .controlSize(.large) + + passkeyButton #else Button { showScanner = true @@ -88,6 +91,8 @@ struct PairingFlowView: View { } .buttonStyle(.bordered) .controlSize(.large) + + passkeyButton #endif } .padding(.horizontal, 24) @@ -118,9 +123,27 @@ struct PairingFlowView: View { ManualEntryView() .macSheetSizing() } + .sheet(isPresented: $showPasskeySignIn) { + ManualEntryView(mode: .passkey) + .macSheetSizing() + } } } + /// URL-only sign-in for hubs where a passkey was already added + /// (Settings → Passkeys after a token pairing). + private var passkeyButton: some View { + Button { + showPasskeySignIn = true + } label: { + Label("Sign in with a Passkey", systemImage: "person.badge.key") + .frame(maxWidth: .infinity) + } + .buttonStyle(.bordered) + .controlSize(.large) + .accessibilityIdentifier("pairing.passkeyEntry") + } + private func authFailureBanner(failedHub: String) -> some View { HStack(alignment: .top, spacing: 12) { Image(systemName: "exclamationmark.triangle.fill") diff --git a/ios/Hapi/Features/Passkeys/PlatformPasskeyAuthenticator.swift b/ios/Hapi/Features/Passkeys/PlatformPasskeyAuthenticator.swift new file mode 100644 index 00000000..7bb07b07 --- /dev/null +++ b/ios/Hapi/Features/Passkeys/PlatformPasskeyAuthenticator.swift @@ -0,0 +1,140 @@ +import AuthenticationServices +import HapiClient +import UIKit + +/// AuthenticationServices implementation of ``PasskeyAuthenticating``. +/// +/// Native passkeys live on the shared RP ID `hapi.run` +/// (`webcredentials:hapi.run` in the Associated Domains entitlement, backed by +/// `https://hapi.run/.well-known/apple-app-site-association`); the system +/// reports the origin `https://hapi.run`, which every hub accepts. Options +/// arrive already RP-checked and decoded (``PasskeyRegistrationRequest`` / +/// ``PasskeyAssertionRequest``); this type only drives the system sheet and +/// returns raw bytes for HapiClient to encode as base64url JSON. +struct PlatformPasskeyAuthenticator: PasskeyAuthenticating { + func register(_ request: PasskeyRegistrationRequest) async throws -> PasskeyRegistrationResult { + let authorization = try await PasskeyCeremony.perform { + let provider = ASAuthorizationPlatformPublicKeyCredentialProvider( + relyingPartyIdentifier: request.relyingPartyID + ) + let registration = provider.createCredentialRegistrationRequest( + challenge: request.challenge, + name: request.userName, + userID: request.userID + ) + registration.userVerificationPreference = .required + if #available(iOS 17.4, macCatalyst 17.4, *) { + registration.excludedCredentials = request.excludedCredentialIDs.map { + ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) + } + } + return registration + } + guard let credential = authorization.credential + as? ASAuthorizationPlatformPublicKeyCredentialRegistration else { + throw PasskeyError.platform("Unexpected credential type") + } + guard let attestation = credential.rawAttestationObject, !attestation.isEmpty else { + throw PasskeyError.missingAttestation + } + return PasskeyRegistrationResult( + credentialID: credential.credentialID, + clientDataJSON: credential.rawClientDataJSON, + attestationObject: attestation + ) + } + + func authenticate(_ request: PasskeyAssertionRequest) async throws -> PasskeyAssertionResult { + let authorization = try await PasskeyCeremony.perform { + let provider = ASAuthorizationPlatformPublicKeyCredentialProvider( + relyingPartyIdentifier: request.relyingPartyID + ) + let assertion = provider.createCredentialAssertionRequest(challenge: request.challenge) + assertion.userVerificationPreference = .required + // Restrict the sheet to this hub's passkeys: every hub shares the + // RP ID, so an empty list would offer all of them. + assertion.allowedCredentials = request.allowedCredentialIDs.map { + ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) + } + return assertion + } + guard let credential = authorization.credential + as? ASAuthorizationPlatformPublicKeyCredentialAssertion else { + throw PasskeyError.platform("Unexpected credential type") + } + return PasskeyAssertionResult( + credentialID: credential.credentialID, + clientDataJSON: credential.rawClientDataJSON, + authenticatorData: credential.rawAuthenticatorData, + signature: credential.signature, + userID: credential.userID + ) + } +} + +/// One `ASAuthorizationController` run bridged to async/await. Kept alive in +/// ``inFlight`` until the delegate fires (the controller holds its delegate +/// weakly). +@MainActor +private final class PasskeyCeremony: NSObject, + ASAuthorizationControllerDelegate, + ASAuthorizationControllerPresentationContextProviding { + private static var inFlight: Set = [] + + private var continuation: CheckedContinuation? + private var controller: ASAuthorizationController? + + static func perform( + _ makeRequest: @MainActor () -> ASAuthorizationRequest + ) async throws -> ASAuthorization { + let ceremony = PasskeyCeremony() + let request = makeRequest() + return try await withCheckedThrowingContinuation { continuation in + ceremony.start(request, continuation: continuation) + } + } + + private func start(_ request: ASAuthorizationRequest, continuation: CheckedContinuation) { + self.continuation = continuation + let controller = ASAuthorizationController(authorizationRequests: [request]) + controller.delegate = self + controller.presentationContextProvider = self + self.controller = controller + Self.inFlight.insert(self) + controller.performRequests() + } + + private func finish(_ result: Result) { + continuation?.resume(with: result) + continuation = nil + controller = nil + Self.inFlight.remove(self) + } + + func authorizationController( + controller: ASAuthorizationController, + didCompleteWithAuthorization authorization: ASAuthorization + ) { + finish(.success(authorization)) + } + + func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) { + if let authorizationError = error as? ASAuthorizationError, authorizationError.code == .canceled { + finish(.failure(PasskeyError.canceled)) + } else { + finish(.failure(PasskeyError.platform(error.localizedDescription))) + } + } + + func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor { + let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first + if let window = scene?.keyWindow ?? scene?.windows.first { + return window + } + if let scene { + return UIWindow(windowScene: scene) + } + return ASPresentationAnchor() + } +} diff --git a/ios/Hapi/Features/Settings/PasskeysView.swift b/ios/Hapi/Features/Settings/PasskeysView.swift new file mode 100644 index 00000000..ab8f6b58 --- /dev/null +++ b/ios/Hapi/Features/Settings/PasskeysView.swift @@ -0,0 +1,322 @@ +import HapiClient +import SwiftUI +import UIKit + +/// Passkeys of the active hub's namespace (`GET /api/passkeys`): add one for +/// this device (native RP `hapi.run`), delete any. Web passkeys (other RP +/// IDs) are listed for management only — the app cannot sign in with them. +@MainActor @Observable +final class PasskeysModel { + enum LoadState: Equatable { + case loading + case loaded + /// The hub predates passkeys (`404` on the list endpoint). + case unsupported + case failed(String?) + } + + private(set) var passkeys: [PasskeySummary] = [] + private(set) var loadState: LoadState = .loading + private(set) var isAdding = false + private(set) var deletingIds: Set = [] + /// Last add/delete failure, shown as an alert. + var actionError: String? + + private let api: APIClient + private let authenticator: any PasskeyAuthenticating + + init(api: APIClient, authenticator: any PasskeyAuthenticating = PlatformPasskeyAuthenticator()) { + self.api = api + self.authenticator = authenticator + } + + /// Default name for a new passkey: the device name (`iPhone`, `iPad`, + /// the Mac's name on Catalyst). + static var defaultPasskeyName: String { + let name = UIDevice.current.name.trimmingCharacters(in: .whitespacesAndNewlines) + return name.isEmpty ? UIDevice.current.model : name + } + + func load() async { + do { + passkeys = try await api.listPasskeys() + loadState = .loaded + } catch is CancellationError { + // View went away mid-flight. + } catch let error as APIError where error.status == 404 { + loadState = .unsupported + } catch { + if loadState != .loaded { + loadState = .failed(error.localizedDescription) + } + } + } + + func add(name: String) async { + guard !isAdding else { return } + isAdding = true + defer { isAdding = false } + do { + try await api.registerPasskey(name: name, using: authenticator) + await load() + } catch PasskeyError.canceled { + // Dismissed the system sheet: nothing to report. + } catch { + actionError = Self.message(forAddError: error) + } + } + + func delete(_ passkey: PasskeySummary) async { + guard !deletingIds.contains(passkey.id) else { return } + deletingIds.insert(passkey.id) + defer { deletingIds.remove(passkey.id) } + do { + try await api.deletePasskey(id: passkey.id) + passkeys.removeAll { $0.id == passkey.id } + } catch let error as APIError where error.status == 404 { + // Already gone (deleted elsewhere). + passkeys.removeAll { $0.id == passkey.id } + } catch { + actionError = String( + format: String(localized: "Could not delete the passkey: %@"), + error.localizedDescription + ) + } + } + + private static func message(forAddError error: Error) -> String { + switch error { + case PasskeyError.relyingPartyMismatch(let rpId): + return String( + format: String(localized: "The hub requested a passkey for “%@”, but this app only supports hapi.run. Update the hub."), + rpId + ) + case PasskeyError.platform(let detail): + return String( + format: String(localized: "This device could not create the passkey: %@"), + detail + ) + case let apiError as APIError where apiError.status == 409: + return String(localized: "This passkey is already registered with the hub.") + case let apiError as APIError: + return String( + format: String(localized: "The hub could not register the passkey (HTTP %lld)."), + Int64(apiError.status) + ) + default: + return String( + format: String(localized: "Could not add the passkey: %@"), + error.localizedDescription + ) + } + } +} + +/// Settings → Passkeys for the active hub. +struct PasskeysView: View { + @State private var model: PasskeysModel + @State private var showNamePrompt = false + @State private var newName = "" + @State private var pendingDelete: PasskeySummary? + + private let hubUrl: String + + init(session: HubSession) { + _model = State(initialValue: PasskeysModel(api: session.api)) + hubUrl = session.hubUrl + } + + var body: some View { + List { + content + } + .navigationTitle("Passkeys") + .navigationBarTitleDisplayMode(.inline) + .task { await model.load() } + .refreshable { await model.load() } + .alert("Name this passkey", isPresented: $showNamePrompt) { + TextField("Passkey name", text: $newName) + Button("Cancel", role: .cancel) {} + Button("Continue") { + let name = newName + Task { await model.add(name: name) } + } + } message: { + Text("Shown in the hub's passkey list so you can tell your devices apart.") + } + .confirmationDialog( + deleteTitle, + isPresented: Binding( + get: { pendingDelete != nil }, + set: { if !$0 { pendingDelete = nil } } + ), + titleVisibility: .visible, + presenting: pendingDelete + ) { passkey in + Button("Delete Passkey", role: .destructive) { + Task { await model.delete(passkey) } + } + } message: { _ in + Text("Devices signed in with this passkey are signed out of the hub. The passkey itself stays in your password manager until you remove it there.") + } + .alert( + "Passkey", + isPresented: Binding( + get: { model.actionError != nil }, + set: { if !$0 { model.actionError = nil } } + ) + ) { + Button("OK", role: .cancel) {} + } message: { + Text(model.actionError ?? "") + } + } + + @ViewBuilder + private var content: some View { + switch model.loadState { + case .loading: + Section { + HStack { + Spacer() + ProgressView() + Spacer() + } + } + case .unsupported: + Section { + Text("This hub does not support passkeys. Update the hub to use them.") + .foregroundStyle(.secondary) + } + case .failed(let message): + Section { + DashboardErrorView(isForbidden: false, message: message) { + Task { await model.load() } + } + .listRowInsets(EdgeInsets()) + .listRowBackground(Color.clear) + } + case .loaded: + loadedSections + } + } + + @ViewBuilder + private var loadedSections: some View { + Section { + if model.passkeys.isEmpty { + Text("No passkeys yet.") + .foregroundStyle(.secondary) + } + ForEach(model.passkeys) { passkey in + PasskeyRow(passkey: passkey, isDeleting: model.deletingIds.contains(passkey.id)) + .swipeActions(edge: .trailing, allowsFullSwipe: false) { + Button("Delete", role: .destructive) { + pendingDelete = passkey + } + } + .contextMenu { + Button("Delete Passkey…", systemImage: "trash", role: .destructive) { + pendingDelete = passkey + } + } + } + } footer: { + Text("Sign in to \(HubDisplay.host(hubUrl)) from another device with “Sign in with a Passkey” — only the hub URL is needed. Passkeys marked Web belong to the browser and are listed here for management only.") + } + + Section { + Button { + newName = PasskeysModel.defaultPasskeyName + showNamePrompt = true + } label: { + if model.isAdding { + HStack(spacing: 8) { + ProgressView() + Text("Adding passkey…") + } + } else { + Label("Add Passkey", systemImage: "plus") + } + } + .disabled(model.isAdding) + .accessibilityIdentifier("passkeys.add") + } + } + + private var deleteTitle: String { + guard let pendingDelete else { return "" } + return String( + format: String(localized: "Delete “%@”?"), + PasskeyRow.displayName(pendingDelete) + ) + } +} + +private struct PasskeyRow: View { + let passkey: PasskeySummary + let isDeleting: Bool + + static func displayName(_ passkey: PasskeySummary) -> String { + if let name = passkey.name?.trimmingCharacters(in: .whitespacesAndNewlines), !name.isEmpty { + return name + } + return String(localized: "Unnamed passkey") + } + + var body: some View { + HStack(alignment: .top, spacing: 12) { + Image(systemName: passkey.isNative ? "person.badge.key" : "globe") + .foregroundStyle(passkey.valid ? Color.accentColor : Color.secondary) + .frame(width: 24) + VStack(alignment: .leading, spacing: 4) { + HStack(spacing: 6) { + Text(Self.displayName(passkey)) + .foregroundStyle(passkey.valid ? Color.primary : Color.secondary) + if !passkey.isNative { + badge(Text("Web"), color: .blue) + } + if !passkey.valid { + badge(Text("Revoked"), color: .orange) + } + } + if !passkey.isNative { + Text(verbatim: passkey.rpId) + .font(.caption) + .foregroundStyle(.secondary) + } + Text("Created \(passkey.createdDate, format: .dateTime.year().month().day())") + .font(.caption) + .foregroundStyle(.secondary) + if let lastUsed = passkey.lastUsedDate { + Text("Last used \(lastUsed, format: .relative(presentation: .named))") + .font(.caption) + .foregroundStyle(.secondary) + } else { + Text("Never used") + .font(.caption) + .foregroundStyle(.secondary) + } + if !passkey.valid { + Text("Registered before the hub's access token was rotated; it can no longer sign in.") + .font(.caption) + .foregroundStyle(.orange) + } + } + Spacer(minLength: 0) + if isDeleting { + ProgressView() + } + } + .accessibilityElement(children: .combine) + } + + private func badge(_ label: Text, color: Color) -> some View { + label + .font(.caption2.weight(.semibold)) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .foregroundStyle(color) + .background(color.opacity(0.12), in: Capsule()) + } +} diff --git a/ios/Hapi/Features/Settings/SettingsView.swift b/ios/Hapi/Features/Settings/SettingsView.swift index b6437791..a6f47f4b 100644 --- a/ios/Hapi/Features/Settings/SettingsView.swift +++ b/ios/Hapi/Features/Settings/SettingsView.swift @@ -115,8 +115,9 @@ struct SettingsView: View { // MARK: - Sections - /// Every action here leaves Settings: switching or signing out replaces - /// the home screen (it is keyed by hub), and pairing opens from home. + /// Every action here except Passkeys leaves Settings: switching or signing + /// out replaces the home screen (it is keyed by hub), and pairing opens + /// from home. Passkeys manages the active hub's passkeys in place. private var hubsSection: some View { Section("Hubs") { ForEach(appModel.hubs, id: \.self) { hub in @@ -138,6 +139,12 @@ struct SettingsView: View { } .accessibilityAddTraits(isActive ? .isSelected : []) } + NavigationLink { + PasskeysView(session: session) + } label: { + detailRow(title: "Passkeys", detail: "Sign in to this hub without the access token") + } + .accessibilityIdentifier("settings.passkeys") Button("Add Hub…") { // Pairing opens from home, where an incoming bind link can // close it to make room for the root confirm sheet. diff --git a/ios/Hapi/Hapi-macOS.entitlements b/ios/Hapi/Hapi-macOS.entitlements index a1c2c4c0..415faa06 100644 --- a/ios/Hapi/Hapi-macOS.entitlements +++ b/ios/Hapi/Hapi-macOS.entitlements @@ -4,6 +4,10 @@ com.apple.developer.aps-environment development + com.apple.developer.associated-domains + + webcredentials:hapi.run + com.apple.security.app-sandbox com.apple.security.device.audio-input diff --git a/ios/Hapi/Hapi.entitlements b/ios/Hapi/Hapi.entitlements index bf73d818..53f5cd0a 100644 --- a/ios/Hapi/Hapi.entitlements +++ b/ios/Hapi/Hapi.entitlements @@ -4,6 +4,10 @@ aps-environment development + com.apple.developer.associated-domains + + webcredentials:hapi.run + keychain-access-groups $(AppIdentifierPrefix)run.hapi.companion.push diff --git a/ios/Hapi/Models/AppModel.swift b/ios/Hapi/Models/AppModel.swift index f808d98b..f3aa3a1d 100644 --- a/ios/Hapi/Models/AppModel.swift +++ b/ios/Hapi/Models/AppModel.swift @@ -115,6 +115,25 @@ final class AppModel { @discardableResult func pair(hubUrl: String, accessToken: String) async throws -> PairedHub { let paired = try await pairingService.pair(rawHubUrl: hubUrl, accessToken: accessToken) + didPair(paired) + return paired + } + + /// URL-only sign-in with a native passkey (health → login options → + /// system sheet → verify); the hub is then authenticated by its passkey + /// session. Throws ``PairingFailure``, or `PasskeyError.canceled` when the + /// user dismissed the sheet. + @discardableResult + func signInWithPasskey(hubUrl: String) async throws -> PairedHub { + let paired = try await pairingService.signInWithPasskey( + rawHubUrl: hubUrl, + authenticator: PlatformPasskeyAuthenticator() + ) + didPair(paired) + return paired + } + + private func didPair(_ paired: PairedHub) { authFailureNotice = nil // Close whichever pairing surface was up; the state flip below swaps // the root to the home screen. @@ -124,7 +143,6 @@ final class AppModel { // Android timing: the notification-permission prompt fires only once // a hub is actually paired — then this hub registers for push. PushCoordinator.shared.hubPaired(paired.hubUrl) - return paired } /// Selects another paired hub, rebuilding the session for it. diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index 92c86f2c..0b271d03 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -1,6 +1,652 @@ { "sourceLanguage" : "en", "strings" : { + "Add Passkey" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавить ключ доступа" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "添加通行密钥" + } + } + } + }, + "Adding passkey…" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Добавление ключа доступа…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在添加通行密钥…" + } + } + } + }, + "Continue" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Продолжить" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "继续" + } + } + } + }, + "Could not add the passkey: %@" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось добавить ключ доступа: %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "无法添加通行密钥:%@" + } + } + } + }, + "Could not delete the passkey: %@" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не удалось удалить ключ доступа: %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "无法删除通行密钥:%@" + } + } + } + }, + "Created %@" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Создан %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "创建于 %@" + } + } + } + }, + "Delete Passkey" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Удалить ключ доступа" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "删除通行密钥" + } + } + } + }, + "Delete Passkey…" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Удалить ключ доступа…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "删除通行密钥…" + } + } + } + }, + "Delete “%@”?" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Удалить «%@»?" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "删除“%@”?" + } + } + } + }, + "Devices signed in with this passkey are signed out of the hub. The passkey itself stays in your password manager until you remove it there." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Устройства, вошедшие с этим ключом, будут отключены от хаба. Сам ключ останется в менеджере паролей, пока вы не удалите его там." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "使用此通行密钥登录的设备将退出该 Hub。通行密钥本身会保留在你的密码管理器中,直到你在那里删除它。" + } + } + } + }, + "Last used %@" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Использован %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "上次使用:%@" + } + } + } + }, + "Name this passkey" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Назовите ключ доступа" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "为通行密钥命名" + } + } + } + }, + "Never used" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Не использовался" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "从未使用" + } + } + } + }, + "No passkeys for this hub" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Для этого хаба нет ключей доступа" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此 Hub 没有通行密钥" + } + } + } + }, + "No passkeys yet." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ключей доступа пока нет." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "还没有通行密钥。" + } + } + } + }, + "Passkey" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ключ доступа" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "通行密钥" + } + } + } + }, + "Passkey name" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Название ключа" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "通行密钥名称" + } + } + } + }, + "Passkey rejected" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ключ доступа отклонён" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "通行密钥被拒绝" + } + } + } + }, + "Passkey unavailable" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ключ доступа недоступен" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "通行密钥不可用" + } + } + } + }, + "Passkeys" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ключи доступа" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "通行密钥" + } + } + } + }, + "Registered before the hub's access token was rotated; it can no longer sign in." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Зарегистрирован до смены токена доступа хаба; вход с ним больше невозможен." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "在 Hub 访问令牌轮换前注册,已无法用于登录。" + } + } + } + }, + "Revoked" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отозван" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "已失效" + } + } + } + }, + "Shown in the hub's passkey list so you can tell your devices apart." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Отображается в списке ключей хаба, чтобы различать устройства." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "显示在 Hub 的通行密钥列表中,便于区分你的设备。" + } + } + } + }, + "Sign in to %@ from another device with “Sign in with a Passkey” — only the hub URL is needed. Passkeys marked Web belong to the browser and are listed here for management only." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Войдите в %@ с другого устройства через «Войти с ключом доступа» — нужен только URL хаба. Ключи с пометкой «Веб» относятся к браузеру и показаны здесь только для управления." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "在其他设备上通过“使用通行密钥登录”登录 %@,只需 Hub 地址。标记为“网页”的通行密钥属于浏览器,此处仅供管理。" + } + } + } + }, + "Sign in to this hub without the access token" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вход в этот хаб без токена доступа" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "无需访问令牌即可登录此 Hub" + } + } + } + }, + "Sign in with a Passkey" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Войти с ключом доступа" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "使用通行密钥登录" + } + } + } + }, + "Signing in…" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Вход…" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "正在登录…" + } + } + } + }, + "The hub could not register the passkey (HTTP %lld)." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб не смог зарегистрировать ключ доступа (HTTP %lld)." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub 无法注册通行密钥(HTTP %lld)。" + } + } + } + }, + "The hub did not accept this passkey. It may have been deleted, or the hub's access token was rotated. Pair with the access token instead." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб не принял этот ключ доступа. Возможно, он удалён или токен доступа хаба был сменён. Подключитесь с токеном доступа." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub 未接受此通行密钥。它可能已被删除,或 Hub 的访问令牌已轮换。请改用访问令牌配对。" + } + } + } + }, + "The hub requested a passkey for “%@”, but this app only supports hapi.run. Update the hub." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Хаб запросил ключ доступа для «%@», но приложение поддерживает только hapi.run. Обновите хаб." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "Hub 请求的是“%@”的通行密钥,但本应用仅支持 hapi.run。请更新 Hub。" + } + } + } + }, + "This device could not create the passkey: %@" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Это устройство не смогло создать ключ доступа: %@" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此设备无法创建通行密钥:%@" + } + } + } + }, + "This device could not use a passkey for this hub. Try again, or pair with the access token." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Это устройство не смогло использовать ключ доступа для этого хаба. Повторите попытку или подключитесь с токеном доступа." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此设备无法为该 Hub 使用通行密钥。请重试,或使用访问令牌配对。" + } + } + } + }, + "This hub does not support passkeys. Update the hub to use them." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот хаб не поддерживает ключи доступа. Обновите хаб, чтобы использовать их." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此 Hub 不支持通行密钥。请更新 Hub 后使用。" + } + } + } + }, + "This hub has no passkeys for the app yet. Pair with the access token, then add a passkey in Settings → Passkeys." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "У этого хаба ещё нет ключей доступа для приложения. Подключитесь с токеном доступа, затем добавьте ключ в Настройки → Ключи доступа." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此 Hub 还没有可供本应用使用的通行密钥。请先用访问令牌配对,然后在“设置 → 通行密钥”中添加。" + } + } + } + }, + "This passkey is already registered with the hub." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Этот ключ доступа уже зарегистрирован в хабе." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "此通行密钥已在 Hub 中注册。" + } + } + } + }, + "Unnamed passkey" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Ключ без названия" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "未命名的通行密钥" + } + } + } + }, + "Uses a passkey you added for this hub in Settings → Passkeys. No access token needed." : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Используется ключ доступа, добавленный для этого хаба в Настройки → Ключи доступа. Токен доступа не нужен." + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "使用你在“设置 → 通行密钥”中为此 Hub 添加的通行密钥,无需访问令牌。" + } + } + } + }, + "Web" : { + "extractionState" : "manual", + "localizations" : { + "ru" : { + "stringUnit" : { + "state" : "translated", + "value" : "Веб" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "网页" + } + } + } + }, "— Canceled" : { "extractionState" : "manual", "localizations" : { diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Auth/AuthManager.swift b/ios/Packages/HapiKit/Sources/HapiClient/Auth/AuthManager.swift index 2d54f9c4..210d8bed 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Auth/AuthManager.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Auth/AuthManager.swift @@ -21,14 +21,15 @@ public enum AuthError: Error, Equatable, Sendable { /// /// Contract (`docs/api/client-contract/auth.md`): /// - JWTs expire after 4 h, so 401s are routine: re-exchange the stored -/// access token via `POST /api/auth {accessToken}` and let the caller -/// retry exactly once. +/// credential via `POST /api/auth` (`{accessToken}` or `{passkeySession}`, +/// see ``HubAuthCredential``) and let the caller retry exactly once. /// - Refreshes are **single-flight**: concurrent callers share one in-flight /// exchange instead of racing N of them. /// - Refresh is proactive when `exp` is within ``proactiveRefreshWindow``, /// so long-lived work (SSE reconnects) rarely sees a stale token. /// - A 401 from `/api/auth` itself is terminal (`authFailed`): the access -/// token was rotated or revoked, and the UI must offer re-pairing. +/// token was rotated or revoked, or the passkey session is no longer +/// valid, and the UI must offer re-pairing / passkey sign-in. /// /// The HTTP performer and clock are injectable for tests. public actor AuthManager { @@ -186,11 +187,11 @@ public actor AuthManager { private func performRefresh() async throws -> String { let stored = try? credentialStore.credentials(forHub: storageKey) - guard let credentials = stored, !credentials.accessToken.isEmpty else { + guard let credentials = stored, !credentials.credential.isEmpty else { throw AuthError.notPaired } do { - let request = try makeAuthRequest(accessToken: credentials.accessToken) + let request = try makeAuthRequest(credential: credentials.credential) let (data, response) = try await performer.perform(request) switch response.statusCode { case 200: @@ -198,7 +199,9 @@ public actor AuthManager { adopt(token: auth.token, credentials: credentials) return auth.token case 401: - // "Invalid access token" — rotated or revoked. Terminal. + // "Invalid access token" (rotated or revoked) or + // "passkey_session_invalid" (passkey deleted, token rotated, + // session expired). Terminal either way. authFailed = true throw AuthError.reauthenticationRequired default: @@ -212,15 +215,12 @@ public actor AuthManager { } } - private func makeAuthRequest(accessToken: String) throws -> URLRequest { - struct AuthRequestBody: Encodable { - let accessToken: String - } + private func makeAuthRequest(credential: HubAuthCredential) throws -> URLRequest { let url = try HubRequestURL.make(baseURL: baseURL, path: "/api/auth", query: []) var request = URLRequest(url: url) request.httpMethod = HTTPMethod.post.rawValue request.setValue("application/json", forHTTPHeaderField: "Content-Type") - request.httpBody = try HapiJSON.encoder.encode(AuthRequestBody(accessToken: accessToken)) + request.httpBody = try HapiJSON.encoder.encode(credential.exchangeBody) return request } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubPairingService.swift b/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubPairingService.swift index 753d5b72..af874da7 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubPairingService.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubPairingService.swift @@ -21,6 +21,15 @@ public enum PairingFailure: Error, Equatable, Sendable { /// The exchange succeeded but the credentials could not be persisted /// (Keychain write failure). case storageFailure + /// Passkey sign-in: the hub has no valid native passkeys + /// (`404 no_passkeys`) — pair with the access token and add one first. + case noPasskeys + /// Passkey sign-in: the hub rejected the assertion (revoked, unknown, + /// expired challenge) or asked for a foreign RP ID. + case passkeyRejected + /// Passkey sign-in: the system could not run the ceremony (missing + /// Associated Domains entitlement, AASA unreachable, …). + case passkeyUnavailable } /// Result of a successful pairing. @@ -47,6 +56,9 @@ public struct PairedHub: Equatable, Sendable { /// 4. persist ``HubCredentials`` (access token + first JWT) in the credential /// store, register the hub, and make it active. /// +/// `signInWithPasskey` replaces step 3 with the native passkey ceremony and +/// persists a passkey session instead of an access token. +/// /// `unpair` deletes the credentials, drops the hub from the registry, and /// reports which hub (if any) is active afterwards. The app layer owns /// everything session-shaped (building/tearing down `HubSession`). @@ -82,15 +94,106 @@ public struct HubPairingService: Sendable { throw PairingFailure.invalidAccessToken } - // Throwaway client: both calls are unauthenticated, so the auth - // manager is wiring-only and never consulted. - let client = APIClient( + let client = makeUnauthenticatedClient(baseURL: baseURL) + try await checkHealth(client) + + // Token exchange. + let auth: AuthResponse + do { + auth = try await client.authenticate(accessToken: token) + } catch let error as APIError { + throw error.status == 401 + ? PairingFailure.invalidAccessToken + : PairingFailure.hubError(status: error.status) + } catch { + throw PairingFailure.unreachable + } + + return try persist( + HubCredentials( + hubUrl: normalized, + credential: .accessToken(token), + jwt: auth.token, + jwtObtainedAt: Int(now().timeIntervalSince1970 * 1000) + ) + ) + } + + /// Signs in to the hub at `rawHubUrl` with a native passkey — only the + /// hub URL is needed. Same health check as ``pair(rawHubUrl:accessToken:)``, + /// then login options (`{client: "native"}`) → RP check → system sheet → + /// verify; the returned passkey session is stored as the hub's + /// credential (no access token). Throws ``PairingFailure``, or + /// ``PasskeyError/canceled`` when the user dismissed the sheet. + public func signInWithPasskey( + rawHubUrl: String, + authenticator: any PasskeyAuthenticating + ) async throws -> PairedHub { + guard let normalized = HubURLNormalization.normalize(rawHubUrl), + let baseURL = URL(string: normalized) else { + throw PairingFailure.invalidHubURL + } + let client = makeUnauthenticatedClient(baseURL: baseURL) + try await checkHealth(client) + + let request: PasskeyAssertionRequest + do { + request = try PasskeyAssertionRequest(options: try await client.passkeyLoginOptions()) + } catch PasskeyError.noPasskeys { + throw PairingFailure.noPasskeys + } catch is PasskeyError { + throw PairingFailure.passkeyRejected + } catch let error as APIError { + throw PairingFailure.hubError(status: error.status) + } catch { + throw PairingFailure.unreachable + } + + let assertion: PasskeyAssertionResult + do { + assertion = try await authenticator.authenticate(request) + } catch PasskeyError.canceled { + throw PasskeyError.canceled + } catch { + throw PairingFailure.passkeyUnavailable + } + + let login: PasskeyLoginResponse + do { + login = try await client.verifyPasskeyLogin(PasskeyAssertionResponseJSON(assertion)) + } catch let error as APIError { + // 401 = revoked / unknown / expired challenge; 400 = bad body. + throw (error.status == 401 || error.status == 400) + ? PairingFailure.passkeyRejected + : PairingFailure.hubError(status: error.status) + } catch { + throw PairingFailure.unreachable + } + + return try persist( + HubCredentials( + hubUrl: normalized, + credential: .passkeySession(login.passkeySession), + jwt: login.token, + jwtObtainedAt: Int(now().timeIntervalSince1970 * 1000) + ) + ) + } + + // MARK: - Steps + + /// Throwaway client: pairing calls are unauthenticated, so the auth + /// manager is wiring-only and never consulted. + private func makeUnauthenticatedClient(baseURL: URL) -> APIClient { + APIClient( baseURL: baseURL, authManager: AuthManager(baseURL: baseURL, credentialStore: credentialStore, performer: performer), performer: performer ) + } - // 1. Reachability + protocol compatibility. + /// Reachability + protocol compatibility. + private func checkHealth(_ client: APIClient) async throws { let health: HubHealthResponse do { health = try await client.health() @@ -110,35 +213,20 @@ public struct HubPairingService: Sendable { supportedVersion: ProtocolVersion.supported ) } + } - // 2. Token exchange. - let auth: AuthResponse + /// Persists the record — credentials first: a hub registered without + /// credentials would restore as paired-but-dead — then registers the hub + /// and makes it active. + private func persist(_ credentials: HubCredentials) throws -> PairedHub { do { - auth = try await client.authenticate(accessToken: token) - } catch let error as APIError { - throw error.status == 401 - ? PairingFailure.invalidAccessToken - : PairingFailure.hubError(status: error.status) - } catch { - throw PairingFailure.unreachable - } - - // 3. Persist. Credentials first: a hub registered without - // credentials would restore as paired-but-dead. - do { - try credentialStore.store(HubCredentials( - hubUrl: normalized, - accessToken: token, - jwt: auth.token, - jwtObtainedAt: Int(now().timeIntervalSince1970 * 1000) - )) + try credentialStore.store(credentials) } catch { throw PairingFailure.storageFailure } - registry.register(normalized) - registry.setActiveHub(normalized) - - return PairedHub(hubUrl: normalized, claims: JWT.claims(from: auth.token)) + registry.register(credentials.hubUrl) + registry.setActiveHub(credentials.hubUrl) + return PairedHub(hubUrl: credentials.hubUrl, claims: credentials.jwt.flatMap(JWT.claims(from:))) } /// Removes a hub: credentials deleted, registry entry dropped, active diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Auth/KeychainStore.swift b/ios/Packages/HapiKit/Sources/HapiClient/Auth/KeychainStore.swift index e1a8806d..cc4150e1 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Auth/KeychainStore.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Auth/KeychainStore.swift @@ -3,26 +3,101 @@ import Foundation import Security #endif +/// The durable secret a paired hub is authenticated with, exchanged for a JWT +/// via `POST /api/auth` (`docs/api/client-contract/auth.md`). +public enum HubAuthCredential: Equatable, Sendable { + /// Pairing secret (`CLI_API_TOKEN[:namespace]`), sent as `{accessToken}`. + case accessToken(String) + /// Refresh credential from `POST /api/passkey/login/verify`, sent as + /// `{passkeySession}`. + case passkeySession(String) + + /// Body of the `POST /api/auth` exchange for this credential. + public var exchangeBody: [String: String] { + switch self { + case .accessToken(let token): ["accessToken": token] + case .passkeySession(let session): ["passkeySession": session] + } + } + + var isEmpty: Bool { + switch self { + case .accessToken(let value), .passkeySession(let value): value.isEmpty + } + } +} + /// The per-hub credential record (`docs/api/client-contract/auth.md`). /// -/// The access token is the durable secret; the JWT is a 4-hour cache -/// persisted only to save one `/api/auth` round-trip at cold start. +/// The credential (access token or passkey session) is the durable secret; +/// the JWT is a 4-hour cache persisted only to save one `/api/auth` +/// round-trip at cold start. Exactly one credential kind is stored, encoded +/// as an `accessToken` or `passkeySession` field. public struct HubCredentials: Codable, Equatable, Sendable { /// Normalized hub origin (see ``HubURLNormalization``); also the storage key. public var hubUrl: String - /// Long-lived pairing secret, passed verbatim to `POST /api/auth`. - public var accessToken: String + /// Secret exchanged by the silent re-auth loop. + public var credential: HubAuthCredential /// Last issued JWT, if any. public var jwt: String? /// When `jwt` was obtained, epoch ms. public var jwtObtainedAt: Int? - public init(hubUrl: String, accessToken: String, jwt: String? = nil, jwtObtainedAt: Int? = nil) { + public init(hubUrl: String, credential: HubAuthCredential, jwt: String? = nil, jwtObtainedAt: Int? = nil) { self.hubUrl = hubUrl - self.accessToken = accessToken + self.credential = credential self.jwt = jwt self.jwtObtainedAt = jwtObtainedAt } + + /// Access-token record (QR / manual / deep-link pairing). + public init(hubUrl: String, accessToken: String, jwt: String? = nil, jwtObtainedAt: Int? = nil) { + self.init(hubUrl: hubUrl, credential: .accessToken(accessToken), jwt: jwt, jwtObtainedAt: jwtObtainedAt) + } + + /// Long-lived pairing secret, when the hub was paired by access token. + public var accessToken: String? { + if case .accessToken(let token) = credential { return token } + return nil + } + + /// Passkey refresh credential, when the hub was signed in by passkey. + public var passkeySession: String? { + if case .passkeySession(let session) = credential { return session } + return nil + } + + private enum CodingKeys: String, CodingKey { + case hubUrl, accessToken, passkeySession, jwt, jwtObtainedAt + } + + public init(from decoder: any Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + hubUrl = try container.decode(String.self, forKey: .hubUrl) + if let token = try container.decodeIfPresent(String.self, forKey: .accessToken) { + credential = .accessToken(token) + } else if let session = try container.decodeIfPresent(String.self, forKey: .passkeySession) { + credential = .passkeySession(session) + } else { + throw DecodingError.keyNotFound(CodingKeys.accessToken, DecodingError.Context( + codingPath: container.codingPath, + debugDescription: "Credential record has neither accessToken nor passkeySession" + )) + } + jwt = try container.decodeIfPresent(String.self, forKey: .jwt) + jwtObtainedAt = try container.decodeIfPresent(Int.self, forKey: .jwtObtainedAt) + } + + public func encode(to encoder: any Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encode(hubUrl, forKey: .hubUrl) + switch credential { + case .accessToken(let token): try container.encode(token, forKey: .accessToken) + case .passkeySession(let session): try container.encode(session, forKey: .passkeySession) + } + try container.encodeIfPresent(jwt, forKey: .jwt) + try container.encodeIfPresent(jwtObtainedAt, forKey: .jwtObtainedAt) + } } /// Storage seam so `AuthManager` and the pairing flow are testable without diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Auth/Passkeys.swift b/ios/Packages/HapiKit/Sources/HapiClient/Auth/Passkeys.swift new file mode 100644 index 00000000..9af85f0f --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Auth/Passkeys.swift @@ -0,0 +1,328 @@ +import Foundation + +/// Native passkeys (`docs/api/client-contract/auth.md#passkeys-native`). +/// +/// The official apps share one relying party, ``nativeRelyingPartyID``, +/// compiled into the Associated Domains entitlement. This file holds the +/// platform-free half: wire models for the WebAuthn options/response JSON, +/// base64url coding, RP validation, and the ``PasskeyAuthenticating`` seam +/// the app implements with AuthenticationServices. +public enum NativePasskeys { + /// RP ID of every native passkey (`webcredentials:hapi.run`). + public static let nativeRelyingPartyID = "hapi.run" + /// Transports reported for a platform (iCloud Keychain) credential. + public static let registrationTransports = ["internal", "hybrid"] +} + +// MARK: - Errors + +/// Why a passkey ceremony or exchange did not complete. +public enum PasskeyError: Error, Equatable, Sendable { + /// The hub asked for a different RP ID than the one this build is + /// entitled to (`rp.id` / `rpId` != ``NativePasskeys/nativeRelyingPartyID``). + case relyingPartyMismatch(String) + /// The options JSON lacked a field or carried invalid base64url. + case malformedOptions + /// `POST /api/passkey/login/options` answered `404 {"error":"no_passkeys"}`. + case noPasskeys + /// The platform returned a registration without an attestation object. + case missingAttestation + /// The user dismissed the system sheet. Callers treat this as silent. + case canceled + /// The platform refused the request (no Associated Domains entitlement, + /// AASA unreachable, no matching credential, …). + case platform(String) +} + +// MARK: - base64url + +/// RFC 4648 §5 base64url without padding, the WebAuthn JSON encoding. +public enum Base64URL { + public static func encode(_ data: Data) -> String { + data.base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") + } + + /// Accepts padded or unpadded input; `nil` for invalid characters. + public static func decode(_ string: String) -> Data? { + var base64 = string + .replacingOccurrences(of: "-", with: "+") + .replacingOccurrences(of: "_", with: "/") + base64 = base64.replacingOccurrences(of: "=", with: "") + let remainder = base64.count % 4 + if remainder == 1 { return nil } + if remainder > 0 { + base64 += String(repeating: "=", count: 4 - remainder) + } + return Data(base64Encoded: base64) + } +} + +// MARK: - Options (hub → app) + +/// `{ "client": "native" }` — asks the hub for the fixed native RP. +public struct PasskeyOptionsRequest: Encodable, Equatable, Sendable { + public let client: String + + public init(client: String = "native") { + self.client = client + } +} + +/// `PublicKeyCredentialDescriptorJSON` (only `id` is used). +public struct PasskeyCredentialDescriptor: Codable, Equatable, Sendable { + public var id: String + public var transports: [String]? + + public init(id: String, transports: [String]? = nil) { + self.id = id + self.transports = transports + } +} + +/// `PublicKeyCredentialCreationOptionsJSON` — the fields a platform +/// registration needs. +public struct PasskeyRegistrationOptions: Decodable, Equatable, Sendable { + public struct RelyingParty: Decodable, Equatable, Sendable { + public var id: String? + public var name: String? + } + + public struct User: Decodable, Equatable, Sendable { + public var id: String + public var name: String + public var displayName: String? + } + + public var challenge: String + public var rp: RelyingParty + public var user: User + public var excludeCredentials: [PasskeyCredentialDescriptor]? +} + +/// `PublicKeyCredentialRequestOptionsJSON` — the fields a platform +/// assertion needs. +public struct PasskeyAssertionOptions: Decodable, Equatable, Sendable { + public var challenge: String + public var rpId: String? + public var allowCredentials: [PasskeyCredentialDescriptor]? +} + +// MARK: - Platform requests (decoded options) + +/// Input for a platform registration, already validated and decoded. +public struct PasskeyRegistrationRequest: Equatable, Sendable { + public let relyingPartyID: String + public let challenge: Data + public let userID: Data + public let userName: String + public let excludedCredentialIDs: [Data] + + /// Validates `rp.id` against ``NativePasskeys/nativeRelyingPartyID`` + /// and decodes the base64url fields. + public init( + options: PasskeyRegistrationOptions, + expectedRelyingPartyID: String = NativePasskeys.nativeRelyingPartyID + ) throws { + guard let rpId = options.rp.id, rpId == expectedRelyingPartyID else { + throw PasskeyError.relyingPartyMismatch(options.rp.id ?? "") + } + guard let challenge = Base64URL.decode(options.challenge), !challenge.isEmpty, + let userID = Base64URL.decode(options.user.id), !userID.isEmpty, + !options.user.name.isEmpty else { + throw PasskeyError.malformedOptions + } + let excluded = try (options.excludeCredentials ?? []).map { descriptor in + guard let id = Base64URL.decode(descriptor.id) else { throw PasskeyError.malformedOptions } + return id + } + self.relyingPartyID = rpId + self.challenge = challenge + self.userID = userID + self.userName = options.user.name + self.excludedCredentialIDs = excluded + } +} + +/// Input for a platform assertion, already validated and decoded. +public struct PasskeyAssertionRequest: Equatable, Sendable { + public let relyingPartyID: String + public let challenge: Data + /// This hub's passkeys; the system sheet offers only these. + public let allowedCredentialIDs: [Data] + + public init( + options: PasskeyAssertionOptions, + expectedRelyingPartyID: String = NativePasskeys.nativeRelyingPartyID + ) throws { + guard let rpId = options.rpId, rpId == expectedRelyingPartyID else { + throw PasskeyError.relyingPartyMismatch(options.rpId ?? "") + } + guard let challenge = Base64URL.decode(options.challenge), !challenge.isEmpty else { + throw PasskeyError.malformedOptions + } + let allowed = try (options.allowCredentials ?? []).map { descriptor in + guard let id = Base64URL.decode(descriptor.id) else { throw PasskeyError.malformedOptions } + return id + } + self.relyingPartyID = rpId + self.challenge = challenge + self.allowedCredentialIDs = allowed + } +} + +// MARK: - Platform results (app → hub) + +/// Raw bytes of a new platform credential. +public struct PasskeyRegistrationResult: Equatable, Sendable { + public let credentialID: Data + public let clientDataJSON: Data + public let attestationObject: Data + + public init(credentialID: Data, clientDataJSON: Data, attestationObject: Data) { + self.credentialID = credentialID + self.clientDataJSON = clientDataJSON + self.attestationObject = attestationObject + } +} + +/// Raw bytes of a platform assertion. +public struct PasskeyAssertionResult: Equatable, Sendable { + public let credentialID: Data + public let clientDataJSON: Data + public let authenticatorData: Data + public let signature: Data + public let userID: Data? + + public init(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userID: Data?) { + self.credentialID = credentialID + self.clientDataJSON = clientDataJSON + self.authenticatorData = authenticatorData + self.signature = signature + self.userID = userID + } +} + +/// `RegistrationResponseJSON` (base64url binary fields). +public struct PasskeyRegistrationResponseJSON: Encodable, Equatable, Sendable { + public struct Response: Encodable, Equatable, Sendable { + public let clientDataJSON: String + public let attestationObject: String + public let transports: [String] + } + + public let id: String + public let rawId: String + public let type: String + public let response: Response + public let authenticatorAttachment: String + public let clientExtensionResults: [String: String] + + public init(_ result: PasskeyRegistrationResult) { + let id = Base64URL.encode(result.credentialID) + self.id = id + self.rawId = id + self.type = "public-key" + self.response = Response( + clientDataJSON: Base64URL.encode(result.clientDataJSON), + attestationObject: Base64URL.encode(result.attestationObject), + transports: NativePasskeys.registrationTransports + ) + self.authenticatorAttachment = "platform" + self.clientExtensionResults = [:] + } +} + +/// `AuthenticationResponseJSON` (base64url binary fields). +public struct PasskeyAssertionResponseJSON: Encodable, Equatable, Sendable { + public struct Response: Encodable, Equatable, Sendable { + public let clientDataJSON: String + public let authenticatorData: String + public let signature: String + public let userHandle: String? + } + + public let id: String + public let rawId: String + public let type: String + public let response: Response + public let authenticatorAttachment: String + public let clientExtensionResults: [String: String] + + public init(_ result: PasskeyAssertionResult) { + let id = Base64URL.encode(result.credentialID) + self.id = id + self.rawId = id + self.type = "public-key" + self.response = Response( + clientDataJSON: Base64URL.encode(result.clientDataJSON), + authenticatorData: Base64URL.encode(result.authenticatorData), + signature: Base64URL.encode(result.signature), + userHandle: result.userID.flatMap { $0.isEmpty ? nil : Base64URL.encode($0) } + ) + self.authenticatorAttachment = "platform" + self.clientExtensionResults = [:] + } +} + +// MARK: - Hub responses + +/// `POST /api/passkey/login/verify` → `{token, user, passkeySession}`. +public struct PasskeyLoginResponse: Decodable, Equatable, Sendable { + public var token: String + public var passkeySession: String +} + +/// One entry of `GET /api/passkeys`. +public struct PasskeySummary: Codable, Equatable, Identifiable, Sendable { + public var id: String + public var name: String? + public var rpId: String + /// Epoch ms. + public var createdAt: Int + /// Epoch ms; `nil` until first sign-in. + public var lastUsedAt: Int? + /// `false` once `CLI_API_TOKEN` has been rotated since registration. + public var valid: Bool + + public init(id: String, name: String?, rpId: String, createdAt: Int, lastUsedAt: Int?, valid: Bool) { + self.id = id + self.name = name + self.rpId = rpId + self.createdAt = createdAt + self.lastUsedAt = lastUsedAt + self.valid = valid + } + + /// Usable from the app (registered for the shared native RP ID). Other + /// entries are web passkeys bound to a browser origin — listed for + /// management only. + public var isNative: Bool { + rpId == NativePasskeys.nativeRelyingPartyID + } + + public var createdDate: Date { + Date(timeIntervalSince1970: TimeInterval(createdAt) / 1000) + } + + public var lastUsedDate: Date? { + lastUsedAt.map { Date(timeIntervalSince1970: TimeInterval($0) / 1000) } + } +} + +/// `GET /api/passkeys`. +public struct PasskeyListResponse: Decodable, Equatable, Sendable { + public var passkeys: [PasskeySummary] +} + +// MARK: - Platform seam + +/// The system passkey sheet. The app implements it with +/// AuthenticationServices; tests script it. Implementations throw +/// ``PasskeyError/canceled`` when the user dismisses the sheet. +public protocol PasskeyAuthenticating: Sendable { + func register(_ request: PasskeyRegistrationRequest) async throws -> PasskeyRegistrationResult + func authenticate(_ request: PasskeyAssertionRequest) async throws -> PasskeyAssertionResult +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/PasskeyEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/PasskeyEndpoints.swift new file mode 100644 index 00000000..8947a270 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/PasskeyEndpoints.swift @@ -0,0 +1,83 @@ +import Foundation +import HapiProtocol + +/// Native passkey endpoints (`docs/api/client-contract/auth.md#passkeys-native`). +/// The app always sends `{ "client": "native" }`, so the hub uses the shared +/// RP ID instead of an `Origin` header (natives send none). +extension APIClient { + /// `POST /api/passkey/register/options` (JWT required). + public func passkeyRegistrationOptions() async throws -> PasskeyRegistrationOptions { + try await request(.post, "/api/passkey/register/options", body: PasskeyOptionsRequest()) + } + + /// `POST /api/passkey/register/verify` `{response, name}` (JWT required). + /// The name is trimmed, omitted when blank, and clamped to the hub's limit. + public func verifyPasskeyRegistration(_ response: PasskeyRegistrationResponseJSON, name: String?) async throws { + struct Body: Encodable { + let response: PasskeyRegistrationResponseJSON + let name: String? + } + let trimmed = name?.trimmingCharacters(in: .whitespacesAndNewlines) + let normalized = trimmed.flatMap { $0.isEmpty ? nil : Self.clampPasskeyName($0) } + try await requestVoid(.post, "/api/passkey/register/verify", body: Body(response: response, name: normalized)) + } + + /// `POST /api/passkey/login/options` (unauthenticated). A + /// `404 {"error":"no_passkeys"}` is mapped to ``PasskeyError/noPasskeys``. + public func passkeyLoginOptions() async throws -> PasskeyAssertionOptions { + do { + return try await request( + .post, + "/api/passkey/login/options", + body: PasskeyOptionsRequest(), + authenticated: false + ) + } catch let error as APIError where error.status == 404 && error.code == "no_passkeys" { + throw PasskeyError.noPasskeys + } + } + + /// `POST /api/passkey/login/verify` `{response}` (unauthenticated) → + /// JWT + passkey session. + public func verifyPasskeyLogin(_ response: PasskeyAssertionResponseJSON) async throws -> PasskeyLoginResponse { + struct Body: Encodable { + let response: PasskeyAssertionResponseJSON + } + return try await request( + .post, + "/api/passkey/login/verify", + body: Body(response: response), + authenticated: false + ) + } + + /// `GET /api/passkeys` — the caller's namespace, native and web. + public func listPasskeys() async throws -> [PasskeySummary] { + let response: PasskeyListResponse = try await request(.get, "/api/passkeys") + return response.passkeys + } + + /// `DELETE /api/passkeys/:id` — also revokes that passkey's sessions. + public func deletePasskey(id: String) async throws { + try await requestVoid(.delete, "/api/passkeys/\(encodePathComponent(id))") + } + + /// Full registration: options → RP check → platform sheet → verify. + /// Throws ``PasskeyError`` (``PasskeyError/canceled`` when dismissed) or + /// ``APIError``. + public func registerPasskey(name: String?, using authenticator: any PasskeyAuthenticating) async throws { + let options = try await passkeyRegistrationOptions() + let request = try PasskeyRegistrationRequest(options: options) + let result = try await authenticator.register(request) + try await verifyPasskeyRegistration(PasskeyRegistrationResponseJSON(result), name: name) + } + + /// The hub caps names at 64 UTF-16 code units (zod `max(64)`). + static func clampPasskeyName(_ name: String) -> String { + var clamped = name + while clamped.utf16.count > 64 { + clamped.removeLast() + } + return clamped + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyAuthTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyAuthTests.swift new file mode 100644 index 00000000..be82cc58 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyAuthTests.swift @@ -0,0 +1,240 @@ +import Foundation +#if canImport(FoundationNetworking) +import FoundationNetworking // URLSession types live here on Linux +#endif +import HapiClient +import HapiProtocol +import Testing + +/// Passkey-session credentials: storage shape, the silent re-auth exchange +/// body, terminal 401 handling, and the URL-only passkey sign-in. +@Suite("Passkey credentials") +struct PasskeyAuthTests { + private func makePasskeyHarness(session: String = "passkey-session", jwt: String? = nil) throws -> Harness { + let harness = try makeHarness(paired: false) + try harness.store.store(HubCredentials( + hubUrl: testHubURLString, + credential: .passkeySession(session), + jwt: jwt + )) + return harness + } + + // MARK: - Storage + + @Test func passkeyRecordRoundTripsWithoutAccessToken() throws { + let record = HubCredentials( + hubUrl: "https://hub.test", + credential: .passkeySession("ps"), + jwt: "j", + jwtObtainedAt: 1 + ) + let data = try JSONEncoder().encode(record) + let object = try #require(try JSONSerialization.jsonObject(with: data) as? [String: Any]) + #expect(object["passkeySession"] as? String == "ps") + #expect(object["accessToken"] == nil) + let decoded = try JSONDecoder().decode(HubCredentials.self, from: data) + #expect(decoded == record) + #expect(decoded.accessToken == nil) + #expect(decoded.passkeySession == "ps") + } + + @Test func legacyAccessTokenRecordStillDecodes() throws { + // Records written before passkeys carried only `accessToken`. + let data = Data("{\"hubUrl\":\"https://hub.test\",\"accessToken\":\"tok\",\"jwt\":\"j\"}".utf8) + let decoded = try JSONDecoder().decode(HubCredentials.self, from: data) + #expect(decoded.credential == .accessToken("tok")) + #expect(decoded.jwt == "j") + } + + @Test func recordWithoutCredentialFailsToDecode() { + let data = Data("{\"hubUrl\":\"https://hub.test\"}".utf8) + #expect(throws: DecodingError.self) { + _ = try JSONDecoder().decode(HubCredentials.self, from: data) + } + } + + // MARK: - Re-auth exchange + + @Test func refreshExchangesPasskeySession() async throws { + let harness = try makePasskeyHarness() + let issued = freshJWT() + await harness.performer.enqueue(json: authResponseJSON(token: issued)) + + let token = try await harness.auth.validToken() + #expect(token == issued) + let requests = await harness.performer.requests + try #require(requests.count == 1) + #expect(requests[0].url?.absoluteString == "\(testHubURLString)/api/auth") + let body = requests[0].httpBody.flatMap { String(data: $0, encoding: .utf8) } + #expect(body == "{\"passkeySession\":\"passkey-session\"}") + + // The refreshed JWT is persisted next to the session, which is kept. + let stored = try harness.store.credentials(forHub: testHubURLString) + #expect(stored?.jwt == issued) + #expect(stored?.credential == .passkeySession("passkey-session")) + } + + @Test func exchangeBodiesPerCredentialKind() { + #expect(HubAuthCredential.accessToken("t").exchangeBody == ["accessToken": "t"]) + #expect(HubAuthCredential.passkeySession("s").exchangeBody == ["passkeySession": "s"]) + } + + @Test func passkeySessionInvalidIsTerminal() async throws { + let harness = try makePasskeyHarness() + await harness.performer.setFallback(status: 401, json: "{\"error\":\"passkey_session_invalid\"}") + + let first = await capturedError { try await harness.auth.validToken() } + #expect(first as? AuthError == .reauthenticationRequired) + let failed = await harness.auth.isAuthenticationFailed + #expect(failed) + let second = await capturedError { try await harness.auth.validToken() } + #expect(second as? AuthError == .reauthenticationRequired) + let count = await harness.performer.requests.count + #expect(count == 1) + } + + @Test func expiredJWTOnRequestReexchangesPasskeySession() async throws { + let stale = freshJWT(ns: "stale") + let harness = try makePasskeyHarness(jwt: stale) + let issued = freshJWT() + await harness.performer.enqueue(status: 401, json: "{\"error\":\"Invalid token\"}") + await harness.performer.enqueue(json: authResponseJSON(token: issued)) + await harness.performer.enqueue(json: "{\"passkeys\":[]}") + + _ = try await harness.client.listPasskeys() + let requests = await harness.performer.requests + try #require(requests.count == 3) + #expect(requests[1].httpBody.flatMap { String(data: $0, encoding: .utf8) } == "{\"passkeySession\":\"passkey-session\"}") + #expect(requests[2].value(forHTTPHeaderField: "Authorization") == "Bearer \(issued)") + } + + // MARK: - Sign-in with passkey + + private struct World { + let defaults: UserDefaults + let suiteName: String + let registry: HubRegistry + let store: InMemoryCredentialStore + let performer: RecordingPerformer + let service: HubPairingService + + func tearDown() { + defaults.removePersistentDomain(forName: suiteName) + } + } + + private func makeWorld() throws -> World { + let suiteName = "PasskeyAuthTests-\(UUID().uuidString)" + let defaults = try #require(UserDefaults(suiteName: suiteName)) + let registry = HubRegistry(defaults: defaults) + let store = InMemoryCredentialStore() + let performer = RecordingPerformer() + let service = HubPairingService(registry: registry, credentialStore: store, performer: performer, now: { testNow }) + return World(defaults: defaults, suiteName: suiteName, registry: registry, store: store, performer: performer, service: service) + } + + private let healthJSON = "{\"status\":\"ok\",\"protocolVersion\":\(ProtocolVersion.supported)}" + + private func loginOptionsJSON(rpId: String = "hapi.run") -> String { + "{\"challenge\":\"\(Base64URL.encode(Data("c".utf8)))\",\"rpId\":\"\(rpId)\",\"allowCredentials\":[{\"id\":\"aWQ\"}]}" + } + + @Test func signInStoresPasskeySessionAndActivatesHub() async throws { + let world = try makeWorld() + defer { world.tearDown() } + let jwt = freshJWT() + await world.performer.enqueue(json: healthJSON) + await world.performer.enqueue(json: loginOptionsJSON()) + await world.performer.enqueue(json: "{\"token\":\"\(jwt)\",\"user\":{\"id\":1},\"passkeySession\":\"ps-1\"}") + let authenticator = ScriptedAuthenticator() + + let paired = try await world.service.signInWithPasskey(rawHubUrl: "https://Hub.Test/", authenticator: authenticator) + + #expect(paired.hubUrl == "https://hub.test") + #expect(paired.claims?.ns == "default") + let stored = try world.store.credentials(forHub: "https://hub.test") + #expect(stored?.credential == .passkeySession("ps-1")) + #expect(stored?.accessToken == nil) + #expect(stored?.jwt == jwt) + #expect(world.registry.activeHub == "https://hub.test") + let assertions = await authenticator.assertions + #expect(assertions.first?.allowedCredentialIDs == [Data("id".utf8)]) + let paths = await world.performer.requests.map { $0.url?.path } + #expect(paths == ["/health", "/api/passkey/login/options", "/api/passkey/login/verify"]) + } + + @Test func signInWithoutPasskeysReportsNoPasskeys() async throws { + let world = try makeWorld() + defer { world.tearDown() } + await world.performer.enqueue(json: healthJSON) + await world.performer.enqueue(status: 404, json: "{\"error\":\"no_passkeys\"}") + let authenticator = ScriptedAuthenticator() + + let error = await capturedError { + try await world.service.signInWithPasskey(rawHubUrl: "https://hub.test", authenticator: authenticator) + } + #expect(error as? PairingFailure == .noPasskeys) + let assertions = await authenticator.assertions + #expect(assertions.isEmpty) + #expect(world.registry.hubs.isEmpty) + } + + @Test func signInRefusesForeignRelyingPartyBeforeCeremony() async throws { + let world = try makeWorld() + defer { world.tearDown() } + await world.performer.enqueue(json: healthJSON) + await world.performer.enqueue(json: loginOptionsJSON(rpId: "hub.test")) + let authenticator = ScriptedAuthenticator() + + let error = await capturedError { + try await world.service.signInWithPasskey(rawHubUrl: "https://hub.test", authenticator: authenticator) + } + #expect(error as? PairingFailure == .passkeyRejected) + let assertions = await authenticator.assertions + #expect(assertions.isEmpty) + } + + @Test func canceledSheetPropagatesCancellationWithoutPersisting() async throws { + let world = try makeWorld() + defer { world.tearDown() } + await world.performer.enqueue(json: healthJSON) + await world.performer.enqueue(json: loginOptionsJSON()) + let authenticator = ScriptedAuthenticator(assertionError: PasskeyError.canceled) + + let error = await capturedError { + try await world.service.signInWithPasskey(rawHubUrl: "https://hub.test", authenticator: authenticator) + } + #expect(error as? PasskeyError == .canceled) + #expect(try world.store.credentials(forHub: "https://hub.test") == nil) + let count = await world.performer.requests.count + #expect(count == 2) + } + + @Test func revokedPasskeyIsRejected() async throws { + let world = try makeWorld() + defer { world.tearDown() } + await world.performer.enqueue(json: healthJSON) + await world.performer.enqueue(json: loginOptionsJSON()) + await world.performer.enqueue(status: 401, json: "{\"error\":\"passkey_revoked\"}") + + let error = await capturedError { + try await world.service.signInWithPasskey(rawHubUrl: "https://hub.test", authenticator: ScriptedAuthenticator()) + } + #expect(error as? PairingFailure == .passkeyRejected) + #expect(world.registry.hubs.isEmpty) + } + + @Test func platformFailureIsReportedAsUnavailable() async throws { + let world = try makeWorld() + defer { world.tearDown() } + await world.performer.enqueue(json: healthJSON) + await world.performer.enqueue(json: loginOptionsJSON()) + let authenticator = ScriptedAuthenticator(assertionError: PasskeyError.platform("not entitled")) + + let error = await capturedError { + try await world.service.signInWithPasskey(rawHubUrl: "https://hub.test", authenticator: authenticator) + } + #expect(error as? PairingFailure == .passkeyUnavailable) + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeysTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeysTests.swift new file mode 100644 index 00000000..8ce09e99 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeysTests.swift @@ -0,0 +1,343 @@ +import Foundation +import HapiClient +import HapiProtocol +import Testing + +/// Native passkey wire encoding (`docs/api/client-contract/auth.md#passkeys-native`). +/// The hub verifies the payload cryptographically, so these pin the JSON +/// shape the app produces against `hub/src/web/routes/passkey.test.ts`. +@Suite("Passkeys") +struct PasskeysTests { + private func registrationOptionsJSON( + rpId: String = "hapi.run", + userID: String = Base64URL.encode(Data("handle".utf8)), + challenge: String = Base64URL.encode(Data("challenge-bytes".utf8)), + exclude: [String] = [] + ) -> String { + let excluded = exclude.map { "{\"id\":\"\($0)\",\"type\":\"public-key\",\"transports\":[\"internal\"]}" } + return """ + {"challenge":"\(challenge)","rp":{"id":"\(rpId)","name":"HAPI"}, + "user":{"id":"\(userID)","name":"hapi@hub.example.com","displayName":"HAPI · hub.example.com"}, + "pubKeyCredParams":[{"alg":-7,"type":"public-key"}], + "excludeCredentials":[\(excluded.joined(separator: ","))], + "authenticatorSelection":{"residentKey":"required","userVerification":"required"}, + "attestation":"none"} + """ + } + + private func assertionOptionsJSON(rpId: String = "hapi.run", credentials: [String] = []) -> String { + let allowed = credentials.map { "{\"id\":\"\($0)\",\"type\":\"public-key\",\"transports\":[\"internal\"]}" } + return """ + {"challenge":"\(Base64URL.encode(Data("challenge-bytes".utf8)))","rpId":"\(rpId)", + "allowCredentials":[\(allowed.joined(separator: ","))],"userVerification":"required"} + """ + } + + // MARK: - base64url + + @Test func base64urlRoundTripsWithoutPadding() throws { + let bytes = Data([0xFB, 0xFF, 0x00, 0x10, 0x7F]) + let encoded = Base64URL.encode(bytes) + #expect(!encoded.contains("+") && !encoded.contains("/") && !encoded.contains("=")) + #expect(encoded == "-_8AEH8") + #expect(Base64URL.decode(encoded) == bytes) + // Padded input decodes too. + #expect(Base64URL.decode("-_8AEH8=") == bytes) + // Length 1 mod 4 is not a valid base64url string. + #expect(Base64URL.decode("abcde") == nil) + } + + // MARK: - Options decoding + + @Test func registrationRequestDecodesBase64URLFields() throws { + let options = try HapiJSON.decoder.decode( + PasskeyRegistrationOptions.self, + from: Data(registrationOptionsJSON(exclude: ["Y3JlZDE"]).utf8) + ) + let request = try PasskeyRegistrationRequest(options: options) + #expect(request.relyingPartyID == "hapi.run") + #expect(request.challenge == Data("challenge-bytes".utf8)) + #expect(request.userID == Data("handle".utf8)) + #expect(request.userName == "hapi@hub.example.com") + #expect(request.excludedCredentialIDs == [Data("cred1".utf8)]) + } + + @Test func registrationRejectsForeignRelyingParty() throws { + let options = try HapiJSON.decoder.decode( + PasskeyRegistrationOptions.self, + from: Data(registrationOptionsJSON(rpId: "hub.example.com").utf8) + ) + #expect(throws: PasskeyError.relyingPartyMismatch("hub.example.com")) { + _ = try PasskeyRegistrationRequest(options: options) + } + } + + @Test func registrationRejectsMissingRelyingParty() throws { + let json = registrationOptionsJSON(rpId: "hapi.run").replacingOccurrences(of: "\"id\":\"hapi.run\"", with: "\"id\":\"\"") + let options = try HapiJSON.decoder.decode(PasskeyRegistrationOptions.self, from: Data(json.utf8)) + #expect(throws: PasskeyError.relyingPartyMismatch("")) { + _ = try PasskeyRegistrationRequest(options: options) + } + } + + @Test func assertionRequestDecodesAllowList() throws { + let options = try HapiJSON.decoder.decode( + PasskeyAssertionOptions.self, + from: Data(assertionOptionsJSON(credentials: ["Y3JlZDE"]).utf8) + ) + let request = try PasskeyAssertionRequest(options: options) + #expect(request.relyingPartyID == "hapi.run") + #expect(request.challenge == Data("challenge-bytes".utf8)) + #expect(request.allowedCredentialIDs == [Data("cred1".utf8)]) + } + + @Test func assertionRejectsForeignRelyingParty() throws { + let options = try HapiJSON.decoder.decode( + PasskeyAssertionOptions.self, + from: Data(assertionOptionsJSON(rpId: "evil.example").utf8) + ) + #expect(throws: PasskeyError.relyingPartyMismatch("evil.example")) { + _ = try PasskeyAssertionRequest(options: options) + } + } + + // MARK: - Response encoding + + @Test func registrationResponseMatchesHubShape() throws { + let result = PasskeyRegistrationResult( + credentialID: Data("credential-id".utf8), + clientDataJSON: Data("{\"type\":\"webauthn.create\"}".utf8), + attestationObject: Data([0xA3]) + ) + let body = try HapiJSON.encoder.encode(PasskeyRegistrationResponseJSON(result)) + let object = try #require( + try JSONSerialization.jsonObject(with: body) as? [String: Any] + ) + let id = Base64URL.encode(Data("credential-id".utf8)) + #expect(object["id"] as? String == id) + #expect(object["rawId"] as? String == id) + #expect(object["type"] as? String == "public-key") + #expect(object["authenticatorAttachment"] as? String == "platform") + #expect((object["clientExtensionResults"] as? [String: Any])?.isEmpty == true) + let response = try #require(object["response"] as? [String: Any]) + #expect(response["clientDataJSON"] as? String == Base64URL.encode(Data("{\"type\":\"webauthn.create\"}".utf8))) + #expect(response["attestationObject"] as? String == "ow") + #expect(response["transports"] as? [String] == ["internal", "hybrid"]) + // No padding anywhere: the hub decodes base64url. + #expect(!String(decoding: body, as: UTF8.self).contains("=")) + } + + @Test func assertionResponseMatchesHubShape() throws { + let result = PasskeyAssertionResult( + credentialID: Data("credential-id".utf8), + clientDataJSON: Data("{\"type\":\"webauthn.get\"}".utf8), + authenticatorData: Data([0x01, 0x02]), + signature: Data([0x03, 0x04]), + userID: Data("handle".utf8) + ) + let body = try HapiJSON.encoder.encode(PasskeyAssertionResponseJSON(result)) + let object = try #require(try JSONSerialization.jsonObject(with: body) as? [String: Any]) + let response = try #require(object["response"] as? [String: Any]) + #expect(object["id"] as? String == Base64URL.encode(Data("credential-id".utf8))) + #expect(response["authenticatorData"] as? String == "AQI") + #expect(response["signature"] as? String == "AwQ") + #expect(response["userHandle"] as? String == Base64URL.encode(Data("handle".utf8))) + #expect(object["type"] as? String == "public-key") + #expect(object["authenticatorAttachment"] as? String == "platform") + } + + @Test func assertionWithoutUserHandleOmitsIt() throws { + let result = PasskeyAssertionResult( + credentialID: Data("id".utf8), + clientDataJSON: Data("{}".utf8), + authenticatorData: Data([0x01]), + signature: Data([0x02]), + userID: nil + ) + let body = try HapiJSON.encoder.encode(PasskeyAssertionResponseJSON(result)) + let object = try #require(try JSONSerialization.jsonObject(with: body) as? [String: Any]) + let response = try #require(object["response"] as? [String: Any]) + #expect(response["userHandle"] == nil) + } + + // MARK: - Summaries + + @Test func passkeySummaryDecodesListResponse() throws { + let json = """ + {"passkeys":[ + {"id":"abc","name":"iPhone","rpId":"hapi.run","createdAt":1700000000000,"lastUsedAt":1700000100000,"valid":true}, + {"id":"def","name":null,"rpId":"hub.example.com","createdAt":1700000000000,"lastUsedAt":null,"valid":false} + ]} + """ + let response = try HapiJSON.decoder.decode(PasskeyListResponse.self, from: Data(json.utf8)) + #expect(response.passkeys.count == 2) + #expect(response.passkeys[0].isNative) + #expect(response.passkeys[0].lastUsedDate == Date(timeIntervalSince1970: 1_700_000_100)) + #expect(response.passkeys[1].isNative == false) + #expect(response.passkeys[1].lastUsedDate == nil) + #expect(response.passkeys[1].valid == false) + } + + // MARK: - Endpoints + + @Test func registrationOptionsRequestSendsNativeClient() async throws { + let harness = try makeHarness(paired: true, jwt: freshJWT()) + await harness.performer.enqueue(json: registrationOptionsJSON()) + _ = try await harness.client.passkeyRegistrationOptions() + let requests = await harness.performer.requests + let request = try #require(requests.first) + #expect(request.url?.absoluteString == "\(testHubURLString)/api/passkey/register/options") + #expect(request.httpMethod == "POST") + #expect(request.value(forHTTPHeaderField: "Authorization") == "Bearer \(freshJWT())") + let body = try #require(request.httpBody.flatMap { String(data: $0, encoding: .utf8) }) + #expect(body == "{\"client\":\"native\"}") + } + + @Test func loginOptionsIsUnauthenticatedAndMapsNoPasskeys() async throws { + let harness = try makeHarness(paired: false) + await harness.performer.enqueue(status: 404, json: "{\"error\":\"no_passkeys\"}") + let error = await capturedError { try await harness.client.passkeyLoginOptions() } + #expect(error as? PasskeyError == .noPasskeys) + let requests = await harness.performer.requests + let request = try #require(requests.first) + #expect(request.url?.absoluteString == "\(testHubURLString)/api/passkey/login/options") + #expect(request.value(forHTTPHeaderField: "Authorization") == nil) + #expect(request.httpBody.flatMap { String(data: $0, encoding: .utf8) } == "{\"client\":\"native\"}") + } + + @Test func loginVerifyPostsResponseEnvelope() async throws { + let harness = try makeHarness(paired: false) + let assertion = PasskeyAssertionResult( + credentialID: Data("credential-id".utf8), + clientDataJSON: Data("{\"type\":\"webauthn.get\"}".utf8), + authenticatorData: Data([0x01]), + signature: Data([0x02]), + userID: nil + ) + await harness.performer.enqueue(json: "{\"token\":\"jwt\",\"user\":{\"id\":1},\"passkeySession\":\"ps\"}") + let login = try await harness.client.verifyPasskeyLogin(PasskeyAssertionResponseJSON(assertion)) + #expect(login.token == "jwt") + #expect(login.passkeySession == "ps") + let requests = await harness.performer.requests + let request = try #require(requests.first) + #expect(request.url?.absoluteString == "\(testHubURLString)/api/passkey/login/verify") + #expect(request.value(forHTTPHeaderField: "Authorization") == nil) + let body = try #require(request.httpBody) + let object = try #require(try JSONSerialization.jsonObject(with: body) as? [String: Any]) + let response = try #require(object["response"] as? [String: Any]) + #expect(response["id"] as? String == Base64URL.encode(Data("credential-id".utf8))) + } + + @Test func registerVerifySendsResponseAndClampedName() async throws { + let harness = try makeHarness(paired: true, jwt: freshJWT()) + let result = PasskeyRegistrationResult( + credentialID: Data("id".utf8), + clientDataJSON: Data("{}".utf8), + attestationObject: Data([0x01]) + ) + let longName = String(repeating: "a", count: 80) + await harness.performer.enqueue(json: "{\"ok\":true}") + try await harness.client.verifyPasskeyRegistration(PasskeyRegistrationResponseJSON(result), name: longName) + let requests = await harness.performer.requests + let request = try #require(requests.first) + #expect(request.url?.absoluteString == "\(testHubURLString)/api/passkey/register/verify") + let body = try #require(request.httpBody) + let object = try #require(try JSONSerialization.jsonObject(with: body) as? [String: Any]) + #expect((object["name"] as? String)?.count == 64) + #expect(object["response"] != nil) + } + + @Test func listAndDeletePasskeys() async throws { + let harness = try makeHarness(paired: true, jwt: freshJWT()) + await harness.performer.enqueue(json: "{\"passkeys\":[]}") + await harness.performer.enqueue(json: "{\"ok\":true}") + let list = try await harness.client.listPasskeys() + #expect(list.isEmpty) + try await harness.client.deletePasskey(id: "a/b") + let requests = await harness.performer.requests + #expect(requests[0].url?.absoluteString == "\(testHubURLString)/api/passkeys") + #expect(requests[1].httpMethod == "DELETE") + #expect(requests[1].url?.absoluteString == "\(testHubURLString)/api/passkeys/a%2Fb") + } + + @Test func registerPasskeyRunsCeremonyAndVerifies() async throws { + let harness = try makeHarness(paired: true, jwt: freshJWT()) + let authenticator = ScriptedAuthenticator( + registration: PasskeyRegistrationResult( + credentialID: Data("id".utf8), + clientDataJSON: Data("{}".utf8), + attestationObject: Data([0x01]) + ) + ) + await harness.performer.enqueue(json: registrationOptionsJSON()) + await harness.performer.enqueue(json: "{\"ok\":true}") + try await harness.client.registerPasskey(name: " iPad ", using: authenticator) + let seen = await authenticator.registrations + #expect(seen.count == 1) + #expect(seen.first?.challenge == Data("challenge-bytes".utf8)) + let requests = await harness.performer.requests + #expect(requests.count == 2) + let body = try #require(requests[1].httpBody) + let object = try #require(try JSONSerialization.jsonObject(with: body) as? [String: Any]) + #expect(object["name"] as? String == "iPad") + } + + @Test func registerPasskeyDoesNotVerifyWhenCanceled() async throws { + let harness = try makeHarness(paired: true, jwt: freshJWT()) + let authenticator = ScriptedAuthenticator(registrationError: PasskeyError.canceled) + await harness.performer.enqueue(json: registrationOptionsJSON()) + let error = await capturedError { + try await harness.client.registerPasskey(name: "x", using: authenticator) + } + #expect(error as? PasskeyError == .canceled) + let count = await harness.performer.requests.count + #expect(count == 1) + } +} + +// MARK: - Scripted platform + +/// Records the platform requests and answers with a fixed result (or error). +actor ScriptedAuthenticator: PasskeyAuthenticating { + private(set) var registrations: [PasskeyRegistrationRequest] = [] + private(set) var assertions: [PasskeyAssertionRequest] = [] + + private let registrationResult: PasskeyRegistrationResult + private let registrationError: (any Error & Sendable)? + private let assertionResult: PasskeyAssertionResult + private let assertionError: (any Error & Sendable)? + + init( + registration: PasskeyRegistrationResult = PasskeyRegistrationResult( + credentialID: Data("id".utf8), + clientDataJSON: Data("{}".utf8), + attestationObject: Data([0x01]) + ), + registrationError: (any Error & Sendable)? = nil, + assertion: PasskeyAssertionResult = PasskeyAssertionResult( + credentialID: Data("id".utf8), + clientDataJSON: Data("{}".utf8), + authenticatorData: Data([0x01]), + signature: Data([0x02]), + userID: nil + ), + assertionError: (any Error & Sendable)? = nil + ) { + self.registrationResult = registration + self.registrationError = registrationError + self.assertionResult = assertion + self.assertionError = assertionError + } + + func register(_ request: PasskeyRegistrationRequest) async throws -> PasskeyRegistrationResult { + registrations.append(request) + if let registrationError { throw registrationError } + return registrationResult + } + + func authenticate(_ request: PasskeyAssertionRequest) async throws -> PasskeyAssertionResult { + assertions.append(request) + if let assertionError { throw assertionError } + return assertionResult + } +} diff --git a/ios/README.md b/ios/README.md index 9cd1c89e..f11a4ed7 100644 --- a/ios/README.md +++ b/ios/README.md @@ -159,6 +159,20 @@ The app supports multiple hubs with one active selection. See the an already-paired hub can be selected directly. - **Simulator:** use manual entry because `DataScannerViewController` is unavailable. Camera pairing is optional on physical devices too. +- **Passkeys:** Settings → Hubs → Passkeys lists the namespace's passkeys + (web ones, other RP IDs, are marked *Web* and are informational; `valid: + false` shows *Revoked*), adds one for the native RP `hapi.run` and deletes + with confirmation. *Sign in with a Passkey* on the pairing screen needs only + the hub URL: `/health` → `POST /api/passkey/login/options {client: + "native"}` (`allowCredentials` limits the sheet to this hub; `404 + no_passkeys` is reported) → system sheet → verify. The record then stores a + passkey session instead of an access token, and silent re-auth exchanges + `{passkeySession}`; its 401 is terminal like a rejected token. The app + refuses options whose `rp.id`/`rpId` is not `hapi.run`. Ceremonies need a + signed build with the Associated Domains capability + (`webcredentials:hapi.run`) on the App ID and the live + `https://hapi.run/.well-known/apple-app-site-association`; the + platform-free logic is covered by `PasskeysTests` / `PasskeyAuthTests`. - **Hubs:** Settings → Hubs switches between paired hubs and adds another. - **Sign out:** Settings → Hubs → Sign Out removes that hub's credentials and falls back to another paired hub or pairing. A rejected access token, or a freshly diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index e00f1b97..56155fbe 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -999,9 +999,20 @@ export const PasskeyCredentialResponseSchema = z.object({ clientDataJSON: z.string().min(1) }), clientExtensionResults: z.record(z.string(), z.unknown()).default({}), - authenticatorAttachment: z.string().optional() + // WebAuthn serializes an unknown attachment as null (e.g. Credential Manager). + authenticatorAttachment: z.string().nullish() }) +/** + * Body of `POST /api/passkey/{login,register}/options`. Web clients omit it + * (the RP is derived from the Origin header); official native apps send + * `{ "client": "native" }` to use the hub's fixed native RP ID. + */ +export const PasskeyOptionsRequestSchema = z.object({ + client: z.enum(['web', 'native']).default('web') +}) +export type PasskeyOptionsRequest = z.infer + export const PasskeyRegisterVerifyRequestSchema = z.object({ response: PasskeyCredentialResponseSchema, name: z.string().trim().max(64).optional() diff --git a/website/public/.well-known/apple-app-site-association b/website/public/.well-known/apple-app-site-association new file mode 100644 index 00000000..0db5e55d --- /dev/null +++ b/website/public/.well-known/apple-app-site-association @@ -0,0 +1,5 @@ +{ + "webcredentials": { + "apps": ["XJB862F92W.run.hapi.app"] + } +} diff --git a/website/public/.well-known/assetlinks.json b/website/public/.well-known/assetlinks.json new file mode 100644 index 00000000..ac694eaa --- /dev/null +++ b/website/public/.well-known/assetlinks.json @@ -0,0 +1,12 @@ +[ + { + "relation": ["delegate_permission/common.get_login_creds"], + "target": { + "namespace": "android_app", + "package_name": "run.hapi.companion", + "sha256_cert_fingerprints": [ + "TODO_PLAY_APP_SIGNING_SHA256_FINGERPRINT" + ] + } + } +] diff --git a/website/public/_headers b/website/public/_headers new file mode 100644 index 00000000..74dadd54 --- /dev/null +++ b/website/public/_headers @@ -0,0 +1,4 @@ +/.well-known/apple-app-site-association + Content-Type: application/json +/.well-known/assetlinks.json + Content-Type: application/json diff --git a/website/src/server/index.ts b/website/src/server/index.ts index 70704f76..2881990b 100644 --- a/website/src/server/index.ts +++ b/website/src/server/index.ts @@ -16,6 +16,14 @@ async function startServer() { ? path.resolve(__dirname, "public") : path.resolve(__dirname, "..", "dist", "public"); + // Passkey association files for the native apps (RP ID hapi.run). + // express.static ignores dot-directories by default. + app.use( + "/.well-known", + express.static(path.join(staticPath, ".well-known"), { + setHeaders: (res) => res.setHeader("Content-Type", "application/json"), + }) + ); app.use(express.static(staticPath)); // Handle client-side routing - serve index.html for all routes