Nostro/implementations/Nostro-Bunq.cpp
2026-10-06 15:39:17 +02:00

232 lines
No EOL
9.5 KiB
C++

//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;
import std;
import :Bunq;
import :Crypto;
import Crafter.Network;
using namespace Nostro;
using namespace Nostro::Crypto;
using namespace nlohmann;
using namespace Crafter;
std::vector<BunqConnector> BunqConnector::connectors;
std::string EscB(std::string_view s) {
std::string out;
out.reserve(s.size() + 8);
for (const char c : s) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (static_cast<unsigned char>(c) < 0x20) {
out += std::format("\\u{:04x}", static_cast<unsigned char>(c));
} else {
out += c;
}
}
}
return out;
}
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;
}
}
}
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");
}
}
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) {
}
void BunqAccount::SendPayment(std::string body) const {
std::string route = std::format("v1/user/{}/monetary-account/{}/payment", connector->id, id);
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
));
if(response.status != "200") {
throw std::runtime_error(std::format("{} non 200 status code: {}", route, response.body));
}
}
void BunqAccount::Send(std::string_view iban, std::string_view name, std::int64_t amount, Currency currency) const {
std::string body = std::format("{{\"amount\": {{\"value\":{}, \"currency\":\"{}\"}},\"counterparty_alias\":{{\"type\":\"IBAN\",\"value\":{}, \"name\":{}}}}}", amount, GetCurrencyCode(currency), iban, name);
SendPayment(body);
}
void BunqAccount::Send(std::string_view iban, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const {
std::string body = std::format("{{\"amount\": {{\"value\":{}, \"currency\":\"{}\"}},\"counterparty_alias\":{{\"type\":\"IBAN\",\"value\":{}, \"name\":{}}}, \"description\":\"{}\"}}", amount, GetCurrencyCode(currency), iban, name, description);
SendPayment(body);
}
void BunqConnector::RefreshSession() {
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);
}
}
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") {
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;
}
}
}
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)},
{"apiKey", connector.apiKey},
{"name", connector.name},
{"id", connector.id},
};
}
void Nostro::from_json(const json& j, BunqConnector& connector) {
j.at("sessionToken").get_to(connector.sessionToken);
j.at("installationToken").get_to(connector.installationToken);
j.at("apiKey").get_to(connector.apiKey);
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);
}