Nostro/implementations/Nostro-Daemon-Worker.cpp
Jorijn van der Graaf b43ab124a6
feat: open payto links on the pay form, and take the checkout over D-Bus out
An app could have nostrod pay an order: it called Pay of
net.catcrafts.Nostro1.Checkout on the system bus, and nostrod paid from
an account the user had chosen, after a dialog of its own. On 2026-11-22
the owner decided that a link takes its place. The app registers for
payto links (RFC 8905), so that an app or a website can hand one to the
desktop, and shows a link as its pay form filled in.

The link:

- The app's desktop entry takes the scheme (Exec=nostro-app %u,
  MimeType=x-scheme-handler/payto), and nostro-app takes an argument
  that is no option as a link: it overwrites it in argv and hands it to
  App::Open once the app has started.
- ReadPaymentLink (Nostro.App:Forms) reads payto://iban/<IBAN> with the
  options amount, receiver-name and message, and refuses a link rather
  than guess at it, in a sentence of the app's own with nothing of the
  link in it. Among what it refuses: an IBAN whose check digits do not
  hold, one of the three options given twice, instruction, a comma in
  the amount, and a name or a message with a code point that is Unshown,
  or Blank and no plain space.
- A link that is read waits until the accounts are read and
  DefaultCheckoutAccount has answered or failed, with a line on the
  accounts' page. Then App::TakeLink fills in the pay form, which says
  in a banner that a link filled it in, and with more than one account
  opens it under the choice of accounts that the form's From row has. A
  link pays nothing: the form's button sends, and polkit's dialog
  confirms as for any payment (design rule 12, and 14, which is new).
- Unshown and Blank are the two tables the worker's Shown() works from.
  They move into Nostro:Utils, where the app's reader asks them too.
  The move is within the library. The reader holds a link's name to
  those two and to no more of Shown(): a name with an & is read, and
  the dialog shows it with a + as it does any name.

The checkout:

- nostrod serves one interface under one bus name. Gone are
  net.catcrafts.Nostro1.Checkout with its XML and its activation file,
  the polkit action Checkout, the module Nostro.Checkout with
  --product=checkout, and the worker's record of orders. That changes
  the published contract after a release, 0.0.0, and design rule 10
  records it as the owner's decision.
