| 1 | import Foundation |
| 2 | import Security |
| 3 | import LocalAuthentication |
| 4 | import CryptoKit |
| 5 | |
| 6 | struct CageAccountError: LocalizedError { |
| 7 | let message: String |
| 8 | var errorDescription: String? { message } |
| 9 | init(_ message: String) { self.message = message } |
| 10 | } |
| 11 | |
| 12 | |
| 13 | |
| 14 | final class CageAccountDevice: NSObject, URLSessionTaskDelegate, @unchecked Sendable { |
| 15 | private lazy var session: URLSession = { |
| 16 | let config = URLSessionConfiguration.ephemeral |
| 17 | config.connectionProxyDictionary = [:] |
| 18 | config.timeoutIntervalForRequest = 15 |
| 19 | return URLSession(configuration: config, delegate: self, delegateQueue: nil) |
| 20 | }() |
| 21 | private let base: URL |
| 22 | private let ticket: String |
| 23 | private let connection: String |
| 24 | |
| 25 | init(entry: URL, connection: String = "local") throws { |
| 26 | guard entry.scheme == "http", entry.host == "localhost", let ticket = entry.fragment, !ticket.isEmpty else { throw CageAccountError("本地账户连接无效") } |
| 27 | var parts = URLComponents(url: entry, resolvingAgainstBaseURL: false)! |
| 28 | parts.fragment = nil; parts.path = ""; parts.query = nil |
| 29 | base = parts.url!; self.ticket = ticket; self.connection = connection |
| 30 | super.init() |
| 31 | } |
| 32 | deinit { session.invalidateAndCancel() } |
| 33 | func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) { completionHandler(nil) } |
| 34 | private func call(_ path: String, _ body: [String: Any]? = nil) async throws -> [String: Any] { |
| 35 | var request = URLRequest(url: base.appendingPathComponent("api/account" + path)) |
| 36 | if path == "@session" { request.url = base.appendingPathComponent("api/session") } |
| 37 | if path == "@context" { request.url = base.appendingPathComponent("api/client/context") } |
| 38 | request.httpMethod = body == nil ? "GET" : "POST" |
| 39 | request.setValue(base.absoluteString.trimmingCharacters(in: CharacterSet(charactersIn: "/")), forHTTPHeaderField: "Origin") |
| 40 | request.setValue(connection, forHTTPHeaderField: "X-Cage-Connection") |
| 41 | if let body { request.setValue("application/json", forHTTPHeaderField: "Content-Type"); request.httpBody = try JSONSerialization.data(withJSONObject: body) } |
| 42 | let (data, response) = try await session.data(for: request) |
| 43 | guard let response = response as? HTTPURLResponse, response.statusCode == 200 else { |
| 44 | throw CageAccountError(String(data: data.prefix(512), encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "账户操作未完成") |
| 45 | } |
| 46 | guard let value = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw CageAccountError("本地账户响应无效") } |
| 47 | return value |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | enum CageAccountKeychain { |
| 52 | private static let service = "io.github.lee-xeo.claude-cage.account" |
| 53 | private static func query(binding: String, kind: String) -> [String: Any] { |
| 54 | var result: [String: Any] = [kSecClass as String: kSecClassGenericPassword, |
| 55 | kSecAttrService as String: service, |
| 56 | kSecAttrAccount as String: binding + "." + kind] |
| 57 | if kind == "biometric" { |
| 58 | result[kSecUseDataProtectionKeychain as String] = true |
| 59 | result[kSecAttrSynchronizable as String] = false |
| 60 | } |
| 61 | return result |
| 62 | } |
| 63 | static func remove(binding: String, kind: String) throws { |
| 64 | let status = SecItemDelete(query(binding: binding, kind: kind) as CFDictionary) |
| 65 | guard status == errSecSuccess || status == errSecItemNotFound else { throw CageAccountError("无法移除本机钥匙串记录,请重试") } |
| 66 | } |
| 67 | static func store(_ credential: [String: Any], binding: String, kind: String) throws { |
| 68 | var item = query(binding: binding, kind: kind) |
| 69 | item[kSecValueData as String] = try JSONSerialization.data(withJSONObject: credential) |
| 70 | if let id = credential["id"] as? String { item[kSecAttrGeneric as String] = Data(id.utf8) } |
| 71 | item[kSecAttrLabel as String] = kind == "biometric" ? "Cage 指纹解锁" : "Cage 记住登录" |
| 72 | if kind == "biometric" { |
| 73 | var error: Unmanaged<CFError>? |
| 74 | guard let access = SecAccessControlCreateWithFlags(nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, .biometryCurrentSet, &error) else { throw CageAccountError("这台 Mac 无法创建指纹保护的凭据") } |
| 75 | item[kSecAttrAccessControl as String] = access |
| 76 | } |
| 77 | try remove(binding: binding, kind: kind) |
| 78 | let status = SecItemAdd(item as CFDictionary, nil) |
| 79 | guard status == errSecSuccess else { throw CageAccountError("macOS 未能保存快捷登录凭据(\(status)),密码登录仍然可用") } |
| 80 | } |
| 81 | |
| 82 | |
| 83 | static func status(binding: String, kind: String, expectedID: String?) -> String { |
| 84 | guard let expectedID else { return "disabled" } |
| 85 | var item = query(binding: binding, kind: kind) |
| 86 | item[kSecReturnAttributes as String] = true |
| 87 | item[kSecMatchLimit as String] = kSecMatchLimitOne |
| 88 | let context = LAContext() |
| 89 | context.interactionNotAllowed = true |
| 90 | item[kSecUseAuthenticationContext as String] = context |
| 91 | var result: CFTypeRef? |
| 92 | let status = SecItemCopyMatching(item as CFDictionary, &result) |
| 93 | return availability(status: status, attributes: result as? [String: Any], expectedID: expectedID, kind: kind) |
| 94 | } |
| 95 | static func availability(status: OSStatus, attributes: [String: Any]?, expectedID: String, kind: String) -> String { |
| 96 | if status == errSecItemNotFound { return "missing" } |
| 97 | |
| 98 | |
| 99 | if kind == "biometric" && status == errSecInteractionNotAllowed { return "authentication_required" } |
| 100 | guard status == errSecSuccess, let attributes else { return "unavailable" } |
| 101 | |
| 102 | |
| 103 | if let id = attributes[kSecAttrGeneric as String] as? Data, id != Data(expectedID.utf8) { return "missing" } |
| 104 | return "available" |
| 105 | } |
| 106 | static func read(binding: String, kind: String) throws -> [String: Any] { |
| 107 | var item = query(binding: binding, kind: kind) |
| 108 | item[kSecReturnData as String] = true; item[kSecMatchLimit as String] = kSecMatchLimitOne |
| 109 | let context = LAContext() |
| 110 | context.localizedReason = "解锁你的 Cage 工作空间" |
| 111 | context.localizedFallbackTitle = "" |
| 112 | if kind == "automatic" { |
| 113 | |
| 114 | |
| 115 | context.interactionNotAllowed = true |
| 116 | } |
| 117 | item[kSecUseAuthenticationContext as String] = context |
| 118 | var result: CFTypeRef? |
| 119 | let status = SecItemCopyMatching(item as CFDictionary, &result) |
| 120 | if status == errSecUserCanceled { throw CageAccountError("已取消指纹验证,可继续使用密码") } |
| 121 | guard status == errSecSuccess, let data = result as? Data, |
| 122 | let value = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw CageAccountError("快捷登录不可用,请使用密码解锁后重新开启") } |
| 123 | return value |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | extension CageAccountDevice { |
| 128 | func handle(operation: String, kind: String?) async throws -> [String: Any] { |
| 129 | defer { session.invalidateAndCancel() } |
| 130 | _ = try await call("@session", ["token": ticket]) |
| 131 | let account = try await call("") |
| 132 | guard let accountBinding = account["device_binding"] as? String, accountBinding.count == 64 else { throw CageAccountError("当前后台不支持快捷登录,请先完成更新") } |
| 133 | var binding = accountBinding |
| 134 | if connection != "local" { |
| 135 | let selected = try await call("@context") |
| 136 | guard selected["connection_id"] as? String == connection else { throw CageAccountError("工作环境已切换,请重新解锁") } |
| 137 | if selected["mode"] as? String == "remote" { |
| 138 | guard let host = selected["host_id"] as? String, !host.isEmpty, |
| 139 | let fingerprint = selected["host_fingerprint"] as? String, fingerprint.hasPrefix("SHA256:"), |
| 140 | let instance = selected["instance_id"] as? String, instance.count == 64 else { throw CageAccountError("远程连接已经切换,请重新解锁当前主机") } |
| 141 | let scoped = ["remote", host, fingerprint, instance, accountBinding].joined(separator: "\u{0}") |
| 142 | binding = SHA256.hash(data: Data(scoped.utf8)).map { String(format: "%02x", $0) }.joined() |
| 143 | } else if selected["mode"] as? String != "local" { |
| 144 | throw CageAccountError("请先选择工作环境") |
| 145 | } |
| 146 | } |
| 147 | let context = LAContext() |
| 148 | let biometricAvailable = context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: nil) |
| 149 | if operation == "status" { |
| 150 | let devices = account["devices"] as? [String: String] ?? [:] |
| 151 | let states = Dictionary(uniqueKeysWithValues: ["automatic", "biometric"].map { kind in |
| 152 | (kind, CageAccountKeychain.status(binding: binding, kind: kind, expectedID: devices[kind])) |
| 153 | }) |
| 154 | return ["supported": true, "biometric_available": biometricAvailable, "device_status": states] |
| 155 | } |
| 156 | guard let kind, ["automatic", "biometric"].contains(kind) else { throw CageAccountError("快捷登录类型无效") } |
| 157 | switch operation { |
| 158 | case "enable": |
| 159 | if kind == "biometric" && !biometricAvailable { throw CageAccountError("请先在 macOS 系统设置中设置 Touch ID") } |
| 160 | let credential = try await call("/device-enroll", ["kind": kind]) |
| 161 | do { try CageAccountKeychain.store(credential, binding: binding, kind: kind) } |
| 162 | catch { |
| 163 | _ = try? await call("/device-revoke", ["kind": kind]) |
| 164 | throw error |
| 165 | } |
| 166 | case "disable": |
| 167 | _ = try await call("/device-revoke", ["kind": kind]) |
| 168 | try CageAccountKeychain.remove(binding: binding, kind: kind) |
| 169 | case "unlock": |
| 170 | |
| 171 | if kind == "automatic" && account["require_authentication"] as? Bool == true { throw CageAccountError("Cage 已手动锁定,请使用指纹或密码") } |
| 172 | guard let devices = account["devices"] as? [String: String], let expectedID = devices[kind] else { throw CageAccountError("请先使用密码登录,再开启快捷登录") } |
| 173 | let credential = try CageAccountKeychain.read(binding: binding, kind: kind) |
| 174 | guard credential["id"] as? String == expectedID else { throw CageAccountError("快捷登录授权已失效,请使用密码") } |
| 175 | _ = try await call("/device-unlock", ["kind": kind, "credential": credential]) |
| 176 | default: throw CageAccountError("快捷登录操作无效") |
| 177 | } |
| 178 | return ["ok": true] |
| 179 | } |
| 180 | } |