import Foundation import CryptoKit /// Coinbase, read-only, two ways in: "Sign in with Coinbase" (OAuth, see `CoinbaseSignIn`), or the /// user's own CDP Secret API key with only "View" permission, for which Bucksley signs a short-lived /// JWT for each request on the Mac. Either way it reads wallet balances from the Coinbase App API. Crypto shows as one /// account whose holdings are the coins; the USD wallet shows as a cash account. No trading, no /// on-chain wallets, no transactions. public struct Coinbase: Sendable { /// What the Keychain keeps for a Coinbase connection, as JSON. public struct Key: Codable, Sendable { public var name: String public var privateKey: String public init(name: String, privateKey: String) { self.name = name.trimmingCharacters(in: .whitespacesAndNewlines) self.privateKey = privateKey.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "\\n", with: "\n") } /// The JSON file Coinbase downloads ({"name": …, "privateKey": …}, or "id" for Ed25519 keys). public init?(json: String) { guard let data = json.data(using: .utf8), let o = try? JSONSerialization.jsonObject(with: data) as? [String: Any], let secret = o["privateKey"] as? String, let name = (o["name"] as? String) ?? (o["id"] as? String) else { return nil } self.init(name: name, privateKey: secret) } var encoded: String { String(data: (try? JSONEncoder().encode(self)) ?? Data(), encoding: .utf8) ?? "" } static func decode(_ text: String) -> Key? { text.data(using: .utf8).flatMap { try? JSONDecoder().decode(Key.self, from: $0) } } } enum Auth { case key(Key), bearer(String) } let auth: Auth let http: HTTPClient public init(key: Key, http: HTTPClient = URLSessionHTTP()) { auth = .key(key); self.http = http } /// With an OAuth access token from Sign in with Coinbase. public init(accessToken: String, http: HTTPClient = URLSessionHTTP()) { auth = .bearer(accessToken); self.http = http } static let host = "api.coinbase.com" // MARK: Signing /// ES256 for ECDSA keys (PEM), EdDSA for Ed25519 keys (base64), per Coinbase's CDP key auth. func jwt(method: String, path: String, now: Date = .now) throws -> String { guard case .key(let key) = auth else { throw BucksleyError.invalid("No Coinbase API key to sign with.") } let isPEM = key.privateKey.contains("BEGIN") let header: [String: Any] = ["alg": isPEM ? "ES256" : "EdDSA", "kid": key.name, "typ": "JWT", "nonce": (0..<16).map { _ in String(format: "%02x", UInt8.random(in: 0...255)) }.joined()] let t = Int(now.timeIntervalSince1970) let payload: [String: Any] = ["sub": key.name, "iss": "cdp", "nbf": t, "exp": t + 120, "uri": "\(method) \(Self.host)\(path)"] let signingInput = try Self.base64URL(JSONSerialization.data(withJSONObject: header, options: .sortedKeys)) + "." + Self.base64URL(JSONSerialization.data(withJSONObject: payload, options: .sortedKeys)) let message = Data(signingInput.utf8) let signature: Data if isPEM { let pk: P256.Signing.PrivateKey do { pk = try P256.Signing.PrivateKey(pemRepresentation: key.privateKey) } catch { throw BucksleyError.invalid("That Coinbase private key isn't a valid ECDSA key. Paste the whole key, including the BEGIN and END lines.") } signature = try pk.signature(for: message).rawRepresentation } else { guard let raw = Data(base64Encoded: key.privateKey), raw.count == 64 || raw.count == 32, let pk = try? Curve25519.Signing.PrivateKey(rawRepresentation: raw.prefix(32)) else { throw BucksleyError.invalid("That Coinbase private key isn't a valid Ed25519 key.") } signature = try pk.signature(for: message) } return signingInput + "." + Self.base64URL(signature) } static func base64URL(_ data: Data) -> String { data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "") } // MARK: Reading struct Wallet: Decodable { struct Money: Decodable { let amount: String; let currency: String } struct Currency: Decodable { let code: String; let name: String? } let id: String let name: String? let type: String? let currency: Currency let balance: Money } struct Page: Decodable { struct Pagination: Decodable { let next_uri: String? } let data: [Wallet] let pagination: Pagination? } struct Rates: Decodable { struct D: Decodable { let rates: [String: String] }; let data: D } func get(_ path: String, signed: Bool) async throws -> Data { var request = URLRequest(url: URL(string: "https://\(Self.host)\(path)")!) request.setValue("application/json", forHTTPHeaderField: "Accept") if signed { switch auth { case .bearer(let token): request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization") case .key: let bare = path.split(separator: "?", maxSplits: 1).first.map(String.init) ?? path request.setValue("Bearer " + (try jwt(method: "GET", path: bare)), forHTTPHeaderField: "Authorization") } } let (data, response) = try await http.send(request) switch response.statusCode { case 200..<300: return data case 401: if case .bearer = auth { throw BucksleyError.notAllowed("Coinbase signed Bucksley out. Sign in with Coinbase again in Settings → Connections.") } throw BucksleyError.notAllowed("Coinbase didn't accept that API key. Check the key name and private key, and that the key has View permission.") case 403: throw BucksleyError.notAllowed("That Coinbase key can't read accounts. Give it View permission on portal.cdp.coinbase.com.") default: throw BucksleyError.network("Coinbase answered \(response.statusCode).") } } public func pull(connectionID: String, now: Date = .now) async throws -> BankPull { var wallets: [Wallet] = [] var path: String? = "/v2/accounts?limit=100" while let p = path, wallets.count < 2_000 { let page = try JSONDecoder().decode(Page.self, from: try await get(p, signed: true)) wallets += page.data path = page.pagination?.next_uri.flatMap { $0.isEmpty ? nil : $0 } } // Public USD rates: units of each currency per dollar. let rates = try JSONDecoder().decode(Rates.self, from: try await get("/v2/exchange-rates?currency=USD", signed: false)).data.rates return Self.pull(wallets: wallets, rates: rates, connectionID: connectionID, now: now) } static func pull(wallets: [Wallet], rates: [String: String], connectionID: String, now: Date) -> BankPull { var pull = BankPull() var cash: Decimal = 0, holdings: [Holding] = [], unpriced: [String] = [] for w in wallets { guard let amount = Decimal(string: w.balance.amount), amount != 0 else { continue } let code = w.currency.code.uppercased() if code == "USD" { cash += amount; continue } guard let rate = rates[code].flatMap({ Decimal(string: $0) }), rate > 0 else { unpriced.append(code); continue } holdings.append(Holding(id: "coinbase.\(w.id)", symbol: code, name: w.currency.name ?? code, shares: amount, marketValue: (amount / rate).rounded(2), costBasis: nil)) } holdings.sort { $0.marketValue > $1.marketValue } var crypto = Account(id: "\(connectionID).crypto", connectionID: connectionID, name: "Coinbase Crypto", institution: "Coinbase", kind: .crypto, balance: holdings.reduce(0) { $0 + $1.marketValue }, balanceDate: now) crypto.holdings = holdings pull.accounts = [crypto, Account(id: "\(connectionID).usd", connectionID: connectionID, name: "Coinbase Cash", institution: "Coinbase", kind: .savings, balance: cash, available: cash, balanceDate: now)] if !unpriced.isEmpty { pull.warnings.append("Coinbase has no USD price for \(unpriced.sorted().joined(separator: ", ")), so they're left out.") } return pull } } #if DEBUG extension Coinbase { /// Test fixture for screenshots only: three made-up wallets and fixed prices, no network. public static func fixturePull(connectionID: String, now: Date = .now) -> BankPull { func w(_ id: String, _ code: String, _ name: String, _ amount: String) -> Wallet { Wallet(id: id, name: name, type: "wallet", currency: .init(code: code, name: name), balance: .init(amount: amount, currency: code)) } return pull(wallets: [w("f1", "BTC", "Bitcoin", "0.0421"), w("f2", "ETH", "Ethereum", "1.35"), w("f3", "SOL", "Solana", "12.8"), w("f4", "USD", "Cash (USD)", "1284.50")], rates: ["BTC": "0.0000105", "ETH": "0.00031", "SOL": "0.0068"], connectionID: connectionID, now: now) } } #endif extension BankSync { /// Saves a Coinbase key and runs a first sync. public func connectCoinbase(_ key: Coinbase.Key) async throws -> Connection { guard !key.name.isEmpty, !key.privateKey.isEmpty else { throw BucksleyError.missing("Paste the API key name and the private key.") } let connection = Connection(kind: .coinbase, name: "Coinbase") let pull = try await Coinbase(key: key, http: http).pull(connectionID: connection.id) try Keychain.set(key.encoded, for: .connection(connection.id)) try store.update { $0.connections.append(connection) } try apply(pull, to: connection) return connection } /// Saves a Sign in with Coinbase connection from the code Coinbase sent back, and runs a first sync. public func connectCoinbase(signInCode code: String, verifier: String) async throws -> Connection { let tokens = try await CoinbaseSignIn.exchange(code: code, verifier: verifier, http: http) let connection = Connection(kind: .coinbase, name: "Coinbase") try Keychain.set(CoinbaseSignIn.Saved(refreshToken: tokens.refresh_token).encoded, for: .connection(connection.id)) let pull = try await Coinbase(accessToken: tokens.access_token, http: http).pull(connectionID: connection.id) try store.update { $0.connections.append(connection) } try apply(pull, to: connection) return connection } func pullCoinbase(secret: String, connectionID: String, now: Date) async throws -> BankPull { if let key = Coinbase.Key.decode(secret) { return try await Coinbase(key: key, http: http).pull(connectionID: connectionID, now: now) } guard let saved = CoinbaseSignIn.Saved.decode(secret) else { throw BucksleyError.missing("Coinbase's sign-in on this Mac is unreadable. Connect Coinbase again in Settings → Connections.") } // Coinbase refresh tokens work once: keep the new one before doing anything else. let tokens = try await CoinbaseSignIn.refresh(saved.refreshToken, http: http) try Keychain.set(CoinbaseSignIn.Saved(refreshToken: tokens.refresh_token).encoded, for: .connection(connectionID)) return try await Coinbase(accessToken: tokens.access_token, http: http).pull(connectionID: connectionID, now: now) } }