Something went wrong. Try again.
become more token aware with this one free trick! providers hate her
Something went wrong. Try again.
8.9 kB · 221 lines
Swift
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222import Foundation
public struct AuthStorage { public static var authURL: URL { let home = FileManager.default.homeDirectoryForCurrentUser return home.appendingPathComponent(".prime/agent/auth.json") }
public static func loadAuth() -> [String: Any]? { guard let data = try? Data(contentsOf: authURL), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return nil } return json }
public static var onAuthSaved: (() -> Void)? = nil
public static func saveAuth(_ dict: [String: Any]) { guard let data = try? JSONSerialization.data(withJSONObject: dict, options: [.prettyPrinted, .sortedKeys]) else { return } let tempURL = authURL.deletingLastPathComponent().appendingPathComponent("auth.json.tmp.\(UUID().uuidString)") do { try data.write(to: tempURL) _ = try FileManager.default.replaceItemAt(authURL, withItemAt: tempURL) onAuthSaved?() } catch { try? FileManager.default.removeItem(at: tempURL) } }
public static func getCredentialList(_ auth: [String: Any], key: String) -> [[String: Any]] { guard let val = auth[key] else { return [] } if let list = val as? [[String: Any]] { return list } if let dict = val as? [String: Any] { return [dict] } return [] }
public static func hasCredential(_ auth: [String: Any], key: String) -> Bool { return !getCredentialList(auth, key: key).isEmpty }
public static func applyCredentialList( auth: inout [String: Any], key: String, credentials: [[String: Any]] ) { if credentials.isEmpty { auth.removeValue(forKey: key) } else if credentials.count == 1 { auth[key] = credentials[0] } else { auth[key] = credentials } }
public static func setCredentialList( auth: inout [String: Any], key: String, credentials: [[String: Any]] ) { applyCredentialList(auth: &auth, key: key, credentials: credentials) saveAuth(auth) }
public static func getApiKey(_ auth: [String: Any], key: String) -> String? { let list = getCredentialList(auth, key: key) for creds in list { if let k = creds["key"] as? String, !k.isEmpty { return k } } return nil }
public static func isTokenValid(creds: [String: Any]) -> Bool { let expires = (creds["expires"] as? Double) ?? (creds["expires"] as? Int).map(Double.init) ?? 0 let nowMs = Date().timeIntervalSince1970 * 1000 guard let access = creds["access"] as? String, !access.isEmpty else { return false } return expires > nowMs + 300_000 }
public static func refreshAnthropicToken(creds: inout [String: Any]) async -> String? { guard let refreshToken = creds["refresh"] as? String, !refreshToken.isEmpty, let tokenURL = URL(string: "https://platform.claude.com/v1/oauth/token") else { return nil }
var request = URLRequest(url: tokenURL) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.setValue("application/json", forHTTPHeaderField: "Accept") request.setValue("claude-cli/1.0.12 (external, cli)", forHTTPHeaderField: "User-Agent")
let body: [String: Any] = [ "grant_type": "refresh_token", "client_id": "9d1c250a-e61b-44d9-88ed-5944d1962f5e", "refresh_token": refreshToken ] request.httpBody = try? JSONSerialization.data(withJSONObject: body)
let nowMs = Date().timeIntervalSince1970 * 1000 do { let (data, response) = try await URLSession.shared.data(for: request) guard let http = response as? HTTPURLResponse, (200...299).contains(http.statusCode), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let newAccess = json["access_token"] as? String else { return nil }
creds["access"] = newAccess if let newRefresh = json["refresh_token"] as? String { creds["refresh"] = newRefresh } if let expiresIn = json["expires_in"] as? Double { creds["expires"] = Int(nowMs + (expiresIn * 1000) - 300_000) } return newAccess } catch { return nil } }
public static func resolveAnthropicToken(creds: inout [String: Any]) async -> String? { if isTokenValid(creds: creds), let access = creds["access"] as? String { return access } return await refreshAnthropicToken(creds: &creds) }
public static func refreshCodexToken(creds: inout [String: Any]) async -> String? { guard let refreshToken = creds["refresh"] as? String, !refreshToken.isEmpty, let tokenURL = URL(string: "https://auth.openai.com/oauth/token") else { return nil }
var request = URLRequest(url: tokenURL) request.httpMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
var components = URLComponents() components.queryItems = [ URLQueryItem(name: "grant_type", value: "refresh_token"), URLQueryItem(name: "refresh_token", value: refreshToken), URLQueryItem(name: "client_id", value: "app_EMoamEEZ73f0CkXaXp7hrann") ] request.httpBody = components.percentEncodedQuery?.data(using: .utf8)
let nowMs = Date().timeIntervalSince1970 * 1000 do { let (data, response) = try await URLSession.shared.data(for: request) guard let http = response as? HTTPURLResponse, (200...299).contains(http.statusCode), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let newAccess = json["access_token"] as? String else { return nil }
creds["access"] = newAccess if let newRefresh = json["refresh_token"] as? String { creds["refresh"] = newRefresh } if let expiresIn = json["expires_in"] as? Double { creds["expires"] = Int(nowMs + (expiresIn * 1000)) } return newAccess } catch { return nil } }
public static func resolveCodexToken(creds: inout [String: Any]) async -> String? { if isTokenValid(creds: creds), let access = creds["access"] as? String { return access } return await refreshCodexToken(creds: &creds) }
public static func refreshAntigravityToken(creds: inout [String: Any]) async -> String? { guard let refreshToken = creds["refresh"] as? String, !refreshToken.isEmpty, let tokenURL = URL(string: "https://oauth2.googleapis.com/token") else { return nil }
var request = URLRequest(url: tokenURL) request.httpMethod = "POST" request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
var components = URLComponents() components.queryItems = [ URLQueryItem(name: "grant_type", value: "refresh_token"), URLQueryItem(name: "refresh_token", value: refreshToken), URLQueryItem(name: "client_id", value: "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com"), URLQueryItem(name: "client_secret", value: "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") ] request.httpBody = components.percentEncodedQuery?.data(using: .utf8)
let nowMs = Date().timeIntervalSince1970 * 1000 do { let (data, response) = try await URLSession.shared.data(for: request) guard let http = response as? HTTPURLResponse, (200...299).contains(http.statusCode), let json = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let newAccess = json["access_token"] as? String else { return nil }
creds["access"] = newAccess if let expiresIn = json["expires_in"] as? Double { creds["expires"] = Int(nowMs + (expiresIn * 1000) - 300_000) } return newAccess } catch { return nil } }
public static func resolveAntigravityToken(creds: inout [String: Any]) async -> String? { if isTokenValid(creds: creds), let access = creds["access"] as? String { return access } return await refreshAntigravityToken(creds: &creds) }}