A native macOS / windows / Linux database IDE built with Swift and AppKit. Connect to PostgreSQL, MySQL, SQLite, and Redis from a single app with a fast, keyboard-driven interface.
C++
feat(ai-core): add PKCE + JWT primitives + ChatGPTTokenBundle
cyenx0beaee629930
diff --git a/macos/Core/Models/AI/ChatGPTTokenBundle.swift b/macos/Core/Models/AI/ChatGPTTokenBundle.swiftnew file mode 100644index 0000000..45d51a8--- /dev/null+++ b/macos/Core/Models/AI/ChatGPTTokenBundle.swift@@ -0,0 +1,60 @@+// ChatGPTTokenBundle.swift+// Gridex+//+// OAuth token bundle persisted in Keychain for the .chatGPT provider type.+// Stored as JSON under key "ai.chatgpt.tokens.<provider-uuid>" — a single blob+// so refresh writes are atomic.++import Foundation++struct ChatGPTTokenBundle: Codable, Sendable, Equatable {+ /// JWT — short-lived, used as `Authorization: Bearer ...` against+ /// chatgpt.com/backend-api/codex.+ var accessToken: String++ /// JWT — long-lived, used to mint new access tokens. Server may rotate+ /// this on refresh; callers must merge the new value over the old bundle+ /// (and keep the old refresh_token if the response omits it).+ var refreshToken: String++ /// JWT — carries claims (`chatgpt_account_id`, `email`, `chatgpt_plan_type`).+ /// Persisted so we can re-derive identity without re-querying the server.+ var idToken: String++ /// Mirrors the `chatgpt_account_id` claim from `idToken`. Sent as the+ /// `ChatGPT-Account-ID` header on backend calls when present.+ var accountId: String?++ /// Mirrors the `email` claim. UI-only, for "Signed in as ..." display.+ var email: String?++ /// Mirrors the `chatgpt_plan_type` claim (e.g. "plus", "pro"). UI-only.+ var planType: String?++ /// Wall-clock time the bundle was minted (sign-in or last refresh).+ var obtainedAt: Date++ /// Reserved for future migrations if OpenAI changes the id_token claim+ /// shape. v1 = the layout above.+ var schemaVersion: Int++ init(+ accessToken: String,+ refreshToken: String,+ idToken: String,+ accountId: String? = nil,+ email: String? = nil,+ planType: String? = nil,+ obtainedAt: Date = Date(),+ schemaVersion: Int = 1+ ) {+ self.accessToken = accessToken+ self.refreshToken = refreshToken+ self.idToken = idToken+ self.accountId = accountId+ self.email = email+ self.planType = planType+ self.obtainedAt = obtainedAt+ self.schemaVersion = schemaVersion+ }+}diff --git a/macos/Services/AI/Auth/JWTDecoder.swift b/macos/Services/AI/Auth/JWTDecoder.swiftnew file mode 100644index 0000000..cbfc389--- /dev/null+++ b/macos/Services/AI/Auth/JWTDecoder.swift@@ -0,0 +1,66 @@+// JWTDecoder.swift+// Gridex+//+// Minimal JWT payload decoder. We never verify the signature here — the issuer+// is auth.openai.com over TLS, and refresh failures are surfaced by the server.+// We only need to read claims (`exp`, `email`, `chatgpt_account_id`, …).++import Foundation++enum JWTDecoder {+ enum DecodeError: Error, CustomStringConvertible {+ case malformed(String)+ var description: String {+ switch self {+ case .malformed(let why): return "Malformed JWT: \(why)"+ }+ }+ }++ /// Decodes the second segment of a JWT (the payload) into a JSON dictionary.+ /// Throws `DecodeError.malformed` if the token doesn't have the expected+ /// `header.payload.signature` shape or the payload isn't a JSON object.+ static func payload(of jwt: String) throws -> [String: Any] {+ let parts = jwt.split(separator: ".", omittingEmptySubsequences: false)+ guard parts.count == 3 else {+ throw DecodeError.malformed("expected 3 segments, got \(parts.count)")+ }+ guard let data = base64URLDecode(String(parts[1])) else {+ throw DecodeError.malformed("payload is not valid base64url")+ }+ guard+ let json = try JSONSerialization.jsonObject(with: data) as? [String: Any]+ else {+ throw DecodeError.malformed("payload is not a JSON object")+ }+ return json+ }++ /// Convenience: extract the `exp` claim and convert to a Date. Returns nil+ /// if the claim is missing or not a number — caller should treat that as+ /// "expired" (forces a refresh).+ static func expiration(of jwt: String) -> Date? {+ guard let claims = try? payload(of: jwt) else { return nil }+ guard let exp = claims["exp"] as? TimeInterval else {+ // Some JWTs encode exp as Int — try that too+ if let expInt = claims["exp"] as? Int {+ return Date(timeIntervalSince1970: TimeInterval(expInt))+ }+ return nil+ }+ return Date(timeIntervalSince1970: exp)+ }++ // MARK: - Internal++ /// base64url → Data. Re-pads to a multiple of 4 with `=` and reverses the+ /// URL-safe substitutions before delegating to `Data(base64Encoded:)`.+ static func base64URLDecode(_ s: String) -> Data? {+ var str = s+ .replacingOccurrences(of: "-", with: "+")+ .replacingOccurrences(of: "_", with: "/")+ let pad = str.count % 4+ if pad > 0 { str.append(String(repeating: "=", count: 4 - pad)) }+ return Data(base64Encoded: str)+ }+}diff --git a/macos/Services/AI/Auth/PKCE.swift b/macos/Services/AI/Auth/PKCE.swiftnew file mode 100644index 0000000..f154d22--- /dev/null+++ b/macos/Services/AI/Auth/PKCE.swift@@ -0,0 +1,58 @@+// PKCE.swift+// Gridex+//+// RFC 7636 PKCE primitives for the ChatGPT OAuth flow. Pure functions, no I/O.+//+// All outputs are base64url-no-pad: standard base64, then `+` → `-`, `/` → `_`,+// trailing `=` stripped.++import CryptoKit+import Foundation+import Security++enum PKCE {+ /// 32 random bytes → base64url-no-pad (43 chars). Suitable as `code_verifier`.+ static func makeVerifier() -> String {+ base64URL(randomBytes(count: 32))+ }++ /// SHA256(verifier) → base64url-no-pad. Used as `code_challenge`+ /// with `code_challenge_method=S256`.+ static func challenge(for verifier: String) -> String {+ let data = Data(verifier.utf8)+ let hash = SHA256.hash(data: data)+ return base64URL(Data(hash))+ }++ /// 32 random bytes → base64url-no-pad. Used as the OAuth `state` param to+ /// detect CSRF on the loopback callback.+ static func makeState() -> String {+ base64URL(randomBytes(count: 32))+ }++ /// Standard base64 → URL-safe variant (no padding).+ /// Exposed for tests that need to verify against RFC 7636 vectors.+ static func base64URL(_ data: Data) -> String {+ data.base64EncodedString()+ .replacingOccurrences(of: "+", with: "-")+ .replacingOccurrences(of: "/", with: "_")+ .replacingOccurrences(of: "=", with: "")+ }++ // MARK: - Internal++ /// Cryptographically secure random bytes via Security framework's CSPRNG.+ /// Falls back to `SystemRandomNumberGenerator` only if `SecRandomCopyBytes`+ /// somehow fails — should never happen on healthy macOS hosts.+ private static func randomBytes(count: Int) -> Data {+ var bytes = [UInt8](repeating: 0, count: count)+ let status = SecRandomCopyBytes(kSecRandomDefault, count, &bytes)+ guard status == errSecSuccess else {+ // Last-resort fallback — keeps the API total without crashing.+ var rng = SystemRandomNumberGenerator()+ for i in 0..<count { bytes[i] = UInt8.random(in: 0...255, using: &rng) }+ return Data(bytes)+ }+ return Data(bytes)+ }+}