SPB Git

Repository Public

Passkey.swift 9.4 KB 167 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr SMS Gateway9// File             : ios/MacLustrSMS/Core/Passkey.swift10// Description      : Clés d'accès du système (AuthenticationServices) pour le11//                    domaine sms.spboucher.ai : connexion et enrôlement.12// Module           : ios13// Repository       : https://git.spboucher.ai/maclustr-sms14// Project Website  : https://sms.spboucher.ai15// Created          : 2026-11-3016// Last Modified    : 2026-11-3017//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author           : Simon-Pierre Boucher23// Position         : Professor of Finance24// Institution      : Université du Québec en Outaouais (UQO)25// Department       : Département des sciences administratives26// Organization     : SP Boucher27//28// Website          : https://spboucher.ai29// Git              : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General          : info@spboucher.ai36// Professional     : contact@spboucher.ai37// Direct           : simon@spboucher.ai38// Research         : research@spboucher.ai39// Development      : dev@spboucher.ai40// Support          : support@spboucher.ai41// Security/Admin   : admin@spboucher.ai42// Notifications    : notifications@spboucher.ai43//44// Preferred Contact: admin@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification   : Public69// Distribution     : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License          : None specified (no license file in this repository)83// Maintainer       : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import AuthenticationServices91import UIKit9293extension Data {94    init?(base64URL s: String) {95        var b = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")96        while b.count % 4 != 0 { b += "=" }97        self.init(base64Encoded: b)98    }99    var base64URL: String { base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") }100}101102enum PasskeyError: LocalizedError {103    case cancelled, notAssociated, failed(String), malformedOptions104    var errorDescription: String? {105        switch self {106        case .cancelled: nil107        case .notAssociated: "Cet iPhone n'a pas encore validé l'association entre l'application et sms.spboucher.ai. Réessayez dans quelques minutes (ou réinstallez l'application) ; si l'erreur persiste, créez la clé d'accès dans Safari avec le lien d'enrôlement."108        case .failed(let m): m109        case .malformedOptions: "Réponse du serveur inattendue."110        }111    }112}113114/// Extrait le jeton d'un lien d'enrôlement (https://sms.spboucher.ai/enroll#<jeton>) ou accepte le jeton seul.115enum EnrollmentLink {116    static func token(from input: String) -> String? {117        let t = input.trimmingCharacters(in: .whitespacesAndNewlines)118        let raw = t.contains("#") ? String(t.split(separator: "#", maxSplits: 1, omittingEmptySubsequences: false).last ?? "") : t119        return raw.count >= 20 && raw.count <= 120 && raw.allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_") }) ? raw : nil120    }121}122123@MainActor124final class PasskeyCoordinator: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {125    private var continuation: CheckedContinuation<ASAuthorization, Error>?126    private func perform(_ request: ASAuthorizationRequest) async throws -> ASAuthorization {127        let controller = ASAuthorizationController(authorizationRequests: [request])128        controller.delegate = self129        controller.presentationContextProvider = self130        return try await withCheckedThrowingContinuation { c in continuation = c; controller.performRequests() }131    }132    nonisolated func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {133        MainActor.assumeIsolated { UIApplication.shared.connectedScenes.compactMap { ($0 as? UIWindowScene)?.keyWindow }.first ?? ASPresentationAnchor() }134    }135    nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {136        nonisolated(unsafe) let a = authorization137        Task { @MainActor in continuation?.resume(returning: a); continuation = nil }138    }139    nonisolated func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {140        let ns = error as NSError141        let mapped: PasskeyError = ns.code == ASAuthorizationError.canceled.rawValue ? .cancelled142            : (ns.code == 1004 || ns.localizedDescription.localizedCaseInsensitiveContains("associated")) ? .notAssociated143            : .failed("La clé d'accès n'a pas pu être utilisée (\(ns.code)).")144        Task { @MainActor in continuation?.resume(throwing: mapped); continuation = nil }145    }146147    /// Connexion : défi du serveur → assertion → réponse au format WebAuthn JSON attendu par le serveur.148    func assertion(options: [String: Any]) async throws -> [String: Any] {149        guard let challenge = (options["challenge"] as? String).flatMap(Data.init(base64URL:)), let rpId = options["rpId"] as? String else { throw PasskeyError.malformedOptions }150        let request = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: rpId).createCredentialAssertionRequest(challenge: challenge)151        request.userVerificationPreference = .required152        guard let c = try await perform(request).credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion else { throw PasskeyError.failed("Réponse inattendue du système.") }153        return ["id": c.credentialID.base64URL, "rawId": c.credentialID.base64URL, "type": "public-key", "clientExtensionResults": [String: Any](), "authenticatorAttachment": "platform",154                "response": ["clientDataJSON": c.rawClientDataJSON.base64URL, "authenticatorData": c.rawAuthenticatorData.base64URL, "signature": c.signature.base64URL, "userHandle": c.userID.base64URL]]155    }156    /// Enrôlement : création d'une clé d'accès liée au compte désigné par le lien à usage unique.157    func registration(options: [String: Any]) async throws -> [String: Any] {158        guard let challenge = (options["challenge"] as? String).flatMap(Data.init(base64URL:)), let rp = options["rp"] as? [String: Any], let rpId = rp["id"] as? String,159              let user = options["user"] as? [String: Any], let userId = (user["id"] as? String).flatMap(Data.init(base64URL:)), let name = user["name"] as? String else { throw PasskeyError.malformedOptions }160        let request = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: rpId).createCredentialRegistrationRequest(challenge: challenge, name: name, userID: userId)161        request.userVerificationPreference = .required162        guard let c = try await perform(request).credential as? ASAuthorizationPlatformPublicKeyCredentialRegistration, let att = c.rawAttestationObject else { throw PasskeyError.failed("Réponse inattendue du système.") }163        return ["id": c.credentialID.base64URL, "rawId": c.credentialID.base64URL, "type": "public-key", "clientExtensionResults": [String: Any](), "authenticatorAttachment": "platform",164                "response": ["clientDataJSON": c.rawClientDataJSON.base64URL, "attestationObject": att.base64URL, "transports": ["internal", "hybrid"]]]165    }166}167
Files main
Menu

Theme