Open History to see the last commit
1import AppKit
2import CryptoKit
3import Network
4import Security
5import LocalAuthentication
6
7struct AgentConnectionError: LocalizedError {
8 let message: String
9 var errorDescription: String? { message }
10}
11
12/// App-owned credentials only. Never reads Codex/OpenCode/browser credential stores.
13@MainActor
14final class AgentCredentials {
15 struct Account: Codable {
16 var clientID: String
17 var subject: String
18 var email: String
19 var accessToken: String
20 var refreshToken: String
21 var idToken: String
22 var expiresAt: Date
23 var scopes: [String]
24 }
25 // Persistent Keychain namespace: preserve saved connections across app renames.
26 private let service: String
27 private var labelledAccounts: Set<String> = []
28 init(service: String = "com.othersock.desktop.agent") { self.service = service }
29 private var listener: NWListener?
30 private var loginTimeout: Task<Void, Never>?
31 private var attempt: UUID?
32 private var refreshTask: Task<String, Error>?
33 var onChange: (() -> Void)?
34 private(set) var status = "Not connected"
35 var account: Account? { guard let data = try? read("chatgpt") else { return nil }; return try? JSONDecoder().decode(Account.self, from: data) }
36 var hasAPIKey: Bool { ((try? read("api-key"))?.isEmpty == false) }
37 var isSigningIn: Bool { attempt != nil }
38
39 func saveAPIKey(_ key: String) throws {
40 guard !key.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { throw AgentConnectionError(message: "Enter an API key first.") }
41 try save(Data(key.trimmingCharacters(in: .whitespacesAndNewlines).utf8), as: "api-key")
42 status = "API key saved in Keychain"; onChange?()
43 }
44 func apiKey() throws -> String {
45 guard let data = try read("api-key"), let key = String(data: data, encoding: .utf8) else { throw AgentConnectionError(message: "Add an API key or continue with ChatGPT.") }
46 return key
47 }
48 func disconnectChatGPT() {
49 cancelSignIn(); refreshTask?.cancel(); refreshTask = nil
50 SecItemDelete(query("chatgpt") as CFDictionary)
51 status = "ChatGPT disconnected"; onChange?()
52 }
53 func removeAPIKey() { SecItemDelete(query("api-key") as CFDictionary); status = "API key removed"; onChange?() }
54 func disconnect() {
55 cancelSignIn(); refreshTask?.cancel(); refreshTask = nil
56 for name in ["chatgpt", "api-key"] { SecItemDelete(query(name) as CFDictionary) }
57 status = "Disconnected"; onChange?()
58 }
59 private func query(_ name: String) -> [String: Any] { [kSecClass as String: kSecClassGenericPassword, kSecAttrService as String: service, kSecAttrAccount as String: name] }
60 private func displayAttributes(_ name: String) -> [String: Any] {
61 [kSecAttrLabel as String: name == "chatgpt" ? "Jerry — ChatGPT" : "Jerry — API key",
62 kSecAttrDescription as String: name == "chatgpt" ? "Jerry ChatGPT connection" : "Jerry API key"]
63 }
64 private func updateDisplayAttributes(_ name: String) {
65 guard !labelledAccounts.contains(name) else { return }
66 var q = query(name)
67 // Relabel old items without reading or replacing their secret, and never
68 // interrupt an automatic status check with an authorisation dialog.
69 let context = LAContext(); context.interactionNotAllowed = true
70 q[kSecUseAuthenticationContext as String] = context
71 var lookup = q; lookup[kSecReturnAttributes as String] = true; lookup[kSecMatchLimit as String] = kSecMatchLimitOne
72 var found: CFTypeRef?
73 let code = Self.nonInteractiveKeychain { SecItemCopyMatching(lookup as CFDictionary, &found) }
74 let expected = displayAttributes(name)
75 if code == errSecSuccess, let attributes = found as? [String: Any],
76 attributes[kSecAttrLabel as String] as? String == expected[kSecAttrLabel as String] as? String,
77 attributes[kSecAttrDescription as String] as? String == expected[kSecAttrDescription as String] as? String {
78 labelledAccounts.insert(name); return
79 }
80 guard code == errSecSuccess else { return }
81 if Self.nonInteractiveKeychain({ SecItemUpdate(q as CFDictionary, expected as CFDictionary) }) == errSecSuccess {
82 labelledAccounts.insert(name)
83 }
84 }
85 /// Legacy login-keychain ACL changes can ignore the modern no-UI query key.
86 /// This synchronous MainActor scope restores the previous process setting
87 /// before any other app-owned credential operation can run.
88 static func nonInteractiveKeychain<T>(_ body: () throws -> T) rethrows -> T {
89 var prior: DarwinBoolean = true
90 let known = SecKeychainGetUserInteractionAllowed(&prior) == errSecSuccess
91 if known { SecKeychainSetUserInteractionAllowed(false) }
92 defer { if known { SecKeychainSetUserInteractionAllowed(prior.boolValue) } }
93 return try body()
94 }
95 private func read(_ name: String) throws -> Data? {
96 updateDisplayAttributes(name)
97 var q = query(name); q[kSecReturnData as String] = true; q[kSecMatchLimit as String] = kSecMatchLimitOne
98 // Automatic status checks must not block startup behind a Keychain prompt.
99 // Unsigned Debug/Release binaries can have different access identities.
100 let context = LAContext(); context.interactionNotAllowed = true
101 q[kSecUseAuthenticationContext as String] = context
102 var result: CFTypeRef?
103 let code = Self.nonInteractiveKeychain { SecItemCopyMatching(q as CFDictionary, &result) }
104 if code == errSecItemNotFound { return nil }
105 guard code == errSecSuccess else { throw AgentConnectionError(message: "Keychain could not be read (\(code)).") }
106 return result as? Data
107 }
108 private func save(_ data: Data, as name: String) throws {
109 let q = query(name)
110 var attributes = displayAttributes(name); attributes[kSecValueData as String] = data
111 let code = SecItemUpdate(q as CFDictionary, attributes as CFDictionary)
112 if code == errSecItemNotFound {
113 var insert = q.merging(attributes) { _, new in new }; insert[kSecAttrAccessible as String] = kSecAttrAccessibleWhenUnlockedThisDeviceOnly
114 guard SecItemAdd(insert as CFDictionary, nil) == errSecSuccess else { throw AgentConnectionError(message: "Could not save credentials to Keychain.") }; labelledAccounts.insert(name); return
115 }
116 guard code == errSecSuccess else { throw AgentConnectionError(message: "Could not update credentials in Keychain.") }
117 labelledAccounts.insert(name)
118 }
119 static func randomToken() throws -> String {
120 var bytes = [UInt8](repeating: 0, count: 32)
121 guard SecRandomCopyBytes(kSecRandomDefault, bytes.count, &bytes) == errSecSuccess else { throw AgentConnectionError(message: "Could not generate sign-in randomness.") }
122 return Data(bytes).base64URL
123 }
124 func cancelSignIn() {
125 if attempt != nil { status = "Sign-in cancelled" }
126 attempt = nil; listener?.cancel(); listener = nil; loginTimeout?.cancel(); loginTimeout = nil
127 }
128 func signIn() {
129 cancelSignIn()
130 do {
131 let id = UUID(); attempt = id
132 let state = try Self.randomToken(), nonce = try Self.randomToken(), verifier = try Self.randomToken()
133 let saved = account
134 let host = UserDefaults.standard.string(forKey: "agentHostID") ?? "urn:uuid:\(UUID().uuidString.lowercased())"
135 UserDefaults.standard.set(host, forKey: "agentHostID")
136 let parameters = NWParameters.tcp
137 parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: .any)
138 let listener = try NWListener(using: parameters)
139 self.listener = listener; status = "Preparing browser sign-in…"; onChange?()
140 listener.newConnectionHandler = { [weak self, weak listener] connection in
141 guard let port = listener?.port else { connection.cancel(); return }
142 let redirect = "http://127.0.0.1:\(port.rawValue)/auth/callback"
143 connection.start(queue: .main)
144 Self.receiveCallback(connection, pending: "", expectedState: state) { [weak self] values in
145 Task { @MainActor [weak self] in
146 guard let self, self.attempt == id else { return }
147 self.listener?.cancel(); self.listener = nil
148 do {
149 guard values["error"] == nil else { throw AgentConnectionError(message: "ChatGPT sign-in was declined. You can try again.") }
150 guard let code = values["code"], let client = values["client_id"] ?? saved?.clientID,
151 client != "dynamic_agent_client", saved == nil || saved?.clientID == client else { throw AgentConnectionError(message: "The sign-in callback did not match this registration.") }
152 self.status = "Validating ChatGPT connection…"; self.onChange?()
153 let response = try await Self.tokenRequest(["grant_type": "authorization_code", "client_id": client, "code": code, "code_verifier": verifier, "redirect_uri": redirect, "resource": "https://api.openai.com/v1"])
154 guard let jwt = response["id_token"] as? String else { throw AgentConnectionError(message: "The sign-in response has no identity token.") }
155 let identity = try await Self.validateIdentity(jwt, clientID: client, nonce: nonce)
156 if let saved, saved.subject != identity.subject { throw AgentConnectionError(message: "The signed-in account differs from the selected account. Disconnect to change account.") }
157 let record = try Self.record(response, clientID: client, identity: identity, previous: nil)
158 guard self.attempt == id else { return }
159 try self.save(JSONEncoder().encode(record), as: "chatgpt")
160 self.cancelSignIn(); self.status = "Connected to ChatGPT: \(record.email)"; self.onChange?()
161 } catch { self.fail(error, attempt: id) }
162 }
163 }
164 }
165
166 listener.stateUpdateHandler = { [weak self, weak listener] listenerState in
167 Task { @MainActor [weak self, weak listener] in
168 guard let self, let listener, self.attempt == id else { return }
169 if case .ready = listenerState, let port = listener.port {
170 let redirect = "http://127.0.0.1:\(port.rawValue)/auth/callback"
171 var url = URLComponents(string: "https://auth.openai.com/api/accounts/authorize")!
172 var items = ["client_id": saved?.clientID ?? "dynamic_agent_client", "ext_agent_host_id": host,
173 "response_type": "code", "redirect_uri": redirect,
174 "scope": "openid profile email offline_access resource.invoke chatgpt.tokens.use.direct",
175 "resource": "https://api.openai.com/v1", "state": state, "nonce": nonce,
176 "code_challenge_method": "S256", "code_challenge": Data(SHA256.hash(data: Data(verifier.utf8))).base64URL]
177 if saved == nil { items["agent_name_hint"] = "Jerry" }
178 else { items["id_token_hint"] = saved?.idToken }
179 url.queryItems = items.sorted { $0.key < $1.key }.map { .init(name: $0.key, value: $0.value) }
180 if let address = url.url, NSWorkspace.shared.open(address) { self.status = "Finish sign-in in your browser"; self.onChange?() }
181 else { self.fail(AgentConnectionError(message: "Could not open the sign-in browser."), attempt: id) }
182 } else if case .failed(let error) = listenerState { self.fail(AgentConnectionError(message: "Could not start the local sign-in callback: \(error.localizedDescription)"), attempt: id) }
183 }
184 }
185 listener.start(queue: .main)
186 loginTimeout = Task { [weak self] in
187 try? await Task.sleep(for: .seconds(300))
188 guard !Task.isCancelled else { return }
189 self?.fail(AgentConnectionError(message: "Sign-in timed out. Please try again."), attempt: id)
190 }
191 } catch { cancelSignIn(); status = error.localizedDescription; onChange?() }
192 }
193 private func fail(_ error: Error, attempt id: UUID) {
194 guard attempt == id else { return }
195 cancelSignIn(); status = error.localizedDescription; onChange?()
196 }
197 nonisolated private static func receiveCallback(_ connection: NWConnection, pending: String, expectedState: String, complete: @escaping @Sendable ([String: String]) -> Void) {
198 connection.receive(minimumIncompleteLength: 1, maximumLength: 16384) { data, _, ended, error in
199 let request = pending + (data.flatMap { String(data: $0, encoding: .utf8) } ?? "")
200 guard request.utf8.count <= 16384 else { connection.cancel(); return }
201 if !request.contains("\r\n\r\n"), !ended, error == nil { receiveCallback(connection, pending: request, expectedState: expectedState, complete: complete); return }
202 let path = request.components(separatedBy: "\r\n").first?.split(separator: " ")
203 let url = path.flatMap { $0.count >= 2 && $0[0] == "GET" ? URLComponents(string: "http://127.0.0.1" + String($0[1])) : nil }
204 let pairs = url?.queryItems ?? []
205 var values: [String: String] = [:]
206 var duplicate = false
207 for item in pairs { if values[item.name] != nil { duplicate = true }; values[item.name] = item.value ?? "" }
208 let valid = url?.path == "/auth/callback" && values["state"] == expectedState && !duplicate
209 let body = valid ? "Sign-in received. Return to Jerry to see the result. You can close this tab." : "Invalid sign-in callback. Return to Jerry and retry."
210 let response = "HTTP/1.1 \(valid ? "200 OK" : "400 Bad Request")\r\nContent-Type: text/plain; charset=utf-8\r\nCache-Control: no-store\r\nConnection: close\r\nContent-Length: \(body.utf8.count)\r\n\r\n\(body)"
211 connection.send(content: Data(response.utf8), completion: .contentProcessed { _ in connection.cancel(); if valid { complete(values) } })
212 }
213 }
214 func accessToken() async throws -> String {
215 guard let record = account else { throw AgentConnectionError(message: "Continue with ChatGPT first.") }
216 if record.expiresAt.timeIntervalSinceNow > 60 { return record.accessToken }
217 if let refreshTask { return try await refreshTask.value }
218 let task = Task { @MainActor [weak self] () throws -> String in
219 guard let self else { throw CancellationError() }
220 let response = try await Self.tokenRequest(["grant_type": "refresh_token", "client_id": record.clientID, "refresh_token": record.refreshToken, "resource": "https://api.openai.com/v1"])
221 var identity = (subject: record.subject, email: record.email)
222 if let jwt = response["id_token"] as? String {
223 identity = try await Self.validateIdentity(jwt, clientID: record.clientID, nonce: nil)
224 guard identity.subject == record.subject else { throw AgentConnectionError(message: "The refreshed account identity changed. Please reconnect.") }
225 }
226 let renewed = try Self.record(response, clientID: record.clientID, identity: identity, previous: record)
227 try Task.checkCancellation()
228 try self.save(JSONEncoder().encode(renewed), as: "chatgpt")
229 return renewed.accessToken
230 }
231 refreshTask = task
232 defer { refreshTask = nil }
233 return try await task.value
234 }
235 private static func record(_ data: [String: Any], clientID: String, identity: (subject: String, email: String), previous: Account?) throws -> Account {
236 let scopes = (data["scope"] as? String)?.split(separator: " ").map(String.init) ?? previous?.scopes ?? []
237 guard let access = data["access_token"] as? String, !access.isEmpty,
238 let refresh = data["refresh_token"] as? String ?? previous?.refreshToken,
239 scopes.contains("chatgpt.tokens.use.direct"), scopes.contains("resource.invoke"),
240 (data["token_type"] as? String)?.lowercased() == "bearer" else { throw AgentConnectionError(message: "ChatGPT did not grant plan usage. Reconnect and enable plan usage in the browser.") }
241 return .init(clientID: clientID, subject: identity.subject, email: identity.email, accessToken: access, refreshToken: refresh,
242 idToken: data["id_token"] as? String ?? previous?.idToken ?? "", expiresAt: Date(timeIntervalSinceNow: (data["expires_in"] as? Double) ?? 3600), scopes: scopes)
243 }
244 private static func tokenRequest(_ values: [String: String]) async throws -> [String: Any] {
245 var request = URLRequest(url: URL(string: "https://auth.openai.com/api/accounts/oauth/token")!)
246 request.httpMethod = "POST"; request.timeoutInterval = 45
247 request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
248 var allowed = CharacterSet.alphanumerics; allowed.insert(charactersIn: "-._~")
249 request.httpBody = Data(values.sorted { $0.key < $1.key }.map { "\($0.key.addingPercentEncoding(withAllowedCharacters: allowed)!)=\($0.value.addingPercentEncoding(withAllowedCharacters: allowed)!)" }.joined(separator: "&").utf8)
250 let (data, response) = try await URLSession.shared.data(for: request)
251 guard let http = response as? HTTPURLResponse, (200..<300).contains(http.statusCode), let result = try JSONSerialization.jsonObject(with: data) as? [String: Any] else {
252 throw AgentConnectionError(message: "ChatGPT token exchange failed. Start a fresh sign-in; the account or local-app flow may not be enabled.")
253 }
254 return result
255 }
256 /// OIDC signature, issuer, audience, nonce and expiry are checked before saving.
257 private static func validateIdentity(_ token: String, clientID: String, nonce: String?) async throws -> (subject: String, email: String) {
258 let parts = token.split(separator: ".").map(String.init)
259 guard parts.count == 3, let headerData = Data(base64URL: parts[0]), let claimsData = Data(base64URL: parts[1]), let signature = Data(base64URL: parts[2]),
260 let header = try JSONSerialization.jsonObject(with: headerData) as? [String: Any], let claims = try JSONSerialization.jsonObject(with: claimsData) as? [String: Any],
261 let kid = header["kid"] as? String, let alg = header["alg"] as? String,
262 claims["iss"] as? String == "https://auth.openai.com", (nonce == nil || claims["nonce"] as? String == nonce),
263 (claims["azp"] == nil || claims["azp"] as? String == clientID),
264 ((claims["aud"] as? [String])?.count ?? 1 <= 1 || claims["azp"] as? String == clientID),
265 (claims["aud"] as? String == clientID || (claims["aud"] as? [String])?.contains(clientID) == true),
266 let expires = claims["exp"] as? Double, expires > Date().timeIntervalSince1970,
267 let subject = claims["sub"] as? String, !subject.isEmpty else { throw AgentConnectionError(message: "ChatGPT identity validation failed.") }
268 let (discoveryData, discoveryResponse) = try await URLSession.shared.data(from: URL(string: "https://auth.openai.com/.well-known/openid-configuration")!)
269 guard (discoveryResponse as? HTTPURLResponse)?.statusCode == 200,
270 let discovery = try JSONSerialization.jsonObject(with: discoveryData) as? [String: Any], discovery["issuer"] as? String == "https://auth.openai.com",
271 let jwks = discovery["jwks_uri"] as? String, let jwksURL = URL(string: jwks), jwksURL.scheme == "https", jwksURL.host == "auth.openai.com" else { throw AgentConnectionError(message: "Could not verify the ChatGPT identity issuer.") }
272 let (keyData, keyResponse) = try await URLSession.shared.data(from: jwksURL)
273 guard (keyResponse as? HTTPURLResponse)?.statusCode == 200,
274 let keys = try JSONSerialization.jsonObject(with: keyData) as? [String: Any], let list = keys["keys"] as? [[String: Any]],
275 let key = list.first(where: { $0["kid"] as? String == kid && ($0["alg"] == nil || $0["alg"] as? String == alg) }) else { throw AgentConnectionError(message: "Could not find the ChatGPT identity signing key.") }
276 let message = Data((parts[0] + "." + parts[1]).utf8)
277 let valid: Bool
278 if alg == "RS256", key["kty"] as? String == "RSA", let n = key["n"] as? String, let e = key["e"] as? String, let modulus = Data(base64URL: n), let exponent = Data(base64URL: e) {
279 func der(_ tag: UInt8, _ value: Data) -> Data {
280 let length: [UInt8] = value.count < 128 ? [UInt8(value.count)] : (value.count < 256 ? [0x81, UInt8(value.count)] : [0x82, UInt8(value.count >> 8), UInt8(value.count & 255)])
281 return Data([tag] + length) + value
282 }
283 func integer(_ value: Data) -> Data { der(2, value.first.map { $0 >= 128 } == true ? Data([0]) + value : value) }
284 let encoded = der(0x30, integer(modulus) + integer(exponent))
285 let attributes: [String: Any] = [kSecAttrKeyType as String: kSecAttrKeyTypeRSA, kSecAttrKeyClass as String: kSecAttrKeyClassPublic]
286 if let publicKey = SecKeyCreateWithData(encoded as CFData, attributes as CFDictionary, nil) { valid = SecKeyVerifySignature(publicKey, .rsaSignatureMessagePKCS1v15SHA256, message as CFData, signature as CFData, nil) } else { valid = false }
287 } else if alg == "ES256", key["kty"] as? String == "EC", key["crv"] as? String == "P-256", let x = key["x"] as? String, let y = key["y"] as? String,
288 let dx = Data(base64URL: x), let dy = Data(base64URL: y) {
289 valid = try P256.Signing.PublicKey(x963Representation: Data([4]) + dx + dy).isValidSignature(P256.Signing.ECDSASignature(rawRepresentation: signature), for: message)
290 } else { valid = false }
291 guard valid else { throw AgentConnectionError(message: "The ChatGPT identity signature is invalid.") }
292 return (subject, claims["email"] as? String ?? "ChatGPT account")
293 }
294}
295
296extension Data {
297 var base64URL: String { base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") }
298 init?(base64URL: String) {
299 let value = base64URL.replacingOccurrences(of: "-", with: "+").replacingOccurrences(of: "_", with: "/")
300 self.init(base64Encoded: value + String(repeating: "=", count: (4 - value.count % 4) % 4))
301 }
302}