// SPDX-License-Identifier: LGPL-3.0-only // SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts® module; #include #include #include #include #include #include #include module Nostro:DaemonWorker_impl; import std; import Crafter.DB; import Nostro.Checkout; import :Daemon; import :Bus; import :Account; import :Bunq; import :Connector; import :Currency; import :File; import :Transaction; import :Utils; using namespace Nostro; using namespace Nostro::Bus; using namespace Crafter; namespace fs = std::filesystem; // One user's worker. Every call is read and checked first (the account, the counterparty, what is to be paid), then // polkit decides with a summary built from the worker's own data, and only then does the call run. The wire carries // bunq's types, so the worker works with bunq's connector directly. namespace { using Work = std::function; // What runs once a call that went through polkit is answered, with the answer it got. using After = std::function; // An order paid at checkout, or being paid, which makes a retry safe. It is written before the payment is sent, // with no payment yet, so a worker that dies or a bank whose answer is lost leaves it saying the order may have been // paid. This is the table's schema: a change to it bumps `version` (see the Crafter.DB notes). struct CheckoutRecord { std::string payee; // the payee's IBAN, without spaces std::string reference; // the app's reference for the order std::int64_t amount = 0; // in the currency's minor unit Currency currency = Currency::Euro; std::string account; // the IBAN it is paid from std::uint64_t payment = 0; // the bank's id of the payment, 0 while the bank's answer is unknown std::chrono::system_clock::time_point time; static constexpr std::uint32_t version = 1; }; static_assert(DB::Layout::rowSize == 80); static_assert(DB::Layout::fingerprint == 0x87a27f8a68f38c52); // Orders are told apart by payee and reference: an app's references are its own. using OrderKey = std::pair; // An order whose call is under way, and the calls for the same order that wait for its answer. struct Paying { std::int64_t amount = 0; Currency currency = Currency::Euro; std::vector waiting; }; struct Worker { DaemonOptions options; std::uint32_t uid = 0; std::string name; fs::path directory; sd_event* event = nullptr; // Before the connection they are registered with, which then goes first however RunWorker ends. std::vector vtable; std::vector checkoutVtable; BusPtr link; BusPtr system; sd_event_source* idle = nullptr; // Why every call is refused: the directory belongs to the user this uid had before. std::optional refusal; bool loaded = false; std::size_t checking = 0; std::uint64_t checks = 0; // The checkouts paid, opened with the first; and the orders being paid now. std::optional> records; std::map paying; }; // Answered as AccessDenied. struct Refused : std::runtime_error { using std::runtime_error::runtime_error; }; // bunq refusing a payment through an OAuth connector, which may only pay the user's own accounts. struct OAuthPaymentRefused : std::runtime_error { using std::runtime_error::runtime_error; }; // A checkout, and no account to pay it from. struct NoCheckoutAccount : std::runtime_error { using std::runtime_error::runtime_error; }; // The library's warnings, sent with the next answer that is not an error. The process's own, as noteSink is. std::vector notes; std::uint64_t Microseconds(std::chrono::seconds duration) { return static_cast(std::chrono::duration_cast(duration).count()); } void Touch(Worker& worker) { sd_event_source_set_time_relative(worker.idle, Microseconds(worker.options.idle)); sd_event_source_set_enabled(worker.idle, SD_EVENT_ONESHOT); } // Idle, and no password prompt open: the worker ends, and the front starts a new one for the next call. std::int32_t OnIdle(sd_event_source*, std::uint64_t, void* userdata) { Worker& worker = *static_cast(userdata); if(worker.checking == 0) { return sd_event_exit(worker.event, 0); } Touch(worker); return 0; } std::int32_t OnFrontGone(sd_bus_message*, void* userdata, sd_bus_error*) { sd_event_exit(static_cast(userdata)->event, 0); return 0; } // An error answer to `call`. Making one fails only when memory runs out, and then the caller's own timeout answers. MessagePtr ErrorReply(sd_bus_message* call, std::string_view name, const std::string& message) { sd_bus_message* raw = nullptr; sd_bus_message_new_method_errorf(call, &raw, std::string(name).c_str(), "%s", message.c_str()); return MessagePtr(raw); } // The error a call is answered with, by what went wrong. MessagePtr ErrorFor(sd_bus_message* call, const std::exception_ptr& error) { std::string_view name = errorFailed; std::string message; try { std::rethrow_exception(error); } catch(const Refused& e) { name = SD_BUS_ERROR_ACCESS_DENIED; message = e.what(); } catch(const NoCheckoutAccount& e) { name = errorNoCheckoutAccount; message = e.what(); } catch(const OAuthPaymentRefused& e) { name = errorOAuthCannotPay; message = e.what(); } catch(const BunqError& e) { name = errorBank; message = e.what(); } catch(const std::invalid_argument& e) { name = errorInvalidArgument; message = e.what(); } catch(const std::exception& e) { message = e.what(); } return ErrorReply(call, name, message); } void Deliver(const MessagePtr& answer) { sd_bus_send(nullptr, answer.get(), nullptr); } // Text from a caller or a bank, made fit for a password dialog: no control, zero-width or direction-changing // characters, nothing a dialog could take for markup or polkit for one of its $(…) fields, and at most 64 // characters, so a long name cannot push what matters out of sight. std::string Shown(std::string_view text) { std::string out; std::size_t characters = 0; std::size_t i = 0; // The text is UTF-8: D-Bus carries nothing else, and nlohmann's parser takes nothing else from the bank. A // sequence is still never read past the end. while(i < text.size()) { const std::uint8_t lead = static_cast(text[i]); const std::size_t length = std::min(lead < 0x80 ? 1 : lead < 0xE0 ? 2 : lead < 0xF0 ? 3 : 4, text.size() - i); std::uint32_t code = length == 1 ? lead : lead & (0xFF >> (length + 1)); for(std::size_t k = 1; k < length; k++) { code = (code << 6) | (static_cast(text[i + k]) & 0x3F); } const std::string_view character = text.substr(i, length); i += length; const bool hidden = code < 0x20 || code == 0x7F || (code >= 0x80 && code < 0xA0) || (code >= 0x200B && code <= 0x200F) || (code >= 0x202A && code <= 0x202E) || (code >= 0x2060 && code <= 0x2069) || code == 0xFEFF; if(hidden) { continue; } if(characters == 64) { out += "…"; break; } characters++; if(code == '<') { out += "‹"; } else if(code == '>') { out += "›"; } else { if(code == '(' && out.ends_with('$')) { out += ' '; } out += character; } } return out; } std::string_view EnvironmentName(BunqEnvironment environment) { return environment == BunqEnvironment::Production ? "production" : "sandbox"; } BunqEnvironment ParseEnvironment(std::string_view name) { if(name == "production") { return BunqEnvironment::Production; } if(name == "sandbox") { return BunqEnvironment::Sandbox; } throw std::invalid_argument(std::format("unknown environment '{}': production or sandbox", name)); } // Who is paid or asked, as a dialog shows it: the address first, so a long name cannot hide it. std::string Party(const BunqCounterparty& party) { return party.name.empty() ? Shown(party.value) : std::format("{} ({})", Shown(party.value), Shown(party.name)); } std::string Party(const BunqLabel& label) { if(label.iban.empty()) { return Shown(label.name); } return label.name.empty() ? Shown(label.iban) : std::format("{} ({})", Shown(label.iban), Shown(label.name)); } std::string Party(const BunqAccount& account) { return std::format("{} ({})", Shown(account.iban), Shown(account.name)); } std::string Utc(std::chrono::system_clock::time_point time) { return std::format("{:%Y-%m-%d %H:%M} UTC", std::chrono::floor(time)); } // When a schedule pays, in words. std::string When(const BunqSchedule& schedule) { const std::map> units = { {"HOURLY", {"hourly", "hours"}}, {"DAILY", {"daily", "days"}}, {"WEEKLY", {"weekly", "weeks"}}, {"MONTHLY", {"monthly", "months"}}, {"YEARLY", {"yearly", "years"}}, }; std::string when; if(const auto unit = units.find(schedule.unit); unit != units.end()) { when = schedule.every == 1 ? std::format("{} from {}", unit->second.first, Utc(schedule.start)) : std::format("every {} {} from {}", schedule.every, unit->second.second, Utc(schedule.start)); } else { when = std::format("once on {}", Utc(schedule.start)); } if(schedule.end) { when += std::format(" until {}", Utc(*schedule.end)); } return when; } void RequirePositive(std::int64_t amount) { if(amount <= 0) { throw std::invalid_argument("the amount must be more than zero"); } } // What the dialog says, and the details polkit rules can test. struct Prompt { std::string_view action; std::string summary; std::vector> details; }; // A payment's details for polkit rules: how much, in what, to whom, from where, at which bunq. std::vector> PaymentDetails(const BunqAccount& account, std::int64_t amount, Currency currency, std::string_view counterparty) { return { {"amount_minor", std::to_string(amount)}, {"currency", std::string(GetCurrencyCode(currency))}, {"counterparty", Shown(counterparty)}, {"account_iban", account.iban}, {"environment", std::string(EnvironmentName(account.connector->environment))}, }; } // Where an account is found again after the prompt, when the accounts may have been refreshed in between. struct AccountKey { std::string connector; std::uint64_t account = 0; }; AccountKey KeyOf(const BunqAccount& account) { return AccountKey{account.connector->StorageKey(), account.id}; } BunqConnector& ConnectorBy(const std::string& storageKey) { const auto found = std::ranges::find_if(BunqConnector::connectors, [&storageKey](const BunqConnector& bank) { return bank.StorageKey() == storageKey; }); if(found == BunqConnector::connectors.end()) { throw std::invalid_argument("that connector is no longer there"); } return *found; } BunqAccount& AccountBy(const AccountKey& key) { BunqConnector& bank = ConnectorBy(key.connector); const auto found = std::ranges::find(bank.accounts, key.account, &BunqAccount::id); if(found == bank.accounts.end()) { throw std::invalid_argument("that account is no longer there"); } return *found; } void RefreshAll() { for(BunqConnector& bank : BunqConnector::connectors) { try { bank.RefreshAccounts(); } catch(const std::exception& e) { Note(std::format("{} connector '{}' is unavailable: {}", BunqConnector::connectorId, bank.name, e.what())); } } } // The one account with this name or IBAN, across every connector. The accounts are refreshed once when none // matches, for an account opened since they were read. BunqAccount& FindAccount(std::string_view key) { for(std::size_t attempt = 0; attempt < 2; attempt++) { std::vector matches; for(BunqConnector& bank : BunqConnector::connectors) { for(BunqAccount& account : bank.accounts) { if(account.name == key || account.iban == key) { matches.push_back(&account); } } } if(matches.size() > 1) { throw std::invalid_argument(std::format("{} accounts are called '{}': use the IBAN", matches.size(), key)); } if(matches.size() == 1) { return *matches.front(); } if(attempt == 0) { RefreshAll(); } } throw std::invalid_argument(std::format("no account is called or has IBAN '{}'", key)); } // The user's connectors, read on the first call: the first call also records whose directory this is. void Load(Worker& worker) { if(worker.loaded) { return; } const fs::path owner = worker.directory / "owner"; if(!fs::exists(owner)) { CreatePrivateFile(owner); std::ofstream out(owner); std::println(out, "{}", worker.name); } Connector::LoadConnectors(); worker.loaded = true; } // Runs `work` and makes the answer to `call` of what it appended, and of the notes, which only nostrod's own // interface carries: they are the user's, and an app at checkout is someone else. MessagePtr Answer(sd_bus_message* call, const Work& work) { sd_bus_message* raw = nullptr; ThrowOnSdBus(sd_bus_message_new_method_return(call, &raw), "answer a call"); MessagePtr reply(raw); work(raw); const std::vector said = std::exchange(notes, {}); if(Interface(call) == interfaceName) { Append(raw, said); } return reply; } struct Check { Worker* worker = nullptr; MessagePtr call; Work work; After after; std::string action; bool interactive = false; std::string cancellation; }; // polkit's answer: run the call, or say why not. Fails closed: no answer is no. std::int32_t OnChecked(sd_bus_message* reply, void* userdata, sd_bus_error*) { const std::unique_ptr check(static_cast(userdata)); Worker& worker = *check->worker; worker.checking--; Touch(worker); sd_bus_message* call = check->call.get(); MessagePtr answer; try { if(sd_bus_message_is_method_error(reply, nullptr)) { const sd_bus_error* error = sd_bus_message_get_error(reply); if(sd_bus_error_has_names(error, SD_BUS_ERROR_NO_REPLY, SD_BUS_ERROR_TIMEOUT)) { // Leave no dialog open for an answer nobody waits for. sd_bus_call_method_async(worker.system.get(), nullptr, "org.freedesktop.PolicyKit1", "/org/freedesktop/PolicyKit1/Authority", "org.freedesktop.PolicyKit1.Authority", "CancelCheckAuthorization", nullptr, nullptr, "s", check->cancellation.c_str()); } throw Refused(std::format("polkit did not decide on {}: {}", check->action, ErrorMessage(*error))); } Enter(reply, 'r', "bba{ss}"); const bool authorized = Read(reply); const bool challenge = Read(reply); std::map details; Enter(reply, 'a', "{ss}"); while(ThrowOnSdBus(sd_bus_message_at_end(reply, 0), "read polkit's answer") == 0) { Enter(reply, 'e', "ss"); std::string key = Read(reply); details[std::move(key)] = Read(reply); Leave(reply); } Leave(reply); Leave(reply); if(authorized) { answer = Answer(call, check->work); } else if(challenge && !check->interactive) { answer = ErrorReply(call, SD_BUS_ERROR_INTERACTIVE_AUTHORIZATION_REQUIRED, std::format("{} needs your password, and the call did not let nostrod ask for it", check->action)); } else if(check->interactive && (details["polkit.dismissed"] == "true" || details["polkit.result"].starts_with("auth_"))) { // Asked, and not authenticated: the dialog was closed, or no agent could ask. answer = ErrorReply(call, errorCancelled, "you did not authenticate, so nothing was done"); } else { throw Refused(std::format("the system's policy does not allow {}", check->action)); } } catch(...) { answer = ErrorFor(call, std::current_exception()); } Deliver(answer); if(check->after) { check->after(answer.get()); } return 0; } // Asks polkit whether the caller may do what `prompt` says, then runs `work` and answers; or answers why not; and // then runs `after` with the answer. The check does not block: other calls are served while a password dialog is // open. std::int32_t Gate(Worker& worker, sd_bus_message* call, const Prompt& prompt, Work work, After after = {}) { const bool interactive = sd_bus_message_get_allow_interactive_authorization(call) > 0; sd_bus_message* raw = nullptr; ThrowOnSdBus(sd_bus_message_new_method_call(worker.system.get(), &raw, "org.freedesktop.PolicyKit1", "/org/freedesktop/PolicyKit1/Authority", "org.freedesktop.PolicyKit1.Authority", "CheckAuthorization"), "ask polkit"); const MessagePtr request(raw); // The subject is the caller's connection, which polkit looks up itself. Open(raw, 'r', "sa{sv}"); Append(raw, std::string("system-bus-name")); Open(raw, 'a', "{sv}"); Open(raw, 'e', "sv"); Append(raw, std::string("name")); Open(raw, 'v', "s"); Append(raw, Sender(call)); Close(raw); Close(raw); Close(raw); Close(raw); Append(raw, std::string(prompt.action)); Open(raw, 'a', "{ss}"); const auto detail = [raw](const std::string& key, const std::string& value) { Open(raw, 'e', "ss"); Append(raw, key); Append(raw, value); Close(raw); }; detail("summary", prompt.summary); for(const auto& [key, value] : prompt.details) { detail(key, value); } Close(raw); Append(raw, std::uint32_t{interactive ? 1u : 0u}); std::string cancellation = std::format("nostro-{}-{}", getpid(), ++worker.checks); Append(raw, cancellation); std::unique_ptr check = std::make_unique(&worker, MessagePtr(sd_bus_message_ref(call)), std::move(work), std::move(after), std::string(prompt.action), interactive, std::move(cancellation)); ThrowOnSdBus(sd_bus_call_async(worker.system.get(), nullptr, raw, OnChecked, check.get(), Microseconds(worker.options.promptTimeout)), "ask polkit"); // OnChecked owns it now. check.release(); worker.checking++; return 1; } // Runs `body` for `call`: it answers through Gate, or throws, and then the call is answered with the error. template std::int32_t Handle(sd_bus_message* call, void* userdata, Body&& body) { Worker& worker = *static_cast(userdata); Touch(worker); try { if(worker.refusal) { throw Refused(*worker.refusal); } Load(worker); return body(worker); } catch(...) { Deliver(ErrorFor(call, std::current_exception())); return 1; } } std::int32_t OnConnectors(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { return Gate(worker, call, Prompt{actionView, "see your bank connectors", {}}, [](sd_bus_message* reply) { std::vector summaries; for(BunqConnector& bank : BunqConnector::connectors) { summaries.push_back(ConnectorSummary{bank.name, std::string(BunqConnector::connectorId), std::string(EnvironmentName(bank.environment)), bank.IsOAuth() ? "oauth" : "api key", bank.TestConnector()}); } Append(reply, summaries); }); }); } void AppendAdded(sd_bus_message* reply, const BunqConnector& added) { Append(reply, added.name); Append(reply, std::string(EnvironmentName(added.environment))); Append(reply, static_cast(added.accounts.size())); } std::int32_t OnAddBunq(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { std::string apiKey = Read(call); std::string allowedIps = Read(call); const std::string requested = Read(call); const BunqEnvironment environment = requested.empty() ? BunqConnector::EnvironmentOfKey(apiKey) : ParseEnvironment(requested); const Prompt prompt{actionConnectors, std::format("add a bunq connector ({})", EnvironmentName(environment)), {{"environment", std::string(EnvironmentName(environment))}}}; return Gate(worker, call, prompt, [apiKey = std::move(apiKey), allowedIps = std::move(allowedIps), environment](sd_bus_message* reply) { AppendAdded(reply, BunqConnector::Create(std::string(apiKey), allowedIps, environment)); Connector::SaveConnectors(); }); }); } std::int32_t OnAddBunqOAuth(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { const BunqEnvironment environment = ParseEnvironment(Read(call)); std::string clientId = Read(call); std::string clientSecret = Read(call); std::string redirectUri = Read(call); std::string code = Read(call); const Prompt prompt{actionConnectors, std::format("add a bunq connector through OAuth ({})", EnvironmentName(environment)), {{"environment", std::string(EnvironmentName(environment))}}}; return Gate(worker, call, prompt, [environment, clientId = std::move(clientId), clientSecret = std::move(clientSecret), redirectUri = std::move(redirectUri), code = std::move(code)](sd_bus_message* reply) { AppendAdded(reply, BunqConnector::Create(BunqConnector::OAuthExchangeCode(environment, clientId, clientSecret, redirectUri, code), "*", environment)); Connector::SaveConnectors(); }); }); } std::int32_t OnRemoveConnector(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { const std::string key = Read(call); // By name, or by the number Connectors() lists it under. std::vector matches; std::size_t number = 1; for(BunqConnector& bank : BunqConnector::connectors) { if(bank.name == key || std::to_string(number++) == key) { matches.push_back(&bank); } } if(matches.size() != 1) { throw std::invalid_argument(matches.empty() ? std::format("no connector is called or numbered '{}'", key) : std::format("{} connectors are called '{}': use the number `nostro connectors` shows", matches.size(), key)); } const std::string storageKey = matches.front()->StorageKey(); const Prompt prompt{actionConnectors, std::format("remove the bunq connector '{}' and its stored transactions", Shown(matches.front()->name)), {}}; return Gate(worker, call, prompt, [storageKey](sd_bus_message* reply) { BunqConnector& bank = ConnectorBy(storageKey); try { bank.Logout(); } catch(const std::exception& e) { Note(std::format("could not log out, forgetting the connector anyway: {}", e.what())); } const std::string removed = bank.name; BunqConnector::Remove(bank); Connector::SaveConnectors(); Append(reply, removed); }); }); } std::int32_t OnAccounts(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { return Gate(worker, call, Prompt{actionView, "see your accounts and balances", {}}, [](sd_bus_message* reply) { RefreshAll(); std::vector listing; for(const BunqConnector& bank : BunqConnector::connectors) { listing.push_back(ConnectorAccounts{bank.name, std::string(BunqConnector::connectorId), std::vector(bank.accounts.begin(), bank.accounts.end())}); } Append(reply, listing); }); }); } std::int32_t OnTransactions(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { const std::string account = Read(call); const TransactionQuery query = ReadQuery(call); const AccountKey key = KeyOf(FindAccount(account)); return Gate(worker, call, Prompt{actionView, "see your transactions", {}}, [key, query](sd_bus_message* reply) { BunqAccount& found = AccountBy(key); found.connector->GetNewTransactions(found); Append(reply, found.FindTransactions(found.StorageKey(), query)); }); }); } // The arguments a payment, a draft, a schedule and a request share. struct Payment { std::string account; std::string counterparty; std::string name; std::int64_t amount = 0; std::string description; static Payment Read(sd_bus_message* call) { Payment payment; payment.account = Bus::Read(call); payment.counterparty = Bus::Read(call); payment.name = Bus::Read(call); payment.amount = Bus::Read(call); payment.description = Bus::Read(call); return payment; } }; std::int32_t OnSend(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { const Payment payment = Payment::Read(call); const BunqAccount& account = FindAccount(payment.account); RequirePositive(payment.amount); const BunqCounterparty payee = BunqCounterparty::Parse(payment.counterparty, payment.name); const Prompt prompt{actionPay, std::format("pay {} to {} from {}", FormatMoney(payment.amount, account.currency), Party(payee), Party(account)), PaymentDetails(account, payment.amount, account.currency, payee.value)}; return Gate(worker, call, prompt, [key = KeyOf(account), payment](sd_bus_message* reply) { const BunqAccount& found = AccountBy(key); std::uint64_t id = 0; try { id = found.Send(payment.counterparty, payment.name, payment.amount, found.currency, payment.description); } catch(const BunqError& e) { // bunq lets an OAuth connection pay between the user's own accounts only. if(found.connector->IsOAuth()) { throw OAuthPaymentRefused(e.what()); } throw; } Append(reply, id); Append(reply, found.currency); }); }); } std::int32_t OnSchedule(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { const Payment payment = Payment::Read(call); const BunqSchedule schedule = Read(call); const BunqAccount& account = FindAccount(payment.account); RequirePositive(payment.amount); schedule.Check(); const BunqCounterparty payee = BunqCounterparty::Parse(payment.counterparty, payment.name); const Prompt prompt{actionPay, std::format("schedule {} to {} from {}, {}", FormatMoney(payment.amount, account.currency), Party(payee), Party(account), When(schedule)), PaymentDetails(account, payment.amount, account.currency, payee.value)}; return Gate(worker, call, prompt, [key = KeyOf(account), payment, schedule](sd_bus_message* reply) { const BunqAccount& found = AccountBy(key); Append(reply, found.Schedule(payment.counterparty, payment.name, payment.amount, found.currency, payment.description, schedule)); Append(reply, found.currency); }); }); } std::int32_t OnRequest(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { const Payment payment = Payment::Read(call); const BunqAccount& account = FindAccount(payment.account); RequirePositive(payment.amount); const BunqCounterparty payer = BunqCounterparty::Parse(payment.counterparty, payment.name); const Prompt prompt{actionChange, std::format("ask {} for {} into {}", Party(payer), FormatMoney(payment.amount, account.currency), Party(account)), PaymentDetails(account, payment.amount, account.currency, payer.value)}; return Gate(worker, call, prompt, [key = KeyOf(account), payment](sd_bus_message* reply) { const BunqAccount& found = AccountBy(key); Append(reply, found.Request(payment.counterparty, payment.name, payment.amount, found.currency, payment.description)); }); }); } // A listing of one account's requests, schedules or drafts. template std::int32_t Listing(sd_bus_message* call, void* userdata, std::string_view what, List list) { return Handle(call, userdata, [call, what, list](Worker& worker) { const AccountKey key = KeyOf(FindAccount(Read(call))); return Gate(worker, call, Prompt{actionView, std::format("see your {}", what), {}}, [key, list](sd_bus_message* reply) { Append(reply, list(AccountBy(key))); }); }); } std::int32_t OnRequests(sd_bus_message* call, void* userdata, sd_bus_error*) { return Listing(call, userdata, "requests for money", [](const BunqAccount& account) { return account.Requests(); }); } std::int32_t OnIncomingRequests(sd_bus_message* call, void* userdata, sd_bus_error*) { return Listing(call, userdata, "incoming requests for money", [](const BunqAccount& account) { return account.IncomingRequests(); }); } std::int32_t OnScheduledPayments(sd_bus_message* call, void* userdata, sd_bus_error*) { return Listing(call, userdata, "scheduled payments", [](const BunqAccount& account) { return account.ScheduledPayments(); }); } std::int32_t OnDraftPayments(sd_bus_message* call, void* userdata, sd_bus_error*) { return Listing(call, userdata, "draft payments", [](const BunqAccount& account) { return account.DraftPayments(); }); } // Revoking a request or cancelling a schedule: a change to one object of one account. template std::int32_t Undo(sd_bus_message* call, void* userdata, std::string_view what, Act act) { return Handle(call, userdata, [call, what, act](Worker& worker) { const BunqAccount& account = FindAccount(Read(call)); const std::uint64_t id = Read(call); const Prompt prompt{actionChange, std::format("{} {} of {}", what, id, Party(account)), {}}; return Gate(worker, call, prompt, [key = KeyOf(account), id, act](sd_bus_message*) { act(AccountBy(key), id); }); }); } std::int32_t OnRevokeRequest(sd_bus_message* call, void* userdata, sd_bus_error*) { return Undo(call, userdata, "revoke request", [](const BunqAccount& account, std::uint64_t id) { account.RevokeRequest(id); }); } std::int32_t OnCancelScheduledPayment(sd_bus_message* call, void* userdata, sd_bus_error*) { return Undo(call, userdata, "cancel scheduled payment", [](const BunqAccount& account, std::uint64_t id) { account.CancelScheduledPayment(id); }); } std::int32_t OnRespondToRequest(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { const BunqAccount& account = FindAccount(Read(call)); const std::uint64_t id = Read(call); const bool accept = Read(call); // The request as bunq has it now, which is what the dialog shows and what accepting pays. const BunqIncomingRequest shown = account.IncomingRequest(id); const Prompt prompt = accept ? Prompt{actionPay, std::format("pay {} to {} from {}, as asked in request {}", FormatMoney(shown.amount, shown.currency), Party(shown.counterparty), Party(account), shown.id), PaymentDetails(account, shown.amount, shown.currency, shown.counterparty.iban)} : Prompt{actionChange, std::format("reject request {} from {}", shown.id, Party(shown.counterparty)), {}}; return Gate(worker, call, prompt, [key = KeyOf(account), shown, accept](sd_bus_message*) { AccountBy(key).RespondToRequest(shown, accept); }); }); } std::int32_t OnDraft(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { const Payment payment = Payment::Read(call); const BunqAccount& account = FindAccount(payment.account); RequirePositive(payment.amount); const BunqCounterparty payee = BunqCounterparty::Parse(payment.counterparty, payment.name); const Prompt prompt{actionChange, std::format("make a draft payment of {} to {} from {}, paid once someone accepts it", FormatMoney(payment.amount, account.currency), Party(payee), Party(account)), PaymentDetails(account, payment.amount, account.currency, payee.value)}; return Gate(worker, call, prompt, [key = KeyOf(account), payment](sd_bus_message* reply) { const BunqAccount& found = AccountBy(key); Append(reply, found.Draft(payment.counterparty, payment.name, payment.amount, found.currency, payment.description)); Append(reply, found.currency); }); }); } std::int32_t OnRespondToDraftPayment(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { const BunqAccount& account = FindAccount(Read(call)); const std::uint64_t id = Read(call); const bool accept = Read(call); // The draft as bunq has it now: the dialog shows it, and bunq refuses the answer if it changes after. const BunqDraftPayment shown = account.DraftPayment(id); std::int64_t total = 0; std::vector payees; for(const BunqDraftPayment::Entry& entry : shown.entries) { total += entry.amount; payees.push_back(Party(entry.counterparty)); } const Currency currency = shown.entries.empty() ? account.currency : shown.entries.front().currency; const std::string firstPayee = shown.entries.empty() ? std::string() : shown.entries.front().counterparty.iban; std::string to = payees.size() <= 3 ? std::string() : std::format(" and {} more", payees.size() - 3); payees.resize(std::min(payees.size(), 3)); to.insert(0, payees.empty() ? std::string("no one") : std::ranges::to(payees | std::views::join_with(std::string_view(", ")))); const Prompt prompt = accept ? Prompt{actionPay, std::format("pay {} to {} from {}, as drafted in draft payment {}", FormatMoney(total, currency), to, Party(account), shown.id), PaymentDetails(account, total, currency, firstPayee)} : Prompt{actionChange, std::format("reject draft payment {} of {} to {}", shown.id, FormatMoney(total, currency), to), {}}; return Gate(worker, call, prompt, [key = KeyOf(account), shown, accept](sd_bus_message*) { AccountBy(key).RespondToDraftPayment(shown, accept); }); }); } std::int32_t OnCards(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { return Gate(worker, call, Prompt{actionView, "see your cards", {}}, [](sd_bus_message* reply) { std::vector listing; for(BunqConnector& bank : BunqConnector::connectors) { listing.push_back(ConnectorCards{bank.name, std::string(BunqConnector::connectorId), bank.Cards()}); } Append(reply, listing); }); }); } std::int32_t OnSetCardStatus(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { const std::uint64_t card = Read(call); const std::string status = Read(call); // Unfreezing lets the card pay again; a card reported lost or stolen is blocked for good. const std::map> changes = { {"ACTIVE", {actionUnfreezeCard, "unfreeze card **** {}"}}, {"DEACTIVATED", {actionChange, "freeze card **** {}"}}, {"LOST", {actionBlockCard, "report card **** {} lost, which blocks it for good"}}, {"STOLEN", {actionBlockCard, "report card **** {} stolen, which blocks it for good"}}, }; const auto change = changes.find(status); if(change == changes.end()) { throw std::invalid_argument(std::format("unknown card status '{}': ACTIVE, DEACTIVATED, LOST or STOLEN", status)); } for(BunqConnector& bank : BunqConnector::connectors) { for(const BunqCard& found : bank.Cards()) { if(found.id == card) { const std::string lastFour = Shown(found.lastFour); const Prompt prompt{change->second.first, std::vformat(change->second.second, std::make_format_args(lastFour)), {{"card", std::to_string(card)}, {"status", status}}}; return Gate(worker, call, prompt, [storageKey = bank.StorageKey(), card, status](sd_bus_message* reply) { Append(reply, ConnectorBy(storageKey).SetCardStatus(card, status)); }); } } } throw std::invalid_argument(std::format("no card has id {}", card)); }); } // Checkout (Nostro.Checkout): an app has nostrod pay an order. The order is read and checked, the account that // pays it is chosen, the user confirms both at a password prompt, and it is paid and recorded. The record answers a // retry with the first payment, and a retry while the first call is still under way waits for its answer. // The account chosen to pay checkouts from, kept beside connectors.json as its connector's storage key and its id: // none when none is chosen, or it is gone. const BunqAccount* CheckoutAccount(const Worker& worker) { std::ifstream in(worker.directory / "checkout-account"); AccountKey key; const BunqAccount* found = nullptr; if(std::getline(in, key.connector) && in >> key.account) { for(const BunqConnector& bank : BunqConnector::connectors) { for(const BunqAccount& account : bank.accounts) { if(bank.StorageKey() == key.connector && account.id == key.account) { found = &account; } } } } return found; } std::int32_t OnDefaultCheckoutAccount(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { return Gate(worker, call, Prompt{actionView, "see which account pays at checkout", {}}, [&worker](sd_bus_message* reply) { const BunqAccount* chosen = CheckoutAccount(worker); Append(reply, chosen ? std::optional(*chosen) : std::nullopt); }); }); } std::int32_t OnSetDefaultCheckoutAccount(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { const BunqAccount& account = FindAccount(Read(call)); // bunq lets an OAuth connection pay the user's own accounts only, so through one no shop could be paid. if(account.connector->IsOAuth()) { throw std::invalid_argument(std::format("'{}' is reached through OAuth, which pays only your own accounts: checkouts need an account added with an API key", account.name)); } const Prompt prompt{actionConnectors, std::format("let apps ask you to pay from {} at checkout", Party(account)), {{"account_iban", account.iban}, {"environment", std::string(EnvironmentName(account.connector->environment))}}}; return Gate(worker, call, prompt, [&worker, key = KeyOf(account)](sd_bus_message* reply) { const BunqAccount& chosen = AccountBy(key); const fs::path file = worker.directory / "checkout-account"; CreatePrivateFile(file); std::ofstream out(file); std::println(out, "{}\n{}", key.connector, key.account); Append(reply, Account(chosen)); }); }); } // An order, as Pay() reads and checks it. The options after its arguments are not read: there are none yet, and // those of a later nostro this one does not know. struct Order { BunqCounterparty payee; // an IBAN, and the name given std::int64_t amount = 0; Currency currency = Currency::Euro; std::string reference; OrderKey Key() const { return {payee.value, reference}; } static Order Read(sd_bus_message* call) { const std::string iban = Bus::Read(call); const std::string name = Bus::Read(call); Order order; order.amount = Bus::Read(call); const std::string currency = Bus::Read(call); order.reference = Bus::Read(call); order.payee = BunqCounterparty::Parse(iban, name); if(order.payee.type != "IBAN") { throw std::invalid_argument(std::format("checkout pays an IBAN, and '{}' is none", iban)); } RequirePositive(order.amount); try { order.currency = GetCurrency(currency); } catch(const std::runtime_error& e) { throw std::invalid_argument(e.what()); } if(order.reference.empty()) { throw std::invalid_argument("an order needs a reference, such as its number: it is what keeps paying it again from paying twice"); } return order; } }; // One reference to one payee is one order, of one amount. void RequireSameOrder(std::int64_t amount, Currency currency, const Order& order) { if(amount != order.amount || currency != order.currency) { throw std::invalid_argument(std::format("reference {} to {} is an order of {}, not of {}: another order needs another reference", Shown(order.reference), order.payee.value, FormatMoney(amount, currency), FormatMoney(order.amount, order.currency))); } } DB::Table& Records(Worker& worker) { if(!worker.records) { // A few rows per order: a reservation of a gigabyte, where the transaction tables take Crafter.DB's 32. worker.records.emplace(worker.directory / "checkouts.cdb", DB::OpenOptions{.reserveBytes = std::uint64_t(1) << 30}); } return *worker.records; } // Pay()'s answer: the payment, and the results, of which `repeated` says the payment was made by an earlier call. void AppendPaid(sd_bus_message* reply, std::uint64_t payment, bool repeated) { ThrowOnSdBus(sd_bus_message_append(reply, "ta{sv}", payment, 1u, "repeated", "b", static_cast(repeated)), "answer a call"); } // Answers a call for an order paid before, or being paid, and returns true; false for an order not seen before. bool AnswerKnownOrder(Worker& worker, sd_bus_message* call, const Order& order) { static constexpr DB::Column<&CheckoutRecord::payee> payee{}; static constexpr DB::Column<&CheckoutRecord::reference> reference{}; if(const std::optional> record = Records(worker).Where(payee == order.payee.value && reference == order.reference).First()) { RequireSameOrder((*record)[&CheckoutRecord::amount], (*record)[&CheckoutRecord::currency], order); const std::uint64_t payment = (*record)[&CheckoutRecord::payment]; if(payment == 0) { throw std::runtime_error(std::format("order {} to {} may have been paid already: the bank's answer to it was lost, so check whether the payment arrived before paying it under another reference", Shown(order.reference), order.payee.value)); } Deliver(Answer(call, [payment](sd_bus_message* reply) { AppendPaid(reply, payment, true); })); return true; } if(const auto paying = worker.paying.find(order.Key()); paying != worker.paying.end()) { RequireSameOrder(paying->second.amount, paying->second.currency, order); paying->second.waiting.push_back(MessagePtr(sd_bus_message_ref(call))); return true; } return false; } // The order's call is answered: the calls that waited for it get the same answer, the payment marked as made by // an earlier call. The order is there: it went in before its account was chosen, and only this takes it out. // Answering fails only when memory runs out, and then the callers' own timeouts answer for them. void Settle(Worker& worker, const OrderKey& key, sd_bus_message* answer) { const std::vector waiting = std::move(worker.paying.extract(key).mapped().waiting); const bool paid = sd_bus_message_is_method_error(answer, nullptr) == 0; std::uint64_t payment = 0; sd_bus_message_rewind(answer, 1); sd_bus_message_read_basic(answer, 't', &payment); for(const MessagePtr& call : waiting) { if(paid) { sd_bus_reply_method_return(call.get(), "ta{sv}", payment, 1u, "repeated", "b", 1); } else { sd_bus_reply_method_error(call.get(), sd_bus_message_get_error(answer)); } } } // Pays an order the user confirmed, and records it. The record goes first, with no payment, so should the worker // die or the bank's answer be lost, a retry finds it and is refused rather than paid twice. Only a refusal bunq // gives before doing anything (below 500) takes it away again. std::uint64_t PayOrder(Worker& worker, const BunqAccount& account, const Order& order) { DB::Table& records = Records(worker); const DB::RowId row = records.Append(CheckoutRecord{order.payee.value, order.reference, order.amount, order.currency, account.iban, 0, std::chrono::system_clock::now()}); records.Flush(); std::uint64_t payment = 0; try { payment = account.Send(order.payee.value, order.payee.name, order.amount, order.currency, order.reference); } catch(const BunqError& e) { if(e.status < 500) { records.Erase(row); records.Flush(); } throw; } records.Set<&CheckoutRecord::payment>(row, payment); records.Flush(); return payment; } // Which account pays an order. Today the one the user chose for checkouts; an account picker, once nostro has a // GUI, asks the user here instead, through an agent in their session, and may take its time. It answers through // `then`, with the account or with what the call is to be refused with, and nothing else of a checkout changes with // it. One that answers later keeps a reference to `call` until it does. using Choice = std::variant; void ChooseAccount(const Worker& worker, sd_bus_message*, const Order&, const std::function& then) { if(const BunqAccount* chosen = CheckoutAccount(worker)) { then(KeyOf(*chosen)); } else { then(std::make_exception_ptr(NoCheckoutAccount("no account is chosen to pay checkouts from, or it is gone: `nostro checkout account ` chooses one"))); } } std::int32_t OnPay(sd_bus_message* call, void* userdata, sd_bus_error*) { return Handle(call, userdata, [call](Worker& worker) { const Order order = Order::Read(call); if(AnswerKnownOrder(worker, call, order)) { return 1; } // From here on, a call for the same order waits for this one, and Settle answers it. worker.paying[order.Key()] = Paying{order.amount, order.currency, {}}; ChooseAccount(worker, call, order, [&worker, call, order](const Choice& choice) { try { if(const std::exception_ptr* refusal = std::get_if(&choice)) { std::rethrow_exception(*refusal); } const AccountKey key = std::get(choice); const BunqAccount& account = AccountBy(key); std::vector> details = PaymentDetails(account, order.amount, order.currency, order.payee.value); details.emplace_back("reference", Shown(order.reference)); const Prompt prompt{actionCheckout, std::format("pay {} to {} from {}, as an app asks at checkout, reference {}", FormatMoney(order.amount, order.currency), Party(order.payee), Party(account), Shown(order.reference)), std::move(details)}; Gate(worker, call, prompt, [&worker, key, order](sd_bus_message* reply) { AppendPaid(reply, PayOrder(worker, AccountBy(key), order), false); }, [&worker, settled = order.Key()](sd_bus_message* answer) { Settle(worker, settled, answer); }); } catch(...) { const MessagePtr answer = ErrorFor(call, std::current_exception()); Deliver(answer); Settle(worker, order.Key(), answer.get()); } }); return 1; }); } const std::map handlers = { {"Connectors", OnConnectors}, {"AddBunq", OnAddBunq}, {"AddBunqOAuth", OnAddBunqOAuth}, {"RemoveConnector", OnRemoveConnector}, {"Accounts", OnAccounts}, {"Transactions", OnTransactions}, {"Send", OnSend}, {"Schedule", OnSchedule}, {"Request", OnRequest}, {"Requests", OnRequests}, {"RevokeRequest", OnRevokeRequest}, {"IncomingRequests", OnIncomingRequests}, {"RespondToRequest", OnRespondToRequest}, {"ScheduledPayments", OnScheduledPayments}, {"CancelScheduledPayment", OnCancelScheduledPayment}, {"Draft", OnDraft}, {"DraftPayments", OnDraftPayments}, {"RespondToDraftPayment", OnRespondToDraftPayment}, {"Cards", OnCards}, {"SetCardStatus", OnSetCardStatus}, {"DefaultCheckoutAccount", OnDefaultCheckoutAccount}, {"SetDefaultCheckoutAccount", OnSetDefaultCheckoutAccount}, }; } std::int32_t Nostro::RunWorker(std::int32_t fd, std::uint32_t uid, std::string_view name, const DaemonOptions& options) { // No other process of this user, and no core dump, gets at the secrets this process holds. prctl(PR_SET_DUMPABLE, 0); Worker worker; worker.options = options; worker.uid = uid; worker.name = std::string(name); worker.directory = options.state / "users" / std::to_string(uid); configPath = worker.directory; cachePath = worker.directory; // A directory made for the user this uid had before stays theirs: deleting a user and adding another hands out the // same uid again. const fs::path owner = worker.directory / "owner"; if(fs::exists(owner)) { std::ifstream in(owner); std::string recorded; std::getline(in, recorded); if(recorded != worker.name) { worker.refusal = std::format("{} holds the bank connections of '{}', who had uid {} before '{}': an administrator removes it, or moves it to that user's new uid, before nostrod serves this uid again", worker.directory.string(), recorded, uid, worker.name); } } noteSink = [](std::string_view note) { notes.emplace_back(note); }; ThrowOnSdBus(sd_event_new(&worker.event), "make an event loop"); // systemd stops the service with SIGTERM, which every process of it gets: the loop ends, and the tables are // flushed and closed on the way out. sigset_t terminate{}; sigemptyset(&terminate); sigaddset(&terminate, SIGTERM); sigprocmask(SIG_BLOCK, &terminate, nullptr); ThrowOnSdBus(sd_event_add_signal(worker.event, nullptr, SIGTERM, nullptr, nullptr), "watch for SIGTERM"); sd_bus* link = nullptr; ThrowOnSdBus(sd_bus_new(&link), "serve the front"); worker.link.reset(link); ThrowOnSdBus(sd_bus_set_fd(link, fd, fd), "serve the front"); sd_id128_t id{}; ThrowOnSdBus(sd_id128_randomize(&id), "serve the front"); ThrowOnSdBus(sd_bus_set_server(link, 1, id), "serve the front"); ThrowOnSdBus(sd_bus_start(link), "serve the front"); worker.vtable = Vtable(methods, [](std::string_view member) { return handlers.at(member); }); ThrowOnSdBus(sd_bus_add_object_vtable(link, nullptr, objectPath.data(), interfaceName.data(), worker.vtable.data(), &worker), "serve the front"); worker.checkoutVtable = Vtable(checkoutMethods, [](std::string_view) { return &OnPay; }); ThrowOnSdBus(sd_bus_add_object_vtable(link, nullptr, objectPath.data(), Checkout::interfaceName.data(), worker.checkoutVtable.data(), &worker), "serve the front"); ThrowOnSdBus(sd_bus_match_signal(link, nullptr, "org.freedesktop.DBus.Local", "/org/freedesktop/DBus/Local", "org.freedesktop.DBus.Local", "Disconnected", OnFrontGone, &worker), "watch the front"); ThrowOnSdBus(sd_bus_attach_event(link, worker.event, SD_EVENT_PRIORITY_NORMAL), "serve the front"); sd_bus* system = nullptr; ThrowOnSdBus(sd_bus_open_system_with_description(&system, "nostrod worker"), "connect to the system bus"); worker.system.reset(system); ThrowOnSdBus(sd_bus_attach_event(system, worker.event, SD_EVENT_PRIORITY_NORMAL), "connect to the system bus"); ThrowOnSdBus(sd_event_add_time_relative(worker.event, &worker.idle, CLOCK_MONOTONIC, Microseconds(options.idle), 0, OnIdle, &worker), "set the idle timer"); const std::int32_t result = sd_event_loop(worker.event); worker.link.reset(); worker.system.reset(); sd_event_source_unref(worker.idle); sd_event_unref(worker.event); ThrowOnSdBus(result, "run the event loop"); return 0; }