import AuthenticationServices import CryptoKit import Foundation import Observation import Security import UIKit struct AtlasError: LocalizedError { let message: String var errorDescription: String? { message } init(_ message: String) { self.message = message } } struct AtlasEndpoints { let api: URL let issuer: URL static let client = "atlas-ios" static let scheme = "com.tutudog.itematlas" static let redirect = "\(scheme):/oauth2/callback" init() throws { func endpoint(_ key: String) throws -> URL { guard let string = Bundle.main.object(forInfoDictionaryKey: key) as? String, let url = URL(string: string), url.scheme == "https", url.host != nil, url.user == nil, url.password == nil, url.query == nil, url.fragment == nil else { throw AtlasError("登录或接口地址未配置。") } return url } api = try endpoint("AtlasAPIBaseURL") issuer = try endpoint("AtlasOIDCIssuer") } } private struct OIDCMetadata: Decodable { let issuer: URL let authorization_endpoint: URL let token_endpoint: URL let revocation_endpoint: URL? } private struct Grant: Codable { let access_token: String let refresh_token: String let expires_in: Double } private struct SessionTokens: Codable { let grant: Grant let expires: Date } private struct Problem: Decodable { let detail: String? } private struct GrantError: Decodable { let error: String } private final class NoRedirects: NSObject, URLSessionTaskDelegate { func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void) { completionHandler(nil) } } @MainActor @Observable final class AtlasAccount { enum SignInProgress { case connecting case authenticating case finishing var title: String { switch self { case .connecting: "正在连接…" case .authenticating: "等待登录…" case .finishing: "正在完成登录…" } } } private static let identityTimeout: TimeInterval = 15 private(set) var signedIn = false private(set) var signInProgress: SignInProgress? private(set) var error: String? private let configuration = try? AtlasEndpoints() private let http: URLSession private var tokens: SessionTokens? private var metadata: OIDCMetadata? private var refreshTask: Task? private var generation = UUID() private let browser = LoginBrowser() init() { let config = URLSessionConfiguration.ephemeral config.urlCache = nil config.httpShouldSetCookies = false config.timeoutIntervalForRequest = 85 http = URLSession(configuration: config, delegate: NoRedirects(), delegateQueue: nil) if let configuration { do { tokens = try TokenKeychain.read(key: configuration.issuer.absoluteString) signedIn = tokens != nil } catch { self.error = error.localizedDescription } } } func signIn() async { guard signInProgress == nil else { return } signInProgress = .connecting error = nil defer { signInProgress = nil } do { guard let configuration else { throw AtlasError("登录服务地址未配置。") } let discovery = try await discover(configuration) let verifier = try Self.randomString() let state = try Self.randomString() let challenge = Self.base64URL(Data(SHA256.hash(data: Data(verifier.utf8)))) guard var url = URLComponents(url: discovery.authorization_endpoint, resolvingAgainstBaseURL: false) else { throw AtlasError("登录地址无效。") } url.queryItems = [ .init(name: "client_id", value: AtlasEndpoints.client), .init(name: "response_type", value: "code"), .init(name: "scope", value: "openid profile"), .init(name: "redirect_uri", value: AtlasEndpoints.redirect), .init(name: "state", value: state), .init(name: "code_challenge_method", value: "S256"), .init(name: "code_challenge", value: challenge) ] guard let authorizationURL = url.url else { throw AtlasError("登录地址无效。") } // Ephemeral browser sessions let a different person sign in after switching accounts. signInProgress = .authenticating let callback = try await browser.authenticate(authorizationURL) signInProgress = .finishing let result = URLComponents(url: callback, resolvingAgainstBaseURL: false) let parameters = result?.queryItems ?? [] guard result?.scheme == AtlasEndpoints.scheme, result?.host == nil, result?.path == "/oauth2/callback", parameters.filter({ $0.name == "state" }).map(\.value) == [state], parameters.filter({ $0.name == "code" }).count == 1, let code = parameters.first(where: { $0.name == "code" })?.value, !code.isEmpty else { throw AtlasError("登录未完成,请重试。") } let grant = try await exchange(discovery.token_endpoint, [ "grant_type": "authorization_code", "code": code, "code_verifier": verifier, "redirect_uri": AtlasEndpoints.redirect, "client_id": AtlasEndpoints.client ]) try save(grant, configuration: configuration) } catch ASWebAuthenticationSessionError.canceledLogin { } catch is URLError { error = "暂时连不上登录服务。请检查网络后重试。" } catch { self.error = error.localizedDescription } } func signOut() async { guard let configuration else { return } let refreshToken = tokens?.grant.refresh_token do { try clear(configuration) } catch { self.error = error.localizedDescription; return } if let refreshToken, let discovery = try? await discover(configuration), let revoke = discovery.revocation_endpoint { let request = Self.form(revoke, ["client_id": AtlasEndpoints.client, "token": refreshToken, "token_type_hint": "refresh_token"]) _ = try? await http.data(for: request) } } func request(_ path: String, method: String = "GET", data: Data? = nil, contentType: String = "application/json") async throws -> Data { guard let configuration, let url = URL(string: path, relativeTo: configuration.api)?.absoluteURL, Self.sameOrigin(url, configuration.api), path.hasPrefix("/api/") else { throw AtlasError("接口地址无效。") } let requestGeneration = generation var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData) request.httpMethod = method request.httpBody = data if data != nil { request.setValue(contentType, forHTTPHeaderField: "Content-Type") } let access = try await accessToken(configuration) guard requestGeneration == generation else { throw CancellationError() } request.setValue("Bearer \(access)", forHTTPHeaderField: "Authorization") var (body, response) = try await http.data(for: request) guard requestGeneration == generation else { throw CancellationError() } if (response as? HTTPURLResponse)?.statusCode == 401 { let renewed = try await accessToken(configuration, replacing: access) guard requestGeneration == generation else { throw CancellationError() } request.setValue("Bearer \(renewed)", forHTTPHeaderField: "Authorization") (body, response) = try await http.data(for: request) } guard requestGeneration == generation else { throw CancellationError() } guard let status = (response as? HTTPURLResponse)?.statusCode, (200..<300).contains(status) else { let problem = try? JSONDecoder().decode(Problem.self, from: body) let status = (response as? HTTPURLResponse)?.statusCode ?? 0 throw AtlasError(problem?.detail ?? "请求失败(\(status)),请稍后重试。") } return body } private func accessToken(_ configuration: AtlasEndpoints, replacing rejected: String? = nil) async throws -> String { guard let tokens else { throw AtlasError("请先登录。") } if tokens.expires.timeIntervalSinceNow > 30, tokens.grant.access_token != rejected { return tokens.grant.access_token } if let refreshTask { return try await refreshTask.value } let currentGeneration = generation let task = Task { @MainActor in let discovery = try await self.discover(configuration) do { let grant = try await self.exchange(discovery.token_endpoint, [ "grant_type": "refresh_token", "refresh_token": tokens.grant.refresh_token, "client_id": AtlasEndpoints.client ]) guard self.generation == currentGeneration else { throw CancellationError() } try self.save(grant, configuration: configuration) return grant.access_token } catch is ExpiredGrant { if self.generation == currentGeneration { try self.clear(configuration) } throw AtlasError("登录已过期,请重新登录。") } } refreshTask = task defer { if generation == currentGeneration { refreshTask = nil } } return try await task.value } private func discover(_ configuration: AtlasEndpoints) async throws -> OIDCMetadata { if let metadata { return metadata } let request = URLRequest(url: configuration.issuer.appending(path: ".well-known/openid-configuration"), timeoutInterval: Self.identityTimeout) let (body, response) = try await http.data(for: request) guard (response as? HTTPURLResponse)?.statusCode == 200, let result = try? JSONDecoder().decode(OIDCMetadata.self, from: body), result.issuer == configuration.issuer, Self.sameOrigin(result.authorization_endpoint, result.issuer), Self.sameOrigin(result.token_endpoint, result.issuer), result.revocation_endpoint.map({ Self.sameOrigin($0, result.issuer) }) ?? true else { throw AtlasError("暂时连不上登录服务,请稍后重试。") } metadata = result return result } private struct ExpiredGrant: Error {} private func exchange(_ url: URL, _ parameters: [String: String]) async throws -> Grant { let (body, response) = try await http.data(for: Self.form(url, parameters)) guard (response as? HTTPURLResponse)?.statusCode == 200, let grant = try? JSONDecoder().decode(Grant.self, from: body) else { if (try? JSONDecoder().decode(GrantError.self, from: body))?.error == "invalid_grant", parameters["grant_type"] == "refresh_token" { throw ExpiredGrant() } throw AtlasError("登录服务未能完成验证,请重试。") } return grant } private func save(_ grant: Grant, configuration: AtlasEndpoints) throws { let session = SessionTokens(grant: grant, expires: .now.addingTimeInterval(grant.expires_in)) try TokenKeychain.save(session, key: configuration.issuer.absoluteString) tokens = session signedIn = true } private func clear(_ configuration: AtlasEndpoints) throws { try TokenKeychain.remove(key: configuration.issuer.absoluteString) refreshTask?.cancel() refreshTask = nil generation = UUID() tokens = nil signedIn = false error = nil } private static func form(_ url: URL, _ parameters: [String: String]) -> URLRequest { var form = URLComponents() form.queryItems = parameters.map { URLQueryItem(name: $0.key, value: $0.value) } var request = URLRequest(url: url, timeoutInterval: identityTimeout) request.httpMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type") request.httpBody = Data((form.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B").utf8) return request } private static func sameOrigin(_ url: URL, _ expected: URL) -> Bool { url.scheme == expected.scheme && url.host == expected.host && (url.port ?? 443) == (expected.port ?? 443) && url.user == nil && url.password == nil && url.fragment == nil } private static func randomString() throws -> String { var bytes = [UInt8](repeating: 0, count: 32) guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { throw AtlasError("无法启动安全登录,请重试。") } return base64URL(Data(bytes)) } private static func base64URL(_ data: Data) -> String { data.base64EncodedString().replacingOccurrences(of: "+", with: "-") .replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") } } private enum TokenKeychain { private static func query(_ key: String) -> [String: Any] { [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: "com.tutudog.itematlas.session", kSecAttrAccount as String: key] } static func read(key: String) throws -> SessionTokens? { var request = query(key) request[kSecReturnData as String] = true request[kSecMatchLimit as String] = kSecMatchLimitOne var value: CFTypeRef? let status = SecItemCopyMatching(request as CFDictionary, &value) if status == errSecItemNotFound { return nil } try check(status) guard let data = value as? Data else { throw AtlasError("无法读取钥匙串中的登录状态。") } return try JSONDecoder().decode(SessionTokens.self, from: data) } static func save(_ tokens: SessionTokens, key: String) throws { let bytes = try JSONEncoder().encode(tokens) let match = query(key) let status = SecItemUpdate(match as CFDictionary, [kSecValueData as String: bytes] as CFDictionary) if status == errSecItemNotFound { var new = match new[kSecValueData as String] = bytes new[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly try check(SecItemAdd(new as CFDictionary, nil)) } else { try check(status) } } static func remove(key: String) throws { let status = SecItemDelete(query(key) as CFDictionary) if status != errSecItemNotFound { try check(status) } } private static func check(_ status: OSStatus) throws { if status != errSecSuccess { throw AtlasError("无法访问本机钥匙串,请解锁设备后重试。") } } } @MainActor private final class LoginBrowser: NSObject, ASWebAuthenticationPresentationContextProviding { private var anchor: ASPresentationAnchor? private var session: ASWebAuthenticationSession? func authenticate(_ url: URL) async throws -> URL { guard let window = UIApplication.shared.connectedScenes .compactMap({ $0 as? UIWindowScene }).filter({ $0.activationState == .foregroundActive }) .flatMap(\.windows).first(where: \.isKeyWindow) else { throw AtlasError("找不到当前窗口,请返回见物后重试。") } anchor = window defer { anchor = nil; session = nil } return try await withCheckedThrowingContinuation { continuation in let authentication = ASWebAuthenticationSession(url: url, callbackURLScheme: AtlasEndpoints.scheme) { url, error in if let error { continuation.resume(throwing: error) } else if let url { continuation.resume(returning: url) } else { continuation.resume(throwing: AtlasError("登录未完成,请重试。")) } } authentication.presentationContextProvider = self authentication.prefersEphemeralWebBrowserSession = true session = authentication if !authentication.start() { continuation.resume(throwing: AtlasError("无法打开登录页面,请重试。")) } } } func presentationAnchor(for session: ASWebAuthenticationSession) -> ASPresentationAnchor { anchor ?? ASPresentationAnchor() } }