| 1 | import Foundation |
| 2 | import Security |
| 3 | |
| 4 | enum InputError: LocalizedError { |
| 5 | case invalid, unavailable |
| 6 | var errorDescription: String? { |
| 7 | switch self { |
| 8 | case .invalid: return "连接文件或指纹格式无效。" |
| 9 | case .unavailable: return "无法读取已保存的凭据,请解锁手机或重新导入连接文件。" |
| 10 | } |
| 11 | } |
| 12 | } |
| 13 | |
| 14 | struct Host: Codable, Equatable { |
| 15 | let relay: String |
| 16 | let pin: String |
| 17 | |
| 18 | init(relay: String, pin: String) throws { |
| 19 | guard var u = URLComponents(string: relay.trimmingCharacters(in: .whitespacesAndNewlines)), |
| 20 | u.scheme?.lowercased() == "https", let host = u.host, !host.isEmpty, |
| 21 | u.user == nil, u.password == nil, u.query == nil, u.fragment == nil, |
| 22 | u.path.isEmpty || u.path == "/", (1...65535).contains(u.port ?? 443) else { throw InputError.invalid } |
| 23 | u.scheme = "https"; u.path = "" |
| 24 | let pin = pin.trimmingCharacters(in: .whitespacesAndNewlines) |
| 25 | let encoded = String(pin.dropFirst(7)) |
| 26 | guard pin.hasPrefix("sha256:"), let bytes = Data(base64Encoded: encoded), bytes.count == 32, |
| 27 | bytes.base64EncodedString() == encoded, let address = u.url?.absoluteString else { throw InputError.invalid } |
| 28 | self.relay = address; self.pin = pin |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | struct Invitation: Decodable { |
| 33 | let id: String |
| 34 | let client_token: String |
| 35 | let expires_at: String |
| 36 | |
| 37 | var expiry: Date? { |
| 38 | let iso = ISO8601DateFormatter() |
| 39 | iso.formatOptions = [.withInternetDateTime, .withFractionalSeconds] |
| 40 | return iso.date(from: expires_at) ?? ISO8601DateFormatter().date(from: expires_at) |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | struct HostAccess: Codable { |
| 45 | let host: Host |
| 46 | let lookup: String |
| 47 | } |
| 48 | |
| 49 | enum ConnectionFile { |
| 50 | case temporary(Invitation) |
| 51 | case persistent(HostAccess) |
| 52 | |
| 53 | static func load(_ file: URL) throws -> Self { |
| 54 | let access = file.startAccessingSecurityScopedResource() |
| 55 | defer { if access { file.stopAccessingSecurityScopedResource() } } |
| 56 | let handle = try FileHandle(forReadingFrom: file) |
| 57 | defer { try? handle.close() } |
| 58 | let data = try handle.read(upToCount: 4097) ?? Data() |
| 59 | return try parse(data) |
| 60 | } |
| 61 | static func parse(_ data: Data) throws -> Self { |
| 62 | guard data.count <= 4096, let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] else { throw InputError.invalid } |
| 63 | let keys = Set(object.keys) |
| 64 | if keys == Set(["id", "client_token", "expires_at"]) { |
| 65 | let value = try JSONDecoder().decode(Invitation.self, from: data) |
| 66 | guard capability(value.id), capability(value.client_token), (value.expiry ?? .distantPast) > Date() else { throw InputError.invalid } |
| 67 | return .temporary(value) |
| 68 | } |
| 69 | struct Record: Decodable { let version: Int; let relay, host_pin, lookup_token: String } |
| 70 | guard keys == Set(["version", "relay", "host_pin", "lookup_token"]) else { throw InputError.invalid } |
| 71 | let record = try JSONDecoder().decode(Record.self, from: data) |
| 72 | guard record.version == 1, capability(record.lookup_token) else { throw InputError.invalid } |
| 73 | return .persistent(HostAccess(host: try Host(relay: record.relay, pin: record.host_pin), lookup: record.lookup_token)) |
| 74 | } |
| 75 | static func capability(_ s: String) -> Bool { |
| 76 | guard s.utf8.count == 43 else { return false } |
| 77 | let base = s.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/") + "=" |
| 78 | guard let bytes = Data(base64Encoded: base), bytes.count == 32 else { return false } |
| 79 | return bytes.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_") |
| 80 | .trimmingCharacters(in: CharacterSet(charactersIn: "=")) == s |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | enum HostKeychain { |
| 85 | private static var query: [String: Any] { |
| 86 | [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: "io.github.lee-xeo.claude-cage.mobile.saved-host", |
| 87 | kSecAttrAccount as String: "v1", kSecAttrSynchronizable as String: false] |
| 88 | } |
| 89 | private static var collectionQuery: [String: Any] { |
| 90 | var q = query; q[kSecAttrAccount as String] = "v2-hosts"; return q |
| 91 | } |
| 92 | private static func data(_ item: [String: Any]) throws -> Data? { |
| 93 | var q = item |
| 94 | q[kSecReturnData as String] = true |
| 95 | q[kSecMatchLimit as String] = kSecMatchLimitOne |
| 96 | var found: CFTypeRef? |
| 97 | let status = SecItemCopyMatching(q as CFDictionary, &found) |
| 98 | if status == errSecItemNotFound {return nil} |
| 99 | guard status == errSecSuccess, let data = found as? Data else {throw InputError.unavailable} |
| 100 | return data |
| 101 | } |
| 102 | static func readAll() throws -> [HostAccess] { |
| 103 | let records: [HostAccess] |
| 104 | if let data = try data(collectionQuery) { |
| 105 | records = try JSONDecoder().decode([HostAccess].self, from: data) |
| 106 | } else if let data = try data(query) { |
| 107 | records = [try JSONDecoder().decode(HostAccess.self, from: data)] |
| 108 | } else {return []} |
| 109 | for record in records { |
| 110 | guard ConnectionFile.capability(record.lookup), |
| 111 | try Host(relay: record.host.relay, pin: record.host.pin) == record.host else {throw InputError.invalid} |
| 112 | } |
| 113 | return records |
| 114 | } |
| 115 | static func read(host: Host? = nil) throws -> HostAccess? { |
| 116 | let records = try readAll() |
| 117 | if let host {return records.first {$0.host == host}} |
| 118 | return records.last |
| 119 | } |
| 120 | private static func store(_ records: [HostAccess]) throws { |
| 121 | let values: [String:Any] = [kSecValueData as String: try JSONEncoder().encode(records), |
| 122 | kSecAttrAccessible as String: kSecAttrAccessibleWhenUnlockedThisDeviceOnly] |
| 123 | var status = SecItemUpdate(collectionQuery as CFDictionary, values as CFDictionary) |
| 124 | if status == errSecItemNotFound { |
| 125 | status = SecItemAdd(collectionQuery.merging(values) {_, value in value} as CFDictionary, nil) |
| 126 | } |
| 127 | guard status == errSecSuccess else {throw InputError.unavailable} |
| 128 | |
| 129 | let legacy = SecItemDelete(query as CFDictionary) |
| 130 | guard legacy == errSecSuccess || legacy == errSecItemNotFound else {throw InputError.unavailable} |
| 131 | } |
| 132 | static func write(_ record: HostAccess) throws { |
| 133 | var records = try readAll(); records.removeAll {$0.host == record.host}; records.append(record) |
| 134 | try store(records) |
| 135 | } |
| 136 | static func forget(host: Host? = nil) throws { |
| 137 | var records = try readAll() |
| 138 | if let host {records.removeAll {$0.host == host}} else {records = []} |
| 139 | |
| 140 | try store(records) |
| 141 | } |
| 142 | } |