feat: passkey sign-in for the iOS and Android apps

Native apps cannot follow a self-hosted hub's domain (entitlements and
asset links are fixed at build time), so they use one shared RP ID,
hapi.run, and every hub accepts it only from exact app origins.

- hub: `{"client":"native"}` on the passkey option routes selects the
  native RP; origins are https://hapi.run (iOS/macOS) and the official
  android:apk-key-hash values, extendable via HAPI_PASSKEY_NATIVE_ORIGINS
  (HAPI_PASSKEY_NATIVE_RP_ID for forks). Native login options restrict
  allowCredentials to this hub's passkeys. Accept a null
  authenticatorAttachment.
- website: publish apple-app-site-association (webcredentials for
  XJB862F92W.run.hapi.app) and assetlinks.json (get_login_creds for
  run.hapi.companion; signing fingerprint still a TODO placeholder).
- iOS: webcredentials:hapi.run, AuthenticationServices ceremonies,
  passkey-only sign-in on the pairing screen, Settings → Passkeys, and a
  passkey-session credential kind used by silent re-auth.
- Android: Credential Manager 1.6.0, the same flows and credential kind,
  and README notes on computing the apk-key-hash origin.
- docs: native passkey contract and user guide.
This commit is contained in:
weishu
2026-11-16 17:24:04 +08:00
parent 809967b7c6
commit 59a486ba88
62 changed files with 5018 additions and 148 deletions
@@ -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<Unit>(
"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<Unit>("DELETE", url("api", "passkeys", id).build())
}
// ------------------------------------------------------------ sessions --
@@ -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,
@@ -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]
@@ -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
@@ -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<ApiError> { 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")
}
}
@@ -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<ApiError> { runBlocking { hub.api.getSessions() } }
assertEquals(401, error.status)
assertEquals(listOf(AuthTerminalReason.PASSKEY_SESSION_INVALID), events.reasons)
assertFailsWith<ApiError> { 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