Nostro/implementations/main.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

378 lines
18 KiB
C++

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