- DefaultCheckoutAccount and SetDefaultCheckoutAccount keep their names
  and signatures. The account they keep is where a link's pay form
  starts: nostrod's dialog for choosing it says "have pay links start
  from", the app's setting reads "Pay links start from", and `nostro
  checkout account` prints "pay links start from".
- The D-Bus policy still lets nostrod own the old name: the nostrod of
  0.0.0 asks for it when it starts, and the system files can be newer
  than the Flatpak it runs from. install.sh removes the old name's
  activation file. A user's checkouts.cdb is read by nothing any more,
  and is left where it is.
- The Arch package stops installing the checkout's two files, and its
  pkgrel goes up to 2. Where makepkg -si finds a package of the version
  already built it installs that one again, which would bring the
  activation file back. The guide now says that pkgrel goes up with a
  change to what the package installs.
- Bus::Interface goes too: the worker called it in two places, to tell
  a call to the checkout from one to the main interface.

The review's own files follow. gate0 loses the build of
--product=checkout, and the three lens sections that named the checkout
no longer do, and ask about a link.

The README has "Pay links" in place of "Checkout for apps", and
AGENTS.consumer.md says what the app reads of a link. Its line on
lib/json.hpp no longer gives a release: the file is of none, and the
guide names its commit. The pay form and the accounts' page change only
by a banner each, shown while a link is in play, which
docs/screenshots/take.sh never has: the README's pictures stand.

Tests: ShouldValidateForms reads and refuses links and fills the form
from one. ShouldDriveTheApp opens links against a real nostrod on the
fake bus: before the accounts are known, with no account, with one and
with several, with the accounts known and the system bus gone, for a
second user whose first connection pays their own accounts only, one
that cannot be read, one whose name has an &, and through polkit's
dialog to the payment. It now counts nostrod's answers to hold that the
account pay links start from is read again once a connection is
removed: the check it had there passed without that.
ShouldHandleMoneyAndText holds the two tables at the ends of their
ranges. ShouldServeEveryUser holds that nostrod serves no checkout, that
the bus's policy lets an older nostrod own the old name, and the account
pay links start from. ShouldRunCommands holds the CLI's wording.

The review's gate0 passes at this commit: the version check, 17 tests,
the builds of the CLI, the library, nostrod, the fake system, the app
and its --debug-api build, and five lint runs that report nothing.
tests/coverage.sh reports lines, functions and regions at 100.00%.

Looked at on 2026-11-22 on the made-up system (run fake), on a desktop
(KWin at a scale of 1.85). At 420x760, at --scale 3 --size 360x760 and
at 1100x720 in the light look: a link's pay form under the choice of
accounts, the form after a tap beside that choice, and the accounts'
page while a link waits, its line above the rows that stand in for the
accounts (--bank-delay 10000). At 420x760: that line above what the
page says when the accounts cannot be read (--polkit deny) and above
the accounts themselves (--polkit slow, the link opened in the running
app), the settings' row and page for the account pay links start from,
the sheet for a link that cannot be read, and with --empty the sheet
for no account.
2026-11-22 13:35:51 +01:00

985 lines
52 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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 <systemd/sd-id128.h>
#include <signal.h>
#include <sys/prctl.h>
#include <time.h>
#include <unistd.h>
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<void(sd_bus_message* reply)>;
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<sd_bus_vtable> 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<std::string> 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<std::string> notes;
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(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<Worker*>(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<Worker*>(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<std::string_view> 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<std::uint8_t>(text[i]);
const std::size_t length = std::min<std::size_t>(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<std::uint8_t>(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<std::chrono::minutes>(time));
}
// When a schedule pays, in words.
std::string When(const BunqSchedule& schedule) {
const std::map<std::string_view, std::pair<std::string_view, std::string_view>> 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<std::pair<std::string, std::string>> details;
};
// A payment's details for polkit rules: how much, in what, to whom, from where, at which bunq.
std::vector<std::pair<std::string, std::string>> 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<BunqAccount*> 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<void()> 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> check(static_cast<Check*>(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<bool>(reply);
const bool challenge = Read<bool>(reply);
std::map<std::string, std::string> 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<std::string>(reply);
details[std::move(key)] = Read<std::string>(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<void()> 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> check = std::make_unique<Check>(&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<typename Body>
std::int32_t Handle(sd_bus_message* call, void* userdata, Body&& body) {
Worker& worker = *static_cast<Worker*>(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<typename Body>
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<ConnectorSummary> 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<std::uint32_t>(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<std::string>(call);
std::string allowedIps = Read<std::string>(call);
const std::string requested = Read<std::string>(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<std::string>(call));
std::string clientId = Read<std::string>(call);
std::string clientSecret = Read<std::string>(call);
std::string redirectUri = Read<std::string>(call);
std::string code = Read<std::string>(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<std::string>(call);
// By name, or by the number Connectors() lists it under.
std::vector<BunqConnector*> 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<ConnectorAccounts> listing;
for(const BunqConnector& bank : BunqConnector::connectors) {
listing.push_back(ConnectorAccounts{bank.name, std::string(BunqConnector::connectorId), std::vector<Account>(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<std::string>(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<std::string>(call);
payment.counterparty = Bus::Read<std::string>(call);
payment.name = Bus::Read<std::string>(call);
payment.amount = Bus::Read<std::int64_t>(call);
payment.description = Bus::Read<std::string>(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<BunqSchedule>(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<typename List>
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<std::string>(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<typename Act>
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<std::string>(call));
const std::uint64_t id = Read<std::uint64_t>(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<std::string>(call));
const std::uint64_t id = Read<std::uint64_t>(call);
const bool accept = Read<bool>(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<std::string>(call));
const std::uint64_t id = Read<std::uint64_t>(call);
const bool accept = Read<bool>(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<std::string> 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<std::size_t>(payees.size(), 3));
to.insert(0, payees.empty() ? std::string("no one") : std::ranges::to<std::string>(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<ConnectorCards> 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<std::uint64_t>(call);
const std::string status = Read<std::string>(call);
// Unfreezing lets the card pay again; a card reported lost or stolen is blocked for good.
const std::map<std::string_view, std::pair<std::string_view, std::string_view>> 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<Account>(*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<std::string>(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<std::string_view, sd_bus_message_handler_t> 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;
}