Files
hapi/ios/Hapi/Features/Passkeys/PlatformPasskeyAuthenticator.swift
T
weishu 59a486ba88 feat: passkey sign-in for the iOS and Android apps
Native apps cannot follow a self-hosted hub's domain (entitlements and
asset links are fixed at build time), so they use one shared RP ID,
hapi.run, and every hub accepts it only from exact app origins.

- hub: `{"client":"native"}` on the passkey option routes selects the
  native RP; origins are https://hapi.run (iOS/macOS) and the official
  android:apk-key-hash values, extendable via HAPI_PASSKEY_NATIVE_ORIGINS
  (HAPI_PASSKEY_NATIVE_RP_ID for forks). Native login options restrict
  allowCredentials to this hub's passkeys. Accept a null
  authenticatorAttachment.
- website: publish apple-app-site-association (webcredentials for
  XJB862F92W.run.hapi.app) and assetlinks.json (get_login_creds for
  run.hapi.companion; signing fingerprint still a TODO placeholder).
- iOS: webcredentials:hapi.run, AuthenticationServices ceremonies,
  passkey-only sign-in on the pairing screen, Settings → Passkeys, and a
  passkey-session credential kind used by silent re-auth.
- Android: Credential Manager 1.6.0, the same flows and credential kind,
  and README notes on computing the apk-key-hash origin.
- docs: native passkey contract and user guide.
2026-11-16 17:24:04 +08:00

141 lines
6.0 KiB
Swift

import AuthenticationServices
import HapiClient
import UIKit
/// AuthenticationServices implementation of ``PasskeyAuthenticating``.
///
/// Native passkeys live on the shared RP ID `hapi.run`
/// (`webcredentials:hapi.run` in the Associated Domains entitlement, backed by
/// `https://hapi.run/.well-known/apple-app-site-association`); the system
/// reports the origin `https://hapi.run`, which every hub accepts. Options
/// arrive already RP-checked and decoded (``PasskeyRegistrationRequest`` /
/// ``PasskeyAssertionRequest``); this type only drives the system sheet and
/// returns raw bytes for HapiClient to encode as base64url JSON.
struct PlatformPasskeyAuthenticator: PasskeyAuthenticating {
func register(_ request: PasskeyRegistrationRequest) async throws -> PasskeyRegistrationResult {
let authorization = try await PasskeyCeremony.perform {
let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(
relyingPartyIdentifier: request.relyingPartyID
)
let registration = provider.createCredentialRegistrationRequest(
challenge: request.challenge,
name: request.userName,
userID: request.userID
)
registration.userVerificationPreference = .required
if #available(iOS 17.4, macCatalyst 17.4, *) {
registration.excludedCredentials = request.excludedCredentialIDs.map {
ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0)
}
}
return registration
}
guard let credential = authorization.credential
as? ASAuthorizationPlatformPublicKeyCredentialRegistration else {
throw PasskeyError.platform("Unexpected credential type")
}
guard let attestation = credential.rawAttestationObject, !attestation.isEmpty else {
throw PasskeyError.missingAttestation
}
return PasskeyRegistrationResult(
credentialID: credential.credentialID,
clientDataJSON: credential.rawClientDataJSON,
attestationObject: attestation
)
}
func authenticate(_ request: PasskeyAssertionRequest) async throws -> PasskeyAssertionResult {
let authorization = try await PasskeyCeremony.perform {
let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(
relyingPartyIdentifier: request.relyingPartyID
)
let assertion = provider.createCredentialAssertionRequest(challenge: request.challenge)
assertion.userVerificationPreference = .required
// Restrict the sheet to this hub's passkeys: every hub shares the
// RP ID, so an empty list would offer all of them.
assertion.allowedCredentials = request.allowedCredentialIDs.map {
ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0)
}
return assertion
}
guard let credential = authorization.credential
as? ASAuthorizationPlatformPublicKeyCredentialAssertion else {
throw PasskeyError.platform("Unexpected credential type")
}
return PasskeyAssertionResult(
credentialID: credential.credentialID,
clientDataJSON: credential.rawClientDataJSON,
authenticatorData: credential.rawAuthenticatorData,
signature: credential.signature,
userID: credential.userID
)
}
}
/// One `ASAuthorizationController` run bridged to async/await. Kept alive in
/// ``inFlight`` until the delegate fires (the controller holds its delegate
/// weakly).
@MainActor
private final class PasskeyCeremony: NSObject,
ASAuthorizationControllerDelegate,
ASAuthorizationControllerPresentationContextProviding {
private static var inFlight: Set<PasskeyCeremony> = []
private var continuation: CheckedContinuation<ASAuthorization, Error>?
private var controller: ASAuthorizationController?
static func perform(
_ makeRequest: @MainActor () -> ASAuthorizationRequest
) async throws -> ASAuthorization {
let ceremony = PasskeyCeremony()
let request = makeRequest()
return try await withCheckedThrowingContinuation { continuation in
ceremony.start(request, continuation: continuation)
}
}
private func start(_ request: ASAuthorizationRequest, continuation: CheckedContinuation<ASAuthorization, Error>) {
self.continuation = continuation
let controller = ASAuthorizationController(authorizationRequests: [request])
controller.delegate = self
controller.presentationContextProvider = self
self.controller = controller
Self.inFlight.insert(self)
controller.performRequests()
}
private func finish(_ result: Result<ASAuthorization, Error>) {
continuation?.resume(with: result)
continuation = nil
controller = nil
Self.inFlight.remove(self)
}
func authorizationController(
controller: ASAuthorizationController,
didCompleteWithAuthorization authorization: ASAuthorization
) {
finish(.success(authorization))
}
func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {
if let authorizationError = error as? ASAuthorizationError, authorizationError.code == .canceled {
finish(.failure(PasskeyError.canceled))
} else {
finish(.failure(PasskeyError.platform(error.localizedDescription)))
}
}
func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {
let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }
let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first
if let window = scene?.keyWindow ?? scene?.windows.first {
return window
}
if let scene {
return UIWindow(windowScene: scene)
}
return ASPresentationAnchor()
}
}