// SPDX-License-Identifier: LGPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® module; #include "../lib/json.hpp" #include module Nostro:Bunq_impl; import std; import :Bunq; import :Connector; import :Crypto; import :Currency; import :File; import :Transaction; import :Utils; import Crafter.Network; using namespace Nostro; using namespace Nostro::Crypto; using namespace nlohmann; using namespace Crafter; std::deque BunqConnector::connectors; namespace { constexpr std::string_view userAgent = "Nostro"; constexpr std::string_view maybeCarriedOut = "; the request may have been carried out, check before trying again"; // Where BunqConnector::RedirectTo sends everything. std::optional& Redirected() { static std::optional redirected; return redirected; } // A request's authority: the host, with the port when it is not HTTPS's own. std::string Authority(const BunqEndpoint& endpoint) { return endpoint.port == 443 ? endpoint.host : std::format("{}:{}", endpoint.host, endpoint.port); } // One persistent connection per endpoint, dialled on first use. ClientHTTP1& ApiClient(const BunqEndpoint& endpoint) { static std::map> clients; std::unique_ptr& client = clients[Authority(endpoint)]; if(!client) { client = std::make_unique(endpoint.host, endpoint.port, TLSClientCredentials{.caPem = endpoint.caPem}); } return *client; } // How often a 429 is waited out, and how long each time. bunq allows 3 GETs, 5 POSTs and 2 PUTs per endpoint in // any 3 seconds, and one session per 30 seconds: the second entry is session-server's. struct RateLimit { std::uint32_t retries; std::chrono::seconds wait; }; constexpr std::array rateLimits = {{ {5, std::chrono::seconds(3)}, {2, std::chrono::seconds(31)}, }}; std::uint16_t ParseStatus(std::string_view status) { std::uint16_t value = 0; std::from_chars(status.data(), status.data() + status.size(), value); return value; } // bunq's {"Error": [{"error_description": ...}]}, or the OAuth server's {"error": ..., "error_description": ...}. std::string ErrorMessage(std::string_view body) { const json doc = json::parse(body, nullptr, false); std::string message; if(doc.is_object()) { if(const json::const_iterator errors = doc.find("Error"); errors != doc.end() && errors->is_array()) { for(const json& error : *errors) { const std::string description = BunqJson::String(error, "error_description"); if(!description.empty()) { message += message.empty() ? description : std::format("; {}", description); } } } if(message.empty()) { message = BunqJson::String(doc, "error_description"); } if(message.empty()) { message = BunqJson::String(doc, "error"); } } if(message.empty()) { message = body.empty() ? std::string("no details") : std::string(body.substr(0, 300)); } return message; } // bunq has no BIC on its own accounts; an IBAN with bank code BUNQ is one of them. std::string BicOf(std::string_view iban, std::string bic) { if(bic.empty() && iban.size() >= 8 && iban.substr(4, 4) == "BUNQ") { return "BUNQNL2A"; } return bic; } } BunqError::BunqError(std::uint16_t status, const std::string& message) : std::runtime_error(message), status(status) { } json BunqJson::Item(const json& response, std::string_view key) { for(const json& item : response.at("Response")) { if(item.is_object()) { if(const json::const_iterator value = item.find(key); value != item.end()) { return *value; } } } throw std::runtime_error(std::format("bunq response has no '{}' object", key)); } std::pair BunqJson::Only(const json& item) { if(!item.is_object() || item.size() != 1) { return {std::string(), nullptr}; } const json::const_iterator only = item.begin(); return {only.key(), &only.value()}; } json BunqJson::Amount(std::int64_t amount, Currency currency) { return json{{"value", FormatAmount(amount, currency)}, {"currency", std::string(GetCurrencyCode(currency))}}; } json BunqJson::Pointer(const BunqCounterparty& counterparty) { json pointer = {{"type", counterparty.type}, {"value", counterparty.value}}; if(!counterparty.name.empty()) { pointer["name"] = counterparty.name; } return pointer; } std::pair BunqJson::ReadAmount(const json& amount) { const Currency currency = GetCurrency(amount.at("currency").get()); return {currency, ParseAmount(amount.at("value").get(), currency)}; } BunqLabel BunqJson::ReadLabel(const json& label) { BunqLabel out{String(label, "display_name"), String(label, "iban")}; if(out.name.empty() && label.is_object()) { if(const json::const_iterator user = label.find("label_user"); user != label.end()) { out.name = String(*user, "display_name"); } } return out; } std::string BunqJson::String(const json& object, std::string_view key) { if(!object.is_object()) { return std::string(); } const json::const_iterator value = object.find(key); return value != object.end() && value->is_string() ? value->get() : std::string(); } json BunqConnector::Call(std::string_view method, std::string_view path, const json* body, Auth auth, bool renew) { // Nothing a session call returns is used unverified: a connector saved before the server key was kept fetches it first. if(auth == Auth::Session && !serverPublicKey && !fetchingServerKey) { EnsureServerPublicKey(); } const bool write = method != "GET"; const std::string target = path.starts_with("/v1/") ? std::string(path) : std::format("/v1{}", path); // The signature covers these exact bytes. Text that is not UTF-8 (a description typed in another encoding) is // replaced rather than refused. const std::string payload = body ? body->dump(-1, ' ', false, json::error_handler_t::replace) : std::string(); std::unordered_map headers = { {"User-Agent", std::string(userAgent)}, {"Cache-Control", "no-cache"}, {"Accept", "application/json"}, }; if(body) { headers.emplace("Content-Type", "application/json"); // Only sessions and payments need a signature, but signing every body costs nothing and covers whatever // else bunq starts to require one for. The installation call is the one that may not carry it. if(auth != Auth::None) { headers.emplace("X-Bunq-Client-Signature", SignBody(privateKey.get(), payload)); } } bool renewed = false; for(std::uint32_t attempt = 0;; attempt++) { if(auth == Auth::Installation) { headers["X-Bunq-Client-Authentication"] = installationToken; } else if(auth == Auth::Session) { headers["X-Bunq-Client-Authentication"] = sessionToken; } // ClientHTTP1 sends a request again on a reused connection that fails before any of the response arrives, // which includes a read timeout: for a payment bunq booked before its answer was lost, that pays twice. It // never replays on a new connection, so a write gets one. const BunqEndpoint endpoint = Endpoint(environment); ClientHTTP1& client = ApiClient(endpoint); if(write) { client.Disconnect(); } HTTPResponse response; try { response = client.Send(CreateRequestHTTP(std::string(method), target, Authority(endpoint), headers, payload)); } catch(const std::exception& e) { if(write) { throw std::runtime_error(std::format("bunq {} {}: {}{}", method, path, e.what(), maybeCarriedOut)); } throw; } const std::uint16_t status = ParseStatus(response.status); // A 429 is refused before anything happens, so even a payment is safe to send again. const RateLimit& limit = rateLimits[target.starts_with("/v1/session-server")]; if(status == 429 && attempt < limit.retries) { std::this_thread::sleep_for(limit.wait); continue; } if(status >= 200 && status < 300) { // An error response can come unsigned; nothing but its message is used. A success is used, so it must verify. if(serverPublicKey && auth != Auth::None) { const std::unordered_map::const_iterator signature = response.headers.find("x-bunq-server-signature"); if(signature == response.headers.end() || !VerifyBody(serverPublicKey.get(), response.body, signature->second)) { // The check comes after the fact: a payment may have been made all the same, and sending it again // could pay twice. throw std::runtime_error(std::format("bunq {} {}: the response is not signed by bunq's server key{}", method, path, write ? maybeCarriedOut : "")); } } try { return response.body.empty() ? json::object() : json::parse(response.body); } catch(const json::exception& e) { throw std::runtime_error(std::format("bunq {} {}: unreadable response: {}{}", method, path, e.what(), write ? maybeCarriedOut : "")); } } const std::string message = ErrorMessage(response.body); // An expired or ended session is a 401, or a 403 "Insufficient authentication.": open a new one, once. if(auth == Auth::Session && renew && !renewed && (status == 401 || (status == 403 && message.contains("authentication")))) { renewed = true; RefreshSession(); Connector::SaveConnectors(); continue; } // A 5xx says nothing about whether a write went through. throw BunqError(status, std::format("bunq {} {}: {} ({}){}", method, path, message, status, write && status >= 500 ? maybeCarriedOut : "")); } } json BunqConnector::Get(std::string_view path) { return Call("GET", path, nullptr, Auth::Session); } json BunqConnector::Post(std::string_view path, const json& body) { return Call("POST", path, &body, Auth::Session); } json BunqConnector::Put(std::string_view path, const json& body) { return Call("PUT", path, &body, Auth::Session); } json BunqConnector::Delete(std::string_view path) { return Call("DELETE", path, nullptr, Auth::Session); } std::vector BunqConnector::List(std::string_view path) { std::vector items; std::string next = std::format("{}{}count=200", path, path.contains('?') ? '&' : '?'); while(!next.empty()) { json page = Get(next); for(json& item : page.at("Response")) { items.push_back(std::move(item)); } next.clear(); if(const json::const_iterator pagination = page.find("Pagination"); pagination != page.end()) { if(const json::const_iterator older = pagination->find("older_url"); older != pagination->end() && older->is_string()) { next = older->get(); } } } return items; } void BunqConnector::ReadUser(const json& response) { const auto displayName = [](const json& user) { constexpr std::array keys = {"display_name", "name", "legal_name", "public_nick_name"}; for(const std::string_view key : keys) { std::string value = BunqJson::String(user, key); if(!value.empty()) { return value; } } return std::string(); }; for(const json& item : response.at("Response")) { const auto [type, user] = BunqJson::Only(item); if(!user) { continue; } if(type == "UserPerson" || type == "UserCompany" || type == "UserPaymentServiceProvider") { userType = type; id = user->at("id").get(); ownerId = id; name = displayName(*user); return; } if(type == "UserApiKey") { // An OAuth connection: its own user id goes in paths; the name and owner are the bunq user who granted access. userType = type; id = user->at("id").get(); const auto [grantedType, granted] = BunqJson::Only(user->at("granted_by_user")); name = granted ? displayName(*granted) : std::string(); ownerId = granted ? granted->at("id").get() : id; return; } } throw std::runtime_error("bunq session names no user"); } void BunqConnector::RefreshSession() { const json body = {{"secret", apiKey}}; const json response = Call("POST", "/session-server", &body, Auth::Installation); sessionToken = BunqJson::Item(response, "Token").at("token").get(); sessionId = BunqJson::Item(response, "Id").at("id").get(); ReadUser(response); } void BunqConnector::EnsureServerPublicKey() { // Connectors saved before the key was kept: fetch it once. These two calls cannot be verified yet; TLS still // authenticates the host. fetchingServerKey = true; struct Reset { bool& flag; ~Reset() { flag = false; } } reset{fetchingServerKey}; const std::uint64_t installation = BunqJson::Item(Get("/installation"), "Id").at("id").get(); const json key = Get(std::format("/installation/{}/server-public-key", installation)); serverPublicKey = OwnKey(LoadPublicKeyFromPem(BunqJson::Item(key, "ServerPublicKey").at("server_public_key").get())); Connector::SaveConnectors(); } BunqConnector& BunqConnector::Create(std::string&& apiKey, std::string_view allowedIps, BunqEnvironment environment) { BunqConnector connector; connector.environment = environment; connector.apiKey = std::move(apiKey); const auto [key, publicKey] = CreateKey(); connector.privateKey = OwnKey(key); const json installation = {{"client_public_key", publicKey}}; const json installed = connector.Call("POST", "/installation", &installation, Auth::None); connector.installationToken = BunqJson::Item(installed, "Token").at("token").get(); connector.serverPublicKey = OwnKey(LoadPublicKeyFromPem(BunqJson::Item(installed, "ServerPublicKey").at("server_public_key").get())); json device = {{"description", "Nostro"}, {"secret", connector.apiKey}}; if(!allowedIps.empty()) { json ips = json::array(); for(const auto part : std::views::split(allowedIps, ',')) { std::string_view ip(part.begin(), part.end()); while(ip.starts_with(' ')) { ip.remove_prefix(1); } while(ip.ends_with(' ')) { ip.remove_suffix(1); } if(!ip.empty()) { ips.push_back(std::string(ip)); } } device["permitted_ips"] = std::move(ips); } connector.Call("POST", "/device-server", &device, Auth::Installation); connector.RefreshSession(); // One connector per bunq user: the same accounts under two connectors would make every one of them ambiguous. // Adding the user again the same way (a renewed API key, a new OAuth grant) replaces the old connector. const std::deque::iterator existing = std::ranges::find_if(connectors, [&connector](const BunqConnector& other) { return other.environment == connector.environment && other.ownerId == connector.ownerId; }); if(existing != connectors.end()) { if(existing->IsOAuth() != connector.IsOAuth()) { try { connector.Logout(); } catch(const std::exception&) { // The new session expires by itself. } throw std::runtime_error(std::format("{} is already connected {}: remove that connector first", connector.name, existing->IsOAuth() ? "through OAuth" : "with an API key")); } try { existing->Logout(); } catch(const std::exception&) { // A key that no longer works has no session to end. } } BunqConnector& added = existing != connectors.end() ? (*existing = std::move(connector)) : connectors.emplace_back(std::move(connector)); added.RefreshAccounts(); return added; } void BunqConnector::Remove(BunqConnector& connector) { const std::deque::iterator it = std::ranges::find_if(connectors, [&connector](const BunqConnector& other) { return &other == &connector; }); if(it == connectors.end()) { throw std::invalid_argument("that connector is not in BunqConnector::connectors"); } Account::ForgetTransactions(connector.StorageKey()); connectors.erase(it); // Erasing from the middle of a deque moves the connectors around it: point their accounts at where they are now. for(BunqConnector& remaining : connectors) { for(BunqAccount& account : remaining.accounts) { account.connector = &remaining; } } } BunqEnvironment BunqConnector::EnvironmentOfKey(std::string_view apiKey) { return apiKey.starts_with("sandbox_") ? BunqEnvironment::Sandbox : BunqEnvironment::Production; } std::string BunqConnector::OAuthAuthorizationUrl(BunqEnvironment environment, std::string_view clientId, std::string_view redirectUri, std::string_view state) { return std::format("https://{}/auth?response_type=code&client_id={}&redirect_uri={}&state={}", environment == BunqEnvironment::Production ? "oauth.bunq.com" : "oauth.sandbox.bunq.com", UrlEncode(clientId), UrlEncode(redirectUri), UrlEncode(state)); } BunqEndpoint BunqConnector::Endpoint(BunqEnvironment environment) { return Redirected().value_or(BunqEndpoint{.host = environment == BunqEnvironment::Production ? "api.bunq.com" : "public-api.sandbox.bunq.com", .port = 443, .caPem = std::string()}); } void BunqConnector::RedirectTo(BunqEndpoint endpoint) { Redirected() = std::move(endpoint); } std::string BunqConnector::OAuthExchangeCode(BunqEnvironment environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code) { // The token endpoint has a host of its own, which a redirect replaces like the API's. const BunqEndpoint endpoint = Redirected().value_or(BunqEndpoint{.host = environment == BunqEnvironment::Production ? "api.oauth.bunq.com" : "api-oauth.sandbox.bunq.com", .port = 443, .caPem = std::string()}); ClientHTTP1 client(endpoint.host, endpoint.port, TLSClientCredentials{.caPem = endpoint.caPem}); const std::string host = Authority(endpoint); // The token endpoint reads its parameters from the query string only: sent as a form body they are reported missing. const std::string target = std::format("/v1/token?grant_type=authorization_code&code={}&redirect_uri={}&client_id={}&client_secret={}", UrlEncode(code), UrlEncode(redirectUri), UrlEncode(clientId), UrlEncode(clientSecret)); const HTTPResponse response = client.Send(CreateRequestHTTP("POST", target, host, {{"User-Agent", std::string(userAgent)}, {"Accept", "application/json"}})); const std::uint16_t status = ParseStatus(response.status); const json doc = json::parse(response.body, nullptr, false); const std::string token = BunqJson::String(doc, "access_token"); if(status == 200 && !token.empty()) { return token; } throw BunqError(status, std::format("bunq OAuth token exchange: {} ({})", ErrorMessage(response.body), status)); } void BunqConnector::RefreshAccounts() { std::vector refreshed; for(const json& item : List(std::format("/user/{}/monetary-account", id))) { const auto [type, account] = BunqJson::Only(item); if(!account || !type.starts_with("MonetaryAccount")) { continue; } // A closed account stays listed. A blocked one is still the user's, with its balance. const std::string status = BunqJson::String(*account, "status"); if(status != "ACTIVE" && status != "BLOCKED") { continue; } std::string description = BunqJson::String(*account, "description"); Currency currency; try { currency = GetCurrency(BunqJson::String(*account, "currency")); } catch(const std::runtime_error& e) { Note(std::format("skipping bunq account '{}': {}", description, e.what())); continue; } std::string iban; if(const json::const_iterator aliases = account->find("alias"); aliases != account->end() && aliases->is_array()) { for(const json& alias : *aliases) { if(BunqJson::String(alias, "type") == "IBAN") { iban = BunqJson::String(alias, "value"); } } } std::int64_t balance = 0; if(const json::const_iterator value = account->find("balance"); value != account->end() && value->is_object()) { balance = BunqJson::ReadAmount(*value).second; } std::string bic = BicOf(iban, std::string()); refreshed.emplace_back(std::move(description), std::move(bic), std::move(iban), currency, balance, account->at("id").get(), std::string(type), this); } accounts = std::move(refreshed); } void BunqConnector::GetNewTransactions() { for(BunqAccount& account : accounts) { GetNewTransactions(account); } } void BunqConnector::GetNewTransactions(BunqAccount& account) { const std::string key = account.StorageKey(); const std::chrono::system_clock::time_point last = account.GetLastTransactionTime(key); std::vector fetched; std::string next = std::format("{}/payment?count=200", account.Path()); while(!next.empty()) { const json page = Get(next); next.clear(); bool reachedStored = false; for(const json& item : page.at("Response")) { const json::const_iterator payment = item.find("Payment"); if(payment == item.end()) { continue; } // Listed newest first. One at the last stored timestamp may still be new: SaveTransactions tells by id. const std::chrono::system_clock::time_point created = ParseTimestamp(payment->at("created").get()); if(created < last) { reachedStored = true; break; } const json& counterparty = payment->at("counterparty_alias"); const auto [currency, amount] = BunqJson::ReadAmount(payment->at("amount")); std::string iban = BunqJson::String(counterparty, "iban"); std::string bic = BicOf(iban, BunqJson::String(counterparty, "swift_bic")); fetched.push_back(Transaction{ .name = BunqJson::ReadLabel(counterparty).name, .bic = std::move(bic), .iban = std::move(iban), .description = BunqJson::String(*payment, "description"), .currency = currency, .amount = amount, .timePoint = created, .id = std::to_string(payment->at("id").get()), .kind = std::format("{}/{}", BunqJson::String(*payment, "type"), BunqJson::String(*payment, "sub_type")), }); } if(!reachedStored) { if(const json::const_iterator pagination = page.find("Pagination"); pagination != page.end()) { if(const json::const_iterator older = pagination->find("older_url"); older != pagination->end() && older->is_string()) { next = older->get(); } } } } account.SaveTransactions(key, std::move(fetched)); } bool BunqConnector::TestConnector() { try { Get(std::format("/user/{}", id)); return true; } catch(const std::exception&) { return false; } } void BunqConnector::Logout() { try { // Not renewed: opening a session to close it would leave the new one open. Call("DELETE", std::format("/session/{}", sessionId), nullptr, Auth::Session, false); } catch(const BunqError& e) { // A session that already ended is logged out. if(e.status != 401 && e.status != 403) { throw; } } sessionToken.clear(); } namespace { BunqCard ReadCard(std::string_view kind, const json& card) { BunqCard out{ .id = card.at("id").get(), .kind = std::string(kind), .productType = BunqJson::String(card, "product_type"), .status = BunqJson::String(card, "status"), .orderStatus = BunqJson::String(card, "order_status"), .nameOnCard = BunqJson::String(card, "name_on_card"), .secondLine = BunqJson::String(card, "second_line"), .lastFour = std::string(), .expiry = BunqJson::String(card, "expiry_date"), .iban = std::string(), }; if(const json::const_iterator numbers = card.find("primary_account_numbers"); numbers != card.end() && numbers->is_array() && !numbers->empty()) { out.lastFour = BunqJson::String(numbers->front(), "four_digit"); } if(const json::const_iterator current = card.find("label_monetary_account_current"); current != card.end()) { out.iban = BunqJson::String(*current, "iban"); } return out; } } std::vector BunqConnector::Cards() { std::vector cards; for(const json& item : List(std::format("/user/{}/card", id))) { const auto [kind, card] = BunqJson::Only(item); if(card) { cards.push_back(ReadCard(kind, *card)); } } return cards; } BunqCard BunqConnector::SetCardStatus(std::uint64_t card, std::string_view status) { // bunq answers with the card as it is now, which is not always as asked: a card that was never activated stays // DEACTIVATED, without an error. const json response = Put(std::format("/user/{}/card/{}", id, card), json{{"status", std::string(status)}}); for(const json& item : response.at("Response")) { const auto [kind, updated] = BunqJson::Only(item); if(updated && kind.starts_with("Card")) { return ReadCard(kind, *updated); } } throw std::runtime_error("bunq did not return the card it updated"); } std::string BunqConnector::StorageKey() const { return std::format("{}/{}/{}", connectorId, environment == BunqEnvironment::Production ? "production" : "sandbox", id); } bool BunqConnector::IsOAuth() const { return userType == "UserApiKey"; } BunqAccount::BunqAccount(std::string&& name, std::string&& bic, std::string&& iban, Currency currency, std::int64_t balance, std::uint64_t id, std::string&& type, BunqConnector* connector) : Account(std::move(name), std::move(bic), std::move(iban), currency, balance), id(id), type(std::move(type)), connector(connector) { } std::string BunqAccount::Path() const { return std::format("/user/{}/monetary-account/{}", connector->id, id); } std::string BunqAccount::StorageKey() const { return std::format("{}/{}", connector->StorageKey(), id); } void Nostro::to_json(json& j, const BunqConnector& connector) { j = json{ {"environment", connector.environment == BunqEnvironment::Production ? "production" : "sandbox"}, {"apiKey", connector.apiKey}, {"installationToken", connector.installationToken}, {"sessionToken", connector.sessionToken}, {"sessionId", connector.sessionId}, {"privateKey", PrivateKeyToPem(connector.privateKey.get())}, {"userType", connector.userType}, {"name", connector.name}, {"id", connector.id}, {"ownerId", connector.ownerId}, }; if(connector.serverPublicKey) { j["serverPublicKey"] = PublicKeyToPem(connector.serverPublicKey.get()); } } void Nostro::from_json(const json& j, BunqConnector& connector) { // Connectors saved before the environment was kept were all made against the sandbox, then the only host. connector.environment = j.value("environment", std::string("sandbox")) == "production" ? BunqEnvironment::Production : BunqEnvironment::Sandbox; j.at("apiKey").get_to(connector.apiKey); j.at("installationToken").get_to(connector.installationToken); j.at("sessionToken").get_to(connector.sessionToken); connector.sessionId = j.value("sessionId", std::uint64_t{0}); connector.privateKey = OwnKey(LoadKeyFromPem(j.at("privateKey").get())); if(const json::const_iterator key = j.find("serverPublicKey"); key != j.end() && key->is_string()) { connector.serverPublicKey = OwnKey(LoadPublicKeyFromPem(key->get())); } connector.userType = j.value("userType", std::string()); j.at("name").get_to(connector.name); j.at("id").get_to(connector.id); // Connectors saved before the owner was kept all used API keys, whose user is the owner. connector.ownerId = j.value("ownerId", connector.id); }