Repository Public
1// SP Music iOS2// File: Core/Sources/SPMusicCore/Authentication/Passkeys.swift3// Description: Passkey sign-in and enrolment through AuthenticationServices (WebAuthn JSON).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import AuthenticationServices9import Foundation1011/// WebAuthn JSON as the server (SimpleWebAuthn) expects it, built from what AuthenticationServices returns.12public enum PasskeyWire {13 public struct LoginOptions: Decodable, Sendable {14 public struct Options: Decodable, Sendable { public var challenge: String; public var rpId: String? }15 public var challengeId: String16 public var options: Options17 }18 public struct RegistrationOptions: Decodable, Sendable {19 public struct User: Decodable, Sendable { public var id: String; public var name: String; public var displayName: String? }20 public struct RP: Decodable, Sendable { public var id: String?; public var name: String }21 public struct Options: Decodable, Sendable { public var challenge: String; public var user: User; public var rp: RP }22 public var challengeId: String23 public var options: Options24 }25 public struct Credential: Encodable, Sendable {26 public struct Response: Encodable, Sendable {27 public var clientDataJSON: String28 public var authenticatorData: String?29 public var signature: String?30 public var userHandle: String?31 public var attestationObject: String?32 public var transports: [String]?33 }34 public var id: String35 public var rawId: String36 public var type = "public-key"37 public var authenticatorAttachment = "platform"38 public var clientExtensionResults: [String: String] = [:]39 public var response: Response40 }41 public struct LoginVerify: Encodable, Sendable { public var challengeId: String; public var response: Credential }42 public struct RegisterVerify: Encodable, Sendable { public var challengeId: String; public var response: Credential; public var name: String?; public var setupToken: String? }43 public struct RegisterResult: Decodable, Sendable { public var recoveryCodes: [String]? }44 struct RegisterOptionsBody: Encodable, Sendable { var setupToken: String? }45 struct EmptyBody: Encodable, Sendable {}4647 public static func assertion(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userID: Data?) -> Credential {48 let id = Base64URL.encode(credentialID)49 return Credential(id: id, rawId: id, response: .init(clientDataJSON: Base64URL.encode(clientDataJSON), authenticatorData: Base64URL.encode(authenticatorData),50 signature: Base64URL.encode(signature), userHandle: userID.flatMap { $0.isEmpty ? nil : Base64URL.encode($0) }))51 }52 public static func attestation(credentialID: Data, clientDataJSON: Data, attestationObject: Data) -> Credential {53 let id = Base64URL.encode(credentialID)54 return Credential(id: id, rawId: id, response: .init(clientDataJSON: Base64URL.encode(clientDataJSON), attestationObject: Base64URL.encode(attestationObject), transports: ["internal", "hybrid"]))55 }56}5758public enum PasskeyError: Error, LocalizedError, Sendable {59 case cancelled, unavailable(String), malformedChallenge60 public var errorDescription: String? {61 switch self {62 case .cancelled: "Connexion annulée."63 case .unavailable(let why): "Clé d'accès indisponible : \(why)"64 case .malformedChallenge: "Réponse du serveur illisible."65 }66 }67}6869/// One AuthenticationServices request, awaited.70@MainActor71final class PasskeyCeremony: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {72 private var continuation: CheckedContinuation<ASAuthorization, any Error>?73 private let anchor: ASPresentationAnchor74 private var controller: ASAuthorizationController?7576 init(anchor: ASPresentationAnchor) { self.anchor = anchor }7778 func perform(_ request: ASAuthorizationRequest) async throws -> ASAuthorization {79 try await withCheckedThrowingContinuation { c in80 continuation = c81 let controller = ASAuthorizationController(authorizationRequests: [request])82 controller.delegate = self83 controller.presentationContextProvider = self84 self.controller = controller85 controller.performRequests()86 }87 }88 func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor { anchor }89 func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {90 continuation?.resume(returning: authorization); continuation = nil; self.controller = nil91 }92 func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: any Error) {93 let e = error as? ASAuthorizationError94 let mapped: PasskeyError = e?.code == .canceled ? .cancelled : .unavailable(error.localizedDescription)95 continuation?.resume(throwing: mapped); continuation = nil; self.controller = nil96 }97}9899public extension APIClient {100 /// Signs in with a passkey of the site (relying party = the site's host, checked by iOS against the site's101 /// apple-app-site-association). Face ID / Touch ID never leaves the device: the server receives a signature.102 @MainActor103 func signInWithPasskey(anchor: ASPresentationAnchor) async throws {104 let o: PasskeyWire.LoginOptions = try await send("POST", "api/v1/auth/login/options", body: PasskeyWire.EmptyBody())105 guard let challenge = Base64URL.decode(o.options.challenge) else { throw PasskeyError.malformedChallenge }106 let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: o.options.rpId ?? baseURL.host ?? "")107 let request = provider.createCredentialAssertionRequest(challenge: challenge)108 request.userVerificationPreference = .required109 let auth = try await PasskeyCeremony(anchor: anchor).perform(request)110 guard let a = auth.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else { throw PasskeyError.unavailable("réponse inattendue") }111 let cred = PasskeyWire.assertion(credentialID: a.credentialID, clientDataJSON: a.rawClientDataJSON, authenticatorData: a.rawAuthenticatorData, signature: a.signature, userID: a.userID)112 try await send("POST", "api/v1/auth/login/verify", body: PasskeyWire.LoginVerify(challengeId: o.challengeId, response: cred), as: Empty.self)113 }114115 /// Creates a passkey on this device: with a one-time enrolment token (first sign-in, invitation), or — without116 /// one — for the account already signed in. Returns the recovery codes when the server issues them.117 @MainActor118 func registerPasskey(anchor: ASPresentationAnchor, setupToken: String?, name: String) async throws -> [String]? {119 let o: PasskeyWire.RegistrationOptions = try await send("POST", "api/v1/auth/register/options", body: PasskeyWire.RegisterOptionsBody(setupToken: setupToken))120 guard let challenge = Base64URL.decode(o.options.challenge), let userID = Base64URL.decode(o.options.user.id) else { throw PasskeyError.malformedChallenge }121 let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: o.options.rp.id ?? baseURL.host ?? "")122 let request = provider.createCredentialRegistrationRequest(challenge: challenge, name: o.options.user.name, userID: userID)123 request.userVerificationPreference = .required124 let auth = try await PasskeyCeremony(anchor: anchor).perform(request)125 guard let r = auth.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration, let attestation = r.rawAttestationObject else { throw PasskeyError.unavailable("réponse inattendue") }126 let cred = PasskeyWire.attestation(credentialID: r.credentialID, clientDataJSON: r.rawClientDataJSON, attestationObject: attestation)127 let out: PasskeyWire.RegisterResult = try await send("POST", "api/v1/auth/register/verify", body: PasskeyWire.RegisterVerify(challengeId: o.challengeId, response: cred, name: name, setupToken: setupToken))128 return out.recoveryCodes129 }130}131