import Foundation /// The network, injectable so connector tests run against recorded responses. public protocol HTTPClient: Sendable { func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) } public struct URLSessionHTTP: HTTPClient { public init() {} public func send(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) { let (data, response) = try await URLSession.shared.data(for: request) guard let http = response as? HTTPURLResponse else { throw BucksleyError.network("No HTTP response.") } return (data, http) } } /// What one sync of one connection brought back. public struct BankPull: Sendable { public var accounts: [Account] = [] public var transactions: [Transaction] = [] public var removedTransactionIDs: [String] = [] public var plaidCursor: String? public var warnings: [String] = [] public init() {} } // MARK: SimpleFIN Bridge /// SimpleFIN Bridge (https://beta-bridge.simplefin.org): the user pastes a setup token, which is /// exchanged once for an access URL. That URL (with its credentials) is the secret kept in the /// Keychain; the Mac reads accounts and transactions from it directly. No server in between. public struct SimpleFIN: Sendable { let http: HTTPClient public init(http: HTTPClient = URLSessionHTTP()) { self.http = http } /// The public demo bridge, handy for trying Bucksley without a bank. public static let demoAccessURL = "https://demo:demo@beta-bridge.simplefin.org/simplefin" /// Setup token (base64 of a claim URL) → access URL. A token can be claimed only once. public func claim(setupToken: String) async throws -> String { let trimmed = setupToken.trimmingCharacters(in: .whitespacesAndNewlines) guard let data = Data(base64Encoded: trimmed) ?? Data(base64Encoded: trimmed + String(repeating: "=", count: (4 - trimmed.count % 4) % 4)), let claim = String(data: data, encoding: .utf8), let url = URL(string: claim), url.scheme == "https" else { throw BucksleyError.invalid("That doesn't look like a SimpleFIN setup token. Copy it again from SimpleFIN Bridge → Connect an app.") } var request = URLRequest(url: url); request.httpMethod = "POST"; request.setValue("0", forHTTPHeaderField: "Content-Length") let (body, response) = try await http.send(request) guard response.statusCode == 200, let access = String(data: body, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines), access.hasPrefix("https://") else { throw BucksleyError.network(response.statusCode == 403 ? "This setup token was already used or has expired. Make a new one in SimpleFIN Bridge." : "SimpleFIN couldn't claim the token (HTTP \(response.statusCode)).") } return access } /// Accounts and transactions since `since`, asked for in 45-day windows (SimpleFIN's limit). public func pull(accessURL: String, connectionID: String, since: Date, now: Date = .now) async throws -> BankPull { guard var parts = URLComponents(string: accessURL), let user = parts.user, let password = parts.password else { throw BucksleyError.invalid("The saved SimpleFIN access URL is incomplete. Connect SimpleFIN again.") } parts.user = nil; parts.password = nil let auth = "Basic " + Data("\(user):\(password)".utf8).base64EncodedString() var pull = BankPull() var seenAccounts: [String: Account] = [:] var windowStart = since while windowStart < now { let windowEnd = min(now, windowStart.addingTimeInterval(45 * 86_400)) var c = parts c.path += "/accounts" c.queryItems = [.init(name: "start-date", value: String(Int(windowStart.timeIntervalSince1970))), .init(name: "end-date", value: String(Int(windowEnd.timeIntervalSince1970) + 1)), .init(name: "pending", value: "1"), .init(name: "version", value: "2")] guard let url = c.url else { throw BucksleyError.invalid("Bad SimpleFIN URL.") } var request = URLRequest(url: url); request.setValue(auth, forHTTPHeaderField: "Authorization") let (data, response) = try await http.send(request) if response.statusCode == 402 { throw BucksleyError.network("Your SimpleFIN Bridge subscription needs attention (payment required).") } if response.statusCode == 403 { throw BucksleyError.network("SimpleFIN refused the access URL. It may have been revoked; connect again.") } guard response.statusCode == 200 else { throw BucksleyError.network("SimpleFIN returned HTTP \(response.statusCode).") } let set = try JSONDecoder().decode(AccountSet.self, from: data) let banks = Dictionary((set.connections ?? []).map { ($0.connID, $0) }, uniquingKeysWith: { first, _ in first }) pull.warnings += (set.errors ?? []).filter { !$0.contains("recommended range") } pull.warnings += (set.errlist ?? []).compactMap { $0.warning(bank: $0.connID.flatMap { banks[$0]?.displayName }) } for bank in banks.values where !set.accounts.contains(where: { $0.connID == bank.connID }) { pull.warnings.append("\(bank.displayName) is connected in SimpleFIN Bridge but sent no accounts. Open beta-bridge.simplefin.org, check that connection (it may need you to sign in again) and that its accounts are shared with this app.") } for a in set.accounts { let id = "\(connectionID):\(a.id)" let institution = a.org?.name ?? a.org?.domain ?? a.connID.flatMap { banks[$0]?.displayName } ?? "Bank" var kind = AccountKind.guess(from: a.name) if kind == .other, AccountKind.guess(from: institution) == .investment { kind = .investment } let balance = Decimal(money: a.balance) ?? 0 if kind == .other && balance < 0 { kind = .credit } var account = Account(id: id, connectionID: connectionID, name: a.name, institution: institution, kind: kind, balance: balance, available: a.availableBalance.flatMap { Decimal(money: $0) }, currency: a.currency.count == 3 ? a.currency : "USD", balanceDate: Date(timeIntervalSince1970: TimeInterval(a.balanceDate))) let holdings = (a.holdings ?? []).compactMap(\.holding) if !holdings.isEmpty { account.holdings = holdings if account.kind == .other || account.kind == .checking { account.kind = .investment } } seenAccounts[id] = account for t in a.transactions ?? [] { let when = Date(timeIntervalSince1970: TimeInterval(t.transactedAt ?? t.posted)) pull.transactions.append(Transaction(id: "\(id):\(t.id)", accountID: id, day: DayKey.from(when), amount: Decimal(money: t.amount) ?? 0, description: t.description, payee: t.payee, bankCategory: t.mcc.map { "mcc:\($0)" } ?? t.memo, pending: t.pending ?? (t.posted == 0))) } } windowStart = windowEnd } pull.accounts = Array(seenAccounts.values).sorted { $0.name < $1.name } return pull } /// Protocol v2 (errlist, connections, conn_id) with the v1 fields (errors, org) still read, /// so either server version decodes. struct AccountSet: Decodable { let errors: [String]? let errlist: [SFError]? let connections: [SFConnection]? let accounts: [SFAccount] } struct SFError: Decodable { let code: String?, msg: String?, connID: String?, accountID: String? enum CodingKeys: String, CodingKey { case code, msg, connID = "conn_id", accountID = "account_id" } func warning(bank: String?) -> String? { guard let msg, !msg.contains("recommended range") else { return nil } if code?.hasPrefix("con.auth") == true { return "\(bank ?? "A bank") needs you to sign in again in SimpleFIN Bridge (beta-bridge.simplefin.org). \(msg)" } return bank.map { "\($0): \(msg)" } ?? msg } } struct SFConnection: Decodable { let connID: String, name: String?, orgName: String?, orgURL: String? enum CodingKeys: String, CodingKey { case connID = "conn_id", name, orgName = "org_name", orgURL = "org_url" } var displayName: String { orgName ?? name ?? orgURL ?? "A bank" } } struct SFAccount: Decodable { struct Org: Decodable { let name: String?; let domain: String? } let id: String, name: String, currency: String, balance: String let availableBalance: String? let balanceDate: Int let org: Org? let connID: String? let transactions: [SFTransaction]? let holdings: [SFHolding]? enum CodingKeys: String, CodingKey { case id, name, currency, balance, org, transactions, holdings case availableBalance = "available-balance", balanceDate = "balance-date", connID = "conn_id" } /// Lenient: brokerages sometimes send numbers where the spec says strings, or skip the date. init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) func text(_ key: CodingKeys) -> String? { (try? c.decodeIfPresent(String.self, forKey: key)) ?? (try? c.decodeIfPresent(Double.self, forKey: key)).flatMap { $0.map { String($0) } } } id = try c.decode(String.self, forKey: .id) name = (try? c.decodeIfPresent(String.self, forKey: .name)) ?? nil ?? "Account" currency = (try? c.decodeIfPresent(String.self, forKey: .currency)) ?? nil ?? "USD" balance = text(.balance) ?? "0" availableBalance = text(.availableBalance) balanceDate = (try? c.decodeIfPresent(Int.self, forKey: .balanceDate)) ?? nil ?? Int(Date().timeIntervalSince1970) org = try? c.decodeIfPresent(Org.self, forKey: .org) connID = try? c.decodeIfPresent(String.self, forKey: .connID) transactions = (try? c.decodeIfPresent([Lenient].self, forKey: .transactions))??.compactMap(\.value) holdings = (try? c.decodeIfPresent([Lenient].self, forKey: .holdings))??.compactMap(\.value) } } /// SimpleFIN Bridge's holdings extension (strings or numbers, per bank). struct SFHolding: Decodable { let id: String, symbol: String?, description: String? let shares: Decimal?, marketValue: Decimal?, costBasis: Decimal? enum CodingKeys: String, CodingKey { case id, symbol, description, shares, marketValue = "market_value", costBasis = "cost_basis" } init(from decoder: Decoder) throws { let c = try decoder.container(keyedBy: CodingKeys.self) func number(_ key: CodingKeys) -> Decimal? { if let s = try? c.decodeIfPresent(String.self, forKey: key) { return Decimal(money: s) } return (try? c.decodeIfPresent(Double.self, forKey: key)).flatMap { $0.map { Decimal($0) } } } id = (try? c.decodeIfPresent(String.self, forKey: .id)) ?? nil ?? UUID().uuidString symbol = (try? c.decodeIfPresent(String.self, forKey: .symbol)) ?? nil description = (try? c.decodeIfPresent(String.self, forKey: .description)) ?? nil shares = number(.shares); marketValue = number(.marketValue); costBasis = number(.costBasis) } var holding: Holding? { guard let marketValue else { return nil } let name = description ?? symbol ?? "Holding" return Holding(id: id, symbol: symbol?.isEmpty == true ? nil : symbol, name: name, shares: shares, marketValue: marketValue, costBasis: costBasis) } } /// Skips one malformed transaction instead of failing the whole pull. struct Lenient: Decodable { let value: T? init(from decoder: Decoder) throws { value = try? T(from: decoder) } } struct SFTransaction: Decodable { let id: String let posted: Int let amount: String let description: String let payee: String? let memo: String? let transactedAt: Int? let pending: Bool? let mcc: String? enum CodingKeys: String, CodingKey { case id, posted, amount, description, payee, memo, pending, mcc, transactedAt = "transacted_at" } } } // MARK: Plaid with the user's own keys /// Plaid, called straight from the Mac with the user's own client ID and secret (from /// dashboard.plaid.com). Bucksley never sees them; they live in the user's Keychain. public struct Plaid: Sendable { public enum Environment: String, CaseIterable, Sendable { case sandbox, production var host: String { "https://\(rawValue).plaid.com" } } let http: HTTPClient let environment: Environment let clientID: String let secret: String public init(environment: Environment, clientID: String, secret: String, http: HTTPClient = URLSessionHTTP()) { self.environment = environment; self.clientID = clientID; self.secret = secret; self.http = http } /// From the Keychain, or nil until the user adds their keys in Settings → Connections. public static func fromKeychain(environment: Environment) -> Plaid? { guard let id = Keychain.get(.plaidClientID), let secret = Keychain.get(.plaidSecret) else { return nil } return Plaid(environment: environment, clientID: id, secret: secret) } func call(_ path: String, _ body: [String: Any]) async throws -> [String: Any] { var request = URLRequest(url: URL(string: environment.host + path)!) request.httpMethod = "POST" request.setValue("application/json", forHTTPHeaderField: "Content-Type") var payload = body; payload["client_id"] = clientID; payload["secret"] = secret request.httpBody = try JSONSerialization.data(withJSONObject: payload) let (data, response) = try await http.send(request) let json = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] ?? [:] guard response.statusCode == 200 else { let message = json["error_message"] as? String ?? "HTTP \(response.statusCode)" let code = json["error_code"] as? String throw BucksleyError.network(code == "ITEM_LOGIN_REQUIRED" ? "Your bank needs you to sign in again. Reconnect it in Settings → Connections." : "Plaid: \(message)") } return json } /// Starts Plaid Link (shown in a web view on the Mac). public func linkToken(userID: String) async throws -> String { let json = try await call("/link/token/create", [ "client_name": "Bucksley", "language": "en", "country_codes": ["US"], "products": ["transactions"], "user": ["client_user_id": userID], "transactions": ["days_requested": 730] ]) guard let token = json["link_token"] as? String else { throw BucksleyError.network("Plaid didn't return a link token.") } return token } /// Link's public token → the item's access token (kept in the Keychain). public func exchange(publicToken: String) async throws -> String { let json = try await call("/item/public_token/exchange", ["public_token": publicToken]) guard let token = json["access_token"] as? String else { throw BucksleyError.network("Plaid didn't return an access token.") } return token } /// Sandbox only: skips Link with Plaid's test bank ("First Platypus Bank"). public func sandboxPublicToken(institution: String = "ins_109508") async throws -> String { let json = try await call("/sandbox/public_token/create", ["institution_id": institution, "initial_products": ["transactions"]]) guard let token = json["public_token"] as? String else { throw BucksleyError.network("Plaid didn't return a sandbox token.") } return token } public func pull(accessToken: String, connectionID: String, institution: String, cursor: String?) async throws -> BankPull { var pull = BankPull() let balances = try await call("/accounts/balance/get", ["access_token": accessToken]) let item = balances["item"] as? [String: Any] let bank = item?["institution_name"] as? String ?? institution for a in balances["accounts"] as? [[String: Any]] ?? [] { guard let accountID = a["account_id"] as? String else { continue } let b = a["balances"] as? [String: Any] ?? [:] let type = a["type"] as? String ?? "other", subtype = a["subtype"] as? String ?? "" let kind = Self.kind(type: type, subtype: subtype) var current = Self.decimal(b["current"]) ?? 0 if kind.isLiability { current = -current } let name = (a["name"] as? String) ?? (a["official_name"] as? String) ?? "Account" let mask = (a["mask"] as? String).map { " ••\($0)" } ?? "" pull.accounts.append(Account(id: "\(connectionID):\(accountID)", connectionID: connectionID, name: name + mask, institution: bank, kind: kind, balance: current, available: Self.decimal(b["available"]), currency: b["iso_currency_code"] as? String ?? "USD")) } var next = cursor var more = true while more { var body: [String: Any] = ["access_token": accessToken, "count": 500] if let next { body["cursor"] = next } let page = try await call("/transactions/sync", body) for t in (page["added"] as? [[String: Any]] ?? []) + (page["modified"] as? [[String: Any]] ?? []) { guard let id = t["transaction_id"] as? String, let account = t["account_id"] as? String, let day = t["date"] as? String else { continue } let category = (t["personal_finance_category"] as? [String: Any])?["detailed"] as? String pull.transactions.append(Transaction(id: "\(connectionID):\(account):\(id)", accountID: "\(connectionID):\(account)", day: day, amount: -(Self.decimal(t["amount"]) ?? 0), // Plaid: positive is money out description: t["name"] as? String ?? "", payee: t["merchant_name"] as? String, bankCategory: category?.lowercased(), pending: t["pending"] as? Bool ?? false)) } for r in page["removed"] as? [[String: Any]] ?? [] { if let id = r["transaction_id"] as? String, let account = r["account_id"] as? String { pull.removedTransactionIDs.append("\(connectionID):\(account):\(id)") } } next = page["next_cursor"] as? String ?? next more = page["has_more"] as? Bool ?? false } pull.plaidCursor = next return pull } static func kind(type: String, subtype: String) -> AccountKind { switch type { case "depository": subtype == "checking" ? .checking : (subtype.contains("saving") || subtype == "money market" || subtype == "cd" ? .savings : .checking) case "credit": .credit case "loan": .loan case "investment", "brokerage": subtype.contains("crypto") ? .crypto : .investment default: .other } } static func decimal(_ any: Any?) -> Decimal? { switch any { case let n as NSNumber: Decimal(string: n.stringValue) case let s as String: Decimal(string: s) default: nil } } } // MARK: CSV import (Copilot Money export and similar) /// Reads a transactions CSV: Copilot Money's export (date, name, amount, status, category, parent /// category, excluded, tags, type, account, account mask, note, recurring) and most bank exports /// with a date, a description and an amount column. Copilot's amounts are positive for spending. public enum CSVImport { public struct Result: Sendable { public var accounts: [Account] = [] public var transactions: [Transaction] = [] public var edits: [TransactionEdit] = [] public var newCategories: [Category] = [] } public static func parse(_ text: String, connectionID: String, categories: [Category]) throws -> Result { let rows = rowsOf(text) guard let header = rows.first?.map({ $0.lowercased().trimmingCharacters(in: .whitespaces) }) else { throw BucksleyError.invalid("The file is empty.") } func col(_ names: String...) -> Int? { names.lazy.compactMap { header.firstIndex(of: $0) }.first } guard let dateCol = col("date", "transaction date", "posted date"), let amountCol = col("amount"), let nameCol = col("name", "description", "payee", "merchant") else { throw BucksleyError.invalid("Bucksley needs date, name (or description) and amount columns.") } let isCopilot = header.contains("parent category") || header.contains("excluded") let categoryCol = col("category"), accountCol = col("account"), maskCol = col("account mask"), noteCol = col("note", "notes"), tagsCol = col("tags"), statusCol = col("status"), excludedCol = col("excluded"), typeCol = col("type") var result = Result() var known = Dictionary(uniqueKeysWithValues: categories.map { ($0.name.lowercased(), $0.id) }) var accounts: [String: Account] = [:] for (n, row) in rows.dropFirst().enumerated() where row.count >= header.count / 2 { func v(_ i: Int?) -> String { guard let i, i < row.count else { return "" }; return row[i].trimmingCharacters(in: .whitespaces) } guard let day = normalizeDay(v(dateCol)), var amount = Decimal(money: v(amountCol)) else { continue } let type = v(typeCol).lowercased() if isCopilot { amount = -amount } // Copilot: positive = spent let accountName = v(accountCol).isEmpty ? "Imported" : v(accountCol) + (v(maskCol).isEmpty ? "" : " ••" + v(maskCol)) let accountID = "\(connectionID):\(accountName.lowercased().filter { $0.isLetter || $0.isNumber })" if accounts[accountID] == nil { accounts[accountID] = Account(id: accountID, connectionID: connectionID, name: accountName, institution: "CSV import", kind: .guess(from: accountName), balance: 0) } let name = v(nameCol) let txID = "\(accountID):\(day):\(n)" let tx = Transaction(id: txID, accountID: accountID, day: day, amount: amount, description: name, bankCategory: v(categoryCol).isEmpty ? nil : v(categoryCol), pending: v(statusCol).lowercased() == "pending") result.transactions.append(tx) var edit = TransactionEdit(transactionID: txID, device: "CSV import") var touched = false let categoryName = v(categoryCol) if !categoryName.isEmpty { let key = categoryName.lowercased() if known[key] == nil { let id = key.filter { $0.isLetter || $0.isNumber } let kind: CategoryKind = type.contains("income") ? .income : (type.contains("transfer") || key.contains("transfer")) ? .transfer : .expense let created = Category(id: id.isEmpty ? UUID().uuidString : id, name: categoryName, symbol: "tag", groupID: kind == .income ? "income" : kind == .transfer ? "transfers" : "lifestyle", colorIndex: (categories.count + result.newCategories.count) % 6, kind: kind) result.newCategories.append(created); known[key] = created.id } edit.categoryID = known[key]; touched = true } if !v(noteCol).isEmpty { edit.note = v(noteCol); touched = true } let tags = v(tagsCol).split(whereSeparator: { $0 == "," || $0 == ";" }).map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty } if !tags.isEmpty { edit.tags = tags; touched = true } if v(excludedCol).lowercased() == "true" { edit.excluded = true; touched = true } if isCopilot { edit.reviewed = true; touched = true } // already reviewed in the old app if touched { result.edits.append(edit) } } result.accounts = Array(accounts.values) return result } static func normalizeDay(_ text: String) -> String? { let t = text.trimmingCharacters(in: .whitespaces) if t.count >= 10, DayKey.date(String(t.prefix(10))) != nil { return String(t.prefix(10)) } let f = DateFormatter(); f.locale = Locale(identifier: "en_US_POSIX") for format in ["M/d/yyyy", "MM/dd/yyyy", "M/d/yy", "MMM d, yyyy"] { f.dateFormat = format if let d = f.date(from: t) { return DayKey.from(d) } } return nil } /// RFC 4180 rows: quoted fields, doubled quotes, commas and newlines inside quotes. static func rowsOf(_ text: String) -> [[String]] { var rows: [[String]] = [], row: [String] = [], field = "", quoted = false var chars = Array(text.replacingOccurrences(of: "\r\n", with: "\n")).makeIterator() var pending: Character? = nil while let c = pending ?? chars.next() { pending = nil if quoted { if c == "\"" { if let n = chars.next() { if n == "\"" { field.append("\"") } else { quoted = false; pending = n } } else { quoted = false } } else { field.append(c) } } else if c == "\"" { quoted = true } else if c == "," { row.append(field); field = "" } else if c == "\n" { row.append(field); field = ""; if !(row.count == 1 && row[0].isEmpty) { rows.append(row) }; row = [] } else { field.append(c) } } if !field.isEmpty || !row.isEmpty { row.append(field); rows.append(row) } return rows } }