From ee3d7eed4c9f64762895842053140deccdebe9de Mon Sep 17 00:00:00 2001 From: weishu Date: Tue, 17 Nov 2026 11:39:01 +0800 Subject: [PATCH] feat(auth): share passkeys across web and native apps Use auth.hapi.run as the shared RP with an isolated static browser bridge, Hub-bound challenges and accounts, and one-time PKCE code exchange. Update iOS and Android validation, app associations, deployment documentation, and bidirectional browser regression coverage. --- .github/workflows/test.yml | 2 + android/README.md | 18 +- .../kotlin/app/hapi/companion/Navigation.kt | 1 + .../feature/pairing/PairingViewModel.kt | 4 +- .../CredentialManagerPasskeyPlatform.kt | 6 +- .../feature/passkey/PasskeyPlatform.kt | 2 +- .../feature/settings/PasskeysScreen.kt | 13 +- .../feature/settings/PasskeysViewModel.kt | 12 +- .../app/src/main/res/values-ru/strings.xml | 2 - .../src/main/res/values-zh-rCN/strings.xml | 2 - android/app/src/main/res/values/strings.xml | 2 - .../feature/pairing/PairingViewModelTest.kt | 8 +- .../feature/passkey/FakePasskeyPlatform.kt | 12 + .../feature/settings/PasskeysViewModelTest.kt | 11 +- .../main/kotlin/app/hapi/data/api/HapiApi.kt | 2 +- .../app/hapi/data/api/PasskeyApiTest.kt | 8 +- .../app/hapi/protocol/wire/PasskeyApi.kt | 87 ++- .../app/hapi/protocol/wire/PasskeyApiTest.kt | 14 +- .../protocol/wire/PasskeyHubBindingTest.kt | 43 ++ docs/api/client-contract/auth.md | 131 +++- docs/api/client-contract/rest.md | 2 +- docs/guide/native-apps.md | 2 +- docs/guide/pwa.md | 6 +- hub/README.md | 4 +- hub/scripts/test-passkey-browser.ts | 147 ++++ hub/src/web/authTokens.ts | 6 +- hub/src/web/routes/auth.ts | 2 + hub/src/web/routes/passkey.test.ts | 502 +++++++------- hub/src/web/routes/passkey.ts | 654 +++++++++--------- hub/src/web/server.ts | 1 + .../web/testHelpers/passkeyAuthenticator.ts | 84 +++ .../PlatformPasskeyAuthenticator.swift | 53 +- ios/Hapi/Features/Settings/PasskeysView.swift | 17 +- ios/Hapi/Hapi-macOS.entitlements | 2 +- ios/Hapi/Hapi.entitlements | 2 +- ios/Hapi/Resources/Localizable.xcstrings | 12 +- .../HapiClient/Auth/HubPairingService.swift | 2 +- .../HapiClient/Auth/PasskeyHubBinding.swift | 60 ++ .../Sources/HapiClient/Auth/Passkeys.swift | 22 +- .../Endpoints/PasskeyEndpoints.swift | 2 +- .../HapiClientTests/PasskeyAuthTests.swift | 4 +- .../PasskeyHubBindingTests.swift | 40 ++ .../HapiClientTests/PasskeyTestSupport.swift | 19 + .../Tests/HapiClientTests/PasskeysTests.swift | 57 +- ios/README.md | 31 +- package.json | 4 +- shared/package.json | 1 + shared/src/apiTypes.ts | 26 +- shared/src/index.ts | 2 + shared/src/passkey.test.ts | 36 + shared/src/passkey.ts | 70 ++ web/README.md | 33 + .../.well-known/apple-app-site-association | 0 .../passkey-site}/.well-known/assetlinks.json | 0 web/passkey-site/_headers | 12 + web/passkey-site/index.html | 23 + web/passkey-site/style.css | 9 + web/scripts/build-passkey-site.ts | 14 + web/scripts/passkey-e2e-entry.ts | 11 + web/src/api/client.ts | 31 +- web/src/components/LoginPrompt.tsx | 8 +- .../components/settings/PasskeySettings.tsx | 4 +- web/src/lib/locales/en.ts | 3 +- web/src/lib/locales/ru.ts | 3 +- web/src/lib/locales/zh-CN.ts | 3 +- web/src/lib/passkey.test.ts | 77 +++ web/src/lib/passkey.ts | 83 ++- web/src/main.tsx | 8 +- web/src/passkey-site/main.ts | 59 ++ web/src/passkey-site/request.test.ts | 49 ++ web/src/passkey-site/request.ts | 45 ++ 71 files changed, 1895 insertions(+), 832 deletions(-) create mode 100644 android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/PasskeyHubBindingTest.kt create mode 100644 hub/scripts/test-passkey-browser.ts create mode 100644 hub/src/web/testHelpers/passkeyAuthenticator.ts create mode 100644 ios/Packages/HapiKit/Sources/HapiClient/Auth/PasskeyHubBinding.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyHubBindingTests.swift create mode 100644 ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyTestSupport.swift create mode 100644 shared/src/passkey.test.ts create mode 100644 shared/src/passkey.ts rename {website/public => web/passkey-site}/.well-known/apple-app-site-association (100%) rename {website/public => web/passkey-site}/.well-known/assetlinks.json (100%) create mode 100644 web/passkey-site/_headers create mode 100644 web/passkey-site/index.html create mode 100644 web/passkey-site/style.css create mode 100644 web/scripts/build-passkey-site.ts create mode 100644 web/scripts/passkey-e2e-entry.ts create mode 100644 web/src/lib/passkey.test.ts create mode 100644 web/src/passkey-site/main.ts create mode 100644 web/src/passkey-site/request.test.ts create mode 100644 web/src/passkey-site/request.ts diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index c0de2fe6..036404f8 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -15,6 +15,8 @@ jobs: - run: bun install --frozen-lockfile - run: bun typecheck - run: bunx playwright install --with-deps chromium + - name: Shared Web/App Passkey browser regression + run: bun run test:passkey:browser # Required by cli/src/utils/windowsProcessTree.pwsh.test.ts — image # inspect alone does not pull; silent skip was fake B1 coverage (#1911). - run: docker pull mcr.microsoft.com/powershell:latest diff --git a/android/README.md b/android/README.md index d70e7389..5e8448f2 100644 --- a/android/README.md +++ b/android/README.md @@ -144,17 +144,20 @@ 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. +the fixed RP ID `auth.hapi.run`; the app refuses options for any other RP ID, and +passkeys created through the web authentication page also sign in to the app. +The app validates the connected Hub, operation/channel and registration user +handle before opening Credential Manager. Set the Hub’s `HAPI_PUBLIC_URL` to +its canonical HTTPS origin. 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 +1. `https://auth.hapi.run/.well-known/assetlinks.json` + (`web/passkey-site/.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` + (colon-separated hex). Otherwise Credential Manager rejects the `auth.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 @@ -181,8 +184,9 @@ 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. +a fork with its own shared RP constant, static authentication site, and matching +app build. Only the auth.hapi.run maintainers can change the official file; +per-Hub RP overrides are not supported. ## Firebase / push 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 b7bc1363..90e0596f 100644 --- a/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt +++ b/android/app/src/main/kotlin/app/hapi/companion/Navigation.kt @@ -1000,6 +1000,7 @@ private class PasskeysViewModelHolder(hubGraph: HubGraph) : ViewModel() { val viewModel = PasskeysViewModel( gateway = object : PasskeysGateway { + override val hubUrl: String = hubGraph.hubUrl private val api = hubGraph.session.api override suspend fun list(): List = api.getPasskeys().passkeys override suspend fun registerOptions(): String = api.passkeyRegisterOptions() 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 5c9960fc..dabc5234 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 @@ -181,8 +181,8 @@ class PairingViewModel( val login = try { val options = client.passkeyLoginOptions() - NativePasskeys.requireRequestRpId(options) - val assertion = platform.getPasskey(options) + val checkedOptions = NativePasskeys.ceremonyOptions(options, hubUrl, "login") + val assertion = platform.getPasskey(checkedOptions) client.passkeyLoginVerify(NativePasskeys.credentialResponse(assertion)) } catch (cancellation: CancellationException) { throw cancellation 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 index 1f1b93a6..26659513 100644 --- 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 @@ -22,13 +22,13 @@ 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` / + * [PasskeyPlatform] over Jetpack Credential Manager. Validated, whitelisted + * options go in as `requestJson`; `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` + * for RP ID `auth.hapi.run` only succeed when `https://auth.hapi.run/.well-known/assetlinks.json` * lists this build's package + signing-certificate SHA-256 (see the Android * README, "Passkeys"). */ 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 index 40483616..19fee20f 100644 --- 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 @@ -7,7 +7,7 @@ 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 + * fake. Both methods take validated, whitelisted WebAuthn options JSON and return * the platform's response JSON, or throw [PasskeyCeremonyException]. */ interface PasskeyPlatform { 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 index 97ee85d6..10887088 100644 --- 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 @@ -54,8 +54,8 @@ 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 + * `CLI_API_TOKEN` rotation or an unsupported RP ID. + * Add registers an `auth.hapi.run` passkey for both Web and App through * Credential Manager; delete asks for confirmation first. */ @OptIn(ExperimentalMaterial3Api::class) @@ -245,7 +245,6 @@ private fun PasskeyRow( 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()) { @@ -256,14 +255,6 @@ private fun PasskeyRow( 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) { 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 index 2839f83d..70d26dac 100644 --- 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 @@ -16,6 +16,8 @@ import kotlinx.serialization.json.JsonObject /** Transport seam over the authed `HapiApi` passkey endpoints (JVM-testable). */ interface PasskeysGateway { + val hubUrl: String + /** `GET /api/passkeys`. */ suspend fun list(): List @@ -53,12 +55,12 @@ 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. + * shared Web/App RP ID (`auth.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. + * A dismissed sheet is silent. Web and native registration create the same + * kind of Hub-scoped credential. */ class PasskeysViewModel( private val gateway: PasskeysGateway, @@ -97,8 +99,8 @@ class PasskeysViewModel( scope.launch { try { val options = gateway.registerOptions() - NativePasskeys.requireCreationRpId(options) - val registration = platform.createPasskey(options) + val checkedOptions = NativePasskeys.ceremonyOptions(options, gateway.hubUrl, "register") + val registration = platform.createPasskey(checkedOptions) gateway.registerVerify( NativePasskeys.credentialResponse(registration), NativePasskeys.normalizeName(name), diff --git a/android/app/src/main/res/values-ru/strings.xml b/android/app/src/main/res/values-ru/strings.xml index d2aa0235..1b3684b6 100644 --- a/android/app/src/main/res/values-ru/strings.xml +++ b/android/app/src/main/res/values-ru/strings.xml @@ -822,9 +822,7 @@ Ключей доступа пока нет. Создан %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 9af0f64c..27f39731 100644 --- a/android/app/src/main/res/values-zh-rCN/strings.xml +++ b/android/app/src/main/res/values-zh-rCN/strings.xml @@ -808,9 +808,7 @@ 还没有通行密钥。 创建于 %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 2e2e3ce4..d733f667 100644 --- a/android/app/src/main/res/values/strings.xml +++ b/android/app/src/main/res/values/strings.xml @@ -808,9 +808,7 @@ 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. 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 2ee70985..cc00d1e7 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,8 @@ package app.hapi.companion.feature.pairing +import app.hapi.protocol.wire.NativePasskeys +import app.hapi.companion.feature.passkey.boundPasskeyOptions import app.hapi.companion.feature.passkey.FakePasskeyPlatform import app.hapi.companion.feature.passkey.PasskeyCeremonyException import app.hapi.companion.feature.passkey.PasskeyIssue @@ -52,7 +54,7 @@ private class FakePairingClient : PairingClient { return authResult(accessToken) } - var loginOptionsResult: () -> String = { """{"challenge":"Y2g","rpId":"hapi.run","allowCredentials":[]}""" } + var loginOptionsResult: () -> String = { boundPasskeyOptions(HUB, "login") } var loginVerifyResult: (JsonObject) -> PasskeyLoginResponse = { PasskeyLoginResponse(token = "jwt-passkey", user = AuthUser(id = 1), passkeySession = "ps-1") } @@ -256,8 +258,8 @@ class PairingViewModelTest { 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()) + assertEquals(1, platform.getRequests.size, "validated options are handed to the platform") + assertEquals(NativePasskeys.ceremonyOptions(client.loginOptionsResult(), HUB, "login"), platform.getRequests.single()) assertTrue(client.authCalls.isEmpty(), "no access-token exchange on the passkey path") val verified = client.verifyBodies.single() 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 index 711c3024..6fa8b660 100644 --- 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 @@ -24,3 +24,15 @@ class FakePasskeyPlatform : PasskeyPlatform { return getResult(requestJson) } } + +/** The production clients must validate these envelopes before platform UI. */ +fun boundPasskeyOptions(hub: String, operation: String): String { + val b64 = java.util.Base64.getUrlEncoder().withoutPadding() + val challenge = b64.encodeToString( + """{"v":1,"hub":"$hub","id":"${"a".repeat(43)}","nonce":"${"b".repeat(43)}","operation":"$operation","channel":"native"}""".toByteArray(), + ) + if (operation == "login") return """{"challenge":"$challenge","rpId":"auth.hapi.run","allowCredentials":[{"id":"Y3JlZA","type":"public-key"}]}""" + val prefix = java.security.MessageDigest.getInstance("SHA-256").digest(hub.toByteArray()) + val user = b64.encodeToString(prefix + ByteArray(32) { 1 }) + return """{"challenge":"$challenge","rp":{"id":"auth.hapi.run"},"user":{"id":"$user","name":"hapi@${java.net.URI(hub).rawAuthority}"}}""" +} 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 index 7216f533..06a5d60d 100644 --- 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 @@ -2,6 +2,8 @@ package app.hapi.companion.feature.settings +import app.hapi.protocol.wire.NativePasskeys +import app.hapi.companion.feature.passkey.boundPasskeyOptions import app.hapi.companion.feature.passkey.FakePasskeyPlatform import app.hapi.companion.feature.passkey.PasskeyCeremonyException import app.hapi.companion.feature.passkey.PasskeyIssue @@ -27,9 +29,10 @@ class PasskeysViewModelTest { CoroutineScope(SupervisorJob() + StandardTestDispatcher(testScheduler)) private class FakeGateway : PasskeysGateway { + override val hubUrl = "https://hub.example.com" var passkeys = mutableListOf() var options: () -> String = { - """{"rp":{"id":"hapi.run","name":"HAPI"},"user":{"id":"dXNlcg","name":"hapi@hub"},"challenge":"Y2g"}""" + boundPasskeyOptions(hubUrl, "register") } var verifyError: Exception? = null val verified = mutableListOf>() @@ -40,7 +43,7 @@ class PasskeysViewModelTest { 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) + passkeys += PasskeySummary(id = "new", name = name, rpId = "auth.hapi.run", createdAt = 99) } override suspend fun delete(id: String) { deleted += id @@ -48,7 +51,7 @@ class PasskeysViewModelTest { } } - private fun passkey(id: String, rpId: String = "hapi.run", createdAt: Long = 1, valid: Boolean = true) = + private fun passkey(id: String, rpId: String = "auth.hapi.run", createdAt: Long = 1, valid: Boolean = true) = PasskeySummary(id = id, name = id, rpId = rpId, createdAt = createdAt, valid = valid) @Test @@ -80,7 +83,7 @@ class PasskeysViewModelTest { assertEquals(PasskeysBusy.Adding, vm.busy.value) advanceUntilIdle() - assertEquals(listOf(gateway.options()), platform.createRequests) + assertEquals(listOf(NativePasskeys.ceremonyOptions(gateway.options(), gateway.hubUrl, "register")), platform.createRequests) val (response, name) = gateway.verified.single() assertEquals("Pixel 9", name) assertEquals("public-key", response["type"]?.jsonPrimitive?.content) 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 a903f92b..a6fa311b 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 @@ -213,7 +213,7 @@ class HapiApi internal constructor( request("POST", url("api", "auth").build(), AuthRequest(accessToken = accessToken).toJsonBody(), authClient) // ------------------------------------------------------------ passkeys -- - // Native passkeys use the fixed RP ID `hapi.run`; every call sends + // Native passkeys use the shared RP ID `auth.hapi.run`; every call sends // `{"client":"native"}` and exchanges base64url WebAuthn JSON with the // platform credential provider. Hub: `hub/src/web/routes/passkey.ts`. 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 index 34da8da6..82a72dbf 100644 --- 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 @@ -29,7 +29,7 @@ class PasskeyApiTest { 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"}""" + """{"rp":{"id":"auth.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"}}""" @@ -84,7 +84,7 @@ class PasskeyApiTest { @Test fun `login options and verify go out without a bearer header`() { - server.enqueue(ok("""{"challenge":"Y2g","rpId":"hapi.run","allowCredentials":[]}""")) + server.enqueue(ok("""{"challenge":"Y2g","rpId":"auth.hapi.run","allowCredentials":[]}""")) server.enqueue( ok("""{"token":"jwt-2","user":{"id":1,"firstName":"Web User"},"passkeySession":"ps-1"}"""), ) @@ -92,7 +92,7 @@ class PasskeyApiTest { val options = runBlocking { session.api.passkeyLoginOptions() } val login = runBlocking { session.api.passkeyLoginVerify(NativePasskeys.credentialResponse(assertion)) } - assertEquals("hapi.run", NativePasskeys.requestRpId(options)) + assertEquals("auth.hapi.run", NativePasskeys.requestRpId(options)) assertEquals("ps-1", login.passkeySession) assertEquals("jwt-2", login.token) @@ -122,7 +122,7 @@ class PasskeyApiTest { 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}]}""", + """{"passkeys":[{"id":"a/b","name":null,"rpId":"auth.hapi.run","createdAt":1,"lastUsedAt":null,"valid":true}]}""", ), ) server.enqueue(ok("""{"ok":true}""")) 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 index cdec5062..b1efdec6 100644 --- 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 @@ -1,9 +1,16 @@ package app.hapi.protocol.wire +import java.net.URI +import java.security.MessageDigest +import java.util.Base64 import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonNull import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.buildJsonArray +import kotlinx.serialization.json.put /** * Native passkey wire types (`docs/api/client-contract/auth.md#passkeys-native`; @@ -11,16 +18,16 @@ import kotlinx.serialization.json.JsonObject * `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. + * WebAuthn options and credential responses use JSON rather than full wire + * models. [NativePasskeys.ceremonyOptions] validates Hub/RP binding and selects + * supported fields before Credential Manager consumes the options and produces + * `RegistrationResponseJSON` / `AuthenticationResponseJSON`. */ /** * 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. + * default on purpose: [HapiJson] does not encode defaults, and direct + * options endpoints require an explicit native client. */ @Serializable data class PasskeyOptionsRequest( @@ -64,7 +71,7 @@ data class PasskeyLoginResponse( data class PasskeySummary( val id: String, val name: String? = null, - /** `hapi.run` for app passkeys; any other value is a web passkey. */ + /** Shared Web/App RP ID (`auth.hapi.run`). */ val rpId: String, val createdAt: Long, val lastUsedAt: Long? = null, @@ -79,8 +86,8 @@ data class PasskeyListResponse( /** 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" + /** RP ID compiled into the official apps (asset links on `auth.hapi.run`). */ + const val RP_ID: String = "auth.hapi.run" /** Hub-side limit on passkey names (`PasskeyRegisterVerifyRequestSchema`). */ const val MAX_NAME_LENGTH: Int = 64 @@ -109,6 +116,68 @@ object NativePasskeys { if (actual != expected) throw PasskeyRpMismatchException(expected, actual) } + /** Reject a different Hub/operation/channel before invoking Credential Manager. */ + fun requireHubBinding(optionsJson: String, hubUrl: String, operation: String) { + require(operation == "login" || operation == "register") + val options = parseObject(optionsJson) ?: error("Invalid passkey options") + val uri = URI(hubUrl) + require(uri.scheme.equals("https", ignoreCase = true) && uri.host != null && uri.rawUserInfo == null + && uri.rawQuery == null && uri.rawFragment == null && (uri.path.isNullOrEmpty() || uri.path == "/")) + val port = if (uri.port == -1 || uri.port == 443) "" else ":${uri.port}" + val hub = "https://${uri.host.lowercase()}$port" + val encoded = options["challenge"].stringOrNull ?: error("Missing passkey challenge") + require(encoded.length <= 4096) + val challenge = parseObject(String(Base64.getUrlDecoder().decode(encoded), Charsets.UTF_8)) + ?: error("Invalid passkey challenge") + require(challenge["v"].toString() == "1" && challenge["hub"].stringOrNull == hub + && challenge["operation"].stringOrNull == operation && challenge["channel"].stringOrNull == "native" + && challenge["id"].stringOrNull?.matches(Regex("[A-Za-z0-9_-]{43}")) == true + && challenge["nonce"].stringOrNull?.matches(Regex("[A-Za-z0-9_-]{43}")) == true) { + "Passkey challenge does not match this Hub or operation" + } + if (operation == "login") require((options["allowCredentials"] as? JsonArray)?.isNotEmpty() == true) + if (operation == "register") { + val user = options["user"].objOrNull ?: error("Missing passkey account") + val handle = Base64.getUrlDecoder().decode(user["id"].stringOrNull ?: error("Missing passkey account")) + val prefix = MessageDigest.getInstance("SHA-256").digest(hub.toByteArray(Charsets.UTF_8)) + require(handle.size == 64 && handle.copyOfRange(0, 32).contentEquals(prefix)) { "Passkey account belongs to another Hub" } + require(user["name"].stringOrNull?.endsWith("@${URI(hub).rawAuthority}") == true) + } + } + + /** Only the WebAuthn fields this client supports reach Credential Manager. + * In particular, an untrusted Hub cannot ask for PRF/largeBlob extensions + * on credentials that share this RP with other Hubs. */ + fun ceremonyOptions(optionsJson: String, hubUrl: String, operation: String): String { + if (operation == "register") requireCreationRpId(optionsJson) else requireRequestRpId(optionsJson) + requireHubBinding(optionsJson, hubUrl, operation) + val input = parseObject(optionsJson)!! + return buildJsonObject { + put("challenge", input.getValue("challenge")) + put("timeout", 120000) + if (operation == "login") { + put("rpId", RP_ID) + put("allowCredentials", input.getValue("allowCredentials")) + put("userVerification", "required") + } else { + put("rp", buildJsonObject { put("id", RP_ID); put("name", "HAPI") }) + val user = input.getValue("user").objOrNull!! + put("user", buildJsonObject { + put("id", user.getValue("id")); put("name", user.getValue("name")) + put("displayName", "HAPI · ${URI(hubUrl).rawAuthority.lowercase()}") + }) + put("pubKeyCredParams", buildJsonArray { + for (alg in listOf(-7, -257)) add(buildJsonObject { put("alg", alg); put("type", "public-key") }) + }) + input["excludeCredentials"]?.let { put("excludeCredentials", it) } + put("authenticatorSelection", buildJsonObject { + put("residentKey", "required"); put("userVerification", "required") + }) + put("attestation", "none") + } + }.toString() + } + /** * Parses a platform credential response for embedding as `response`. * Top-level JSON `null`s are dropped: the hub schema allows optional 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 index dd933cb1..4104051f 100644 --- 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 @@ -17,7 +17,7 @@ class PasskeyApiTest { private val creationOptions = """ { - "rp": {"id": "hapi.run", "name": "HAPI"}, + "rp": {"id": "auth.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}], @@ -28,7 +28,7 @@ class PasskeyApiTest { private val requestOptions = """ { "challenge": "Y2hhbGxlbmdl", - "rpId": "hapi.run", + "rpId": "auth.hapi.run", "allowCredentials": [{"type": "public-key", "id": "Y3JlZA"}], "userVerification": "required" } @@ -100,7 +100,7 @@ class PasskeyApiTest { val list = HapiJson.decodeFromString( """ {"passkeys":[ - {"id":"native-1","name":"Pixel 9","rpId":"hapi.run","createdAt":1750000000000, + {"id":"native-1","name":"Pixel 9","rpId":"auth.hapi.run","createdAt":1750000000000, "lastUsedAt":null,"valid":true}, {"id":"web-1","name":null,"rpId":"hub.example","createdAt":1750000000001,"valid":false} ]} @@ -123,19 +123,19 @@ class PasskeyApiTest { @Test fun `reads the declared relying party from both option shapes`() { - assertEquals("hapi.run", NativePasskeys.creationRpId(creationOptions)) - assertEquals("hapi.run", NativePasskeys.requestRpId(requestOptions)) + assertEquals("auth.hapi.run", NativePasskeys.creationRpId(creationOptions)) + assertEquals("auth.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 foreign = creationOptions.replace("\"auth.hapi.run\"", "\"evil.example\"") val mismatch = assertFailsWith { NativePasskeys.requireCreationRpId(foreign) } - assertEquals("hapi.run", mismatch.expected) + assertEquals("auth.hapi.run", mismatch.expected) assertEquals("evil.example", mismatch.actual) val missing = assertFailsWith { diff --git a/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/PasskeyHubBindingTest.kt b/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/PasskeyHubBindingTest.kt new file mode 100644 index 00000000..8aa24454 --- /dev/null +++ b/android/core/protocol/src/test/kotlin/app/hapi/protocol/wire/PasskeyHubBindingTest.kt @@ -0,0 +1,43 @@ +package app.hapi.protocol.wire + +import java.security.MessageDigest +import java.util.Base64 +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFalse +import kotlin.test.assertFailsWith + +class PasskeyHubBindingTest { + private val hub = "https://hub.example.com" + private fun options(origin: String = hub, operation: String = "login", channel: String = "native", accountHub: String = origin): String { + val b64 = Base64.getUrlEncoder().withoutPadding() + val challenge = b64.encodeToString("""{"v":1,"hub":"$origin","id":"${"a".repeat(43)}","nonce":"${"b".repeat(43)}","operation":"$operation","channel":"$channel"}""".toByteArray()) + val user = b64.encodeToString(MessageDigest.getInstance("SHA-256").digest(accountHub.toByteArray()) + ByteArray(32)) + return """{"challenge":"$challenge","allowCredentials":[{"id":"Y3JlZA"}],"user":{"id":"$user","name":"hapi@hub.example.com"}}""" + } + + @Test fun `only supported fields reach the credential provider`() { + val input = options().dropLast(1) + """, "rpId":"auth.hapi.run", "userVerification":"discouraged", "extensions":{"prf":{}}}""" + val checked = NativePasskeys.ceremonyOptions(input, hub, "login") + assertFalse(checked.contains("extensions")) + assertFalse(checked.contains("discouraged")) + assertEquals(true, checked.contains("required")) + } + + @Test fun `validates both operations and canonical default port`() { + NativePasskeys.requireHubBinding(options(), "https://HUB.example.com:443/", "login") + NativePasskeys.requireHubBinding(options(operation = "register"), hub, "register") + } + + @Test fun `refuses forwarded challenges and wrong channels before the system UI`() { + for (input in listOf(options(origin = "https://other.example"), options(operation = "register"), options(channel = "browser"), "{}")) { + assertFailsWith { NativePasskeys.requireHubBinding(input, hub, "login") } + } + } + + @Test fun `refuses account handles belonging to another Hub`() { + assertFailsWith { + NativePasskeys.requireHubBinding(options(operation = "register", accountHub = "https://other.example"), hub, "register") + } + } +} diff --git a/docs/api/client-contract/auth.md b/docs/api/client-contract/auth.md index 763cdc56..6044536e 100644 --- a/docs/api/client-contract/auth.md +++ b/docs/api/client-contract/auth.md @@ -10,7 +10,7 @@ Source of truth: `hub/src/config/cliApiToken.ts`, `hub/src/web/routes/auth.ts`. |------------|----------|--------------------|---------------| | **Access token** | Long-lived (until the operator rotates `CLI_API_TOKEN`) | Pairing QR / deeplink, or typed in manually | Exchanged for a JWT via `POST /api/auth`; the client's durable secret | | **JWT** | 4 hours | Response of `POST /api/auth` | `Authorization: Bearer` on every `/api/*` request | -| **Passkey session** (web only) | 30 days, and only while its passkey is valid | Response of `POST /api/passkey/login/verify` | Exchanged for a JWT via `POST /api/auth`; never accepted as a bearer token | +| **Passkey session** (web and native) | 30 days, and only while its passkey is valid | Native login verification or browser code exchange | Exchanged for a JWT via `POST /api/auth`; never accepted as a bearer token | The hub's base token (`CLI_API_TOKEN`) is auto-generated on first run (32 random bytes, base64url, ~43 chars) and persisted in the hub's `settings.json`; an operator-provided env token overrides it. The configured base token never contains a `:` — the hub refuses to start otherwise (`validateCliApiToken`). @@ -92,7 +92,7 @@ Treat the token as opaque for auth purposes, but clients may base64url-decode th Source of truth: `hub/src/web/middleware/auth.ts`. - Every `/api/*` request: `Authorization: Bearer `. -- Exceptions: `/api/auth`, `/api/bind`, `/api/passkey/login/options` and `/api/passkey/login/verify` are unauthenticated; `GET /health` is outside `/api` and unauthenticated. +- Exceptions: `/api/auth`, `/api/bind`, `/api/passkey/login/options`, `/api/passkey/login/verify`, `/api/passkey/browser/login/start`, `/api/passkey/browser/complete` and `/api/passkey/browser/exchange` are unauthenticated; `GET /health` is outside `/api` and unauthenticated. - `GET /api/events` (SSE) **additionally** accepts `?token=` as a query param, for HTTP stacks whose EventSource cannot set headers. The header wins when both are present. No other endpoint accepts query-param auth. ## Silent re-auth (401 handling) @@ -117,37 +117,122 @@ Implementation notes: ## Passkeys (web) {#passkeys-web} -Source of truth: `hub/src/web/routes/passkey.ts`, `hub/src/web/authTokens.ts`, `web/src/lib/passkey.ts`. +Source of truth: `shared/src/passkey.ts`, `hub/src/web/routes/passkey.ts`, +`web/src/lib/passkey.ts`, `web/src/passkey-site/`. -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). +Web and native clients use **one RP ID: `auth.hapi.run`**. A credential registered +from either client can sign in to the other, for the **same Hub and namespace**. +The public key and credential-to-namespace mapping stay in that Hub's database; +the official authentication site is static, not an account server. -- **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. +Set `HAPI_PUBLIC_URL` to the Hub's canonical **HTTPS origin** (no path, query, +credentials, or fragment). The configured origin, never an untrusted proxy Host +header, identifies the Hub. The client must connect through that same origin. +The web app must also use HTTPS and allow the authentication popup. Separately +hosted web apps must have their exact origin in `CORS_ORIGINS`; `*` does not grant +permission to receive authentication callbacks. + +### Browser ceremony + +1. The initiating tab generates a random state and PKCE verifier; it keeps the + verifier in memory. Call `POST /api/passkey/browser/login/start` with + `{codeChallenge, state, callbackOrigin}`. Use + `POST /api/passkey/browser/register/start` with a JWT for registration; it + additionally accepts `name`. PKCE is SHA-256/base64url, without padding. +2. The Hub creates a one-time, five-minute transaction and returns `{url}`. + Open that URL on `https://auth.hapi.run/` in the popup. Its fragment contains + `{hub, operation, options}` only, never an access token/JWT/verifier. +3. The static page checks the challenge/account's Hub binding, shows the Hub + address, and calls WebAuthn after user confirmation. It enforces user + verification and the fixed RP, ignoring untrusted extension choices. +4. The page submits an `application/x-www-form-urlencoded` top-level form to + the challenge-bound Hub's fixed `POST /api/passkey/browser/complete`, with + `challenge` and JSON `response` (or `error=cancelled`). No cross-origin API + fetch or general CORS access from the authentication site is required. +5. The Hub verifies the stored challenge, exact expected origin, signature, + namespace and token fingerprint. It redirects with 303 to the transaction's + fixed `/passkey/callback#state=...&code=...` (or `error`). + Only the canonical Hub origin or an explicitly configured web origin may + receive this callback; arbitrary return URLs are not supported. +6. The callback clears the fragment and sends the code/state to its opener at + its own exact origin. The opener checks origin, popup identity and state, + then calls `POST /api/passkey/browser/exchange {code, verifier}`. Codes expire + in 60 seconds and are atomically consumed after PKCE validation. Login + returns `{operation:"login", token, user, passkeySession}`; registration + returns `{operation:"register"}`. No long-lived token reaches the static site. + +Registration authorization is scoped to the JWT namespace and the current +`CLI_API_TOKEN` fingerprint at transaction creation. Rotation during registration +aborts it. Code exchange re-checks credential existence, namespace and token +fingerprint; deletion/rotation cannot revive a pending authorization. + +The web stores `passkeySession` under `hapi_passkey_session::` instead of +an access token. Refresh remains `POST /api/auth {passkeySession}`. Sessions last +30 days while the credential is valid. Deletion revokes them immediately; +rotating `CLI_API_TOKEN` revokes all passkeys and their refresh sessions. + +### Shared-RP isolation + +The decoded challenge is `{v:1, hub, id, operation, channel, nonce}` with +cryptographically random 32-byte `id` and `nonce` (base64url). `hub` is the +canonical HTTPS Hub origin, `operation` is `login|register`, and `channel` is +`browser|native`. Clients validate these fields **before opening the system +sheet**; the Hub verifies its exact saved challenge and consumes it once. +A malicious Hub cannot proxy another Hub's challenge through the shared RP. + +The 64-byte user handle is `SHA-256(hub) || HMAC-SHA256(secret, namespace)` (the +HMAC uses a domain-separated input). Clients validate the Hub prefix before +registration so a malicious Hub cannot overwrite another Hub's account. It is +not a Hub URL discovery mechanism. Login options restrict `allowCredentials` to +this Hub's currently valid shared-RP credentials. + +The authentication origin is part of the security boundary. It must contain no +marketing app, third-party scripts, analytics, or service worker. Compromising +that origin compromises the shared browser authentication surface. Existing +credentials using other RP IDs are not supported; register new credentials. ## Native passkeys {#passkeys-native} -Source of truth: `hub/src/web/routes/passkey.ts` (`nativePasskeyConfigFromEnv`), `website/public/.well-known/`. +Native clients use the same RP/credentials, without a browser redirect: -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`**: +1. `POST /api/passkey/register/options {client:"native"}` (JWT required), + validate RP, connected Hub, operation/channel and user-handle prefix, invoke + the platform API, then `POST /api/passkey/register/verify {response, name}`. +2. `POST /api/passkey/login/options {client:"native"}` (unauthenticated), + validate RP and challenge binding, invoke the platform API, then + `POST /api/passkey/login/verify {response}`. `404 no_passkeys` means none of + this Hub's shared-RP credentials are valid; fall back to the access token. +3. Store `{token, passkeySession}` in secure per-Hub storage and use the normal + silent re-auth exchange. `401 passkey_session_invalid` is terminal. -- `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. +Native clients ignore unsupported WebAuthn extensions and enforce user +verification before invoking the platform. iOS offers both platform and roaming +security-key assertion providers, so web-created security-key passkeys are not +restricted to the browser. A credential must be available through the device’s +provider, a synced password manager, or an accessible authenticator. - Pages on other `*.hapi.run` hosts can request `hapi.run` assertions, but the hub rejects their origins. +Direct options/verify routes are native-only; browser-channel challenges cannot +be used there, and native-channel challenges cannot use the browser bridge. +All binary fields are base64url without padding; user verification is required. -Client flow (same endpoints as the web; natives send no `Origin` header): +- iOS/macOS declares `webcredentials:auth.hapi.run`. The RP's static + `/.well-known/apple-app-site-association` lists `XJB862F92W.run.hapi.app`. + Expected client-data origin: `https://auth.hapi.run`. +- Android uses Credential Manager. The RP's static `/.well-known/assetlinks.json` + grants `delegate_permission/common.get_login_creds` to `run.hapi.companion` + with the official signing-certificate fingerprint. Expected origin: + `android:apk-key-hash:`. +- `HAPI_PASSKEY_NATIVE_ORIGINS` adds explicitly trusted Android signing-certificate + origins for debug builds. Arbitrary HTTPS origins and per-Hub RP overrides + are not accepted. Forks change the shared constant, static site and app + associations together. -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. +Static association sources: `web/passkey-site/.well-known/`. Build with +`bun run build:passkey-site`; deploy **only `website/dist/auth/`** to +`https://auth.hapi.run`, with the supplied security headers. The bridge uses `strict-origin` referrers +(origin only, no request parameters); `no-referrer` would turn Chromium form +POST origins into `null` and is not appropriate for this bridge. It is independent +of the marketing site's `website/dist/public/` output. ## Namespaces diff --git a/docs/api/client-contract/rest.md b/docs/api/client-contract/rest.md index b42c83ac..cd51dba8 100644 --- a/docs/api/client-contract/rest.md +++ b/docs/api/client-contract/rest.md @@ -8,7 +8,7 @@ does not mean the app offers that feature. ## Conventions -- All paths below are relative to the hub base URL. `/api` routes require `Authorization: Bearer ` except the `/api/auth` exchange, Telegram `/api/bind`, and the web passkey sign-in (`/api/passkey/login/*`) ([Auth](./auth.md)). +- All paths below are relative to the hub base URL. `/api` routes require `Authorization: Bearer ` except the `/api/auth` exchange, Telegram `/api/bind`, and the native passkey sign-in (`/api/passkey/login/*`) and browser sign-in/completion/exchange (`/api/passkey/browser/login/start`, `/api/passkey/browser/complete`, `/api/passkey/browser/exchange`) ([Auth](./auth.md)). - Path params (`:id`, `:messageId`, …) must be URL-encoded (the web client uses `encodeURIComponent` throughout). - Request bodies are JSON (`content-type: application/json`) with **one exception**: `POST /api/voice/transcription` is `multipart/form-data`. Responses are JSON unless noted (generated images and scratchlist attachments return raw bytes). - Bodies are validated with Zod; failures return `400` (see [Errors](./errors.md)). diff --git a/docs/guide/native-apps.md b/docs/guide/native-apps.md index ec54a3f2..8260c94f 100644 --- a/docs/guide/native-apps.md +++ b/docs/guide/native-apps.md @@ -70,7 +70,7 @@ 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. +- Web and App passkeys use the shared `auth.hapi.run` relying party. Register once in either client to sign in to that same Hub from both. Configure the Hub’s `HAPI_PUBLIC_URL` as its canonical HTTPS origin; no association files are needed on your own domain. - Rotating the hub's access token, or deleting the passkey, signs out every device that signed in with it. ## Sessions and everyday use diff --git a/docs/guide/pwa.md b/docs/guide/pwa.md index f650c2d8..125f5786 100644 --- a/docs/guide/pwa.md +++ b/docs/guide/pwa.md @@ -103,9 +103,11 @@ See [Web Share Target](https://developer.chrome.com/docs/capabilities/web-apis/w After you sign in with the access token once, open **Settings → Passkeys → Add passkey** to register Face ID, Touch ID, Windows Hello, or a security key. Next time, choose **Sign in with a passkey** on the login screen. The browser then no longer keeps your access token. -- Passkeys need HTTPS, or `http://localhost`. Plain-HTTP LAN addresses such as `http://192.168.x.x` cannot use them. -- A passkey only works on the address where it was added. For example, a passkey added on your relay URL does not work on `localhost`. +- Configure the Hub's `HAPI_PUBLIC_URL` as its canonical HTTPS origin and open the web app over HTTPS. Allow the authentication popup. +- Registration and sign-in open the isolated static page at `auth.hapi.run`. Passkeys created from the web and the official apps work in both, for the same Hub. +- A separately hosted web app must have its exact origin in the Hub's `CORS_ORIGINS`; a wildcard is not enough for authentication callbacks. - Rotating `CLI_API_TOKEN` disables all passkeys. Sign in with the new token and add them again. +- Credentials from the previous domain-specific/`hapi.run` RP design must be registered again. ## Caching Strategy diff --git a/hub/README.md b/hub/README.md index 1ab928b2..14193a0b 100644 --- a/hub/README.md +++ b/hub/README.md @@ -22,7 +22,7 @@ See `src/configuration.ts` for all options. ### Optional (Telegram) - `TELEGRAM_BOT_TOKEN` - Token from @BotFather. -- `HAPI_PUBLIC_URL` - Public HTTPS URL for Telegram Mini App access. Also used to derive default CORS origins for the web app. +- `HAPI_PUBLIC_URL` - Canonical public HTTPS origin for shared Passkeys and Telegram Mini App access. Also used to derive default CORS origins for the web app. ### Optional (Voice) @@ -108,7 +108,7 @@ for request/response shapes and error semantics, and `src/web/routes/` for all e - `POST /api/auth` - Get JWT token (Telegram initData, `CLI_API_TOKEN[:namespace]`, or a `passkeySession`). - `POST /api/passkey/login/options`, `POST /api/passkey/login/verify` - Unauthenticated WebAuthn sign-in; returns a JWT plus a 30-day `passkeySession`. -- `POST /api/passkey/register/options`, `POST /api/passkey/register/verify`, `GET /api/passkeys`, `DELETE /api/passkeys/:id` - Manage passkeys for the caller's namespace (JWT required). Passkeys are bound to the browser origin and to the current `CLI_API_TOKEN`; rotating the token revokes them. See the [client contract](../docs/api/client-contract/auth.md#passkeys-web). +- `POST /api/passkey/register/options`, `POST /api/passkey/register/verify`, `GET /api/passkeys`, `DELETE /api/passkeys/:id` - Manage passkeys for the caller's namespace (JWT required). Web and App passkeys share RP ID `auth.hapi.run` and are scoped to this Hub/namespace and the current `CLI_API_TOKEN`; rotating the token revokes them. Browser ceremonies use `/api/passkey/browser/{login,register}/start`, `/complete`, and `/exchange`. Set `HAPI_PUBLIC_URL` to the canonical HTTPS Hub origin. See the [client contract](../docs/api/client-contract/auth.md#passkeys-web). - `POST /api/bind` - Bind a Telegram account using initData + `CLI_API_TOKEN:`. ### Sessions (`src/web/routes/sessions.ts`) diff --git a/hub/scripts/test-passkey-browser.ts b/hub/scripts/test-passkey-browser.ts new file mode 100644 index 00000000..ab946345 --- /dev/null +++ b/hub/scripts/test-passkey-browser.ts @@ -0,0 +1,147 @@ +/** Real Chromium WebAuthn + production Hub/bridge, entirely intercepted locally. + * No DNS, requests to production, signed app, or central account service needed. */ +import { chromium, type Page, type CDPSession } from '@playwright/test' +import { createHash, createPrivateKey, randomBytes, sign } from 'node:crypto' +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { Hono } from 'hono' +import { PASSKEY_ORIGIN, PASSKEY_RP_ID } from '@hapi/protocol/passkey' +import { createConfiguration } from '../src/configuration' +import { Store } from '../src/store' +import { signWebJwt } from '../src/web/authTokens' +import { createAuthMiddleware, type WebAppEnv } from '../src/web/middleware/auth' +import { createPasskeyLoginRoutes, createPasskeyManagementRoutes, PasskeyChallengeStore } from '../src/web/routes/passkey' +import { SoftAuthenticator } from '../src/web/testHelpers/passkeyAuthenticator' + +const hub = 'https://hub.test' +const androidOrigin = 'android:apk-key-hash:browser-integration-test' +const secret = randomBytes(32) +const home = await mkdtemp(join(tmpdir(), 'hapi-passkey-browser-')) +const previousHome = process.env.HAPI_HOME +process.env.HAPI_HOME = home +await createConfiguration() +const store = new Store(':memory:') +const deps = { + jwtSecret: secret, store, hubUrl: () => hub, corsOrigins: () => [], + challenges: new PasskeyChallengeStore(), native: { rpId: PASSKEY_RP_ID, origins: [PASSKEY_ORIGIN, androidOrigin] } +} +const app = new Hono() +app.route('/api', createPasskeyLoginRoutes(deps)) +app.use('/api/*', createAuthMiddleware(secret)) +app.route('/api', createPasskeyManagementRoutes(deps)) +const token = await signWebJwt(secret, 1, 'team') +const bundle = await Bun.build({ entrypoints: [resolve(import.meta.dir, '../../web/scripts/passkey-e2e-entry.ts')], target: 'browser', minify: false }) +if (!bundle.success) throw new AggregateError(bundle.logs) +const bundleJS = await bundle.outputs[0].text() +let browser: Awaited> | undefined +const requests: string[] = [] +let cdp: CDPSession | undefined +try { + browser = await chromium.launch({ headless: true, channel: process.env.PLAYWRIGHT_CHANNEL, args: ['--no-sandbox'] }) + const context = await browser.newContext() + context.setDefaultTimeout(15000) + context.on('page', (p) => { + p.on('pageerror', (error) => console.error('Browser error:', error.message)) + }) + // Block everything except in-memory Hub requests and built local auth files. + await context.route('**/*', async (route) => { + const request = route.request() + const url = new URL(request.url()) + if (url.origin === hub && url.pathname.startsWith('/api/')) { + requests.push(`${request.method()} ${url.pathname} (${request.headers().origin ?? "no-origin"})`) + const response = await app.request(request.url(), { + method: request.method(), headers: request.headers(), body: request.postDataBuffer() ?? undefined + }) + requests.push(`→ ${response.status}`) + await route.fulfill({ status: response.status, headers: Object.fromEntries(response.headers), body: Buffer.from(await response.arrayBuffer()) }) + } else if (url.origin === hub && url.pathname === '/fixture.js') { + await route.fulfill({ contentType: 'text/javascript', body: bundleJS }) + } else if (url.origin === hub && url.pathname === '/passkey/callback') { + await route.fulfill({ contentType: 'text/html', body: `` }) + } else if (url.origin === hub && url.pathname === '/callback.js') { + // Exported production callback handler, without mounting the app/router. + await route.fulfill({ contentType: 'text/javascript', body: callbackJS }) + } else if (url.origin === hub && url.pathname === '/') { + await route.fulfill({ contentType: 'text/html', body: `

