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,210 +1,117 @@
//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 Nostro:Account_impl;
import :Account;
import :File;
import std;
import Crafter.DB;
using namespace Nostro;
using namespace Crafter;
namespace fs = std::filesystem;
// Transaction is the on-disk schema of the tables below. These fail when it changes, as a reminder to bump
// Transaction::version; update them together with it.
static_assert(DB::Layout<Transaction>::rowSize == 120);
static_assert(DB::Layout<Transaction>::fingerprint == 0x1ceea246dfcdf4f0);
// Version 1, which existing tables migrate from. It must never change.
static_assert(DB::Layout<Transaction::Previous>::rowSize == 88);
static_assert(DB::Layout<Transaction::Previous>::fingerprint == 0x6b478e471876761f);
namespace {
// An account name is the file name of its table: one with a '/' in it would be a path.
std::string FileName(std::string_view account) {
std::string name(account);
std::ranges::replace(name, '/', '_');
return std::format("{}.cdb", name);
}
// Each table is opened on first use and kept open for the rest of the process, or until its connector is
// forgotten: an open maps the whole file, and a second writable Table on the same file would throw DB::LockedError.
std::map<fs::path, DB::Table<Transaction>>& Tables() {
static std::map<fs::path, DB::Table<Transaction>> tables;
return tables;
}
DB::Table<Transaction>& GetTable(std::string_view connector, std::string_view account) {
const fs::path path = cachePath / "transactions" / connector / FileName(account);
return Tables().try_emplace(path, path).first->second;
}
// ASCII case folding: enough for names and descriptions, IBANs are upper case anyway.
char Lower(char c) {
return c >= 'A' && c <= 'Z' ? static_cast<char>(c + ('a' - 'A')) : c;
}
// `search` is lower case already.
bool Contains(std::string_view text, std::string_view search) {
return !std::ranges::search(text, search, {}, Lower).empty();
}
}
std::chrono::system_clock::time_point Account::GetLastTransactionTime(std::string_view connector) const {
const fs::path path = cachePath / "transactions" / connector / (name + ".bin");
if(!fs::exists(path) || fs::file_size(path) == 0) {
const DB::Table<Transaction>& table = GetTable(connector, name);
if(table.Empty()) {
return std::chrono::system_clock::time_point::min();
}
std::ifstream file(path, std::ios::binary);
if(!file) {
throw std::runtime_error(std::format("cannot open {}", path.string()));
}
file.seekg(-static_cast<std::streamoff>(sizeof(std::int64_t)), std::ios::end);
std::int64_t lastTime;
file.read(reinterpret_cast<char*>(&lastTime), sizeof(lastTime));
return std::chrono::system_clock::time_point(std::chrono::microseconds(lastTime));
return table.Back()[&Transaction::timePoint];
}
void Account::SaveTransactions(std::string_view connector) {
const fs::path path = cachePath / "transactions" / connector / (name + ".bin");
CreatePrivateFile(path);
std::ofstream file(path, std::ios::in | std::ios::out | std::ios::binary);
if(!file) {
throw std::runtime_error(std::format("cannot open {}", path.string()));
}
void Account::SaveTransactions(std::string_view connector, std::vector<Transaction> transactions) {
DB::Table<Transaction>& table = GetTable(connector, name);
const std::chrono::system_clock::time_point last = GetLastTransactionTime(connector);
std::uint32_t pendingIndex = transactions.size();
for(std::uint32_t i = 0; i < transactions.size(); i++) {
if(transactions[i].timePoint > last) {
pendingIndex = i;
break;
}
}
file.seekp(0, std::ios::end);
for(std::uint32_t i = pendingIndex; i < transactions.size(); i++) {
WriteString(file, transactions[i].name);
WriteString(file, transactions[i].bic);
WriteString(file, transactions[i].iban);
WriteString(file, transactions[i].description);
file.write(reinterpret_cast<char*>(&transactions[i].amount), sizeof(transactions[i].amount));
file.write(reinterpret_cast<char*>(&transactions[i].currency), sizeof(Currency));
std::int64_t time = std::chrono::duration_cast<std::chrono::microseconds>(transactions[i].timePoint.time_since_epoch()).count();
file.write(reinterpret_cast<char*>(&time), sizeof(time));
}
}
Transaction& Account::LoadTransaction(std::ifstream& file) {
Transaction& tr = transactions.emplace_back();
ReadString(file, tr.name);
ReadString(file, tr.bic);
ReadString(file, tr.iban);
ReadString(file, tr.description);
file.read(reinterpret_cast<char*>(&tr.amount), sizeof(tr.amount));
file.read(reinterpret_cast<char*>(&tr.currency), sizeof(tr.currency));
std::int64_t time;
file.read(reinterpret_cast<char*>(&time), sizeof(time));
tr.timePoint = std::chrono::system_clock::time_point(std::chrono::duration_cast<std::chrono::system_clock::duration>(std::chrono::microseconds(time)));
return tr;
}
void Account::LoadTransactions(std::string_view connector) {
const fs::path path = cachePath / "transactions" / connector / (name + ".bin");
if(!fs::exists(path)) {
return;
}
std::fstream file(path, std::ios::in | std::ios::binary);
if(!file) {
throw std::runtime_error(std::format("cannot open {}", path.string()));
}
while(file.peek() != std::fstream::traits_type::eof()) {
LoadTransaction();
}
}
std::ifstream Account::LoadUntilFrom(std::string_view connector, std::chrono::system_clock::time_point from) {
const fs::path path = cachePath / "transactions" / connector / (name + ".bin");
if(!fs::exists(path)) {
return;
}
std::ifstream file(path, std::ios::in | std::ios::binary);
if(!file) {
throw std::runtime_error(std::format("cannot open {}", path.string()));
}
while(file.peek() != std::fstream::traits_type::eof()) {
std::uint16_t seeked = SeekString();
seeked += SeekString();
seeked += SeekString();
seeked += SeekString();
in.seekg(sizeof(tr.amount)+sizeof(tr.Currency), std::ios::cur);
std::int64_t timeI;
file.read(reinterpret_cast<char*>(&timeI), sizeof(tr.timeI));
std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::from_time_t(timeI);
if(timePoint > from) {
in.seekg(-seeked-sizeof(tr.amount)-sizeof(tr.Currency)-sizeof(tr.timeI), std::ios::cur);
LoadTransaction();
break;
}
}
return file;
}
void Account::LoadTransactions(std::string_view connector, std::chrono::system_clock::time_point from, std::chrono::system_clock::time_point to) {
std::ifstream file = LoadUntilFrom(connector, from);
while(file.peek() != std::fstream::traits_type::eof()) {
Transaction& tr = LoadTransaction();
if(tr.timePoint > to) {
transactions.pop_back();
break;
}
}
}
void Account::LoadTransactions(std::string_view connector, std::chrono::system_clock::time_point from) {
std::ifstream file = LoadUntilFrom(connector, from);
while(file.peek() != std::fstream::traits_type::eof()) {
LoadTransaction();
}
}
void Account::LoadTransactionsByProperty(std::string_view connector, std::string_view property) {
const fs::path path = cachePath / "transactions" / connector / (name + ".bin");
if(!fs::exists(path)) {
return;
}
std::ifstream file(path, std::ios::in | std::ios::binary);
if(!file) {
throw std::runtime_error(std::format("cannot open {}", path.string()));
}
while(file.peek() != std::fstream::traits_type::eof()) {
std::uint16_t seeked = SeekString();
seeked += SeekString();
seeked += SeekString();
std::uint16_t size;
file.read(reinterpret_cast<char*>(&size), sizeof(size));
if(description.size() == size) {
std::string readDescription;
readDescription.resize(size);
file.read(readDescription.data(), size);
if(readDescription == description) {
in.seekg(-seeked-readDescription.size()-sizeof(size), std::ios::cur);
Transaction& tr = transactions.emplace_back();
ReadString(file, tr.name);
ReadString(file, tr.bic);
ReadString(file, tr.iban);
SeekString();
file.read(reinterpret_cast<char*>(&tr.amount), sizeof(tr.amount));
file.read(reinterpret_cast<char*>(&tr.currency), sizeof(tr.Currency));
file.read(reinterpret_cast<char*>(&tr.time), sizeof(tr.time));
// The ids stored at the last timestamp: a fetch that includes that timestamp again brings them back. A row there
// without an id (stored by version 1) cannot be matched, so then nothing at that timestamp is taken as new.
std::vector<std::string> known;
bool unmatchable = false;
if(!table.Empty()) {
for(DB::RowId id = table.LowerBound<&Transaction::timePoint>(last); id < table.SlotCount(); id++) {
const DB::Row<Transaction> row = table[id];
if(!row.Erased()) {
const std::string_view stored = row[&Transaction::id];
unmatchable = unmatchable || stored.empty();
known.emplace_back(stored);
}
}
}
// The table is ordered by timePoint and refuses a row older than its last one. A row at the last timestamp is
// new when its id is.
std::ranges::stable_sort(transactions, {}, &Transaction::timePoint);
std::erase_if(transactions, [last, unmatchable, &known](const Transaction& transaction) {
return transaction.timePoint < last || (transaction.timePoint == last && (unmatchable || transaction.id.empty() || std::ranges::contains(known, transaction.id)));
});
table.Append(std::span<const Transaction>(transactions));
table.Flush();
}
void Account::LoadTransactionsByIban(std::string_view connector, std::string_view iban) {
transactions.clear();
void Account::ForgetTransactions(std::string_view connector) {
const fs::path directory = cachePath / "transactions" / connector;
std::erase_if(Tables(), [&directory](const std::pair<const fs::path, DB::Table<Transaction>>& table) {
return std::mismatch(directory.begin(), directory.end(), table.first.begin(), table.first.end()).first == directory.end();
});
fs::remove_all(directory);
}
const fs::path path = cachePath / "transactions" / connector / (name + ".bin");
if(!fs::exists(path)) {
return;
}
std::vector<Transaction> Account::FindTransactions(std::string_view connector, const TransactionQuery& query) const {
const DB::Table<Transaction>& table = GetTable(connector, name);
const std::string search = query.search | std::views::transform(Lower) | std::ranges::to<std::string>();
std::ifstream file(path, std::ios::in | std::ios::binary);
if(!file) {
throw std::runtime_error(std::format("cannot open {}", path.string()));
}
while(file.peek() != std::fstream::traits_type::eof()) {
std::uint16_t seeked = SeekString();
seeked += SeekString();
std::uint16_t size;
file.read(reinterpret_cast<char*>(&size), sizeof(size));
if(iban.size() == size) {
std::string readIban;
readIban.resize(size);
file.read(readIban.data(), size);
if(readIban == iban) {
in.seekg(-seeked-readIban.size()-sizeof(size), std::ios::cur);
Transaction& tr = transactions.emplace_back();
ReadString(file, tr.name);
ReadString(file, tr.bic);
SeekString();
ReadString(file, tr.description);
file.read(reinterpret_cast<char*>(&tr.amount), sizeof(tr.amount));
file.read(reinterpret_cast<char*>(&tr.currency), sizeof(tr.Currency));
file.read(reinterpret_cast<char*>(&tr.time), sizeof(tr.time));
}
// Walk the time range backwards from the newest row and stop at the limit, so a search that matches often
// returns early; only a rare or failed one reads the whole range.
const DB::RowId first = table.LowerBound<&Transaction::timePoint>(query.from);
std::vector<Transaction> rows;
for(DB::RowId id = table.UpperBound<&Transaction::timePoint>(query.to); id > first && rows.size() < query.limit; id--) {
const DB::Row<Transaction> row = table[id - 1];
if(row.Erased() || (query.amount && row[&Transaction::amount] != *query.amount)) {
continue;
}
if(search.empty() || Contains(row[&Transaction::name], search) || Contains(row[&Transaction::description], search) || Contains(row[&Transaction::iban], search)) {
rows.push_back(row.Materialize());
}
}
}
return rows;
}

View file

@ -0,0 +1,333 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include "../lib/json.hpp"
module Nostro:BunqPayments_impl;
import std;
import :Bunq;
import :Currency;
import :Utils;
using namespace Nostro;
using namespace nlohmann;
namespace {
// ISO 13616: with the first four characters moved to the end and letters read as 10 to 35, the number is 1 mod 97.
bool ValidIban(std::string_view iban) {
if(iban.size() < 15 || iban.size() > 34 || !std::isalpha(static_cast<std::uint8_t>(iban[0])) || !std::isalpha(static_cast<std::uint8_t>(iban[1])) || !std::isdigit(static_cast<std::uint8_t>(iban[2])) || !std::isdigit(static_cast<std::uint8_t>(iban[3]))) {
return false;
}
std::uint32_t remainder = 0;
const std::string rearranged = std::format("{}{}", iban.substr(4), iban.substr(0, 4));
for(const char c : rearranged) {
if(c >= '0' && c <= '9') {
remainder = (remainder * 10 + static_cast<std::uint32_t>(c - '0')) % 97;
} else if(c >= 'A' && c <= 'Z') {
remainder = (remainder * 100 + static_cast<std::uint32_t>(c - 'A' + 10)) % 97;
} else {
return false;
}
}
return remainder == 1;
}
void RequirePositive(std::int64_t amount) {
if(amount <= 0) {
throw std::invalid_argument("the amount must be more than zero");
}
}
std::uint64_t CreatedId(const json& response) {
return BunqJson::Item(response, "Id").at("id").get<std::uint64_t>();
}
// The objects of one type in a listing, skipping anything else bunq puts in it. Some listings name their objects
// differently from the spec (scheduled payments come as ScheduledPayment, not SchedulePayment): every name in
// `types` is taken.
template<typename T, typename Read>
std::vector<T> ReadAll(const std::vector<json>& items, std::initializer_list<std::string_view> types, Read&& read) {
std::vector<T> out;
for(const json& item : items) {
for(const std::string_view type : types) {
if(const json::const_iterator object = item.find(type); object != item.end()) {
out.push_back(read(*object));
break;
}
}
}
return out;
}
std::chrono::system_clock::time_point Timestamp(const json& object, std::string_view key) {
const std::string text = BunqJson::String(object, key);
return text.empty() ? std::chrono::system_clock::time_point() : ParseTimestamp(text);
}
BunqPaymentRequest ReadRequest(const json& inquiry) {
const auto [currency, amount] = BunqJson::ReadAmount(inquiry.at("amount_inquired"));
BunqPaymentRequest out{
.id = inquiry.at("id").get<std::uint64_t>(),
.status = BunqJson::String(inquiry, "status"),
.counterparty = BunqJson::ReadLabel(inquiry.at("counterparty_alias")),
.currency = currency,
.amount = amount,
.amountPaid = std::nullopt,
.description = BunqJson::String(inquiry, "description"),
.created = Timestamp(inquiry, "created"),
.shareUrl = BunqJson::String(inquiry, "bunqme_share_url"),
};
if(const json::const_iterator paid = inquiry.find("amount_responded"); paid != inquiry.end() && paid->is_object()) {
out.amountPaid = BunqJson::ReadAmount(*paid).second;
}
return out;
}
BunqIncomingRequest ReadIncoming(const json& response) {
const auto [currency, amount] = BunqJson::ReadAmount(response.at("amount_inquired"));
return BunqIncomingRequest{
.id = response.at("id").get<std::uint64_t>(),
.status = BunqJson::String(response, "status"),
.type = BunqJson::String(response, "type"),
.counterparty = BunqJson::ReadLabel(response.at("counterparty_alias")),
.currency = currency,
.amount = amount,
.description = BunqJson::String(response, "description"),
.created = Timestamp(response, "created"),
};
}
BunqScheduledPayment ReadScheduled(const json& scheduled) {
const json& payment = scheduled.at("payment");
const json& schedule = scheduled.at("schedule");
const auto [currency, amount] = BunqJson::ReadAmount(payment.at("amount"));
BunqSchedule when{
.start = Timestamp(schedule, "time_start"),
.end = std::nullopt,
.unit = BunqJson::String(schedule, "recurrence_unit"),
.every = schedule.value("recurrence_size", std::uint32_t{1}),
.status = BunqJson::String(scheduled, "status"),
.next = std::nullopt,
};
if(!BunqJson::String(schedule, "time_end").empty()) {
when.end = Timestamp(schedule, "time_end");
}
if(!BunqJson::String(schedule, "time_next").empty()) {
when.next = Timestamp(schedule, "time_next");
}
if(when.status.empty()) {
when.status = BunqJson::String(schedule, "status");
}
return BunqScheduledPayment{
.id = scheduled.at("id").get<std::uint64_t>(),
.counterparty = BunqJson::ReadLabel(payment.at("counterparty_alias")),
.currency = currency,
// Each run sends this much; bunq lists it as positive or negative depending on the endpoint.
.amount = amount < 0 ? -amount : amount,
.description = BunqJson::String(payment, "description"),
.schedule = std::move(when),
};
}
BunqDraftPayment ReadDraft(const json& draft) {
BunqDraftPayment out{
.id = draft.at("id").get<std::uint64_t>(),
.status = BunqJson::String(draft, "status"),
.createdBy = std::string(),
.entries = {},
.updated = BunqJson::String(draft, "updated"),
};
if(const json::const_iterator creator = draft.find("user_alias_created"); creator != draft.end()) {
out.createdBy = BunqJson::String(*creator, "display_name");
}
if(const json::const_iterator entries = draft.find("entries"); entries != draft.end() && entries->is_array()) {
for(const json& entry : *entries) {
const auto [currency, amount] = BunqJson::ReadAmount(entry.at("amount"));
out.entries.push_back(BunqDraftPayment::Entry{
.counterparty = BunqJson::ReadLabel(entry.at("counterparty_alias")),
.currency = currency,
.amount = amount < 0 ? -amount : amount,
.description = BunqJson::String(entry, "description"),
});
}
}
return out;
}
// What a payment, draft entry and scheduled payment share.
json PaymentBody(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) {
RequirePositive(amount);
return json{
{"amount", BunqJson::Amount(amount, currency)},
{"counterparty_alias", BunqJson::Pointer(BunqCounterparty::Parse(to, name))},
{"description", std::string(description)},
};
}
}
BunqCounterparty BunqCounterparty::Parse(std::string_view value, std::string_view name) {
while(value.starts_with(' ')) {
value.remove_prefix(1);
}
while(value.ends_with(' ')) {
value.remove_suffix(1);
}
if(value.contains('@')) {
return BunqCounterparty{"EMAIL", std::string(value), std::string(name)};
}
if(value.starts_with('+')) {
std::string phone = "+";
for(const char c : value.substr(1)) {
if(c >= '0' && c <= '9') {
phone += c;
} else if(c != ' ' && c != '-' && c != '(' && c != ')') {
throw std::invalid_argument(std::format("'{}' is not a phone number", value));
}
}
if(phone.size() < 8) {
throw std::invalid_argument(std::format("'{}' is not a phone number", value));
}
return BunqCounterparty{"PHONE_NUMBER", std::move(phone), std::string(name)};
}
std::string iban;
for(const char c : value) {
if(c != ' ') {
iban += static_cast<char>(std::toupper(static_cast<std::uint8_t>(c)));
}
}
if(!ValidIban(iban)) {
throw std::invalid_argument(std::format("'{}' is not a valid IBAN, e-mail address or phone number (+31...)", value));
}
return BunqCounterparty{"IBAN", std::move(iban), std::string(name)};
}
std::uint64_t BunqAccount::Send(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const {
return CreatedId(connector->Post(std::format("{}/payment", Path()), PaymentBody(to, name, amount, currency, description)));
}
std::uint64_t BunqAccount::Draft(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const {
const json body = {
{"entries", json::array({PaymentBody(to, name, amount, currency, description)})},
{"number_of_required_accepts", 1},
};
return CreatedId(connector->Post(std::format("{}/draft-payment", Path()), body));
}
void BunqSchedule::Check() const {
constexpr std::array<std::string_view, 6> units = {"ONCE", "HOURLY", "DAILY", "WEEKLY", "MONTHLY", "YEARLY"};
if(!std::ranges::contains(units, unit)) {
throw std::invalid_argument(std::format("'{}' is not a schedule: once, hourly, daily, weekly, monthly or yearly", unit));
}
if(every == 0) {
throw std::invalid_argument("a schedule repeats at least every 1 unit");
}
}
std::uint64_t BunqAccount::Schedule(std::string_view to, std::string_view name, std::int64_t amount, Currency currency, std::string_view description, const BunqSchedule& schedule) const {
schedule.Check();
json when = {
{"time_start", FormatTimestamp(schedule.start)},
{"recurrence_unit", schedule.unit},
{"recurrence_size", schedule.every},
};
if(schedule.end) {
when["time_end"] = FormatTimestamp(*schedule.end);
}
const json body = {
{"payment", PaymentBody(to, name, amount, currency, description)},
{"schedule", std::move(when)},
};
return CreatedId(connector->Post(std::format("{}/schedule-payment", Path()), body));
}
BunqPaymentRequest BunqAccount::Request(std::string_view from, std::string_view name, std::int64_t amount, Currency currency, std::string_view description) const {
RequirePositive(amount);
const json body = {
{"amount_inquired", BunqJson::Amount(amount, currency)},
{"counterparty_alias", BunqJson::Pointer(BunqCounterparty::Parse(from, name))},
{"description", std::string(description)},
{"allow_bunqme", true},
};
const std::uint64_t id = CreatedId(connector->Post(std::format("{}/request-inquiry", Path()), body));
// The share URL is only on the object, not in the creation's response. The request exists whatever happens to
// this read: failing here would look like a failed request, and asking again would ask twice.
try {
return ReadRequest(BunqJson::Item(connector->Get(std::format("{}/request-inquiry/{}", Path(), id)), "RequestInquiry"));
} catch(const std::exception& e) {
Note(std::format("request {} was made, but reading it back failed: {}", id, e.what()));
const BunqCounterparty counterparty = BunqCounterparty::Parse(from, name);
return BunqPaymentRequest{
.id = id,
.status = "PENDING",
.counterparty = BunqLabel{counterparty.name, counterparty.type == "IBAN" ? counterparty.value : std::string()},
.currency = currency,
.amount = amount,
.amountPaid = std::nullopt,
.description = std::string(description),
.created = std::chrono::system_clock::now(),
.shareUrl = std::string(),
};
}
}
std::vector<BunqPaymentRequest> BunqAccount::Requests() const {
return ReadAll<BunqPaymentRequest>(connector->List(std::format("{}/request-inquiry", Path())), {"RequestInquiry"}, ReadRequest);
}
std::vector<BunqIncomingRequest> BunqAccount::IncomingRequests() const {
return ReadAll<BunqIncomingRequest>(connector->List(std::format("{}/request-response", Path())), {"RequestResponse"}, ReadIncoming);
}
std::vector<BunqScheduledPayment> BunqAccount::ScheduledPayments() const {
return ReadAll<BunqScheduledPayment>(connector->List(std::format("{}/schedule-payment", Path())), {"ScheduledPayment", "SchedulePayment"}, ReadScheduled);
}
std::vector<BunqDraftPayment> BunqAccount::DraftPayments() const {
return ReadAll<BunqDraftPayment>(connector->List(std::format("{}/draft-payment", Path())), {"DraftPayment"}, ReadDraft);
}
BunqIncomingRequest BunqAccount::IncomingRequest(std::uint64_t id) const {
return ReadIncoming(BunqJson::Item(connector->Get(std::format("{}/request-response/{}", Path(), id)), "RequestResponse"));
}
BunqDraftPayment BunqAccount::DraftPayment(std::uint64_t id) const {
return ReadDraft(BunqJson::Item(connector->Get(std::format("{}/draft-payment/{}", Path(), id)), "DraftPayment"));
}
void BunqAccount::RevokeRequest(std::uint64_t id) const {
connector->Put(std::format("{}/request-inquiry/{}", Path(), id), json{{"status", "REVOKED"}});
}
void BunqAccount::RespondToRequest(const BunqIncomingRequest& shown, bool accept) const {
const std::string path = std::format("{}/request-response/{}", Path(), shown.id);
if(!accept) {
connector->Put(path, json{{"status", "REJECTED"}});
return;
}
// Accepting names the amount paid: the amount that was shown, not what the request asks by the time this runs,
// which the asker can change in between.
connector->Put(path, json{{"amount_responded", BunqJson::Amount(shown.amount, shown.currency)}, {"status", "ACCEPTED"}});
}
void BunqAccount::CancelScheduledPayment(std::uint64_t id) const {
connector->Delete(std::format("{}/schedule-payment/{}", Path(), id));
}
void BunqAccount::RespondToDraftPayment(const BunqDraftPayment& shown, bool accept) const {
// bunq refuses a response to a draft that changed since it was read, by its updated timestamp: the one of the
// draft that was shown, so a change made after that is refused rather than accepted unseen.
json body = {{"status", accept ? "ACCEPTED" : "REJECTED"}};
if(!shown.updated.empty()) {
body["previous_updated_timestamp"] = shown.updated;
}
connector->Put(std::format("{}/draft-payment/{}", Path(), shown.id), body);
}

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);
}

View file

@ -0,0 +1,554 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include <errno.h>
#include <systemd/sd-bus.h>
module Nostro:Bus_impl;
import std;
import :Bus;
import :Account;
import :Bunq;
import :Currency;
import :Transaction;
using namespace Nostro;
using namespace Nostro::Bus;
std::int32_t Bus::ThrowOnSdBus(std::int32_t result, std::string_view what) {
if(result < 0) {
throw std::system_error(-result, std::generic_category(), std::format("cannot {}", what));
}
return result;
}
namespace {
// A C string sd-bus handed out, as a string; null is empty.
// lint-disable-next-line no-char-pointer
std::string Text(const char* text) {
return text ? std::string(text) : std::string();
}
}
std::string Bus::Sender(sd_bus_message* message) {
return Text(sd_bus_message_get_sender(message));
}
std::string Bus::Interface(sd_bus_message* message) {
return Text(sd_bus_message_get_interface(message));
}
std::string Bus::Member(sd_bus_message* message) {
return Text(sd_bus_message_get_member(message));
}
std::string Bus::ErrorName(const sd_bus_error& error) {
return Text(error.name);
}
std::string Bus::ErrorMessage(const sd_bus_error& error) {
return Text(error.message);
}
bool Bus::IsSensitive(std::string_view member) {
return std::ranges::any_of(methods, [member](const Method& method) { return method.member == member && method.sensitive; });
}
std::string Bus::ReadText(sd_bus_message* message, char type) {
// sd-bus hands out strings as C strings into the message, valid while it lives.
// lint-disable-next-line no-char-pointer
const char* value = nullptr;
ThrowOnSdBus(sd_bus_message_read_basic(message, type, &value), "read a string");
return Text(value);
}
void Bus::BusUnref::operator()(sd_bus* bus) const {
sd_bus_flush_close_unref(bus);
}
void Bus::MessageUnref::operator()(sd_bus_message* message) const {
sd_bus_message_unref(message);
}
Bus::Error::~Error() {
sd_bus_error_free(&error);
}
std::vector<sd_bus_vtable> Bus::Vtable(std::span<const Method> table, const std::function<sd_bus_message_handler_t(std::string_view member)>& handler) {
std::vector<sd_bus_vtable> vtable = {SD_BUS_VTABLE_START(0)};
for(const Method& method : table) {
const std::uint64_t flags = SD_BUS_VTABLE_UNPRIVILEGED | (method.sensitive ? SD_BUS_VTABLE_SENSITIVE : 0);
sd_bus_vtable entry = SD_BUS_METHOD_WITH_NAMES_OFFSET(method.member.data(), method.in.data(), "", method.out.data(), "", handler(method.member), 0, flags);
// The names of the arguments and of the reply, which the macro would only take as literals to join.
entry.x.method.names = method.names.data();
vtable.push_back(entry);
}
vtable.push_back(SD_BUS_VTABLE_END);
return vtable;
}
void Bus::Enter(sd_bus_message* message, char type, std::string_view contents) {
// Every message was checked against its signature before it got here, so the container is there.
ThrowOnSdBus(sd_bus_message_enter_container(message, type, std::string(contents).c_str()), "read a container");
}
void Bus::Leave(sd_bus_message* message) {
ThrowOnSdBus(sd_bus_message_exit_container(message), "leave a container");
}
void Bus::Open(sd_bus_message* message, char type, std::string_view contents) {
ThrowOnSdBus(sd_bus_message_open_container(message, type, std::string(contents).c_str()), "open a container");
}
void Bus::Close(sd_bus_message* message) {
ThrowOnSdBus(sd_bus_message_close_container(message), "close a container");
}
namespace {
// A basic value, or an exception when the message holds something else or has ended.
template<typename T>
T ReadBasic(sd_bus_message* message, char type) {
T value{};
ThrowOnSdBus(sd_bus_message_read_basic(message, type, &value), "read a value");
return value;
}
std::chrono::system_clock::time_point FromMicroseconds(std::int64_t microseconds) {
return std::chrono::system_clock::time_point(std::chrono::microseconds(microseconds));
}
std::int64_t ToMicroseconds(std::chrono::system_clock::time_point time) {
return std::chrono::duration_cast<std::chrono::microseconds>(time.time_since_epoch()).count();
}
}
void Bus::Wire<std::string>::Append(sd_bus_message* message, const std::string& value) {
// D-Bus carries UTF-8 only: sd-bus refuses anything else.
const std::int32_t result = sd_bus_message_append_basic(message, 's', value.c_str());
if(result == -EINVAL) {
throw std::invalid_argument("text that is not UTF-8 cannot be sent to nostrod");
}
ThrowOnSdBus(result, "append a string");
}
std::string Bus::Wire<std::string>::Read(sd_bus_message* message) {
return ReadText(message, 's');
}
void Bus::Wire<bool>::Append(sd_bus_message* message, bool value) {
const std::int32_t b = value ? 1 : 0;
ThrowOnSdBus(sd_bus_message_append_basic(message, 'b', &b), "append a boolean");
}
bool Bus::Wire<bool>::Read(sd_bus_message* message) {
return ReadBasic<std::int32_t>(message, 'b') != 0;
}
void Bus::Wire<std::uint32_t>::Append(sd_bus_message* message, std::uint32_t value) {
ThrowOnSdBus(sd_bus_message_append_basic(message, 'u', &value), "append a number");
}
std::uint32_t Bus::Wire<std::uint32_t>::Read(sd_bus_message* message) {
return ReadBasic<std::uint32_t>(message, 'u');
}
void Bus::Wire<std::int64_t>::Append(sd_bus_message* message, std::int64_t value) {
ThrowOnSdBus(sd_bus_message_append_basic(message, 'x', &value), "append a number");
}
std::int64_t Bus::Wire<std::int64_t>::Read(sd_bus_message* message) {
return ReadBasic<std::int64_t>(message, 'x');
}
void Bus::Wire<std::uint64_t>::Append(sd_bus_message* message, std::uint64_t value) {
ThrowOnSdBus(sd_bus_message_append_basic(message, 't', &value), "append a number");
}
std::uint64_t Bus::Wire<std::uint64_t>::Read(sd_bus_message* message) {
return ReadBasic<std::uint64_t>(message, 't');
}
void Bus::Wire<std::chrono::system_clock::time_point>::Append(sd_bus_message* message, std::chrono::system_clock::time_point value) {
Wire<std::int64_t>::Append(message, ToMicroseconds(value));
}
std::chrono::system_clock::time_point Bus::Wire<std::chrono::system_clock::time_point>::Read(sd_bus_message* message) {
return FromMicroseconds(Wire<std::int64_t>::Read(message));
}
void Bus::Wire<Currency>::Append(sd_bus_message* message, Currency value) {
Wire<std::string>::Append(message, std::string(GetCurrencyCode(value)));
}
Currency Bus::Wire<Currency>::Read(sd_bus_message* message) {
return GetCurrency(Wire<std::string>::Read(message));
}
void Bus::Wire<Account>::Append(sd_bus_message* message, const Account& value) {
Open(message, 'r', contents);
Bus::Append(message, value.name);
Bus::Append(message, value.bic);
Bus::Append(message, value.iban);
Bus::Append(message, value.currency);
Bus::Append(message, value.balance);
Close(message);
}
Account Bus::Wire<Account>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
Account value{};
value.name = Bus::Read<std::string>(message);
value.bic = Bus::Read<std::string>(message);
value.iban = Bus::Read<std::string>(message);
value.currency = Bus::Read<Currency>(message);
value.balance = Bus::Read<std::int64_t>(message);
Leave(message);
return value;
}
void Bus::Wire<Transaction>::Append(sd_bus_message* message, const Transaction& value) {
Open(message, 'r', contents);
Bus::Append(message, value.name);
Bus::Append(message, value.bic);
Bus::Append(message, value.iban);
Bus::Append(message, value.description);
Bus::Append(message, value.currency);
Bus::Append(message, value.amount);
Bus::Append(message, value.timePoint);
Bus::Append(message, value.id);
Bus::Append(message, value.kind);
Close(message);
}
Transaction Bus::Wire<Transaction>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
Transaction value{};
value.name = Bus::Read<std::string>(message);
value.bic = Bus::Read<std::string>(message);
value.iban = Bus::Read<std::string>(message);
value.description = Bus::Read<std::string>(message);
value.currency = Bus::Read<Currency>(message);
value.amount = Bus::Read<std::int64_t>(message);
value.timePoint = Bus::Read<std::chrono::system_clock::time_point>(message);
value.id = Bus::Read<std::string>(message);
value.kind = Bus::Read<std::string>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqLabel>::Append(sd_bus_message* message, const BunqLabel& value) {
Open(message, 'r', contents);
Bus::Append(message, value.name);
Bus::Append(message, value.iban);
Close(message);
}
BunqLabel Bus::Wire<BunqLabel>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqLabel value;
value.name = Bus::Read<std::string>(message);
value.iban = Bus::Read<std::string>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqPaymentRequest>::Append(sd_bus_message* message, const BunqPaymentRequest& value) {
Open(message, 'r', contents);
Bus::Append(message, value.id);
Bus::Append(message, value.status);
Bus::Append(message, value.counterparty);
Bus::Append(message, value.currency);
Bus::Append(message, value.amount);
Bus::Append(message, value.amountPaid);
Bus::Append(message, value.description);
Bus::Append(message, value.created);
Bus::Append(message, value.shareUrl);
Close(message);
}
BunqPaymentRequest Bus::Wire<BunqPaymentRequest>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqPaymentRequest value{};
value.id = Bus::Read<std::uint64_t>(message);
value.status = Bus::Read<std::string>(message);
value.counterparty = Bus::Read<BunqLabel>(message);
value.currency = Bus::Read<Currency>(message);
value.amount = Bus::Read<std::int64_t>(message);
value.amountPaid = Bus::Read<std::optional<std::int64_t>>(message);
value.description = Bus::Read<std::string>(message);
value.created = Bus::Read<std::chrono::system_clock::time_point>(message);
value.shareUrl = Bus::Read<std::string>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqIncomingRequest>::Append(sd_bus_message* message, const BunqIncomingRequest& value) {
Open(message, 'r', contents);
Bus::Append(message, value.id);
Bus::Append(message, value.status);
Bus::Append(message, value.type);
Bus::Append(message, value.counterparty);
Bus::Append(message, value.currency);
Bus::Append(message, value.amount);
Bus::Append(message, value.description);
Bus::Append(message, value.created);
Close(message);
}
BunqIncomingRequest Bus::Wire<BunqIncomingRequest>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqIncomingRequest value{};
value.id = Bus::Read<std::uint64_t>(message);
value.status = Bus::Read<std::string>(message);
value.type = Bus::Read<std::string>(message);
value.counterparty = Bus::Read<BunqLabel>(message);
value.currency = Bus::Read<Currency>(message);
value.amount = Bus::Read<std::int64_t>(message);
value.description = Bus::Read<std::string>(message);
value.created = Bus::Read<std::chrono::system_clock::time_point>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqSchedule>::Append(sd_bus_message* message, const BunqSchedule& value) {
Open(message, 'r', contents);
Bus::Append(message, value.start);
Bus::Append(message, value.end);
Bus::Append(message, value.unit);
Bus::Append(message, value.every);
Bus::Append(message, value.status);
Bus::Append(message, value.next);
Close(message);
}
BunqSchedule Bus::Wire<BunqSchedule>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqSchedule value;
value.start = Bus::Read<std::chrono::system_clock::time_point>(message);
value.end = Bus::Read<std::optional<std::chrono::system_clock::time_point>>(message);
value.unit = Bus::Read<std::string>(message);
value.every = Bus::Read<std::uint32_t>(message);
value.status = Bus::Read<std::string>(message);
value.next = Bus::Read<std::optional<std::chrono::system_clock::time_point>>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqScheduledPayment>::Append(sd_bus_message* message, const BunqScheduledPayment& value) {
Open(message, 'r', contents);
Bus::Append(message, value.id);
Bus::Append(message, value.counterparty);
Bus::Append(message, value.currency);
Bus::Append(message, value.amount);
Bus::Append(message, value.description);
Bus::Append(message, value.schedule);
Close(message);
}
BunqScheduledPayment Bus::Wire<BunqScheduledPayment>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqScheduledPayment value{};
value.id = Bus::Read<std::uint64_t>(message);
value.counterparty = Bus::Read<BunqLabel>(message);
value.currency = Bus::Read<Currency>(message);
value.amount = Bus::Read<std::int64_t>(message);
value.description = Bus::Read<std::string>(message);
value.schedule = Bus::Read<BunqSchedule>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqDraftPayment::Entry>::Append(sd_bus_message* message, const BunqDraftPayment::Entry& value) {
Open(message, 'r', contents);
Bus::Append(message, value.counterparty);
Bus::Append(message, value.currency);
Bus::Append(message, value.amount);
Bus::Append(message, value.description);
Close(message);
}
BunqDraftPayment::Entry Bus::Wire<BunqDraftPayment::Entry>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqDraftPayment::Entry value{};
value.counterparty = Bus::Read<BunqLabel>(message);
value.currency = Bus::Read<Currency>(message);
value.amount = Bus::Read<std::int64_t>(message);
value.description = Bus::Read<std::string>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqDraftPayment>::Append(sd_bus_message* message, const BunqDraftPayment& value) {
Open(message, 'r', contents);
Bus::Append(message, value.id);
Bus::Append(message, value.status);
Bus::Append(message, value.createdBy);
Bus::Append(message, value.entries);
Bus::Append(message, value.updated);
Close(message);
}
BunqDraftPayment Bus::Wire<BunqDraftPayment>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqDraftPayment value{};
value.id = Bus::Read<std::uint64_t>(message);
value.status = Bus::Read<std::string>(message);
value.createdBy = Bus::Read<std::string>(message);
value.entries = Bus::Read<std::vector<BunqDraftPayment::Entry>>(message);
value.updated = Bus::Read<std::string>(message);
Leave(message);
return value;
}
void Bus::Wire<BunqCard>::Append(sd_bus_message* message, const BunqCard& value) {
Open(message, 'r', contents);
Bus::Append(message, value.id);
Bus::Append(message, value.kind);
Bus::Append(message, value.productType);
Bus::Append(message, value.status);
Bus::Append(message, value.orderStatus);
Bus::Append(message, value.nameOnCard);
Bus::Append(message, value.secondLine);
Bus::Append(message, value.lastFour);
Bus::Append(message, value.expiry);
Bus::Append(message, value.iban);
Close(message);
}
BunqCard Bus::Wire<BunqCard>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
BunqCard value{};
value.id = Bus::Read<std::uint64_t>(message);
value.kind = Bus::Read<std::string>(message);
value.productType = Bus::Read<std::string>(message);
value.status = Bus::Read<std::string>(message);
value.orderStatus = Bus::Read<std::string>(message);
value.nameOnCard = Bus::Read<std::string>(message);
value.secondLine = Bus::Read<std::string>(message);
value.lastFour = Bus::Read<std::string>(message);
value.expiry = Bus::Read<std::string>(message);
value.iban = Bus::Read<std::string>(message);
Leave(message);
return value;
}
void Bus::Wire<ConnectorSummary>::Append(sd_bus_message* message, const ConnectorSummary& value) {
Open(message, 'r', contents);
Bus::Append(message, value.name);
Bus::Append(message, value.bank);
Bus::Append(message, value.environment);
Bus::Append(message, value.auth);
Bus::Append(message, value.working);
Close(message);
}
ConnectorSummary Bus::Wire<ConnectorSummary>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
ConnectorSummary value;
value.name = Bus::Read<std::string>(message);
value.bank = Bus::Read<std::string>(message);
value.environment = Bus::Read<std::string>(message);
value.auth = Bus::Read<std::string>(message);
value.working = Bus::Read<bool>(message);
Leave(message);
return value;
}
void Bus::Wire<ConnectorAccounts>::Append(sd_bus_message* message, const ConnectorAccounts& value) {
Open(message, 'r', contents);
Bus::Append(message, value.name);
Bus::Append(message, value.bank);
Bus::Append(message, value.accounts);
Close(message);
}
ConnectorAccounts Bus::Wire<ConnectorAccounts>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
ConnectorAccounts value;
value.name = Bus::Read<std::string>(message);
value.bank = Bus::Read<std::string>(message);
value.accounts = Bus::Read<std::vector<Account>>(message);
Leave(message);
return value;
}
void Bus::Wire<ConnectorCards>::Append(sd_bus_message* message, const ConnectorCards& value) {
Open(message, 'r', contents);
Bus::Append(message, value.name);
Bus::Append(message, value.bank);
Bus::Append(message, value.cards);
Close(message);
}
ConnectorCards Bus::Wire<ConnectorCards>::Read(sd_bus_message* message) {
Enter(message, 'r', contents);
ConnectorCards value;
value.name = Bus::Read<std::string>(message);
value.bank = Bus::Read<std::string>(message);
value.cards = Bus::Read<std::vector<BunqCard>>(message);
Leave(message);
return value;
}
void Bus::AppendQuery(sd_bus_message* message, const TransactionQuery& query) {
Open(message, 'a', "{sv}");
const auto entry = [message](std::string_view key, std::string_view type, const auto& value) {
Open(message, 'e', "sv");
Bus::Append(message, std::string(key));
Open(message, 'v', type);
Bus::Append(message, value);
Close(message);
Close(message);
};
if(!query.search.empty()) {
entry("search", "s", query.search);
}
if(query.amount) {
entry("amount", "x", *query.amount);
}
if(query.from != std::chrono::system_clock::time_point::min()) {
entry("from", "x", query.from);
}
if(query.to != std::chrono::system_clock::time_point::max()) {
entry("to", "x", query.to);
}
entry("limit", "t", static_cast<std::uint64_t>(query.limit));
Close(message);
}
TransactionQuery Bus::ReadQuery(sd_bus_message* message) {
TransactionQuery query;
Enter(message, 'a', "{sv}");
while(ThrowOnSdBus(sd_bus_message_at_end(message, 0), "read a query") == 0) {
Enter(message, 'e', "sv");
const std::string key = Bus::Read<std::string>(message);
if(key == "search") {
Enter(message, 'v', "s");
query.search = Bus::Read<std::string>(message);
Leave(message);
} else if(key == "amount") {
Enter(message, 'v', "x");
query.amount = Bus::Read<std::int64_t>(message);
Leave(message);
} else if(key == "from") {
Enter(message, 'v', "x");
query.from = Bus::Read<std::chrono::system_clock::time_point>(message);
Leave(message);
} else if(key == "to") {
Enter(message, 'v', "x");
query.to = Bus::Read<std::chrono::system_clock::time_point>(message);
Leave(message);
} else if(key == "limit") {
Enter(message, 'v', "t");
query.limit = Bus::Read<std::uint64_t>(message);
Leave(message);
} else {
ThrowOnSdBus(sd_bus_message_skip(message, "v"), "skip an unknown query key");
}
Leave(message);
}
Leave(message);
return query;
}

View file

@ -0,0 +1,246 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include <systemd/sd-bus.h>
module Nostro:Client_impl;
import std;
import :Client;
import :Bus;
import :Account;
import :Bunq;
import :Currency;
import :Transaction;
using namespace Nostro;
using namespace Nostro::Bus;
DaemonError::DaemonError(std::string name, const std::string& message) : std::runtime_error(message), name(std::move(name)) {
}
Client Client::System(std::chrono::seconds timeout) {
sd_bus* bus = nullptr;
ThrowOnSdBus(sd_bus_open_system_with_description(&bus, "nostro"), "connect to the system bus");
BusPtr owned(bus);
ThrowOnSdBus(sd_bus_set_method_call_timeout(bus, static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(timeout).count())), "connect to the system bus");
ThrowOnSdBus(sd_bus_set_allow_interactive_authorization(bus, 1), "connect to the system bus");
return Client(std::move(owned));
}
Client::Client(BusPtr bus) : bus(std::move(bus)) {
}
namespace {
// nostrod's error, as an exception: input it refused as std::invalid_argument, the rest as a DaemonError.
[[noreturn]] void Throw(const sd_bus_error& error, bool changes) {
const std::string name = ErrorName(error);
const std::string message = ErrorMessage(error);
if(name == SD_BUS_ERROR_SERVICE_UNKNOWN) {
throw std::runtime_error(std::format("nostrod is not running, and the system bus cannot start it: is it installed? ({})", message));
}
if(name == errorInvalidArgument) {
throw std::invalid_argument(message);
}
if(changes && (name == SD_BUS_ERROR_NO_REPLY || name == SD_BUS_ERROR_TIMEOUT)) {
throw std::runtime_error(std::format("nostrod did not answer in time ({}): what you asked for may have been carried out, check before trying again", message));
}
throw DaemonError(name, message);
}
// Calls `member` with what `append` appends, reads the answer with `read`, and keeps the notes that end it.
// `changes` says whether the call moves money or changes anything, for what a lost answer means.
template<typename AppendArguments, typename ReadAnswer>
auto Call(sd_bus* bus, std::vector<std::string>& notes, std::string_view member, bool changes, AppendArguments&& append, ReadAnswer&& read) {
sd_bus_message* raw = nullptr;
ThrowOnSdBus(sd_bus_message_new_method_call(bus, &raw, busName.data(), objectPath.data(), interfaceName.data(), std::string(member).c_str()), "call nostrod");
const MessagePtr call(raw);
if(IsSensitive(member)) {
ThrowOnSdBus(sd_bus_message_sensitive(raw), "call nostrod");
}
append(raw);
Error error;
sd_bus_message* answer = nullptr;
if(sd_bus_call(bus, raw, 0, &error.error, &answer) < 0) {
Throw(error.error, changes);
}
const MessagePtr reply(answer);
auto result = read(answer);
const std::vector<std::string> more = Read<std::vector<std::string>>(answer);
notes.insert(notes.end(), more.begin(), more.end());
return result;
}
void Nothing(sd_bus_message*) {
}
// The answer of a call that answers nothing but its notes.
std::monostate NoAnswer(sd_bus_message*) {
return std::monostate();
}
AddedConnector ReadAdded(sd_bus_message* reply) {
AddedConnector added;
added.name = Read<std::string>(reply);
added.environment = Read<std::string>(reply);
added.accounts = Read<std::uint32_t>(reply);
return added;
}
Created ReadCreated(sd_bus_message* reply) {
Created created;
created.id = Read<std::uint64_t>(reply);
created.currency = Read<Currency>(reply);
return created;
}
// The arguments a payment, a draft, a schedule and a request share.
auto PaymentArguments(std::string_view account, std::string_view counterparty, std::string_view name, std::int64_t amount, std::string_view description) {
return [=](sd_bus_message* call) {
Append(call, std::string(account));
Append(call, std::string(counterparty));
Append(call, std::string(name));
Append(call, amount);
Append(call, std::string(description));
};
}
auto AccountArgument(std::string_view account) {
return [account](sd_bus_message* call) {
Append(call, std::string(account));
};
}
auto AccountAndId(std::string_view account, std::uint64_t id) {
return [account, id](sd_bus_message* call) {
Append(call, std::string(account));
Append(call, id);
};
}
template<typename T>
T ReadAs(sd_bus_message* reply) {
return Read<T>(reply);
}
}
std::vector<ConnectorSummary> Client::Connectors() {
return Call(bus.get(), notes, "Connectors", false, Nothing, ReadAs<std::vector<ConnectorSummary>>);
}
AddedConnector Client::AddBunq(std::string_view apiKey, std::string_view allowedIps, std::string_view environment) {
return Call(bus.get(), notes, "AddBunq", true, [=](sd_bus_message* call) {
Append(call, std::string(apiKey));
Append(call, std::string(allowedIps));
Append(call, std::string(environment));
}, ReadAdded);
}
AddedConnector Client::AddBunqOAuth(std::string_view environment, std::string_view clientId, std::string_view clientSecret, std::string_view redirectUri, std::string_view code) {
return Call(bus.get(), notes, "AddBunqOAuth", true, [=](sd_bus_message* call) {
Append(call, std::string(environment));
Append(call, std::string(clientId));
Append(call, std::string(clientSecret));
Append(call, std::string(redirectUri));
Append(call, std::string(code));
}, ReadAdded);
}
std::string Client::RemoveConnector(std::string_view connector) {
return Call(bus.get(), notes, "RemoveConnector", true, AccountArgument(connector), ReadAs<std::string>);
}
std::vector<ConnectorAccounts> Client::Accounts() {
return Call(bus.get(), notes, "Accounts", false, Nothing, ReadAs<std::vector<ConnectorAccounts>>);
}
std::vector<Transaction> Client::Transactions(std::string_view account, const TransactionQuery& query) {
return Call(bus.get(), notes, "Transactions", false, [account, &query](sd_bus_message* call) {
Append(call, std::string(account));
AppendQuery(call, query);
}, ReadAs<std::vector<Transaction>>);
}
Created Client::Send(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description) {
return Call(bus.get(), notes, "Send", true, PaymentArguments(account, to, name, amount, description), ReadCreated);
}
Created Client::Schedule(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description, const BunqSchedule& schedule) {
const auto payment = PaymentArguments(account, to, name, amount, description);
return Call(bus.get(), notes, "Schedule", true, [&payment, &schedule](sd_bus_message* call) {
payment(call);
Append(call, schedule);
}, ReadCreated);
}
Created Client::Draft(std::string_view account, std::string_view to, std::string_view name, std::int64_t amount, std::string_view description) {
return Call(bus.get(), notes, "Draft", true, PaymentArguments(account, to, name, amount, description), ReadCreated);
}
BunqPaymentRequest Client::Request(std::string_view account, std::string_view from, std::string_view name, std::int64_t amount, std::string_view description) {
return Call(bus.get(), notes, "Request", true, PaymentArguments(account, from, name, amount, description), ReadAs<BunqPaymentRequest>);
}
std::vector<BunqPaymentRequest> Client::Requests(std::string_view account) {
return Call(bus.get(), notes, "Requests", false, AccountArgument(account), ReadAs<std::vector<BunqPaymentRequest>>);
}
void Client::RevokeRequest(std::string_view account, std::uint64_t id) {
Call(bus.get(), notes, "RevokeRequest", true, AccountAndId(account, id), NoAnswer);
}
std::vector<BunqIncomingRequest> Client::IncomingRequests(std::string_view account) {
return Call(bus.get(), notes, "IncomingRequests", false, AccountArgument(account), ReadAs<std::vector<BunqIncomingRequest>>);
}
void Client::RespondToRequest(std::string_view account, std::uint64_t id, bool accept) {
Call(bus.get(), notes, "RespondToRequest", true, [account, id, accept](sd_bus_message* call) {
Append(call, std::string(account));
Append(call, id);
Append(call, accept);
}, NoAnswer);
}
std::vector<BunqScheduledPayment> Client::ScheduledPayments(std::string_view account) {
return Call(bus.get(), notes, "ScheduledPayments", false, AccountArgument(account), ReadAs<std::vector<BunqScheduledPayment>>);
}
void Client::CancelScheduledPayment(std::string_view account, std::uint64_t id) {
Call(bus.get(), notes, "CancelScheduledPayment", true, AccountAndId(account, id), NoAnswer);
}
std::vector<BunqDraftPayment> Client::DraftPayments(std::string_view account) {
return Call(bus.get(), notes, "DraftPayments", false, AccountArgument(account), ReadAs<std::vector<BunqDraftPayment>>);
}
void Client::RespondToDraftPayment(std::string_view account, std::uint64_t id, bool accept) {
Call(bus.get(), notes, "RespondToDraftPayment", true, [account, id, accept](sd_bus_message* call) {
Append(call, std::string(account));
Append(call, id);
Append(call, accept);
}, NoAnswer);
}
std::vector<ConnectorCards> Client::Cards() {
return Call(bus.get(), notes, "Cards", false, Nothing, ReadAs<std::vector<ConnectorCards>>);
}
BunqCard Client::SetCardStatus(std::uint64_t card, std::string_view status) {
return Call(bus.get(), notes, "SetCardStatus", true, [card, status](sd_bus_message* call) {
Append(call, card);
Append(call, std::string(status));
}, ReadAs<BunqCard>);
}
std::optional<Account> Client::DefaultCheckoutAccount() {
return Call(bus.get(), notes, "DefaultCheckoutAccount", false, Nothing, ReadAs<std::optional<Account>>);
}
Account Client::SetDefaultCheckoutAccount(std::string_view account) {
return Call(bus.get(), notes, "SetDefaultCheckoutAccount", true, AccountArgument(account), ReadAs<Account>);
}
std::vector<std::string> Client::TakeNotes() {
return std::exchange(notes, {});
}

View file

@ -1,11 +1,12 @@
//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 <cerrno>
#include <fcntl.h>
#include <sys/file.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fstream>
@ -15,31 +16,130 @@ import std;
import :Connector;
import :Banks;
import :File;
import :Utils;
using namespace Nostro;
using namespace nlohmann;
namespace fs = std::filesystem;
namespace {
[[noreturn]] void ThrowErrno(std::string_view what, const fs::path& path) {
throw std::system_error(errno, std::generic_category(), std::format("cannot {} {}", what, path.string()));
}
// One nostro process at a time works on the connectors: two that each load, change and save the file would each
// write back their own view, and the later one would drop what the other added or renewed. The lock is taken by
// the first load or save and held until the process ends.
void LockConnectors() {
static std::int32_t lock = -1;
if(lock != -1) {
return;
}
const fs::path path = configPath/"connectors.lock";
CreatePrivateFile(path);
const std::int32_t fd = open(path.c_str(), O_RDWR | O_CLOEXEC);
if(fd == -1) {
ThrowErrno("open", path);
}
// Remembered only once it is held: a failure here leaves the next call to try again, not to think it locked.
std::int32_t result = flock(fd, LOCK_EX | LOCK_NB);
if(result == -1 && errno == EWOULDBLOCK) {
Note("waiting for another nostro process to finish");
do {
result = flock(fd, LOCK_EX);
} while(result == -1 && errno == EINTR);
}
if(result == -1) {
const std::int32_t error = errno;
close(fd);
errno = error;
ThrowErrno("lock", path);
}
lock = fd;
}
void WriteAll(std::int32_t fd, std::string_view data, const fs::path& path) {
while(!data.empty()) {
const ssize_t written = write(fd, data.data(), data.size());
if(written >= 0) {
data.remove_prefix(static_cast<std::size_t>(written));
} else if(errno != EINTR) {
ThrowErrno("write", path);
}
}
}
}
void Connector::SaveConnectors() {
LockConnectors();
const fs::path path = configPath/"connectors.json";
CreatePrivateFile(path);
const fs::path temporary = configPath/std::format("connectors.json.tmp-{}", getpid());
json jsonConnectors = json::object();
tuple_for<EnabledBanks>([&jsonConnectors]<typename Bank>() {
jsonConnectors[Bank::connectorId] = Bank::connectors;
});
const std::string text = jsonConnectors.dump(4);
std::ofstream out(path, std::ios::binary);
out << jsonConnectors.dump(4);
// The file holds the only copy of each connector's private key. The new one is on the disk before it replaces the
// old one, and the rename after, so a crash or a power cut leaves one whole file or the other.
CreatePrivateFile(temporary);
const std::int32_t fd = open(temporary.c_str(), O_WRONLY | O_TRUNC | O_CLOEXEC);
if(fd == -1) {
ThrowErrno("open", temporary);
}
try {
WriteAll(fd, text, temporary);
if(fsync(fd) == -1) {
ThrowErrno("sync", temporary);
}
} catch(...) {
close(fd);
fs::remove(temporary);
throw;
}
close(fd);
fs::rename(temporary, path);
const std::int32_t directory = open(configPath.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
if(directory != -1) {
fsync(directory);
close(directory);
}
}
void Connector::LoadConnectors() {
std::ifstream f(configPath/"connectors.json");
const json jsonConnectors = json::parse(f);
tuple_for<EnabledBanks>([&jsonConnectors]<typename Bank>() {
Bank::connectors = std::move(jsonConnectors.at(Bank::connectorId).template get<std::vector<Bank>>());
for(Bank& bank : Bank::connectors) {
bank.RefreshAccounts();
LockConnectors();
const fs::path path = configPath/"connectors.json";
if(!fs::exists(path)) {
return;
}
std::ifstream f(path);
const json jsonConnectors = [&path, &f] {
try {
return json::parse(f);
} catch(const json::parse_error& e) {
// nlohmann's own message quotes the text it read last, which can be part of a private key: say where the
// file breaks, not what it holds.
throw std::runtime_error(std::format("{} is not valid JSON (it breaks at byte {})", path.string(), e.byte));
}
}();
// Every bank's list is in place before any refresh: a refresh can save, and a save writes all of them.
tuple_for<EnabledBanks>([&jsonConnectors]<typename Bank>() {
if(jsonConnectors.contains(Bank::connectorId)) {
Bank::connectors = jsonConnectors.at(Bank::connectorId).template get<std::remove_cvref_t<decltype(Bank::connectors)>>();
}
});
}
tuple_for<EnabledBanks>([]<typename Bank>() {
for(Bank& bank : Bank::connectors) {
try {
bank.RefreshAccounts();
} catch(const std::exception& e) {
Note(std::format("{} connector '{}' is unavailable: {}", Bank::connectorId, bank.name, e.what()));
}
}
});
}

View file

@ -1,5 +1,5 @@
//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;
@ -7,6 +7,7 @@ module;
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/err.h>
#include <openssl/rand.h>
module Nostro:Crypto_impl;
import :Crypto;
@ -14,7 +15,19 @@ import std;
using namespace Nostro;
long Crypto::ThrowOnOpenssl(long status) {
namespace {
std::string ReadBio(BIO* bio) {
// BIO_get_mem_data hands out its buffer through a char*.
// lint-disable-next-line no-char-pointer
char* data;
const std::int64_t len = Crypto::ThrowOnOpenssl(BIO_get_mem_data(bio, &data));
std::string out(data, len);
BIO_free(bio);
return out;
}
}
std::int64_t Crypto::ThrowOnOpenssl(std::int64_t status) {
if(status <= 0) {
ERR_print_errors_fp(stderr);
throw std::runtime_error("openssl error");
@ -22,6 +35,10 @@ long Crypto::ThrowOnOpenssl(long status) {
return status;
}
Crypto::Key Crypto::OwnKey(EVP_PKEY* key) {
return Key(key, EVP_PKEY_free);
}
std::string Crypto::SignBody(EVP_PKEY* privateKey, std::string_view body) {
EVP_MD_CTX* ctx = ThrowOnOpenssl(EVP_MD_CTX_new());
ThrowOnOpenssl(EVP_DigestSignInit(ctx, nullptr, EVP_sha256(), nullptr, privateKey));
@ -32,30 +49,49 @@ std::string Crypto::SignBody(EVP_PKEY* privateKey, std::string_view body) {
std::string sig;
sig.resize(sigLen);
ThrowOnOpenssl(EVP_DigestSignFinal(ctx, reinterpret_cast<unsigned char*>(sig.data()), &sigLen));
ThrowOnOpenssl(EVP_DigestSignFinal(ctx, reinterpret_cast<std::uint8_t*>(sig.data()), &sigLen));
sig.resize(sigLen);
std::string sig64;
sig64.resize(4 * ((sig.size() + 2) / 3));
int n = EVP_EncodeBlock(reinterpret_cast<unsigned char*>(sig64.data()), reinterpret_cast<const unsigned char*>(sig.data()), static_cast<int>(sig.size()));
const std::int32_t n = EVP_EncodeBlock(reinterpret_cast<unsigned char*>(sig64.data()), reinterpret_cast<const unsigned char*>(sig.data()), static_cast<int>(sig.size()));
sig64.resize(n);
EVP_MD_CTX_free(ctx);
return sig64;
}
bool Crypto::VerifyBody(EVP_PKEY* publicKey, std::string_view body, std::string_view signature) {
// EVP_DecodeBlock keeps the bytes the '=' padding stands for, as zeros: count the padding and drop them.
if(signature.empty() || signature.size() % 4 != 0) {
return false;
}
std::string decoded(3 * (signature.size() / 4), '\0');
const int n = EVP_DecodeBlock(reinterpret_cast<unsigned char*>(decoded.data()), reinterpret_cast<const unsigned char*>(signature.data()), static_cast<int>(signature.size()));
if(n < 0) {
return false;
}
std::size_t padding = 0;
if(signature.ends_with("==")) {
padding = 2;
} else if(signature.ends_with('=')) {
padding = 1;
}
decoded.resize(static_cast<std::size_t>(n) - padding);
EVP_MD_CTX* ctx = ThrowOnOpenssl(EVP_MD_CTX_new());
const bool valid = EVP_DigestVerifyInit(ctx, nullptr, EVP_sha256(), nullptr, publicKey) == 1
&& EVP_DigestVerifyUpdate(ctx, body.data(), body.length()) == 1
&& EVP_DigestVerifyFinal(ctx, reinterpret_cast<const unsigned char*>(decoded.data()), decoded.size()) == 1;
EVP_MD_CTX_free(ctx);
// A failed verification leaves its reason on OpenSSL's error queue; it is not an error of the next call.
ERR_clear_error();
return valid;
}
std::tuple<EVP_PKEY*, std::string> Crypto::CreateKey() {
EVP_PKEY* pkey = ThrowOnOpenssl(EVP_RSA_gen(2048));
char* data;
BIO* pubBio = ThrowOnOpenssl(BIO_new(BIO_s_mem()));
ThrowOnOpenssl(PEM_write_bio_PUBKEY(pubBio, pkey));
const long len = ThrowOnOpenssl(BIO_get_mem_data(pubBio, &data));
std::string publicKey(data, len);
BIO_free(pubBio);
return {pkey, publicKey};
return {pkey, PublicKeyToPem(pkey)};
}
EVP_PKEY* Crypto::LoadKeyFromPem(std::string_view pem) {
@ -63,4 +99,33 @@ EVP_PKEY* Crypto::LoadKeyFromPem(std::string_view pem) {
EVP_PKEY* pkey = PEM_read_bio_PrivateKey(bio, nullptr, nullptr, nullptr);
BIO_free(bio);
return ThrowOnOpenssl(pkey);
}
}
EVP_PKEY* Crypto::LoadPublicKeyFromPem(std::string_view pem) {
BIO* bio = ThrowOnOpenssl(BIO_new_mem_buf(pem.data(), static_cast<int>(pem.size())));
EVP_PKEY* pkey = PEM_read_bio_PUBKEY(bio, nullptr, nullptr, nullptr);
BIO_free(bio);
return ThrowOnOpenssl(pkey);
}
std::string Crypto::PrivateKeyToPem(EVP_PKEY* key) {
BIO* bio = ThrowOnOpenssl(BIO_new(BIO_s_mem()));
ThrowOnOpenssl(PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, nullptr, nullptr));
return ReadBio(bio);
}
std::string Crypto::PublicKeyToPem(EVP_PKEY* key) {
BIO* bio = ThrowOnOpenssl(BIO_new(BIO_s_mem()));
ThrowOnOpenssl(PEM_write_bio_PUBKEY(bio, key));
return ReadBio(bio);
}
std::string Crypto::RandomHex(std::size_t bytes) {
std::vector<unsigned char> random(bytes);
ThrowOnOpenssl(RAND_bytes(random.data(), static_cast<std::int32_t>(random.size())));
std::string out;
for(const unsigned char byte : random) {
out += std::format("{:02x}", byte);
}
return out;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,354 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include <systemd/sd-bus.h>
#include <systemd/sd-event.h>
#include <errno.h>
#include <signal.h>
#include <spawn.h>
#include <sys/socket.h>
#include <sys/wait.h>
#include <time.h>
#include <unistd.h>
module Nostro:Daemon_impl;
import std;
import Nostro.Checkout;
import :Daemon;
import :Bus;
using namespace Nostro;
using namespace Nostro::Bus;
// The front holds no connector and no secret: it only learns who calls, starts that user's worker, and passes the call
// on. Each worker is a process of its own, so one user's connectors never share a process with another's, and the
// library's process-wide state (the connector list, the paths, the lock, the open tables) belongs to one user.
namespace {
struct Front;
// One user's worker: its process, and the D-Bus connection to it over a socketpair.
struct Worker {
Front* front = nullptr;
std::uint32_t uid = 0;
pid_t pid = -1;
BusPtr bus;
// Set once the connection is gone, to free it after the dispatch that noticed.
sd_event_source* reap = nullptr;
Worker() = default;
Worker(const Worker&) = delete;
Worker& operator=(const Worker&) = delete;
~Worker() {
sd_event_source_unref(reap);
}
};
struct Front {
DaemonOptions options;
sd_event* event = nullptr;
// Before the connections, so the connection each is registered with goes first however RunDaemon ends.
std::vector<sd_bus_vtable> vtable;
std::vector<sd_bus_vtable> checkoutVtable;
BusPtr bus;
// Checkout::busName, with net.catcrafts.Nostro1.Checkout alone, on a connection of its own: an app allowed to
// talk to that name and no other (a Flatpak's --system-talk-name) may call its owner's unique name too, and this
// one serves nothing else.
BusPtr checkout;
std::map<std::uint32_t, std::unique_ptr<Worker>> workers;
std::size_t inFlight = 0;
sd_event_source* idle = nullptr;
};
// A call handed to a worker, waiting for its answer.
struct Forwarded {
Front* front = nullptr;
MessagePtr call;
};
// Refused before any worker sees the call: a caller the bus cannot name, or a uid without a login session.
struct Refused : std::runtime_error {
using std::runtime_error::runtime_error;
};
std::uint64_t Microseconds(std::chrono::seconds duration) {
return static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(duration).count());
}
void Touch(Front& front) {
sd_event_source_set_time_relative(front.idle, Microseconds(front.options.idle));
sd_event_source_set_enabled(front.idle, SD_EVENT_ONESHOT);
}
// Once idle with no call under way and no worker left, the front ends; D-Bus activation starts it again.
std::int32_t OnIdle(sd_event_source*, std::uint64_t, void* userdata) {
Front& front = *static_cast<Front*>(userdata);
if(front.inFlight == 0 && front.workers.empty()) {
return sd_event_exit(front.event, 0);
}
Touch(front);
return 0;
}
std::int32_t OnBusGone(sd_bus_message*, void* userdata, sd_bus_error*) {
sd_event_exit(static_cast<Front*>(userdata)->event, 0);
return 0;
}
// Calls a method of a service on the system bus and returns its answer, or throws with what it said.
template<typename... Args>
MessagePtr CallSystem(sd_bus* bus, std::string_view destination, std::string_view path, std::string_view interface, std::string_view member, std::string_view types, Args... args) {
Error error;
sd_bus_message* reply = nullptr;
const std::int32_t result = sd_bus_call_method(bus, destination.data(), path.data(), interface.data(), member.data(), &error.error, &reply, types.data(), args...);
if(result < 0) {
throw std::runtime_error(std::format("{} {}: {}", destination, member, ErrorMessage(error.error)));
}
return MessagePtr(reply);
}
// The uid behind a connection, as the bus knows it. Asked of the bus itself rather than worked out by sd-bus, which
// behaves the same on every bus implementation.
std::uint32_t CallerUid(sd_bus* bus, const std::string& sender) {
const MessagePtr reply = CallSystem(bus, "org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetConnectionCredentials", "s", sender.c_str());
std::optional<std::uint32_t> uid;
Enter(reply.get(), 'a', "{sv}");
while(ThrowOnSdBus(sd_bus_message_at_end(reply.get(), 0), "read the caller's credentials") == 0) {
Enter(reply.get(), 'e', "sv");
if(Read<std::string>(reply.get()) == "UnixUserID") {
Enter(reply.get(), 'v', "u");
uid = Read<std::uint32_t>(reply.get());
Leave(reply.get());
} else {
ThrowOnSdBus(sd_bus_message_skip(reply.get(), "v"), "read the caller's credentials");
}
Leave(reply.get());
}
Leave(reply.get());
if(!uid) {
throw Refused(std::format("the bus did not say which user {} is", sender));
}
return *uid;
}
// The user name logind has for `uid`: the worker keeps it beside the user's files, so a uid handed to a new user
// after the old one was deleted does not open the old one's connectors. A uid logind does not know is refused.
std::string LogindName(sd_bus* bus, std::uint32_t uid) {
std::string path;
try {
const MessagePtr user = CallSystem(bus, "org.freedesktop.login1", "/org/freedesktop/login1", "org.freedesktop.login1.Manager", "GetUser", "u", uid);
path = ReadText(user.get(), 'o');
} catch(const std::runtime_error& e) {
throw Refused(std::format("nostrod serves users with a login session, and logind knows no user {} ({})", uid, e.what()));
}
const MessagePtr name = CallSystem(bus, "org.freedesktop.login1", path, "org.freedesktop.DBus.Properties", "Get", "ss", "org.freedesktop.login1.User", "Name");
Enter(name.get(), 'v', "s");
std::string text = Read<std::string>(name.get());
Leave(name.get());
return text;
}
std::int32_t OnReap(sd_event_source*, void* userdata) {
Worker& worker = *static_cast<Worker*>(userdata);
Front& front = *worker.front;
waitpid(worker.pid, nullptr, 0);
front.workers.erase(worker.uid);
Touch(front);
return 0;
}
// A worker's connection ended: it went idle, or it died. Every call it still had was failed by sd-bus before this
// signal, so all that is left is to reap the process, which cannot happen inside the connection's own dispatch.
// (sd-bus callbacks return 0 whatever happens: a negative result from one closes the connection it came on.)
std::int32_t OnWorkerGone(sd_bus_message*, void* userdata, sd_bus_error*) {
Worker& worker = *static_cast<Worker*>(userdata);
if(sd_event_add_defer(worker.front->event, &worker.reap, OnReap, &worker) >= 0) {
sd_event_source_set_enabled(worker.reap, SD_EVENT_ONESHOT);
}
return 0;
}
// A socket that closes itself.
struct Descriptor {
std::int32_t fd = -1;
Descriptor() = default;
Descriptor(const Descriptor&) = delete;
Descriptor& operator=(const Descriptor&) = delete;
~Descriptor() {
if(fd != -1) {
close(fd);
}
}
};
// Starts `uid`'s worker: this executable again, as `nostrod --worker`, with its end of a socketpair as fd 3.
// posix_spawn rather than fork and exec: nothing of this process runs in the child before the exec.
std::unique_ptr<Worker> Spawn(Front& front, std::uint32_t uid, const std::string& name) {
std::array<std::int32_t, 2> ends{};
if(socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, ends.data()) == -1) {
throw std::system_error(errno, std::generic_category(), "cannot make a socket for a worker");
}
Descriptor ours;
ours.fd = ends[0];
Descriptor theirs;
theirs.fd = ends[1];
std::vector<std::string> args = {"nostrod", "--worker", std::to_string(uid), name, "--state", front.options.state.string(), "--idle", std::to_string(front.options.idle.count()), "--prompt-timeout", std::to_string(front.options.promptTimeout.count())};
// posix_spawn takes C strings.
// lint-disable-next-line no-char-pointer
std::vector<char*> argv;
for(std::string& arg : args) {
argv.push_back(arg.data());
}
argv.push_back(nullptr);
posix_spawn_file_actions_t actions;
posix_spawn_file_actions_init(&actions);
// Duplicated onto fd 3 without close-on-exec; POSIX clears the flag even when the socket already is fd 3.
posix_spawn_file_actions_adddup2(&actions, theirs.fd, 3);
pid_t pid = -1;
const std::int32_t spawned = posix_spawn(&pid, "/proc/self/exe", &actions, nullptr, argv.data(), environ);
posix_spawn_file_actions_destroy(&actions);
if(spawned != 0) {
throw std::system_error(spawned, std::generic_category(), "cannot start a worker");
}
std::unique_ptr<Worker> worker = std::make_unique<Worker>();
worker->front = &front;
worker->uid = uid;
worker->pid = pid;
sd_bus* bus = nullptr;
ThrowOnSdBus(sd_bus_new(&bus), "connect to a worker");
worker->bus.reset(bus);
ThrowOnSdBus(sd_bus_set_fd(bus, ours.fd, ours.fd), "connect to a worker");
// The connection owns the socket now.
ours.fd = -1;
ThrowOnSdBus(sd_bus_set_description(bus, std::format("worker for uid {}", uid).c_str()), "connect to a worker");
ThrowOnSdBus(sd_bus_start(bus), "connect to a worker");
ThrowOnSdBus(sd_bus_match_signal(bus, nullptr, "org.freedesktop.DBus.Local", "/org/freedesktop/DBus/Local", "org.freedesktop.DBus.Local", "Disconnected", OnWorkerGone, worker.get()), "watch a worker");
ThrowOnSdBus(sd_bus_attach_event(bus, front.event, SD_EVENT_PRIORITY_NORMAL), "connect to a worker");
return worker;
}
Worker& WorkerFor(Front& front, std::uint32_t uid) {
if(const auto existing = front.workers.find(uid); existing != front.workers.end()) {
return *existing->second;
}
const std::string name = LogindName(front.bus.get(), uid);
return *front.workers.emplace(uid, Spawn(front, uid, name)).first->second;
}
// The call as the worker gets it: the same method and arguments, from the caller's unique name, which is what the
// worker asks polkit about, and allowing a password prompt only when the caller did.
MessagePtr Copy(sd_bus* to, sd_bus_message* call, const std::string& sender) {
sd_bus_message* copy = nullptr;
ThrowOnSdBus(sd_bus_message_new_method_call(to, &copy, nullptr, sd_bus_message_get_path(call), sd_bus_message_get_interface(call), sd_bus_message_get_member(call)), "pass a call on");
MessagePtr owned(copy);
if(IsSensitive(Member(call))) {
ThrowOnSdBus(sd_bus_message_sensitive(copy), "pass a call on");
}
ThrowOnSdBus(sd_bus_message_rewind(call, 1), "pass a call on");
ThrowOnSdBus(sd_bus_message_copy(copy, call, 1), "pass a call on");
ThrowOnSdBus(sd_bus_message_set_sender(copy, sender.c_str()), "pass a call on");
ThrowOnSdBus(sd_bus_message_set_allow_interactive_authorization(copy, sd_bus_message_get_allow_interactive_authorization(call)), "pass a call on");
return owned;
}
// The worker's answer, as the answer to the caller.
std::int32_t OnWorkerReply(sd_bus_message* reply, void* userdata, sd_bus_error*) {
const std::unique_ptr<Forwarded> forwarded(static_cast<Forwarded*>(userdata));
Front& front = *forwarded->front;
front.inFlight--;
Touch(front);
sd_bus_message* call = forwarded->call.get();
if(sd_bus_message_is_method_error(reply, nullptr)) {
const sd_bus_error* error = sd_bus_message_get_error(reply);
// sd-bus fails a call whose worker went away, or did not answer in time, with errors of its own.
if(sd_bus_error_has_names(error, SD_BUS_ERROR_NO_REPLY, SD_BUS_ERROR_TIMEOUT, SD_BUS_ERROR_DISCONNECTED)) {
sd_bus_reply_method_errorf(call, errorFailed.data(), "nostrod's worker for you stopped before it answered (%s): what you asked for may have been carried out, check before trying again", ErrorMessage(*error).c_str());
} else {
sd_bus_reply_method_error(call, error);
}
return 0;
}
// These fail only when memory runs out; the caller's own timeout then answers for them.
sd_bus_message* answer = nullptr;
sd_bus_message_new_method_return(call, &answer);
const MessagePtr owned(answer);
sd_bus_message_rewind(reply, 1);
sd_bus_message_copy(answer, reply, 1);
sd_bus_send(nullptr, answer, nullptr);
return 0;
}
// Every method of the interface: passed on to the caller's worker, whose answer is relayed when it comes, so a
// password prompt one user leaves open holds up nobody else.
std::int32_t Forward(sd_bus_message* call, void* userdata, sd_bus_error* error) {
Front& front = *static_cast<Front*>(userdata);
Touch(front);
try {
const std::string sender = Sender(call);
Worker& worker = WorkerFor(front, CallerUid(sd_bus_message_get_bus(call), sender));
const MessagePtr copy = Copy(worker.bus.get(), call, sender);
std::unique_ptr<Forwarded> forwarded = std::make_unique<Forwarded>(&front, MessagePtr(sd_bus_message_ref(call)));
// Long enough for the prompt and then the bank, which waits out its rate limits.
ThrowOnSdBus(sd_bus_call_async(worker.bus.get(), nullptr, copy.get(), OnWorkerReply, forwarded.get(), Microseconds(front.options.promptTimeout + std::chrono::minutes(10))), "pass a call on");
// OnWorkerReply owns it now.
forwarded.release();
front.inFlight++;
return 1;
} catch(const Refused& e) {
return sd_bus_error_set(error, SD_BUS_ERROR_ACCESS_DENIED, e.what());
} catch(const std::exception& e) {
return sd_bus_error_set(error, errorFailed.data(), e.what());
}
}
// A system bus connection that serves `interface` under `name`, every method passed on by Forward, and ends the
// loop when the bus goes.
BusPtr Serve(Front& front, std::string_view description, std::string_view name, std::string_view interface, std::vector<sd_bus_vtable>& vtable) {
sd_bus* bus = nullptr;
ThrowOnSdBus(sd_bus_open_system_with_description(&bus, description.data()), "connect to the system bus");
BusPtr owned(bus);
ThrowOnSdBus(sd_bus_add_object_vtable(bus, nullptr, objectPath.data(), interface.data(), vtable.data(), &front), std::format("serve {}", interface));
ThrowOnSdBus(sd_bus_match_signal(bus, nullptr, "org.freedesktop.DBus.Local", "/org/freedesktop/DBus/Local", "org.freedesktop.DBus.Local", "Disconnected", OnBusGone, &front), "watch the system bus");
ThrowOnSdBus(sd_bus_request_name(bus, name.data(), 0), std::format("own {}", name));
ThrowOnSdBus(sd_bus_attach_event(bus, front.event, SD_EVENT_PRIORITY_NORMAL), std::format("serve {}", interface));
return owned;
}
}
std::int32_t Nostro::RunDaemon(const DaemonOptions& options) {
Front front;
front.options = options;
ThrowOnSdBus(sd_event_new(&front.event), "make an event loop");
// systemd stops the service with SIGTERM: the loop ends then, and everything is closed and flushed on the way out.
sigset_t terminate{};
sigemptyset(&terminate);
sigaddset(&terminate, SIGTERM);
sigprocmask(SIG_BLOCK, &terminate, nullptr);
ThrowOnSdBus(sd_event_add_signal(front.event, nullptr, SIGTERM, nullptr, nullptr), "watch for SIGTERM");
front.vtable = Vtable(methods, [](std::string_view) { return &Forward; });
front.checkoutVtable = Vtable(checkoutMethods, [](std::string_view) { return &Forward; });
// The main name last: systemd counts the service as started once it is owned, and by then both are.
front.checkout = Serve(front, "nostrod checkout", Checkout::busName, Checkout::interfaceName, front.checkoutVtable);
front.bus = Serve(front, "nostrod", busName, interfaceName, front.vtable);
ThrowOnSdBus(sd_event_add_time_relative(front.event, &front.idle, CLOCK_MONOTONIC, Microseconds(options.idle), 0, OnIdle, &front), "set the idle timer");
const std::int32_t result = sd_event_loop(front.event);
// Closing a worker's connection ends it; wait for each, so none outlives the front.
for(auto& [uid, worker] : front.workers) {
worker->bus.reset();
waitpid(worker->pid, nullptr, 0);
}
front.workers.clear();
front.bus.reset();
front.checkout.reset();
sd_event_source_unref(front.idle);
sd_event_unref(front.event);
ThrowOnSdBus(result, "run the event loop");
return 0;
}

View file

@ -1,10 +1,12 @@
//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 <cerrno>
#include <errno.h>
#include <sys/stat.h>
#include <termios.h>
#include <unistd.h>
module Nostro:File_impl;
import :File;
@ -13,31 +15,33 @@ import std;
using namespace Nostro;
namespace fs = std::filesystem;
namespace {
// An environment variable as a path, or nothing when it is not set.
std::optional<fs::path> Environment(const std::string& name) {
// getenv answers with a char*, null when the variable is not set.
// lint-disable-next-line no-char-pointer
const char* const value = std::getenv(name.c_str());
return value ? std::optional<fs::path>(value) : std::nullopt;
}
}
fs::path Nostro::GetConfigPath() {
const char* const xdg = std::getenv("XDG_CONFIG_HOME");
if(xdg) {
return fs::path(fs::path(std::move(xdg)) / ".config/nostro");
if(const std::optional<fs::path> xdg = Environment("XDG_CONFIG_HOME")) {
return *xdg / ".config/nostro";
}
const char* const home = std::getenv("HOME");
if(home) {
return fs::path(fs::path(std::move(home)) / ".config/nostro");
if(const std::optional<fs::path> home = Environment("HOME")) {
return *home / ".config/nostro";
}
throw std::runtime_error("XDG_CONFIG_HOME and HOME not set");
}
fs::path Nostro::GetCachePath() {
const char* const xdg = std::getenv("XDG_CACHE_HOME");
if(xdg) {
return fs::path(fs::path(std::move(xdg)) / "nostro");
if(const std::optional<fs::path> xdg = Environment("XDG_CACHE_HOME")) {
return *xdg / "nostro";
}
const char* const home = std::getenv("HOME");
if(home) {
return fs::path(fs::path(std::move(home)) / ".cache/nostro");
if(const std::optional<fs::path> home = Environment("HOME")) {
return *home / ".cache/nostro";
}
throw std::runtime_error("XDG_CACHE_HOME and HOME not set");
}
@ -60,22 +64,28 @@ void Nostro::CreatePrivateFile(const fs::path& path) {
}
}
void Nostro::WriteString(std::ofstream& file, std::string_view str) {
std::uint16_t size = str.size();
file.write(reinterpret_cast<char*>(&size), sizeof(size));
file.write(str.data(), size);
}
std::string Nostro::ReadSecret(std::string_view prompt) {
const bool terminal = isatty(STDIN_FILENO) == 1;
termios shown{};
if(terminal) {
std::print(std::cerr, "{}", prompt);
tcgetattr(STDIN_FILENO, &shown);
termios hidden = shown;
hidden.c_lflag &= ~static_cast<tcflag_t>(ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &hidden);
}
void Nostro::ReadString(std::ifstream& file, std::string& str) {
std::uint16_t size;
file.read(reinterpret_cast<char*>(&size), sizeof(size));
str.resize(size);
file.read(str.data(), size);
}
std::string line;
const bool read = static_cast<bool>(std::getline(std::cin, line));
if(terminal) {
tcsetattr(STDIN_FILENO, TCSANOW, &shown);
std::println(std::cerr);
}
if(!read) {
throw std::runtime_error(std::format("nothing given for '{}'", prompt));
}
std::uint16_t Nostro::SeekString(std::ifstream& file) {
std::uint16_t size;
file.read(reinterpret_cast<char*>(&size), sizeof(size));
file.seekg(size, std::ios::cur);
return size;
}
const std::size_t first = line.find_first_not_of(" \t\r");
const std::size_t last = line.find_last_not_of(" \t\r");
return first == std::string::npos ? std::string() : line.substr(first, last - first + 1);
}

View file

@ -1,13 +0,0 @@
//SPDX-License-Identifier: LGPL-3.0-only
//SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module Nostro:Transaction_impl;
import :Transaction;
import std;
using namespace Nostro;
namespace fs = std::filesystem;
Transaction::Transaction(std::string&& name, std::string&& bic, std::string&& iban, std::string&& description, Currency currency, std::int64_t amount, std::chrono::system_clock::time_point timePoint): name(std::move(name)), bic(std::move(bic)), iban(std::move(iban)), description(std::move(description)), currency(currency), amount(amount), timePoint(timePoint) {
}

View file

@ -0,0 +1,121 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
module;
#include <systemd/sd-bus.h>
#include <errno.h>
module Nostro.Checkout;
import std;
using namespace Nostro;
Checkout::Error::Error(std::string name, const std::string& message) : std::runtime_error(message), name(std::move(name)) {
}
namespace {
// What sd-bus hands out, freed at the end of the scope.
struct Connection {
sd_bus* bus = nullptr;
Connection() = default;
Connection(const Connection&) = delete;
Connection& operator=(const Connection&) = delete;
~Connection() {
sd_bus_flush_close_unref(bus);
}
};
struct Message {
sd_bus_message* message = nullptr;
Message() = default;
Message(const Message&) = delete;
Message& operator=(const Message&) = delete;
~Message() {
sd_bus_message_unref(message);
}
};
struct BusError {
sd_bus_error error = SD_BUS_ERROR_NULL;
BusError() = default;
BusError(const BusError&) = delete;
BusError& operator=(const BusError&) = delete;
~BusError() {
sd_bus_error_free(&error);
}
};
// Throws a std::system_error naming `what` when an sd-bus call returned a negative errno; returns the result.
std::int32_t ThrowOn(std::int32_t result, std::string_view what) {
if(result < 0) {
throw std::system_error(-result, std::generic_category(), std::format("cannot {}", what));
}
return result;
}
// sd-bus hands strings out as C strings, the ones of an error possibly none.
// lint-disable-next-line no-char-pointer
std::string Text(const char* text) {
return text ? std::string(text) : std::string();
}
std::string ReadString(sd_bus_message* message) {
// lint-disable-next-line no-char-pointer
const char* text = nullptr;
ThrowOn(sd_bus_message_read_basic(message, 's', &text), "read nostrod's answer");
return Text(text);
}
}
Checkout::Paid Checkout::Pay(const Order& order, std::chrono::seconds timeout) {
Connection connection;
ThrowOn(sd_bus_open_system_with_description(&connection.bus, "nostro checkout"), "connect to the system bus");
// The user confirms the order at a password prompt.
ThrowOn(sd_bus_set_allow_interactive_authorization(connection.bus, 1), "connect to the system bus");
Message call;
ThrowOn(sd_bus_message_new_method_call(connection.bus, &call.message, busName.data(), objectPath.data(), interfaceName.data(), "Pay"), "call nostrod");
// No options yet; a nostrod skips the ones it does not know, so adding one breaks no older nostrod.
const std::int32_t appended = sd_bus_message_append(call.message, "ssxssa{sv}", order.payeeIban.c_str(), order.payeeName.c_str(), order.amount, order.currency.c_str(), order.reference.c_str(), 0u);
if(appended == -EINVAL) {
throw std::invalid_argument("text that is not UTF-8 cannot be sent to nostrod");
}
ThrowOn(appended, "call nostrod");
BusError error;
Message reply;
if(sd_bus_call(connection.bus, call.message, static_cast<std::uint64_t>(std::chrono::duration_cast<std::chrono::microseconds>(timeout).count()), &error.error, &reply.message) < 0) {
std::string name = Text(error.error.name);
const std::string message = Text(error.error.message);
if(name == errorCancelled) {
throw Cancelled(std::move(name), message);
}
if(name == errorNoCheckoutAccount) {
throw NoCheckoutAccount(std::move(name), message);
}
if(name == SD_BUS_ERROR_SERVICE_UNKNOWN) {
throw Error(std::move(name), std::format("nostro is not installed, or the system bus cannot start it ({})", message));
}
if(name == SD_BUS_ERROR_NO_REPLY || name == SD_BUS_ERROR_TIMEOUT) {
throw Error(std::move(name), std::format("nostrod did not answer in time ({}): the order may have been paid, and paying the same order again answers with its payment rather than paying twice", message));
}
throw Error(std::move(name), message);
}
Paid paid;
ThrowOn(sd_bus_message_read_basic(reply.message, 't', &paid.paymentId), "read nostrod's answer");
// The results: a later nostrod may add to them, and what this one does not know it skips.
ThrowOn(sd_bus_message_enter_container(reply.message, 'a', "{sv}"), "read nostrod's answer");
while(ThrowOn(sd_bus_message_enter_container(reply.message, 'e', "sv"), "read nostrod's answer") > 0) {
if(ReadString(reply.message) == "repeated") {
std::int32_t repeated = 0;
ThrowOn(sd_bus_message_read(reply.message, "v", "b", &repeated), "read nostrod's answer");
paid.repeated = repeated != 0;
} else {
ThrowOn(sd_bus_message_skip(reply.message, "v"), "read nostrod's answer");
}
ThrowOn(sd_bus_message_exit_container(reply.message), "read nostrod's answer");
}
ThrowOn(sd_bus_message_exit_container(reply.message), "read nostrod's answer");
return paid;
}

View file

@ -1,125 +1,388 @@
//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®
import std;
import Nostro;
using namespace Nostro;
int main(int argc, char *argv[]) {
if(argc < 2) {
std::println("no command provided");
return -1;
}
namespace {
constexpr std::string_view usage = R"(usage:
nostro connectors list connectors and whether they work
nostro connectors add bunq [allowed ips] [--sandbox] asks for the API key; ips default to *
nostro connectors add bunq-oauth <client id> <redirect uri> [--sandbox] asks for the client secret
nostro connectors remove <name or number> log out and forget a connector and its stored transactions
nostro accounts
nostro transactions <account> [--search text] [--amount n] [--from date] [--to date] [--limit n]
nostro send <account> <to> <name> <amount> [description]
nostro request <account> <from> <name> <amount> [description]
nostro requests <account> [revoke <id>] requests for money you sent
nostro incoming <account> [accept|reject <id>] requests for money you received
nostro schedule <account> <to> <name> <amount> <start date> <once|daily|weekly|monthly|yearly> [description] [--every n] [--until date]
nostro scheduled <account> [cancel <id>]
nostro draft <account> <to> <name> <amount> [description]
nostro drafts <account> [accept|reject <id>]
nostro cards [freeze|unfreeze|lost|stolen <card id>]
nostro checkout account [<account>] the account apps may ask you to pay from at checkout
Connector::LoadConnectors();
<account> is an account's name or IBAN. <to> and <from> are an IBAN, an e-mail address, or a phone number
starting with +. Amounts are in the smallest unit of the account's currency: 1250 is 12.50. Dates are
YYYY-MM-DD or "YYYY-MM-DD hh:mm", in local time. A sandbox API key is recognised by its prefix.
nostrod does the work, and asks for your password before anything that moves money, a checkout included.)";
std::string_view cmd = argv[1];
// Positional arguments, with "--name value" options (and the "--sandbox" and "--help" flags) taken out wherever they are.
struct Arguments {
std::vector<std::string_view> positional;
std::map<std::string_view, std::string_view, std::less<>> options;
bool sandbox = false;
if(cmd == "connectors") {
if(argc > 2) {
cmd = argv[2];
if(cmd == "add") {
if(argc > 3) {
cmd = argv[3];
if(cmd == "bunq") {
if(argc > 4) {
cmd = argv[4];
std::string ip;
if(argc > 5) {
ip = argv[5];
} else {
ip = "*";
}
BunqConnector::Create(std::string(cmd), std::move(ip));
} else {
std::println("api key not provided");
}
} else {
std::println("unknown connector type");
explicit Arguments(std::span<const std::string_view> args) {
for(std::size_t i = 0; i < args.size(); i++) {
const std::string_view arg = args[i];
if(arg == "--sandbox") {
sandbox = true;
} else if(arg == "--help") {
positional.push_back("help");
} else if(arg.starts_with("--") && arg.size() > 2) {
if(i + 1 >= args.size()) {
throw std::invalid_argument(std::format("{} needs a value", arg));
}
options[arg] = args[++i];
} else {
std::println("connector type not provided");
}
} else {
std::println("unknown command");
}
} else {
std::string out;
tuple_for<EnabledBanks>([&out]<typename Bank>() {
for(Bank& bank : Bank::connectors) {
out += std::format("{}\t{}\t{}\n", bank, Bank::connectorId, bank.TestConnector());
}
});
if(out.size()) {
out.pop_back();
}
std::println("{}", out);
}
} else if(cmd == "accounts") {
std::string out;
tuple_for<EnabledBanks>([&out]<typename Bank>() {
for(Bank& bank : Bank::connectors) {
out += std::format("{}\t{}\n", bank, Bank::connectorId);
for(typename Bank::Account& account : bank.accounts) {
out += std::format("\t{}\n", account);
positional.push_back(arg);
}
}
});
if(out.size()) {
out.pop_back();
}
std::println("{}", out);
} else if(cmd == "send") {
if(argc > 2) {
std::string_view accountName = argv[2];
bool notFound = true;
tuple_for<EnabledBanks>([argc, argv, accountName, &notFound]<typename Bank>() {
for(Bank& bank : Bank::connectors) {
for(typename Bank::Account& account : bank.accounts) {
if(account.name == accountName) {
notFound = false;
if(argc > 3) {
std::string_view iban = argv[3];
if(argc > 4) {
std::string_view name = argv[4];
if(argc > 5) {
std::int64_t amount = std::stoll(argv[5]);
if(argc > 6) {
account.Send(iban, name, amount, account.currency, argv[6]);
} else {
account.Send(iban, name, amount, account.currency, "");
}
} else {
std::println("amount not provided");
}
} else {
std::println("recipient name not provided");
}
} else {
std::println("iban not provided");
}
return;
}
}
}
});
if(notFound) {
std::println("account not found");
return -1;
std::string_view At(std::size_t index, std::string_view what) const {
if(index >= positional.size()) {
throw std::invalid_argument(std::format("{} not provided", what));
}
} else {
std::println("account name not provided");
return -1;
return positional[index];
}
} else {
std::println("unknown command");
return -1;
std::string_view Or(std::size_t index, std::string_view fallback) const {
return index < positional.size() ? positional[index] : fallback;
}
std::optional<std::string_view> Option(std::string_view name) const {
const auto it = options.find(name);
return it == options.end() ? std::nullopt : std::optional<std::string_view>(it->second);
}
};
template<typename T>
T ParseNumber(std::string_view text, std::string_view what) {
T value{};
const std::from_chars_result result = std::from_chars(text.data(), text.data() + text.size(), value);
if(result.ec != std::errc() || result.ptr != text.data() + text.size()) {
throw std::invalid_argument(std::format("{} '{}' is not a whole number", what, text));
}
return value;
}
}
// Amounts are whole numbers of the currency's minor unit; "12.50" is refused rather than guessed at.
std::int64_t ParseAmountArgument(std::string_view text) {
if(text.contains('.') || text.contains(',')) {
throw std::invalid_argument(std::format("amount '{}': give it in the smallest unit, 1250 for 12.50", text));
}
return ParseNumber<std::int64_t>(text, "amount");
}
// The end of the day for a date without a time, so "--to 2026-10-31" includes that day.
std::chrono::system_clock::time_point ParseEnd(std::string_view text) {
return text.size() == 10 ? ParseLocalDate(text, 1) - std::chrono::microseconds(1) : ParseLocalDate(text);
}
// The arguments a payment, a draft, a schedule and a request share, read in order so a missing one is named the
// same way every time.
struct Payment {
std::string_view account;
std::string_view counterparty;
std::string_view name;
std::int64_t amount = 0;
std::string_view description;
Payment(const Arguments& args, std::string_view counterpartyIs, std::string_view nameIs, std::size_t descriptionAt) {
account = args.At(1, "account");
counterparty = args.At(2, counterpartyIs);
name = args.At(3, nameIs);
amount = ParseAmountArgument(args.At(4, "amount"));
description = args.Or(descriptionAt, "");
}
};
void ListConnectors(Client& client) {
std::size_t number = 1;
for(const ConnectorSummary& connector : client.Connectors()) {
std::println("{}\t{}\t{}\t{}\t{}\t{}", number++, connector.name, connector.bank, connector.environment, connector.auth, connector.working ? "ok" : "failing");
}
}
void AddBunq(Client& client, const Arguments& args) {
// Read at a prompt, or from stdin, never from the command line: every local user can read a process's
// arguments, and polkit writes them to the journal.
const std::string key = ReadSecret("bunq API key: ");
const AddedConnector added = client.AddBunq(key, args.Or(3, "*"), args.sandbox ? "sandbox" : "");
std::println("added {} ({}, {} accounts)", added.name, added.environment, added.accounts);
}
void AddBunqOAuth(Client& client, const Arguments& args) {
const std::string_view clientId = args.At(3, "client id");
const std::string_view redirectUri = args.At(4, "redirect uri");
const BunqEnvironment environment = args.sandbox ? BunqEnvironment::Sandbox : BunqEnvironment::Production;
const std::string clientSecret = ReadSecret("OAuth client secret: ");
// `state` ties the redirect to this request: a code from anyone else's authorization is refused.
const std::string state = Crypto::RandomHex(16);
std::println("Open this address and approve the connection with the bunq app:\n\n{}\n", BunqConnector::OAuthAuthorizationUrl(environment, clientId, redirectUri, state));
std::println("Then paste the address your browser was sent to:");
std::string redirected;
if(!std::getline(std::cin, redirected)) {
throw std::runtime_error("no address given");
}
if(const std::optional<std::string> error = QueryParameter(redirected, "error")) {
throw std::runtime_error(std::format("bunq did not authorize: {} {}", *error, QueryParameter(redirected, "error_description").value_or("")));
}
const std::optional<std::string> code = QueryParameter(redirected, "code");
if(!code || code->empty()) {
throw std::runtime_error("that address has no code= in it");
}
if(QueryParameter(redirected, "state") != state) {
throw std::runtime_error("that address is not the answer to this authorization (its state differs): start again");
}
// nostrod exchanges the code for its token and keeps it; the token never comes here.
const AddedConnector added = client.AddBunqOAuth(args.sandbox ? "sandbox" : "production", clientId, clientSecret, redirectUri, *code);
std::println("added {} through OAuth ({}, {} accounts)", added.name, added.environment, added.accounts);
}
void Connectors(Client& client, const Arguments& args) {
const std::string_view verb = args.Or(1, "");
if(verb.empty()) {
ListConnectors(client);
} else if(verb == "add") {
const std::string_view type = args.At(2, "connector type");
if(type == "bunq") {
AddBunq(client, args);
} else if(type == "bunq-oauth") {
AddBunqOAuth(client, args);
} else {
throw std::invalid_argument(std::format("unknown connector type '{}'", type));
}
} else if(verb == "remove") {
std::println("removed {}", client.RemoveConnector(args.At(2, "connector name")));
} else {
throw std::invalid_argument(std::format("unknown connectors command '{}'", verb));
}
}
void ListAccounts(Client& client, const Arguments&) {
for(const ConnectorAccounts& connector : client.Accounts()) {
std::println("{}\t{}", connector.name, connector.bank);
for(const Account& account : connector.accounts) {
std::println("\t{}", account);
}
}
}
void ListTransactions(Client& client, const Arguments& args) {
TransactionQuery query;
query.search = args.Option("--search").value_or("");
if(const std::optional<std::string_view> amount = args.Option("--amount")) {
query.amount = ParseNumber<std::int64_t>(*amount, "amount");
}
if(const std::optional<std::string_view> from = args.Option("--from")) {
query.from = ParseLocalDate(*from);
}
if(const std::optional<std::string_view> to = args.Option("--to")) {
query.to = ParseEnd(*to);
}
if(const std::optional<std::string_view> limit = args.Option("--limit")) {
query.limit = ParseNumber<std::size_t>(*limit, "limit");
}
for(const Transaction& transaction : client.Transactions(args.At(1, "account"), query)) {
std::println("{}", transaction);
}
}
void Send(Client& client, const Arguments& args) {
const Payment payment(args, "recipient", "recipient name", 5);
try {
const Created sent = client.Send(payment.account, payment.counterparty, payment.name, payment.amount, payment.description);
std::println("sent {} to {} (payment {})", FormatMoney(payment.amount, sent.currency), payment.name, sent.id);
} catch(const DaemonError& e) {
// bunq lets an OAuth connection pay between the user's own accounts only.
if(e.name == Bus::errorOAuthCannotPay) {
throw std::runtime_error(std::format("{}\nThis connector was added through OAuth, which can only pay your own accounts: `nostro draft` makes a payment to approve in the bunq app.", e.what()));
}
throw;
}
}
void Request(Client& client, const Arguments& args) {
const Payment payment(args, "who to ask", "their name", 5);
std::println("{}", client.Request(payment.account, payment.counterparty, payment.name, payment.amount, payment.description));
}
void Requests(Client& client, const Arguments& args) {
const std::string_view account = args.At(1, "account");
if(args.Or(2, "") == "revoke") {
client.RevokeRequest(account, ParseNumber<std::uint64_t>(args.At(3, "request id"), "request id"));
std::println("revoked request {}", args.At(3, ""));
return;
}
for(const BunqPaymentRequest& request : client.Requests(account)) {
std::println("{}", request);
}
}
void Incoming(Client& client, const Arguments& args) {
const std::string_view account = args.At(1, "account");
const std::string_view verb = args.Or(2, "");
if(verb == "accept" || verb == "reject") {
client.RespondToRequest(account, ParseNumber<std::uint64_t>(args.At(3, "request id"), "request id"), verb == "accept");
std::println("{} request {}", verb == "accept" ? "paid" : "rejected", args.At(3, ""));
return;
}
for(const BunqIncomingRequest& request : client.IncomingRequests(account)) {
std::println("{}", request);
}
}
void Schedule(Client& client, const Arguments& args) {
const Payment payment(args, "recipient", "recipient name", 7);
BunqSchedule schedule;
schedule.start = ParseLocalDate(args.At(5, "start date"));
schedule.unit = std::string(args.At(6, "recurrence"));
std::ranges::transform(schedule.unit, schedule.unit.begin(), [](char c) { return static_cast<char>(std::toupper(static_cast<std::uint8_t>(c))); });
if(const std::optional<std::string_view> every = args.Option("--every")) {
schedule.every = ParseNumber<std::uint32_t>(*every, "--every");
}
if(const std::optional<std::string_view> until = args.Option("--until")) {
schedule.end = ParseEnd(*until);
}
const Created scheduled = client.Schedule(payment.account, payment.counterparty, payment.name, payment.amount, payment.description, schedule);
std::println("scheduled {} to {} (schedule {})", FormatMoney(payment.amount, scheduled.currency), payment.name, scheduled.id);
}
void Scheduled(Client& client, const Arguments& args) {
const std::string_view account = args.At(1, "account");
if(args.Or(2, "") == "cancel") {
client.CancelScheduledPayment(account, ParseNumber<std::uint64_t>(args.At(3, "schedule id"), "schedule id"));
std::println("cancelled schedule {}", args.At(3, ""));
return;
}
for(const BunqScheduledPayment& scheduled : client.ScheduledPayments(account)) {
std::println("{}", scheduled);
}
}
void Draft(Client& client, const Arguments& args) {
const Payment payment(args, "recipient", "recipient name", 5);
const Created drafted = client.Draft(payment.account, payment.counterparty, payment.name, payment.amount, payment.description);
std::println("drafted {} to {} (draft {}); it is paid once accepted", FormatMoney(payment.amount, drafted.currency), payment.name, drafted.id);
}
void Drafts(Client& client, const Arguments& args) {
const std::string_view account = args.At(1, "account");
const std::string_view verb = args.Or(2, "");
if(verb == "accept" || verb == "reject") {
client.RespondToDraftPayment(account, ParseNumber<std::uint64_t>(args.At(3, "draft id"), "draft id"), verb == "accept");
std::println("{} draft {}", verb == "accept" ? "accepted" : "rejected", args.At(3, ""));
return;
}
for(const BunqDraftPayment& draft : client.DraftPayments(account)) {
std::println("{}", draft);
}
}
void Cards(Client& client, const Arguments& args) {
const std::string_view verb = args.Or(1, "");
if(verb.empty()) {
for(const ConnectorCards& connector : client.Cards()) {
std::println("{}\t{}", connector.name, connector.bank);
for(const BunqCard& card : connector.cards) {
std::println("\t{}", card);
}
}
return;
}
const std::map<std::string_view, std::string_view> statuses = {{"freeze", "DEACTIVATED"}, {"unfreeze", "ACTIVE"}, {"lost", "LOST"}, {"stolen", "STOLEN"}};
const auto status = statuses.find(verb);
if(status == statuses.end()) {
throw std::invalid_argument(std::format("unknown card action '{}'", verb));
}
const std::uint64_t id = ParseNumber<std::uint64_t>(args.At(2, "card id"), "card id");
const BunqCard card = client.SetCardStatus(id, status->second);
if(card.status != status->second) {
throw std::runtime_error(std::format("bunq kept card {} {} (its order status is {}): a card can only be frozen or unfrozen once it has been activated", id, card.status, card.orderStatus));
}
std::println("card {} is now {}", id, card.status);
}
// Apps pay at checkout from one account, and the user confirms each payment with their password.
void CheckoutAccount(Client& client, const Arguments& args) {
const std::string_view verb = args.At(1, "checkout command");
if(verb != "account") {
throw std::invalid_argument(std::format("unknown checkout command '{}'", verb));
}
if(args.positional.size() > 2) {
std::println("checkouts pay from {}", client.SetDefaultCheckoutAccount(args.positional[2]));
} else if(const std::optional<Account> chosen = client.DefaultCheckoutAccount()) {
std::println("{}", *chosen);
} else {
std::println("no account pays at checkout: `nostro checkout account <account>` chooses one");
}
}
std::int32_t Run(std::span<const std::string_view> arguments) {
const Arguments args(arguments);
if(args.positional.empty()) {
std::println("{}", usage);
return 1;
}
const std::string_view cmd = args.positional[0];
if(cmd == "help") {
std::println("{}", usage);
return 0;
}
const std::map<std::string_view, void (*)(Client&, const Arguments&)> commands = {
{"connectors", Connectors}, {"accounts", ListAccounts}, {"transactions", ListTransactions},
{"send", Send}, {"request", Request}, {"requests", Requests}, {"incoming", Incoming},
{"schedule", Schedule}, {"scheduled", Scheduled}, {"draft", Draft}, {"drafts", Drafts}, {"cards", Cards},
{"checkout", CheckoutAccount},
};
const auto command = commands.find(cmd);
if(command == commands.end()) {
std::println(std::cerr, "unknown command '{}'\n\n{}", cmd, usage);
return 1;
}
Client client = Client::System();
command->second(client, args);
// The library's warnings during the call, such as a connector that could not be reached.
for(const std::string& note : client.TakeNotes()) {
std::println(std::cerr, "{}", note);
}
return 0;
}
}
// main's signature is C's; past it the arguments are string views.
// lint-disable-next-line no-char-pointer
int main(int argc, char *argv[]) {
std::vector<std::string_view> arguments;
for(std::int32_t i = 1; i < argc; i++) {
arguments.emplace_back(argv[i]);
}
try {
return Run(arguments);
} catch(const std::exception& e) {
std::println(std::cerr, "error: {}", e.what());
return 1;
}
}

View file

@ -0,0 +1,63 @@
// SPDX-License-Identifier: LGPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// nostrod: the daemon that holds the connectors (Nostro:Daemon). This file only reads the command line:
// nostrod [--state <dir>] [--idle <seconds>] [--prompt-timeout <seconds>]
// nostrod --worker <uid> <name> ... what the daemon starts for one user, with its socket as fd 3
// Without --state the users' directories go below $XDG_DATA_HOME (which Flatpak points into the app's own data), or
// ~/.local/share.
import std;
import Nostro;
// main's signature is C's; past it the arguments are string views.
// lint-disable-next-line no-char-pointer
int main(int argc, char* argv[]) {
const std::vector<std::string_view> args(argv + 1, argv + argc);
try {
const auto value = [&args](std::size_t index) {
if(index >= args.size()) {
throw std::invalid_argument(std::format("{} needs a value", args[index - 1]));
}
return args[index];
};
const auto number = [](std::string_view text) {
std::uint32_t count = 0;
const std::from_chars_result result = std::from_chars(text.data(), text.data() + text.size(), count);
if(result.ec != std::errc() || result.ptr != text.data() + text.size()) {
throw std::invalid_argument(std::format("'{}' is not a whole number", text));
}
return count;
};
Nostro::DaemonOptions options;
// getenv answers with a char*, null when the variable is not set.
// lint-disable-next-line no-char-pointer
const char* const dataHome = std::getenv("XDG_DATA_HOME");
// lint-disable-next-line no-char-pointer
const char* const home = std::getenv("HOME");
options.state = dataHome ? std::filesystem::path(dataHome) : std::filesystem::path(home ? home : "/") / ".local/share";
std::optional<std::pair<std::uint32_t, std::string>> worker;
for(std::size_t i = 0; i < args.size(); i++) {
if(args[i] == "--state") {
options.state = value(++i);
} else if(args[i] == "--idle") {
options.idle = std::chrono::seconds(number(value(++i)));
} else if(args[i] == "--prompt-timeout") {
options.promptTimeout = std::chrono::seconds(number(value(++i)));
} else if(args[i] == "--worker") {
const std::uint32_t uid = number(value(++i));
worker = std::pair{uid, std::string(value(++i))};
} else {
throw std::invalid_argument(std::format("unknown argument '{}'", args[i]));
}
}
if(worker) {
return Nostro::RunWorker(3, worker->first, worker->second, options);
}
return Nostro::RunDaemon(options);
} catch(const std::exception& e) {
std::println(std::cerr, "nostrod: {}", e.what());
return 1;
}
}