Branchwell

Bucksley / app / Sources / BucksleyKit / CoinbaseSignIn.swift

1import Foundation
2import CryptoKit
3
4/// Sign in with Coinbase (OAuth 2 with PKCE). Coinbase requires a client secret for the token
5/// exchange, and that secret can't ship inside an app, so token requests go through a small
6/// pass-through at connect.bucksley.ai (the `connect/` folder in this repo). It adds the secret,
7/// forwards the request to Coinbase and returns the answer. It stores nothing. The refresh token
8/// lives only in this Mac's Keychain, and balances are read straight from Coinbase.
9public enum CoinbaseSignIn {
10 public static let server = URL(string: "https://connect.bucksley.ai")!
11 public static let callbackScheme = "bucksley"
12
13 struct Config: Decodable { let client_id: String; let redirect_uri: String; let scope: String }
14 struct Tokens: Decodable { let access_token: String; let refresh_token: String }
15
16 /// What the Keychain keeps for a signed-in connection.
17 public struct Saved: Codable, Sendable {
18 public var refreshToken: String
19 var encoded: String { String(data: (try? JSONEncoder().encode(self)) ?? Data(), encoding: .utf8) ?? "" }
20 static func decode(_ text: String) -> Saved? { text.data(using: .utf8).flatMap { try? JSONDecoder().decode(Saved.self, from: $0) } }
21 }
22
23 /// The Coinbase page to open, with the PKCE verifier and state to check when Coinbase comes back.
24 public struct Request: Sendable {
25 public let url: URL
26 public let state: String
27 public let verifier: String
28 }
29
30 /// True once connect.bucksley.ai has a Coinbase client to sign in with. Until Coinbase approves
31 /// Bucksley's OAuth client, Settings shows only the API-key option.
32 public static func isAvailable(http: HTTPClient = URLSessionHTTP()) async -> Bool {
33 guard let data = try? await send(URLRequest(url: server.appendingPathComponent("coinbase/config")), http: http) else { return false }
34 return (try? JSONDecoder().decode(Config.self, from: data)) != nil
35 }
36
37 public static func start(http: HTTPClient = URLSessionHTTP()) async throws -> Request {
38 let config = try JSONDecoder().decode(Config.self, from: try await send(URLRequest(url: server.appendingPathComponent("coinbase/config")), http: http))
39 let verifier = random(48), state = random(16)
40 let challenge = Coinbase.base64URL(Data(SHA256.hash(data: Data(verifier.utf8))))
41 var parts = URLComponents(string: "https://login.coinbase.com/oauth2/auth")!
42 parts.queryItems = [.init(name: "response_type", value: "code"), .init(name: "client_id", value: config.client_id),
43 .init(name: "redirect_uri", value: config.redirect_uri), .init(name: "scope", value: config.scope),
44 .init(name: "state", value: state), .init(name: "code_challenge", value: challenge),
45 .init(name: "code_challenge_method", value: "S256")]
46 return Request(url: parts.url!, state: state, verifier: verifier)
47 }
48
49 /// Reads the code from the URL Coinbase sent back (through connect.bucksley.ai) after checking its state.
50 public static func code(from callback: URL, expecting request: Request) throws -> String {
51 let items = URLComponents(url: callback, resolvingAgainstBaseURL: false)?.queryItems ?? []
52 func value(_ name: String) -> String? { items.first { $0.name == name }?.value }
53 if let error = value("error") {
54 throw BucksleyError.notAllowed(error == "access_denied" ? "Coinbase sign-in was canceled." : "Coinbase sign-in failed: \(error).")
55 }
56 guard value("state") == request.state, let code = value("code"), !code.isEmpty else {
57 throw BucksleyError.invalid("Coinbase's answer didn't match this sign-in. Try again.")
58 }
59 return code
60 }
61
62 static func exchange(code: String, verifier: String, http: HTTPClient) async throws -> Tokens {
63 try await token(["grant_type": "authorization_code", "code": code, "code_verifier": verifier], http: http)
64 }
65
66 static func refresh(_ refreshToken: String, http: HTTPClient) async throws -> Tokens {
67 try await token(["grant_type": "refresh_token", "refresh_token": refreshToken], http: http)
68 }
69
70 static func token(_ body: [String: String], http: HTTPClient) async throws -> Tokens {
71 var request = URLRequest(url: server.appendingPathComponent("coinbase/token"))
72 request.httpMethod = "POST"
73 request.setValue("application/json", forHTTPHeaderField: "Content-Type")
74 request.httpBody = try JSONSerialization.data(withJSONObject: body)
75 return try JSONDecoder().decode(Tokens.self, from: try await send(request, http: http))
76 }
77
78 static func send(_ request: URLRequest, http: HTTPClient) async throws -> Data {
79 let (data, response) = try await http.send(request)
80 switch response.statusCode {
81 case 200..<300: return data
82 case 400, 401: throw BucksleyError.notAllowed("Coinbase signed Bucksley out. Sign in with Coinbase again in Settings → Connections.")
83 default: throw BucksleyError.network("Coinbase sign-in answered \(response.statusCode).")
84 }
85 }
86
87 static func random(_ bytes: Int) -> String {
88 Coinbase.base64URL(Data((0..<bytes).map { _ in UInt8.random(in: 0...255) }))
89 }
90}