` }) + } else if (url.origin === PASSKEY_ORIGIN && ['/', '/main.js', '/style.css'].includes(url.pathname)) { + const file = resolve(import.meta.dir, '../../website/dist/auth', url.pathname === '/' ? 'index.html' : url.pathname.slice(1)) + await route.fulfill({ + contentType: url.pathname.endsWith('.js') ? 'text/javascript' : url.pathname.endsWith('.css') ? 'text/css' : 'text/html', + headers: { 'content-security-policy': "default-src 'none'; script-src 'self'; style-src 'self'; form-action https:; frame-ancestors 'none'; base-uri 'none'", 'referrer-policy': 'strict-origin' }, + body: await readFile(file) + }) + } else { await route.abort() } + }) + const callbackBuild = await Bun.build({ entrypoints: [resolve(import.meta.dir, '../../web/src/lib/passkey.ts')], target: 'browser' }) + if (!callbackBuild.success) throw new AggregateError(callbackBuild.logs) + const callbackJS = await callbackBuild.outputs[0].text() + const page = await context.newPage() + await page.goto(hub) + + type Credential = { credentialId: string; privateKey: string; userHandle?: string; signCount: number; rpId: string; isResidentCredential: boolean } + async function virtualPopup(button: string, credential?: Credential): Promise<{ popup: Page; id: string }> { + const popupEvent = page.waitForEvent('popup') + await page.click(button) + const popup = await popupEvent + await popup.waitForURL(`${PASSKEY_ORIGIN}/**`) + cdp = await context.newCDPSession(popup) + await cdp.send('WebAuthn.enable') + const { authenticatorId } = await cdp.send('WebAuthn.addVirtualAuthenticator', { + options: { protocol: 'ctap2', transport: 'internal', hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true } + }) + if (credential) await cdp.send('WebAuthn.addCredential', { authenticatorId, credential }) + return { popup, id: authenticatorId } + } + const first = await virtualPopup('#register') + const created = new Promise((resolve) => cdp!.once('WebAuthn.credentialAdded', (event) => resolve(event.credential))) + await first.popup.click('#continue') + let timer: ReturnType | undefined + const credential = await Promise.race([ + created, + new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('Virtual authenticator did not create a credential')), 15000) }) + ]).finally(() => clearTimeout(timer)) + await page.waitForFunction(() => Boolean(document.querySelector('#result')?.textContent)) + if (await page.locator('#result').textContent() !== 'registered') throw new Error(await page.locator('#result').textContent() ?? 'Registration failed') + if (store.passkeys.listByNamespace('team').length !== 1) throw new Error('Browser registration did not reach Hub') + + // A synced browser-created key signs an Android-origin assertion to the real Hub. + const optionsResponse = await app.request('/api/passkey/login/options', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"client":"native"}' }) + const options = await optionsResponse.json() as { challenge: string } + const hash = (value: string | Buffer) => createHash('sha256').update(value).digest() + const data = Buffer.from(JSON.stringify({ type: 'webauthn.get', challenge: options.challenge, origin: androidOrigin, crossOrigin: false })) + const counter = Buffer.alloc(4); counter.writeUInt32BE(credential.signCount + 1) + const authData = Buffer.concat([hash(PASSKEY_RP_ID), Buffer.from([0x05]), counter]) + const signature = sign('sha256', Buffer.concat([authData, hash(data)]), createPrivateKey({ key: Buffer.from(credential.privateKey, 'base64'), type: 'pkcs8', format: 'der' })) + const id = Buffer.from(credential.credentialId, 'base64').toString('base64url') + const native = await app.request('/api/passkey/login/verify', { + method: 'POST', headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ response: { id, rawId: id, type: 'public-key', clientExtensionResults: {}, response: { clientDataJSON: data.toString('base64url'), authenticatorData: authData.toString('base64url'), signature: signature.toString('base64url') } } }) + }) + if (native.status !== 200) throw new Error(`Browser → App failed: ${await native.text()}`) + console.log('PASS: browser-created Passkey signs into native endpoint') + + // Register through native endpoints, then import the synced key into Chromium. + const soft = new SoftAuthenticator(PASSKEY_RP_ID, androidOrigin) + const registration = await app.request('/api/passkey/register/options', { + method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` }, body: '{"client":"native"}' + }) + const creation = await registration.json() as { challenge: string; user: { id: string } } + const registered = await app.request('/api/passkey/register/verify', { + method: 'POST', headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` }, body: JSON.stringify({ response: soft.create(creation) }) + }) + if (registered.status !== 200) throw new Error(await registered.text()) + const second = await virtualPopup('#login', soft.virtualCredential()) + await second.popup.click('#continue') + await page.waitForFunction(() => document.querySelector('#result')?.textContent?.startsWith('session:')) + console.log('PASS: native-created Passkey signs into web via static bridge, callback, and PKCE') +} catch (error) { + console.error(requests.join("\n")) + throw error +} finally { + await browser?.close() + store.close() + if (previousHome === undefined) delete process.env.HAPI_HOME + else process.env.HAPI_HOME = previousHome + await rm(home, { recursive: true, force: true }) +} diff --git a/hub/src/web/authTokens.ts b/hub/src/web/authTokens.ts index abac538a..e49d98d5 100644 --- a/hub/src/web/authTokens.ts +++ b/hub/src/web/authTokens.ts @@ -1,4 +1,4 @@ -import { createHmac } from 'node:crypto' +import { createHash, createHmac } from 'node:crypto' import { SignJWT, jwtVerify } from 'jose' import { z } from 'zod' @@ -65,9 +65,9 @@ export function cliTokenFingerprint(jwtSecret: Uint8Array, cliApiToken: string): } /** Stable, hub-specific WebAuthn user handle for a namespace. */ -export function passkeyUserHandle(jwtSecret: Uint8Array, namespace: string): Uint8Array { +export function passkeyUserHandle(jwtSecret: Uint8Array, namespace: string, hub: string): Uint8Array { const digest = createHmac('sha256', jwtSecret) .update(`hapi-passkey-user:${namespace}`) .digest() - return new Uint8Array(digest) + return new Uint8Array(Buffer.concat([createHash('sha256').update(hub).digest(), digest])) } diff --git a/hub/src/web/routes/auth.ts b/hub/src/web/routes/auth.ts index 9038b526..3abf8d3e 100644 --- a/hub/src/web/routes/auth.ts +++ b/hub/src/web/routes/auth.ts @@ -1,4 +1,5 @@ import { Hono } from 'hono' +import { PASSKEY_RP_ID } from '@hapi/protocol/passkey' import { AuthRequestSchema } from '@hapi/protocol' import { getConfiguration } from '../../configuration' import { constantTimeEquals } from '../../utils/crypto' @@ -44,6 +45,7 @@ export function createAuthRoutes(jwtSecret: Uint8Array, store: Store): Hono { for (const store of stores.splice(0)) store.close() }) + const JWT_SECRET = new Uint8Array(randomBytes(32)) const ORIGIN = 'https://hub.example.com' const HOST = 'hub.example.com' @@ -26,305 +31,278 @@ 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() -/** Minimal software authenticator: ES256, `none` attestation, UP+UV set. */ -class SoftAuthenticator { - readonly credentialId = randomBytes(16) - private readonly privateKey: KeyObject - private readonly publicJwk: { x: string; y: string } - private counter = 0 - userHandle: string | null = null +type Options = { challenge: string; rp: { id: string }; user: { id: string; name: string }; allowCredentials: Array<{ id: string }> } +type Session = { token: string; passkeySession: string; operation: string } +type Listed = { passkeys: Array<{ valid: boolean }> } - constructor(private readonly rpId: string, private readonly origin: string) { - const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' }) - this.privateKey = privateKey - this.publicJwk = publicKey.export({ format: 'jwk' }) as { x: string; y: string } - } - - private clientData(type: string, challenge: string): Buffer { - return Buffer.from(JSON.stringify({ type, challenge, origin: this.origin, crossOrigin: false })) - } - - create(options: { challenge: string; user: { id: string } }) { - this.userHandle = options.user.id - const cose = new Map([ - [1, 2], [3, -7], [-1, 1], - [-2, new Uint8Array(Buffer.from(this.publicJwk.x, 'base64url'))], - [-3, new Uint8Array(Buffer.from(this.publicJwk.y, 'base64url'))] - ]) - const idLength = Buffer.alloc(2) - idLength.writeUInt16BE(this.credentialId.length) - const authData = Buffer.concat([ - sha256(this.rpId), Buffer.from([0x45]), Buffer.alloc(4), Buffer.alloc(16), - idLength, this.credentialId, Buffer.from(isoCBOR.encode(cose)) - ]) - const attestationObject = isoCBOR.encode(new Map([ - ['fmt', 'none'], ['attStmt', new Map()], ['authData', new Uint8Array(authData)] - ]) as never) - return { - id: b64url(this.credentialId), - rawId: b64url(this.credentialId), - type: 'public-key', - response: { - clientDataJSON: b64url(this.clientData('webauthn.create', options.challenge)), - attestationObject: b64url(attestationObject), - transports: ['internal'] - }, - clientExtensionResults: {}, - authenticatorAttachment: null - } - } - - get(options: { challenge: string }) { - this.counter += 1 - const counter = Buffer.alloc(4) - counter.writeUInt32BE(this.counter) - const authData = Buffer.concat([sha256(this.rpId), Buffer.from([0x05]), counter]) - const clientData = this.clientData('webauthn.get', options.challenge) - const signature = sign('sha256', Buffer.concat([authData, sha256(clientData)]), this.privateKey) - return { - id: b64url(this.credentialId), - rawId: b64url(this.credentialId), - type: 'public-key', - response: { - clientDataJSON: b64url(clientData), - authenticatorData: b64url(authData), - signature: b64url(signature), - userHandle: this.userHandle ?? undefined - }, - clientExtensionResults: {} - } - } -} - -function createApp(store: Store) { +function createApp(store: Store, config: { now?: () => number; cors?: string[]; hub?: string } = {}) { const app = new Hono() const deps = { - jwtSecret: JWT_SECRET, - store, - corsOrigins: () => [], - challenges: new PasskeyChallengeStore(), - native: { rpId: 'hapi.run', origins: ['https://hapi.run', ANDROID_ORIGIN] } + jwtSecret: JWT_SECRET, store, + hubUrl: () => config.hub ?? ORIGIN, + corsOrigins: () => config.cors ?? [], + challenges: new PasskeyChallengeStore(config.now), + native: { rpId: PASSKEY_RP_ID, origins: [PASSKEY_ORIGIN, ANDROID_ORIGIN] } } app.route('/api', createAuthRoutes(JWT_SECRET, store)) app.route('/api', createPasskeyLoginRoutes(deps)) app.use('/api/*', createAuthMiddleware(JWT_SECRET)) app.route('/api', createPasskeyManagementRoutes(deps)) - return app + return { app, deps } } function post(app: Hono, path: string, body: unknown, extra: Record = {}) { return app.request(path, { - method: 'POST', - headers: { origin: ORIGIN, host: HOST, 'content-type': 'application/json', ...extra }, + method: 'POST', headers: { origin: ORIGIN, host: HOST, 'content-type': 'application/json', ...extra }, body: JSON.stringify(body) }) } - async function bearer(namespace = 'default') { return { authorization: `Bearer ${await signWebJwt(JWT_SECRET, 1, namespace)}` } } - -async function register(app: Hono, authenticator: SoftAuthenticator, namespace = 'default') { - const auth = await bearer(namespace) - const options = await (await post(app, '/api/passkey/register/options', {}, auth)).json() as { challenge: string; user: { id: string } } - const res = await post(app, '/api/passkey/register/verify', { response: authenticator.create(options), name: 'Laptop' }, auth) - expect(res.status).toBe(200) +async function nativeOptions(app: Hono, kind: 'register' | 'login', namespace = 'default') { + return post(app, `/api/passkey/${kind}/options`, { client: 'native' }, kind === 'register' ? await bearer(namespace) : {}) } - -async function login(app: Hono, authenticator: SoftAuthenticator) { - const options = await (await post(app, '/api/passkey/login/options', {})).json() as { challenge: string } +async function registerNative(app: Hono, authenticator: SoftAuthenticator, namespace = 'default') { + const res = await nativeOptions(app, 'register', namespace) + expect(res.status).toBe(200) + const options = await res.json() as Options + expect(options.rp.id).toBe(PASSKEY_RP_ID) + expect(Buffer.from(options.user.id, 'base64url')).toHaveLength(64) + expect(options.user.name).toBe(`${namespace === 'default' ? 'hapi' : `hapi:${namespace}`}@${HOST}`) + const verify = await post(app, '/api/passkey/register/verify', { response: authenticator.create(options), name: 'Laptop' }, await bearer(namespace)) + expect([verify.status, await verify.clone().text()]).toEqual([200, expect.any(String)]) + return options +} +async function nativeLogin(app: Hono, authenticator: SoftAuthenticator) { + const options = await (await nativeOptions(app, 'login')).json() as Options const assertion = authenticator.get(options) - return { res: await post(app, '/api/passkey/login/verify', { response: assertion }), assertion } + const res = await post(app, '/api/passkey/login/verify', { response: assertion }) + return { res, assertion } +} +const verifier = randomBytes(32).toString('base64url') +const startBody = () => ({ state: randomBytes(32).toString('base64url'), codeChallenge: b64url(sha256(verifier)), callbackOrigin: ORIGIN }) +async function browserStart(app: Hono, operation: 'register' | 'login', namespace = 'default') { + const input = startBody() + const res = await post(app, `/api/passkey/browser/${operation}/start`, { ...input, name: 'Browser' }, operation === 'register' ? await bearer(namespace) : {}) + expect(res.status).toBe(200) + const body = await res.json() as { url: string } + const url = new URL(body.url) + expect(url.origin).toBe(PASSKEY_ORIGIN) + return { request: JSON.parse(decodeURIComponent(url.hash.slice(1))) as { options: Options }, input } +} +async function complete(app: Hono, challenge: string, response?: unknown, origin = PASSKEY_ORIGIN) { + return app.request('/api/passkey/browser/complete', { + method: 'POST', headers: { origin, 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ challenge, ...(response ? { response: JSON.stringify(response) } : { error: 'cancelled' }) }) + }) +} +async function exchange(app: Hono, redirect: Response, proof = verifier) { + expect(redirect.status).toBe(303) + const target = new URL(redirect.headers.get('location')!) + expect(target.origin).toBe(ORIGIN) + expect(target.pathname).toBe('/passkey/callback') + return post(app, '/api/passkey/browser/exchange', { code: new URLSearchParams(target.hash.slice(1)).get('code'), verifier: proof }) } beforeAll(async () => { process.env.HAPI_HOME ??= mkdtempSync(join(tmpdir(), 'hapi-passkey-test-')) await createConfiguration() }) +beforeEach(() => { getConfiguration()._setCliApiToken('token-one', 'env', false) }) -beforeEach(() => { - getConfiguration()._setCliApiToken('token-one', 'env', false) -}) - -describe('passkey routes', () => { - it('registers, logs in, refreshes via passkey session, and rejects replay', async () => { - const store = new Store(':memory:') - const app = createApp(store) - const authenticator = new SoftAuthenticator(HOST, ORIGIN) - await register(app, authenticator, 'team') - - const { res, assertion } = await login(app, authenticator) +describe('unified passkeys', () => { + it('logs into web with an App-created passkey; the bridge never gets tokens', async () => { + const store = newStore() + const { app } = createApp(store) + const a = new SoftAuthenticator(PASSKEY_RP_ID, ANDROID_ORIGIN) + await registerNative(app, a, 'team') + a.origin = PASSKEY_ORIGIN + const { request, input } = await browserStart(app, 'login') + expect(request.options.allowCredentials.map((c: { id: string }) => c.id)).toEqual([b64url(a.credentialId)]) + const response = a.get(request.options) + const redirect = await complete(app, request.options.challenge, response) + expect(redirect.headers.get('cache-control')).toBe('no-store') + expect(redirect.headers.get('location')).not.toContain('token=') + const callback = new URLSearchParams(new URL(redirect.headers.get('location')!).hash.slice(1)) + expect(callback.get('state')).toBe(input.state) + const result = await exchange(app, redirect) + expect(result.status).toBe(200) + const body = await result.json() as Session + expect(body.operation).toBe('login') + expect(body.passkeySession).toBeString() + expect(JSON.parse(Buffer.from(body.token.split('.')[1], 'base64url').toString()).ns).toBe('team') + expect((await post(app, '/api/auth', { passkeySession: body.passkeySession })).status).toBe(200) + expect((await complete(app, request.options.challenge, response)).status).toBe(401) + expect((await exchange(app, redirect)).status).toBe(401) + }) + it('logs into the App with a web-created passkey', async () => { + const store = newStore() + const { app } = createApp(store) + const a = new SoftAuthenticator(PASSKEY_RP_ID, PASSKEY_ORIGIN) + const { request } = await browserStart(app, 'register', 'team') + const redirect = await complete(app, request.options.challenge, a.create(request.options)) + expect(await (await exchange(app, redirect)).json()).toEqual({ operation: 'register' }) + a.origin = ANDROID_ORIGIN + const { res, assertion } = await nativeLogin(app, a) expect(res.status).toBe(200) - const body = await res.json() as { token: string; passkeySession: string } + const body = await res.json() as Session const list = await app.request('/api/passkeys', { headers: { authorization: `Bearer ${body.token}` } }) - const listed = await list.json() as { passkeys: Array<{ name: string; valid: boolean; lastUsedAt: number | null }> } - expect(listed.passkeys).toHaveLength(1) - expect(listed.passkeys[0]).toMatchObject({ name: 'Laptop', valid: true }) - expect(listed.passkeys[0]?.lastUsedAt).not.toBeNull() - - // The same signed assertion cannot be used twice. + expect((await list.json() as Listed).passkeys).toMatchObject([{ rpId: PASSKEY_RP_ID, valid: true, name: 'Browser' }]) expect((await post(app, '/api/passkey/login/verify', { response: assertion })).status).toBe(401) - - // The long-lived session is exchangeable, but never usable as a bearer token. - const refreshed = await post(app, '/api/auth', { passkeySession: body.passkeySession }) - expect(refreshed.status).toBe(200) - expect((await app.request('/api/passkeys', { - headers: { authorization: `Bearer ${body.passkeySession}` } - })).status).toBe(401) - store.close() + expect((await app.request('/api/passkeys', { headers: { authorization: `Bearer ${body.passkeySession}` } })).status).toBe(401) }) - - it('scopes the issued JWT to the registering namespace', async () => { - const store = new Store(':memory:') - const app = createApp(store) - const authenticator = new SoftAuthenticator(HOST, ORIGIN) - await register(app, authenticator, 'team') - const { res } = await login(app, authenticator) - const { token } = await res.json() as { token: string } - const payload = JSON.parse(Buffer.from(token.split('.')[1]!, 'base64url').toString()) as { ns: string } - expect(payload.ns).toBe('team') - - const other = await (await app.request('/api/passkeys', { headers: await bearer('default') })).json() as { passkeys: unknown[] } - expect(other.passkeys).toHaveLength(0) - const id = b64url(authenticator.credentialId) - expect((await app.request(`/api/passkeys/${id}`, { method: 'DELETE', headers: await bearer('default') })).status).toBe(404) - expect((await app.request(`/api/passkeys/${id}`, { method: 'DELETE', headers: await bearer('team') })).status).toBe(200) - expect((await login(app, authenticator)).res.status).toBe(401) - store.close() + it('enforces PKCE without consuming a code on an incorrect verifier', async () => { + const store = newStore() + const { app } = createApp(store) + const a = new SoftAuthenticator(PASSKEY_RP_ID, PASSKEY_ORIGIN) + await registerNative(app, a) + const { request } = await browserStart(app, 'login') + const redirect = await complete(app, request.options.challenge, a.get(request.options)) + expect((await exchange(app, redirect, randomBytes(32).toString('base64url'))).status).toBe(401) + expect((await exchange(app, redirect)).status).toBe(200) }) - - it('revokes passkeys and passkey sessions when the CLI token rotates', async () => { - const store = new Store(':memory:') - const app = createApp(store) - const authenticator = new SoftAuthenticator(HOST, ORIGIN) - await register(app, authenticator) - const { passkeySession } = await (await login(app, authenticator)).res.json() as { passkeySession: string } - + it('expires authorization codes', async () => { + const store = newStore() + let now = Date.now() + const { app } = createApp(store, { now: () => now }) + const a = new SoftAuthenticator(PASSKEY_RP_ID, PASSKEY_ORIGIN) + await registerNative(app, a) + const { request } = await browserStart(app, 'login') + const redirect = await complete(app, request.options.challenge, a.get(request.options)) + now += 61000 + expect((await exchange(app, redirect)).status).toBe(401) + }) + it('requires an existing JWT to begin registration', async () => { + const store = newStore() + const { app } = createApp(store) + expect((await post(app, '/api/passkey/browser/register/start', startBody())).status).toBe(401) + expect((await post(app, '/api/passkey/register/options', { client: 'native' })).status).toBe(401) + }) + it('rejects wildcard/untrusted callbacks and caller-selected redirect paths', async () => { + const store = newStore() + const { app } = createApp(store, { cors: ['*'] }) + for (const callbackOrigin of ['https://evil.example', `${ORIGIN}/evil`, `${ORIGIN}/`, 'javascript:alert(1)']) { + const res = await post(app, '/api/passkey/browser/login/start', { ...startBody(), callbackOrigin }, { origin: callbackOrigin }) + expect(res.status).toBe(400) + } + expect((await post(app, '/api/passkey/browser/login/start', { ...startBody(), returnUrl: 'https://evil.example' })).status).toBe(400) + expect((await post(app, '/api/passkey/browser/login/start', startBody(), { origin: 'https://evil.example' })).status).toBe(400) + }) + it('allows an explicitly trusted separately hosted web app with a fixed callback', async () => { + const store = newStore() + const origin = 'https://app.hapi.run' + const { app } = createApp(store, { cors: [origin] }) + const a = new SoftAuthenticator(PASSKEY_RP_ID, PASSKEY_ORIGIN) + await registerNative(app, a) + const start = await post(app, '/api/passkey/browser/login/start', { ...startBody(), callbackOrigin: origin }, { origin }) + expect(start.status).toBe(200) + const request = JSON.parse(decodeURIComponent(new URL((await start.json() as { url: string }).url).hash.slice(1))) + const result = await complete(app, request.options.challenge, a.get(request.options)) + expect(new URL(result.headers.get('location')!).origin).toBe(origin) + }) + it('does not trust a proxy Host header as the Hub identity', async () => { + const store = newStore() + const { app } = createApp(store) + const res = await post(app, '/api/passkey/register/options', { client: 'native' }, { ...await bearer(), host: '127.0.0.1:3006' }) + expect((await res.json() as Options).user.name).toBe(`hapi@${HOST}`) + const invalid = createApp(store, { hub: 'http://localhost:3006' }).app + expect((await nativeOptions(invalid, 'register')).status).toBe(400) + }) + it('isolates namespaces, validates origins, and rejects cross-channel exchanges', async () => { + const store = newStore() + const { app } = createApp(store) + const a = new SoftAuthenticator(PASSKEY_RP_ID, PASSKEY_ORIGIN) + await registerNative(app, a, 'team') + const id = b64url(a.credentialId) + expect((await app.request(`/api/passkeys/${id}`, { method: 'DELETE', headers: await bearer() })).status).toBe(404) + const { request } = await browserStart(app, 'login') + expect((await complete(app, request.options.challenge, a.get(request.options), 'https://evil.example')).status).toBe(400) + // Wrong origin did not consume the challenge. + expect((await exchange(app, await complete(app, request.options.challenge, a.get(request.options)))).status).toBe(200) + const native = await (await nativeOptions(app, 'login')).json() as Options + expect((await complete(app, native.challenge, a.get(native))).status).toBe(401) + const browser = await browserStart(app, 'login') + expect((await post(app, '/api/passkey/login/verify', { response: a.get(browser.request.options) })).status).toBe(401) + a.origin = 'https://evil.auth.hapi.run' + expect((await nativeLogin(app, a)).res.status).toBe(401) + }) + it('rejects wrong namespace and token rotation during registration', async () => { + const store = newStore() + const { app } = createApp(store) + const a = new SoftAuthenticator(PASSKEY_RP_ID, PASSKEY_ORIGIN) + const options = await (await nativeOptions(app, 'register', 'team')).json() as Options + expect((await post(app, '/api/passkey/register/verify', { response: a.create(options) }, await bearer())).status).toBe(400) + const { request } = await browserStart(app, 'register') getConfiguration()._setCliApiToken('token-two', 'env', false) - const { res } = await login(app, authenticator) - expect(res.status).toBe(401) - expect(await res.json()).toEqual({ error: 'passkey_revoked' }) - expect((await post(app, '/api/auth', { passkeySession })).status).toBe(401) - const listed = await (await app.request('/api/passkeys', { headers: await bearer() })).json() as { passkeys: Array<{ valid: boolean }> } - expect(listed.passkeys[0]?.valid).toBe(false) - store.close() + const redirect = await complete(app, request.options.challenge, a.create(request.options)) + expect(redirect.headers.get('location')).toContain('error=passkey_revoked') + expect(store.passkeys.listByNamespace('default')).toHaveLength(0) }) - - it('rejects untrusted origins and registration without a JWT', async () => { - const store = new Store(':memory:') - const app = createApp(store) - expect((await post(app, '/api/passkey/login/options', {}, { origin: 'https://evil.example' })).status).toBe(400) - expect((await post(app, '/api/passkey/register/options', {})).status).toBe(401) - - // An assertion produced for another origin fails even with a valid challenge. - const authenticator = new SoftAuthenticator(HOST, ORIGIN) - await register(app, authenticator) - const phished = new SoftAuthenticator(HOST, 'https://evil.example') - Object.assign(phished, { credentialId: authenticator.credentialId }) - expect((await login(app, phished)).res.status).toBe(401) - store.close() + it('revokes pending authorizations and refresh sessions on deletion/rotation', async () => { + const store = newStore() + const { app } = createApp(store) + const a = new SoftAuthenticator(PASSKEY_RP_ID, PASSKEY_ORIGIN) + await registerNative(app, a) + const login = await (await nativeLogin(app, a)).res.json() as Session + const { request } = await browserStart(app, 'login') + const redirect = await complete(app, request.options.challenge, a.get(request.options)) + getConfiguration()._setCliApiToken('token-two', 'env', false) + expect((await exchange(app, redirect)).status).toBe(401) + expect((await post(app, '/api/auth', { passkeySession: login.passkeySession })).status).toBe(401) + expect((await nativeOptions(app, 'login')).status).toBe(404) + expect((await post(app, '/api/passkey/login/options', {})).status).toBe(400) + const listed = await (await app.request('/api/passkeys', { headers: await bearer() })).json() as Listed + expect(listed.passkeys[0].valid).toBe(false) + }) + it('rejects deletion between authentication and code exchange', async () => { + const store = newStore() + const { app } = createApp(store) + const a = new SoftAuthenticator(PASSKEY_RP_ID, PASSKEY_ORIGIN) + await registerNative(app, a) + const { request } = await browserStart(app, 'login') + const redirect = await complete(app, request.options.challenge, a.get(request.options)) + store.passkeys.remove(b64url(a.credentialId), 'default') + expect((await exchange(app, redirect)).status).toBe(401) + }) + it('returns cancellation to the initiating window without an authorization code', async () => { + const store = newStore() + const { app } = createApp(store) + const { request, input } = await browserStart(app, 'register') + const redirect = await complete(app, request.options.challenge) + const params = new URLSearchParams(new URL(redirect.headers.get('location')!).hash.slice(1)) + expect(params.get('state')).toBe(input.state) + expect(params.get('error')).toBe('cancelled') + expect(params.has('code')).toBe(false) + }) + it('limits ceremony request bodies', async () => { + const store = newStore() + const { app } = createApp(store) + expect((await post(app, '/api/passkey/login/options', { padding: 'x'.repeat(128 * 1024) })).status).toBe(413) }) }) -describe('resolveRelyingParty', () => { - it('requires a trusted, secure, domain-name origin', () => { - 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') - expect(resolveRelyingParty(undefined, 'hub.example.com', [])).toHaveProperty('error') - }) -}) - -describe('PasskeyChallengeStore', () => { - it('is one-time, expires, and evicts the oldest entry instead of refusing new ones', () => { +describe('bounded one-time state', () => { + it('expires and evicts the oldest pending ceremony', () => { let now = 0 - const store = new PasskeyChallengeStore(() => now) - 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() - - store.put('b', entry(100)) + const state = new PasskeyChallengeStore(() => now) + const entry = { kind: 'login' as const, channel: 'native' as const, hub: ORIGIN, fingerprint: 'f', rpId: PASSKEY_RP_ID, origins: [PASSKEY_ORIGIN], expiresAt: 100 } + state.put('a', entry) + expect(state.take('a')).not.toBeNull() + expect(state.take('a')).toBeNull() + state.put('b', entry) now = 100 - expect(store.take('b')).toBeNull() - - for (let i = 0; i < 300; i++) store.put(`c${i}`, entry(1000)) - expect(store.take('c0')).toBeNull() - expect(store.take('c299')).not.toBeNull() + expect(state.take('b')).toBeNull() + for (let i = 0; i < 300; i++) state.put(`c${i}`, { ...entry, expiresAt: 1000 }) + expect(state.take('c0')).toBeNull() + expect(state.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', 'android:apk-key-hash:gPW441aKA2v53lho7kg86hFe1WjiLKXKUy4Iz3Kvfs8'] - }) - 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'] }) +describe('native origins', () => { + it('pins the shared RP and accepts only explicitly trusted Android extras', () => { + expect(nativePasskeyConfigFromEnv({})).toEqual({ rpId: PASSKEY_RP_ID, origins: [PASSKEY_ORIGIN, ...OFFICIAL_ANDROID_PASSKEY_ORIGINS] }) + expect(nativePasskeyConfigFromEnv({ HAPI_PASSKEY_NATIVE_ORIGINS: 'android:apk-key-hash:debug' }).origins).toContain('android:apk-key-hash:debug') + expect(() => nativePasskeyConfigFromEnv({ HAPI_PASSKEY_NATIVE_ORIGINS: 'https://evil.example' })).toThrow() }) }) diff --git a/hub/src/web/routes/passkey.ts b/hub/src/web/routes/passkey.ts index 05ff7262..3cf0257b 100644 --- a/hub/src/web/routes/passkey.ts +++ b/hub/src/web/routes/passkey.ts @@ -1,402 +1,382 @@ +import { createHash, randomBytes } from 'node:crypto' import { Hono } from 'hono' import type { Context } from 'hono' import type { AuthenticationResponseJSON, RegistrationResponseJSON } from '@simplewebauthn/server' import { + PasskeyBrowserExchangeRequestSchema, + PasskeyBrowserStartRequestSchema, PasskeyLoginVerifyRequestSchema, PasskeyOptionsRequestSchema, PasskeyRegisterVerifyRequestSchema, + type PasskeyBrowserStartRequest, type PasskeyListResponse } from '@hapi/protocol' +import { + canonicalPasskeyHub, encodePasskeyChallenge, PASSKEY_CALLBACK_PATH, + PASSKEY_MAX_REQUEST_LENGTH, PASSKEY_ORIGIN, PASSKEY_RP_ID, + type PasskeyChannel, type PasskeyOperation +} from '@hapi/protocol/passkey' import { getConfiguration } from '../../configuration' import { getOrCreateOwnerId } from '../../config/ownerId' import { constantTimeEquals } from '../../utils/crypto' import type { Store } from '../../store' import type { WebAppEnv } from '../middleware/auth' -import { - cliTokenFingerprint, - passkeyUserHandle, - signPasskeySession, - signWebJwt -} from '../authTokens' +import { cliTokenFingerprint, passkeyUserHandle, signPasskeySession, signWebJwt } from '../authTokens' -// Bun can initialize SimpleWebAuthn's transitive tsyringe before its polyfill -// in dynamic bundles. Await the polyfill before loading either runtime entry. await import('reflect-metadata') -const { - generateAuthenticationOptions, - generateRegistrationOptions, - verifyAuthenticationResponse, - verifyRegistrationResponse -} = await import('@simplewebauthn/server') +const { generateAuthenticationOptions, generateRegistrationOptions, verifyAuthenticationResponse, verifyRegistrationResponse } + = await import('@simplewebauthn/server') const { decodeClientDataJSON } = await import('@simplewebauthn/server/helpers') const CHALLENGE_TTL_MS = 5 * 60 * 1000 -const MAX_PENDING_CHALLENGES = 256 -const RP_NAME = 'HAPI' +const CODE_TTL_MS = 60 * 1000 +const random = () => randomBytes(32).toString('base64url') +const sha256 = (value: string) => createHash('sha256').update(value).digest('base64url') -type ChallengeEntry = - | { kind: 'register'; rpId: string; origins: string[]; namespace: string; expiresAt: number } - | { kind: 'login'; rpId: string; origins: string[]; expiresAt: number } +type BrowserBinding = PasskeyBrowserStartRequest -/** - * 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 = { +type ChallengeEntry = { + kind: PasskeyOperation + channel: PasskeyChannel rpId: string origins: string[] + hub: string + namespace?: string + fingerprint: string + expiresAt: number + browser?: BrowserBinding } -export const DEFAULT_NATIVE_PASSKEY_RP_ID = 'hapi.run' +type CodeEntry = { + operation: PasskeyOperation + credentialId: string + namespace: string + fingerprint: string + codeChallenge: string + expiresAt: number +} -/** - * `android:apk-key-hash:` origins of official Android builds: base64url (no - * padding) of the Play App Signing certificate SHA-256 - * 80:F5:B8:E3:56:8A:03:6B:F9:DE:58:68:EE:48:3C:EA:11:5E:D5:68:E2:2C:A5:CA:53:2E:08:CF:72:AF:7E:CF - * (Play Console → App integrity → App signing). Keep in sync with - * website/public/.well-known/assetlinks.json. - */ -export const OFFICIAL_ANDROID_PASSKEY_ORIGINS: readonly string[] = [ +/** Bounded, expiring state. A code is consumed only after PKCE is checked. */ +class OneTimeStore { + private readonly entries = new Map() + constructor(private readonly now: () => number = Date.now) {} + put(key: string, entry: T): void { + for (const [id, value] of this.entries) if (value.expiresAt <= this.now()) this.entries.delete(id) + while (this.entries.size >= 256) this.entries.delete(this.entries.keys().next().value!) + this.entries.set(key, entry) + } + get(key: string): T | null { + const entry = this.entries.get(key) + if (!entry || entry.expiresAt <= this.now()) { + this.entries.delete(key) + return null + } + return entry + } + take(key: string): T | null { + const entry = this.get(key) + this.entries.delete(key) + return entry + } +} + +export class PasskeyChallengeStore extends OneTimeStore { + readonly codes: OneTimeStore + constructor(now: () => number = Date.now) { + super(now) + this.codes = new OneTimeStore(now) + } +} + +export type NativePasskeyConfig = { rpId: string; origins: string[] } +export const OFFICIAL_ANDROID_PASSKEY_ORIGINS = [ 'android:apk-key-hash:gPW441aKA2v53lho7kg86hFe1WjiLKXKUy4Iz3Kvfs8' ] -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:...`. - */ +/** Forks must change the shared RP and app associations together. Extra origins + * are only for explicitly trusted Android signing certificates (e.g. debug). */ 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 - * replayed assertion fails even if it is otherwise valid. - */ -export class PasskeyChallengeStore { - private readonly entries = new Map() - - constructor(private readonly now: () => number = Date.now) {} - - /** - * Bounded: when full, the oldest pending challenge is evicted rather than - * rejecting new ones, so unauthenticated option requests cannot lock - * legitimate users out for the whole TTL. - */ - put(challenge: string, entry: ChallengeEntry): void { - this.prune() - while (this.entries.size >= MAX_PENDING_CHALLENGES) { - const oldest = this.entries.keys().next().value - if (oldest === undefined) break - this.entries.delete(oldest) - } - this.entries.set(challenge, entry) - } - - take(challenge: string): ChallengeEntry | null { - const entry = this.entries.get(challenge) - if (!entry) return null - this.entries.delete(challenge) - return entry.expiresAt > this.now() ? entry : null - } - - private prune(): void { - const now = this.now() - for (const [key, entry] of this.entries) { - if (entry.expiresAt <= now) this.entries.delete(key) - } - } -} - -function isIpHostname(hostname: string): boolean { - return /^[\d.]+$/.test(hostname) || hostname.includes(':') || hostname.startsWith('[') -} - -/** - * Resolve the WebAuthn relying party from the browser's Origin header. - * - * The origin must be trusted (same host as the request, i.e. the hub-served - * web app, or an explicitly configured CORS origin) and a secure context with - * a domain name: WebAuthn rejects IP-address RP IDs and plain HTTP except on - * `localhost`. - */ -export function resolveRelyingParty( - originHeader: string | undefined, - hostHeader: string | undefined, - corsOrigins: string[] -): { origins: string[]; rpId: string } | { error: string } { - if (!originHeader) { - return { error: 'Missing Origin header' } - } - let url: URL - try { - url = new URL(originHeader) - } catch { - return { error: 'Invalid Origin header' } - } - const origin = url.origin - const hostname = url.hostname.toLowerCase() - const isLocalhost = hostname === 'localhost' || hostname.endsWith('.localhost') - if (url.protocol !== 'https:' && !(url.protocol === 'http:' && isLocalhost)) { - return { error: 'Passkeys require HTTPS (or localhost)' } - } - if (isIpHostname(hostname)) { - return { error: 'Passkeys require a domain name, not an IP address' } - } - - const sameHost = hostHeader !== undefined && url.host.toLowerCase() === hostHeader.toLowerCase() - const listed = corsOrigins.some((allowed) => allowed !== '*' && allowed === origin) - if (!sameHost && !listed) { - return { error: 'Origin is not allowed to use passkeys' } - } - return { origins: [origin], rpId: hostname } -} - -/** 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 { - return cliTokenFingerprint(jwtSecret, getConfiguration().cliApiToken) -} - -function challengeOf(clientDataJSON: string): string | null { - try { - return decodeClientDataJSON(clientDataJSON).challenge - } catch { - return null + const extra = (env.HAPI_PASSKEY_NATIVE_ORIGINS ?? '').split(',').map((v) => v.trim()).filter(Boolean) + if (extra.some((origin) => !/^android:apk-key-hash:[A-Za-z0-9_-]+$/.test(origin))) { + throw new Error('HAPI_PASSKEY_NATIVE_ORIGINS only accepts Android signing-certificate origins') } + return { rpId: PASSKEY_RP_ID, origins: [...new Set([PASSKEY_ORIGIN, ...OFFICIAL_ANDROID_PASSKEY_ORIGINS, ...extra])] } } export type PasskeyRouteDeps = { jwtSecret: Uint8Array store: Store corsOrigins: () => string[] + hubUrl: () => string challenges: PasskeyChallengeStore native: NativePasskeyConfig } -/** Unauthenticated: exchange a passkey assertion for a web JWT + passkey session. */ -export function createPasskeyLoginRoutes(deps: PasskeyRouteDeps): Hono { +function fingerprint(deps: PasskeyRouteDeps): string { + return cliTokenFingerprint(deps.jwtSecret, getConfiguration().cliApiToken) +} + +function hubOrigin(deps: PasskeyRouteDeps): string { + try { return canonicalPasskeyHub(deps.hubUrl()) } catch { + throw new Error('Configure HAPI_PUBLIC_URL as the canonical HTTPS Hub origin to use passkeys') + } +} + +async function optionsFor( + deps: PasskeyRouteDeps, kind: PasskeyOperation, channel: PasskeyChannel, + namespace?: string, browser?: BrowserBinding +) { + const hub = hubOrigin(deps) + const entry: ChallengeEntry = { + kind, channel, hub, namespace, browser, fingerprint: fingerprint(deps), rpId: PASSKEY_RP_ID, + origins: channel === 'browser' ? [PASSKEY_ORIGIN] : deps.native.origins, + expiresAt: Date.now() + CHALLENGE_TTL_MS + } + const challenge = encodePasskeyChallenge({ v: 1, hub, operation: kind, channel, id: random(), nonce: random() }) + if (kind === 'login') { + const allowCredentials = deps.store.passkeys.listByRpId(PASSKEY_RP_ID) + .filter((p) => constantTimeEquals(p.tokenFingerprint, entry.fingerprint)) + .map((p) => ({ id: p.id, transports: p.transports })) + if (allowCredentials.length === 0) throw new Error('no_passkeys') + const options = await generateAuthenticationOptions({ rpID: PASSKEY_RP_ID, challenge: Buffer.from(challenge, 'base64url'), allowCredentials, userVerification: 'required' }) + deps.challenges.put(challenge, entry) + return options + } + const ns = namespace! + const existing = deps.store.passkeys.listByNamespace(ns).filter((p) => p.rpId === PASSKEY_RP_ID) + const account = ns === 'default' ? 'hapi' : `hapi:${ns}` + const options = await generateRegistrationOptions({ + rpName: 'HAPI', rpID: PASSKEY_RP_ID, challenge: Buffer.from(challenge, 'base64url'), + userID: passkeyUserHandle(deps.jwtSecret, ns, hub), + userName: `${account}@${new URL(hub).host}`, + userDisplayName: `HAPI · ${new URL(hub).host}${ns === 'default' ? '' : ` (${ns})`}`, + attestationType: 'none', + excludeCredentials: existing.map((p) => ({ id: p.id, transports: p.transports })), + authenticatorSelection: { residentKey: 'required', userVerification: 'required' } + }) + deps.challenges.put(challenge, entry) + return options +} + +function entryFor(deps: PasskeyRouteDeps, clientData: string, channel: PasskeyChannel, kind?: PasskeyOperation) { + const challenge = decodeClientDataJSON(clientData).challenge + const entry = deps.challenges.take(challenge) + if (!entry || entry.channel !== channel || (kind && entry.kind !== kind)) throw new Error('Passkey challenge expired') + assertCurrent(deps, entry) + return { entry, challenge } +} + +function assertCurrent(deps: PasskeyRouteDeps, entry: { fingerprint: string; expiresAt: number }) { + if (entry.expiresAt <= Date.now()) throw new Error('Passkey challenge expired') + if (!constantTimeEquals(entry.fingerprint, fingerprint(deps))) throw new Error('passkey_revoked') +} + +async function authenticate(deps: PasskeyRouteDeps, entry: ChallengeEntry, challenge: string, response: AuthenticationResponseJSON) { + const credential = deps.store.passkeys.get(response.id) + if (!credential || credential.rpId !== entry.rpId) throw new Error('Unknown passkey') + if (!constantTimeEquals(credential.tokenFingerprint, entry.fingerprint)) throw new Error('passkey_revoked') + const result = await verifyAuthenticationResponse({ + response, expectedChallenge: challenge, expectedOrigin: entry.origins, expectedRPID: entry.rpId, + credential: { id: credential.id, publicKey: credential.publicKey, counter: credential.counter, transports: credential.transports }, + requireUserVerification: true + }) + if (!result.verified) throw new Error('Passkey verification failed') + assertCurrent(deps, entry) + // Deletion while an asynchronous verification is in flight must not revive it. + const current = deps.store.passkeys.get(credential.id) + if (!current) throw new Error('Unknown passkey') + if (result.authenticationInfo.newCounter !== 0 && current.counter >= result.authenticationInfo.newCounter) { + throw new Error('Passkey verification failed') + } + deps.store.passkeys.recordUse(credential.id, result.authenticationInfo.newCounter, Date.now()) + return { credentialId: credential.id, namespace: credential.namespace } +} + +async function register(deps: PasskeyRouteDeps, entry: ChallengeEntry, challenge: string, response: RegistrationResponseJSON, name?: string) { + const result = await verifyRegistrationResponse({ + response, expectedChallenge: challenge, expectedOrigin: entry.origins, expectedRPID: entry.rpId, requireUserVerification: true + }) + if (!result.verified) throw new Error('Passkey verification failed') + assertCurrent(deps, entry) + const credential = result.registrationInfo.credential + if (deps.store.passkeys.get(credential.id)) throw new Error('Passkey already registered') + deps.store.passkeys.add({ + id: credential.id, publicKey: credential.publicKey, counter: credential.counter, transports: credential.transports ?? [], + namespace: entry.namespace!, rpId: entry.rpId, tokenFingerprint: entry.fingerprint, + name: name || null, createdAt: Date.now() + }) + return { credentialId: credential.id, namespace: entry.namespace! } +} + +async function session(deps: PasskeyRouteDeps, id: string, namespace: string) { + const userId = await getOrCreateOwnerId() + return { + token: await signWebJwt(deps.jwtSecret, userId, namespace), + passkeySession: await signPasskeySession(deps.jwtSecret, id, namespace), + user: { id: userId, firstName: 'Web User' } + } +} + +function message(error: unknown): string { + const text = error instanceof Error ? error.message : '' + return ['cancelled', 'no_passkeys', 'passkey_revoked', 'Unknown passkey', 'Passkey challenge expired', 'Passkey already registered'].includes(text) + || text.startsWith('Configure HAPI_PUBLIC_URL') ? text : 'Passkey verification failed' +} + +const limitedRequests = new WeakSet() + +function secureRoutes() { const app = new Hono() - const { jwtSecret, store, challenges } = deps - - app.post('/passkey/login/options', async (c) => { - 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, - origins: rp.origins, - expiresAt: Date.now() + CHALLENGE_TTL_MS - }) - return c.json(options) - }) - - app.post('/passkey/login/verify', async (c) => { - const parsed = PasskeyLoginVerifyRequestSchema.safeParse(await c.req.json().catch(() => null)) - if (!parsed.success) { - return c.json({ error: 'Invalid body' }, 400) - } - const response = parsed.data.response as unknown as AuthenticationResponseJSON - const challenge = challengeOf(response.response.clientDataJSON) - const entry = challenge ? challenges.take(challenge) : null - if (!challenge || !entry || entry.kind !== 'login') { - return c.json({ error: 'Passkey challenge expired' }, 401) - } - - const credential = store.passkeys.get(response.id) - if (!credential || credential.rpId !== entry.rpId) { - return c.json({ error: 'Unknown passkey' }, 401) - } - if (!constantTimeEquals(credential.tokenFingerprint, currentFingerprint(jwtSecret))) { - return c.json({ error: 'passkey_revoked' }, 401) - } - - let newCounter: number - try { - const verification = await verifyAuthenticationResponse({ - response, - expectedChallenge: challenge, - expectedOrigin: entry.origins, - expectedRPID: entry.rpId, - credential: { - id: credential.id, - publicKey: credential.publicKey, - counter: credential.counter, - transports: credential.transports - }, - requireUserVerification: true - }) - if (!verification.verified) { - return c.json({ error: 'Passkey verification failed' }, 401) + app.use('/passkey/*', async (c, next) => { + c.header('Cache-Control', 'no-store') + c.header('Referrer-Policy', 'no-referrer') + c.header('X-Content-Type-Options', 'nosniff') + // Route groups share middleware paths. Cache a bounded body once, + // before route-level parse error handling, including chunked requests. + if (c.req.raw.body && !limitedRequests.has(c.req)) { + const reader = c.req.raw.body.getReader() + const chunks: Uint8Array[] = [] + let size = 0 + for (;;) { + const { value, done } = await reader.read() + if (done) break + size += value.byteLength + if (size > 128 * 1024) { + await reader.cancel() + return c.json({ error: 'Payload too large' }, 413) + } + chunks.push(value) } - newCounter = verification.authenticationInfo.newCounter - } catch { - return c.json({ error: 'Passkey verification failed' }, 401) + const bytes = new Uint8Array(size) + let offset = 0 + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength } + c.req.raw = new Request(c.req.raw, { body: bytes }) + limitedRequests.add(c.req) } - - store.passkeys.recordUse(credential.id, newCounter, Date.now()) - const userId = await getOrCreateOwnerId() - return c.json({ - token: await signWebJwt(jwtSecret, userId, credential.namespace), - passkeySession: await signPasskeySession(jwtSecret, credential.id, credential.namespace), - user: { id: userId, firstName: 'Web User' } - }) + return next() }) - return app } -/** Authenticated: register, list, and delete passkeys for the caller's namespace. */ -export function createPasskeyManagementRoutes(deps: PasskeyRouteDeps): Hono { - const app = new Hono() - const { jwtSecret, store, challenges } = deps - - app.post('/passkey/register/options', async (c) => { - const rp = await relyingPartyFor(c, deps) - if ('error' in rp) { - return c.json({ error: rp.error }, 400) +async function browserStart(c: Context, deps: PasskeyRouteDeps, operation: PasskeyOperation) { + const parsed = PasskeyBrowserStartRequestSchema.safeParse(await c.req.json().catch(() => null)) + if (!parsed.success) return c.json({ error: 'Invalid body' }, 400) + const b = parsed.data + try { + const origin = canonicalPasskeyHub(b.callbackOrigin) + if (origin !== b.callbackOrigin || c.req.header('origin') !== origin + || (origin !== hubOrigin(deps) && !deps.corsOrigins().some((o) => o !== '*' && o === origin))) { + return c.json({ error: 'Passkey callback origin is not allowed' }, 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: 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: { - residentKey: 'required', - userVerification: 'required' - } - }) - challenges.put(options.challenge, { - kind: 'register', - rpId: rp.rpId, - origins: rp.origins, - namespace, - expiresAt: Date.now() + CHALLENGE_TTL_MS - }) - return c.json(options) - }) + const options = await optionsFor(deps, operation, 'browser', operation === 'register' ? c.get('namespace') : undefined, b) + const request = JSON.stringify({ hub: hubOrigin(deps), operation, options }) + if (request.length > PASSKEY_MAX_REQUEST_LENGTH) return c.json({ error: 'Too many passkeys for browser sign-in' }, 400) + return c.json({ url: `${PASSKEY_ORIGIN}/#${encodeURIComponent(request)}` }) + } catch (error) { return c.json({ error: message(error) }, message(error) === 'no_passkeys' ? 404 : 400) } +} +export function createPasskeyLoginRoutes(deps: PasskeyRouteDeps): Hono { + const app = secureRoutes() + app.post('/passkey/login/options', async (c) => { + if (!PasskeyOptionsRequestSchema.safeParse(await c.req.json().catch(() => null)).success) return c.json({ error: 'Native client required' }, 400) + try { return c.json(await optionsFor(deps, 'login', 'native')) } + catch (error) { return c.json({ error: message(error) }, message(error) === 'no_passkeys' ? 404 : 400) } + }) + app.post('/passkey/login/verify', async (c) => { + const parsed = PasskeyLoginVerifyRequestSchema.safeParse(await c.req.json().catch(() => null)) + if (!parsed.success) return c.json({ error: 'Invalid body' }, 400) + try { + const response = parsed.data.response as unknown as AuthenticationResponseJSON + const { entry, challenge } = entryFor(deps, response.response.clientDataJSON, 'native', 'login') + const result = await authenticate(deps, entry, challenge, response) + return c.json(await session(deps, result.credentialId, result.namespace)) + } catch (error) { return c.json({ error: message(error) }, 401) } + }) + app.post('/passkey/browser/login/start', (c) => browserStart(c, deps, 'login')) + app.post('/passkey/browser/complete', async (c) => { + if (c.req.header('origin') !== PASSKEY_ORIGIN || !c.req.header('content-type')?.startsWith('application/x-www-form-urlencoded')) { + return c.json({ error: 'Invalid ceremony origin or content type' }, 400) + } + // A native challenge can never be exchanged through the browser bridge. + let entry: ChallengeEntry + let challenge: string + try { + const form = Object.fromEntries(new URLSearchParams(await c.req.text())) + if (typeof form.challenge !== 'string') throw new Error('Invalid body') + challenge = form.challenge + const found = deps.challenges.take(challenge) + if (!found || found.channel !== 'browser' || !found.browser) throw new Error('Passkey challenge expired') + entry = found + } catch (error) { return c.json({ error: message(error) }, 401) } + const callback = new URL(PASSKEY_CALLBACK_PATH, entry.browser!.callbackOrigin) + const fragment = new URLSearchParams({ state: entry.browser!.state }) + try { + assertCurrent(deps, entry) + const form = Object.fromEntries(new URLSearchParams(await c.req.text())) + if (form.error === 'cancelled') throw new Error('cancelled') + const parsed = PasskeyLoginVerifyRequestSchema.safeParse({ response: typeof form.response === 'string' ? JSON.parse(form.response) : null }) + if (!parsed.success) throw new Error('Invalid body') + if (decodeClientDataJSON(parsed.data.response.response.clientDataJSON).challenge !== challenge) throw new Error('Invalid challenge') + const result = entry.kind === 'login' + ? await authenticate(deps, entry, challenge, parsed.data.response as unknown as AuthenticationResponseJSON) + : await register(deps, entry, challenge, parsed.data.response as unknown as RegistrationResponseJSON, entry.browser!.name) + const code = random() + deps.challenges.codes.put(code, { + ...result, operation: entry.kind, fingerprint: entry.fingerprint, + codeChallenge: entry.browser!.codeChallenge, expiresAt: Date.now() + CODE_TTL_MS + }) + fragment.set('code', code) + } catch (error) { fragment.set('error', message(error)) } + callback.hash = fragment.toString() + return c.redirect(callback.href, 303) + }) + app.post('/passkey/browser/exchange', async (c) => { + const parsed = PasskeyBrowserExchangeRequestSchema.safeParse(await c.req.json().catch(() => null)) + if (!parsed.success) return c.json({ error: 'Invalid body' }, 400) + const { code, verifier } = parsed.data + const entry = deps.challenges.codes.get(code) + if (!entry || !constantTimeEquals(sha256(verifier), entry.codeChallenge)) return c.json({ error: 'Invalid authorization code' }, 401) + deps.challenges.codes.take(code) + const credential = deps.store.passkeys.get(entry.credentialId) + if (!credential || credential.namespace !== entry.namespace || !constantTimeEquals(credential.tokenFingerprint, fingerprint(deps)) + || !constantTimeEquals(entry.fingerprint, fingerprint(deps))) return c.json({ error: 'passkey_revoked' }, 401) + if (entry.operation === 'register') return c.json({ operation: 'register' as const }) + return c.json({ operation: 'login' as const, ...await session(deps, entry.credentialId, entry.namespace) }) + }) + return app +} + +export function createPasskeyManagementRoutes(deps: PasskeyRouteDeps): Hono { + const app = secureRoutes() + app.post('/passkey/browser/register/start', (c) => browserStart(c, deps, 'register')) + app.post('/passkey/register/options', async (c) => { + if (!PasskeyOptionsRequestSchema.safeParse(await c.req.json().catch(() => null)).success) return c.json({ error: 'Native client required' }, 400) + try { return c.json(await optionsFor(deps, 'register', 'native', c.get('namespace'))) } + catch (error) { return c.json({ error: message(error) }, 400) } + }) app.post('/passkey/register/verify', async (c) => { const parsed = PasskeyRegisterVerifyRequestSchema.safeParse(await c.req.json().catch(() => null)) - if (!parsed.success) { - return c.json({ error: 'Invalid body' }, 400) - } - const namespace = c.get('namespace') - const response = parsed.data.response as unknown as RegistrationResponseJSON - const challenge = challengeOf(response.response.clientDataJSON) - const entry = challenge ? challenges.take(challenge) : null - if (!challenge || !entry || entry.kind !== 'register' || entry.namespace !== namespace) { - return c.json({ error: 'Passkey challenge expired' }, 400) - } - - let registered: { id: string; publicKey: Uint8Array; counter: number; transports: string[] } + if (!parsed.success) return c.json({ error: 'Invalid body' }, 400) try { - const verification = await verifyRegistrationResponse({ - response, - expectedChallenge: challenge, - expectedOrigin: entry.origins, - expectedRPID: entry.rpId, - requireUserVerification: true - }) - if (!verification.verified) { - return c.json({ error: 'Passkey verification failed' }, 400) - } - const credential = verification.registrationInfo.credential - registered = { - id: credential.id, - publicKey: credential.publicKey, - counter: credential.counter, - transports: credential.transports ?? [] - } - } catch { - return c.json({ error: 'Passkey verification failed' }, 400) - } - - if (store.passkeys.get(registered.id)) { - return c.json({ error: 'Passkey already registered' }, 409) - } - store.passkeys.add({ - ...registered, - namespace, - rpId: entry.rpId, - tokenFingerprint: currentFingerprint(jwtSecret), - name: parsed.data.name || null, - createdAt: Date.now() - }) - return c.json({ ok: true, id: registered.id }) + const response = parsed.data.response as unknown as RegistrationResponseJSON + const { entry, challenge } = entryFor(deps, response.response.clientDataJSON, 'native', 'register') + if (entry.namespace !== c.get('namespace')) throw new Error('Invalid namespace') + const result = await register(deps, entry, challenge, response, parsed.data.name) + return c.json({ ok: true, id: result.credentialId }) + } catch (error) { return c.json({ error: message(error) }, message(error) === 'Passkey already registered' ? 409 : 400) } }) - app.get('/passkeys', (c) => { - const fingerprint = currentFingerprint(jwtSecret) const body: PasskeyListResponse = { - passkeys: store.passkeys.listByNamespace(c.get('namespace')).map((p) => ({ - id: p.id, - name: p.name, - rpId: p.rpId, - createdAt: p.createdAt, - lastUsedAt: p.lastUsedAt, - valid: constantTimeEquals(p.tokenFingerprint, fingerprint) + passkeys: deps.store.passkeys.listByNamespace(c.get('namespace')).map((p) => ({ + id: p.id, name: p.name, rpId: p.rpId, createdAt: p.createdAt, lastUsedAt: p.lastUsedAt, + valid: p.rpId === PASSKEY_RP_ID && constantTimeEquals(p.tokenFingerprint, fingerprint(deps)) })) } return c.json(body) }) - app.delete('/passkeys/:id', (c) => { - const removed = store.passkeys.remove(c.req.param('id'), c.get('namespace')) - if (!removed) { - return c.json({ error: 'Passkey not found' }, 404) - } + if (!deps.store.passkeys.remove(c.req.param('id'), c.get('namespace'))) return c.json({ error: 'Passkey not found' }, 404) return c.json({ ok: true }) }) - return app } diff --git a/hub/src/web/server.ts b/hub/src/web/server.ts index 3583a40a..65401f20 100644 --- a/hub/src/web/server.ts +++ b/hub/src/web/server.ts @@ -295,6 +295,7 @@ function createWebApp(options: { jwtSecret: options.jwtSecret, store: options.store, corsOrigins: () => corsOrigins, + hubUrl: () => configuration.publicUrl, challenges: new PasskeyChallengeStore(), native: nativePasskeyConfigFromEnv() } diff --git a/hub/src/web/testHelpers/passkeyAuthenticator.ts b/hub/src/web/testHelpers/passkeyAuthenticator.ts new file mode 100644 index 00000000..7fa83bce --- /dev/null +++ b/hub/src/web/testHelpers/passkeyAuthenticator.ts @@ -0,0 +1,84 @@ +import { createHash, generateKeyPairSync, randomBytes, sign, type KeyObject } from 'node:crypto' +await import('reflect-metadata') +const { isoCBOR } = await import('@simplewebauthn/server/helpers') +const b64url = (bytes: Uint8Array | Buffer) => Buffer.from(bytes).toString('base64url') +const sha256 = (data: Uint8Array | string) => createHash('sha256').update(data).digest() + +/** Minimal software authenticator: ES256, `none` attestation, UP+UV set. */ +export class SoftAuthenticator { + readonly credentialId = randomBytes(16) + private readonly privateKey: KeyObject + private readonly publicJwk: { x: string; y: string } + private counter = 0 + userHandle: string | null = null + + constructor(private readonly rpId: string, public origin: string) { + const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' }) + this.privateKey = privateKey + this.publicJwk = publicKey.export({ format: 'jwk' }) as { x: string; y: string } + } + + virtualCredential() { + return { + credentialId: this.credentialId.toString('base64'), rpId: this.rpId, + privateKey: this.privateKey.export({ format: 'der', type: 'pkcs8' }).toString('base64'), + userHandle: this.userHandle ? Buffer.from(this.userHandle, 'base64url').toString('base64') : undefined, + signCount: this.counter, isResidentCredential: true + } + } + + private clientData(type: string, challenge: string): Buffer { + return Buffer.from(JSON.stringify({ type, challenge, origin: this.origin, crossOrigin: false })) + } + + create(options: { challenge: string; user: { id: string } }) { + this.userHandle = options.user.id + const cose = new Map([ + [1, 2], [3, -7], [-1, 1], + [-2, new Uint8Array(Buffer.from(this.publicJwk.x, 'base64url'))], + [-3, new Uint8Array(Buffer.from(this.publicJwk.y, 'base64url'))] + ]) + const idLength = Buffer.alloc(2) + idLength.writeUInt16BE(this.credentialId.length) + const authData = Buffer.concat([ + sha256(this.rpId), Buffer.from([0x45]), Buffer.alloc(4), Buffer.alloc(16), + idLength, this.credentialId, Buffer.from(isoCBOR.encode(cose)) + ]) + const attestationObject = isoCBOR.encode(new Map([ + ['fmt', 'none'], ['attStmt', new Map()], ['authData', new Uint8Array(authData)] + ]) as never) + return { + id: b64url(this.credentialId), + rawId: b64url(this.credentialId), + type: 'public-key', + response: { + clientDataJSON: b64url(this.clientData('webauthn.create', options.challenge)), + attestationObject: b64url(attestationObject), + transports: ['internal'] + }, + clientExtensionResults: {}, + authenticatorAttachment: null + } + } + + get(options: { challenge: string }) { + this.counter += 1 + const counter = Buffer.alloc(4) + counter.writeUInt32BE(this.counter) + const authData = Buffer.concat([sha256(this.rpId), Buffer.from([0x05]), counter]) + const clientData = this.clientData('webauthn.get', options.challenge) + const signature = sign('sha256', Buffer.concat([authData, sha256(clientData)]), this.privateKey) + return { + id: b64url(this.credentialId), + rawId: b64url(this.credentialId), + type: 'public-key', + response: { + clientDataJSON: b64url(clientData), + authenticatorData: b64url(authData), + signature: b64url(signature), + userHandle: this.userHandle ?? undefined + }, + clientExtensionResults: {} + } + } +} diff --git a/ios/Hapi/Features/Passkeys/PlatformPasskeyAuthenticator.swift b/ios/Hapi/Features/Passkeys/PlatformPasskeyAuthenticator.swift index 7bb07b07..33841624 100644 --- a/ios/Hapi/Features/Passkeys/PlatformPasskeyAuthenticator.swift +++ b/ios/Hapi/Features/Passkeys/PlatformPasskeyAuthenticator.swift @@ -4,10 +4,10 @@ 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 +/// Native passkeys live on the shared RP ID `auth.hapi.run` +/// (`webcredentials:auth.hapi.run` in the Associated Domains entitlement, backed by +/// `https://auth.hapi.run/.well-known/apple-app-site-association`); the system +/// reports the origin `https://auth.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. @@ -28,7 +28,7 @@ struct PlatformPasskeyAuthenticator: PasskeyAuthenticating { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) } } - return registration + return [registration] } guard let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration else { @@ -56,19 +56,34 @@ struct PlatformPasskeyAuthenticator: PasskeyAuthenticating { assertion.allowedCredentials = request.allowedCredentialIDs.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) } - return assertion + // Web-created resident credentials may live on a roaming security + // key rather than iCloud. Offer both providers for the same Hub. + let securityKey = ASAuthorizationSecurityKeyPublicKeyCredentialProvider( + relyingPartyIdentifier: request.relyingPartyID + ).createCredentialAssertionRequest(challenge: request.challenge) + securityKey.userVerificationPreference = .required + securityKey.allowedCredentials = request.allowedCredentialIDs.map { + ASAuthorizationSecurityKeyPublicKeyCredentialDescriptor( + credentialID: $0, transports: [.usb, .nfc, .bluetooth] + ) + } + return [assertion, securityKey] } - guard let credential = authorization.credential - as? ASAuthorizationPlatformPublicKeyCredentialAssertion else { - throw PasskeyError.platform("Unexpected credential type") + if let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion { + return PasskeyAssertionResult( + credentialID: credential.credentialID, clientDataJSON: credential.rawClientDataJSON, + authenticatorData: credential.rawAuthenticatorData, signature: credential.signature, + userID: credential.userID + ) } - return PasskeyAssertionResult( - credentialID: credential.credentialID, - clientDataJSON: credential.rawClientDataJSON, - authenticatorData: credential.rawAuthenticatorData, - signature: credential.signature, - userID: credential.userID - ) + if let credential = authorization.credential as? ASAuthorizationSecurityKeyPublicKeyCredentialAssertion { + return PasskeyAssertionResult( + credentialID: credential.credentialID, clientDataJSON: credential.rawClientDataJSON, + authenticatorData: credential.rawAuthenticatorData, signature: credential.signature, + userID: credential.userID, authenticatorAttachment: "cross-platform" + ) + } + throw PasskeyError.platform("Unexpected credential type") } } @@ -85,7 +100,7 @@ private final class PasskeyCeremony: NSObject, private var controller: ASAuthorizationController? static func perform( - _ makeRequest: @MainActor () -> ASAuthorizationRequest + _ makeRequest: @MainActor () -> [ASAuthorizationRequest] ) async throws -> ASAuthorization { let ceremony = PasskeyCeremony() let request = makeRequest() @@ -94,9 +109,9 @@ private final class PasskeyCeremony: NSObject, } } - private func start(_ request: ASAuthorizationRequest, continuation: CheckedContinuation) { + private func start(_ request: [ASAuthorizationRequest], continuation: CheckedContinuation) { self.continuation = continuation - let controller = ASAuthorizationController(authorizationRequests: [request]) + let controller = ASAuthorizationController(authorizationRequests: request) controller.delegate = self controller.presentationContextProvider = self self.controller = controller diff --git a/ios/Hapi/Features/Settings/PasskeysView.swift b/ios/Hapi/Features/Settings/PasskeysView.swift index ab8f6b58..0c5b9013 100644 --- a/ios/Hapi/Features/Settings/PasskeysView.swift +++ b/ios/Hapi/Features/Settings/PasskeysView.swift @@ -3,8 +3,7 @@ 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. +/// the shared Web/App RP `auth.hapi.run`, or delete a credential. @MainActor @Observable final class PasskeysModel { enum LoadState: Equatable { @@ -88,7 +87,7 @@ final class PasskeysModel { 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."), + format: String(localized: "The hub requested a passkey for “%@”, but this app only supports auth.hapi.run. Update the hub."), rpId ) case PasskeyError.platform(let detail): @@ -222,7 +221,7 @@ struct PasskeysView: View { } } } 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.") + Text("Sign in to \(HubDisplay.host(hubUrl)) from another device with “Sign in with a Passkey” — only the hub URL is needed. Passkeys work in both the web app and this app.") } Section { @@ -266,25 +265,17 @@ private struct PasskeyRow: View { var body: some View { HStack(alignment: .top, spacing: 12) { - Image(systemName: passkey.isNative ? "person.badge.key" : "globe") + Image(systemName: "person.badge.key") .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) diff --git a/ios/Hapi/Hapi-macOS.entitlements b/ios/Hapi/Hapi-macOS.entitlements index 415faa06..293bc65e 100644 --- a/ios/Hapi/Hapi-macOS.entitlements +++ b/ios/Hapi/Hapi-macOS.entitlements @@ -6,7 +6,7 @@ development com.apple.developer.associated-domains - webcredentials:hapi.run + webcredentials:auth.hapi.run com.apple.security.app-sandbox diff --git a/ios/Hapi/Hapi.entitlements b/ios/Hapi/Hapi.entitlements index 53f5cd0a..f9710074 100644 --- a/ios/Hapi/Hapi.entitlements +++ b/ios/Hapi/Hapi.entitlements @@ -6,7 +6,7 @@ development com.apple.developer.associated-domains - webcredentials:hapi.run + webcredentials:auth.hapi.run keychain-access-groups diff --git a/ios/Hapi/Resources/Localizable.xcstrings b/ios/Hapi/Resources/Localizable.xcstrings index 0b271d03..c4be1ac6 100644 --- a/ios/Hapi/Resources/Localizable.xcstrings +++ b/ios/Hapi/Resources/Localizable.xcstrings @@ -392,19 +392,19 @@ } } }, - "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." : { + "Sign in to %@ from another device with “Sign in with a Passkey” — only the hub URL is needed. Passkeys work in both the web app and this app." : { "extractionState" : "manual", "localizations" : { "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Войдите в %@ с другого устройства через «Войти с ключом доступа» — нужен только URL хаба. Ключи с пометкой «Веб» относятся к браузеру и показаны здесь только для управления." + "value" : "Войдите в %@ с другого устройства через «Войти с ключом доступа» — нужен только URL хаба. Ключи работают и в браузере, и в этом приложении." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "在其他设备上通过“使用通行密钥登录”登录 %@,只需 Hub 地址。标记为“网页”的通行密钥属于浏览器,此处仅供管理。" + "value" : "在其他设备上通过“使用通行密钥登录”登录 %@,只需 Hub 地址。通行密钥可同时用于网页版和本应用。" } } } @@ -494,19 +494,19 @@ } } }, - "The hub requested a passkey for “%@”, but this app only supports hapi.run. Update the hub." : { + "The hub requested a passkey for “%@”, but this app only supports auth.hapi.run. Update the hub." : { "extractionState" : "manual", "localizations" : { "ru" : { "stringUnit" : { "state" : "translated", - "value" : "Хаб запросил ключ доступа для «%@», но приложение поддерживает только hapi.run. Обновите хаб." + "value" : "Хаб запросил ключ доступа для «%@», но приложение поддерживает только auth.hapi.run. Обновите хаб." } }, "zh-Hans" : { "stringUnit" : { "state" : "translated", - "value" : "Hub 请求的是“%@”的通行密钥,但本应用仅支持 hapi.run。请更新 Hub。" + "value" : "Hub 请求的是“%@”的通行密钥,但本应用仅支持 auth.hapi.run。请更新 Hub。" } } } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubPairingService.swift b/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubPairingService.swift index af874da7..7cc55df6 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubPairingService.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Auth/HubPairingService.swift @@ -138,7 +138,7 @@ public struct HubPairingService: Sendable { let request: PasskeyAssertionRequest do { - request = try PasskeyAssertionRequest(options: try await client.passkeyLoginOptions()) + request = try PasskeyAssertionRequest(options: try await client.passkeyLoginOptions(), hubURL: baseURL) } catch PasskeyError.noPasskeys { throw PairingFailure.noPasskeys } catch is PasskeyError { diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Auth/PasskeyHubBinding.swift b/ios/Packages/HapiKit/Sources/HapiClient/Auth/PasskeyHubBinding.swift new file mode 100644 index 00000000..2ee10744 --- /dev/null +++ b/ios/Packages/HapiKit/Sources/HapiClient/Auth/PasskeyHubBinding.swift @@ -0,0 +1,60 @@ +import Foundation +#if canImport(CryptoKit) +import CryptoKit +#endif + +/// Shared-RP isolation. Validate the connected Hub before opening any system UI. +enum PasskeyHubBinding { + struct Challenge: Decodable { + let v: Int + let hub: String + let id: String + let operation: String + let channel: String + let nonce: String + } + + static func origin(_ url: URL) throws -> String { + guard var c = URLComponents(url: url, resolvingAgainstBaseURL: false), + c.scheme?.lowercased() == "https", let host = c.host, !host.isEmpty, + c.user == nil, c.password == nil, c.query == nil, c.fragment == nil, + c.path.isEmpty || c.path == "/" else { throw PasskeyError.malformedOptions } + c.scheme = "https" + c.host = host.lowercased() + c.path = "" + if c.port == 443 { c.port = nil } + guard let value = c.url?.absoluteString else { throw PasskeyError.malformedOptions } + return value.hasSuffix("/") ? String(value.dropLast()) : value + } + + static func validate(_ challenge: Data, hub: URL, operation: String) throws { + guard challenge.count <= 3072, + let value = try? JSONDecoder().decode(Challenge.self, from: challenge), + value.v == 1, value.hub == (try origin(hub)), value.operation == operation, + value.channel == "native", validNonce(value.id), validNonce(value.nonce) else { + throw PasskeyError.malformedOptions + } + } + + private static func validNonce(_ value: String) -> Bool { + value.utf8.count == 43 && value.utf8.allSatisfy { + (65...90).contains($0) || (97...122).contains($0) || (48...57).contains($0) || $0 == 45 || $0 == 95 + } + } + + static func validateUser(_ user: Data, hub: URL) throws { + guard user.count == 64, user.prefix(32) == (try digest(Data(origin(hub).utf8))) else { + throw PasskeyError.malformedOptions + } + } + + static func digest(_ data: Data) -> Data { + #if canImport(CryptoKit) + return Data(SHA256.hash(data: data)) + #else + // Linux package tests have no CryptoKit. Fail closed rather than silently + // skip an account-binding check; native passkeys run on Apple platforms. + return Data() + #endif + } +} diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Auth/Passkeys.swift b/ios/Packages/HapiKit/Sources/HapiClient/Auth/Passkeys.swift index 9af85f0f..cb2e4f8e 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Auth/Passkeys.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Auth/Passkeys.swift @@ -8,8 +8,8 @@ import Foundation /// 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" + /// RP ID of every native passkey (`webcredentials:auth.hapi.run`). + public static let nativeRelyingPartyID = "auth.hapi.run" /// Transports reported for a platform (iCloud Keychain) credential. public static let registrationTransports = ["internal", "hybrid"] } @@ -124,6 +124,7 @@ public struct PasskeyRegistrationRequest: Equatable, Sendable { /// and decodes the base64url fields. public init( options: PasskeyRegistrationOptions, + hubURL: URL, expectedRelyingPartyID: String = NativePasskeys.nativeRelyingPartyID ) throws { guard let rpId = options.rp.id, rpId == expectedRelyingPartyID else { @@ -134,6 +135,10 @@ public struct PasskeyRegistrationRequest: Equatable, Sendable { !options.user.name.isEmpty else { throw PasskeyError.malformedOptions } + try PasskeyHubBinding.validate(challenge, hub: hubURL, operation: "register") + try PasskeyHubBinding.validateUser(userID, hub: hubURL) + let authority = try PasskeyHubBinding.origin(hubURL).dropFirst("https://".count) + guard options.user.name.hasSuffix("@\(authority)") 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 @@ -155,6 +160,7 @@ public struct PasskeyAssertionRequest: Equatable, Sendable { public init( options: PasskeyAssertionOptions, + hubURL: URL, expectedRelyingPartyID: String = NativePasskeys.nativeRelyingPartyID ) throws { guard let rpId = options.rpId, rpId == expectedRelyingPartyID else { @@ -163,12 +169,14 @@ public struct PasskeyAssertionRequest: Equatable, Sendable { guard let challenge = Base64URL.decode(options.challenge), !challenge.isEmpty else { throw PasskeyError.malformedOptions } + try PasskeyHubBinding.validate(challenge, hub: hubURL, operation: "login") 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 + guard !allowed.isEmpty else { throw PasskeyError.malformedOptions } self.allowedCredentialIDs = allowed } } @@ -195,13 +203,15 @@ public struct PasskeyAssertionResult: Equatable, Sendable { public let authenticatorData: Data public let signature: Data public let userID: Data? + public let authenticatorAttachment: String - public init(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userID: Data?) { + public init(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userID: Data?, authenticatorAttachment: String = "platform") { self.credentialID = credentialID self.clientDataJSON = clientDataJSON self.authenticatorData = authenticatorData self.signature = signature self.userID = userID + self.authenticatorAttachment = authenticatorAttachment } } @@ -262,7 +272,7 @@ public struct PasskeyAssertionResponseJSON: Encodable, Equatable, Sendable { signature: Base64URL.encode(result.signature), userHandle: result.userID.flatMap { $0.isEmpty ? nil : Base64URL.encode($0) } ) - self.authenticatorAttachment = "platform" + self.authenticatorAttachment = result.authenticatorAttachment self.clientExtensionResults = [:] } } @@ -296,9 +306,7 @@ public struct PasskeySummary: Codable, Equatable, Identifiable, Sendable { 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. + /// Registered for the supported shared Web/App RP ID. public var isNative: Bool { rpId == NativePasskeys.nativeRelyingPartyID } diff --git a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/PasskeyEndpoints.swift b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/PasskeyEndpoints.swift index 8947a270..3ef85205 100644 --- a/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/PasskeyEndpoints.swift +++ b/ios/Packages/HapiKit/Sources/HapiClient/Endpoints/PasskeyEndpoints.swift @@ -67,7 +67,7 @@ extension APIClient { /// ``APIError``. public func registerPasskey(name: String?, using authenticator: any PasskeyAuthenticating) async throws { let options = try await passkeyRegistrationOptions() - let request = try PasskeyRegistrationRequest(options: options) + let request = try PasskeyRegistrationRequest(options: options, hubURL: baseURL) let result = try await authenticator.register(request) try await verifyPasskeyRegistration(PasskeyRegistrationResponseJSON(result), name: name) } diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyAuthTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyAuthTests.swift index be82cc58..619c7678 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyAuthTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyAuthTests.swift @@ -136,8 +136,8 @@ struct PasskeyAuthTests { 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\"}]}" + private func loginOptionsJSON(rpId: String = "auth.hapi.run") -> String { + "{\"challenge\":\"\(Base64URL.encode(boundPasskeyChallenge()))\",\"rpId\":\"\(rpId)\",\"allowCredentials\":[{\"id\":\"aWQ\"}]}" } @Test func signInStoresPasskeySessionAndActivatesHub() async throws { diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyHubBindingTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyHubBindingTests.swift new file mode 100644 index 00000000..fe4a62b8 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyHubBindingTests.swift @@ -0,0 +1,40 @@ +import Foundation +@testable import HapiClient +import Testing + +@Suite("Passkey Hub isolation") +struct PasskeyHubBindingTests { + let hub = URL(string: "https://hub.test")! + + @Test func challengeCannotBeForwardedBetweenHubsOrChannels() throws { + try PasskeyHubBinding.validate(boundPasskeyChallenge(), hub: hub, operation: "login") + for data in [ + boundPasskeyChallenge(hub: "https://other.test"), + boundPasskeyChallenge(operation: "register"), + boundPasskeyChallenge(channel: "browser"), + Data("{}".utf8), Data("null".utf8) + ] { + #expect(throws: PasskeyError.malformedOptions) { + try PasskeyHubBinding.validate(data, hub: hub, operation: "login") + } + } + } + + @Test func originCanonicalizationIsStrict() throws { + #expect(try PasskeyHubBinding.origin(URL(string: "https://HUB.test:443/")!) == "https://hub.test") + for value in ["http://hub.test", "https://u:p@hub.test", "https://hub.test/path", "https://hub.test?q=1", "https://hub.test#fragment"] { + #expect(throws: PasskeyError.malformedOptions) { try PasskeyHubBinding.origin(URL(string: value)!) } + } + } + + @Test(.enabled(if: passkeyRegistrationAvailable)) func accountHandleCannotOverwriteAnotherHubsAccount() throws { + try PasskeyHubBinding.validateUser(boundPasskeyUser(), hub: hub) + #expect(throws: PasskeyError.malformedOptions) { + try PasskeyHubBinding.validateUser(boundPasskeyUser(), hub: URL(string: "https://other.test")!) + } + #expect(throws: PasskeyError.malformedOptions) { try PasskeyHubBinding.validateUser(Data(repeating: 0, count: 32), hub: hub) } + // Cross-language SHA-256 vector, also used by the Hub's account prefix. + #expect(PasskeyHubBinding.digest(Data("https://hub.test".utf8)).map { String(format: "%02x", $0) }.joined() + == "96c5db5fa93f9ae43b5a061e2e69edc818a05634fb139bbd45dd887da3bfd27f") + } +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyTestSupport.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyTestSupport.swift new file mode 100644 index 00000000..2e34e6c8 --- /dev/null +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeyTestSupport.swift @@ -0,0 +1,19 @@ +import Foundation +@testable import HapiClient + +#if canImport(CryptoKit) +let passkeyRegistrationAvailable = true +#else +let passkeyRegistrationAvailable = false +#endif + +func boundPasskeyChallenge(hub: String = testHubURLString, operation: String = "login", channel: String = "native") -> Data { + try! JSONSerialization.data(withJSONObject: [ + "v": 1, "hub": hub, "id": String(repeating: "a", count: 43), + "nonce": String(repeating: "b", count: 43), "operation": operation, "channel": channel + ], options: [.sortedKeys]) +} + +func boundPasskeyUser(hub: String = testHubURLString) -> Data { + PasskeyHubBinding.digest(Data(hub.utf8)) + Data(repeating: 1, count: 32) +} diff --git a/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeysTests.swift b/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeysTests.swift index 8ce09e99..eada9236 100644 --- a/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeysTests.swift +++ b/ios/Packages/HapiKit/Tests/HapiClientTests/PasskeysTests.swift @@ -9,15 +9,15 @@ import Testing @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)), + rpId: String = "auth.hapi.run", + userID: String = Base64URL.encode(boundPasskeyUser()), + challenge: String = Base64URL.encode(boundPasskeyChallenge(operation: "register")), 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"}, + "user":{"id":"\(userID)","name":"hapi@hub.test","displayName":"HAPI · hub.test"}, "pubKeyCredParams":[{"alg":-7,"type":"public-key"}], "excludeCredentials":[\(excluded.joined(separator: ","))], "authenticatorSelection":{"residentKey":"required","userVerification":"required"}, @@ -25,10 +25,10 @@ struct PasskeysTests { """ } - private func assertionOptionsJSON(rpId: String = "hapi.run", credentials: [String] = []) -> String { + private func assertionOptionsJSON(rpId: String = "auth.hapi.run", credentials: [String] = ["Y3JlZA"]) -> String { let allowed = credentials.map { "{\"id\":\"\($0)\",\"type\":\"public-key\",\"transports\":[\"internal\"]}" } return """ - {"challenge":"\(Base64URL.encode(Data("challenge-bytes".utf8)))","rpId":"\(rpId)", + {"challenge":"\(Base64URL.encode(boundPasskeyChallenge()))","rpId":"\(rpId)", "allowCredentials":[\(allowed.joined(separator: ","))],"userVerification":"required"} """ } @@ -49,16 +49,16 @@ struct PasskeysTests { // MARK: - Options decoding - @Test func registrationRequestDecodesBase64URLFields() throws { + @Test(.enabled(if: passkeyRegistrationAvailable)) 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") + let request = try PasskeyRegistrationRequest(options: options, hubURL: URL(string: testHubURLString)!) + #expect(request.relyingPartyID == "auth.hapi.run") + #expect(request.challenge == boundPasskeyChallenge(operation: "register")) + #expect(request.userID == boundPasskeyUser()) + #expect(request.userName == "hapi@hub.test") #expect(request.excludedCredentialIDs == [Data("cred1".utf8)]) } @@ -68,15 +68,15 @@ struct PasskeysTests { from: Data(registrationOptionsJSON(rpId: "hub.example.com").utf8) ) #expect(throws: PasskeyError.relyingPartyMismatch("hub.example.com")) { - _ = try PasskeyRegistrationRequest(options: options) + _ = try PasskeyRegistrationRequest(options: options, hubURL: URL(string: testHubURLString)!) } } @Test func registrationRejectsMissingRelyingParty() throws { - let json = registrationOptionsJSON(rpId: "hapi.run").replacingOccurrences(of: "\"id\":\"hapi.run\"", with: "\"id\":\"\"") + let json = registrationOptionsJSON(rpId: "auth.hapi.run").replacingOccurrences(of: "\"id\":\"auth.hapi.run\"", with: "\"id\":\"\"") let options = try HapiJSON.decoder.decode(PasskeyRegistrationOptions.self, from: Data(json.utf8)) #expect(throws: PasskeyError.relyingPartyMismatch("")) { - _ = try PasskeyRegistrationRequest(options: options) + _ = try PasskeyRegistrationRequest(options: options, hubURL: URL(string: testHubURLString)!) } } @@ -85,9 +85,9 @@ struct PasskeysTests { 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)) + let request = try PasskeyAssertionRequest(options: options, hubURL: URL(string: testHubURLString)!) + #expect(request.relyingPartyID == "auth.hapi.run") + #expect(request.challenge == boundPasskeyChallenge()) #expect(request.allowedCredentialIDs == [Data("cred1".utf8)]) } @@ -97,7 +97,7 @@ struct PasskeysTests { from: Data(assertionOptionsJSON(rpId: "evil.example").utf8) ) #expect(throws: PasskeyError.relyingPartyMismatch("evil.example")) { - _ = try PasskeyAssertionRequest(options: options) + _ = try PasskeyAssertionRequest(options: options, hubURL: URL(string: testHubURLString)!) } } @@ -146,6 +146,17 @@ struct PasskeysTests { #expect(object["authenticatorAttachment"] as? String == "platform") } + @Test func roamingSecurityKeyAssertionPreservesAttachment() throws { + let result = PasskeyAssertionResult( + credentialID: Data("id".utf8), clientDataJSON: Data("{}".utf8), + authenticatorData: Data([1]), signature: Data([2]), userID: nil, + authenticatorAttachment: "cross-platform" + ) + let body = try HapiJSON.encoder.encode(PasskeyAssertionResponseJSON(result)) + let object = try #require(try JSONSerialization.jsonObject(with: body) as? [String: Any]) + #expect(object["authenticatorAttachment"] as? String == "cross-platform") + } + @Test func assertionWithoutUserHandleOmitsIt() throws { let result = PasskeyAssertionResult( credentialID: Data("id".utf8), @@ -165,7 +176,7 @@ struct PasskeysTests { @Test func passkeySummaryDecodesListResponse() throws { let json = """ {"passkeys":[ - {"id":"abc","name":"iPhone","rpId":"hapi.run","createdAt":1700000000000,"lastUsedAt":1700000100000,"valid":true}, + {"id":"abc","name":"iPhone","rpId":"auth.hapi.run","createdAt":1700000000000,"lastUsedAt":1700000100000,"valid":true}, {"id":"def","name":null,"rpId":"hub.example.com","createdAt":1700000000000,"lastUsedAt":null,"valid":false} ]} """ @@ -260,7 +271,7 @@ struct PasskeysTests { #expect(requests[1].url?.absoluteString == "\(testHubURLString)/api/passkeys/a%2Fb") } - @Test func registerPasskeyRunsCeremonyAndVerifies() async throws { + @Test(.enabled(if: passkeyRegistrationAvailable)) func registerPasskeyRunsCeremonyAndVerifies() async throws { let harness = try makeHarness(paired: true, jwt: freshJWT()) let authenticator = ScriptedAuthenticator( registration: PasskeyRegistrationResult( @@ -274,7 +285,7 @@ struct PasskeysTests { 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)) + #expect(seen.first?.challenge == boundPasskeyChallenge(operation: "register")) let requests = await harness.performer.requests #expect(requests.count == 2) let body = try #require(requests[1].httpBody) @@ -282,7 +293,7 @@ struct PasskeysTests { #expect(object["name"] as? String == "iPad") } - @Test func registerPasskeyDoesNotVerifyWhenCanceled() async throws { + @Test(.enabled(if: passkeyRegistrationAvailable)) func registerPasskeyDoesNotVerifyWhenCanceled() async throws { let harness = try makeHarness(paired: true, jwt: freshJWT()) let authenticator = ScriptedAuthenticator(registrationError: PasskeyError.canceled) await harness.performer.enqueue(json: registrationOptionsJSON()) diff --git a/ios/README.md b/ios/README.md index f11a4ed7..2eb319a6 100644 --- a/ios/README.md +++ b/ios/README.md @@ -159,20 +159,23 @@ 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`. +- **Passkeys:** Settings → Hubs → Passkeys manages this namespace's credentials. + Web and App credentials share RP ID `auth.hapi.run`: a credential created in + either client signs in to the same Hub from both. Configure the Hub's + `HAPI_PUBLIC_URL` as its canonical HTTPS origin. Native sign-in uses + `/health` → `POST /api/passkey/login/options {client:"native"}` → validate + RP/Hub/operation/channel → system sheet → verify. The allowlist limits the + sheet to this Hub's valid credentials; `404 no_passkeys` falls back to pairing. + A passkey session replaces the access token in secure per-Hub storage; + silent re-auth exchanges `{passkeySession}` and treats its 401 as terminal. + Registration also validates the Hub-bound user handle before system UI. + Ceremonies need a signed build with Associated Domains enabled and + `webcredentials:auth.hapi.run`, backed by + `https://auth.hapi.run/.well-known/apple-app-site-association` (source: + `web/passkey-site/.well-known/`). No association file is needed on a user's + Hub domain. `PasskeysTests`, `PasskeyAuthTests`, and `PasskeyHubBindingTests` + cover the wire flow and isolation rules. CryptoKit-backed registration tests + run on macOS; non-Apple builds fail closed for registration without CryptoKit. - **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/package.json b/package.json index bc76149d..f946b0a6 100644 --- a/package.json +++ b/package.json @@ -12,7 +12,8 @@ ], "packageManager": "bun@1.4.4", "scripts": { - "build:site": "bun run --cwd website build && bun run --cwd docs docs:build && cp -r docs/.vitepress/dist website/dist/public/docs", + "build:passkey-site": "bun web/scripts/build-passkey-site.ts", + "build:site": "bun run --cwd website build && bun run --cwd docs docs:build && cp -r docs/.vitepress/dist website/dist/public/docs && bun run build:passkey-site", "dev": "bun run --parallel dev:hub dev:web", "build": "bun run build:cli && bun run build:web && (cd hub && bun run generate:embedded-web-assets) && bun run build:hub", "build:cli": "bun run typecheck:cli", @@ -35,6 +36,7 @@ "test:relay": "cd relay && bun run test", "test:web": "cd web && bun run test", "test:shared": "cd shared && bun run test", + "test:passkey:browser": "bun run build:passkey-site && bun hub/scripts/test-passkey-browser.ts", "test:e2e": "playwright test", "test:e2e:ui": "playwright test --ui", "test:mermaid-lightbox:playwright": "timeout 600 node scripts/dev/mermaid-lightbox-playwright.mjs", diff --git a/shared/package.json b/shared/package.json index bc69b3c4..14ed4beb 100644 --- a/shared/package.json +++ b/shared/package.json @@ -7,6 +7,7 @@ "types": "./src/index.ts", "exports": { ".": "./src/index.ts", + "./passkey": "./src/passkey.ts", "./apiTypes": "./src/apiTypes.ts", "./localTranscript": "./src/localTranscript.ts", "./messages": "./src/messages.ts", diff --git a/shared/src/apiTypes.ts b/shared/src/apiTypes.ts index 56155fbe..258c97b0 100644 --- a/shared/src/apiTypes.ts +++ b/shared/src/apiTypes.ts @@ -1003,16 +1003,26 @@ export const PasskeyCredentialResponseSchema = z.object({ 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') -}) +/** Direct options/verify ceremonies are native-only. Browsers use the bridge. */ +export const PasskeyOptionsRequestSchema = z.object({ client: z.literal('native') }) export type PasskeyOptionsRequest = z.infer +export const PasskeyBrowserStartRequestSchema = z.object({ + codeChallenge: z.string().regex(/^[A-Za-z0-9_-]{43}$/), + state: z.string().regex(/^[A-Za-z0-9_-]{43}$/), + callbackOrigin: z.string().url().max(2048), + name: z.string().trim().max(64).optional() +}).strict() +export type PasskeyBrowserStartRequest = z.infer +export type PasskeyBrowserStartResponse = { url: string } +export const PasskeyBrowserExchangeRequestSchema = z.object({ + code: z.string().regex(/^[A-Za-z0-9_-]{43}$/), + verifier: z.string().regex(/^[A-Za-z0-9_-]{43}$/) +}).strict() +export type PasskeyBrowserExchangeResponse = + | { operation: 'register' } + | { operation: 'login'; token: string; passkeySession: string } + export const PasskeyRegisterVerifyRequestSchema = z.object({ response: PasskeyCredentialResponseSchema, name: z.string().trim().max(64).optional() diff --git a/shared/src/index.ts b/shared/src/index.ts index e58b72d6..4c89aa88 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -48,3 +48,5 @@ export type { AttachedJobStatus } from './schemas' export type * from './types' + +export * from './passkey' diff --git a/shared/src/passkey.test.ts b/shared/src/passkey.test.ts new file mode 100644 index 00000000..7da053cb --- /dev/null +++ b/shared/src/passkey.test.ts @@ -0,0 +1,36 @@ +import { describe, expect, it } from 'bun:test' +import { createHash } from 'node:crypto' +import { + canonicalPasskeyHub, encodePasskeyChallenge, validatePasskeyChallenge, + validatePasskeyUserHandle, passkeyBase64url, passkeyDecode, type PasskeyChallenge +} from './passkey' + +const hub = 'https://hub.example.com' +const challenge: PasskeyChallenge = { v: 1, hub, id: 'a'.repeat(43), nonce: 'b'.repeat(43), operation: 'login', channel: 'browser' } + +describe('passkey Hub isolation', () => { + it('canonicalizes HTTPS origins, never credentials/paths or insecure URLs', () => { + expect(canonicalPasskeyHub('https://HUB.example.com:443/')).toBe(hub) + for (const invalid of ['http://hub.example.com', 'https://u:p@hub.example.com', `${hub}/other`, `${hub}/?q=1`, `${hub}/#f`]) { + expect(() => canonicalPasskeyHub(invalid)).toThrow() + } + }) + it('validates Hub, operation, channel, version, and unpredictable nonce shape', () => { + const encoded = encodePasskeyChallenge(challenge) + expect(validatePasskeyChallenge(encoded, hub, 'login', 'browser')).toEqual(challenge) + for (const changed of [{ hub: 'https://other.example' }, { operation: 'register' }, { channel: 'native' }, { v: 0 }, { nonce: '' }, { id: '' }]) { + expect(() => validatePasskeyChallenge(encodePasskeyChallenge({ ...challenge, ...changed } as PasskeyChallenge), hub, 'login', 'browser')).toThrow() + } + for (const invalid of ['!', 'a', 'x'.repeat(5000), passkeyBase64url(new TextEncoder().encode('null'))]) { + expect(() => validatePasskeyChallenge(invalid, hub, 'login', 'browser')).toThrow() + } + }) + it('binds the account handle to its Hub and round-trips base64url', async () => { + const bytes = Buffer.concat([createHash('sha256').update(hub).digest(), Buffer.alloc(32, 1)]) + const encoded = passkeyBase64url(bytes) + expect(Buffer.from(passkeyDecode(encoded))).toEqual(bytes) + await validatePasskeyUserHandle(encoded, hub) + await expect(validatePasskeyUserHandle(encoded, 'https://other.example')).rejects.toThrow() + await expect(validatePasskeyUserHandle(passkeyBase64url(bytes.subarray(0, 63)), hub)).rejects.toThrow() + }) +}) diff --git a/shared/src/passkey.ts b/shared/src/passkey.ts new file mode 100644 index 00000000..b631e54b --- /dev/null +++ b/shared/src/passkey.ts @@ -0,0 +1,70 @@ +/** Shared RP for native apps and the isolated, static browser ceremony page. */ +export const PASSKEY_RP_ID = 'auth.hapi.run' +export const PASSKEY_ORIGIN = `https://${PASSKEY_RP_ID}` +export const PASSKEY_CALLBACK_PATH = '/passkey/callback' +export const PASSKEY_COMPLETE_PATH = '/api/passkey/browser/complete' +export const PASSKEY_MAX_REQUEST_LENGTH = 64 * 1024 + +export type PasskeyOperation = 'login' | 'register' +export type PasskeyChannel = 'browser' | 'native' +export type PasskeyChallenge = { + v: 1 + hub: string + id: string + operation: PasskeyOperation + channel: PasskeyChannel + nonce: string +} + +/** No credentials, paths, query strings, or HTTP downgrades in Hub identities. */ +export function canonicalPasskeyHub(input: string): string { + const url = new URL(input) + if (url.protocol !== 'https:' || url.username || url.password || url.search || url.hash || url.pathname !== '/') { + throw new Error('Passkeys require a canonical HTTPS Hub origin') + } + return url.origin +} + +export function passkeyBase64url(bytes: Uint8Array): string { + return btoa(Array.from(bytes, (byte) => String.fromCharCode(byte)).join('')) + .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '') +} + +export function passkeyDecode(value: string): Uint8Array { + if (!/^[A-Za-z0-9_-]+$/.test(value) || value.length % 4 === 1) throw new Error('Invalid base64url') + const decoded = atob(value.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - value.length % 4) % 4)) + return Uint8Array.from(decoded, (char) => char.charCodeAt(0)) +} + +export function encodePasskeyChallenge(value: PasskeyChallenge): string { + return passkeyBase64url(new TextEncoder().encode(JSON.stringify(value))) +} + +/** Validate before asking the authenticator to sign: a malicious Hub must not + * proxy a different Hub's challenge under the shared RP. The issuer still + * verifies its exact, stored, unpredictable challenge after the ceremony. */ +export function validatePasskeyChallenge( + encoded: string, + hub: string, + operation: PasskeyOperation, + channel: PasskeyChannel +): PasskeyChallenge { + if (encoded.length > 4096) throw new Error('Invalid passkey challenge') + const value: unknown = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(passkeyDecode(encoded))) + if (!value || typeof value !== 'object') throw new Error('Invalid passkey challenge') + const c = value as Partial + if (c.v !== 1 || c.hub !== canonicalPasskeyHub(hub) || c.operation !== operation || c.channel !== channel + || typeof c.id !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(c.id) + || typeof c.nonce !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(c.nonce)) { + throw new Error('Passkey challenge does not match this Hub or operation') + } + return c as PasskeyChallenge +} + +export async function validatePasskeyUserHandle(encoded: string, hub: string): Promise { + const handle = passkeyDecode(encoded) + const prefix = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(canonicalPasskeyHub(hub)))) + if (handle.length !== 64 || !prefix.every((byte, index) => byte === handle[index])) { + throw new Error('Passkey account does not belong to this Hub') + } +} diff --git a/web/README.md b/web/README.md index 74f7205a..f6fc8489 100644 --- a/web/README.md +++ b/web/README.md @@ -257,3 +257,36 @@ bun run build:web -- --base // 4. Open the static site, click the top-right Hub button on the login screen, and enter the hapi hub origin. Clear the hub override in the same dialog to return to same-origin behavior. + +## Shared Passkeys + +Web and native apps use RP ID `auth.hapi.run`. Web registration/sign-in opens +a popup on the isolated static authentication origin; the Hub performs all +verification. The opener keeps the PKCE verifier and exchanges only a short-lived +authorization code. Configure `HAPI_PUBLIC_URL` as the canonical HTTPS Hub origin. +Separately hosted web apps need an explicit Hub `CORS_ORIGINS` entry for their +callback origin. Wildcards do not authorize authentication callbacks. Popups +and the opener relationship must be allowed; do not set COOP headers that sever +the cross-origin popup/opener relationship on either site. + +Build the independent authentication site with `bun run build:passkey-site`. +Deploy **only `website/dist/auth/`** to `auth.hapi.run`, not the marketing app. +Serve the supplied `_headers` policies (or equivalent host configuration), +including CSP, frame restrictions, origin-only referrers and no-store, and preserve the +`.well-known` files. No third-party scripts, analytics, or service worker belong +on this origin. The Hub callback path `/passkey/callback` must serve the web +app shell (including on separately hosted static deployments). + +See the [authentication contract](../docs/api/client-contract/auth.md#passkeys-web) +for transaction, challenge/account binding, and code-exchange details. + +The bridge uses `Referrer-Policy: strict-origin`: only the authentication origin +is disclosed, never its fragment or path. Do not replace it with `no-referrer`: +Chromium otherwise serializes a cross-origin form POST's `Origin` as `null`, +which the Hub correctly rejects. Hub ceremony responses remain `no-referrer`. + +Browser regression: `bun run test:passkey:browser` uses Chromium's virtual +authenticator against the production Hub and built static site, with all page +requests intercepted locally. It checks both web-created → native and +native-created → web authentication. Install the normal Playwright Chromium +build, or use an existing Chrome with `PLAYWRIGHT_CHANNEL=chrome`. diff --git a/website/public/.well-known/apple-app-site-association b/web/passkey-site/.well-known/apple-app-site-association similarity index 100% rename from website/public/.well-known/apple-app-site-association rename to web/passkey-site/.well-known/apple-app-site-association diff --git a/website/public/.well-known/assetlinks.json b/web/passkey-site/.well-known/assetlinks.json similarity index 100% rename from website/public/.well-known/assetlinks.json rename to web/passkey-site/.well-known/assetlinks.json diff --git a/web/passkey-site/_headers b/web/passkey-site/_headers new file mode 100644 index 00000000..43812b93 --- /dev/null +++ b/web/passkey-site/_headers @@ -0,0 +1,12 @@ +/* + Content-Security-Policy: default-src 'none'; script-src 'self'; style-src 'self'; form-action https:; frame-ancestors 'none'; base-uri 'none'; object-src 'none' + Referrer-Policy: strict-origin + X-Content-Type-Options: nosniff + X-Frame-Options: DENY + Cache-Control: no-store + Strict-Transport-Security: max-age=31536000 + +/.well-known/apple-app-site-association + Content-Type: application/json +/.well-known/assetlinks.json + Content-Type: application/json diff --git a/web/passkey-site/index.html b/web/passkey-site/index.html new file mode 100644 index 00000000..ce26b9cb --- /dev/null +++ b/web/passkey-site/index.html @@ -0,0 +1,23 @@ + + + + + + + + HAPI Passkey + + + + +
+

HAPI · Secure sign-in

+

HAPI Passkey

+

+

Checking authentication request…

+ + +

Your Hub verifies the passkey. This site does not store your account or receive your session tokens.

+
+ + diff --git a/web/passkey-site/style.css b/web/passkey-site/style.css new file mode 100644 index 00000000..56e92b51 --- /dev/null +++ b/web/passkey-site/style.css @@ -0,0 +1,9 @@ +:root { color-scheme: light dark; font: 17px/1.6 system-ui, sans-serif; } +body { margin: 0; padding: 24px; } +main { max-width: 480px; margin: 10vh auto; } +h1 { line-height: 1.2; } +#hub { font-weight: 650; overflow-wrap: anywhere; } +#status { min-height: 3em; } +button { font: inherit; padding: 10px 16px; margin: 0 8px 16px 0; cursor: pointer; } +button:disabled { cursor: default; opacity: .5; } +main > p:last-child { font-size: 14px; opacity: .7; } diff --git a/web/scripts/build-passkey-site.ts b/web/scripts/build-passkey-site.ts new file mode 100644 index 00000000..18c137f9 --- /dev/null +++ b/web/scripts/build-passkey-site.ts @@ -0,0 +1,14 @@ +import { cp, mkdir, rm } from 'node:fs/promises' +import { resolve } from 'node:path' + +// Independent output: never deploy the marketing app/scripts to this origin. +const outdir = resolve(import.meta.dir, '../../website/dist/auth') +await rm(outdir, { recursive: true, force: true }) +await mkdir(outdir, { recursive: true }) +await cp(resolve(import.meta.dir, '../passkey-site'), outdir, { recursive: true }) +const result = await Bun.build({ + entrypoints: [resolve(import.meta.dir, '../src/passkey-site/main.ts')], + outdir, target: 'browser', minify: true, naming: 'main.js' +}) +if (!result.success) throw new AggregateError(result.logs, 'Passkey site build failed') +console.log(`Static passkey site: ${outdir} (deploy only this directory to auth.hapi.run)`) diff --git a/web/scripts/passkey-e2e-entry.ts b/web/scripts/passkey-e2e-entry.ts new file mode 100644 index 00000000..22663302 --- /dev/null +++ b/web/scripts/passkey-e2e-entry.ts @@ -0,0 +1,11 @@ +// Bundled only by the isolated browser regression harness, not the auth site. +import { ApiClient } from '../src/api/client' +import { registerPasskey, signInWithPasskey } from '../src/lib/passkey' +const api = new ApiClient(document.body.dataset.token!, { baseUrl: location.origin }) +const output = document.querySelector('#result')! +document.querySelector('#register')!.addEventListener('click', () => { + void registerPasskey(api, 'Browser integration').then(() => { output.textContent = 'registered' }).catch((e) => { output.textContent = String(e) }) +}) +document.querySelector('#login')!.addEventListener('click', () => { + void signInWithPasskey(location.origin).then((session) => { output.textContent = `session:${session}` }).catch((e) => { output.textContent = String(e) }) +}) diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 9e799096..d223d744 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -80,13 +80,8 @@ import type { import { fetchThroughAuthProxy } from '@/api/authProxy' import { FOLLOW_SESSION_REDIRECTS_HEADER } from '@hapi/protocol' import type { SessionReadState, SessionReadStateRequest, AgentFlavor, MessageDeliveryMode } from '@hapi/protocol' -import type { PasskeyListResponse } from '@hapi/protocol' -import type { - AuthenticationResponseJSON, - PublicKeyCredentialCreationOptionsJSON, - PublicKeyCredentialRequestOptionsJSON, - RegistrationResponseJSON -} from '@simplewebauthn/browser' +import type { PasskeyListResponse, PasskeyBrowserStartRequest, PasskeyBrowserStartResponse, PasskeyBrowserExchangeResponse } from '@hapi/protocol' + import type { CancelMessageResponse, SteerQueuedMessageResponse } from '@hapi/protocol/schemas' import type { TranscriptionMode, TranscriptionProvider, TranscriptionProviderInfo } from '@hapi/protocol/voice' @@ -365,23 +360,15 @@ export class ApiClient { return await res.json() as T } - async getPasskeyLoginOptions(): Promise { - return await this.postPublic('/api/passkey/login/options', {}, 'Passkey sign-in failed') + async startPasskeyBrowser(operation: 'login' | 'register', body: PasskeyBrowserStartRequest): Promise { + const path = `/api/passkey/browser/${operation}/start` + return operation === 'register' + ? await this.request(path, { method: 'POST', body: JSON.stringify(body) }) + : await this.postPublic(path, body, 'Passkey sign-in failed') } - async verifyPasskeyLogin(response: AuthenticationResponseJSON): Promise { - return await this.postPublic('/api/passkey/login/verify', { response }, 'Passkey sign-in failed') - } - - async getPasskeyRegistrationOptions(): Promise { - return await this.request('/api/passkey/register/options', { method: 'POST', body: '{}' }) - } - - async verifyPasskeyRegistration(response: RegistrationResponseJSON, name?: string): Promise { - await this.request('/api/passkey/register/verify', { - method: 'POST', - body: JSON.stringify({ response, name }) - }) + async exchangePasskeyCode(code: string, verifier: string): Promise { + return await this.postPublic('/api/passkey/browser/exchange', { code, verifier }, 'Passkey sign-in failed') } async listPasskeys(): Promise { diff --git a/web/src/components/LoginPrompt.tsx b/web/src/components/LoginPrompt.tsx index 99f68cad..ef11384b 100644 --- a/web/src/components/LoginPrompt.tsx +++ b/web/src/components/LoginPrompt.tsx @@ -49,9 +49,11 @@ export function LoginPrompt(props: LoginPromptProps) { } catch (e) { if (isPasskeyCancelled(e)) return const code = e instanceof ApiError ? e.code : undefined - setError(code === 'passkey_revoked' - ? t('login.passkey.revoked') - : t('login.passkey.failed')) + setError(code === 'passkey_popup_blocked' + ? t('login.passkey.popupBlocked') + : code === 'passkey_revoked' + ? t('login.passkey.revoked') + : t('login.passkey.failed')) } finally { setIsPasskeyLoading(false) } diff --git a/web/src/components/settings/PasskeySettings.tsx b/web/src/components/settings/PasskeySettings.tsx index c3b9b84f..a8e43c44 100644 --- a/web/src/components/settings/PasskeySettings.tsx +++ b/web/src/components/settings/PasskeySettings.tsx @@ -1,3 +1,4 @@ +import { ApiError } from '@/api/client' import { useState } from 'react' import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import type { PasskeySummary } from '@hapi/protocol' @@ -59,7 +60,8 @@ export function PasskeySettings() { onMutate: () => setError(null), onSuccess: () => queryClient.invalidateQueries({ queryKey: queryKeys.passkeys }), onError: (e) => { - if (!isPasskeyCancelled(e)) setError(t('settings.passkeys.addFailed')) + if (!isPasskeyCancelled(e)) setError(e instanceof ApiError && e.code === 'passkey_popup_blocked' + ? t('login.passkey.popupBlocked') : t('settings.passkeys.addFailed')) } }) diff --git a/web/src/lib/locales/en.ts b/web/src/lib/locales/en.ts index 1b0a05df..1014c396 100644 --- a/web/src/lib/locales/en.ts +++ b/web/src/lib/locales/en.ts @@ -69,6 +69,7 @@ export default { 'login.footer.copyright': '©', 'login.passkey.or': 'or', 'login.passkey.submit': 'Sign in with a passkey', + 'login.passkey.popupBlocked': 'Allow popups for this site to sign in with a passkey.', 'login.passkey.failed': 'Passkey sign-in failed. The passkey may not be registered on this hub.', 'login.passkey.revoked': 'This passkey stopped working because the access token was rotated. Sign in with the access token and add the passkey again.', @@ -1296,7 +1297,7 @@ export default { 'settings.voice.proactive': 'Start voice session with summary', 'settings.voice.proactive.description': 'When on, starting a voice session opens with a spoken summary of current agent activity. When off, the assistant greets you and waits for you to speak.', 'settings.passkeys.title': 'Passkeys', - 'settings.passkeys.description': 'Sign in to this hub with Face ID, Touch ID, Windows Hello, or a security key instead of pasting the access token. Passkeys only work on the address where they were added, and stop working when the access token (CLI_API_TOKEN) is rotated.', + 'settings.passkeys.description': 'Sign in to this hub on the web or in the app with Face ID, Touch ID, Windows Hello, or a security key. Registration opens auth.hapi.run. Rotating the access token (CLI_API_TOKEN) disables these passkeys.', 'settings.passkeys.unsupported': 'Passkeys need HTTPS (or localhost) and a browser that supports them. Open this hub over HTTPS to add one.', 'settings.passkeys.add': 'Add passkey', 'settings.passkeys.addFailed': 'Could not add the passkey.', diff --git a/web/src/lib/locales/ru.ts b/web/src/lib/locales/ru.ts index b93a6c1a..e49b9898 100644 --- a/web/src/lib/locales/ru.ts +++ b/web/src/lib/locales/ru.ts @@ -69,6 +69,7 @@ export default { 'login.footer.copyright': '©', 'login.passkey.or': 'или', 'login.passkey.submit': 'Войти с ключом доступа', + 'login.passkey.popupBlocked': 'Разрешите всплывающие окна для этого сайта, чтобы использовать ключ доступа.', 'login.passkey.failed': 'Не удалось войти с ключом доступа. Возможно, он не зарегистрирован на этом хабе.', 'login.passkey.revoked': 'Ключ доступа перестал работать, потому что токен доступа был заменён. Войдите по токену и добавьте ключ заново.', @@ -1200,7 +1201,7 @@ export default { 'settings.voice.proactive': 'Начинать голосовую сессию со сводкой', 'settings.voice.proactive.description': 'При включении голосовая сессия начинается с озвученной сводки текущей активности агента. При выключении ассистент здоровается и ждёт, пока вы заговорите.', 'settings.passkeys.title': 'Ключи доступа', - 'settings.passkeys.description': 'Входите в этот хаб с помощью Face ID, Touch ID, Windows Hello или аппаратного ключа вместо вставки токена доступа. Ключ работает только на том адресе, где был добавлен, и перестаёт работать после замены токена доступа (CLI_API_TOKEN).', + 'settings.passkeys.description': 'Входите в этот хаб в браузере и приложении с Face ID, Touch ID, Windows Hello или аппаратным ключом. Регистрация открывает auth.hapi.run. Замена токена доступа (CLI_API_TOKEN) отключает ключи.', 'settings.passkeys.unsupported': 'Для ключей доступа нужен HTTPS (или localhost) и поддерживающий их браузер. Откройте хаб по HTTPS, чтобы добавить ключ.', 'settings.passkeys.add': 'Добавить ключ доступа', 'settings.passkeys.addFailed': 'Не удалось добавить ключ доступа.', diff --git a/web/src/lib/locales/zh-CN.ts b/web/src/lib/locales/zh-CN.ts index f16d40e1..3c7bff17 100644 --- a/web/src/lib/locales/zh-CN.ts +++ b/web/src/lib/locales/zh-CN.ts @@ -69,6 +69,7 @@ export default { 'login.footer.copyright': '©', 'login.passkey.or': '或', 'login.passkey.submit': '使用 Passkey 登录', + 'login.passkey.popupBlocked': '请允许此网站打开弹窗,以使用 Passkey。', 'login.passkey.failed': 'Passkey 登录失败,这个 Passkey 可能没有在此 Hub 上注册。', 'login.passkey.revoked': '访问令牌已轮换,这个 Passkey 已失效。请用访问令牌登录后重新添加。', @@ -1294,7 +1295,7 @@ export default { 'settings.voice.proactive': '以摘要开始语音会话', 'settings.voice.proactive.description': '开启后,启动语音会话时将朗读当前代理活动的摘要。关闭后,助手向您打招呼并等待您先开口。', 'settings.passkeys.title': 'Passkey', - 'settings.passkeys.description': '用面容 ID、触控 ID、Windows Hello 或安全密钥登录此 Hub,无需粘贴访问令牌。Passkey 只能在添加时的地址上使用;访问令牌(CLI_API_TOKEN)轮换后会失效。', + 'settings.passkeys.description': '用面容 ID、触控 ID、Windows Hello 或安全密钥在网页和 App 中登录此 Hub。添加时会打开 auth.hapi.run。访问令牌(CLI_API_TOKEN)轮换后会失效。', 'settings.passkeys.unsupported': 'Passkey 需要 HTTPS(或 localhost)以及支持它的浏览器。请通过 HTTPS 打开此 Hub 后再添加。', 'settings.passkeys.add': '添加 Passkey', 'settings.passkeys.addFailed': '无法添加 Passkey。', diff --git a/web/src/lib/passkey.test.ts b/web/src/lib/passkey.test.ts new file mode 100644 index 00000000..3df75ac9 --- /dev/null +++ b/web/src/lib/passkey.test.ts @@ -0,0 +1,77 @@ +import { webcrypto } from 'node:crypto' +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { ApiClient, ApiError } from '@/api/client' +import { PASSKEY_ORIGIN, passkeyBase64url } from '@hapi/protocol/passkey' +import { signInWithPasskey } from './passkey' + +const start = vi.spyOn(ApiClient.prototype, 'startPasskeyBrowser') +const exchange = vi.spyOn(ApiClient.prototype, 'exchangePasskeyCode') +const replace = vi.fn() +const close = vi.fn() +const popup = { closed: false, location: { replace }, close } as unknown as Window + +beforeEach(() => { + Object.assign(popup, { closed: false }) + vi.stubGlobal('crypto', webcrypto) + vi.spyOn(window, 'open').mockReturnValue(popup) + start.mockResolvedValue({ url: `${PASSKEY_ORIGIN}/#request` }) + exchange.mockResolvedValue({ operation: 'login', token: 'jwt', passkeySession: 'session' }) +}) +afterEach(() => { vi.clearAllMocks(); vi.unstubAllGlobals() }) + +afterAll(() => { vi.restoreAllMocks() }) + +function callback(data: Record, origin = window.location.origin, source = popup) { + window.dispatchEvent(new MessageEvent('message', { origin, source, data: { type: 'hapi-passkey-callback', ...data } })) +} + +describe('Passkey browser handoff', () => { + it('checks popup identity, callback origin and state; keeps PKCE out of the bridge URL', async () => { + const result = signInWithPasskey('https://hub.example') + await vi.waitFor(() => expect(replace).toHaveBeenCalled()) + const input = start.mock.calls[0]![1] + callback({ state: input.state, code: 'bad' }, 'https://evil.example') + callback({ state: 'bad', code: 'bad' }) + callback({ state: input.state, code: 'bad' }, window.location.origin, window) + expect(exchange).not.toHaveBeenCalled() + callback({ state: input.state, code: 'code' }) + expect(await result).toBe('session') + const verifier = exchange.mock.calls[0]![1] + const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier))) + expect(passkeyBase64url(digest)).toBe(input.codeChallenge) + expect(replace).toHaveBeenCalledWith(`${PASSKEY_ORIGIN}/#request`) + expect(close).toHaveBeenCalled() + }) + it('does not navigate to a Hub-supplied foreign authentication page', async () => { + start.mockResolvedValueOnce({ url: 'https://evil.example/#request' }) + await expect(signInWithPasskey('https://hub.example')).rejects.toThrow('Unexpected Passkey') + expect(replace).not.toHaveBeenCalled() + expect(close).toHaveBeenCalled() + }) + it('treats a cancelled bridge ceremony as a silent browser cancellation', async () => { + const result = signInWithPasskey('https://hub.example') + const rejected = expect(result).rejects.toMatchObject({ name: 'NotAllowedError' }) + await vi.waitFor(() => expect(replace).toHaveBeenCalled()) + callback({ state: start.mock.calls[0]![1].state, error: 'cancelled' }) + await rejected + expect(exchange).not.toHaveBeenCalled() + }) + it('allows closing the popup even when the Hub start request stalls', async () => { + start.mockReturnValueOnce(new Promise(() => {})) + const result = signInWithPasskey('https://hub.example') + const rejected = expect(result).rejects.toMatchObject({ name: 'NotAllowedError' }) + await vi.waitFor(() => expect(start).toHaveBeenCalled()) + Object.assign(popup, { closed: true }) + await rejected + expect(exchange).not.toHaveBeenCalled() + expect(close).toHaveBeenCalled() + }) + it('propagates revocation without exchanging a code', async () => { + const result = signInWithPasskey('https://hub.example') + const rejected = expect(result).rejects.toMatchObject({ code: 'passkey_revoked' } satisfies Partial) + await vi.waitFor(() => expect(replace).toHaveBeenCalled()) + callback({ state: start.mock.calls[0]![1].state, error: 'passkey_revoked' }) + await rejected + expect(exchange).not.toHaveBeenCalled() + }) +}) diff --git a/web/src/lib/passkey.ts b/web/src/lib/passkey.ts index 4c3ab681..d01fcf44 100644 --- a/web/src/lib/passkey.ts +++ b/web/src/lib/passkey.ts @@ -1,10 +1,9 @@ +import { PASSKEY_ORIGIN, passkeyBase64url } from '@hapi/protocol/passkey' import { browserSupportsWebAuthn, - startAuthentication, - startRegistration, WebAuthnError } from '@simplewebauthn/browser' -import { ApiClient } from '@/api/client' +import { ApiClient, ApiError } from '@/api/client' /** WebAuthn needs a secure context; plain-HTTP LAN addresses are not one. */ export function isPasskeySupported(): boolean { @@ -19,19 +18,81 @@ export function isPasskeyCancelled(error: unknown): boolean { return error instanceof Error && error.name === 'NotAllowedError' } -/** Run the sign-in ceremony and return the long-lived passkey session. */ +const CALLBACK_MESSAGE = 'hapi-passkey-callback' + +function cancelled(): Error { + return new DOMException('Passkey sign-in cancelled', 'NotAllowedError') +} + +/** Open synchronously in the click handler, before any network/crypto awaits. + * The verifier remains in the initiating tab; the bridge never receives it. */ +async function browserCeremony(api: ApiClient, operation: 'login' | 'register', name?: string) { + const popup = window.open('about:blank', '_blank', 'popup,width=480,height=700') + if (!popup) throw new ApiError('Allow popups to use Passkey sign-in', 0, 'passkey_popup_blocked') + const state = passkeyBase64url(crypto.getRandomValues(new Uint8Array(32))) + const verifier = passkeyBase64url(crypto.getRandomValues(new Uint8Array(32))) + let timer: ReturnType | undefined + let listener: ((event: MessageEvent) => void) | undefined + try { + const codeChallenge = passkeyBase64url(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)))) + const callback = new Promise((resolve, reject) => { + listener = (event) => { + if (event.origin !== window.location.origin || event.source !== popup || !event.data + || event.data.type !== CALLBACK_MESSAGE || event.data.state !== state) return + if (event.data.error) { + reject(event.data.error === 'cancelled' ? cancelled() : new ApiError('Passkey sign-in failed', 401, String(event.data.error))) + } else if (typeof event.data.code === 'string') resolve(event.data.code) + } + window.addEventListener('message', listener) + const expiresAt = Date.now() + 5 * 60 * 1000 + timer = setInterval(() => { + if (popup.closed || Date.now() >= expiresAt) reject(cancelled()) + }, 400) + }) + // Attach a rejection handler while awaiting start (e.g. user closes early). + void callback.catch(() => {}) + const { url } = await Promise.race([ + api.startPasskeyBrowser(operation, { state, codeChallenge, callbackOrigin: window.location.origin, name }), + callback.then(() => { throw new Error('Unexpected early Passkey callback') }) + ]) + const target = new URL(url) + if (target.origin !== PASSKEY_ORIGIN || target.pathname !== '/' || target.search || !target.hash) { + throw new Error('Unexpected Passkey authentication page') + } + if (popup.closed) throw cancelled() + popup.location.replace(target.href) + const code = await callback + const result = await api.exchangePasskeyCode(code, verifier) + if (result.operation !== operation) throw new Error('Passkey operation mismatch') + return result + } finally { + if (timer) clearInterval(timer) + if (listener) window.removeEventListener('message', listener) + popup.close() + } +} + export async function signInWithPasskey(baseUrl: string): Promise { - const client = new ApiClient('', { baseUrl }) - const optionsJSON = await client.getPasskeyLoginOptions() - const response = await startAuthentication({ optionsJSON }) - const result = await client.verifyPasskeyLogin(response) + const result = await browserCeremony(new ApiClient('', { baseUrl }), 'login') + if (result.operation !== 'login') throw new Error('Passkey operation mismatch') return result.passkeySession } export async function registerPasskey(api: ApiClient, name?: string): Promise { - const optionsJSON = await api.getPasskeyRegistrationOptions() - const response = await startRegistration({ optionsJSON }) - await api.verifyPasskeyRegistration(response, name) + await browserCeremony(api, 'register', name) +} + +/** Standalone popup landing: no auth/router or analytics, and no token in URL. */ +export function completePasskeyCallback(): void { + const params = new URLSearchParams(window.location.hash.slice(1)) + window.history.replaceState(null, '', window.location.pathname) + if (window.opener && params.has('state')) { + window.opener.postMessage({ + type: CALLBACK_MESSAGE, state: params.get('state'), code: params.get('code'), error: params.get('error') + }, window.location.origin) + window.close() + } + document.body.textContent = 'Return to the HAPI window to finish signing in.' } /** Best-effort label for a new passkey, e.g. "Chrome on macOS". */ diff --git a/web/src/main.tsx b/web/src/main.tsx index 6c5aee2e..c440c35b 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -1,3 +1,5 @@ +import { completePasskeyCallback } from '@/lib/passkey' +import { PASSKEY_CALLBACK_PATH } from '@hapi/protocol/passkey' import React from 'react' import ReactDOM from 'react-dom/client' import { QueryClientProvider } from '@tanstack/react-query' @@ -68,4 +70,8 @@ async function bootstrap() { ) } -bootstrap() +if (window.location.pathname === PASSKEY_CALLBACK_PATH) { + completePasskeyCallback() +} else { + bootstrap() +} diff --git a/web/src/passkey-site/main.ts b/web/src/passkey-site/main.ts new file mode 100644 index 00000000..d5eb9874 --- /dev/null +++ b/web/src/passkey-site/main.ts @@ -0,0 +1,59 @@ +import { startAuthentication, startRegistration } from '@simplewebauthn/browser' +import { PASSKEY_COMPLETE_PATH, PASSKEY_ORIGIN } from '@hapi/protocol/passkey' +import { parseCeremonyRequest } from './request' + +const title = document.querySelector('h1')! +const hubLabel = document.querySelector('#hub')! +const status = document.querySelector('#status')! +const proceed = document.querySelector('#continue')! +const cancel = document.querySelector('#cancel')! + +async function setup() { + const fragment = location.hash + history.replaceState(null, '', '/') + if (location.origin !== PASSKEY_ORIGIN || window.top !== window.self || !window.isSecureContext) { + throw new Error('Open this authentication page directly on auth.hapi.run over HTTPS.') + } + const request = await parseCeremonyRequest(fragment) + hubLabel.textContent = request.hub + title.textContent = request.operation === 'register' ? 'Add a HAPI passkey' : 'Sign in to HAPI' + status.textContent = 'Continue only if this is the Hub you intended to use.' + proceed.disabled = false + cancel.disabled = false + + function submit(response?: unknown) { + // Only a fixed endpoint of the challenge-bound Hub can receive results. + const form = document.createElement('form') + form.method = 'POST' + form.action = new URL(PASSKEY_COMPLETE_PATH, request.hub).href + const fields = { challenge: request.options.challenge, ...(response ? { response: JSON.stringify(response) } : { error: 'cancelled' }) } + for (const [name, value] of Object.entries(fields)) { + const input = document.createElement('input') + input.type = 'hidden' + input.name = name + input.value = value + form.append(input) + } + document.body.append(form) + form.submit() + } + cancel.onclick = () => submit() + proceed.onclick = async () => { + proceed.disabled = true + cancel.disabled = true + try { + const response = request.operation === 'register' + ? await startRegistration({ optionsJSON: request.options }) + : await startAuthentication({ optionsJSON: request.options }) + submit(response) + } catch (error) { + status.textContent = error instanceof Error ? error.message : 'Passkey operation failed.' + proceed.disabled = false + cancel.disabled = false + } + } +} + +void setup().catch((error: unknown) => { + status.textContent = error instanceof Error ? error.message : 'Invalid authentication request.' +}) diff --git a/web/src/passkey-site/request.test.ts b/web/src/passkey-site/request.test.ts new file mode 100644 index 00000000..f93a99cf --- /dev/null +++ b/web/src/passkey-site/request.test.ts @@ -0,0 +1,49 @@ +import { webcrypto } from 'node:crypto' +import { beforeAll, describe, expect, it, vi } from 'vitest' +import { encodePasskeyChallenge, passkeyBase64url, PASSKEY_RP_ID } from '@hapi/protocol/passkey' +import { parseCeremonyRequest } from './request' + +beforeAll(() => { vi.stubGlobal('crypto', webcrypto) }) +const hub = 'https://hub.example.com' +function request(operation: 'login' | 'register' = 'login') { + const challenge = encodePasskeyChallenge({ v: 1, hub, id: 'a'.repeat(43), nonce: 'b'.repeat(43), operation, channel: 'browser' }) + return { hub, operation, options: { challenge, rpId: PASSKEY_RP_ID, allowCredentials: [{ id: 'Y3JlZA', type: 'public-key' }] } } +} +const fragment = (r: unknown) => `#${encodeURIComponent(JSON.stringify(r))}` + +describe('static passkey bridge', () => { + it('pins the RP and user verification, ignoring untrusted extensions', async () => { + const input = { ...request(), options: { ...request().options, userVerification: 'discouraged', extensions: { largeBlob: { read: true } } } } + const result = await parseCeremonyRequest(fragment(input)) + expect(result.options).toMatchObject({ rpId: PASSKEY_RP_ID, userVerification: 'required' }) + expect(result.options).not.toHaveProperty('extensions') + }) + it('rejects a malicious Hub proxying another Hub challenge', async () => { + await expect(parseCeremonyRequest(fragment({ ...request(), hub: 'https://evil.example' }))).rejects.toThrow() + }) + it('rejects native-channel challenges, wrong RPs, and unrestricted discovery', async () => { + const input = request() + const native = encodePasskeyChallenge({ v: 1, hub, id: 'a'.repeat(43), nonce: 'b'.repeat(43), operation: 'login', channel: 'native' }) + for (const options of [{ ...input.options, challenge: native }, { ...input.options, rpId: 'evil.example' }, { ...input.options, allowCredentials: [] }]) { + await expect(parseCeremonyRequest(fragment({ ...input, options }))).rejects.toThrow() + } + }) + it('validates registration account binding and strips RP/attestation/extension choices', async () => { + const prefix = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(hub))) + const bytes = new Uint8Array(64); bytes.set(prefix) + const input = { + ...request('register'), options: { + challenge: request('register').options.challenge, rp: { id: PASSKEY_RP_ID, name: 'untrusted' }, + user: { id: passkeyBase64url(bytes), name: 'hapi@hub.example.com', displayName: 'untrusted' } + } + } + const result = await parseCeremonyRequest(fragment(input)) + expect(result.options).toMatchObject({ rp: { id: PASSKEY_RP_ID, name: 'HAPI' }, attestation: 'none' }) + await expect(parseCeremonyRequest(fragment({ ...input, options: { ...input.options, user: { ...input.options.user, id: 'YQ' } } }))).rejects.toThrow() + }) + it('rejects malformed or oversized input and non-HTTPS Hub identities', async () => { + for (const input of ['#null', '#%zz', '#'+ 'x'.repeat(400000), fragment({ ...request(), hub: 'http://hub.example.com' })]) { + await expect(parseCeremonyRequest(input)).rejects.toThrow() + } + }) +}) diff --git a/web/src/passkey-site/request.ts b/web/src/passkey-site/request.ts new file mode 100644 index 00000000..d964c3a9 --- /dev/null +++ b/web/src/passkey-site/request.ts @@ -0,0 +1,45 @@ +import type { PublicKeyCredentialCreationOptionsJSON, PublicKeyCredentialRequestOptionsJSON } from '@simplewebauthn/browser' +import { + canonicalPasskeyHub, PASSKEY_MAX_REQUEST_LENGTH, PASSKEY_RP_ID, + validatePasskeyChallenge, validatePasskeyUserHandle +} from '@hapi/protocol/passkey' + +type Request = + | { hub: string; operation: 'login'; options: PublicKeyCredentialRequestOptionsJSON } + | { hub: string; operation: 'register'; options: PublicKeyCredentialCreationOptionsJSON } + +/** This page accepts messages from untrusted, independently operated Hubs. + * Never execute a ceremony without binding its challenge/account to that Hub. */ +export async function parseCeremonyRequest(fragment: string): Promise { + if (fragment.length > PASSKEY_MAX_REQUEST_LENGTH * 6) throw new Error('Request is too large') + const json = decodeURIComponent(fragment.replace(/^#/, '')) + if (json.length > PASSKEY_MAX_REQUEST_LENGTH) throw new Error('Request is too large') + const value = JSON.parse(json) as Request + if (!value || !value.options || (value.operation !== 'login' && value.operation !== 'register')) throw new Error('Invalid request') + const hub = canonicalPasskeyHub(value.hub) + if (hub !== value.hub) throw new Error('Invalid Hub address') + validatePasskeyChallenge(value.options.challenge, hub, value.operation, 'browser') + if (value.operation === 'login') { + if (value.options.rpId !== PASSKEY_RP_ID || !value.options.allowCredentials?.length) throw new Error('Invalid relying party or credentials') + return { + hub, operation: 'login', options: { + challenge: value.options.challenge, rpId: PASSKEY_RP_ID, + allowCredentials: value.options.allowCredentials, userVerification: 'required', timeout: 120000 + } + } + } + if (value.options.rp?.id !== PASSKEY_RP_ID) throw new Error('Invalid relying party') + await validatePasskeyUserHandle(value.options.user.id, hub) + if (!value.options.user.name.endsWith(`@${new URL(hub).host}`)) throw new Error('Invalid account name') + return { + hub, operation: 'register', options: { + challenge: value.options.challenge, + rp: { id: PASSKEY_RP_ID, name: 'HAPI' }, + user: { ...value.options.user, displayName: `HAPI · ${new URL(hub).host}` }, + pubKeyCredParams: [{ alg: -7, type: 'public-key' }, { alg: -257, type: 'public-key' }], + excludeCredentials: value.options.excludeCredentials, + authenticatorSelection: { residentKey: 'required', userVerification: 'required' }, + attestation: 'none', timeout: 120000 + } + } +}