SPB Git

Repository Public

PasskeyService.swift 13.1 KB 223 lines swift

1//2//  VQuant iOS3//  File: VQuant/Auth/PasskeyService.swift4//  Description: Passkey ceremonies with AuthenticationServices against the VQuant native bridge (`/api/native/*`):5//               sign-in, enrolment from an invitation, and fresh verification before sensitive operations.6//7//  Author: Simon-Pierre Boucher8//  Contact: contact@spboucher.ai9//1011import AuthenticationServices12import Foundation13import UIKit1415struct PasskeyError: Error, LocalizedError, Equatable, Sendable {16    enum Kind: Sendable { case cancelled, refused, notAssociated, network, rateLimited, expiredInvite }17    var kind: Kind18    var message: String19    var errorDescription: String? { message }20    static let cancelled = PasskeyError(kind: .cancelled, message: "Vérification annulée.")21}2223/// WebAuthn options as sent by `@simplewebauthn/server` (binary fields are base64url).24struct AssertionOptions: Decodable, Sendable {25    struct Descriptor: Decodable, Sendable { var id: String }26    var challenge: String27    var rpId: String?28    var allowCredentials: [Descriptor]?29}30struct CreationOptions: Decodable, Sendable {31    struct RP: Decodable, Sendable { var id: String?; var name: String }32    struct User: Decodable, Sendable { var id: String; var name: String; var displayName: String? }33    var challenge: String34    var rp: RP35    var user: User36    var excludeCredentials: [AssertionOptions.Descriptor]?37}3839extension Data {40    init?(base64URLEncoded s: String) {41        var t = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")42        while t.count % 4 != 0 { t.append("=") }43        self.init(base64Encoded: t)44    }45    func base64URLEncodedString() -> String {46        base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")47    }48}4950/// The device half of WebAuthn. iOS shows the system sheet (Face ID, Touch ID or the device passcode; a nearby device51/// or a security key also work); the app receives a signed assertion and never sees biometric data. The server52/// verifies the signature against the public key it stored when the passkey was created — the same passkeys as53/// vquant.spboucher.ai, because the relying party is the same and the app is listed in the site's54/// apple-app-site-association file (`webcredentials`).55@MainActor56final class PasskeyService: NSObject {57    private let client: APIClient58    private let relyingParty: String59    private var continuation: CheckedContinuation<ASAuthorization, Error>?60    private var controller: ASAuthorizationController?6162    init(client: APIClient, relyingParty: String) {63        self.client = client64        self.relyingParty = relyingParty65    }6667    // MARK: ceremonies6869    /// Sign-in with an existing VQuant passkey → device session.70    func signIn(deviceName: String) async throws -> SignInResult {71        let options: AssertionOptions = try await call { try await self.client.decode(.send("POST", "/api/native/login/options")) }72        let response = try await assert(options)73        return try await call {74            try await self.client.decode(try .json("POST", "/api/native/login/verify", JSONValue.object(["response": response, "device": .object(["name": .string(deviceName)])])))75        }76    }7778    /// Creates a passkey for this device from a single-use invitation (`/setup/<token>`), then signs in.79    func enrol(inviteToken: String, deviceName: String) async throws -> SignInResult {80        let options: CreationOptions = try await call { try await self.client.decode(try .json("POST", "/api/native/register/options", ["token": inviteToken])) }81        guard let challenge = Data(base64URLEncoded: options.challenge), let userID = Data(base64URLEncoded: options.user.id) else { throw unreadable }82        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        request.excludedCredentials = (options.excludeCredentials ?? []).compactMap { Data(base64URLEncoded: $0.id) }.map(ASAuthorizationPlatformPublicKeyCredentialDescriptor.init(credentialID:))86        let authorization = try await perform([request])87        guard let credential = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration, let attestation = credential.rawAttestationObject else {88            throw PasskeyError(kind: .refused, message: "La clé d’accès n’a pas pu être créée.")89        }90        let id = credential.credentialID.base64URLEncodedString()91        let response: JSONValue = .object([92            "id": .string(id), "rawId": .string(id), "type": .string("public-key"), "authenticatorAttachment": .string("platform"),93            "clientExtensionResults": .object([:]),94            "response": .object([95                "clientDataJSON": .string(credential.rawClientDataJSON.base64URLEncodedString()),96                "attestationObject": .string(attestation.base64URLEncodedString()),97                "transports": .array([.string("internal"), .string("hybrid")]),98            ]),99        ])100        return try await call {101            try await self.client.decode(try .json("POST", "/api/native/register/verify",102                                                   JSONValue.object(["token": .string(inviteToken), "response": response, "device": .object(["name": .string(deviceName)])])))103        }104    }105106    /// Fresh passkey verification for the signed-in device: the server then accepts sensitive operations107    /// (revoking a device or a passkey) for five minutes.108    func reauthenticate() async throws {109        let options: AssertionOptions = try await call { try await self.client.decode(.send("POST", "/api/native/reauth/options")) }110        let response = try await assert(options)111        _ = try await call { try await self.client.data(try .json("POST", "/api/native/reauth/verify", JSONValue.object(["response": response]))) }112    }113114    // MARK: assertion115116    private var unreadable: PasskeyError { PasskeyError(kind: .refused, message: "Réponse du serveur illisible.") }117118    private func assert(_ options: AssertionOptions) async throws -> JSONValue {119        guard let challenge = Data(base64URLEncoded: options.challenge) else { throw unreadable }120        let rp = options.rpId ?? relyingParty121        let allowed = (options.allowCredentials ?? []).compactMap { Data(base64URLEncoded: $0.id) }122        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: Data, clientData: Data, authenticatorData: Data?, signature: Data?, userID: Data?, attachment: String131        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: "La vérification n’a pas abouti.")138        }139        guard let authenticatorData, let signature else { throw PasskeyError(kind: .refused, message: "La vérification n’a pas abouti.") }140        return Self.assertionJSON(credentialID: credentialID, clientData: clientData, authenticatorData: authenticatorData, signature: signature, userID: userID, attachment: attachment)141    }142143    /// The `AuthenticationResponseJSON` the server's verifier expects.144    nonisolated static func assertionJSON(credentialID: Data, clientData: Data, authenticatorData: Data, signature: Data, userID: Data?, attachment: String) -> JSONValue {145        let id = credentialID.base64URLEncodedString()146        var inner: [String: JSONValue] = [147            "clientDataJSON": .string(clientData.base64URLEncodedString()),148            "authenticatorData": .string(authenticatorData.base64URLEncodedString()),149            "signature": .string(signature.base64URLEncodedString()),150        ]151        if let userID, !userID.isEmpty { inner["userHandle"] = .string(userID.base64URLEncodedString()) }152        return .object(["id": .string(id), "rawId": .string(id), "type": .string("public-key"), "authenticatorAttachment": .string(attachment),153                        "clientExtensionResults": .object([:]), "response": .object(inner)])154    }155156    // MARK: ASAuthorizationController bridge157158    private func call<T: Sendable>(_ work: @Sendable () async throws -> T) async throws -> T {159        do { return try await work() } catch { throw map(error) }160    }161162    private func perform(_ requests: [ASAuthorizationRequest]) async throws -> ASAuthorization {163        if continuation != nil { throw PasskeyError(kind: .refused, message: "Une vérification est déjà en cours.") }164        let controller = ASAuthorizationController(authorizationRequests: requests)165        controller.delegate = self166        controller.presentationContextProvider = self167        self.controller = controller168        do {169            return try await withCheckedThrowingContinuation { (c: CheckedContinuation<ASAuthorization, Error>) in170                continuation = c171                controller.performRequests()172            }173        } catch { throw map(error) }174    }175176    private func finish(_ result: Result<ASAuthorization, Error>) {177        let c = continuation; continuation = nil; controller = nil178        c?.resume(with: result)179    }180181    func map(_ error: Error) -> PasskeyError {182        if let e = error as? PasskeyError { return e }183        if let e = error as? APIError {184            switch e.kind {185            case .network, .offline: return PasskeyError(kind: .network, message: "Réseau indisponible. Vérifiez la connexion et réessayez.")186            case .rateLimited: return PasskeyError(kind: .rateLimited, message: e.message)187            case .cancelled: return .cancelled188            case .notFound where e.status == 410: return PasskeyError(kind: .expiredInvite, message: "Ce lien d’invitation a expiré ou a déjà servi. Demandez-en un nouveau.")189            case .unauthorized: return PasskeyError(kind: .refused, message: "Le serveur n’a pas reconnu cette clé d’accès.")190            default: return PasskeyError(kind: .refused, message: e.message)191            }192        }193        if let e = error as? ASAuthorizationError {194            switch e.code {195            case .canceled: return .cancelled196            default:197                let detail = (e.userInfo[NSLocalizedFailureReasonErrorKey] as? String) ?? e.localizedDescription198                if detail.localizedCaseInsensitiveContains("not associated") || detail.localizedCaseInsensitiveContains("associated domain") {199                    return PasskeyError(kind: .notAssociated, message: "iOS n’a pas encore associé cette application au domaine \(relyingParty). Réessayez dans quelques minutes (Apple met le fichier d’association en cache).")200                }201                return PasskeyError(kind: .refused, message: "Aucune clé d’accès utilisable sur cet appareil, ou vérification refusée.")202            }203        }204        return PasskeyError(kind: .refused, message: "La vérification n’a pas abouti.")205    }206}207208extension PasskeyService: ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {209    nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {210        Task { @MainActor in self.finish(.success(authorization)) }211    }212    nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {213        Task { @MainActor in self.finish(.failure(error)) }214    }215    nonisolated func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {216        MainActor.assumeIsolated {217            let scenes = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }218            let scene = scenes.first { $0.activationState == .foregroundActive } ?? scenes.first219            return scene?.keyWindow ?? scene?.windows.first ?? ASPresentationAnchor()220        }221    }222}223
Files main
Menu

Theme