Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : MacLustr Identity9// File : sdk/swift/Sources/MacLustrIdentityUI/IdentityWebFlow.swift10// Module : MacLustrIdentityUI11// Repository : https://git.spboucher.ai/maclustr-identity12// Project Website : https://identity.spboucher.ai13// Created : 2026-12-0114// Last Modified : 2026-12-0115//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: admin@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788// Zero-UI alternative: the hosted web page of the session, for apps that prefer the web flow.89import AuthenticationServices90import Foundation91import MacLustrIdentityCore92#if canImport(SafariServices) && os(iOS)93import SafariServices94#endif9596public enum IdentityWebFlowResult: Equatable, Sendable {97 /// The page redirected to the session's `return_url` (custom scheme given as `callbackURLScheme`).98 case returned(URL)99 /// The person closed the page.100 case dismissed101 /// macOS without a callback scheme: the page was opened in the default browser; the app is not told when it ends.102 case openedInBrowser103 /// The page could not be presented.104 case failed105}106107/// Presents `https://…/verify/{id}#{client_secret}`.108///109/// - With `callbackURLScheme`: `ASWebAuthenticationSession`, which ends when the page navigates to a URL of that110/// scheme. The session's `return_url` must use it and be registered in the application's allowed redirect URLs.111/// - Without: `SFSafariViewController` on iOS (ends when the person taps Done), the default browser on macOS.112///113/// As with the native flow, the result is for user experience only: ask your backend for the outcome.114@MainActor115public final class IdentityWebFlow: NSObject {116 private var authSession: ASWebAuthenticationSession?117 private var completion: ((IdentityWebFlowResult) -> Void)?118 private static var active: IdentityWebFlow?119120 /// Starts the web flow. Returns false when nothing could be presented.121 @discardableResult122 public static func start(session: IdentitySession, callbackURLScheme: String? = nil, completion: @escaping (IdentityWebFlowResult) -> Void) -> Bool {123 let flow = IdentityWebFlow()124 flow.completion = completion125 active = flow126 return flow.present(session.hostedURL, scheme: callbackURLScheme)127 }128129 private func finish(_ result: IdentityWebFlowResult) {130 let done = completion131 completion = nil132 authSession = nil133 if IdentityWebFlow.active === self { IdentityWebFlow.active = nil }134 done?(result)135 }136137 private func present(_ url: URL, scheme: String?) -> Bool {138 if let scheme {139 let s = ASWebAuthenticationSession(url: url, callbackURLScheme: scheme) { [weak self] callback, _ in140 Task { @MainActor in self?.finish(callback.map(IdentityWebFlowResult.returned) ?? .dismissed) }141 }142 s.presentationContextProvider = self143 s.prefersEphemeralWebBrowserSession = true144 authSession = s145 if s.start() { return true }146 finish(.failed)147 return false148 }149 #if os(iOS)150 guard let top = IdentityWebFlow.topViewController() else { finish(.failed); return false }151 let config = SFSafariViewController.Configuration()152 config.entersReaderIfAvailable = false153 let safari = SFSafariViewController(url: url, configuration: config)154 safari.delegate = self155 safari.dismissButtonStyle = .close156 top.present(safari, animated: true)157 return true158 #else159 let opened = NSWorkspace.shared.open(url)160 finish(opened ? .openedInBrowser : .failed)161 return opened162 #endif163 }164165 #if os(iOS)166 private static func topViewController() -> UIViewController? {167 let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first { $0.activationState == .foregroundActive }168 var top = scene?.windows.first { $0.isKeyWindow }?.rootViewController169 while let presented = top?.presentedViewController { top = presented }170 return top171 }172 #endif173}174175extension IdentityWebFlow: ASWebAuthenticationPresentationContextProviding {176 public nonisolated func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor {177 MainActor.assumeIsolated {178 #if os(iOS)179 let scene = UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene }.first { $0.activationState == .foregroundActive }180 return scene?.windows.first { $0.isKeyWindow } ?? ASPresentationAnchor()181 #else182 return NSApp.keyWindow ?? NSApp.windows.first ?? ASPresentationAnchor()183 #endif184 }185 }186}187188#if os(iOS)189extension IdentityWebFlow: SFSafariViewControllerDelegate {190 public nonisolated func safariViewControllerDidFinish(_ controller: SFSafariViewController) {191 Task { @MainActor in self.finish(.dismissed) }192 }193}194#endif195