Branchwell

Bucksley / app / Sources / BucksleyKit / Coinbase.swift

1import Foundation
2import CryptoKit
3
4/// Coinbase, read-only, two ways in: "Sign in with Coinbase" (OAuth, see `CoinbaseSignIn`), or the
5/// user's own CDP Secret API key with only "View" permission, for which Bucksley signs a short-lived
6/// JWT for each request on the Mac. Either way it reads wallet balances from the Coinbase App API. Crypto shows as one
7/// account whose holdings are the coins; the USD wallet shows as a cash account. No trading, no
8/// on-chain wallets, no transactions.
9public struct Coinbase: Sendable {
10 /// What the Keychain keeps for a Coinbase connection, as JSON.
11 public struct Key: Codable, Sendable {
12 public var name: String
13 public var privateKey: String
14 public init(name: String, privateKey: String) {
15 self.name = name.trimmingCharacters(in: .whitespacesAndNewlines)
16 self.privateKey = privateKey.trimmingCharacters(in: .whitespacesAndNewlines).replacingOccurrences(of: "\\n", with: "\n")
17 }
18
19 /// The JSON file Coinbase downloads ({"name": …, "privateKey": …}, or "id" for Ed25519 keys).
20 public init?(json: String) {
21 guard let data = json.data(using: .utf8), let o = try? JSONSerialization.jsonObject(with: data) as? [String: Any],
22 let secret = o["privateKey"] as? String, let name = (o["name"] as? String) ?? (o["id"] as? String) else { return nil }
23 self.init(name: name, privateKey: secret)
24 }
25
26 var encoded: String { String(data: (try? JSONEncoder().encode(self)) ?? Data(), encoding: .utf8) ?? "" }
27 static func decode(_ text: String) -> Key? { text.data(using: .utf8).flatMap { try? JSONDecoder().decode(Key.self, from: $0) } }
28 }
29
30 enum Auth { case key(Key), bearer(String) }
31 let auth: Auth
32 let http: HTTPClient
33 public init(key: Key, http: HTTPClient = URLSessionHTTP()) { auth = .key(key); self.http = http }
34 /// With an OAuth access token from Sign in with Coinbase.
35 public init(accessToken: String, http: HTTPClient = URLSessionHTTP()) { auth = .bearer(accessToken); self.http = http }
36
37 static let host = "api.coinbase.com"
38
39 // MARK: Signing
40
41 /// ES256 for ECDSA keys (PEM), EdDSA for Ed25519 keys (base64), per Coinbase's CDP key auth.
42 func jwt(method: String, path: String, now: Date = .now) throws -> String {
43 guard case .key(let key) = auth else { throw BucksleyError.invalid("No Coinbase API key to sign with.") }
44 let isPEM = key.privateKey.contains("BEGIN")
45 let header: [String: Any] = ["alg": isPEM ? "ES256" : "EdDSA", "kid": key.name, "typ": "JWT",
46 "nonce": (0..<16).map { _ in String(format: "%02x", UInt8.random(in: 0...255)) }.joined()]
47 let t = Int(now.timeIntervalSince1970)
48 let payload: [String: Any] = ["sub": key.name, "iss": "cdp", "nbf": t, "exp": t + 120, "uri": "\(method) \(Self.host)\(path)"]
49 let signingInput = try Self.base64URL(JSONSerialization.data(withJSONObject: header, options: .sortedKeys)) + "."
50 + Self.base64URL(JSONSerialization.data(withJSONObject: payload, options: .sortedKeys))
51 let message = Data(signingInput.utf8)
52 let signature: Data
53 if isPEM {
54 let pk: P256.Signing.PrivateKey
55 do { pk = try P256.Signing.PrivateKey(pemRepresentation: key.privateKey) }
56 catch { throw BucksleyError.invalid("That Coinbase private key isn't a valid ECDSA key. Paste the whole key, including the BEGIN and END lines.") }
57 signature = try pk.signature(for: message).rawRepresentation
58 } else {
59 guard let raw = Data(base64Encoded: key.privateKey), raw.count == 64 || raw.count == 32,
60 let pk = try? Curve25519.Signing.PrivateKey(rawRepresentation: raw.prefix(32)) else {
61 throw BucksleyError.invalid("That Coinbase private key isn't a valid Ed25519 key.")
62 }
63 signature = try pk.signature(for: message)
64 }
65 return signingInput + "." + Self.base64URL(signature)
66 }
67
68 static func base64URL(_ data: Data) -> String {
69 data.base64EncodedString().replacingOccurrences(of: "+", with: "-").replacingOccurrences(of: "/", with: "_").replacingOccurrences(of: "=", with: "")
70 }
71
72 // MARK: Reading
73
74 struct Wallet: Decodable {
75 struct Money: Decodable { let amount: String; let currency: String }
76 struct Currency: Decodable { let code: String; let name: String? }
77 let id: String
78 let name: String?
79 let type: String?
80 let currency: Currency
81 let balance: Money
82 }
83 struct Page: Decodable {
84 struct Pagination: Decodable { let next_uri: String? }
85 let data: [Wallet]
86 let pagination: Pagination?
87 }
88 struct Rates: Decodable { struct D: Decodable { let rates: [String: String] }; let data: D }
89
90 func get(_ path: String, signed: Bool) async throws -> Data {
91 var request = URLRequest(url: URL(string: "https://\(Self.host)\(path)")!)
92 request.setValue("application/json", forHTTPHeaderField: "Accept")
93 if signed {
94 switch auth {
95 case .bearer(let token):
96 request.setValue("Bearer " + token, forHTTPHeaderField: "Authorization")
97 case .key:
98 let bare = path.split(separator: "?", maxSplits: 1).first.map(String.init) ?? path
99 request.setValue("Bearer " + (try jwt(method: "GET", path: bare)), forHTTPHeaderField: "Authorization")
100 }
101 }
102 let (data, response) = try await http.send(request)
103 switch response.statusCode {
104 case 200..<300: return data
105 case 401:
106 if case .bearer = auth { throw BucksleyError.notAllowed("Coinbase signed Bucksley out. Sign in with Coinbase again in Settings → Connections.") }
107 throw BucksleyError.notAllowed("Coinbase didn't accept that API key. Check the key name and private key, and that the key has View permission.")
108 case 403: throw BucksleyError.notAllowed("That Coinbase key can't read accounts. Give it View permission on portal.cdp.coinbase.com.")
109 default: throw BucksleyError.network("Coinbase answered \(response.statusCode).")
110 }
111 }
112
113 public func pull(connectionID: String, now: Date = .now) async throws -> BankPull {
114 var wallets: [Wallet] = []
115 var path: String? = "/v2/accounts?limit=100"
116 while let p = path, wallets.count < 2_000 {
117 let page = try JSONDecoder().decode(Page.self, from: try await get(p, signed: true))
118 wallets += page.data
119 path = page.pagination?.next_uri.flatMap { $0.isEmpty ? nil : $0 }
120 }
121 // Public USD rates: units of each currency per dollar.
122 let rates = try JSONDecoder().decode(Rates.self, from: try await get("/v2/exchange-rates?currency=USD", signed: false)).data.rates
123 return Self.pull(wallets: wallets, rates: rates, connectionID: connectionID, now: now)
124 }
125
126 static func pull(wallets: [Wallet], rates: [String: String], connectionID: String, now: Date) -> BankPull {
127 var pull = BankPull()
128 var cash: Decimal = 0, holdings: [Holding] = [], unpriced: [String] = []
129 for w in wallets {
130 guard let amount = Decimal(string: w.balance.amount), amount != 0 else { continue }
131 let code = w.currency.code.uppercased()
132 if code == "USD" { cash += amount; continue }
133 guard let rate = rates[code].flatMap({ Decimal(string: $0) }), rate > 0 else { unpriced.append(code); continue }
134 holdings.append(Holding(id: "coinbase.\(w.id)", symbol: code, name: w.currency.name ?? code, shares: amount,
135 marketValue: (amount / rate).rounded(2), costBasis: nil))
136 }
137 holdings.sort { $0.marketValue > $1.marketValue }
138 var crypto = Account(id: "\(connectionID).crypto", connectionID: connectionID, name: "Coinbase Crypto", institution: "Coinbase",
139 kind: .crypto, balance: holdings.reduce(0) { $0 + $1.marketValue }, balanceDate: now)
140 crypto.holdings = holdings
141 pull.accounts = [crypto,
142 Account(id: "\(connectionID).usd", connectionID: connectionID, name: "Coinbase Cash", institution: "Coinbase",
143 kind: .savings, balance: cash, available: cash, balanceDate: now)]
144 if !unpriced.isEmpty { pull.warnings.append("Coinbase has no USD price for \(unpriced.sorted().joined(separator: ", ")), so they're left out.") }
145 return pull
146 }
147}
148
149#if DEBUG
150extension Coinbase {
151 /// Test fixture for screenshots only: three made-up wallets and fixed prices, no network.
152 public static func fixturePull(connectionID: String, now: Date = .now) -> BankPull {
153 func w(_ id: String, _ code: String, _ name: String, _ amount: String) -> Wallet {
154 Wallet(id: id, name: name, type: "wallet", currency: .init(code: code, name: name), balance: .init(amount: amount, currency: code))
155 }
156 return pull(wallets: [w("f1", "BTC", "Bitcoin", "0.0421"), w("f2", "ETH", "Ethereum", "1.35"), w("f3", "SOL", "Solana", "12.8"),
157 w("f4", "USD", "Cash (USD)", "1284.50")],
158 rates: ["BTC": "0.0000105", "ETH": "0.00031", "SOL": "0.0068"], connectionID: connectionID, now: now)
159 }
160}
161#endif
162
163extension BankSync {
164 /// Saves a Coinbase key and runs a first sync.
165 public func connectCoinbase(_ key: Coinbase.Key) async throws -> Connection {
166 guard !key.name.isEmpty, !key.privateKey.isEmpty else { throw BucksleyError.missing("Paste the API key name and the private key.") }
167 let connection = Connection(kind: .coinbase, name: "Coinbase")
168 let pull = try await Coinbase(key: key, http: http).pull(connectionID: connection.id)
169 try Keychain.set(key.encoded, for: .connection(connection.id))
170 try store.update { $0.connections.append(connection) }
171 try apply(pull, to: connection)
172 return connection
173 }
174
175 /// Saves a Sign in with Coinbase connection from the code Coinbase sent back, and runs a first sync.
176 public func connectCoinbase(signInCode code: String, verifier: String) async throws -> Connection {
177 let tokens = try await CoinbaseSignIn.exchange(code: code, verifier: verifier, http: http)
178 let connection = Connection(kind: .coinbase, name: "Coinbase")
179 try Keychain.set(CoinbaseSignIn.Saved(refreshToken: tokens.refresh_token).encoded, for: .connection(connection.id))
180 let pull = try await Coinbase(accessToken: tokens.access_token, http: http).pull(connectionID: connection.id)
181 try store.update { $0.connections.append(connection) }
182 try apply(pull, to: connection)
183 return connection
184 }
185
186 func pullCoinbase(secret: String, connectionID: String, now: Date) async throws -> BankPull {
187 if let key = Coinbase.Key.decode(secret) {
188 return try await Coinbase(key: key, http: http).pull(connectionID: connectionID, now: now)
189 }
190 guard let saved = CoinbaseSignIn.Saved.decode(secret) else {
191 throw BucksleyError.missing("Coinbase's sign-in on this Mac is unreadable. Connect Coinbase again in Settings → Connections.")
192 }
193 // Coinbase refresh tokens work once: keep the new one before doing anything else.
194 let tokens = try await CoinbaseSignIn.refresh(saved.refreshToken, http: http)
195 try Keychain.set(CoinbaseSignIn.Saved(refreshToken: tokens.refresh_token).encoded, for: .connection(connectionID))
196 return try await Coinbase(accessToken: tokens.access_token, http: http).pull(connectionID: connectionID, now: now)
197 }
198}