SPB Git

Repository Public

PasskeySignIn.swift 7.1 KB 137 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : SP Music pour macOS9// File             : App/Integration/PasskeySignIn.swift10// Description      : Passkey assertion through AuthenticationServices (Touch11//                    ID, iCloud Keychain, nearby iPhone, security key).12// Module           : App13// Repository       : https://git.spboucher.ai/sp-music-macos14// Created          : 2026-11-1815// Last Modified    : 2026-11-1816//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author           : Simon-Pierre Boucher22// Position         : Professor of Finance23// Institution      : Université du Québec en Outaouais (UQO)24// Department       : Département des sciences administratives25// Organization     : SP Boucher26//27// Website          : https://spboucher.ai28// Git              : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General          : info@spboucher.ai35// Professional     : contact@spboucher.ai36// Direct           : simon@spboucher.ai37// Research         : research@spboucher.ai38// Development      : dev@spboucher.ai39// Support          : support@spboucher.ai40// Security/Admin   : admin@spboucher.ai41// Notifications    : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification   : Public68// Distribution     : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License          : None specified (no license file in this repository)82// Maintainer       : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import AppKit90import AuthenticationServices9192/// Asks the system for a passkey assertion for the site's relying party (Touch ID, iCloud Keychain, a nearby93/// iPhone, a security key). The private key never leaves the authenticator; the app only relays the signature.94final class PasskeySignIn: NSObject, ASAuthorizationControllerDelegate, ASAuthorizationControllerPresentationContextProviding {95    struct Assertion { let credentialID: Data; let clientDataJSON: Data; let authenticatorData: Data; let signature: Data; let userHandle: Data? }96    enum Failure: Error { case cancelled, notAssociated, failed(String) }9798    private var continuation: CheckedContinuation<Assertion, Error>?99    private var controller: ASAuthorizationController?100101    func assert(challenge: Data, relyingParty: String) async throws -> Assertion {102        let request = ASAuthorizationPlatformPublicKeyCredentialProvider(relyingPartyIdentifier: relyingParty).createCredentialAssertionRequest(challenge: challenge)103        request.userVerificationPreference = .required104        let securityKey = ASAuthorizationSecurityKeyPublicKeyCredentialProvider(relyingPartyIdentifier: relyingParty).createCredentialAssertionRequest(challenge: challenge)105        securityKey.userVerificationPreference = .required106        let c = ASAuthorizationController(authorizationRequests: [request, securityKey])107        c.delegate = self; c.presentationContextProvider = self108        controller = c109        return try await withCheckedThrowingContinuation { cont in110            continuation = cont111            c.performRequests()112        }113    }114115    func presentationAnchor(for controller: ASAuthorizationController) -> ASPresentationAnchor {116        NSApp.keyWindow ?? NSApp.mainWindow ?? NSApp.windows.first ?? ASPresentationAnchor()117    }118119    func authorizationController(controller: ASAuthorizationController, didCompleteWithAuthorization authorization: ASAuthorization) {120        defer { continuation = nil; self.controller = nil }121        if let c = authorization.credential as? ASAuthorizationPlatformPublicKeyCredentialAssertion {122            continuation?.resume(returning: Assertion(credentialID: c.credentialID, clientDataJSON: c.rawClientDataJSON, authenticatorData: c.rawAuthenticatorData, signature: c.signature, userHandle: c.userID))123        } else if let c = authorization.credential as? ASAuthorizationSecurityKeyPublicKeyCredentialAssertion {124            continuation?.resume(returning: Assertion(credentialID: c.credentialID, clientDataJSON: c.rawClientDataJSON, authenticatorData: c.rawAuthenticatorData, signature: c.signature, userHandle: c.userID))125        } else { continuation?.resume(throwing: Failure.failed("réponse inattendue du système")) }126    }127128    func authorizationController(controller: ASAuthorizationController, didCompleteWithError error: Error) {129        defer { continuation = nil; self.controller = nil }130        let e = error as NSError131        if e.domain == ASAuthorizationError.errorDomain, e.code == ASAuthorizationError.canceled.rawValue { continuation?.resume(throwing: Failure.cancelled); return }132        // 1004: the system could not associate this copy of the app with the domain (no entitlement, or not installed in /Applications).133        if e.code == 1004 || e.localizedDescription.localizedCaseInsensitiveContains("not associated") { continuation?.resume(throwing: Failure.notAssociated); return }134        continuation?.resume(throwing: Failure.failed(e.localizedDescription))135    }136}137
Files main
Menu

Theme