import AuthenticationServices import CryptoKit import Security import SwiftUI import UIKit // iOS 17.4+. The app owns callbackURL's associated domain; Cmine ID owns issuer. @MainActor public final class CmineAuth: NSObject, ObservableObject, ASWebAuthenticationPresentationContextProviding { public struct Configuration { public let clientID: String public let callbackURL: URL public let issuer: URL public init(clientID: String, callbackURL: URL, issuer: URL = URL(string: "https://identity.chwjh.com")!) { self.clientID = clientID; self.callbackURL = callbackURL; self.issuer = issuer } } public struct Profile: Decodable { public let sub: String; public let name: String?; public let email: String? } private struct Tokens: Codable { let access_token: String; let refresh_token: String?; let token_type: String; let expires_in: Int } private struct Transaction { let id: UUID; let state: String; let verifier: String; let started: Date } public enum Failure: Error { case invalidConfiguration, alreadyRunning, random, badCallback, expired, cancelled, network, server, secureStorage } @Published public private(set) var profile: Profile? @Published public private(set) var busy = false @Published public private(set) var message = "" private let config: Configuration private let storageKey: String private var transaction: Transaction? private var session: ASWebAuthenticationSession? private var window: ASPresentationAnchor? public init(configuration: Configuration) { config = configuration; storageKey = "cn.cmine.tokens." + configuration.clientID super.init() } public func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { window! } public func signIn(from window: ASPresentationAnchor) { guard !busy else { return } do { guard config.issuer.scheme == "https", config.issuer.host != nil, config.issuer.user == nil, config.issuer.query == nil, config.issuer.fragment == nil, ["", "/"].contains(config.issuer.path), !config.clientID.isEmpty, config.callbackURL.scheme == "https", config.callbackURL.host != nil, config.callbackURL.user == nil, config.callbackURL.port == nil, config.callbackURL.query == nil, config.callbackURL.fragment == nil else { throw Failure.invalidConfiguration } let verifier = try Self.random(), state = try Self.random() let id = UUID() transaction = Transaction(id: id, state: state, verifier: verifier, started: Date()) var url = URLComponents(url: config.issuer.appendingPathComponent("oauth/authorize"), resolvingAgainstBaseURL: false)! url.queryItems = ["response_type":"code", "client_id":config.clientID, "redirect_uri":config.callbackURL.absoluteString, "scope":"openid profile email offline_access", "state":state, "code_challenge":Self.base64url(Data(SHA256.hash(data: Data(verifier.utf8)))), "code_challenge_method":"S256", "display":"touch"].map { URLQueryItem(name:$0.key,value:$0.value) } self.window = window; busy = true; message = "正在打开 Cmine ID" session = ASWebAuthenticationSession(url: url.url!, callback: .https(host: config.callbackURL.host!, path: config.callbackURL.path)) { [weak self] callback, error in Task { @MainActor in guard let self, self.transaction?.id == id else { return } if error != nil { self.finish("登录已取消,可以重新开始。"); return } guard let callback else { self.finish("未收到应用回调,请重新登录。"); return } await self.consume(callback) } } session?.presentationContextProvider = self session?.prefersEphemeralWebBrowserSession = false if session?.start() != true { finish("无法打开系统认证窗口,请重试。"); } } catch { finish("登录配置或安全存储暂不可用,请检查后重试。"); } } // Forward .onOpenURL and NSUserActivityTypeBrowsingWeb here as a fallback. public func handle(_ url: URL) { Task { await consume(url) } } private func consume(_ url: URL) async { guard let tx = transaction else { if !busy { message = "没有待完成的登录,请重新发起。" }; return } do { guard (0..<300).contains(Date().timeIntervalSince(tx.started)) else { throw Failure.expired } guard url.scheme == config.callbackURL.scheme, url.host == config.callbackURL.host, url.port == config.callbackURL.port, url.path == config.callbackURL.path, url.user == nil, url.password == nil, url.fragment == nil else { throw Failure.badCallback } let items = URLComponents(url:url,resolvingAgainstBaseURL:false)?.queryItems ?? [] guard ["code", "state", "error"].allSatisfy({ key in items.filter { $0.name == key }.count <= 1 }) else { throw Failure.badCallback } func one(_ key: String) -> String? { let values = items.filter { $0.name == key }; return values.count == 1 ? values[0].value : nil } guard one("state") == tx.state else { throw Failure.badCallback } // Consume locally before asynchronous work; duplicate OS callbacks cannot exchange twice. transaction = nil; session?.cancel(); session = nil if one("error") != nil { throw Failure.cancelled } guard let code = one("code"), !code.isEmpty else { throw Failure.badCallback } message = "正在完成登录" let tokens: Tokens = try await request(path:"oauth/token", form:["grant_type":"authorization_code", "client_id":config.clientID,"code":code,"code_verifier":tx.verifier,"redirect_uri":config.callbackURL.absoluteString]) guard tokens.token_type.lowercased() == "bearer", !tokens.access_token.isEmpty else { throw Failure.server } // ID tokens are intentionally not decoded or treated as verified identity here. // UserInfo over issuer HTTPS validates the access token on the server. let user: Profile = try await request(path:"oauth/userinfo", bearer:tokens.access_token) guard !user.sub.isEmpty else { throw Failure.server } try save(tokens); profile = user; busy = false; message = "已使用 Cmine ID 登录" } catch Failure.cancelled { finish("你已取消授权,可以重新登录。"); } catch Failure.expired { finish("本次登录已过期,请重新开始。"); } catch { finish("未能完成登录,请检查网络后重新开始。"); } } public func refresh() async { guard !busy else { return }; busy = true do { guard let previous = try load(), let refresh = previous.refresh_token else { throw Failure.expired } let tokens: Tokens = try await request(path:"oauth/token",form:["grant_type":"refresh_token","client_id":config.clientID,"refresh_token":refresh]) // Persist the rotated token BEFORE another refresh can start. Never retry an old token. try save(tokens) profile = try await request(path:"oauth/userinfo",bearer:tokens.access_token) busy = false; message = "登录状态已更新" } catch { try? clear(); profile = nil; finish("登录状态需要更新,请重新登录。"); } } public func cancel() { guard transaction != nil || session != nil else { return }; transaction = nil; session?.cancel(); session = nil; busy = false; message = "登录已取消" } public func signOut() async { guard !busy else { return }; busy = true if let tokens = try? load(), let refresh = tokens.refresh_token { var request = URLRequest(url:config.issuer.appendingPathComponent("oauth/revoke")) request.httpMethod = "POST"; request.httpBody = Self.form(["token":refresh,"client_id":config.clientID]) request.setValue("application/x-www-form-urlencoded",forHTTPHeaderField:"Content-Type") _ = try? await URLSession.shared.data(for:request) } try? clear(); profile = nil; busy = false; message = "已退出此 App,Cmine ID 浏览器会话仍可用于其他 App。" } private func finish(_ text: String) { transaction = nil; session = nil; busy = false; message = text } private func request(path: String, form: [String:String]? = nil, bearer: String? = nil) async throws -> T { var request = URLRequest(url:config.issuer.appendingPathComponent(path)); request.timeoutInterval = 25 if let form { request.httpMethod = "POST"; request.httpBody = Self.form(form); request.setValue("application/x-www-form-urlencoded",forHTTPHeaderField:"Content-Type") } if let bearer { request.setValue("Bearer " + bearer,forHTTPHeaderField:"Authorization") } let configuration = URLSessionConfiguration.ephemeral let client = URLSession(configuration:configuration); defer { client.finishTasksAndInvalidate() } let (data,response) = try await client.data(for:request, delegate: RejectRedirects()) guard let response = response as? HTTPURLResponse, response.statusCode == 200, response.url?.host == config.issuer.host, response.url?.scheme == "https" else { throw Failure.server } return try JSONDecoder().decode(T.self,from:data) } private static func random() throws -> String { var bytes = [UInt8](repeating:0,count:32); guard SecRandomCopyBytes(kSecRandomDefault,bytes.count,&bytes) == errSecSuccess else { throw Failure.random }; return base64url(Data(bytes)) } static func base64url(_ data: Data) -> String { data.base64EncodedString().replacingOccurrences(of:"+",with:"-").replacingOccurrences(of:"/",with:"_").replacingOccurrences(of:"=",with:"") } static func form(_ values:[String:String]) -> Data { let chars = CharacterSet(charactersIn:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"); return values.sorted{$0.key<$1.key}.map { $0.key.addingPercentEncoding(withAllowedCharacters:chars)! + "=" + $0.value.addingPercentEncoding(withAllowedCharacters:chars)! }.joined(separator:"&").data(using:.utf8)! } private func query() -> [String:Any] { [kSecClass as String:kSecClassGenericPassword,kSecAttrService as String:storageKey,kSecAttrAccount as String:"tokens"] } private func save(_ tokens: Tokens) throws { let data = try JSONEncoder().encode(tokens), q = query() let update = SecItemUpdate(q as CFDictionary,[kSecValueData as String:data] as CFDictionary) if update == errSecItemNotFound { var add = q; add[kSecValueData as String] = data; add[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly; guard SecItemAdd(add as CFDictionary,nil) == errSecSuccess else { throw Failure.secureStorage } } else if update != errSecSuccess { throw Failure.secureStorage } } private func load() throws -> Tokens? { var q = query(); q[kSecReturnData as String] = true; q[kSecMatchLimit as String] = kSecMatchLimitOne var result: CFTypeRef?; let status = SecItemCopyMatching(q as CFDictionary,&result) if status == errSecItemNotFound { return nil }; guard status == errSecSuccess, let data = result as? Data else { throw Failure.secureStorage } return try JSONDecoder().decode(Tokens.self,from:data) } private func clear() throws { let status = SecItemDelete(query() as CFDictionary); guard status == errSecSuccess || status == errSecItemNotFound else { throw Failure.secureStorage } } } private final class RejectRedirects: NSObject, URLSessionTaskDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) } } public struct CmineSignInButton: View { let action: () -> Void public init(action: @escaping () -> Void) { self.action = action } public var body: some View { Button(action:action) { HStack(spacing:10) { Text("c").font(.system(size:23,weight:.bold)).frame(width:25,height:25).background(.white,in:RoundedRectangle(cornerRadius:8)).foregroundStyle(.black); Text("使用 Cmine ID 登录").font(.system(size:16,weight:.medium)) }.frame(maxWidth:.infinity,minHeight:50).foregroundStyle(.white).background(Color(white:0.11),in:RoundedRectangle(cornerRadius:13)) }.buttonStyle(.plain).accessibilityLabel("使用 Cmine ID 登录") } }