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.
This commit is contained in:
Jorijn van der Graaf 2026-11-22 13:35:51 +01:00
commit b43ab124a6
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
42 changed files with 1234 additions and 994 deletions

View file

@ -13,8 +13,6 @@ module;
module Nostro:DaemonWorker_impl;
import std;
import Crafter.DB;
import Nostro.Checkout;
import :Daemon;
import :Bus;
import :Account;
@ -27,48 +25,17 @@ import :Utils;
using namespace Nostro;
using namespace Nostro::Bus;
using namespace Crafter;
namespace fs = std::filesystem;
// One user's worker. Every call is read and checked first (the account, the counterparty, what is to be paid), then
// polkit decides with a summary built from the worker's own data, and only then does the call run. On nostrod's own
// interface 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). The checkout is the one that reads before it asks: an order it knows is answered from its record,
// and the account that pays a new one is chosen for the dialog to name (OnPay). The wire carries bunq's types, so the
// worker works with bunq's connector directly.
// 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)>;
// What runs once a call that went through polkit is answered, with the answer it got.
using After = std::function<void(sd_bus_message* answer)>;
// An order paid at checkout, or being paid, which makes a retry safe. It is written before the payment is sent,
// with no payment yet, so a worker that dies or a bank whose answer is lost leaves it saying the order may have been
// paid. This is the table's schema: a change to it bumps `version` (see the Crafter.DB notes).
struct CheckoutRecord {
std::string payee; // the payee's IBAN, without spaces
std::string reference; // the app's reference for the order
std::int64_t amount = 0; // in the currency's minor unit
Currency currency = Currency::Euro;
std::string account; // the IBAN it is paid from
std::uint64_t payment = 0; // the bank's id of the payment, 0 while the bank's answer is unknown
std::chrono::system_clock::time_point time;
static constexpr std::uint32_t version = 1;
};
static_assert(DB::Layout<CheckoutRecord>::rowSize == 80);
static_assert(DB::Layout<CheckoutRecord>::fingerprint == 0x87a27f8a68f38c52);
// Orders are told apart by payee and reference: an app's references are its own.
using OrderKey = std::pair<std::string, std::string>;
// An order whose call is under way, and the calls for the same order that wait for its answer.
struct Paying {
std::int64_t amount = 0;
Currency currency = Currency::Euro;
std::vector<MessagePtr> waiting;
};
struct Worker {
DaemonOptions options;
@ -76,9 +43,8 @@ namespace {
std::string name;
fs::path directory;
sd_event* event = nullptr;
// Before the connection they are registered with, which then goes first however RunWorker ends.
// Before the connection it is registered with, which then goes first however RunWorker ends.
std::vector<sd_bus_vtable> vtable;
std::vector<sd_bus_vtable> checkoutVtable;
BusPtr link;
BusPtr system;
sd_event_source* idle = nullptr;
@ -87,9 +53,6 @@ namespace {
bool loaded = false;
std::size_t checking = 0;
std::uint64_t checks = 0;
// The checkouts paid, opened with the first; and the orders being paid now.
std::optional<DB::Table<CheckoutRecord>> records;
std::map<OrderKey, Paying> paying;
};
// Answered as AccessDenied.
@ -102,11 +65,6 @@ namespace {
using std::runtime_error::runtime_error;
};
// A checkout, and no account to pay it from.
struct NoCheckoutAccount : std::runtime_error {
using std::runtime_error::runtime_error;
};
// The library's warnings, sent with the next answer that is not an error. The process's own, as noteSink is.
std::vector<std::string> notes;
@ -150,9 +108,6 @@ namespace {
} catch(const Refused& e) {
name = SD_BUS_ERROR_ACCESS_DENIED;
message = e.what();
} catch(const NoCheckoutAccount& e) {
name = errorNoCheckoutAccount;
message = e.what();
} catch(const OAuthPaymentRefused& e) {
name = errorOAuthCannotPay;
message = e.what();
@ -165,13 +120,6 @@ namespace {
} catch(const std::exception& e) {
message = e.what();
}
// The connector says which call went wrong, "bunq POST /user/…/monetary-account/…/payment: …", and that names
// the user and the account at the bank. An app at checkout never sees the account, so it is told what the bank
// said and whether the payment may have been made all the same, and not what was asked of the bank.
const std::size_t said = message.find(": ");
if(Interface(call) == Checkout::interfaceName && message.starts_with("bunq ") && said != std::string::npos) {
message.replace(0, said, "bunq");
}
return ErrorReply(call, name, message);
}
@ -179,38 +127,18 @@ namespace {
sd_bus_send(nullptr, answer.get(), nullptr);
}
// The most a password dialog shows of a name, a description or a reference, in characters; and of an address,
// which it shows whole: the longest an e-mail address gets.
// 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;
using Range = std::pair<std::uint32_t, std::uint32_t>;
// What draws nothing, or tells the reader's own text where to go: control and format characters, the line and
// paragraph separators, what Unicode leaves out of a display by default (soft hyphens, joiners, fillers, variation
// selectors, tags), surrogates, private use, and what is no character at all.
constexpr std::array<Range, 31> unshown = {{
{0x0000, 0x001F}, {0x007F, 0x009F}, {0x00AD, 0x00AD}, {0x034F, 0x034F}, {0x0600, 0x0605}, {0x061C, 0x061C}, {0x06DD, 0x06DD}, {0x070F, 0x070F},
{0x0890, 0x0891}, {0x08E2, 0x08E2}, {0x115F, 0x1160}, {0x17B4, 0x17B5}, {0x180B, 0x180F}, {0x200B, 0x200F}, {0x2028, 0x202E}, {0x2060, 0x206F},
{0x3164, 0x3164}, {0xD800, 0xF8FF}, {0xFDD0, 0xFDEF}, {0xFE00, 0xFE0F}, {0xFEFF, 0xFEFF}, {0xFFA0, 0xFFA0}, {0xFFF0, 0xFFFC}, {0xFFFE, 0xFFFF},
{0x110BD, 0x110BD}, {0x110CD, 0x110CD}, {0x13430, 0x1343F}, {0x1BCA0, 0x1BCA3}, {0x1D173, 0x1D17A}, {0xE0000, 0xE0FFF}, {0xF0000, 0xFFFFFFFF},
}};
// A space of any width, and the Braille pattern without a dot, which is one to the eye.
constexpr std::array<Range, 8> blank = {{
{0x0020, 0x0020}, {0x00A0, 0x00A0}, {0x1680, 0x1680}, {0x2000, 0x200A}, {0x202F, 0x202F}, {0x205F, 0x205F}, {0x2800, 0x2800}, {0x3000, 0x3000},
}};
bool Among(std::span<const Range> ranges, std::uint32_t code) {
return std::ranges::any_of(ranges, [code](const Range& range) { return code >= range.first && code <= range.second; });
}
// 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 of `unshown`, so no text hides, turns around or starts a line of its own; a space of any kind 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.
// 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;
@ -227,10 +155,10 @@ namespace {
}
const std::string_view character = text.substr(i, length);
i += length;
if(Among(unshown, code)) {
if(Unshown(code)) {
continue;
}
if(Among(blank, code)) {
if(Blank(code)) {
spaced = !shown.empty();
continue;
}
@ -399,8 +327,8 @@ namespace {
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, or the first new order at checkout: that call
// also records whose directory this is. Reading them refreshes each one's accounts, which asks the bank.
// 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;
@ -415,17 +343,13 @@ namespace {
worker.loaded = true;
}
// Runs `work` and makes the answer to `call` of what it appended, and of the notes, which only nostrod's own
// interface carries: they are the user's, and an app at checkout is someone else.
// 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);
const std::vector<std::string> said = std::exchange(notes, {});
if(Interface(call) == interfaceName) {
Append(raw, said);
}
Append(raw, std::exchange(notes, {}));
return reply;
}
@ -433,7 +357,6 @@ namespace {
Worker* worker = nullptr;
MessagePtr call;
Work work;
After after;
// 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;
@ -492,17 +415,13 @@ namespace {
answer = ErrorFor(call, std::current_exception());
}
Deliver(answer);
if(check->after) {
check->after(answer.get());
}
return 0;
}
// Asks polkit whether the caller may do what `prompt` says. 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. Then it runs `after` with the answer it gave. 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, After after, std::function<void()> next) {
// 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");
@ -536,7 +455,7 @@ namespace {
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(after), std::move(next), std::string(prompt.action), interactive, std::move(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();
@ -544,10 +463,9 @@ namespace {
return 1;
}
// Asks polkit whether the caller may do what `prompt` says, then runs `work` and answers; or answers why not; and
// then runs `after` with the answer.
std::int32_t Gate(Worker& worker, sd_bus_message* call, const Prompt& prompt, Work work, After after = {}) {
return Ask(worker, call, prompt, std::move(work), std::move(after), {});
// 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
@ -576,7 +494,7 @@ namespace {
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)] {
return Ask(worker, call, Prompt{actionView, std::string(seen), {}}, {}, [&worker, body = std::move(body)] {
body(worker);
});
});
@ -927,12 +845,12 @@ namespace {
});
}
// Checkout (Nostro.Checkout): an app has nostrod pay an order. The order is read and checked, the account that
// pays it is chosen, the user confirms both at a password prompt, and it is paid and recorded. The record answers a
// retry with the first payment, and a retry while the first call is still under way waits for its answer.
// The account chosen to pay checkouts from, kept beside connectors.json as its connector's storage key and its id:
// none when none is chosen, or it is gone.
// 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;
@ -951,7 +869,7 @@ namespace {
std::int32_t OnDefaultCheckoutAccount(sd_bus_message* call, void* userdata, sd_bus_error*) {
return Handle(call, userdata, [call](Worker& worker) {
return Gate(worker, call, Prompt{actionView, "see which account pays at checkout", {}}, [&worker](sd_bus_message* reply) {
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);
});
@ -961,11 +879,12 @@ namespace {
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, so through one no shop could be paid.
// 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: checkouts need an account added with an API key", account.name));
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("let apps ask you to pay from {} at checkout", Party(account)), {{"account_iban", account.iban}, {"environment", std::string(EnvironmentName(account.connector->environment))}}};
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";
@ -977,173 +896,6 @@ namespace {
});
}
// An order, as Pay() reads and checks it. The options after its arguments are not read: there are none yet, and
// those of a later nostro this one does not know.
struct Order {
BunqCounterparty payee; // an IBAN, and the name given
std::int64_t amount = 0;
Currency currency = Currency::Euro;
std::string reference;
OrderKey Key() const {
return {payee.value, reference};
}
static Order Read(sd_bus_message* call) {
const std::string iban = Bus::Read<std::string>(call);
const std::string name = Bus::Read<std::string>(call);
Order order;
order.amount = Bus::Read<std::int64_t>(call);
const std::string currency = Bus::Read<std::string>(call);
order.reference = Bus::Read<std::string>(call);
order.payee = BunqCounterparty::Parse(iban, name);
if(order.payee.type != "IBAN") {
throw std::invalid_argument(std::format("checkout pays an IBAN, and '{}' is none", iban));
}
RequirePositive(order.amount);
try {
order.currency = GetCurrency(currency);
} catch(const std::runtime_error& e) {
throw std::invalid_argument(e.what());
}
if(order.reference.empty()) {
throw std::invalid_argument("an order needs a reference, such as its number: it is what keeps paying it again from paying twice");
}
return order;
}
};
// One reference to one payee is one order, of one amount. Which amount the order has is not said: any app that
// knows the payee and the reference of an order another app had paid would learn from it what was paid for it.
void RequireSameOrder(std::int64_t amount, Currency currency, const Order& order) {
if(amount != order.amount || currency != order.currency) {
throw std::invalid_argument(std::format("reference {} to {} is an order of another amount than {}: another order needs another reference", Shown(order.reference), order.payee.value, FormatMoney(order.amount, order.currency)));
}
}
DB::Table<CheckoutRecord>& Records(Worker& worker) {
if(!worker.records) {
// A few rows per order: a reservation of a gigabyte, where the transaction tables take Crafter.DB's 32.
worker.records.emplace(worker.directory / "checkouts.cdb", DB::OpenOptions{.reserveBytes = std::uint64_t(1) << 30});
}
return *worker.records;
}
// Pay()'s answer: the payment, and the results, of which `repeated` says the payment was made by an earlier call.
void AppendPaid(sd_bus_message* reply, std::uint64_t payment, bool repeated) {
ThrowOnSdBus(sd_bus_message_append(reply, "ta{sv}", payment, 1u, "repeated", "b", static_cast<std::int32_t>(repeated)), "answer a call");
}
// Answers a call for an order paid before, or being paid, and returns true; false for an order not seen before.
bool AnswerKnownOrder(Worker& worker, sd_bus_message* call, const Order& order) {
static constexpr DB::Column<&CheckoutRecord::payee> payee{};
static constexpr DB::Column<&CheckoutRecord::reference> reference{};
if(const std::optional<DB::Row<CheckoutRecord>> record = Records(worker).Where(payee == order.payee.value && reference == order.reference).First()) {
RequireSameOrder((*record)[&CheckoutRecord::amount], (*record)[&CheckoutRecord::currency], order);
const std::uint64_t payment = (*record)[&CheckoutRecord::payment];
if(payment == 0) {
throw std::runtime_error(std::format("order {} to {} may have been paid already: the bank's answer to it was lost, so check whether the payment arrived before paying it under another reference", Shown(order.reference), order.payee.value));
}
Deliver(Answer(call, [payment](sd_bus_message* reply) { AppendPaid(reply, payment, true); }));
return true;
}
if(const auto paying = worker.paying.find(order.Key()); paying != worker.paying.end()) {
RequireSameOrder(paying->second.amount, paying->second.currency, order);
paying->second.waiting.push_back(MessagePtr(sd_bus_message_ref(call)));
return true;
}
return false;
}
// The order's call is answered: the calls that waited for it get the same answer, the payment marked as made by
// an earlier call. The order is there: it went in before its account was chosen, and only this takes it out.
// Answering fails only when memory runs out, and then the callers' own timeouts answer for them.
void Settle(Worker& worker, const OrderKey& key, sd_bus_message* answer) {
const std::vector<MessagePtr> waiting = std::move(worker.paying.extract(key).mapped().waiting);
const bool paid = sd_bus_message_is_method_error(answer, nullptr) == 0;
std::uint64_t payment = 0;
sd_bus_message_rewind(answer, 1);
sd_bus_message_read_basic(answer, 't', &payment);
for(const MessagePtr& call : waiting) {
if(paid) {
sd_bus_reply_method_return(call.get(), "ta{sv}", payment, 1u, "repeated", "b", 1);
} else {
sd_bus_reply_method_error(call.get(), sd_bus_message_get_error(answer));
}
}
}
// Pays an order the user confirmed, and records it. The record goes first, with no payment, so should the worker
// die or the bank's answer be lost, a retry finds it and is refused rather than paid twice. Only a refusal bunq
// gives before doing anything (below 500) takes it away again.
std::uint64_t PayOrder(Worker& worker, const BunqAccount& account, const Order& order) {
DB::Table<CheckoutRecord>& records = Records(worker);
const DB::RowId row = records.Append(CheckoutRecord{order.payee.value, order.reference, order.amount, order.currency, account.iban, 0, std::chrono::system_clock::now()});
records.Flush();
std::uint64_t payment = 0;
try {
payment = account.Send(order.payee.value, order.payee.name, order.amount, order.currency, order.reference);
} catch(const BunqError& e) {
if(e.status < 500) {
records.Erase(row);
records.Flush();
}
throw;
}
records.Set<&CheckoutRecord::payment>(row, payment);
records.Flush();
return payment;
}
// Which account pays an order. Today the one the user chose for checkouts; an account picker, once nostro has a
// GUI, asks the user here instead, through an agent in their session, and may take its time. It answers through
// `then`, with the account or with what the call is to be refused with, and nothing else of a checkout changes with
// it. One that answers later keeps a reference to `call` until it does.
using Choice = std::variant<AccountKey, std::exception_ptr>;
void ChooseAccount(const Worker& worker, sd_bus_message*, const Order&, const std::function<void(const Choice&)>& then) {
if(const BunqAccount* chosen = CheckoutAccount(worker)) {
then(KeyOf(*chosen));
} else {
then(std::make_exception_ptr(NoCheckoutAccount("no account is chosen to pay checkouts from, or it is gone: choose one in Nostro's settings, or with `nostro checkout account`")));
}
}
std::int32_t OnPay(sd_bus_message* call, void* userdata, sd_bus_error*) {
return Handle(call, userdata, [call](Worker& worker) {
const Order order = Order::Read(call);
if(AnswerKnownOrder(worker, call, order)) {
return 1;
}
// The account that pays is chosen before the user is asked, since the dialog names it: an order not seen
// before has the connectors read for it, which no call of nostrod's own interface does before polkit's yes.
Load(worker);
// From here on, a call for the same order waits for this one, and Settle answers it.
worker.paying[order.Key()] = Paying{order.amount, order.currency, {}};
ChooseAccount(worker, call, order, [&worker, call, order](const Choice& choice) {
try {
if(const std::exception_ptr* refusal = std::get_if<std::exception_ptr>(&choice)) {
std::rethrow_exception(*refusal);
}
const AccountKey key = std::get<AccountKey>(choice);
const BunqAccount& account = AccountBy(key);
std::vector<std::pair<std::string, std::string>> details = PaymentDetails(account, order.amount, order.currency, order.payee.value);
details.emplace_back("reference", Shown(order.reference));
const Prompt prompt{actionCheckout, std::format("pay {} to {} from {}, as an app asks at checkout, reference {}", FormatMoney(order.amount, order.currency), Party(order.payee), Party(account), Shown(order.reference)), std::move(details)};
Gate(worker, call, prompt, [&worker, key, order](sd_bus_message* reply) {
AppendPaid(reply, PayOrder(worker, AccountBy(key), order), false);
}, [&worker, settled = order.Key()](sd_bus_message* answer) {
Settle(worker, settled, answer);
});
} catch(...) {
const MessagePtr answer = ErrorFor(call, std::current_exception());
Deliver(answer);
Settle(worker, order.Key(), answer.get());
}
});
return 1;
});
}
const std::map<std::string_view, sd_bus_message_handler_t> handlers = {
{"Connectors", OnConnectors},
{"AddBunq", OnAddBunq},
@ -1214,8 +966,6 @@ std::int32_t Nostro::RunWorker(std::int32_t fd, std::uint32_t uid, std::string_v
ThrowOnSdBus(sd_bus_start(link), "serve the front");
worker.vtable = Vtable(methods, [](std::string_view member) { return handlers.at(member); });
ThrowOnSdBus(sd_bus_add_object_vtable(link, nullptr, objectPath.data(), interfaceName.data(), worker.vtable.data(), &worker), "serve the front");
worker.checkoutVtable = Vtable(checkoutMethods, [](std::string_view) { return &OnPay; });
ThrowOnSdBus(sd_bus_add_object_vtable(link, nullptr, objectPath.data(), Checkout::interfaceName.data(), worker.checkoutVtable.data(), &worker), "serve the front");
ThrowOnSdBus(sd_bus_match_signal(link, nullptr, "org.freedesktop.DBus.Local", "/org/freedesktop/DBus/Local", "org.freedesktop.DBus.Local", "Disconnected", OnFrontGone, &worker), "watch the front");
ThrowOnSdBus(sd_bus_attach_event(link, worker.event, SD_EVENT_PRIORITY_NORMAL), "serve the front");