| 1 | import Cocoa |
| 2 | import Security |
| 3 | |
| 4 | |
| 5 | |
| 6 | enum MacGuestLoginCredential { |
| 7 | private static func item() throws -> [String: Any] { |
| 8 | guard CageProfile.macGuestTrial else { throw CageUpdateError("此操作只适用于本机 macOS 试用版。") } |
| 9 | struct Binding: Decodable { let machineID: String; let user: String } |
| 10 | let url = CageProfile.configURL().deletingLastPathComponent().appendingPathComponent("macos-guest.json") |
| 11 | let binding = try JSONDecoder().decode(Binding.self, from: Data(contentsOf: url)) |
| 12 | return [kSecClass as String: kSecClassGenericPassword, |
| 13 | kSecAttrService as String: "io.github.lee-xeo.claude-cage.macos-trial.guest-login", |
| 14 | kSecAttrAccount as String: binding.user + "@" + binding.machineID, |
| 15 | kSecAttrSynchronizable as String: false] |
| 16 | } |
| 17 | static func importFromPipe() throws { |
| 18 | guard isatty(STDIN_FILENO) == 0 else { throw CageUpdateError("请通过私有管道提供试用客机凭据。") } |
| 19 | let secret = FileHandle.standardInput.readData(ofLength: 1025) |
| 20 | guard !secret.isEmpty, secret.count <= 1024 else { throw CageUpdateError("客机凭据为空或过长。") } |
| 21 | var query = try item() |
| 22 | query[kSecAttrLabel as String] = "Cage macOS 试用客机登录" |
| 23 | query[kSecValueData as String] = secret |
| 24 | let status = SecItemAdd(query as CFDictionary, nil) |
| 25 | if status == errSecDuplicateItem, try read() == secret { return } |
| 26 | guard status == errSecSuccess else { throw CageUpdateError("无法保存本机试用客机凭据(\(status))。") } |
| 27 | } |
| 28 | private static func read() throws -> Data { |
| 29 | var query = try item() |
| 30 | query[kSecReturnData as String] = true |
| 31 | query[kSecMatchLimit as String] = kSecMatchLimitOne |
| 32 | var value: CFTypeRef? |
| 33 | let status = SecItemCopyMatching(query as CFDictionary, &value) |
| 34 | guard status == errSecSuccess, let data = value as? Data else { throw CageUpdateError("本机钥匙串中没有可用的试用客机密码。") } |
| 35 | return data |
| 36 | } |
| 37 | static func copyForLogin() throws { |
| 38 | guard let text = String(data: try read(), encoding: .utf8) else { throw CageUpdateError("客机密码格式无效。") } |
| 39 | let item = NSPasteboardItem() |
| 40 | item.setString(text, forType: .string) |
| 41 | item.setData(Data(), forType: .init("org.nspasteboard.ConcealedType")) |
| 42 | item.setData(Data(), forType: .init("org.nspasteboard.TransientType")) |
| 43 | let board = NSPasteboard.general |
| 44 | board.clearContents() |
| 45 | guard board.writeObjects([item]) else { throw CageUpdateError("无法写入剪贴板。") } |
| 46 | let change = board.changeCount |
| 47 | DispatchQueue.main.asyncAfter(deadline: .now() + 60) { |
| 48 | if board.changeCount == change { board.clearContents() } |
| 49 | } |
| 50 | } |
| 51 | } |