SPB Git

Repository Public

PasskeyService.swift 12.4 KB 217 lines swift

1//2//  SP Chat iOS3//  File: SPChat-iOS/Core/Authentication/PasskeyService.swift4//  Description: Passkey ceremonies with AuthenticationServices (sign-in, re-authentication, enrolment), verified by the server.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//910import AuthenticationServices11import Foundation12import UIKit1314struct PasskeyError: Error, LocalizedError, Equatable, Sendable {15    enum Kind: Sendable { case cancelled, refused, notAssociated, network, rateLimited, unsupported }16    var kind: Kind17    var message: String18    var errorDescription: String? { message }19    static let cancelled = PasskeyError(kind: .cancelled, message: String(localized: "Vérification annulée."))20}2122/// WebAuthn request options as sent by the server (`@simplewebauthn/server` JSON form; binary fields are base64url).23struct AssertionOptions: Decodable, Sendable {24    struct Descriptor: Decodable, Sendable { var id: String }25    var challenge: String26    var rpId: String?27    var allowCredentials: [Descriptor]?28}29struct CreationOptions: Decodable, Sendable {30    struct RP: Decodable, Sendable { var id: String?; var name: String }31    struct User: Decodable, Sendable { var id: String; var name: String; var displayName: String? }32    var challenge: String33    var rp: RP34    var user: User35    var excludeCredentials: [AssertionOptions.Descriptor]?36}3738/// The WebAuthn half that runs on the device. iOS shows the system sheet (Face ID, Touch ID or the device passcode,39/// or a nearby device / security key); the app receives a signed assertion and never sees biometric data. The private40/// key stays in the Secure Enclave / iCloud Keychain; the server verifies the signature with the stored public key.41@MainActor42final class PasskeyService: NSObject {43    private let http: HTTPClient44    private let relyingParty: String45    private var continuation: CheckedContinuation<ASAuthorization, Error>?46    private var controller: ASAuthorizationController?4748    init(http: HTTPClient, relyingParty: String) {49        self.http = http50        self.relyingParty = relyingParty51    }5253    // MARK: public ceremonies5455    /// Sign-in: fresh single-use challenge → system passkey sheet → server verification → session cookie (stored by `HTTPClient`).56    func signIn() async throws {57        try await assertion(optionsPath: "/api/auth/login/options", verifyPath: "/api/auth/login/verify")58    }5960    /// Fresh verification for the current session: unlocks sensitive operations for 10 minutes and rotates the session token.61    func reauthenticate() async throws {62        try await assertion(optionsPath: "/api/auth/reauth/options", verifyPath: "/api/auth/reauth/verify")63    }6465    /// Opens a 10-minute enrolment window with a bootstrap or recovery code (never signs in by itself).66    func redeemSetupCode(_ code: String) async throws {67        do { _ = try await http.data(.json("POST", "/api/auth/setup", object: ["code": .string(code.trimmingCharacters(in: .whitespacesAndNewlines))])) }68        catch { throw map(error) }69    }7071    /// Creates a passkey for this device: either inside an enrolment window, or for a signed-in session that verified72    /// a passkey in the last 10 minutes ("add this device").73    func register(label: String?) async throws {74        struct Envelope: Decodable { var options: CreationOptions }75        let options: CreationOptions76        do {77            var req = HTTPRequest.json("POST", "/api/auth/register/options"); req.allowReauth = false78            options = try await http.decode(Envelope.self, req).options79        } catch { throw map(error) }80        guard let challenge = Data(base64URLEncoded: options.challenge), let userID = Data(base64URLEncoded: options.user.id) else { throw PasskeyError(kind: .refused, message: String(localized: "Réponse du serveur illisible.")) }8182        let provider = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: options.rp.id ?? relyingParty)83        let request = provider.createCredentialRegistrationRequest(challenge: challenge, name: options.user.name, userID: userID)84        request.userVerificationPreference = .required85        if #available(iOS 17.4, *) {86            request.excludedCredentials = (options.excludeCredentials ?? []).compactMap { Data(base64URLEncoded: $0.id) }.map(ASAuthorizationPlatformPublicKeyCredentialDescriptor.init(credentialID:))87        }88        let authorization = try await perform([request])89        guard let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration, let attestation = credential.rawAttestationObject else {90            throw PasskeyError(kind: .refused, message: String(localized: "La clé d’accès n’a pas pu être créée."))91        }92        let id = credential.credentialID.base64URLEncodedString()93        var body: [String: JSONValue] = ["response": .object([94            "id": .string(id), "rawId": .string(id), "type": .string("public-key"), "authenticatorAttachment": .string("platform"),95            "clientExtensionResults": .object([:]),96            "response": .object([97                "clientDataJSON": .string(credential.rawClientDataJSON.base64URLEncodedString()),98                "attestationObject": .string(attestation.base64URLEncodedString()),99                "transports": .array([.string("internal"), .string("hybrid")]),100            ]),101        ])]102        if let label, !label.isEmpty { body["label"] = .string(String(label.prefix(60))) }103        do {104            var req = HTTPRequest.json("POST", "/api/auth/register/verify", object: body); req.allowReauth = false105            _ = try await http.data(req)106        } catch { throw map(error) }107    }108109    // MARK: assertion110111    private func assertion(optionsPath: String, verifyPath: String) async throws {112        struct Envelope: Decodable { var options: AssertionOptions }113        let options: AssertionOptions114        do {115            var req = HTTPRequest.json("POST", optionsPath); req.allowReauth = false116            options = try await http.decode(Envelope.self, req).options117        } catch { throw map(error) }118        guard let challenge = Data(base64URLEncoded: options.challenge) else { throw PasskeyError(kind: .refused, message: String(localized: "Réponse du serveur illisible.")) }119        let rp = options.rpId ?? relyingParty120        let allowed = (options.allowCredentials ?? []).compactMap { Data(base64URLEncoded: $0.id) }121122        let platform = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: rp).createCredentialAssertionRequest(challenge: challenge)123        platform.userVerificationPreference = .required124        platform.allowedCredentials = allowed.map(ASAuthorizationPlatformPublicKeyCredentialDescriptor.init(credentialID:))125        let key = ASAuthorizationSecurityKeyPublicKeyCredentialProvider(relyingPartyIdentifier: rp).createCredentialAssertionRequest(challenge: challenge)126        key.userVerificationPreference = .required127        key.allowedCredentials = allowed.map { ASAuthorizationSecurityKeyPublicKeyCredentialDescriptor(credentialID: $0, transports: ASAuthorizationSecurityKeyPublicKeyCredentialDescriptor.Transport.allSupported) }128129        let authorization = try await perform([platform, key])130        let (credentialID, clientData, authenticatorData, signature, userID, attachment): (Data, Data, Data?, Data?, Data?, String)131        switch authorization.credential {132        case let c as ASAuthorizationPlatformPublicKeyCredentialAssertion:133            (credentialID, clientData, authenticatorData, signature, userID, attachment) = (c.credentialID, c.rawClientDataJSON, c.rawAuthenticatorData, c.signature, c.userID, "platform")134        case let c as ASAuthorizationSecurityKeyPublicKeyCredentialAssertion:135            (credentialID, clientData, authenticatorData, signature, userID, attachment) = (c.credentialID, c.rawClientDataJSON, c.rawAuthenticatorData, c.signature, c.userID, "cross-platform")136        default:137            throw PasskeyError(kind: .refused, message: String(localized: "La vérification n’a pas abouti."))138        }139        guard let authenticatorData, let signature else { throw PasskeyError(kind: .refused, message: String(localized: "La vérification n’a pas abouti.")) }140        let id = credentialID.base64URLEncodedString()141        var inner: [String: JSONValue] = [142            "clientDataJSON": .string(clientData.base64URLEncodedString()),143            "authenticatorData": .string(authenticatorData.base64URLEncodedString()),144            "signature": .string(signature.base64URLEncodedString()),145        ]146        if let userID, !userID.isEmpty { inner["userHandle"] = .string(userID.base64URLEncodedString()) }147        let body: [String: JSONValue] = ["response": .object([148            "id": .string(id), "rawId": .string(id), "type": .string("public-key"), "authenticatorAttachment": .string(attachment),149            "clientExtensionResults": .object([:]), "response": .object(inner),150        ])]151        do {152            var req = HTTPRequest.json("POST", verifyPath, object: body); req.allowReauth = false153            _ = try await http.data(req)154        } catch { throw map(error) }155    }156157    // MARK: ASAuthorizationController bridge158159    private func perform(_ requests: [ASAuthorizationRequest]) async throws -> ASAuthorization {160        if continuation != nil { throw PasskeyError(kind: .refused, message: String(localized: "Une vérification est déjà en cours.")) }161        let controller = ASAuthorizationController(authorizationRequests: requests)162        controller.delegate = self163        controller.presentationContextProvider = self164        self.controller = controller165        do {166            return try await withCheckedThrowingContinuation { (c: CheckedContinuation<ASAuthorization, Error>) in167                continuation = c168                controller.performRequests()169            }170        } catch { throw map(error) }171    }172173    private func finish(_ result: Result<ASAuthorization, Error>) {174        let c = continuation; continuation = nil; controller = nil175        c?.resume(with: result)176    }177178    private func map(_ error: Error) -> PasskeyError {179        if let e = error as? PasskeyError { return e }180        if let e = error as? APIError {181            switch e.kind {182            case .network: return PasskeyError(kind: .network, message: String(localized: "Réseau indisponible. Vérifie ta connexion et réessaie."))183            case .rateLimited: return PasskeyError(kind: .rateLimited, message: e.message)184            case .cancelled: return .cancelled185            default: return PasskeyError(kind: .refused, message: e.message)186            }187        }188        if let e = error as? ASAuthorizationError {189            switch e.code {190            case .canceled: return .cancelled191            case .notInteractive: return PasskeyError(kind: .refused, message: String(localized: "La vérification demande une interaction."))192            default:193                let detail = (e.userInfo[NSLocalizedFailureReasonErrorKey] as? String) ?? e.localizedDescription194                if detail.localizedCaseInsensitiveContains("not associated") || detail.localizedCaseInsensitiveContains("associated domain") {195                    return PasskeyError(kind: .notAssociated, message: String(localized: "iOS n’a pas encore associé cette application au domaine \(relyingParty). Réessaie dans quelques minutes (le fichier d’association est mis en cache par Apple)."))196                }197                return PasskeyError(kind: .refused, message: String(localized: "Aucune clé d’accès utilisable, ou vérification refusée."))198            }199        }200        return PasskeyError(kind: .refused, message: String(localized: "La vérification n’a pas abouti."))201    }202}203204extension PasskeyService: ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {205    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {206        finish(.success(authorization))207    }208    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {209        finish(.failure(error))210    }211    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {212        let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }213        let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first214        return scene?.keyWindow ?? scene?.windows.first ?? ASPresentationAnchor()215    }216}217
Files main
Menu

Theme