This commit is contained in:
Jorijn van der Graaf 2026-11-01 18:35:23 +01:00
commit 1ea50c50bc
62 changed files with 9982 additions and 608 deletions

View file

@ -1,14 +1,10 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include "../lib/json.hpp"
#include <openssl/types.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/err.h>
module Nostro:Bunq_impl;
@ -16,6 +12,9 @@ import std;
import :Bunq;
import :Connector;
import :Crypto;
import :Currency;
import :File;
import :Transaction;
import :Utils;
import Crafter.Network;
@ -24,250 +23,655 @@ using namespace Nostro::Crypto;
using namespace nlohmann;
using namespace Crafter;
std::vector<BunqConnector> BunqConnector::connectors;
std::deque<BunqConnector> BunqConnector::connectors;
json InResponse(const json& doc, std::string_view key) {
for (const json& item : doc.at("Response")) {
if (item.is_object()) {
if (const json::const_iterator v = item.find(key); v != item.end()) {
return *v;
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<BunqEndpoint>& Redirected() {
static std::optional<BunqEndpoint> 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<std::string, std::unique_ptr<ClientHTTP1>> clients;
std::unique_ptr<ClientHTTP1>& client = clients[Authority(endpoint)];
if(!client) {
client = std::make_unique<ClientHTTP1>(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<RateLimit, 2> 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));
}
json GetUser(std::string_view body) {
try {
return InResponse(json::parse(body), "UserCompany");
} catch(std::runtime_error e) {
return InResponse(json::parse(body), "UserPerson");
std::pair<std::string, const json*> 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()};
}
std::string StringOrEmpty(const json& object, std::string_view key) {
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<Currency, std::int64_t> BunqJson::ReadAmount(const json& amount) {
const Currency currency = GetCurrency(amount.at("currency").get<std::string>());
return {currency, ParseAmount(amount.at("value").get<std::string>(), 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);
if(value == object.end() || !value->is_string()) {
return "";
}
return value->get<std::string>();
return value != object.end() && value->is_string() ? value->get<std::string>() : std::string();
}
BunqAccount::BunqAccount(std::string&& name, std::string&& bic, std::string&& iban, Currency currency, std::int64_t balance, std::uint32_t id, BunqConnector* connector) : Account(std::move(name), std::move(bic), std::move(iban), currency, balance), id(id), connector(connector) {
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<std::string, std::string> 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<std::string, std::string>::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 : ""));
}
}
void BunqAccount::Send(std::string_view iban, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const {
const std::string body = std::format("{{\"amount\": {{\"value\":\"{}\", \"currency\":\"{}\"}},\"counterparty_alias\":{{\"type\":\"IBAN\",\"value\":\"{}\", \"name\":\"{}\"}}, \"description\":\"{}\"}}", amount, GetCurrencyCode(currency), iban, name, description);
const std::string route = std::format("/v1/user/{}/monetary-account/{}/payment", connector->id, id);
json BunqConnector::Get(std::string_view path) {
return Call("GET", path, nullptr, Auth::Session);
}
HTTPResponse response = connector->client.Send(CreateRequestHTTP("POST", route, "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", connector->sessionToken}, {"X-Bunq-Client-Signature", EscB(SignBody(connector->privateKey, body))}},
body
));
json BunqConnector::Post(std::string_view path, const json& body) {
return Call("POST", path, &body, Auth::Session);
}
if(response.status != "200") {
throw std::runtime_error(std::format("{} non 200 status code: {}", route, response.body));
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<json> BunqConnector::List(std::string_view path) {
std::vector<json> 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<std::string>();
}
}
}
return items;
}
void BunqConnector::ReadUser(const json& response) {
const auto displayName = [](const json& user) {
constexpr std::array<std::string_view, 4> 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<std::uint64_t>();
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<std::uint64_t>();
const auto [grantedType, granted] = BunqJson::Only(user->at("granted_by_user"));
name = granted ? displayName(*granted) : std::string();
ownerId = granted ? granted->at("id").get<std::uint64_t>() : 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<std::string>();
sessionId = BunqJson::Item(response, "Id").at("id").get<std::uint64_t>();
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<std::uint64_t>();
const json key = Get(std::format("/installation/{}/server-public-key", installation));
serverPublicKey = OwnKey(LoadPublicKeyFromPem(BunqJson::Item(key, "ServerPublicKey").at("server_public_key").get<std::string>()));
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<std::string>();
connector.serverPublicKey = OwnKey(LoadPublicKeyFromPem(BunqJson::Item(installed, "ServerPublicKey").at("server_public_key").get<std::string>()));
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<BunqConnector>::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<BunqConnector>::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<BunqAccount> 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::uint64_t>(), std::string(type), this);
}
accounts = std::move(refreshed);
}
void BunqConnector::GetNewTransactions() {
for(BunqAccount& account : accounts) {
account.transactions.clear();
GetNewTransactions(account);
}
}
const std::chrono::system_clock::time_point last = account.GetLastTransactionTime(connectorId);
void BunqConnector::GetNewTransactions(BunqAccount& account) {
const std::string key = account.StorageKey();
const std::chrono::system_clock::time_point last = account.GetLastTransactionTime(key);
std::vector<Transaction> fetched;
std::string route = std::format("/v1/user/{}/monetary-account/{}/payment?count=200", id, account.id);
while(!route.empty()) {
HTTPResponse response = client.Send(CreateRequestHTTP("GET", route, "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", sessionToken}}));
std::string next = std::format("{}/payment?count=200", account.Path());
while(!next.empty()) {
const json page = Get(next);
next.clear();
if(response.status == "429") {
std::this_thread::sleep_for(std::chrono::seconds(2));
bool reachedStored = false;
for(const json& item : page.at("Response")) {
const json::const_iterator payment = item.find("Payment");
if(payment == item.end()) {
continue;
}
if(response.status != "200") {
throw std::runtime_error(std::format("{} non 200 status code: {}", route, response.body));
// 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<std::string>());
if(created < last) {
reachedStored = true;
break;
}
const json doc = json::parse(response.body);
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<std::uint64_t>()),
.kind = std::format("{}/{}", BunqJson::String(*payment, "type"), BunqJson::String(*payment, "sub_type")),
});
}
const json& olderUrl = doc.at("Pagination").at("older_url");
if( olderUrl.is_null()) {
route.clear();
} else {
route = olderUrl.get<std::string>();
}
for(const json& item : doc.at("Response")) {
const json::const_iterator paymentIt = item.find("Payment");
if(paymentIt == item.end()) {
continue;
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<std::string>();
}
const json& paymentJ = *paymentIt;
const std::chrono::system_clock::time_point timePoint = ParseTimestamp(paymentJ.at("created").get<std::string>());
if(timePoint <= last) {
route.clear();
break;
}
const json& counterpartyJ = paymentJ.at("counterparty_alias");
const Currency currency = GetCurrency(paymentJ.at("amount").at("currency").get<std::string>());
account.transactions.emplace_back(
StringOrEmpty(counterpartyJ, "display_name"),
StringOrEmpty(counterpartyJ, "swift_bic"),
StringOrEmpty(counterpartyJ, "iban"),
StringOrEmpty(paymentJ, "description"),
currency,
ParseAmount(paymentJ.at("amount").at("value").get<std::string>(), currency),
timePoint
);
}
}
std::ranges::reverse(account.transactions);
account.SaveTransactions();
}
}
void BunqConnector::RefreshSession() {
const std::string body = std::format("{{\"secret\": \"{}\"}}", apiKey);
HTTPResponse response = client.Send(CreateRequestHTTP("POST", "/v1/session-server", "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", installationToken}, {"X-Bunq-Client-Signature", EscB(SignBody(privateKey, body))}},
body
));
if(response.status != "200") {
throw std::runtime_error(std::format("/v1/session-server non 200 status code: {}", response.body));
}
sessionToken = InResponse(json::parse(response.body), "Token").at("token");
json user = GetUser(response.body);
name = user.at("name");
id = user.at("id");
}
BunqConnector& BunqConnector::Create(std::string&& apiKey, std::string_view allowedIp) {
BunqConnector& connector = connectors.emplace_back();
std::tuple<EVP_PKEY*, std::string> keys = CreateKey();
connector.apiKey = std::move(apiKey);
connector.privateKey = std::get<0>(keys);
HTTPResponse response = client.Send(CreateRequestHTTP("POST", "/v1/installation", "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}},
std::format("{{\"client_public_key\": \"{}\"}}", EscB(std::get<1>(keys)))
));
if(response.status != "200") {
throw std::runtime_error(std::format("/v1/installation non 200 status code: {}", response.body));
}
connector.installationToken = InResponse(json::parse(response.body), "Token").at("token");
response = client.Send(CreateRequestHTTP("POST", "/v1/device-server", "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", connector.installationToken}},
std::format("{{\"description\": \"Nostro\", \"secret\": \"{}\", \"permitted_ips\": [{}]}}", connector.apiKey, allowedIp)
));
if(response.status != "200") {
throw std::runtime_error(std::format("/v1/device-server non 200 status code: {}", response.body));
}
connector.RefreshSession();
return connector;
}
void BunqConnector::RefreshAccounts() {
HTTPResponse response = client.Send(CreateRequestHTTP("GET", std::format("/v1/user/{}/monetary-account", id), "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", sessionToken}}));
if(response.status != "200") {
throw std::runtime_error(std::format("/v1/user/{}/monetary-account non 200 status code: {}", id, response.body));
}
for(const json& item : json::parse(response.body).at("Response")) {
json::const_iterator accountIt = item.find("MonetaryAccountBank");
if(accountIt == item.end()) {
accountIt = item.find("MonetaryAccountSavings");
}
if(accountIt == item.end()) {
continue;
}
const json& accountJ = *accountIt;
const std::uint32_t accountId = accountJ.at("id").get<std::uint32_t>();
const Currency currency = GetCurrency(accountJ.at("currency").get<std::string>());
const std::int64_t balance = ParseAmount(accountJ.at("balance").at("value").get<std::string>(), currency);
const std::vector<BunqAccount>::iterator existing = std::ranges::find(accounts, accountId, &BunqAccount::id);
if(existing != accounts.end()) {
existing->balance = balance;
continue;
}
std::string_view iban;
for(const json& alias : accountJ.at("alias")) {
if(alias.at("type").get<std::string>() == "IBAN") {
iban = alias.at("value").get_ref<const std::string&>();
}
}
accounts.emplace_back(accountJ.at("description").get<std::string>(), "", std::string(iban), currency, balance, accountId, this);
}
account.SaveTransactions(key, std::move(fetched));
}
bool BunqConnector::TestConnector() {
HTTPResponse response = client.Send(CreateRequestHTTP("GET", std::format("/v1/user/{}/monetary-account", id), "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", sessionToken}}));
if(response.status == "200") {
try {
Get(std::format("/user/{}", id));
return true;
} else {
RefreshSession();
HTTPResponse response = client.Send(CreateRequestHTTP("GET", std::format("/v1/user/{}/monetary-account", id), "public-api.sandbox.bunq.com", {{"User-Agent", "Nostro Crafter.Network"}, {"Content-Type", "application/json"}, {"Accept", "application/json"}, {"X-Bunq-Client-Authentication", sessionToken}}));
if(response.status == "200") {
return true;
} else {
return false;
}
} 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<std::uint64_t>(),
.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<BunqCard> BunqConnector::Cards() {
std::vector<BunqCard> 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) {
BIO* bio = ThrowOnOpenssl(BIO_new(BIO_s_mem()));
ThrowOnOpenssl(PEM_write_bio_PrivateKey(bio, connector.privateKey, nullptr, nullptr, 0, nullptr, nullptr));
char* data;
const long len = ThrowOnOpenssl(BIO_get_mem_data(bio, &data));
std::string privateKey(data, len);
BIO_free(bio);
j = json{
{"sessionToken", connector.sessionToken},
{"installationToken", connector.installationToken},
{"privateKey", std::move(privateKey)},
{"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) {
j.at("sessionToken").get_to(connector.sessionToken);
j.at("installationToken").get_to(connector.installationToken);
// 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<std::string>()));
if(const json::const_iterator key = j.find("serverPublicKey"); key != j.end() && key->is_string()) {
connector.serverPublicKey = OwnKey(LoadPublicKeyFromPem(key->get<std::string>()));
}
connector.userType = j.value("userType", std::string());
j.at("name").get_to(connector.name);
j.at("id").get_to(connector.id);
const std::string& pem = j.at("privateKey").get_ref<const std::string&>();
BIO* bio = ThrowOnOpenssl(BIO_new_mem_buf(pem.data(), static_cast<int>(pem.size())));
EVP_PKEY* pkey = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr);
BIO_free(bio);
connector.privateKey = ThrowOnOpenssl(pkey);
}
// Connectors saved before the owner was kept all used API keys, whose user is the owner.
connector.ownerId = j.value("ownerId", connector.id);
}