import Foundation import CryptoKit /// Sign in with Coinbase (OAuth 2 with PKCE). Coinbase requires a client secret for the token /// exchange, and that secret can't ship inside an app, so token requests go through a small /// pass-through at connect.bucksley.ai (the `connect/` folder in this repo). It adds the secret, /// forwards the request to Coinbase and returns the answer. It stores nothing. The refresh token /// lives only in this Mac's Keychain, and balances are read straight from Coinbase. public enum CoinbaseSignIn { public static let server = URL(string: "https://connect.bucksley.ai")! public static let callbackScheme = "bucksley" struct Config: Decodable { let client_id: String; let redirect_uri: String; let scope: String } struct Tokens: Decodable { let access_token: String; let refresh_token: String } /// What the Keychain keeps for a signed-in connection. public struct Saved: Codable, Sendable { public var refreshToken: String var encoded: String { String(data: (try? JSONEncoder().encode(self)) ?? Data(), encoding: .utf8) ?? "" } static func decode(_ text: String) -> Saved? { text.data(using: .utf8).flatMap { try? JSONDecoder().decode(Saved.self, from: $0) } } } /// The Coinbase page to open, with the PKCE verifier and state to check when Coinbase comes back. public struct Request: Sendable { public let url: URL public let state: String public let verifier: String } /// True once connect.bucksley.ai has a Coinbase client to sign in with. Until Coinbase approves /// Bucksley's OAuth client, Settings shows only the API-key option. public static func isAvailable(http: HTTPClient = URLSessionHTTP()) async -> Bool { guard let data = try? await send(URLRequest(url: server.appendingPathComponent("coinbase/config")), http: http) else { return false } return (try? JSONDecoder().decode(Config.self, from: data)) != nil } public static func start(http: HTTPClient = URLSessionHTTP()) async throws -> Request { let config = try JSONDecoder().decode(Config.self, from: try await send(URLRequest(url: server.appendingPathComponent("coinbase/config")), http: http)) let verifier = random(48), state = random(16) let challenge = Coinbase.base64URL(Data(SHA256.hash(data: Data(verifier.utf8)))) var parts = URLComponents(string: "https://login.coinbase.com/oauth2/auth")! parts.queryItems = [.init(name: "response_type", value: "code"), .init(name: "client_id", value: config.client_id), .init(name: "redirect_uri", value: config.redirect_uri), .init(name: "scope", value: config.scope), .init(name: "state", value: state), .init(name: "code_challenge", value: challenge), .init(name: "code_challenge_method", value: "S256")] return Request(url: parts.url!, state: state, verifier: verifier) } /// Reads the code from the URL Coinbase sent back (through connect.bucksley.ai) after checking its state. public static func code(from callback: URL, expecting request: Request) throws -> String { let items = URLComponents(url: callback, resolvingAgainstBaseURL: false)?.queryItems ?? [] func value(_ name: String) -> String? { items.first { $0.name == name }?.value } if let error = value("error") { throw BucksleyError.notAllowed(error == "access_denied" ? "Coinbase sign-in was canceled." : "Coinbase sign-in failed: \(error).") } guard value("state") == request.state, let code = value("code"), !code.isEmpty else { throw BucksleyError.invalid("Coinbase's answer didn't match this sign-in. Try again.") } return code } static func exchange(code: String, verifier: String, http: HTTPClient) async throws -> Tokens { try await token(["grant_type": "authorization_code", "code": code, "code_verifier": verifier], http: http) } static func refresh(_ refreshToken: String, http: HTTPClient) async throws -> Tokens { try await token(["grant_type": "refresh_token", "refresh_token": refreshToken], http: http) } static func token(_ body: [String: String], http: HTTPClient) async throws -> Tokens { var request = URLRequest(url: server.appendingPathComponent("coinbase/token")) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") request.httpBody = try JSONSerialization.data(withJSONObject: body) return try JSONDecoder().decode(Tokens.self, from: try await send(request, http: http)) } static func send(_ request: URLRequest, http: HTTPClient) async throws -> Data { let (data, response) = try await http.send(request) switch response.statusCode { case 200..<300: return data case 400, 401: throw BucksleyError.notAllowed("Coinbase signed Bucksley out. Sign in with Coinbase again in Settings → Connections.") default: throw BucksleyError.network("Coinbase sign-in answered \(response.statusCode).") } } static func random(_ bytes: Int) -> String { Coinbase.base64URL(Data((0..