import Foundation import Observation import Security 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" 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 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 let native: Bool? } private struct NativeGrant: Decodable { let accessToken: String let refreshToken: String let expiresIn: Double var grant: Grant { Grant(access_token: accessToken, refresh_token: refreshToken, expires_in: expiresIn) } } private struct Credentials: Encodable { let username: String let password: String } private struct Refresh: Encodable { let refreshToken: String } 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 { private static let identityTimeout: TimeInterval = 15 private(set) var signedIn = false private(set) var signingIn = false 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() var preferenceScope: String? { guard let segment = tokens?.grant.access_token.split(separator: ".").dropFirst().first, let issuer = configuration?.issuer else { return nil } let payload = segment.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") let padding = String(repeating: "=", count: (4 - payload.count % 4) % 4) guard let data = Data(base64Encoded: payload + padding), let claims = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], let subject = claims["sub"] as? String, !subject.isEmpty else { return nil } return issuer.absoluteString + "/" + subject } 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(username: String, password: String) async { guard !signingIn, !Task.isCancelled else { return } signingIn = true error = nil defer { signingIn = false } do { guard let configuration else { throw AtlasError("登录服务地址未配置。") } let grant = try await nativeGrant("login", body: Credentials(username: username, password: password), configuration: configuration) try Task.checkCancellation() try save(grant, native: true, configuration: configuration) } catch is CancellationError { } catch let error as URLError where error.code == .cancelled { } catch is ExpiredGrant { error = "账号或密码不正确。" } catch is URLError { error = "暂时连不上登录服务。请检查网络后重试。" } catch { self.error = error.localizedDescription } } func clearSignInError() { error = nil } func signOut() async { guard let configuration else { return } let previous = tokens do { try clear(configuration) } catch { self.error = error.localizedDescription; return } guard let previous else { return } let refreshToken = previous.grant.refresh_token if previous.native == true { _ = try? await nativeRequest("logout", body: Refresh(refreshToken: refreshToken), configuration: configuration) } else if 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 do { let grant: Grant let native = tokens.native == true if native { grant = try await self.nativeGrant("refresh", body: Refresh(refreshToken: tokens.grant.refresh_token), configuration: configuration) } else { let discovery = try await self.discover(configuration) 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, native: native, 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.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 nativeRequest(_ action: String, body: some Encodable, configuration: AtlasEndpoints) async throws -> (Data, Int) { guard let url = URL(string: "/api/session/" + action, relativeTo: configuration.api)?.absoluteURL else { throw AtlasError("登录地址无效。") } var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: Self.identityTimeout) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = try JSONEncoder().encode(body) let (data, response) = try await http.data(for: request) return (data, (response as? HTTPURLResponse)?.statusCode ?? 0) } private func nativeGrant(_ action: String, body: some Encodable, configuration: AtlasEndpoints) async throws -> Grant { let (data, status) = try await nativeRequest(action, body: body, configuration: configuration) if status == 401 { throw ExpiredGrant() } if status == 429 { throw AtlasError("操作太频繁,请稍等再试。") } guard status == 200, let result = try? JSONDecoder().decode(NativeGrant.self, from: data), !result.accessToken.isEmpty, !result.refreshToken.isEmpty, result.expiresIn > 0 else { throw AtlasError("暂时连不上登录服务,请稍后重试。") } return result.grant } 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, native: Bool, configuration: AtlasEndpoints) throws { let session = SessionTokens(grant: grant, expires: .now.addingTimeInterval(grant.expires_in), native: native) 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 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("无法访问本机钥匙串,请解锁设备后重试。") } } }