Repository Public
1// SP Drive iOS2// File: App/Auth/PasskeyController.swift3// Description: Native passkeys (AuthenticationServices). Turns the server's WebAuthn options into a system request and the system's answer4// back into the WebAuthn JSON the server verifies. No web view, no biometric data: the signature is made by the device.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import AuthenticationServices9import Foundation10import UIKit1112enum PasskeyError: LocalizedError {13 case malformedOptions, cancelled, unsupportedCredential, failed(String)14 var errorDescription: String? {15 switch self {16 case .malformedOptions: "La réponse du serveur est invalide."17 case .cancelled: "Connexion annulée."18 case .unsupportedCredential: "Ce type de clé n’est pas pris en charge."19 case .failed(let m): m20 }21 }22}2324/// Pure encoding helpers, separated from the system sheet so they can be unit-tested.25enum WebAuthnJSON {26 static func b64url(_ d: Data) -> String {27 d.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")28 }29 static func data(b64url s: String) -> Data? {30 var t = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")31 while t.count % 4 != 0 { t += "=" }32 return Data(base64Encoded: t)33 }3435 struct AssertionOptions { let challenge: Data; let rpId: String; let allowed: [Data] }36 struct RegistrationOptions { let challenge: Data; let rpId: String; let userID: Data; let userName: String; let excluded: [Data] }3738 static func assertionOptions(_ json: Data, defaultRP: String) throws -> AssertionOptions {39 guard let o = try? JSONSerialization.jsonObject(with: json) as? [String: Any], let c = (o["challenge"] as? String).flatMap(data(b64url:)) else { throw PasskeyError.malformedOptions }40 let allow = (o["allowCredentials"] as? [[String: Any]] ?? []).compactMap { ($0["id"] as? String).flatMap(data(b64url:)) }41 return .init(challenge: c, rpId: o["rpId"] as? String ?? defaultRP, allowed: allow)42 }43 static func registrationOptions(_ json: Data, defaultRP: String) throws -> RegistrationOptions {44 guard let o = try? JSONSerialization.jsonObject(with: json) as? [String: Any], let c = (o["challenge"] as? String).flatMap(data(b64url:)),45 let user = o["user"] as? [String: Any], let uid = (user["id"] as? String).flatMap(data(b64url:)), let name = user["name"] as? String else { throw PasskeyError.malformedOptions }46 let rp = (o["rp"] as? [String: Any])?["id"] as? String ?? defaultRP47 let ex = (o["excludeCredentials"] as? [[String: Any]] ?? []).compactMap { ($0["id"] as? String).flatMap(data(b64url:)) }48 return .init(challenge: c, rpId: rp, userID: uid, userName: name, excluded: ex)49 }5051 /// AuthenticationResponseJSON as @simplewebauthn/server expects it.52 static func assertionResponse(credentialID: Data, clientDataJSON: Data, authenticatorData: Data, signature: Data, userHandle: Data?, platform: Bool) -> Data {53 var response: [String: Any] = ["clientDataJSON": b64url(clientDataJSON), "authenticatorData": b64url(authenticatorData), "signature": b64url(signature)]54 if let userHandle, !userHandle.isEmpty { response["userHandle"] = b64url(userHandle) }55 let body: [String: Any] = ["id": b64url(credentialID), "rawId": b64url(credentialID), "type": "public-key", "response": response,56 "clientExtensionResults": [String: Any](), "authenticatorAttachment": platform ? "platform" : "cross-platform"]57 return (try? JSONSerialization.data(withJSONObject: body)) ?? Data()58 }59 /// RegistrationResponseJSON.60 static func registrationResponse(credentialID: Data, clientDataJSON: Data, attestationObject: Data, platform: Bool) -> Data {61 let response: [String: Any] = ["clientDataJSON": b64url(clientDataJSON), "attestationObject": b64url(attestationObject), "transports": platform ? ["internal", "hybrid"] : ["usb", "nfc"]]62 let body: [String: Any] = ["id": b64url(credentialID), "rawId": b64url(credentialID), "type": "public-key", "response": response,63 "clientExtensionResults": [String: Any](), "authenticatorAttachment": platform ? "platform" : "cross-platform"]64 return (try? JSONSerialization.data(withJSONObject: body)) ?? Data()65 }66}6768/// Presents the system passkey sheet. One request at a time.69@MainActor70final class PasskeyController: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {71 private var continuation: CheckedContinuation<Data, Error>?72 private var controller: ASAuthorizationController?7374 /// `optionsJSON` is the `options` object returned by `/auth/login/options` (or `/auth/reauth/options`). Returns the response JSON to post back.75 func assert(optionsJSON: Data) async throws -> Data {76 let o = try WebAuthnJSON.assertionOptions(optionsJSON, defaultRP: AppGroup.relyingParty)77 let platform = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: o.rpId).createCredentialAssertionRequest(challenge: o.challenge)78 platform.userVerificationPreference = .required79 platform.allowedCredentials = o.allowed.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) }80 let key = ASAuthorizationSecurityKeyPublicKeyCredentialProvider(relyingPartyIdentifier: o.rpId).createCredentialAssertionRequest(challenge: o.challenge)81 key.userVerificationPreference = .required82 key.allowedCredentials = o.allowed.map { ASAuthorizationSecurityKeyPublicKeyCredentialDescriptor(credentialID: $0, transports: ASAuthorizationSecurityKeyPublicKeyCredentialDescriptor.Transport.allSupported) }83 return try await perform([platform, key])84 }8586 /// `optionsJSON` is the `options` object of a registration ceremony (invitation or « add a passkey »).87 func register(optionsJSON: Data) async throws -> Data {88 let o = try WebAuthnJSON.registrationOptions(optionsJSON, defaultRP: AppGroup.relyingParty)89 let req = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: o.rpId).createCredentialRegistrationRequest(challenge: o.challenge, name: o.userName, userID: o.userID)90 req.userVerificationPreference = .required91 req.excludedCredentials = o.excluded.map { ASAuthorizationPlatformPublicKeyCredentialDescriptor(credentialID: $0) }92 return try await perform([req])93 }9495 private func perform(_ requests: [ASAuthorizationRequest]) async throws -> Data {96 if continuation != nil { throw PasskeyError.failed("Une demande est déjà en cours.") }97 return try await withCheckedThrowingContinuation { c in98 continuation = c99 let ctl = ASAuthorizationController(authorizationRequests: requests)100 ctl.delegate = self101 ctl.presentationContextProvider = self102 controller = ctl103 ctl.performRequests()104 }105 }106107 private func finish(_ r: Result<Data, Error>) {108 let c = continuation109 continuation = nil110 controller = nil111 c?.resume(with: r)112 }113114 func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {115 switch authorization.credential {116 case let a as ASAuthorizationPlatformPublicKeyCredentialAssertion:117 finish(.success(WebAuthnJSON.assertionResponse(credentialID: a.credentialID, clientDataJSON: a.rawClientDataJSON, authenticatorData: a.rawAuthenticatorData, signature: a.signature, userHandle: a.userID, platform: true)))118 case let a as ASAuthorizationSecurityKeyPublicKeyCredentialAssertion:119 finish(.success(WebAuthnJSON.assertionResponse(credentialID: a.credentialID, clientDataJSON: a.rawClientDataJSON, authenticatorData: a.rawAuthenticatorData, signature: a.signature, userHandle: a.userID, platform: false)))120 case let r as ASAuthorizationPlatformPublicKeyCredentialRegistration:121 guard let att = r.rawAttestationObject else { return finish(.failure(PasskeyError.failed("Le système n’a pas fourni d’attestation."))) }122 finish(.success(WebAuthnJSON.registrationResponse(credentialID: r.credentialID, clientDataJSON: r.rawClientDataJSON, attestationObject: att, platform: true)))123 default:124 finish(.failure(PasskeyError.unsupportedCredential))125 }126 }127128 func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {129 let code = (error as? ASAuthorizationError)?.code130 if code == .canceled { finish(.failure(PasskeyError.cancelled)) } else { finish(.failure(PasskeyError.failed(error.localizedDescription))) }131 }132133 func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {134 let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }135 return scenes.first(where: { $0.activationState == .foregroundActive })?.keyWindow ?? scenes.first?.keyWindow ?? ASPresentationAnchor()136 }137}138