// 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 :Daemon; import :Bus; import :Account; import :Bunq; import :Connector; import :Currency; import :File; import :Transaction; import :Utils; using namespace Nostro; using namespace Nostro::Bus; 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. Nothing of the // user's is read, and the bank is asked nothing, for a caller polkit has not said yes to: a call that must look // something up to word its question asks first whether the caller may see the accounts (HandleLookup). That has no // exception: the one it had, a checkout over D-Bus that answered an order it knew before anyone was asked, went on // 2026-11-22. The wire carries bunq's types, so the worker works with bunq's connector directly. namespace { using Work = std::function; struct Worker { DaemonOptions options; std::uint32_t uid = 0; std::string name; fs::path directory; sd_event* event = nullptr; // Before the connection it is registered with, which then goes first however RunWorker ends. std::vector vtable; 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; }; // 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; }; // 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 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); } // The most a password dialog shows of a name, in characters; and of an address, which it shows whole: the longest // an e-mail address gets. constexpr std::size_t shownLimit = 64; constexpr std::size_t addressLimit = 254; // Text from a caller or a bank, made fit for a password dialog, which is where the user reads what a password is // for. Nothing that is Unshown (the library's list, which the app holds a link's text to as well), so no text // hides, turns around or starts a line of its own; a space of any kind, whatever is Blank, is one plain space, and // none leads or trails, so none pushes what follows onto another line; nothing a dialog could take for markup, or // polkit for one of its $(…) fields; and at most `limit` characters, so a long name cannot push what matters out // of sight. An & goes with < and >: an agent that reads its message as Pango markup, as GNOME's older one and // MATE's do, shows nothing at all of a message with a bare & in it, the amount included. std::string Shown(std::string_view text, std::size_t limit = shownLimit) { // Each character as it is shown, up to the first that does not fit, which is there to say that there is more. std::vector shown; bool spaced = false; 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() && shown.size() <= limit) { 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; if(Unshown(code)) { continue; } if(Blank(code)) { spaced = !shown.empty(); continue; } // The one space that stands for however many there were; and one that keeps a $ and a ( apart. if(std::exchange(spaced, false) || (code == '(' && !shown.empty() && shown.back() == "$")) { shown.emplace_back(" "); } shown.push_back(code == '<' ? "‹" : code == '>' ? "›" : code == '&' ? "+" : character); } std::string out; for(const std::string_view piece : shown | std::views::take(limit)) { out += piece; } if(shown.size() > limit) { out += "…"; } 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 a caller wants paid or asked. The address is what decides where the money goes, so the dialog shows it whole // and as it is, or the call is refused before anyone is asked: an address that would read otherwise there than it // is (one with an & reads as one with a +, which is somebody else's) could have the user confirm a payment to // someone they did not mean. A name is only made fit to show. BunqCounterparty Counterparty(std::string_view value, std::string_view name) { BunqCounterparty party = BunqCounterparty::Parse(value, name); if(Shown(party.value, addressLimit) != party.value) { throw std::invalid_argument(std::format("'{}' cannot be paid or asked through nostro: the password dialog would not show that address as it is, since it holds an &, a <, a > or a $(, something that draws nothing, or more than {} characters", Shown(party.value), addressLimit)); } return party; } // 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, addressLimit) : std::format("{} ({})", Shown(party.value, addressLimit), 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, addressLimit)}, {"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 for the first call polkit says yes to: that call also records whose directory this // is. Reading them refreshes each one's accounts, which asks the bank. 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. 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); Append(raw, std::exchange(notes, {})); return reply; } struct Check { Worker* worker = nullptr; MessagePtr call; Work work; // What a yes is followed by in place of an answer: the rest of a call that asked before it looked (HandleLookup). std::function next; 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) { // The connectors are read for a caller polkit said yes to, and for no other: reading them asks the bank. Load(worker); if(check->next) { // The call goes on to its own question, and is answered through that one. check->next(); return 0; } 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); return 0; } // Asks polkit whether the caller may do what `prompt` says. On a yes it runs `next` when there is one, which // answers the call itself, and else runs `work` and answers with what that appended; on anything else it answers // why not. The check does not block: other calls are served while a password dialog is open. std::int32_t Ask(Worker& worker, sd_bus_message* call, const Prompt& prompt, Work work, std::function next) { 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(next), 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; } // Asks polkit whether the caller may do what `prompt` says, then runs `work` and answers; or answers why not. std::int32_t Gate(Worker& worker, sd_bus_message* call, const Prompt& prompt, Work work) { return Ask(worker, call, prompt, std::move(work), {}); } // Runs `body` for `call`: it answers through Gate, or throws, and then the call is answered with the error. Nothing // of the user's is read here: a body reads its arguments and asks polkit, and what it then does runs after a yes. 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); } return body(worker); } catch(...) { Deliver(ErrorFor(call, std::current_exception())); return 1; } } // Runs `body` for a call that names something of the user's (an account, a card, a request, a draft, a connector) // and is not a call to see it. Such a call's own question to polkit is worded from what was found, so the body // looks it up first; and whether it is there is the user's to know, and finding it can take a question to the // bank. Both are for a caller who may see the user's accounts: polkit is asked that first, as `seen` words it, // and `body` runs on its yes. An active session has that yes without a dialog, as shipped; where seeing takes a // password, such a call asks for it twice, once to look and once to act. template std::int32_t HandleLookup(sd_bus_message* call, void* userdata, std::string_view seen, Body body) { return Handle(call, userdata, [call, seen, &body](Worker& worker) { return Ask(worker, call, Prompt{actionView, std::string(seen), {}}, {}, [&worker, body = std::move(body)] { body(worker); }); }); } 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); // The key says itself which environment it is of, by how it starts. One the caller names is held to that, // before anyone is asked and before the key goes anywhere: sent to the environment it is not of, a key // would only be refused there, after a real one had been shown to the sandbox. const BunqEnvironment environment = BunqConnector::EnvironmentOfKey(apiKey); if(!requested.empty() && ParseEnvironment(requested) != environment) { throw std::invalid_argument(std::format("that API key is a {} key, not a {} one: a sandbox key starts with sandbox_, and no other key does", EnvironmentName(environment), 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 HandleLookup(call, userdata, "see your bank connectors", [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 its number in the list of connectors", 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); // The account is looked up once polkit has said yes: whether there is one of that name is for a caller who // may see the accounts, and finding it can take a question to the bank. return Gate(worker, call, Prompt{actionView, "see your transactions", {}}, [account, query](sd_bus_message* reply) { BunqAccount& found = FindAccount(account); // What is new at the bank first: a call to it, which takes its time and which it counts. Not for a // question about what is stored alone, as a search in a list just given is: that is answered at once. if(!query.stored) { 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 HandleLookup(call, userdata, "see your accounts and balances", [call](Worker& worker) { const Payment payment = Payment::Read(call); const BunqAccount& account = FindAccount(payment.account); RequirePositive(payment.amount); const BunqCounterparty payee = Counterparty(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 HandleLookup(call, userdata, "see your accounts and balances", [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 = Counterparty(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 HandleLookup(call, userdata, "see your accounts and balances", [call](Worker& worker) { const Payment payment = Payment::Read(call); const BunqAccount& account = FindAccount(payment.account); RequirePositive(payment.amount); const BunqCounterparty payer = Counterparty(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 std::string account = Read(call); // Looked up once polkit has said yes, as in OnTransactions. return Gate(worker, call, Prompt{actionView, std::format("see your {}", what), {}}, [account, list](sd_bus_message* reply) { Append(reply, list(FindAccount(account))); }); }); } 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 HandleLookup(call, userdata, "see your accounts and balances", [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 HandleLookup(call, userdata, "see your incoming requests for money", [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 HandleLookup(call, userdata, "see your accounts and balances", [call](Worker& worker) { const Payment payment = Payment::Read(call); const BunqAccount& account = FindAccount(payment.account); RequirePositive(payment.amount); const BunqCounterparty payee = Counterparty(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 HandleLookup(call, userdata, "see your draft payments", [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 HandleLookup(call, userdata, "see your cards", [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) { // bunq does not freeze or unfreeze a virtual card when asked, and answers as if nothing were // wrong, with the card DEACTIVATED as it has it all along: a freeze answered so would look as // if it had worked. Refused before anyone is asked for a password. if(found.Virtual() && change->second.first != actionBlockCard) { throw std::invalid_argument(std::format("card {} is a virtual card, which bunq does not freeze or unfreeze when asked: do that in the bunq app", 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)); }); } // The account a pay link's form starts from in the app, which the user chooses once: "Pay links start from" in // its settings. It is where a form starts and no more: the app asks which account pays when a link opens, the // form's own row changes which account pays, and what a link pays is a payment like any other, asked about as // one. nostrod only keeps it, and pays nothing from it by itself. Until 2026-11-22 it was the account that paid an // app's order at a checkout over D-Bus, which is where these methods and the file have their names from. It is // 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 pay links start from", {}}, [&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 HandleLookup(call, userdata, "see your accounts and balances", [call](Worker& worker) { const BunqAccount& account = FindAccount(Read(call)); // bunq lets an OAuth connection pay the user's own accounts only: from one, what a shop's link asks for // could do no more than become a draft. if(account.connector->IsOAuth()) { throw std::invalid_argument(std::format("'{}' is reached through OAuth, which pays only your own accounts: a shop's pay link needs an account added with an API key", account.name)); } const Prompt prompt{actionConnectors, std::format("have pay links start from {}", 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)); }); }); } 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"); 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; }